@supatype/client 0.3.5 → 0.7.0
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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +58 -31
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +78 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +373 -274
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +153 -157
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +20 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +105 -12
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +129 -37
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +84 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +421 -280
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +272 -201
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +116 -13
- package/src/select-types.ts +184 -0
- package/src/storage.ts +214 -43
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +90 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +122 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +139 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +139 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +3 -2
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +12 -22
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +13 -13
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
package/src/auth.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
AuthChangeEvent,
|
|
3
3
|
AuthFlowType,
|
|
4
|
+
AuthRedirectError,
|
|
4
5
|
AuthMFAChallengeResponse,
|
|
5
6
|
AuthMFAEnrollResponse,
|
|
6
7
|
AuthMFAListFactorsResponse,
|
|
@@ -10,12 +11,33 @@ import type {
|
|
|
10
11
|
Session,
|
|
11
12
|
SupatypeError,
|
|
12
13
|
User,
|
|
14
|
+
UserIdentity,
|
|
13
15
|
} from "./types.js"
|
|
14
16
|
import {
|
|
15
17
|
createCodeChallengeS256,
|
|
16
18
|
generateCodeVerifier,
|
|
17
19
|
PKCE_METHOD_S256,
|
|
18
20
|
} from "./pkce.js"
|
|
21
|
+
import { plainFetch, type RequestTransport } from "./fetch-with-retry.js"
|
|
22
|
+
import {
|
|
23
|
+
browserHref,
|
|
24
|
+
carriesImplicitResult,
|
|
25
|
+
cleanBrowserUrl,
|
|
26
|
+
redirectParam,
|
|
27
|
+
redirectParams,
|
|
28
|
+
} from "./auth-redirect.js"
|
|
29
|
+
import {
|
|
30
|
+
isJsonObject,
|
|
31
|
+
isNumber,
|
|
32
|
+
isOneOf,
|
|
33
|
+
isShape,
|
|
34
|
+
isString,
|
|
35
|
+
objectOrEmpty,
|
|
36
|
+
readJson,
|
|
37
|
+
readJsonObject,
|
|
38
|
+
type Guard,
|
|
39
|
+
} from "./json.js"
|
|
40
|
+
import { decodeJwtPayload } from "./jwt.js"
|
|
19
41
|
|
|
20
42
|
export type AuthListener = (event: AuthChangeEvent, session: Session | null) => void
|
|
21
43
|
|
|
@@ -26,12 +48,88 @@ interface AuthClientOptions {
|
|
|
26
48
|
cookiePrefix?: string | undefined
|
|
27
49
|
/** Custom session store (replaces browser localStorage/cookies when set). */
|
|
28
50
|
storage?: AuthStorage | undefined
|
|
51
|
+
/** How requests are sent. `createClient` passes its fetch, so `timeout` and `retry` apply here too. */
|
|
52
|
+
transport?: RequestTransport | undefined
|
|
53
|
+
/** Finish a sign-in carried by the page's URL on start (browser only). Default: true. */
|
|
54
|
+
detectSessionInUrl?: boolean | undefined
|
|
29
55
|
}
|
|
30
56
|
|
|
31
57
|
const DEFAULT_STORAGE_KEY = "supatype.auth.session"
|
|
32
58
|
const DEFAULT_COOKIE_PREFIX = "st"
|
|
59
|
+
/** Storage key suffixes for the state an OAuth redirect has to survive. */
|
|
60
|
+
const VERIFIER_SUFFIX = "-code-verifier"
|
|
61
|
+
const PROVIDER_SUFFIX = "-oauth-provider"
|
|
33
62
|
const DEBUG_AUTH = typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1"
|
|
34
63
|
|
|
64
|
+
/**
|
|
65
|
+
* The auth server's refusal as a `SupatypeError`, with its machine-readable code kept.
|
|
66
|
+
*
|
|
67
|
+
* Two body shapes arrive: `{ code, error_code, msg }` from the API, and the OAuth token endpoint's
|
|
68
|
+
* `{ error, error_description }`, where `error` is the code. The code is what an app branches on
|
|
69
|
+
* (`invalid_credentials`, `weak_password`, `email_not_confirmed`); the numeric `code` in the first
|
|
70
|
+
* shape is only the HTTP status again, so it is not used. Message precedence follows supabase-js.
|
|
71
|
+
*/
|
|
72
|
+
function authErrorFromBody(body: Record<string, unknown>, status: number): SupatypeError {
|
|
73
|
+
const text = (key: string): string | undefined => {
|
|
74
|
+
const value = body[key]
|
|
75
|
+
return typeof value === "string" && value !== "" ? value : undefined
|
|
76
|
+
}
|
|
77
|
+
const code = text("error_code") ?? text("error")
|
|
78
|
+
const message =
|
|
79
|
+
text("msg") ?? text("message") ?? text("error_description") ?? text("error") ??
|
|
80
|
+
`Auth request failed (HTTP ${status})`
|
|
81
|
+
return { message, status, ...(code !== undefined && { code }) }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The assurance levels the client reports; the server's unused `aal3` reads as unknown. */
|
|
85
|
+
const isAal = isOneOf(["aal1", "aal2"])
|
|
86
|
+
/** One entry of the JWT's `amr` claim: how the session was authenticated, and when. */
|
|
87
|
+
const isAmrEntry = isShape({ method: isString })
|
|
88
|
+
/** The factor types and states supatype-auth defines (internal/auth/models/factor.go). */
|
|
89
|
+
const isFactorType = isOneOf(["totp", "phone", "webauthn"])
|
|
90
|
+
const isFactorStatus = isOneOf(["verified", "unverified"])
|
|
91
|
+
|
|
92
|
+
/** The assurance level and the authentication methods an access token's claims carry. */
|
|
93
|
+
function assuranceClaims(claims: Record<string, unknown>): {
|
|
94
|
+
currentLevel: "aal1" | "aal2" | null
|
|
95
|
+
methods: string[]
|
|
96
|
+
} {
|
|
97
|
+
const aal = claims["aal"]
|
|
98
|
+
const amr = claims["amr"]
|
|
99
|
+
return {
|
|
100
|
+
currentLevel: isAal(aal) ? aal : null,
|
|
101
|
+
methods: Array.isArray(amr) ? amr.filter(isAmrEntry).map((entry) => entry.method) : [],
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The value under `first` when the guard accepts it, else the one under `second`, else undefined. */
|
|
106
|
+
function eitherKey<T>(
|
|
107
|
+
body: Record<string, unknown>,
|
|
108
|
+
first: string,
|
|
109
|
+
second: string,
|
|
110
|
+
guard: Guard<T>,
|
|
111
|
+
): T | undefined {
|
|
112
|
+
const a = body[first]
|
|
113
|
+
if (guard(a)) return a
|
|
114
|
+
const b = body[second]
|
|
115
|
+
return guard(b) ? b : undefined
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A stored user with its camelCase keys copied to the snake_case ones `_parseUser` reads. */
|
|
119
|
+
function snakeCaseUser(user: Record<string, unknown>): Record<string, unknown> {
|
|
120
|
+
const aliases = [
|
|
121
|
+
["app_metadata", "appMetadata"],
|
|
122
|
+
["user_metadata", "userMetadata"],
|
|
123
|
+
["created_at", "createdAt"],
|
|
124
|
+
["updated_at", "updatedAt"],
|
|
125
|
+
] as const
|
|
126
|
+
const normalized = { ...user }
|
|
127
|
+
for (const [snake, camel] of aliases) {
|
|
128
|
+
if (user[snake] === undefined && user[camel] !== undefined) normalized[snake] = user[camel]
|
|
129
|
+
}
|
|
130
|
+
return normalized
|
|
131
|
+
}
|
|
132
|
+
|
|
35
133
|
export class AuthClient {
|
|
36
134
|
private readonly url: string
|
|
37
135
|
private readonly baseHeaders: Record<string, string>
|
|
@@ -42,10 +140,14 @@ export class AuthClient {
|
|
|
42
140
|
private readonly storageKey: string
|
|
43
141
|
private readonly cookieName: string
|
|
44
142
|
private readonly storage: AuthStorage | null
|
|
143
|
+
/** The client's fetch, with its timeout; only reads are retried. */
|
|
144
|
+
private readonly send: RequestTransport
|
|
45
145
|
/** When true, session is also mirrored to document.cookie (browser default path only). */
|
|
46
146
|
private readonly useCookies: boolean
|
|
47
|
-
/** Resolves when async storage hydration
|
|
147
|
+
/** Resolves when async storage hydration and any sign-in carried by the page's URL complete. */
|
|
48
148
|
private readonly ready: Promise<void>
|
|
149
|
+
/** What `ready` settles with: the refusal the page's URL reported, if any. */
|
|
150
|
+
private readonly initialized: Promise<{ error: AuthRedirectError | null }>
|
|
49
151
|
/** Pending auto-refresh timer; refreshes the access token shortly before it expires. */
|
|
50
152
|
private refreshTimer: ReturnType<typeof setTimeout> | null = null
|
|
51
153
|
/** Dedupes concurrent refresh attempts (getSession + auto-refresh). */
|
|
@@ -62,47 +164,90 @@ export class AuthClient {
|
|
|
62
164
|
this.cookieName = `${cookiePrefix}-auth-token`
|
|
63
165
|
this.useCookies = opts.storage === undefined
|
|
64
166
|
this.storage = opts.storage ?? this.getBrowserStorage()
|
|
167
|
+
this.send = opts.transport ?? plainFetch
|
|
65
168
|
|
|
169
|
+
const hydrated = this.loadInitialSession(opts)
|
|
170
|
+
this.initialized = opts.detectSessionInUrl === false
|
|
171
|
+
? hydrated.then(() => ({ error: null }))
|
|
172
|
+
: hydrated.then(() => this.completeRedirect())
|
|
173
|
+
this.ready = this.initialized.then(() => undefined)
|
|
174
|
+
// Keep the access token fresh while the app is open (and refresh immediately
|
|
175
|
+
// if a persisted session loaded already expired).
|
|
176
|
+
this.scheduleAutoRefresh()
|
|
177
|
+
if (this.currentSession !== null && this.isAccessTokenExpired(this.currentSession)) {
|
|
178
|
+
void this.ensureValidSession()
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** The session the client starts with: the one passed in, else the persisted one. */
|
|
183
|
+
private loadInitialSession(opts: AuthClientOptions): Promise<void> {
|
|
66
184
|
if (opts.initialSession !== undefined) {
|
|
67
185
|
this.currentSession = opts.initialSession
|
|
68
|
-
this.ready = Promise.resolve()
|
|
69
186
|
if (DEBUG_AUTH) {
|
|
70
187
|
console.debug("[supatype:auth] constructor initialSession provided", {
|
|
71
188
|
hasSession: true,
|
|
72
189
|
userId: opts.initialSession.user.id,
|
|
73
190
|
})
|
|
74
191
|
}
|
|
75
|
-
|
|
76
|
-
if (opts.storage !== undefined) {
|
|
77
|
-
this.ready = this.hydrateFromStorage()
|
|
78
|
-
} else {
|
|
79
|
-
this.currentSession = this.loadPersistedSession()
|
|
80
|
-
this.ready = Promise.resolve()
|
|
81
|
-
if (DEBUG_AUTH) {
|
|
82
|
-
console.debug("[supatype:auth] constructor loaded persisted session", {
|
|
83
|
-
hasSession: this.currentSession !== null,
|
|
84
|
-
userId: this.currentSession?.user.id ?? null,
|
|
85
|
-
storageKey: this.storageKey,
|
|
86
|
-
cookieName: this.cookieName,
|
|
87
|
-
})
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
} else {
|
|
91
|
-
this.ready = Promise.resolve()
|
|
192
|
+
return Promise.resolve()
|
|
92
193
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
this.
|
|
96
|
-
if (
|
|
97
|
-
|
|
194
|
+
if (!this.persistSession) return Promise.resolve()
|
|
195
|
+
if (opts.storage !== undefined) return this.hydrateFromStorage()
|
|
196
|
+
this.currentSession = this.loadPersistedSession()
|
|
197
|
+
if (DEBUG_AUTH) {
|
|
198
|
+
console.debug("[supatype:auth] constructor loaded persisted session", {
|
|
199
|
+
hasSession: this.currentSession !== null,
|
|
200
|
+
userId: this.currentSession?.user.id ?? null,
|
|
201
|
+
storageKey: this.storageKey,
|
|
202
|
+
cookieName: this.cookieName,
|
|
203
|
+
})
|
|
98
204
|
}
|
|
205
|
+
return Promise.resolve()
|
|
99
206
|
}
|
|
100
207
|
|
|
101
|
-
/** Resolves when
|
|
208
|
+
/** Resolves when the client has its starting session (storage hydrated, any URL sign-in done). */
|
|
102
209
|
whenReady(): Promise<void> {
|
|
103
210
|
return this.ready
|
|
104
211
|
}
|
|
105
212
|
|
|
213
|
+
/**
|
|
214
|
+
* Wait for the client's start, and learn whether a sign-in in the page's URL was refused.
|
|
215
|
+
*
|
|
216
|
+
* The same shape as supabase-js's `initialize()`. A refused OAuth sign-in comes back as
|
|
217
|
+
* `?error=...&error_description=...`; this is where an app (or `useAuth`) reads it.
|
|
218
|
+
*/
|
|
219
|
+
initialize(): Promise<{ error: AuthRedirectError | null }> {
|
|
220
|
+
return this.initialized
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Finish the sign-in the page's URL carries, as supabase-js's `detectSessionInUrl` does.
|
|
225
|
+
*
|
|
226
|
+
* Whatever session was stored is set aside first, so a new sign-in is announced as `SIGNED_IN`
|
|
227
|
+
* and a refused one leaves the browser signed out, as supabase-js does after a failed attempt.
|
|
228
|
+
*/
|
|
229
|
+
private async completeRedirect(): Promise<{ error: AuthRedirectError | null }> {
|
|
230
|
+
const href = browserHref()
|
|
231
|
+
if (href === null || !(await this.isAuthRedirect(href))) return { error: null }
|
|
232
|
+
const provider = await this.takeFlowItem(PROVIDER_SUFFIX)
|
|
233
|
+
this.currentSession = null
|
|
234
|
+
const { error } = await this.getSessionFromUrl(href).catch((err: unknown) => ({
|
|
235
|
+
error: { message: err instanceof Error ? err.message : "Could not finish the sign-in" },
|
|
236
|
+
}))
|
|
237
|
+
cleanBrowserUrl(href)
|
|
238
|
+
if (error === null) return { error: null }
|
|
239
|
+
this._setSession(null)
|
|
240
|
+
return { error: { ...error, ...(provider !== null && { provider }) } }
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** A URL with tokens or a refusal, or with a `code` for a PKCE flow this client started. */
|
|
244
|
+
private async isAuthRedirect(href: string): Promise<boolean> {
|
|
245
|
+
const params = redirectParams(href)
|
|
246
|
+
if (params === null) return false
|
|
247
|
+
if (carriesImplicitResult(params)) return true
|
|
248
|
+
return redirectParam(params, "code") !== null && (await this.readCodeVerifier()) !== null
|
|
249
|
+
}
|
|
250
|
+
|
|
106
251
|
private async hydrateFromStorage(): Promise<void> {
|
|
107
252
|
try {
|
|
108
253
|
const session = await this.loadPersistedSessionAsync()
|
|
@@ -135,13 +280,8 @@ export class AuthClient {
|
|
|
135
280
|
private jwtExpMs(accessToken: string): number | null {
|
|
136
281
|
const parts = accessToken.split(".")
|
|
137
282
|
if (parts.length !== 3) return null
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const exp = payload["exp"]
|
|
141
|
-
return typeof exp === "number" ? exp * 1000 : null
|
|
142
|
-
} catch {
|
|
143
|
-
return null
|
|
144
|
-
}
|
|
283
|
+
const exp = decodeJwtPayload(parts[1]!)?.["exp"]
|
|
284
|
+
return typeof exp === "number" ? exp * 1000 : null
|
|
145
285
|
}
|
|
146
286
|
|
|
147
287
|
private isAccessTokenExpired(session: Session, skewMs = 0): boolean {
|
|
@@ -195,12 +335,13 @@ export class AuthClient {
|
|
|
195
335
|
? Math.max(0, (session.expiresIn || 3600) * 1000 - 60_000)
|
|
196
336
|
: Math.max(0, expiryMs - Date.now() - 60_000)
|
|
197
337
|
|
|
198
|
-
|
|
338
|
+
const timer = setTimeout(() => {
|
|
199
339
|
this.refreshTimer = null
|
|
200
340
|
void this.ensureValidSession()
|
|
201
341
|
}, delay)
|
|
202
|
-
|
|
203
|
-
|
|
342
|
+
this.refreshTimer = timer
|
|
343
|
+
// Avoid keeping a Node process alive for this timer. A browser's timer is a number: nothing to do.
|
|
344
|
+
if (typeof timer === "object" && "unref" in timer) timer.unref()
|
|
204
345
|
}
|
|
205
346
|
|
|
206
347
|
async signUp(credentials: {
|
|
@@ -218,7 +359,7 @@ export class AuthClient {
|
|
|
218
359
|
if (credentials.options?.data !== undefined) {
|
|
219
360
|
body["data"] = credentials.options.data
|
|
220
361
|
}
|
|
221
|
-
const res = await
|
|
362
|
+
const res = await this.send(`${this.url}/signup`, {
|
|
222
363
|
method: "POST",
|
|
223
364
|
headers: this.baseHeaders,
|
|
224
365
|
body: JSON.stringify(body),
|
|
@@ -233,7 +374,7 @@ export class AuthClient {
|
|
|
233
374
|
data: { session: Session | null; user: User | null }
|
|
234
375
|
error: SupatypeError | null
|
|
235
376
|
}> {
|
|
236
|
-
const res = await
|
|
377
|
+
const res = await this.send(`${this.url}/token?grant_type=password`, {
|
|
237
378
|
method: "POST",
|
|
238
379
|
headers: this.baseHeaders,
|
|
239
380
|
body: JSON.stringify({
|
|
@@ -260,7 +401,7 @@ export class AuthClient {
|
|
|
260
401
|
if (credentials?.options?.captchaToken !== undefined) {
|
|
261
402
|
body["supatype_meta_security"] = { captcha_token: credentials.options.captchaToken }
|
|
262
403
|
}
|
|
263
|
-
const res = await
|
|
404
|
+
const res = await this.send(`${this.url}/signup`, {
|
|
264
405
|
method: "POST",
|
|
265
406
|
headers: this.baseHeaders,
|
|
266
407
|
body: JSON.stringify(body),
|
|
@@ -268,6 +409,17 @@ export class AuthClient {
|
|
|
268
409
|
return this._parseAuthResponse(res)
|
|
269
410
|
}
|
|
270
411
|
|
|
412
|
+
/**
|
|
413
|
+
* An auth endpoint, carrying the caller's redirect as `redirect_to` in the query string. The
|
|
414
|
+
* server reads it from there (or a header) and never from a JSON body, so a redirect sent in the
|
|
415
|
+
* body is dropped in silence and the email links to SITE_URL instead.
|
|
416
|
+
*/
|
|
417
|
+
private endpoint(path: string, redirectTo: string | undefined): URL {
|
|
418
|
+
const url = new URL(`${this.url}${path}`)
|
|
419
|
+
if (redirectTo !== undefined) url.searchParams.set("redirect_to", redirectTo)
|
|
420
|
+
return url
|
|
421
|
+
}
|
|
422
|
+
|
|
271
423
|
async signInWithOAuth(opts: {
|
|
272
424
|
provider: string
|
|
273
425
|
options?: {
|
|
@@ -275,16 +427,28 @@ export class AuthClient {
|
|
|
275
427
|
/** Default: `implicit` (web-compatible). Pass `pkce` for mobile / RN. */
|
|
276
428
|
flowType?: AuthFlowType | undefined
|
|
277
429
|
scopes?: string | undefined
|
|
430
|
+
/**
|
|
431
|
+
* Extra `/authorize` query parameters, sent as given. The flow's own (`provider`,
|
|
432
|
+
* `redirect_to`, `scopes`, the PKCE challenge) are set after these and cannot be replaced.
|
|
433
|
+
*/
|
|
434
|
+
queryParams?: Record<string, string> | undefined
|
|
278
435
|
} | undefined
|
|
279
436
|
}): Promise<{
|
|
280
437
|
data: { url: string; provider: string }
|
|
281
438
|
error: SupatypeError | null
|
|
282
439
|
}> {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
if (opts.
|
|
286
|
-
|
|
440
|
+
// The server answers /authorize for a disabled provider with a bare JSON 400, which a browser
|
|
441
|
+
// navigating there shows as raw text; asking first lets the caller show a message instead.
|
|
442
|
+
if (await this.providerDisabled(opts.provider)) {
|
|
443
|
+
const message = `Sign-in with ${opts.provider} is not enabled for this project.`
|
|
444
|
+
return { data: { url: "", provider: opts.provider }, error: { message, status: 400, code: "provider_disabled" } }
|
|
287
445
|
}
|
|
446
|
+
await this.writeFlowItem(PROVIDER_SUFFIX, opts.provider)
|
|
447
|
+
const url = this.endpoint("/authorize", opts.options?.redirectTo)
|
|
448
|
+
for (const [key, value] of Object.entries(opts.options?.queryParams ?? {})) {
|
|
449
|
+
if (!url.searchParams.has(key)) url.searchParams.set(key, value)
|
|
450
|
+
}
|
|
451
|
+
url.searchParams.set("provider", opts.provider)
|
|
288
452
|
if (opts.options?.scopes !== undefined) {
|
|
289
453
|
url.searchParams.set("scopes", opts.options.scopes)
|
|
290
454
|
}
|
|
@@ -297,6 +461,22 @@ export class AuthClient {
|
|
|
297
461
|
return { data: { url: url.toString(), provider: opts.provider }, error: null }
|
|
298
462
|
}
|
|
299
463
|
|
|
464
|
+
/**
|
|
465
|
+
* True only when the server's `/settings` list the provider as off. A provider they do not list
|
|
466
|
+
* (a `custom:` one) or settings that cannot be read leave the decision to `/authorize`. Looked up
|
|
467
|
+
* in lower case, as `/authorize` resolves it, so `GitHub` is refused exactly when `github` is.
|
|
468
|
+
*/
|
|
469
|
+
private async providerDisabled(provider: string): Promise<boolean> {
|
|
470
|
+
try {
|
|
471
|
+
const res = await this.send(`${this.url}/settings`, { headers: this.baseHeaders })
|
|
472
|
+
if (!res.ok) return false
|
|
473
|
+
const external = objectOrEmpty((await readJsonObject(res))["external"])
|
|
474
|
+
return external[provider.toLowerCase()] === false
|
|
475
|
+
} catch {
|
|
476
|
+
return false
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
300
480
|
/**
|
|
301
481
|
* Apply tokens from an OAuth / deep-link redirect (implicit grant) or restore a session.
|
|
302
482
|
* Fetches `/user` to hydrate the user object, then persists via the configured storage.
|
|
@@ -308,7 +488,7 @@ export class AuthClient {
|
|
|
308
488
|
data: { session: Session | null; user: User | null }
|
|
309
489
|
error: SupatypeError | null
|
|
310
490
|
}> {
|
|
311
|
-
const res = await
|
|
491
|
+
const res = await this.send(`${this.url}/user`, {
|
|
312
492
|
headers: {
|
|
313
493
|
...this.baseHeaders,
|
|
314
494
|
Authorization: `Bearer ${params.accessToken}`,
|
|
@@ -320,8 +500,7 @@ export class AuthClient {
|
|
|
320
500
|
error: await this._parseError(res),
|
|
321
501
|
}
|
|
322
502
|
}
|
|
323
|
-
const
|
|
324
|
-
const user = this._parseUser(raw)
|
|
503
|
+
const user = await this._readUser(res)
|
|
325
504
|
const session: Session = {
|
|
326
505
|
accessToken: params.accessToken,
|
|
327
506
|
refreshToken: params.refreshToken,
|
|
@@ -357,7 +536,7 @@ export class AuthClient {
|
|
|
357
536
|
},
|
|
358
537
|
}
|
|
359
538
|
}
|
|
360
|
-
const res = await
|
|
539
|
+
const res = await this.send(`${this.url}/token?grant_type=pkce`, {
|
|
361
540
|
method: "POST",
|
|
362
541
|
headers: this.baseHeaders,
|
|
363
542
|
body: JSON.stringify({
|
|
@@ -377,33 +556,35 @@ export class AuthClient {
|
|
|
377
556
|
data: { session: Session | null; user: User | null }
|
|
378
557
|
error: SupatypeError | null
|
|
379
558
|
}> {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
parsed = new URL(url)
|
|
383
|
-
} catch {
|
|
559
|
+
const params = redirectParams(url)
|
|
560
|
+
if (params === null) {
|
|
384
561
|
return {
|
|
385
562
|
data: { session: null, user: null },
|
|
386
563
|
error: { message: `Invalid redirect URL: ${url}`, status: 400 },
|
|
387
564
|
}
|
|
388
565
|
}
|
|
566
|
+
const { query, fragment: hashParams } = params
|
|
389
567
|
|
|
390
|
-
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
const errorDescription =
|
|
396
|
-
query.get("error_description") ??
|
|
397
|
-
hashParams.get("error_description") ??
|
|
398
|
-
query.get("error") ??
|
|
399
|
-
hashParams.get("error")
|
|
400
|
-
if (errorDescription !== null && errorDescription !== "") {
|
|
401
|
-
return {
|
|
402
|
-
data: { session: null, user: null },
|
|
403
|
-
error: { message: errorDescription, status: 400 },
|
|
404
|
-
}
|
|
568
|
+
// A refused link comes back with the same fields as a refused request, in the URL instead.
|
|
569
|
+
const redirectError = { ...Object.fromEntries(hashParams), ...Object.fromEntries(query) }
|
|
570
|
+
if (redirectError["error_description"] || redirectError["error"]) {
|
|
571
|
+
return { data: { session: null, user: null }, error: authErrorFromBody(redirectError, 400) }
|
|
405
572
|
}
|
|
406
573
|
|
|
574
|
+
// The auth server marks the link it sent with `type`; a recovery link signs the user in so they
|
|
575
|
+
// can choose a new password, and the app needs to know that is why they arrived.
|
|
576
|
+
const recovery = (hashParams.get("type") ?? query.get("type")) === "recovery"
|
|
577
|
+
return this.announceRecovery(await this.sessionFromRedirect(query, hashParams), recovery)
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** The session a redirect carries: a PKCE code to exchange, or implicit-grant tokens. */
|
|
581
|
+
private async sessionFromRedirect(
|
|
582
|
+
query: URLSearchParams,
|
|
583
|
+
hashParams: URLSearchParams,
|
|
584
|
+
): Promise<{
|
|
585
|
+
data: { session: Session | null; user: User | null }
|
|
586
|
+
error: SupatypeError | null
|
|
587
|
+
}> {
|
|
407
588
|
const code = query.get("code") ?? hashParams.get("code")
|
|
408
589
|
if (code !== null && code !== "") {
|
|
409
590
|
return this.exchangeCodeForSession(code)
|
|
@@ -426,6 +607,22 @@ export class AuthClient {
|
|
|
426
607
|
}
|
|
427
608
|
}
|
|
428
609
|
|
|
610
|
+
/**
|
|
611
|
+
* Emit `PASSWORD_RECOVERY` once a recovery link or code has produced a session.
|
|
612
|
+
*
|
|
613
|
+
* After the `SIGNED_IN` that establishing the session already emitted, as `MFA_CHALLENGE_VERIFIED`
|
|
614
|
+
* follows it, so a listener keyed on sign-in still sees one and a reset page can key on this.
|
|
615
|
+
*/
|
|
616
|
+
private announceRecovery<T extends { data: { session: Session | null }; error: SupatypeError | null }>(
|
|
617
|
+
result: T,
|
|
618
|
+
recovery: boolean,
|
|
619
|
+
): T {
|
|
620
|
+
if (recovery && result.error === null && result.data.session !== null) {
|
|
621
|
+
this._emitEvent("PASSWORD_RECOVERY", result.data.session)
|
|
622
|
+
}
|
|
623
|
+
return result
|
|
624
|
+
}
|
|
625
|
+
|
|
429
626
|
async signInWithOtp(opts: {
|
|
430
627
|
email?: string | undefined
|
|
431
628
|
phone?: string | undefined
|
|
@@ -447,13 +644,13 @@ export class AuthClient {
|
|
|
447
644
|
body["channel"] = opts.options.channel
|
|
448
645
|
}
|
|
449
646
|
}
|
|
450
|
-
const res = await
|
|
647
|
+
const res = await this.send(this.endpoint("/otp", opts.options?.emailRedirectTo).toString(), {
|
|
451
648
|
method: "POST",
|
|
452
649
|
headers: this.baseHeaders,
|
|
453
650
|
body: JSON.stringify(body),
|
|
454
651
|
})
|
|
455
652
|
if (res.ok) {
|
|
456
|
-
const json = await res
|
|
653
|
+
const json = await readJsonObject(res)
|
|
457
654
|
return {
|
|
458
655
|
data: {
|
|
459
656
|
...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
|
|
@@ -461,19 +658,12 @@ export class AuthClient {
|
|
|
461
658
|
error: null,
|
|
462
659
|
}
|
|
463
660
|
}
|
|
464
|
-
|
|
465
|
-
return {
|
|
466
|
-
data: {},
|
|
467
|
-
error: {
|
|
468
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
469
|
-
status: res.status,
|
|
470
|
-
},
|
|
471
|
-
}
|
|
661
|
+
return { data: {}, error: await this._parseError(res) }
|
|
472
662
|
}
|
|
473
663
|
|
|
474
664
|
async signOut(): Promise<{ error: SupatypeError | null }> {
|
|
475
665
|
if (this.currentSession !== null) {
|
|
476
|
-
await
|
|
666
|
+
await this.send(`${this.url}/logout`, {
|
|
477
667
|
method: "POST",
|
|
478
668
|
headers: {
|
|
479
669
|
...this.baseHeaders,
|
|
@@ -501,20 +691,16 @@ export class AuthClient {
|
|
|
501
691
|
if (this.currentSession === null) {
|
|
502
692
|
return { data: { user: null }, error: null }
|
|
503
693
|
}
|
|
504
|
-
const res = await
|
|
694
|
+
const res = await this.send(`${this.url}/user`, {
|
|
505
695
|
headers: {
|
|
506
696
|
...this.baseHeaders,
|
|
507
697
|
Authorization: `Bearer ${this.currentSession.accessToken}`,
|
|
508
698
|
},
|
|
509
699
|
})
|
|
510
700
|
if (!res.ok) {
|
|
511
|
-
return {
|
|
512
|
-
data: { user: null },
|
|
513
|
-
error: { message: "Could not get user", status: res.status },
|
|
514
|
-
}
|
|
701
|
+
return { data: { user: null }, error: await this._parseError(res) }
|
|
515
702
|
}
|
|
516
|
-
|
|
517
|
-
return { data: { user: this._parseUser(raw) }, error: null }
|
|
703
|
+
return { data: { user: await this._readUser(res) }, error: null }
|
|
518
704
|
}
|
|
519
705
|
|
|
520
706
|
async refreshSession(): Promise<{
|
|
@@ -529,7 +715,7 @@ export class AuthClient {
|
|
|
529
715
|
return { data: { session: null }, error: { message: "No refresh token" } }
|
|
530
716
|
}
|
|
531
717
|
try {
|
|
532
|
-
const res = await
|
|
718
|
+
const res = await this.send(`${this.url}/token?grant_type=refresh_token`, {
|
|
533
719
|
method: "POST",
|
|
534
720
|
headers: this.baseHeaders,
|
|
535
721
|
body: JSON.stringify({ refresh_token: this.currentSession.refreshToken }),
|
|
@@ -551,24 +737,13 @@ export class AuthClient {
|
|
|
551
737
|
email: string,
|
|
552
738
|
options?: { redirectTo?: string | undefined } | undefined,
|
|
553
739
|
): Promise<{ data: Record<string, never>; error: SupatypeError | null }> {
|
|
554
|
-
const
|
|
555
|
-
if (options?.redirectTo !== undefined) {
|
|
556
|
-
body["redirect_to"] = options.redirectTo
|
|
557
|
-
}
|
|
558
|
-
const res = await fetch(`${this.url}/recover`, {
|
|
740
|
+
const res = await this.send(this.endpoint("/recover", options?.redirectTo).toString(), {
|
|
559
741
|
method: "POST",
|
|
560
742
|
headers: this.baseHeaders,
|
|
561
|
-
body: JSON.stringify(
|
|
743
|
+
body: JSON.stringify({ email }),
|
|
562
744
|
})
|
|
563
745
|
if (res.ok) return { data: {}, error: null }
|
|
564
|
-
|
|
565
|
-
return {
|
|
566
|
-
data: {},
|
|
567
|
-
error: {
|
|
568
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
569
|
-
status: res.status,
|
|
570
|
-
},
|
|
571
|
-
}
|
|
746
|
+
return { data: {}, error: await this._parseError(res) }
|
|
572
747
|
}
|
|
573
748
|
|
|
574
749
|
async updateUser(updates: {
|
|
@@ -579,7 +754,7 @@ export class AuthClient {
|
|
|
579
754
|
if (this.currentSession === null) {
|
|
580
755
|
return { data: { user: null }, error: { message: "Not authenticated" } }
|
|
581
756
|
}
|
|
582
|
-
const res = await
|
|
757
|
+
const res = await this.send(`${this.url}/user`, {
|
|
583
758
|
method: "PUT",
|
|
584
759
|
headers: {
|
|
585
760
|
...this.baseHeaders,
|
|
@@ -588,17 +763,25 @@ export class AuthClient {
|
|
|
588
763
|
body: JSON.stringify(updates),
|
|
589
764
|
})
|
|
590
765
|
if (!res.ok) {
|
|
591
|
-
|
|
592
|
-
return {
|
|
593
|
-
data: { user: null },
|
|
594
|
-
error: {
|
|
595
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
596
|
-
status: res.status,
|
|
597
|
-
},
|
|
598
|
-
}
|
|
766
|
+
return { data: { user: null }, error: await this._parseError(res) }
|
|
599
767
|
}
|
|
600
|
-
const
|
|
601
|
-
|
|
768
|
+
const user = await this._readUser(res)
|
|
769
|
+
this.applyUpdatedUser(user)
|
|
770
|
+
return { data: { user }, error: null }
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* Put the server's updated user on the session, persist it, and tell listeners.
|
|
775
|
+
*
|
|
776
|
+
* The tokens are unchanged, so this neither reschedules the refresh nor emits `TOKEN_REFRESHED`;
|
|
777
|
+
* without it the session kept the old email and metadata until the next refresh.
|
|
778
|
+
*/
|
|
779
|
+
private applyUpdatedUser(user: User): void {
|
|
780
|
+
if (this.currentSession === null) return
|
|
781
|
+
const session: Session = { ...this.currentSession, user }
|
|
782
|
+
this.currentSession = session
|
|
783
|
+
this.syncPersistedSession(session)
|
|
784
|
+
this._emitEvent("USER_UPDATED", session)
|
|
602
785
|
}
|
|
603
786
|
|
|
604
787
|
/**
|
|
@@ -625,12 +808,12 @@ export class AuthClient {
|
|
|
625
808
|
if (params.email !== undefined) body["email"] = params.email
|
|
626
809
|
if (params.phone !== undefined) body["phone"] = params.phone
|
|
627
810
|
}
|
|
628
|
-
const res = await
|
|
811
|
+
const res = await this.send(`${this.url}/verify`, {
|
|
629
812
|
method: "POST",
|
|
630
813
|
headers: this.baseHeaders,
|
|
631
814
|
body: JSON.stringify(body),
|
|
632
815
|
})
|
|
633
|
-
return this._parseAuthResponse(res)
|
|
816
|
+
return this.announceRecovery(await this._parseAuthResponse(res), params.type === "recovery")
|
|
634
817
|
}
|
|
635
818
|
|
|
636
819
|
/**
|
|
@@ -652,7 +835,7 @@ export class AuthClient {
|
|
|
652
835
|
if (credentials.nonce !== undefined) {
|
|
653
836
|
body["nonce"] = credentials.nonce
|
|
654
837
|
}
|
|
655
|
-
const res = await
|
|
838
|
+
const res = await this.send(`${this.url}/token?grant_type=id_token`, {
|
|
656
839
|
method: "POST",
|
|
657
840
|
headers: this.baseHeaders,
|
|
658
841
|
body: JSON.stringify(body),
|
|
@@ -671,13 +854,13 @@ export class AuthClient {
|
|
|
671
854
|
const body: Record<string, unknown> = { type: params.type }
|
|
672
855
|
if (params.email !== undefined) body["email"] = params.email
|
|
673
856
|
if (params.phone !== undefined) body["phone"] = params.phone
|
|
674
|
-
const res = await
|
|
857
|
+
const res = await this.send(`${this.url}/resend`, {
|
|
675
858
|
method: "POST",
|
|
676
859
|
headers: this.baseHeaders,
|
|
677
860
|
body: JSON.stringify(body),
|
|
678
861
|
})
|
|
679
862
|
if (res.ok) {
|
|
680
|
-
const json = await res
|
|
863
|
+
const json = await readJsonObject(res)
|
|
681
864
|
return {
|
|
682
865
|
data: {
|
|
683
866
|
...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
|
|
@@ -685,14 +868,7 @@ export class AuthClient {
|
|
|
685
868
|
error: null,
|
|
686
869
|
}
|
|
687
870
|
}
|
|
688
|
-
|
|
689
|
-
return {
|
|
690
|
-
data: {},
|
|
691
|
-
error: {
|
|
692
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
693
|
-
status: res.status,
|
|
694
|
-
},
|
|
695
|
-
}
|
|
871
|
+
return { data: {}, error: await this._parseError(res) }
|
|
696
872
|
}
|
|
697
873
|
|
|
698
874
|
// ─── MFA ──────────────────────────────────────────────────────────────────────
|
|
@@ -725,7 +901,7 @@ export class AuthClient {
|
|
|
725
901
|
if (params.friendlyName !== undefined) body["friendly_name"] = params.friendlyName
|
|
726
902
|
if (params.issuer !== undefined) body["issuer"] = params.issuer
|
|
727
903
|
if (params.phone !== undefined) body["phone"] = params.phone
|
|
728
|
-
const res = await
|
|
904
|
+
const res = await this.send(`${this.url}/factors`, {
|
|
729
905
|
method: "POST",
|
|
730
906
|
headers: {
|
|
731
907
|
...this.baseHeaders,
|
|
@@ -736,16 +912,17 @@ export class AuthClient {
|
|
|
736
912
|
if (!res.ok) {
|
|
737
913
|
return { data: null, error: await this._parseError(res) }
|
|
738
914
|
}
|
|
739
|
-
const json = await res
|
|
915
|
+
const json = await readJson(res, isJsonObject)
|
|
916
|
+
const totp = json["totp"]
|
|
740
917
|
const data: AuthMFAEnrollResponse = {
|
|
741
918
|
id: String(json["id"] ?? ""),
|
|
742
919
|
type: String(json["type"] ?? ""),
|
|
743
920
|
friendlyName: String(json["friendly_name"] ?? ""),
|
|
744
|
-
...(
|
|
921
|
+
...(isJsonObject(totp) && {
|
|
745
922
|
totp: {
|
|
746
|
-
qrCode: String(
|
|
747
|
-
secret: String(
|
|
748
|
-
uri: String(
|
|
923
|
+
qrCode: String(totp["qr_code"] ?? ""),
|
|
924
|
+
secret: String(totp["secret"] ?? ""),
|
|
925
|
+
uri: String(totp["uri"] ?? ""),
|
|
749
926
|
},
|
|
750
927
|
}),
|
|
751
928
|
...(json["phone"] !== undefined && { phone: String(json["phone"]) }),
|
|
@@ -769,7 +946,7 @@ export class AuthClient {
|
|
|
769
946
|
}
|
|
770
947
|
const body: Record<string, unknown> = {}
|
|
771
948
|
if (params.channel !== undefined) body["channel"] = params.channel
|
|
772
|
-
const res = await
|
|
949
|
+
const res = await this.send(
|
|
773
950
|
`${this.url}/factors/${params.factorId}/challenge`,
|
|
774
951
|
{
|
|
775
952
|
method: "POST",
|
|
@@ -783,7 +960,7 @@ export class AuthClient {
|
|
|
783
960
|
if (!res.ok) {
|
|
784
961
|
return { data: null, error: await this._parseError(res) }
|
|
785
962
|
}
|
|
786
|
-
const json = await res
|
|
963
|
+
const json = await readJson(res, isJsonObject)
|
|
787
964
|
return {
|
|
788
965
|
data: {
|
|
789
966
|
id: String(json["id"] ?? ""),
|
|
@@ -812,7 +989,7 @@ export class AuthClient {
|
|
|
812
989
|
error: { message: "Not authenticated" },
|
|
813
990
|
}
|
|
814
991
|
}
|
|
815
|
-
const res = await
|
|
992
|
+
const res = await this.send(
|
|
816
993
|
`${this.url}/factors/${params.factorId}/verify`,
|
|
817
994
|
{
|
|
818
995
|
method: "POST",
|
|
@@ -871,7 +1048,7 @@ export class AuthClient {
|
|
|
871
1048
|
if (this.currentSession === null) {
|
|
872
1049
|
return { data: null, error: { message: "Not authenticated" } }
|
|
873
1050
|
}
|
|
874
|
-
const res = await
|
|
1051
|
+
const res = await this.send(
|
|
875
1052
|
`${this.url}/factors/${params.factorId}`,
|
|
876
1053
|
{
|
|
877
1054
|
method: "DELETE",
|
|
@@ -884,7 +1061,7 @@ export class AuthClient {
|
|
|
884
1061
|
if (!res.ok) {
|
|
885
1062
|
return { data: null, error: await this._parseError(res) }
|
|
886
1063
|
}
|
|
887
|
-
const json = await res
|
|
1064
|
+
const json = await readJson(res, isJsonObject)
|
|
888
1065
|
return { data: { id: String(json["id"] ?? "") }, error: null }
|
|
889
1066
|
},
|
|
890
1067
|
|
|
@@ -931,26 +1108,18 @@ export class AuthClient {
|
|
|
931
1108
|
if (parts.length !== 3) {
|
|
932
1109
|
return { data: null, error: { message: "Invalid access token format" } }
|
|
933
1110
|
}
|
|
1111
|
+
const payload = decodeJwtPayload(parts[1]!)
|
|
1112
|
+
if (payload === null) {
|
|
1113
|
+
return { data: null, error: { message: "Failed to decode access token" } }
|
|
1114
|
+
}
|
|
1115
|
+
const { currentLevel, methods } = assuranceClaims(payload)
|
|
934
1116
|
try {
|
|
935
|
-
const payload = JSON.parse(atob(parts[1]!)) as Record<string, unknown>
|
|
936
|
-
const currentLevel = (payload["aal"] as "aal1" | "aal2" | undefined) ?? null
|
|
937
|
-
const amr = (payload["amr"] as Array<{ method: string }> | undefined) ?? []
|
|
938
|
-
const methods = amr.map((entry) => entry.method)
|
|
939
|
-
|
|
940
1117
|
// Determine next level: if user has verified factors, next could be aal2
|
|
941
1118
|
const userResult = await this.getUser()
|
|
942
|
-
const factors = userResult.data
|
|
1119
|
+
const factors = userResult.data.user?.factors ?? []
|
|
943
1120
|
const hasVerifiedFactors = factors.some((f) => f.status === "verified")
|
|
944
1121
|
const nextLevel = hasVerifiedFactors ? "aal2" : "aal1"
|
|
945
|
-
|
|
946
|
-
return {
|
|
947
|
-
data: {
|
|
948
|
-
currentLevel,
|
|
949
|
-
nextLevel: nextLevel as "aal1" | "aal2",
|
|
950
|
-
currentAuthenticationMethods: methods,
|
|
951
|
-
},
|
|
952
|
-
error: null,
|
|
953
|
-
}
|
|
1122
|
+
return { data: { currentLevel, nextLevel, currentAuthenticationMethods: methods }, error: null }
|
|
954
1123
|
} catch {
|
|
955
1124
|
return { data: null, error: { message: "Failed to decode access token" } }
|
|
956
1125
|
}
|
|
@@ -993,63 +1162,68 @@ export class AuthClient {
|
|
|
993
1162
|
}
|
|
994
1163
|
}
|
|
995
1164
|
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
private async
|
|
1001
|
-
const verifier = generateCodeVerifier()
|
|
1002
|
-
this.codeVerifier = verifier
|
|
1165
|
+
/**
|
|
1166
|
+
* Keep a value for the OAuth redirect to find on the way back (a new page load, so not memory).
|
|
1167
|
+
* A write that fails is ignored: same-process flows still have the in-memory copy.
|
|
1168
|
+
*/
|
|
1169
|
+
private async writeFlowItem(suffix: string, value: string): Promise<void> {
|
|
1003
1170
|
if (!this.persistSession || this.storage === null) return
|
|
1004
1171
|
try {
|
|
1005
|
-
await this.storage.setItem(this.
|
|
1172
|
+
await this.storage.setItem(`${this.storageKey}${suffix}`, value)
|
|
1006
1173
|
} catch {
|
|
1007
|
-
// Ignore storage write failures
|
|
1174
|
+
// Ignore storage write failures.
|
|
1008
1175
|
}
|
|
1009
1176
|
}
|
|
1010
1177
|
|
|
1011
|
-
private async
|
|
1012
|
-
if (this.codeVerifier !== null) return this.codeVerifier
|
|
1178
|
+
private async readFlowItem(suffix: string): Promise<string | null> {
|
|
1013
1179
|
if (this.storage === null) return null
|
|
1014
1180
|
try {
|
|
1015
|
-
const stored = await this.storage.getItem(this.
|
|
1016
|
-
|
|
1017
|
-
this.codeVerifier = stored
|
|
1018
|
-
return stored
|
|
1019
|
-
}
|
|
1181
|
+
const stored = await this.storage.getItem(`${this.storageKey}${suffix}`)
|
|
1182
|
+
return stored !== null && stored !== "" ? stored : null
|
|
1020
1183
|
} catch {
|
|
1021
|
-
|
|
1184
|
+
return null
|
|
1022
1185
|
}
|
|
1023
|
-
return null
|
|
1024
1186
|
}
|
|
1025
1187
|
|
|
1026
|
-
private async
|
|
1027
|
-
this.codeVerifier = null
|
|
1188
|
+
private async removeFlowItem(suffix: string): Promise<void> {
|
|
1028
1189
|
if (this.storage === null) return
|
|
1029
1190
|
try {
|
|
1030
|
-
await this.storage.removeItem(this.
|
|
1191
|
+
await this.storage.removeItem(`${this.storageKey}${suffix}`)
|
|
1031
1192
|
} catch {
|
|
1032
1193
|
// Ignore
|
|
1033
1194
|
}
|
|
1034
1195
|
}
|
|
1035
1196
|
|
|
1197
|
+
/** Read a flow value once: the redirect it was kept for has now arrived. */
|
|
1198
|
+
private async takeFlowItem(suffix: string): Promise<string | null> {
|
|
1199
|
+
const value = await this.readFlowItem(suffix)
|
|
1200
|
+
if (value !== null) await this.removeFlowItem(suffix)
|
|
1201
|
+
return value
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
private async beginPkce(): Promise<void> {
|
|
1205
|
+
const verifier = generateCodeVerifier()
|
|
1206
|
+
this.codeVerifier = verifier
|
|
1207
|
+
await this.writeFlowItem(VERIFIER_SUFFIX, verifier)
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
private async readCodeVerifier(): Promise<string | null> {
|
|
1211
|
+
if (this.codeVerifier !== null) return this.codeVerifier
|
|
1212
|
+
this.codeVerifier = await this.readFlowItem(VERIFIER_SUFFIX)
|
|
1213
|
+
return this.codeVerifier
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
private async clearCodeVerifier(): Promise<void> {
|
|
1217
|
+
this.codeVerifier = null
|
|
1218
|
+
await this.removeFlowItem(VERIFIER_SUFFIX)
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1036
1221
|
/** Decode JWT `exp` claim without verifying the signature. */
|
|
1037
1222
|
private decodeJwtExp(accessToken: string): number | null {
|
|
1038
1223
|
const parts = accessToken.split(".")
|
|
1039
1224
|
if (parts.length < 2) return null
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
const padded = payload + "=".repeat((4 - (payload.length % 4)) % 4)
|
|
1043
|
-
const b64 = padded.replace(/-/g, "+").replace(/_/g, "/")
|
|
1044
|
-
const json =
|
|
1045
|
-
typeof atob === "function"
|
|
1046
|
-
? atob(b64)
|
|
1047
|
-
: Buffer.from(b64, "base64").toString("utf8")
|
|
1048
|
-
const claims = JSON.parse(json) as { exp?: unknown }
|
|
1049
|
-
return typeof claims.exp === "number" ? claims.exp : null
|
|
1050
|
-
} catch {
|
|
1051
|
-
return null
|
|
1052
|
-
}
|
|
1225
|
+
const exp = decodeJwtPayload(parts[1]!)?.["exp"]
|
|
1226
|
+
return typeof exp === "number" ? exp : null
|
|
1053
1227
|
}
|
|
1054
1228
|
|
|
1055
1229
|
private async readStorageItem(key: string): Promise<string | null> {
|
|
@@ -1103,70 +1277,27 @@ export class AuthClient {
|
|
|
1103
1277
|
|
|
1104
1278
|
private parsePersistedSession(raw: string): Session | null {
|
|
1105
1279
|
try {
|
|
1106
|
-
|
|
1107
|
-
return this.normalizePersistedSession(parsed)
|
|
1280
|
+
return this.normalizePersistedSession(JSON.parse(raw))
|
|
1108
1281
|
} catch {
|
|
1109
1282
|
return null
|
|
1110
1283
|
}
|
|
1111
1284
|
}
|
|
1112
1285
|
|
|
1286
|
+
/** A stored session, written by this client (camelCase) or by a server-side helper (snake_case). */
|
|
1113
1287
|
private normalizePersistedSession(raw: unknown): Session | null {
|
|
1114
|
-
if (
|
|
1115
|
-
const
|
|
1116
|
-
const
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
? r["access_token"]
|
|
1121
|
-
: null
|
|
1122
|
-
if (accessToken === null) return null
|
|
1123
|
-
const refreshToken =
|
|
1124
|
-
typeof r["refreshToken"] === "string"
|
|
1125
|
-
? r["refreshToken"]
|
|
1126
|
-
: typeof r["refresh_token"] === "string"
|
|
1127
|
-
? r["refresh_token"]
|
|
1128
|
-
: ""
|
|
1129
|
-
const tokenType =
|
|
1130
|
-
typeof r["tokenType"] === "string"
|
|
1131
|
-
? r["tokenType"]
|
|
1132
|
-
: typeof r["token_type"] === "string"
|
|
1133
|
-
? r["token_type"]
|
|
1134
|
-
: "bearer"
|
|
1135
|
-
const expiresIn =
|
|
1136
|
-
typeof r["expiresIn"] === "number"
|
|
1137
|
-
? r["expiresIn"]
|
|
1138
|
-
: typeof r["expires_in"] === "number"
|
|
1139
|
-
? r["expires_in"]
|
|
1140
|
-
: 3600
|
|
1141
|
-
const userRaw =
|
|
1142
|
-
typeof r["user"] === "object" && r["user"] !== null
|
|
1143
|
-
? (r["user"] as Record<string, unknown>)
|
|
1144
|
-
: null
|
|
1145
|
-
if (userRaw === null) return null
|
|
1146
|
-
const normalizedUserRaw: Record<string, unknown> = {
|
|
1147
|
-
...userRaw,
|
|
1148
|
-
...(userRaw["app_metadata"] === undefined &&
|
|
1149
|
-
userRaw["appMetadata"] !== undefined && { app_metadata: userRaw["appMetadata"] }),
|
|
1150
|
-
...(userRaw["user_metadata"] === undefined &&
|
|
1151
|
-
userRaw["userMetadata"] !== undefined && { user_metadata: userRaw["userMetadata"] }),
|
|
1152
|
-
...(userRaw["created_at"] === undefined &&
|
|
1153
|
-
userRaw["createdAt"] !== undefined && { created_at: userRaw["createdAt"] }),
|
|
1154
|
-
...(userRaw["updated_at"] === undefined &&
|
|
1155
|
-
userRaw["updatedAt"] !== undefined && { updated_at: userRaw["updatedAt"] }),
|
|
1156
|
-
}
|
|
1157
|
-
const session: Session = {
|
|
1288
|
+
if (!isJsonObject(raw)) return null
|
|
1289
|
+
const accessToken = eitherKey(raw, "accessToken", "access_token", isString)
|
|
1290
|
+
const user = raw["user"]
|
|
1291
|
+
if (accessToken === undefined || !isJsonObject(user)) return null
|
|
1292
|
+
const expiresAt = eitherKey(raw, "expiresAt", "expires_at", isNumber)
|
|
1293
|
+
return {
|
|
1158
1294
|
accessToken,
|
|
1159
|
-
refreshToken,
|
|
1160
|
-
tokenType,
|
|
1161
|
-
expiresIn,
|
|
1162
|
-
user: this._parseUser(
|
|
1163
|
-
...(
|
|
1164
|
-
? { expiresAt: r["expiresAt"] }
|
|
1165
|
-
: typeof r["expires_at"] === "number"
|
|
1166
|
-
? { expiresAt: r["expires_at"] }
|
|
1167
|
-
: {}),
|
|
1295
|
+
refreshToken: eitherKey(raw, "refreshToken", "refresh_token", isString) ?? "",
|
|
1296
|
+
tokenType: eitherKey(raw, "tokenType", "token_type", isString) ?? "bearer",
|
|
1297
|
+
expiresIn: eitherKey(raw, "expiresIn", "expires_in", isNumber) ?? 3600,
|
|
1298
|
+
user: this._parseUser(snakeCaseUser(user)),
|
|
1299
|
+
...(expiresAt !== undefined && { expiresAt }),
|
|
1168
1300
|
}
|
|
1169
|
-
return session
|
|
1170
1301
|
}
|
|
1171
1302
|
|
|
1172
1303
|
private syncPersistedSession(session: Session | null): void {
|
|
@@ -1295,13 +1426,14 @@ export class AuthClient {
|
|
|
1295
1426
|
}
|
|
1296
1427
|
}
|
|
1297
1428
|
|
|
1429
|
+
/** Every refusal from the auth server goes through here, so none of them drops the code. */
|
|
1298
1430
|
private async _parseError(res: Response): Promise<SupatypeError> {
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1431
|
+
return authErrorFromBody(await readJsonObject(res), res.status)
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
/** The user a `/user` response describes. Throws on a body that is not a JSON object. */
|
|
1435
|
+
private async _readUser(res: Response): Promise<User> {
|
|
1436
|
+
return this._parseUser(await readJson(res, isJsonObject))
|
|
1305
1437
|
}
|
|
1306
1438
|
|
|
1307
1439
|
private async _parseAuthResponse(res: Response): Promise<{
|
|
@@ -1309,19 +1441,19 @@ export class AuthClient {
|
|
|
1309
1441
|
error: SupatypeError | null
|
|
1310
1442
|
}> {
|
|
1311
1443
|
if (!res.ok) {
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1444
|
+
return { data: { session: null, user: null }, error: await this._parseError(res) }
|
|
1445
|
+
}
|
|
1446
|
+
const json = await readJson(res, isJsonObject)
|
|
1447
|
+
const accessToken = json["access_token"]
|
|
1448
|
+
// A sign-up still waiting for its email confirmation is answered with the bare user and no
|
|
1449
|
+
// tokens. That is not a session, so nothing is stored and no SIGNED_IN is emitted.
|
|
1450
|
+
if (typeof accessToken !== "string" || accessToken === "") {
|
|
1451
|
+
const bareUser = json["user"]
|
|
1452
|
+
return { data: { session: null, user: this._parseUser(isJsonObject(bareUser) ? bareUser : json) }, error: null }
|
|
1320
1453
|
}
|
|
1321
|
-
const
|
|
1322
|
-
const user = this._parseUser((json["user"] ?? {}) as Record<string, unknown>)
|
|
1454
|
+
const user = this._parseUser(objectOrEmpty(json["user"]))
|
|
1323
1455
|
const session: Session = {
|
|
1324
|
-
accessToken
|
|
1456
|
+
accessToken,
|
|
1325
1457
|
tokenType: String(json["token_type"] ?? "bearer"),
|
|
1326
1458
|
expiresIn: Number(json["expires_in"] ?? 3600),
|
|
1327
1459
|
...(json["expires_at"] !== undefined && { expiresAt: Number(json["expires_at"]) }),
|
|
@@ -1339,34 +1471,43 @@ export class AuthClient {
|
|
|
1339
1471
|
...(raw["phone"] !== undefined && { phone: String(raw["phone"]) }),
|
|
1340
1472
|
...(raw["role"] !== undefined && { role: String(raw["role"]) }),
|
|
1341
1473
|
...(raw["is_anonymous"] !== undefined && { isAnonymous: Boolean(raw["is_anonymous"]) }),
|
|
1342
|
-
appMetadata: (raw["app_metadata"]
|
|
1343
|
-
userMetadata: (raw["user_metadata"]
|
|
1474
|
+
appMetadata: objectOrEmpty(raw["app_metadata"]),
|
|
1475
|
+
userMetadata: objectOrEmpty(raw["user_metadata"]),
|
|
1344
1476
|
createdAt: String(raw["created_at"] ?? ""),
|
|
1345
1477
|
updatedAt: String(raw["updated_at"] ?? ""),
|
|
1346
1478
|
}
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
identityData: (i["identity_data"] ?? {}) as Record<string, unknown>,
|
|
1352
|
-
identityId: String(i["identity_id"] ?? ""),
|
|
1353
|
-
provider: String(i["provider"] ?? ""),
|
|
1354
|
-
createdAt: String(i["created_at"] ?? ""),
|
|
1355
|
-
updatedAt: String(i["updated_at"] ?? ""),
|
|
1356
|
-
...(i["last_sign_in_at"] !== undefined && { lastSignInAt: String(i["last_sign_in_at"]) }),
|
|
1357
|
-
}))
|
|
1358
|
-
}
|
|
1359
|
-
if (Array.isArray(raw["factors"])) {
|
|
1360
|
-
user.factors = (raw["factors"] as Record<string, unknown>[]).map((f) => ({
|
|
1361
|
-
id: String(f["id"] ?? ""),
|
|
1362
|
-
factorType: String(f["factor_type"] ?? "totp") as "totp" | "phone" | "webauthn",
|
|
1363
|
-
status: String(f["status"] ?? "unverified") as "verified" | "unverified",
|
|
1364
|
-
createdAt: String(f["created_at"] ?? ""),
|
|
1365
|
-
updatedAt: String(f["updated_at"] ?? ""),
|
|
1366
|
-
...(f["friendly_name"] !== undefined && { friendlyName: String(f["friendly_name"]) }),
|
|
1367
|
-
...(f["phone"] !== undefined && { phone: String(f["phone"]) }),
|
|
1368
|
-
}))
|
|
1369
|
-
}
|
|
1479
|
+
const identities = raw["identities"]
|
|
1480
|
+
if (Array.isArray(identities)) user.identities = identities.filter(isJsonObject).map(parseIdentity)
|
|
1481
|
+
const factors = raw["factors"]
|
|
1482
|
+
if (Array.isArray(factors)) user.factors = factors.filter(isJsonObject).map(parseFactor)
|
|
1370
1483
|
return user
|
|
1371
1484
|
}
|
|
1372
1485
|
}
|
|
1486
|
+
|
|
1487
|
+
function parseIdentity(i: Record<string, unknown>): UserIdentity {
|
|
1488
|
+
return {
|
|
1489
|
+
id: String(i["id"] ?? ""),
|
|
1490
|
+
userId: String(i["user_id"] ?? ""),
|
|
1491
|
+
identityData: objectOrEmpty(i["identity_data"]),
|
|
1492
|
+
identityId: String(i["identity_id"] ?? ""),
|
|
1493
|
+
provider: String(i["provider"] ?? ""),
|
|
1494
|
+
createdAt: String(i["created_at"] ?? ""),
|
|
1495
|
+
updatedAt: String(i["updated_at"] ?? ""),
|
|
1496
|
+
...(i["last_sign_in_at"] !== undefined && { lastSignInAt: String(i["last_sign_in_at"]) }),
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
/** A factor as the server lists it. A type or state it leaves out reads as `totp` / `unverified`. */
|
|
1501
|
+
function parseFactor(f: Record<string, unknown>): Factor {
|
|
1502
|
+
const factorType = f["factor_type"]
|
|
1503
|
+
const status = f["status"]
|
|
1504
|
+
return {
|
|
1505
|
+
id: String(f["id"] ?? ""),
|
|
1506
|
+
factorType: isFactorType(factorType) ? factorType : "totp",
|
|
1507
|
+
status: isFactorStatus(status) ? status : "unverified",
|
|
1508
|
+
createdAt: String(f["created_at"] ?? ""),
|
|
1509
|
+
updatedAt: String(f["updated_at"] ?? ""),
|
|
1510
|
+
...(f["friendly_name"] !== undefined && { friendlyName: String(f["friendly_name"]) }),
|
|
1511
|
+
...(f["phone"] !== undefined && { phone: String(f["phone"]) }),
|
|
1512
|
+
}
|
|
1513
|
+
}
|