-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathauth.ts
More file actions
899 lines (727 loc) · 28 KB
/
auth.ts
File metadata and controls
899 lines (727 loc) · 28 KB
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
import { Observer, SequenceWaaSBase } from './base'
import {
Account,
IdentityType,
IntentDataOpenSession,
IntentDataSendTransaction,
IntentResponseIdToken
} from './clients/intent.gen'
import { newSessionFromSessionId } from './session'
import { LocalStore, Store, StoreObj } from './store'
import {
GetTransactionReceiptArgs,
SendContractCallArgs,
SendERC1155Args,
SendERC20Args,
SendERC721Args,
SendTransactionsArgs,
SignedIntent,
SignMessageArgs,
getTimeDrift,
updateTimeDrift,
AdoptChildWalletArgs
} from './intents'
import {
FeeOptionsResponse,
isChildWalletAdoptedResponse,
isCloseSessionResponse,
isFeeOptionsResponse,
isFinishValidateSessionResponse,
isGetAdopterResponse,
isGetIdTokenResponse,
isGetSessionResponse,
isInitiateAuthResponse,
isIntentTimeError,
isLinkAccountResponse,
isListAccountsResponse,
isMaySentTransactionResponse,
isSessionAuthProofResponse,
isSignedMessageResponse,
isTimedOutTransactionResponse,
isValidationRequiredResponse,
MaySentTransactionResponse,
SignedMessageResponse
} from './intents/responses'
import { WaasAuthenticator, AnswerIncorrectError, Chain, EmailAlreadyInUseError, Session } from './clients/authenticator.gen'
import { SimpleNetwork, WithSimpleNetwork } from './networks'
import { EmailAuth } from './email'
import { ethers } from 'ethers'
import { getDefaultSubtleCryptoBackend, SubtleCryptoBackend } from './subtle-crypto'
import { getDefaultSecureStoreBackend, SecureStoreBackend } from './secure-store'
import { Challenge, EmailChallenge, GuestChallenge, IdTokenChallenge, PlayFabChallenge, StytchChallenge } from './challenge'
import { jwtDecode } from 'jwt-decode'
export type Sessions = (Session & { isThis: boolean })[]
export type { Account }
export { IdentityType }
export type SequenceConfig = {
projectAccessKey: string
waasConfigKey: string
network?: SimpleNetwork
disableHttpSignatureCheck?: boolean
}
export type ExtendedSequenceConfig = {
rpcServer: string
emailRegion?: string
}
export type WaaSConfigKey = {
projectId: number
emailClientId?: string
}
export type GuestIdentity = { guest: true }
export type IdTokenIdentity = { idToken: string }
export type EmailIdentity = { email: string }
export type PlayFabIdentity = {
playFabTitleId: string
playFabSessionTicket: string
}
export type Identity = IdTokenIdentity | EmailIdentity | PlayFabIdentity | GuestIdentity
export type SignInResponse = {
sessionId: string
wallet: string
email?: string
}
export type ValidationArgs = {
onValidationRequired?: () => boolean
}
export type CommonAuthArgs = {
validation?: ValidationArgs
identifier?: string
}
export type Network = Chain
export type NetworkList = Network[]
export type EmailConflictInfo = {
type: IdentityType
email: string
issuer: string
}
export function parseSequenceWaaSConfigKey<T>(key: string): Partial<T> {
return JSON.parse(atob(key))
}
export function defaultArgsOrFail(
config: SequenceConfig & Partial<ExtendedSequenceConfig>
): Required<SequenceConfig> & Required<WaaSConfigKey> & ExtendedSequenceConfig {
const key = (config as any).waasConfigKey
const keyOverrides = key ? parseSequenceWaaSConfigKey<SequenceConfig & WaaSConfigKey & ExtendedSequenceConfig>(key) : {}
const preconfig = { ...config, ...keyOverrides }
if (preconfig.network === undefined) {
preconfig.network = 1
}
if (preconfig.projectId === undefined) {
throw new Error('Missing project id')
}
if (preconfig.projectAccessKey === undefined) {
throw new Error('Missing access key')
}
return preconfig as Required<SequenceConfig> & Required<WaaSConfigKey> & ExtendedSequenceConfig
}
const fetch = globalThis.fetch
const jwksDev = {
keys: [
{
alg: 'RS256',
e: 'AQAB',
kid: '9LkLZyHdNq1N2aeHMlC5jw',
kty: 'RSA',
n: 'qllUB_ERsOjbKx4SirGow4XDov05lQyhiF7Duo4sPkH9CwMN11OqhLuIqeIXPq0rPNIXGP99A7riXTcpRNk-5ZNL29zs-Xjj3idp7nZQZLIU1CBQErTcbxbwUYp8Q46k7lJXVlMmwoLQvQAgH8BZLuSe-Xk1tye0mDC-bHvmrMfqm2zmuWeDnZercU3Jg2iYwyPrjKWx7YSBSMTXTKPGndws4m3s3XIEpI2alLcLLWsPQk2UjIlux6I7vLwvjM_BgjFhYHqgg1tgZUPn_Xxt4wvhobF8UIacRVmGcuyYBnhRxKnBQhEClGSBVtnFYYBSvRjTgliOwf3DhFoXdnmyPQ',
use: 'sig'
}
]
}
const jwksProd = {
keys: [
{
alg: 'RS256',
e: 'AQAB',
kid: 'nWh-_3nQ1lnhhI1ZSQTQmw',
kty: 'RSA',
n: 'pECaEq2k0k22J9e7hFLAFmKbzPLlWToUJJmFeWAdEiU4zpW17EUEOyfjRzjgBewc7KFJQEblC3eTD7Vc5bh9-rafPEj8LaKyZzzS5Y9ZATXhlMo5Pnlar3BrTm48XcnT6HnLsvDeJHUVbrYd1JyE1kqeTjUKWvgKX4mgIJiuYhpdzbOC22cPaWb1dYCVhArDVAPHGqaEwRjX7JneETdY5hLJ6JhsAws706W7fwfNKddPQo2mY95S9q8HFxMr5EaXEMmhwxk8nT5k-Ouar2dobMXRMmQiEZSt9fJaGKlK7KWJSnbPOVa2cZud1evs1Rz2SdCSA2bhuZ6NnZCxkqnagw',
use: 'sig'
}
]
}
export class SequenceWaaS {
private waas: SequenceWaaSBase
private client: WaasAuthenticator
private validationRequiredCallback: (() => void)[] = []
private emailConflictCallback: ((info: EmailConflictInfo, forceCreate: () => Promise<void>) => Promise<void>)[] = []
private emailAuthCodeRequiredCallback: ((respondWithCode: (code: string) => Promise<void>) => Promise<void>)[] = []
private validationRequiredSalt: string
public readonly config: Required<SequenceConfig> & Required<WaaSConfigKey> & ExtendedSequenceConfig
private readonly deviceName: StoreObj<string | undefined>
private emailClient: EmailAuth | undefined
// The last Date header value returned by the server, used for users with desynchronised clocks
private lastDate: Date | undefined
// Flag for disabling consequent requests if signature verification fails
private signatureVerificationFailed: boolean = false
constructor(
config: SequenceConfig & Partial<ExtendedSequenceConfig>,
private readonly store: Store = new LocalStore(),
private readonly cryptoBackend: SubtleCryptoBackend | null = getDefaultSubtleCryptoBackend(),
private readonly secureStoreBackend: SecureStoreBackend | null = getDefaultSecureStoreBackend()
) {
this.config = defaultArgsOrFail(config)
this.waas = new SequenceWaaSBase({ network: 1, ...config }, this.store, this.cryptoBackend, this.secureStoreBackend)
this.client = new WaasAuthenticator(this.config.rpcServer, this._fetch)
this.deviceName = new StoreObj(this.store, '@0xsequence.waas.auth.deviceName', undefined)
}
_fetch = (input: RequestInfo, init?: RequestInit): Promise<Response> => {
if (this.signatureVerificationFailed) {
throw new Error('Signature verification failed')
}
if (this.cryptoBackend && this.config.disableHttpSignatureCheck !== true && init?.headers) {
const headers: { [key: string]: any } = {}
headers['Accept-Signature'] = 'sig=();alg="rsa-v1_5-sha256"'
init!.headers = { ...init!.headers, ...headers }
}
const response = fetch(input, init)
if (this.cryptoBackend && this.config.disableHttpSignatureCheck !== true) {
response.then(async r => {
try {
const clone = r.clone()
const responseBodyText = await clone.text()
const contentDigest = r.headers.get('Content-Digest')
const signatureInput = r.headers.get('Signature-Input')
const signature = r.headers.get('Signature')
if (!contentDigest) {
throw new Error('Content-Digest header not set')
}
if (!signatureInput) {
throw new Error('Signature-Input header not set')
}
if (!signature) {
throw new Error('Signature header not set')
}
const contentDigestSha = contentDigest.match(':(.*):')?.[1]
if (!contentDigestSha) {
throw new Error('Content digest not found')
}
const responseBodyTextUint8Array = new TextEncoder().encode(responseBodyText)
const responseBodyTextDigest = await this.cryptoBackend!.digest('SHA-256', responseBodyTextUint8Array)
const base64EncodedDigest = btoa(String.fromCharCode(...responseBodyTextDigest))
if (contentDigestSha !== base64EncodedDigest) {
throw new Error('Digest mismatch')
}
// we're removing the first 4 characters from signatureInput to trim the sig= prefix
const message = `"content-digest": ${contentDigest}\n"@signature-params": ${signatureInput.substring(4)}`
const algo = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }
const jwks = r.url.includes('dev-waas') ? jwksDev : jwksProd
const key = await this.cryptoBackend!.importKey('jwk', jwks.keys[0], algo, false, ['verify'])
const sig = signature.match(':(.*):')?.[1]
if (!sig) {
throw new Error('Signature not found')
}
const signatureBuffer = Uint8Array.from(atob(sig), c => c.charCodeAt(0))
const verifyResult = await this.cryptoBackend!.verify(algo, key, signatureBuffer, new TextEncoder().encode(message))
if (!verifyResult) {
throw new Error('Signature verification failed, consequent requests will fail')
}
} catch (e) {
this.signatureVerificationFailed = true
throw e
}
})
}
return response
}
public get email() {
if (this.emailClient) {
return this.emailClient
}
if (!this.config.emailRegion) {
throw new Error('Missing emailRegion')
}
if (!this.config.emailClientId) {
throw new Error('Missing emailClientId')
}
this.emailClient = new EmailAuth(this.config.emailRegion, this.config.emailClientId)
return this.emailClient
}
async onValidationRequired(callback: () => void) {
this.validationRequiredCallback.push(callback)
return () => {
this.validationRequiredCallback = this.validationRequiredCallback.filter(c => c !== callback)
}
}
onEmailConflict(callback: (info: EmailConflictInfo, forceCreate: () => Promise<void>) => Promise<void>) {
this.emailConflictCallback.push(callback)
return () => {
this.emailConflictCallback = this.emailConflictCallback.filter(c => c !== callback)
}
}
onEmailAuthCodeRequired(callback: (respondWithCode: (code: string) => Promise<void>) => Promise<void>) {
this.emailAuthCodeRequiredCallback.push(callback)
return () => {
this.emailAuthCodeRequiredCallback = this.emailAuthCodeRequiredCallback.filter(c => c !== callback)
}
}
private async handleValidationRequired({ onValidationRequired }: ValidationArgs = {}): Promise<boolean> {
const proceed = onValidationRequired ? onValidationRequired() : true
if (!proceed) {
return false
}
const intent = await this.waas.validateSession({
deviceMetadata: (await this.deviceName.get()) ?? 'Unknown device'
})
const sendIntent = await this.sendIntent(intent)
this.validationRequiredSalt = sendIntent.data.salt
for (const callback of this.validationRequiredCallback) {
callback()
}
return this.waitForSessionValid()
}
private headers() {
return {
'X-Access-Key': this.config.projectAccessKey
}
}
private async updateTimeDrift() {
if (getTimeDrift() === undefined) {
const res = await fetch(`${this.config.rpcServer}/status`)
const date = res.headers.get('Date')
if (!date) {
throw new Error('failed to get Date header value from /status')
}
updateTimeDrift(new Date(date))
}
}
private async sendIntent(intent: SignedIntent<any>) {
const sessionId = await this.waas.getSessionId()
if (!sessionId) {
throw new Error('session not open')
}
try {
const res = await this.client.sendIntent({ intent: intent }, this.headers())
return res.response
} catch (e) {
if (isIntentTimeError(e) && this.lastDate) {
const newIntent = await this.waas.updateIntentTime(intent, this.lastDate)
const res = await this.client.sendIntent({ intent: newIntent }, this.headers())
return res.response
}
throw e
}
}
async isSignedIn() {
return this.waas.isSignedIn()
}
async signIn(creds: Identity, sessionName: string): Promise<SignInResponse> {
// We clear and drop session regardless of whether it's signed in or not
const currentSessionId = await this.waas.getSessionId()
if (currentSessionId) {
await this.dropSession({ sessionId: currentSessionId, strict: false })
}
const isEmailAuth = 'email' in creds
if (isEmailAuth && this.emailAuthCodeRequiredCallback.length == 0) {
return Promise.reject('Missing emailAuthCodeRequired callback')
}
return new Promise<SignInResponse>(async (resolve, reject) => {
let challenge: Challenge
try {
challenge = await this.initAuth(creds)
} catch (e) {
return reject(e)
}
const respondToChallenge = async (answer: string) => {
try {
const res = await this.completeAuth(challenge.withAnswer(answer), { sessionName })
resolve(res)
} catch (e) {
if (e instanceof AnswerIncorrectError) {
// This will NOT resolve NOR reject the top-level promise returned from signIn, it'll keep being pending
// It allows the caller to retry calling the respondToChallenge callback
throw e
} else if (e instanceof EmailAlreadyInUseError) {
const forceCreate = async () => {
try {
const res = await this.completeAuth(challenge.withAnswer(answer), { sessionName, forceCreateAccount: true })
resolve(res)
} catch (e) {
reject(e)
}
}
const info: EmailConflictInfo = {
type: IdentityType.None,
email: '',
issuer: ''
}
if (e.cause) {
const parts = e.cause.split('|')
if (parts.length >= 2) {
info.type = parts[0] as IdentityType
info.email = parts[1]
}
if (parts.length >= 3) {
info.issuer = parts[2]
}
}
for (const callback of this.emailConflictCallback) {
callback(info, forceCreate)
}
} else {
reject(e)
}
}
}
if (isEmailAuth) {
for (const callback of this.emailAuthCodeRequiredCallback) {
callback(respondToChallenge)
}
} else {
respondToChallenge('')
}
})
}
async initAuth(identity: Identity): Promise<Challenge> {
await this.updateTimeDrift()
if ('guest' in identity && identity.guest) {
return this.initGuestAuth()
} else if ('idToken' in identity) {
return this.initIdTokenAuth(identity.idToken)
} else if ('email' in identity) {
return this.initEmailAuth(identity.email)
} else if ('playFabTitleId' in identity) {
return this.initPlayFabAuth(identity.playFabTitleId, identity.playFabSessionTicket)
}
throw new Error('invalid identity')
}
private async initGuestAuth() {
const sessionId = await this.waas.getSessionId()
const intent = await this.waas.initiateGuestAuth()
const res = await this.sendIntent(intent)
if (!isInitiateAuthResponse(res)) {
throw new Error(`Invalid response: ${JSON.stringify(res)}`)
}
return new GuestChallenge(sessionId, res.data.challenge!)
}
private async initIdTokenAuth(idToken: string) {
const decoded = jwtDecode(idToken)
const isStytch = decoded.iss?.startsWith('stytch.com/') || false
const intent = isStytch
? await this.waas.initiateStytchAuth(idToken, decoded.exp)
: await this.waas.initiateIdTokenAuth(idToken, decoded.exp)
const res = await this.sendIntent(intent)
if (!isInitiateAuthResponse(res)) {
throw new Error(`Invalid response: ${JSON.stringify(res)}`)
}
return isStytch ? new StytchChallenge(idToken) : new IdTokenChallenge(idToken)
}
private async initEmailAuth(email: string) {
const sessionId = await this.waas.getSessionId()
const intent = await this.waas.initiateEmailAuth(email)
const res = await this.sendIntent(intent)
if (!isInitiateAuthResponse(res)) {
throw new Error(`Invalid response: ${JSON.stringify(res)}`)
}
return new EmailChallenge(email, sessionId, res.data.challenge!)
}
private async initPlayFabAuth(titleId: string, sessionTicket: string) {
const intent = await this.waas.initiatePlayFabAuth(titleId, sessionTicket)
const res = await this.sendIntent(intent)
if (!isInitiateAuthResponse(res)) {
throw new Error(`Invalid response: ${JSON.stringify(res)}`)
}
return new PlayFabChallenge(titleId, sessionTicket)
}
async completeAuth(
challenge: Challenge,
opts?: { sessionName?: string; forceCreateAccount?: boolean }
): Promise<SignInResponse> {
await this.updateTimeDrift()
// initAuth can start while user is already signed in and continue with linkAccount method,
// but it can't be used to completeAuth while user is already signed in. In this
// case we should throw an error.
const isSignedIn = await this.isSignedIn()
if (isSignedIn) {
throw new Error('You are already signed in. Use dropSession to sign out from current session first.')
}
if (!opts) {
opts = {}
}
if (!opts.sessionName) {
opts.sessionName = 'session name'
}
const intent = await this.waas.completeAuth(challenge.getIntentParams(), { forceCreateAccount: opts.forceCreateAccount })
try {
const res = await this.registerSession(intent, opts.sessionName)
await this.waas.completeSignIn({
code: 'sessionOpened',
data: {
sessionId: res.session.id,
wallet: res.response.data.wallet
}
})
return {
sessionId: res.session.id,
wallet: res.response.data.wallet,
email: res.session.identity.email
}
} catch (e) {
if (!(e instanceof EmailAlreadyInUseError) && !(e instanceof AnswerIncorrectError)) {
await this.waas.completeSignOut()
}
throw e
}
}
private async registerSession(intent: SignedIntent<IntentDataOpenSession>, name: string) {
try {
const res = await this.client.registerSession({ intent, friendlyName: name }, this.headers())
return res
} catch (e) {
if (isIntentTimeError(e) && this.lastDate) {
const newIntent = await this.waas.updateIntentTime(intent, this.lastDate)
return await this.client.registerSession({ intent: newIntent, friendlyName: name }, this.headers())
}
throw e
}
}
private async refreshSession() {
throw new Error('Not implemented')
}
async getSessionId() {
return this.waas.getSessionId()
}
async getSessionHash() {
const sessionId = (await this.waas.getSessionId()).toLowerCase()
return ethers.id(sessionId)
}
async dropSession({ sessionId, strict }: { sessionId?: string; strict?: boolean } = {}) {
await this.updateTimeDrift()
const thisSessionId = await this.waas.getSessionId()
if (!thisSessionId) {
throw new Error('session not open')
}
const closeSessionId = sessionId || thisSessionId
try {
const intent = await this.waas.signOutSession(closeSessionId)
const result = await this.sendIntent(intent)
if (!isCloseSessionResponse(result)) {
throw new Error(`Invalid response: ${JSON.stringify(result)}`)
}
} catch (e) {
if (strict) {
throw e
}
console.error(e)
}
if (closeSessionId === thisSessionId) {
if (!this.secureStoreBackend) {
throw new Error('No secure store available')
}
const session = await newSessionFromSessionId(thisSessionId, this.cryptoBackend, this.secureStoreBackend)
session.clear()
await this.waas.completeSignOut()
await this.deviceName.set(undefined)
}
}
async listSessions(): Promise<Sessions> {
await this.updateTimeDrift()
const sessionId = await this.waas.getSessionId()
if (!sessionId) {
throw new Error('session not open')
}
const intent = await this.waas.listSessions()
const res = await this.sendIntent(intent)
return (res.data as Session[]).map(session => ({
...session,
isThis: session.id === sessionId
}))
}
// WaaS specific methods
async getAddress() {
return this.waas.getAddress()
}
async validateSession(args?: ValidationArgs) {
await this.updateTimeDrift()
if (await this.isSessionValid()) {
return true
}
return this.handleValidationRequired(args)
}
async finishValidateSession(challenge: string): Promise<boolean> {
await this.updateTimeDrift()
const intent = await this.waas.finishValidateSession(this.validationRequiredSalt, challenge)
const result = await this.sendIntent(intent)
if (!isFinishValidateSessionResponse(result)) {
throw new Error(`Invalid response: ${JSON.stringify(result)}`)
}
this.validationRequiredSalt = ''
return result.data.isValid
}
async isSessionValid(): Promise<boolean> {
await this.updateTimeDrift()
const intent = await this.waas.getSession()
const result = await this.sendIntent(intent)
if (!isGetSessionResponse(result)) {
throw new Error(`Invalid response: ${JSON.stringify(result)}`)
}
return result.data.validated
}
async waitForSessionValid(timeout: number = 600000, pollRate: number = 2000) {
const start = Date.now()
while (Date.now() - start < timeout) {
if (await this.isSessionValid()) {
return true
}
await new Promise(resolve => setTimeout(resolve, pollRate))
}
return false
}
async sessionAuthProof({ nonce, network, validation }: { nonce?: string; network?: string; validation?: ValidationArgs }) {
await this.updateTimeDrift()
const intent = await this.waas.sessionAuthProof({ nonce, network })
return await this.trySendIntent({ validation }, intent, isSessionAuthProofResponse)
}
async listAccounts() {
await this.updateTimeDrift()
const intent = await this.waas.listAccounts()
const res = await this.sendIntent(intent)
if (!isListAccountsResponse(res)) {
throw new Error(`Invalid response: ${JSON.stringify(res)}`)
}
return res.data
}
async linkAccount(challenge: Challenge) {
await this.updateTimeDrift()
const intent = await this.waas.linkAccount(challenge.getIntentParams())
const res = await this.sendIntent(intent)
if (!isLinkAccountResponse(res)) {
throw new Error(`Invalid response: ${JSON.stringify(res)}`)
}
return res.data
}
async removeAccount(accountId: string) {
await this.updateTimeDrift()
const intent = await this.waas.removeAccount({ accountId })
await this.sendIntent(intent)
}
async getIdToken(args?: { nonce?: string }): Promise<IntentResponseIdToken> {
await this.updateTimeDrift()
const intent = await this.waas.getIdToken({ nonce: args?.nonce })
const res = await this.sendIntent(intent)
if (!isGetIdTokenResponse(res)) {
throw new Error(`Invalid response: ${JSON.stringify(res)}`)
}
return res.data
}
async getAdopter(): Promise<string> {
await this.updateTimeDrift()
const intent = await this.waas.getAdopter()
const res = await this.sendIntent(intent)
if (!isGetAdopterResponse(res)) {
throw new Error(`Invalid response: ${JSON.stringify(res)}`)
}
return res.data.adopterAddress
}
async useIdentifier<T extends CommonAuthArgs>(args: T): Promise<T & { identifier: string }> {
if (args.identifier) {
return args as T & { identifier: string }
}
// Generate a new identifier
const identifier = `ts-sdk-${Date.now()}-${await this.waas.getSessionId()}`
return { ...args, identifier } as T & { identifier: string }
}
private async trySendIntent<T>(
args: CommonAuthArgs,
intent: SignedIntent<any>,
isExpectedResponse: (response: any) => response is T
): Promise<T> {
const response = await this.sendIntent(intent)
if (isExpectedResponse(response)) {
return response
}
if (isValidationRequiredResponse(response)) {
const proceed = await this.handleValidationRequired(args.validation)
if (proceed) {
const response2 = await this.sendIntent(intent)
if (isExpectedResponse(response2)) {
return response2
}
}
}
throw new Error(JSON.stringify(response))
}
async signMessage(args: WithSimpleNetwork<SignMessageArgs> & CommonAuthArgs): Promise<SignedMessageResponse> {
await this.updateTimeDrift()
const intent = await this.waas.signMessage(await this.useIdentifier(args))
return this.trySendIntent(args, intent, isSignedMessageResponse)
}
private async trySendTransactionIntent(
intent: SignedIntent<IntentDataSendTransaction>,
args: CommonAuthArgs
): Promise<MaySentTransactionResponse> {
let result = await this.trySendIntent(args, intent, isMaySentTransactionResponse)
while (isTimedOutTransactionResponse(result)) {
await new Promise(resolve => setTimeout(resolve, 1000))
const receiptArgs: WithSimpleNetwork<GetTransactionReceiptArgs> & CommonAuthArgs = {
metaTxHash: result.data.metaTxHash,
network: intent.data.network,
identifier: intent.data.identifier,
validation: args.validation
}
const receiptIntent = await this.waas.getTransactionReceipt(await this.useIdentifier(receiptArgs))
result = await this.trySendIntent(receiptArgs, receiptIntent, isMaySentTransactionResponse)
}
return result
}
async sendTransaction(args: WithSimpleNetwork<SendTransactionsArgs> & CommonAuthArgs): Promise<MaySentTransactionResponse> {
await this.updateTimeDrift()
const intent = await this.waas.sendTransaction(await this.useIdentifier(args))
return this.trySendTransactionIntent(intent, args)
}
async sendERC20(args: WithSimpleNetwork<SendERC20Args> & CommonAuthArgs): Promise<MaySentTransactionResponse> {
await this.updateTimeDrift()
const intent = await this.waas.sendERC20(await this.useIdentifier(args))
return this.trySendTransactionIntent(intent, args)
}
async sendERC721(args: WithSimpleNetwork<SendERC721Args> & CommonAuthArgs): Promise<MaySentTransactionResponse> {
await this.updateTimeDrift()
const intent = await this.waas.sendERC721(await this.useIdentifier(args))
return this.trySendTransactionIntent(intent, args)
}
async sendERC1155(args: WithSimpleNetwork<SendERC1155Args> & CommonAuthArgs): Promise<MaySentTransactionResponse> {
await this.updateTimeDrift()
const intent = await this.waas.sendERC1155(await this.useIdentifier(args))
return this.trySendTransactionIntent(intent, args)
}
async callContract(args: WithSimpleNetwork<SendContractCallArgs> & CommonAuthArgs): Promise<MaySentTransactionResponse> {
await this.updateTimeDrift()
const intent = await this.waas.callContract(await this.useIdentifier(args))
return this.trySendTransactionIntent(intent, args)
}
async feeOptions(args: WithSimpleNetwork<SendTransactionsArgs> & CommonAuthArgs): Promise<FeeOptionsResponse> {
await this.updateTimeDrift()
const intent = await this.waas.feeOptions(await this.useIdentifier(args))
return this.trySendIntent(args, intent, isFeeOptionsResponse)
}
async adoptChildWallet(args: WithSimpleNetwork<AdoptChildWalletArgs> & CommonAuthArgs) {
await this.updateTimeDrift()
const intent = await this.waas.adoptChildWallet(args)
return this.trySendIntent(args, intent, isChildWalletAdoptedResponse)
}
async networkList(): Promise<NetworkList> {
const networks: NetworkList = []
const chainList = await this.client.chainList({
'X-Access-Key': this.config.projectAccessKey
})
for (const chain of chainList.chains) {
networks.push({
id: chain.id,
name: chain.name,
isEnabled: chain.isEnabled
})
}
return networks
}
onSessionStateChanged(callback: Observer<string>) {
return this.waas.onSessionStateChanged(callback)
}
// Special version of fetch that keeps track of the last seen Date header
async fetch(input: RequestInfo, init?: RequestInit) {
const res = await globalThis.fetch(input, init)
const headerValue = res.headers.get('date')
if (headerValue) {
this.lastDate = new Date(headerValue)
}
return res
}
}