@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/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;
|
|
@@ -9,13 +73,21 @@ export class AuthClient {
|
|
|
9
73
|
listeners = new Map();
|
|
10
74
|
listenerIdCounter = 0;
|
|
11
75
|
persistSession;
|
|
76
|
+
/** False leaves every refresh to `ensureValidSession`, which each request calls first. */
|
|
77
|
+
autoRefreshToken;
|
|
78
|
+
/** False makes `ensureValidSession` leave an expired session as it is, for the server to refuse. */
|
|
79
|
+
refreshExpiredToken;
|
|
12
80
|
storageKey;
|
|
13
81
|
cookieName;
|
|
14
82
|
storage;
|
|
83
|
+
/** The client's fetch, with its timeout; only reads are retried. */
|
|
84
|
+
send;
|
|
15
85
|
/** When true, session is also mirrored to document.cookie (browser default path only). */
|
|
16
86
|
useCookies;
|
|
17
|
-
/** Resolves when async storage hydration
|
|
87
|
+
/** Resolves when async storage hydration and any sign-in carried by the page's URL complete. */
|
|
18
88
|
ready;
|
|
89
|
+
/** What `ready` settles with: the refusal the page's URL reported, if any. */
|
|
90
|
+
initialized;
|
|
19
91
|
/** Pending auto-refresh timer; refreshes the access token shortly before it expires. */
|
|
20
92
|
refreshTimer = null;
|
|
21
93
|
/** Dedupes concurrent refresh attempts (getSession + auto-refresh). */
|
|
@@ -26,52 +98,96 @@ export class AuthClient {
|
|
|
26
98
|
this.url = url;
|
|
27
99
|
this.baseHeaders = baseHeaders;
|
|
28
100
|
this.persistSession = opts.persistSession ?? true;
|
|
101
|
+
this.autoRefreshToken = opts.autoRefreshToken ?? true;
|
|
102
|
+
this.refreshExpiredToken = opts.refreshExpiredToken ?? true;
|
|
29
103
|
this.storageKey = opts.storageKey ?? DEFAULT_STORAGE_KEY;
|
|
30
104
|
const cookiePrefix = opts.cookiePrefix ?? DEFAULT_COOKIE_PREFIX;
|
|
31
105
|
this.cookieName = `${cookiePrefix}-auth-token`;
|
|
32
106
|
this.useCookies = opts.storage === undefined;
|
|
33
107
|
this.storage = opts.storage ?? this.getBrowserStorage();
|
|
108
|
+
this.send = opts.transport ?? plainFetch;
|
|
109
|
+
const hydrated = this.loadInitialSession(opts);
|
|
110
|
+
this.initialized = opts.detectSessionInUrl === false
|
|
111
|
+
? hydrated.then(() => ({ error: null }))
|
|
112
|
+
: hydrated.then(() => this.completeRedirect());
|
|
113
|
+
this.ready = this.initialized.then(() => undefined);
|
|
114
|
+
// Keep the access token fresh while the app is open (and refresh immediately
|
|
115
|
+
// if a persisted session loaded already expired).
|
|
116
|
+
this.scheduleAutoRefresh();
|
|
117
|
+
if (this.autoRefreshToken && this.currentSession !== null && this.isAccessTokenExpired(this.currentSession)) {
|
|
118
|
+
void this.ensureValidSession();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** The session the client starts with: the one passed in, else the persisted one. */
|
|
122
|
+
loadInitialSession(opts) {
|
|
34
123
|
if (opts.initialSession !== undefined) {
|
|
35
124
|
this.currentSession = opts.initialSession;
|
|
36
|
-
this.ready = Promise.resolve();
|
|
37
125
|
if (DEBUG_AUTH) {
|
|
38
126
|
console.debug("[supatype:auth] constructor initialSession provided", {
|
|
39
127
|
hasSession: true,
|
|
40
128
|
userId: opts.initialSession.user.id,
|
|
41
129
|
});
|
|
42
130
|
}
|
|
131
|
+
return Promise.resolve();
|
|
43
132
|
}
|
|
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();
|
|
133
|
+
if (!this.persistSession)
|
|
134
|
+
return Promise.resolve();
|
|
135
|
+
if (opts.storage !== undefined)
|
|
136
|
+
return this.hydrateFromStorage();
|
|
137
|
+
this.currentSession = this.loadPersistedSession();
|
|
138
|
+
if (DEBUG_AUTH) {
|
|
139
|
+
console.debug("[supatype:auth] constructor loaded persisted session", {
|
|
140
|
+
hasSession: this.currentSession !== null,
|
|
141
|
+
userId: this.currentSession?.user.id ?? null,
|
|
142
|
+
storageKey: this.storageKey,
|
|
143
|
+
cookieName: this.cookieName,
|
|
144
|
+
});
|
|
69
145
|
}
|
|
146
|
+
return Promise.resolve();
|
|
70
147
|
}
|
|
71
|
-
/** Resolves when
|
|
148
|
+
/** Resolves when the client has its starting session (storage hydrated, any URL sign-in done). */
|
|
72
149
|
whenReady() {
|
|
73
150
|
return this.ready;
|
|
74
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* Wait for the client's start, and learn whether a sign-in in the page's URL was refused.
|
|
154
|
+
*
|
|
155
|
+
* The same shape as supabase-js's `initialize()`. A refused OAuth sign-in comes back as
|
|
156
|
+
* `?error=...&error_description=...`; this is where an app (or `useAuth`) reads it.
|
|
157
|
+
*/
|
|
158
|
+
initialize() {
|
|
159
|
+
return this.initialized;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Finish the sign-in the page's URL carries, as supabase-js's `detectSessionInUrl` does.
|
|
163
|
+
*
|
|
164
|
+
* Whatever session was stored is set aside first, so a new sign-in is announced as `SIGNED_IN`
|
|
165
|
+
* and a refused one leaves the browser signed out, as supabase-js does after a failed attempt.
|
|
166
|
+
*/
|
|
167
|
+
async completeRedirect() {
|
|
168
|
+
const href = browserHref();
|
|
169
|
+
if (href === null || !(await this.isAuthRedirect(href)))
|
|
170
|
+
return { error: null };
|
|
171
|
+
const provider = await this.takeFlowItem(PROVIDER_SUFFIX);
|
|
172
|
+
this.currentSession = null;
|
|
173
|
+
const { error } = await this.getSessionFromUrl(href).catch((err) => ({
|
|
174
|
+
error: { message: err instanceof Error ? err.message : "Could not finish the sign-in" },
|
|
175
|
+
}));
|
|
176
|
+
cleanBrowserUrl(href);
|
|
177
|
+
if (error === null)
|
|
178
|
+
return { error: null };
|
|
179
|
+
this._setSession(null);
|
|
180
|
+
return { error: { ...error, ...(provider !== null && { provider }) } };
|
|
181
|
+
}
|
|
182
|
+
/** A URL with tokens or a refusal, or with a `code` for a PKCE flow this client started. */
|
|
183
|
+
async isAuthRedirect(href) {
|
|
184
|
+
const params = redirectParams(href);
|
|
185
|
+
if (params === null)
|
|
186
|
+
return false;
|
|
187
|
+
if (carriesImplicitResult(params))
|
|
188
|
+
return true;
|
|
189
|
+
return redirectParam(params, "code") !== null && (await this.readCodeVerifier()) !== null;
|
|
190
|
+
}
|
|
75
191
|
async hydrateFromStorage() {
|
|
76
192
|
try {
|
|
77
193
|
const session = await this.loadPersistedSessionAsync();
|
|
@@ -107,14 +223,8 @@ export class AuthClient {
|
|
|
107
223
|
const parts = accessToken.split(".");
|
|
108
224
|
if (parts.length !== 3)
|
|
109
225
|
return null;
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
const exp = payload["exp"];
|
|
113
|
-
return typeof exp === "number" ? exp * 1000 : null;
|
|
114
|
-
}
|
|
115
|
-
catch {
|
|
116
|
-
return null;
|
|
117
|
-
}
|
|
226
|
+
const exp = decodeJwtPayload(parts[1])?.["exp"];
|
|
227
|
+
return typeof exp === "number" ? exp * 1000 : null;
|
|
118
228
|
}
|
|
119
229
|
isAccessTokenExpired(session, skewMs = 0) {
|
|
120
230
|
const expiresAtMs = this.sessionExpiresAtMs(session);
|
|
@@ -135,6 +245,9 @@ export class AuthClient {
|
|
|
135
245
|
const session = this.currentSession;
|
|
136
246
|
if (session === null || !this.isAccessTokenExpired(session))
|
|
137
247
|
return;
|
|
248
|
+
// Sent as it is: a refresh nobody can store spends a refresh token someone else holds.
|
|
249
|
+
if (!this.refreshExpiredToken)
|
|
250
|
+
return;
|
|
138
251
|
if (!session.refreshToken?.trim()) {
|
|
139
252
|
this._setSession(null);
|
|
140
253
|
return;
|
|
@@ -156,7 +269,7 @@ export class AuthClient {
|
|
|
156
269
|
clearTimeout(this.refreshTimer);
|
|
157
270
|
this.refreshTimer = null;
|
|
158
271
|
}
|
|
159
|
-
if (typeof setTimeout === "undefined")
|
|
272
|
+
if (!this.autoRefreshToken || typeof setTimeout === "undefined")
|
|
160
273
|
return;
|
|
161
274
|
const session = this.currentSession;
|
|
162
275
|
if (session === null || !session.refreshToken)
|
|
@@ -165,11 +278,14 @@ export class AuthClient {
|
|
|
165
278
|
const delay = expiryMs === null
|
|
166
279
|
? Math.max(0, (session.expiresIn || 3600) * 1000 - 60_000)
|
|
167
280
|
: Math.max(0, expiryMs - Date.now() - 60_000);
|
|
168
|
-
|
|
281
|
+
const timer = setTimeout(() => {
|
|
169
282
|
this.refreshTimer = null;
|
|
170
283
|
void this.ensureValidSession();
|
|
171
284
|
}, delay);
|
|
172
|
-
this.refreshTimer
|
|
285
|
+
this.refreshTimer = timer;
|
|
286
|
+
// Avoid keeping a Node process alive for this timer. A browser's timer is a number: nothing to do.
|
|
287
|
+
if (typeof timer === "object" && "unref" in timer)
|
|
288
|
+
timer.unref();
|
|
173
289
|
}
|
|
174
290
|
async signUp(credentials) {
|
|
175
291
|
const body = {
|
|
@@ -179,7 +295,7 @@ export class AuthClient {
|
|
|
179
295
|
if (credentials.options?.data !== undefined) {
|
|
180
296
|
body["data"] = credentials.options.data;
|
|
181
297
|
}
|
|
182
|
-
const res = await
|
|
298
|
+
const res = await this.send(`${this.url}/signup`, {
|
|
183
299
|
method: "POST",
|
|
184
300
|
headers: this.baseHeaders,
|
|
185
301
|
body: JSON.stringify(body),
|
|
@@ -187,7 +303,7 @@ export class AuthClient {
|
|
|
187
303
|
return this._parseAuthResponse(res);
|
|
188
304
|
}
|
|
189
305
|
async signInWithPassword(credentials) {
|
|
190
|
-
const res = await
|
|
306
|
+
const res = await this.send(`${this.url}/token?grant_type=password`, {
|
|
191
307
|
method: "POST",
|
|
192
308
|
headers: this.baseHeaders,
|
|
193
309
|
body: JSON.stringify({
|
|
@@ -205,19 +321,38 @@ export class AuthClient {
|
|
|
205
321
|
if (credentials?.options?.captchaToken !== undefined) {
|
|
206
322
|
body["supatype_meta_security"] = { captcha_token: credentials.options.captchaToken };
|
|
207
323
|
}
|
|
208
|
-
const res = await
|
|
324
|
+
const res = await this.send(`${this.url}/signup`, {
|
|
209
325
|
method: "POST",
|
|
210
326
|
headers: this.baseHeaders,
|
|
211
327
|
body: JSON.stringify(body),
|
|
212
328
|
});
|
|
213
329
|
return this._parseAuthResponse(res);
|
|
214
330
|
}
|
|
331
|
+
/**
|
|
332
|
+
* An auth endpoint, carrying the caller's redirect as `redirect_to` in the query string. The
|
|
333
|
+
* server reads it from there (or a header) and never from a JSON body, so a redirect sent in the
|
|
334
|
+
* body is dropped in silence and the email links to SITE_URL instead.
|
|
335
|
+
*/
|
|
336
|
+
endpoint(path, redirectTo) {
|
|
337
|
+
const url = new URL(`${this.url}${path}`);
|
|
338
|
+
if (redirectTo !== undefined)
|
|
339
|
+
url.searchParams.set("redirect_to", redirectTo);
|
|
340
|
+
return url;
|
|
341
|
+
}
|
|
215
342
|
async signInWithOAuth(opts) {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
if (opts.
|
|
219
|
-
|
|
343
|
+
// The server answers /authorize for a disabled provider with a bare JSON 400, which a browser
|
|
344
|
+
// navigating there shows as raw text; asking first lets the caller show a message instead.
|
|
345
|
+
if (await this.providerDisabled(opts.provider)) {
|
|
346
|
+
const message = `Sign-in with ${opts.provider} is not enabled for this project.`;
|
|
347
|
+
return { data: { url: "", provider: opts.provider }, error: { message, status: 400, code: "provider_disabled" } };
|
|
348
|
+
}
|
|
349
|
+
await this.writeFlowItem(PROVIDER_SUFFIX, opts.provider);
|
|
350
|
+
const url = this.endpoint("/authorize", opts.options?.redirectTo);
|
|
351
|
+
for (const [key, value] of Object.entries(opts.options?.queryParams ?? {})) {
|
|
352
|
+
if (!url.searchParams.has(key))
|
|
353
|
+
url.searchParams.set(key, value);
|
|
220
354
|
}
|
|
355
|
+
url.searchParams.set("provider", opts.provider);
|
|
221
356
|
if (opts.options?.scopes !== undefined) {
|
|
222
357
|
url.searchParams.set("scopes", opts.options.scopes);
|
|
223
358
|
}
|
|
@@ -229,12 +364,29 @@ export class AuthClient {
|
|
|
229
364
|
}
|
|
230
365
|
return { data: { url: url.toString(), provider: opts.provider }, error: null };
|
|
231
366
|
}
|
|
367
|
+
/**
|
|
368
|
+
* True only when the server's `/settings` list the provider as off. A provider they do not list
|
|
369
|
+
* (a `custom:` one) or settings that cannot be read leave the decision to `/authorize`. Looked up
|
|
370
|
+
* in lower case, as `/authorize` resolves it, so `GitHub` is refused exactly when `github` is.
|
|
371
|
+
*/
|
|
372
|
+
async providerDisabled(provider) {
|
|
373
|
+
try {
|
|
374
|
+
const res = await this.send(`${this.url}/settings`, { headers: this.baseHeaders });
|
|
375
|
+
if (!res.ok)
|
|
376
|
+
return false;
|
|
377
|
+
const external = objectOrEmpty((await readJsonObject(res))["external"]);
|
|
378
|
+
return external[provider.toLowerCase()] === false;
|
|
379
|
+
}
|
|
380
|
+
catch {
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
232
384
|
/**
|
|
233
385
|
* Apply tokens from an OAuth / deep-link redirect (implicit grant) or restore a session.
|
|
234
386
|
* Fetches `/user` to hydrate the user object, then persists via the configured storage.
|
|
235
387
|
*/
|
|
236
388
|
async setSession(params) {
|
|
237
|
-
const res = await
|
|
389
|
+
const res = await this.send(`${this.url}/user`, {
|
|
238
390
|
headers: {
|
|
239
391
|
...this.baseHeaders,
|
|
240
392
|
Authorization: `Bearer ${params.accessToken}`,
|
|
@@ -246,8 +398,7 @@ export class AuthClient {
|
|
|
246
398
|
error: await this._parseError(res),
|
|
247
399
|
};
|
|
248
400
|
}
|
|
249
|
-
const
|
|
250
|
-
const user = this._parseUser(raw);
|
|
401
|
+
const user = await this._readUser(res);
|
|
251
402
|
const session = {
|
|
252
403
|
accessToken: params.accessToken,
|
|
253
404
|
refreshToken: params.refreshToken,
|
|
@@ -279,7 +430,7 @@ export class AuthClient {
|
|
|
279
430
|
},
|
|
280
431
|
};
|
|
281
432
|
}
|
|
282
|
-
const res = await
|
|
433
|
+
const res = await this.send(`${this.url}/token?grant_type=pkce`, {
|
|
283
434
|
method: "POST",
|
|
284
435
|
headers: this.baseHeaders,
|
|
285
436
|
body: JSON.stringify({
|
|
@@ -295,28 +446,26 @@ export class AuthClient {
|
|
|
295
446
|
* Supports PKCE (`?code=`) and implicit (`#access_token=` / query tokens).
|
|
296
447
|
*/
|
|
297
448
|
async getSessionFromUrl(url) {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
parsed = new URL(url);
|
|
301
|
-
}
|
|
302
|
-
catch {
|
|
449
|
+
const params = redirectParams(url);
|
|
450
|
+
if (params === null) {
|
|
303
451
|
return {
|
|
304
452
|
data: { session: null, user: null },
|
|
305
453
|
error: { message: `Invalid redirect URL: ${url}`, status: 400 },
|
|
306
454
|
};
|
|
307
455
|
}
|
|
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
|
-
};
|
|
456
|
+
const { query, fragment: hashParams } = params;
|
|
457
|
+
// A refused link comes back with the same fields as a refused request, in the URL instead.
|
|
458
|
+
const redirectError = { ...Object.fromEntries(hashParams), ...Object.fromEntries(query) };
|
|
459
|
+
if (redirectError["error_description"] || redirectError["error"]) {
|
|
460
|
+
return { data: { session: null, user: null }, error: authErrorFromBody(redirectError, 400) };
|
|
319
461
|
}
|
|
462
|
+
// The auth server marks the link it sent with `type`; a recovery link signs the user in so they
|
|
463
|
+
// can choose a new password, and the app needs to know that is why they arrived.
|
|
464
|
+
const recovery = (hashParams.get("type") ?? query.get("type")) === "recovery";
|
|
465
|
+
return this.announceRecovery(await this.sessionFromRedirect(query, hashParams), recovery);
|
|
466
|
+
}
|
|
467
|
+
/** The session a redirect carries: a PKCE code to exchange, or implicit-grant tokens. */
|
|
468
|
+
async sessionFromRedirect(query, hashParams) {
|
|
320
469
|
const code = query.get("code") ?? hashParams.get("code");
|
|
321
470
|
if (code !== null && code !== "") {
|
|
322
471
|
return this.exchangeCodeForSession(code);
|
|
@@ -334,6 +483,18 @@ export class AuthClient {
|
|
|
334
483
|
},
|
|
335
484
|
};
|
|
336
485
|
}
|
|
486
|
+
/**
|
|
487
|
+
* Emit `PASSWORD_RECOVERY` once a recovery link or code has produced a session.
|
|
488
|
+
*
|
|
489
|
+
* After the `SIGNED_IN` that establishing the session already emitted, as `MFA_CHALLENGE_VERIFIED`
|
|
490
|
+
* follows it, so a listener keyed on sign-in still sees one and a reset page can key on this.
|
|
491
|
+
*/
|
|
492
|
+
announceRecovery(result, recovery) {
|
|
493
|
+
if (recovery && result.error === null && result.data.session !== null) {
|
|
494
|
+
this._emitEvent("PASSWORD_RECOVERY", result.data.session);
|
|
495
|
+
}
|
|
496
|
+
return result;
|
|
497
|
+
}
|
|
337
498
|
async signInWithOtp(opts) {
|
|
338
499
|
const body = {
|
|
339
500
|
create_user: opts.options?.createUser ?? true,
|
|
@@ -347,13 +508,13 @@ export class AuthClient {
|
|
|
347
508
|
body["channel"] = opts.options.channel;
|
|
348
509
|
}
|
|
349
510
|
}
|
|
350
|
-
const res = await
|
|
511
|
+
const res = await this.send(this.endpoint("/otp", opts.options?.emailRedirectTo).toString(), {
|
|
351
512
|
method: "POST",
|
|
352
513
|
headers: this.baseHeaders,
|
|
353
514
|
body: JSON.stringify(body),
|
|
354
515
|
});
|
|
355
516
|
if (res.ok) {
|
|
356
|
-
const json = await res
|
|
517
|
+
const json = await readJsonObject(res);
|
|
357
518
|
return {
|
|
358
519
|
data: {
|
|
359
520
|
...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
|
|
@@ -361,18 +522,11 @@ export class AuthClient {
|
|
|
361
522
|
error: null,
|
|
362
523
|
};
|
|
363
524
|
}
|
|
364
|
-
|
|
365
|
-
return {
|
|
366
|
-
data: {},
|
|
367
|
-
error: {
|
|
368
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
369
|
-
status: res.status,
|
|
370
|
-
},
|
|
371
|
-
};
|
|
525
|
+
return { data: {}, error: await this._parseError(res) };
|
|
372
526
|
}
|
|
373
527
|
async signOut() {
|
|
374
528
|
if (this.currentSession !== null) {
|
|
375
|
-
await
|
|
529
|
+
await this.send(`${this.url}/logout`, {
|
|
376
530
|
method: "POST",
|
|
377
531
|
headers: {
|
|
378
532
|
...this.baseHeaders,
|
|
@@ -392,20 +546,16 @@ export class AuthClient {
|
|
|
392
546
|
if (this.currentSession === null) {
|
|
393
547
|
return { data: { user: null }, error: null };
|
|
394
548
|
}
|
|
395
|
-
const res = await
|
|
549
|
+
const res = await this.send(`${this.url}/user`, {
|
|
396
550
|
headers: {
|
|
397
551
|
...this.baseHeaders,
|
|
398
552
|
Authorization: `Bearer ${this.currentSession.accessToken}`,
|
|
399
553
|
},
|
|
400
554
|
});
|
|
401
555
|
if (!res.ok) {
|
|
402
|
-
return {
|
|
403
|
-
data: { user: null },
|
|
404
|
-
error: { message: "Could not get user", status: res.status },
|
|
405
|
-
};
|
|
556
|
+
return { data: { user: null }, error: await this._parseError(res) };
|
|
406
557
|
}
|
|
407
|
-
|
|
408
|
-
return { data: { user: this._parseUser(raw) }, error: null };
|
|
558
|
+
return { data: { user: await this._readUser(res) }, error: null };
|
|
409
559
|
}
|
|
410
560
|
async refreshSession() {
|
|
411
561
|
if (this.currentSession === null) {
|
|
@@ -416,7 +566,7 @@ export class AuthClient {
|
|
|
416
566
|
return { data: { session: null }, error: { message: "No refresh token" } };
|
|
417
567
|
}
|
|
418
568
|
try {
|
|
419
|
-
const res = await
|
|
569
|
+
const res = await this.send(`${this.url}/token?grant_type=refresh_token`, {
|
|
420
570
|
method: "POST",
|
|
421
571
|
headers: this.baseHeaders,
|
|
422
572
|
body: JSON.stringify({ refresh_token: this.currentSession.refreshToken }),
|
|
@@ -435,31 +585,20 @@ export class AuthClient {
|
|
|
435
585
|
}
|
|
436
586
|
}
|
|
437
587
|
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`, {
|
|
588
|
+
const res = await this.send(this.endpoint("/recover", options?.redirectTo).toString(), {
|
|
443
589
|
method: "POST",
|
|
444
590
|
headers: this.baseHeaders,
|
|
445
|
-
body: JSON.stringify(
|
|
591
|
+
body: JSON.stringify({ email }),
|
|
446
592
|
});
|
|
447
593
|
if (res.ok)
|
|
448
594
|
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
|
-
};
|
|
595
|
+
return { data: {}, error: await this._parseError(res) };
|
|
457
596
|
}
|
|
458
597
|
async updateUser(updates) {
|
|
459
598
|
if (this.currentSession === null) {
|
|
460
599
|
return { data: { user: null }, error: { message: "Not authenticated" } };
|
|
461
600
|
}
|
|
462
|
-
const res = await
|
|
601
|
+
const res = await this.send(`${this.url}/user`, {
|
|
463
602
|
method: "PUT",
|
|
464
603
|
headers: {
|
|
465
604
|
...this.baseHeaders,
|
|
@@ -468,17 +607,25 @@ export class AuthClient {
|
|
|
468
607
|
body: JSON.stringify(updates),
|
|
469
608
|
});
|
|
470
609
|
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
|
-
};
|
|
610
|
+
return { data: { user: null }, error: await this._parseError(res) };
|
|
479
611
|
}
|
|
480
|
-
const
|
|
481
|
-
|
|
612
|
+
const user = await this._readUser(res);
|
|
613
|
+
this.applyUpdatedUser(user);
|
|
614
|
+
return { data: { user }, error: null };
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Put the server's updated user on the session, persist it, and tell listeners.
|
|
618
|
+
*
|
|
619
|
+
* The tokens are unchanged, so this neither reschedules the refresh nor emits `TOKEN_REFRESHED`;
|
|
620
|
+
* without it the session kept the old email and metadata until the next refresh.
|
|
621
|
+
*/
|
|
622
|
+
applyUpdatedUser(user) {
|
|
623
|
+
if (this.currentSession === null)
|
|
624
|
+
return;
|
|
625
|
+
const session = { ...this.currentSession, user };
|
|
626
|
+
this.currentSession = session;
|
|
627
|
+
this.syncPersistedSession(session);
|
|
628
|
+
this._emitEvent("USER_UPDATED", session);
|
|
482
629
|
}
|
|
483
630
|
/**
|
|
484
631
|
* Verify an OTP token received via email or phone.
|
|
@@ -498,12 +645,12 @@ export class AuthClient {
|
|
|
498
645
|
if (params.phone !== undefined)
|
|
499
646
|
body["phone"] = params.phone;
|
|
500
647
|
}
|
|
501
|
-
const res = await
|
|
648
|
+
const res = await this.send(`${this.url}/verify`, {
|
|
502
649
|
method: "POST",
|
|
503
650
|
headers: this.baseHeaders,
|
|
504
651
|
body: JSON.stringify(body),
|
|
505
652
|
});
|
|
506
|
-
return this._parseAuthResponse(res);
|
|
653
|
+
return this.announceRecovery(await this._parseAuthResponse(res), params.type === "recovery");
|
|
507
654
|
}
|
|
508
655
|
/**
|
|
509
656
|
* Sign in with an ID token from an external provider (e.g. Google One Tap).
|
|
@@ -517,7 +664,7 @@ export class AuthClient {
|
|
|
517
664
|
if (credentials.nonce !== undefined) {
|
|
518
665
|
body["nonce"] = credentials.nonce;
|
|
519
666
|
}
|
|
520
|
-
const res = await
|
|
667
|
+
const res = await this.send(`${this.url}/token?grant_type=id_token`, {
|
|
521
668
|
method: "POST",
|
|
522
669
|
headers: this.baseHeaders,
|
|
523
670
|
body: JSON.stringify(body),
|
|
@@ -533,13 +680,13 @@ export class AuthClient {
|
|
|
533
680
|
body["email"] = params.email;
|
|
534
681
|
if (params.phone !== undefined)
|
|
535
682
|
body["phone"] = params.phone;
|
|
536
|
-
const res = await
|
|
683
|
+
const res = await this.send(`${this.url}/resend`, {
|
|
537
684
|
method: "POST",
|
|
538
685
|
headers: this.baseHeaders,
|
|
539
686
|
body: JSON.stringify(body),
|
|
540
687
|
});
|
|
541
688
|
if (res.ok) {
|
|
542
|
-
const json = await res
|
|
689
|
+
const json = await readJsonObject(res);
|
|
543
690
|
return {
|
|
544
691
|
data: {
|
|
545
692
|
...(json["message_id"] !== undefined && { messageId: String(json["message_id"]) }),
|
|
@@ -547,14 +694,7 @@ export class AuthClient {
|
|
|
547
694
|
error: null,
|
|
548
695
|
};
|
|
549
696
|
}
|
|
550
|
-
|
|
551
|
-
return {
|
|
552
|
-
data: {},
|
|
553
|
-
error: {
|
|
554
|
-
message: String(err["error_description"] ?? err["msg"] ?? "Error"),
|
|
555
|
-
status: res.status,
|
|
556
|
-
},
|
|
557
|
-
};
|
|
697
|
+
return { data: {}, error: await this._parseError(res) };
|
|
558
698
|
}
|
|
559
699
|
// ─── MFA ──────────────────────────────────────────────────────────────────────
|
|
560
700
|
/**
|
|
@@ -580,7 +720,7 @@ export class AuthClient {
|
|
|
580
720
|
body["issuer"] = params.issuer;
|
|
581
721
|
if (params.phone !== undefined)
|
|
582
722
|
body["phone"] = params.phone;
|
|
583
|
-
const res = await
|
|
723
|
+
const res = await this.send(`${this.url}/factors`, {
|
|
584
724
|
method: "POST",
|
|
585
725
|
headers: {
|
|
586
726
|
...this.baseHeaders,
|
|
@@ -591,16 +731,17 @@ export class AuthClient {
|
|
|
591
731
|
if (!res.ok) {
|
|
592
732
|
return { data: null, error: await this._parseError(res) };
|
|
593
733
|
}
|
|
594
|
-
const json = await res
|
|
734
|
+
const json = await readJson(res, isJsonObject);
|
|
735
|
+
const totp = json["totp"];
|
|
595
736
|
const data = {
|
|
596
737
|
id: String(json["id"] ?? ""),
|
|
597
738
|
type: String(json["type"] ?? ""),
|
|
598
739
|
friendlyName: String(json["friendly_name"] ?? ""),
|
|
599
|
-
...(
|
|
740
|
+
...(isJsonObject(totp) && {
|
|
600
741
|
totp: {
|
|
601
|
-
qrCode: String(
|
|
602
|
-
secret: String(
|
|
603
|
-
uri: String(
|
|
742
|
+
qrCode: String(totp["qr_code"] ?? ""),
|
|
743
|
+
secret: String(totp["secret"] ?? ""),
|
|
744
|
+
uri: String(totp["uri"] ?? ""),
|
|
604
745
|
},
|
|
605
746
|
}),
|
|
606
747
|
...(json["phone"] !== undefined && { phone: String(json["phone"]) }),
|
|
@@ -618,7 +759,7 @@ export class AuthClient {
|
|
|
618
759
|
const body = {};
|
|
619
760
|
if (params.channel !== undefined)
|
|
620
761
|
body["channel"] = params.channel;
|
|
621
|
-
const res = await
|
|
762
|
+
const res = await this.send(`${this.url}/factors/${params.factorId}/challenge`, {
|
|
622
763
|
method: "POST",
|
|
623
764
|
headers: {
|
|
624
765
|
...this.baseHeaders,
|
|
@@ -629,7 +770,7 @@ export class AuthClient {
|
|
|
629
770
|
if (!res.ok) {
|
|
630
771
|
return { data: null, error: await this._parseError(res) };
|
|
631
772
|
}
|
|
632
|
-
const json = await res
|
|
773
|
+
const json = await readJson(res, isJsonObject);
|
|
633
774
|
return {
|
|
634
775
|
data: {
|
|
635
776
|
id: String(json["id"] ?? ""),
|
|
@@ -650,7 +791,7 @@ export class AuthClient {
|
|
|
650
791
|
error: { message: "Not authenticated" },
|
|
651
792
|
};
|
|
652
793
|
}
|
|
653
|
-
const res = await
|
|
794
|
+
const res = await this.send(`${this.url}/factors/${params.factorId}/verify`, {
|
|
654
795
|
method: "POST",
|
|
655
796
|
headers: {
|
|
656
797
|
...this.baseHeaders,
|
|
@@ -693,7 +834,7 @@ export class AuthClient {
|
|
|
693
834
|
if (this.currentSession === null) {
|
|
694
835
|
return { data: null, error: { message: "Not authenticated" } };
|
|
695
836
|
}
|
|
696
|
-
const res = await
|
|
837
|
+
const res = await this.send(`${this.url}/factors/${params.factorId}`, {
|
|
697
838
|
method: "DELETE",
|
|
698
839
|
headers: {
|
|
699
840
|
...this.baseHeaders,
|
|
@@ -703,7 +844,7 @@ export class AuthClient {
|
|
|
703
844
|
if (!res.ok) {
|
|
704
845
|
return { data: null, error: await this._parseError(res) };
|
|
705
846
|
}
|
|
706
|
-
const json = await res
|
|
847
|
+
const json = await readJson(res, isJsonObject);
|
|
707
848
|
return { data: { id: String(json["id"] ?? "") }, error: null };
|
|
708
849
|
},
|
|
709
850
|
/**
|
|
@@ -738,24 +879,18 @@ export class AuthClient {
|
|
|
738
879
|
if (parts.length !== 3) {
|
|
739
880
|
return { data: null, error: { message: "Invalid access token format" } };
|
|
740
881
|
}
|
|
882
|
+
const payload = decodeJwtPayload(parts[1]);
|
|
883
|
+
if (payload === null) {
|
|
884
|
+
return { data: null, error: { message: "Failed to decode access token" } };
|
|
885
|
+
}
|
|
886
|
+
const { currentLevel, methods } = assuranceClaims(payload);
|
|
741
887
|
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
888
|
// Determine next level: if user has verified factors, next could be aal2
|
|
747
889
|
const userResult = await this.getUser();
|
|
748
|
-
const factors = userResult.data
|
|
890
|
+
const factors = userResult.data.user?.factors ?? [];
|
|
749
891
|
const hasVerifiedFactors = factors.some((f) => f.status === "verified");
|
|
750
892
|
const nextLevel = hasVerifiedFactors ? "aal2" : "aal1";
|
|
751
|
-
return {
|
|
752
|
-
data: {
|
|
753
|
-
currentLevel,
|
|
754
|
-
nextLevel: nextLevel,
|
|
755
|
-
currentAuthenticationMethods: methods,
|
|
756
|
-
},
|
|
757
|
-
error: null,
|
|
758
|
-
};
|
|
893
|
+
return { data: { currentLevel, nextLevel, currentAuthenticationMethods: methods }, error: null };
|
|
759
894
|
}
|
|
760
895
|
catch {
|
|
761
896
|
return { data: null, error: { message: "Failed to decode access token" } };
|
|
@@ -794,67 +929,70 @@ export class AuthClient {
|
|
|
794
929
|
return null;
|
|
795
930
|
}
|
|
796
931
|
}
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
this.codeVerifier = verifier;
|
|
932
|
+
/**
|
|
933
|
+
* Keep a value for the OAuth redirect to find on the way back (a new page load, so not memory).
|
|
934
|
+
* A write that fails is ignored: same-process flows still have the in-memory copy.
|
|
935
|
+
*/
|
|
936
|
+
async writeFlowItem(suffix, value) {
|
|
803
937
|
if (!this.persistSession || this.storage === null)
|
|
804
938
|
return;
|
|
805
939
|
try {
|
|
806
|
-
await this.storage.setItem(this.
|
|
940
|
+
await this.storage.setItem(`${this.storageKey}${suffix}`, value);
|
|
807
941
|
}
|
|
808
942
|
catch {
|
|
809
|
-
// Ignore storage write failures
|
|
943
|
+
// Ignore storage write failures.
|
|
810
944
|
}
|
|
811
945
|
}
|
|
812
|
-
async
|
|
813
|
-
if (this.codeVerifier !== null)
|
|
814
|
-
return this.codeVerifier;
|
|
946
|
+
async readFlowItem(suffix) {
|
|
815
947
|
if (this.storage === null)
|
|
816
948
|
return null;
|
|
817
949
|
try {
|
|
818
|
-
const stored = await this.storage.getItem(this.
|
|
819
|
-
|
|
820
|
-
this.codeVerifier = stored;
|
|
821
|
-
return stored;
|
|
822
|
-
}
|
|
950
|
+
const stored = await this.storage.getItem(`${this.storageKey}${suffix}`);
|
|
951
|
+
return stored !== null && stored !== "" ? stored : null;
|
|
823
952
|
}
|
|
824
953
|
catch {
|
|
825
|
-
|
|
954
|
+
return null;
|
|
826
955
|
}
|
|
827
|
-
return null;
|
|
828
956
|
}
|
|
829
|
-
async
|
|
830
|
-
this.codeVerifier = null;
|
|
957
|
+
async removeFlowItem(suffix) {
|
|
831
958
|
if (this.storage === null)
|
|
832
959
|
return;
|
|
833
960
|
try {
|
|
834
|
-
await this.storage.removeItem(this.
|
|
961
|
+
await this.storage.removeItem(`${this.storageKey}${suffix}`);
|
|
835
962
|
}
|
|
836
963
|
catch {
|
|
837
964
|
// Ignore
|
|
838
965
|
}
|
|
839
966
|
}
|
|
967
|
+
/** Read a flow value once: the redirect it was kept for has now arrived. */
|
|
968
|
+
async takeFlowItem(suffix) {
|
|
969
|
+
const value = await this.readFlowItem(suffix);
|
|
970
|
+
if (value !== null)
|
|
971
|
+
await this.removeFlowItem(suffix);
|
|
972
|
+
return value;
|
|
973
|
+
}
|
|
974
|
+
async beginPkce() {
|
|
975
|
+
const verifier = generateCodeVerifier();
|
|
976
|
+
this.codeVerifier = verifier;
|
|
977
|
+
await this.writeFlowItem(VERIFIER_SUFFIX, verifier);
|
|
978
|
+
}
|
|
979
|
+
async readCodeVerifier() {
|
|
980
|
+
if (this.codeVerifier !== null)
|
|
981
|
+
return this.codeVerifier;
|
|
982
|
+
this.codeVerifier = await this.readFlowItem(VERIFIER_SUFFIX);
|
|
983
|
+
return this.codeVerifier;
|
|
984
|
+
}
|
|
985
|
+
async clearCodeVerifier() {
|
|
986
|
+
this.codeVerifier = null;
|
|
987
|
+
await this.removeFlowItem(VERIFIER_SUFFIX);
|
|
988
|
+
}
|
|
840
989
|
/** Decode JWT `exp` claim without verifying the signature. */
|
|
841
990
|
decodeJwtExp(accessToken) {
|
|
842
991
|
const parts = accessToken.split(".");
|
|
843
992
|
if (parts.length < 2)
|
|
844
993
|
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
|
-
}
|
|
994
|
+
const exp = decodeJwtPayload(parts[1])?.["exp"];
|
|
995
|
+
return typeof exp === "number" ? exp : null;
|
|
858
996
|
}
|
|
859
997
|
async readStorageItem(key) {
|
|
860
998
|
if (this.storage === null)
|
|
@@ -907,68 +1045,29 @@ export class AuthClient {
|
|
|
907
1045
|
}
|
|
908
1046
|
parsePersistedSession(raw) {
|
|
909
1047
|
try {
|
|
910
|
-
|
|
911
|
-
return this.normalizePersistedSession(parsed);
|
|
1048
|
+
return this.normalizePersistedSession(JSON.parse(raw));
|
|
912
1049
|
}
|
|
913
1050
|
catch {
|
|
914
1051
|
return null;
|
|
915
1052
|
}
|
|
916
1053
|
}
|
|
1054
|
+
/** A stored session, written by this client (camelCase) or by a server-side helper (snake_case). */
|
|
917
1055
|
normalizePersistedSession(raw) {
|
|
918
|
-
if (
|
|
1056
|
+
if (!isJsonObject(raw))
|
|
919
1057
|
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)
|
|
1058
|
+
const accessToken = eitherKey(raw, "accessToken", "access_token", isString);
|
|
1059
|
+
const user = raw["user"];
|
|
1060
|
+
if (accessToken === undefined || !isJsonObject(user))
|
|
947
1061
|
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 = {
|
|
1062
|
+
const expiresAt = eitherKey(raw, "expiresAt", "expires_at", isNumber);
|
|
1063
|
+
return {
|
|
960
1064
|
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
|
-
: {}),
|
|
1065
|
+
refreshToken: eitherKey(raw, "refreshToken", "refresh_token", isString) ?? "",
|
|
1066
|
+
tokenType: eitherKey(raw, "tokenType", "token_type", isString) ?? "bearer",
|
|
1067
|
+
expiresIn: eitherKey(raw, "expiresIn", "expires_in", isNumber) ?? 3600,
|
|
1068
|
+
user: this._parseUser(snakeCaseUser(user)),
|
|
1069
|
+
...(expiresAt !== undefined && { expiresAt }),
|
|
970
1070
|
};
|
|
971
|
-
return session;
|
|
972
1071
|
}
|
|
973
1072
|
syncPersistedSession(session) {
|
|
974
1073
|
if (!this.persistSession)
|
|
@@ -1097,29 +1196,29 @@ export class AuthClient {
|
|
|
1097
1196
|
cb(event, session);
|
|
1098
1197
|
}
|
|
1099
1198
|
}
|
|
1199
|
+
/** Every refusal from the auth server goes through here, so none of them drops the code. */
|
|
1100
1200
|
async _parseError(res) {
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
};
|
|
1201
|
+
return authErrorFromBody(await readJsonObject(res), res.status);
|
|
1202
|
+
}
|
|
1203
|
+
/** The user a `/user` response describes. Throws on a body that is not a JSON object. */
|
|
1204
|
+
async _readUser(res) {
|
|
1205
|
+
return this._parseUser(await readJson(res, isJsonObject));
|
|
1107
1206
|
}
|
|
1108
1207
|
async _parseAuthResponse(res) {
|
|
1109
1208
|
if (!res.ok) {
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1209
|
+
return { data: { session: null, user: null }, error: await this._parseError(res) };
|
|
1210
|
+
}
|
|
1211
|
+
const json = await readJson(res, isJsonObject);
|
|
1212
|
+
const accessToken = json["access_token"];
|
|
1213
|
+
// A sign-up still waiting for its email confirmation is answered with the bare user and no
|
|
1214
|
+
// tokens. That is not a session, so nothing is stored and no SIGNED_IN is emitted.
|
|
1215
|
+
if (typeof accessToken !== "string" || accessToken === "") {
|
|
1216
|
+
const bareUser = json["user"];
|
|
1217
|
+
return { data: { session: null, user: this._parseUser(isJsonObject(bareUser) ? bareUser : json) }, error: null };
|
|
1118
1218
|
}
|
|
1119
|
-
const
|
|
1120
|
-
const user = this._parseUser((json["user"] ?? {}));
|
|
1219
|
+
const user = this._parseUser(objectOrEmpty(json["user"]));
|
|
1121
1220
|
const session = {
|
|
1122
|
-
accessToken
|
|
1221
|
+
accessToken,
|
|
1123
1222
|
tokenType: String(json["token_type"] ?? "bearer"),
|
|
1124
1223
|
expiresIn: Number(json["expires_in"] ?? 3600),
|
|
1125
1224
|
...(json["expires_at"] !== undefined && { expiresAt: Number(json["expires_at"]) }),
|
|
@@ -1136,35 +1235,44 @@ export class AuthClient {
|
|
|
1136
1235
|
...(raw["phone"] !== undefined && { phone: String(raw["phone"]) }),
|
|
1137
1236
|
...(raw["role"] !== undefined && { role: String(raw["role"]) }),
|
|
1138
1237
|
...(raw["is_anonymous"] !== undefined && { isAnonymous: Boolean(raw["is_anonymous"]) }),
|
|
1139
|
-
appMetadata: (raw["app_metadata"]
|
|
1140
|
-
userMetadata: (raw["user_metadata"]
|
|
1238
|
+
appMetadata: objectOrEmpty(raw["app_metadata"]),
|
|
1239
|
+
userMetadata: objectOrEmpty(raw["user_metadata"]),
|
|
1141
1240
|
createdAt: String(raw["created_at"] ?? ""),
|
|
1142
1241
|
updatedAt: String(raw["updated_at"] ?? ""),
|
|
1143
1242
|
};
|
|
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
|
-
}
|
|
1243
|
+
const identities = raw["identities"];
|
|
1244
|
+
if (Array.isArray(identities))
|
|
1245
|
+
user.identities = identities.filter(isJsonObject).map(parseIdentity);
|
|
1246
|
+
const factors = raw["factors"];
|
|
1247
|
+
if (Array.isArray(factors))
|
|
1248
|
+
user.factors = factors.filter(isJsonObject).map(parseFactor);
|
|
1167
1249
|
return user;
|
|
1168
1250
|
}
|
|
1169
1251
|
}
|
|
1252
|
+
function parseIdentity(i) {
|
|
1253
|
+
return {
|
|
1254
|
+
id: String(i["id"] ?? ""),
|
|
1255
|
+
userId: String(i["user_id"] ?? ""),
|
|
1256
|
+
identityData: objectOrEmpty(i["identity_data"]),
|
|
1257
|
+
identityId: String(i["identity_id"] ?? ""),
|
|
1258
|
+
provider: String(i["provider"] ?? ""),
|
|
1259
|
+
createdAt: String(i["created_at"] ?? ""),
|
|
1260
|
+
updatedAt: String(i["updated_at"] ?? ""),
|
|
1261
|
+
...(i["last_sign_in_at"] !== undefined && { lastSignInAt: String(i["last_sign_in_at"]) }),
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
/** A factor as the server lists it. A type or state it leaves out reads as `totp` / `unverified`. */
|
|
1265
|
+
function parseFactor(f) {
|
|
1266
|
+
const factorType = f["factor_type"];
|
|
1267
|
+
const status = f["status"];
|
|
1268
|
+
return {
|
|
1269
|
+
id: String(f["id"] ?? ""),
|
|
1270
|
+
factorType: isFactorType(factorType) ? factorType : "totp",
|
|
1271
|
+
status: isFactorStatus(status) ? status : "unverified",
|
|
1272
|
+
createdAt: String(f["created_at"] ?? ""),
|
|
1273
|
+
updatedAt: String(f["updated_at"] ?? ""),
|
|
1274
|
+
...(f["friendly_name"] !== undefined && { friendlyName: String(f["friendly_name"]) }),
|
|
1275
|
+
...(f["phone"] !== undefined && { phone: String(f["phone"]) }),
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1170
1278
|
//# sourceMappingURL=auth.js.map
|