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