@azlib/identity 0.2.0 → 0.3.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.
Files changed (80) hide show
  1. package/README.md +149 -40
  2. package/dist/cookie-header-DptIxRmW.mjs +76 -0
  3. package/dist/cookie-header-DptIxRmW.mjs.map +1 -0
  4. package/dist/cookie-header-Dqd5k5BU.cjs +115 -0
  5. package/dist/cookie-header-LFWHKQ04.d.cts +86 -0
  6. package/dist/cookie-header-LFWHKQ04.d.cts.map +1 -0
  7. package/dist/cookie-header-LFWHKQ04.d.mts +86 -0
  8. package/dist/cookie-header-LFWHKQ04.d.mts.map +1 -0
  9. package/dist/{errors-C2xZAatu.d.cts → errors-0Zh7EG06.d.cts} +4 -3
  10. package/dist/errors-0Zh7EG06.d.cts.map +1 -0
  11. package/dist/{errors-BGMwaW5s.d.mts → errors-DVDEUk9-.d.mts} +4 -3
  12. package/dist/errors-DVDEUk9-.d.mts.map +1 -0
  13. package/dist/express.cjs +34 -0
  14. package/dist/express.d.cts +5 -6
  15. package/dist/express.d.cts.map +1 -1
  16. package/dist/express.d.mts +5 -6
  17. package/dist/express.d.mts.map +1 -1
  18. package/dist/express.mjs +34 -1
  19. package/dist/express.mjs.map +1 -1
  20. package/dist/{identity-Bz9RDOvT.mjs → identity-D0qyca_c.mjs} +37 -3
  21. package/dist/identity-D0qyca_c.mjs.map +1 -0
  22. package/dist/{identity-4eP45YIP.cjs → identity-Yz1BVkrM.cjs} +46 -0
  23. package/dist/{identity-router-DBL20UWT.d.mts → identity-router-BiratpJR.d.mts} +22 -6
  24. package/dist/identity-router-BiratpJR.d.mts.map +1 -0
  25. package/dist/{identity-router-Dib30Waj.d.cts → identity-router-D4oqYI60.d.cts} +22 -6
  26. package/dist/identity-router-D4oqYI60.d.cts.map +1 -0
  27. package/dist/{identity-service-CLzKx8Z7.d.cts → identity-service-DE0Ffguz.d.cts} +3 -4
  28. package/dist/identity-service-DE0Ffguz.d.cts.map +1 -0
  29. package/dist/{identity-service-B9zrvE9z.d.mts → identity-service-JtsoA6lv.d.mts} +3 -4
  30. package/dist/identity-service-JtsoA6lv.d.mts.map +1 -0
  31. package/dist/identity-store-BRRahxcS.d.cts.map +1 -1
  32. package/dist/identity-store-BRRahxcS.d.mts.map +1 -1
  33. package/dist/index-CsYqHPvK.d.cts +54 -0
  34. package/dist/index-CsYqHPvK.d.cts.map +1 -0
  35. package/dist/index-LhSdoWEP.d.mts +54 -0
  36. package/dist/index-LhSdoWEP.d.mts.map +1 -0
  37. package/dist/index.cjs +11 -1
  38. package/dist/index.d.cts +4 -3
  39. package/dist/index.d.mts +4 -3
  40. package/dist/index.mjs +3 -2
  41. package/dist/logger-CcCHJVVe.mjs.map +1 -1
  42. package/dist/nestjs.cjs +4 -5
  43. package/dist/nestjs.d.cts +3 -4
  44. package/dist/nestjs.d.cts.map +1 -1
  45. package/dist/nestjs.d.mts +3 -4
  46. package/dist/nestjs.d.mts.map +1 -1
  47. package/dist/nestjs.mjs +4 -5
  48. package/dist/nestjs.mjs.map +1 -1
  49. package/dist/next.cjs +285 -0
  50. package/dist/next.d.cts +58 -0
  51. package/dist/next.d.cts.map +1 -0
  52. package/dist/next.d.mts +58 -0
  53. package/dist/next.d.mts.map +1 -0
  54. package/dist/next.mjs +274 -0
  55. package/dist/next.mjs.map +1 -0
  56. package/dist/node.cjs +18 -19
  57. package/dist/node.d.cts +5 -5
  58. package/dist/node.d.cts.map +1 -1
  59. package/dist/node.d.mts +5 -5
  60. package/dist/node.d.mts.map +1 -1
  61. package/dist/node.mjs +10 -20
  62. package/dist/node.mjs.map +1 -1
  63. package/dist/test-utils.d.cts +0 -1
  64. package/dist/test-utils.d.cts.map +1 -1
  65. package/dist/test-utils.d.mts +0 -1
  66. package/dist/test-utils.d.mts.map +1 -1
  67. package/dist/test-utils.mjs.map +1 -1
  68. package/package.json +18 -18
  69. package/schema/model.ts +110 -22
  70. package/dist/errors-BGMwaW5s.d.mts.map +0 -1
  71. package/dist/errors-C2xZAatu.d.cts.map +0 -1
  72. package/dist/identity-Bz9RDOvT.mjs.map +0 -1
  73. package/dist/identity-router-DBL20UWT.d.mts.map +0 -1
  74. package/dist/identity-router-Dib30Waj.d.cts.map +0 -1
  75. package/dist/identity-service-B9zrvE9z.d.mts.map +0 -1
  76. package/dist/identity-service-CLzKx8Z7.d.cts.map +0 -1
  77. package/dist/index-CpufYgyn.d.cts +0 -30
  78. package/dist/index-CpufYgyn.d.cts.map +0 -1
  79. package/dist/index-CpufYgyn.d.mts +0 -30
  80. package/dist/index-CpufYgyn.d.mts.map +0 -1
package/dist/next.mjs ADDED
@@ -0,0 +1,274 @@
1
+ import { a as IdentityError, s as InvalidTokenError, t as AccountUnavailableError } from "./errors-CEmnZxIn.mjs";
2
+ import { a as readCookieValue, i as parseCookieHeader, n as DEFAULT_REFRESH_COOKIE, o as resolveCookieAttributes, r as hasIdentityCookies, s as resolveCookieNames, t as DEFAULT_ACCESS_COOKIE } from "./cookie-header-DptIxRmW.mjs";
3
+ //#region core/next/cookies.ts
4
+ function maxAgeSeconds(expiresAt, now) {
5
+ return Math.max(0, Math.floor((expiresAt.getTime() - now.getTime()) / 1e3));
6
+ }
7
+ function writeAttributes(options, expiresAt, now) {
8
+ const attrs = resolveCookieAttributes(options);
9
+ return {
10
+ httpOnly: attrs.httpOnly,
11
+ secure: attrs.secure,
12
+ sameSite: attrs.sameSite,
13
+ path: attrs.path,
14
+ domain: attrs.domain,
15
+ maxAge: maxAgeSeconds(expiresAt, now),
16
+ expires: expiresAt
17
+ };
18
+ }
19
+ /**
20
+ * Writes the access and refresh tokens as HttpOnly cookies.
21
+ * `maxAge` is in seconds (Next.js / `Set-Cookie` convention).
22
+ */
23
+ function applyAuthCookies(cookies, tokens, options = {}, now = /* @__PURE__ */ new Date()) {
24
+ const names = resolveCookieNames(options);
25
+ cookies.set(names.access, tokens.accessToken, writeAttributes(options, tokens.accessTokenExpiresAt, now));
26
+ cookies.set(names.refresh, tokens.refreshToken, writeAttributes(options, tokens.refreshTokenExpiresAt, now));
27
+ }
28
+ /** Clears both identity cookies (logout or failed session). */
29
+ function clearAuthCookies(cookies, options = {}) {
30
+ const names = resolveCookieNames(options);
31
+ const attrs = resolveCookieAttributes(options);
32
+ const deleteOpts = {
33
+ path: attrs.path,
34
+ domain: attrs.domain
35
+ };
36
+ cookies.delete(names.access, deleteOpts);
37
+ cookies.delete(names.refresh, deleteOpts);
38
+ }
39
+ /**
40
+ * In-memory {@link CookieStore} for tests and Fetch-based Route Handlers.
41
+ * Not for production browser storage.
42
+ */
43
+ function createMemoryCookieStore(initial = {}) {
44
+ const values = new Map(Object.entries(initial).filter(([, value]) => value.length > 0));
45
+ return {
46
+ get(name) {
47
+ const value = values.get(name);
48
+ return value === void 0 ? void 0 : { value };
49
+ },
50
+ set(name, value) {
51
+ if (value.length === 0) {
52
+ values.delete(name);
53
+ return;
54
+ }
55
+ values.set(name, value);
56
+ },
57
+ delete(name) {
58
+ values.delete(name);
59
+ }
60
+ };
61
+ }
62
+ /** Builds a cookie store seeded from an incoming `Cookie` header. */
63
+ function cookieStoreFromHeader(header) {
64
+ return createMemoryCookieStore(Object.fromEntries(parseCookieHeader(header)));
65
+ }
66
+ //#endregion
67
+ //#region core/next/session.ts
68
+ /**
69
+ * Resolves the current principal from identity cookies.
70
+ *
71
+ * - Valid access cookie → `service.authenticate`.
72
+ * - Expired/missing access + refresh cookie → `service.refresh` and rotate cookies.
73
+ * - Failure → clear cookies and return `null` (degrade to logged out).
74
+ *
75
+ * Call this where cookies can be written (Server Actions, Route Handlers). Refresh
76
+ * rotates the refresh token; skipping the write would invalidate the browser session.
77
+ */
78
+ async function getIdentity(service, cookies, options = {}) {
79
+ const names = resolveCookieNames(options);
80
+ const access = readCookieValue(cookies, names.access);
81
+ const refresh = readCookieValue(cookies, names.refresh);
82
+ if (access) try {
83
+ return await service.authenticate(access);
84
+ } catch (error) {
85
+ if (error instanceof AccountUnavailableError) {
86
+ clearAuthCookies(cookies, options);
87
+ return null;
88
+ }
89
+ if (!(error instanceof InvalidTokenError)) throw error;
90
+ }
91
+ if (!refresh) {
92
+ if (access) clearAuthCookies(cookies, options);
93
+ return null;
94
+ }
95
+ try {
96
+ const result = await service.refresh(refresh);
97
+ applyAuthCookies(cookies, result.tokens, options);
98
+ return result.user;
99
+ } catch (error) {
100
+ clearAuthCookies(cookies, options);
101
+ if (error instanceof InvalidTokenError || error instanceof AccountUnavailableError) return null;
102
+ throw error;
103
+ }
104
+ }
105
+ //#endregion
106
+ //#region core/next/handlers.ts
107
+ function json(body, status, cookies) {
108
+ const headers = new Headers({ "content-type": "application/json" });
109
+ if (cookies) for (const header of cookies.headers) headers.append("set-cookie", header);
110
+ return new Response(JSON.stringify(body), {
111
+ status,
112
+ headers
113
+ });
114
+ }
115
+ function errorResponse(error) {
116
+ if (error instanceof IdentityError) return json({
117
+ code: error.code,
118
+ message: error.message
119
+ }, error.statusCode);
120
+ throw error;
121
+ }
122
+ function serializeSetCookie(cookie) {
123
+ const parts = [`${cookie.name}=${encodeURIComponent(cookie.value)}`];
124
+ const opts = cookie.options ?? {};
125
+ if (opts.maxAge !== void 0) parts.push(`Max-Age=${Math.max(0, Math.floor(opts.maxAge))}`);
126
+ if (opts.expires) parts.push(`Expires=${opts.expires.toUTCString()}`);
127
+ parts.push(`Path=${opts.path ?? "/"}`);
128
+ if (opts.domain) parts.push(`Domain=${opts.domain}`);
129
+ if (opts.httpOnly !== false) parts.push("HttpOnly");
130
+ if (opts.secure) parts.push("Secure");
131
+ const sameSite = opts.sameSite ?? "lax";
132
+ parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`);
133
+ return parts.join("; ");
134
+ }
135
+ function recordingStore(header) {
136
+ const inner = cookieStoreFromHeader(header);
137
+ const writes = [];
138
+ const deleted = [];
139
+ const expired = /* @__PURE__ */ new Date(0);
140
+ return {
141
+ store: {
142
+ get: inner.get.bind(inner),
143
+ set(name, value, options) {
144
+ inner.set(name, value, options);
145
+ writes.push({
146
+ name,
147
+ value,
148
+ options
149
+ });
150
+ },
151
+ delete(name, options) {
152
+ inner.delete(name, options);
153
+ deleted.push({
154
+ name,
155
+ value: "",
156
+ options: {
157
+ ...options,
158
+ maxAge: 0,
159
+ expires: expired
160
+ }
161
+ });
162
+ }
163
+ },
164
+ headers() {
165
+ return [...writes.map(serializeSetCookie), ...deleted.map(serializeSetCookie)];
166
+ }
167
+ };
168
+ }
169
+ async function readJsonBody(request) {
170
+ try {
171
+ const body = await request.json();
172
+ if (typeof body === "object" && body !== null && !Array.isArray(body)) return body;
173
+ return {};
174
+ } catch {
175
+ return {};
176
+ }
177
+ }
178
+ function actionFromUrl(url, prefix) {
179
+ const pathname = new URL(url).pathname.replace(/\/+$/, "");
180
+ const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, "");
181
+ if (normalizedPrefix) {
182
+ const marker = `/${normalizedPrefix}/`;
183
+ const idx = pathname.lastIndexOf(marker);
184
+ if (idx >= 0) return pathname.slice(idx + marker.length);
185
+ }
186
+ const slash = pathname.lastIndexOf("/");
187
+ return slash >= 0 ? pathname.slice(slash + 1) : pathname;
188
+ }
189
+ function createIdentityHandlers(service, options = {}) {
190
+ const prefix = options.prefix ?? "";
191
+ const names = resolveCookieNames(options);
192
+ const login = async (request) => {
193
+ try {
194
+ const body = await readJsonBody(request);
195
+ const email = typeof body.email === "string" ? body.email : "";
196
+ const password = typeof body.password === "string" ? body.password : "";
197
+ const result = await service.login({
198
+ email,
199
+ password
200
+ });
201
+ if ("kind" in result) return json(result, 200);
202
+ const recorded = recordingStore(request.headers.get("cookie"));
203
+ applyAuthCookies(recorded.store, result.tokens, options);
204
+ return json({ user: result.user }, 200, { headers: recorded.headers() });
205
+ } catch (error) {
206
+ return errorResponse(error);
207
+ }
208
+ };
209
+ const logout = async (request) => {
210
+ try {
211
+ const recorded = recordingStore(request.headers.get("cookie"));
212
+ const refresh = readCookieValue(recorded.store, names.refresh);
213
+ if (refresh) await service.logout(refresh);
214
+ clearAuthCookies(recorded.store, options);
215
+ return json({ ok: true }, 200, { headers: recorded.headers() });
216
+ } catch (error) {
217
+ return errorResponse(error);
218
+ }
219
+ };
220
+ const refresh = async (request) => {
221
+ try {
222
+ const recorded = recordingStore(request.headers.get("cookie"));
223
+ const token = readCookieValue(recorded.store, names.refresh);
224
+ if (!token) throw new InvalidTokenError();
225
+ const result = await service.refresh(token);
226
+ applyAuthCookies(recorded.store, result.tokens, options);
227
+ return json({ user: result.user }, 200, { headers: recorded.headers() });
228
+ } catch (error) {
229
+ const recorded = recordingStore(request.headers.get("cookie"));
230
+ clearAuthCookies(recorded.store, options);
231
+ if (error instanceof IdentityError) return json({
232
+ code: error.code,
233
+ message: error.message
234
+ }, error.statusCode, { headers: recorded.headers() });
235
+ throw error;
236
+ }
237
+ };
238
+ const me = async (request) => {
239
+ try {
240
+ const recorded = recordingStore(request.headers.get("cookie"));
241
+ const identity = await getIdentity(service, recorded.store, options);
242
+ if (!identity) return json({
243
+ code: "identity/unauthenticated",
244
+ message: "Authentication is required."
245
+ }, 401, { headers: recorded.headers() });
246
+ return json({ user: identity }, 200, { headers: recorded.headers() });
247
+ } catch (error) {
248
+ return errorResponse(error);
249
+ }
250
+ };
251
+ const dispatch = async (request) => {
252
+ const action = actionFromUrl(request.url, prefix);
253
+ const method = request.method.toUpperCase();
254
+ if (method === "POST" && action === "login") return login(request);
255
+ if (method === "POST" && action === "logout") return logout(request);
256
+ if (method === "POST" && action === "refresh") return refresh(request);
257
+ if (method === "GET" && action === "me") return me(request);
258
+ return json({
259
+ code: "identity/not-found",
260
+ message: "Not found."
261
+ }, 404);
262
+ };
263
+ return {
264
+ login,
265
+ logout,
266
+ refresh,
267
+ me,
268
+ dispatch
269
+ };
270
+ }
271
+ //#endregion
272
+ export { DEFAULT_ACCESS_COOKIE, DEFAULT_REFRESH_COOKIE, applyAuthCookies, clearAuthCookies, cookieStoreFromHeader, createIdentityHandlers, createMemoryCookieStore, getIdentity, hasIdentityCookies, parseCookieHeader, readCookieValue, resolveCookieAttributes, resolveCookieNames };
273
+
274
+ //# sourceMappingURL=next.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.mjs","names":[],"sources":["../core/next/cookies.ts","../core/next/session.ts","../core/next/handlers.ts"],"sourcesContent":["import {\n parseCookieHeader,\n resolveCookieAttributes,\n resolveCookieNames,\n type CookieStore,\n type CookieWriter,\n type IdentityCookieOptions,\n} from \"../cookie-header\";\nimport type { AuthTokens } from \"../types\";\n\nexport type { CookieStore, CookieWriter };\n\nfunction maxAgeSeconds(expiresAt: Date, now: Date): number {\n return Math.max(0, Math.floor((expiresAt.getTime() - now.getTime()) / 1000));\n}\n\nfunction writeAttributes(\n options: IdentityCookieOptions,\n expiresAt: Date,\n now: Date,\n) {\n const attrs = resolveCookieAttributes(options);\n return {\n httpOnly: attrs.httpOnly,\n secure: attrs.secure,\n sameSite: attrs.sameSite,\n path: attrs.path,\n domain: attrs.domain,\n maxAge: maxAgeSeconds(expiresAt, now),\n expires: expiresAt,\n };\n}\n\n/**\n * Writes the access and refresh tokens as HttpOnly cookies.\n * `maxAge` is in seconds (Next.js / `Set-Cookie` convention).\n */\nexport function applyAuthCookies(\n cookies: CookieWriter,\n tokens: AuthTokens,\n options: IdentityCookieOptions = {},\n now: Date = new Date(),\n): void {\n const names = resolveCookieNames(options);\n cookies.set(\n names.access,\n tokens.accessToken,\n writeAttributes(options, tokens.accessTokenExpiresAt, now),\n );\n cookies.set(\n names.refresh,\n tokens.refreshToken,\n writeAttributes(options, tokens.refreshTokenExpiresAt, now),\n );\n}\n\n/** Clears both identity cookies (logout or failed session). */\nexport function clearAuthCookies(\n cookies: CookieWriter,\n options: IdentityCookieOptions = {},\n): void {\n const names = resolveCookieNames(options);\n const attrs = resolveCookieAttributes(options);\n const deleteOpts = { path: attrs.path, domain: attrs.domain };\n cookies.delete(names.access, deleteOpts);\n cookies.delete(names.refresh, deleteOpts);\n}\n\n/**\n * In-memory {@link CookieStore} for tests and Fetch-based Route Handlers.\n * Not for production browser storage.\n */\nexport function createMemoryCookieStore(\n initial: Record<string, string> = {},\n): CookieStore {\n const values = new Map(\n Object.entries(initial).filter(([, value]) => value.length > 0),\n );\n return {\n get(name) {\n const value = values.get(name);\n return value === undefined ? undefined : { value };\n },\n set(name, value) {\n if (value.length === 0) {\n values.delete(name);\n return;\n }\n values.set(name, value);\n },\n delete(name) {\n values.delete(name);\n },\n };\n}\n\n/** Builds a cookie store seeded from an incoming `Cookie` header. */\nexport function cookieStoreFromHeader(\n header: string | null | undefined,\n): CookieStore {\n return createMemoryCookieStore(\n Object.fromEntries(parseCookieHeader(header)),\n );\n}\n","import { AccountUnavailableError, InvalidTokenError } from \"../errors\";\nimport type { IdentityService } from \"../identity-service\";\nimport {\n readCookieValue,\n type CookieStore,\n type IdentityCookieOptions,\n resolveCookieNames,\n} from \"../cookie-header\";\nimport type { AuthenticatedIdentity } from \"../types\";\nimport { applyAuthCookies, clearAuthCookies } from \"./cookies\";\n\n/** Subset of {@link IdentityService} used to read and rotate a cookie session. */\nexport type IdentitySessionService = Pick<\n IdentityService,\n \"authenticate\" | \"refresh\"\n>;\n\n/**\n * Resolves the current principal from identity cookies.\n *\n * - Valid access cookie → `service.authenticate`.\n * - Expired/missing access + refresh cookie → `service.refresh` and rotate cookies.\n * - Failure → clear cookies and return `null` (degrade to logged out).\n *\n * Call this where cookies can be written (Server Actions, Route Handlers). Refresh\n * rotates the refresh token; skipping the write would invalidate the browser session.\n */\nexport async function getIdentity(\n service: IdentitySessionService,\n cookies: CookieStore,\n options: IdentityCookieOptions = {},\n): Promise<AuthenticatedIdentity | null> {\n const names = resolveCookieNames(options);\n const access = readCookieValue(cookies, names.access);\n const refresh = readCookieValue(cookies, names.refresh);\n\n if (access) {\n try {\n return await service.authenticate(access);\n } catch (error) {\n if (error instanceof AccountUnavailableError) {\n clearAuthCookies(cookies, options);\n return null;\n }\n if (!(error instanceof InvalidTokenError)) {\n throw error;\n }\n }\n }\n\n if (!refresh) {\n if (access) {\n clearAuthCookies(cookies, options);\n }\n return null;\n }\n\n try {\n const result = await service.refresh(refresh);\n applyAuthCookies(cookies, result.tokens, options);\n return result.user;\n } catch (error) {\n clearAuthCookies(cookies, options);\n if (\n error instanceof InvalidTokenError ||\n error instanceof AccountUnavailableError\n ) {\n return null;\n }\n throw error;\n }\n}\n","import { IdentityError, InvalidTokenError } from \"../errors\";\nimport type { IdentityService } from \"../identity-service\";\nimport {\n readCookieValue,\n type IdentityCookieOptions,\n resolveCookieNames,\n} from \"../cookie-header\";\nimport { applyAuthCookies, clearAuthCookies, cookieStoreFromHeader } from \"./cookies\";\nimport { getIdentity } from \"./session\";\n\nexport interface IdentityHandlerOptions extends IdentityCookieOptions {\n /**\n * Path prefix used by {@link createIdentityHandlers.dispatch} to match routes.\n * Default: `\"\"` (last path segment is the action: `login`, `logout`, …).\n */\n prefix?: string;\n}\n\nfunction json(\n body: unknown,\n status: number,\n cookies?: { headers: string[] },\n): Response {\n const headers = new Headers({ \"content-type\": \"application/json\" });\n if (cookies) {\n for (const header of cookies.headers) {\n headers.append(\"set-cookie\", header);\n }\n }\n return new Response(JSON.stringify(body), { status, headers });\n}\n\nfunction errorResponse(error: unknown): Response {\n if (error instanceof IdentityError) {\n return json({ code: error.code, message: error.message }, error.statusCode);\n }\n throw error;\n}\n\ntype RecordedCookie = {\n name: string;\n value: string;\n options?: {\n httpOnly?: boolean;\n secure?: boolean;\n sameSite?: \"strict\" | \"lax\" | \"none\";\n path?: string;\n domain?: string;\n maxAge?: number;\n expires?: Date;\n };\n};\n\nfunction serializeSetCookie(cookie: RecordedCookie): string {\n const parts = [`${cookie.name}=${encodeURIComponent(cookie.value)}`];\n const opts = cookie.options ?? {};\n if (opts.maxAge !== undefined) {\n parts.push(`Max-Age=${Math.max(0, Math.floor(opts.maxAge))}`);\n }\n if (opts.expires) {\n parts.push(`Expires=${opts.expires.toUTCString()}`);\n }\n parts.push(`Path=${opts.path ?? \"/\"}`);\n if (opts.domain) parts.push(`Domain=${opts.domain}`);\n if (opts.httpOnly !== false) parts.push(\"HttpOnly\");\n if (opts.secure) parts.push(\"Secure\");\n const sameSite = opts.sameSite ?? \"lax\";\n parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`);\n return parts.join(\"; \");\n}\n\nfunction recordingStore(header: string | null) {\n const inner = cookieStoreFromHeader(header);\n const writes: RecordedCookie[] = [];\n const deleted: RecordedCookie[] = [];\n const expired = new Date(0);\n\n return {\n store: {\n get: inner.get.bind(inner),\n set(name: string, value: string, options?: RecordedCookie[\"options\"]) {\n inner.set(name, value, options);\n writes.push({ name, value, options });\n },\n delete(name: string, options?: { path?: string; domain?: string }) {\n inner.delete(name, options);\n deleted.push({\n name,\n value: \"\",\n options: { ...options, maxAge: 0, expires: expired },\n });\n },\n },\n headers(): string[] {\n return [\n ...writes.map(serializeSetCookie),\n ...deleted.map(serializeSetCookie),\n ];\n },\n };\n}\n\nasync function readJsonBody(\n request: Request,\n): Promise<Record<string, unknown>> {\n try {\n const body: unknown = await request.json();\n if (typeof body === \"object\" && body !== null && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n return {};\n }\n}\n\nfunction actionFromUrl(url: string, prefix: string): string {\n const pathname = new URL(url).pathname.replace(/\\/+$/, \"\");\n const normalizedPrefix = prefix.replace(/^\\/+|\\/+$/g, \"\");\n if (normalizedPrefix) {\n const marker = `/${normalizedPrefix}/`;\n const idx = pathname.lastIndexOf(marker);\n if (idx >= 0) {\n return pathname.slice(idx + marker.length);\n }\n }\n const slash = pathname.lastIndexOf(\"/\");\n return slash >= 0 ? pathname.slice(slash + 1) : pathname;\n}\n\n/**\n * Fetch API Route Handlers for cookie-based identity sessions (Next.js App Router).\n *\n * Mount individually or use {@link IdentityHandlers.dispatch} from a catch-all route.\n */\nexport interface IdentityHandlers {\n login(request: Request): Promise<Response>;\n logout(request: Request): Promise<Response>;\n refresh(request: Request): Promise<Response>;\n me(request: Request): Promise<Response>;\n dispatch(request: Request): Promise<Response>;\n}\n\nexport function createIdentityHandlers(\n service: IdentityService,\n options: IdentityHandlerOptions = {},\n): IdentityHandlers {\n const prefix = options.prefix ?? \"\";\n const names = resolveCookieNames(options);\n\n const login = async (request: Request): Promise<Response> => {\n try {\n const body = await readJsonBody(request);\n const email = typeof body.email === \"string\" ? body.email : \"\";\n const password = typeof body.password === \"string\" ? body.password : \"\";\n const result = await service.login({ email, password });\n if (\"kind\" in result) {\n return json(result, 200);\n }\n const recorded = recordingStore(request.headers.get(\"cookie\"));\n applyAuthCookies(recorded.store, result.tokens, options);\n return json({ user: result.user }, 200, { headers: recorded.headers() });\n } catch (error) {\n return errorResponse(error);\n }\n };\n\n const logout = async (request: Request): Promise<Response> => {\n try {\n const recorded = recordingStore(request.headers.get(\"cookie\"));\n const refresh = readCookieValue(recorded.store, names.refresh);\n if (refresh) {\n await service.logout(refresh);\n }\n clearAuthCookies(recorded.store, options);\n return json({ ok: true }, 200, { headers: recorded.headers() });\n } catch (error) {\n return errorResponse(error);\n }\n };\n\n const refresh = async (request: Request): Promise<Response> => {\n try {\n const recorded = recordingStore(request.headers.get(\"cookie\"));\n const token = readCookieValue(recorded.store, names.refresh);\n if (!token) {\n throw new InvalidTokenError();\n }\n const result = await service.refresh(token);\n applyAuthCookies(recorded.store, result.tokens, options);\n return json({ user: result.user }, 200, { headers: recorded.headers() });\n } catch (error) {\n const recorded = recordingStore(request.headers.get(\"cookie\"));\n clearAuthCookies(recorded.store, options);\n if (error instanceof IdentityError) {\n return json(\n { code: error.code, message: error.message },\n error.statusCode,\n { headers: recorded.headers() },\n );\n }\n throw error;\n }\n };\n\n const me = async (request: Request): Promise<Response> => {\n try {\n const recorded = recordingStore(request.headers.get(\"cookie\"));\n const identity = await getIdentity(service, recorded.store, options);\n if (!identity) {\n return json(\n { code: \"identity/unauthenticated\", message: \"Authentication is required.\" },\n 401,\n { headers: recorded.headers() },\n );\n }\n return json({ user: identity }, 200, { headers: recorded.headers() });\n } catch (error) {\n return errorResponse(error);\n }\n };\n\n const dispatch = async (request: Request): Promise<Response> => {\n const action = actionFromUrl(request.url, prefix);\n const method = request.method.toUpperCase();\n if (method === \"POST\" && action === \"login\") return login(request);\n if (method === \"POST\" && action === \"logout\") return logout(request);\n if (method === \"POST\" && action === \"refresh\") return refresh(request);\n if (method === \"GET\" && action === \"me\") return me(request);\n return json({ code: \"identity/not-found\", message: \"Not found.\" }, 404);\n };\n\n return { login, logout, refresh, me, dispatch };\n}\n"],"mappings":";;;AAYA,SAAS,cAAc,WAAiB,KAAmB;CACzD,OAAO,KAAK,IAAI,GAAG,KAAK,OAAO,UAAU,QAAQ,IAAI,IAAI,QAAQ,KAAK,GAAI,CAAC;AAC7E;AAEA,SAAS,gBACP,SACA,WACA,KACA;CACA,MAAM,QAAQ,wBAAwB,OAAO;CAC7C,OAAO;EACL,UAAU,MAAM;EAChB,QAAQ,MAAM;EACd,UAAU,MAAM;EAChB,MAAM,MAAM;EACZ,QAAQ,MAAM;EACd,QAAQ,cAAc,WAAW,GAAG;EACpC,SAAS;CACX;AACF;;;;;AAMA,SAAgB,iBACd,SACA,QACA,UAAiC,CAAC,GAClC,sBAAY,IAAI,KAAK,GACf;CACN,MAAM,QAAQ,mBAAmB,OAAO;CACxC,QAAQ,IACN,MAAM,QACN,OAAO,aACP,gBAAgB,SAAS,OAAO,sBAAsB,GAAG,CAC3D;CACA,QAAQ,IACN,MAAM,SACN,OAAO,cACP,gBAAgB,SAAS,OAAO,uBAAuB,GAAG,CAC5D;AACF;;AAGA,SAAgB,iBACd,SACA,UAAiC,CAAC,GAC5B;CACN,MAAM,QAAQ,mBAAmB,OAAO;CACxC,MAAM,QAAQ,wBAAwB,OAAO;CAC7C,MAAM,aAAa;EAAE,MAAM,MAAM;EAAM,QAAQ,MAAM;CAAO;CAC5D,QAAQ,OAAO,MAAM,QAAQ,UAAU;CACvC,QAAQ,OAAO,MAAM,SAAS,UAAU;AAC1C;;;;;AAMA,SAAgB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");
3
3
  const require_logger = require("./logger-Be1wDzBC.cjs");
4
- const require_identity = require("./identity-4eP45YIP.cjs");
5
- let node_crypto = require("node:crypto");
4
+ const require_identity = require("./identity-Yz1BVkrM.cjs");
5
+ const require_cookie_header = require("./cookie-header-Dqd5k5BU.cjs");
6
6
  let jose = require("jose");
7
+ let node_crypto = require("node:crypto");
7
8
  //#region core/password-hasher.ts
8
9
  /**
9
10
  * Password hashing using Node's scrypt. Hashes are self-describing:
@@ -58,22 +59,11 @@ function createTokenService(config) {
58
59
  };
59
60
  },
60
61
  async verifyAccessToken(token) {
61
- try {
62
- const { payload } = await (0, jose.jwtVerify)(token, secret, {
63
- issuer: config.issuer,
64
- audience: config.audience
65
- });
66
- if (typeof payload.sub !== "string" || typeof payload.authVersion !== "number") throw new require_errors.InvalidTokenError();
67
- return {
68
- sub: payload.sub,
69
- authVersion: payload.authVersion,
70
- iat: payload.iat ?? 0,
71
- exp: payload.exp ?? 0
72
- };
73
- } catch (error) {
74
- if (error instanceof require_errors.InvalidTokenError) throw error;
75
- throw new require_errors.InvalidTokenError();
76
- }
62
+ return require_identity.verifyAccessToken(token, {
63
+ secret: config.accessTokenSecret,
64
+ issuer: config.issuer,
65
+ audience: config.audience
66
+ });
77
67
  },
78
68
  createRefreshToken(sessionId) {
79
69
  const token = `${sessionId}.${(0, node_crypto.randomBytes)(32).toString("base64url")}`;
@@ -689,7 +679,7 @@ async function disableAccount(deps, userId) {
689
679
  //#region core/identity-service.ts
690
680
  /**
691
681
  * Wires the framework-agnostic identity runtime with Node defaults (scrypt hashing,
692
- * `jose` HS256 tokens). Express and NestJS adapters build on top of this service.
682
+ * `jose` HS256 tokens). Express, NestJS, and Next.js adapters build on top of this service.
693
683
  */
694
684
  function createIdentityService(configInput, store) {
695
685
  const config = require_identity.resolveIdentityConfig(configInput);
@@ -888,6 +878,9 @@ function createMicrosoftOAuthProvider(config) {
888
878
  //#endregion
889
879
  exports.AccountAdminError = AccountAdminError;
890
880
  exports.AccountUnavailableError = require_errors.AccountUnavailableError;
881
+ exports.DEFAULT_ACCESS_COOKIE = require_cookie_header.DEFAULT_ACCESS_COOKIE;
882
+ exports.DEFAULT_ISSUER = require_identity.DEFAULT_ISSUER;
883
+ exports.DEFAULT_REFRESH_COOKIE = require_cookie_header.DEFAULT_REFRESH_COOKIE;
891
884
  exports.EmailAlreadyRegisteredError = require_errors.EmailAlreadyRegisteredError;
892
885
  exports.EmailVerificationError = EmailVerificationError;
893
886
  exports.ForbiddenError = require_errors.ForbiddenError;
@@ -922,6 +915,7 @@ exports.evaluateAuthorization = require_identity.evaluateAuthorization;
922
915
  exports.generateTotp = generateTotp;
923
916
  exports.generateTotpSecret = generateTotpSecret;
924
917
  exports.generateVerificationToken = generateVerificationToken;
918
+ exports.hasIdentityCookies = require_cookie_header.hasIdentityCookies;
925
919
  exports.hashVerificationToken = hashVerificationToken;
926
920
  exports.identitySchemaModel = require_identity.identitySchemaModel;
927
921
  exports.isAuthorized = require_identity.isAuthorized;
@@ -930,17 +924,22 @@ exports.lockAccount = lockAccount;
930
924
  exports.loginUser = loginUser;
931
925
  exports.noopLogger = require_logger.noopLogger;
932
926
  exports.normalizeEmail = normalizeEmail;
927
+ exports.parseCookieHeader = require_cookie_header.parseCookieHeader;
928
+ exports.readCookieValue = require_cookie_header.readCookieValue;
933
929
  exports.recordFailedAttempt = recordFailedAttempt;
934
930
  exports.refreshSession = refreshSession;
935
931
  exports.registerUser = registerUser;
936
932
  exports.requestEmailVerification = requestEmailVerification;
937
933
  exports.requestPasswordReset = requestPasswordReset;
938
934
  exports.resetPassword = resetPassword;
935
+ exports.resolveCookieAttributes = require_cookie_header.resolveCookieAttributes;
936
+ exports.resolveCookieNames = require_cookie_header.resolveCookieNames;
939
937
  exports.resolveIdentityConfig = require_identity.resolveIdentityConfig;
940
938
  exports.resolveLogger = require_logger.resolveLogger;
941
939
  exports.revokeSession = revokeSession;
942
940
  exports.setup2FA = setup2FA;
943
941
  exports.unlockAccount = unlockAccount;
942
+ exports.verifyAccessToken = require_identity.verifyAccessToken;
944
943
  exports.verifyEmail = verifyEmail;
945
944
  exports.verifyMfaChallenge = verifyMfaChallenge;
946
945
  exports.verifyTotp = verifyTotp;
package/dist/node.d.cts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { C as RolePermissionGrant, D as VerificationToken, E as UserRoleAssignment, O as VerificationTokenType, S as Role, T as TotpSetupResult, _ as IdentityUserStatus, a as generateVerificationToken, b as OAuthLinkedAccount, c as AuthResult, d as AuthenticatedIdentity, f as CredentialRecord, g as IdentityUser, h as IdentityEventType, i as CreateVerificationTokenInput, l as AuthSession, m as IdentityEvent, n as CreateIdentityUserInput, o as hashVerificationToken, p as DirectPermissionGrant, r as IdentityStore, s as AccessTokenClaims, t as CreateAuthSessionInput, u as AuthTokens, v as LoginResult, w as TotpSecret, x as Permission, y as MfaRequiredResult } from "./identity-store-BRRahxcS.cjs";
2
- import { A as resolveIdentityConfig, B as AuthorizationDecision, C as createTokenService, D as IdentityConfigInput, E as IdentityConfig, F as IdentityLogger, H as PolicyRule, I as consoleLogger, L as noopLogger, M as NotificationService, N as PasswordResetParams, O as IdentityOverrides, P as TwoFactorSmsParams, R as resolveLogger, S as TokenService, T as createAuditLogger, U as evaluateAuthorization, V as AuthorizationRequirement, W as isAuthorized, _ as ExchangeCodeParams, a as IdentityError, b as OAuthUserInfo, c as UnauthenticatedError, d as OAuthProviderNotFoundError, f as OAuthService, g as BuildAuthUrlParams, h as createOAuthService, i as IdentityConfigError, j as EmailVerificationParams, k as LockoutConfig, l as OAuthAuthorizationUrl, m as OAuthStateMismatchError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, p as OAuthServiceDeps, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError, u as OAuthCallbackParams, v as OAuthProvider, w as AuditLogger, x as SessionDeps, y as OAuthTokens, z as AuthorizationContext } from "./errors-C2xZAatu.cjs";
3
- import { a as RegisterInput, c as registerUser, d as loginUser, f as PasswordHasher, i as RegisterDeps, l as LoginDeps, n as IdentityServiceConfig, o as RegistrationValidationError, p as createPasswordHasher, r as createIdentityService, s as normalizeEmail, t as IdentityService, u as LoginInput } from "./identity-service-CLzKx8Z7.cjs";
4
- import { t as identitySchemaModel } from "./index-CpufYgyn.cjs";
5
-
2
+ import { A as LockoutConfig, B as AuthorizationContext, C as createTokenService, D as IdentityConfig, E as DEFAULT_ISSUER, F as TwoFactorSmsParams, G as isAuthorized, H as AuthorizationRequirement, I as IdentityLogger, L as consoleLogger, M as EmailVerificationParams, N as NotificationService, O as IdentityConfigInput, P as PasswordResetParams, R as noopLogger, S as TokenService, T as createAuditLogger, U as PolicyRule, V as AuthorizationDecision, W as evaluateAuthorization, _ as ExchangeCodeParams, a as IdentityError, b as OAuthUserInfo, c as UnauthenticatedError, d as OAuthProviderNotFoundError, f as OAuthService, g as BuildAuthUrlParams, h as createOAuthService, i as IdentityConfigError, j as resolveIdentityConfig, k as IdentityOverrides, l as OAuthAuthorizationUrl, m as OAuthStateMismatchError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, p as OAuthServiceDeps, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError, u as OAuthCallbackParams, v as OAuthProvider, w as AuditLogger, x as SessionDeps, y as OAuthTokens, z as resolveLogger } from "./errors-0Zh7EG06.cjs";
3
+ import { a as RegisterInput, c as registerUser, d as loginUser, f as PasswordHasher, i as RegisterDeps, l as LoginDeps, n as IdentityServiceConfig, o as RegistrationValidationError, p as createPasswordHasher, r as createIdentityService, s as normalizeEmail, t as IdentityService, u as LoginInput } from "./identity-service-DE0Ffguz.cjs";
4
+ import { n as VerifyAccessTokenOptions, r as verifyAccessToken, t as identitySchemaModel } from "./index-CsYqHPvK.cjs";
5
+ import { a as DEFAULT_ACCESS_COOKIE, c as IdentityCookieNames, d as parseCookieHeader, f as readCookieValue, i as CookieWriter, l as IdentityCookieOptions, m as resolveCookieNames, n as CookieSource, o as DEFAULT_REFRESH_COOKIE, p as resolveCookieAttributes, r as CookieStore, s as IdentityCookieAttributes, t as CookieReader, u as hasIdentityCookies } from "./cookie-header-LFWHKQ04.cjs";
6
6
  //#region core/lockout.d.ts
7
7
  /**
8
8
  * Checks whether the user account is currently locked. Throws {@link AccountUnavailableError}
@@ -256,5 +256,5 @@ declare function unlockAccount(deps: AccountAdminDeps, userId: string): Promise<
256
256
  */
257
257
  declare function disableAccount(deps: AccountAdminDeps, userId: string): Promise<void>;
258
258
  //#endregion
259
- export { AccessTokenClaims, AccountAdminDeps, AccountAdminError, AccountUnavailableError, AuditLogger, AuthResult, AuthSession, AuthTokens, AuthenticatedIdentity, AuthorizationContext, AuthorizationDecision, AuthorizationRequirement, BuildAuthUrlParams, CreateAuthSessionInput, CreateIdentityUserInput, CreateVerificationTokenInput, CredentialRecord, DirectPermissionGrant, EmailAlreadyRegisteredError, EmailVerificationDeps, EmailVerificationError, EmailVerificationParams, ExchangeCodeParams, ForbiddenError, type GoogleOAuthConfig, IdentityConfig, IdentityConfigError, IdentityConfigInput, IdentityError, IdentityEvent, IdentityEventType, IdentityLogger, IdentityOverrides, IdentityService, IdentityServiceConfig, IdentityStore, IdentityUser, IdentityUserStatus, InvalidCredentialsError, InvalidTokenError, LockoutConfig, LoginDeps, LoginInput, LoginResult, MfaRequiredResult, type MicrosoftOAuthConfig, NotificationService, OAuthAuthorizationUrl, OAuthCallbackParams, OAuthLinkedAccount, OAuthProvider, OAuthProviderNotFoundError, OAuthService, OAuthServiceDeps, OAuthStateMismatchError, OAuthTokens, OAuthUserInfo, PasswordHasher, PasswordResetDeps, PasswordResetError, PasswordResetParams, Permission, PolicyRule, RefreshDeps, RegisterDeps, RegisterInput, RegistrationValidationError, Role, RolePermissionGrant, TokenService, TotpSecret, TotpSetupResult, TwoFactorDeps, TwoFactorError, TwoFactorRequiredError, TwoFactorSmsParams, UnauthenticatedError, UserRoleAssignment, VerificationToken, VerificationTokenType, base32Decode, base32Encode, buildOtpAuthUri, checkLockout, clearLockout, consoleLogger, createAuditLogger, createGoogleOAuthProvider, createIdentityService, createMicrosoftOAuthProvider, createOAuthService, createPasswordHasher, createTokenService, disable2FA, disableAccount, enable2FA, evaluateAuthorization, generateTotp, generateTotpSecret, generateVerificationToken, hashVerificationToken, identitySchemaModel, isAuthorized, issueMfaChallengeToken, lockAccount, loginUser, noopLogger, normalizeEmail, recordFailedAttempt, refreshSession, registerUser, requestEmailVerification, requestPasswordReset, resetPassword, resolveIdentityConfig, resolveLogger, revokeSession, setup2FA, unlockAccount, verifyEmail, verifyMfaChallenge, verifyTotp };
259
+ export { AccessTokenClaims, AccountAdminDeps, AccountAdminError, AccountUnavailableError, AuditLogger, AuthResult, AuthSession, AuthTokens, AuthenticatedIdentity, AuthorizationContext, AuthorizationDecision, AuthorizationRequirement, BuildAuthUrlParams, type CookieReader, type CookieSource, type CookieStore, type CookieWriter, CreateAuthSessionInput, CreateIdentityUserInput, CreateVerificationTokenInput, CredentialRecord, DEFAULT_ACCESS_COOKIE, DEFAULT_ISSUER, DEFAULT_REFRESH_COOKIE, DirectPermissionGrant, EmailAlreadyRegisteredError, EmailVerificationDeps, EmailVerificationError, EmailVerificationParams, ExchangeCodeParams, ForbiddenError, type GoogleOAuthConfig, IdentityConfig, IdentityConfigError, IdentityConfigInput, type IdentityCookieAttributes, type IdentityCookieNames, type IdentityCookieOptions, IdentityError, IdentityEvent, IdentityEventType, IdentityLogger, IdentityOverrides, IdentityService, IdentityServiceConfig, IdentityStore, IdentityUser, IdentityUserStatus, InvalidCredentialsError, InvalidTokenError, LockoutConfig, LoginDeps, LoginInput, LoginResult, MfaRequiredResult, type MicrosoftOAuthConfig, NotificationService, OAuthAuthorizationUrl, OAuthCallbackParams, OAuthLinkedAccount, OAuthProvider, OAuthProviderNotFoundError, OAuthService, OAuthServiceDeps, OAuthStateMismatchError, OAuthTokens, OAuthUserInfo, PasswordHasher, PasswordResetDeps, PasswordResetError, PasswordResetParams, Permission, PolicyRule, RefreshDeps, RegisterDeps, RegisterInput, RegistrationValidationError, Role, RolePermissionGrant, TokenService, TotpSecret, TotpSetupResult, TwoFactorDeps, TwoFactorError, TwoFactorRequiredError, TwoFactorSmsParams, UnauthenticatedError, UserRoleAssignment, VerificationToken, VerificationTokenType, type VerifyAccessTokenOptions, base32Decode, base32Encode, buildOtpAuthUri, checkLockout, clearLockout, consoleLogger, createAuditLogger, createGoogleOAuthProvider, createIdentityService, createMicrosoftOAuthProvider, createOAuthService, createPasswordHasher, createTokenService, disable2FA, disableAccount, enable2FA, evaluateAuthorization, generateTotp, generateTotpSecret, generateVerificationToken, hasIdentityCookies, hashVerificationToken, identitySchemaModel, isAuthorized, issueMfaChallengeToken, lockAccount, loginUser, noopLogger, normalizeEmail, parseCookieHeader, readCookieValue, recordFailedAttempt, refreshSession, registerUser, requestEmailVerification, requestPasswordReset, resetPassword, resolveCookieAttributes, resolveCookieNames, resolveIdentityConfig, resolveLogger, revokeSession, setup2FA, unlockAccount, verifyAccessToken, verifyEmail, verifyMfaChallenge, verifyTotp };
260
260
  //# sourceMappingURL=node.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.cts","names":[],"sources":["../core/lockout.ts","../core/refresh-service.ts","../core/oauth/providers/google.ts","../core/oauth/providers/microsoft.ts","../core/email-verification.ts","../core/password-reset.ts","../core/totp.ts","../core/two-factor.ts","../core/account-admin.ts"],"mappings":";;;;;;;;;AAYA;;;;iBAAgB,YAAA,CACd,IAAA,EAAM,YAAA,EACN,MAAA,EAAQ,aAAA,EACR,GAAA,QAAW,IAAA;;;;;iBAYS,mBAAA,CACpB,KAAA,EAAO,aAAA,EACP,IAAA,EAAM,YAAA,EACN,MAAA,EAAQ,aAAA,EACR,GAAA,QAAW,IAAA,GACV,OAAA;;;;;iBAwBmB,YAAA,CACpB,KAAA,EAAO,aAAA,EACP,IAAA,EAAM,YAAA,GACL,OAAA;;;;UClDc,WAAA;EACf,MAAA,EAAQ,cAAA;EACR,KAAA,EAAO,aAAA;EACP,YAAA,EAAc,YAAA;EACd,KAAA,EA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.d.cts","names":[],"sources":["../core/lockout.ts","../core/refresh-service.ts","../core/oauth/providers/google.ts","../core/oauth/providers/microsoft.ts","../core/email-verification.ts","../core/password-reset.ts","../core/totp.ts","../core/two-factor.ts","../core/account-admin.ts"],"mappings":";;;;;;;;;;;;;iBAYgB,aACd,MAAM,cACN,QAAQ,eACR,WAAW;;;;;iBAYS,oBACpB,OAAO,eACP,MAAM,cACN,QAAQ,eACR,WAAW,OACV;;;;;iBAwBmB,aACpB,OAAO,eACP,MAAM,eACL;;;;UClDc;EACf,QAAQ;EACR,OAAO;EACP,cAAc;EACd,OAAO;;;;;;;;;iBAUa,eACpB,MAAM,aACN,yBACC,QAAQ;;iBA+DW,cACpB,MAAM,KAAK,6DACX,yBACC;;;;UC5Dc;;EAEf;;;;;EAKA;;;;EAIA;;;;;;;;;;;iBA+Bc,0BACd,QAAQ,oBACP;;;;UC7Cc;;EAEf;;;;;EAKA;;;;;;EAMA;;;;;EAKA;;;;;;;;;;;iBA+Bc,6BACd,QAAQ,uBACP;;;;cCpEU,+BAA+B;EAC1C,YAAY;;UAKG;EACf,QAAQ;EACR,OAAO;EACP,OAAO;;;;;;;;iBASa,yBACpB,MAAM,uBACN,iBACC;;;;;;iBAmCmB,YACpB,MAAM,uBACN,mBACC;;;;cCvDU,2BAA2B;EACtC,YAAY;;UAKG;EACf,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,OAAO;;;;;;;;iBASa,qBACpB,MAAM,mBACN,gBACC;;;;;;;iBAwCmB,cACpB,MAAM,mBACN,kBACA,sBACC;;;;iBC3Ea,aAAa,QAAQ;;iBAoBrB,aAAa,kBAAkB;;;;;iBAkD/B;;;;iBAOA,aACd,sBACA,MAAK;;;;;;iBAWS,WACd,cACA,sBACA,MAAK;;;;;iBAaS,gBAAgB;EAC9B;EACA;EACA;;;;;cCvGW,uBAAuB;EAClC,YAAY;;;;;;cASD,+BAA+B;EAC1C;;UAae,sBAAsB;EACrC,OAAO;;;;;;;;iBAaa,SACpB,MAAM,eACN,iBACC,QAAQ;;;;;iBAoCW,UACpB,MAAM,eACN,gBACA,mBACC;;;;;iBA6BmB,WACpB,MAAM,eACN,gBACA,mBACC;;;;;iBA6BmB,uBACpB,QAAQ,gBACR,iBACC;;;;;;;iBAqBmB,mBACpB,MAAM,eACN,kBACA,mBACC,QAAQ;;;;cCpLE,0BAA0B;EACrC,YAAY;;UAKG;EACf,QAAQ;EACR,OAAO;EACP,OAAO;;;;;;;;;iBAUa,YACpB,MAAM,kBACN,iBACC;;;;;iBAiBmB,cACpB,MAAM,kBACN,iBACC;;;;;;iBAoBmB,eACpB,MAAM,kBACN,iBACC"}
package/dist/node.d.mts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { C as RolePermissionGrant, D as VerificationToken, E as UserRoleAssignment, O as VerificationTokenType, S as Role, T as TotpSetupResult, _ as IdentityUserStatus, a as generateVerificationToken, b as OAuthLinkedAccount, c as AuthResult, d as AuthenticatedIdentity, f as CredentialRecord, g as IdentityUser, h as IdentityEventType, i as CreateVerificationTokenInput, l as AuthSession, m as IdentityEvent, n as CreateIdentityUserInput, o as hashVerificationToken, p as DirectPermissionGrant, r as IdentityStore, s as AccessTokenClaims, t as CreateAuthSessionInput, u as AuthTokens, v as LoginResult, w as TotpSecret, x as Permission, y as MfaRequiredResult } from "./identity-store-BRRahxcS.mjs";
2
- import { A as resolveIdentityConfig, B as AuthorizationDecision, C as createTokenService, D as IdentityConfigInput, E as IdentityConfig, F as IdentityLogger, H as PolicyRule, I as consoleLogger, L as noopLogger, M as NotificationService, N as PasswordResetParams, O as IdentityOverrides, P as TwoFactorSmsParams, R as resolveLogger, S as TokenService, T as createAuditLogger, U as evaluateAuthorization, V as AuthorizationRequirement, W as isAuthorized, _ as ExchangeCodeParams, a as IdentityError, b as OAuthUserInfo, c as UnauthenticatedError, d as OAuthProviderNotFoundError, f as OAuthService, g as BuildAuthUrlParams, h as createOAuthService, i as IdentityConfigError, j as EmailVerificationParams, k as LockoutConfig, l as OAuthAuthorizationUrl, m as OAuthStateMismatchError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, p as OAuthServiceDeps, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError, u as OAuthCallbackParams, v as OAuthProvider, w as AuditLogger, x as SessionDeps, y as OAuthTokens, z as AuthorizationContext } from "./errors-BGMwaW5s.mjs";
3
- import { a as RegisterInput, c as registerUser, d as loginUser, f as PasswordHasher, i as RegisterDeps, l as LoginDeps, n as IdentityServiceConfig, o as RegistrationValidationError, p as createPasswordHasher, r as createIdentityService, s as normalizeEmail, t as IdentityService, u as LoginInput } from "./identity-service-B9zrvE9z.mjs";
4
- import { t as identitySchemaModel } from "./index-CpufYgyn.mjs";
5
-
2
+ import { A as LockoutConfig, B as AuthorizationContext, C as createTokenService, D as IdentityConfig, E as DEFAULT_ISSUER, F as TwoFactorSmsParams, G as isAuthorized, H as AuthorizationRequirement, I as IdentityLogger, L as consoleLogger, M as EmailVerificationParams, N as NotificationService, O as IdentityConfigInput, P as PasswordResetParams, R as noopLogger, S as TokenService, T as createAuditLogger, U as PolicyRule, V as AuthorizationDecision, W as evaluateAuthorization, _ as ExchangeCodeParams, a as IdentityError, b as OAuthUserInfo, c as UnauthenticatedError, d as OAuthProviderNotFoundError, f as OAuthService, g as BuildAuthUrlParams, h as createOAuthService, i as IdentityConfigError, j as resolveIdentityConfig, k as IdentityOverrides, l as OAuthAuthorizationUrl, m as OAuthStateMismatchError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, p as OAuthServiceDeps, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError, u as OAuthCallbackParams, v as OAuthProvider, w as AuditLogger, x as SessionDeps, y as OAuthTokens, z as resolveLogger } from "./errors-DVDEUk9-.mjs";
3
+ import { a as RegisterInput, c as registerUser, d as loginUser, f as PasswordHasher, i as RegisterDeps, l as LoginDeps, n as IdentityServiceConfig, o as RegistrationValidationError, p as createPasswordHasher, r as createIdentityService, s as normalizeEmail, t as IdentityService, u as LoginInput } from "./identity-service-JtsoA6lv.mjs";
4
+ import { n as VerifyAccessTokenOptions, r as verifyAccessToken, t as identitySchemaModel } from "./index-LhSdoWEP.mjs";
5
+ import { a as DEFAULT_ACCESS_COOKIE, c as IdentityCookieNames, d as parseCookieHeader, f as readCookieValue, i as CookieWriter, l as IdentityCookieOptions, m as resolveCookieNames, n as CookieSource, o as DEFAULT_REFRESH_COOKIE, p as resolveCookieAttributes, r as CookieStore, s as IdentityCookieAttributes, t as CookieReader, u as hasIdentityCookies } from "./cookie-header-LFWHKQ04.mjs";
6
6
  //#region core/lockout.d.ts
7
7
  /**
8
8
  * Checks whether the user account is currently locked. Throws {@link AccountUnavailableError}
@@ -256,5 +256,5 @@ declare function unlockAccount(deps: AccountAdminDeps, userId: string): Promise<
256
256
  */
257
257
  declare function disableAccount(deps: AccountAdminDeps, userId: string): Promise<void>;
258
258
  //#endregion
259
- export { AccessTokenClaims, AccountAdminDeps, AccountAdminError, AccountUnavailableError, AuditLogger, AuthResult, AuthSession, AuthTokens, AuthenticatedIdentity, AuthorizationContext, AuthorizationDecision, AuthorizationRequirement, BuildAuthUrlParams, CreateAuthSessionInput, CreateIdentityUserInput, CreateVerificationTokenInput, CredentialRecord, DirectPermissionGrant, EmailAlreadyRegisteredError, EmailVerificationDeps, EmailVerificationError, EmailVerificationParams, ExchangeCodeParams, ForbiddenError, type GoogleOAuthConfig, IdentityConfig, IdentityConfigError, IdentityConfigInput, IdentityError, IdentityEvent, IdentityEventType, IdentityLogger, IdentityOverrides, IdentityService, IdentityServiceConfig, IdentityStore, IdentityUser, IdentityUserStatus, InvalidCredentialsError, InvalidTokenError, LockoutConfig, LoginDeps, LoginInput, LoginResult, MfaRequiredResult, type MicrosoftOAuthConfig, NotificationService, OAuthAuthorizationUrl, OAuthCallbackParams, OAuthLinkedAccount, OAuthProvider, OAuthProviderNotFoundError, OAuthService, OAuthServiceDeps, OAuthStateMismatchError, OAuthTokens, OAuthUserInfo, PasswordHasher, PasswordResetDeps, PasswordResetError, PasswordResetParams, Permission, PolicyRule, RefreshDeps, RegisterDeps, RegisterInput, RegistrationValidationError, Role, RolePermissionGrant, TokenService, TotpSecret, TotpSetupResult, TwoFactorDeps, TwoFactorError, TwoFactorRequiredError, TwoFactorSmsParams, UnauthenticatedError, UserRoleAssignment, VerificationToken, VerificationTokenType, base32Decode, base32Encode, buildOtpAuthUri, checkLockout, clearLockout, consoleLogger, createAuditLogger, createGoogleOAuthProvider, createIdentityService, createMicrosoftOAuthProvider, createOAuthService, createPasswordHasher, createTokenService, disable2FA, disableAccount, enable2FA, evaluateAuthorization, generateTotp, generateTotpSecret, generateVerificationToken, hashVerificationToken, identitySchemaModel, isAuthorized, issueMfaChallengeToken, lockAccount, loginUser, noopLogger, normalizeEmail, recordFailedAttempt, refreshSession, registerUser, requestEmailVerification, requestPasswordReset, resetPassword, resolveIdentityConfig, resolveLogger, revokeSession, setup2FA, unlockAccount, verifyEmail, verifyMfaChallenge, verifyTotp };
259
+ export { AccessTokenClaims, AccountAdminDeps, AccountAdminError, AccountUnavailableError, AuditLogger, AuthResult, AuthSession, AuthTokens, AuthenticatedIdentity, AuthorizationContext, AuthorizationDecision, AuthorizationRequirement, BuildAuthUrlParams, type CookieReader, type CookieSource, type CookieStore, type CookieWriter, CreateAuthSessionInput, CreateIdentityUserInput, CreateVerificationTokenInput, CredentialRecord, DEFAULT_ACCESS_COOKIE, DEFAULT_ISSUER, DEFAULT_REFRESH_COOKIE, DirectPermissionGrant, EmailAlreadyRegisteredError, EmailVerificationDeps, EmailVerificationError, EmailVerificationParams, ExchangeCodeParams, ForbiddenError, type GoogleOAuthConfig, IdentityConfig, IdentityConfigError, IdentityConfigInput, type IdentityCookieAttributes, type IdentityCookieNames, type IdentityCookieOptions, IdentityError, IdentityEvent, IdentityEventType, IdentityLogger, IdentityOverrides, IdentityService, IdentityServiceConfig, IdentityStore, IdentityUser, IdentityUserStatus, InvalidCredentialsError, InvalidTokenError, LockoutConfig, LoginDeps, LoginInput, LoginResult, MfaRequiredResult, type MicrosoftOAuthConfig, NotificationService, OAuthAuthorizationUrl, OAuthCallbackParams, OAuthLinkedAccount, OAuthProvider, OAuthProviderNotFoundError, OAuthService, OAuthServiceDeps, OAuthStateMismatchError, OAuthTokens, OAuthUserInfo, PasswordHasher, PasswordResetDeps, PasswordResetError, PasswordResetParams, Permission, PolicyRule, RefreshDeps, RegisterDeps, RegisterInput, RegistrationValidationError, Role, RolePermissionGrant, TokenService, TotpSecret, TotpSetupResult, TwoFactorDeps, TwoFactorError, TwoFactorRequiredError, TwoFactorSmsParams, UnauthenticatedError, UserRoleAssignment, VerificationToken, VerificationTokenType, type VerifyAccessTokenOptions, base32Decode, base32Encode, buildOtpAuthUri, checkLockout, clearLockout, consoleLogger, createAuditLogger, createGoogleOAuthProvider, createIdentityService, createMicrosoftOAuthProvider, createOAuthService, createPasswordHasher, createTokenService, disable2FA, disableAccount, enable2FA, evaluateAuthorization, generateTotp, generateTotpSecret, generateVerificationToken, hasIdentityCookies, hashVerificationToken, identitySchemaModel, isAuthorized, issueMfaChallengeToken, lockAccount, loginUser, noopLogger, normalizeEmail, parseCookieHeader, readCookieValue, recordFailedAttempt, refreshSession, registerUser, requestEmailVerification, requestPasswordReset, resetPassword, resolveCookieAttributes, resolveCookieNames, resolveIdentityConfig, resolveLogger, revokeSession, setup2FA, unlockAccount, verifyAccessToken, verifyEmail, verifyMfaChallenge, verifyTotp };
260
260
  //# sourceMappingURL=node.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.mts","names":[],"sources":["../core/lockout.ts","../core/refresh-service.ts","../core/oauth/providers/google.ts","../core/oauth/providers/microsoft.ts","../core/email-verification.ts","../core/password-reset.ts","../core/totp.ts","../core/two-factor.ts","../core/account-admin.ts"],"mappings":";;;;;;;;;AAYA;;;;iBAAgB,YAAA,CACd,IAAA,EAAM,YAAA,EACN,MAAA,EAAQ,aAAA,EACR,GAAA,QAAW,IAAA;;;;;iBAYS,mBAAA,CACpB,KAAA,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AAA;AAAA;;;;;;;;iBAUa,WAAA,CAAY,IAAA,EAAM,gBAAA,EAAkB,MAAA,WAAiB,OAAO;ARVjE;AAYjB;;;AAZiB,iBQ2BK,aAAA,CAAc,IAAA,EAAM,gBAAA,EAAkB,MAAA,WAAiB,OAAO;;;;;;iBAoB9D,cAAA,CAAe,IAAA,EAAM,gBAAA,EAAkB,MAAA,WAAiB,OAAO"}
1
+ {"version":3,"file":"node.d.mts","names":[],"sources":["../core/lockout.ts","../core/refresh-service.ts","../core/oauth/providers/google.ts","../core/oauth/providers/microsoft.ts","../core/email-verification.ts","../core/password-reset.ts","../core/totp.ts","../core/two-factor.ts","../core/account-admin.ts"],"mappings":";;;;;;;;;;;;;iBAYgB,aACd,MAAM,cACN,QAAQ,eACR,WAAW;;;;;iBAYS,oBACpB,OAAO,eACP,MAAM,cACN,QAAQ,eACR,WAAW,OACV;;;;;iBAwBmB,aACpB,OAAO,eACP,MAAM,eACL;;;;UClDc;EACf,QAAQ;EACR,OAAO;EACP,cAAc;EACd,OAAO;;;;;;;;;iBAUa,eACpB,MAAM,aACN,yBACC,QAAQ;;iBA+DW,cACpB,MAAM,KAAK,6DACX,yBACC;;;;UC5Dc;;EAEf;;;;;EAKA;;;;EAIA;;;;;;;;;;;iBA+Bc,0BACd,QAAQ,oBACP;;;;UC7Cc;;EAEf;;;;;EAKA;;;;;;EAMA;;;;;EAKA;;;;;;;;;;;iBA+Bc,6BACd,QAAQ,uBACP;;;;cCpEU,+BAA+B;EAC1C,YAAY;;UAKG;EACf,QAAQ;EACR,OAAO;EACP,OAAO;;;;;;;;iBASa,yBACpB,MAAM,uBACN,iBACC;;;;;;iBAmCmB,YACpB,MAAM,uBACN,mBACC;;;;cCvDU,2BAA2B;EACtC,YAAY;;UAKG;EACf,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,OAAO;;;;;;;;iBASa,qBACpB,MAAM,mBACN,gBACC;;;;;;;iBAwCmB,cACpB,MAAM,mBACN,kBACA,sBACC;;;;iBC3Ea,aAAa,QAAQ;;iBAoBrB,aAAa,kBAAkB;;;;;iBAkD/B;;;;iBAOA,aACd,sBACA,MAAK;;;;;;iBAWS,WACd,cACA,sBACA,MAAK;;;;;iBAaS,gBAAgB;EAC9B;EACA;EACA;;;;;cCvGW,uBAAuB;EAClC,YAAY;;;;;;cASD,+BAA+B;EAC1C;;UAae,sBAAsB;EACrC,OAAO;;;;;;;;iBAaa,SACpB,MAAM,eACN,iBACC,QAAQ;;;;;iBAoCW,UACpB,MAAM,eACN,gBACA,mBACC;;;;;iBA6BmB,WACpB,MAAM,eACN,gBACA,mBACC;;;;;iBA6BmB,uBACpB,QAAQ,gBACR,iBACC;;;;;;;iBAqBmB,mBACpB,MAAM,eACN,kBACA,mBACC,QAAQ;;;;cCpLE,0BAA0B;EACrC,YAAY;;UAKG;EACf,QAAQ;EACR,OAAO;EACP,OAAO;;;;;;;;;iBAUa,YACpB,MAAM,kBACN,iBACC;;;;;iBAiBmB,cACpB,MAAM,kBACN,iBACC;;;;;;iBAoBmB,eACpB,MAAM,kBACN,iBACC"}
package/dist/node.mjs CHANGED
@@ -1,8 +1,9 @@
1
1
  import { a as IdentityError, c as UnauthenticatedError, i as IdentityConfigError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError } from "./errors-CEmnZxIn.mjs";
2
2
  import { n as noopLogger, r as resolveLogger, t as consoleLogger } from "./logger-CcCHJVVe.mjs";
3
- import { a as hydratePrincipal, c as isAuthorized, i as createOAuthService, l as resolveIdentityConfig, n as OAuthProviderNotFoundError, o as issueSession, r as OAuthStateMismatchError, s as evaluateAuthorization, t as identitySchemaModel } from "./identity-Bz9RDOvT.mjs";
4
- import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
3
+ import { a as createOAuthService, c as evaluateAuthorization, d as resolveIdentityConfig, i as OAuthStateMismatchError, l as isAuthorized, n as verifyAccessToken, o as hydratePrincipal, r as OAuthProviderNotFoundError, s as issueSession, t as identitySchemaModel, u as DEFAULT_ISSUER } from "./identity-D0qyca_c.mjs";
4
+ import { a as readCookieValue, i as parseCookieHeader, n as DEFAULT_REFRESH_COOKIE, o as resolveCookieAttributes, r as hasIdentityCookies, s as resolveCookieNames, t as DEFAULT_ACCESS_COOKIE } from "./cookie-header-DptIxRmW.mjs";
5
5
  import { SignJWT, jwtVerify } from "jose";
6
+ import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
6
7
  //#region core/password-hasher.ts
7
8
  /**
8
9
  * Password hashing using Node's scrypt. Hashes are self-describing:
@@ -57,22 +58,11 @@ function createTokenService(config) {
57
58
  };
58
59
  },
59
60
  async verifyAccessToken(token) {
60
- try {
61
- const { payload } = await jwtVerify(token, secret, {
62
- issuer: config.issuer,
63
- audience: config.audience
64
- });
65
- if (typeof payload.sub !== "string" || typeof payload.authVersion !== "number") throw new InvalidTokenError();
66
- return {
67
- sub: payload.sub,
68
- authVersion: payload.authVersion,
69
- iat: payload.iat ?? 0,
70
- exp: payload.exp ?? 0
71
- };
72
- } catch (error) {
73
- if (error instanceof InvalidTokenError) throw error;
74
- throw new InvalidTokenError();
75
- }
61
+ return verifyAccessToken(token, {
62
+ secret: config.accessTokenSecret,
63
+ issuer: config.issuer,
64
+ audience: config.audience
65
+ });
76
66
  },
77
67
  createRefreshToken(sessionId) {
78
68
  const token = `${sessionId}.${randomBytes(32).toString("base64url")}`;
@@ -688,7 +678,7 @@ async function disableAccount(deps, userId) {
688
678
  //#region core/identity-service.ts
689
679
  /**
690
680
  * Wires the framework-agnostic identity runtime with Node defaults (scrypt hashing,
691
- * `jose` HS256 tokens). Express and NestJS adapters build on top of this service.
681
+ * `jose` HS256 tokens). Express, NestJS, and Next.js adapters build on top of this service.
692
682
  */
693
683
  function createIdentityService(configInput, store) {
694
684
  const config = resolveIdentityConfig(configInput);
@@ -885,6 +875,6 @@ function createMicrosoftOAuthProvider(config) {
885
875
  };
886
876
  }
887
877
  //#endregion
888
- export { AccountAdminError, AccountUnavailableError, EmailAlreadyRegisteredError, EmailVerificationError, ForbiddenError, IdentityConfigError, IdentityError, InvalidCredentialsError, InvalidTokenError, OAuthProviderNotFoundError, OAuthStateMismatchError, PasswordResetError, RegistrationValidationError, TwoFactorError, TwoFactorRequiredError, UnauthenticatedError, base32Decode, base32Encode, buildOtpAuthUri, checkLockout, clearLockout, consoleLogger, createAuditLogger, createGoogleOAuthProvider, createIdentityService, createMicrosoftOAuthProvider, createOAuthService, createPasswordHasher, createTokenService, disable2FA, disableAccount, enable2FA, evaluateAuthorization, generateTotp, generateTotpSecret, generateVerificationToken, hashVerificationToken, identitySchemaModel, isAuthorized, issueMfaChallengeToken, lockAccount, loginUser, noopLogger, normalizeEmail, recordFailedAttempt, refreshSession, registerUser, requestEmailVerification, requestPasswordReset, resetPassword, resolveIdentityConfig, resolveLogger, revokeSession, setup2FA, unlockAccount, verifyEmail, verifyMfaChallenge, verifyTotp };
878
+ export { AccountAdminError, AccountUnavailableError, DEFAULT_ACCESS_COOKIE, DEFAULT_ISSUER, DEFAULT_REFRESH_COOKIE, EmailAlreadyRegisteredError, EmailVerificationError, ForbiddenError, IdentityConfigError, IdentityError, InvalidCredentialsError, InvalidTokenError, OAuthProviderNotFoundError, OAuthStateMismatchError, PasswordResetError, RegistrationValidationError, TwoFactorError, TwoFactorRequiredError, UnauthenticatedError, base32Decode, base32Encode, buildOtpAuthUri, checkLockout, clearLockout, consoleLogger, createAuditLogger, createGoogleOAuthProvider, createIdentityService, createMicrosoftOAuthProvider, createOAuthService, createPasswordHasher, createTokenService, disable2FA, disableAccount, enable2FA, evaluateAuthorization, generateTotp, generateTotpSecret, generateVerificationToken, hasIdentityCookies, hashVerificationToken, identitySchemaModel, isAuthorized, issueMfaChallengeToken, lockAccount, loginUser, noopLogger, normalizeEmail, parseCookieHeader, readCookieValue, recordFailedAttempt, refreshSession, registerUser, requestEmailVerification, requestPasswordReset, resetPassword, resolveCookieAttributes, resolveCookieNames, resolveIdentityConfig, resolveLogger, revokeSession, setup2FA, unlockAccount, verifyAccessToken, verifyEmail, verifyMfaChallenge, verifyTotp };
889
879
 
890
880
  //# sourceMappingURL=node.mjs.map