@sylphx/sdk 0.27.0 → 0.30.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -73
  3. package/dist/access.d.ts +659 -0
  4. package/dist/access.js +638 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/ai.d.ts +176 -0
  7. package/dist/ai.js +112 -0
  8. package/dist/ai.js.map +1 -0
  9. package/dist/artifacts.d.ts +165 -0
  10. package/dist/artifacts.js +129 -0
  11. package/dist/artifacts.js.map +1 -0
  12. package/dist/auth.d.ts +896 -0
  13. package/dist/auth.js +828 -0
  14. package/dist/auth.js.map +1 -0
  15. package/dist/billing.d.ts +758 -0
  16. package/dist/billing.js +553 -0
  17. package/dist/billing.js.map +1 -0
  18. package/dist/broker.d.ts +226 -0
  19. package/dist/broker.js +187 -0
  20. package/dist/broker.js.map +1 -0
  21. package/dist/build.d.ts +313 -0
  22. package/dist/build.js +271 -0
  23. package/dist/build.js.map +1 -0
  24. package/dist/common.d.ts +162 -0
  25. package/dist/common.js +41 -0
  26. package/dist/common.js.map +1 -0
  27. package/dist/config.d.ts +198 -0
  28. package/dist/config.js +168 -0
  29. package/dist/config.js.map +1 -0
  30. package/dist/connections.d.ts +354 -0
  31. package/dist/connections.js +313 -0
  32. package/dist/connections.js.map +1 -0
  33. package/dist/data.d.ts +858 -0
  34. package/dist/data.js +814 -0
  35. package/dist/data.js.map +1 -0
  36. package/dist/entitlement.d.ts +172 -0
  37. package/dist/entitlement.js +116 -0
  38. package/dist/entitlement.js.map +1 -0
  39. package/dist/events.d.ts +1324 -0
  40. package/dist/events.js +1227 -0
  41. package/dist/events.js.map +1 -0
  42. package/dist/hosting.d.ts +709 -0
  43. package/dist/hosting.js +611 -0
  44. package/dist/hosting.js.map +1 -0
  45. package/dist/index.d.ts +79 -11493
  46. package/dist/index.js +113 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/keys.d.ts +438 -0
  49. package/dist/keys.js +406 -0
  50. package/dist/keys.js.map +1 -0
  51. package/dist/methods.d.ts +2 -0
  52. package/dist/methods.js +3995 -0
  53. package/dist/methods.js.map +1 -0
  54. package/dist/network.d.ts +733 -0
  55. package/dist/network.js +711 -0
  56. package/dist/network.js.map +1 -0
  57. package/dist/notify.d.ts +1359 -0
  58. package/dist/notify.js +1282 -0
  59. package/dist/notify.js.map +1 -0
  60. package/dist/observability.d.ts +509 -0
  61. package/dist/observability.js +437 -0
  62. package/dist/observability.js.map +1 -0
  63. package/dist/release.d.ts +303 -0
  64. package/dist/release.js +214 -0
  65. package/dist/release.js.map +1 -0
  66. package/dist/runners.d.ts +262 -0
  67. package/dist/runners.js +238 -0
  68. package/dist/runners.js.map +1 -0
  69. package/dist/runtime.d.ts +88 -0
  70. package/dist/runtime.js +226 -0
  71. package/dist/runtime.js.map +1 -0
  72. package/dist/sandboxes.d.ts +1705 -0
  73. package/dist/sandboxes.js +1226 -0
  74. package/dist/sandboxes.js.map +1 -0
  75. package/dist/secrets.d.ts +508 -0
  76. package/dist/secrets.js +474 -0
  77. package/dist/secrets.js.map +1 -0
  78. package/dist/workflows.d.ts +678 -0
  79. package/dist/workflows.js +595 -0
  80. package/dist/workflows.js.map +1 -0
  81. package/package.json +33 -106
  82. package/dist/health/index.d.ts +0 -1394
  83. package/dist/health/index.mjs +0 -1394
  84. package/dist/health/index.mjs.map +0 -1
  85. package/dist/index.mjs +0 -10386
  86. package/dist/index.mjs.map +0 -1
  87. package/dist/nextjs/index.d.ts +0 -724
  88. package/dist/nextjs/index.mjs +0 -3329
  89. package/dist/nextjs/index.mjs.map +0 -1
  90. package/dist/react/index.d.ts +0 -14168
  91. package/dist/react/index.mjs +0 -37002
  92. package/dist/react/index.mjs.map +0 -1
  93. package/dist/server/index.d.ts +0 -2017
  94. package/dist/server/index.mjs +0 -3446
  95. package/dist/server/index.mjs.map +0 -1
  96. package/dist/tasks.d.ts +0 -1463
  97. package/dist/tasks.mjs +0 -1907
  98. package/dist/tasks.mjs.map +0 -1
  99. package/dist/web-analytics.d.ts +0 -90
  100. package/dist/web-analytics.mjs +0 -225
  101. package/dist/web-analytics.mjs.map +0 -1
@@ -1,3329 +0,0 @@
1
- // src/nextjs/middleware.ts
2
- import { NextResponse as NextResponse2 } from "next/server";
3
-
4
- // src/key-validation.ts
5
- var PUBLIC_KEY_PATTERN = /^pk_(dev|stg|prod|prev)(?:_[a-z0-9]{12})?_[a-f0-9]{32}$/;
6
- var APP_ID_PATTERN = /^(app|pk)_(dev|stg|prod|prev)_[a-z0-9_-]+$/;
7
- var SECRET_KEY_PATTERN = /^sk_(dev|stg|prod|prev)_[a-z0-9_-]+$/;
8
- var ENV_PREFIX_MAP = {
9
- dev: "development",
10
- stg: "staging",
11
- prod: "production",
12
- prev: "preview"
13
- };
14
- function detectKeyIssues(key) {
15
- const issues = [];
16
- if (key !== key.trim()) issues.push("whitespace");
17
- if (key.includes("\n")) issues.push("newline");
18
- if (key.includes("\r")) issues.push("carriage-return");
19
- if (key.includes(" ")) issues.push("space");
20
- if (key !== key.toLowerCase()) issues.push("uppercase-chars");
21
- return issues;
22
- }
23
- function createSanitizationWarning(keyType, issues, envVarName) {
24
- const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
25
- return `[Sylphx] ${keyTypeName} contains ${issues.join(", ")}. This is commonly caused by Vercel CLI's 'env pull' command.
26
-
27
- To fix permanently:
28
- 1. Go to Vercel Dashboard \u2192 Your Project \u2192 Settings \u2192 Environment Variables
29
- 2. Edit ${envVarName}
30
- 3. Remove any trailing whitespace or newline characters
31
- 4. Redeploy your application
32
-
33
- The SDK will automatically sanitize the key, but fixing the source is recommended.`;
34
- }
35
- function createInvalidKeyError(keyType, key, envVarName) {
36
- const maskedKey = key.length > 20 ? `${key.slice(0, 20)}...` : key;
37
- const formatHint = keyType === "appId" ? "pk_(dev|stg|prod|prev)_{ref}_{hex} or app_(dev|stg|prod|prev)_[id]" : "sk_(dev|stg|prod|prev)_{ref}_{hex}";
38
- const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
39
- return `[Sylphx] Invalid ${keyTypeName} format.
40
-
41
- Expected format: ${formatHint}
42
- Received: "${maskedKey}"
43
-
44
- Please check your ${envVarName} environment variable.
45
- You can find your keys in the Sylphx Console \u2192 API Keys.
46
-
47
- Common issues:
48
- \u2022 Key has uppercase characters (must be lowercase)
49
- \u2022 Key has wrong prefix (App ID: pk_ or app_, Secret Key: sk_)
50
- \u2022 Key has invalid environment (must be dev, stg, prod, or prev)
51
- \u2022 Key was copied with extra whitespace`;
52
- }
53
- function extractEnvironment(key) {
54
- const match = key.match(/^(?:app|pk|sk)_(dev|stg|prod|prev)_/);
55
- if (!match) return void 0;
56
- return ENV_PREFIX_MAP[match[1]];
57
- }
58
- function validateKeyForType(key, keyType, pattern, envVarName) {
59
- const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
60
- if (!key) {
61
- return {
62
- valid: false,
63
- sanitizedKey: "",
64
- error: `[Sylphx] ${keyTypeName} is required. Set ${envVarName} in your environment variables.`,
65
- issues: ["missing"]
66
- };
67
- }
68
- const issues = detectKeyIssues(key);
69
- if (pattern.test(key)) {
70
- return {
71
- valid: true,
72
- sanitizedKey: key,
73
- keyType,
74
- environment: extractEnvironment(key),
75
- issues: []
76
- };
77
- }
78
- const sanitized = key.trim().toLowerCase();
79
- if (pattern.test(sanitized)) {
80
- return {
81
- valid: true,
82
- sanitizedKey: sanitized,
83
- keyType,
84
- environment: extractEnvironment(sanitized),
85
- warning: createSanitizationWarning(keyType, issues, envVarName),
86
- issues
87
- };
88
- }
89
- return {
90
- valid: false,
91
- sanitizedKey: "",
92
- error: createInvalidKeyError(keyType, key, envVarName),
93
- issues: [...issues, "invalid-format"]
94
- };
95
- }
96
- function validatePublicKey(key) {
97
- return validateKeyForType(key, "publicKey", PUBLIC_KEY_PATTERN, "publishable credential");
98
- }
99
- function validateAndSanitizePublicKey(key) {
100
- const result = validatePublicKey(key);
101
- if (!result.valid) throw new Error(result.error);
102
- if (result.warning) console.warn(result.warning);
103
- return result.sanitizedKey;
104
- }
105
- function validateAppId(key) {
106
- return validateKeyForType(key, "appId", APP_ID_PATTERN, "NEXT_PUBLIC_SYLPHX_APP_ID");
107
- }
108
- function validateAndSanitizeAppId(key) {
109
- const result = validateAppId(key);
110
- if (!result.valid) {
111
- throw new Error(result.error);
112
- }
113
- if (result.warning) {
114
- console.warn(result.warning);
115
- }
116
- return result.sanitizedKey;
117
- }
118
- function validateSecretKey(key) {
119
- return validateKeyForType(key, "secret", SECRET_KEY_PATTERN, "secret credential");
120
- }
121
- function validateAndSanitizeSecretKey(key) {
122
- const result = validateSecretKey(key);
123
- if (!result.valid) {
124
- throw new Error(result.error);
125
- }
126
- if (result.warning) {
127
- console.warn(result.warning);
128
- }
129
- return result.sanitizedKey;
130
- }
131
- function detectEnvironment(key) {
132
- const sanitized = key.trim().toLowerCase();
133
- if (sanitized.startsWith("pk_")) {
134
- const result = validatePublicKey(sanitized);
135
- if (!result.valid) throw new Error(result.error);
136
- return result.environment;
137
- }
138
- if (sanitized.startsWith("sk_")) {
139
- const result = validateSecretKey(sanitized);
140
- if (!result.valid) throw new Error(result.error);
141
- return result.environment;
142
- }
143
- if (sanitized.startsWith("app_")) {
144
- const result = validateAppId(sanitized);
145
- if (!result.valid) throw new Error(result.error);
146
- return result.environment;
147
- }
148
- throw new Error(
149
- `[Sylphx] Invalid key format. Key must start with 'pk_' (publishable), 'sk_' (secret), or 'app_' (legacy App ID).`
150
- );
151
- }
152
- function getCookieNamespace(secretKey) {
153
- const env = detectEnvironment(secretKey);
154
- const shortEnv = env === "development" ? "dev" : env === "staging" ? "stg" : env === "preview" ? "prev" : "prod";
155
- return `sylphx_${shortEnv}`;
156
- }
157
-
158
- // src/nextjs/auth-authority.ts
159
- function resolveSessionAuthority(input) {
160
- if (!input.sessionTokenPresent) {
161
- return { authenticated: false, reason: "missing_session" };
162
- }
163
- if (!input.tokenCryptographicallyVerified) {
164
- return { authenticated: false, reason: "verification_failed" };
165
- }
166
- const userId = input.verifiedUserId?.trim();
167
- if (!userId) {
168
- return { authenticated: false, reason: "verification_failed" };
169
- }
170
- return { authenticated: true, userId };
171
- }
172
- function resolveHydrationCookieAuthority(input) {
173
- void input.hydrationUserId;
174
- void input.hydrationExpiresAt;
175
- void input.hasRefreshToken;
176
- void input.nowMs;
177
- return { authenticated: false, reason: "hydration_cookie_not_authority" };
178
- }
179
- function middlewareMayTreatAsAuthenticated(input) {
180
- return resolveSessionAuthority({
181
- sessionTokenPresent: input.sessionTokenPresent,
182
- tokenCryptographicallyVerified: input.tokenCryptographicallyVerified,
183
- verifiedUserId: input.tokenCryptographicallyVerified ? "verified" : null
184
- }).authenticated;
185
- }
186
-
187
- // src/nextjs/cookies.ts
188
- import { cookies } from "next/headers";
189
-
190
- // src/constants.ts
191
- var ENV_URL = "SYLPHX_URL";
192
- var ENV_PUBLIC_URL = "NEXT_PUBLIC_SYLPHX_URL";
193
- var ENV_SECRET_URL = "SYLPHX_SECRET_URL";
194
- var SDK_API_PATH = `/v1`;
195
- var DEFAULT_SDK_API_HOST = "api.sylphx.com";
196
- var DEFAULT_PLATFORM_URL = "https://sylphx.com";
197
- function detectSdkPlatform() {
198
- if (typeof window !== "undefined") return "browser";
199
- const runtimeGlobal = globalThis;
200
- if (typeof runtimeGlobal.EdgeRuntime !== "undefined") return "edge";
201
- return "node";
202
- }
203
- var SDK_PLATFORM = detectSdkPlatform();
204
- var TOKEN_EXPIRY_BUFFER_MS = 3e4;
205
- var SESSION_TOKEN_LIFETIME_SECONDS = 5 * 60;
206
- var SESSION_TOKEN_LIFETIME_MS = SESSION_TOKEN_LIFETIME_SECONDS * 1e3;
207
- var REFRESH_TOKEN_LIFETIME_SECONDS = 30 * 24 * 60 * 60;
208
- var FLAGS_CACHE_TTL_MS = 5 * 60 * 1e3;
209
- var FLAGS_STALE_WHILE_REVALIDATE_MS = 60 * 1e3;
210
- var ANALYTICS_SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
211
- var WEBHOOK_MAX_AGE_MS = 5 * 60 * 1e3;
212
- var WEBHOOK_CLOCK_SKEW_MS = 30 * 1e3;
213
- var PKCE_CODE_TTL_MS = 10 * 60 * 1e3;
214
- var JOBS_DLQ_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
215
- var SESSION_REPLAY_MAX_DURATION_MS = 60 * 60 * 1e3;
216
- var FLAGS_EXPOSURE_DEDUPE_WINDOW_MS = 60 * 60 * 1e3;
217
- var CLICK_ID_EXPIRY_MS = 90 * 24 * 60 * 60 * 1e3;
218
- var STALE_TIME_FREQUENT_MS = 60 * 1e3;
219
- var STALE_TIME_MODERATE_MS = 2 * 60 * 1e3;
220
- var STALE_TIME_STABLE_MS = 5 * 60 * 1e3;
221
- var STALE_TIME_STATS_MS = 30 * 1e3;
222
- var NEW_USER_THRESHOLD_MS = 60 * 1e3;
223
- var STORAGE_MULTIPART_THRESHOLD_BYTES = 5 * 1024 * 1024;
224
- var STORAGE_DEFAULT_MAX_SIZE_BYTES = 5 * 1024 * 1024;
225
- var STORAGE_AVATAR_MAX_SIZE_BYTES = 2 * 1024 * 1024;
226
- var STORAGE_LARGE_MAX_SIZE_BYTES = 10 * 1024 * 1024;
227
- var JWK_CACHE_TTL_MS = 60 * 60 * 1e3;
228
- var ETAG_CACHE_TTL_MS = 5 * 60 * 1e3;
229
-
230
- // src/nextjs/cookies.ts
231
- function getCookieNames(namespace) {
232
- return {
233
- /** HttpOnly JWT access token (5 min) */
234
- SESSION: `__${namespace}_session`,
235
- /** HttpOnly refresh token (30 days) */
236
- REFRESH: `__${namespace}_refresh`,
237
- /** JS-readable user data for client hydration (5 min) */
238
- USER: `__${namespace}_user`,
239
- /** HttpOnly active organization ID used to preserve org-scoped sessions */
240
- ACTIVE_ORG_ID: `__${namespace}_active_org_id`,
241
- /** HttpOnly active organization slug used to preserve org-scoped sessions */
242
- ACTIVE_ORG_SLUG: `__${namespace}_active_org_slug`
243
- };
244
- }
245
- var SESSION_TOKEN_LIFETIME = SESSION_TOKEN_LIFETIME_SECONDS;
246
- var REFRESH_TOKEN_LIFETIME = REFRESH_TOKEN_LIFETIME_SECONDS;
247
- var ACTIVE_ORG_LIFETIME = REFRESH_TOKEN_LIFETIME_SECONDS;
248
- var SECURE_COOKIE_OPTIONS = {
249
- httpOnly: true,
250
- secure: process.env.NODE_ENV === "production",
251
- sameSite: "lax",
252
- path: "/"
253
- };
254
- var USER_COOKIE_OPTIONS = {
255
- httpOnly: false,
256
- // Readable by client JS for hydration
257
- secure: process.env.NODE_ENV === "production",
258
- sameSite: "lax",
259
- path: "/"
260
- };
261
- var ACTIVE_ORG_COOKIE_OPTIONS = {
262
- ...SECURE_COOKIE_OPTIONS,
263
- httpOnly: true
264
- };
265
- function decodeCookieValue(value) {
266
- try {
267
- return decodeURIComponent(value);
268
- } catch {
269
- return value;
270
- }
271
- }
272
- function readCookieValueFromHeader(cookieHeader, name) {
273
- if (!cookieHeader) return null;
274
- let value = null;
275
- for (const cookie of cookieHeader.split(";")) {
276
- const trimmed = cookie.trim();
277
- const eq = trimmed.indexOf("=");
278
- if (eq === -1) continue;
279
- if (trimmed.slice(0, eq) === name) {
280
- value = decodeCookieValue(trimmed.slice(eq + 1));
281
- }
282
- }
283
- return value;
284
- }
285
- async function getAuthCookies(namespace) {
286
- const cookieStore = await cookies();
287
- const names = getCookieNames(namespace);
288
- const sessionToken = cookieStore.get(names.SESSION)?.value || null;
289
- const refreshToken = cookieStore.get(names.REFRESH)?.value || null;
290
- const userCookieValue = cookieStore.get(names.USER)?.value || null;
291
- let user = null;
292
- let expiresAt = null;
293
- if (userCookieValue) {
294
- try {
295
- const parsed = JSON.parse(userCookieValue);
296
- user = parsed.user;
297
- expiresAt = parsed.expiresAt;
298
- } catch {
299
- user = null;
300
- expiresAt = null;
301
- }
302
- }
303
- return { sessionToken, refreshToken, user, expiresAt };
304
- }
305
- async function setAuthCookies(namespace, response, options) {
306
- const cookieStore = await cookies();
307
- const names = getCookieNames(namespace);
308
- const sessionLifetime = options?.sessionLifetime ?? SESSION_TOKEN_LIFETIME;
309
- const expiresAt = Date.now() + sessionLifetime * 1e3;
310
- cookieStore.set(names.SESSION, response.accessToken, {
311
- ...SECURE_COOKIE_OPTIONS,
312
- maxAge: sessionLifetime
313
- });
314
- cookieStore.set(names.REFRESH, response.refreshToken, {
315
- ...SECURE_COOKIE_OPTIONS,
316
- maxAge: REFRESH_TOKEN_LIFETIME
317
- });
318
- const userData = {
319
- user: response.user,
320
- expiresAt
321
- };
322
- cookieStore.set(names.USER, JSON.stringify(userData), {
323
- ...USER_COOKIE_OPTIONS,
324
- maxAge: sessionLifetime
325
- });
326
- }
327
- async function clearAuthCookies(namespace) {
328
- const cookieStore = await cookies();
329
- const names = getCookieNames(namespace);
330
- cookieStore.delete(names.SESSION);
331
- cookieStore.delete(names.REFRESH);
332
- cookieStore.delete(names.USER);
333
- cookieStore.delete(names.ACTIVE_ORG_ID);
334
- cookieStore.delete(names.ACTIVE_ORG_SLUG);
335
- }
336
- async function isSessionExpired(namespace) {
337
- const { expiresAt } = await getAuthCookies(namespace);
338
- if (!expiresAt) return true;
339
- return expiresAt < Date.now() + TOKEN_EXPIRY_BUFFER_MS;
340
- }
341
- async function hasRefreshToken(namespace) {
342
- const { refreshToken } = await getAuthCookies(namespace);
343
- return !!refreshToken;
344
- }
345
- function setAuthCookiesMiddleware(response, namespace, tokens) {
346
- const names = getCookieNames(namespace);
347
- const expiresAt = Date.now() + SESSION_TOKEN_LIFETIME * 1e3;
348
- response.cookies.set(names.SESSION, tokens.accessToken, {
349
- ...SECURE_COOKIE_OPTIONS,
350
- maxAge: SESSION_TOKEN_LIFETIME
351
- });
352
- response.cookies.set(names.REFRESH, tokens.refreshToken, {
353
- ...SECURE_COOKIE_OPTIONS,
354
- maxAge: REFRESH_TOKEN_LIFETIME
355
- });
356
- const userData = {
357
- user: tokens.user,
358
- expiresAt
359
- };
360
- response.cookies.set(names.USER, JSON.stringify(userData), {
361
- ...USER_COOKIE_OPTIONS,
362
- maxAge: SESSION_TOKEN_LIFETIME
363
- });
364
- }
365
- function clearAuthCookiesMiddleware(response, namespace) {
366
- const names = getCookieNames(namespace);
367
- response.cookies.delete(names.SESSION);
368
- response.cookies.delete(names.REFRESH);
369
- response.cookies.delete(names.USER);
370
- response.cookies.delete(names.ACTIVE_ORG_ID);
371
- response.cookies.delete(names.ACTIVE_ORG_SLUG);
372
- }
373
- function parseUserCookie(value) {
374
- try {
375
- return JSON.parse(value);
376
- } catch {
377
- return null;
378
- }
379
- }
380
-
381
- // src/nextjs/middleware-helpers.ts
382
- var OAUTH_PKCE_TTL_SECONDS = 10 * 60;
383
- var OAUTH_PKCE_TTL_MS = OAUTH_PKCE_TTL_SECONDS * 1e3;
384
- var DEFAULT_BAAS_PREFIX = "/sylphx";
385
- var BAAS_PROXY_AUTH_REQUIRED_PATHS = [
386
- "/challenge/",
387
- "/security/",
388
- "/user/",
389
- "/notifications/",
390
- "/referrals/",
391
- "/analytics/",
392
- "/realtime/",
393
- "/billing/",
394
- "/consent/",
395
- "/privacy/",
396
- "/engagement/"
397
- ];
398
- var BAAS_PROXY_PUBLIC_PATHS = ["/app"];
399
- var BODYLESS_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
400
- var RESPONSE_HEADER_ALLOWLIST = [
401
- "cache-control",
402
- "content-language",
403
- "content-type",
404
- "etag",
405
- "expires",
406
- "last-modified",
407
- "retry-after"
408
- ];
409
- function isTokenResponse(data) {
410
- return typeof data === "object" && data !== null && "accessToken" in data && "refreshToken" in data && "user" in data && typeof data.accessToken === "string" && typeof data.refreshToken === "string";
411
- }
412
- function decodeJwtPayload(token) {
413
- try {
414
- const parts = token.split(".");
415
- if (parts.length !== 3) return null;
416
- const payload = parts[1];
417
- const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
418
- const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
419
- const jsonPayload = atob(padded);
420
- return JSON.parse(jsonPayload);
421
- } catch {
422
- return null;
423
- }
424
- }
425
- function matchesPattern(pathname, pattern) {
426
- if (pattern === pathname) return true;
427
- if (pattern.endsWith("/*")) {
428
- const base = pattern.slice(0, -2);
429
- return pathname === base || pathname.startsWith(`${base}/`);
430
- }
431
- if (pattern.endsWith("/**")) {
432
- const base = pattern.slice(0, -3);
433
- return pathname === base || pathname.startsWith(`${base}/`);
434
- }
435
- return false;
436
- }
437
- function matchesAny(pathname, patterns) {
438
- return patterns.some((p) => matchesPattern(pathname, p));
439
- }
440
- function normalizeRoutePrefix(prefix) {
441
- const normalized = prefix.trim().replace(/\/+$/u, "");
442
- return normalized.startsWith("/") ? normalized : `/${normalized}`;
443
- }
444
- function stripRoutePrefix(pathname, prefix) {
445
- if (pathname === prefix) return "/";
446
- if (!pathname.startsWith(`${prefix}/`)) return null;
447
- return pathname.slice(prefix.length);
448
- }
449
- function isPublicBaasProxyPath(pathname) {
450
- return BAAS_PROXY_PUBLIC_PATHS.some((path) => pathname === path);
451
- }
452
- function isAuthenticatedBaasProxyPath(pathname) {
453
- return BAAS_PROXY_AUTH_REQUIRED_PATHS.some((prefix) => pathname.startsWith(prefix));
454
- }
455
- function isAllowedBaasProxyPath(pathname) {
456
- return isPublicBaasProxyPath(pathname) || isAuthenticatedBaasProxyPath(pathname);
457
- }
458
- function copyRequestHeader(source, target, name) {
459
- const value = source.get(name);
460
- if (value) target.set(name, value);
461
- }
462
- function buildUpstreamProxyHeaders(request, ctx, sessionToken) {
463
- const headers = new Headers();
464
- copyRequestHeader(request.headers, headers, "accept");
465
- copyRequestHeader(request.headers, headers, "content-type");
466
- copyRequestHeader(request.headers, headers, "user-agent");
467
- copyRequestHeader(request.headers, headers, "x-correlation-id");
468
- headers.set("x-app-secret", ctx.secretKey);
469
- if (sessionToken) headers.set("authorization", `Bearer ${sessionToken}`);
470
- return headers;
471
- }
472
- function copyResponseHeaders(source) {
473
- const headers = new Headers();
474
- for (const name of RESPONSE_HEADER_ALLOWLIST) {
475
- const value = source.get(name);
476
- if (value) headers.set(name, value);
477
- }
478
- return headers;
479
- }
480
- function requestPathWithSearch(request) {
481
- const { pathname, search } = request.nextUrl;
482
- return `${pathname}${search}`;
483
- }
484
- function isSafeRelativeRedirectPath(value) {
485
- return typeof value === "string" && value.startsWith("/") && !value.startsWith("//");
486
- }
487
- function resolveSafeRelativeRedirectPath(value, fallback) {
488
- if (isSafeRelativeRedirectPath(value)) return value;
489
- if (isSafeRelativeRedirectPath(fallback)) return fallback;
490
- return "/";
491
- }
492
- function resolveSameOriginUrl(request, value, fallbackPath) {
493
- if (!value) return new URL(fallbackPath, request.url).toString();
494
- if (isSafeRelativeRedirectPath(value)) {
495
- const url = new URL(value, request.url);
496
- if (url.hash) return null;
497
- return url.toString();
498
- }
499
- try {
500
- const url = new URL(value);
501
- if (url.origin !== new URL(request.url).origin) return null;
502
- if (url.hash) return null;
503
- return url.toString();
504
- } catch {
505
- return null;
506
- }
507
- }
508
- function normalizeAppUrl(value) {
509
- if (!value?.trim()) return null;
510
- try {
511
- const url = new URL(value);
512
- return url.origin;
513
- } catch {
514
- return null;
515
- }
516
- }
517
- function resolveOAuthCallbackUrl(request, ctx) {
518
- const origin = ctx.config.appUrl ?? new URL(request.url).origin;
519
- return new URL(`${ctx.config.authPrefix}/callback`, origin);
520
- }
521
- function bytesToBase64Url(bytes) {
522
- let binary = "";
523
- for (const byte of bytes) binary += String.fromCharCode(byte);
524
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/u, "");
525
- }
526
- function randomBase64Url(byteLength) {
527
- const bytes = new Uint8Array(byteLength);
528
- crypto.getRandomValues(bytes);
529
- return bytesToBase64Url(bytes);
530
- }
531
- async function sha256Base64Url(value) {
532
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
533
- return bytesToBase64Url(new Uint8Array(digest));
534
- }
535
- async function parseJsonObject(request) {
536
- try {
537
- const body = await request.json();
538
- if (typeof body === "object" && body !== null && !Array.isArray(body)) return body;
539
- return null;
540
- } catch {
541
- return null;
542
- }
543
- }
544
-
545
- // src/nextjs/middleware-token-route.ts
546
- import { NextResponse } from "next/server";
547
-
548
- // src/server/index.ts
549
- import {
550
- isPlatformProjectIdentity,
551
- LEGACY_PLATFORM_PROJECT_ID,
552
- PLATFORM_CONSOLE_SLUG
553
- } from "@sylphx/contract";
554
-
555
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/buffer_utils.js
556
- var encoder = new TextEncoder();
557
- var decoder = new TextDecoder();
558
- var MAX_INT32 = 2 ** 32;
559
- function concat(...buffers) {
560
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
561
- const buf = new Uint8Array(size);
562
- let i = 0;
563
- for (const buffer of buffers) {
564
- buf.set(buffer, i);
565
- i += buffer.length;
566
- }
567
- return buf;
568
- }
569
- function encode(string) {
570
- const bytes = new Uint8Array(string.length);
571
- for (let i = 0; i < string.length; i++) {
572
- const code = string.charCodeAt(i);
573
- if (code > 127) {
574
- throw new TypeError("non-ASCII string encountered in encode()");
575
- }
576
- bytes[i] = code;
577
- }
578
- return bytes;
579
- }
580
-
581
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/base64.js
582
- function decodeBase64(encoded) {
583
- if (Uint8Array.fromBase64) {
584
- return Uint8Array.fromBase64(encoded);
585
- }
586
- const binary = atob(encoded);
587
- const bytes = new Uint8Array(binary.length);
588
- for (let i = 0; i < binary.length; i++) {
589
- bytes[i] = binary.charCodeAt(i);
590
- }
591
- return bytes;
592
- }
593
-
594
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/util/base64url.js
595
- function decode(input) {
596
- if (Uint8Array.fromBase64) {
597
- return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
598
- alphabet: "base64url"
599
- });
600
- }
601
- let encoded = input;
602
- if (encoded instanceof Uint8Array) {
603
- encoded = decoder.decode(encoded);
604
- }
605
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
606
- try {
607
- return decodeBase64(encoded);
608
- } catch {
609
- throw new TypeError("The input to be decoded is not correctly encoded.");
610
- }
611
- }
612
-
613
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/util/errors.js
614
- var JOSEError = class extends Error {
615
- static code = "ERR_JOSE_GENERIC";
616
- code = "ERR_JOSE_GENERIC";
617
- constructor(message2, options) {
618
- super(message2, options);
619
- this.name = this.constructor.name;
620
- Error.captureStackTrace?.(this, this.constructor);
621
- }
622
- };
623
- var JWTClaimValidationFailed = class extends JOSEError {
624
- static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
625
- code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
626
- claim;
627
- reason;
628
- payload;
629
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
630
- super(message2, { cause: { claim, reason, payload } });
631
- this.claim = claim;
632
- this.reason = reason;
633
- this.payload = payload;
634
- }
635
- };
636
- var JWTExpired = class extends JOSEError {
637
- static code = "ERR_JWT_EXPIRED";
638
- code = "ERR_JWT_EXPIRED";
639
- claim;
640
- reason;
641
- payload;
642
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
643
- super(message2, { cause: { claim, reason, payload } });
644
- this.claim = claim;
645
- this.reason = reason;
646
- this.payload = payload;
647
- }
648
- };
649
- var JOSEAlgNotAllowed = class extends JOSEError {
650
- static code = "ERR_JOSE_ALG_NOT_ALLOWED";
651
- code = "ERR_JOSE_ALG_NOT_ALLOWED";
652
- };
653
- var JOSENotSupported = class extends JOSEError {
654
- static code = "ERR_JOSE_NOT_SUPPORTED";
655
- code = "ERR_JOSE_NOT_SUPPORTED";
656
- };
657
- var JWSInvalid = class extends JOSEError {
658
- static code = "ERR_JWS_INVALID";
659
- code = "ERR_JWS_INVALID";
660
- };
661
- var JWTInvalid = class extends JOSEError {
662
- static code = "ERR_JWT_INVALID";
663
- code = "ERR_JWT_INVALID";
664
- };
665
- var JWSSignatureVerificationFailed = class extends JOSEError {
666
- static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
667
- code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
668
- constructor(message2 = "signature verification failed", options) {
669
- super(message2, options);
670
- }
671
- };
672
-
673
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/crypto_key.js
674
- var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
675
- var isAlgorithm = (algorithm, name) => algorithm.name === name;
676
- function getHashLength(hash) {
677
- return parseInt(hash.name.slice(4), 10);
678
- }
679
- function getNamedCurve(alg) {
680
- switch (alg) {
681
- case "ES256":
682
- return "P-256";
683
- case "ES384":
684
- return "P-384";
685
- case "ES512":
686
- return "P-521";
687
- default:
688
- throw new Error("unreachable");
689
- }
690
- }
691
- function checkUsage(key, usage) {
692
- if (usage && !key.usages.includes(usage)) {
693
- throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
694
- }
695
- }
696
- function checkSigCryptoKey(key, alg, usage) {
697
- switch (alg) {
698
- case "HS256":
699
- case "HS384":
700
- case "HS512": {
701
- if (!isAlgorithm(key.algorithm, "HMAC"))
702
- throw unusable("HMAC");
703
- const expected = parseInt(alg.slice(2), 10);
704
- const actual = getHashLength(key.algorithm.hash);
705
- if (actual !== expected)
706
- throw unusable(`SHA-${expected}`, "algorithm.hash");
707
- break;
708
- }
709
- case "RS256":
710
- case "RS384":
711
- case "RS512": {
712
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
713
- throw unusable("RSASSA-PKCS1-v1_5");
714
- const expected = parseInt(alg.slice(2), 10);
715
- const actual = getHashLength(key.algorithm.hash);
716
- if (actual !== expected)
717
- throw unusable(`SHA-${expected}`, "algorithm.hash");
718
- break;
719
- }
720
- case "PS256":
721
- case "PS384":
722
- case "PS512": {
723
- if (!isAlgorithm(key.algorithm, "RSA-PSS"))
724
- throw unusable("RSA-PSS");
725
- const expected = parseInt(alg.slice(2), 10);
726
- const actual = getHashLength(key.algorithm.hash);
727
- if (actual !== expected)
728
- throw unusable(`SHA-${expected}`, "algorithm.hash");
729
- break;
730
- }
731
- case "Ed25519":
732
- case "EdDSA": {
733
- if (!isAlgorithm(key.algorithm, "Ed25519"))
734
- throw unusable("Ed25519");
735
- break;
736
- }
737
- case "ML-DSA-44":
738
- case "ML-DSA-65":
739
- case "ML-DSA-87": {
740
- if (!isAlgorithm(key.algorithm, alg))
741
- throw unusable(alg);
742
- break;
743
- }
744
- case "ES256":
745
- case "ES384":
746
- case "ES512": {
747
- if (!isAlgorithm(key.algorithm, "ECDSA"))
748
- throw unusable("ECDSA");
749
- const expected = getNamedCurve(alg);
750
- const actual = key.algorithm.namedCurve;
751
- if (actual !== expected)
752
- throw unusable(expected, "algorithm.namedCurve");
753
- break;
754
- }
755
- default:
756
- throw new TypeError("CryptoKey does not support this operation");
757
- }
758
- checkUsage(key, usage);
759
- }
760
-
761
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/invalid_key_input.js
762
- function message(msg, actual, ...types) {
763
- types = types.filter(Boolean);
764
- if (types.length > 2) {
765
- const last = types.pop();
766
- msg += `one of type ${types.join(", ")}, or ${last}.`;
767
- } else if (types.length === 2) {
768
- msg += `one of type ${types[0]} or ${types[1]}.`;
769
- } else {
770
- msg += `of type ${types[0]}.`;
771
- }
772
- if (actual == null) {
773
- msg += ` Received ${actual}`;
774
- } else if (typeof actual === "function" && actual.name) {
775
- msg += ` Received function ${actual.name}`;
776
- } else if (typeof actual === "object" && actual != null) {
777
- if (actual.constructor?.name) {
778
- msg += ` Received an instance of ${actual.constructor.name}`;
779
- }
780
- }
781
- return msg;
782
- }
783
- var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
784
- var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
785
-
786
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/is_key_like.js
787
- var isCryptoKey = (key) => {
788
- if (key?.[Symbol.toStringTag] === "CryptoKey")
789
- return true;
790
- try {
791
- return key instanceof CryptoKey;
792
- } catch {
793
- return false;
794
- }
795
- };
796
- var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
797
- var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
798
-
799
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/is_disjoint.js
800
- function isDisjoint(...headers) {
801
- const sources = headers.filter(Boolean);
802
- if (sources.length === 0 || sources.length === 1) {
803
- return true;
804
- }
805
- let acc;
806
- for (const header of sources) {
807
- const parameters = Object.keys(header);
808
- if (!acc || acc.size === 0) {
809
- acc = new Set(parameters);
810
- continue;
811
- }
812
- for (const parameter of parameters) {
813
- if (acc.has(parameter)) {
814
- return false;
815
- }
816
- acc.add(parameter);
817
- }
818
- }
819
- return true;
820
- }
821
-
822
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/is_object.js
823
- var isObjectLike = (value) => typeof value === "object" && value !== null;
824
- function isObject(input) {
825
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
826
- return false;
827
- }
828
- if (Object.getPrototypeOf(input) === null) {
829
- return true;
830
- }
831
- let proto = input;
832
- while (Object.getPrototypeOf(proto) !== null) {
833
- proto = Object.getPrototypeOf(proto);
834
- }
835
- return Object.getPrototypeOf(input) === proto;
836
- }
837
-
838
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/check_key_length.js
839
- function checkKeyLength(alg, key) {
840
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
841
- const { modulusLength } = key.algorithm;
842
- if (typeof modulusLength !== "number" || modulusLength < 2048) {
843
- throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
844
- }
845
- }
846
- }
847
-
848
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/jwk_to_key.js
849
- function subtleMapping(jwk) {
850
- let algorithm;
851
- let keyUsages;
852
- switch (jwk.kty) {
853
- case "AKP": {
854
- switch (jwk.alg) {
855
- case "ML-DSA-44":
856
- case "ML-DSA-65":
857
- case "ML-DSA-87":
858
- algorithm = { name: jwk.alg };
859
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
860
- break;
861
- default:
862
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
863
- }
864
- break;
865
- }
866
- case "RSA": {
867
- switch (jwk.alg) {
868
- case "PS256":
869
- case "PS384":
870
- case "PS512":
871
- algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
872
- keyUsages = jwk.d ? ["sign"] : ["verify"];
873
- break;
874
- case "RS256":
875
- case "RS384":
876
- case "RS512":
877
- algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
878
- keyUsages = jwk.d ? ["sign"] : ["verify"];
879
- break;
880
- case "RSA-OAEP":
881
- case "RSA-OAEP-256":
882
- case "RSA-OAEP-384":
883
- case "RSA-OAEP-512":
884
- algorithm = {
885
- name: "RSA-OAEP",
886
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
887
- };
888
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
889
- break;
890
- default:
891
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
892
- }
893
- break;
894
- }
895
- case "EC": {
896
- switch (jwk.alg) {
897
- case "ES256":
898
- algorithm = { name: "ECDSA", namedCurve: "P-256" };
899
- keyUsages = jwk.d ? ["sign"] : ["verify"];
900
- break;
901
- case "ES384":
902
- algorithm = { name: "ECDSA", namedCurve: "P-384" };
903
- keyUsages = jwk.d ? ["sign"] : ["verify"];
904
- break;
905
- case "ES512":
906
- algorithm = { name: "ECDSA", namedCurve: "P-521" };
907
- keyUsages = jwk.d ? ["sign"] : ["verify"];
908
- break;
909
- case "ECDH-ES":
910
- case "ECDH-ES+A128KW":
911
- case "ECDH-ES+A192KW":
912
- case "ECDH-ES+A256KW":
913
- algorithm = { name: "ECDH", namedCurve: jwk.crv };
914
- keyUsages = jwk.d ? ["deriveBits"] : [];
915
- break;
916
- default:
917
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
918
- }
919
- break;
920
- }
921
- case "OKP": {
922
- switch (jwk.alg) {
923
- case "Ed25519":
924
- case "EdDSA":
925
- algorithm = { name: "Ed25519" };
926
- keyUsages = jwk.d ? ["sign"] : ["verify"];
927
- break;
928
- case "ECDH-ES":
929
- case "ECDH-ES+A128KW":
930
- case "ECDH-ES+A192KW":
931
- case "ECDH-ES+A256KW":
932
- algorithm = { name: jwk.crv };
933
- keyUsages = jwk.d ? ["deriveBits"] : [];
934
- break;
935
- default:
936
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
937
- }
938
- break;
939
- }
940
- default:
941
- throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
942
- }
943
- return { algorithm, keyUsages };
944
- }
945
- async function jwkToKey(jwk) {
946
- if (!jwk.alg) {
947
- throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
948
- }
949
- const { algorithm, keyUsages } = subtleMapping(jwk);
950
- const keyData = { ...jwk };
951
- if (keyData.kty !== "AKP") {
952
- delete keyData.alg;
953
- }
954
- delete keyData.use;
955
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
956
- }
957
-
958
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/key/import.js
959
- async function importJWK(jwk, alg, options) {
960
- if (!isObject(jwk)) {
961
- throw new TypeError("JWK must be an object");
962
- }
963
- let ext;
964
- alg ??= jwk.alg;
965
- ext ??= options?.extractable ?? jwk.ext;
966
- switch (jwk.kty) {
967
- case "oct":
968
- if (typeof jwk.k !== "string" || !jwk.k) {
969
- throw new TypeError('missing "k" (Key Value) Parameter value');
970
- }
971
- return decode(jwk.k);
972
- case "RSA":
973
- if ("oth" in jwk && jwk.oth !== void 0) {
974
- throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
975
- }
976
- return jwkToKey({ ...jwk, alg, ext });
977
- case "AKP": {
978
- if (typeof jwk.alg !== "string" || !jwk.alg) {
979
- throw new TypeError('missing "alg" (Algorithm) Parameter value');
980
- }
981
- if (alg !== void 0 && alg !== jwk.alg) {
982
- throw new TypeError("JWK alg and alg option value mismatch");
983
- }
984
- return jwkToKey({ ...jwk, ext });
985
- }
986
- case "EC":
987
- case "OKP":
988
- return jwkToKey({ ...jwk, alg, ext });
989
- default:
990
- throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
991
- }
992
- }
993
-
994
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/validate_crit.js
995
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
996
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
997
- throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
998
- }
999
- if (!protectedHeader || protectedHeader.crit === void 0) {
1000
- return /* @__PURE__ */ new Set();
1001
- }
1002
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
1003
- throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
1004
- }
1005
- let recognized;
1006
- if (recognizedOption !== void 0) {
1007
- recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
1008
- } else {
1009
- recognized = recognizedDefault;
1010
- }
1011
- for (const parameter of protectedHeader.crit) {
1012
- if (!recognized.has(parameter)) {
1013
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
1014
- }
1015
- if (joseHeader[parameter] === void 0) {
1016
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
1017
- }
1018
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
1019
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
1020
- }
1021
- }
1022
- return new Set(protectedHeader.crit);
1023
- }
1024
-
1025
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/validate_algorithms.js
1026
- function validateAlgorithms(option, algorithms) {
1027
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
1028
- throw new TypeError(`"${option}" option must be an array of strings`);
1029
- }
1030
- if (!algorithms) {
1031
- return void 0;
1032
- }
1033
- return new Set(algorithms);
1034
- }
1035
-
1036
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/is_jwk.js
1037
- var isJWK = (key) => isObject(key) && typeof key.kty === "string";
1038
- var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
1039
- var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
1040
- var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
1041
-
1042
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/normalize_key.js
1043
- var cache;
1044
- var handleJWK = async (key, jwk, alg, freeze = false) => {
1045
- cache ||= /* @__PURE__ */ new WeakMap();
1046
- let cached = cache.get(key);
1047
- if (cached?.[alg]) {
1048
- return cached[alg];
1049
- }
1050
- const cryptoKey = await jwkToKey({ ...jwk, alg });
1051
- if (freeze)
1052
- Object.freeze(key);
1053
- if (!cached) {
1054
- cache.set(key, { [alg]: cryptoKey });
1055
- } else {
1056
- cached[alg] = cryptoKey;
1057
- }
1058
- return cryptoKey;
1059
- };
1060
- var handleKeyObject = (keyObject, alg) => {
1061
- cache ||= /* @__PURE__ */ new WeakMap();
1062
- let cached = cache.get(keyObject);
1063
- if (cached?.[alg]) {
1064
- return cached[alg];
1065
- }
1066
- const isPublic = keyObject.type === "public";
1067
- const extractable = isPublic ? true : false;
1068
- let cryptoKey;
1069
- if (keyObject.asymmetricKeyType === "x25519") {
1070
- switch (alg) {
1071
- case "ECDH-ES":
1072
- case "ECDH-ES+A128KW":
1073
- case "ECDH-ES+A192KW":
1074
- case "ECDH-ES+A256KW":
1075
- break;
1076
- default:
1077
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1078
- }
1079
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
1080
- }
1081
- if (keyObject.asymmetricKeyType === "ed25519") {
1082
- if (alg !== "EdDSA" && alg !== "Ed25519") {
1083
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1084
- }
1085
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
1086
- isPublic ? "verify" : "sign"
1087
- ]);
1088
- }
1089
- switch (keyObject.asymmetricKeyType) {
1090
- case "ml-dsa-44":
1091
- case "ml-dsa-65":
1092
- case "ml-dsa-87": {
1093
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
1094
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1095
- }
1096
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
1097
- isPublic ? "verify" : "sign"
1098
- ]);
1099
- }
1100
- }
1101
- if (keyObject.asymmetricKeyType === "rsa") {
1102
- let hash;
1103
- switch (alg) {
1104
- case "RSA-OAEP":
1105
- hash = "SHA-1";
1106
- break;
1107
- case "RS256":
1108
- case "PS256":
1109
- case "RSA-OAEP-256":
1110
- hash = "SHA-256";
1111
- break;
1112
- case "RS384":
1113
- case "PS384":
1114
- case "RSA-OAEP-384":
1115
- hash = "SHA-384";
1116
- break;
1117
- case "RS512":
1118
- case "PS512":
1119
- case "RSA-OAEP-512":
1120
- hash = "SHA-512";
1121
- break;
1122
- default:
1123
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1124
- }
1125
- if (alg.startsWith("RSA-OAEP")) {
1126
- return keyObject.toCryptoKey({
1127
- name: "RSA-OAEP",
1128
- hash
1129
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
1130
- }
1131
- cryptoKey = keyObject.toCryptoKey({
1132
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
1133
- hash
1134
- }, extractable, [isPublic ? "verify" : "sign"]);
1135
- }
1136
- if (keyObject.asymmetricKeyType === "ec") {
1137
- const nist = /* @__PURE__ */ new Map([
1138
- ["prime256v1", "P-256"],
1139
- ["secp384r1", "P-384"],
1140
- ["secp521r1", "P-521"]
1141
- ]);
1142
- const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
1143
- if (!namedCurve) {
1144
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1145
- }
1146
- if (alg === "ES256" && namedCurve === "P-256") {
1147
- cryptoKey = keyObject.toCryptoKey({
1148
- name: "ECDSA",
1149
- namedCurve
1150
- }, extractable, [isPublic ? "verify" : "sign"]);
1151
- }
1152
- if (alg === "ES384" && namedCurve === "P-384") {
1153
- cryptoKey = keyObject.toCryptoKey({
1154
- name: "ECDSA",
1155
- namedCurve
1156
- }, extractable, [isPublic ? "verify" : "sign"]);
1157
- }
1158
- if (alg === "ES512" && namedCurve === "P-521") {
1159
- cryptoKey = keyObject.toCryptoKey({
1160
- name: "ECDSA",
1161
- namedCurve
1162
- }, extractable, [isPublic ? "verify" : "sign"]);
1163
- }
1164
- if (alg.startsWith("ECDH-ES")) {
1165
- cryptoKey = keyObject.toCryptoKey({
1166
- name: "ECDH",
1167
- namedCurve
1168
- }, extractable, isPublic ? [] : ["deriveBits"]);
1169
- }
1170
- }
1171
- if (!cryptoKey) {
1172
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1173
- }
1174
- if (!cached) {
1175
- cache.set(keyObject, { [alg]: cryptoKey });
1176
- } else {
1177
- cached[alg] = cryptoKey;
1178
- }
1179
- return cryptoKey;
1180
- };
1181
- async function normalizeKey(key, alg) {
1182
- if (key instanceof Uint8Array) {
1183
- return key;
1184
- }
1185
- if (isCryptoKey(key)) {
1186
- return key;
1187
- }
1188
- if (isKeyObject(key)) {
1189
- if (key.type === "secret") {
1190
- return key.export();
1191
- }
1192
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
1193
- try {
1194
- return handleKeyObject(key, alg);
1195
- } catch (err) {
1196
- if (err instanceof TypeError) {
1197
- throw err;
1198
- }
1199
- }
1200
- }
1201
- let jwk = key.export({ format: "jwk" });
1202
- return handleJWK(key, jwk, alg);
1203
- }
1204
- if (isJWK(key)) {
1205
- if (key.k) {
1206
- return decode(key.k);
1207
- }
1208
- return handleJWK(key, key, alg, true);
1209
- }
1210
- throw new Error("unreachable");
1211
- }
1212
-
1213
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/check_key_type.js
1214
- var tag = (key) => key?.[Symbol.toStringTag];
1215
- var jwkMatchesOp = (alg, key, usage) => {
1216
- if (key.use !== void 0) {
1217
- let expected;
1218
- switch (usage) {
1219
- case "sign":
1220
- case "verify":
1221
- expected = "sig";
1222
- break;
1223
- case "encrypt":
1224
- case "decrypt":
1225
- expected = "enc";
1226
- break;
1227
- }
1228
- if (key.use !== expected) {
1229
- throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
1230
- }
1231
- }
1232
- if (key.alg !== void 0 && key.alg !== alg) {
1233
- throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
1234
- }
1235
- if (Array.isArray(key.key_ops)) {
1236
- let expectedKeyOp;
1237
- switch (true) {
1238
- case (usage === "sign" || usage === "verify"):
1239
- case alg === "dir":
1240
- case alg.includes("CBC-HS"):
1241
- expectedKeyOp = usage;
1242
- break;
1243
- case alg.startsWith("PBES2"):
1244
- expectedKeyOp = "deriveBits";
1245
- break;
1246
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
1247
- if (!alg.includes("GCM") && alg.endsWith("KW")) {
1248
- expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
1249
- } else {
1250
- expectedKeyOp = usage;
1251
- }
1252
- break;
1253
- case (usage === "encrypt" && alg.startsWith("RSA")):
1254
- expectedKeyOp = "wrapKey";
1255
- break;
1256
- case usage === "decrypt":
1257
- expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
1258
- break;
1259
- }
1260
- if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
1261
- throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
1262
- }
1263
- }
1264
- return true;
1265
- };
1266
- var symmetricTypeCheck = (alg, key, usage) => {
1267
- if (key instanceof Uint8Array)
1268
- return;
1269
- if (isJWK(key)) {
1270
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
1271
- return;
1272
- 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`);
1273
- }
1274
- if (!isKeyLike(key)) {
1275
- throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
1276
- }
1277
- if (key.type !== "secret") {
1278
- throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
1279
- }
1280
- };
1281
- var asymmetricTypeCheck = (alg, key, usage) => {
1282
- if (isJWK(key)) {
1283
- switch (usage) {
1284
- case "decrypt":
1285
- case "sign":
1286
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
1287
- return;
1288
- throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
1289
- case "encrypt":
1290
- case "verify":
1291
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
1292
- return;
1293
- throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
1294
- }
1295
- }
1296
- if (!isKeyLike(key)) {
1297
- throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
1298
- }
1299
- if (key.type === "secret") {
1300
- throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
1301
- }
1302
- if (key.type === "public") {
1303
- switch (usage) {
1304
- case "sign":
1305
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
1306
- case "decrypt":
1307
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
1308
- }
1309
- }
1310
- if (key.type === "private") {
1311
- switch (usage) {
1312
- case "verify":
1313
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
1314
- case "encrypt":
1315
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
1316
- }
1317
- }
1318
- };
1319
- function checkKeyType(alg, key, usage) {
1320
- switch (alg.substring(0, 2)) {
1321
- case "A1":
1322
- case "A2":
1323
- case "di":
1324
- case "HS":
1325
- case "PB":
1326
- symmetricTypeCheck(alg, key, usage);
1327
- break;
1328
- default:
1329
- asymmetricTypeCheck(alg, key, usage);
1330
- }
1331
- }
1332
-
1333
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/subtle_dsa.js
1334
- function subtleAlgorithm(alg, algorithm) {
1335
- const hash = `SHA-${alg.slice(-3)}`;
1336
- switch (alg) {
1337
- case "HS256":
1338
- case "HS384":
1339
- case "HS512":
1340
- return { hash, name: "HMAC" };
1341
- case "PS256":
1342
- case "PS384":
1343
- case "PS512":
1344
- return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
1345
- case "RS256":
1346
- case "RS384":
1347
- case "RS512":
1348
- return { hash, name: "RSASSA-PKCS1-v1_5" };
1349
- case "ES256":
1350
- case "ES384":
1351
- case "ES512":
1352
- return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
1353
- case "Ed25519":
1354
- case "EdDSA":
1355
- return { name: "Ed25519" };
1356
- case "ML-DSA-44":
1357
- case "ML-DSA-65":
1358
- case "ML-DSA-87":
1359
- return { name: alg };
1360
- default:
1361
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
1362
- }
1363
- }
1364
-
1365
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
1366
- async function getSigKey(alg, key, usage) {
1367
- if (key instanceof Uint8Array) {
1368
- if (!alg.startsWith("HS")) {
1369
- throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
1370
- }
1371
- return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
1372
- }
1373
- checkSigCryptoKey(key, alg, usage);
1374
- return key;
1375
- }
1376
-
1377
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/verify.js
1378
- async function verify(alg, key, signature, data) {
1379
- const cryptoKey = await getSigKey(alg, key, "verify");
1380
- checkKeyLength(alg, cryptoKey);
1381
- const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
1382
- try {
1383
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
1384
- } catch {
1385
- return false;
1386
- }
1387
- }
1388
-
1389
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/jws/flattened/verify.js
1390
- async function flattenedVerify(jws, key, options) {
1391
- if (!isObject(jws)) {
1392
- throw new JWSInvalid("Flattened JWS must be an object");
1393
- }
1394
- if (jws.protected === void 0 && jws.header === void 0) {
1395
- throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
1396
- }
1397
- if (jws.protected !== void 0 && typeof jws.protected !== "string") {
1398
- throw new JWSInvalid("JWS Protected Header incorrect type");
1399
- }
1400
- if (jws.payload === void 0) {
1401
- throw new JWSInvalid("JWS Payload missing");
1402
- }
1403
- if (typeof jws.signature !== "string") {
1404
- throw new JWSInvalid("JWS Signature missing or incorrect type");
1405
- }
1406
- if (jws.header !== void 0 && !isObject(jws.header)) {
1407
- throw new JWSInvalid("JWS Unprotected Header incorrect type");
1408
- }
1409
- let parsedProt = {};
1410
- if (jws.protected) {
1411
- try {
1412
- const protectedHeader = decode(jws.protected);
1413
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
1414
- } catch {
1415
- throw new JWSInvalid("JWS Protected Header is invalid");
1416
- }
1417
- }
1418
- if (!isDisjoint(parsedProt, jws.header)) {
1419
- throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1420
- }
1421
- const joseHeader = {
1422
- ...parsedProt,
1423
- ...jws.header
1424
- };
1425
- const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
1426
- let b64 = true;
1427
- if (extensions.has("b64")) {
1428
- b64 = parsedProt.b64;
1429
- if (typeof b64 !== "boolean") {
1430
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
1431
- }
1432
- }
1433
- const { alg } = joseHeader;
1434
- if (typeof alg !== "string" || !alg) {
1435
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
1436
- }
1437
- const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
1438
- if (algorithms && !algorithms.has(alg)) {
1439
- throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
1440
- }
1441
- if (b64) {
1442
- if (typeof jws.payload !== "string") {
1443
- throw new JWSInvalid("JWS Payload must be a string");
1444
- }
1445
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
1446
- throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
1447
- }
1448
- let resolvedKey = false;
1449
- if (typeof key === "function") {
1450
- key = await key(parsedProt, jws);
1451
- resolvedKey = true;
1452
- }
1453
- checkKeyType(alg, key, "verify");
1454
- 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);
1455
- let signature;
1456
- try {
1457
- signature = decode(jws.signature);
1458
- } catch {
1459
- throw new JWSInvalid("Failed to base64url decode the signature");
1460
- }
1461
- const k = await normalizeKey(key, alg);
1462
- const verified = await verify(alg, k, signature, data);
1463
- if (!verified) {
1464
- throw new JWSSignatureVerificationFailed();
1465
- }
1466
- let payload;
1467
- if (b64) {
1468
- try {
1469
- payload = decode(jws.payload);
1470
- } catch {
1471
- throw new JWSInvalid("Failed to base64url decode the payload");
1472
- }
1473
- } else if (typeof jws.payload === "string") {
1474
- payload = encoder.encode(jws.payload);
1475
- } else {
1476
- payload = jws.payload;
1477
- }
1478
- const result = { payload };
1479
- if (jws.protected !== void 0) {
1480
- result.protectedHeader = parsedProt;
1481
- }
1482
- if (jws.header !== void 0) {
1483
- result.unprotectedHeader = jws.header;
1484
- }
1485
- if (resolvedKey) {
1486
- return { ...result, key: k };
1487
- }
1488
- return result;
1489
- }
1490
-
1491
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/jws/compact/verify.js
1492
- async function compactVerify(jws, key, options) {
1493
- if (jws instanceof Uint8Array) {
1494
- jws = decoder.decode(jws);
1495
- }
1496
- if (typeof jws !== "string") {
1497
- throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
1498
- }
1499
- const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
1500
- if (length !== 3) {
1501
- throw new JWSInvalid("Invalid Compact JWS");
1502
- }
1503
- const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
1504
- const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
1505
- if (typeof key === "function") {
1506
- return { ...result, key: verified.key };
1507
- }
1508
- return result;
1509
- }
1510
-
1511
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
1512
- var epoch = (date) => Math.floor(date.getTime() / 1e3);
1513
- var minute = 60;
1514
- var hour = minute * 60;
1515
- var day = hour * 24;
1516
- var week = day * 7;
1517
- var year = day * 365.25;
1518
- 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;
1519
- function secs(str) {
1520
- const matched = REGEX.exec(str);
1521
- if (!matched || matched[4] && matched[1]) {
1522
- throw new TypeError("Invalid time period format");
1523
- }
1524
- const value = parseFloat(matched[2]);
1525
- const unit = matched[3].toLowerCase();
1526
- let numericDate;
1527
- switch (unit) {
1528
- case "sec":
1529
- case "secs":
1530
- case "second":
1531
- case "seconds":
1532
- case "s":
1533
- numericDate = Math.round(value);
1534
- break;
1535
- case "minute":
1536
- case "minutes":
1537
- case "min":
1538
- case "mins":
1539
- case "m":
1540
- numericDate = Math.round(value * minute);
1541
- break;
1542
- case "hour":
1543
- case "hours":
1544
- case "hr":
1545
- case "hrs":
1546
- case "h":
1547
- numericDate = Math.round(value * hour);
1548
- break;
1549
- case "day":
1550
- case "days":
1551
- case "d":
1552
- numericDate = Math.round(value * day);
1553
- break;
1554
- case "week":
1555
- case "weeks":
1556
- case "w":
1557
- numericDate = Math.round(value * week);
1558
- break;
1559
- default:
1560
- numericDate = Math.round(value * year);
1561
- break;
1562
- }
1563
- if (matched[1] === "-" || matched[4] === "ago") {
1564
- return -numericDate;
1565
- }
1566
- return numericDate;
1567
- }
1568
- var normalizeTyp = (value) => {
1569
- if (value.includes("/")) {
1570
- return value.toLowerCase();
1571
- }
1572
- return `application/${value.toLowerCase()}`;
1573
- };
1574
- var checkAudiencePresence = (audPayload, audOption) => {
1575
- if (typeof audPayload === "string") {
1576
- return audOption.includes(audPayload);
1577
- }
1578
- if (Array.isArray(audPayload)) {
1579
- return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
1580
- }
1581
- return false;
1582
- };
1583
- function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
1584
- let payload;
1585
- try {
1586
- payload = JSON.parse(decoder.decode(encodedPayload));
1587
- } catch {
1588
- }
1589
- if (!isObject(payload)) {
1590
- throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
1591
- }
1592
- const { typ } = options;
1593
- if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
1594
- throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
1595
- }
1596
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
1597
- const presenceCheck = [...requiredClaims];
1598
- if (maxTokenAge !== void 0)
1599
- presenceCheck.push("iat");
1600
- if (audience !== void 0)
1601
- presenceCheck.push("aud");
1602
- if (subject !== void 0)
1603
- presenceCheck.push("sub");
1604
- if (issuer !== void 0)
1605
- presenceCheck.push("iss");
1606
- for (const claim of new Set(presenceCheck.reverse())) {
1607
- if (!(claim in payload)) {
1608
- throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
1609
- }
1610
- }
1611
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
1612
- throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
1613
- }
1614
- if (subject && payload.sub !== subject) {
1615
- throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
1616
- }
1617
- if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
1618
- throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
1619
- }
1620
- let tolerance;
1621
- switch (typeof options.clockTolerance) {
1622
- case "string":
1623
- tolerance = secs(options.clockTolerance);
1624
- break;
1625
- case "number":
1626
- tolerance = options.clockTolerance;
1627
- break;
1628
- case "undefined":
1629
- tolerance = 0;
1630
- break;
1631
- default:
1632
- throw new TypeError("Invalid clockTolerance option type");
1633
- }
1634
- const { currentDate } = options;
1635
- const now = epoch(currentDate || /* @__PURE__ */ new Date());
1636
- if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
1637
- throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
1638
- }
1639
- if (payload.nbf !== void 0) {
1640
- if (typeof payload.nbf !== "number") {
1641
- throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
1642
- }
1643
- if (payload.nbf > now + tolerance) {
1644
- throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
1645
- }
1646
- }
1647
- if (payload.exp !== void 0) {
1648
- if (typeof payload.exp !== "number") {
1649
- throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
1650
- }
1651
- if (payload.exp <= now - tolerance) {
1652
- throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
1653
- }
1654
- }
1655
- if (maxTokenAge) {
1656
- const age = now - payload.iat;
1657
- const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
1658
- if (age - tolerance > max) {
1659
- throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
1660
- }
1661
- if (age < 0 - tolerance) {
1662
- throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
1663
- }
1664
- }
1665
- return payload;
1666
- }
1667
-
1668
- // ../../../../../.bun/install/cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/jwt/verify.js
1669
- async function jwtVerify(jwt, key, options) {
1670
- const verified = await compactVerify(jwt, key, options);
1671
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
1672
- throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1673
- }
1674
- const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
1675
- const result = { payload, protectedHeader: verified.protectedHeader };
1676
- if (typeof key === "function") {
1677
- return { ...result, key: verified.key };
1678
- }
1679
- return result;
1680
- }
1681
-
1682
- // src/connection-url.ts
1683
- var SYLPHX_PROTOCOL = "sylphx:";
1684
- var DEFAULT_VERSION = "v1";
1685
- var CREDENTIAL_REGEX = /^(pk|sk)_(dev|stg|prod|prev)(?:_[a-z0-9]{12})?_[a-f0-9]{32,64}$/;
1686
- var VERSION_REGEX = /^v[0-9]+$/;
1687
- var SLUG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
1688
- var InvalidConnectionUrlError = class _InvalidConnectionUrlError extends Error {
1689
- code = "INVALID_CONNECTION_URL";
1690
- constructor(message2) {
1691
- super(message2);
1692
- this.name = "InvalidConnectionUrlError";
1693
- Object.setPrototypeOf(this, _InvalidConnectionUrlError.prototype);
1694
- }
1695
- };
1696
- function fail(reason) {
1697
- throw new InvalidConnectionUrlError(`Invalid Sylphx connection URL: ${reason}`);
1698
- }
1699
- function parseCredential(raw) {
1700
- const match = CREDENTIAL_REGEX.exec(raw);
1701
- if (!match) {
1702
- fail(`credential must match (pk|sk)_(dev|stg|prod|prev)(_{ref})?_{hex}, got "${raw}"`);
1703
- }
1704
- return {
1705
- credentialType: match[1],
1706
- env: match[2]
1707
- };
1708
- }
1709
- function validateSlug(candidate) {
1710
- if (!candidate || candidate.length > 63 || !SLUG_REGEX.test(candidate)) {
1711
- fail(`slug "${candidate}" is not a valid DNS label (lowercase alnum + hyphens, 1-63 chars)`);
1712
- }
1713
- return candidate;
1714
- }
1715
- function parseConnectionUrl(url) {
1716
- if (typeof url !== "string" || url.length === 0) {
1717
- fail("url must be a non-empty string");
1718
- }
1719
- let parsed;
1720
- try {
1721
- parsed = new URL(url);
1722
- } catch {
1723
- fail(`not a valid URL: "${url}"`);
1724
- }
1725
- if (parsed.protocol !== SYLPHX_PROTOCOL) {
1726
- fail(`protocol must be "sylphx:", got "${parsed.protocol}"`);
1727
- }
1728
- const credential = decodeURIComponent(parsed.username);
1729
- if (!credential) {
1730
- fail("missing credential (expected `sylphx://<credential>@<host>`)");
1731
- }
1732
- if (parsed.password) {
1733
- fail("connection URL must not contain a password component");
1734
- }
1735
- const { credentialType, env } = parseCredential(credential);
1736
- const host = parsed.host;
1737
- if (!host) {
1738
- fail("missing host");
1739
- }
1740
- const hostname = parsed.hostname;
1741
- const firstDot = hostname.indexOf(".");
1742
- if (firstDot <= 0) {
1743
- fail(`host "${hostname}" must contain at least one dot (slug.domain)`);
1744
- }
1745
- const slugCandidate = hostname.slice(0, firstDot);
1746
- const domainSuffix = hostname.slice(firstDot + 1);
1747
- if (!domainSuffix) {
1748
- fail(`host "${hostname}" has empty domain suffix`);
1749
- }
1750
- const slug = validateSlug(slugCandidate);
1751
- const rawPath = parsed.pathname.replace(/^\/+/, "").replace(/\/+$/, "");
1752
- let version = DEFAULT_VERSION;
1753
- if (rawPath !== "") {
1754
- if (!VERSION_REGEX.test(rawPath)) {
1755
- fail(`path "${parsed.pathname}" must be empty or match /v{N}`);
1756
- }
1757
- version = rawPath;
1758
- }
1759
- if (parsed.search) {
1760
- fail("connection URL must not contain a query string");
1761
- }
1762
- if (parsed.hash) {
1763
- fail("connection URL must not contain a fragment");
1764
- }
1765
- const apiBaseUrl = `https://${host}/${version}`;
1766
- return {
1767
- credential,
1768
- credentialType,
1769
- env,
1770
- slug,
1771
- host,
1772
- apiBaseUrl
1773
- };
1774
- }
1775
-
1776
- // src/lib/ids.ts
1777
- var CB32 = "0123456789abcdefghjkmnpqrstvwxyz";
1778
- var CB32_MAP = Object.fromEntries([...CB32].map((c, i) => [c, i]));
1779
- var B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1780
- var B58_MAP = Object.fromEntries([...B58].map((c, i) => [c, i]));
1781
- function cb32Encode(hex) {
1782
- const num = BigInt(`0x${hex}`);
1783
- const chars = [];
1784
- let n = num;
1785
- for (let i = 0; i < 26; i++) {
1786
- chars.unshift(CB32[Number(n & 0x1fn)]);
1787
- n >>= 5n;
1788
- }
1789
- return chars.join("");
1790
- }
1791
- function cb32Decode(str) {
1792
- if (str.length !== 26) return null;
1793
- let n = 0n;
1794
- for (const c of str.toLowerCase()) {
1795
- const idx = CB32_MAP[c];
1796
- if (idx === void 0) return null;
1797
- n = n << 5n | BigInt(idx);
1798
- }
1799
- return n.toString(16).padStart(32, "0");
1800
- }
1801
- function b58Decode(str) {
1802
- let n = 0n;
1803
- for (const c of str) {
1804
- const i = B58_MAP[c] ?? -1;
1805
- if (i === -1) return null;
1806
- n = n * 58n + BigInt(i);
1807
- }
1808
- const hex = n.toString(16).padStart(32, "0");
1809
- return hex.length === 32 ? hex : null;
1810
- }
1811
- function hexToUuid(hex) {
1812
- return [
1813
- hex.slice(0, 8),
1814
- hex.slice(8, 12),
1815
- hex.slice(12, 16),
1816
- hex.slice(16, 20),
1817
- hex.slice(20)
1818
- ].join("-");
1819
- }
1820
- function encodeUserId(uuid) {
1821
- const hex = uuid.replace(/-/g, "");
1822
- if (hex.length !== 32)
1823
- throw new Error("Invalid UUID: expected 32 hex chars after stripping dashes");
1824
- return `user_${cb32Encode(hex)}`;
1825
- }
1826
- function decodeUserId(prefixedId) {
1827
- if (!prefixedId.startsWith("user_")) return null;
1828
- const enc = prefixedId.slice(5);
1829
- if (!enc) return null;
1830
- if (enc.length === 26) {
1831
- const hex2 = cb32Decode(enc);
1832
- if (hex2) return hexToUuid(hex2);
1833
- }
1834
- const hex = b58Decode(enc);
1835
- if (hex) return hexToUuid(hex);
1836
- return null;
1837
- }
1838
-
1839
- // src/server/index.ts
1840
- var PLATFORM_TENANT_BAAS_URL = `https://${PLATFORM_CONSOLE_SLUG}.${DEFAULT_SDK_API_HOST}${SDK_API_PATH}`;
1841
- function isJwksResponse(data) {
1842
- return typeof data === "object" && data !== null && "keys" in data && Array.isArray(data.keys);
1843
- }
1844
- function isAccessTokenPayload(payload) {
1845
- return typeof payload.sub === "string" && typeof payload.email === "string" && typeof payload.app_id === "string" && typeof payload.iat === "number" && typeof payload.exp === "number";
1846
- }
1847
- var DEFAULT_JWT_ISSUER = DEFAULT_PLATFORM_URL;
1848
- var JWT_JWKS_PATH = "/api/v1/auth/.well-known/jwks.json";
1849
- var jwksCache = null;
1850
- function normalizeIssuerOrigin(issuer) {
1851
- return issuer.trim().replace(/\/+$/, "");
1852
- }
1853
- function resolveJwtIssuer(explicit) {
1854
- const fromEnv = process.env.SYLPHX_JWT_ISSUER?.trim();
1855
- return normalizeIssuerOrigin(explicit || fromEnv || DEFAULT_JWT_ISSUER);
1856
- }
1857
- async function getJwks(issuer = DEFAULT_JWT_ISSUER) {
1858
- const issuerOrigin = resolveJwtIssuer(issuer);
1859
- const now = Date.now();
1860
- if (jwksCache && jwksCache.issuer === issuerOrigin && jwksCache.expiresAt > now) {
1861
- return jwksCache.keys;
1862
- }
1863
- const response = await fetch(`${issuerOrigin}${JWT_JWKS_PATH}`);
1864
- if (!response.ok) {
1865
- throw new Error(`Failed to fetch JWKS from ${issuerOrigin}${JWT_JWKS_PATH}`);
1866
- }
1867
- const data = await response.json();
1868
- if (!isJwksResponse(data)) {
1869
- throw new Error("Invalid JWKS response format");
1870
- }
1871
- jwksCache = {
1872
- issuer: issuerOrigin,
1873
- keys: data.keys,
1874
- expiresAt: now + JWK_CACHE_TTL_MS
1875
- // Cache for 1 hour
1876
- };
1877
- return data.keys;
1878
- }
1879
- async function verifyAccessToken(token, options) {
1880
- const audience = options.audience;
1881
- if (audience === void 0 || audience === null || typeof audience === "string" && !audience.trim() || Array.isArray(audience) && audience.length === 0) {
1882
- throw new Error(
1883
- "verifyAccessToken requires audience (token aud / app.slug). Omitting audience is fail-open and is not allowed."
1884
- );
1885
- }
1886
- void options.platformUrl;
1887
- void options.secretKey;
1888
- const issuer = resolveJwtIssuer(options.issuer);
1889
- const keys = await getJwks(issuer);
1890
- if (!keys.length) {
1891
- throw new Error("No keys in JWKS");
1892
- }
1893
- let lastError = null;
1894
- for (const key of keys) {
1895
- try {
1896
- const jwk = await importJWK(key, "RS256");
1897
- const { payload } = await jwtVerify(token, jwk, {
1898
- issuer,
1899
- audience
1900
- });
1901
- if (!isAccessTokenPayload(payload)) {
1902
- throw new Error("Invalid token payload structure");
1903
- }
1904
- const cnfRaw = payload.cnf;
1905
- const cnf = cnfRaw && typeof cnfRaw === "object" && "jkt" in cnfRaw ? { jkt: typeof cnfRaw.jkt === "string" ? cnfRaw.jkt : void 0 } : void 0;
1906
- return {
1907
- sub: payload.sub,
1908
- pid: payload.pid,
1909
- email: payload.email,
1910
- name: payload.name,
1911
- picture: payload.picture,
1912
- email_verified: payload.email_verified,
1913
- app_id: payload.app_id,
1914
- role: payload.role,
1915
- // Org context — preserved so downstream org-scoped authz works
1916
- // (ADR-2062). Absent on plain user tokens.
1917
- org_id: typeof payload.org_id === "string" ? payload.org_id : void 0,
1918
- org_slug: typeof payload.org_slug === "string" ? payload.org_slug : void 0,
1919
- org_role: typeof payload.org_role === "string" ? payload.org_role : void 0,
1920
- iat: payload.iat,
1921
- exp: payload.exp,
1922
- ...cnf ? { cnf } : {}
1923
- };
1924
- } catch (err) {
1925
- lastError = err;
1926
- }
1927
- }
1928
- throw lastError || new Error("Token verification failed");
1929
- }
1930
-
1931
- // src/nextjs/token-audience.ts
1932
- var SylphxTokenAudienceError = class extends Error {
1933
- name = "SylphxTokenAudienceError";
1934
- };
1935
- function projectSlugFromBaasHost(hostname) {
1936
- const host = hostname.trim().toLowerCase().replace(/\.$/, "");
1937
- if (!host || host === "localhost" || host.startsWith("127.")) return null;
1938
- const match = /^([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.api\./.exec(host);
1939
- if (!match?.[1]) return null;
1940
- if (match[1] === "api") return null;
1941
- return match[1];
1942
- }
1943
- function resolveNextjsTokenAudience(options) {
1944
- void options.secretKey;
1945
- const explicit = options.explicitAudience?.trim();
1946
- if (explicit) return explicit;
1947
- const fromEnv = process.env.SYLPHX_TOKEN_AUDIENCE?.trim();
1948
- if (fromEnv) return fromEnv;
1949
- if (options.platformUrl) {
1950
- try {
1951
- const host = new URL(options.platformUrl).hostname;
1952
- const slug = projectSlugFromBaasHost(host);
1953
- if (slug) return slug;
1954
- } catch {
1955
- }
1956
- }
1957
- throw new SylphxTokenAudienceError(
1958
- "[Sylphx] Token audience is required for session verification. Set SYLPHX_TOKEN_AUDIENCE to your project slug (JWT aud / app.slug), or use a BaaS platformUrl of the form https://{slug}.api.sylphx.com, or pass audience explicitly to configureServer()."
1959
- );
1960
- }
1961
-
1962
- // src/nextjs/session-verify.ts
1963
- var defaultVerifier = (token, options) => {
1964
- const audience = options.audience?.trim() || resolveNextjsTokenAudience({
1965
- platformUrl: options.platformUrl,
1966
- secretKey: options.secretKey
1967
- });
1968
- return verifyAccessToken(token, {
1969
- issuer: options.issuer ?? DEFAULT_JWT_ISSUER,
1970
- audience,
1971
- // platformUrl intentionally not used as issuer/JWKS origin
1972
- platformUrl: options.platformUrl,
1973
- secretKey: options.secretKey
1974
- });
1975
- };
1976
- var sessionVerifier = defaultVerifier;
1977
- function verifyNextjsSessionToken(token, options) {
1978
- return sessionVerifier(token, options);
1979
- }
1980
- async function resolveVerifiedSessionToken(token, options) {
1981
- if (!token) return null;
1982
- try {
1983
- await verifyNextjsSessionToken(token, options);
1984
- return token;
1985
- } catch {
1986
- return null;
1987
- }
1988
- }
1989
-
1990
- // src/nextjs/middleware-token-route.ts
1991
- function withNoStoreAuthHeaders(response) {
1992
- response.headers.set("Cache-Control", "no-store, no-cache, must-revalidate, private");
1993
- response.headers.set("Pragma", "no-cache");
1994
- return response;
1995
- }
1996
- function sessionMetadataBody(sessionToken, user) {
1997
- const payload = decodeJwtPayload(sessionToken);
1998
- const userId = payload?.sub ?? user.id;
1999
- const expiresAt = typeof payload?.exp === "number" ? new Date(payload.exp * 1e3).toISOString() : new Date(Date.now() + SESSION_TOKEN_LIFETIME * 1e3).toISOString();
2000
- return {
2001
- success: true,
2002
- session: {
2003
- id: `platform:${userId}`,
2004
- userId,
2005
- expiresAt
2006
- },
2007
- user
2008
- };
2009
- }
2010
- async function handleTokenRoute(params) {
2011
- const {
2012
- request,
2013
- ctx,
2014
- sessionToken,
2015
- userCookie,
2016
- hasRefreshCookie,
2017
- refreshSessionFromCookie: refreshSessionFromCookie2,
2018
- setRestoredSessionCookies: setRestoredSessionCookies2
2019
- } = params;
2020
- if (request.method !== "GET") {
2021
- return withNoStoreAuthHeaders(
2022
- NextResponse.json({ error: "Method not allowed" }, { status: 405 })
2023
- );
2024
- }
2025
- ctx.log("Token status/refresh request (no bearer body)");
2026
- const verifyOpts = { secretKey: ctx.secretKey, platformUrl: ctx.platformUrl };
2027
- const verifiedSession = await resolveVerifiedSessionToken(sessionToken, verifyOpts);
2028
- if (verifiedSession && userCookie?.user) {
2029
- return withNoStoreAuthHeaders(
2030
- NextResponse.json(sessionMetadataBody(verifiedSession, userCookie.user))
2031
- );
2032
- }
2033
- if (verifiedSession) {
2034
- const payload = decodeJwtPayload(verifiedSession);
2035
- const userId = typeof payload?.sub === "string" ? payload.sub : null;
2036
- const expiresAt = typeof payload?.exp === "number" ? new Date(payload.exp * 1e3).toISOString() : new Date(Date.now() + SESSION_TOKEN_LIFETIME * 1e3).toISOString();
2037
- return withNoStoreAuthHeaders(
2038
- NextResponse.json({
2039
- success: true,
2040
- authenticated: true,
2041
- session: userId ? { id: `platform:${userId}`, userId, expiresAt } : { id: null, userId: null, expiresAt },
2042
- user: null
2043
- })
2044
- );
2045
- }
2046
- const restored = await refreshSessionFromCookie2(request, ctx, sessionToken);
2047
- const verifiedRestored = restored ? await resolveVerifiedSessionToken(restored.tokens.accessToken, verifyOpts) : null;
2048
- if (restored && verifiedRestored) {
2049
- ctx.log("Session cookies refreshed; bearer not returned to JS");
2050
- const response2 = withNoStoreAuthHeaders(
2051
- NextResponse.json(sessionMetadataBody(verifiedRestored, restored.tokens.user))
2052
- );
2053
- setRestoredSessionCookies2(response2, ctx, restored);
2054
- return response2;
2055
- }
2056
- ctx.log(sessionToken ? "Session token expired" : "No session token");
2057
- const response = withNoStoreAuthHeaders(
2058
- NextResponse.json(
2059
- {
2060
- error: sessionToken ? "Session expired" : "Not authenticated",
2061
- authenticated: false,
2062
- session: null,
2063
- user: null
2064
- },
2065
- { status: 401 }
2066
- )
2067
- );
2068
- if (sessionToken || hasRefreshCookie) {
2069
- clearAuthCookiesMiddleware(response, ctx.namespace);
2070
- }
2071
- return response;
2072
- }
2073
-
2074
- // src/nextjs/runtime-config.ts
2075
- var SylphxRoutingConfigurationError = class extends Error {
2076
- name = "SylphxRoutingConfigurationError";
2077
- };
2078
- function normalizePlatformUrl(url) {
2079
- const trimmed = url.trim().replace(/\/+$/, "");
2080
- return trimmed.endsWith("/v1") ? trimmed.slice(0, -3) : trimmed;
2081
- }
2082
- function parseConnection(value) {
2083
- if (!value) return null;
2084
- return parseConnectionUrl(value.trim());
2085
- }
2086
- function platformUrlFromConnectionUrl(value) {
2087
- const parsed = parseConnection(value);
2088
- return parsed ? `https://${parsed.host}` : null;
2089
- }
2090
- function secretKeyFromConnectionUrl(value) {
2091
- const parsed = parseConnection(value);
2092
- if (!parsed || parsed.credentialType !== "sk") return null;
2093
- return parsed.credential;
2094
- }
2095
- function publishableKeyFromConnectionUrl(value) {
2096
- const parsed = parseConnection(value);
2097
- if (!parsed || parsed.credentialType !== "pk") return null;
2098
- return parsed.credential;
2099
- }
2100
- function resolveNextjsPlatformUrl(options) {
2101
- if (options.explicitPlatformUrl) return normalizePlatformUrl(options.explicitPlatformUrl);
2102
- const fromExplicitSecretUrl = platformUrlFromConnectionUrl(options.secretUrl);
2103
- if (fromExplicitSecretUrl) return fromExplicitSecretUrl;
2104
- const fromSecretUrl = platformUrlFromConnectionUrl(process.env[ENV_SECRET_URL]);
2105
- if (fromSecretUrl) return fromSecretUrl;
2106
- const fromConnectionUrl = platformUrlFromConnectionUrl(process.env[ENV_URL]);
2107
- if (fromConnectionUrl) return fromConnectionUrl;
2108
- const fromBaasOverride = process.env.SYLPHX_BAAS_URL ?? process.env.SYLPHX_RUNTIME_URL;
2109
- if (fromBaasOverride) return normalizePlatformUrl(fromBaasOverride);
2110
- throw new SylphxRoutingConfigurationError(
2111
- '[Sylphx] BaaS routing target is required for @sylphx/sdk/nextjs. Set SYLPHX_SECRET_URL="sylphx://sk_<env>_<hex>@<tenant>.api.sylphx.com" or SYLPHX_URL="sylphx://<credential>@<tenant>.api.sylphx.com" or pass platformUrl explicitly. New-format sk_* credentials do not carry routing material.'
2112
- );
2113
- }
2114
- function resolveNextjsSecretKey(options) {
2115
- if (options.explicitSecretKey?.trim()) return options.explicitSecretKey.trim();
2116
- const fromExplicitSecretUrl = secretKeyFromConnectionUrl(options.explicitSecretUrl);
2117
- if (fromExplicitSecretUrl) return fromExplicitSecretUrl;
2118
- const fromSecretUrl = secretKeyFromConnectionUrl(process.env[ENV_SECRET_URL]);
2119
- if (fromSecretUrl) return fromSecretUrl;
2120
- const fromGenericUrl = secretKeyFromConnectionUrl(process.env[ENV_URL]);
2121
- if (fromGenericUrl) return fromGenericUrl;
2122
- return null;
2123
- }
2124
- function resolveNextjsPublishableKey(options) {
2125
- if (options.explicitPublishableKey?.trim()) return options.explicitPublishableKey.trim();
2126
- const fromExplicitPublicUrl = publishableKeyFromConnectionUrl(options.explicitPublicUrl);
2127
- if (fromExplicitPublicUrl) return fromExplicitPublicUrl;
2128
- const fromPublicUrl = publishableKeyFromConnectionUrl(process.env[ENV_URL]);
2129
- if (fromPublicUrl) return fromPublicUrl;
2130
- const fromNextPublicUrl = publishableKeyFromConnectionUrl(process.env[ENV_PUBLIC_URL]);
2131
- if (fromNextPublicUrl) return fromNextPublicUrl;
2132
- return null;
2133
- }
2134
-
2135
- // src/nextjs/middleware.ts
2136
- function getOAuthPkceCookieName(ctx) {
2137
- return `__${ctx.namespace}_oauth_pkce`;
2138
- }
2139
- function encodeOAuthPkceCookie(value) {
2140
- return encodeURIComponent(JSON.stringify(value));
2141
- }
2142
- function readOAuthPkceVerifier(request, ctx) {
2143
- const raw = request.cookies.get(getOAuthPkceCookieName(ctx))?.value;
2144
- if (!raw) return null;
2145
- try {
2146
- const parsed = JSON.parse(decodeURIComponent(raw));
2147
- if (typeof parsed.verifier !== "string" || parsed.verifier.length < 43) return null;
2148
- if (typeof parsed.createdAt !== "number") return null;
2149
- if (Date.now() - parsed.createdAt > OAUTH_PKCE_TTL_MS) return null;
2150
- return parsed.verifier;
2151
- } catch {
2152
- return null;
2153
- }
2154
- }
2155
- function setOAuthPkceCookie(response, ctx, value) {
2156
- response.cookies.set(getOAuthPkceCookieName(ctx), encodeOAuthPkceCookie(value), {
2157
- ...SECURE_COOKIE_OPTIONS,
2158
- maxAge: OAUTH_PKCE_TTL_SECONDS,
2159
- path: ctx.config.authPrefix
2160
- });
2161
- }
2162
- function clearOAuthPkceCookie(response, ctx) {
2163
- response.cookies.set(getOAuthPkceCookieName(ctx), "", {
2164
- ...SECURE_COOKIE_OPTIONS,
2165
- maxAge: 0,
2166
- path: ctx.config.authPrefix
2167
- });
2168
- }
2169
- function readRequestCookieValue(request, name) {
2170
- const values = request.cookies.getAll(name);
2171
- if (values.length > 0) {
2172
- const value = values[values.length - 1]?.value;
2173
- return value === void 0 ? void 0 : decodeCookieValue(value);
2174
- }
2175
- const cookie = request.cookies.get(name);
2176
- if (cookie) return decodeCookieValue(cookie.value);
2177
- return readCookieValueFromHeader(request.headers.get("cookie"), name) ?? void 0;
2178
- }
2179
- function hasRequestCookie(request, name) {
2180
- return readRequestCookieValue(request, name) !== void 0;
2181
- }
2182
- function isTwoFactorLoginResponse(data) {
2183
- return typeof data === "object" && data !== null && data.requiresTwoFactor === true && typeof data.userId === "string";
2184
- }
2185
- function isOAuthAuthorizeResponse(data) {
2186
- return typeof data === "object" && data !== null && typeof data.authorization_url === "string";
2187
- }
2188
- function authCookieJsonResponse(ctx, data) {
2189
- const response = NextResponse2.json({ success: true, user: data.user });
2190
- setAuthCookiesMiddleware(response, ctx.namespace, data);
2191
- return response;
2192
- }
2193
- function sessionMetadataBody2(sessionToken, user) {
2194
- const payload = decodeJwtPayload(sessionToken);
2195
- const userId = payload?.sub ?? user.id;
2196
- const expiresAt = typeof payload?.exp === "number" ? new Date(payload.exp * 1e3).toISOString() : new Date(Date.now() + SESSION_TOKEN_LIFETIME * 1e3).toISOString();
2197
- return {
2198
- success: true,
2199
- session: {
2200
- id: `platform:${userId}`,
2201
- userId,
2202
- expiresAt
2203
- },
2204
- user
2205
- };
2206
- }
2207
- function setRestoredSessionCookies(response, ctx, restored) {
2208
- setAuthCookiesMiddleware(response, ctx.namespace, restored.tokens);
2209
- if (restored.activeOrganization) {
2210
- setActiveOrganizationCookies(response, ctx, restored.activeOrganization);
2211
- }
2212
- }
2213
- async function refreshSessionFromCookie(request, ctx, previousSessionToken) {
2214
- const refreshToken = readRequestCookieValue(request, ctx.cookieNames.REFRESH);
2215
- if (!refreshToken) return null;
2216
- const refreshedTokens = await refreshTokens(refreshToken, ctx);
2217
- if (!refreshedTokens) return null;
2218
- return restoreOrganizationScopeAfterRefresh(request, ctx, refreshedTokens, previousSessionToken);
2219
- }
2220
- function headersForProjectAuth(ctx) {
2221
- return {
2222
- "Content-Type": "application/json",
2223
- "x-app-secret": ctx.publishableKey
2224
- };
2225
- }
2226
- async function handleRegister(request, ctx) {
2227
- if (request.method !== "POST") {
2228
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2229
- }
2230
- const body = await parseJsonObject(request);
2231
- const res = await fetch(`${ctx.platformUrl}/v1/auth/register`, {
2232
- method: "POST",
2233
- headers: headersForProjectAuth(ctx),
2234
- body: JSON.stringify(body ?? {})
2235
- });
2236
- const data = await res.json().catch(() => ({}));
2237
- return NextResponse2.json(data, { status: res.status });
2238
- }
2239
- async function handleLogin(request, ctx) {
2240
- if (request.method !== "POST") {
2241
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2242
- }
2243
- const body = await parseJsonObject(request);
2244
- const email = typeof body?.email === "string" ? body.email : null;
2245
- const password = typeof body?.password === "string" ? body.password : null;
2246
- if (!email || !password) {
2247
- return NextResponse2.json({ error: "email and password are required" }, { status: 400 });
2248
- }
2249
- const res = await fetch(`${ctx.platformUrl}/v1/auth/login`, {
2250
- method: "POST",
2251
- headers: headersForProjectAuth(ctx),
2252
- body: JSON.stringify({ email, password })
2253
- });
2254
- const data = await res.json().catch(() => ({}));
2255
- if (!res.ok) {
2256
- return NextResponse2.json(data, { status: res.status });
2257
- }
2258
- if (isTwoFactorLoginResponse(data)) {
2259
- return NextResponse2.json(data);
2260
- }
2261
- if (!isTokenResponse(data)) {
2262
- return NextResponse2.json({ error: "invalid_response" }, { status: 502 });
2263
- }
2264
- return authCookieJsonResponse(ctx, data);
2265
- }
2266
- async function handleVerifyEmail(request, ctx) {
2267
- if (request.method !== "POST") {
2268
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2269
- }
2270
- const body = await parseJsonObject(request);
2271
- const token = typeof body?.token === "string" ? body.token : null;
2272
- if (!token) {
2273
- return NextResponse2.json({ error: "token is required" }, { status: 400 });
2274
- }
2275
- const res = await fetch(`${ctx.platformUrl}/v1/auth/verify-email`, {
2276
- method: "POST",
2277
- headers: headersForProjectAuth(ctx),
2278
- body: JSON.stringify({ token })
2279
- });
2280
- const data = await res.json().catch(() => ({}));
2281
- return NextResponse2.json(data, { status: res.status });
2282
- }
2283
- async function handleVerifyTwoFactor(request, ctx) {
2284
- if (request.method !== "POST") {
2285
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2286
- }
2287
- const body = await parseJsonObject(request);
2288
- const userId = typeof body?.userId === "string" ? body.userId : null;
2289
- const code = typeof body?.code === "string" ? body.code : null;
2290
- if (!userId || !code) {
2291
- return NextResponse2.json({ error: "userId and code are required" }, { status: 400 });
2292
- }
2293
- const res = await fetch(`${ctx.platformUrl}/v1/auth/verify-2fa`, {
2294
- method: "POST",
2295
- headers: headersForProjectAuth(ctx),
2296
- body: JSON.stringify({ userId, code })
2297
- });
2298
- const data = await res.json().catch(() => ({}));
2299
- if (!res.ok) {
2300
- return NextResponse2.json(data, { status: res.status });
2301
- }
2302
- if (!isTokenResponse(data)) {
2303
- return NextResponse2.json({ error: "invalid_response" }, { status: 502 });
2304
- }
2305
- return authCookieJsonResponse(ctx, data);
2306
- }
2307
- async function handleSession(request, ctx) {
2308
- if (request.method !== "GET") {
2309
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2310
- }
2311
- const sessionToken = readRequestCookieValue(request, ctx.cookieNames.SESSION);
2312
- const userCookie = parseUserCookie2(readRequestCookieValue(request, ctx.cookieNames.USER));
2313
- const verifyOpts = { secretKey: ctx.secretKey, platformUrl: ctx.platformUrl };
2314
- const verifiedSession = await resolveVerifiedSessionToken(sessionToken, verifyOpts);
2315
- if (verifiedSession && userCookie?.user) {
2316
- return NextResponse2.json(sessionMetadataBody2(verifiedSession, userCookie.user));
2317
- }
2318
- const restored = await refreshSessionFromCookie(request, ctx, sessionToken);
2319
- const verifiedRestored = restored ? await resolveVerifiedSessionToken(restored.tokens.accessToken, verifyOpts) : null;
2320
- if (restored && verifiedRestored) {
2321
- const response2 = NextResponse2.json(sessionMetadataBody2(verifiedRestored, restored.tokens.user));
2322
- setRestoredSessionCookies(response2, ctx, restored);
2323
- return response2;
2324
- }
2325
- const response = NextResponse2.json({ success: true, session: null, user: null });
2326
- if (sessionToken || hasRequestCookie(request, ctx.cookieNames.REFRESH) || userCookie) {
2327
- clearAuthCookiesMiddleware(response, ctx.namespace);
2328
- }
2329
- return response;
2330
- }
2331
- async function handleOAuthProviders(ctx) {
2332
- const res = await fetch(`${ctx.platformUrl}/v1/auth/oauth-providers`, {
2333
- method: "GET",
2334
- headers: headersForProjectAuth(ctx)
2335
- });
2336
- const data = await res.json().catch(() => ({}));
2337
- return NextResponse2.json(data, { status: res.status });
2338
- }
2339
- async function handleOAuthAuthorize(request, ctx) {
2340
- if (request.method !== "GET" && request.method !== "POST") {
2341
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2342
- }
2343
- const body = request.method === "POST" ? await parseJsonObject(request) : null;
2344
- const provider = typeof body?.provider === "string" ? body.provider : request.nextUrl.searchParams.get("provider");
2345
- const rawRedirectTo = typeof body?.redirectTo === "string" ? body.redirectTo : request.nextUrl.searchParams.get("redirect_to") ?? request.nextUrl.searchParams.get("callbackUrl");
2346
- if (!provider) {
2347
- return NextResponse2.json({ error: "provider is required" }, { status: 400 });
2348
- }
2349
- const redirectTo = resolveSafeRelativeRedirectPath(rawRedirectTo, ctx.config.afterSignInUrl);
2350
- const redirectUri = resolveOAuthCallbackUrl(request, ctx);
2351
- redirectUri.searchParams.set("redirect_to", redirectTo);
2352
- const verifier = randomBase64Url(32);
2353
- const challenge = await sha256Base64Url(verifier);
2354
- const scopes = Array.isArray(body?.scopes) ? body.scopes.filter((scope) => typeof scope === "string") : void 0;
2355
- const res = await fetch(`${ctx.platformUrl}/v1/oauth/authorize`, {
2356
- method: "POST",
2357
- headers: headersForProjectAuth(ctx),
2358
- body: JSON.stringify({
2359
- provider,
2360
- redirect_uri: redirectUri.toString(),
2361
- code_challenge: challenge,
2362
- code_challenge_method: "S256",
2363
- ...scopes && scopes.length > 0 ? { scopes } : {}
2364
- })
2365
- });
2366
- const data = await res.json().catch(() => ({}));
2367
- if (!res.ok || !isOAuthAuthorizeResponse(data)) {
2368
- return NextResponse2.json(res.ok ? { error: "invalid_response" } : data, {
2369
- status: res.ok ? 502 : res.status
2370
- });
2371
- }
2372
- const response = request.method === "GET" ? NextResponse2.redirect(data.authorization_url) : NextResponse2.json({
2373
- authorization_url: data.authorization_url,
2374
- authorizationUrl: data.authorization_url
2375
- });
2376
- setOAuthPkceCookie(response, ctx, { verifier, createdAt: Date.now() });
2377
- return response;
2378
- }
2379
- async function handlePasskeyOptions(request, ctx) {
2380
- if (request.method !== "POST") {
2381
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2382
- }
2383
- const body = await parseJsonObject(request);
2384
- const res = await fetch(`${ctx.platformUrl}/v1/auth/passkey/options`, {
2385
- method: "POST",
2386
- headers: headersForProjectAuth(ctx),
2387
- body: JSON.stringify(body ?? {})
2388
- });
2389
- const data = await res.json().catch(() => ({}));
2390
- return NextResponse2.json(data, { status: res.status });
2391
- }
2392
- async function handlePasskeyAuthenticate(request, ctx) {
2393
- if (request.method !== "POST") {
2394
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2395
- }
2396
- const body = await parseJsonObject(request);
2397
- const res = await fetch(`${ctx.platformUrl}/v1/auth/passkey/authenticate`, {
2398
- method: "POST",
2399
- headers: headersForProjectAuth(ctx),
2400
- body: JSON.stringify(body ?? {})
2401
- });
2402
- const data = await res.json().catch(() => ({}));
2403
- if (!res.ok) {
2404
- return NextResponse2.json(data, { status: res.status });
2405
- }
2406
- if (!isTokenResponse(data)) {
2407
- return NextResponse2.json({ error: "invalid_response" }, { status: 502 });
2408
- }
2409
- return authCookieJsonResponse(ctx, data);
2410
- }
2411
- async function handleForgotPassword(request, ctx) {
2412
- if (request.method !== "POST") {
2413
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2414
- }
2415
- const body = await parseJsonObject(request);
2416
- const email = typeof body?.email === "string" ? body.email : null;
2417
- const rawRedirect = typeof body?.redirectUrl === "string" ? body.redirectUrl : typeof body?.redirectTo === "string" ? body.redirectTo : null;
2418
- const redirectUrl = resolveSameOriginUrl(request, rawRedirect, "/reset-password");
2419
- if (!email) {
2420
- return NextResponse2.json({ error: "email is required" }, { status: 400 });
2421
- }
2422
- if (!redirectUrl) {
2423
- return NextResponse2.json({ error: "invalid_redirect_url" }, { status: 400 });
2424
- }
2425
- const res = await fetch(`${ctx.platformUrl}/v1/auth/forgot-password`, {
2426
- method: "POST",
2427
- headers: headersForProjectAuth(ctx),
2428
- body: JSON.stringify({ email, redirectUrl })
2429
- });
2430
- const data = await res.json().catch(() => ({}));
2431
- return NextResponse2.json(data, { status: res.status });
2432
- }
2433
- async function handleResetPassword(request, ctx) {
2434
- if (request.method !== "POST") {
2435
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2436
- }
2437
- const body = await parseJsonObject(request);
2438
- const token = typeof body?.token === "string" ? body.token : null;
2439
- const password = typeof body?.password === "string" ? body.password : typeof body?.newPassword === "string" ? body.newPassword : null;
2440
- if (!token || !password) {
2441
- return NextResponse2.json({ error: "token and password are required" }, { status: 400 });
2442
- }
2443
- const res = await fetch(`${ctx.platformUrl}/v1/auth/reset-password`, {
2444
- method: "POST",
2445
- headers: headersForProjectAuth(ctx),
2446
- body: JSON.stringify({ token, password })
2447
- });
2448
- const data = await res.json().catch(() => ({}));
2449
- return NextResponse2.json(data, { status: res.status });
2450
- }
2451
- async function handleCallback(request, ctx) {
2452
- const { searchParams } = request.nextUrl;
2453
- const code = searchParams.get("code");
2454
- const error = searchParams.get("error");
2455
- const errorDescription = searchParams.get("error_description");
2456
- const redirectTo = searchParams.get("redirect_to") || ctx.config.afterSignInUrl;
2457
- ctx.log("Callback", { hasCode: !!code, error });
2458
- if (error) {
2459
- const url = new URL(ctx.config.signInUrl, request.url);
2460
- url.searchParams.set("error", error);
2461
- if (errorDescription) url.searchParams.set("error_description", errorDescription);
2462
- return NextResponse2.redirect(url);
2463
- }
2464
- if (!code) {
2465
- const url = new URL(ctx.config.signInUrl, request.url);
2466
- url.searchParams.set("error", "missing_code");
2467
- return NextResponse2.redirect(url);
2468
- }
2469
- try {
2470
- const codeVerifier = readOAuthPkceVerifier(request, ctx);
2471
- const res = await fetch(`${ctx.platformUrl}/v1/auth/token`, {
2472
- method: "POST",
2473
- headers: { "Content-Type": "application/json" },
2474
- body: JSON.stringify({
2475
- grant_type: "authorization_code",
2476
- code,
2477
- client_secret: ctx.secretKey,
2478
- ...codeVerifier ? { code_verifier: codeVerifier } : {}
2479
- })
2480
- });
2481
- if (!res.ok) {
2482
- const data2 = await res.json().catch(() => ({}));
2483
- const url = new URL(ctx.config.signInUrl, request.url);
2484
- url.searchParams.set("error", data2.error || "token_exchange_failed");
2485
- const response2 = NextResponse2.redirect(url);
2486
- clearOAuthPkceCookie(response2, ctx);
2487
- return response2;
2488
- }
2489
- const data = await res.json();
2490
- if (!isTokenResponse(data)) {
2491
- const url = new URL(ctx.config.signInUrl, request.url);
2492
- url.searchParams.set("error", "invalid_response");
2493
- const response2 = NextResponse2.redirect(url);
2494
- clearOAuthPkceCookie(response2, ctx);
2495
- return response2;
2496
- }
2497
- const successUrl = new URL(redirectTo, request.url);
2498
- const response = NextResponse2.redirect(successUrl);
2499
- setAuthCookiesMiddleware(response, ctx.namespace, data);
2500
- clearOAuthPkceCookie(response, ctx);
2501
- ctx.log("Callback success", { redirectTo });
2502
- return response;
2503
- } catch (err) {
2504
- console.error("[Sylphx] Callback error:", err);
2505
- const url = new URL(ctx.config.signInUrl, request.url);
2506
- url.searchParams.set("error", "internal_error");
2507
- return NextResponse2.redirect(url);
2508
- }
2509
- }
2510
- async function handleSignOut(request, ctx) {
2511
- ctx.log("Signout");
2512
- const refreshToken = readRequestCookieValue(request, ctx.cookieNames.REFRESH);
2513
- if (refreshToken) {
2514
- try {
2515
- await fetch(`${ctx.platformUrl}/v1/auth/revoke`, {
2516
- method: "POST",
2517
- headers: { "Content-Type": "application/json" },
2518
- body: JSON.stringify({
2519
- token: refreshToken,
2520
- client_secret: ctx.secretKey
2521
- })
2522
- });
2523
- } catch {
2524
- }
2525
- }
2526
- const url = new URL(ctx.config.afterSignOutUrl, request.url);
2527
- const response = NextResponse2.redirect(url);
2528
- clearAuthCookiesMiddleware(response, ctx.namespace);
2529
- ctx.log("Signout complete");
2530
- return response;
2531
- }
2532
- async function handleToken(request, ctx) {
2533
- const sessionToken = readRequestCookieValue(request, ctx.cookieNames.SESSION) ?? null;
2534
- return handleTokenRoute({
2535
- request,
2536
- ctx,
2537
- sessionToken,
2538
- userCookie: parseUserCookie2(readRequestCookieValue(request, ctx.cookieNames.USER)),
2539
- hasRefreshCookie: hasRequestCookie(request, ctx.cookieNames.REFRESH),
2540
- refreshSessionFromCookie: (req, c, token) => refreshSessionFromCookie(req, c, token ?? void 0),
2541
- setRestoredSessionCookies: (response, c, restored) => {
2542
- setRestoredSessionCookies(response, c, restored);
2543
- }
2544
- });
2545
- }
2546
- function resolveOrgScopedTokenExpiresIn(data) {
2547
- if (typeof data.expiresIn === "number") return data.expiresIn;
2548
- if (typeof data.expires_in === "number") return data.expires_in;
2549
- return SESSION_TOKEN_LIFETIME;
2550
- }
2551
- function resolveOrgScopedAccessToken(data) {
2552
- if (data.accessToken) return data.accessToken;
2553
- if (data.access_token) return data.access_token;
2554
- return null;
2555
- }
2556
- function resolveOrgScopedRefreshToken(data, fallbackRefreshToken) {
2557
- if (data.refreshToken) return data.refreshToken;
2558
- if (data.refresh_token) return data.refresh_token;
2559
- return fallbackRefreshToken;
2560
- }
2561
- function resolveOrgScopedTokenType(data) {
2562
- if (data.tokenType) return data.tokenType;
2563
- if (data.token_type) return data.token_type;
2564
- return "Bearer";
2565
- }
2566
- function parseUserCookie2(value) {
2567
- if (!value) return null;
2568
- try {
2569
- return JSON.parse(decodeCookieValue(value));
2570
- } catch {
2571
- return null;
2572
- }
2573
- }
2574
- function readFirstCookieValue(request, names) {
2575
- for (const name of names) {
2576
- const value = readRequestCookieValue(request, name);
2577
- if (value) return value;
2578
- }
2579
- return null;
2580
- }
2581
- function uniqueCookieNames(names) {
2582
- return [...new Set(names.filter((name) => Boolean(name)))];
2583
- }
2584
- function readActiveOrganizationContext(request, ctx, sessionToken) {
2585
- const orgIdCookieNames = uniqueCookieNames([
2586
- ctx.cookieNames.ACTIVE_ORG_ID,
2587
- ...ctx.config.organizationContext.additionalOrgIdCookies
2588
- ]);
2589
- const orgSlugCookieNames = uniqueCookieNames([
2590
- ctx.cookieNames.ACTIVE_ORG_SLUG,
2591
- ...ctx.config.organizationContext.additionalOrgSlugCookies
2592
- ]);
2593
- const fromCookie = {
2594
- id: readFirstCookieValue(request, orgIdCookieNames),
2595
- slug: readFirstCookieValue(request, orgSlugCookieNames)
2596
- };
2597
- if (fromCookie.id || fromCookie.slug) return fromCookie;
2598
- const payload = sessionToken ? decodeJwtPayload(sessionToken) : null;
2599
- return {
2600
- id: payload?.org_id ?? null,
2601
- slug: payload?.org_slug ?? null
2602
- };
2603
- }
2604
- function setActiveOrganizationCookies(response, ctx, org) {
2605
- if (org.id) {
2606
- response.cookies.set(ctx.cookieNames.ACTIVE_ORG_ID, org.id, {
2607
- ...ACTIVE_ORG_COOKIE_OPTIONS,
2608
- maxAge: ACTIVE_ORG_LIFETIME
2609
- });
2610
- }
2611
- if (org.slug) {
2612
- response.cookies.set(ctx.cookieNames.ACTIVE_ORG_SLUG, org.slug, {
2613
- ...ACTIVE_ORG_COOKIE_OPTIONS,
2614
- maxAge: ACTIVE_ORG_LIFETIME
2615
- });
2616
- }
2617
- }
2618
- async function getUserOrganizations(accessToken, ctx) {
2619
- try {
2620
- const res = await fetch(`${ctx.platformUrl}/v1/orgs/memberships`, {
2621
- method: "GET",
2622
- headers: {
2623
- "Content-Type": "application/json",
2624
- "x-app-secret": ctx.secretKey,
2625
- Authorization: `Bearer ${accessToken}`
2626
- }
2627
- });
2628
- if (!res.ok) {
2629
- ctx.log("Organization memberships fetch failed", res.status);
2630
- return null;
2631
- }
2632
- const data = await res.json().catch(() => ({}));
2633
- return Array.isArray(data.organizations) ? data.organizations : null;
2634
- } catch (err) {
2635
- ctx.log("Organization memberships fetch error", err);
2636
- return null;
2637
- }
2638
- }
2639
- async function getOrgScopedTokens(accessToken, orgId, ctx) {
2640
- try {
2641
- const res = await fetch(`${ctx.platformUrl}/v1/auth/switch-org`, {
2642
- method: "POST",
2643
- headers: {
2644
- "Content-Type": "application/json",
2645
- "x-app-secret": ctx.secretKey,
2646
- Authorization: `Bearer ${accessToken}`
2647
- },
2648
- body: JSON.stringify({ orgId })
2649
- });
2650
- const data = await res.json().catch(() => ({}));
2651
- if (!res.ok) {
2652
- ctx.log("Org scope restore failed", data.error || data.message || res.status);
2653
- return { status: res.status, data };
2654
- }
2655
- return { status: res.status, data };
2656
- } catch (err) {
2657
- ctx.log("Org scope restore error", err);
2658
- return null;
2659
- }
2660
- }
2661
- async function restoreOrganizationScopeAfterRefresh(request, ctx, refreshedTokens, previousSessionToken) {
2662
- if (!ctx.config.organizationContext.enabled) {
2663
- return { tokens: refreshedTokens, activeOrganization: null };
2664
- }
2665
- const activeOrg = readActiveOrganizationContext(request, ctx, previousSessionToken);
2666
- let targetOrgId = activeOrg.id;
2667
- let targetOrgSlug = activeOrg.slug;
2668
- let organizations = null;
2669
- if (!targetOrgId && targetOrgSlug) {
2670
- organizations = await getUserOrganizations(refreshedTokens.accessToken, ctx);
2671
- targetOrgId = organizations?.find((org) => org.slug === targetOrgSlug)?.id ?? null;
2672
- }
2673
- if (!targetOrgId && !targetOrgSlug && ctx.config.organizationContext.autoSelectSingleOrganization) {
2674
- organizations = organizations ?? await getUserOrganizations(refreshedTokens.accessToken, ctx);
2675
- const onlyOrg = organizations?.length === 1 ? organizations[0] : null;
2676
- targetOrgId = onlyOrg?.id ?? null;
2677
- targetOrgSlug = onlyOrg?.slug ?? null;
2678
- }
2679
- if (!targetOrgId) {
2680
- return { tokens: refreshedTokens, activeOrganization: null };
2681
- }
2682
- const scoped = await getOrgScopedTokens(refreshedTokens.accessToken, targetOrgId, ctx);
2683
- const scopedData = scoped?.data;
2684
- const accessToken = scopedData ? resolveOrgScopedAccessToken(scopedData) : null;
2685
- if (!scoped || scoped.status >= 400 || !scopedData || !accessToken) {
2686
- return { tokens: refreshedTokens, activeOrganization: null };
2687
- }
2688
- const payload = decodeJwtPayload(accessToken);
2689
- const resolvedOrg = {
2690
- id: payload?.org_id ?? targetOrgId,
2691
- slug: payload?.org_slug ?? targetOrgSlug
2692
- };
2693
- return {
2694
- tokens: {
2695
- ...refreshedTokens,
2696
- accessToken,
2697
- refreshToken: resolveOrgScopedRefreshToken(scopedData, refreshedTokens.refreshToken),
2698
- expiresIn: resolveOrgScopedTokenExpiresIn(scopedData),
2699
- tokenType: resolveOrgScopedTokenType(scopedData),
2700
- user: scopedData.user ?? refreshedTokens.user
2701
- },
2702
- activeOrganization: resolvedOrg
2703
- };
2704
- }
2705
- async function handleSwitchOrg(request, ctx) {
2706
- ctx.log("Switch org request");
2707
- if (request.method !== "POST") {
2708
- return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
2709
- }
2710
- const currentSessionToken = readRequestCookieValue(request, ctx.cookieNames.SESSION);
2711
- const verifyOpts = { secretKey: ctx.secretKey, platformUrl: ctx.platformUrl };
2712
- let sessionToken = await resolveVerifiedSessionToken(currentSessionToken, verifyOpts);
2713
- let restoredBaseSession = null;
2714
- if (!sessionToken) {
2715
- restoredBaseSession = await refreshSessionFromCookie(request, ctx, currentSessionToken);
2716
- sessionToken = restoredBaseSession ? await resolveVerifiedSessionToken(restoredBaseSession.tokens.accessToken, verifyOpts) : null;
2717
- if (!sessionToken) restoredBaseSession = null;
2718
- }
2719
- if (!sessionToken) {
2720
- const response = NextResponse2.json(
2721
- { error: "Not authenticated", accessToken: null },
2722
- { status: 401 }
2723
- );
2724
- if (currentSessionToken || hasRequestCookie(request, ctx.cookieNames.REFRESH)) {
2725
- clearAuthCookiesMiddleware(response, ctx.namespace);
2726
- }
2727
- return response;
2728
- }
2729
- let orgId = null;
2730
- let requestedOrgSlug = null;
2731
- try {
2732
- const body = await request.json();
2733
- orgId = typeof body.orgId === "string" && body.orgId.trim() ? body.orgId.trim() : null;
2734
- requestedOrgSlug = typeof body.orgSlug === "string" && body.orgSlug.trim() ? body.orgSlug.trim() : null;
2735
- } catch {
2736
- return NextResponse2.json({ error: "Invalid request body" }, { status: 400 });
2737
- }
2738
- if (!orgId) {
2739
- return NextResponse2.json({ error: "orgId is required" }, { status: 400 });
2740
- }
2741
- try {
2742
- const scoped = await getOrgScopedTokens(sessionToken, orgId, ctx);
2743
- const data = scoped?.data;
2744
- if (!scoped || scoped.status >= 400 || !data) {
2745
- return NextResponse2.json(
2746
- { error: data?.error || data?.message || "switch_org_failed" },
2747
- { status: scoped?.status ?? 502 }
2748
- );
2749
- }
2750
- const accessToken = resolveOrgScopedAccessToken(data);
2751
- if (!accessToken) {
2752
- return NextResponse2.json(
2753
- { error: data.error || data.message || "invalid_response" },
2754
- { status: 502 }
2755
- );
2756
- }
2757
- const verifiedSwitched = await resolveVerifiedSessionToken(accessToken, verifyOpts);
2758
- if (!verifiedSwitched) {
2759
- return NextResponse2.json({ error: "switch_org_token_verification_failed" }, { status: 502 });
2760
- }
2761
- const expiresIn = resolveOrgScopedTokenExpiresIn(data);
2762
- const expiresAt = Date.now() + expiresIn * 1e3;
2763
- const payload = decodeJwtPayload(verifiedSwitched);
2764
- const activeOrganization = {
2765
- id: payload?.org_id ?? orgId,
2766
- slug: payload?.org_slug ?? requestedOrgSlug
2767
- };
2768
- const response = NextResponse2.json({
2769
- success: true,
2770
- user: data.user ?? null,
2771
- organization: activeOrganization
2772
- });
2773
- if (restoredBaseSession) {
2774
- setAuthCookiesMiddleware(response, ctx.namespace, restoredBaseSession.tokens);
2775
- if (restoredBaseSession.activeOrganization) {
2776
- setActiveOrganizationCookies(response, ctx, restoredBaseSession.activeOrganization);
2777
- }
2778
- }
2779
- response.cookies.set(ctx.cookieNames.SESSION, verifiedSwitched, {
2780
- ...SECURE_COOKIE_OPTIONS,
2781
- maxAge: expiresIn
2782
- });
2783
- const existingUser = parseUserCookie2(readRequestCookieValue(request, ctx.cookieNames.USER));
2784
- const user = data.user ?? existingUser?.user;
2785
- if (user) {
2786
- response.cookies.set(
2787
- ctx.cookieNames.USER,
2788
- JSON.stringify({
2789
- user,
2790
- expiresAt
2791
- }),
2792
- {
2793
- ...USER_COOKIE_OPTIONS,
2794
- maxAge: expiresIn
2795
- }
2796
- );
2797
- }
2798
- setActiveOrganizationCookies(response, ctx, activeOrganization);
2799
- ctx.log("Switch org success", { orgId });
2800
- return response;
2801
- } catch (err) {
2802
- ctx.log("Switch org error", err);
2803
- return NextResponse2.json({ error: "internal_error" }, { status: 500 });
2804
- }
2805
- }
2806
- async function handleBaasProxy(request, ctx, sessionToken) {
2807
- const prefix = ctx.config.baasPrefix;
2808
- if (!prefix) return NextResponse2.json({ error: "Not found" }, { status: 404 });
2809
- const upstreamPath = stripRoutePrefix(request.nextUrl.pathname, prefix);
2810
- if (!upstreamPath || !isAllowedBaasProxyPath(upstreamPath)) {
2811
- return NextResponse2.json({ error: "Not found" }, { status: 404 });
2812
- }
2813
- if (isAuthenticatedBaasProxyPath(upstreamPath) && !sessionToken) {
2814
- return NextResponse2.json({ error: "Not authenticated" }, { status: 401 });
2815
- }
2816
- const upstreamUrl = new URL(`${ctx.platformUrl}/v1${upstreamPath}`);
2817
- upstreamUrl.search = request.nextUrl.search;
2818
- const method = request.method.toUpperCase();
2819
- const body = BODYLESS_METHODS.has(method) ? void 0 : await request.arrayBuffer();
2820
- const res = await fetch(upstreamUrl, {
2821
- method,
2822
- headers: buildUpstreamProxyHeaders(request, ctx, sessionToken),
2823
- body
2824
- });
2825
- return new NextResponse2(res.body, {
2826
- status: res.status,
2827
- headers: copyResponseHeaders(res.headers)
2828
- });
2829
- }
2830
- async function refreshTokens(refreshToken, ctx) {
2831
- ctx.log("Refreshing tokens");
2832
- try {
2833
- const res = await fetch(`${ctx.platformUrl}/v1/auth/token`, {
2834
- method: "POST",
2835
- headers: { "Content-Type": "application/json" },
2836
- body: JSON.stringify({
2837
- grant_type: "refresh_token",
2838
- refresh_token: refreshToken,
2839
- client_secret: ctx.secretKey
2840
- })
2841
- });
2842
- if (!res.ok) {
2843
- ctx.log("Refresh failed", res.status);
2844
- return null;
2845
- }
2846
- const data = await res.json();
2847
- if (!isTokenResponse(data)) {
2848
- ctx.log("Invalid refresh response");
2849
- return null;
2850
- }
2851
- ctx.log("Refresh success");
2852
- return data;
2853
- } catch (err) {
2854
- ctx.log("Refresh error", err);
2855
- return null;
2856
- }
2857
- }
2858
- function createSylphxMiddleware(userConfig = {}) {
2859
- let secretKey = null;
2860
- function resolveSecretKey() {
2861
- if (secretKey) return secretKey;
2862
- const rawSecretKey = resolveNextjsSecretKey({
2863
- explicitSecretKey: userConfig.secretKey,
2864
- explicitSecretUrl: userConfig.secretUrl
2865
- });
2866
- if (!rawSecretKey) {
2867
- throw new Error(
2868
- "[Sylphx] Server connection URL is required.\nEither pass secretUrl in config or set SYLPHX_SECRET_URL env var."
2869
- );
2870
- }
2871
- secretKey = validateAndSanitizeSecretKey(rawSecretKey);
2872
- return secretKey;
2873
- }
2874
- let publishableKey = null;
2875
- function resolvePublishableKey() {
2876
- if (publishableKey) return publishableKey;
2877
- const rawPublishableKey = resolveNextjsPublishableKey({
2878
- explicitPublishableKey: userConfig.publishableKey,
2879
- explicitPublicUrl: userConfig.publicUrl
2880
- });
2881
- if (!rawPublishableKey) {
2882
- throw new Error(
2883
- "[Sylphx] Publishable connection URL is required for public auth routes.\nEither pass publicUrl/publishableKey in config or set SYLPHX_URL/NEXT_PUBLIC_SYLPHX_URL."
2884
- );
2885
- }
2886
- publishableKey = validateAndSanitizePublicKey(rawPublishableKey);
2887
- return publishableKey;
2888
- }
2889
- let platformUrl;
2890
- let namespace;
2891
- let cookieNames;
2892
- function resolveConfig() {
2893
- const key = resolveSecretKey();
2894
- platformUrl = resolveNextjsPlatformUrl({
2895
- explicitPlatformUrl: userConfig.platformUrl,
2896
- secretKey: key,
2897
- secretUrl: userConfig.secretUrl
2898
- });
2899
- namespace = getCookieNamespace(key);
2900
- cookieNames = getCookieNames(namespace);
2901
- }
2902
- const config = {
2903
- publicRoutes: userConfig.publicRoutes ?? ["/"],
2904
- ignoredRoutes: userConfig.ignoredRoutes ?? [],
2905
- signInUrl: userConfig.signInUrl ?? "/login",
2906
- afterSignOutUrl: userConfig.afterSignOutUrl ?? "/",
2907
- afterSignInUrl: userConfig.afterSignInUrl ?? "/dashboard",
2908
- authPrefix: userConfig.authPrefix ?? "/auth",
2909
- baasPrefix: userConfig.baasPrefix === false ? null : normalizeRoutePrefix(userConfig.baasPrefix ?? DEFAULT_BAAS_PREFIX),
2910
- appUrl: normalizeAppUrl(userConfig.appUrl),
2911
- debug: userConfig.debug ?? false,
2912
- orgRequired: userConfig.orgRequired ?? false,
2913
- orgSelectionUrl: userConfig.orgSelectionUrl ?? "/select-organization",
2914
- organizationContext: {
2915
- enabled: userConfig.organizationContext?.enabled ?? true,
2916
- autoSelectSingleOrganization: userConfig.organizationContext?.autoSelectSingleOrganization ?? true,
2917
- additionalOrgIdCookies: userConfig.organizationContext?.additionalOrgIdCookies ?? [],
2918
- additionalOrgSlugCookies: userConfig.organizationContext?.additionalOrgSlugCookies ?? []
2919
- },
2920
- onResponse: userConfig.onResponse
2921
- };
2922
- const publicRoutes = [
2923
- ...config.publicRoutes,
2924
- config.signInUrl,
2925
- "/signup",
2926
- `${config.authPrefix}/*`,
2927
- ...config.baasPrefix ? [`${config.baasPrefix}/*`] : []
2928
- ];
2929
- const log = (msg, data) => {
2930
- if (config.debug) {
2931
- }
2932
- };
2933
- const ctx = {
2934
- get secretKey() {
2935
- return secretKey;
2936
- },
2937
- get publishableKey() {
2938
- return resolvePublishableKey();
2939
- },
2940
- get platformUrl() {
2941
- return platformUrl;
2942
- },
2943
- get namespace() {
2944
- return namespace;
2945
- },
2946
- get cookieNames() {
2947
- return cookieNames;
2948
- },
2949
- config,
2950
- log
2951
- };
2952
- return async function middleware(request) {
2953
- resolveConfig();
2954
- const { pathname } = request.nextUrl;
2955
- log(`${request.method} ${pathname}`);
2956
- if (matchesAny(pathname, config.ignoredRoutes)) {
2957
- log("Ignored route");
2958
- return NextResponse2.next();
2959
- }
2960
- if (pathname.includes(".") || pathname.startsWith("/_next")) {
2961
- return NextResponse2.next();
2962
- }
2963
- if (pathname === `${config.authPrefix}/register`) {
2964
- return handleRegister(request, ctx);
2965
- }
2966
- if (pathname === `${config.authPrefix}/callback`) {
2967
- return handleCallback(request, ctx);
2968
- }
2969
- if (pathname === `${config.authPrefix}/login`) {
2970
- return handleLogin(request, ctx);
2971
- }
2972
- if (pathname === `${config.authPrefix}/verify-email`) {
2973
- return handleVerifyEmail(request, ctx);
2974
- }
2975
- if (pathname === `${config.authPrefix}/oauth-providers`) {
2976
- return handleOAuthProviders(ctx);
2977
- }
2978
- if (pathname === `${config.authPrefix}/oauth/authorize`) {
2979
- return handleOAuthAuthorize(request, ctx);
2980
- }
2981
- if (pathname === `${config.authPrefix}/passkey/options`) {
2982
- return handlePasskeyOptions(request, ctx);
2983
- }
2984
- if (pathname === `${config.authPrefix}/passkey/authenticate`) {
2985
- return handlePasskeyAuthenticate(request, ctx);
2986
- }
2987
- if (pathname === `${config.authPrefix}/verify-2fa`) {
2988
- return handleVerifyTwoFactor(request, ctx);
2989
- }
2990
- if (pathname === `${config.authPrefix}/forgot-password`) {
2991
- return handleForgotPassword(request, ctx);
2992
- }
2993
- if (pathname === `${config.authPrefix}/reset-password`) {
2994
- return handleResetPassword(request, ctx);
2995
- }
2996
- if (pathname === `${config.authPrefix}/session`) {
2997
- return handleSession(request, ctx);
2998
- }
2999
- if (pathname === `${config.authPrefix}/signout`) {
3000
- return handleSignOut(request, ctx);
3001
- }
3002
- if (pathname === `${config.authPrefix}/token`) {
3003
- return handleToken(request, ctx);
3004
- }
3005
- if (pathname === `${config.authPrefix}/switch-org`) {
3006
- return handleSwitchOrg(request, ctx);
3007
- }
3008
- const sessionToken = readRequestCookieValue(request, cookieNames.SESSION);
3009
- const refreshToken = readRequestCookieValue(request, cookieNames.REFRESH);
3010
- const verifyOpts = { secretKey: ctx.secretKey, platformUrl: ctx.platformUrl };
3011
- const response = NextResponse2.next({ request: { headers: request.headers } });
3012
- let activeSessionToken = await resolveVerifiedSessionToken(sessionToken, verifyOpts);
3013
- let isAuthenticated = activeSessionToken !== null && middlewareMayTreatAsAuthenticated({
3014
- sessionTokenPresent: true,
3015
- tokenCryptographicallyVerified: true
3016
- });
3017
- if (!isAuthenticated && refreshToken) {
3018
- log("Session missing/invalid, refreshing");
3019
- const tokens = await refreshTokens(refreshToken, ctx);
3020
- if (tokens) {
3021
- const restored = await restoreOrganizationScopeAfterRefresh(
3022
- request,
3023
- ctx,
3024
- tokens,
3025
- sessionToken
3026
- );
3027
- setAuthCookiesMiddleware(response, namespace, restored.tokens);
3028
- if (restored.activeOrganization) {
3029
- setActiveOrganizationCookies(response, ctx, restored.activeOrganization);
3030
- }
3031
- activeSessionToken = await resolveVerifiedSessionToken(
3032
- restored.tokens.accessToken,
3033
- verifyOpts
3034
- );
3035
- if (activeSessionToken) {
3036
- isAuthenticated = true;
3037
- } else {
3038
- clearAuthCookiesMiddleware(response, namespace);
3039
- isAuthenticated = false;
3040
- }
3041
- } else {
3042
- clearAuthCookiesMiddleware(response, namespace);
3043
- isAuthenticated = false;
3044
- activeSessionToken = null;
3045
- }
3046
- }
3047
- if (config.baasPrefix && stripRoutePrefix(pathname, config.baasPrefix)) {
3048
- return handleBaasProxy(request, ctx, activeSessionToken);
3049
- }
3050
- const isPublic = matchesAny(pathname, publicRoutes);
3051
- if (!isPublic && !isAuthenticated) {
3052
- log("Redirecting to sign-in");
3053
- const url = new URL(config.signInUrl, request.url);
3054
- url.searchParams.set("callbackUrl", requestPathWithSearch(request));
3055
- return NextResponse2.redirect(url);
3056
- }
3057
- if (isAuthenticated && pathname === config.signInUrl) {
3058
- const callbackUrl = resolveSafeRelativeRedirectPath(
3059
- request.nextUrl.searchParams.get("callbackUrl"),
3060
- config.afterSignInUrl
3061
- );
3062
- log("Redirecting from sign-in", { callbackUrl });
3063
- return NextResponse2.redirect(new URL(callbackUrl, request.url));
3064
- }
3065
- if (config.orgRequired && !isPublic && isAuthenticated && activeSessionToken && !matchesPattern(pathname, config.orgSelectionUrl)) {
3066
- const payload = decodeJwtPayload(activeSessionToken);
3067
- if (!payload?.org_id) {
3068
- log("Redirecting to organization selection");
3069
- const url = new URL(config.orgSelectionUrl, request.url);
3070
- url.searchParams.set("redirect_to", requestPathWithSearch(request));
3071
- return NextResponse2.redirect(url);
3072
- }
3073
- }
3074
- if (config.onResponse) {
3075
- await config.onResponse(response, request);
3076
- }
3077
- return response;
3078
- };
3079
- }
3080
- var sylphxMiddleware = createSylphxMiddleware;
3081
- function createMatcher() {
3082
- return {
3083
- matcher: ["/((?!_next|monitoring|.*\\..*).*)", "/"]
3084
- };
3085
- }
3086
- function getNamespace(secretKey) {
3087
- return getCookieNamespace(validateAndSanitizeSecretKey(secretKey));
3088
- }
3089
-
3090
- // src/nextjs/server.ts
3091
- import { cache as cache2 } from "react";
3092
- function isTokenResponse2(data) {
3093
- return typeof data === "object" && data !== null && "accessToken" in data && "refreshToken" in data && "user" in data && typeof data.accessToken === "string" && typeof data.refreshToken === "string";
3094
- }
3095
- var serverConfig = null;
3096
- function configureServer(config) {
3097
- const rawSecretKey = resolveNextjsSecretKey({
3098
- explicitSecretKey: config.secretKey,
3099
- explicitSecretUrl: config.secretUrl
3100
- });
3101
- if (!rawSecretKey) {
3102
- throw new Error(
3103
- "[Sylphx] Server credential is required. Set SYLPHX_SECRET_URL or pass secretUrl/secretKey to configureServer()."
3104
- );
3105
- }
3106
- const secretKey = validateAndSanitizeSecretKey(rawSecretKey);
3107
- const platformUrl = resolveNextjsPlatformUrl({
3108
- explicitPlatformUrl: config.platformUrl,
3109
- secretKey,
3110
- secretUrl: config.secretUrl
3111
- });
3112
- serverConfig = {
3113
- secretKey,
3114
- platformUrl,
3115
- audience: resolveNextjsTokenAudience({
3116
- explicitAudience: config.audience,
3117
- platformUrl,
3118
- secretKey
3119
- }),
3120
- issuer: config.issuer?.trim() || DEFAULT_JWT_ISSUER
3121
- };
3122
- }
3123
- function getConfig() {
3124
- if (serverConfig) {
3125
- return serverConfig;
3126
- }
3127
- const rawSecretKey = resolveNextjsSecretKey({});
3128
- if (!rawSecretKey) {
3129
- return null;
3130
- }
3131
- try {
3132
- const secretKey = validateAndSanitizeSecretKey(rawSecretKey);
3133
- const platformUrl = resolveNextjsPlatformUrl({ secretKey });
3134
- const audience = resolveNextjsTokenAudience({ platformUrl, secretKey });
3135
- serverConfig = {
3136
- secretKey,
3137
- platformUrl,
3138
- audience,
3139
- issuer: DEFAULT_JWT_ISSUER
3140
- };
3141
- return serverConfig;
3142
- } catch (error) {
3143
- console.warn("[Sylphx] Invalid @sylphx/sdk/nextjs server configuration:", error);
3144
- return null;
3145
- }
3146
- }
3147
- function getCookieNamespace2() {
3148
- const config = getConfig();
3149
- if (!config) return "sylphx";
3150
- return getCookieNamespace(config.secretKey);
3151
- }
3152
- var auth = cache2(async () => {
3153
- const config = getConfig();
3154
- if (!config) {
3155
- return { userId: null, user: null, sessionToken: null };
3156
- }
3157
- const namespace = getCookieNamespace2();
3158
- const { sessionToken, refreshToken, user, expiresAt } = await getAuthCookies(namespace);
3159
- if (!sessionToken) {
3160
- const hydration = resolveHydrationCookieAuthority({
3161
- hydrationUserId: user?.id ?? null,
3162
- hydrationExpiresAt: expiresAt,
3163
- hasRefreshToken: Boolean(refreshToken)
3164
- });
3165
- void hydration;
3166
- return { userId: null, user: null, sessionToken: null };
3167
- }
3168
- try {
3169
- const payload = await verifyAccessToken(sessionToken, {
3170
- issuer: config.issuer,
3171
- audience: config.audience,
3172
- // platformUrl is routing only — never issuer/JWKS
3173
- platformUrl: config.platformUrl,
3174
- secretKey: config.secretKey
3175
- });
3176
- const resolvedUserId = payload.pid ?? payload.sub;
3177
- const decision = resolveSessionAuthority({
3178
- sessionTokenPresent: true,
3179
- tokenCryptographicallyVerified: true,
3180
- verifiedUserId: resolvedUserId
3181
- });
3182
- if (!decision.authenticated) {
3183
- return { userId: null, user: null, sessionToken: null };
3184
- }
3185
- return {
3186
- userId: decision.userId,
3187
- user: user ? { ...user, id: decision.userId } : {
3188
- id: decision.userId,
3189
- email: payload.email,
3190
- name: payload.name || null,
3191
- image: payload.picture || null,
3192
- emailVerified: payload.email_verified
3193
- },
3194
- sessionToken
3195
- };
3196
- } catch {
3197
- void resolveHydrationCookieAuthority({
3198
- hydrationUserId: user?.id ?? null,
3199
- hydrationExpiresAt: expiresAt,
3200
- hasRefreshToken: Boolean(refreshToken)
3201
- });
3202
- return { userId: null, user: null, sessionToken: null };
3203
- }
3204
- });
3205
- async function currentUser() {
3206
- const { user } = await auth();
3207
- return user;
3208
- }
3209
- async function currentUserId() {
3210
- const { userId } = await auth();
3211
- return userId;
3212
- }
3213
- async function handleCallback2(code) {
3214
- const config = getConfig();
3215
- if (!config) {
3216
- throw new Error("Sylphx SDK not configured. Set SYLPHX_SECRET_URL environment variable.");
3217
- }
3218
- const response = await fetch(`${config.platformUrl}/v1/auth/token`, {
3219
- method: "POST",
3220
- headers: { "Content-Type": "application/json" },
3221
- body: JSON.stringify({
3222
- grant_type: "authorization_code",
3223
- code,
3224
- client_secret: config.secretKey
3225
- })
3226
- });
3227
- if (!response.ok) {
3228
- const errorData = await response.json().catch(() => ({ error: "Token exchange failed" }));
3229
- throw new Error(errorData.error || "Token exchange failed");
3230
- }
3231
- const data = await response.json();
3232
- if (!isTokenResponse2(data)) {
3233
- throw new Error("Invalid token response format");
3234
- }
3235
- const namespace = getCookieNamespace2();
3236
- await setAuthCookies(namespace, data);
3237
- return data.user;
3238
- }
3239
- async function signOut() {
3240
- const config = getConfig();
3241
- if (!config) {
3242
- return;
3243
- }
3244
- const namespace = getCookieNamespace2();
3245
- const { refreshToken } = await getAuthCookies(namespace);
3246
- if (refreshToken) {
3247
- try {
3248
- await fetch(`${config.platformUrl}/v1/auth/revoke`, {
3249
- method: "POST",
3250
- headers: { "Content-Type": "application/json" },
3251
- body: JSON.stringify({
3252
- token: refreshToken,
3253
- client_secret: config.secretKey
3254
- })
3255
- });
3256
- } catch {
3257
- }
3258
- }
3259
- await clearAuthCookies(namespace);
3260
- }
3261
- async function syncAuthToCookies(tokens) {
3262
- "use server";
3263
- const namespace = getCookieNamespace2();
3264
- await setAuthCookies(namespace, tokens);
3265
- }
3266
- function getAuthorizationUrl(options) {
3267
- const config = getConfig();
3268
- if (!config) {
3269
- throw new Error("Sylphx SDK not configured. Set SYLPHX_SECRET_URL environment variable.");
3270
- }
3271
- const rawClientId = options?.appId || process.env.NEXT_PUBLIC_SYLPHX_APP_ID;
3272
- if (!rawClientId) {
3273
- throw new Error("App ID is required for authorization URL. Set NEXT_PUBLIC_SYLPHX_APP_ID.");
3274
- }
3275
- const clientId = validateAndSanitizeAppId(rawClientId);
3276
- const params = new URLSearchParams({
3277
- client_id: clientId,
3278
- redirect_uri: options?.redirectUri || "/",
3279
- response_type: "code"
3280
- });
3281
- if (options?.mode === "signup") {
3282
- params.set("mode", "signup");
3283
- }
3284
- if (options?.state) {
3285
- params.set("state", options.state);
3286
- }
3287
- return `${config.platformUrl}/auth/authorize?${params}`;
3288
- }
3289
- async function getSessionToken() {
3290
- const { sessionToken } = await auth();
3291
- return sessionToken;
3292
- }
3293
- export {
3294
- ACTIVE_ORG_COOKIE_OPTIONS,
3295
- ACTIVE_ORG_LIFETIME,
3296
- REFRESH_TOKEN_LIFETIME,
3297
- SECURE_COOKIE_OPTIONS,
3298
- SESSION_TOKEN_LIFETIME,
3299
- SESSION_TOKEN_LIFETIME_MS,
3300
- TOKEN_EXPIRY_BUFFER_MS,
3301
- USER_COOKIE_OPTIONS,
3302
- auth,
3303
- clearAuthCookies,
3304
- clearAuthCookiesMiddleware,
3305
- configureServer,
3306
- createMatcher,
3307
- createSylphxMiddleware,
3308
- currentUser,
3309
- currentUserId,
3310
- decodeCookieValue,
3311
- decodeUserId,
3312
- encodeUserId,
3313
- getAuthCookies,
3314
- getAuthorizationUrl,
3315
- getCookieNames,
3316
- getNamespace,
3317
- getSessionToken,
3318
- handleCallback2 as handleCallback,
3319
- hasRefreshToken,
3320
- isSessionExpired,
3321
- parseUserCookie,
3322
- readCookieValueFromHeader,
3323
- setAuthCookies,
3324
- setAuthCookiesMiddleware,
3325
- signOut,
3326
- sylphxMiddleware,
3327
- syncAuthToCookies
3328
- };
3329
- //# sourceMappingURL=index.mjs.map