@sylphx/sdk 0.0.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.
@@ -0,0 +1,1941 @@
1
+ // src/nextjs/middleware.ts
2
+ import { NextResponse } from "next/server";
3
+
4
+ // src/constants.ts
5
+ var DEFAULT_PLATFORM_URL = "https://sylphx.com";
6
+ var SDK_PLATFORM = typeof window !== "undefined" ? "browser" : typeof process !== "undefined" && process.versions?.node ? "node" : "unknown";
7
+ var TOKEN_EXPIRY_BUFFER_MS = 3e4;
8
+ var SESSION_TOKEN_LIFETIME_SECONDS = 5 * 60;
9
+ var SESSION_TOKEN_LIFETIME_MS = SESSION_TOKEN_LIFETIME_SECONDS * 1e3;
10
+ var REFRESH_TOKEN_LIFETIME_SECONDS = 30 * 24 * 60 * 60;
11
+ var FLAGS_CACHE_TTL_MS = 5 * 60 * 1e3;
12
+ var FLAGS_STALE_WHILE_REVALIDATE_MS = 60 * 1e3;
13
+ var ANALYTICS_SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
14
+ var WEBHOOK_MAX_AGE_MS = 5 * 60 * 1e3;
15
+ var WEBHOOK_CLOCK_SKEW_MS = 30 * 1e3;
16
+ var PKCE_CODE_TTL_MS = 10 * 60 * 1e3;
17
+ var JOBS_DLQ_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
18
+ var SESSION_REPLAY_MAX_DURATION_MS = 60 * 60 * 1e3;
19
+ var FLAGS_EXPOSURE_DEDUPE_WINDOW_MS = 60 * 60 * 1e3;
20
+ var CLICK_ID_EXPIRY_MS = 90 * 24 * 60 * 60 * 1e3;
21
+ var STALE_TIME_FREQUENT_MS = 60 * 1e3;
22
+ var STALE_TIME_MODERATE_MS = 2 * 60 * 1e3;
23
+ var STALE_TIME_STABLE_MS = 5 * 60 * 1e3;
24
+ var STALE_TIME_STATS_MS = 30 * 1e3;
25
+ var NEW_USER_THRESHOLD_MS = 60 * 1e3;
26
+ var STORAGE_MULTIPART_THRESHOLD_BYTES = 5 * 1024 * 1024;
27
+ var STORAGE_DEFAULT_MAX_SIZE_BYTES = 5 * 1024 * 1024;
28
+ var STORAGE_AVATAR_MAX_SIZE_BYTES = 2 * 1024 * 1024;
29
+ var STORAGE_LARGE_MAX_SIZE_BYTES = 10 * 1024 * 1024;
30
+ var JWK_CACHE_TTL_MS = 60 * 60 * 1e3;
31
+ var ETAG_CACHE_TTL_MS = 5 * 60 * 1e3;
32
+
33
+ // src/key-validation.ts
34
+ var APP_ID_PATTERN = /^app_(dev|stg|prod)_[a-z0-9_-]+$/;
35
+ var SECRET_KEY_PATTERN = /^sk_(dev|stg|prod)_[a-z0-9_-]+$/;
36
+ var ENV_PREFIX_MAP = {
37
+ dev: "development",
38
+ stg: "staging",
39
+ prod: "production"
40
+ };
41
+ function detectKeyIssues(key) {
42
+ const issues = [];
43
+ if (key !== key.trim()) issues.push("whitespace");
44
+ if (key.includes("\n")) issues.push("newline");
45
+ if (key.includes("\r")) issues.push("carriage-return");
46
+ if (key.includes(" ")) issues.push("space");
47
+ if (key !== key.toLowerCase()) issues.push("uppercase-chars");
48
+ return issues;
49
+ }
50
+ function createSanitizationWarning(keyType, issues, envVarName) {
51
+ const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
52
+ return `[Sylphx] ${keyTypeName} contains ${issues.join(", ")}. This is commonly caused by Vercel CLI's 'env pull' command.
53
+
54
+ To fix permanently:
55
+ 1. Go to Vercel Dashboard \u2192 Your Project \u2192 Settings \u2192 Environment Variables
56
+ 2. Edit ${envVarName}
57
+ 3. Remove any trailing whitespace or newline characters
58
+ 4. Redeploy your application
59
+
60
+ The SDK will automatically sanitize the key, but fixing the source is recommended.`;
61
+ }
62
+ function createInvalidKeyError(keyType, key, envVarName) {
63
+ const prefix = keyType === "appId" ? "app" : "sk";
64
+ const maskedKey = key.length > 20 ? `${key.slice(0, 20)}...` : key;
65
+ const formatHint = `${prefix}_(dev|stg|prod)_[identifier]`;
66
+ const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
67
+ return `[Sylphx] Invalid ${keyTypeName} format.
68
+
69
+ Expected format: ${formatHint}
70
+ Received: "${maskedKey}"
71
+
72
+ Please check your ${envVarName} environment variable.
73
+ You can find your keys in the Sylphx Console \u2192 API Keys.
74
+
75
+ Common issues:
76
+ \u2022 Key has uppercase characters (must be lowercase)
77
+ \u2022 Key has wrong prefix (App ID: app_, Secret Key: sk_)
78
+ \u2022 Key has invalid environment (must be dev, stg, or prod)
79
+ \u2022 Key was copied with extra whitespace`;
80
+ }
81
+ function extractEnvironment(key) {
82
+ const match = key.match(/^(?:app|sk)_(dev|stg|prod)_/);
83
+ if (!match) return void 0;
84
+ return ENV_PREFIX_MAP[match[1]];
85
+ }
86
+ function validateKeyForType(key, keyType, pattern, envVarName) {
87
+ const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
88
+ if (!key) {
89
+ return {
90
+ valid: false,
91
+ sanitizedKey: "",
92
+ error: `[Sylphx] ${keyTypeName} is required. Set ${envVarName} in your environment variables.`,
93
+ issues: ["missing"]
94
+ };
95
+ }
96
+ const issues = detectKeyIssues(key);
97
+ if (pattern.test(key)) {
98
+ return {
99
+ valid: true,
100
+ sanitizedKey: key,
101
+ keyType,
102
+ environment: extractEnvironment(key),
103
+ issues: []
104
+ };
105
+ }
106
+ const sanitized = key.trim().toLowerCase();
107
+ if (pattern.test(sanitized)) {
108
+ return {
109
+ valid: true,
110
+ sanitizedKey: sanitized,
111
+ keyType,
112
+ environment: extractEnvironment(sanitized),
113
+ warning: createSanitizationWarning(keyType, issues, envVarName),
114
+ issues
115
+ };
116
+ }
117
+ return {
118
+ valid: false,
119
+ sanitizedKey: "",
120
+ error: createInvalidKeyError(keyType, key, envVarName),
121
+ issues: [...issues, "invalid-format"]
122
+ };
123
+ }
124
+ function validateAppId(key) {
125
+ return validateKeyForType(
126
+ key,
127
+ "appId",
128
+ APP_ID_PATTERN,
129
+ "NEXT_PUBLIC_SYLPHX_APP_ID"
130
+ );
131
+ }
132
+ function validateAndSanitizeAppId(key) {
133
+ const result = validateAppId(key);
134
+ if (!result.valid) {
135
+ throw new Error(result.error);
136
+ }
137
+ if (result.warning) {
138
+ console.warn(result.warning);
139
+ }
140
+ return result.sanitizedKey;
141
+ }
142
+ function validateSecretKey(key) {
143
+ return validateKeyForType(
144
+ key,
145
+ "secret",
146
+ SECRET_KEY_PATTERN,
147
+ "SYLPHX_SECRET_KEY"
148
+ );
149
+ }
150
+ function validateAndSanitizeSecretKey(key) {
151
+ const result = validateSecretKey(key);
152
+ if (!result.valid) {
153
+ throw new Error(result.error);
154
+ }
155
+ if (result.warning) {
156
+ console.warn(result.warning);
157
+ }
158
+ return result.sanitizedKey;
159
+ }
160
+ function detectEnvironment(key) {
161
+ const sanitized = key.trim().toLowerCase();
162
+ if (sanitized.startsWith("sk_")) {
163
+ const result = validateSecretKey(sanitized);
164
+ if (!result.valid) {
165
+ throw new Error(result.error);
166
+ }
167
+ return result.environment;
168
+ }
169
+ if (sanitized.startsWith("app_")) {
170
+ const result = validateAppId(sanitized);
171
+ if (!result.valid) {
172
+ throw new Error(result.error);
173
+ }
174
+ return result.environment;
175
+ }
176
+ throw new Error(
177
+ `[Sylphx] Invalid key format. Key must start with 'sk_' (secret) or 'app_' (App ID).`
178
+ );
179
+ }
180
+ function getCookieNamespace(secretKey) {
181
+ const env = detectEnvironment(secretKey);
182
+ const shortEnv = env === "development" ? "dev" : env === "staging" ? "stg" : "prod";
183
+ return `sylphx_${shortEnv}`;
184
+ }
185
+
186
+ // src/nextjs/cookies.ts
187
+ import { cookies } from "next/headers";
188
+ function getCookieNames(namespace) {
189
+ return {
190
+ /** HttpOnly JWT access token (5 min) */
191
+ SESSION: `__${namespace}_session`,
192
+ /** HttpOnly refresh token (30 days) */
193
+ REFRESH: `__${namespace}_refresh`,
194
+ /** JS-readable user data for client hydration (5 min) */
195
+ USER: `__${namespace}_user`
196
+ };
197
+ }
198
+ var SESSION_TOKEN_LIFETIME = SESSION_TOKEN_LIFETIME_SECONDS;
199
+ var REFRESH_TOKEN_LIFETIME = REFRESH_TOKEN_LIFETIME_SECONDS;
200
+ var SECURE_COOKIE_OPTIONS = {
201
+ httpOnly: true,
202
+ secure: process.env.NODE_ENV === "production",
203
+ sameSite: "lax",
204
+ path: "/"
205
+ };
206
+ var USER_COOKIE_OPTIONS = {
207
+ httpOnly: false,
208
+ // Readable by client JS for hydration
209
+ secure: process.env.NODE_ENV === "production",
210
+ sameSite: "lax",
211
+ path: "/"
212
+ };
213
+ async function getAuthCookies(namespace) {
214
+ const cookieStore = await cookies();
215
+ const names = getCookieNames(namespace);
216
+ const sessionToken = cookieStore.get(names.SESSION)?.value || null;
217
+ const refreshToken = cookieStore.get(names.REFRESH)?.value || null;
218
+ const userCookieValue = cookieStore.get(names.USER)?.value || null;
219
+ let user = null;
220
+ let expiresAt = null;
221
+ if (userCookieValue) {
222
+ try {
223
+ const parsed = JSON.parse(userCookieValue);
224
+ user = parsed.user;
225
+ expiresAt = parsed.expiresAt;
226
+ } catch {
227
+ user = null;
228
+ expiresAt = null;
229
+ }
230
+ }
231
+ return { sessionToken, refreshToken, user, expiresAt };
232
+ }
233
+ async function setAuthCookies(namespace, response, options) {
234
+ const cookieStore = await cookies();
235
+ const names = getCookieNames(namespace);
236
+ const sessionLifetime = options?.sessionLifetime ?? SESSION_TOKEN_LIFETIME;
237
+ const expiresAt = Date.now() + sessionLifetime * 1e3;
238
+ cookieStore.set(names.SESSION, response.accessToken, {
239
+ ...SECURE_COOKIE_OPTIONS,
240
+ maxAge: sessionLifetime
241
+ });
242
+ cookieStore.set(names.REFRESH, response.refreshToken, {
243
+ ...SECURE_COOKIE_OPTIONS,
244
+ maxAge: REFRESH_TOKEN_LIFETIME
245
+ });
246
+ const userData = {
247
+ user: response.user,
248
+ expiresAt
249
+ };
250
+ cookieStore.set(names.USER, JSON.stringify(userData), {
251
+ ...USER_COOKIE_OPTIONS,
252
+ maxAge: sessionLifetime
253
+ });
254
+ }
255
+ async function clearAuthCookies(namespace) {
256
+ const cookieStore = await cookies();
257
+ const names = getCookieNames(namespace);
258
+ cookieStore.delete(names.SESSION);
259
+ cookieStore.delete(names.REFRESH);
260
+ cookieStore.delete(names.USER);
261
+ }
262
+ async function isSessionExpired(namespace) {
263
+ const { expiresAt } = await getAuthCookies(namespace);
264
+ if (!expiresAt) return true;
265
+ return expiresAt < Date.now() + TOKEN_EXPIRY_BUFFER_MS;
266
+ }
267
+ async function hasRefreshToken(namespace) {
268
+ const { refreshToken } = await getAuthCookies(namespace);
269
+ return !!refreshToken;
270
+ }
271
+ function setAuthCookiesMiddleware(response, namespace, tokens) {
272
+ const names = getCookieNames(namespace);
273
+ const expiresAt = Date.now() + SESSION_TOKEN_LIFETIME * 1e3;
274
+ response.cookies.set(names.SESSION, tokens.accessToken, {
275
+ ...SECURE_COOKIE_OPTIONS,
276
+ maxAge: SESSION_TOKEN_LIFETIME
277
+ });
278
+ response.cookies.set(names.REFRESH, tokens.refreshToken, {
279
+ ...SECURE_COOKIE_OPTIONS,
280
+ maxAge: REFRESH_TOKEN_LIFETIME
281
+ });
282
+ const userData = {
283
+ user: tokens.user,
284
+ expiresAt
285
+ };
286
+ response.cookies.set(names.USER, JSON.stringify(userData), {
287
+ ...USER_COOKIE_OPTIONS,
288
+ maxAge: SESSION_TOKEN_LIFETIME
289
+ });
290
+ }
291
+ function clearAuthCookiesMiddleware(response, namespace) {
292
+ const names = getCookieNames(namespace);
293
+ response.cookies.delete(names.SESSION);
294
+ response.cookies.delete(names.REFRESH);
295
+ response.cookies.delete(names.USER);
296
+ }
297
+ function parseUserCookie(value) {
298
+ try {
299
+ return JSON.parse(value);
300
+ } catch {
301
+ return null;
302
+ }
303
+ }
304
+
305
+ // src/nextjs/middleware.ts
306
+ function isTokenResponse(data) {
307
+ return typeof data === "object" && data !== null && "accessToken" in data && "refreshToken" in data && "user" in data && typeof data.accessToken === "string" && typeof data.refreshToken === "string";
308
+ }
309
+ function decodeJwtPayload(token) {
310
+ try {
311
+ const parts = token.split(".");
312
+ if (parts.length !== 3) return null;
313
+ const payload = parts[1];
314
+ const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
315
+ const jsonPayload = atob(base64);
316
+ return JSON.parse(jsonPayload);
317
+ } catch {
318
+ return null;
319
+ }
320
+ }
321
+ function isTokenExpired(token) {
322
+ const payload = decodeJwtPayload(token);
323
+ if (!payload?.exp) return true;
324
+ return payload.exp * 1e3 < Date.now() + TOKEN_EXPIRY_BUFFER_MS;
325
+ }
326
+ function matchesPattern(pathname, pattern) {
327
+ if (pattern === pathname) return true;
328
+ if (pattern.endsWith("/*")) {
329
+ const base = pattern.slice(0, -2);
330
+ return pathname === base || pathname.startsWith(`${base}/`);
331
+ }
332
+ if (pattern.endsWith("/**")) {
333
+ const base = pattern.slice(0, -3);
334
+ return pathname === base || pathname.startsWith(`${base}/`);
335
+ }
336
+ return false;
337
+ }
338
+ function matchesAny(pathname, patterns) {
339
+ return patterns.some((p) => matchesPattern(pathname, p));
340
+ }
341
+ async function handleCallback(request, ctx) {
342
+ const { searchParams } = request.nextUrl;
343
+ const code = searchParams.get("code");
344
+ const error = searchParams.get("error");
345
+ const errorDescription = searchParams.get("error_description");
346
+ const redirectTo = searchParams.get("redirect_to") || ctx.config.afterSignInUrl;
347
+ ctx.log("Callback", { hasCode: !!code, error });
348
+ if (error) {
349
+ const url = new URL(ctx.config.signInUrl, request.url);
350
+ url.searchParams.set("error", error);
351
+ if (errorDescription) url.searchParams.set("error_description", errorDescription);
352
+ return NextResponse.redirect(url);
353
+ }
354
+ if (!code) {
355
+ const url = new URL(ctx.config.signInUrl, request.url);
356
+ url.searchParams.set("error", "missing_code");
357
+ return NextResponse.redirect(url);
358
+ }
359
+ try {
360
+ const res = await fetch(`${ctx.platformUrl}/api/v1/auth/token`, {
361
+ method: "POST",
362
+ headers: { "Content-Type": "application/json" },
363
+ body: JSON.stringify({
364
+ grant_type: "authorization_code",
365
+ code,
366
+ client_secret: ctx.secretKey
367
+ })
368
+ });
369
+ if (!res.ok) {
370
+ const data2 = await res.json().catch(() => ({}));
371
+ const url = new URL(ctx.config.signInUrl, request.url);
372
+ url.searchParams.set("error", data2.error || "token_exchange_failed");
373
+ return NextResponse.redirect(url);
374
+ }
375
+ const data = await res.json();
376
+ if (!isTokenResponse(data)) {
377
+ const url = new URL(ctx.config.signInUrl, request.url);
378
+ url.searchParams.set("error", "invalid_response");
379
+ return NextResponse.redirect(url);
380
+ }
381
+ const successUrl = new URL(redirectTo, request.url);
382
+ const response = NextResponse.redirect(successUrl);
383
+ setAuthCookiesMiddleware(response, ctx.namespace, data);
384
+ ctx.log("Callback success", { redirectTo });
385
+ return response;
386
+ } catch (err) {
387
+ console.error("[Sylphx] Callback error:", err);
388
+ const url = new URL(ctx.config.signInUrl, request.url);
389
+ url.searchParams.set("error", "internal_error");
390
+ return NextResponse.redirect(url);
391
+ }
392
+ }
393
+ async function handleSignOut(request, ctx) {
394
+ ctx.log("Signout");
395
+ const refreshToken = request.cookies.get(ctx.cookieNames.REFRESH)?.value;
396
+ if (refreshToken) {
397
+ try {
398
+ await fetch(`${ctx.platformUrl}/api/v1/auth/revoke`, {
399
+ method: "POST",
400
+ headers: { "Content-Type": "application/json" },
401
+ body: JSON.stringify({
402
+ token: refreshToken,
403
+ client_secret: ctx.secretKey
404
+ })
405
+ });
406
+ } catch {
407
+ }
408
+ }
409
+ const url = new URL(ctx.config.afterSignOutUrl, request.url);
410
+ const response = NextResponse.redirect(url);
411
+ clearAuthCookiesMiddleware(response, ctx.namespace);
412
+ ctx.log("Signout complete");
413
+ return response;
414
+ }
415
+ function handleToken(request, ctx) {
416
+ ctx.log("Token request");
417
+ const sessionToken = request.cookies.get(ctx.cookieNames.SESSION)?.value;
418
+ if (!sessionToken) {
419
+ ctx.log("No session token");
420
+ return NextResponse.json({ error: "Not authenticated", accessToken: null }, { status: 401 });
421
+ }
422
+ if (isTokenExpired(sessionToken)) {
423
+ ctx.log("Session token expired");
424
+ return NextResponse.json({ error: "Session expired", accessToken: null }, { status: 401 });
425
+ }
426
+ ctx.log("Token returned");
427
+ return NextResponse.json({ accessToken: sessionToken });
428
+ }
429
+ async function refreshTokens(refreshToken, ctx) {
430
+ ctx.log("Refreshing tokens");
431
+ try {
432
+ const res = await fetch(`${ctx.platformUrl}/api/v1/auth/token`, {
433
+ method: "POST",
434
+ headers: { "Content-Type": "application/json" },
435
+ body: JSON.stringify({
436
+ grant_type: "refresh_token",
437
+ refresh_token: refreshToken,
438
+ client_secret: ctx.secretKey
439
+ })
440
+ });
441
+ if (!res.ok) {
442
+ ctx.log("Refresh failed", res.status);
443
+ return null;
444
+ }
445
+ const data = await res.json();
446
+ if (!isTokenResponse(data)) {
447
+ ctx.log("Invalid refresh response");
448
+ return null;
449
+ }
450
+ ctx.log("Refresh success");
451
+ return data;
452
+ } catch (err) {
453
+ ctx.log("Refresh error", err);
454
+ return null;
455
+ }
456
+ }
457
+ function createSylphxMiddleware(userConfig = {}) {
458
+ const rawSecretKey = userConfig.secretKey || process.env.SYLPHX_SECRET_KEY;
459
+ if (!rawSecretKey) {
460
+ throw new Error(
461
+ "[Sylphx] Secret key is required.\nEither pass secretKey in config or set SYLPHX_SECRET_KEY env var.\nGet your key from Sylphx Console \u2192 API Keys."
462
+ );
463
+ }
464
+ const secretKey = validateAndSanitizeSecretKey(rawSecretKey);
465
+ const platformUrl = (userConfig.platformUrl || process.env.SYLPHX_PLATFORM_URL || DEFAULT_PLATFORM_URL).trim();
466
+ const namespace = getCookieNamespace(secretKey);
467
+ const cookieNames = getCookieNames(namespace);
468
+ const config = {
469
+ publicRoutes: userConfig.publicRoutes ?? ["/"],
470
+ ignoredRoutes: userConfig.ignoredRoutes ?? [],
471
+ signInUrl: userConfig.signInUrl ?? "/login",
472
+ afterSignOutUrl: userConfig.afterSignOutUrl ?? "/",
473
+ afterSignInUrl: userConfig.afterSignInUrl ?? "/dashboard",
474
+ authPrefix: userConfig.authPrefix ?? "/auth",
475
+ debug: userConfig.debug ?? false,
476
+ onResponse: userConfig.onResponse
477
+ };
478
+ const publicRoutes = [
479
+ ...config.publicRoutes,
480
+ config.signInUrl,
481
+ "/signup",
482
+ `${config.authPrefix}/*`
483
+ ];
484
+ const log = (msg, data) => {
485
+ if (config.debug) {
486
+ console.log(`[Sylphx] ${msg}`, data ?? "");
487
+ }
488
+ };
489
+ const ctx = {
490
+ secretKey,
491
+ platformUrl,
492
+ namespace,
493
+ cookieNames,
494
+ config,
495
+ log
496
+ };
497
+ return async function middleware(request) {
498
+ const { pathname } = request.nextUrl;
499
+ log(`${request.method} ${pathname}`);
500
+ if (matchesAny(pathname, config.ignoredRoutes)) {
501
+ log("Ignored route");
502
+ return NextResponse.next();
503
+ }
504
+ if (pathname.includes(".") || pathname.startsWith("/_next")) {
505
+ return NextResponse.next();
506
+ }
507
+ if (pathname === `${config.authPrefix}/callback`) {
508
+ return handleCallback(request, ctx);
509
+ }
510
+ if (pathname === `${config.authPrefix}/signout`) {
511
+ return handleSignOut(request, ctx);
512
+ }
513
+ if (pathname === `${config.authPrefix}/token`) {
514
+ return handleToken(request, ctx);
515
+ }
516
+ const sessionToken = request.cookies.get(cookieNames.SESSION)?.value;
517
+ const refreshToken = request.cookies.get(cookieNames.REFRESH)?.value;
518
+ const hasValidSession = sessionToken && !isTokenExpired(sessionToken);
519
+ const response = NextResponse.next();
520
+ let isAuthenticated = hasValidSession;
521
+ if (!hasValidSession && refreshToken) {
522
+ log("Session expired, refreshing");
523
+ const tokens = await refreshTokens(refreshToken, ctx);
524
+ if (tokens) {
525
+ setAuthCookiesMiddleware(response, namespace, tokens);
526
+ isAuthenticated = true;
527
+ } else {
528
+ clearAuthCookiesMiddleware(response, namespace);
529
+ isAuthenticated = false;
530
+ }
531
+ }
532
+ const isPublic = matchesAny(pathname, publicRoutes);
533
+ if (!isPublic && !isAuthenticated) {
534
+ log("Redirecting to sign-in");
535
+ const url = new URL(config.signInUrl, request.url);
536
+ url.searchParams.set("redirect_to", pathname);
537
+ return NextResponse.redirect(url);
538
+ }
539
+ if (isAuthenticated && pathname === config.signInUrl) {
540
+ log("Redirecting from sign-in to dashboard");
541
+ return NextResponse.redirect(new URL(config.afterSignInUrl, request.url));
542
+ }
543
+ if (config.onResponse) {
544
+ await config.onResponse(response, request);
545
+ }
546
+ return response;
547
+ };
548
+ }
549
+ function createMatcher() {
550
+ return {
551
+ matcher: ["/((?!_next|monitoring|.*\\..*).*)", "/"]
552
+ };
553
+ }
554
+ function getNamespace(secretKey) {
555
+ return getCookieNamespace(validateAndSanitizeSecretKey(secretKey));
556
+ }
557
+
558
+ // src/nextjs/server.ts
559
+ import { cache as cache2 } from "react";
560
+
561
+ // ../../node_modules/jose/dist/webapi/lib/buffer_utils.js
562
+ var encoder = new TextEncoder();
563
+ var decoder = new TextDecoder();
564
+ var MAX_INT32 = 2 ** 32;
565
+ function concat(...buffers) {
566
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
567
+ const buf = new Uint8Array(size);
568
+ let i = 0;
569
+ for (const buffer of buffers) {
570
+ buf.set(buffer, i);
571
+ i += buffer.length;
572
+ }
573
+ return buf;
574
+ }
575
+ function encode(string) {
576
+ const bytes = new Uint8Array(string.length);
577
+ for (let i = 0; i < string.length; i++) {
578
+ const code = string.charCodeAt(i);
579
+ if (code > 127) {
580
+ throw new TypeError("non-ASCII string encountered in encode()");
581
+ }
582
+ bytes[i] = code;
583
+ }
584
+ return bytes;
585
+ }
586
+
587
+ // ../../node_modules/jose/dist/webapi/lib/base64.js
588
+ function decodeBase64(encoded) {
589
+ if (Uint8Array.fromBase64) {
590
+ return Uint8Array.fromBase64(encoded);
591
+ }
592
+ const binary = atob(encoded);
593
+ const bytes = new Uint8Array(binary.length);
594
+ for (let i = 0; i < binary.length; i++) {
595
+ bytes[i] = binary.charCodeAt(i);
596
+ }
597
+ return bytes;
598
+ }
599
+
600
+ // ../../node_modules/jose/dist/webapi/util/base64url.js
601
+ function decode(input) {
602
+ if (Uint8Array.fromBase64) {
603
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
604
+ alphabet: "base64url"
605
+ });
606
+ }
607
+ let encoded = input;
608
+ if (encoded instanceof Uint8Array) {
609
+ encoded = decoder.decode(encoded);
610
+ }
611
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
612
+ try {
613
+ return decodeBase64(encoded);
614
+ } catch {
615
+ throw new TypeError("The input to be decoded is not correctly encoded.");
616
+ }
617
+ }
618
+
619
+ // ../../node_modules/jose/dist/webapi/util/errors.js
620
+ var JOSEError = class extends Error {
621
+ static code = "ERR_JOSE_GENERIC";
622
+ code = "ERR_JOSE_GENERIC";
623
+ constructor(message2, options) {
624
+ super(message2, options);
625
+ this.name = this.constructor.name;
626
+ Error.captureStackTrace?.(this, this.constructor);
627
+ }
628
+ };
629
+ var JWTClaimValidationFailed = class extends JOSEError {
630
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
631
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
632
+ claim;
633
+ reason;
634
+ payload;
635
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
636
+ super(message2, { cause: { claim, reason, payload } });
637
+ this.claim = claim;
638
+ this.reason = reason;
639
+ this.payload = payload;
640
+ }
641
+ };
642
+ var JWTExpired = class extends JOSEError {
643
+ static code = "ERR_JWT_EXPIRED";
644
+ code = "ERR_JWT_EXPIRED";
645
+ claim;
646
+ reason;
647
+ payload;
648
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
649
+ super(message2, { cause: { claim, reason, payload } });
650
+ this.claim = claim;
651
+ this.reason = reason;
652
+ this.payload = payload;
653
+ }
654
+ };
655
+ var JOSEAlgNotAllowed = class extends JOSEError {
656
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
657
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
658
+ };
659
+ var JOSENotSupported = class extends JOSEError {
660
+ static code = "ERR_JOSE_NOT_SUPPORTED";
661
+ code = "ERR_JOSE_NOT_SUPPORTED";
662
+ };
663
+ var JWSInvalid = class extends JOSEError {
664
+ static code = "ERR_JWS_INVALID";
665
+ code = "ERR_JWS_INVALID";
666
+ };
667
+ var JWTInvalid = class extends JOSEError {
668
+ static code = "ERR_JWT_INVALID";
669
+ code = "ERR_JWT_INVALID";
670
+ };
671
+ var JWSSignatureVerificationFailed = class extends JOSEError {
672
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
673
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
674
+ constructor(message2 = "signature verification failed", options) {
675
+ super(message2, options);
676
+ }
677
+ };
678
+
679
+ // ../../node_modules/jose/dist/webapi/lib/crypto_key.js
680
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
681
+ var isAlgorithm = (algorithm, name) => algorithm.name === name;
682
+ function getHashLength(hash) {
683
+ return parseInt(hash.name.slice(4), 10);
684
+ }
685
+ function getNamedCurve(alg) {
686
+ switch (alg) {
687
+ case "ES256":
688
+ return "P-256";
689
+ case "ES384":
690
+ return "P-384";
691
+ case "ES512":
692
+ return "P-521";
693
+ default:
694
+ throw new Error("unreachable");
695
+ }
696
+ }
697
+ function checkUsage(key, usage) {
698
+ if (usage && !key.usages.includes(usage)) {
699
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
700
+ }
701
+ }
702
+ function checkSigCryptoKey(key, alg, usage) {
703
+ switch (alg) {
704
+ case "HS256":
705
+ case "HS384":
706
+ case "HS512": {
707
+ if (!isAlgorithm(key.algorithm, "HMAC"))
708
+ throw unusable("HMAC");
709
+ const expected = parseInt(alg.slice(2), 10);
710
+ const actual = getHashLength(key.algorithm.hash);
711
+ if (actual !== expected)
712
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
713
+ break;
714
+ }
715
+ case "RS256":
716
+ case "RS384":
717
+ case "RS512": {
718
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
719
+ throw unusable("RSASSA-PKCS1-v1_5");
720
+ const expected = parseInt(alg.slice(2), 10);
721
+ const actual = getHashLength(key.algorithm.hash);
722
+ if (actual !== expected)
723
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
724
+ break;
725
+ }
726
+ case "PS256":
727
+ case "PS384":
728
+ case "PS512": {
729
+ if (!isAlgorithm(key.algorithm, "RSA-PSS"))
730
+ throw unusable("RSA-PSS");
731
+ const expected = parseInt(alg.slice(2), 10);
732
+ const actual = getHashLength(key.algorithm.hash);
733
+ if (actual !== expected)
734
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
735
+ break;
736
+ }
737
+ case "Ed25519":
738
+ case "EdDSA": {
739
+ if (!isAlgorithm(key.algorithm, "Ed25519"))
740
+ throw unusable("Ed25519");
741
+ break;
742
+ }
743
+ case "ML-DSA-44":
744
+ case "ML-DSA-65":
745
+ case "ML-DSA-87": {
746
+ if (!isAlgorithm(key.algorithm, alg))
747
+ throw unusable(alg);
748
+ break;
749
+ }
750
+ case "ES256":
751
+ case "ES384":
752
+ case "ES512": {
753
+ if (!isAlgorithm(key.algorithm, "ECDSA"))
754
+ throw unusable("ECDSA");
755
+ const expected = getNamedCurve(alg);
756
+ const actual = key.algorithm.namedCurve;
757
+ if (actual !== expected)
758
+ throw unusable(expected, "algorithm.namedCurve");
759
+ break;
760
+ }
761
+ default:
762
+ throw new TypeError("CryptoKey does not support this operation");
763
+ }
764
+ checkUsage(key, usage);
765
+ }
766
+
767
+ // ../../node_modules/jose/dist/webapi/lib/invalid_key_input.js
768
+ function message(msg, actual, ...types) {
769
+ types = types.filter(Boolean);
770
+ if (types.length > 2) {
771
+ const last = types.pop();
772
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
773
+ } else if (types.length === 2) {
774
+ msg += `one of type ${types[0]} or ${types[1]}.`;
775
+ } else {
776
+ msg += `of type ${types[0]}.`;
777
+ }
778
+ if (actual == null) {
779
+ msg += ` Received ${actual}`;
780
+ } else if (typeof actual === "function" && actual.name) {
781
+ msg += ` Received function ${actual.name}`;
782
+ } else if (typeof actual === "object" && actual != null) {
783
+ if (actual.constructor?.name) {
784
+ msg += ` Received an instance of ${actual.constructor.name}`;
785
+ }
786
+ }
787
+ return msg;
788
+ }
789
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
790
+ var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
791
+
792
+ // ../../node_modules/jose/dist/webapi/lib/is_key_like.js
793
+ var isCryptoKey = (key) => {
794
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
795
+ return true;
796
+ try {
797
+ return key instanceof CryptoKey;
798
+ } catch {
799
+ return false;
800
+ }
801
+ };
802
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
803
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
804
+
805
+ // ../../node_modules/jose/dist/webapi/lib/is_disjoint.js
806
+ function isDisjoint(...headers) {
807
+ const sources = headers.filter(Boolean);
808
+ if (sources.length === 0 || sources.length === 1) {
809
+ return true;
810
+ }
811
+ let acc;
812
+ for (const header of sources) {
813
+ const parameters = Object.keys(header);
814
+ if (!acc || acc.size === 0) {
815
+ acc = new Set(parameters);
816
+ continue;
817
+ }
818
+ for (const parameter of parameters) {
819
+ if (acc.has(parameter)) {
820
+ return false;
821
+ }
822
+ acc.add(parameter);
823
+ }
824
+ }
825
+ return true;
826
+ }
827
+
828
+ // ../../node_modules/jose/dist/webapi/lib/is_object.js
829
+ var isObjectLike = (value) => typeof value === "object" && value !== null;
830
+ function isObject(input) {
831
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
832
+ return false;
833
+ }
834
+ if (Object.getPrototypeOf(input) === null) {
835
+ return true;
836
+ }
837
+ let proto = input;
838
+ while (Object.getPrototypeOf(proto) !== null) {
839
+ proto = Object.getPrototypeOf(proto);
840
+ }
841
+ return Object.getPrototypeOf(input) === proto;
842
+ }
843
+
844
+ // ../../node_modules/jose/dist/webapi/lib/check_key_length.js
845
+ function checkKeyLength(alg, key) {
846
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
847
+ const { modulusLength } = key.algorithm;
848
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
849
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
850
+ }
851
+ }
852
+ }
853
+
854
+ // ../../node_modules/jose/dist/webapi/lib/jwk_to_key.js
855
+ function subtleMapping(jwk) {
856
+ let algorithm;
857
+ let keyUsages;
858
+ switch (jwk.kty) {
859
+ case "AKP": {
860
+ switch (jwk.alg) {
861
+ case "ML-DSA-44":
862
+ case "ML-DSA-65":
863
+ case "ML-DSA-87":
864
+ algorithm = { name: jwk.alg };
865
+ keyUsages = jwk.priv ? ["sign"] : ["verify"];
866
+ break;
867
+ default:
868
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
869
+ }
870
+ break;
871
+ }
872
+ case "RSA": {
873
+ switch (jwk.alg) {
874
+ case "PS256":
875
+ case "PS384":
876
+ case "PS512":
877
+ algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
878
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
879
+ break;
880
+ case "RS256":
881
+ case "RS384":
882
+ case "RS512":
883
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
884
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
885
+ break;
886
+ case "RSA-OAEP":
887
+ case "RSA-OAEP-256":
888
+ case "RSA-OAEP-384":
889
+ case "RSA-OAEP-512":
890
+ algorithm = {
891
+ name: "RSA-OAEP",
892
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
893
+ };
894
+ keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
895
+ break;
896
+ default:
897
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
898
+ }
899
+ break;
900
+ }
901
+ case "EC": {
902
+ switch (jwk.alg) {
903
+ case "ES256":
904
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
905
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
906
+ break;
907
+ case "ES384":
908
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
909
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
910
+ break;
911
+ case "ES512":
912
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
913
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
914
+ break;
915
+ case "ECDH-ES":
916
+ case "ECDH-ES+A128KW":
917
+ case "ECDH-ES+A192KW":
918
+ case "ECDH-ES+A256KW":
919
+ algorithm = { name: "ECDH", namedCurve: jwk.crv };
920
+ keyUsages = jwk.d ? ["deriveBits"] : [];
921
+ break;
922
+ default:
923
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
924
+ }
925
+ break;
926
+ }
927
+ case "OKP": {
928
+ switch (jwk.alg) {
929
+ case "Ed25519":
930
+ case "EdDSA":
931
+ algorithm = { name: "Ed25519" };
932
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
933
+ break;
934
+ case "ECDH-ES":
935
+ case "ECDH-ES+A128KW":
936
+ case "ECDH-ES+A192KW":
937
+ case "ECDH-ES+A256KW":
938
+ algorithm = { name: jwk.crv };
939
+ keyUsages = jwk.d ? ["deriveBits"] : [];
940
+ break;
941
+ default:
942
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
943
+ }
944
+ break;
945
+ }
946
+ default:
947
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
948
+ }
949
+ return { algorithm, keyUsages };
950
+ }
951
+ async function jwkToKey(jwk) {
952
+ if (!jwk.alg) {
953
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
954
+ }
955
+ const { algorithm, keyUsages } = subtleMapping(jwk);
956
+ const keyData = { ...jwk };
957
+ if (keyData.kty !== "AKP") {
958
+ delete keyData.alg;
959
+ }
960
+ delete keyData.use;
961
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
962
+ }
963
+
964
+ // ../../node_modules/jose/dist/webapi/key/import.js
965
+ async function importJWK(jwk, alg, options) {
966
+ if (!isObject(jwk)) {
967
+ throw new TypeError("JWK must be an object");
968
+ }
969
+ let ext;
970
+ alg ??= jwk.alg;
971
+ ext ??= options?.extractable ?? jwk.ext;
972
+ switch (jwk.kty) {
973
+ case "oct":
974
+ if (typeof jwk.k !== "string" || !jwk.k) {
975
+ throw new TypeError('missing "k" (Key Value) Parameter value');
976
+ }
977
+ return decode(jwk.k);
978
+ case "RSA":
979
+ if ("oth" in jwk && jwk.oth !== void 0) {
980
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
981
+ }
982
+ return jwkToKey({ ...jwk, alg, ext });
983
+ case "AKP": {
984
+ if (typeof jwk.alg !== "string" || !jwk.alg) {
985
+ throw new TypeError('missing "alg" (Algorithm) Parameter value');
986
+ }
987
+ if (alg !== void 0 && alg !== jwk.alg) {
988
+ throw new TypeError("JWK alg and alg option value mismatch");
989
+ }
990
+ return jwkToKey({ ...jwk, ext });
991
+ }
992
+ case "EC":
993
+ case "OKP":
994
+ return jwkToKey({ ...jwk, alg, ext });
995
+ default:
996
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
997
+ }
998
+ }
999
+
1000
+ // ../../node_modules/jose/dist/webapi/lib/validate_crit.js
1001
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
1002
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
1003
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
1004
+ }
1005
+ if (!protectedHeader || protectedHeader.crit === void 0) {
1006
+ return /* @__PURE__ */ new Set();
1007
+ }
1008
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
1009
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
1010
+ }
1011
+ let recognized;
1012
+ if (recognizedOption !== void 0) {
1013
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
1014
+ } else {
1015
+ recognized = recognizedDefault;
1016
+ }
1017
+ for (const parameter of protectedHeader.crit) {
1018
+ if (!recognized.has(parameter)) {
1019
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
1020
+ }
1021
+ if (joseHeader[parameter] === void 0) {
1022
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
1023
+ }
1024
+ if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
1025
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
1026
+ }
1027
+ }
1028
+ return new Set(protectedHeader.crit);
1029
+ }
1030
+
1031
+ // ../../node_modules/jose/dist/webapi/lib/validate_algorithms.js
1032
+ function validateAlgorithms(option, algorithms) {
1033
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
1034
+ throw new TypeError(`"${option}" option must be an array of strings`);
1035
+ }
1036
+ if (!algorithms) {
1037
+ return void 0;
1038
+ }
1039
+ return new Set(algorithms);
1040
+ }
1041
+
1042
+ // ../../node_modules/jose/dist/webapi/lib/is_jwk.js
1043
+ var isJWK = (key) => isObject(key) && typeof key.kty === "string";
1044
+ var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
1045
+ var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
1046
+ var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
1047
+
1048
+ // ../../node_modules/jose/dist/webapi/lib/normalize_key.js
1049
+ var cache;
1050
+ var handleJWK = async (key, jwk, alg, freeze = false) => {
1051
+ cache ||= /* @__PURE__ */ new WeakMap();
1052
+ let cached = cache.get(key);
1053
+ if (cached?.[alg]) {
1054
+ return cached[alg];
1055
+ }
1056
+ const cryptoKey = await jwkToKey({ ...jwk, alg });
1057
+ if (freeze)
1058
+ Object.freeze(key);
1059
+ if (!cached) {
1060
+ cache.set(key, { [alg]: cryptoKey });
1061
+ } else {
1062
+ cached[alg] = cryptoKey;
1063
+ }
1064
+ return cryptoKey;
1065
+ };
1066
+ var handleKeyObject = (keyObject, alg) => {
1067
+ cache ||= /* @__PURE__ */ new WeakMap();
1068
+ let cached = cache.get(keyObject);
1069
+ if (cached?.[alg]) {
1070
+ return cached[alg];
1071
+ }
1072
+ const isPublic = keyObject.type === "public";
1073
+ const extractable = isPublic ? true : false;
1074
+ let cryptoKey;
1075
+ if (keyObject.asymmetricKeyType === "x25519") {
1076
+ switch (alg) {
1077
+ case "ECDH-ES":
1078
+ case "ECDH-ES+A128KW":
1079
+ case "ECDH-ES+A192KW":
1080
+ case "ECDH-ES+A256KW":
1081
+ break;
1082
+ default:
1083
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1084
+ }
1085
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
1086
+ }
1087
+ if (keyObject.asymmetricKeyType === "ed25519") {
1088
+ if (alg !== "EdDSA" && alg !== "Ed25519") {
1089
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1090
+ }
1091
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
1092
+ isPublic ? "verify" : "sign"
1093
+ ]);
1094
+ }
1095
+ switch (keyObject.asymmetricKeyType) {
1096
+ case "ml-dsa-44":
1097
+ case "ml-dsa-65":
1098
+ case "ml-dsa-87": {
1099
+ if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
1100
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1101
+ }
1102
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
1103
+ isPublic ? "verify" : "sign"
1104
+ ]);
1105
+ }
1106
+ }
1107
+ if (keyObject.asymmetricKeyType === "rsa") {
1108
+ let hash;
1109
+ switch (alg) {
1110
+ case "RSA-OAEP":
1111
+ hash = "SHA-1";
1112
+ break;
1113
+ case "RS256":
1114
+ case "PS256":
1115
+ case "RSA-OAEP-256":
1116
+ hash = "SHA-256";
1117
+ break;
1118
+ case "RS384":
1119
+ case "PS384":
1120
+ case "RSA-OAEP-384":
1121
+ hash = "SHA-384";
1122
+ break;
1123
+ case "RS512":
1124
+ case "PS512":
1125
+ case "RSA-OAEP-512":
1126
+ hash = "SHA-512";
1127
+ break;
1128
+ default:
1129
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1130
+ }
1131
+ if (alg.startsWith("RSA-OAEP")) {
1132
+ return keyObject.toCryptoKey({
1133
+ name: "RSA-OAEP",
1134
+ hash
1135
+ }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
1136
+ }
1137
+ cryptoKey = keyObject.toCryptoKey({
1138
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
1139
+ hash
1140
+ }, extractable, [isPublic ? "verify" : "sign"]);
1141
+ }
1142
+ if (keyObject.asymmetricKeyType === "ec") {
1143
+ const nist = /* @__PURE__ */ new Map([
1144
+ ["prime256v1", "P-256"],
1145
+ ["secp384r1", "P-384"],
1146
+ ["secp521r1", "P-521"]
1147
+ ]);
1148
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
1149
+ if (!namedCurve) {
1150
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1151
+ }
1152
+ if (alg === "ES256" && namedCurve === "P-256") {
1153
+ cryptoKey = keyObject.toCryptoKey({
1154
+ name: "ECDSA",
1155
+ namedCurve
1156
+ }, extractable, [isPublic ? "verify" : "sign"]);
1157
+ }
1158
+ if (alg === "ES384" && namedCurve === "P-384") {
1159
+ cryptoKey = keyObject.toCryptoKey({
1160
+ name: "ECDSA",
1161
+ namedCurve
1162
+ }, extractable, [isPublic ? "verify" : "sign"]);
1163
+ }
1164
+ if (alg === "ES512" && namedCurve === "P-521") {
1165
+ cryptoKey = keyObject.toCryptoKey({
1166
+ name: "ECDSA",
1167
+ namedCurve
1168
+ }, extractable, [isPublic ? "verify" : "sign"]);
1169
+ }
1170
+ if (alg.startsWith("ECDH-ES")) {
1171
+ cryptoKey = keyObject.toCryptoKey({
1172
+ name: "ECDH",
1173
+ namedCurve
1174
+ }, extractable, isPublic ? [] : ["deriveBits"]);
1175
+ }
1176
+ }
1177
+ if (!cryptoKey) {
1178
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1179
+ }
1180
+ if (!cached) {
1181
+ cache.set(keyObject, { [alg]: cryptoKey });
1182
+ } else {
1183
+ cached[alg] = cryptoKey;
1184
+ }
1185
+ return cryptoKey;
1186
+ };
1187
+ async function normalizeKey(key, alg) {
1188
+ if (key instanceof Uint8Array) {
1189
+ return key;
1190
+ }
1191
+ if (isCryptoKey(key)) {
1192
+ return key;
1193
+ }
1194
+ if (isKeyObject(key)) {
1195
+ if (key.type === "secret") {
1196
+ return key.export();
1197
+ }
1198
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
1199
+ try {
1200
+ return handleKeyObject(key, alg);
1201
+ } catch (err) {
1202
+ if (err instanceof TypeError) {
1203
+ throw err;
1204
+ }
1205
+ }
1206
+ }
1207
+ let jwk = key.export({ format: "jwk" });
1208
+ return handleJWK(key, jwk, alg);
1209
+ }
1210
+ if (isJWK(key)) {
1211
+ if (key.k) {
1212
+ return decode(key.k);
1213
+ }
1214
+ return handleJWK(key, key, alg, true);
1215
+ }
1216
+ throw new Error("unreachable");
1217
+ }
1218
+
1219
+ // ../../node_modules/jose/dist/webapi/lib/check_key_type.js
1220
+ var tag = (key) => key?.[Symbol.toStringTag];
1221
+ var jwkMatchesOp = (alg, key, usage) => {
1222
+ if (key.use !== void 0) {
1223
+ let expected;
1224
+ switch (usage) {
1225
+ case "sign":
1226
+ case "verify":
1227
+ expected = "sig";
1228
+ break;
1229
+ case "encrypt":
1230
+ case "decrypt":
1231
+ expected = "enc";
1232
+ break;
1233
+ }
1234
+ if (key.use !== expected) {
1235
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
1236
+ }
1237
+ }
1238
+ if (key.alg !== void 0 && key.alg !== alg) {
1239
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
1240
+ }
1241
+ if (Array.isArray(key.key_ops)) {
1242
+ let expectedKeyOp;
1243
+ switch (true) {
1244
+ case (usage === "sign" || usage === "verify"):
1245
+ case alg === "dir":
1246
+ case alg.includes("CBC-HS"):
1247
+ expectedKeyOp = usage;
1248
+ break;
1249
+ case alg.startsWith("PBES2"):
1250
+ expectedKeyOp = "deriveBits";
1251
+ break;
1252
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
1253
+ if (!alg.includes("GCM") && alg.endsWith("KW")) {
1254
+ expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
1255
+ } else {
1256
+ expectedKeyOp = usage;
1257
+ }
1258
+ break;
1259
+ case (usage === "encrypt" && alg.startsWith("RSA")):
1260
+ expectedKeyOp = "wrapKey";
1261
+ break;
1262
+ case usage === "decrypt":
1263
+ expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
1264
+ break;
1265
+ }
1266
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
1267
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
1268
+ }
1269
+ }
1270
+ return true;
1271
+ };
1272
+ var symmetricTypeCheck = (alg, key, usage) => {
1273
+ if (key instanceof Uint8Array)
1274
+ return;
1275
+ if (isJWK(key)) {
1276
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
1277
+ return;
1278
+ throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
1279
+ }
1280
+ if (!isKeyLike(key)) {
1281
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
1282
+ }
1283
+ if (key.type !== "secret") {
1284
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
1285
+ }
1286
+ };
1287
+ var asymmetricTypeCheck = (alg, key, usage) => {
1288
+ if (isJWK(key)) {
1289
+ switch (usage) {
1290
+ case "decrypt":
1291
+ case "sign":
1292
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
1293
+ return;
1294
+ throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
1295
+ case "encrypt":
1296
+ case "verify":
1297
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
1298
+ return;
1299
+ throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
1300
+ }
1301
+ }
1302
+ if (!isKeyLike(key)) {
1303
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
1304
+ }
1305
+ if (key.type === "secret") {
1306
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
1307
+ }
1308
+ if (key.type === "public") {
1309
+ switch (usage) {
1310
+ case "sign":
1311
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
1312
+ case "decrypt":
1313
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
1314
+ }
1315
+ }
1316
+ if (key.type === "private") {
1317
+ switch (usage) {
1318
+ case "verify":
1319
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
1320
+ case "encrypt":
1321
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
1322
+ }
1323
+ }
1324
+ };
1325
+ function checkKeyType(alg, key, usage) {
1326
+ switch (alg.substring(0, 2)) {
1327
+ case "A1":
1328
+ case "A2":
1329
+ case "di":
1330
+ case "HS":
1331
+ case "PB":
1332
+ symmetricTypeCheck(alg, key, usage);
1333
+ break;
1334
+ default:
1335
+ asymmetricTypeCheck(alg, key, usage);
1336
+ }
1337
+ }
1338
+
1339
+ // ../../node_modules/jose/dist/webapi/lib/subtle_dsa.js
1340
+ function subtleAlgorithm(alg, algorithm) {
1341
+ const hash = `SHA-${alg.slice(-3)}`;
1342
+ switch (alg) {
1343
+ case "HS256":
1344
+ case "HS384":
1345
+ case "HS512":
1346
+ return { hash, name: "HMAC" };
1347
+ case "PS256":
1348
+ case "PS384":
1349
+ case "PS512":
1350
+ return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
1351
+ case "RS256":
1352
+ case "RS384":
1353
+ case "RS512":
1354
+ return { hash, name: "RSASSA-PKCS1-v1_5" };
1355
+ case "ES256":
1356
+ case "ES384":
1357
+ case "ES512":
1358
+ return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
1359
+ case "Ed25519":
1360
+ case "EdDSA":
1361
+ return { name: "Ed25519" };
1362
+ case "ML-DSA-44":
1363
+ case "ML-DSA-65":
1364
+ case "ML-DSA-87":
1365
+ return { name: alg };
1366
+ default:
1367
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
1368
+ }
1369
+ }
1370
+
1371
+ // ../../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
1372
+ async function getSigKey(alg, key, usage) {
1373
+ if (key instanceof Uint8Array) {
1374
+ if (!alg.startsWith("HS")) {
1375
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
1376
+ }
1377
+ return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
1378
+ }
1379
+ checkSigCryptoKey(key, alg, usage);
1380
+ return key;
1381
+ }
1382
+
1383
+ // ../../node_modules/jose/dist/webapi/lib/verify.js
1384
+ async function verify(alg, key, signature, data) {
1385
+ const cryptoKey = await getSigKey(alg, key, "verify");
1386
+ checkKeyLength(alg, cryptoKey);
1387
+ const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
1388
+ try {
1389
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
1390
+ } catch {
1391
+ return false;
1392
+ }
1393
+ }
1394
+
1395
+ // ../../node_modules/jose/dist/webapi/jws/flattened/verify.js
1396
+ async function flattenedVerify(jws, key, options) {
1397
+ if (!isObject(jws)) {
1398
+ throw new JWSInvalid("Flattened JWS must be an object");
1399
+ }
1400
+ if (jws.protected === void 0 && jws.header === void 0) {
1401
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
1402
+ }
1403
+ if (jws.protected !== void 0 && typeof jws.protected !== "string") {
1404
+ throw new JWSInvalid("JWS Protected Header incorrect type");
1405
+ }
1406
+ if (jws.payload === void 0) {
1407
+ throw new JWSInvalid("JWS Payload missing");
1408
+ }
1409
+ if (typeof jws.signature !== "string") {
1410
+ throw new JWSInvalid("JWS Signature missing or incorrect type");
1411
+ }
1412
+ if (jws.header !== void 0 && !isObject(jws.header)) {
1413
+ throw new JWSInvalid("JWS Unprotected Header incorrect type");
1414
+ }
1415
+ let parsedProt = {};
1416
+ if (jws.protected) {
1417
+ try {
1418
+ const protectedHeader = decode(jws.protected);
1419
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
1420
+ } catch {
1421
+ throw new JWSInvalid("JWS Protected Header is invalid");
1422
+ }
1423
+ }
1424
+ if (!isDisjoint(parsedProt, jws.header)) {
1425
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1426
+ }
1427
+ const joseHeader = {
1428
+ ...parsedProt,
1429
+ ...jws.header
1430
+ };
1431
+ const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
1432
+ let b64 = true;
1433
+ if (extensions.has("b64")) {
1434
+ b64 = parsedProt.b64;
1435
+ if (typeof b64 !== "boolean") {
1436
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
1437
+ }
1438
+ }
1439
+ const { alg } = joseHeader;
1440
+ if (typeof alg !== "string" || !alg) {
1441
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
1442
+ }
1443
+ const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
1444
+ if (algorithms && !algorithms.has(alg)) {
1445
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
1446
+ }
1447
+ if (b64) {
1448
+ if (typeof jws.payload !== "string") {
1449
+ throw new JWSInvalid("JWS Payload must be a string");
1450
+ }
1451
+ } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
1452
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
1453
+ }
1454
+ let resolvedKey = false;
1455
+ if (typeof key === "function") {
1456
+ key = await key(parsedProt, jws);
1457
+ resolvedKey = true;
1458
+ }
1459
+ checkKeyType(alg, key, "verify");
1460
+ const data = concat(jws.protected !== void 0 ? encode(jws.protected) : new Uint8Array(), encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
1461
+ let signature;
1462
+ try {
1463
+ signature = decode(jws.signature);
1464
+ } catch {
1465
+ throw new JWSInvalid("Failed to base64url decode the signature");
1466
+ }
1467
+ const k = await normalizeKey(key, alg);
1468
+ const verified = await verify(alg, k, signature, data);
1469
+ if (!verified) {
1470
+ throw new JWSSignatureVerificationFailed();
1471
+ }
1472
+ let payload;
1473
+ if (b64) {
1474
+ try {
1475
+ payload = decode(jws.payload);
1476
+ } catch {
1477
+ throw new JWSInvalid("Failed to base64url decode the payload");
1478
+ }
1479
+ } else if (typeof jws.payload === "string") {
1480
+ payload = encoder.encode(jws.payload);
1481
+ } else {
1482
+ payload = jws.payload;
1483
+ }
1484
+ const result = { payload };
1485
+ if (jws.protected !== void 0) {
1486
+ result.protectedHeader = parsedProt;
1487
+ }
1488
+ if (jws.header !== void 0) {
1489
+ result.unprotectedHeader = jws.header;
1490
+ }
1491
+ if (resolvedKey) {
1492
+ return { ...result, key: k };
1493
+ }
1494
+ return result;
1495
+ }
1496
+
1497
+ // ../../node_modules/jose/dist/webapi/jws/compact/verify.js
1498
+ async function compactVerify(jws, key, options) {
1499
+ if (jws instanceof Uint8Array) {
1500
+ jws = decoder.decode(jws);
1501
+ }
1502
+ if (typeof jws !== "string") {
1503
+ throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
1504
+ }
1505
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
1506
+ if (length !== 3) {
1507
+ throw new JWSInvalid("Invalid Compact JWS");
1508
+ }
1509
+ const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
1510
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
1511
+ if (typeof key === "function") {
1512
+ return { ...result, key: verified.key };
1513
+ }
1514
+ return result;
1515
+ }
1516
+
1517
+ // ../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js
1518
+ var epoch = (date) => Math.floor(date.getTime() / 1e3);
1519
+ var minute = 60;
1520
+ var hour = minute * 60;
1521
+ var day = hour * 24;
1522
+ var week = day * 7;
1523
+ var year = day * 365.25;
1524
+ var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
1525
+ function secs(str) {
1526
+ const matched = REGEX.exec(str);
1527
+ if (!matched || matched[4] && matched[1]) {
1528
+ throw new TypeError("Invalid time period format");
1529
+ }
1530
+ const value = parseFloat(matched[2]);
1531
+ const unit = matched[3].toLowerCase();
1532
+ let numericDate;
1533
+ switch (unit) {
1534
+ case "sec":
1535
+ case "secs":
1536
+ case "second":
1537
+ case "seconds":
1538
+ case "s":
1539
+ numericDate = Math.round(value);
1540
+ break;
1541
+ case "minute":
1542
+ case "minutes":
1543
+ case "min":
1544
+ case "mins":
1545
+ case "m":
1546
+ numericDate = Math.round(value * minute);
1547
+ break;
1548
+ case "hour":
1549
+ case "hours":
1550
+ case "hr":
1551
+ case "hrs":
1552
+ case "h":
1553
+ numericDate = Math.round(value * hour);
1554
+ break;
1555
+ case "day":
1556
+ case "days":
1557
+ case "d":
1558
+ numericDate = Math.round(value * day);
1559
+ break;
1560
+ case "week":
1561
+ case "weeks":
1562
+ case "w":
1563
+ numericDate = Math.round(value * week);
1564
+ break;
1565
+ default:
1566
+ numericDate = Math.round(value * year);
1567
+ break;
1568
+ }
1569
+ if (matched[1] === "-" || matched[4] === "ago") {
1570
+ return -numericDate;
1571
+ }
1572
+ return numericDate;
1573
+ }
1574
+ var normalizeTyp = (value) => {
1575
+ if (value.includes("/")) {
1576
+ return value.toLowerCase();
1577
+ }
1578
+ return `application/${value.toLowerCase()}`;
1579
+ };
1580
+ var checkAudiencePresence = (audPayload, audOption) => {
1581
+ if (typeof audPayload === "string") {
1582
+ return audOption.includes(audPayload);
1583
+ }
1584
+ if (Array.isArray(audPayload)) {
1585
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
1586
+ }
1587
+ return false;
1588
+ };
1589
+ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
1590
+ let payload;
1591
+ try {
1592
+ payload = JSON.parse(decoder.decode(encodedPayload));
1593
+ } catch {
1594
+ }
1595
+ if (!isObject(payload)) {
1596
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
1597
+ }
1598
+ const { typ } = options;
1599
+ if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
1600
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
1601
+ }
1602
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
1603
+ const presenceCheck = [...requiredClaims];
1604
+ if (maxTokenAge !== void 0)
1605
+ presenceCheck.push("iat");
1606
+ if (audience !== void 0)
1607
+ presenceCheck.push("aud");
1608
+ if (subject !== void 0)
1609
+ presenceCheck.push("sub");
1610
+ if (issuer !== void 0)
1611
+ presenceCheck.push("iss");
1612
+ for (const claim of new Set(presenceCheck.reverse())) {
1613
+ if (!(claim in payload)) {
1614
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
1615
+ }
1616
+ }
1617
+ if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
1618
+ throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
1619
+ }
1620
+ if (subject && payload.sub !== subject) {
1621
+ throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
1622
+ }
1623
+ if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
1624
+ throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
1625
+ }
1626
+ let tolerance;
1627
+ switch (typeof options.clockTolerance) {
1628
+ case "string":
1629
+ tolerance = secs(options.clockTolerance);
1630
+ break;
1631
+ case "number":
1632
+ tolerance = options.clockTolerance;
1633
+ break;
1634
+ case "undefined":
1635
+ tolerance = 0;
1636
+ break;
1637
+ default:
1638
+ throw new TypeError("Invalid clockTolerance option type");
1639
+ }
1640
+ const { currentDate } = options;
1641
+ const now = epoch(currentDate || /* @__PURE__ */ new Date());
1642
+ if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
1643
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
1644
+ }
1645
+ if (payload.nbf !== void 0) {
1646
+ if (typeof payload.nbf !== "number") {
1647
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
1648
+ }
1649
+ if (payload.nbf > now + tolerance) {
1650
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
1651
+ }
1652
+ }
1653
+ if (payload.exp !== void 0) {
1654
+ if (typeof payload.exp !== "number") {
1655
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
1656
+ }
1657
+ if (payload.exp <= now - tolerance) {
1658
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
1659
+ }
1660
+ }
1661
+ if (maxTokenAge) {
1662
+ const age = now - payload.iat;
1663
+ const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
1664
+ if (age - tolerance > max) {
1665
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
1666
+ }
1667
+ if (age < 0 - tolerance) {
1668
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
1669
+ }
1670
+ }
1671
+ return payload;
1672
+ }
1673
+
1674
+ // ../../node_modules/jose/dist/webapi/jwt/verify.js
1675
+ async function jwtVerify(jwt, key, options) {
1676
+ const verified = await compactVerify(jwt, key, options);
1677
+ if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
1678
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1679
+ }
1680
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
1681
+ const result = { payload, protectedHeader: verified.protectedHeader };
1682
+ if (typeof key === "function") {
1683
+ return { ...result, key: verified.key };
1684
+ }
1685
+ return result;
1686
+ }
1687
+
1688
+ // src/server/index.ts
1689
+ function isJwksResponse(data) {
1690
+ return typeof data === "object" && data !== null && "keys" in data && Array.isArray(data.keys);
1691
+ }
1692
+ function isAccessTokenPayload(payload) {
1693
+ return typeof payload.sub === "string" && typeof payload.email === "string" && typeof payload.app_id === "string" && typeof payload.iat === "number" && typeof payload.exp === "number";
1694
+ }
1695
+ var jwksCache = null;
1696
+ async function getJwks(platformUrl = DEFAULT_PLATFORM_URL) {
1697
+ const now = Date.now();
1698
+ if (jwksCache && jwksCache.expiresAt > now) {
1699
+ return jwksCache.keys;
1700
+ }
1701
+ const response = await fetch(`${platformUrl}/api/v1/auth/.well-known/jwks.json`);
1702
+ if (!response.ok) {
1703
+ throw new Error("Failed to fetch JWKS");
1704
+ }
1705
+ const data = await response.json();
1706
+ if (!isJwksResponse(data)) {
1707
+ throw new Error("Invalid JWKS response format");
1708
+ }
1709
+ jwksCache = {
1710
+ keys: data.keys,
1711
+ expiresAt: now + JWK_CACHE_TTL_MS
1712
+ // Cache for 1 hour
1713
+ };
1714
+ return data.keys;
1715
+ }
1716
+ async function verifyAccessToken(token, options) {
1717
+ const platformUrl = options.platformUrl || DEFAULT_PLATFORM_URL;
1718
+ const keys = await getJwks(platformUrl);
1719
+ if (!keys.length) {
1720
+ throw new Error("No keys in JWKS");
1721
+ }
1722
+ let lastError = null;
1723
+ for (const key of keys) {
1724
+ try {
1725
+ const jwk = await importJWK(key, "RS256");
1726
+ const { payload } = await jwtVerify(token, jwk, {
1727
+ issuer: platformUrl
1728
+ });
1729
+ if (!isAccessTokenPayload(payload)) {
1730
+ throw new Error("Invalid token payload structure");
1731
+ }
1732
+ return {
1733
+ sub: payload.sub,
1734
+ email: payload.email,
1735
+ name: payload.name,
1736
+ picture: payload.picture,
1737
+ email_verified: payload.email_verified,
1738
+ app_id: payload.app_id,
1739
+ role: payload.role,
1740
+ iat: payload.iat,
1741
+ exp: payload.exp
1742
+ };
1743
+ } catch (err) {
1744
+ lastError = err;
1745
+ }
1746
+ }
1747
+ throw lastError || new Error("Token verification failed");
1748
+ }
1749
+
1750
+ // src/nextjs/server.ts
1751
+ function isTokenResponse2(data) {
1752
+ return typeof data === "object" && data !== null && "accessToken" in data && "refreshToken" in data && "user" in data && typeof data.accessToken === "string" && typeof data.refreshToken === "string";
1753
+ }
1754
+ var serverConfig = null;
1755
+ function configureServer(config) {
1756
+ const secretKey = validateAndSanitizeSecretKey(config.secretKey);
1757
+ serverConfig = {
1758
+ secretKey,
1759
+ platformUrl: (config.platformUrl || DEFAULT_PLATFORM_URL).trim()
1760
+ };
1761
+ }
1762
+ function getConfig() {
1763
+ if (serverConfig) {
1764
+ return serverConfig;
1765
+ }
1766
+ const rawSecretKey = process.env.SYLPHX_SECRET_KEY;
1767
+ if (!rawSecretKey) {
1768
+ return null;
1769
+ }
1770
+ try {
1771
+ const secretKey = validateAndSanitizeSecretKey(rawSecretKey);
1772
+ const platformUrl = (process.env.SYLPHX_PLATFORM_URL || DEFAULT_PLATFORM_URL).trim();
1773
+ serverConfig = { secretKey, platformUrl };
1774
+ return serverConfig;
1775
+ } catch (error) {
1776
+ console.warn("[Sylphx] Invalid SYLPHX_SECRET_KEY format:", error);
1777
+ return null;
1778
+ }
1779
+ }
1780
+ function getCookieNamespace2() {
1781
+ const config = getConfig();
1782
+ if (!config) return "sylphx";
1783
+ return getCookieNamespace(config.secretKey);
1784
+ }
1785
+ var auth = cache2(async () => {
1786
+ const config = getConfig();
1787
+ if (!config) {
1788
+ return { userId: null, user: null, sessionToken: null };
1789
+ }
1790
+ const namespace = getCookieNamespace2();
1791
+ const { sessionToken, refreshToken, user, expiresAt } = await getAuthCookies(namespace);
1792
+ if (!sessionToken && !refreshToken) {
1793
+ return { userId: null, user: null, sessionToken: null };
1794
+ }
1795
+ if (sessionToken && expiresAt && expiresAt > Date.now() + TOKEN_EXPIRY_BUFFER_MS) {
1796
+ try {
1797
+ const payload = await verifyAccessToken(sessionToken, config);
1798
+ return {
1799
+ userId: payload.sub,
1800
+ user: user || {
1801
+ id: payload.sub,
1802
+ email: payload.email,
1803
+ name: payload.name || null,
1804
+ image: payload.picture || null,
1805
+ emailVerified: payload.email_verified
1806
+ },
1807
+ sessionToken
1808
+ };
1809
+ } catch {
1810
+ }
1811
+ }
1812
+ if (refreshToken && user && expiresAt) {
1813
+ if (expiresAt > Date.now()) {
1814
+ return {
1815
+ userId: user.id,
1816
+ user,
1817
+ sessionToken: sessionToken || null
1818
+ // May be expired, but user data is valid
1819
+ };
1820
+ }
1821
+ }
1822
+ return { userId: null, user: null, sessionToken: null };
1823
+ });
1824
+ async function currentUser() {
1825
+ const { user } = await auth();
1826
+ return user;
1827
+ }
1828
+ async function currentUserId() {
1829
+ const { userId } = await auth();
1830
+ return userId;
1831
+ }
1832
+ async function handleCallback2(code) {
1833
+ const config = getConfig();
1834
+ if (!config) {
1835
+ throw new Error("Sylphx SDK not configured. Set SYLPHX_SECRET_KEY environment variable.");
1836
+ }
1837
+ const response = await fetch(`${config.platformUrl}/api/v1/auth/token`, {
1838
+ method: "POST",
1839
+ headers: { "Content-Type": "application/json" },
1840
+ body: JSON.stringify({
1841
+ grant_type: "authorization_code",
1842
+ code,
1843
+ client_secret: config.secretKey
1844
+ })
1845
+ });
1846
+ if (!response.ok) {
1847
+ const errorData = await response.json().catch(() => ({ error: "Token exchange failed" }));
1848
+ throw new Error(errorData.error || "Token exchange failed");
1849
+ }
1850
+ const data = await response.json();
1851
+ if (!isTokenResponse2(data)) {
1852
+ throw new Error("Invalid token response format");
1853
+ }
1854
+ const namespace = getCookieNamespace2();
1855
+ await setAuthCookies(namespace, data);
1856
+ return data.user;
1857
+ }
1858
+ async function signOut() {
1859
+ const config = getConfig();
1860
+ if (!config) {
1861
+ return;
1862
+ }
1863
+ const namespace = getCookieNamespace2();
1864
+ const { refreshToken } = await getAuthCookies(namespace);
1865
+ if (refreshToken) {
1866
+ try {
1867
+ await fetch(`${config.platformUrl}/api/v1/auth/revoke`, {
1868
+ method: "POST",
1869
+ headers: { "Content-Type": "application/json" },
1870
+ body: JSON.stringify({
1871
+ token: refreshToken,
1872
+ client_secret: config.secretKey
1873
+ })
1874
+ });
1875
+ } catch {
1876
+ }
1877
+ }
1878
+ await clearAuthCookies(namespace);
1879
+ }
1880
+ async function syncAuthToCookies(tokens) {
1881
+ "use server";
1882
+ const namespace = getCookieNamespace2();
1883
+ await setAuthCookies(namespace, tokens);
1884
+ }
1885
+ function getAuthorizationUrl(options) {
1886
+ const config = getConfig();
1887
+ if (!config) {
1888
+ throw new Error("Sylphx SDK not configured. Set SYLPHX_SECRET_KEY environment variable.");
1889
+ }
1890
+ const rawClientId = options?.appId || process.env.NEXT_PUBLIC_SYLPHX_APP_ID;
1891
+ if (!rawClientId) {
1892
+ throw new Error("App ID is required for authorization URL. Set NEXT_PUBLIC_SYLPHX_APP_ID.");
1893
+ }
1894
+ const clientId = validateAndSanitizeAppId(rawClientId);
1895
+ const params = new URLSearchParams({
1896
+ client_id: clientId,
1897
+ redirect_uri: options?.redirectUri || "/",
1898
+ response_type: "code"
1899
+ });
1900
+ if (options?.mode === "signup") {
1901
+ params.set("mode", "signup");
1902
+ }
1903
+ if (options?.state) {
1904
+ params.set("state", options.state);
1905
+ }
1906
+ return `${config.platformUrl}/auth/authorize?${params}`;
1907
+ }
1908
+ async function getSessionToken() {
1909
+ const { sessionToken } = await auth();
1910
+ return sessionToken;
1911
+ }
1912
+ export {
1913
+ REFRESH_TOKEN_LIFETIME,
1914
+ SECURE_COOKIE_OPTIONS,
1915
+ SESSION_TOKEN_LIFETIME,
1916
+ SESSION_TOKEN_LIFETIME_MS,
1917
+ TOKEN_EXPIRY_BUFFER_MS,
1918
+ USER_COOKIE_OPTIONS,
1919
+ auth,
1920
+ clearAuthCookies,
1921
+ clearAuthCookiesMiddleware,
1922
+ configureServer,
1923
+ createMatcher,
1924
+ createSylphxMiddleware,
1925
+ currentUser,
1926
+ currentUserId,
1927
+ getAuthCookies,
1928
+ getAuthorizationUrl,
1929
+ getCookieNames,
1930
+ getNamespace,
1931
+ getSessionToken,
1932
+ handleCallback2 as handleCallback,
1933
+ hasRefreshToken,
1934
+ isSessionExpired,
1935
+ parseUserCookie,
1936
+ setAuthCookies,
1937
+ setAuthCookiesMiddleware,
1938
+ signOut,
1939
+ syncAuthToCookies
1940
+ };
1941
+ //# sourceMappingURL=index.mjs.map