-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathclient.ts
383 lines (353 loc) · 11.6 KB
/
client.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// TODO: Figure out how to get types from this lib:
import { ParsedMessage, parseIntegerNumber } from '@spruceid/siwe-parser';
import { Provider, verifyMessage } from './ethersCompat';
import {
SiweError,
SiweErrorType,
SiweResponse,
VerifyOpts,
VerifyOptsKeys,
VerifyParams,
VerifyParamsKeys,
} from './types';
import {
checkContractWalletSignature,
generateNonce,
checkInvalidKeys,
} from './utils';
export class SiweMessage {
/**RFC 3986 URI scheme for the authority that is requesting the signing. */
scheme?: string;
/**RFC 4501 dns authority that is requesting the signing. */
domain: string;
/**Ethereum address performing the signing conformant to capitalization
* encoded checksum specified in EIP-55 where applicable. */
address: string;
/**Human-readable ASCII assertion that the user will sign, and it must not
* contain `\n`. */
statement?: string;
/**RFC 3986 URI referring to the resource that is the subject of the signing
* (as in the __subject__ of a claim). */
uri: string;
/**Current version of the message. */
version: string;
/**EIP-155 Chain ID to which the session is bound, and the network where
* Contract Accounts must be resolved. */
chainId: number;
/**Randomized token used to prevent replay attacks, at least 8 alphanumeric
* characters. */
nonce: string;
/**ISO 8601 datetime string of the current time. */
issuedAt?: string;
/**ISO 8601 datetime string that, if present, indicates when the signed
* authentication message is no longer valid. */
expirationTime?: string;
/**ISO 8601 datetime string that, if present, indicates when the signed
* authentication message will become valid. */
notBefore?: string;
/**System-specific identifier that may be used to uniquely refer to the
* sign-in request. */
requestId?: string;
/**List of information or references to information the user wishes to have
* resolved as part of authentication by the relying party. They are
* expressed as RFC 3986 URIs separated by `\n- `. */
resources?: Array<string>;
/**
* Creates a parsed Sign-In with Ethereum Message (EIP-4361) object from a
* string or an object. If a string is used an ABNF parser is called to
* validate the parameter, otherwise the fields are attributed.
* @param param {string | SiweMessage} Sign message as a string or an object.
*/
constructor(param: string | Partial<SiweMessage>) {
if (typeof param === 'string') {
/* the message string (including nonce) is valid or ParsedMessage will throw */
const parsedMessage = new ParsedMessage(param);
this.scheme = parsedMessage.scheme;
this.domain = parsedMessage.domain;
this.address = parsedMessage.address;
this.statement = parsedMessage.statement;
this.uri = parsedMessage.uri;
this.version = parsedMessage.version;
this.nonce = parsedMessage.nonce;
this.issuedAt = parsedMessage.issuedAt;
this.expirationTime = parsedMessage.expirationTime;
this.notBefore = parsedMessage.notBefore;
this.requestId = parsedMessage.requestId;
this.chainId = parsedMessage.chainId;
this.resources = parsedMessage.resources;
} else {
this.scheme = param?.scheme;
this.domain = param.domain;
this.address = param.address;
this.statement = param?.statement;
this.uri = param.uri;
this.version = param.version;
this.chainId = param.chainId;
this.nonce = param.nonce;
this.issuedAt = param?.issuedAt;
this.expirationTime = param?.expirationTime;
this.notBefore = param?.notBefore;
this.requestId = param?.requestId;
this.resources = param?.resources;
if (typeof this.chainId === 'string') {
this.chainId = parseIntegerNumber(this.chainId);
}
this.nonce = this.nonce || generateNonce();
/* the message object is valid or parsing its stringified value will throw */
new ParsedMessage(this.prepareMessage());
}
}
/**
* This function can be used to retrieve an EIP-4361 formatted message for
* signature, although you can call it directly it's advised to use
* [prepareMessage()] instead which will resolve to the correct method based
* on the [type] attribute of this object, in case of other formats being
* implemented.
* @returns {string} EIP-4361 formatted message, ready for EIP-191 signing.
*/
toMessage(): string {
/** Validates all fields of the object */
// this.validateMessage();
const headerPrefix = this.scheme
? `${this.scheme}://${this.domain}`
: this.domain;
const header = `${headerPrefix} wants you to sign in with your Ethereum account:`;
const uriField = `URI: ${this.uri}`;
let prefix = [header, this.address].join('\n');
const versionField = `Version: ${this.version}`;
if (!this.nonce) {
this.nonce = generateNonce();
}
const chainField = `Chain ID: ` + this.chainId || '1';
const nonceField = `Nonce: ${this.nonce}`;
const suffixArray = [uriField, versionField, chainField, nonceField];
this.issuedAt = this.issuedAt || new Date().toISOString();
suffixArray.push(`Issued At: ${this.issuedAt}`);
if (this.expirationTime) {
const expiryField = `Expiration Time: ${this.expirationTime}`;
suffixArray.push(expiryField);
}
if (this.notBefore) {
suffixArray.push(`Not Before: ${this.notBefore}`);
}
if (this.requestId) {
suffixArray.push(`Request ID: ${this.requestId}`);
}
if (this.resources) {
suffixArray.push(
[`Resources:`, ...this.resources.map(x => `- ${x}`)].join('\n')
);
}
const suffix = suffixArray.join('\n');
prefix = [prefix, this.statement].join('\n\n');
if (this.statement !== undefined) {
prefix += '\n';
}
return [prefix, suffix].join('\n');
}
/**
* This method parses all the fields in the object and creates a messaging for signing
* message according with the type defined.
* @returns {string} Returns a message ready to be signed according with the
* type defined in the object.
*/
prepareMessage(): string {
let message: string;
switch (this.version) {
case '1': {
message = this.toMessage();
break;
}
default: {
message = this.toMessage();
break;
}
}
return message;
}
/**
* Verifies the integrity of the object by matching its signature.
* @param params Parameters to verify the integrity of the message, signature is required.
* @returns {Promise<SiweMessage>} This object if valid.
*/
async verify(
params: VerifyParams,
opts: VerifyOpts = { suppressExceptions: false }
): Promise<SiweResponse> {
return new Promise<SiweResponse>((resolve, reject) => {
const fail = result => {
if (opts.suppressExceptions) {
return resolve(result);
} else {
return reject(result);
}
};
const invalidParams: Array<keyof VerifyParams> =
checkInvalidKeys<VerifyParams>(params, VerifyParamsKeys);
if (invalidParams.length > 0) {
fail({
success: false,
data: this,
error: new Error(
`${invalidParams.join(
', '
)} is/are not valid key(s) for VerifyParams.`
),
});
}
const invalidOpts: Array<keyof VerifyOpts> = checkInvalidKeys<VerifyOpts>(
opts,
VerifyOptsKeys
);
if (invalidOpts.length > 0) {
fail({
success: false,
data: this,
error: new Error(
`${invalidOpts.join(', ')} is/are not valid key(s) for VerifyOpts.`
),
});
}
const { signature, scheme, domain, nonce, time } = params;
/** Scheme for domain binding */
if (scheme && scheme !== this.scheme) {
fail({
success: false,
data: this,
error: new SiweError(
SiweErrorType.SCHEME_MISMATCH,
scheme,
this.scheme
),
});
}
/** Domain binding */
if (domain && domain !== this.domain) {
fail({
success: false,
data: this,
error: new SiweError(
SiweErrorType.DOMAIN_MISMATCH,
domain,
this.domain
),
});
}
/** Nonce binding */
if (nonce && nonce !== this.nonce) {
fail({
success: false,
data: this,
error: new SiweError(SiweErrorType.NONCE_MISMATCH, nonce, this.nonce),
});
}
/** Check time or now */
const checkTime = new Date(time || new Date());
/** Message not expired */
if (this.expirationTime) {
const expirationDate = new Date(this.expirationTime);
if (checkTime.getTime() >= expirationDate.getTime()) {
fail({
success: false,
data: this,
error: new SiweError(
SiweErrorType.EXPIRED_MESSAGE,
`${checkTime.toISOString()} < ${expirationDate.toISOString()}`,
`${checkTime.toISOString()} >= ${expirationDate.toISOString()}`
),
});
}
}
/** Message is valid already */
if (this.notBefore) {
const notBefore = new Date(this.notBefore);
if (checkTime.getTime() < notBefore.getTime()) {
fail({
success: false,
data: this,
error: new SiweError(
SiweErrorType.NOT_YET_VALID_MESSAGE,
`${checkTime.toISOString()} >= ${notBefore.toISOString()}`,
`${checkTime.toISOString()} < ${notBefore.toISOString()}`
),
});
}
}
let EIP4361Message;
try {
EIP4361Message = this.prepareMessage();
} catch (e) {
fail({
success: false,
data: this,
error: e,
});
}
/** Recover address from signature */
let addr;
try {
addr = verifyMessage(EIP4361Message, signature);
} catch (e) {
console.error(e);
}
/** Match signature with message's address */
if (addr === this.address) {
return resolve({
success: true,
data: this,
});
} else {
const EIP1271Promise = checkContractWalletSignature(
this,
signature,
opts.provider
)
.then(isValid => {
if (!isValid) {
return {
success: false,
data: this,
error: new SiweError(
SiweErrorType.INVALID_SIGNATURE,
addr,
`Resolved address to be ${this.address}`
),
};
}
return {
success: true,
data: this,
};
})
.catch(error => {
return {
success: false,
data: this,
error,
};
});
Promise.all([
EIP1271Promise,
opts
?.verificationFallback?.(params, opts, this, EIP1271Promise)
?.then(res => res)
?.catch((res: SiweResponse) => res),
]).then(([EIP1271Response, fallbackResponse]) => {
if (fallbackResponse) {
if (fallbackResponse.success) {
return resolve(fallbackResponse);
} else {
fail(fallbackResponse);
}
} else {
if (EIP1271Response.success) {
return resolve(EIP1271Response);
} else {
fail(EIP1271Response);
}
}
});
}
});
}
}