@supatype/client 0.3.6 → 0.8.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 +69 -30
- 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 +86 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +383 -275
- 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 +170 -165
- 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 +57 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +300 -88
- 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 +137 -38
- 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 +98 -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 +434 -281
- 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 +289 -208
- 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 +333 -90
- package/src/select-types.ts +184 -0
- package/src/storage.ts +223 -44
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +104 -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 +187 -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 +142 -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-ack-ref.test.ts +112 -0
- 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-shared-channel.test.ts +209 -0
- 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 +187 -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 +7 -9
- 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 +17 -31
- package/tests/storage-url-encoding.test.ts +52 -0
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/blob.ts +10 -0
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +41 -14
- 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,28 +11,129 @@ 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
|
|
|
22
44
|
interface AuthClientOptions {
|
|
23
45
|
initialSession?: Session | undefined
|
|
24
46
|
persistSession?: boolean | undefined
|
|
47
|
+
/** Refresh on a timer before the token expires, and at once when it starts expired. Default: true. */
|
|
48
|
+
autoRefreshToken?: boolean | undefined
|
|
49
|
+
/** Refresh an expired access token when a request or `getSession` finds it. Default: true. */
|
|
50
|
+
refreshExpiredToken?: boolean | undefined
|
|
25
51
|
storageKey?: string | undefined
|
|
26
52
|
cookiePrefix?: string | undefined
|
|
27
53
|
/** Custom session store (replaces browser localStorage/cookies when set). */
|
|
28
54
|
storage?: AuthStorage | undefined
|
|
55
|
+
/** How requests are sent. `createClient` passes its fetch, so `timeout` and `retry` apply here too. */
|
|
56
|
+
transport?: RequestTransport | undefined
|
|
57
|
+
/** Finish a sign-in carried by the page's URL on start (browser only). Default: true. */
|
|
58
|
+
detectSessionInUrl?: boolean | undefined
|
|
29
59
|
}
|
|
30
60
|
|
|
31
61
|
const DEFAULT_STORAGE_KEY = "supatype.auth.session"
|
|
32
62
|
const DEFAULT_COOKIE_PREFIX = "st"
|
|
63
|
+
/** Storage key suffixes for the state an OAuth redirect has to survive. */
|
|
64
|
+
const VERIFIER_SUFFIX = "-code-verifier"
|
|
65
|
+
const PROVIDER_SUFFIX = "-oauth-provider"
|
|
33
66
|
const DEBUG_AUTH = typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1"
|
|
34
67
|
|
|
68
|
+
/**
|
|
69
|
+
* The auth server's refusal as a `SupatypeError`, with its machine-readable code kept.
|
|
70
|
+
*
|
|
71
|
+
* Two body shapes arrive: `{ code, error_code, msg }` from the API, and the OAuth token endpoint's
|
|
72
|
+
* `{ error, error_description }`, where `error` is the code. The code is what an app branches on
|
|
73
|
+
* (`invalid_credentials`, `weak_password`, `email_not_confirmed`); the numeric `code` in the first
|
|
74
|
+
* shape is only the HTTP status again, so it is not used. Message precedence follows supabase-js.
|
|
75
|
+
*/
|
|
76
|
+
function authErrorFromBody(body: Record<string, unknown>, status: number): SupatypeError {
|
|
77
|
+
const text = (key: string): string | undefined => {
|
|
78
|
+
const value = body[key]
|
|
79
|
+
return typeof value === "string" && value !== "" ? value : undefined
|
|
80
|
+
}
|
|
81
|
+
const code = text("error_code") ?? text("error")
|
|
82
|
+
const message =
|
|
83
|
+
text("msg") ?? text("message") ?? text("error_description") ?? text("error") ??
|
|
84
|
+
`Auth request failed (HTTP ${status})`
|
|
85
|
+
return { message, status, ...(code !== undefined && { code }) }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The assurance levels the client reports; the server's unused `aal3` reads as unknown. */
|
|
89
|
+
const isAal = isOneOf(["aal1", "aal2"])
|
|
90
|
+
/** One entry of the JWT's `amr` claim: how the session was authenticated, and when. */
|
|
91
|
+
const isAmrEntry = isShape({ method: isString })
|
|
92
|
+
/** The factor types and states supatype-auth defines (internal/auth/models/factor.go). */
|
|
93
|
+
const isFactorType = isOneOf(["totp", "phone", "webauthn"])
|
|
94
|
+
const isFactorStatus = isOneOf(["verified", "unverified"])
|
|
95
|
+
|
|
96
|
+
/** The assurance level and the authentication methods an access token's claims carry. */
|
|
97
|
+
function assuranceClaims(claims: Record<string, unknown>): {
|
|
98
|
+
currentLevel: "aal1" | "aal2" | null
|
|
99
|
+
methods: string[]
|
|
100
|
+
} {
|
|
101
|
+
const aal = claims["aal"]
|
|
102
|
+
const amr = claims["amr"]
|
|
103
|
+
return {
|
|
104
|
+
currentLevel: isAal(aal) ? aal : null,
|
|
105
|
+
methods: Array.isArray(amr) ? amr.filter(isAmrEntry).map((entry) => entry.method) : [],
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The value under `first` when the guard accepts it, else the one under `second`, else undefined. */
|
|
110
|
+
function eitherKey<T>(
|
|
111
|
+
body: Record<string, unknown>,
|
|
112
|
+
first: string,
|
|
113
|
+
second: string,
|
|
114
|
+
guard: Guard<T>,
|
|
115
|
+
): T | undefined {
|
|
116
|
+
const a = body[first]
|
|
117
|
+
if (guard(a)) return a
|
|
118
|
+
const b = body[second]
|
|
119
|
+
return guard(b) ? b : undefined
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A stored user with its camelCase keys copied to the snake_case ones `_parseUser` reads. */
|
|
123
|
+
function snakeCaseUser(user: Record<string, unknown>): Record<string, unknown> {
|
|
124
|
+
const aliases = [
|
|
125
|
+
["app_metadata", "appMetadata"],
|
|
126
|
+
["user_metadata", "userMetadata"],
|
|
127
|
+
["created_at", "createdAt"],
|
|
128
|
+
["updated_at", "updatedAt"],
|
|
129
|
+
] as const
|
|
130
|
+
const normalized = { ...user }
|
|
131
|
+
for (const [snake, camel] of aliases) {
|
|
132
|
+
if (user[snake] === undefined && user[camel] !== undefined) normalized[snake] = user[camel]
|
|
133
|
+
}
|
|
134
|
+
return normalized
|
|
135
|
+
}
|
|
136
|
+
|
|
35
137
|
export class AuthClient {
|
|
36
138
|
private readonly url: string
|
|
37
139
|
private readonly baseHeaders: Record<string, string>
|
|
@@ -39,13 +141,21 @@ export class AuthClient {
|
|
|
39
141
|
private readonly listeners = new Map<string, AuthListener>()
|
|
40
142
|
private listenerIdCounter = 0
|
|
41
143
|
private readonly persistSession: boolean
|
|
144
|
+
/** False leaves every refresh to `ensureValidSession`, which each request calls first. */
|
|
145
|
+
private readonly autoRefreshToken: boolean
|
|
146
|
+
/** False makes `ensureValidSession` leave an expired session as it is, for the server to refuse. */
|
|
147
|
+
private readonly refreshExpiredToken: boolean
|
|
42
148
|
private readonly storageKey: string
|
|
43
149
|
private readonly cookieName: string
|
|
44
150
|
private readonly storage: AuthStorage | null
|
|
151
|
+
/** The client's fetch, with its timeout; only reads are retried. */
|
|
152
|
+
private readonly send: RequestTransport
|
|
45
153
|
/** When true, session is also mirrored to document.cookie (browser default path only). */
|
|
46
154
|
private readonly useCookies: boolean
|
|
47
|
-
/** Resolves when async storage hydration
|
|
155
|
+
/** Resolves when async storage hydration and any sign-in carried by the page's URL complete. */
|
|
48
156
|
private readonly ready: Promise<void>
|
|
157
|
+
/** What `ready` settles with: the refusal the page's URL reported, if any. */
|
|
158
|
+
private readonly initialized: Promise<{ error: AuthRedirectError | null }>
|
|
49
159
|
/** Pending auto-refresh timer; refreshes the access token shortly before it expires. */
|
|
50
160
|
private refreshTimer: ReturnType<typeof setTimeout> | null = null
|
|
51
161
|
/** Dedupes concurrent refresh attempts (getSession + auto-refresh). */
|
|
@@ -57,52 +167,97 @@ export class AuthClient {
|
|
|
57
167
|
this.url = url
|
|
58
168
|
this.baseHeaders = baseHeaders
|
|
59
169
|
this.persistSession = opts.persistSession ?? true
|
|
170
|
+
this.autoRefreshToken = opts.autoRefreshToken ?? true
|
|
171
|
+
this.refreshExpiredToken = opts.refreshExpiredToken ?? true
|
|
60
172
|
this.storageKey = opts.storageKey ?? DEFAULT_STORAGE_KEY
|
|
61
173
|
const cookiePrefix = opts.cookiePrefix ?? DEFAULT_COOKIE_PREFIX
|
|
62
174
|
this.cookieName = `${cookiePrefix}-auth-token`
|
|
63
175
|
this.useCookies = opts.storage === undefined
|
|
64
176
|
this.storage = opts.storage ?? this.getBrowserStorage()
|
|
177
|
+
this.send = opts.transport ?? plainFetch
|
|
65
178
|
|
|
179
|
+
const hydrated = this.loadInitialSession(opts)
|
|
180
|
+
this.initialized = opts.detectSessionInUrl === false
|
|
181
|
+
? hydrated.then(() => ({ error: null }))
|
|
182
|
+
: hydrated.then(() => this.completeRedirect())
|
|
183
|
+
this.ready = this.initialized.then(() => undefined)
|
|
184
|
+
// Keep the access token fresh while the app is open (and refresh immediately
|
|
185
|
+
// if a persisted session loaded already expired).
|
|
186
|
+
this.scheduleAutoRefresh()
|
|
187
|
+
if (this.autoRefreshToken && this.currentSession !== null && this.isAccessTokenExpired(this.currentSession)) {
|
|
188
|
+
void this.ensureValidSession()
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** The session the client starts with: the one passed in, else the persisted one. */
|
|
193
|
+
private loadInitialSession(opts: AuthClientOptions): Promise<void> {
|
|
66
194
|
if (opts.initialSession !== undefined) {
|
|
67
195
|
this.currentSession = opts.initialSession
|
|
68
|
-
this.ready = Promise.resolve()
|
|
69
196
|
if (DEBUG_AUTH) {
|
|
70
197
|
console.debug("[supatype:auth] constructor initialSession provided", {
|
|
71
198
|
hasSession: true,
|
|
72
199
|
userId: opts.initialSession.user.id,
|
|
73
200
|
})
|
|
74
201
|
}
|
|
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()
|
|
202
|
+
return Promise.resolve()
|
|
92
203
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
this.
|
|
96
|
-
if (
|
|
97
|
-
|
|
204
|
+
if (!this.persistSession) return Promise.resolve()
|
|
205
|
+
if (opts.storage !== undefined) return this.hydrateFromStorage()
|
|
206
|
+
this.currentSession = this.loadPersistedSession()
|
|
207
|
+
if (DEBUG_AUTH) {
|
|
208
|
+
console.debug("[supatype:auth] constructor loaded persisted session", {
|
|
209
|
+
hasSession: this.currentSession !== null,
|
|
210
|
+
userId: this.currentSession?.user.id ?? null,
|
|
211
|
+
storageKey: this.storageKey,
|
|
212
|
+
cookieName: this.cookieName,
|
|
213
|
+
})
|
|
98
214
|
}
|
|
215
|
+
return Promise.resolve()
|
|
99
216
|
}
|
|
100
217
|
|
|
101
|
-
/** Resolves when
|
|
218
|
+
/** Resolves when the client has its starting session (storage hydrated, any URL sign-in done). */
|
|
102
219
|
whenReady(): Promise<void> {
|
|
103
220
|
return this.ready
|
|
104
221
|
}
|
|
105
222
|
|
|
223
|
+
/**
|
|
224
|
+
* Wait for the client's start, and learn whether a sign-in in the page's URL was refused.
|
|
225
|
+
*
|
|
226
|
+
* The same shape as supabase-js's `initialize()`. A refused OAuth sign-in comes back as
|
|
227
|
+
* `?error=...&error_description=...`; this is where an app (or `useAuth`) reads it.
|
|
228
|
+
*/
|
|
229
|
+
initialize(): Promise<{ error: AuthRedirectError | null }> {
|
|
230
|
+
return this.initialized
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Finish the sign-in the page's URL carries, as supabase-js's `detectSessionInUrl` does.
|
|
235
|
+
*
|
|
236
|
+
* Whatever session was stored is set aside first, so a new sign-in is announced as `SIGNED_IN`
|
|
237
|
+
* and a refused one leaves the browser signed out, as supabase-js does after a failed attempt.
|
|
238
|
+
*/
|
|
239
|
+
private async completeRedirect(): Promise<{ error: AuthRedirectError | null }> {
|
|
240
|
+
const href = browserHref()
|
|
241
|
+
if (href === null || !(await this.isAuthRedirect(href))) return { error: null }
|
|
242
|
+
const provider = await this.takeFlowItem(PROVIDER_SUFFIX)
|
|
243
|
+
this.currentSession = null
|
|
244
|
+
const { error } = await this.getSessionFromUrl(href).catch((err: unknown) => ({
|
|
245
|
+
error: { message: err instanceof Error ? err.message : "Could not finish the sign-in" },
|
|
246
|
+
}))
|
|
247
|
+
cleanBrowserUrl(href)
|
|
248
|
+
if (error === null) return { error: null }
|
|
249
|
+
this._setSession(null)
|
|
250
|
+
return { error: { ...error, ...(provider !== null && { provider }) } }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** A URL with tokens or a refusal, or with a `code` for a PKCE flow this client started. */
|
|
254
|
+
private async isAuthRedirect(href: string): Promise<boolean> {
|
|
255
|
+
const params = redirectParams(href)
|
|
256
|
+
if (params === null) return false
|
|
257
|
+
if (carriesImplicitResult(params)) return true
|
|
258
|
+
return redirectParam(params, "code") !== null && (await this.readCodeVerifier()) !== null
|
|
259
|
+
}
|
|
260
|
+
|
|
106
261
|
private async hydrateFromStorage(): Promise<void> {
|
|
107
262
|
try {
|
|
108
263
|
const session = await this.loadPersistedSessionAsync()
|
|
@@ -135,13 +290,8 @@ export class AuthClient {
|
|
|
135
290
|
private jwtExpMs(accessToken: string): number | null {
|
|
136
291
|
const parts = accessToken.split(".")
|
|
137
292
|
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
|
-
}
|
|
293
|
+
const exp = decodeJwtPayload(parts[1]!)?.["exp"]
|
|
294
|
+
return typeof exp === "number" ? exp * 1000 : null
|
|
145
295
|
}
|
|
146
296
|
|
|
147
297
|
private isAccessTokenExpired(session: Session, skewMs = 0): boolean {
|
|
@@ -163,6 +313,8 @@ export class AuthClient {
|
|
|
163
313
|
private async ensureValidSessionInternal(): Promise<void> {
|
|
164
314
|
const session = this.currentSession
|
|
165
315
|
if (session === null || !this.isAccessTokenExpired(session)) return
|
|
316
|
+
// Sent as it is: a refresh nobody can store spends a refresh token someone else holds.
|
|
317
|
+
if (!this.refreshExpiredToken) return
|
|
166
318
|
if (!session.refreshToken?.trim()) {
|
|
167
319
|
this._setSession(null)
|
|
168
320
|
return
|
|
@@ -185,7 +337,7 @@ export class AuthClient {
|
|
|
185
337
|
clearTimeout(this.refreshTimer)
|
|
186
338
|
this.refreshTimer = null
|
|
187
339
|
}
|
|
188
|
-
if (typeof setTimeout === "undefined") return
|
|
340
|
+
if (!this.autoRefreshToken || typeof setTimeout === "undefined") return
|
|
189
341
|
const session = this.currentSession
|
|
190
342
|
if (session === null || !session.refreshToken) return
|
|
191
343
|
|
|
@@ -195,12 +347,13 @@ export class AuthClient {
|
|
|
195
347
|
? Math.max(0, (session.expiresIn || 3600) * 1000 - 60_000)
|
|
196
348
|
: Math.max(0, expiryMs - Date.now() - 60_000)
|
|
197
349
|
|
|
198
|
-
|
|
350
|
+
const timer = setTimeout(() => {
|
|
199
351
|
this.refreshTimer = null
|
|
200
352
|
void this.ensureValidSession()
|
|
201
353
|
}, delay)
|
|
202
|
-
|
|
203
|
-
|
|
354
|
+
this.refreshTimer = timer
|
|
355
|
+
// Avoid keeping a Node process alive for this timer. A browser's timer is a number: nothing to do.
|
|
356
|
+
if (typeof timer === "object" && "unref" in timer) timer.unref()
|
|
204
357
|
}
|
|
205
358
|
|
|
206
359
|
async signUp(credentials: {
|
|
@@ -218,7 +371,7 @@ export class AuthClient {
|
|
|
218
371
|
if (credentials.options?.data !== undefined) {
|
|
219
372
|
body["data"] = credentials.options.data
|
|
220
373
|
}
|
|
221
|
-
const res = await
|
|
374
|
+
const res = await this.send(`${this.url}/signup`, {
|
|
222
375
|
method: "POST",
|
|
223
376
|
headers: this.baseHeaders,
|
|
224
377
|
body: JSON.stringify(body),
|
|
@@ -233,7 +386,7 @@ export class AuthClient {
|
|
|
233
386
|
data: { session: Session | null; user: User | null }
|
|
234
387
|
error: SupatypeError | null
|
|
235
388
|
}> {
|
|
236
|
-
const res = await
|
|
389
|
+
const res = await this.send(`${this.url}/token?grant_type=password`, {
|
|
237
390
|
method: "POST",
|
|
238
391
|
headers: this.baseHeaders,
|
|
239
392
|
body: JSON.stringify({
|
|
@@ -260,7 +413,7 @@ export class AuthClient {
|
|
|
260
413
|
if (credentials?.options?.captchaToken !== undefined) {
|
|
261
414
|
body["supatype_meta_security"] = { captcha_token: credentials.options.captchaToken }
|
|
262
415
|
}
|
|
263
|
-
const res = await
|
|
416
|
+
const res = await this.send(`${this.url}/signup`, {
|
|
264
417
|
method: "POST",
|
|
265
418
|
headers: this.baseHeaders,
|
|
266
419
|
body: JSON.stringify(body),
|
|
@@ -268,6 +421,17 @@ export class AuthClient {
|
|
|
268
421
|
return this._parseAuthResponse(res)
|
|
269
422
|
}
|
|
270
423
|
|
|
424
|
+
/**
|
|
425
|
+
* An auth endpoint, carrying the caller's redirect as `redirect_to` in the query string. The
|
|
426
|
+
* server reads it from there (or a header) and never from a JSON body, so a redirect sent in the
|
|
427
|
+
* body is dropped in silence and the email links to SITE_URL instead.
|
|
428
|
+
*/
|
|
429
|
+
private endpoint(path: string, redirectTo: string | undefined): URL {
|
|
430
|
+
const url = new URL(`${this.url}${path}`)
|
|
431
|
+
if (redirectTo !== undefined) url.searchParams.set("redirect_to", redirectTo)
|
|
432
|
+
return url
|
|
433
|
+
}
|
|
434
|
+
|
|
271
435
|
async signInWithOAuth(opts: {
|
|
272
436
|
provider: string
|
|
273
437
|
options?: {
|
|
@@ -275,16 +439,28 @@ export class AuthClient {
|
|
|
275
439
|
/** Default: `implicit` (web-compatible). Pass `pkce` for mobile / RN. */
|
|
276
440
|
flowType?: AuthFlowType | undefined
|
|
277
441
|
scopes?: string | undefined
|
|
442
|
+
/**
|
|
443
|
+
* Extra `/authorize` query parameters, sent as given. The flow's own (`provider`,
|
|
444
|
+
* `redirect_to`, `scopes`, the PKCE challenge) are set after these and cannot be replaced.
|
|
445
|
+
*/
|
|
446
|
+
queryParams?: Record<string, string> | undefined
|
|
278
447
|
} | undefined
|
|
279
448
|
}): Promise<{
|
|
280
449
|
data: { url: string; provider: string }
|
|
281
450
|
error: SupatypeError | null
|
|
282
451
|
}> {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
if (opts.
|
|
286
|
-
|
|
452
|
+
// The server answers /authorize for a disabled provider with a bare JSON 400, which a browser
|
|
453
|
+
// navigating there shows as raw text; asking first lets the caller show a message instead.
|
|
454
|
+
if (await this.providerDisabled(opts.provider)) {
|
|
455
|
+
const message = `Sign-in with ${opts.provider} is not enabled for this project.`
|
|
456
|
+
return { data: { url: "", provider: opts.provider }, error: { message, status: 400, code: "provider_disabled" } }
|
|
457
|
+
}
|
|
458
|
+
await this.writeFlowItem(PROVIDER_SUFFIX, opts.provider)
|
|
459
|
+
const url = this.endpoint("/authorize", opts.options?.redirectTo)
|
|
460
|
+
for (const [key, value] of Object.entries(opts.options?.queryParams ?? {})) {
|
|
461
|
+
if (!url.searchParams.has(key)) url.searchParams.set(key, value)
|
|
287
462
|
}
|
|
463
|
+
url.searchParams.set("provider", opts.provider)
|
|
288
464
|
if (opts.options?.scopes !== undefined) {
|
|
289
465
|
url.searchParams.set("scopes", opts.options.scopes)
|
|
290
466
|
}
|
|
@@ -297,6 +473,22 @@ export class AuthClient {
|
|
|
297
473
|
return { data: { url: url.toString(), provider: opts.provider }, error: null }
|
|
298
474
|
}
|
|
299
475
|
|
|
476
|
+
/**
|
|
477
|
+
* True only when the server's `/settings` list the provider as off. A provider they do not list
|
|
478
|
+
* (a `custom:` one) or settings that cannot be read leave the decision to `/authorize`. Looked up
|
|
479
|
+
* in lower case, as `/authorize` resolves it, so `GitHub` is refused exactly when `github` is.
|
|
480
|
+
*/
|
|
481
|
+
private async providerDisabled(provider: string): Promise<boolean> {
|
|
482
|
+
try {
|
|
483
|
+
const res = await this.send(`${this.url}/settings`, { headers: this.baseHeaders })
|
|
484
|
+
if (!res.ok) return false
|
|
485
|
+
const external = objectOrEmpty((await readJsonObject(res))["external"])
|
|
486
|
+
return external[provider.toLowerCase()] === false
|
|
487
|
+
} catch {
|
|
488
|
+
return false
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
300
492
|
/**
|
|
301
493
|
* Apply tokens from an OAuth / deep-link redirect (implicit grant) or restore a session.
|
|
302
494
|
* Fetches `/user` to hydrate the user object, then persists via the configured storage.
|
|
@@ -308,7 +500,7 @@ export class AuthClient {
|
|
|
308
500
|
data: { session: Session | null; user: User | null }
|
|
309
501
|
error: SupatypeError | null
|
|
310
502
|
}> {
|
|
311
|
-
const res = await
|
|
503
|
+
const res = await this.send(`${this.url}/user`, {
|
|
312
504
|
headers: {
|
|
313
505
|
...this.baseHeaders,
|
|
314
506
|
Authorization: `Bearer ${params.accessToken}`,
|
|
@@ -320,8 +512,7 @@ export class AuthClient {
|
|
|
320
512
|
error: await this._parseError(res),
|
|
321
513
|
}
|
|
322
514
|
}
|
|
323
|
-
const
|
|
324
|
-
const user = this._parseUser(raw)
|
|
515
|
+
const user = await this._readUser(res)
|
|
325
516
|
const session: Session = {
|
|
326
517
|
accessToken: params.accessToken,
|
|
327
518
|
refreshToken: params.refreshToken,
|
|
@@ -357,7 +548,7 @@ export class AuthClient {
|
|
|
357
548
|
},
|
|
358
549
|
}
|
|
359
550
|
}
|
|
360
|
-
const res = await
|
|
551
|
+
const res = await this.send(`${this.url}/token?grant_type=pkce`, {
|
|
361
552
|
method: "POST",
|
|
362
553
|
headers: this.baseHeaders,
|
|
363
554
|
body: JSON.stringify({
|
|
@@ -377,33 +568,35 @@ export class AuthClient {
|
|
|
377
568
|
data: { session: Session | null; user: User | null }
|
|
378
569
|
error: SupatypeError | null
|
|
379
570
|
}> {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
parsed = new URL(url)
|
|
383
|
-
} catch {
|
|
571
|
+
const params = redirectParams(url)
|
|
572
|
+
if (params === null) {
|
|
384
573
|
return {
|
|
385
574
|
data: { session: null, user: null },
|
|
386
575
|
error: { message: `Invalid redirect URL: ${url}`, status: 400 },
|
|
387
576
|
}
|
|
388
577
|
}
|
|
578
|
+
const { query, fragment: hashParams } = params
|
|
389
579
|
|
|
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
|
-
}
|
|
580
|
+
// A refused link comes back with the same fields as a refused request, in the URL instead.
|
|
581
|
+
const redirectError = { ...Object.fromEntries(hashParams), ...Object.fromEntries(query) }
|
|
582
|
+
if (redirectError["error_description"] || redirectError["error"]) {
|
|
583
|
+
return { data: { session: null, user: null }, error: authErrorFromBody(redirectError, 400) }
|
|
405
584
|
}
|
|
406
585
|
|
|
586
|
+
// The auth server marks the link it sent with `type`; a recovery link signs the user in so they
|
|
587
|
+
// can choose a new password, and the app needs to know that is why they arrived.
|
|
588
|
+
const recovery = (hashParams.get("type") ?? query.get("type")) === "recovery"
|
|
589
|
+
return this.announceRecovery(await this.sessionFromRedirect(query, hashParams), recovery)
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** The session a redirect carries: a PKCE code to exchange, or implicit-grant tokens. */
|
|
593
|
+
private async sessionFromRedirect(
|
|
594
|
+
query: URLSearchParams,
|
|
595
|
+
hashParams: URLSearchParams,
|
|
596
|
+
): Promise<{
|
|
597
|
+
data: { session: Session | null; user: User | null }
|
|
598
|
+
error: SupatypeError | null
|
|
599
|
+
}> {
|
|
407
600
|
const code = query.get("code") ?? hashParams.get("code")
|
|
408
601
|
if (code !== null && code !== "") {
|
|
409
602
|
return this.exchangeCodeForSession(code)
|
|
@@ -426,6 +619,22 @@ export class AuthClient {
|
|
|
426
619
|
}
|
|
427
620
|
}
|
|
428
621
|
|
|
622
|
+
/**
|
|
623
|
+
* Emit `PASSWORD_RECOVERY` once a recovery link or code has produced a session.
|
|
624
|
+
*
|
|
625
|
+
* After the `SIGNED_IN` that establishing the session already emitted, as `MFA_CHALLENGE_VERIFIED`
|
|
626
|
+
* follows it, so a listener keyed on sign-in still sees one and a reset page can key on this.
|
|
627
|
+
*/
|
|
628
|
+
private announceRecovery<T extends { data: { session: Session | null }; error: SupatypeError | null }>(
|
|
629
|
+
result: T,
|
|
630
|
+
recovery: boolean,
|
|
631
|
+
): T {
|
|
632
|
+
if (recovery && result.error === null && result.data.session !== null) {
|
|
633
|
+
this._emitEvent("PASSWORD_RECOVERY", result.data.session)
|
|
634
|
+
}
|
|
635
|
+
return result
|
|
636
|
+
}
|
|
637
|
+
|
|
429
638
|
async signInWithOtp(opts: {
|
|
430
639
|
email?: string | undefined
|
|
431
640
|
phone?: string | undefined
|
|
@@ -447,13 +656,13 @@ export class AuthClient {
|
|
|
447
656
|
body["channel"] = opts.options.channel
|
|
448
657
|
}
|
|
449
658
|
}
|
|
450
|
-
const res = await
|
|
659
|
+
const res = await this.send(this.endpoint("/otp", opts.options?.emailRedirectTo).toString(), {
|
|
451
660
|
method: "POST",
|
|
452
661
|
headers: this.baseHeaders,
|
|
453
662
|
body: JSON.stringify(body),
|
|
454
663
|
})
|
|
455
664
|
if (res.ok) {
|
|
456
|
-
const json = await res
|
|
665
|
+
const json = await readJsonObject(res)
|
|
457
666
|
return {
|
|
458
667
|
data: {
|
|
459
668
|
...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
|
|
@@ -461,19 +670,12 @@ export class AuthClient {
|
|
|
461
670
|
error: null,
|
|
462
671
|
}
|
|
463
672
|
}
|
|
464
|
-
|
|
465
|
-
return {
|
|
466
|
-
data: {},
|
|
467
|
-
error: {
|
|
468
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
469
|
-
status: res.status,
|
|
470
|
-
},
|
|
471
|
-
}
|
|
673
|
+
return { data: {}, error: await this._parseError(res) }
|
|
472
674
|
}
|
|
473
675
|
|
|
474
676
|
async signOut(): Promise<{ error: SupatypeError | null }> {
|
|
475
677
|
if (this.currentSession !== null) {
|
|
476
|
-
await
|
|
678
|
+
await this.send(`${this.url}/logout`, {
|
|
477
679
|
method: "POST",
|
|
478
680
|
headers: {
|
|
479
681
|
...this.baseHeaders,
|
|
@@ -501,20 +703,16 @@ export class AuthClient {
|
|
|
501
703
|
if (this.currentSession === null) {
|
|
502
704
|
return { data: { user: null }, error: null }
|
|
503
705
|
}
|
|
504
|
-
const res = await
|
|
706
|
+
const res = await this.send(`${this.url}/user`, {
|
|
505
707
|
headers: {
|
|
506
708
|
...this.baseHeaders,
|
|
507
709
|
Authorization: `Bearer ${this.currentSession.accessToken}`,
|
|
508
710
|
},
|
|
509
711
|
})
|
|
510
712
|
if (!res.ok) {
|
|
511
|
-
return {
|
|
512
|
-
data: { user: null },
|
|
513
|
-
error: { message: "Could not get user", status: res.status },
|
|
514
|
-
}
|
|
713
|
+
return { data: { user: null }, error: await this._parseError(res) }
|
|
515
714
|
}
|
|
516
|
-
|
|
517
|
-
return { data: { user: this._parseUser(raw) }, error: null }
|
|
715
|
+
return { data: { user: await this._readUser(res) }, error: null }
|
|
518
716
|
}
|
|
519
717
|
|
|
520
718
|
async refreshSession(): Promise<{
|
|
@@ -529,7 +727,7 @@ export class AuthClient {
|
|
|
529
727
|
return { data: { session: null }, error: { message: "No refresh token" } }
|
|
530
728
|
}
|
|
531
729
|
try {
|
|
532
|
-
const res = await
|
|
730
|
+
const res = await this.send(`${this.url}/token?grant_type=refresh_token`, {
|
|
533
731
|
method: "POST",
|
|
534
732
|
headers: this.baseHeaders,
|
|
535
733
|
body: JSON.stringify({ refresh_token: this.currentSession.refreshToken }),
|
|
@@ -551,24 +749,13 @@ export class AuthClient {
|
|
|
551
749
|
email: string,
|
|
552
750
|
options?: { redirectTo?: string | undefined } | undefined,
|
|
553
751
|
): 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`, {
|
|
752
|
+
const res = await this.send(this.endpoint("/recover", options?.redirectTo).toString(), {
|
|
559
753
|
method: "POST",
|
|
560
754
|
headers: this.baseHeaders,
|
|
561
|
-
body: JSON.stringify(
|
|
755
|
+
body: JSON.stringify({ email }),
|
|
562
756
|
})
|
|
563
757
|
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
|
-
}
|
|
758
|
+
return { data: {}, error: await this._parseError(res) }
|
|
572
759
|
}
|
|
573
760
|
|
|
574
761
|
async updateUser(updates: {
|
|
@@ -579,7 +766,7 @@ export class AuthClient {
|
|
|
579
766
|
if (this.currentSession === null) {
|
|
580
767
|
return { data: { user: null }, error: { message: "Not authenticated" } }
|
|
581
768
|
}
|
|
582
|
-
const res = await
|
|
769
|
+
const res = await this.send(`${this.url}/user`, {
|
|
583
770
|
method: "PUT",
|
|
584
771
|
headers: {
|
|
585
772
|
...this.baseHeaders,
|
|
@@ -588,17 +775,25 @@ export class AuthClient {
|
|
|
588
775
|
body: JSON.stringify(updates),
|
|
589
776
|
})
|
|
590
777
|
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
|
-
}
|
|
778
|
+
return { data: { user: null }, error: await this._parseError(res) }
|
|
599
779
|
}
|
|
600
|
-
const
|
|
601
|
-
|
|
780
|
+
const user = await this._readUser(res)
|
|
781
|
+
this.applyUpdatedUser(user)
|
|
782
|
+
return { data: { user }, error: null }
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* Put the server's updated user on the session, persist it, and tell listeners.
|
|
787
|
+
*
|
|
788
|
+
* The tokens are unchanged, so this neither reschedules the refresh nor emits `TOKEN_REFRESHED`;
|
|
789
|
+
* without it the session kept the old email and metadata until the next refresh.
|
|
790
|
+
*/
|
|
791
|
+
private applyUpdatedUser(user: User): void {
|
|
792
|
+
if (this.currentSession === null) return
|
|
793
|
+
const session: Session = { ...this.currentSession, user }
|
|
794
|
+
this.currentSession = session
|
|
795
|
+
this.syncPersistedSession(session)
|
|
796
|
+
this._emitEvent("USER_UPDATED", session)
|
|
602
797
|
}
|
|
603
798
|
|
|
604
799
|
/**
|
|
@@ -625,12 +820,12 @@ export class AuthClient {
|
|
|
625
820
|
if (params.email !== undefined) body["email"] = params.email
|
|
626
821
|
if (params.phone !== undefined) body["phone"] = params.phone
|
|
627
822
|
}
|
|
628
|
-
const res = await
|
|
823
|
+
const res = await this.send(`${this.url}/verify`, {
|
|
629
824
|
method: "POST",
|
|
630
825
|
headers: this.baseHeaders,
|
|
631
826
|
body: JSON.stringify(body),
|
|
632
827
|
})
|
|
633
|
-
return this._parseAuthResponse(res)
|
|
828
|
+
return this.announceRecovery(await this._parseAuthResponse(res), params.type === "recovery")
|
|
634
829
|
}
|
|
635
830
|
|
|
636
831
|
/**
|
|
@@ -652,7 +847,7 @@ export class AuthClient {
|
|
|
652
847
|
if (credentials.nonce !== undefined) {
|
|
653
848
|
body["nonce"] = credentials.nonce
|
|
654
849
|
}
|
|
655
|
-
const res = await
|
|
850
|
+
const res = await this.send(`${this.url}/token?grant_type=id_token`, {
|
|
656
851
|
method: "POST",
|
|
657
852
|
headers: this.baseHeaders,
|
|
658
853
|
body: JSON.stringify(body),
|
|
@@ -671,13 +866,13 @@ export class AuthClient {
|
|
|
671
866
|
const body: Record<string, unknown> = { type: params.type }
|
|
672
867
|
if (params.email !== undefined) body["email"] = params.email
|
|
673
868
|
if (params.phone !== undefined) body["phone"] = params.phone
|
|
674
|
-
const res = await
|
|
869
|
+
const res = await this.send(`${this.url}/resend`, {
|
|
675
870
|
method: "POST",
|
|
676
871
|
headers: this.baseHeaders,
|
|
677
872
|
body: JSON.stringify(body),
|
|
678
873
|
})
|
|
679
874
|
if (res.ok) {
|
|
680
|
-
const json = await res
|
|
875
|
+
const json = await readJsonObject(res)
|
|
681
876
|
return {
|
|
682
877
|
data: {
|
|
683
878
|
...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
|
|
@@ -685,14 +880,7 @@ export class AuthClient {
|
|
|
685
880
|
error: null,
|
|
686
881
|
}
|
|
687
882
|
}
|
|
688
|
-
|
|
689
|
-
return {
|
|
690
|
-
data: {},
|
|
691
|
-
error: {
|
|
692
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
693
|
-
status: res.status,
|
|
694
|
-
},
|
|
695
|
-
}
|
|
883
|
+
return { data: {}, error: await this._parseError(res) }
|
|
696
884
|
}
|
|
697
885
|
|
|
698
886
|
// ─── MFA ──────────────────────────────────────────────────────────────────────
|
|
@@ -725,7 +913,7 @@ export class AuthClient {
|
|
|
725
913
|
if (params.friendlyName !== undefined) body["friendly_name"] = params.friendlyName
|
|
726
914
|
if (params.issuer !== undefined) body["issuer"] = params.issuer
|
|
727
915
|
if (params.phone !== undefined) body["phone"] = params.phone
|
|
728
|
-
const res = await
|
|
916
|
+
const res = await this.send(`${this.url}/factors`, {
|
|
729
917
|
method: "POST",
|
|
730
918
|
headers: {
|
|
731
919
|
...this.baseHeaders,
|
|
@@ -736,16 +924,17 @@ export class AuthClient {
|
|
|
736
924
|
if (!res.ok) {
|
|
737
925
|
return { data: null, error: await this._parseError(res) }
|
|
738
926
|
}
|
|
739
|
-
const json = await res
|
|
927
|
+
const json = await readJson(res, isJsonObject)
|
|
928
|
+
const totp = json["totp"]
|
|
740
929
|
const data: AuthMFAEnrollResponse = {
|
|
741
930
|
id: String(json["id"] ?? ""),
|
|
742
931
|
type: String(json["type"] ?? ""),
|
|
743
932
|
friendlyName: String(json["friendly_name"] ?? ""),
|
|
744
|
-
...(
|
|
933
|
+
...(isJsonObject(totp) && {
|
|
745
934
|
totp: {
|
|
746
|
-
qrCode: String(
|
|
747
|
-
secret: String(
|
|
748
|
-
uri: String(
|
|
935
|
+
qrCode: String(totp["qr_code"] ?? ""),
|
|
936
|
+
secret: String(totp["secret"] ?? ""),
|
|
937
|
+
uri: String(totp["uri"] ?? ""),
|
|
749
938
|
},
|
|
750
939
|
}),
|
|
751
940
|
...(json["phone"] !== undefined && { phone: String(json["phone"]) }),
|
|
@@ -769,7 +958,7 @@ export class AuthClient {
|
|
|
769
958
|
}
|
|
770
959
|
const body: Record<string, unknown> = {}
|
|
771
960
|
if (params.channel !== undefined) body["channel"] = params.channel
|
|
772
|
-
const res = await
|
|
961
|
+
const res = await this.send(
|
|
773
962
|
`${this.url}/factors/${params.factorId}/challenge`,
|
|
774
963
|
{
|
|
775
964
|
method: "POST",
|
|
@@ -783,7 +972,7 @@ export class AuthClient {
|
|
|
783
972
|
if (!res.ok) {
|
|
784
973
|
return { data: null, error: await this._parseError(res) }
|
|
785
974
|
}
|
|
786
|
-
const json = await res
|
|
975
|
+
const json = await readJson(res, isJsonObject)
|
|
787
976
|
return {
|
|
788
977
|
data: {
|
|
789
978
|
id: String(json["id"] ?? ""),
|
|
@@ -812,7 +1001,7 @@ export class AuthClient {
|
|
|
812
1001
|
error: { message: "Not authenticated" },
|
|
813
1002
|
}
|
|
814
1003
|
}
|
|
815
|
-
const res = await
|
|
1004
|
+
const res = await this.send(
|
|
816
1005
|
`${this.url}/factors/${params.factorId}/verify`,
|
|
817
1006
|
{
|
|
818
1007
|
method: "POST",
|
|
@@ -871,7 +1060,7 @@ export class AuthClient {
|
|
|
871
1060
|
if (this.currentSession === null) {
|
|
872
1061
|
return { data: null, error: { message: "Not authenticated" } }
|
|
873
1062
|
}
|
|
874
|
-
const res = await
|
|
1063
|
+
const res = await this.send(
|
|
875
1064
|
`${this.url}/factors/${params.factorId}`,
|
|
876
1065
|
{
|
|
877
1066
|
method: "DELETE",
|
|
@@ -884,7 +1073,7 @@ export class AuthClient {
|
|
|
884
1073
|
if (!res.ok) {
|
|
885
1074
|
return { data: null, error: await this._parseError(res) }
|
|
886
1075
|
}
|
|
887
|
-
const json = await res
|
|
1076
|
+
const json = await readJson(res, isJsonObject)
|
|
888
1077
|
return { data: { id: String(json["id"] ?? "") }, error: null }
|
|
889
1078
|
},
|
|
890
1079
|
|
|
@@ -931,26 +1120,18 @@ export class AuthClient {
|
|
|
931
1120
|
if (parts.length !== 3) {
|
|
932
1121
|
return { data: null, error: { message: "Invalid access token format" } }
|
|
933
1122
|
}
|
|
1123
|
+
const payload = decodeJwtPayload(parts[1]!)
|
|
1124
|
+
if (payload === null) {
|
|
1125
|
+
return { data: null, error: { message: "Failed to decode access token" } }
|
|
1126
|
+
}
|
|
1127
|
+
const { currentLevel, methods } = assuranceClaims(payload)
|
|
934
1128
|
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
1129
|
// Determine next level: if user has verified factors, next could be aal2
|
|
941
1130
|
const userResult = await this.getUser()
|
|
942
|
-
const factors = userResult.data
|
|
1131
|
+
const factors = userResult.data.user?.factors ?? []
|
|
943
1132
|
const hasVerifiedFactors = factors.some((f) => f.status === "verified")
|
|
944
1133
|
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
|
-
}
|
|
1134
|
+
return { data: { currentLevel, nextLevel, currentAuthenticationMethods: methods }, error: null }
|
|
954
1135
|
} catch {
|
|
955
1136
|
return { data: null, error: { message: "Failed to decode access token" } }
|
|
956
1137
|
}
|
|
@@ -993,63 +1174,68 @@ export class AuthClient {
|
|
|
993
1174
|
}
|
|
994
1175
|
}
|
|
995
1176
|
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
private async
|
|
1001
|
-
const verifier = generateCodeVerifier()
|
|
1002
|
-
this.codeVerifier = verifier
|
|
1177
|
+
/**
|
|
1178
|
+
* Keep a value for the OAuth redirect to find on the way back (a new page load, so not memory).
|
|
1179
|
+
* A write that fails is ignored: same-process flows still have the in-memory copy.
|
|
1180
|
+
*/
|
|
1181
|
+
private async writeFlowItem(suffix: string, value: string): Promise<void> {
|
|
1003
1182
|
if (!this.persistSession || this.storage === null) return
|
|
1004
1183
|
try {
|
|
1005
|
-
await this.storage.setItem(this.
|
|
1184
|
+
await this.storage.setItem(`${this.storageKey}${suffix}`, value)
|
|
1006
1185
|
} catch {
|
|
1007
|
-
// Ignore storage write failures
|
|
1186
|
+
// Ignore storage write failures.
|
|
1008
1187
|
}
|
|
1009
1188
|
}
|
|
1010
1189
|
|
|
1011
|
-
private async
|
|
1012
|
-
if (this.codeVerifier !== null) return this.codeVerifier
|
|
1190
|
+
private async readFlowItem(suffix: string): Promise<string | null> {
|
|
1013
1191
|
if (this.storage === null) return null
|
|
1014
1192
|
try {
|
|
1015
|
-
const stored = await this.storage.getItem(this.
|
|
1016
|
-
|
|
1017
|
-
this.codeVerifier = stored
|
|
1018
|
-
return stored
|
|
1019
|
-
}
|
|
1193
|
+
const stored = await this.storage.getItem(`${this.storageKey}${suffix}`)
|
|
1194
|
+
return stored !== null && stored !== "" ? stored : null
|
|
1020
1195
|
} catch {
|
|
1021
|
-
|
|
1196
|
+
return null
|
|
1022
1197
|
}
|
|
1023
|
-
return null
|
|
1024
1198
|
}
|
|
1025
1199
|
|
|
1026
|
-
private async
|
|
1027
|
-
this.codeVerifier = null
|
|
1200
|
+
private async removeFlowItem(suffix: string): Promise<void> {
|
|
1028
1201
|
if (this.storage === null) return
|
|
1029
1202
|
try {
|
|
1030
|
-
await this.storage.removeItem(this.
|
|
1203
|
+
await this.storage.removeItem(`${this.storageKey}${suffix}`)
|
|
1031
1204
|
} catch {
|
|
1032
1205
|
// Ignore
|
|
1033
1206
|
}
|
|
1034
1207
|
}
|
|
1035
1208
|
|
|
1209
|
+
/** Read a flow value once: the redirect it was kept for has now arrived. */
|
|
1210
|
+
private async takeFlowItem(suffix: string): Promise<string | null> {
|
|
1211
|
+
const value = await this.readFlowItem(suffix)
|
|
1212
|
+
if (value !== null) await this.removeFlowItem(suffix)
|
|
1213
|
+
return value
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
private async beginPkce(): Promise<void> {
|
|
1217
|
+
const verifier = generateCodeVerifier()
|
|
1218
|
+
this.codeVerifier = verifier
|
|
1219
|
+
await this.writeFlowItem(VERIFIER_SUFFIX, verifier)
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
private async readCodeVerifier(): Promise<string | null> {
|
|
1223
|
+
if (this.codeVerifier !== null) return this.codeVerifier
|
|
1224
|
+
this.codeVerifier = await this.readFlowItem(VERIFIER_SUFFIX)
|
|
1225
|
+
return this.codeVerifier
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
private async clearCodeVerifier(): Promise<void> {
|
|
1229
|
+
this.codeVerifier = null
|
|
1230
|
+
await this.removeFlowItem(VERIFIER_SUFFIX)
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1036
1233
|
/** Decode JWT `exp` claim without verifying the signature. */
|
|
1037
1234
|
private decodeJwtExp(accessToken: string): number | null {
|
|
1038
1235
|
const parts = accessToken.split(".")
|
|
1039
1236
|
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
|
-
}
|
|
1237
|
+
const exp = decodeJwtPayload(parts[1]!)?.["exp"]
|
|
1238
|
+
return typeof exp === "number" ? exp : null
|
|
1053
1239
|
}
|
|
1054
1240
|
|
|
1055
1241
|
private async readStorageItem(key: string): Promise<string | null> {
|
|
@@ -1103,70 +1289,27 @@ export class AuthClient {
|
|
|
1103
1289
|
|
|
1104
1290
|
private parsePersistedSession(raw: string): Session | null {
|
|
1105
1291
|
try {
|
|
1106
|
-
|
|
1107
|
-
return this.normalizePersistedSession(parsed)
|
|
1292
|
+
return this.normalizePersistedSession(JSON.parse(raw))
|
|
1108
1293
|
} catch {
|
|
1109
1294
|
return null
|
|
1110
1295
|
}
|
|
1111
1296
|
}
|
|
1112
1297
|
|
|
1298
|
+
/** A stored session, written by this client (camelCase) or by a server-side helper (snake_case). */
|
|
1113
1299
|
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 = {
|
|
1300
|
+
if (!isJsonObject(raw)) return null
|
|
1301
|
+
const accessToken = eitherKey(raw, "accessToken", "access_token", isString)
|
|
1302
|
+
const user = raw["user"]
|
|
1303
|
+
if (accessToken === undefined || !isJsonObject(user)) return null
|
|
1304
|
+
const expiresAt = eitherKey(raw, "expiresAt", "expires_at", isNumber)
|
|
1305
|
+
return {
|
|
1158
1306
|
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
|
-
: {}),
|
|
1307
|
+
refreshToken: eitherKey(raw, "refreshToken", "refresh_token", isString) ?? "",
|
|
1308
|
+
tokenType: eitherKey(raw, "tokenType", "token_type", isString) ?? "bearer",
|
|
1309
|
+
expiresIn: eitherKey(raw, "expiresIn", "expires_in", isNumber) ?? 3600,
|
|
1310
|
+
user: this._parseUser(snakeCaseUser(user)),
|
|
1311
|
+
...(expiresAt !== undefined && { expiresAt }),
|
|
1168
1312
|
}
|
|
1169
|
-
return session
|
|
1170
1313
|
}
|
|
1171
1314
|
|
|
1172
1315
|
private syncPersistedSession(session: Session | null): void {
|
|
@@ -1295,13 +1438,14 @@ export class AuthClient {
|
|
|
1295
1438
|
}
|
|
1296
1439
|
}
|
|
1297
1440
|
|
|
1441
|
+
/** Every refusal from the auth server goes through here, so none of them drops the code. */
|
|
1298
1442
|
private async _parseError(res: Response): Promise<SupatypeError> {
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1443
|
+
return authErrorFromBody(await readJsonObject(res), res.status)
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
/** The user a `/user` response describes. Throws on a body that is not a JSON object. */
|
|
1447
|
+
private async _readUser(res: Response): Promise<User> {
|
|
1448
|
+
return this._parseUser(await readJson(res, isJsonObject))
|
|
1305
1449
|
}
|
|
1306
1450
|
|
|
1307
1451
|
private async _parseAuthResponse(res: Response): Promise<{
|
|
@@ -1309,19 +1453,19 @@ export class AuthClient {
|
|
|
1309
1453
|
error: SupatypeError | null
|
|
1310
1454
|
}> {
|
|
1311
1455
|
if (!res.ok) {
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1456
|
+
return { data: { session: null, user: null }, error: await this._parseError(res) }
|
|
1457
|
+
}
|
|
1458
|
+
const json = await readJson(res, isJsonObject)
|
|
1459
|
+
const accessToken = json["access_token"]
|
|
1460
|
+
// A sign-up still waiting for its email confirmation is answered with the bare user and no
|
|
1461
|
+
// tokens. That is not a session, so nothing is stored and no SIGNED_IN is emitted.
|
|
1462
|
+
if (typeof accessToken !== "string" || accessToken === "") {
|
|
1463
|
+
const bareUser = json["user"]
|
|
1464
|
+
return { data: { session: null, user: this._parseUser(isJsonObject(bareUser) ? bareUser : json) }, error: null }
|
|
1320
1465
|
}
|
|
1321
|
-
const
|
|
1322
|
-
const user = this._parseUser((json["user"] ?? {}) as Record<string, unknown>)
|
|
1466
|
+
const user = this._parseUser(objectOrEmpty(json["user"]))
|
|
1323
1467
|
const session: Session = {
|
|
1324
|
-
accessToken
|
|
1468
|
+
accessToken,
|
|
1325
1469
|
tokenType: String(json["token_type"] ?? "bearer"),
|
|
1326
1470
|
expiresIn: Number(json["expires_in"] ?? 3600),
|
|
1327
1471
|
...(json["expires_at"] !== undefined && { expiresAt: Number(json["expires_at"]) }),
|
|
@@ -1339,34 +1483,43 @@ export class AuthClient {
|
|
|
1339
1483
|
...(raw["phone"] !== undefined && { phone: String(raw["phone"]) }),
|
|
1340
1484
|
...(raw["role"] !== undefined && { role: String(raw["role"]) }),
|
|
1341
1485
|
...(raw["is_anonymous"] !== undefined && { isAnonymous: Boolean(raw["is_anonymous"]) }),
|
|
1342
|
-
appMetadata: (raw["app_metadata"]
|
|
1343
|
-
userMetadata: (raw["user_metadata"]
|
|
1486
|
+
appMetadata: objectOrEmpty(raw["app_metadata"]),
|
|
1487
|
+
userMetadata: objectOrEmpty(raw["user_metadata"]),
|
|
1344
1488
|
createdAt: String(raw["created_at"] ?? ""),
|
|
1345
1489
|
updatedAt: String(raw["updated_at"] ?? ""),
|
|
1346
1490
|
}
|
|
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
|
-
}
|
|
1491
|
+
const identities = raw["identities"]
|
|
1492
|
+
if (Array.isArray(identities)) user.identities = identities.filter(isJsonObject).map(parseIdentity)
|
|
1493
|
+
const factors = raw["factors"]
|
|
1494
|
+
if (Array.isArray(factors)) user.factors = factors.filter(isJsonObject).map(parseFactor)
|
|
1370
1495
|
return user
|
|
1371
1496
|
}
|
|
1372
1497
|
}
|
|
1498
|
+
|
|
1499
|
+
function parseIdentity(i: Record<string, unknown>): UserIdentity {
|
|
1500
|
+
return {
|
|
1501
|
+
id: String(i["id"] ?? ""),
|
|
1502
|
+
userId: String(i["user_id"] ?? ""),
|
|
1503
|
+
identityData: objectOrEmpty(i["identity_data"]),
|
|
1504
|
+
identityId: String(i["identity_id"] ?? ""),
|
|
1505
|
+
provider: String(i["provider"] ?? ""),
|
|
1506
|
+
createdAt: String(i["created_at"] ?? ""),
|
|
1507
|
+
updatedAt: String(i["updated_at"] ?? ""),
|
|
1508
|
+
...(i["last_sign_in_at"] !== undefined && { lastSignInAt: String(i["last_sign_in_at"]) }),
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
/** A factor as the server lists it. A type or state it leaves out reads as `totp` / `unverified`. */
|
|
1513
|
+
function parseFactor(f: Record<string, unknown>): Factor {
|
|
1514
|
+
const factorType = f["factor_type"]
|
|
1515
|
+
const status = f["status"]
|
|
1516
|
+
return {
|
|
1517
|
+
id: String(f["id"] ?? ""),
|
|
1518
|
+
factorType: isFactorType(factorType) ? factorType : "totp",
|
|
1519
|
+
status: isFactorStatus(status) ? status : "unverified",
|
|
1520
|
+
createdAt: String(f["created_at"] ?? ""),
|
|
1521
|
+
updatedAt: String(f["updated_at"] ?? ""),
|
|
1522
|
+
...(f["friendly_name"] !== undefined && { friendlyName: String(f["friendly_name"]) }),
|
|
1523
|
+
...(f["phone"] !== undefined && { phone: String(f["phone"]) }),
|
|
1524
|
+
}
|
|
1525
|
+
}
|