@supatype/client 0.1.0-alpha.10

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 +23 -0
  3. package/.turbo/turbo-typecheck.log +4 -0
  4. package/dist/auth.d.ts +279 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +848 -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 +151 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +285 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/query.d.ts +55 -0
  25. package/dist/query.d.ts.map +1 -0
  26. package/dist/query.js +264 -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 +102 -0
  41. package/dist/storage.d.ts.map +1 -0
  42. package/dist/storage.js +169 -0
  43. package/dist/storage.js.map +1 -0
  44. package/dist/types.d.ts +212 -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 +1024 -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 +518 -0
  54. package/src/query.ts +331 -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 +234 -0
  59. package/src/types.ts +264 -0
  60. package/tests/auth.test.ts +351 -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 +137 -0
  70. package/tsconfig.json +11 -0
  71. package/tsconfig.tsbuildinfo +1 -0
package/src/auth.ts ADDED
@@ -0,0 +1,1024 @@
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
+ interface AuthStorageAdapter {
16
+ getItem(key: string): string | null
17
+ setItem(key: string, value: string): void
18
+ removeItem(key: string): void
19
+ }
20
+
21
+ interface AuthClientOptions {
22
+ initialSession?: Session | undefined
23
+ persistSession?: boolean | undefined
24
+ storageKey?: string | undefined
25
+ cookiePrefix?: string | undefined
26
+ }
27
+
28
+ const DEFAULT_STORAGE_KEY = "supatype.auth.session"
29
+ const DEFAULT_COOKIE_PREFIX = "st"
30
+ const DEBUG_AUTH = typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1"
31
+
32
+ export class AuthClient {
33
+ private readonly url: string
34
+ private readonly baseHeaders: Record<string, string>
35
+ private currentSession: Session | null = null
36
+ private readonly listeners = new Map<string, AuthListener>()
37
+ private listenerIdCounter = 0
38
+ private readonly persistSession: boolean
39
+ private readonly storageKey: string
40
+ private readonly cookieName: string
41
+ private readonly storage: AuthStorageAdapter | null
42
+ /** Pending auto-refresh timer; refreshes the access token shortly before it expires. */
43
+ private refreshTimer: ReturnType<typeof setTimeout> | null = null
44
+
45
+ constructor(url: string, baseHeaders: Record<string, string>, opts: AuthClientOptions = {}) {
46
+ this.url = url
47
+ this.baseHeaders = baseHeaders
48
+ this.persistSession = opts.persistSession ?? true
49
+ this.storageKey = opts.storageKey ?? DEFAULT_STORAGE_KEY
50
+ const cookiePrefix = opts.cookiePrefix ?? DEFAULT_COOKIE_PREFIX
51
+ this.cookieName = `${cookiePrefix}-auth-token`
52
+ this.storage = this.getBrowserStorage()
53
+
54
+ if (opts.initialSession !== undefined) {
55
+ this.currentSession = opts.initialSession
56
+ if (DEBUG_AUTH) {
57
+ console.debug("[supatype:auth] constructor initialSession provided", {
58
+ hasSession: true,
59
+ userId: opts.initialSession.user.id,
60
+ })
61
+ }
62
+ } else if (this.persistSession) {
63
+ this.currentSession = this.loadPersistedSession()
64
+ if (DEBUG_AUTH) {
65
+ console.debug("[supatype:auth] constructor loaded persisted session", {
66
+ hasSession: this.currentSession !== null,
67
+ userId: this.currentSession?.user.id ?? null,
68
+ storageKey: this.storageKey,
69
+ cookieName: this.cookieName,
70
+ })
71
+ }
72
+ }
73
+ // Keep the access token fresh while the app is open (and refresh immediately
74
+ // if a persisted session loaded already expired).
75
+ this.scheduleAutoRefresh()
76
+ }
77
+
78
+ /** Schedule a token refresh ~60s before the current session expires. */
79
+ private scheduleAutoRefresh(): void {
80
+ if (this.refreshTimer !== null) {
81
+ clearTimeout(this.refreshTimer)
82
+ this.refreshTimer = null
83
+ }
84
+ if (typeof setTimeout === "undefined") return
85
+ const session = this.currentSession
86
+ if (session === null || !session.refreshToken) return
87
+
88
+ const expiryMs =
89
+ session.expiresAt !== undefined
90
+ ? session.expiresAt * 1000
91
+ : Date.now() + (session.expiresIn || 3600) * 1000
92
+ const delay = Math.max(0, expiryMs - Date.now() - 60_000)
93
+
94
+ this.refreshTimer = setTimeout(() => {
95
+ this.refreshTimer = null
96
+ // refreshSession() flows through _setSession on success, which reschedules.
97
+ void this.refreshSession().catch(() => undefined)
98
+ }, delay)
99
+ // Avoid keeping a Node process alive for this timer (no-op in browsers).
100
+ ;(this.refreshTimer as unknown as { unref?: () => void }).unref?.()
101
+ }
102
+
103
+ async signUp(credentials: {
104
+ email: string
105
+ password: string
106
+ options?: { data?: Record<string, unknown> } | undefined
107
+ }): Promise<{
108
+ data: { session: Session | null; user: User | null }
109
+ error: SupatypeError | null
110
+ }> {
111
+ const body: Record<string, unknown> = {
112
+ email: credentials.email,
113
+ password: credentials.password,
114
+ }
115
+ if (credentials.options?.data !== undefined) {
116
+ body["data"] = credentials.options.data
117
+ }
118
+ const res = await fetch(`${this.url}/signup`, {
119
+ method: "POST",
120
+ headers: this.baseHeaders,
121
+ body: JSON.stringify(body),
122
+ })
123
+ return this._parseAuthResponse(res)
124
+ }
125
+
126
+ async signInWithPassword(credentials: {
127
+ email: string
128
+ password: string
129
+ }): Promise<{
130
+ data: { session: Session | null; user: User | null }
131
+ error: SupatypeError | null
132
+ }> {
133
+ const res = await fetch(`${this.url}/token?grant_type=password`, {
134
+ method: "POST",
135
+ headers: this.baseHeaders,
136
+ body: JSON.stringify({
137
+ email: credentials.email,
138
+ password: credentials.password,
139
+ }),
140
+ })
141
+ return this._parseAuthResponse(res)
142
+ }
143
+
144
+ async signInAnonymously(credentials?: {
145
+ options?: {
146
+ data?: Record<string, unknown> | undefined
147
+ captchaToken?: string | undefined
148
+ } | undefined
149
+ }): Promise<{
150
+ data: { session: Session | null; user: User | null }
151
+ error: SupatypeError | null
152
+ }> {
153
+ const body: Record<string, unknown> = {}
154
+ if (credentials?.options?.data !== undefined) {
155
+ body["data"] = credentials.options.data
156
+ }
157
+ if (credentials?.options?.captchaToken !== undefined) {
158
+ body["gotrue_meta_security"] = { captcha_token: credentials.options.captchaToken }
159
+ }
160
+ const res = await fetch(`${this.url}/signup`, {
161
+ method: "POST",
162
+ headers: this.baseHeaders,
163
+ body: JSON.stringify(body),
164
+ })
165
+ return this._parseAuthResponse(res)
166
+ }
167
+
168
+ async signInWithOAuth(opts: {
169
+ provider: string
170
+ options?: { redirectTo?: string | undefined } | undefined
171
+ }): Promise<{
172
+ data: { url: string; provider: string }
173
+ error: SupatypeError | null
174
+ }> {
175
+ const url = new URL(`${this.url}/authorize`)
176
+ url.searchParams.set("provider", opts.provider)
177
+ if (opts.options?.redirectTo !== undefined) {
178
+ url.searchParams.set("redirect_to", opts.options.redirectTo)
179
+ }
180
+ return { data: { url: url.toString(), provider: opts.provider }, error: null }
181
+ }
182
+
183
+ async signInWithOtp(opts: {
184
+ email?: string | undefined
185
+ phone?: string | undefined
186
+ options?: {
187
+ emailRedirectTo?: string | undefined
188
+ channel?: "sms" | "whatsapp" | undefined
189
+ createUser?: boolean | undefined
190
+ } | undefined
191
+ }): Promise<{ data: { messageId?: string | undefined }; error: SupatypeError | null }> {
192
+ const body: Record<string, unknown> = {
193
+ create_user: opts.options?.createUser ?? true,
194
+ }
195
+ if (opts.email !== undefined) {
196
+ body["email"] = opts.email
197
+ }
198
+ if (opts.phone !== undefined) {
199
+ body["phone"] = opts.phone
200
+ if (opts.options?.channel !== undefined) {
201
+ body["channel"] = opts.options.channel
202
+ }
203
+ }
204
+ const res = await fetch(`${this.url}/otp`, {
205
+ method: "POST",
206
+ headers: this.baseHeaders,
207
+ body: JSON.stringify(body),
208
+ })
209
+ if (res.ok) {
210
+ const json = await res.json().catch(() => ({})) as Record<string, unknown>
211
+ return {
212
+ data: {
213
+ ...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
214
+ },
215
+ error: null,
216
+ }
217
+ }
218
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
219
+ return {
220
+ data: {},
221
+ error: {
222
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
223
+ status: res.status,
224
+ },
225
+ }
226
+ }
227
+
228
+ async signOut(): Promise<{ error: SupatypeError | null }> {
229
+ if (this.currentSession !== null) {
230
+ await fetch(`${this.url}/logout`, {
231
+ method: "POST",
232
+ headers: {
233
+ ...this.baseHeaders,
234
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
235
+ },
236
+ }).catch(() => undefined)
237
+ }
238
+ this._setSession(null)
239
+ return { error: null }
240
+ }
241
+
242
+ async getSession(): Promise<{
243
+ data: { session: Session | null }
244
+ error: SupatypeError | null
245
+ }> {
246
+ return { data: { session: this.currentSession }, error: null }
247
+ }
248
+
249
+ async getUser(): Promise<{
250
+ data: { user: User | null }
251
+ error: SupatypeError | null
252
+ }> {
253
+ if (this.currentSession === null) {
254
+ return { data: { user: null }, error: null }
255
+ }
256
+ const res = await fetch(`${this.url}/user`, {
257
+ headers: {
258
+ ...this.baseHeaders,
259
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
260
+ },
261
+ })
262
+ if (!res.ok) {
263
+ return {
264
+ data: { user: null },
265
+ error: { message: "Could not get user", status: res.status },
266
+ }
267
+ }
268
+ const raw = await res.json() as Record<string, unknown>
269
+ return { data: { user: this._parseUser(raw) }, error: null }
270
+ }
271
+
272
+ async refreshSession(): Promise<{
273
+ data: { session: Session | null }
274
+ error: SupatypeError | null
275
+ }> {
276
+ if (this.currentSession === null) {
277
+ return { data: { session: null }, error: { message: "No active session" } }
278
+ }
279
+ const res = await fetch(`${this.url}/token?grant_type=refresh_token`, {
280
+ method: "POST",
281
+ headers: this.baseHeaders,
282
+ body: JSON.stringify({ refresh_token: this.currentSession.refreshToken }),
283
+ })
284
+ const result = await this._parseAuthResponse(res)
285
+ return { data: { session: result.data.session }, error: result.error }
286
+ }
287
+
288
+ async resetPasswordForEmail(
289
+ email: string,
290
+ options?: { redirectTo?: string | undefined } | undefined,
291
+ ): Promise<{ data: Record<string, never>; error: SupatypeError | null }> {
292
+ const body: Record<string, unknown> = { email }
293
+ if (options?.redirectTo !== undefined) {
294
+ body["redirect_to"] = options.redirectTo
295
+ }
296
+ const res = await fetch(`${this.url}/recover`, {
297
+ method: "POST",
298
+ headers: this.baseHeaders,
299
+ body: JSON.stringify(body),
300
+ })
301
+ if (res.ok) return { data: {}, error: null }
302
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
303
+ return {
304
+ data: {},
305
+ error: {
306
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
307
+ status: res.status,
308
+ },
309
+ }
310
+ }
311
+
312
+ async updateUser(updates: {
313
+ email?: string | undefined
314
+ password?: string | undefined
315
+ data?: Record<string, unknown> | undefined
316
+ }): Promise<{ data: { user: User | null }; error: SupatypeError | null }> {
317
+ if (this.currentSession === null) {
318
+ return { data: { user: null }, error: { message: "Not authenticated" } }
319
+ }
320
+ const res = await fetch(`${this.url}/user`, {
321
+ method: "PUT",
322
+ headers: {
323
+ ...this.baseHeaders,
324
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
325
+ },
326
+ body: JSON.stringify(updates),
327
+ })
328
+ if (!res.ok) {
329
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
330
+ return {
331
+ data: { user: null },
332
+ error: {
333
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
334
+ status: res.status,
335
+ },
336
+ }
337
+ }
338
+ const raw = await res.json() as Record<string, unknown>
339
+ return { data: { user: this._parseUser(raw) }, error: null }
340
+ }
341
+
342
+ /**
343
+ * Verify an OTP token received via email or phone.
344
+ * Completes email confirmation, magic link, recovery, or phone OTP flows.
345
+ */
346
+ async verifyOtp(params: {
347
+ token: string
348
+ type: OtpType
349
+ email?: string | undefined
350
+ phone?: string | undefined
351
+ tokenHash?: string | undefined
352
+ }): Promise<{
353
+ data: { session: Session | null; user: User | null }
354
+ error: SupatypeError | null
355
+ }> {
356
+ const body: Record<string, unknown> = {
357
+ type: params.type,
358
+ }
359
+ if (params.tokenHash !== undefined) {
360
+ body["token_hash"] = params.tokenHash
361
+ } else {
362
+ body["token"] = params.token
363
+ if (params.email !== undefined) body["email"] = params.email
364
+ if (params.phone !== undefined) body["phone"] = params.phone
365
+ }
366
+ const res = await fetch(`${this.url}/verify`, {
367
+ method: "POST",
368
+ headers: this.baseHeaders,
369
+ body: JSON.stringify(body),
370
+ })
371
+ return this._parseAuthResponse(res)
372
+ }
373
+
374
+ /**
375
+ * Sign in with an ID token from an external provider (e.g. Google One Tap).
376
+ * Uses the token grant with id_token grant type.
377
+ */
378
+ async signInWithIdToken(credentials: {
379
+ provider: "google" | "apple" | string
380
+ token: string
381
+ nonce?: string | undefined
382
+ }): Promise<{
383
+ data: { session: Session | null; user: User | null }
384
+ error: SupatypeError | null
385
+ }> {
386
+ const body: Record<string, unknown> = {
387
+ provider: credentials.provider,
388
+ id_token: credentials.token,
389
+ }
390
+ if (credentials.nonce !== undefined) {
391
+ body["nonce"] = credentials.nonce
392
+ }
393
+ const res = await fetch(`${this.url}/token?grant_type=id_token`, {
394
+ method: "POST",
395
+ headers: this.baseHeaders,
396
+ body: JSON.stringify(body),
397
+ })
398
+ return this._parseAuthResponse(res)
399
+ }
400
+
401
+ /**
402
+ * Resend an OTP or confirmation email/SMS.
403
+ */
404
+ async resend(params: {
405
+ type: "signup" | "sms" | "phone_change" | "email_change"
406
+ email?: string | undefined
407
+ phone?: string | undefined
408
+ }): Promise<{ data: { messageId?: string | undefined }; error: SupatypeError | null }> {
409
+ const body: Record<string, unknown> = { type: params.type }
410
+ if (params.email !== undefined) body["email"] = params.email
411
+ if (params.phone !== undefined) body["phone"] = params.phone
412
+ const res = await fetch(`${this.url}/resend`, {
413
+ method: "POST",
414
+ headers: this.baseHeaders,
415
+ body: JSON.stringify(body),
416
+ })
417
+ if (res.ok) {
418
+ const json = await res.json().catch(() => ({})) as Record<string, unknown>
419
+ return {
420
+ data: {
421
+ ...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
422
+ },
423
+ error: null,
424
+ }
425
+ }
426
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
427
+ return {
428
+ data: {},
429
+ error: {
430
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
431
+ status: res.status,
432
+ },
433
+ }
434
+ }
435
+
436
+ // ─── MFA ──────────────────────────────────────────────────────────────────────
437
+
438
+ /**
439
+ * Multi-Factor Authentication namespace.
440
+ * Provides methods for enrolling, challenging, and verifying MFA factors.
441
+ */
442
+ get mfa() {
443
+ return {
444
+ /**
445
+ * Enroll a new MFA factor (TOTP or Phone).
446
+ * Returns the factor ID and, for TOTP, the QR code and secret.
447
+ */
448
+ enroll: async (params: {
449
+ factorType: "totp" | "phone"
450
+ friendlyName?: string | undefined
451
+ issuer?: string | undefined
452
+ phone?: string | undefined
453
+ }): Promise<{
454
+ data: AuthMFAEnrollResponse | null
455
+ error: SupatypeError | null
456
+ }> => {
457
+ if (this.currentSession === null) {
458
+ return { data: null, error: { message: "Not authenticated" } }
459
+ }
460
+ const body: Record<string, unknown> = {
461
+ factor_type: params.factorType,
462
+ }
463
+ if (params.friendlyName !== undefined) body["friendly_name"] = params.friendlyName
464
+ if (params.issuer !== undefined) body["issuer"] = params.issuer
465
+ if (params.phone !== undefined) body["phone"] = params.phone
466
+ const res = await fetch(`${this.url}/factors`, {
467
+ method: "POST",
468
+ headers: {
469
+ ...this.baseHeaders,
470
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
471
+ },
472
+ body: JSON.stringify(body),
473
+ })
474
+ if (!res.ok) {
475
+ return { data: null, error: await this._parseError(res) }
476
+ }
477
+ const json = await res.json() as Record<string, unknown>
478
+ const data: AuthMFAEnrollResponse = {
479
+ id: String(json["id"] ?? ""),
480
+ type: String(json["type"] ?? ""),
481
+ friendlyName: String(json["friendly_name"] ?? ""),
482
+ ...(json["totp"] !== undefined && {
483
+ totp: {
484
+ qrCode: String((json["totp"] as Record<string, unknown>)["qr_code"] ?? ""),
485
+ secret: String((json["totp"] as Record<string, unknown>)["secret"] ?? ""),
486
+ uri: String((json["totp"] as Record<string, unknown>)["uri"] ?? ""),
487
+ },
488
+ }),
489
+ ...(json["phone"] !== undefined && { phone: String(json["phone"]) }),
490
+ }
491
+ return { data, error: null }
492
+ },
493
+
494
+ /**
495
+ * Create a challenge for an enrolled MFA factor.
496
+ * For TOTP, this simply creates a challenge ID. For Phone, it sends an SMS.
497
+ */
498
+ challenge: async (params: {
499
+ factorId: string
500
+ channel?: "sms" | "whatsapp" | undefined
501
+ }): Promise<{
502
+ data: AuthMFAChallengeResponse | null
503
+ error: SupatypeError | null
504
+ }> => {
505
+ if (this.currentSession === null) {
506
+ return { data: null, error: { message: "Not authenticated" } }
507
+ }
508
+ const body: Record<string, unknown> = {}
509
+ if (params.channel !== undefined) body["channel"] = params.channel
510
+ const res = await fetch(
511
+ `${this.url}/factors/${params.factorId}/challenge`,
512
+ {
513
+ method: "POST",
514
+ headers: {
515
+ ...this.baseHeaders,
516
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
517
+ },
518
+ body: JSON.stringify(body),
519
+ },
520
+ )
521
+ if (!res.ok) {
522
+ return { data: null, error: await this._parseError(res) }
523
+ }
524
+ const json = await res.json() as Record<string, unknown>
525
+ return {
526
+ data: {
527
+ id: String(json["id"] ?? ""),
528
+ type: String(json["type"] ?? ""),
529
+ expiresAt: Number(json["expires_at"] ?? 0),
530
+ },
531
+ error: null,
532
+ }
533
+ },
534
+
535
+ /**
536
+ * Verify an MFA challenge with a TOTP code or phone OTP.
537
+ * On success, elevates the session to AAL2 and returns new tokens.
538
+ */
539
+ verify: async (params: {
540
+ factorId: string
541
+ challengeId: string
542
+ code: string
543
+ }): Promise<{
544
+ data: { session: Session | null; user: User | null }
545
+ error: SupatypeError | null
546
+ }> => {
547
+ if (this.currentSession === null) {
548
+ return {
549
+ data: { session: null, user: null },
550
+ error: { message: "Not authenticated" },
551
+ }
552
+ }
553
+ const res = await fetch(
554
+ `${this.url}/factors/${params.factorId}/verify`,
555
+ {
556
+ method: "POST",
557
+ headers: {
558
+ ...this.baseHeaders,
559
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
560
+ },
561
+ body: JSON.stringify({
562
+ challenge_id: params.challengeId,
563
+ code: params.code,
564
+ }),
565
+ },
566
+ )
567
+ const result = await this._parseAuthResponse(res)
568
+ if (result.data.session !== null) {
569
+ this._emitEvent("MFA_CHALLENGE_VERIFIED", result.data.session)
570
+ }
571
+ return result
572
+ },
573
+
574
+ /**
575
+ * Convenience method: create a challenge and immediately verify it.
576
+ */
577
+ challengeAndVerify: async (params: {
578
+ factorId: string
579
+ code: string
580
+ }): Promise<{
581
+ data: { session: Session | null; user: User | null }
582
+ error: SupatypeError | null
583
+ }> => {
584
+ const challengeResult = await this.mfa.challenge({
585
+ factorId: params.factorId,
586
+ })
587
+ if (challengeResult.error !== null || challengeResult.data === null) {
588
+ return {
589
+ data: { session: null, user: null },
590
+ error: challengeResult.error,
591
+ }
592
+ }
593
+ return this.mfa.verify({
594
+ factorId: params.factorId,
595
+ challengeId: challengeResult.data.id,
596
+ code: params.code,
597
+ })
598
+ },
599
+
600
+ /**
601
+ * Unenroll (remove) an MFA factor. Requires AAL2 for verified factors.
602
+ */
603
+ unenroll: async (params: {
604
+ factorId: string
605
+ }): Promise<{
606
+ data: { id: string } | null
607
+ error: SupatypeError | null
608
+ }> => {
609
+ if (this.currentSession === null) {
610
+ return { data: null, error: { message: "Not authenticated" } }
611
+ }
612
+ const res = await fetch(
613
+ `${this.url}/factors/${params.factorId}`,
614
+ {
615
+ method: "DELETE",
616
+ headers: {
617
+ ...this.baseHeaders,
618
+ Authorization: `Bearer ${this.currentSession.accessToken}`,
619
+ },
620
+ },
621
+ )
622
+ if (!res.ok) {
623
+ return { data: null, error: await this._parseError(res) }
624
+ }
625
+ const json = await res.json() as Record<string, unknown>
626
+ return { data: { id: String(json["id"] ?? "") }, error: null }
627
+ },
628
+
629
+ /**
630
+ * List the user's enrolled MFA factors, categorized by type.
631
+ */
632
+ listFactors: async (): Promise<{
633
+ data: AuthMFAListFactorsResponse | null
634
+ error: SupatypeError | null
635
+ }> => {
636
+ const userResult = await this.getUser()
637
+ if (userResult.error !== null || userResult.data.user === null) {
638
+ return { data: null, error: userResult.error ?? { message: "Could not get user" } }
639
+ }
640
+ const allFactors: Factor[] = userResult.data.user.factors ?? []
641
+ const verifiedFactors = allFactors.filter((f) => f.status === "verified")
642
+ return {
643
+ data: {
644
+ all: allFactors,
645
+ totp: verifiedFactors.filter((f) => f.factorType === "totp"),
646
+ phone: verifiedFactors.filter((f) => f.factorType === "phone"),
647
+ },
648
+ error: null,
649
+ }
650
+ },
651
+
652
+ /**
653
+ * Returns the current Authenticator Assurance Level (AAL) for the session.
654
+ * aal1 = password/otp only; aal2 = MFA verified.
655
+ */
656
+ getAuthenticatorAssuranceLevel: async (): Promise<{
657
+ data: {
658
+ currentLevel: "aal1" | "aal2" | null
659
+ nextLevel: "aal1" | "aal2" | null
660
+ currentAuthenticationMethods: string[]
661
+ } | null
662
+ error: SupatypeError | null
663
+ }> => {
664
+ if (this.currentSession === null) {
665
+ return { data: null, error: { message: "Not authenticated" } }
666
+ }
667
+ // Decode the JWT payload to read the aal and amr claims
668
+ const parts = this.currentSession.accessToken.split(".")
669
+ if (parts.length !== 3) {
670
+ return { data: null, error: { message: "Invalid access token format" } }
671
+ }
672
+ try {
673
+ const payload = JSON.parse(atob(parts[1]!)) as Record<string, unknown>
674
+ const currentLevel = (payload["aal"] as "aal1" | "aal2" | undefined) ?? null
675
+ const amr = (payload["amr"] as Array<{ method: string }> | undefined) ?? []
676
+ const methods = amr.map((entry) => entry.method)
677
+
678
+ // Determine next level: if user has verified factors, next could be aal2
679
+ const userResult = await this.getUser()
680
+ const factors = userResult.data?.user?.factors ?? []
681
+ const hasVerifiedFactors = factors.some((f) => f.status === "verified")
682
+ const nextLevel = hasVerifiedFactors ? "aal2" : "aal1"
683
+
684
+ return {
685
+ data: {
686
+ currentLevel,
687
+ nextLevel: nextLevel as "aal1" | "aal2",
688
+ currentAuthenticationMethods: methods,
689
+ },
690
+ error: null,
691
+ }
692
+ } catch {
693
+ return { data: null, error: { message: "Failed to decode access token" } }
694
+ }
695
+ },
696
+ }
697
+ }
698
+
699
+ onAuthStateChange(callback: AuthListener): {
700
+ data: { subscription: { unsubscribe(): void } }
701
+ } {
702
+ const id = String(++this.listenerIdCounter)
703
+ this.listeners.set(id, callback)
704
+ // Emit current state immediately
705
+ const event: AuthChangeEvent = this.currentSession !== null ? "SIGNED_IN" : "SIGNED_OUT"
706
+ callback(event, this.currentSession)
707
+ return {
708
+ data: {
709
+ subscription: {
710
+ unsubscribe: () => {
711
+ this.listeners.delete(id)
712
+ },
713
+ },
714
+ },
715
+ }
716
+ }
717
+
718
+ // ─── Internal ────────────────────────────────────────────────────────────────
719
+
720
+ /** Returns the current session's access token, or null when signed out. */
721
+ get currentAccessToken(): string | null {
722
+ return this.currentSession?.accessToken ?? null
723
+ }
724
+
725
+ private getBrowserStorage(): AuthStorageAdapter | null {
726
+ if (typeof window === "undefined") return null
727
+ try {
728
+ return window.localStorage
729
+ } catch {
730
+ return null
731
+ }
732
+ }
733
+
734
+ private loadPersistedSession(): Session | null {
735
+ const fromStorage = this.storage?.getItem(this.storageKey) ?? null
736
+ if (fromStorage !== null) {
737
+ const parsed = this.parsePersistedSession(fromStorage)
738
+ if (DEBUG_AUTH) {
739
+ console.debug("[supatype:auth] loadPersistedSession localStorage", {
740
+ found: true,
741
+ parsed: parsed !== null,
742
+ })
743
+ }
744
+ if (parsed !== null) return parsed
745
+ }
746
+ if (typeof document !== "undefined") {
747
+ const fromCookie = this.readCookie(this.cookieName)
748
+ if (fromCookie !== null) {
749
+ const parsed = this.parsePersistedSession(fromCookie)
750
+ if (DEBUG_AUTH) {
751
+ console.debug("[supatype:auth] loadPersistedSession cookie", {
752
+ found: true,
753
+ parsed: parsed !== null,
754
+ cookieName: this.cookieName,
755
+ })
756
+ }
757
+ if (parsed !== null) return parsed
758
+ }
759
+ }
760
+ return null
761
+ }
762
+
763
+ private parsePersistedSession(raw: string): Session | null {
764
+ try {
765
+ const parsed = JSON.parse(raw) as unknown
766
+ return this.normalizePersistedSession(parsed)
767
+ } catch {
768
+ return null
769
+ }
770
+ }
771
+
772
+ private normalizePersistedSession(raw: unknown): Session | null {
773
+ if (typeof raw !== "object" || raw === null) return null
774
+ const r = raw as Record<string, unknown>
775
+ const accessToken =
776
+ typeof r["accessToken"] === "string"
777
+ ? r["accessToken"]
778
+ : typeof r["access_token"] === "string"
779
+ ? r["access_token"]
780
+ : null
781
+ if (accessToken === null) return null
782
+ const refreshToken =
783
+ typeof r["refreshToken"] === "string"
784
+ ? r["refreshToken"]
785
+ : typeof r["refresh_token"] === "string"
786
+ ? r["refresh_token"]
787
+ : ""
788
+ const tokenType =
789
+ typeof r["tokenType"] === "string"
790
+ ? r["tokenType"]
791
+ : typeof r["token_type"] === "string"
792
+ ? r["token_type"]
793
+ : "bearer"
794
+ const expiresIn =
795
+ typeof r["expiresIn"] === "number"
796
+ ? r["expiresIn"]
797
+ : typeof r["expires_in"] === "number"
798
+ ? r["expires_in"]
799
+ : 3600
800
+ const userRaw =
801
+ typeof r["user"] === "object" && r["user"] !== null
802
+ ? (r["user"] as Record<string, unknown>)
803
+ : null
804
+ if (userRaw === null) return null
805
+ const normalizedUserRaw: Record<string, unknown> = {
806
+ ...userRaw,
807
+ ...(userRaw["app_metadata"] === undefined &&
808
+ userRaw["appMetadata"] !== undefined && { app_metadata: userRaw["appMetadata"] }),
809
+ ...(userRaw["user_metadata"] === undefined &&
810
+ userRaw["userMetadata"] !== undefined && { user_metadata: userRaw["userMetadata"] }),
811
+ ...(userRaw["created_at"] === undefined &&
812
+ userRaw["createdAt"] !== undefined && { created_at: userRaw["createdAt"] }),
813
+ ...(userRaw["updated_at"] === undefined &&
814
+ userRaw["updatedAt"] !== undefined && { updated_at: userRaw["updatedAt"] }),
815
+ }
816
+ const session: Session = {
817
+ accessToken,
818
+ refreshToken,
819
+ tokenType,
820
+ expiresIn,
821
+ user: this._parseUser(normalizedUserRaw),
822
+ ...(typeof r["expiresAt"] === "number"
823
+ ? { expiresAt: r["expiresAt"] }
824
+ : typeof r["expires_at"] === "number"
825
+ ? { expiresAt: r["expires_at"] }
826
+ : {}),
827
+ }
828
+ return session
829
+ }
830
+
831
+ private syncPersistedSession(session: Session | null): void {
832
+ if (!this.persistSession) return
833
+ const storage = this.storage
834
+ const cookieExpires = session?.expiresAt
835
+ if (session === null) {
836
+ try {
837
+ storage?.removeItem(this.storageKey)
838
+ } catch {
839
+ // Ignore storage write failures.
840
+ }
841
+ this.writeCookie(this.cookieName, "", -1)
842
+ if (DEBUG_AUTH) {
843
+ console.debug("[supatype:auth] cleared persisted session", {
844
+ storageKey: this.storageKey,
845
+ cookieName: this.cookieName,
846
+ })
847
+ }
848
+ return
849
+ }
850
+
851
+ const json = JSON.stringify(session)
852
+ const cookiePayload = JSON.stringify({
853
+ access_token: session.accessToken,
854
+ refresh_token: session.refreshToken,
855
+ token_type: session.tokenType,
856
+ expires_in: session.expiresIn,
857
+ ...(session.expiresAt !== undefined && { expires_at: session.expiresAt }),
858
+ user: this.serializeUserForCookie(session.user),
859
+ })
860
+ try {
861
+ storage?.setItem(this.storageKey, json)
862
+ } catch {
863
+ // Ignore storage write failures.
864
+ }
865
+ this.writeCookie(this.cookieName, cookiePayload, cookieExpires)
866
+ if (DEBUG_AUTH) {
867
+ console.debug("[supatype:auth] persisted session", {
868
+ userId: session.user.id,
869
+ storageKey: this.storageKey,
870
+ cookieName: this.cookieName,
871
+ hasExpiresAt: session.expiresAt !== undefined,
872
+ })
873
+ }
874
+ }
875
+
876
+ private serializeUserForCookie(user: User): Record<string, unknown> {
877
+ return {
878
+ id: user.id,
879
+ ...(user.email !== undefined && { email: user.email }),
880
+ ...(user.phone !== undefined && { phone: user.phone }),
881
+ ...(user.role !== undefined && { role: user.role }),
882
+ app_metadata: user.appMetadata,
883
+ user_metadata: user.userMetadata,
884
+ created_at: user.createdAt,
885
+ updated_at: user.updatedAt,
886
+ }
887
+ }
888
+
889
+ private readCookie(name: string): string | null {
890
+ if (typeof document === "undefined") return null
891
+ const all = document.cookie ? document.cookie.split("; ") : []
892
+ for (const item of all) {
893
+ const idx = item.indexOf("=")
894
+ if (idx <= 0) continue
895
+ const key = item.slice(0, idx)
896
+ if (key !== name) continue
897
+ const value = item.slice(idx + 1)
898
+ try {
899
+ return decodeURIComponent(value)
900
+ } catch {
901
+ return value
902
+ }
903
+ }
904
+ return null
905
+ }
906
+
907
+ private writeCookie(name: string, value: string, expiresAtSeconds?: number): void {
908
+ if (typeof document === "undefined") return
909
+ const secure = typeof window !== "undefined" && window.location.protocol === "https:"
910
+ const attrs = [
911
+ `Path=/`,
912
+ "SameSite=Lax",
913
+ ...(secure ? ["Secure"] : []),
914
+ ]
915
+ if (expiresAtSeconds !== undefined) {
916
+ attrs.push(`Expires=${new Date(expiresAtSeconds * 1000).toUTCString()}`)
917
+ } else if (value === "") {
918
+ attrs.push("Expires=Thu, 01 Jan 1970 00:00:00 GMT")
919
+ }
920
+ document.cookie = `${name}=${encodeURIComponent(value)}; ${attrs.join("; ")}`
921
+ }
922
+
923
+ _setSession(session: Session | null): void {
924
+ const prev = this.currentSession
925
+ this.currentSession = session
926
+ this.syncPersistedSession(session)
927
+ if (session !== null) {
928
+ this.scheduleAutoRefresh()
929
+ } else if (this.refreshTimer !== null) {
930
+ clearTimeout(this.refreshTimer)
931
+ this.refreshTimer = null
932
+ }
933
+ const event: AuthChangeEvent =
934
+ session !== null
935
+ ? prev !== null
936
+ ? "TOKEN_REFRESHED"
937
+ : "SIGNED_IN"
938
+ : "SIGNED_OUT"
939
+ for (const cb of this.listeners.values()) {
940
+ cb(event, session)
941
+ }
942
+ }
943
+
944
+ private _emitEvent(event: AuthChangeEvent, session: Session | null): void {
945
+ for (const cb of this.listeners.values()) {
946
+ cb(event, session)
947
+ }
948
+ }
949
+
950
+ private async _parseError(res: Response): Promise<SupatypeError> {
951
+ const err = await res.json().catch(() => ({})) as Record<string, unknown>
952
+ return {
953
+ message: String(err["error_description"] ?? err["msg"] ?? err["message"] ?? "Error"),
954
+ status: res.status,
955
+ ...(err["error_code"] !== undefined && { code: String(err["error_code"]) }),
956
+ }
957
+ }
958
+
959
+ private async _parseAuthResponse(res: Response): Promise<{
960
+ data: { session: Session | null; user: User | null }
961
+ error: SupatypeError | null
962
+ }> {
963
+ if (!res.ok) {
964
+ const err = await res.json().catch(() => ({ msg: "Unknown error" })) as Record<string, unknown>
965
+ return {
966
+ data: { session: null, user: null },
967
+ error: {
968
+ message: String(err["error_description"] ?? err["msg"] ?? "Error"),
969
+ status: res.status,
970
+ },
971
+ }
972
+ }
973
+ const json = await res.json() as Record<string, unknown>
974
+ const user = this._parseUser((json["user"] ?? {}) as Record<string, unknown>)
975
+ const session: Session = {
976
+ accessToken: String(json["access_token"] ?? ""),
977
+ tokenType: String(json["token_type"] ?? "bearer"),
978
+ expiresIn: Number(json["expires_in"] ?? 3600),
979
+ ...(json["expires_at"] !== undefined && { expiresAt: Number(json["expires_at"]) }),
980
+ refreshToken: String(json["refresh_token"] ?? ""),
981
+ user,
982
+ }
983
+ this._setSession(session)
984
+ return { data: { session, user }, error: null }
985
+ }
986
+
987
+ private _parseUser(raw: Record<string, unknown>): User {
988
+ const user: User = {
989
+ id: String(raw["id"] ?? ""),
990
+ ...(raw["email"] !== undefined && { email: String(raw["email"]) }),
991
+ ...(raw["phone"] !== undefined && { phone: String(raw["phone"]) }),
992
+ ...(raw["role"] !== undefined && { role: String(raw["role"]) }),
993
+ ...(raw["is_anonymous"] !== undefined && { isAnonymous: Boolean(raw["is_anonymous"]) }),
994
+ appMetadata: (raw["app_metadata"] ?? {}) as Record<string, unknown>,
995
+ userMetadata: (raw["user_metadata"] ?? {}) as Record<string, unknown>,
996
+ createdAt: String(raw["created_at"] ?? ""),
997
+ updatedAt: String(raw["updated_at"] ?? ""),
998
+ }
999
+ if (Array.isArray(raw["identities"])) {
1000
+ user.identities = (raw["identities"] as Record<string, unknown>[]).map((i) => ({
1001
+ id: String(i["id"] ?? ""),
1002
+ userId: String(i["user_id"] ?? ""),
1003
+ identityData: (i["identity_data"] ?? {}) as Record<string, unknown>,
1004
+ identityId: String(i["identity_id"] ?? ""),
1005
+ provider: String(i["provider"] ?? ""),
1006
+ createdAt: String(i["created_at"] ?? ""),
1007
+ updatedAt: String(i["updated_at"] ?? ""),
1008
+ ...(i["last_sign_in_at"] !== undefined && { lastSignInAt: String(i["last_sign_in_at"]) }),
1009
+ }))
1010
+ }
1011
+ if (Array.isArray(raw["factors"])) {
1012
+ user.factors = (raw["factors"] as Record<string, unknown>[]).map((f) => ({
1013
+ id: String(f["id"] ?? ""),
1014
+ factorType: String(f["factor_type"] ?? "totp") as "totp" | "phone" | "webauthn",
1015
+ status: String(f["status"] ?? "unverified") as "verified" | "unverified",
1016
+ createdAt: String(f["created_at"] ?? ""),
1017
+ updatedAt: String(f["updated_at"] ?? ""),
1018
+ ...(f["friendly_name"] !== undefined && { friendlyName: String(f["friendly_name"]) }),
1019
+ ...(f["phone"] !== undefined && { phone: String(f["phone"]) }),
1020
+ }))
1021
+ }
1022
+ return user
1023
+ }
1024
+ }