@supatype/client 0.1.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/.turbo/turbo-test.log +7 -0
  3. package/.turbo/turbo-typecheck.log +4 -0
  4. package/dist/auth.d.ts +243 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +560 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/error-codes-doc.d.ts +31 -0
  9. package/dist/error-codes-doc.d.ts.map +1 -0
  10. package/dist/error-codes-doc.js +294 -0
  11. package/dist/error-codes-doc.js.map +1 -0
  12. package/dist/errors.d.ts +197 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +162 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/fetch-with-retry.d.ts +49 -0
  17. package/dist/fetch-with-retry.d.ts.map +1 -0
  18. package/dist/fetch-with-retry.js +150 -0
  19. package/dist/fetch-with-retry.js.map +1 -0
  20. package/dist/index.d.ts +137 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +225 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/query.d.ts +53 -0
  25. package/dist/query.d.ts.map +1 -0
  26. package/dist/query.js +216 -0
  27. package/dist/query.js.map +1 -0
  28. package/dist/realtime.d.ts +69 -0
  29. package/dist/realtime.d.ts.map +1 -0
  30. package/dist/realtime.js +279 -0
  31. package/dist/realtime.js.map +1 -0
  32. package/dist/retry.d.ts +24 -0
  33. package/dist/retry.d.ts.map +1 -0
  34. package/dist/retry.js +25 -0
  35. package/dist/retry.js.map +1 -0
  36. package/dist/serverless-docs.d.ts +38 -0
  37. package/dist/serverless-docs.d.ts.map +1 -0
  38. package/dist/serverless-docs.js +83 -0
  39. package/dist/serverless-docs.js.map +1 -0
  40. package/dist/storage.d.ts +79 -0
  41. package/dist/storage.d.ts.map +1 -0
  42. package/dist/storage.js +130 -0
  43. package/dist/storage.js.map +1 -0
  44. package/dist/types.d.ts +141 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/types.js +3 -0
  47. package/dist/types.js.map +1 -0
  48. package/package.json +26 -0
  49. package/src/auth.ts +713 -0
  50. package/src/error-codes-doc.ts +315 -0
  51. package/src/errors.ts +201 -0
  52. package/src/fetch-with-retry.ts +200 -0
  53. package/src/index.ts +418 -0
  54. package/src/query.ts +280 -0
  55. package/src/realtime.ts +418 -0
  56. package/src/retry.ts +35 -0
  57. package/src/serverless-docs.ts +107 -0
  58. package/src/storage.ts +182 -0
  59. package/src/types.ts +184 -0
  60. package/tests/auth.test.ts +282 -0
  61. package/tests/mfa-totp-integration.test.ts +359 -0
  62. package/tests/query.test.ts +286 -0
  63. package/tests/rate-limit-integration.test.ts +185 -0
  64. package/tests/realtime-multi-tenant-integration.test.ts +372 -0
  65. package/tests/retry-integration.test.ts +212 -0
  66. package/tests/serverless.test.ts +115 -0
  67. package/tests/storage-quota-integration.test.ts +189 -0
  68. package/tests/storage-upload-limit-integration.test.ts +185 -0
  69. package/tests/types.test.ts +123 -0
  70. package/tsconfig.json +11 -0
  71. package/tsconfig.tsbuildinfo +1 -0
package/src/auth.ts ADDED
@@ -0,0 +1,713 @@
1
+ import type {
2
+ AuthChangeEvent,
3
+ AuthMFAChallengeResponse,
4
+ AuthMFAEnrollResponse,
5
+ AuthMFAListFactorsResponse,
6
+ Factor,
7
+ OtpType,
8
+ Session,
9
+ SupatypeError,
10
+ User,
11
+ } from "./types.js"
12
+
13
+ type AuthListener = (event: AuthChangeEvent, session: Session | null) => void
14
+
15
+ export class AuthClient {
16
+ private readonly url: string
17
+ private readonly baseHeaders: Record<string, string>
18
+ private currentSession: Session | null = null
19
+ private readonly listeners = new Map<string, AuthListener>()
20
+ private listenerIdCounter = 0
21
+
22
+ constructor(url: string, baseHeaders: Record<string, string>) {
23
+ this.url = url
24
+ this.baseHeaders = baseHeaders
25
+ }
26
+
27
+ async signUp(credentials: {
28
+ email: string
29
+ password: string
30
+ options?: { data?: Record<string, unknown> } | undefined
31
+ }): Promise<{
32
+ data: { session: Session | null; user: User | null }
33
+ error: SupatypeError | null
34
+ }> {
35
+ const body: Record<string, unknown> = {
36
+ email: credentials.email,
37
+ password: credentials.password,
38
+ }
39
+ if (credentials.options?.data !== undefined) {
40
+ body["data"] = credentials.options.data
41
+ }
42
+ const res = await fetch(`${this.url}/signup`, {
43
+ method: "POST",
44
+ headers: this.baseHeaders,
45
+ body: JSON.stringify(body),
46
+ })
47
+ return this._parseAuthResponse(res)
48
+ }
49
+
50
+ async signInWithPassword(credentials: {
51
+ email: string
52
+ password: string
53
+ }): Promise<{
54
+ data: { session: Session | null; user: User | null }
55
+ error: SupatypeError | null
56
+ }> {
57
+ const res = await fetch(`${this.url}/token?grant_type=password`, {
58
+ method: "POST",
59
+ headers: this.baseHeaders,
60
+ body: JSON.stringify({
61
+ email: credentials.email,
62
+ password: credentials.password,
63
+ }),
64
+ })
65
+ return this._parseAuthResponse(res)
66
+ }
67
+
68
+ async signInWithOAuth(opts: {
69
+ provider: string
70
+ options?: { redirectTo?: string | undefined } | undefined
71
+ }): Promise<{
72
+ data: { url: string; provider: string }
73
+ error: SupatypeError | null
74
+ }> {
75
+ const url = new URL(`${this.url}/authorize`)
76
+ url.searchParams.set("provider", opts.provider)
77
+ if (opts.options?.redirectTo !== undefined) {
78
+ url.searchParams.set("redirect_to", opts.options.redirectTo)
79
+ }
80
+ return { data: { url: url.toString(), provider: opts.provider }, error: null }
81
+ }
82
+
83
+ async signInWithOtp(opts: {
84
+ email?: string | undefined
85
+ phone?: string | undefined
86
+ options?: {
87
+ emailRedirectTo?: string | undefined
88
+ channel?: "sms" | "whatsapp" | undefined
89
+ createUser?: boolean | undefined
90
+ } | undefined
91
+ }): Promise<{ data: { messageId?: string | undefined }; error: SupatypeError | null }> {
92
+ const body: Record<string, unknown> = {
93
+ create_user: opts.options?.createUser ?? true,
94
+ }
95
+ if (opts.email !== undefined) {
96
+ body["email"] = opts.email
97
+ }
98
+ if (opts.phone !== undefined) {
99
+ body["phone"] = opts.phone
100
+ if (opts.options?.channel !== undefined) {
101
+ body["channel"] = opts.options.channel
102
+ }
103
+ }
104
+ const res = await fetch(`${this.url}/otp`, {
105
+ method: "POST",
106
+ headers: this.baseHeaders,
107
+ body: JSON.stringify(body),
108
+ })
109
+ if (res.ok) {
110
+ const json = await res.json().catch(() => ({})) as Record<string, unknown>
111
+ return {
112
+ data: {
113
+ ...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
114
+ },
115
+ error: null,
116
+ }
117
+ }
118
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
119
+ return {
120
+ data: {},
121
+ error: {
122
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
123
+ status: res.status,
124
+ },
125
+ }
126
+ }
127
+
128
+ async signOut(): Promise<{ error: SupatypeError | null }> {
129
+ if (this.currentSession !== null) {
130
+ await fetch(`${this.url}/logout`, {
131
+ method: "POST",
132
+ headers: {
133
+ ...this.baseHeaders,
134
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
135
+ },
136
+ }).catch(() => undefined)
137
+ }
138
+ this._setSession(null)
139
+ return { error: null }
140
+ }
141
+
142
+ async getSession(): Promise<{
143
+ data: { session: Session | null }
144
+ error: SupatypeError | null
145
+ }> {
146
+ return { data: { session: this.currentSession }, error: null }
147
+ }
148
+
149
+ async getUser(): Promise<{
150
+ data: { user: User | null }
151
+ error: SupatypeError | null
152
+ }> {
153
+ if (this.currentSession === null) {
154
+ return { data: { user: null }, error: null }
155
+ }
156
+ const res = await fetch(`${this.url}/user`, {
157
+ headers: {
158
+ ...this.baseHeaders,
159
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
160
+ },
161
+ })
162
+ if (!res.ok) {
163
+ return {
164
+ data: { user: null },
165
+ error: { message: "Could not get user", status: res.status },
166
+ }
167
+ }
168
+ const raw = await res.json() as Record<string, unknown>
169
+ return { data: { user: this._parseUser(raw) }, error: null }
170
+ }
171
+
172
+ async refreshSession(): Promise<{
173
+ data: { session: Session | null }
174
+ error: SupatypeError | null
175
+ }> {
176
+ if (this.currentSession === null) {
177
+ return { data: { session: null }, error: { message: "No active session" } }
178
+ }
179
+ const res = await fetch(`${this.url}/token?grant_type=refresh_token`, {
180
+ method: "POST",
181
+ headers: this.baseHeaders,
182
+ body: JSON.stringify({ refresh_token: this.currentSession.refreshToken }),
183
+ })
184
+ const result = await this._parseAuthResponse(res)
185
+ return { data: { session: result.data.session }, error: result.error }
186
+ }
187
+
188
+ async resetPasswordForEmail(
189
+ email: string,
190
+ options?: { redirectTo?: string | undefined } | undefined,
191
+ ): Promise<{ data: Record<string, never>; error: SupatypeError | null }> {
192
+ const body: Record<string, unknown> = { email }
193
+ if (options?.redirectTo !== undefined) {
194
+ body["redirect_to"] = options.redirectTo
195
+ }
196
+ const res = await fetch(`${this.url}/recover`, {
197
+ method: "POST",
198
+ headers: this.baseHeaders,
199
+ body: JSON.stringify(body),
200
+ })
201
+ if (res.ok) return { data: {}, error: null }
202
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
203
+ return {
204
+ data: {},
205
+ error: {
206
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
207
+ status: res.status,
208
+ },
209
+ }
210
+ }
211
+
212
+ async updateUser(updates: {
213
+ email?: string | undefined
214
+ password?: string | undefined
215
+ data?: Record<string, unknown> | undefined
216
+ }): Promise<{ data: { user: User | null }; error: SupatypeError | null }> {
217
+ if (this.currentSession === null) {
218
+ return { data: { user: null }, error: { message: "Not authenticated" } }
219
+ }
220
+ const res = await fetch(`${this.url}/user`, {
221
+ method: "PUT",
222
+ headers: {
223
+ ...this.baseHeaders,
224
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
225
+ },
226
+ body: JSON.stringify(updates),
227
+ })
228
+ if (!res.ok) {
229
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
230
+ return {
231
+ data: { user: null },
232
+ error: {
233
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
234
+ status: res.status,
235
+ },
236
+ }
237
+ }
238
+ const raw = await res.json() as Record<string, unknown>
239
+ return { data: { user: this._parseUser(raw) }, error: null }
240
+ }
241
+
242
+ /**
243
+ * Verify an OTP token received via email or phone.
244
+ * Completes email confirmation, magic link, recovery, or phone OTP flows.
245
+ */
246
+ async verifyOtp(params: {
247
+ token: string
248
+ type: OtpType
249
+ email?: string | undefined
250
+ phone?: string | undefined
251
+ tokenHash?: string | undefined
252
+ }): Promise<{
253
+ data: { session: Session | null; user: User | null }
254
+ error: SupatypeError | null
255
+ }> {
256
+ const body: Record<string, unknown> = {
257
+ type: params.type,
258
+ }
259
+ if (params.tokenHash !== undefined) {
260
+ body["token_hash"] = params.tokenHash
261
+ } else {
262
+ body["token"] = params.token
263
+ if (params.email !== undefined) body["email"] = params.email
264
+ if (params.phone !== undefined) body["phone"] = params.phone
265
+ }
266
+ const res = await fetch(`${this.url}/verify`, {
267
+ method: "POST",
268
+ headers: this.baseHeaders,
269
+ body: JSON.stringify(body),
270
+ })
271
+ return this._parseAuthResponse(res)
272
+ }
273
+
274
+ /**
275
+ * Sign in with an ID token from an external provider (e.g. Google One Tap).
276
+ * Uses the token grant with id_token grant type.
277
+ */
278
+ async signInWithIdToken(credentials: {
279
+ provider: "google" | "apple" | string
280
+ token: string
281
+ nonce?: string | undefined
282
+ }): Promise<{
283
+ data: { session: Session | null; user: User | null }
284
+ error: SupatypeError | null
285
+ }> {
286
+ const body: Record<string, unknown> = {
287
+ provider: credentials.provider,
288
+ id_token: credentials.token,
289
+ }
290
+ if (credentials.nonce !== undefined) {
291
+ body["nonce"] = credentials.nonce
292
+ }
293
+ const res = await fetch(`${this.url}/token?grant_type=id_token`, {
294
+ method: "POST",
295
+ headers: this.baseHeaders,
296
+ body: JSON.stringify(body),
297
+ })
298
+ return this._parseAuthResponse(res)
299
+ }
300
+
301
+ /**
302
+ * Resend an OTP or confirmation email/SMS.
303
+ */
304
+ async resend(params: {
305
+ type: "signup" | "sms" | "phone_change" | "email_change"
306
+ email?: string | undefined
307
+ phone?: string | undefined
308
+ }): Promise<{ data: { messageId?: string | undefined }; error: SupatypeError | null }> {
309
+ const body: Record<string, unknown> = { type: params.type }
310
+ if (params.email !== undefined) body["email"] = params.email
311
+ if (params.phone !== undefined) body["phone"] = params.phone
312
+ const res = await fetch(`${this.url}/resend`, {
313
+ method: "POST",
314
+ headers: this.baseHeaders,
315
+ body: JSON.stringify(body),
316
+ })
317
+ if (res.ok) {
318
+ const json = await res.json().catch(() => ({})) as Record<string, unknown>
319
+ return {
320
+ data: {
321
+ ...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
322
+ },
323
+ error: null,
324
+ }
325
+ }
326
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
327
+ return {
328
+ data: {},
329
+ error: {
330
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
331
+ status: res.status,
332
+ },
333
+ }
334
+ }
335
+
336
+ // ─── MFA ──────────────────────────────────────────────────────────────────────
337
+
338
+ /**
339
+ * Multi-Factor Authentication namespace.
340
+ * Provides methods for enrolling, challenging, and verifying MFA factors.
341
+ */
342
+ get mfa() {
343
+ return {
344
+ /**
345
+ * Enroll a new MFA factor (TOTP or Phone).
346
+ * Returns the factor ID and, for TOTP, the QR code and secret.
347
+ */
348
+ enroll: async (params: {
349
+ factorType: "totp" | "phone"
350
+ friendlyName?: string | undefined
351
+ issuer?: string | undefined
352
+ phone?: string | undefined
353
+ }): Promise<{
354
+ data: AuthMFAEnrollResponse | null
355
+ error: SupatypeError | null
356
+ }> => {
357
+ if (this.currentSession === null) {
358
+ return { data: null, error: { message: "Not authenticated" } }
359
+ }
360
+ const body: Record<string, unknown> = {
361
+ factor_type: params.factorType,
362
+ }
363
+ if (params.friendlyName !== undefined) body["friendly_name"] = params.friendlyName
364
+ if (params.issuer !== undefined) body["issuer"] = params.issuer
365
+ if (params.phone !== undefined) body["phone"] = params.phone
366
+ const res = await fetch(`${this.url}/factors`, {
367
+ method: "POST",
368
+ headers: {
369
+ ...this.baseHeaders,
370
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
371
+ },
372
+ body: JSON.stringify(body),
373
+ })
374
+ if (!res.ok) {
375
+ return { data: null, error: await this._parseError(res) }
376
+ }
377
+ const json = await res.json() as Record<string, unknown>
378
+ const data: AuthMFAEnrollResponse = {
379
+ id: String(json["id"] ?? ""),
380
+ type: String(json["type"] ?? ""),
381
+ friendlyName: String(json["friendly_name"] ?? ""),
382
+ ...(json["totp"] !== undefined && {
383
+ totp: {
384
+ qrCode: String((json["totp"] as Record<string, unknown>)["qr_code"] ?? ""),
385
+ secret: String((json["totp"] as Record<string, unknown>)["secret"] ?? ""),
386
+ uri: String((json["totp"] as Record<string, unknown>)["uri"] ?? ""),
387
+ },
388
+ }),
389
+ ...(json["phone"] !== undefined && { phone: String(json["phone"]) }),
390
+ }
391
+ return { data, error: null }
392
+ },
393
+
394
+ /**
395
+ * Create a challenge for an enrolled MFA factor.
396
+ * For TOTP, this simply creates a challenge ID. For Phone, it sends an SMS.
397
+ */
398
+ challenge: async (params: {
399
+ factorId: string
400
+ channel?: "sms" | "whatsapp" | undefined
401
+ }): Promise<{
402
+ data: AuthMFAChallengeResponse | null
403
+ error: SupatypeError | null
404
+ }> => {
405
+ if (this.currentSession === null) {
406
+ return { data: null, error: { message: "Not authenticated" } }
407
+ }
408
+ const body: Record<string, unknown> = {}
409
+ if (params.channel !== undefined) body["channel"] = params.channel
410
+ const res = await fetch(
411
+ `${this.url}/factors/${params.factorId}/challenge`,
412
+ {
413
+ method: "POST",
414
+ headers: {
415
+ ...this.baseHeaders,
416
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
417
+ },
418
+ body: JSON.stringify(body),
419
+ },
420
+ )
421
+ if (!res.ok) {
422
+ return { data: null, error: await this._parseError(res) }
423
+ }
424
+ const json = await res.json() as Record<string, unknown>
425
+ return {
426
+ data: {
427
+ id: String(json["id"] ?? ""),
428
+ type: String(json["type"] ?? ""),
429
+ expiresAt: Number(json["expires_at"] ?? 0),
430
+ },
431
+ error: null,
432
+ }
433
+ },
434
+
435
+ /**
436
+ * Verify an MFA challenge with a TOTP code or phone OTP.
437
+ * On success, elevates the session to AAL2 and returns new tokens.
438
+ */
439
+ verify: async (params: {
440
+ factorId: string
441
+ challengeId: string
442
+ code: string
443
+ }): Promise<{
444
+ data: { session: Session | null; user: User | null }
445
+ error: SupatypeError | null
446
+ }> => {
447
+ if (this.currentSession === null) {
448
+ return {
449
+ data: { session: null, user: null },
450
+ error: { message: "Not authenticated" },
451
+ }
452
+ }
453
+ const res = await fetch(
454
+ `${this.url}/factors/${params.factorId}/verify`,
455
+ {
456
+ method: "POST",
457
+ headers: {
458
+ ...this.baseHeaders,
459
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
460
+ },
461
+ body: JSON.stringify({
462
+ challenge_id: params.challengeId,
463
+ code: params.code,
464
+ }),
465
+ },
466
+ )
467
+ const result = await this._parseAuthResponse(res)
468
+ if (result.data.session !== null) {
469
+ this._emitEvent("MFA_CHALLENGE_VERIFIED", result.data.session)
470
+ }
471
+ return result
472
+ },
473
+
474
+ /**
475
+ * Convenience method: create a challenge and immediately verify it.
476
+ */
477
+ challengeAndVerify: async (params: {
478
+ factorId: string
479
+ code: string
480
+ }): Promise<{
481
+ data: { session: Session | null; user: User | null }
482
+ error: SupatypeError | null
483
+ }> => {
484
+ const challengeResult = await this.mfa.challenge({
485
+ factorId: params.factorId,
486
+ })
487
+ if (challengeResult.error !== null || challengeResult.data === null) {
488
+ return {
489
+ data: { session: null, user: null },
490
+ error: challengeResult.error,
491
+ }
492
+ }
493
+ return this.mfa.verify({
494
+ factorId: params.factorId,
495
+ challengeId: challengeResult.data.id,
496
+ code: params.code,
497
+ })
498
+ },
499
+
500
+ /**
501
+ * Unenroll (remove) an MFA factor. Requires AAL2 for verified factors.
502
+ */
503
+ unenroll: async (params: {
504
+ factorId: string
505
+ }): Promise<{
506
+ data: { id: string } | null
507
+ error: SupatypeError | null
508
+ }> => {
509
+ if (this.currentSession === null) {
510
+ return { data: null, error: { message: "Not authenticated" } }
511
+ }
512
+ const res = await fetch(
513
+ `${this.url}/factors/${params.factorId}`,
514
+ {
515
+ method: "DELETE",
516
+ headers: {
517
+ ...this.baseHeaders,
518
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
519
+ },
520
+ },
521
+ )
522
+ if (!res.ok) {
523
+ return { data: null, error: await this._parseError(res) }
524
+ }
525
+ const json = await res.json() as Record<string, unknown>
526
+ return { data: { id: String(json["id"] ?? "") }, error: null }
527
+ },
528
+
529
+ /**
530
+ * List the user's enrolled MFA factors, categorized by type.
531
+ */
532
+ listFactors: async (): Promise<{
533
+ data: AuthMFAListFactorsResponse | null
534
+ error: SupatypeError | null
535
+ }> => {
536
+ const userResult = await this.getUser()
537
+ if (userResult.error !== null || userResult.data.user === null) {
538
+ return { data: null, error: userResult.error ?? { message: "Could not get user" } }
539
+ }
540
+ const allFactors: Factor[] = userResult.data.user.factors ?? []
541
+ const verifiedFactors = allFactors.filter((f) => f.status === "verified")
542
+ return {
543
+ data: {
544
+ all: allFactors,
545
+ totp: verifiedFactors.filter((f) => f.factorType === "totp"),
546
+ phone: verifiedFactors.filter((f) => f.factorType === "phone"),
547
+ },
548
+ error: null,
549
+ }
550
+ },
551
+
552
+ /**
553
+ * Returns the current Authenticator Assurance Level (AAL) for the session.
554
+ * aal1 = password/otp only; aal2 = MFA verified.
555
+ */
556
+ getAuthenticatorAssuranceLevel: async (): Promise<{
557
+ data: {
558
+ currentLevel: "aal1" | "aal2" | null
559
+ nextLevel: "aal1" | "aal2" | null
560
+ currentAuthenticationMethods: string[]
561
+ } | null
562
+ error: SupatypeError | null
563
+ }> => {
564
+ if (this.currentSession === null) {
565
+ return { data: null, error: { message: "Not authenticated" } }
566
+ }
567
+ // Decode the JWT payload to read the aal and amr claims
568
+ const parts = this.currentSession.accessToken.split(".")
569
+ if (parts.length !== 3) {
570
+ return { data: null, error: { message: "Invalid access token format" } }
571
+ }
572
+ try {
573
+ const payload = JSON.parse(atob(parts[1]!)) as Record<string, unknown>
574
+ const currentLevel = (payload["aal"] as "aal1" | "aal2" | undefined) ?? null
575
+ const amr = (payload["amr"] as Array<{ method: string }> | undefined) ?? []
576
+ const methods = amr.map((entry) => entry.method)
577
+
578
+ // Determine next level: if user has verified factors, next could be aal2
579
+ const userResult = await this.getUser()
580
+ const factors = userResult.data?.user?.factors ?? []
581
+ const hasVerifiedFactors = factors.some((f) => f.status === "verified")
582
+ const nextLevel = hasVerifiedFactors ? "aal2" : "aal1"
583
+
584
+ return {
585
+ data: {
586
+ currentLevel,
587
+ nextLevel: nextLevel as "aal1" | "aal2",
588
+ currentAuthenticationMethods: methods,
589
+ },
590
+ error: null,
591
+ }
592
+ } catch {
593
+ return { data: null, error: { message: "Failed to decode access token" } }
594
+ }
595
+ },
596
+ }
597
+ }
598
+
599
+ onAuthStateChange(callback: AuthListener): {
600
+ data: { subscription: { unsubscribe(): void } }
601
+ } {
602
+ const id = String(++this.listenerIdCounter)
603
+ this.listeners.set(id, callback)
604
+ // Emit current state immediately
605
+ const event: AuthChangeEvent = this.currentSession !== null ? "SIGNED_IN" : "SIGNED_OUT"
606
+ callback(event, this.currentSession)
607
+ return {
608
+ data: {
609
+ subscription: {
610
+ unsubscribe: () => {
611
+ this.listeners.delete(id)
612
+ },
613
+ },
614
+ },
615
+ }
616
+ }
617
+
618
+ // ─── Internal ────────────────────────────────────────────────────────────────
619
+
620
+ _setSession(session: Session | null): void {
621
+ const prev = this.currentSession
622
+ this.currentSession = session
623
+ const event: AuthChangeEvent =
624
+ session !== null
625
+ ? prev !== null
626
+ ? "TOKEN_REFRESHED"
627
+ : "SIGNED_IN"
628
+ : "SIGNED_OUT"
629
+ for (const cb of this.listeners.values()) {
630
+ cb(event, session)
631
+ }
632
+ }
633
+
634
+ private _emitEvent(event: AuthChangeEvent, session: Session | null): void {
635
+ for (const cb of this.listeners.values()) {
636
+ cb(event, session)
637
+ }
638
+ }
639
+
640
+ private async _parseError(res: Response): Promise<SupatypeError> {
641
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
642
+ return {
643
+ message: String(err["error_description"] ?? err["msg"] ?? err["message"] ?? "Error"),
644
+ status: res.status,
645
+ ...(err["error_code"] !== undefined && { code: String(err["error_code"]) }),
646
+ }
647
+ }
648
+
649
+ private async _parseAuthResponse(res: Response): Promise<{
650
+ data: { session: Session | null; user: User | null }
651
+ error: SupatypeError | null
652
+ }> {
653
+ if (!res.ok) {
654
+ const err = await res.json().catch(() => ({ msg: "Unknown error" })) as Record<string, unknown>
655
+ return {
656
+ data: { session: null, user: null },
657
+ error: {
658
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
659
+ status: res.status,
660
+ },
661
+ }
662
+ }
663
+ const json = await res.json() as Record<string, unknown>
664
+ const user = this._parseUser((json["user"] ?? {}) as Record<string, unknown>)
665
+ const session: Session = {
666
+ accessToken: String(json["access_token"] ?? ""),
667
+ tokenType: String(json["token_type"] ?? "bearer"),
668
+ expiresIn: Number(json["expires_in"] ?? 3600),
669
+ ...(json["expires_at"] !== undefined && { expiresAt: Number(json["expires_at"]) }),
670
+ refreshToken: String(json["refresh_token"] ?? ""),
671
+ user,
672
+ }
673
+ this._setSession(session)
674
+ return { data: { session, user }, error: null }
675
+ }
676
+
677
+ private _parseUser(raw: Record<string, unknown>): User {
678
+ const user: User = {
679
+ id: String(raw["id"] ?? ""),
680
+ ...(raw["email"] !== undefined && { email: String(raw["email"]) }),
681
+ ...(raw["phone"] !== undefined && { phone: String(raw["phone"]) }),
682
+ ...(raw["role"] !== undefined && { role: String(raw["role"]) }),
683
+ appMetadata: (raw["app_metadata"] ?? {}) as Record<string, unknown>,
684
+ userMetadata: (raw["user_metadata"] ?? {}) as Record<string, unknown>,
685
+ createdAt: String(raw["created_at"] ?? ""),
686
+ updatedAt: String(raw["updated_at"] ?? ""),
687
+ }
688
+ if (Array.isArray(raw["identities"])) {
689
+ user.identities = (raw["identities"] as Record<string, unknown>[]).map((i) => ({
690
+ id: String(i["id"] ?? ""),
691
+ userId: String(i["user_id"] ?? ""),
692
+ identityData: (i["identity_data"] ?? {}) as Record<string, unknown>,
693
+ identityId: String(i["identity_id"] ?? ""),
694
+ provider: String(i["provider"] ?? ""),
695
+ createdAt: String(i["created_at"] ?? ""),
696
+ updatedAt: String(i["updated_at"] ?? ""),
697
+ ...(i["last_sign_in_at"] !== undefined && { lastSignInAt: String(i["last_sign_in_at"]) }),
698
+ }))
699
+ }
700
+ if (Array.isArray(raw["factors"])) {
701
+ user.factors = (raw["factors"] as Record<string, unknown>[]).map((f) => ({
702
+ id: String(f["id"] ?? ""),
703
+ factorType: String(f["factor_type"] ?? "totp") as "totp" | "phone" | "webauthn",
704
+ status: String(f["status"] ?? "unverified") as "verified" | "unverified",
705
+ createdAt: String(f["created_at"] ?? ""),
706
+ updatedAt: String(f["updated_at"] ?? ""),
707
+ ...(f["friendly_name"] !== undefined && { friendlyName: String(f["friendly_name"]) }),
708
+ ...(f["phone"] !== undefined && { phone: String(f["phone"]) }),
709
+ }))
710
+ }
711
+ return user
712
+ }
713
+ }