@sylphx/sdk 0.21.1 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/health/index.d.ts +4 -1
- package/dist/health/index.mjs +1 -0
- package/dist/health/index.mjs.map +1 -1
- package/dist/index.d.ts +86 -96
- package/dist/index.mjs +329 -208
- package/dist/index.mjs.map +1 -1
- package/dist/nextjs/index.d.ts +4 -0
- package/dist/nextjs/index.mjs +2415 -2181
- package/dist/nextjs/index.mjs.map +1 -1
- package/dist/react/index.d.ts +40 -66
- package/dist/react/index.mjs +117 -144
- package/dist/react/index.mjs.map +1 -1
- package/dist/server/index.d.ts +51 -40
- package/dist/server/index.mjs +31 -8
- package/dist/server/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/nextjs/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/nextjs/middleware.ts
|
|
2
|
-
import { NextResponse } from "next/server";
|
|
2
|
+
import { NextResponse as NextResponse2 } from "next/server";
|
|
3
3
|
|
|
4
4
|
// src/key-validation.ts
|
|
5
5
|
var PUBLIC_KEY_PATTERN = /^pk_(dev|stg|prod|prev)(?:_[a-z0-9]{12})?_[a-f0-9]{32}$/;
|
|
@@ -155,6 +155,35 @@ function getCookieNamespace(secretKey) {
|
|
|
155
155
|
return `sylphx_${shortEnv}`;
|
|
156
156
|
}
|
|
157
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
|
+
|
|
158
187
|
// src/nextjs/cookies.ts
|
|
159
188
|
import { cookies } from "next/headers";
|
|
160
189
|
|
|
@@ -164,6 +193,7 @@ var ENV_PUBLIC_URL = "NEXT_PUBLIC_SYLPHX_URL";
|
|
|
164
193
|
var ENV_SECRET_URL = "SYLPHX_SECRET_URL";
|
|
165
194
|
var SDK_API_PATH = `/v1`;
|
|
166
195
|
var DEFAULT_SDK_API_HOST = "api.sylphx.com";
|
|
196
|
+
var DEFAULT_PLATFORM_URL = "https://sylphx.com";
|
|
167
197
|
function detectSdkPlatform() {
|
|
168
198
|
if (typeof window !== "undefined") return "browser";
|
|
169
199
|
const runtimeGlobal = globalThis;
|
|
@@ -352,7 +382,19 @@ function parseUserCookie(value) {
|
|
|
352
382
|
var OAUTH_PKCE_TTL_SECONDS = 10 * 60;
|
|
353
383
|
var OAUTH_PKCE_TTL_MS = OAUTH_PKCE_TTL_SECONDS * 1e3;
|
|
354
384
|
var DEFAULT_BAAS_PREFIX = "/sylphx";
|
|
355
|
-
var BAAS_PROXY_AUTH_REQUIRED_PATHS = [
|
|
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
|
+
];
|
|
356
398
|
var BAAS_PROXY_PUBLIC_PATHS = ["/app"];
|
|
357
399
|
var BODYLESS_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
358
400
|
var RESPONSE_HEADER_ALLOWLIST = [
|
|
@@ -380,11 +422,6 @@ function decodeJwtPayload(token) {
|
|
|
380
422
|
return null;
|
|
381
423
|
}
|
|
382
424
|
}
|
|
383
|
-
function isTokenExpired(token) {
|
|
384
|
-
const payload = decodeJwtPayload(token);
|
|
385
|
-
if (!payload?.exp) return true;
|
|
386
|
-
return payload.exp * 1e3 < Date.now() + TOKEN_EXPIRY_BUFFER_MS;
|
|
387
|
-
}
|
|
388
425
|
function matchesPattern(pathname, pattern) {
|
|
389
426
|
if (pattern === pathname) return true;
|
|
390
427
|
if (pattern.endsWith("/*")) {
|
|
@@ -505,2382 +542,2553 @@ async function parseJsonObject(request) {
|
|
|
505
542
|
}
|
|
506
543
|
}
|
|
507
544
|
|
|
508
|
-
// src/
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
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-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;
|
|
520
566
|
}
|
|
521
|
-
|
|
522
|
-
function fail(reason) {
|
|
523
|
-
throw new InvalidConnectionUrlError(`Invalid Sylphx connection URL: ${reason}`);
|
|
567
|
+
return buf;
|
|
524
568
|
}
|
|
525
|
-
function
|
|
526
|
-
const
|
|
527
|
-
|
|
528
|
-
|
|
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;
|
|
529
577
|
}
|
|
530
|
-
return
|
|
531
|
-
credentialType: match[1],
|
|
532
|
-
env: match[2]
|
|
533
|
-
};
|
|
578
|
+
return bytes;
|
|
534
579
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
580
|
+
|
|
581
|
+
// ../../../../.bun-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);
|
|
538
585
|
}
|
|
539
|
-
|
|
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;
|
|
540
592
|
}
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
593
|
+
|
|
594
|
+
// ../../../../.bun-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
|
+
});
|
|
544
600
|
}
|
|
545
|
-
let
|
|
601
|
+
let encoded = input;
|
|
602
|
+
if (encoded instanceof Uint8Array) {
|
|
603
|
+
encoded = decoder.decode(encoded);
|
|
604
|
+
}
|
|
605
|
+
encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
|
|
546
606
|
try {
|
|
547
|
-
|
|
607
|
+
return decodeBase64(encoded);
|
|
548
608
|
} catch {
|
|
549
|
-
|
|
550
|
-
}
|
|
551
|
-
if (parsed.protocol !== SYLPHX_PROTOCOL) {
|
|
552
|
-
fail(`protocol must be "sylphx:", got "${parsed.protocol}"`);
|
|
553
|
-
}
|
|
554
|
-
const credential = decodeURIComponent(parsed.username);
|
|
555
|
-
if (!credential) {
|
|
556
|
-
fail("missing credential (expected `sylphx://<credential>@<host>`)");
|
|
557
|
-
}
|
|
558
|
-
if (parsed.password) {
|
|
559
|
-
fail("connection URL must not contain a password component");
|
|
560
|
-
}
|
|
561
|
-
const { credentialType, env } = parseCredential(credential);
|
|
562
|
-
const host = parsed.host;
|
|
563
|
-
if (!host) {
|
|
564
|
-
fail("missing host");
|
|
565
|
-
}
|
|
566
|
-
const hostname = parsed.hostname;
|
|
567
|
-
const firstDot = hostname.indexOf(".");
|
|
568
|
-
if (firstDot <= 0) {
|
|
569
|
-
fail(`host "${hostname}" must contain at least one dot (slug.domain)`);
|
|
609
|
+
throw new TypeError("The input to be decoded is not correctly encoded.");
|
|
570
610
|
}
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// ../../../../.bun-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);
|
|
575
621
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
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;
|
|
584
634
|
}
|
|
585
|
-
|
|
586
|
-
|
|
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;
|
|
587
647
|
}
|
|
588
|
-
|
|
589
|
-
|
|
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);
|
|
590
670
|
}
|
|
591
|
-
const apiBaseUrl = `https://${host}/${version}`;
|
|
592
|
-
return {
|
|
593
|
-
credential,
|
|
594
|
-
credentialType,
|
|
595
|
-
env,
|
|
596
|
-
slug,
|
|
597
|
-
host,
|
|
598
|
-
apiBaseUrl
|
|
599
|
-
};
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
// src/nextjs/runtime-config.ts
|
|
603
|
-
var SylphxRoutingConfigurationError = class extends Error {
|
|
604
|
-
name = "SylphxRoutingConfigurationError";
|
|
605
671
|
};
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
function
|
|
611
|
-
|
|
612
|
-
return parseConnectionUrl(value.trim());
|
|
613
|
-
}
|
|
614
|
-
function platformUrlFromConnectionUrl(value) {
|
|
615
|
-
const parsed = parseConnection(value);
|
|
616
|
-
return parsed ? `https://${parsed.host}` : null;
|
|
617
|
-
}
|
|
618
|
-
function secretKeyFromConnectionUrl(value) {
|
|
619
|
-
const parsed = parseConnection(value);
|
|
620
|
-
if (!parsed || parsed.credentialType !== "sk") return null;
|
|
621
|
-
return parsed.credential;
|
|
672
|
+
|
|
673
|
+
// ../../../../.bun-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);
|
|
622
678
|
}
|
|
623
|
-
function
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
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
|
+
}
|
|
627
690
|
}
|
|
628
|
-
function
|
|
629
|
-
if (
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
const fromSecretUrl = platformUrlFromConnectionUrl(process.env[ENV_SECRET_URL]);
|
|
633
|
-
if (fromSecretUrl) return fromSecretUrl;
|
|
634
|
-
const fromConnectionUrl = platformUrlFromConnectionUrl(process.env[ENV_URL]);
|
|
635
|
-
if (fromConnectionUrl) return fromConnectionUrl;
|
|
636
|
-
const fromBaasOverride = process.env.SYLPHX_BAAS_URL ?? process.env.SYLPHX_RUNTIME_URL;
|
|
637
|
-
if (fromBaasOverride) return normalizePlatformUrl(fromBaasOverride);
|
|
638
|
-
throw new SylphxRoutingConfigurationError(
|
|
639
|
-
'[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.'
|
|
640
|
-
);
|
|
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
|
+
}
|
|
641
695
|
}
|
|
642
|
-
function
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
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);
|
|
661
759
|
}
|
|
662
760
|
|
|
663
|
-
//
|
|
664
|
-
function
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
761
|
+
// ../../../../.bun-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;
|
|
669
782
|
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
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-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;
|
|
673
790
|
try {
|
|
674
|
-
|
|
675
|
-
if (typeof parsed.verifier !== "string" || parsed.verifier.length < 43) return null;
|
|
676
|
-
if (typeof parsed.createdAt !== "number") return null;
|
|
677
|
-
if (Date.now() - parsed.createdAt > OAUTH_PKCE_TTL_MS) return null;
|
|
678
|
-
return parsed.verifier;
|
|
791
|
+
return key instanceof CryptoKey;
|
|
679
792
|
} catch {
|
|
680
|
-
return
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
function setOAuthPkceCookie(response, ctx, value) {
|
|
684
|
-
response.cookies.set(getOAuthPkceCookieName(ctx), encodeOAuthPkceCookie(value), {
|
|
685
|
-
...SECURE_COOKIE_OPTIONS,
|
|
686
|
-
maxAge: OAUTH_PKCE_TTL_SECONDS,
|
|
687
|
-
path: ctx.config.authPrefix
|
|
688
|
-
});
|
|
689
|
-
}
|
|
690
|
-
function clearOAuthPkceCookie(response, ctx) {
|
|
691
|
-
response.cookies.set(getOAuthPkceCookieName(ctx), "", {
|
|
692
|
-
...SECURE_COOKIE_OPTIONS,
|
|
693
|
-
maxAge: 0,
|
|
694
|
-
path: ctx.config.authPrefix
|
|
695
|
-
});
|
|
696
|
-
}
|
|
697
|
-
function readRequestCookieValue(request, name) {
|
|
698
|
-
const values = request.cookies.getAll(name);
|
|
699
|
-
if (values.length > 0) {
|
|
700
|
-
const value = values[values.length - 1]?.value;
|
|
701
|
-
return value === void 0 ? void 0 : decodeCookieValue(value);
|
|
793
|
+
return false;
|
|
702
794
|
}
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
}
|
|
713
|
-
function isOAuthAuthorizeResponse(data) {
|
|
714
|
-
return typeof data === "object" && data !== null && typeof data.authorization_url === "string";
|
|
715
|
-
}
|
|
716
|
-
function authCookieJsonResponse(ctx, data) {
|
|
717
|
-
const response = NextResponse.json({ success: true, user: data.user });
|
|
718
|
-
setAuthCookiesMiddleware(response, ctx.namespace, data);
|
|
719
|
-
return response;
|
|
720
|
-
}
|
|
721
|
-
function sessionMetadataBody(sessionToken, user) {
|
|
722
|
-
const payload = decodeJwtPayload(sessionToken);
|
|
723
|
-
const userId = payload?.sub ?? user.id;
|
|
724
|
-
const expiresAt = typeof payload?.exp === "number" ? new Date(payload.exp * 1e3).toISOString() : new Date(Date.now() + SESSION_TOKEN_LIFETIME * 1e3).toISOString();
|
|
725
|
-
return {
|
|
726
|
-
success: true,
|
|
727
|
-
session: {
|
|
728
|
-
id: `platform:${userId}`,
|
|
729
|
-
userId,
|
|
730
|
-
expiresAt
|
|
731
|
-
},
|
|
732
|
-
user
|
|
733
|
-
};
|
|
734
|
-
}
|
|
735
|
-
function setRestoredSessionCookies(response, ctx, restored) {
|
|
736
|
-
setAuthCookiesMiddleware(response, ctx.namespace, restored.tokens);
|
|
737
|
-
if (restored.activeOrganization) {
|
|
738
|
-
setActiveOrganizationCookies(response, ctx, restored.activeOrganization);
|
|
795
|
+
};
|
|
796
|
+
var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
|
|
797
|
+
var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
|
|
798
|
+
|
|
799
|
+
// ../../../../.bun-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;
|
|
739
804
|
}
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
}
|
|
754
|
-
async function handleRegister(request, ctx) {
|
|
755
|
-
if (request.method !== "POST") {
|
|
756
|
-
return NextResponse.json({ error: "Method not allowed" }, { status: 405 });
|
|
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
|
+
}
|
|
757
818
|
}
|
|
758
|
-
|
|
759
|
-
const res = await fetch(`${ctx.platformUrl}/v1/auth/register`, {
|
|
760
|
-
method: "POST",
|
|
761
|
-
headers: headersForProjectAuth(ctx),
|
|
762
|
-
body: JSON.stringify(body ?? {})
|
|
763
|
-
});
|
|
764
|
-
const data = await res.json().catch(() => ({}));
|
|
765
|
-
return NextResponse.json(data, { status: res.status });
|
|
819
|
+
return true;
|
|
766
820
|
}
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
const password = typeof body?.password === "string" ? body.password : null;
|
|
774
|
-
if (!email || !password) {
|
|
775
|
-
return NextResponse.json({ error: "email and password are required" }, { status: 400 });
|
|
776
|
-
}
|
|
777
|
-
const res = await fetch(`${ctx.platformUrl}/v1/auth/login`, {
|
|
778
|
-
method: "POST",
|
|
779
|
-
headers: headersForProjectAuth(ctx),
|
|
780
|
-
body: JSON.stringify({ email, password })
|
|
781
|
-
});
|
|
782
|
-
const data = await res.json().catch(() => ({}));
|
|
783
|
-
if (!res.ok) {
|
|
784
|
-
return NextResponse.json(data, { status: res.status });
|
|
821
|
+
|
|
822
|
+
// ../../../../.bun-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;
|
|
785
827
|
}
|
|
786
|
-
if (
|
|
787
|
-
return
|
|
828
|
+
if (Object.getPrototypeOf(input) === null) {
|
|
829
|
+
return true;
|
|
788
830
|
}
|
|
789
|
-
|
|
790
|
-
|
|
831
|
+
let proto = input;
|
|
832
|
+
while (Object.getPrototypeOf(proto) !== null) {
|
|
833
|
+
proto = Object.getPrototypeOf(proto);
|
|
791
834
|
}
|
|
792
|
-
return
|
|
835
|
+
return Object.getPrototypeOf(input) === proto;
|
|
793
836
|
}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
837
|
+
|
|
838
|
+
// ../../../../.bun-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
|
+
}
|
|
797
845
|
}
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// ../../../../.bun-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');
|
|
802
942
|
}
|
|
803
|
-
|
|
804
|
-
method: "POST",
|
|
805
|
-
headers: headersForProjectAuth(ctx),
|
|
806
|
-
body: JSON.stringify({ token })
|
|
807
|
-
});
|
|
808
|
-
const data = await res.json().catch(() => ({}));
|
|
809
|
-
return NextResponse.json(data, { status: res.status });
|
|
943
|
+
return { algorithm, keyUsages };
|
|
810
944
|
}
|
|
811
|
-
async function
|
|
812
|
-
if (
|
|
813
|
-
|
|
945
|
+
async function jwkToKey(jwk) {
|
|
946
|
+
if (!jwk.alg) {
|
|
947
|
+
throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
|
|
814
948
|
}
|
|
815
|
-
const
|
|
816
|
-
const
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
return NextResponse.json({ error: "userId and code are required" }, { status: 400 });
|
|
949
|
+
const { algorithm, keyUsages } = subtleMapping(jwk);
|
|
950
|
+
const keyData = { ...jwk };
|
|
951
|
+
if (keyData.kty !== "AKP") {
|
|
952
|
+
delete keyData.alg;
|
|
820
953
|
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
if (!
|
|
828
|
-
|
|
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-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");
|
|
829
962
|
}
|
|
830
|
-
|
|
831
|
-
|
|
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');
|
|
832
991
|
}
|
|
833
|
-
return authCookieJsonResponse(ctx, data);
|
|
834
992
|
}
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
993
|
+
|
|
994
|
+
// ../../../../.bun-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');
|
|
838
998
|
}
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
if (sessionToken && !isTokenExpired(sessionToken) && userCookie?.user) {
|
|
842
|
-
return NextResponse.json(sessionMetadataBody(sessionToken, userCookie.user));
|
|
999
|
+
if (!protectedHeader || protectedHeader.crit === void 0) {
|
|
1000
|
+
return /* @__PURE__ */ new Set();
|
|
843
1001
|
}
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
const response2 = NextResponse.json(
|
|
847
|
-
sessionMetadataBody(restored.tokens.accessToken, restored.tokens.user)
|
|
848
|
-
);
|
|
849
|
-
setRestoredSessionCookies(response2, ctx, restored);
|
|
850
|
-
return response2;
|
|
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');
|
|
851
1004
|
}
|
|
852
|
-
|
|
853
|
-
if (
|
|
854
|
-
|
|
1005
|
+
let recognized;
|
|
1006
|
+
if (recognizedOption !== void 0) {
|
|
1007
|
+
recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
|
|
1008
|
+
} else {
|
|
1009
|
+
recognized = recognizedDefault;
|
|
855
1010
|
}
|
|
856
|
-
|
|
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);
|
|
857
1023
|
}
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
1024
|
+
|
|
1025
|
+
// ../../../../.bun-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);
|
|
865
1034
|
}
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
1035
|
+
|
|
1036
|
+
// ../../../../.bun-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-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];
|
|
869
1049
|
}
|
|
870
|
-
const
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
if (!
|
|
874
|
-
|
|
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;
|
|
875
1057
|
}
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
method: "POST",
|
|
884
|
-
headers: headersForProjectAuth(ctx),
|
|
885
|
-
body: JSON.stringify({
|
|
886
|
-
provider,
|
|
887
|
-
redirect_uri: redirectUri.toString(),
|
|
888
|
-
code_challenge: challenge,
|
|
889
|
-
code_challenge_method: "S256",
|
|
890
|
-
...scopes && scopes.length > 0 ? { scopes } : {}
|
|
891
|
-
})
|
|
892
|
-
});
|
|
893
|
-
const data = await res.json().catch(() => ({}));
|
|
894
|
-
if (!res.ok || !isOAuthAuthorizeResponse(data)) {
|
|
895
|
-
return NextResponse.json(res.ok ? { error: "invalid_response" } : data, {
|
|
896
|
-
status: res.ok ? 502 : res.status
|
|
897
|
-
});
|
|
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];
|
|
898
1065
|
}
|
|
899
|
-
const
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
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"]);
|
|
909
1080
|
}
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
return NextResponse.json(data, { status: res.status });
|
|
918
|
-
}
|
|
919
|
-
async function handlePasskeyAuthenticate(request, ctx) {
|
|
920
|
-
if (request.method !== "POST") {
|
|
921
|
-
return NextResponse.json({ error: "Method not allowed" }, { status: 405 });
|
|
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
|
+
]);
|
|
922
1088
|
}
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
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
|
+
}
|
|
932
1100
|
}
|
|
933
|
-
if (
|
|
934
|
-
|
|
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"]);
|
|
935
1135
|
}
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
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
|
+
}
|
|
941
1170
|
}
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
const rawRedirect = typeof body?.redirectUrl === "string" ? body.redirectUrl : typeof body?.redirectTo === "string" ? body.redirectTo : null;
|
|
945
|
-
const redirectUrl = resolveSameOriginUrl(request, rawRedirect, "/reset-password");
|
|
946
|
-
if (!email) {
|
|
947
|
-
return NextResponse.json({ error: "email is required" }, { status: 400 });
|
|
1171
|
+
if (!cryptoKey) {
|
|
1172
|
+
throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
948
1173
|
}
|
|
949
|
-
if (!
|
|
950
|
-
|
|
1174
|
+
if (!cached) {
|
|
1175
|
+
cache.set(keyObject, { [alg]: cryptoKey });
|
|
1176
|
+
} else {
|
|
1177
|
+
cached[alg] = cryptoKey;
|
|
951
1178
|
}
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
const data = await res.json().catch(() => ({}));
|
|
958
|
-
return NextResponse.json(data, { status: res.status });
|
|
959
|
-
}
|
|
960
|
-
async function handleResetPassword(request, ctx) {
|
|
961
|
-
if (request.method !== "POST") {
|
|
962
|
-
return NextResponse.json({ error: "Method not allowed" }, { status: 405 });
|
|
1179
|
+
return cryptoKey;
|
|
1180
|
+
};
|
|
1181
|
+
async function normalizeKey(key, alg) {
|
|
1182
|
+
if (key instanceof Uint8Array) {
|
|
1183
|
+
return key;
|
|
963
1184
|
}
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
const password = typeof body?.password === "string" ? body.password : typeof body?.newPassword === "string" ? body.newPassword : null;
|
|
967
|
-
if (!token || !password) {
|
|
968
|
-
return NextResponse.json({ error: "token and password are required" }, { status: 400 });
|
|
1185
|
+
if (isCryptoKey(key)) {
|
|
1186
|
+
return key;
|
|
969
1187
|
}
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
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");
|
|
977
1211
|
}
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
1212
|
+
|
|
1213
|
+
// ../../../../.bun-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
|
+
}
|
|
990
1231
|
}
|
|
991
|
-
if (
|
|
992
|
-
|
|
993
|
-
url.searchParams.set("error", "missing_code");
|
|
994
|
-
return NextResponse.redirect(url);
|
|
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`);
|
|
995
1234
|
}
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
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;
|
|
1015
1259
|
}
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
const url = new URL(ctx.config.signInUrl, request.url);
|
|
1019
|
-
url.searchParams.set("error", "invalid_response");
|
|
1020
|
-
const response2 = NextResponse.redirect(url);
|
|
1021
|
-
clearOAuthPkceCookie(response2, ctx);
|
|
1022
|
-
return response2;
|
|
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`);
|
|
1023
1262
|
}
|
|
1024
|
-
const successUrl = new URL(redirectTo, request.url);
|
|
1025
|
-
const response = NextResponse.redirect(successUrl);
|
|
1026
|
-
setAuthCookiesMiddleware(response, ctx.namespace, data);
|
|
1027
|
-
clearOAuthPkceCookie(response, ctx);
|
|
1028
|
-
ctx.log("Callback success", { redirectTo });
|
|
1029
|
-
return response;
|
|
1030
|
-
} catch (err) {
|
|
1031
|
-
console.error("[Sylphx] Callback error:", err);
|
|
1032
|
-
const url = new URL(ctx.config.signInUrl, request.url);
|
|
1033
|
-
url.searchParams.set("error", "internal_error");
|
|
1034
|
-
return NextResponse.redirect(url);
|
|
1035
1263
|
}
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
}
|
|
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`);
|
|
1051
1294
|
}
|
|
1052
1295
|
}
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
clearAuthCookiesMiddleware(response, ctx.namespace);
|
|
1056
|
-
ctx.log("Signout complete");
|
|
1057
|
-
return response;
|
|
1058
|
-
}
|
|
1059
|
-
async function handleToken(request, ctx) {
|
|
1060
|
-
ctx.log("Token request");
|
|
1061
|
-
const sessionToken = readRequestCookieValue(request, ctx.cookieNames.SESSION);
|
|
1062
|
-
if (sessionToken && !isTokenExpired(sessionToken)) {
|
|
1063
|
-
ctx.log("Token returned");
|
|
1064
|
-
return NextResponse.json({ accessToken: sessionToken });
|
|
1296
|
+
if (!isKeyLike(key)) {
|
|
1297
|
+
throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
1065
1298
|
}
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
ctx.log("Token refreshed and returned");
|
|
1069
|
-
const response2 = NextResponse.json({ accessToken: restored.tokens.accessToken });
|
|
1070
|
-
setRestoredSessionCookies(response2, ctx, restored);
|
|
1071
|
-
return response2;
|
|
1299
|
+
if (key.type === "secret") {
|
|
1300
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
|
|
1072
1301
|
}
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
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);
|
|
1080
1330
|
}
|
|
1081
|
-
return response;
|
|
1082
|
-
}
|
|
1083
|
-
function resolveOrgScopedTokenExpiresIn(data) {
|
|
1084
|
-
if (typeof data.expiresIn === "number") return data.expiresIn;
|
|
1085
|
-
if (typeof data.expires_in === "number") return data.expires_in;
|
|
1086
|
-
return SESSION_TOKEN_LIFETIME;
|
|
1087
|
-
}
|
|
1088
|
-
function resolveOrgScopedAccessToken(data) {
|
|
1089
|
-
if (data.accessToken) return data.accessToken;
|
|
1090
|
-
if (data.access_token) return data.access_token;
|
|
1091
|
-
return null;
|
|
1092
1331
|
}
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1332
|
+
|
|
1333
|
+
// ../../../../.bun-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
|
+
}
|
|
1097
1363
|
}
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1364
|
+
|
|
1365
|
+
// ../../../../.bun-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;
|
|
1102
1375
|
}
|
|
1103
|
-
|
|
1104
|
-
|
|
1376
|
+
|
|
1377
|
+
// ../../../../.bun-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);
|
|
1105
1382
|
try {
|
|
1106
|
-
return
|
|
1383
|
+
return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
|
|
1107
1384
|
} catch {
|
|
1108
|
-
return
|
|
1385
|
+
return false;
|
|
1109
1386
|
}
|
|
1110
1387
|
}
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1388
|
+
|
|
1389
|
+
// ../../../../.bun-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");
|
|
1115
1393
|
}
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
function uniqueCookieNames(names) {
|
|
1119
|
-
return [...new Set(names.filter((name) => Boolean(name)))];
|
|
1120
|
-
}
|
|
1121
|
-
function readActiveOrganizationContext(request, ctx, sessionToken) {
|
|
1122
|
-
const orgIdCookieNames = uniqueCookieNames([
|
|
1123
|
-
ctx.cookieNames.ACTIVE_ORG_ID,
|
|
1124
|
-
...ctx.config.organizationContext.additionalOrgIdCookies
|
|
1125
|
-
]);
|
|
1126
|
-
const orgSlugCookieNames = uniqueCookieNames([
|
|
1127
|
-
ctx.cookieNames.ACTIVE_ORG_SLUG,
|
|
1128
|
-
...ctx.config.organizationContext.additionalOrgSlugCookies
|
|
1129
|
-
]);
|
|
1130
|
-
const fromCookie = {
|
|
1131
|
-
id: readFirstCookieValue(request, orgIdCookieNames),
|
|
1132
|
-
slug: readFirstCookieValue(request, orgSlugCookieNames)
|
|
1133
|
-
};
|
|
1134
|
-
if (fromCookie.id || fromCookie.slug) return fromCookie;
|
|
1135
|
-
const payload = sessionToken ? decodeJwtPayload(sessionToken) : null;
|
|
1136
|
-
return {
|
|
1137
|
-
id: payload?.org_id ?? null,
|
|
1138
|
-
slug: payload?.org_slug ?? null
|
|
1139
|
-
};
|
|
1140
|
-
}
|
|
1141
|
-
function setActiveOrganizationCookies(response, ctx, org) {
|
|
1142
|
-
if (org.id) {
|
|
1143
|
-
response.cookies.set(ctx.cookieNames.ACTIVE_ORG_ID, org.id, {
|
|
1144
|
-
...ACTIVE_ORG_COOKIE_OPTIONS,
|
|
1145
|
-
maxAge: ACTIVE_ORG_LIFETIME
|
|
1146
|
-
});
|
|
1147
|
-
}
|
|
1148
|
-
if (org.slug) {
|
|
1149
|
-
response.cookies.set(ctx.cookieNames.ACTIVE_ORG_SLUG, org.slug, {
|
|
1150
|
-
...ACTIVE_ORG_COOKIE_OPTIONS,
|
|
1151
|
-
maxAge: ACTIVE_ORG_LIFETIME
|
|
1152
|
-
});
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
async function getUserOrganizations(accessToken, ctx) {
|
|
1156
|
-
try {
|
|
1157
|
-
const res = await fetch(`${ctx.platformUrl}/v1/orgs/memberships`, {
|
|
1158
|
-
method: "GET",
|
|
1159
|
-
headers: {
|
|
1160
|
-
"Content-Type": "application/json",
|
|
1161
|
-
"x-app-secret": ctx.secretKey,
|
|
1162
|
-
Authorization: `Bearer ${accessToken}`
|
|
1163
|
-
}
|
|
1164
|
-
});
|
|
1165
|
-
if (!res.ok) {
|
|
1166
|
-
ctx.log("Organization memberships fetch failed", res.status);
|
|
1167
|
-
return null;
|
|
1168
|
-
}
|
|
1169
|
-
const data = await res.json().catch(() => ({}));
|
|
1170
|
-
return Array.isArray(data.organizations) ? data.organizations : null;
|
|
1171
|
-
} catch (err) {
|
|
1172
|
-
ctx.log("Organization memberships fetch error", err);
|
|
1173
|
-
return null;
|
|
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');
|
|
1174
1396
|
}
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
try {
|
|
1178
|
-
const res = await fetch(`${ctx.platformUrl}/v1/auth/switch-org`, {
|
|
1179
|
-
method: "POST",
|
|
1180
|
-
headers: {
|
|
1181
|
-
"Content-Type": "application/json",
|
|
1182
|
-
"x-app-secret": ctx.secretKey,
|
|
1183
|
-
Authorization: `Bearer ${accessToken}`
|
|
1184
|
-
},
|
|
1185
|
-
body: JSON.stringify({ orgId })
|
|
1186
|
-
});
|
|
1187
|
-
const data = await res.json().catch(() => ({}));
|
|
1188
|
-
if (!res.ok) {
|
|
1189
|
-
ctx.log("Org scope restore failed", data.error || data.message || res.status);
|
|
1190
|
-
return { status: res.status, data };
|
|
1191
|
-
}
|
|
1192
|
-
return { status: res.status, data };
|
|
1193
|
-
} catch (err) {
|
|
1194
|
-
ctx.log("Org scope restore error", err);
|
|
1195
|
-
return null;
|
|
1397
|
+
if (jws.protected !== void 0 && typeof jws.protected !== "string") {
|
|
1398
|
+
throw new JWSInvalid("JWS Protected Header incorrect type");
|
|
1196
1399
|
}
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
if (!ctx.config.organizationContext.enabled) {
|
|
1200
|
-
return { tokens: refreshedTokens, activeOrganization: null };
|
|
1400
|
+
if (jws.payload === void 0) {
|
|
1401
|
+
throw new JWSInvalid("JWS Payload missing");
|
|
1201
1402
|
}
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
let targetOrgSlug = activeOrg.slug;
|
|
1205
|
-
let organizations = null;
|
|
1206
|
-
if (!targetOrgId && targetOrgSlug) {
|
|
1207
|
-
organizations = await getUserOrganizations(refreshedTokens.accessToken, ctx);
|
|
1208
|
-
targetOrgId = organizations?.find((org) => org.slug === targetOrgSlug)?.id ?? null;
|
|
1403
|
+
if (typeof jws.signature !== "string") {
|
|
1404
|
+
throw new JWSInvalid("JWS Signature missing or incorrect type");
|
|
1209
1405
|
}
|
|
1210
|
-
if (
|
|
1211
|
-
|
|
1212
|
-
const onlyOrg = organizations?.length === 1 ? organizations[0] : null;
|
|
1213
|
-
targetOrgId = onlyOrg?.id ?? null;
|
|
1214
|
-
targetOrgSlug = onlyOrg?.slug ?? null;
|
|
1406
|
+
if (jws.header !== void 0 && !isObject(jws.header)) {
|
|
1407
|
+
throw new JWSInvalid("JWS Unprotected Header incorrect type");
|
|
1215
1408
|
}
|
|
1216
|
-
|
|
1217
|
-
|
|
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
|
+
}
|
|
1218
1417
|
}
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
const accessToken = scopedData ? resolveOrgScopedAccessToken(scopedData) : null;
|
|
1222
|
-
if (!scoped || scoped.status >= 400 || !scopedData || !accessToken) {
|
|
1223
|
-
return { tokens: refreshedTokens, activeOrganization: null };
|
|
1418
|
+
if (!isDisjoint(parsedProt, jws.header)) {
|
|
1419
|
+
throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
1224
1420
|
}
|
|
1225
|
-
const
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
slug: payload?.org_slug ?? targetOrgSlug
|
|
1229
|
-
};
|
|
1230
|
-
return {
|
|
1231
|
-
tokens: {
|
|
1232
|
-
...refreshedTokens,
|
|
1233
|
-
accessToken,
|
|
1234
|
-
refreshToken: resolveOrgScopedRefreshToken(scopedData, refreshedTokens.refreshToken),
|
|
1235
|
-
expiresIn: resolveOrgScopedTokenExpiresIn(scopedData),
|
|
1236
|
-
tokenType: resolveOrgScopedTokenType(scopedData),
|
|
1237
|
-
user: scopedData.user ?? refreshedTokens.user
|
|
1238
|
-
},
|
|
1239
|
-
activeOrganization: resolvedOrg
|
|
1421
|
+
const joseHeader = {
|
|
1422
|
+
...parsedProt,
|
|
1423
|
+
...jws.header
|
|
1240
1424
|
};
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
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
|
+
}
|
|
1246
1432
|
}
|
|
1247
|
-
const
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
if (!sessionToken) {
|
|
1251
|
-
restoredBaseSession = await refreshSessionFromCookie(request, ctx, currentSessionToken);
|
|
1252
|
-
sessionToken = restoredBaseSession?.tokens.accessToken ?? null;
|
|
1433
|
+
const { alg } = joseHeader;
|
|
1434
|
+
if (typeof alg !== "string" || !alg) {
|
|
1435
|
+
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
|
1253
1436
|
}
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
if (
|
|
1260
|
-
|
|
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");
|
|
1261
1444
|
}
|
|
1262
|
-
|
|
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");
|
|
1263
1447
|
}
|
|
1264
|
-
let
|
|
1265
|
-
|
|
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;
|
|
1266
1456
|
try {
|
|
1267
|
-
|
|
1268
|
-
orgId = typeof body.orgId === "string" && body.orgId.trim() ? body.orgId.trim() : null;
|
|
1269
|
-
requestedOrgSlug = typeof body.orgSlug === "string" && body.orgSlug.trim() ? body.orgSlug.trim() : null;
|
|
1457
|
+
signature = decode(jws.signature);
|
|
1270
1458
|
} catch {
|
|
1271
|
-
|
|
1459
|
+
throw new JWSInvalid("Failed to base64url decode the signature");
|
|
1272
1460
|
}
|
|
1273
|
-
|
|
1274
|
-
|
|
1461
|
+
const k = await normalizeKey(key, alg);
|
|
1462
|
+
const verified = await verify(alg, k, signature, data);
|
|
1463
|
+
if (!verified) {
|
|
1464
|
+
throw new JWSSignatureVerificationFailed();
|
|
1275
1465
|
}
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
{ status: scoped?.status ?? 502 }
|
|
1283
|
-
);
|
|
1284
|
-
}
|
|
1285
|
-
const accessToken = resolveOrgScopedAccessToken(data);
|
|
1286
|
-
if (!accessToken) {
|
|
1287
|
-
return NextResponse.json(
|
|
1288
|
-
{ error: data.error || data.message || "invalid_response" },
|
|
1289
|
-
{ status: 502 }
|
|
1290
|
-
);
|
|
1291
|
-
}
|
|
1292
|
-
const expiresIn = resolveOrgScopedTokenExpiresIn(data);
|
|
1293
|
-
const expiresAt = Date.now() + expiresIn * 1e3;
|
|
1294
|
-
const payload = decodeJwtPayload(accessToken);
|
|
1295
|
-
const activeOrganization = {
|
|
1296
|
-
id: payload?.org_id ?? orgId,
|
|
1297
|
-
slug: payload?.org_slug ?? requestedOrgSlug
|
|
1298
|
-
};
|
|
1299
|
-
const response = NextResponse.json({
|
|
1300
|
-
success: true,
|
|
1301
|
-
user: data.user ?? null,
|
|
1302
|
-
organization: activeOrganization
|
|
1303
|
-
});
|
|
1304
|
-
if (restoredBaseSession) {
|
|
1305
|
-
setAuthCookiesMiddleware(response, ctx.namespace, restoredBaseSession.tokens);
|
|
1306
|
-
if (restoredBaseSession.activeOrganization) {
|
|
1307
|
-
setActiveOrganizationCookies(response, ctx, restoredBaseSession.activeOrganization);
|
|
1308
|
-
}
|
|
1309
|
-
}
|
|
1310
|
-
response.cookies.set(ctx.cookieNames.SESSION, accessToken, {
|
|
1311
|
-
...SECURE_COOKIE_OPTIONS,
|
|
1312
|
-
maxAge: expiresIn
|
|
1313
|
-
});
|
|
1314
|
-
const existingUser = parseUserCookie2(readRequestCookieValue(request, ctx.cookieNames.USER));
|
|
1315
|
-
const user = data.user ?? existingUser?.user;
|
|
1316
|
-
if (user) {
|
|
1317
|
-
response.cookies.set(
|
|
1318
|
-
ctx.cookieNames.USER,
|
|
1319
|
-
JSON.stringify({
|
|
1320
|
-
user,
|
|
1321
|
-
expiresAt
|
|
1322
|
-
}),
|
|
1323
|
-
{
|
|
1324
|
-
...USER_COOKIE_OPTIONS,
|
|
1325
|
-
maxAge: expiresIn
|
|
1326
|
-
}
|
|
1327
|
-
);
|
|
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");
|
|
1328
1472
|
}
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
ctx.log("Switch org error", err);
|
|
1334
|
-
return NextResponse.json({ error: "internal_error" }, { status: 500 });
|
|
1473
|
+
} else if (typeof jws.payload === "string") {
|
|
1474
|
+
payload = encoder.encode(jws.payload);
|
|
1475
|
+
} else {
|
|
1476
|
+
payload = jws.payload;
|
|
1335
1477
|
}
|
|
1336
|
-
}
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
if (!prefix) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
|
1340
|
-
const upstreamPath = stripRoutePrefix(request.nextUrl.pathname, prefix);
|
|
1341
|
-
if (!upstreamPath || !isAllowedBaasProxyPath(upstreamPath)) {
|
|
1342
|
-
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
|
1478
|
+
const result = { payload };
|
|
1479
|
+
if (jws.protected !== void 0) {
|
|
1480
|
+
result.protectedHeader = parsedProt;
|
|
1343
1481
|
}
|
|
1344
|
-
if (
|
|
1345
|
-
|
|
1482
|
+
if (jws.header !== void 0) {
|
|
1483
|
+
result.unprotectedHeader = jws.header;
|
|
1346
1484
|
}
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
const res = await fetch(upstreamUrl, {
|
|
1352
|
-
method,
|
|
1353
|
-
headers: buildUpstreamProxyHeaders(request, ctx, sessionToken),
|
|
1354
|
-
body
|
|
1355
|
-
});
|
|
1356
|
-
return new NextResponse(res.body, {
|
|
1357
|
-
status: res.status,
|
|
1358
|
-
headers: copyResponseHeaders(res.headers)
|
|
1359
|
-
});
|
|
1485
|
+
if (resolvedKey) {
|
|
1486
|
+
return { ...result, key: k };
|
|
1487
|
+
}
|
|
1488
|
+
return result;
|
|
1360
1489
|
}
|
|
1361
|
-
|
|
1362
|
-
|
|
1490
|
+
|
|
1491
|
+
// ../../../../.bun-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-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;
|
|
1363
1585
|
try {
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
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");
|
|
1376
1609
|
}
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
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");
|
|
1381
1645
|
}
|
|
1382
|
-
ctx.log("Refresh success");
|
|
1383
|
-
return data;
|
|
1384
|
-
} catch (err) {
|
|
1385
|
-
ctx.log("Refresh error", err);
|
|
1386
|
-
return null;
|
|
1387
1646
|
}
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
if (
|
|
1393
|
-
|
|
1394
|
-
explicitSecretKey: userConfig.secretKey,
|
|
1395
|
-
explicitSecretUrl: userConfig.secretUrl
|
|
1396
|
-
});
|
|
1397
|
-
if (!rawSecretKey) {
|
|
1398
|
-
throw new Error(
|
|
1399
|
-
"[Sylphx] Server connection URL is required.\nEither pass secretUrl in config or set SYLPHX_SECRET_URL env var."
|
|
1400
|
-
);
|
|
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");
|
|
1401
1653
|
}
|
|
1402
|
-
secretKey = validateAndSanitizeSecretKey(rawSecretKey);
|
|
1403
|
-
return secretKey;
|
|
1404
1654
|
}
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
throw new Error(
|
|
1414
|
-
"[Sylphx] Publishable connection URL is required for public auth routes.\nEither pass publicUrl/publishableKey in config or set SYLPHX_URL/NEXT_PUBLIC_SYLPHX_URL."
|
|
1415
|
-
);
|
|
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");
|
|
1416
1663
|
}
|
|
1417
|
-
publishableKey = validateAndSanitizePublicKey(rawPublishableKey);
|
|
1418
|
-
return publishableKey;
|
|
1419
1664
|
}
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
secretUrl: userConfig.secretUrl
|
|
1429
|
-
});
|
|
1430
|
-
namespace = getCookieNamespace(key);
|
|
1431
|
-
cookieNames = getCookieNames(namespace);
|
|
1665
|
+
return payload;
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
// ../../../../.bun-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");
|
|
1432
1673
|
}
|
|
1433
|
-
const
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
authPrefix: userConfig.authPrefix ?? "/auth",
|
|
1440
|
-
baasPrefix: userConfig.baasPrefix === false ? null : normalizeRoutePrefix(userConfig.baasPrefix ?? DEFAULT_BAAS_PREFIX),
|
|
1441
|
-
appUrl: normalizeAppUrl(userConfig.appUrl),
|
|
1442
|
-
debug: userConfig.debug ?? false,
|
|
1443
|
-
orgRequired: userConfig.orgRequired ?? false,
|
|
1444
|
-
orgSelectionUrl: userConfig.orgSelectionUrl ?? "/select-organization",
|
|
1445
|
-
organizationContext: {
|
|
1446
|
-
enabled: userConfig.organizationContext?.enabled ?? true,
|
|
1447
|
-
autoSelectSingleOrganization: userConfig.organizationContext?.autoSelectSingleOrganization ?? true,
|
|
1448
|
-
additionalOrgIdCookies: userConfig.organizationContext?.additionalOrgIdCookies ?? [],
|
|
1449
|
-
additionalOrgSlugCookies: userConfig.organizationContext?.additionalOrgSlugCookies ?? []
|
|
1450
|
-
},
|
|
1451
|
-
onResponse: userConfig.onResponse
|
|
1452
|
-
};
|
|
1453
|
-
const publicRoutes = [
|
|
1454
|
-
...config.publicRoutes,
|
|
1455
|
-
config.signInUrl,
|
|
1456
|
-
"/signup",
|
|
1457
|
-
`${config.authPrefix}/*`,
|
|
1458
|
-
...config.baasPrefix ? [`${config.baasPrefix}/*`] : []
|
|
1459
|
-
];
|
|
1460
|
-
const log = (msg, data) => {
|
|
1461
|
-
if (config.debug) {
|
|
1462
|
-
}
|
|
1463
|
-
};
|
|
1464
|
-
const ctx = {
|
|
1465
|
-
get secretKey() {
|
|
1466
|
-
return secretKey;
|
|
1467
|
-
},
|
|
1468
|
-
get publishableKey() {
|
|
1469
|
-
return resolvePublishableKey();
|
|
1470
|
-
},
|
|
1471
|
-
get platformUrl() {
|
|
1472
|
-
return platformUrl;
|
|
1473
|
-
},
|
|
1474
|
-
get namespace() {
|
|
1475
|
-
return namespace;
|
|
1476
|
-
},
|
|
1477
|
-
get cookieNames() {
|
|
1478
|
-
return cookieNames;
|
|
1479
|
-
},
|
|
1480
|
-
config,
|
|
1481
|
-
log
|
|
1482
|
-
};
|
|
1483
|
-
return async function middleware(request) {
|
|
1484
|
-
resolveConfig();
|
|
1485
|
-
const { pathname } = request.nextUrl;
|
|
1486
|
-
log(`${request.method} ${pathname}`);
|
|
1487
|
-
if (matchesAny(pathname, config.ignoredRoutes)) {
|
|
1488
|
-
log("Ignored route");
|
|
1489
|
-
return NextResponse.next();
|
|
1490
|
-
}
|
|
1491
|
-
if (pathname.includes(".") || pathname.startsWith("/_next")) {
|
|
1492
|
-
return NextResponse.next();
|
|
1493
|
-
}
|
|
1494
|
-
if (pathname === `${config.authPrefix}/register`) {
|
|
1495
|
-
return handleRegister(request, ctx);
|
|
1496
|
-
}
|
|
1497
|
-
if (pathname === `${config.authPrefix}/callback`) {
|
|
1498
|
-
return handleCallback(request, ctx);
|
|
1499
|
-
}
|
|
1500
|
-
if (pathname === `${config.authPrefix}/login`) {
|
|
1501
|
-
return handleLogin(request, ctx);
|
|
1502
|
-
}
|
|
1503
|
-
if (pathname === `${config.authPrefix}/verify-email`) {
|
|
1504
|
-
return handleVerifyEmail(request, ctx);
|
|
1505
|
-
}
|
|
1506
|
-
if (pathname === `${config.authPrefix}/oauth-providers`) {
|
|
1507
|
-
return handleOAuthProviders(ctx);
|
|
1508
|
-
}
|
|
1509
|
-
if (pathname === `${config.authPrefix}/oauth/authorize`) {
|
|
1510
|
-
return handleOAuthAuthorize(request, ctx);
|
|
1511
|
-
}
|
|
1512
|
-
if (pathname === `${config.authPrefix}/passkey/options`) {
|
|
1513
|
-
return handlePasskeyOptions(request, ctx);
|
|
1514
|
-
}
|
|
1515
|
-
if (pathname === `${config.authPrefix}/passkey/authenticate`) {
|
|
1516
|
-
return handlePasskeyAuthenticate(request, ctx);
|
|
1517
|
-
}
|
|
1518
|
-
if (pathname === `${config.authPrefix}/verify-2fa`) {
|
|
1519
|
-
return handleVerifyTwoFactor(request, ctx);
|
|
1520
|
-
}
|
|
1521
|
-
if (pathname === `${config.authPrefix}/forgot-password`) {
|
|
1522
|
-
return handleForgotPassword(request, ctx);
|
|
1523
|
-
}
|
|
1524
|
-
if (pathname === `${config.authPrefix}/reset-password`) {
|
|
1525
|
-
return handleResetPassword(request, ctx);
|
|
1526
|
-
}
|
|
1527
|
-
if (pathname === `${config.authPrefix}/session`) {
|
|
1528
|
-
return handleSession(request, ctx);
|
|
1529
|
-
}
|
|
1530
|
-
if (pathname === `${config.authPrefix}/signout`) {
|
|
1531
|
-
return handleSignOut(request, ctx);
|
|
1532
|
-
}
|
|
1533
|
-
if (pathname === `${config.authPrefix}/token`) {
|
|
1534
|
-
return handleToken(request, ctx);
|
|
1535
|
-
}
|
|
1536
|
-
if (pathname === `${config.authPrefix}/switch-org`) {
|
|
1537
|
-
return handleSwitchOrg(request, ctx);
|
|
1538
|
-
}
|
|
1539
|
-
const sessionToken = readRequestCookieValue(request, cookieNames.SESSION);
|
|
1540
|
-
const refreshToken = readRequestCookieValue(request, cookieNames.REFRESH);
|
|
1541
|
-
const hasValidSession = sessionToken && !isTokenExpired(sessionToken);
|
|
1542
|
-
const response = NextResponse.next({ request: { headers: request.headers } });
|
|
1543
|
-
let isAuthenticated = hasValidSession;
|
|
1544
|
-
let activeSessionToken = hasValidSession ? sessionToken : null;
|
|
1545
|
-
if (!hasValidSession && refreshToken) {
|
|
1546
|
-
log("Session expired, refreshing");
|
|
1547
|
-
const tokens = await refreshTokens(refreshToken, ctx);
|
|
1548
|
-
if (tokens) {
|
|
1549
|
-
const restored = await restoreOrganizationScopeAfterRefresh(
|
|
1550
|
-
request,
|
|
1551
|
-
ctx,
|
|
1552
|
-
tokens,
|
|
1553
|
-
sessionToken
|
|
1554
|
-
);
|
|
1555
|
-
setAuthCookiesMiddleware(response, namespace, restored.tokens);
|
|
1556
|
-
if (restored.activeOrganization) {
|
|
1557
|
-
setActiveOrganizationCookies(response, ctx, restored.activeOrganization);
|
|
1558
|
-
}
|
|
1559
|
-
isAuthenticated = true;
|
|
1560
|
-
activeSessionToken = restored.tokens.accessToken;
|
|
1561
|
-
} else {
|
|
1562
|
-
clearAuthCookiesMiddleware(response, namespace);
|
|
1563
|
-
isAuthenticated = false;
|
|
1564
|
-
activeSessionToken = null;
|
|
1565
|
-
}
|
|
1566
|
-
}
|
|
1567
|
-
if (config.baasPrefix && stripRoutePrefix(pathname, config.baasPrefix)) {
|
|
1568
|
-
return handleBaasProxy(request, ctx, activeSessionToken);
|
|
1569
|
-
}
|
|
1570
|
-
const isPublic = matchesAny(pathname, publicRoutes);
|
|
1571
|
-
if (!isPublic && !isAuthenticated) {
|
|
1572
|
-
log("Redirecting to sign-in");
|
|
1573
|
-
const url = new URL(config.signInUrl, request.url);
|
|
1574
|
-
url.searchParams.set("callbackUrl", requestPathWithSearch(request));
|
|
1575
|
-
return NextResponse.redirect(url);
|
|
1576
|
-
}
|
|
1577
|
-
if (isAuthenticated && pathname === config.signInUrl) {
|
|
1578
|
-
const callbackUrl = resolveSafeRelativeRedirectPath(
|
|
1579
|
-
request.nextUrl.searchParams.get("callbackUrl"),
|
|
1580
|
-
config.afterSignInUrl
|
|
1581
|
-
);
|
|
1582
|
-
log("Redirecting from sign-in", { callbackUrl });
|
|
1583
|
-
return NextResponse.redirect(new URL(callbackUrl, request.url));
|
|
1584
|
-
}
|
|
1585
|
-
if (config.orgRequired && !isPublic && isAuthenticated && activeSessionToken && !matchesPattern(pathname, config.orgSelectionUrl)) {
|
|
1586
|
-
const payload = decodeJwtPayload(activeSessionToken);
|
|
1587
|
-
if (!payload?.org_id) {
|
|
1588
|
-
log("Redirecting to organization selection");
|
|
1589
|
-
const url = new URL(config.orgSelectionUrl, request.url);
|
|
1590
|
-
url.searchParams.set("redirect_to", requestPathWithSearch(request));
|
|
1591
|
-
return NextResponse.redirect(url);
|
|
1592
|
-
}
|
|
1593
|
-
}
|
|
1594
|
-
if (config.onResponse) {
|
|
1595
|
-
await config.onResponse(response, request);
|
|
1596
|
-
}
|
|
1597
|
-
return response;
|
|
1598
|
-
};
|
|
1599
|
-
}
|
|
1600
|
-
var sylphxMiddleware = createSylphxMiddleware;
|
|
1601
|
-
function createMatcher() {
|
|
1602
|
-
return {
|
|
1603
|
-
matcher: ["/((?!_next|monitoring|.*\\..*).*)", "/"]
|
|
1604
|
-
};
|
|
1605
|
-
}
|
|
1606
|
-
function getNamespace(secretKey) {
|
|
1607
|
-
return getCookieNamespace(validateAndSanitizeSecretKey(secretKey));
|
|
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;
|
|
1608
1680
|
}
|
|
1609
1681
|
|
|
1610
|
-
// src/
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
var decoder = new TextDecoder();
|
|
1623
|
-
var MAX_INT32 = 2 ** 32;
|
|
1624
|
-
function concat(...buffers) {
|
|
1625
|
-
const size = buffers.reduce((acc, { length }) => acc + length, 0);
|
|
1626
|
-
const buf = new Uint8Array(size);
|
|
1627
|
-
let i = 0;
|
|
1628
|
-
for (const buffer of buffers) {
|
|
1629
|
-
buf.set(buffer, i);
|
|
1630
|
-
i += buffer.length;
|
|
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);
|
|
1631
1694
|
}
|
|
1632
|
-
|
|
1695
|
+
};
|
|
1696
|
+
function fail(reason) {
|
|
1697
|
+
throw new InvalidConnectionUrlError(`Invalid Sylphx connection URL: ${reason}`);
|
|
1633
1698
|
}
|
|
1634
|
-
function
|
|
1635
|
-
const
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
if (code > 127) {
|
|
1639
|
-
throw new TypeError("non-ASCII string encountered in encode()");
|
|
1640
|
-
}
|
|
1641
|
-
bytes[i] = code;
|
|
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}"`);
|
|
1642
1703
|
}
|
|
1643
|
-
return
|
|
1704
|
+
return {
|
|
1705
|
+
credentialType: match[1],
|
|
1706
|
+
env: match[2]
|
|
1707
|
+
};
|
|
1644
1708
|
}
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
if (Uint8Array.fromBase64) {
|
|
1649
|
-
return Uint8Array.fromBase64(encoded);
|
|
1650
|
-
}
|
|
1651
|
-
const binary = atob(encoded);
|
|
1652
|
-
const bytes = new Uint8Array(binary.length);
|
|
1653
|
-
for (let i = 0; i < binary.length; i++) {
|
|
1654
|
-
bytes[i] = binary.charCodeAt(i);
|
|
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)`);
|
|
1655
1712
|
}
|
|
1656
|
-
return
|
|
1713
|
+
return candidate;
|
|
1657
1714
|
}
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
if (Uint8Array.fromBase64) {
|
|
1662
|
-
return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
|
|
1663
|
-
alphabet: "base64url"
|
|
1664
|
-
});
|
|
1665
|
-
}
|
|
1666
|
-
let encoded = input;
|
|
1667
|
-
if (encoded instanceof Uint8Array) {
|
|
1668
|
-
encoded = decoder.decode(encoded);
|
|
1715
|
+
function parseConnectionUrl(url) {
|
|
1716
|
+
if (typeof url !== "string" || url.length === 0) {
|
|
1717
|
+
fail("url must be a non-empty string");
|
|
1669
1718
|
}
|
|
1670
|
-
|
|
1719
|
+
let parsed;
|
|
1671
1720
|
try {
|
|
1672
|
-
|
|
1721
|
+
parsed = new URL(url);
|
|
1673
1722
|
} catch {
|
|
1674
|
-
|
|
1723
|
+
fail(`not a valid URL: "${url}"`);
|
|
1675
1724
|
}
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
// ../../../../.bun-cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/util/errors.js
|
|
1679
|
-
var JOSEError = class extends Error {
|
|
1680
|
-
static code = "ERR_JOSE_GENERIC";
|
|
1681
|
-
code = "ERR_JOSE_GENERIC";
|
|
1682
|
-
constructor(message2, options) {
|
|
1683
|
-
super(message2, options);
|
|
1684
|
-
this.name = this.constructor.name;
|
|
1685
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
1725
|
+
if (parsed.protocol !== SYLPHX_PROTOCOL) {
|
|
1726
|
+
fail(`protocol must be "sylphx:", got "${parsed.protocol}"`);
|
|
1686
1727
|
}
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
1691
|
-
claim;
|
|
1692
|
-
reason;
|
|
1693
|
-
payload;
|
|
1694
|
-
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
1695
|
-
super(message2, { cause: { claim, reason, payload } });
|
|
1696
|
-
this.claim = claim;
|
|
1697
|
-
this.reason = reason;
|
|
1698
|
-
this.payload = payload;
|
|
1728
|
+
const credential = decodeURIComponent(parsed.username);
|
|
1729
|
+
if (!credential) {
|
|
1730
|
+
fail("missing credential (expected `sylphx://<credential>@<host>`)");
|
|
1699
1731
|
}
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
static code = "ERR_JWT_EXPIRED";
|
|
1703
|
-
code = "ERR_JWT_EXPIRED";
|
|
1704
|
-
claim;
|
|
1705
|
-
reason;
|
|
1706
|
-
payload;
|
|
1707
|
-
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
1708
|
-
super(message2, { cause: { claim, reason, payload } });
|
|
1709
|
-
this.claim = claim;
|
|
1710
|
-
this.reason = reason;
|
|
1711
|
-
this.payload = payload;
|
|
1732
|
+
if (parsed.password) {
|
|
1733
|
+
fail("connection URL must not contain a password component");
|
|
1712
1734
|
}
|
|
1713
|
-
};
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
};
|
|
1718
|
-
var JOSENotSupported = class extends JOSEError {
|
|
1719
|
-
static code = "ERR_JOSE_NOT_SUPPORTED";
|
|
1720
|
-
code = "ERR_JOSE_NOT_SUPPORTED";
|
|
1721
|
-
};
|
|
1722
|
-
var JWSInvalid = class extends JOSEError {
|
|
1723
|
-
static code = "ERR_JWS_INVALID";
|
|
1724
|
-
code = "ERR_JWS_INVALID";
|
|
1725
|
-
};
|
|
1726
|
-
var JWTInvalid = class extends JOSEError {
|
|
1727
|
-
static code = "ERR_JWT_INVALID";
|
|
1728
|
-
code = "ERR_JWT_INVALID";
|
|
1729
|
-
};
|
|
1730
|
-
var JWSSignatureVerificationFailed = class extends JOSEError {
|
|
1731
|
-
static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
1732
|
-
code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
1733
|
-
constructor(message2 = "signature verification failed", options) {
|
|
1734
|
-
super(message2, options);
|
|
1735
|
+
const { credentialType, env } = parseCredential(credential);
|
|
1736
|
+
const host = parsed.host;
|
|
1737
|
+
if (!host) {
|
|
1738
|
+
fail("missing host");
|
|
1735
1739
|
}
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
var isAlgorithm = (algorithm, name) => algorithm.name === name;
|
|
1741
|
-
function getHashLength(hash) {
|
|
1742
|
-
return parseInt(hash.name.slice(4), 10);
|
|
1743
|
-
}
|
|
1744
|
-
function getNamedCurve(alg) {
|
|
1745
|
-
switch (alg) {
|
|
1746
|
-
case "ES256":
|
|
1747
|
-
return "P-256";
|
|
1748
|
-
case "ES384":
|
|
1749
|
-
return "P-384";
|
|
1750
|
-
case "ES512":
|
|
1751
|
-
return "P-521";
|
|
1752
|
-
default:
|
|
1753
|
-
throw new Error("unreachable");
|
|
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)`);
|
|
1754
1744
|
}
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
if (
|
|
1758
|
-
|
|
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`);
|
|
1759
1749
|
}
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
if (!isAlgorithm(key.algorithm, "HMAC"))
|
|
1767
|
-
throw unusable("HMAC");
|
|
1768
|
-
const expected = parseInt(alg.slice(2), 10);
|
|
1769
|
-
const actual = getHashLength(key.algorithm.hash);
|
|
1770
|
-
if (actual !== expected)
|
|
1771
|
-
throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
1772
|
-
break;
|
|
1773
|
-
}
|
|
1774
|
-
case "RS256":
|
|
1775
|
-
case "RS384":
|
|
1776
|
-
case "RS512": {
|
|
1777
|
-
if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
|
|
1778
|
-
throw unusable("RSASSA-PKCS1-v1_5");
|
|
1779
|
-
const expected = parseInt(alg.slice(2), 10);
|
|
1780
|
-
const actual = getHashLength(key.algorithm.hash);
|
|
1781
|
-
if (actual !== expected)
|
|
1782
|
-
throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
1783
|
-
break;
|
|
1784
|
-
}
|
|
1785
|
-
case "PS256":
|
|
1786
|
-
case "PS384":
|
|
1787
|
-
case "PS512": {
|
|
1788
|
-
if (!isAlgorithm(key.algorithm, "RSA-PSS"))
|
|
1789
|
-
throw unusable("RSA-PSS");
|
|
1790
|
-
const expected = parseInt(alg.slice(2), 10);
|
|
1791
|
-
const actual = getHashLength(key.algorithm.hash);
|
|
1792
|
-
if (actual !== expected)
|
|
1793
|
-
throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
1794
|
-
break;
|
|
1795
|
-
}
|
|
1796
|
-
case "Ed25519":
|
|
1797
|
-
case "EdDSA": {
|
|
1798
|
-
if (!isAlgorithm(key.algorithm, "Ed25519"))
|
|
1799
|
-
throw unusable("Ed25519");
|
|
1800
|
-
break;
|
|
1801
|
-
}
|
|
1802
|
-
case "ML-DSA-44":
|
|
1803
|
-
case "ML-DSA-65":
|
|
1804
|
-
case "ML-DSA-87": {
|
|
1805
|
-
if (!isAlgorithm(key.algorithm, alg))
|
|
1806
|
-
throw unusable(alg);
|
|
1807
|
-
break;
|
|
1808
|
-
}
|
|
1809
|
-
case "ES256":
|
|
1810
|
-
case "ES384":
|
|
1811
|
-
case "ES512": {
|
|
1812
|
-
if (!isAlgorithm(key.algorithm, "ECDSA"))
|
|
1813
|
-
throw unusable("ECDSA");
|
|
1814
|
-
const expected = getNamedCurve(alg);
|
|
1815
|
-
const actual = key.algorithm.namedCurve;
|
|
1816
|
-
if (actual !== expected)
|
|
1817
|
-
throw unusable(expected, "algorithm.namedCurve");
|
|
1818
|
-
break;
|
|
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}`);
|
|
1819
1756
|
}
|
|
1820
|
-
|
|
1821
|
-
throw new TypeError("CryptoKey does not support this operation");
|
|
1757
|
+
version = rawPath;
|
|
1822
1758
|
}
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
// ../../../../.bun-cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/invalid_key_input.js
|
|
1827
|
-
function message(msg, actual, ...types) {
|
|
1828
|
-
types = types.filter(Boolean);
|
|
1829
|
-
if (types.length > 2) {
|
|
1830
|
-
const last = types.pop();
|
|
1831
|
-
msg += `one of type ${types.join(", ")}, or ${last}.`;
|
|
1832
|
-
} else if (types.length === 2) {
|
|
1833
|
-
msg += `one of type ${types[0]} or ${types[1]}.`;
|
|
1834
|
-
} else {
|
|
1835
|
-
msg += `of type ${types[0]}.`;
|
|
1759
|
+
if (parsed.search) {
|
|
1760
|
+
fail("connection URL must not contain a query string");
|
|
1836
1761
|
}
|
|
1837
|
-
if (
|
|
1838
|
-
|
|
1839
|
-
} else if (typeof actual === "function" && actual.name) {
|
|
1840
|
-
msg += ` Received function ${actual.name}`;
|
|
1841
|
-
} else if (typeof actual === "object" && actual != null) {
|
|
1842
|
-
if (actual.constructor?.name) {
|
|
1843
|
-
msg += ` Received an instance of ${actual.constructor.name}`;
|
|
1844
|
-
}
|
|
1762
|
+
if (parsed.hash) {
|
|
1763
|
+
fail("connection URL must not contain a fragment");
|
|
1845
1764
|
}
|
|
1846
|
-
|
|
1765
|
+
const apiBaseUrl = `https://${host}/${version}`;
|
|
1766
|
+
return {
|
|
1767
|
+
credential,
|
|
1768
|
+
credentialType,
|
|
1769
|
+
env,
|
|
1770
|
+
slug,
|
|
1771
|
+
host,
|
|
1772
|
+
apiBaseUrl
|
|
1773
|
+
};
|
|
1847
1774
|
}
|
|
1848
|
-
var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
|
|
1849
|
-
var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
|
|
1850
|
-
|
|
1851
|
-
// ../../../../.bun-cache/links/jose@6.1.3-bb9fbb1164201cee/node_modules/jose/dist/webapi/lib/is_key_like.js
|
|
1852
|
-
var isCryptoKey = (key) => {
|
|
1853
|
-
if (key?.[Symbol.toStringTag] === "CryptoKey")
|
|
1854
|
-
return true;
|
|
1855
|
-
try {
|
|
1856
|
-
return key instanceof CryptoKey;
|
|
1857
|
-
} catch {
|
|
1858
|
-
return false;
|
|
1859
|
-
}
|
|
1860
|
-
};
|
|
1861
|
-
var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
|
|
1862
|
-
var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
|
|
1863
1775
|
|
|
1864
|
-
//
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
}
|
|
1877
|
-
for (const parameter of parameters) {
|
|
1878
|
-
if (acc.has(parameter)) {
|
|
1879
|
-
return false;
|
|
1880
|
-
}
|
|
1881
|
-
acc.add(parameter);
|
|
1882
|
-
}
|
|
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;
|
|
1883
1788
|
}
|
|
1884
|
-
return
|
|
1789
|
+
return chars.join("");
|
|
1885
1790
|
}
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
return
|
|
1892
|
-
|
|
1893
|
-
if (Object.getPrototypeOf(input) === null) {
|
|
1894
|
-
return true;
|
|
1895
|
-
}
|
|
1896
|
-
let proto = input;
|
|
1897
|
-
while (Object.getPrototypeOf(proto) !== null) {
|
|
1898
|
-
proto = Object.getPrototypeOf(proto);
|
|
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);
|
|
1899
1798
|
}
|
|
1900
|
-
return
|
|
1799
|
+
return n.toString(16).padStart(32, "0");
|
|
1901
1800
|
}
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
|
1909
|
-
}
|
|
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);
|
|
1910
1807
|
}
|
|
1808
|
+
const hex = n.toString(16).padStart(32, "0");
|
|
1809
|
+
return hex.length === 32 ? hex : null;
|
|
1911
1810
|
}
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
case "PS384":
|
|
1935
|
-
case "PS512":
|
|
1936
|
-
algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
|
|
1937
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
1938
|
-
break;
|
|
1939
|
-
case "RS256":
|
|
1940
|
-
case "RS384":
|
|
1941
|
-
case "RS512":
|
|
1942
|
-
algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
|
|
1943
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
1944
|
-
break;
|
|
1945
|
-
case "RSA-OAEP":
|
|
1946
|
-
case "RSA-OAEP-256":
|
|
1947
|
-
case "RSA-OAEP-384":
|
|
1948
|
-
case "RSA-OAEP-512":
|
|
1949
|
-
algorithm = {
|
|
1950
|
-
name: "RSA-OAEP",
|
|
1951
|
-
hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
|
|
1952
|
-
};
|
|
1953
|
-
keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
|
|
1954
|
-
break;
|
|
1955
|
-
default:
|
|
1956
|
-
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
1957
|
-
}
|
|
1958
|
-
break;
|
|
1959
|
-
}
|
|
1960
|
-
case "EC": {
|
|
1961
|
-
switch (jwk.alg) {
|
|
1962
|
-
case "ES256":
|
|
1963
|
-
algorithm = { name: "ECDSA", namedCurve: "P-256" };
|
|
1964
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
1965
|
-
break;
|
|
1966
|
-
case "ES384":
|
|
1967
|
-
algorithm = { name: "ECDSA", namedCurve: "P-384" };
|
|
1968
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
1969
|
-
break;
|
|
1970
|
-
case "ES512":
|
|
1971
|
-
algorithm = { name: "ECDSA", namedCurve: "P-521" };
|
|
1972
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
1973
|
-
break;
|
|
1974
|
-
case "ECDH-ES":
|
|
1975
|
-
case "ECDH-ES+A128KW":
|
|
1976
|
-
case "ECDH-ES+A192KW":
|
|
1977
|
-
case "ECDH-ES+A256KW":
|
|
1978
|
-
algorithm = { name: "ECDH", namedCurve: jwk.crv };
|
|
1979
|
-
keyUsages = jwk.d ? ["deriveBits"] : [];
|
|
1980
|
-
break;
|
|
1981
|
-
default:
|
|
1982
|
-
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
1983
|
-
}
|
|
1984
|
-
break;
|
|
1985
|
-
}
|
|
1986
|
-
case "OKP": {
|
|
1987
|
-
switch (jwk.alg) {
|
|
1988
|
-
case "Ed25519":
|
|
1989
|
-
case "EdDSA":
|
|
1990
|
-
algorithm = { name: "Ed25519" };
|
|
1991
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
1992
|
-
break;
|
|
1993
|
-
case "ECDH-ES":
|
|
1994
|
-
case "ECDH-ES+A128KW":
|
|
1995
|
-
case "ECDH-ES+A192KW":
|
|
1996
|
-
case "ECDH-ES+A256KW":
|
|
1997
|
-
algorithm = { name: jwk.crv };
|
|
1998
|
-
keyUsages = jwk.d ? ["deriveBits"] : [];
|
|
1999
|
-
break;
|
|
2000
|
-
default:
|
|
2001
|
-
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
2002
|
-
}
|
|
2003
|
-
break;
|
|
2004
|
-
}
|
|
2005
|
-
default:
|
|
2006
|
-
throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
|
|
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);
|
|
2007
1833
|
}
|
|
2008
|
-
|
|
1834
|
+
const hex = b58Decode(enc);
|
|
1835
|
+
if (hex) return hexToUuid(hex);
|
|
1836
|
+
return null;
|
|
2009
1837
|
}
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
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;
|
|
2013
1862
|
}
|
|
2014
|
-
const
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
delete keyData.alg;
|
|
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}`);
|
|
2018
1866
|
}
|
|
2019
|
-
|
|
2020
|
-
|
|
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;
|
|
2021
1878
|
}
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
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
|
+
);
|
|
2027
1885
|
}
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
if (
|
|
2044
|
-
throw new
|
|
2045
|
-
}
|
|
2046
|
-
if (alg !== void 0 && alg !== jwk.alg) {
|
|
2047
|
-
throw new TypeError("JWK alg and alg option value mismatch");
|
|
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");
|
|
2048
1903
|
}
|
|
2049
|
-
|
|
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;
|
|
2050
1926
|
}
|
|
2051
|
-
case "EC":
|
|
2052
|
-
case "OKP":
|
|
2053
|
-
return jwkToKey({ ...jwk, alg, ext });
|
|
2054
|
-
default:
|
|
2055
|
-
throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
|
|
2056
1927
|
}
|
|
1928
|
+
throw lastError || new Error("Token verification failed");
|
|
2057
1929
|
}
|
|
2058
1930
|
|
|
2059
|
-
//
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
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
|
+
}
|
|
2063
1956
|
}
|
|
2064
|
-
|
|
2065
|
-
|
|
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;
|
|
2066
1987
|
}
|
|
2067
|
-
if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
|
|
2068
|
-
throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
|
|
2069
|
-
}
|
|
2070
|
-
let recognized;
|
|
2071
|
-
if (recognizedOption !== void 0) {
|
|
2072
|
-
recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
|
|
2073
|
-
} else {
|
|
2074
|
-
recognized = recognizedDefault;
|
|
2075
|
-
}
|
|
2076
|
-
for (const parameter of protectedHeader.crit) {
|
|
2077
|
-
if (!recognized.has(parameter)) {
|
|
2078
|
-
throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
|
|
2079
|
-
}
|
|
2080
|
-
if (joseHeader[parameter] === void 0) {
|
|
2081
|
-
throw new Err(`Extension Header Parameter "${parameter}" is missing`);
|
|
2082
|
-
}
|
|
2083
|
-
if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
|
|
2084
|
-
throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
|
|
2085
|
-
}
|
|
2086
|
-
}
|
|
2087
|
-
return new Set(protectedHeader.crit);
|
|
2088
1988
|
}
|
|
2089
1989
|
|
|
2090
|
-
//
|
|
2091
|
-
function
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
if (!algorithms) {
|
|
2096
|
-
return void 0;
|
|
2097
|
-
}
|
|
2098
|
-
return new Set(algorithms);
|
|
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;
|
|
2099
1995
|
}
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
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
|
+
);
|
|
2114
2024
|
}
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
if (
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
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
|
+
);
|
|
2122
2032
|
}
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
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
|
+
);
|
|
2130
2045
|
}
|
|
2131
|
-
const
|
|
2132
|
-
const
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
break;
|
|
2141
|
-
default:
|
|
2142
|
-
throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
2143
|
-
}
|
|
2144
|
-
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
|
|
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;
|
|
2145
2055
|
}
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
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);
|
|
2153
2070
|
}
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
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;
|
|
2165
2153
|
}
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
break;
|
|
2187
|
-
default:
|
|
2188
|
-
throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
2189
|
-
}
|
|
2190
|
-
if (alg.startsWith("RSA-OAEP")) {
|
|
2191
|
-
return keyObject.toCryptoKey({
|
|
2192
|
-
name: "RSA-OAEP",
|
|
2193
|
-
hash
|
|
2194
|
-
}, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
|
|
2195
|
-
}
|
|
2196
|
-
cryptoKey = keyObject.toCryptoKey({
|
|
2197
|
-
name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
|
|
2198
|
-
hash
|
|
2199
|
-
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
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);
|
|
2200
2174
|
}
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
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);
|
|
2235
2211
|
}
|
|
2236
|
-
|
|
2237
|
-
|
|
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 });
|
|
2238
2229
|
}
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
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 });
|
|
2243
2242
|
}
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
if (
|
|
2248
|
-
return
|
|
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 });
|
|
2249
2248
|
}
|
|
2250
|
-
|
|
2251
|
-
|
|
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 });
|
|
2252
2257
|
}
|
|
2253
|
-
if (
|
|
2254
|
-
|
|
2255
|
-
return key.export();
|
|
2256
|
-
}
|
|
2257
|
-
if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
|
|
2258
|
-
try {
|
|
2259
|
-
return handleKeyObject(key, alg);
|
|
2260
|
-
} catch (err) {
|
|
2261
|
-
if (err instanceof TypeError) {
|
|
2262
|
-
throw err;
|
|
2263
|
-
}
|
|
2264
|
-
}
|
|
2265
|
-
}
|
|
2266
|
-
let jwk = key.export({ format: "jwk" });
|
|
2267
|
-
return handleJWK(key, jwk, alg);
|
|
2258
|
+
if (isTwoFactorLoginResponse(data)) {
|
|
2259
|
+
return NextResponse2.json(data);
|
|
2268
2260
|
}
|
|
2269
|
-
if (
|
|
2270
|
-
|
|
2271
|
-
return decode(key.k);
|
|
2272
|
-
}
|
|
2273
|
-
return handleJWK(key, key, alg, true);
|
|
2261
|
+
if (!isTokenResponse(data)) {
|
|
2262
|
+
return NextResponse2.json({ error: "invalid_response" }, { status: 502 });
|
|
2274
2263
|
}
|
|
2275
|
-
|
|
2264
|
+
return authCookieJsonResponse(ctx, data);
|
|
2276
2265
|
}
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
var jwkMatchesOp = (alg, key, usage) => {
|
|
2281
|
-
if (key.use !== void 0) {
|
|
2282
|
-
let expected;
|
|
2283
|
-
switch (usage) {
|
|
2284
|
-
case "sign":
|
|
2285
|
-
case "verify":
|
|
2286
|
-
expected = "sig";
|
|
2287
|
-
break;
|
|
2288
|
-
case "encrypt":
|
|
2289
|
-
case "decrypt":
|
|
2290
|
-
expected = "enc";
|
|
2291
|
-
break;
|
|
2292
|
-
}
|
|
2293
|
-
if (key.use !== expected) {
|
|
2294
|
-
throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
|
|
2295
|
-
}
|
|
2266
|
+
async function handleVerifyEmail(request, ctx) {
|
|
2267
|
+
if (request.method !== "POST") {
|
|
2268
|
+
return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
|
|
2296
2269
|
}
|
|
2297
|
-
|
|
2298
|
-
|
|
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 });
|
|
2299
2274
|
}
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
|
|
2312
|
-
if (!alg.includes("GCM") && alg.endsWith("KW")) {
|
|
2313
|
-
expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
|
|
2314
|
-
} else {
|
|
2315
|
-
expectedKeyOp = usage;
|
|
2316
|
-
}
|
|
2317
|
-
break;
|
|
2318
|
-
case (usage === "encrypt" && alg.startsWith("RSA")):
|
|
2319
|
-
expectedKeyOp = "wrapKey";
|
|
2320
|
-
break;
|
|
2321
|
-
case usage === "decrypt":
|
|
2322
|
-
expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
|
|
2323
|
-
break;
|
|
2324
|
-
}
|
|
2325
|
-
if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
|
|
2326
|
-
throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
|
|
2327
|
-
}
|
|
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 });
|
|
2328
2286
|
}
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
if (
|
|
2333
|
-
return;
|
|
2334
|
-
if (isJWK(key)) {
|
|
2335
|
-
if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
|
|
2336
|
-
return;
|
|
2337
|
-
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`);
|
|
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 });
|
|
2338
2292
|
}
|
|
2339
|
-
|
|
2340
|
-
|
|
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 });
|
|
2341
2301
|
}
|
|
2342
|
-
if (
|
|
2343
|
-
|
|
2302
|
+
if (!isTokenResponse(data)) {
|
|
2303
|
+
return NextResponse2.json({ error: "invalid_response" }, { status: 502 });
|
|
2344
2304
|
}
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
case "sign":
|
|
2351
|
-
if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
|
|
2352
|
-
return;
|
|
2353
|
-
throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
|
|
2354
|
-
case "encrypt":
|
|
2355
|
-
case "verify":
|
|
2356
|
-
if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
|
|
2357
|
-
return;
|
|
2358
|
-
throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
|
|
2359
|
-
}
|
|
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 });
|
|
2360
2310
|
}
|
|
2361
|
-
|
|
2362
|
-
|
|
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));
|
|
2363
2317
|
}
|
|
2364
|
-
|
|
2365
|
-
|
|
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;
|
|
2366
2324
|
}
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
|
|
2371
|
-
case "decrypt":
|
|
2372
|
-
throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
|
|
2373
|
-
}
|
|
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);
|
|
2374
2328
|
}
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
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 });
|
|
2382
2342
|
}
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
case "di":
|
|
2389
|
-
case "HS":
|
|
2390
|
-
case "PB":
|
|
2391
|
-
symmetricTypeCheck(alg, key, usage);
|
|
2392
|
-
break;
|
|
2393
|
-
default:
|
|
2394
|
-
asymmetricTypeCheck(alg, key, usage);
|
|
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 });
|
|
2395
2348
|
}
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
const
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
case "Ed25519":
|
|
2419
|
-
case "EdDSA":
|
|
2420
|
-
return { name: "Ed25519" };
|
|
2421
|
-
case "ML-DSA-44":
|
|
2422
|
-
case "ML-DSA-65":
|
|
2423
|
-
case "ML-DSA-87":
|
|
2424
|
-
return { name: alg };
|
|
2425
|
-
default:
|
|
2426
|
-
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
|
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
|
+
});
|
|
2427
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;
|
|
2428
2378
|
}
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
if (key instanceof Uint8Array) {
|
|
2433
|
-
if (!alg.startsWith("HS")) {
|
|
2434
|
-
throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
2435
|
-
}
|
|
2436
|
-
return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
|
|
2379
|
+
async function handlePasskeyOptions(request, ctx) {
|
|
2380
|
+
if (request.method !== "POST") {
|
|
2381
|
+
return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
|
|
2437
2382
|
}
|
|
2438
|
-
|
|
2439
|
-
|
|
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 });
|
|
2440
2391
|
}
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
const
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
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 });
|
|
2451
2408
|
}
|
|
2409
|
+
return authCookieJsonResponse(ctx, data);
|
|
2452
2410
|
}
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
if (!isObject(jws)) {
|
|
2457
|
-
throw new JWSInvalid("Flattened JWS must be an object");
|
|
2411
|
+
async function handleForgotPassword(request, ctx) {
|
|
2412
|
+
if (request.method !== "POST") {
|
|
2413
|
+
return NextResponse2.json({ error: "Method not allowed" }, { status: 405 });
|
|
2458
2414
|
}
|
|
2459
|
-
|
|
2460
|
-
|
|
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 });
|
|
2461
2421
|
}
|
|
2462
|
-
if (
|
|
2463
|
-
|
|
2422
|
+
if (!redirectUrl) {
|
|
2423
|
+
return NextResponse2.json({ error: "invalid_redirect_url" }, { status: 400 });
|
|
2464
2424
|
}
|
|
2465
|
-
|
|
2466
|
-
|
|
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 });
|
|
2467
2436
|
}
|
|
2468
|
-
|
|
2469
|
-
|
|
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 });
|
|
2470
2442
|
}
|
|
2471
|
-
|
|
2472
|
-
|
|
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);
|
|
2473
2463
|
}
|
|
2474
|
-
|
|
2475
|
-
|
|
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) {
|
|
2476
2514
|
try {
|
|
2477
|
-
|
|
2478
|
-
|
|
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
|
+
});
|
|
2479
2523
|
} catch {
|
|
2480
|
-
throw new JWSInvalid("JWS Protected Header is invalid");
|
|
2481
2524
|
}
|
|
2482
2525
|
}
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
const
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
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);
|
|
2496
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;
|
|
2497
2572
|
}
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
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
|
+
});
|
|
2501
2610
|
}
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
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
|
+
});
|
|
2505
2616
|
}
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
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;
|
|
2509
2631
|
}
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
}
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
key = await key(parsedProt, jws);
|
|
2516
|
-
resolvedKey = true;
|
|
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;
|
|
2517
2637
|
}
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
let signature;
|
|
2638
|
+
}
|
|
2639
|
+
async function getOrgScopedTokens(accessToken, orgId, ctx) {
|
|
2521
2640
|
try {
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
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;
|
|
2525
2659
|
}
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
if (!
|
|
2529
|
-
|
|
2660
|
+
}
|
|
2661
|
+
async function restoreOrganizationScopeAfterRefresh(request, ctx, refreshedTokens, previousSessionToken) {
|
|
2662
|
+
if (!ctx.config.organizationContext.enabled) {
|
|
2663
|
+
return { tokens: refreshedTokens, activeOrganization: null };
|
|
2530
2664
|
}
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
} else if (typeof jws.payload === "string") {
|
|
2539
|
-
payload = encoder.encode(jws.payload);
|
|
2540
|
-
} else {
|
|
2541
|
-
payload = jws.payload;
|
|
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;
|
|
2542
2672
|
}
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
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;
|
|
2546
2678
|
}
|
|
2547
|
-
if (
|
|
2548
|
-
|
|
2679
|
+
if (!targetOrgId) {
|
|
2680
|
+
return { tokens: refreshedTokens, activeOrganization: null };
|
|
2549
2681
|
}
|
|
2550
|
-
|
|
2551
|
-
|
|
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 };
|
|
2552
2687
|
}
|
|
2553
|
-
|
|
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
|
+
};
|
|
2554
2704
|
}
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
jws = decoder.decode(jws);
|
|
2560
|
-
}
|
|
2561
|
-
if (typeof jws !== "string") {
|
|
2562
|
-
throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
|
|
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 });
|
|
2563
2709
|
}
|
|
2564
|
-
const
|
|
2565
|
-
|
|
2566
|
-
|
|
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;
|
|
2567
2718
|
}
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
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;
|
|
2572
2728
|
}
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
var week = day * 7;
|
|
2582
|
-
var year = day * 365.25;
|
|
2583
|
-
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;
|
|
2584
|
-
function secs(str) {
|
|
2585
|
-
const matched = REGEX.exec(str);
|
|
2586
|
-
if (!matched || matched[4] && matched[1]) {
|
|
2587
|
-
throw new TypeError("Invalid time period format");
|
|
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 });
|
|
2588
2737
|
}
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
let numericDate;
|
|
2592
|
-
switch (unit) {
|
|
2593
|
-
case "sec":
|
|
2594
|
-
case "secs":
|
|
2595
|
-
case "second":
|
|
2596
|
-
case "seconds":
|
|
2597
|
-
case "s":
|
|
2598
|
-
numericDate = Math.round(value);
|
|
2599
|
-
break;
|
|
2600
|
-
case "minute":
|
|
2601
|
-
case "minutes":
|
|
2602
|
-
case "min":
|
|
2603
|
-
case "mins":
|
|
2604
|
-
case "m":
|
|
2605
|
-
numericDate = Math.round(value * minute);
|
|
2606
|
-
break;
|
|
2607
|
-
case "hour":
|
|
2608
|
-
case "hours":
|
|
2609
|
-
case "hr":
|
|
2610
|
-
case "hrs":
|
|
2611
|
-
case "h":
|
|
2612
|
-
numericDate = Math.round(value * hour);
|
|
2613
|
-
break;
|
|
2614
|
-
case "day":
|
|
2615
|
-
case "days":
|
|
2616
|
-
case "d":
|
|
2617
|
-
numericDate = Math.round(value * day);
|
|
2618
|
-
break;
|
|
2619
|
-
case "week":
|
|
2620
|
-
case "weeks":
|
|
2621
|
-
case "w":
|
|
2622
|
-
numericDate = Math.round(value * week);
|
|
2623
|
-
break;
|
|
2624
|
-
default:
|
|
2625
|
-
numericDate = Math.round(value * year);
|
|
2626
|
-
break;
|
|
2738
|
+
if (!orgId) {
|
|
2739
|
+
return NextResponse2.json({ error: "orgId is required" }, { status: 400 });
|
|
2627
2740
|
}
|
|
2628
|
-
|
|
2629
|
-
|
|
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 });
|
|
2630
2804
|
}
|
|
2631
|
-
return numericDate;
|
|
2632
2805
|
}
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
};
|
|
2639
|
-
var checkAudiencePresence = (audPayload, audOption) => {
|
|
2640
|
-
if (typeof audPayload === "string") {
|
|
2641
|
-
return audOption.includes(audPayload);
|
|
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 });
|
|
2642
2812
|
}
|
|
2643
|
-
if (
|
|
2644
|
-
return
|
|
2813
|
+
if (isAuthenticatedBaasProxyPath(upstreamPath) && !sessionToken) {
|
|
2814
|
+
return NextResponse2.json({ error: "Not authenticated" }, { status: 401 });
|
|
2645
2815
|
}
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
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");
|
|
2650
2832
|
try {
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
if (maxTokenAge !== void 0)
|
|
2664
|
-
presenceCheck.push("iat");
|
|
2665
|
-
if (audience !== void 0)
|
|
2666
|
-
presenceCheck.push("aud");
|
|
2667
|
-
if (subject !== void 0)
|
|
2668
|
-
presenceCheck.push("sub");
|
|
2669
|
-
if (issuer !== void 0)
|
|
2670
|
-
presenceCheck.push("iss");
|
|
2671
|
-
for (const claim of new Set(presenceCheck.reverse())) {
|
|
2672
|
-
if (!(claim in payload)) {
|
|
2673
|
-
throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
|
|
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;
|
|
2674
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;
|
|
2675
2856
|
}
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
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;
|
|
2684
2873
|
}
|
|
2685
|
-
let
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
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;
|
|
2698
2888
|
}
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
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);
|
|
2703
2901
|
}
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
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);
|
|
2707
2989
|
}
|
|
2708
|
-
if (
|
|
2709
|
-
|
|
2990
|
+
if (pathname === `${config.authPrefix}/forgot-password`) {
|
|
2991
|
+
return handleForgotPassword(request, ctx);
|
|
2710
2992
|
}
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
if (typeof payload.exp !== "number") {
|
|
2714
|
-
throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
|
|
2993
|
+
if (pathname === `${config.authPrefix}/reset-password`) {
|
|
2994
|
+
return handleResetPassword(request, ctx);
|
|
2715
2995
|
}
|
|
2716
|
-
if (
|
|
2717
|
-
|
|
2996
|
+
if (pathname === `${config.authPrefix}/session`) {
|
|
2997
|
+
return handleSession(request, ctx);
|
|
2718
2998
|
}
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
const age = now - payload.iat;
|
|
2722
|
-
const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
|
|
2723
|
-
if (age - tolerance > max) {
|
|
2724
|
-
throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
|
|
2999
|
+
if (pathname === `${config.authPrefix}/signout`) {
|
|
3000
|
+
return handleSignOut(request, ctx);
|
|
2725
3001
|
}
|
|
2726
|
-
if (
|
|
2727
|
-
|
|
3002
|
+
if (pathname === `${config.authPrefix}/token`) {
|
|
3003
|
+
return handleToken(request, ctx);
|
|
2728
3004
|
}
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
}
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
}
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
}
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
if (hex2) return hexToUuid(hex2);
|
|
2804
|
-
}
|
|
2805
|
-
const hex = b58Decode(enc);
|
|
2806
|
-
if (hex) return hexToUuid(hex);
|
|
2807
|
-
return null;
|
|
2808
|
-
}
|
|
2809
|
-
|
|
2810
|
-
// src/server/index.ts
|
|
2811
|
-
var PLATFORM_TENANT_BAAS_URL = `https://${PLATFORM_CONSOLE_SLUG}.${DEFAULT_SDK_API_HOST}${SDK_API_PATH}`;
|
|
2812
|
-
function isJwksResponse(data) {
|
|
2813
|
-
return typeof data === "object" && data !== null && "keys" in data && Array.isArray(data.keys);
|
|
2814
|
-
}
|
|
2815
|
-
function isAccessTokenPayload(payload) {
|
|
2816
|
-
return typeof payload.sub === "string" && typeof payload.email === "string" && typeof payload.app_id === "string" && typeof payload.iat === "number" && typeof payload.exp === "number";
|
|
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
|
+
};
|
|
2817
3079
|
}
|
|
2818
|
-
var
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
return jwksCache.keys;
|
|
2823
|
-
}
|
|
2824
|
-
const response = await fetch(`${platformUrl}/api/v1/auth/.well-known/jwks.json`);
|
|
2825
|
-
if (!response.ok) {
|
|
2826
|
-
throw new Error("Failed to fetch JWKS");
|
|
2827
|
-
}
|
|
2828
|
-
const data = await response.json();
|
|
2829
|
-
if (!isJwksResponse(data)) {
|
|
2830
|
-
throw new Error("Invalid JWKS response format");
|
|
2831
|
-
}
|
|
2832
|
-
jwksCache = {
|
|
2833
|
-
keys: data.keys,
|
|
2834
|
-
expiresAt: now + JWK_CACHE_TTL_MS
|
|
2835
|
-
// Cache for 1 hour
|
|
3080
|
+
var sylphxMiddleware = createSylphxMiddleware;
|
|
3081
|
+
function createMatcher() {
|
|
3082
|
+
return {
|
|
3083
|
+
matcher: ["/((?!_next|monitoring|.*\\..*).*)", "/"]
|
|
2836
3084
|
};
|
|
2837
|
-
return data.keys;
|
|
2838
3085
|
}
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
const keys = await getJwks(platformUrl);
|
|
2842
|
-
if (!keys.length) {
|
|
2843
|
-
throw new Error("No keys in JWKS");
|
|
2844
|
-
}
|
|
2845
|
-
let lastError = null;
|
|
2846
|
-
for (const key of keys) {
|
|
2847
|
-
try {
|
|
2848
|
-
const jwk = await importJWK(key, "RS256");
|
|
2849
|
-
const { payload } = await jwtVerify(token, jwk, {
|
|
2850
|
-
issuer: platformUrl,
|
|
2851
|
-
...options.audience !== void 0 ? { audience: options.audience } : {}
|
|
2852
|
-
});
|
|
2853
|
-
if (!isAccessTokenPayload(payload)) {
|
|
2854
|
-
throw new Error("Invalid token payload structure");
|
|
2855
|
-
}
|
|
2856
|
-
const cnfRaw = payload.cnf;
|
|
2857
|
-
const cnf = cnfRaw && typeof cnfRaw === "object" && "jkt" in cnfRaw ? { jkt: typeof cnfRaw.jkt === "string" ? cnfRaw.jkt : void 0 } : void 0;
|
|
2858
|
-
return {
|
|
2859
|
-
sub: payload.sub,
|
|
2860
|
-
pid: payload.pid,
|
|
2861
|
-
email: payload.email,
|
|
2862
|
-
name: payload.name,
|
|
2863
|
-
picture: payload.picture,
|
|
2864
|
-
email_verified: payload.email_verified,
|
|
2865
|
-
app_id: payload.app_id,
|
|
2866
|
-
role: payload.role,
|
|
2867
|
-
// Org context — preserved so downstream org-scoped authz works
|
|
2868
|
-
// (ADR-2062). Absent on plain user tokens.
|
|
2869
|
-
org_id: typeof payload.org_id === "string" ? payload.org_id : void 0,
|
|
2870
|
-
org_slug: typeof payload.org_slug === "string" ? payload.org_slug : void 0,
|
|
2871
|
-
org_role: typeof payload.org_role === "string" ? payload.org_role : void 0,
|
|
2872
|
-
iat: payload.iat,
|
|
2873
|
-
exp: payload.exp,
|
|
2874
|
-
...cnf ? { cnf } : {}
|
|
2875
|
-
};
|
|
2876
|
-
} catch (err) {
|
|
2877
|
-
lastError = err;
|
|
2878
|
-
}
|
|
2879
|
-
}
|
|
2880
|
-
throw lastError || new Error("Token verification failed");
|
|
3086
|
+
function getNamespace(secretKey) {
|
|
3087
|
+
return getCookieNamespace(validateAndSanitizeSecretKey(secretKey));
|
|
2881
3088
|
}
|
|
2882
3089
|
|
|
2883
3090
|
// src/nextjs/server.ts
|
|
3091
|
+
import { cache as cache2 } from "react";
|
|
2884
3092
|
function isTokenResponse2(data) {
|
|
2885
3093
|
return typeof data === "object" && data !== null && "accessToken" in data && "refreshToken" in data && "user" in data && typeof data.accessToken === "string" && typeof data.refreshToken === "string";
|
|
2886
3094
|
}
|
|
@@ -2896,13 +3104,20 @@ function configureServer(config) {
|
|
|
2896
3104
|
);
|
|
2897
3105
|
}
|
|
2898
3106
|
const secretKey = validateAndSanitizeSecretKey(rawSecretKey);
|
|
3107
|
+
const platformUrl = resolveNextjsPlatformUrl({
|
|
3108
|
+
explicitPlatformUrl: config.platformUrl,
|
|
3109
|
+
secretKey,
|
|
3110
|
+
secretUrl: config.secretUrl
|
|
3111
|
+
});
|
|
2899
3112
|
serverConfig = {
|
|
2900
3113
|
secretKey,
|
|
2901
|
-
platformUrl
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
3114
|
+
platformUrl,
|
|
3115
|
+
audience: resolveNextjsTokenAudience({
|
|
3116
|
+
explicitAudience: config.audience,
|
|
3117
|
+
platformUrl,
|
|
3118
|
+
secretKey
|
|
3119
|
+
}),
|
|
3120
|
+
issuer: config.issuer?.trim() || DEFAULT_JWT_ISSUER
|
|
2906
3121
|
};
|
|
2907
3122
|
}
|
|
2908
3123
|
function getConfig() {
|
|
@@ -2916,7 +3131,13 @@ function getConfig() {
|
|
|
2916
3131
|
try {
|
|
2917
3132
|
const secretKey = validateAndSanitizeSecretKey(rawSecretKey);
|
|
2918
3133
|
const platformUrl = resolveNextjsPlatformUrl({ secretKey });
|
|
2919
|
-
|
|
3134
|
+
const audience = resolveNextjsTokenAudience({ platformUrl, secretKey });
|
|
3135
|
+
serverConfig = {
|
|
3136
|
+
secretKey,
|
|
3137
|
+
platformUrl,
|
|
3138
|
+
audience,
|
|
3139
|
+
issuer: DEFAULT_JWT_ISSUER
|
|
3140
|
+
};
|
|
2920
3141
|
return serverConfig;
|
|
2921
3142
|
} catch (error) {
|
|
2922
3143
|
console.warn("[Sylphx] Invalid @sylphx/sdk/nextjs server configuration:", error);
|
|
@@ -2935,38 +3156,51 @@ var auth = cache2(async () => {
|
|
|
2935
3156
|
}
|
|
2936
3157
|
const namespace = getCookieNamespace2();
|
|
2937
3158
|
const { sessionToken, refreshToken, user, expiresAt } = await getAuthCookies(namespace);
|
|
2938
|
-
if (!sessionToken
|
|
3159
|
+
if (!sessionToken) {
|
|
3160
|
+
const hydration = resolveHydrationCookieAuthority({
|
|
3161
|
+
hydrationUserId: user?.id ?? null,
|
|
3162
|
+
hydrationExpiresAt: expiresAt,
|
|
3163
|
+
hasRefreshToken: Boolean(refreshToken)
|
|
3164
|
+
});
|
|
3165
|
+
void hydration;
|
|
2939
3166
|
return { userId: null, user: null, sessionToken: null };
|
|
2940
3167
|
}
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
}
|
|
2958
|
-
}
|
|
2959
|
-
if (refreshToken && user && expiresAt) {
|
|
2960
|
-
if (expiresAt > Date.now()) {
|
|
2961
|
-
return {
|
|
2962
|
-
userId: user.id,
|
|
2963
|
-
user,
|
|
2964
|
-
sessionToken: sessionToken || null
|
|
2965
|
-
// May be expired, but user data is valid
|
|
2966
|
-
};
|
|
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 };
|
|
2967
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 };
|
|
2968
3203
|
}
|
|
2969
|
-
return { userId: null, user: null, sessionToken: null };
|
|
2970
3204
|
});
|
|
2971
3205
|
async function currentUser() {
|
|
2972
3206
|
const { user } = await auth();
|