-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.ts
235 lines (213 loc) · 5.74 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import { GPublicKey, GTransaction, GKeypair } from "@glow-xyz/solana-client";
import bs58 from "bs58";
import { Buffer } from "buffer";
import { DateTime, Duration } from "luxon";
import { sign } from "tweetnacl";
import { Address } from "./window-types";
const SIGN_IN_REGEX_STR =
`^(?<appName>.{0,100}?)[ ]?would like you to sign in with your Solana account:
(?<address>[5KL1-9A-HJ-NP-Za-km-z]{32,44})
Domain: (?<domain>[A-Za-z0-9.\\-]+)
Requested At: (?<requestedAt>.+)
Nonce: (?<nonce>[A-Za-z0-9\-\.]+)$`
.split("\n")
.map((s) => s.trim())
.join("\n");
const SIGN_IN_REGEX = new RegExp(SIGN_IN_REGEX_STR);
const DEFAULT_MAX_ALLOWED_TIME_DIFF_MS = Duration.fromObject({
minutes: 10,
}).toMillis();
/**
* We take in either a signature or a signed transaction.
*
* The signed transaction option is useful for Ledger which does not support signing messages
* directly.
*/
export const verifySignIn = ({
message,
expectedDomain,
expectedAddress,
maxAllowedTimeDiffMs = DEFAULT_MAX_ALLOWED_TIME_DIFF_MS,
...params
}: {
message: string;
expectedDomain: string | string[];
expectedAddress: Address;
/**
* How long is a signature valid for, both ways.
* Providing value of 10 minutes will cause signatures
* from [t - 10 minutes, t + 10 minutes] to be considered valid.
*/
maxAllowedTimeDiffMs?: number;
} & (
| {
signature: string; // base64
signed_transaction_base64?: string; // base64
}
| {
signed_transaction_base64: string; // base64
signature?: string; // base64
}
)): {
appName: string;
domain: string;
address: Address;
nonce: string;
requestedAt: DateTime;
} => {
if (!expectedAddress) {
throw new Error("Missing expected address.");
}
const match = message.match(SIGN_IN_REGEX);
if (!match || !match.groups) {
throw new Error("Invalid message format.");
}
const {
appName,
domain,
address,
nonce: _nonce,
requestedAt: _requestedAt,
} = match.groups;
const nonce = _nonce;
const requestedAt = DateTime.fromISO(_requestedAt).toUTC();
if (Array.isArray(expectedDomain)) {
if (expectedDomain.indexOf(domain) === -1) {
throw new Error("Domain does not match expected domain.");
}
} else {
if (expectedDomain !== domain) {
throw new Error("Domain does not match expected domain.");
}
}
if (expectedAddress !== address) {
throw new Error("Address does not match expected address.");
}
const timeDiff = DateTime.now().diff(requestedAt);
if (Math.abs(timeDiff.toMillis()) > maxAllowedTimeDiffMs) {
throw new Error("Message is not recent.");
}
if (
"signed_transaction_base64" in params &&
typeof params.signed_transaction_base64 === "string"
) {
const gtransaction = GTransaction.parse({
buffer: Buffer.from(params.signed_transaction_base64!, "base64"),
});
const messageFromTx = Buffer.from(
gtransaction.instructions[0].data_base64,
"base64"
).toString("utf-8");
if (messageFromTx !== message) {
throw new Error(
"The transaction message does not match the message passed in."
);
}
const signature = gtransaction.signatures.find(
(s) => s.address === address
)!.signature!;
verifySignature({
signature: Buffer.from(bs58.decode(signature)).toString("base64"),
messageBuffer: Buffer.from(gtransaction.messageBase64, "base64"),
signer: address,
});
} else {
verifySignature({ signature: params.signature!, message, signer: address });
}
return {
appName,
domain,
address,
nonce,
requestedAt,
};
};
export const constructSignInMessage = ({
appName,
domain,
address,
nonce,
requestedAt,
}: {
appName: string | null;
domain: string;
address: string;
nonce: number;
requestedAt: DateTime;
}): string => {
const message = `${
appName ?? domain
} would like you to sign in with your Solana account:
${address}
Domain: ${domain}
Requested At: ${requestedAt.toUTC().toISO()}
Nonce: ${nonce}`;
return message
.split("\n")
.map((line) => line.trim())
.join("\n");
};
export const constructSignInTx = ({
address,
appName,
domain,
signer,
}: {
address: string;
appName: string;
domain: string;
signer?: GKeypair;
}): { gtransaction: GTransaction.GTransaction; message: string } => {
const message = constructSignInMessage({
appName,
domain,
address,
nonce: Math.floor(Math.random() * 1000),
requestedAt: DateTime.now(),
});
const gtransaction = GTransaction.create({
instructions: [
{
accounts: [
{ address, signer: true },
{ address: GPublicKey.nullString, signer: true },
],
program: NOTE_PROGRAM,
data_base64: Buffer.from(message).toString("base64"),
},
],
recentBlockhash: GPublicKey.nullString,
feePayer: GPublicKey.nullString,
signers: signer ? [signer] : undefined,
});
return { gtransaction, message };
};
export const NOTE_PROGRAM = "noteD9tEFTDH1Jn9B1HbpoC7Zu8L9QXRo7FjZj3PT93";
export const verifySignature = ({
signature,
signer,
...params
}: {
signature: string; // base64
signer: Address;
} & (
| {
message: string;
}
| {
messageBuffer: Buffer;
}
)) => {
const signatureUint = new Uint8Array(Buffer.from(signature, "base64"));
const addressUint = bs58.decode(signer);
let messageUint: Uint8Array;
if ("message" in params) {
messageUint = new Uint8Array(Buffer.from(params.message));
} else {
messageUint = new Uint8Array(params.messageBuffer);
}
if (!sign.detached.verify(messageUint, signatureUint, addressUint)) {
console.error("Problem verifying signature...");
throw new Error("The Solana signature is invalid.");
}
};