@netlify/identity 0.1.1 → 0.2.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/README.md +726 -13
- package/dist/index.cjs +636 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +175 -5
- package/dist/index.d.ts +175 -5
- package/dist/index.js +628 -25
- package/dist/index.js.map +1 -1
- package/package.json +10 -2
package/dist/index.js
CHANGED
|
@@ -1,8 +1,40 @@
|
|
|
1
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
+
}) : x)(function(x) {
|
|
4
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
+
});
|
|
7
|
+
|
|
1
8
|
// src/types.ts
|
|
2
9
|
var AUTH_PROVIDERS = ["google", "github", "gitlab", "bitbucket", "facebook", "saml", "email"];
|
|
3
10
|
|
|
4
11
|
// src/environment.ts
|
|
5
12
|
import GoTrue from "gotrue-js";
|
|
13
|
+
|
|
14
|
+
// src/errors.ts
|
|
15
|
+
var AuthError = class _AuthError extends Error {
|
|
16
|
+
constructor(message, status, options) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "AuthError";
|
|
19
|
+
this.status = status;
|
|
20
|
+
if (options && "cause" in options) {
|
|
21
|
+
this.cause = options.cause;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
static from(error) {
|
|
25
|
+
if (error instanceof _AuthError) return error;
|
|
26
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
27
|
+
return new _AuthError(message, void 0, { cause: error });
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
var MissingIdentityError = class extends Error {
|
|
31
|
+
constructor(message = "Netlify Identity is not available.") {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "MissingIdentityError";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/environment.ts
|
|
6
38
|
var IDENTITY_PATH = "/.netlify/identity";
|
|
7
39
|
var goTrueClient = null;
|
|
8
40
|
var cachedApiUrl;
|
|
@@ -18,6 +50,8 @@ var discoverApiUrl = () => {
|
|
|
18
50
|
cachedApiUrl = identityContext.url;
|
|
19
51
|
} else if (globalThis.Netlify?.context?.url) {
|
|
20
52
|
cachedApiUrl = new URL(IDENTITY_PATH, globalThis.Netlify.context.url).href;
|
|
53
|
+
} else if (typeof process !== "undefined" && process.env?.URL) {
|
|
54
|
+
cachedApiUrl = new URL(IDENTITY_PATH, process.env.URL).href;
|
|
21
55
|
}
|
|
22
56
|
}
|
|
23
57
|
return cachedApiUrl ?? null;
|
|
@@ -34,9 +68,14 @@ var getGoTrueClient = () => {
|
|
|
34
68
|
}
|
|
35
69
|
return null;
|
|
36
70
|
}
|
|
37
|
-
goTrueClient = new GoTrue({ APIUrl: apiUrl, setCookie:
|
|
71
|
+
goTrueClient = new GoTrue({ APIUrl: apiUrl, setCookie: false });
|
|
38
72
|
return goTrueClient;
|
|
39
73
|
};
|
|
74
|
+
var getClient = () => {
|
|
75
|
+
const client = getGoTrueClient();
|
|
76
|
+
if (!client) throw new MissingIdentityError();
|
|
77
|
+
return client;
|
|
78
|
+
};
|
|
40
79
|
var getIdentityContext = () => {
|
|
41
80
|
const identityContext = globalThis.netlifyIdentityContext;
|
|
42
81
|
if (identityContext?.url) {
|
|
@@ -48,9 +87,96 @@ var getIdentityContext = () => {
|
|
|
48
87
|
if (globalThis.Netlify?.context?.url) {
|
|
49
88
|
return { url: new URL(IDENTITY_PATH, globalThis.Netlify.context.url).href };
|
|
50
89
|
}
|
|
90
|
+
const siteUrl = typeof process !== "undefined" ? process.env?.URL : void 0;
|
|
91
|
+
if (siteUrl) {
|
|
92
|
+
return { url: new URL(IDENTITY_PATH, siteUrl).href };
|
|
93
|
+
}
|
|
51
94
|
return null;
|
|
52
95
|
};
|
|
53
96
|
|
|
97
|
+
// src/cookies.ts
|
|
98
|
+
var NF_JWT_COOKIE = "nf_jwt";
|
|
99
|
+
var NF_REFRESH_COOKIE = "nf_refresh";
|
|
100
|
+
var getCookie = (name) => {
|
|
101
|
+
if (typeof document === "undefined") return null;
|
|
102
|
+
const match = document.cookie.match(new RegExp(`(?:^|; )${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}=([^;]*)`));
|
|
103
|
+
if (!match) return null;
|
|
104
|
+
try {
|
|
105
|
+
return decodeURIComponent(match[1]);
|
|
106
|
+
} catch {
|
|
107
|
+
return match[1];
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
var setAuthCookies = (cookies, accessToken, refreshToken) => {
|
|
111
|
+
cookies.set({
|
|
112
|
+
name: NF_JWT_COOKIE,
|
|
113
|
+
value: accessToken,
|
|
114
|
+
httpOnly: false,
|
|
115
|
+
secure: true,
|
|
116
|
+
path: "/",
|
|
117
|
+
sameSite: "Lax"
|
|
118
|
+
});
|
|
119
|
+
if (refreshToken) {
|
|
120
|
+
cookies.set({
|
|
121
|
+
name: NF_REFRESH_COOKIE,
|
|
122
|
+
value: refreshToken,
|
|
123
|
+
httpOnly: false,
|
|
124
|
+
secure: true,
|
|
125
|
+
path: "/",
|
|
126
|
+
sameSite: "Lax"
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
var deleteAuthCookies = (cookies) => {
|
|
131
|
+
cookies.delete(NF_JWT_COOKIE);
|
|
132
|
+
cookies.delete(NF_REFRESH_COOKIE);
|
|
133
|
+
};
|
|
134
|
+
var setBrowserAuthCookies = (accessToken, refreshToken) => {
|
|
135
|
+
if (typeof document === "undefined") return;
|
|
136
|
+
document.cookie = `${NF_JWT_COOKIE}=${encodeURIComponent(accessToken)}; path=/; secure; samesite=lax`;
|
|
137
|
+
if (refreshToken) {
|
|
138
|
+
document.cookie = `${NF_REFRESH_COOKIE}=${encodeURIComponent(refreshToken)}; path=/; secure; samesite=lax`;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
var deleteBrowserAuthCookies = () => {
|
|
142
|
+
if (typeof document === "undefined") return;
|
|
143
|
+
document.cookie = `${NF_JWT_COOKIE}=; path=/; secure; samesite=lax; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
|
144
|
+
document.cookie = `${NF_REFRESH_COOKIE}=; path=/; secure; samesite=lax; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
|
145
|
+
};
|
|
146
|
+
var getServerCookie = (name) => {
|
|
147
|
+
const cookies = globalThis.Netlify?.context?.cookies;
|
|
148
|
+
if (!cookies || typeof cookies.get !== "function") return null;
|
|
149
|
+
return cookies.get(name) ?? null;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// src/nextjs.ts
|
|
153
|
+
var nextHeadersFn;
|
|
154
|
+
var triggerNextjsDynamic = () => {
|
|
155
|
+
if (nextHeadersFn === null) return;
|
|
156
|
+
if (nextHeadersFn === void 0) {
|
|
157
|
+
try {
|
|
158
|
+
if (typeof __require === "undefined") {
|
|
159
|
+
nextHeadersFn = null;
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const mod = __require("next/headers");
|
|
163
|
+
nextHeadersFn = mod.headers;
|
|
164
|
+
} catch {
|
|
165
|
+
nextHeadersFn = null;
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const fn = nextHeadersFn;
|
|
170
|
+
if (!fn) return;
|
|
171
|
+
try {
|
|
172
|
+
fn();
|
|
173
|
+
} catch (e) {
|
|
174
|
+
if (e instanceof Error && ("digest" in e || /bail\s*out.*prerende/i.test(e.message))) {
|
|
175
|
+
throw e;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
|
|
54
180
|
// src/user.ts
|
|
55
181
|
var toAuthProvider = (value) => typeof value === "string" && AUTH_PROVIDERS.includes(value) ? value : void 0;
|
|
56
182
|
var toUser = (userData) => {
|
|
@@ -83,36 +209,80 @@ var claimsToUser = (claims) => {
|
|
|
83
209
|
metadata: userMeta
|
|
84
210
|
};
|
|
85
211
|
};
|
|
212
|
+
var hydrating = false;
|
|
213
|
+
var backgroundHydrate = (accessToken) => {
|
|
214
|
+
if (hydrating) return;
|
|
215
|
+
hydrating = true;
|
|
216
|
+
const refreshToken = getCookie(NF_REFRESH_COOKIE) ?? "";
|
|
217
|
+
const decoded = decodeJwtPayload(accessToken);
|
|
218
|
+
const expiresAt = decoded?.exp ?? Math.floor(Date.now() / 1e3) + 3600;
|
|
219
|
+
const expiresIn = Math.max(0, expiresAt - Math.floor(Date.now() / 1e3));
|
|
220
|
+
setTimeout(() => {
|
|
221
|
+
try {
|
|
222
|
+
const client = getClient();
|
|
223
|
+
client.createUser(
|
|
224
|
+
{
|
|
225
|
+
access_token: accessToken,
|
|
226
|
+
token_type: "bearer",
|
|
227
|
+
expires_in: expiresIn,
|
|
228
|
+
expires_at: expiresAt,
|
|
229
|
+
refresh_token: refreshToken
|
|
230
|
+
},
|
|
231
|
+
true
|
|
232
|
+
).catch(() => {
|
|
233
|
+
}).finally(() => {
|
|
234
|
+
hydrating = false;
|
|
235
|
+
});
|
|
236
|
+
} catch {
|
|
237
|
+
hydrating = false;
|
|
238
|
+
}
|
|
239
|
+
}, 0);
|
|
240
|
+
};
|
|
241
|
+
var decodeJwtPayload = (token) => {
|
|
242
|
+
try {
|
|
243
|
+
const parts = token.split(".");
|
|
244
|
+
if (parts.length !== 3) return null;
|
|
245
|
+
const payload = atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"));
|
|
246
|
+
return JSON.parse(payload);
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
};
|
|
86
251
|
var getUser = () => {
|
|
87
252
|
if (isBrowser()) {
|
|
88
253
|
const client = getGoTrueClient();
|
|
89
254
|
const currentUser = client?.currentUser() ?? null;
|
|
90
|
-
if (
|
|
91
|
-
|
|
255
|
+
if (currentUser) {
|
|
256
|
+
const jwt2 = getCookie(NF_JWT_COOKIE);
|
|
257
|
+
if (!jwt2) {
|
|
258
|
+
try {
|
|
259
|
+
currentUser.clearSession();
|
|
260
|
+
} catch {
|
|
261
|
+
}
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
return toUser(currentUser);
|
|
265
|
+
}
|
|
266
|
+
const jwt = getCookie(NF_JWT_COOKIE);
|
|
267
|
+
if (!jwt) return null;
|
|
268
|
+
const claims = decodeJwtPayload(jwt);
|
|
269
|
+
if (!claims) return null;
|
|
270
|
+
backgroundHydrate(jwt);
|
|
271
|
+
return claimsToUser(claims);
|
|
92
272
|
}
|
|
273
|
+
triggerNextjsDynamic();
|
|
93
274
|
const identityContext = globalThis.netlifyIdentityContext;
|
|
94
|
-
if (
|
|
95
|
-
|
|
96
|
-
};
|
|
97
|
-
var isAuthenticated = () => getUser() !== null;
|
|
98
|
-
|
|
99
|
-
// src/errors.ts
|
|
100
|
-
var AuthError = class extends Error {
|
|
101
|
-
constructor(message, status, options) {
|
|
102
|
-
super(message);
|
|
103
|
-
this.name = "AuthError";
|
|
104
|
-
this.status = status;
|
|
105
|
-
if (options && "cause" in options) {
|
|
106
|
-
this.cause = options.cause;
|
|
107
|
-
}
|
|
275
|
+
if (identityContext?.user) {
|
|
276
|
+
return claimsToUser(identityContext.user);
|
|
108
277
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
this.name = "MissingIdentityError";
|
|
278
|
+
const serverJwt = getServerCookie(NF_JWT_COOKIE);
|
|
279
|
+
if (serverJwt) {
|
|
280
|
+
const claims = decodeJwtPayload(serverJwt);
|
|
281
|
+
if (claims) return claimsToUser(claims);
|
|
114
282
|
}
|
|
283
|
+
return null;
|
|
115
284
|
};
|
|
285
|
+
var isAuthenticated = () => getUser() !== null;
|
|
116
286
|
|
|
117
287
|
// src/config.ts
|
|
118
288
|
var getIdentityConfig = () => {
|
|
@@ -122,8 +292,7 @@ var getIdentityConfig = () => {
|
|
|
122
292
|
return getIdentityContext();
|
|
123
293
|
};
|
|
124
294
|
var getSettings = async () => {
|
|
125
|
-
const client =
|
|
126
|
-
if (!client) throw new MissingIdentityError();
|
|
295
|
+
const client = getClient();
|
|
127
296
|
try {
|
|
128
297
|
const raw = await client.settings();
|
|
129
298
|
const external = raw.external ?? {};
|
|
@@ -144,12 +313,446 @@ var getSettings = async () => {
|
|
|
144
313
|
throw new AuthError(err instanceof Error ? err.message : "Failed to fetch identity settings", 502, { cause: err });
|
|
145
314
|
}
|
|
146
315
|
};
|
|
316
|
+
|
|
317
|
+
// src/events.ts
|
|
318
|
+
var AUTH_EVENTS = {
|
|
319
|
+
LOGIN: "login",
|
|
320
|
+
LOGOUT: "logout",
|
|
321
|
+
TOKEN_REFRESH: "token_refresh",
|
|
322
|
+
USER_UPDATED: "user_updated",
|
|
323
|
+
RECOVERY: "recovery"
|
|
324
|
+
};
|
|
325
|
+
var GOTRUE_STORAGE_KEY = "gotrue.user";
|
|
326
|
+
var listeners = /* @__PURE__ */ new Set();
|
|
327
|
+
var emitAuthEvent = (event, user) => {
|
|
328
|
+
for (const listener of listeners) {
|
|
329
|
+
try {
|
|
330
|
+
listener(event, user);
|
|
331
|
+
} catch {
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
var storageListenerAttached = false;
|
|
336
|
+
var attachStorageListener = () => {
|
|
337
|
+
if (storageListenerAttached || !isBrowser()) return;
|
|
338
|
+
storageListenerAttached = true;
|
|
339
|
+
window.addEventListener("storage", (event) => {
|
|
340
|
+
if (event.key !== GOTRUE_STORAGE_KEY) return;
|
|
341
|
+
if (event.newValue) {
|
|
342
|
+
const client = getGoTrueClient();
|
|
343
|
+
const currentUser = client?.currentUser();
|
|
344
|
+
emitAuthEvent(AUTH_EVENTS.LOGIN, currentUser ? toUser(currentUser) : null);
|
|
345
|
+
} else {
|
|
346
|
+
emitAuthEvent(AUTH_EVENTS.LOGOUT, null);
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
};
|
|
350
|
+
var onAuthChange = (callback) => {
|
|
351
|
+
if (!isBrowser()) {
|
|
352
|
+
return () => {
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
listeners.add(callback);
|
|
356
|
+
attachStorageListener();
|
|
357
|
+
return () => {
|
|
358
|
+
listeners.delete(callback);
|
|
359
|
+
};
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
// src/auth.ts
|
|
363
|
+
var getCookies = () => {
|
|
364
|
+
const cookies = globalThis.Netlify?.context?.cookies;
|
|
365
|
+
if (!cookies) {
|
|
366
|
+
throw new AuthError("Server-side auth requires Netlify Functions runtime");
|
|
367
|
+
}
|
|
368
|
+
return cookies;
|
|
369
|
+
};
|
|
370
|
+
var getServerIdentityUrl = () => {
|
|
371
|
+
const ctx = getIdentityContext();
|
|
372
|
+
if (!ctx?.url) {
|
|
373
|
+
throw new AuthError("Could not determine the Identity endpoint URL on the server");
|
|
374
|
+
}
|
|
375
|
+
return ctx.url;
|
|
376
|
+
};
|
|
377
|
+
var persistSession = true;
|
|
378
|
+
var login = async (email, password) => {
|
|
379
|
+
if (!isBrowser()) {
|
|
380
|
+
const identityUrl = getServerIdentityUrl();
|
|
381
|
+
const cookies = getCookies();
|
|
382
|
+
const body = new URLSearchParams({
|
|
383
|
+
grant_type: "password",
|
|
384
|
+
username: email,
|
|
385
|
+
password
|
|
386
|
+
});
|
|
387
|
+
let res;
|
|
388
|
+
try {
|
|
389
|
+
res = await fetch(`${identityUrl}/token`, {
|
|
390
|
+
method: "POST",
|
|
391
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
392
|
+
body: body.toString()
|
|
393
|
+
});
|
|
394
|
+
} catch (error) {
|
|
395
|
+
throw AuthError.from(error);
|
|
396
|
+
}
|
|
397
|
+
if (!res.ok) {
|
|
398
|
+
const errorBody = await res.json().catch(() => ({}));
|
|
399
|
+
throw new AuthError(errorBody.msg || errorBody.error_description || `Login failed (${res.status})`, res.status);
|
|
400
|
+
}
|
|
401
|
+
const data = await res.json();
|
|
402
|
+
const accessToken = data.access_token;
|
|
403
|
+
let userRes;
|
|
404
|
+
try {
|
|
405
|
+
userRes = await fetch(`${identityUrl}/user`, {
|
|
406
|
+
headers: { Authorization: `Bearer ${accessToken}` }
|
|
407
|
+
});
|
|
408
|
+
} catch (error) {
|
|
409
|
+
throw AuthError.from(error);
|
|
410
|
+
}
|
|
411
|
+
if (!userRes.ok) {
|
|
412
|
+
const errorBody = await userRes.json().catch(() => ({}));
|
|
413
|
+
throw new AuthError(errorBody.msg || `Failed to fetch user data (${userRes.status})`, userRes.status);
|
|
414
|
+
}
|
|
415
|
+
const userData = await userRes.json();
|
|
416
|
+
const user = toUser(userData);
|
|
417
|
+
setAuthCookies(cookies, accessToken, data.refresh_token);
|
|
418
|
+
return user;
|
|
419
|
+
}
|
|
420
|
+
const client = getClient();
|
|
421
|
+
try {
|
|
422
|
+
const gotrueUser = await client.login(email, password, persistSession);
|
|
423
|
+
const jwt = await gotrueUser.jwt();
|
|
424
|
+
setBrowserAuthCookies(jwt, gotrueUser.tokenDetails()?.refresh_token);
|
|
425
|
+
const user = toUser(gotrueUser);
|
|
426
|
+
emitAuthEvent(AUTH_EVENTS.LOGIN, user);
|
|
427
|
+
return user;
|
|
428
|
+
} catch (error) {
|
|
429
|
+
throw AuthError.from(error);
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
var signup = async (email, password, data) => {
|
|
433
|
+
if (!isBrowser()) {
|
|
434
|
+
const identityUrl = getServerIdentityUrl();
|
|
435
|
+
const cookies = getCookies();
|
|
436
|
+
let res;
|
|
437
|
+
try {
|
|
438
|
+
res = await fetch(`${identityUrl}/signup`, {
|
|
439
|
+
method: "POST",
|
|
440
|
+
headers: { "Content-Type": "application/json" },
|
|
441
|
+
body: JSON.stringify({ email, password, data })
|
|
442
|
+
});
|
|
443
|
+
} catch (error) {
|
|
444
|
+
throw AuthError.from(error);
|
|
445
|
+
}
|
|
446
|
+
if (!res.ok) {
|
|
447
|
+
const errorBody = await res.json().catch(() => ({}));
|
|
448
|
+
throw new AuthError(errorBody.msg || `Signup failed (${res.status})`, res.status);
|
|
449
|
+
}
|
|
450
|
+
const responseData = await res.json();
|
|
451
|
+
const user = toUser(responseData);
|
|
452
|
+
if (responseData.confirmed_at) {
|
|
453
|
+
const accessToken = responseData.access_token;
|
|
454
|
+
if (accessToken) {
|
|
455
|
+
setAuthCookies(cookies, accessToken, responseData.refresh_token);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return user;
|
|
459
|
+
}
|
|
460
|
+
const client = getClient();
|
|
461
|
+
try {
|
|
462
|
+
const response = await client.signup(email, password, data);
|
|
463
|
+
const user = toUser(response);
|
|
464
|
+
if (response.confirmed_at) {
|
|
465
|
+
const jwt = await response.jwt?.();
|
|
466
|
+
if (jwt) {
|
|
467
|
+
const refreshToken = response.tokenDetails?.()?.refresh_token;
|
|
468
|
+
setBrowserAuthCookies(jwt, refreshToken);
|
|
469
|
+
}
|
|
470
|
+
emitAuthEvent(AUTH_EVENTS.LOGIN, user);
|
|
471
|
+
}
|
|
472
|
+
return user;
|
|
473
|
+
} catch (error) {
|
|
474
|
+
throw AuthError.from(error);
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
var logout = async () => {
|
|
478
|
+
if (!isBrowser()) {
|
|
479
|
+
const identityUrl = getServerIdentityUrl();
|
|
480
|
+
const cookies = getCookies();
|
|
481
|
+
const jwt = cookies.get(NF_JWT_COOKIE);
|
|
482
|
+
if (jwt) {
|
|
483
|
+
try {
|
|
484
|
+
await fetch(`${identityUrl}/logout`, {
|
|
485
|
+
method: "POST",
|
|
486
|
+
headers: { Authorization: `Bearer ${jwt}` }
|
|
487
|
+
});
|
|
488
|
+
} catch {
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
deleteAuthCookies(cookies);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
const client = getClient();
|
|
495
|
+
try {
|
|
496
|
+
const currentUser = client.currentUser();
|
|
497
|
+
if (currentUser) {
|
|
498
|
+
await currentUser.logout();
|
|
499
|
+
}
|
|
500
|
+
deleteBrowserAuthCookies();
|
|
501
|
+
emitAuthEvent(AUTH_EVENTS.LOGOUT, null);
|
|
502
|
+
} catch (error) {
|
|
503
|
+
throw AuthError.from(error);
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
var oauthLogin = (provider) => {
|
|
507
|
+
if (!isBrowser()) {
|
|
508
|
+
throw new AuthError("oauthLogin() is only available in the browser");
|
|
509
|
+
}
|
|
510
|
+
const client = getClient();
|
|
511
|
+
window.location.href = client.loginExternalUrl(provider);
|
|
512
|
+
throw new AuthError("Redirecting to OAuth provider");
|
|
513
|
+
};
|
|
514
|
+
var handleAuthCallback = async () => {
|
|
515
|
+
if (!isBrowser()) return null;
|
|
516
|
+
const hash = window.location.hash.substring(1);
|
|
517
|
+
if (!hash) return null;
|
|
518
|
+
const client = getClient();
|
|
519
|
+
const params = new URLSearchParams(hash);
|
|
520
|
+
try {
|
|
521
|
+
const accessToken = params.get("access_token");
|
|
522
|
+
if (accessToken) return await handleOAuthCallback(client, params, accessToken);
|
|
523
|
+
const confirmationToken = params.get("confirmation_token");
|
|
524
|
+
if (confirmationToken) return await handleConfirmationCallback(client, confirmationToken);
|
|
525
|
+
const recoveryToken = params.get("recovery_token");
|
|
526
|
+
if (recoveryToken) return await handleRecoveryCallback(client, recoveryToken);
|
|
527
|
+
const inviteToken = params.get("invite_token");
|
|
528
|
+
if (inviteToken) return handleInviteCallback(inviteToken);
|
|
529
|
+
const emailChangeToken = params.get("email_change_token");
|
|
530
|
+
if (emailChangeToken) return await handleEmailChangeCallback(client, emailChangeToken);
|
|
531
|
+
return null;
|
|
532
|
+
} catch (error) {
|
|
533
|
+
if (error instanceof AuthError) throw error;
|
|
534
|
+
throw AuthError.from(error);
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
var handleOAuthCallback = async (client, params, accessToken) => {
|
|
538
|
+
const refreshToken = params.get("refresh_token") ?? "";
|
|
539
|
+
const expiresIn = parseInt(params.get("expires_in") ?? "", 10);
|
|
540
|
+
const expiresAt = parseInt(params.get("expires_at") ?? "", 10);
|
|
541
|
+
const gotrueUser = await client.createUser(
|
|
542
|
+
{
|
|
543
|
+
access_token: accessToken,
|
|
544
|
+
token_type: params.get("token_type") ?? "bearer",
|
|
545
|
+
expires_in: isFinite(expiresIn) ? expiresIn : 3600,
|
|
546
|
+
expires_at: isFinite(expiresAt) ? expiresAt : Math.floor(Date.now() / 1e3) + 3600,
|
|
547
|
+
refresh_token: refreshToken
|
|
548
|
+
},
|
|
549
|
+
persistSession
|
|
550
|
+
);
|
|
551
|
+
setBrowserAuthCookies(accessToken, refreshToken || void 0);
|
|
552
|
+
const user = toUser(gotrueUser);
|
|
553
|
+
clearHash();
|
|
554
|
+
emitAuthEvent(AUTH_EVENTS.LOGIN, user);
|
|
555
|
+
return { type: "oauth", user };
|
|
556
|
+
};
|
|
557
|
+
var handleConfirmationCallback = async (client, token) => {
|
|
558
|
+
const gotrueUser = await client.confirm(token, persistSession);
|
|
559
|
+
const jwt = await gotrueUser.jwt();
|
|
560
|
+
setBrowserAuthCookies(jwt, gotrueUser.tokenDetails()?.refresh_token);
|
|
561
|
+
const user = toUser(gotrueUser);
|
|
562
|
+
clearHash();
|
|
563
|
+
emitAuthEvent(AUTH_EVENTS.LOGIN, user);
|
|
564
|
+
return { type: "confirmation", user };
|
|
565
|
+
};
|
|
566
|
+
var handleRecoveryCallback = async (client, token) => {
|
|
567
|
+
const gotrueUser = await client.recover(token, persistSession);
|
|
568
|
+
const jwt = await gotrueUser.jwt();
|
|
569
|
+
setBrowserAuthCookies(jwt, gotrueUser.tokenDetails()?.refresh_token);
|
|
570
|
+
const user = toUser(gotrueUser);
|
|
571
|
+
clearHash();
|
|
572
|
+
emitAuthEvent(AUTH_EVENTS.RECOVERY, user);
|
|
573
|
+
return { type: "recovery", user };
|
|
574
|
+
};
|
|
575
|
+
var handleInviteCallback = (token) => {
|
|
576
|
+
clearHash();
|
|
577
|
+
return { type: "invite", user: null, token };
|
|
578
|
+
};
|
|
579
|
+
var handleEmailChangeCallback = async (client, emailChangeToken) => {
|
|
580
|
+
const currentUser = client.currentUser();
|
|
581
|
+
if (!currentUser) {
|
|
582
|
+
throw new AuthError("Email change verification requires an active browser session");
|
|
583
|
+
}
|
|
584
|
+
const jwt = await currentUser.jwt();
|
|
585
|
+
const identityUrl = `${window.location.origin}${IDENTITY_PATH}`;
|
|
586
|
+
const emailChangeRes = await fetch(`${identityUrl}/user`, {
|
|
587
|
+
method: "PUT",
|
|
588
|
+
headers: {
|
|
589
|
+
"Content-Type": "application/json",
|
|
590
|
+
Authorization: `Bearer ${jwt}`
|
|
591
|
+
},
|
|
592
|
+
body: JSON.stringify({ email_change_token: emailChangeToken })
|
|
593
|
+
});
|
|
594
|
+
if (!emailChangeRes.ok) {
|
|
595
|
+
const errorBody = await emailChangeRes.json().catch(() => ({}));
|
|
596
|
+
throw new AuthError(
|
|
597
|
+
errorBody.msg || `Email change verification failed (${emailChangeRes.status})`,
|
|
598
|
+
emailChangeRes.status
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
const emailChangeData = await emailChangeRes.json();
|
|
602
|
+
const user = toUser(emailChangeData);
|
|
603
|
+
clearHash();
|
|
604
|
+
emitAuthEvent(AUTH_EVENTS.USER_UPDATED, user);
|
|
605
|
+
return { type: "email_change", user };
|
|
606
|
+
};
|
|
607
|
+
var clearHash = () => {
|
|
608
|
+
history.replaceState(null, "", window.location.pathname + window.location.search);
|
|
609
|
+
};
|
|
610
|
+
var hydrateSession = async () => {
|
|
611
|
+
if (!isBrowser()) return null;
|
|
612
|
+
const client = getClient();
|
|
613
|
+
const currentUser = client.currentUser();
|
|
614
|
+
if (currentUser) return toUser(currentUser);
|
|
615
|
+
const accessToken = getCookie(NF_JWT_COOKIE);
|
|
616
|
+
if (!accessToken) return null;
|
|
617
|
+
const refreshToken = getCookie(NF_REFRESH_COOKIE) ?? "";
|
|
618
|
+
const decoded = decodeJwtPayload(accessToken);
|
|
619
|
+
const expiresAt = decoded?.exp ?? Math.floor(Date.now() / 1e3) + 3600;
|
|
620
|
+
const expiresIn = Math.max(0, expiresAt - Math.floor(Date.now() / 1e3));
|
|
621
|
+
let gotrueUser;
|
|
622
|
+
try {
|
|
623
|
+
gotrueUser = await client.createUser(
|
|
624
|
+
{
|
|
625
|
+
access_token: accessToken,
|
|
626
|
+
token_type: "bearer",
|
|
627
|
+
expires_in: expiresIn,
|
|
628
|
+
expires_at: expiresAt,
|
|
629
|
+
refresh_token: refreshToken
|
|
630
|
+
},
|
|
631
|
+
persistSession
|
|
632
|
+
);
|
|
633
|
+
} catch {
|
|
634
|
+
deleteBrowserAuthCookies();
|
|
635
|
+
return null;
|
|
636
|
+
}
|
|
637
|
+
const user = toUser(gotrueUser);
|
|
638
|
+
emitAuthEvent(AUTH_EVENTS.LOGIN, user);
|
|
639
|
+
return user;
|
|
640
|
+
};
|
|
641
|
+
|
|
642
|
+
// src/account.ts
|
|
643
|
+
var resolveCurrentUser = async () => {
|
|
644
|
+
const client = getClient();
|
|
645
|
+
let currentUser = client.currentUser();
|
|
646
|
+
if (!currentUser && isBrowser()) {
|
|
647
|
+
try {
|
|
648
|
+
await hydrateSession();
|
|
649
|
+
} catch {
|
|
650
|
+
}
|
|
651
|
+
currentUser = client.currentUser();
|
|
652
|
+
}
|
|
653
|
+
if (!currentUser) throw new AuthError("No user is currently logged in");
|
|
654
|
+
return currentUser;
|
|
655
|
+
};
|
|
656
|
+
var requestPasswordRecovery = async (email) => {
|
|
657
|
+
const client = getClient();
|
|
658
|
+
try {
|
|
659
|
+
await client.requestPasswordRecovery(email);
|
|
660
|
+
} catch (error) {
|
|
661
|
+
throw AuthError.from(error);
|
|
662
|
+
}
|
|
663
|
+
};
|
|
664
|
+
var recoverPassword = async (token, newPassword) => {
|
|
665
|
+
const client = getClient();
|
|
666
|
+
try {
|
|
667
|
+
const gotrueUser = await client.recover(token, persistSession);
|
|
668
|
+
const updatedUser = await gotrueUser.update({ password: newPassword });
|
|
669
|
+
const user = toUser(updatedUser);
|
|
670
|
+
emitAuthEvent(AUTH_EVENTS.LOGIN, user);
|
|
671
|
+
return user;
|
|
672
|
+
} catch (error) {
|
|
673
|
+
throw AuthError.from(error);
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
var confirmEmail = async (token) => {
|
|
677
|
+
const client = getClient();
|
|
678
|
+
try {
|
|
679
|
+
const gotrueUser = await client.confirm(token, persistSession);
|
|
680
|
+
const user = toUser(gotrueUser);
|
|
681
|
+
emitAuthEvent(AUTH_EVENTS.LOGIN, user);
|
|
682
|
+
return user;
|
|
683
|
+
} catch (error) {
|
|
684
|
+
throw AuthError.from(error);
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
var acceptInvite = async (token, password) => {
|
|
688
|
+
const client = getClient();
|
|
689
|
+
try {
|
|
690
|
+
const gotrueUser = await client.acceptInvite(token, password, persistSession);
|
|
691
|
+
const user = toUser(gotrueUser);
|
|
692
|
+
emitAuthEvent(AUTH_EVENTS.LOGIN, user);
|
|
693
|
+
return user;
|
|
694
|
+
} catch (error) {
|
|
695
|
+
throw AuthError.from(error);
|
|
696
|
+
}
|
|
697
|
+
};
|
|
698
|
+
var verifyEmailChange = async (token) => {
|
|
699
|
+
if (!isBrowser()) throw new AuthError("verifyEmailChange() is only available in the browser");
|
|
700
|
+
const currentUser = await resolveCurrentUser();
|
|
701
|
+
try {
|
|
702
|
+
const jwt = await currentUser.jwt();
|
|
703
|
+
const identityUrl = `${window.location.origin}${IDENTITY_PATH}`;
|
|
704
|
+
const res = await fetch(`${identityUrl}/user`, {
|
|
705
|
+
method: "PUT",
|
|
706
|
+
headers: {
|
|
707
|
+
"Content-Type": "application/json",
|
|
708
|
+
Authorization: `Bearer ${jwt}`
|
|
709
|
+
},
|
|
710
|
+
body: JSON.stringify({ email_change_token: token })
|
|
711
|
+
});
|
|
712
|
+
if (!res.ok) {
|
|
713
|
+
const errorBody = await res.json().catch(() => ({}));
|
|
714
|
+
throw new AuthError(errorBody.msg || `Email change verification failed (${res.status})`, res.status);
|
|
715
|
+
}
|
|
716
|
+
const userData = await res.json();
|
|
717
|
+
const user = toUser(userData);
|
|
718
|
+
emitAuthEvent(AUTH_EVENTS.USER_UPDATED, user);
|
|
719
|
+
return user;
|
|
720
|
+
} catch (error) {
|
|
721
|
+
if (error instanceof AuthError) throw error;
|
|
722
|
+
throw AuthError.from(error);
|
|
723
|
+
}
|
|
724
|
+
};
|
|
725
|
+
var updateUser = async (updates) => {
|
|
726
|
+
const currentUser = await resolveCurrentUser();
|
|
727
|
+
try {
|
|
728
|
+
const updatedUser = await currentUser.update(updates);
|
|
729
|
+
const user = toUser(updatedUser);
|
|
730
|
+
emitAuthEvent(AUTH_EVENTS.USER_UPDATED, user);
|
|
731
|
+
return user;
|
|
732
|
+
} catch (error) {
|
|
733
|
+
throw AuthError.from(error);
|
|
734
|
+
}
|
|
735
|
+
};
|
|
147
736
|
export {
|
|
737
|
+
AUTH_EVENTS,
|
|
148
738
|
AuthError,
|
|
149
739
|
MissingIdentityError,
|
|
740
|
+
acceptInvite,
|
|
741
|
+
confirmEmail,
|
|
150
742
|
getIdentityConfig,
|
|
151
743
|
getSettings,
|
|
152
744
|
getUser,
|
|
153
|
-
|
|
745
|
+
handleAuthCallback,
|
|
746
|
+
hydrateSession,
|
|
747
|
+
isAuthenticated,
|
|
748
|
+
login,
|
|
749
|
+
logout,
|
|
750
|
+
oauthLogin,
|
|
751
|
+
onAuthChange,
|
|
752
|
+
recoverPassword,
|
|
753
|
+
requestPasswordRecovery,
|
|
754
|
+
signup,
|
|
755
|
+
updateUser,
|
|
756
|
+
verifyEmailChange
|
|
154
757
|
};
|
|
155
758
|
//# sourceMappingURL=index.js.map
|