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