@supatype/client 0.3.6 → 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/dist/auth.js
CHANGED
|
@@ -1,7 +1,71 @@
|
|
|
1
1
|
import { createCodeChallengeS256, generateCodeVerifier, PKCE_METHOD_S256, } from "./pkce.js";
|
|
2
|
+
import { plainFetch } from "./fetch-with-retry.js";
|
|
3
|
+
import { browserHref, carriesImplicitResult, cleanBrowserUrl, redirectParam, redirectParams, } from "./auth-redirect.js";
|
|
4
|
+
import { isJsonObject, isNumber, isOneOf, isShape, isString, objectOrEmpty, readJson, readJsonObject, } from "./json.js";
|
|
5
|
+
import { decodeJwtPayload } from "./jwt.js";
|
|
2
6
|
const DEFAULT_STORAGE_KEY = "supatype.auth.session";
|
|
3
7
|
const DEFAULT_COOKIE_PREFIX = "st";
|
|
8
|
+
/** Storage key suffixes for the state an OAuth redirect has to survive. */
|
|
9
|
+
const VERIFIER_SUFFIX = "-code-verifier";
|
|
10
|
+
const PROVIDER_SUFFIX = "-oauth-provider";
|
|
4
11
|
const DEBUG_AUTH = typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1";
|
|
12
|
+
/**
|
|
13
|
+
* The auth server's refusal as a `SupatypeError`, with its machine-readable code kept.
|
|
14
|
+
*
|
|
15
|
+
* Two body shapes arrive: `{ code, error_code, msg }` from the API, and the OAuth token endpoint's
|
|
16
|
+
* `{ error, error_description }`, where `error` is the code. The code is what an app branches on
|
|
17
|
+
* (`invalid_credentials`, `weak_password`, `email_not_confirmed`); the numeric `code` in the first
|
|
18
|
+
* shape is only the HTTP status again, so it is not used. Message precedence follows supabase-js.
|
|
19
|
+
*/
|
|
20
|
+
function authErrorFromBody(body, status) {
|
|
21
|
+
const text = (key) => {
|
|
22
|
+
const value = body[key];
|
|
23
|
+
return typeof value === "string" && value !== "" ? value : undefined;
|
|
24
|
+
};
|
|
25
|
+
const code = text("error_code") ?? text("error");
|
|
26
|
+
const message = text("msg") ?? text("message") ?? text("error_description") ?? text("error") ??
|
|
27
|
+
`Auth request failed (HTTP ${status})`;
|
|
28
|
+
return { message, status, ...(code !== undefined && { code }) };
|
|
29
|
+
}
|
|
30
|
+
/** The assurance levels the client reports; the server's unused `aal3` reads as unknown. */
|
|
31
|
+
const isAal = isOneOf(["aal1", "aal2"]);
|
|
32
|
+
/** One entry of the JWT's `amr` claim: how the session was authenticated, and when. */
|
|
33
|
+
const isAmrEntry = isShape({ method: isString });
|
|
34
|
+
/** The factor types and states supatype-auth defines (internal/auth/models/factor.go). */
|
|
35
|
+
const isFactorType = isOneOf(["totp", "phone", "webauthn"]);
|
|
36
|
+
const isFactorStatus = isOneOf(["verified", "unverified"]);
|
|
37
|
+
/** The assurance level and the authentication methods an access token's claims carry. */
|
|
38
|
+
function assuranceClaims(claims) {
|
|
39
|
+
const aal = claims["aal"];
|
|
40
|
+
const amr = claims["amr"];
|
|
41
|
+
return {
|
|
42
|
+
currentLevel: isAal(aal) ? aal : null,
|
|
43
|
+
methods: Array.isArray(amr) ? amr.filter(isAmrEntry).map((entry) => entry.method) : [],
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** The value under `first` when the guard accepts it, else the one under `second`, else undefined. */
|
|
47
|
+
function eitherKey(body, first, second, guard) {
|
|
48
|
+
const a = body[first];
|
|
49
|
+
if (guard(a))
|
|
50
|
+
return a;
|
|
51
|
+
const b = body[second];
|
|
52
|
+
return guard(b) ? b : undefined;
|
|
53
|
+
}
|
|
54
|
+
/** A stored user with its camelCase keys copied to the snake_case ones `_parseUser` reads. */
|
|
55
|
+
function snakeCaseUser(user) {
|
|
56
|
+
const aliases = [
|
|
57
|
+
["app_metadata", "appMetadata"],
|
|
58
|
+
["user_metadata", "userMetadata"],
|
|
59
|
+
["created_at", "createdAt"],
|
|
60
|
+
["updated_at", "updatedAt"],
|
|
61
|
+
];
|
|
62
|
+
const normalized = { ...user };
|
|
63
|
+
for (const [snake, camel] of aliases) {
|
|
64
|
+
if (user[snake] === undefined && user[camel] !== undefined)
|
|
65
|
+
normalized[snake] = user[camel];
|
|
66
|
+
}
|
|
67
|
+
return normalized;
|
|
68
|
+
}
|
|
5
69
|
export class AuthClient {
|
|
6
70
|
url;
|
|
7
71
|
baseHeaders;
|
|
@@ -12,10 +76,14 @@ export class AuthClient {
|
|
|
12
76
|
storageKey;
|
|
13
77
|
cookieName;
|
|
14
78
|
storage;
|
|
79
|
+
/** The client's fetch, with its timeout; only reads are retried. */
|
|
80
|
+
send;
|
|
15
81
|
/** When true, session is also mirrored to document.cookie (browser default path only). */
|
|
16
82
|
useCookies;
|
|
17
|
-
/** Resolves when async storage hydration
|
|
83
|
+
/** Resolves when async storage hydration and any sign-in carried by the page's URL complete. */
|
|
18
84
|
ready;
|
|
85
|
+
/** What `ready` settles with: the refusal the page's URL reported, if any. */
|
|
86
|
+
initialized;
|
|
19
87
|
/** Pending auto-refresh timer; refreshes the access token shortly before it expires. */
|
|
20
88
|
refreshTimer = null;
|
|
21
89
|
/** Dedupes concurrent refresh attempts (getSession + auto-refresh). */
|
|
@@ -31,47 +99,89 @@ export class AuthClient {
|
|
|
31
99
|
this.cookieName = `${cookiePrefix}-auth-token`;
|
|
32
100
|
this.useCookies = opts.storage === undefined;
|
|
33
101
|
this.storage = opts.storage ?? this.getBrowserStorage();
|
|
102
|
+
this.send = opts.transport ?? plainFetch;
|
|
103
|
+
const hydrated = this.loadInitialSession(opts);
|
|
104
|
+
this.initialized = opts.detectSessionInUrl === false
|
|
105
|
+
? hydrated.then(() => ({ error: null }))
|
|
106
|
+
: hydrated.then(() => this.completeRedirect());
|
|
107
|
+
this.ready = this.initialized.then(() => undefined);
|
|
108
|
+
// Keep the access token fresh while the app is open (and refresh immediately
|
|
109
|
+
// if a persisted session loaded already expired).
|
|
110
|
+
this.scheduleAutoRefresh();
|
|
111
|
+
if (this.currentSession !== null && this.isAccessTokenExpired(this.currentSession)) {
|
|
112
|
+
void this.ensureValidSession();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** The session the client starts with: the one passed in, else the persisted one. */
|
|
116
|
+
loadInitialSession(opts) {
|
|
34
117
|
if (opts.initialSession !== undefined) {
|
|
35
118
|
this.currentSession = opts.initialSession;
|
|
36
|
-
this.ready = Promise.resolve();
|
|
37
119
|
if (DEBUG_AUTH) {
|
|
38
120
|
console.debug("[supatype:auth] constructor initialSession provided", {
|
|
39
121
|
hasSession: true,
|
|
40
122
|
userId: opts.initialSession.user.id,
|
|
41
123
|
});
|
|
42
124
|
}
|
|
125
|
+
return Promise.resolve();
|
|
43
126
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
cookieName: this.cookieName,
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
else {
|
|
62
|
-
this.ready = Promise.resolve();
|
|
63
|
-
}
|
|
64
|
-
// Keep the access token fresh while the app is open (and refresh immediately
|
|
65
|
-
// if a persisted session loaded already expired).
|
|
66
|
-
this.scheduleAutoRefresh();
|
|
67
|
-
if (this.currentSession !== null && this.isAccessTokenExpired(this.currentSession)) {
|
|
68
|
-
void this.ensureValidSession();
|
|
127
|
+
if (!this.persistSession)
|
|
128
|
+
return Promise.resolve();
|
|
129
|
+
if (opts.storage !== undefined)
|
|
130
|
+
return this.hydrateFromStorage();
|
|
131
|
+
this.currentSession = this.loadPersistedSession();
|
|
132
|
+
if (DEBUG_AUTH) {
|
|
133
|
+
console.debug("[supatype:auth] constructor loaded persisted session", {
|
|
134
|
+
hasSession: this.currentSession !== null,
|
|
135
|
+
userId: this.currentSession?.user.id ?? null,
|
|
136
|
+
storageKey: this.storageKey,
|
|
137
|
+
cookieName: this.cookieName,
|
|
138
|
+
});
|
|
69
139
|
}
|
|
140
|
+
return Promise.resolve();
|
|
70
141
|
}
|
|
71
|
-
/** Resolves when
|
|
142
|
+
/** Resolves when the client has its starting session (storage hydrated, any URL sign-in done). */
|
|
72
143
|
whenReady() {
|
|
73
144
|
return this.ready;
|
|
74
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* Wait for the client's start, and learn whether a sign-in in the page's URL was refused.
|
|
148
|
+
*
|
|
149
|
+
* The same shape as supabase-js's `initialize()`. A refused OAuth sign-in comes back as
|
|
150
|
+
* `?error=...&error_description=...`; this is where an app (or `useAuth`) reads it.
|
|
151
|
+
*/
|
|
152
|
+
initialize() {
|
|
153
|
+
return this.initialized;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Finish the sign-in the page's URL carries, as supabase-js's `detectSessionInUrl` does.
|
|
157
|
+
*
|
|
158
|
+
* Whatever session was stored is set aside first, so a new sign-in is announced as `SIGNED_IN`
|
|
159
|
+
* and a refused one leaves the browser signed out, as supabase-js does after a failed attempt.
|
|
160
|
+
*/
|
|
161
|
+
async completeRedirect() {
|
|
162
|
+
const href = browserHref();
|
|
163
|
+
if (href === null || !(await this.isAuthRedirect(href)))
|
|
164
|
+
return { error: null };
|
|
165
|
+
const provider = await this.takeFlowItem(PROVIDER_SUFFIX);
|
|
166
|
+
this.currentSession = null;
|
|
167
|
+
const { error } = await this.getSessionFromUrl(href).catch((err) => ({
|
|
168
|
+
error: { message: err instanceof Error ? err.message : "Could not finish the sign-in" },
|
|
169
|
+
}));
|
|
170
|
+
cleanBrowserUrl(href);
|
|
171
|
+
if (error === null)
|
|
172
|
+
return { error: null };
|
|
173
|
+
this._setSession(null);
|
|
174
|
+
return { error: { ...error, ...(provider !== null && { provider }) } };
|
|
175
|
+
}
|
|
176
|
+
/** A URL with tokens or a refusal, or with a `code` for a PKCE flow this client started. */
|
|
177
|
+
async isAuthRedirect(href) {
|
|
178
|
+
const params = redirectParams(href);
|
|
179
|
+
if (params === null)
|
|
180
|
+
return false;
|
|
181
|
+
if (carriesImplicitResult(params))
|
|
182
|
+
return true;
|
|
183
|
+
return redirectParam(params, "code") !== null && (await this.readCodeVerifier()) !== null;
|
|
184
|
+
}
|
|
75
185
|
async hydrateFromStorage() {
|
|
76
186
|
try {
|
|
77
187
|
const session = await this.loadPersistedSessionAsync();
|
|
@@ -107,14 +217,8 @@ export class AuthClient {
|
|
|
107
217
|
const parts = accessToken.split(".");
|
|
108
218
|
if (parts.length !== 3)
|
|
109
219
|
return null;
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
const exp = payload["exp"];
|
|
113
|
-
return typeof exp === "number" ? exp * 1000 : null;
|
|
114
|
-
}
|
|
115
|
-
catch {
|
|
116
|
-
return null;
|
|
117
|
-
}
|
|
220
|
+
const exp = decodeJwtPayload(parts[1])?.["exp"];
|
|
221
|
+
return typeof exp === "number" ? exp * 1000 : null;
|
|
118
222
|
}
|
|
119
223
|
isAccessTokenExpired(session, skewMs = 0) {
|
|
120
224
|
const expiresAtMs = this.sessionExpiresAtMs(session);
|
|
@@ -165,11 +269,14 @@ export class AuthClient {
|
|
|
165
269
|
const delay = expiryMs === null
|
|
166
270
|
? Math.max(0, (session.expiresIn || 3600) * 1000 - 60_000)
|
|
167
271
|
: Math.max(0, expiryMs - Date.now() - 60_000);
|
|
168
|
-
|
|
272
|
+
const timer = setTimeout(() => {
|
|
169
273
|
this.refreshTimer = null;
|
|
170
274
|
void this.ensureValidSession();
|
|
171
275
|
}, delay);
|
|
172
|
-
this.refreshTimer
|
|
276
|
+
this.refreshTimer = timer;
|
|
277
|
+
// Avoid keeping a Node process alive for this timer. A browser's timer is a number: nothing to do.
|
|
278
|
+
if (typeof timer === "object" && "unref" in timer)
|
|
279
|
+
timer.unref();
|
|
173
280
|
}
|
|
174
281
|
async signUp(credentials) {
|
|
175
282
|
const body = {
|
|
@@ -179,7 +286,7 @@ export class AuthClient {
|
|
|
179
286
|
if (credentials.options?.data !== undefined) {
|
|
180
287
|
body["data"] = credentials.options.data;
|
|
181
288
|
}
|
|
182
|
-
const res = await
|
|
289
|
+
const res = await this.send(`${this.url}/signup`, {
|
|
183
290
|
method: "POST",
|
|
184
291
|
headers: this.baseHeaders,
|
|
185
292
|
body: JSON.stringify(body),
|
|
@@ -187,7 +294,7 @@ export class AuthClient {
|
|
|
187
294
|
return this._parseAuthResponse(res);
|
|
188
295
|
}
|
|
189
296
|
async signInWithPassword(credentials) {
|
|
190
|
-
const res = await
|
|
297
|
+
const res = await this.send(`${this.url}/token?grant_type=password`, {
|
|
191
298
|
method: "POST",
|
|
192
299
|
headers: this.baseHeaders,
|
|
193
300
|
body: JSON.stringify({
|
|
@@ -205,19 +312,38 @@ export class AuthClient {
|
|
|
205
312
|
if (credentials?.options?.captchaToken !== undefined) {
|
|
206
313
|
body["supatype_meta_security"] = { captcha_token: credentials.options.captchaToken };
|
|
207
314
|
}
|
|
208
|
-
const res = await
|
|
315
|
+
const res = await this.send(`${this.url}/signup`, {
|
|
209
316
|
method: "POST",
|
|
210
317
|
headers: this.baseHeaders,
|
|
211
318
|
body: JSON.stringify(body),
|
|
212
319
|
});
|
|
213
320
|
return this._parseAuthResponse(res);
|
|
214
321
|
}
|
|
322
|
+
/**
|
|
323
|
+
* An auth endpoint, carrying the caller's redirect as `redirect_to` in the query string. The
|
|
324
|
+
* server reads it from there (or a header) and never from a JSON body, so a redirect sent in the
|
|
325
|
+
* body is dropped in silence and the email links to SITE_URL instead.
|
|
326
|
+
*/
|
|
327
|
+
endpoint(path, redirectTo) {
|
|
328
|
+
const url = new URL(`${this.url}${path}`);
|
|
329
|
+
if (redirectTo !== undefined)
|
|
330
|
+
url.searchParams.set("redirect_to", redirectTo);
|
|
331
|
+
return url;
|
|
332
|
+
}
|
|
215
333
|
async signInWithOAuth(opts) {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
if (opts.
|
|
219
|
-
|
|
334
|
+
// The server answers /authorize for a disabled provider with a bare JSON 400, which a browser
|
|
335
|
+
// navigating there shows as raw text; asking first lets the caller show a message instead.
|
|
336
|
+
if (await this.providerDisabled(opts.provider)) {
|
|
337
|
+
const message = `Sign-in with ${opts.provider} is not enabled for this project.`;
|
|
338
|
+
return { data: { url: "", provider: opts.provider }, error: { message, status: 400, code: "provider_disabled" } };
|
|
339
|
+
}
|
|
340
|
+
await this.writeFlowItem(PROVIDER_SUFFIX, opts.provider);
|
|
341
|
+
const url = this.endpoint("/authorize", opts.options?.redirectTo);
|
|
342
|
+
for (const [key, value] of Object.entries(opts.options?.queryParams ?? {})) {
|
|
343
|
+
if (!url.searchParams.has(key))
|
|
344
|
+
url.searchParams.set(key, value);
|
|
220
345
|
}
|
|
346
|
+
url.searchParams.set("provider", opts.provider);
|
|
221
347
|
if (opts.options?.scopes !== undefined) {
|
|
222
348
|
url.searchParams.set("scopes", opts.options.scopes);
|
|
223
349
|
}
|
|
@@ -229,12 +355,29 @@ export class AuthClient {
|
|
|
229
355
|
}
|
|
230
356
|
return { data: { url: url.toString(), provider: opts.provider }, error: null };
|
|
231
357
|
}
|
|
358
|
+
/**
|
|
359
|
+
* True only when the server's `/settings` list the provider as off. A provider they do not list
|
|
360
|
+
* (a `custom:` one) or settings that cannot be read leave the decision to `/authorize`. Looked up
|
|
361
|
+
* in lower case, as `/authorize` resolves it, so `GitHub` is refused exactly when `github` is.
|
|
362
|
+
*/
|
|
363
|
+
async providerDisabled(provider) {
|
|
364
|
+
try {
|
|
365
|
+
const res = await this.send(`${this.url}/settings`, { headers: this.baseHeaders });
|
|
366
|
+
if (!res.ok)
|
|
367
|
+
return false;
|
|
368
|
+
const external = objectOrEmpty((await readJsonObject(res))["external"]);
|
|
369
|
+
return external[provider.toLowerCase()] === false;
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
return false;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
232
375
|
/**
|
|
233
376
|
* Apply tokens from an OAuth / deep-link redirect (implicit grant) or restore a session.
|
|
234
377
|
* Fetches `/user` to hydrate the user object, then persists via the configured storage.
|
|
235
378
|
*/
|
|
236
379
|
async setSession(params) {
|
|
237
|
-
const res = await
|
|
380
|
+
const res = await this.send(`${this.url}/user`, {
|
|
238
381
|
headers: {
|
|
239
382
|
...this.baseHeaders,
|
|
240
383
|
Authorization: `Bearer ${params.accessToken}`,
|
|
@@ -246,8 +389,7 @@ export class AuthClient {
|
|
|
246
389
|
error: await this._parseError(res),
|
|
247
390
|
};
|
|
248
391
|
}
|
|
249
|
-
const
|
|
250
|
-
const user = this._parseUser(raw);
|
|
392
|
+
const user = await this._readUser(res);
|
|
251
393
|
const session = {
|
|
252
394
|
accessToken: params.accessToken,
|
|
253
395
|
refreshToken: params.refreshToken,
|
|
@@ -279,7 +421,7 @@ export class AuthClient {
|
|
|
279
421
|
},
|
|
280
422
|
};
|
|
281
423
|
}
|
|
282
|
-
const res = await
|
|
424
|
+
const res = await this.send(`${this.url}/token?grant_type=pkce`, {
|
|
283
425
|
method: "POST",
|
|
284
426
|
headers: this.baseHeaders,
|
|
285
427
|
body: JSON.stringify({
|
|
@@ -295,28 +437,26 @@ export class AuthClient {
|
|
|
295
437
|
* Supports PKCE (`?code=`) and implicit (`#access_token=` / query tokens).
|
|
296
438
|
*/
|
|
297
439
|
async getSessionFromUrl(url) {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
parsed = new URL(url);
|
|
301
|
-
}
|
|
302
|
-
catch {
|
|
440
|
+
const params = redirectParams(url);
|
|
441
|
+
if (params === null) {
|
|
303
442
|
return {
|
|
304
443
|
data: { session: null, user: null },
|
|
305
444
|
error: { message: `Invalid redirect URL: ${url}`, status: 400 },
|
|
306
445
|
};
|
|
307
446
|
}
|
|
308
|
-
const query =
|
|
309
|
-
|
|
310
|
-
const
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
hashParams.get("error");
|
|
314
|
-
if (errorDescription !== null && errorDescription !== "") {
|
|
315
|
-
return {
|
|
316
|
-
data: { session: null, user: null },
|
|
317
|
-
error: { message: errorDescription, status: 400 },
|
|
318
|
-
};
|
|
447
|
+
const { query, fragment: hashParams } = params;
|
|
448
|
+
// A refused link comes back with the same fields as a refused request, in the URL instead.
|
|
449
|
+
const redirectError = { ...Object.fromEntries(hashParams), ...Object.fromEntries(query) };
|
|
450
|
+
if (redirectError["error_description"] || redirectError["error"]) {
|
|
451
|
+
return { data: { session: null, user: null }, error: authErrorFromBody(redirectError, 400) };
|
|
319
452
|
}
|
|
453
|
+
// The auth server marks the link it sent with `type`; a recovery link signs the user in so they
|
|
454
|
+
// can choose a new password, and the app needs to know that is why they arrived.
|
|
455
|
+
const recovery = (hashParams.get("type") ?? query.get("type")) === "recovery";
|
|
456
|
+
return this.announceRecovery(await this.sessionFromRedirect(query, hashParams), recovery);
|
|
457
|
+
}
|
|
458
|
+
/** The session a redirect carries: a PKCE code to exchange, or implicit-grant tokens. */
|
|
459
|
+
async sessionFromRedirect(query, hashParams) {
|
|
320
460
|
const code = query.get("code") ?? hashParams.get("code");
|
|
321
461
|
if (code !== null && code !== "") {
|
|
322
462
|
return this.exchangeCodeForSession(code);
|
|
@@ -334,6 +474,18 @@ export class AuthClient {
|
|
|
334
474
|
},
|
|
335
475
|
};
|
|
336
476
|
}
|
|
477
|
+
/**
|
|
478
|
+
* Emit `PASSWORD_RECOVERY` once a recovery link or code has produced a session.
|
|
479
|
+
*
|
|
480
|
+
* After the `SIGNED_IN` that establishing the session already emitted, as `MFA_CHALLENGE_VERIFIED`
|
|
481
|
+
* follows it, so a listener keyed on sign-in still sees one and a reset page can key on this.
|
|
482
|
+
*/
|
|
483
|
+
announceRecovery(result, recovery) {
|
|
484
|
+
if (recovery && result.error === null && result.data.session !== null) {
|
|
485
|
+
this._emitEvent("PASSWORD_RECOVERY", result.data.session);
|
|
486
|
+
}
|
|
487
|
+
return result;
|
|
488
|
+
}
|
|
337
489
|
async signInWithOtp(opts) {
|
|
338
490
|
const body = {
|
|
339
491
|
create_user: opts.options?.createUser ?? true,
|
|
@@ -347,13 +499,13 @@ export class AuthClient {
|
|
|
347
499
|
body["channel"] = opts.options.channel;
|
|
348
500
|
}
|
|
349
501
|
}
|
|
350
|
-
const res = await
|
|
502
|
+
const res = await this.send(this.endpoint("/otp", opts.options?.emailRedirectTo).toString(), {
|
|
351
503
|
method: "POST",
|
|
352
504
|
headers: this.baseHeaders,
|
|
353
505
|
body: JSON.stringify(body),
|
|
354
506
|
});
|
|
355
507
|
if (res.ok) {
|
|
356
|
-
const json = await res
|
|
508
|
+
const json = await readJsonObject(res);
|
|
357
509
|
return {
|
|
358
510
|
data: {
|
|
359
511
|
...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
|
|
@@ -361,18 +513,11 @@ export class AuthClient {
|
|
|
361
513
|
error: null,
|
|
362
514
|
};
|
|
363
515
|
}
|
|
364
|
-
|
|
365
|
-
return {
|
|
366
|
-
data: {},
|
|
367
|
-
error: {
|
|
368
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
369
|
-
status: res.status,
|
|
370
|
-
},
|
|
371
|
-
};
|
|
516
|
+
return { data: {}, error: await this._parseError(res) };
|
|
372
517
|
}
|
|
373
518
|
async signOut() {
|
|
374
519
|
if (this.currentSession !== null) {
|
|
375
|
-
await
|
|
520
|
+
await this.send(`${this.url}/logout`, {
|
|
376
521
|
method: "POST",
|
|
377
522
|
headers: {
|
|
378
523
|
...this.baseHeaders,
|
|
@@ -392,20 +537,16 @@ export class AuthClient {
|
|
|
392
537
|
if (this.currentSession === null) {
|
|
393
538
|
return { data: { user: null }, error: null };
|
|
394
539
|
}
|
|
395
|
-
const res = await
|
|
540
|
+
const res = await this.send(`${this.url}/user`, {
|
|
396
541
|
headers: {
|
|
397
542
|
...this.baseHeaders,
|
|
398
543
|
Authorization: `Bearer ${this.currentSession.accessToken}`,
|
|
399
544
|
},
|
|
400
545
|
});
|
|
401
546
|
if (!res.ok) {
|
|
402
|
-
return {
|
|
403
|
-
data: { user: null },
|
|
404
|
-
error: { message: "Could not get user", status: res.status },
|
|
405
|
-
};
|
|
547
|
+
return { data: { user: null }, error: await this._parseError(res) };
|
|
406
548
|
}
|
|
407
|
-
|
|
408
|
-
return { data: { user: this._parseUser(raw) }, error: null };
|
|
549
|
+
return { data: { user: await this._readUser(res) }, error: null };
|
|
409
550
|
}
|
|
410
551
|
async refreshSession() {
|
|
411
552
|
if (this.currentSession === null) {
|
|
@@ -416,7 +557,7 @@ export class AuthClient {
|
|
|
416
557
|
return { data: { session: null }, error: { message: "No refresh token" } };
|
|
417
558
|
}
|
|
418
559
|
try {
|
|
419
|
-
const res = await
|
|
560
|
+
const res = await this.send(`${this.url}/token?grant_type=refresh_token`, {
|
|
420
561
|
method: "POST",
|
|
421
562
|
headers: this.baseHeaders,
|
|
422
563
|
body: JSON.stringify({ refresh_token: this.currentSession.refreshToken }),
|
|
@@ -435,31 +576,20 @@ export class AuthClient {
|
|
|
435
576
|
}
|
|
436
577
|
}
|
|
437
578
|
async resetPasswordForEmail(email, options) {
|
|
438
|
-
const
|
|
439
|
-
if (options?.redirectTo !== undefined) {
|
|
440
|
-
body["redirect_to"] = options.redirectTo;
|
|
441
|
-
}
|
|
442
|
-
const res = await fetch(`${this.url}/recover`, {
|
|
579
|
+
const res = await this.send(this.endpoint("/recover", options?.redirectTo).toString(), {
|
|
443
580
|
method: "POST",
|
|
444
581
|
headers: this.baseHeaders,
|
|
445
|
-
body: JSON.stringify(
|
|
582
|
+
body: JSON.stringify({ email }),
|
|
446
583
|
});
|
|
447
584
|
if (res.ok)
|
|
448
585
|
return { data: {}, error: null };
|
|
449
|
-
|
|
450
|
-
return {
|
|
451
|
-
data: {},
|
|
452
|
-
error: {
|
|
453
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
454
|
-
status: res.status,
|
|
455
|
-
},
|
|
456
|
-
};
|
|
586
|
+
return { data: {}, error: await this._parseError(res) };
|
|
457
587
|
}
|
|
458
588
|
async updateUser(updates) {
|
|
459
589
|
if (this.currentSession === null) {
|
|
460
590
|
return { data: { user: null }, error: { message: "Not authenticated" } };
|
|
461
591
|
}
|
|
462
|
-
const res = await
|
|
592
|
+
const res = await this.send(`${this.url}/user`, {
|
|
463
593
|
method: "PUT",
|
|
464
594
|
headers: {
|
|
465
595
|
...this.baseHeaders,
|
|
@@ -468,17 +598,25 @@ export class AuthClient {
|
|
|
468
598
|
body: JSON.stringify(updates),
|
|
469
599
|
});
|
|
470
600
|
if (!res.ok) {
|
|
471
|
-
|
|
472
|
-
return {
|
|
473
|
-
data: { user: null },
|
|
474
|
-
error: {
|
|
475
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
476
|
-
status: res.status,
|
|
477
|
-
},
|
|
478
|
-
};
|
|
601
|
+
return { data: { user: null }, error: await this._parseError(res) };
|
|
479
602
|
}
|
|
480
|
-
const
|
|
481
|
-
|
|
603
|
+
const user = await this._readUser(res);
|
|
604
|
+
this.applyUpdatedUser(user);
|
|
605
|
+
return { data: { user }, error: null };
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Put the server's updated user on the session, persist it, and tell listeners.
|
|
609
|
+
*
|
|
610
|
+
* The tokens are unchanged, so this neither reschedules the refresh nor emits `TOKEN_REFRESHED`;
|
|
611
|
+
* without it the session kept the old email and metadata until the next refresh.
|
|
612
|
+
*/
|
|
613
|
+
applyUpdatedUser(user) {
|
|
614
|
+
if (this.currentSession === null)
|
|
615
|
+
return;
|
|
616
|
+
const session = { ...this.currentSession, user };
|
|
617
|
+
this.currentSession = session;
|
|
618
|
+
this.syncPersistedSession(session);
|
|
619
|
+
this._emitEvent("USER_UPDATED", session);
|
|
482
620
|
}
|
|
483
621
|
/**
|
|
484
622
|
* Verify an OTP token received via email or phone.
|
|
@@ -498,12 +636,12 @@ export class AuthClient {
|
|
|
498
636
|
if (params.phone !== undefined)
|
|
499
637
|
body["phone"] = params.phone;
|
|
500
638
|
}
|
|
501
|
-
const res = await
|
|
639
|
+
const res = await this.send(`${this.url}/verify`, {
|
|
502
640
|
method: "POST",
|
|
503
641
|
headers: this.baseHeaders,
|
|
504
642
|
body: JSON.stringify(body),
|
|
505
643
|
});
|
|
506
|
-
return this._parseAuthResponse(res);
|
|
644
|
+
return this.announceRecovery(await this._parseAuthResponse(res), params.type === "recovery");
|
|
507
645
|
}
|
|
508
646
|
/**
|
|
509
647
|
* Sign in with an ID token from an external provider (e.g. Google One Tap).
|
|
@@ -517,7 +655,7 @@ export class AuthClient {
|
|
|
517
655
|
if (credentials.nonce !== undefined) {
|
|
518
656
|
body["nonce"] = credentials.nonce;
|
|
519
657
|
}
|
|
520
|
-
const res = await
|
|
658
|
+
const res = await this.send(`${this.url}/token?grant_type=id_token`, {
|
|
521
659
|
method: "POST",
|
|
522
660
|
headers: this.baseHeaders,
|
|
523
661
|
body: JSON.stringify(body),
|
|
@@ -533,13 +671,13 @@ export class AuthClient {
|
|
|
533
671
|
body["email"] = params.email;
|
|
534
672
|
if (params.phone !== undefined)
|
|
535
673
|
body["phone"] = params.phone;
|
|
536
|
-
const res = await
|
|
674
|
+
const res = await this.send(`${this.url}/resend`, {
|
|
537
675
|
method: "POST",
|
|
538
676
|
headers: this.baseHeaders,
|
|
539
677
|
body: JSON.stringify(body),
|
|
540
678
|
});
|
|
541
679
|
if (res.ok) {
|
|
542
|
-
const json = await res
|
|
680
|
+
const json = await readJsonObject(res);
|
|
543
681
|
return {
|
|
544
682
|
data: {
|
|
545
683
|
...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
|
|
@@ -547,14 +685,7 @@ export class AuthClient {
|
|
|
547
685
|
error: null,
|
|
548
686
|
};
|
|
549
687
|
}
|
|
550
|
-
|
|
551
|
-
return {
|
|
552
|
-
data: {},
|
|
553
|
-
error: {
|
|
554
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
555
|
-
status: res.status,
|
|
556
|
-
},
|
|
557
|
-
};
|
|
688
|
+
return { data: {}, error: await this._parseError(res) };
|
|
558
689
|
}
|
|
559
690
|
// ─── MFA ──────────────────────────────────────────────────────────────────────
|
|
560
691
|
/**
|
|
@@ -580,7 +711,7 @@ export class AuthClient {
|
|
|
580
711
|
body["issuer"] = params.issuer;
|
|
581
712
|
if (params.phone !== undefined)
|
|
582
713
|
body["phone"] = params.phone;
|
|
583
|
-
const res = await
|
|
714
|
+
const res = await this.send(`${this.url}/factors`, {
|
|
584
715
|
method: "POST",
|
|
585
716
|
headers: {
|
|
586
717
|
...this.baseHeaders,
|
|
@@ -591,16 +722,17 @@ export class AuthClient {
|
|
|
591
722
|
if (!res.ok) {
|
|
592
723
|
return { data: null, error: await this._parseError(res) };
|
|
593
724
|
}
|
|
594
|
-
const json = await res
|
|
725
|
+
const json = await readJson(res, isJsonObject);
|
|
726
|
+
const totp = json["totp"];
|
|
595
727
|
const data = {
|
|
596
728
|
id: String(json["id"] ?? ""),
|
|
597
729
|
type: String(json["type"] ?? ""),
|
|
598
730
|
friendlyName: String(json["friendly_name"] ?? ""),
|
|
599
|
-
...(
|
|
731
|
+
...(isJsonObject(totp) && {
|
|
600
732
|
totp: {
|
|
601
|
-
qrCode: String(
|
|
602
|
-
secret: String(
|
|
603
|
-
uri: String(
|
|
733
|
+
qrCode: String(totp["qr_code"] ?? ""),
|
|
734
|
+
secret: String(totp["secret"] ?? ""),
|
|
735
|
+
uri: String(totp["uri"] ?? ""),
|
|
604
736
|
},
|
|
605
737
|
}),
|
|
606
738
|
...(json["phone"] !== undefined && { phone: String(json["phone"]) }),
|
|
@@ -618,7 +750,7 @@ export class AuthClient {
|
|
|
618
750
|
const body = {};
|
|
619
751
|
if (params.channel !== undefined)
|
|
620
752
|
body["channel"] = params.channel;
|
|
621
|
-
const res = await
|
|
753
|
+
const res = await this.send(`${this.url}/factors/${params.factorId}/challenge`, {
|
|
622
754
|
method: "POST",
|
|
623
755
|
headers: {
|
|
624
756
|
...this.baseHeaders,
|
|
@@ -629,7 +761,7 @@ export class AuthClient {
|
|
|
629
761
|
if (!res.ok) {
|
|
630
762
|
return { data: null, error: await this._parseError(res) };
|
|
631
763
|
}
|
|
632
|
-
const json = await res
|
|
764
|
+
const json = await readJson(res, isJsonObject);
|
|
633
765
|
return {
|
|
634
766
|
data: {
|
|
635
767
|
id: String(json["id"] ?? ""),
|
|
@@ -650,7 +782,7 @@ export class AuthClient {
|
|
|
650
782
|
error: { message: "Not authenticated" },
|
|
651
783
|
};
|
|
652
784
|
}
|
|
653
|
-
const res = await
|
|
785
|
+
const res = await this.send(`${this.url}/factors/${params.factorId}/verify`, {
|
|
654
786
|
method: "POST",
|
|
655
787
|
headers: {
|
|
656
788
|
...this.baseHeaders,
|
|
@@ -693,7 +825,7 @@ export class AuthClient {
|
|
|
693
825
|
if (this.currentSession === null) {
|
|
694
826
|
return { data: null, error: { message: "Not authenticated" } };
|
|
695
827
|
}
|
|
696
|
-
const res = await
|
|
828
|
+
const res = await this.send(`${this.url}/factors/${params.factorId}`, {
|
|
697
829
|
method: "DELETE",
|
|
698
830
|
headers: {
|
|
699
831
|
...this.baseHeaders,
|
|
@@ -703,7 +835,7 @@ export class AuthClient {
|
|
|
703
835
|
if (!res.ok) {
|
|
704
836
|
return { data: null, error: await this._parseError(res) };
|
|
705
837
|
}
|
|
706
|
-
const json = await res
|
|
838
|
+
const json = await readJson(res, isJsonObject);
|
|
707
839
|
return { data: { id: String(json["id"] ?? "") }, error: null };
|
|
708
840
|
},
|
|
709
841
|
/**
|
|
@@ -738,24 +870,18 @@ export class AuthClient {
|
|
|
738
870
|
if (parts.length !== 3) {
|
|
739
871
|
return { data: null, error: { message: "Invalid access token format" } };
|
|
740
872
|
}
|
|
873
|
+
const payload = decodeJwtPayload(parts[1]);
|
|
874
|
+
if (payload === null) {
|
|
875
|
+
return { data: null, error: { message: "Failed to decode access token" } };
|
|
876
|
+
}
|
|
877
|
+
const { currentLevel, methods } = assuranceClaims(payload);
|
|
741
878
|
try {
|
|
742
|
-
const payload = JSON.parse(atob(parts[1]));
|
|
743
|
-
const currentLevel = payload["aal"] ?? null;
|
|
744
|
-
const amr = payload["amr"] ?? [];
|
|
745
|
-
const methods = amr.map((entry) => entry.method);
|
|
746
879
|
// Determine next level: if user has verified factors, next could be aal2
|
|
747
880
|
const userResult = await this.getUser();
|
|
748
|
-
const factors = userResult.data
|
|
881
|
+
const factors = userResult.data.user?.factors ?? [];
|
|
749
882
|
const hasVerifiedFactors = factors.some((f) => f.status === "verified");
|
|
750
883
|
const nextLevel = hasVerifiedFactors ? "aal2" : "aal1";
|
|
751
|
-
return {
|
|
752
|
-
data: {
|
|
753
|
-
currentLevel,
|
|
754
|
-
nextLevel: nextLevel,
|
|
755
|
-
currentAuthenticationMethods: methods,
|
|
756
|
-
},
|
|
757
|
-
error: null,
|
|
758
|
-
};
|
|
884
|
+
return { data: { currentLevel, nextLevel, currentAuthenticationMethods: methods }, error: null };
|
|
759
885
|
}
|
|
760
886
|
catch {
|
|
761
887
|
return { data: null, error: { message: "Failed to decode access token" } };
|
|
@@ -794,67 +920,70 @@ export class AuthClient {
|
|
|
794
920
|
return null;
|
|
795
921
|
}
|
|
796
922
|
}
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
this.codeVerifier = verifier;
|
|
923
|
+
/**
|
|
924
|
+
* Keep a value for the OAuth redirect to find on the way back (a new page load, so not memory).
|
|
925
|
+
* A write that fails is ignored: same-process flows still have the in-memory copy.
|
|
926
|
+
*/
|
|
927
|
+
async writeFlowItem(suffix, value) {
|
|
803
928
|
if (!this.persistSession || this.storage === null)
|
|
804
929
|
return;
|
|
805
930
|
try {
|
|
806
|
-
await this.storage.setItem(this.
|
|
931
|
+
await this.storage.setItem(`${this.storageKey}${suffix}`, value);
|
|
807
932
|
}
|
|
808
933
|
catch {
|
|
809
|
-
// Ignore storage write failures
|
|
934
|
+
// Ignore storage write failures.
|
|
810
935
|
}
|
|
811
936
|
}
|
|
812
|
-
async
|
|
813
|
-
if (this.codeVerifier !== null)
|
|
814
|
-
return this.codeVerifier;
|
|
937
|
+
async readFlowItem(suffix) {
|
|
815
938
|
if (this.storage === null)
|
|
816
939
|
return null;
|
|
817
940
|
try {
|
|
818
|
-
const stored = await this.storage.getItem(this.
|
|
819
|
-
|
|
820
|
-
this.codeVerifier = stored;
|
|
821
|
-
return stored;
|
|
822
|
-
}
|
|
941
|
+
const stored = await this.storage.getItem(`${this.storageKey}${suffix}`);
|
|
942
|
+
return stored !== null && stored !== "" ? stored : null;
|
|
823
943
|
}
|
|
824
944
|
catch {
|
|
825
|
-
|
|
945
|
+
return null;
|
|
826
946
|
}
|
|
827
|
-
return null;
|
|
828
947
|
}
|
|
829
|
-
async
|
|
830
|
-
this.codeVerifier = null;
|
|
948
|
+
async removeFlowItem(suffix) {
|
|
831
949
|
if (this.storage === null)
|
|
832
950
|
return;
|
|
833
951
|
try {
|
|
834
|
-
await this.storage.removeItem(this.
|
|
952
|
+
await this.storage.removeItem(`${this.storageKey}${suffix}`);
|
|
835
953
|
}
|
|
836
954
|
catch {
|
|
837
955
|
// Ignore
|
|
838
956
|
}
|
|
839
957
|
}
|
|
958
|
+
/** Read a flow value once: the redirect it was kept for has now arrived. */
|
|
959
|
+
async takeFlowItem(suffix) {
|
|
960
|
+
const value = await this.readFlowItem(suffix);
|
|
961
|
+
if (value !== null)
|
|
962
|
+
await this.removeFlowItem(suffix);
|
|
963
|
+
return value;
|
|
964
|
+
}
|
|
965
|
+
async beginPkce() {
|
|
966
|
+
const verifier = generateCodeVerifier();
|
|
967
|
+
this.codeVerifier = verifier;
|
|
968
|
+
await this.writeFlowItem(VERIFIER_SUFFIX, verifier);
|
|
969
|
+
}
|
|
970
|
+
async readCodeVerifier() {
|
|
971
|
+
if (this.codeVerifier !== null)
|
|
972
|
+
return this.codeVerifier;
|
|
973
|
+
this.codeVerifier = await this.readFlowItem(VERIFIER_SUFFIX);
|
|
974
|
+
return this.codeVerifier;
|
|
975
|
+
}
|
|
976
|
+
async clearCodeVerifier() {
|
|
977
|
+
this.codeVerifier = null;
|
|
978
|
+
await this.removeFlowItem(VERIFIER_SUFFIX);
|
|
979
|
+
}
|
|
840
980
|
/** Decode JWT `exp` claim without verifying the signature. */
|
|
841
981
|
decodeJwtExp(accessToken) {
|
|
842
982
|
const parts = accessToken.split(".");
|
|
843
983
|
if (parts.length < 2)
|
|
844
984
|
return null;
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
const padded = payload + "=".repeat((4 - (payload.length % 4)) % 4);
|
|
848
|
-
const b64 = padded.replace(/-/g, "+").replace(/_/g, "/");
|
|
849
|
-
const json = typeof atob === "function"
|
|
850
|
-
? atob(b64)
|
|
851
|
-
: Buffer.from(b64, "base64").toString("utf8");
|
|
852
|
-
const claims = JSON.parse(json);
|
|
853
|
-
return typeof claims.exp === "number" ? claims.exp : null;
|
|
854
|
-
}
|
|
855
|
-
catch {
|
|
856
|
-
return null;
|
|
857
|
-
}
|
|
985
|
+
const exp = decodeJwtPayload(parts[1])?.["exp"];
|
|
986
|
+
return typeof exp === "number" ? exp : null;
|
|
858
987
|
}
|
|
859
988
|
async readStorageItem(key) {
|
|
860
989
|
if (this.storage === null)
|
|
@@ -907,68 +1036,29 @@ export class AuthClient {
|
|
|
907
1036
|
}
|
|
908
1037
|
parsePersistedSession(raw) {
|
|
909
1038
|
try {
|
|
910
|
-
|
|
911
|
-
return this.normalizePersistedSession(parsed);
|
|
1039
|
+
return this.normalizePersistedSession(JSON.parse(raw));
|
|
912
1040
|
}
|
|
913
1041
|
catch {
|
|
914
1042
|
return null;
|
|
915
1043
|
}
|
|
916
1044
|
}
|
|
1045
|
+
/** A stored session, written by this client (camelCase) or by a server-side helper (snake_case). */
|
|
917
1046
|
normalizePersistedSession(raw) {
|
|
918
|
-
if (
|
|
1047
|
+
if (!isJsonObject(raw))
|
|
919
1048
|
return null;
|
|
920
|
-
const
|
|
921
|
-
const
|
|
922
|
-
|
|
923
|
-
: typeof r["access_token"] === "string"
|
|
924
|
-
? r["access_token"]
|
|
925
|
-
: null;
|
|
926
|
-
if (accessToken === null)
|
|
927
|
-
return null;
|
|
928
|
-
const refreshToken = typeof r["refreshToken"] === "string"
|
|
929
|
-
? r["refreshToken"]
|
|
930
|
-
: typeof r["refresh_token"] === "string"
|
|
931
|
-
? r["refresh_token"]
|
|
932
|
-
: "";
|
|
933
|
-
const tokenType = typeof r["tokenType"] === "string"
|
|
934
|
-
? r["tokenType"]
|
|
935
|
-
: typeof r["token_type"] === "string"
|
|
936
|
-
? r["token_type"]
|
|
937
|
-
: "bearer";
|
|
938
|
-
const expiresIn = typeof r["expiresIn"] === "number"
|
|
939
|
-
? r["expiresIn"]
|
|
940
|
-
: typeof r["expires_in"] === "number"
|
|
941
|
-
? r["expires_in"]
|
|
942
|
-
: 3600;
|
|
943
|
-
const userRaw = typeof r["user"] === "object" && r["user"] !== null
|
|
944
|
-
? r["user"]
|
|
945
|
-
: null;
|
|
946
|
-
if (userRaw === null)
|
|
1049
|
+
const accessToken = eitherKey(raw, "accessToken", "access_token", isString);
|
|
1050
|
+
const user = raw["user"];
|
|
1051
|
+
if (accessToken === undefined || !isJsonObject(user))
|
|
947
1052
|
return null;
|
|
948
|
-
const
|
|
949
|
-
|
|
950
|
-
...(userRaw["app_metadata"] === undefined &&
|
|
951
|
-
userRaw["appMetadata"] !== undefined && { app_metadata: userRaw["appMetadata"] }),
|
|
952
|
-
...(userRaw["user_metadata"] === undefined &&
|
|
953
|
-
userRaw["userMetadata"] !== undefined && { user_metadata: userRaw["userMetadata"] }),
|
|
954
|
-
...(userRaw["created_at"] === undefined &&
|
|
955
|
-
userRaw["createdAt"] !== undefined && { created_at: userRaw["createdAt"] }),
|
|
956
|
-
...(userRaw["updated_at"] === undefined &&
|
|
957
|
-
userRaw["updatedAt"] !== undefined && { updated_at: userRaw["updatedAt"] }),
|
|
958
|
-
};
|
|
959
|
-
const session = {
|
|
1053
|
+
const expiresAt = eitherKey(raw, "expiresAt", "expires_at", isNumber);
|
|
1054
|
+
return {
|
|
960
1055
|
accessToken,
|
|
961
|
-
refreshToken,
|
|
962
|
-
tokenType,
|
|
963
|
-
expiresIn,
|
|
964
|
-
user: this._parseUser(
|
|
965
|
-
...(
|
|
966
|
-
? { expiresAt: r["expiresAt"] }
|
|
967
|
-
: typeof r["expires_at"] === "number"
|
|
968
|
-
? { expiresAt: r["expires_at"] }
|
|
969
|
-
: {}),
|
|
1056
|
+
refreshToken: eitherKey(raw, "refreshToken", "refresh_token", isString) ?? "",
|
|
1057
|
+
tokenType: eitherKey(raw, "tokenType", "token_type", isString) ?? "bearer",
|
|
1058
|
+
expiresIn: eitherKey(raw, "expiresIn", "expires_in", isNumber) ?? 3600,
|
|
1059
|
+
user: this._parseUser(snakeCaseUser(user)),
|
|
1060
|
+
...(expiresAt !== undefined && { expiresAt }),
|
|
970
1061
|
};
|
|
971
|
-
return session;
|
|
972
1062
|
}
|
|
973
1063
|
syncPersistedSession(session) {
|
|
974
1064
|
if (!this.persistSession)
|
|
@@ -1097,29 +1187,29 @@ export class AuthClient {
|
|
|
1097
1187
|
cb(event, session);
|
|
1098
1188
|
}
|
|
1099
1189
|
}
|
|
1190
|
+
/** Every refusal from the auth server goes through here, so none of them drops the code. */
|
|
1100
1191
|
async _parseError(res) {
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
};
|
|
1192
|
+
return authErrorFromBody(await readJsonObject(res), res.status);
|
|
1193
|
+
}
|
|
1194
|
+
/** The user a `/user` response describes. Throws on a body that is not a JSON object. */
|
|
1195
|
+
async _readUser(res) {
|
|
1196
|
+
return this._parseUser(await readJson(res, isJsonObject));
|
|
1107
1197
|
}
|
|
1108
1198
|
async _parseAuthResponse(res) {
|
|
1109
1199
|
if (!res.ok) {
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1200
|
+
return { data: { session: null, user: null }, error: await this._parseError(res) };
|
|
1201
|
+
}
|
|
1202
|
+
const json = await readJson(res, isJsonObject);
|
|
1203
|
+
const accessToken = json["access_token"];
|
|
1204
|
+
// A sign-up still waiting for its email confirmation is answered with the bare user and no
|
|
1205
|
+
// tokens. That is not a session, so nothing is stored and no SIGNED_IN is emitted.
|
|
1206
|
+
if (typeof accessToken !== "string" || accessToken === "") {
|
|
1207
|
+
const bareUser = json["user"];
|
|
1208
|
+
return { data: { session: null, user: this._parseUser(isJsonObject(bareUser) ? bareUser : json) }, error: null };
|
|
1118
1209
|
}
|
|
1119
|
-
const
|
|
1120
|
-
const user = this._parseUser((json["user"] ?? {}));
|
|
1210
|
+
const user = this._parseUser(objectOrEmpty(json["user"]));
|
|
1121
1211
|
const session = {
|
|
1122
|
-
accessToken
|
|
1212
|
+
accessToken,
|
|
1123
1213
|
tokenType: String(json["token_type"] ?? "bearer"),
|
|
1124
1214
|
expiresIn: Number(json["expires_in"] ?? 3600),
|
|
1125
1215
|
...(json["expires_at"] !== undefined && { expiresAt: Number(json["expires_at"]) }),
|
|
@@ -1136,35 +1226,44 @@ export class AuthClient {
|
|
|
1136
1226
|
...(raw["phone"] !== undefined && { phone: String(raw["phone"]) }),
|
|
1137
1227
|
...(raw["role"] !== undefined && { role: String(raw["role"]) }),
|
|
1138
1228
|
...(raw["is_anonymous"] !== undefined && { isAnonymous: Boolean(raw["is_anonymous"]) }),
|
|
1139
|
-
appMetadata: (raw["app_metadata"]
|
|
1140
|
-
userMetadata: (raw["user_metadata"]
|
|
1229
|
+
appMetadata: objectOrEmpty(raw["app_metadata"]),
|
|
1230
|
+
userMetadata: objectOrEmpty(raw["user_metadata"]),
|
|
1141
1231
|
createdAt: String(raw["created_at"] ?? ""),
|
|
1142
1232
|
updatedAt: String(raw["updated_at"] ?? ""),
|
|
1143
1233
|
};
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
provider: String(i["provider"] ?? ""),
|
|
1151
|
-
createdAt: String(i["created_at"] ?? ""),
|
|
1152
|
-
updatedAt: String(i["updated_at"] ?? ""),
|
|
1153
|
-
...(i["last_sign_in_at"] !== undefined && { lastSignInAt: String(i["last_sign_in_at"]) }),
|
|
1154
|
-
}));
|
|
1155
|
-
}
|
|
1156
|
-
if (Array.isArray(raw["factors"])) {
|
|
1157
|
-
user.factors = raw["factors"].map((f) => ({
|
|
1158
|
-
id: String(f["id"] ?? ""),
|
|
1159
|
-
factorType: String(f["factor_type"] ?? "totp"),
|
|
1160
|
-
status: String(f["status"] ?? "unverified"),
|
|
1161
|
-
createdAt: String(f["created_at"] ?? ""),
|
|
1162
|
-
updatedAt: String(f["updated_at"] ?? ""),
|
|
1163
|
-
...(f["friendly_name"] !== undefined && { friendlyName: String(f["friendly_name"]) }),
|
|
1164
|
-
...(f["phone"] !== undefined && { phone: String(f["phone"]) }),
|
|
1165
|
-
}));
|
|
1166
|
-
}
|
|
1234
|
+
const identities = raw["identities"];
|
|
1235
|
+
if (Array.isArray(identities))
|
|
1236
|
+
user.identities = identities.filter(isJsonObject).map(parseIdentity);
|
|
1237
|
+
const factors = raw["factors"];
|
|
1238
|
+
if (Array.isArray(factors))
|
|
1239
|
+
user.factors = factors.filter(isJsonObject).map(parseFactor);
|
|
1167
1240
|
return user;
|
|
1168
1241
|
}
|
|
1169
1242
|
}
|
|
1243
|
+
function parseIdentity(i) {
|
|
1244
|
+
return {
|
|
1245
|
+
id: String(i["id"] ?? ""),
|
|
1246
|
+
userId: String(i["user_id"] ?? ""),
|
|
1247
|
+
identityData: objectOrEmpty(i["identity_data"]),
|
|
1248
|
+
identityId: String(i["identity_id"] ?? ""),
|
|
1249
|
+
provider: String(i["provider"] ?? ""),
|
|
1250
|
+
createdAt: String(i["created_at"] ?? ""),
|
|
1251
|
+
updatedAt: String(i["updated_at"] ?? ""),
|
|
1252
|
+
...(i["last_sign_in_at"] !== undefined && { lastSignInAt: String(i["last_sign_in_at"]) }),
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
/** A factor as the server lists it. A type or state it leaves out reads as `totp` / `unverified`. */
|
|
1256
|
+
function parseFactor(f) {
|
|
1257
|
+
const factorType = f["factor_type"];
|
|
1258
|
+
const status = f["status"];
|
|
1259
|
+
return {
|
|
1260
|
+
id: String(f["id"] ?? ""),
|
|
1261
|
+
factorType: isFactorType(factorType) ? factorType : "totp",
|
|
1262
|
+
status: isFactorStatus(status) ? status : "unverified",
|
|
1263
|
+
createdAt: String(f["created_at"] ?? ""),
|
|
1264
|
+
updatedAt: String(f["updated_at"] ?? ""),
|
|
1265
|
+
...(f["friendly_name"] !== undefined && { friendlyName: String(f["friendly_name"]) }),
|
|
1266
|
+
...(f["phone"] !== undefined && { phone: String(f["phone"]) }),
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1170
1269
|
//# sourceMappingURL=auth.js.map
|