@lepistabioinformatics/mycelium-sdk 2.0.0 → 2.1.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/README.md +127 -1
- package/dist/chunk-FQWYV2WC.js +1390 -0
- package/dist/chunk-FQWYV2WC.js.map +1 -0
- package/dist/express/index.cjs +696 -3
- package/dist/express/index.cjs.map +1 -1
- package/dist/express/index.d.cts +21 -4
- package/dist/express/index.d.ts +21 -4
- package/dist/express/index.js +36 -3
- package/dist/express/index.js.map +1 -1
- package/dist/fastify/index.cjs +682 -2
- package/dist/fastify/index.cjs.map +1 -1
- package/dist/fastify/index.d.cts +16 -1
- package/dist/fastify/index.d.ts +16 -1
- package/dist/fastify/index.js +21 -2
- package/dist/fastify/index.js.map +1 -1
- package/dist/index.cjs +737 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +149 -3
- package/dist/index.d.ts +149 -3
- package/dist/index.js +81 -3
- package/dist/{profile-CUKBifyR.d.cts → profileSignatureEnforcement-C-bhVkEp.d.cts} +134 -29
- package/dist/{profile-CUKBifyR.d.ts → profileSignatureEnforcement-C-bhVkEp.d.ts} +134 -29
- package/package.json +3 -2
- package/dist/chunk-VPKHPMDS.js +0 -682
- package/dist/chunk-VPKHPMDS.js.map +0 -1
package/dist/express/index.cjs
CHANGED
|
@@ -56,6 +56,22 @@ var ProfileDecodingError = class extends MyceliumError {
|
|
|
56
56
|
this.name = "ProfileDecodingError";
|
|
57
57
|
}
|
|
58
58
|
};
|
|
59
|
+
var PROFILE_SIGNATURE_INVALID_CODE = "MYC_PROFILE_SIGNATURE_INVALID";
|
|
60
|
+
var PROFILE_SIGNATURE_CONFIG_INVALID_CODE = "MYC_PROFILE_SIGNATURE_CONFIG_INVALID";
|
|
61
|
+
var ProfileSignatureConfigurationError = class extends MyceliumError {
|
|
62
|
+
constructor(message) {
|
|
63
|
+
super(message, PROFILE_SIGNATURE_CONFIG_INVALID_CODE, false);
|
|
64
|
+
this.name = "ProfileSignatureConfigurationError";
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
var ProfileSignatureError = class extends MyceliumError {
|
|
68
|
+
reason;
|
|
69
|
+
constructor(reason) {
|
|
70
|
+
super(`Profile signature rejected: ${reason}`, PROFILE_SIGNATURE_INVALID_CODE, true);
|
|
71
|
+
this.name = "ProfileSignatureError";
|
|
72
|
+
this.reason = reason;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
59
75
|
|
|
60
76
|
// src/functions/decodeAndDecompressProfileFromBase64.ts
|
|
61
77
|
var import_node_zlib = require("zlib");
|
|
@@ -93,7 +109,10 @@ var Permission = {
|
|
|
93
109
|
};
|
|
94
110
|
var PermissionSchema = import_zod2.z.union([
|
|
95
111
|
import_zod2.z.literal(0),
|
|
96
|
-
import_zod2.z.literal(1)
|
|
112
|
+
import_zod2.z.literal(1),
|
|
113
|
+
// Rust serializes Permission with serde rename_all = camelCase.
|
|
114
|
+
import_zod2.z.literal("read").transform(() => Permission.READ),
|
|
115
|
+
import_zod2.z.literal("write").transform(() => Permission.WRITE)
|
|
97
116
|
]);
|
|
98
117
|
function permissionToInt(permission) {
|
|
99
118
|
return permission;
|
|
@@ -316,7 +335,7 @@ var ProfileSchema = import_zod9.z.object({
|
|
|
316
335
|
accountWasApproved: import_zod9.z.boolean(),
|
|
317
336
|
accountWasArchived: import_zod9.z.boolean(),
|
|
318
337
|
accountWasDeleted: import_zod9.z.boolean(),
|
|
319
|
-
verboseStatus: VerboseStatusSchema.
|
|
338
|
+
verboseStatus: VerboseStatusSchema.nullish(),
|
|
320
339
|
licensedResources: LicensedResourcesSchema.optional(),
|
|
321
340
|
tenantsOwnership: TenantsOwnershipSchema.optional(),
|
|
322
341
|
meta: ProfileMetaSchema.optional(),
|
|
@@ -628,8 +647,672 @@ function formatZodError(error) {
|
|
|
628
647
|
|
|
629
648
|
// src/settings.ts
|
|
630
649
|
var DEFAULT_PROFILE_KEY = "x-mycelium-profile";
|
|
650
|
+
var DEFAULT_PROFILE_SIGNATURE_KEY = "x-mycelium-profile-signature";
|
|
651
|
+
var PROFILE_JWKS_URL_ENV = "MYCELIUM_JWKS_URL";
|
|
652
|
+
var PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV = "MYCELIUM_JWKS_ALLOW_INSECURE_HTTP";
|
|
653
|
+
var PROFILE_JWKS_PATH = "/.well-known/mycelium-profile-jwks.json";
|
|
654
|
+
var PROFILE_JWKS_FETCH_TIMEOUT_SECONDS = 5;
|
|
655
|
+
var PROFILE_JWKS_MAX_BYTES = 64 * 1024;
|
|
656
|
+
var PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS = 30;
|
|
657
|
+
var PROFILE_JWKS_EMPTY_RETRY_SECONDS = 5;
|
|
658
|
+
var PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS = 43200;
|
|
659
|
+
var PROFILE_JWKS_MIN_MAX_AGE_SECONDS = 60;
|
|
660
|
+
var PROFILE_JWKS_MAX_MAX_AGE_SECONDS = 86400;
|
|
661
|
+
var PROFILE_JWKS_MAX_STALE_SECONDS = 86400;
|
|
662
|
+
var PROFILE_SIGNATURE_TOLERANCE_ENV = "MYC_PROFILE_SIGNATURE_TOLERANCE_SECONDS";
|
|
663
|
+
var PROFILE_SIGNATURE_AUDIENCE_ENV = "MYC_PROFILE_SIGNATURE_AUDIENCE";
|
|
664
|
+
var DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS = 60;
|
|
665
|
+
var MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS = 300;
|
|
666
|
+
var MAX_PROFILE_SIGNATURE_BYTES = 4096;
|
|
667
|
+
|
|
668
|
+
// src/jwks/parseProfileJwks.ts
|
|
669
|
+
var import_node_crypto = require("crypto");
|
|
670
|
+
|
|
671
|
+
// src/profileSignatureVerifier.ts
|
|
672
|
+
var CANONICAL_POSITIVE_INTEGER = /^[1-9][0-9]*$/;
|
|
673
|
+
var MAX_KEY_VERSION = 4294967295;
|
|
674
|
+
var ProfileSignatureVerifier = class {
|
|
675
|
+
#keys;
|
|
676
|
+
toleranceSeconds;
|
|
677
|
+
expectedAudience;
|
|
678
|
+
constructor(keys, toleranceSeconds, expectedAudience) {
|
|
679
|
+
this.#keys = new Map(keys);
|
|
680
|
+
this.toleranceSeconds = toleranceSeconds;
|
|
681
|
+
this.expectedAudience = expectedAudience;
|
|
682
|
+
Object.freeze(this);
|
|
683
|
+
}
|
|
684
|
+
keyFor(kid) {
|
|
685
|
+
return this.#keys.get(kid);
|
|
686
|
+
}
|
|
687
|
+
get keyVersions() {
|
|
688
|
+
return [...this.#keys.keys()].sort();
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
function isCanonicalKeyVersion(raw) {
|
|
692
|
+
return CANONICAL_POSITIVE_INTEGER.test(raw) && Number(raw) <= MAX_KEY_VERSION;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// src/jwks/parseProfileJwks.ts
|
|
696
|
+
var JWKS = "profile JWKS";
|
|
697
|
+
var BASE64URL = /^[A-Za-z0-9_-]+$/;
|
|
698
|
+
var ED25519_PUBLIC_KEY_BYTES = 32;
|
|
699
|
+
function invalid(problem) {
|
|
700
|
+
return new ProfileSignatureConfigurationError(`${JWKS} ${problem}`);
|
|
701
|
+
}
|
|
702
|
+
function isObject(value) {
|
|
703
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
704
|
+
}
|
|
705
|
+
function expectMember(jwk, name, expected, required) {
|
|
706
|
+
if (!(name in jwk) && !required) return;
|
|
707
|
+
if (jwk[name] !== expected) {
|
|
708
|
+
throw invalid(`entry member ${name} must be ${expected}`);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
function readKid(jwk) {
|
|
712
|
+
const kid = jwk.kid;
|
|
713
|
+
if (typeof kid !== "string" || !isCanonicalKeyVersion(kid)) {
|
|
714
|
+
throw invalid("entry kid must be a canonical positive integer");
|
|
715
|
+
}
|
|
716
|
+
return kid;
|
|
717
|
+
}
|
|
718
|
+
function readX(jwk) {
|
|
719
|
+
const x = jwk.x;
|
|
720
|
+
const isKey = typeof x === "string" && BASE64URL.test(x) && Buffer.from(x, "base64url").length === ED25519_PUBLIC_KEY_BYTES && Buffer.from(x, "base64url").toString("base64url") === x;
|
|
721
|
+
if (!isKey) throw invalid("entry x must be a 32-byte Base64URL key");
|
|
722
|
+
return x;
|
|
723
|
+
}
|
|
724
|
+
function importEntry(entry) {
|
|
725
|
+
if (!isObject(entry)) throw invalid("entry is not a JSON object");
|
|
726
|
+
if ("d" in entry) throw invalid("entry carries private key material (d)");
|
|
727
|
+
expectMember(entry, "kty", "OKP", true);
|
|
728
|
+
expectMember(entry, "crv", "Ed25519", true);
|
|
729
|
+
expectMember(entry, "use", "sig", false);
|
|
730
|
+
expectMember(entry, "alg", "EdDSA", false);
|
|
731
|
+
const kid = readKid(entry);
|
|
732
|
+
const x = readX(entry);
|
|
733
|
+
try {
|
|
734
|
+
const key = (0, import_node_crypto.createPublicKey)({
|
|
735
|
+
key: { kty: "OKP", crv: "Ed25519", x },
|
|
736
|
+
format: "jwk"
|
|
737
|
+
});
|
|
738
|
+
return [kid, key];
|
|
739
|
+
} catch {
|
|
740
|
+
throw invalid("entry x is not an Ed25519 key");
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
function parseProfileJwks(document) {
|
|
744
|
+
let parsed;
|
|
745
|
+
try {
|
|
746
|
+
parsed = JSON.parse(document);
|
|
747
|
+
} catch {
|
|
748
|
+
throw invalid("is not JSON");
|
|
749
|
+
}
|
|
750
|
+
const entries = isObject(parsed) ? parsed.keys : void 0;
|
|
751
|
+
if (!Array.isArray(entries) || entries.length === 0) {
|
|
752
|
+
throw invalid("has no keys array");
|
|
753
|
+
}
|
|
754
|
+
const keys = /* @__PURE__ */ new Map();
|
|
755
|
+
for (const entry of entries) {
|
|
756
|
+
const [kid, key] = importEntry(entry);
|
|
757
|
+
if (keys.has(kid)) throw invalid("has a duplicated kid");
|
|
758
|
+
keys.set(kid, key);
|
|
759
|
+
}
|
|
760
|
+
return keys;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
// src/jwks/readJwksCacheMaxAge.ts
|
|
764
|
+
var UNSIGNED_INTEGER = /^\+?[0-9]+$/;
|
|
765
|
+
var U64_MAX = 18446744073709551615n;
|
|
766
|
+
function readMaxAgeDirective(directive) {
|
|
767
|
+
const separator = directive.indexOf("=");
|
|
768
|
+
if (separator < 0) return void 0;
|
|
769
|
+
const name = directive.slice(0, separator).trim().toLowerCase();
|
|
770
|
+
const value = directive.slice(separator + 1).trim();
|
|
771
|
+
if (name !== "max-age" || !UNSIGNED_INTEGER.test(value)) return void 0;
|
|
772
|
+
const seconds = BigInt(value);
|
|
773
|
+
if (seconds > U64_MAX) return void 0;
|
|
774
|
+
return seconds > BigInt(PROFILE_JWKS_MAX_MAX_AGE_SECONDS) ? PROFILE_JWKS_MAX_MAX_AGE_SECONDS : Number(seconds);
|
|
775
|
+
}
|
|
776
|
+
function readJwksCacheMaxAge(cacheControl) {
|
|
777
|
+
let announced;
|
|
778
|
+
for (const directive of (cacheControl ?? "").split(",")) {
|
|
779
|
+
announced = readMaxAgeDirective(directive);
|
|
780
|
+
if (announced !== void 0) break;
|
|
781
|
+
}
|
|
782
|
+
const seconds = announced ?? PROFILE_JWKS_DEFAULT_MAX_AGE_SECONDS;
|
|
783
|
+
return Math.min(
|
|
784
|
+
Math.max(seconds, PROFILE_JWKS_MIN_MAX_AGE_SECONDS),
|
|
785
|
+
PROFILE_JWKS_MAX_MAX_AGE_SECONDS
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// src/jwks/fetchProfileJwks.ts
|
|
790
|
+
var ProfileJwksFetchError = class extends Error {
|
|
791
|
+
constructor(problem) {
|
|
792
|
+
super(`profile_jwks_fetch_failed: ${problem}`);
|
|
793
|
+
this.name = "ProfileJwksFetchError";
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
async function readBounded(response) {
|
|
797
|
+
const declared = Number(response.headers.get("content-length") ?? "0");
|
|
798
|
+
if (declared > PROFILE_JWKS_MAX_BYTES) {
|
|
799
|
+
throw new ProfileJwksFetchError("body exceeds the size limit");
|
|
800
|
+
}
|
|
801
|
+
const chunks = [];
|
|
802
|
+
let total = 0;
|
|
803
|
+
for await (const chunk of response.body ?? []) {
|
|
804
|
+
total += chunk.byteLength;
|
|
805
|
+
if (total > PROFILE_JWKS_MAX_BYTES) {
|
|
806
|
+
throw new ProfileJwksFetchError("body exceeds the size limit");
|
|
807
|
+
}
|
|
808
|
+
chunks.push(chunk);
|
|
809
|
+
}
|
|
810
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
811
|
+
}
|
|
812
|
+
async function download(url) {
|
|
813
|
+
try {
|
|
814
|
+
return await fetch(url, {
|
|
815
|
+
method: "GET",
|
|
816
|
+
headers: { accept: "application/json" },
|
|
817
|
+
redirect: "manual",
|
|
818
|
+
signal: AbortSignal.timeout(PROFILE_JWKS_FETCH_TIMEOUT_SECONDS * 1e3)
|
|
819
|
+
});
|
|
820
|
+
} catch (error) {
|
|
821
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
822
|
+
throw new ProfileJwksFetchError(`request failed: ${detail}`);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
var fetchProfileJwks = async (url) => {
|
|
826
|
+
const response = await download(url);
|
|
827
|
+
if (response.status < 200 || response.status > 299) {
|
|
828
|
+
await response.body?.cancel();
|
|
829
|
+
throw new ProfileJwksFetchError(`status ${response.status}`);
|
|
830
|
+
}
|
|
831
|
+
const maxAgeSeconds = readJwksCacheMaxAge(response.headers.get("cache-control"));
|
|
832
|
+
let body;
|
|
833
|
+
try {
|
|
834
|
+
body = await readBounded(response);
|
|
835
|
+
} catch (error) {
|
|
836
|
+
await response.body?.cancel().catch(() => void 0);
|
|
837
|
+
if (error instanceof ProfileJwksFetchError) throw error;
|
|
838
|
+
throw new ProfileJwksFetchError("body unreadable");
|
|
839
|
+
}
|
|
840
|
+
return { keys: parseProfileJwks(body), maxAgeSeconds };
|
|
841
|
+
};
|
|
842
|
+
|
|
843
|
+
// src/functions/verifyProfileSignature.ts
|
|
844
|
+
var import_node_crypto2 = require("crypto");
|
|
845
|
+
var import_jose = require("jose");
|
|
846
|
+
var import_zod10 = require("zod");
|
|
847
|
+
var FORBIDDEN_HEADER_MEMBERS = ["crit", "b64", "jku", "jwk", "x5u", "x5c"];
|
|
848
|
+
var ENCODED_DIGEST_LENGTH = 43;
|
|
849
|
+
function reject(reason) {
|
|
850
|
+
return new ProfileSignatureError(reason);
|
|
851
|
+
}
|
|
852
|
+
function isCanonicalHash(value) {
|
|
853
|
+
if (value.length !== ENCODED_DIGEST_LENGTH) return false;
|
|
854
|
+
const raw = Buffer.from(value, "base64url");
|
|
855
|
+
return raw.length === 32 && raw.toString("base64url") === value;
|
|
856
|
+
}
|
|
857
|
+
var claimsSchema = import_zod10.z.object({
|
|
858
|
+
iat: import_zod10.z.number().refine((value) => Number.isSafeInteger(value) && value >= 0),
|
|
859
|
+
ph: import_zod10.z.string().refine(isCanonicalHash),
|
|
860
|
+
aud: import_zod10.z.string().refine((value) => value.trim() !== "")
|
|
861
|
+
});
|
|
862
|
+
function decodeSegment(segment) {
|
|
863
|
+
try {
|
|
864
|
+
const value = JSON.parse(
|
|
865
|
+
Buffer.from(segment, "base64url").toString("utf8")
|
|
866
|
+
);
|
|
867
|
+
const isObject2 = typeof value === "object" && value !== null && !Array.isArray(value);
|
|
868
|
+
return isObject2 ? value : void 0;
|
|
869
|
+
} catch {
|
|
870
|
+
return void 0;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
function splitToken(signatureHeader) {
|
|
874
|
+
if (signatureHeader === "") throw reject("missing_signature");
|
|
875
|
+
const parts = signatureHeader.split(".");
|
|
876
|
+
const oversized = Buffer.byteLength(signatureHeader, "utf8") > MAX_PROFILE_SIGNATURE_BYTES;
|
|
877
|
+
if (oversized || parts.length !== 3) throw reject("malformed_signature");
|
|
878
|
+
return parts;
|
|
879
|
+
}
|
|
880
|
+
function selectKey(header, verifier) {
|
|
881
|
+
if (header.alg !== "EdDSA") throw reject("unsupported_algorithm");
|
|
882
|
+
const hasForbidden = FORBIDDEN_HEADER_MEMBERS.some((member) => member in header);
|
|
883
|
+
if (hasForbidden) throw reject("malformed_signature");
|
|
884
|
+
const kid = header.kid;
|
|
885
|
+
const key = typeof kid === "string" && isCanonicalKeyVersion(kid) ? verifier.keyFor(kid) : void 0;
|
|
886
|
+
if (key === void 0) throw reject("unknown_key");
|
|
887
|
+
return key;
|
|
888
|
+
}
|
|
889
|
+
async function verifyJws(token, key) {
|
|
890
|
+
try {
|
|
891
|
+
const { payload } = await (0, import_jose.compactVerify)(token, key, {
|
|
892
|
+
algorithms: ["EdDSA"]
|
|
893
|
+
});
|
|
894
|
+
return payload;
|
|
895
|
+
} catch (error) {
|
|
896
|
+
if (error instanceof import_jose.errors.JWSSignatureVerificationFailed) {
|
|
897
|
+
throw reject("invalid_signature");
|
|
898
|
+
}
|
|
899
|
+
throw reject("malformed_signature");
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
function parseClaims(payload) {
|
|
903
|
+
let decoded;
|
|
904
|
+
try {
|
|
905
|
+
decoded = JSON.parse(Buffer.from(payload).toString("utf8"));
|
|
906
|
+
} catch {
|
|
907
|
+
throw reject("invalid_claims");
|
|
908
|
+
}
|
|
909
|
+
const parsed = claimsSchema.safeParse(decoded);
|
|
910
|
+
if (!parsed.success) throw reject("invalid_claims");
|
|
911
|
+
return parsed.data;
|
|
912
|
+
}
|
|
913
|
+
function resolveNow(nowSeconds) {
|
|
914
|
+
const now = nowSeconds ?? Math.floor(Date.now() / 1e3);
|
|
915
|
+
if (!Number.isSafeInteger(now) || now < 0) {
|
|
916
|
+
throw new RangeError("Verifier clock is outside the safe integer range");
|
|
917
|
+
}
|
|
918
|
+
return now;
|
|
919
|
+
}
|
|
920
|
+
function profileHeaderHash(profileHeader) {
|
|
921
|
+
return (0, import_node_crypto2.createHash)("sha256").update(profileHeader, "utf8").digest("base64url");
|
|
922
|
+
}
|
|
923
|
+
function sameHash(received, expected) {
|
|
924
|
+
const left = Buffer.from(received, "utf8");
|
|
925
|
+
const right = Buffer.from(expected, "utf8");
|
|
926
|
+
return left.length === right.length && (0, import_node_crypto2.timingSafeEqual)(left, right);
|
|
927
|
+
}
|
|
928
|
+
function checkClaims(claims, profileHeader, verifier, now) {
|
|
929
|
+
if (Math.abs(now - claims.iat) > verifier.toleranceSeconds) {
|
|
930
|
+
throw reject("timestamp_out_of_tolerance");
|
|
931
|
+
}
|
|
932
|
+
if (!sameHash(claims.ph, profileHeaderHash(profileHeader))) {
|
|
933
|
+
throw reject("profile_hash_mismatch");
|
|
934
|
+
}
|
|
935
|
+
const expected = verifier.expectedAudience;
|
|
936
|
+
if (expected !== void 0 && claims.aud !== expected) {
|
|
937
|
+
throw reject("audience_mismatch");
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
async function verifyProfileSignature(profileHeader, signatureHeader, verifier, nowSeconds) {
|
|
941
|
+
if (profileHeader === "") throw reject("missing_profile");
|
|
942
|
+
const parts = splitToken(signatureHeader);
|
|
943
|
+
const header = decodeSegment(parts[0] ?? "");
|
|
944
|
+
if (header === void 0) throw reject("malformed_signature");
|
|
945
|
+
const key = selectKey(header, verifier);
|
|
946
|
+
const payload = await verifyJws(signatureHeader, key);
|
|
947
|
+
const claims = parseClaims(payload);
|
|
948
|
+
checkClaims(claims, profileHeader, verifier, resolveNow(nowSeconds));
|
|
949
|
+
}
|
|
950
|
+
async function verifyAndDecodeProfile(profileHeader, signatureHeader, verifier, nowSeconds) {
|
|
951
|
+
await verifyProfileSignature(profileHeader, signatureHeader, verifier, nowSeconds);
|
|
952
|
+
try {
|
|
953
|
+
return decodeAndDecompressProfileFromBase64(profileHeader);
|
|
954
|
+
} catch {
|
|
955
|
+
throw reject("invalid_profile");
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// src/jwks/readSignatureKeyVersion.ts
|
|
960
|
+
function readSignatureKeyVersion(signatureHeader) {
|
|
961
|
+
const protectedHeader = signatureHeader.split(".")[0] ?? "";
|
|
962
|
+
try {
|
|
963
|
+
const header = JSON.parse(
|
|
964
|
+
Buffer.from(protectedHeader, "base64url").toString("utf8")
|
|
965
|
+
);
|
|
966
|
+
const kid = typeof header === "object" && header !== null ? header.kid : void 0;
|
|
967
|
+
return typeof kid === "string" && isCanonicalKeyVersion(kid) ? kid : void 0;
|
|
968
|
+
} catch {
|
|
969
|
+
return void 0;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// src/jwks/jwksProfileSignatureVerifier.ts
|
|
974
|
+
var JwksProfileSignatureVerifier = class {
|
|
975
|
+
store;
|
|
976
|
+
toleranceSeconds;
|
|
977
|
+
expectedAudience;
|
|
978
|
+
constructor(store, toleranceSeconds, expectedAudience) {
|
|
979
|
+
this.store = store;
|
|
980
|
+
this.toleranceSeconds = toleranceSeconds;
|
|
981
|
+
this.expectedAudience = expectedAudience;
|
|
982
|
+
Object.freeze(this);
|
|
983
|
+
}
|
|
984
|
+
/** Download the key set before serving; rejects when it cannot. */
|
|
985
|
+
prefetch() {
|
|
986
|
+
return this.store.prefetch();
|
|
987
|
+
}
|
|
988
|
+
/**
|
|
989
|
+
* Verify the signed profile, refetching the JWKS once on an unknown,
|
|
990
|
+
* canonical `kid`. Rejects with `ProfileSignatureError` like
|
|
991
|
+
* `verifyAndDecodeProfile`.
|
|
992
|
+
*/
|
|
993
|
+
async verifyAndDecode(profileHeader, signatureHeader, nowSeconds) {
|
|
994
|
+
await this.store.refreshIfStale();
|
|
995
|
+
const { generation } = this.store.current();
|
|
996
|
+
try {
|
|
997
|
+
return await this.#verifyWithCurrentKeys(profileHeader, signatureHeader, nowSeconds);
|
|
998
|
+
} catch (error) {
|
|
999
|
+
const deservesRefetch = error instanceof ProfileSignatureError && error.reason === "unknown_key" && readSignatureKeyVersion(signatureHeader) !== void 0;
|
|
1000
|
+
if (!deservesRefetch) throw error;
|
|
1001
|
+
if (!await this.store.refreshAfterUnknownKey(generation)) throw error;
|
|
1002
|
+
}
|
|
1003
|
+
return this.#verifyWithCurrentKeys(profileHeader, signatureHeader, nowSeconds);
|
|
1004
|
+
}
|
|
1005
|
+
#verifyWithCurrentKeys(profileHeader, signatureHeader, nowSeconds) {
|
|
1006
|
+
const verifier = new ProfileSignatureVerifier(
|
|
1007
|
+
this.store.current().keys,
|
|
1008
|
+
this.toleranceSeconds,
|
|
1009
|
+
this.expectedAudience
|
|
1010
|
+
);
|
|
1011
|
+
return verifyAndDecodeProfile(profileHeader, signatureHeader, verifier, nowSeconds);
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
|
|
1015
|
+
// src/jwks/parseProfileJwksUrl.ts
|
|
1016
|
+
function invalid2(problem) {
|
|
1017
|
+
return new ProfileSignatureConfigurationError(
|
|
1018
|
+
`${PROFILE_JWKS_URL_ENV} ${problem}`
|
|
1019
|
+
);
|
|
1020
|
+
}
|
|
1021
|
+
function withDefaultScheme(configured) {
|
|
1022
|
+
if (configured.includes("://")) return configured;
|
|
1023
|
+
if (configured === "" || configured.startsWith("/")) {
|
|
1024
|
+
throw invalid2("is not an absolute URL");
|
|
1025
|
+
}
|
|
1026
|
+
return `https://${configured}`;
|
|
1027
|
+
}
|
|
1028
|
+
function checkScheme(url, allowInsecureHttp) {
|
|
1029
|
+
if (url.protocol === "https:") return;
|
|
1030
|
+
if (url.protocol === "http:" && allowInsecureHttp) {
|
|
1031
|
+
console.warn(
|
|
1032
|
+
`[mycelium-sdk] ${PROFILE_JWKS_URL_ENV} uses plain HTTP; development only`
|
|
1033
|
+
);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
throw invalid2("must use https");
|
|
1037
|
+
}
|
|
1038
|
+
function withJwksPath(url) {
|
|
1039
|
+
if (url.pathname.endsWith(PROFILE_JWKS_PATH)) return url;
|
|
1040
|
+
if (/[?#]/.test(url.href)) {
|
|
1041
|
+
throw invalid2("must not carry a query or fragment");
|
|
1042
|
+
}
|
|
1043
|
+
try {
|
|
1044
|
+
return new URL(`${url.href.replace(/\/+$/, "")}${PROFILE_JWKS_PATH}`);
|
|
1045
|
+
} catch {
|
|
1046
|
+
throw invalid2("is not an absolute URL");
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
function parseProfileJwksUrl(raw, allowInsecureHttp) {
|
|
1050
|
+
let url;
|
|
1051
|
+
try {
|
|
1052
|
+
url = new URL(withDefaultScheme(raw.trim()));
|
|
1053
|
+
} catch (error) {
|
|
1054
|
+
if (error instanceof ProfileSignatureConfigurationError) throw error;
|
|
1055
|
+
throw invalid2("is not an absolute URL");
|
|
1056
|
+
}
|
|
1057
|
+
if (url.username !== "" || url.password !== "") {
|
|
1058
|
+
throw invalid2("must not carry credentials");
|
|
1059
|
+
}
|
|
1060
|
+
checkScheme(url, allowInsecureHttp);
|
|
1061
|
+
return withJwksPath(url);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// src/jwks/profileKeyStore.ts
|
|
1065
|
+
var systemClock = () => performance.now();
|
|
1066
|
+
var ProfileKeyStore = class {
|
|
1067
|
+
#url;
|
|
1068
|
+
#fetcher;
|
|
1069
|
+
#cooldownMs;
|
|
1070
|
+
#clock;
|
|
1071
|
+
#keys = /* @__PURE__ */ new Map();
|
|
1072
|
+
#generation = 0;
|
|
1073
|
+
#freshUntil;
|
|
1074
|
+
#lastAttempt;
|
|
1075
|
+
#inFlight;
|
|
1076
|
+
constructor(url, fetcher, cooldownSeconds, clock = systemClock) {
|
|
1077
|
+
this.#url = url;
|
|
1078
|
+
this.#fetcher = fetcher;
|
|
1079
|
+
this.#cooldownMs = cooldownSeconds * 1e3;
|
|
1080
|
+
this.#clock = clock;
|
|
1081
|
+
}
|
|
1082
|
+
get url() {
|
|
1083
|
+
return new URL(this.#url);
|
|
1084
|
+
}
|
|
1085
|
+
/** The trusted keys now, and the generation they belong to. */
|
|
1086
|
+
current() {
|
|
1087
|
+
return { keys: this.#trustedKeys(), generation: this.#generation };
|
|
1088
|
+
}
|
|
1089
|
+
/** The cached keys, or none once they outlived the maximum staleness. */
|
|
1090
|
+
#trustedKeys() {
|
|
1091
|
+
const outlived = this.#freshUntil !== void 0 && this.#clock() >= this.#freshUntil + PROFILE_JWKS_MAX_STALE_SECONDS * 1e3;
|
|
1092
|
+
return outlived ? /* @__PURE__ */ new Map() : this.#keys;
|
|
1093
|
+
}
|
|
1094
|
+
/** Fetch the set now; any failure rejects (startup must abort). */
|
|
1095
|
+
async prefetch() {
|
|
1096
|
+
await this.#inFlight?.catch(() => void 0);
|
|
1097
|
+
const fetching = this.#fetchAndStore();
|
|
1098
|
+
this.#inFlight = fetching.then(
|
|
1099
|
+
() => true,
|
|
1100
|
+
() => false
|
|
1101
|
+
);
|
|
1102
|
+
try {
|
|
1103
|
+
await fetching;
|
|
1104
|
+
} finally {
|
|
1105
|
+
this.#inFlight = void 0;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
/** Refresh when the cached set expired (or was never fetched). */
|
|
1109
|
+
async refreshIfStale() {
|
|
1110
|
+
const stale = this.#freshUntil === void 0 || this.#clock() >= this.#freshUntil;
|
|
1111
|
+
if (!stale) return;
|
|
1112
|
+
if (this.#generation > 0 && this.#inFlight !== void 0) return;
|
|
1113
|
+
await this.#refreshFrom(this.#generation);
|
|
1114
|
+
}
|
|
1115
|
+
/** Refetch after an unknown `kid`; `true` when newer keys are available. */
|
|
1116
|
+
refreshAfterUnknownKey(seenGeneration) {
|
|
1117
|
+
return this.#refreshFrom(seenGeneration);
|
|
1118
|
+
}
|
|
1119
|
+
async #refreshFrom(seenGeneration) {
|
|
1120
|
+
while (this.#inFlight !== void 0) {
|
|
1121
|
+
await this.#inFlight.catch(() => void 0);
|
|
1122
|
+
}
|
|
1123
|
+
if (this.#generation !== seenGeneration) return true;
|
|
1124
|
+
const coolingDown = this.#lastAttempt !== void 0 && this.#clock() - this.#lastAttempt < this.#retryIntervalMs();
|
|
1125
|
+
if (coolingDown) return false;
|
|
1126
|
+
this.#inFlight = this.#fetchAndStore().then(
|
|
1127
|
+
() => true,
|
|
1128
|
+
(error) => {
|
|
1129
|
+
logRefreshFailure(error);
|
|
1130
|
+
return false;
|
|
1131
|
+
}
|
|
1132
|
+
);
|
|
1133
|
+
try {
|
|
1134
|
+
return await this.#inFlight;
|
|
1135
|
+
} finally {
|
|
1136
|
+
this.#inFlight = void 0;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
/** The cooldown, shortened while no key set was ever stored. */
|
|
1140
|
+
#retryIntervalMs() {
|
|
1141
|
+
if (this.#generation > 0) return this.#cooldownMs;
|
|
1142
|
+
return Math.min(this.#cooldownMs, PROFILE_JWKS_EMPTY_RETRY_SECONDS * 1e3);
|
|
1143
|
+
}
|
|
1144
|
+
async #fetchAndStore() {
|
|
1145
|
+
let fetched;
|
|
1146
|
+
try {
|
|
1147
|
+
fetched = await this.#fetcher(new URL(this.#url));
|
|
1148
|
+
} finally {
|
|
1149
|
+
this.#lastAttempt = this.#clock();
|
|
1150
|
+
}
|
|
1151
|
+
this.#keys = new Map(fetched.keys);
|
|
1152
|
+
this.#generation += 1;
|
|
1153
|
+
this.#freshUntil = this.#clock() + fetched.maxAgeSeconds * 1e3;
|
|
1154
|
+
}
|
|
1155
|
+
};
|
|
1156
|
+
function logRefreshFailure(error) {
|
|
1157
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
1158
|
+
console.warn(
|
|
1159
|
+
`[mycelium-sdk] profile_signature.jwks outcome=refresh_failed reason=${reason}; keeping the last valid profile JWKS`
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
// src/profileSignatureConfig.ts
|
|
1164
|
+
var CANONICAL_POSITIVE_INTEGER2 = /^[1-9][0-9]*$/;
|
|
1165
|
+
function parseTolerance(env) {
|
|
1166
|
+
const raw = env[PROFILE_SIGNATURE_TOLERANCE_ENV];
|
|
1167
|
+
if (raw === void 0) return DEFAULT_PROFILE_SIGNATURE_TOLERANCE_SECONDS;
|
|
1168
|
+
const trimmed = raw.trim();
|
|
1169
|
+
const value = Number(trimmed);
|
|
1170
|
+
if (!CANONICAL_POSITIVE_INTEGER2.test(trimmed) || !(value <= MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS)) {
|
|
1171
|
+
throw new ProfileSignatureConfigurationError(
|
|
1172
|
+
`${PROFILE_SIGNATURE_TOLERANCE_ENV} must be an integer between 1 and ${MAX_PROFILE_SIGNATURE_TOLERANCE_SECONDS}`
|
|
1173
|
+
);
|
|
1174
|
+
}
|
|
1175
|
+
return value;
|
|
1176
|
+
}
|
|
1177
|
+
function parseAudience(env) {
|
|
1178
|
+
const raw = env[PROFILE_SIGNATURE_AUDIENCE_ENV];
|
|
1179
|
+
if (raw === void 0) return void 0;
|
|
1180
|
+
if (raw.trim() === "") {
|
|
1181
|
+
throw new ProfileSignatureConfigurationError(
|
|
1182
|
+
`${PROFILE_SIGNATURE_AUDIENCE_ENV} must not be empty`
|
|
1183
|
+
);
|
|
1184
|
+
}
|
|
1185
|
+
return raw;
|
|
1186
|
+
}
|
|
1187
|
+
function parseInsecureSwitch(env) {
|
|
1188
|
+
const raw = env[PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV]?.trim();
|
|
1189
|
+
if (raw === void 0 || raw === "false") return false;
|
|
1190
|
+
if (raw === "true") return true;
|
|
1191
|
+
throw new ProfileSignatureConfigurationError(
|
|
1192
|
+
`${PROFILE_JWKS_ALLOW_INSECURE_HTTP_ENV} must be true or false`
|
|
1193
|
+
);
|
|
1194
|
+
}
|
|
1195
|
+
function loadProfileSignatureVerifierFromEnv(env = process.env, fetcher = fetchProfileJwks) {
|
|
1196
|
+
const toleranceSeconds = parseTolerance(env);
|
|
1197
|
+
const audience = parseAudience(env);
|
|
1198
|
+
const allowInsecureHttp = parseInsecureSwitch(env);
|
|
1199
|
+
const rawUrl = env[PROFILE_JWKS_URL_ENV];
|
|
1200
|
+
if (rawUrl === void 0) return void 0;
|
|
1201
|
+
const url = parseProfileJwksUrl(rawUrl, allowInsecureHttp);
|
|
1202
|
+
if (audience === void 0) {
|
|
1203
|
+
throw new ProfileSignatureConfigurationError(
|
|
1204
|
+
`${PROFILE_SIGNATURE_AUDIENCE_ENV} is required when ${PROFILE_JWKS_URL_ENV} is set`
|
|
1205
|
+
);
|
|
1206
|
+
}
|
|
1207
|
+
const store = new ProfileKeyStore(
|
|
1208
|
+
url,
|
|
1209
|
+
fetcher,
|
|
1210
|
+
PROFILE_JWKS_REFETCH_COOLDOWN_SECONDS
|
|
1211
|
+
);
|
|
1212
|
+
return new JwksProfileSignatureVerifier(store, toleranceSeconds, audience);
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
// src/profileSignatureEnforcement.ts
|
|
1216
|
+
var SIGNATURE_REJECTION_DETAIL = "Unable to verify Mycelium profile";
|
|
1217
|
+
var SIGNATURE_INTERNAL_DETAIL = "Unable to check user identity. Please contact administrators";
|
|
1218
|
+
async function reportRejection(listener, reason) {
|
|
1219
|
+
try {
|
|
1220
|
+
await listener?.(reason);
|
|
1221
|
+
return true;
|
|
1222
|
+
} catch {
|
|
1223
|
+
return false;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
function singleValue(values, missingReason) {
|
|
1227
|
+
if (values !== void 0 && values.length > 1) {
|
|
1228
|
+
throw new ProfileSignatureError("duplicate_header");
|
|
1229
|
+
}
|
|
1230
|
+
const value = values?.[0];
|
|
1231
|
+
if (value === void 0 || value === "") {
|
|
1232
|
+
throw new ProfileSignatureError(missingReason);
|
|
1233
|
+
}
|
|
1234
|
+
return value;
|
|
1235
|
+
}
|
|
1236
|
+
function receivedValues(message, name) {
|
|
1237
|
+
const distinct = message.headersDistinct?.[name];
|
|
1238
|
+
if (distinct !== void 0) return distinct;
|
|
1239
|
+
const raw = message.rawHeaders;
|
|
1240
|
+
if (Array.isArray(raw) && raw.length > 0) {
|
|
1241
|
+
const values = raw.filter(
|
|
1242
|
+
(_value, index) => index % 2 === 1 && String(raw[index - 1]).toLowerCase() === name
|
|
1243
|
+
);
|
|
1244
|
+
return values.length === 0 ? void 0 : values;
|
|
1245
|
+
}
|
|
1246
|
+
const value = message.headers[name];
|
|
1247
|
+
if (value === void 0) return void 0;
|
|
1248
|
+
return Array.isArray(value) ? value : [value];
|
|
1249
|
+
}
|
|
1250
|
+
function distinctValues(message, name) {
|
|
1251
|
+
return receivedValues(message, name)?.flatMap(
|
|
1252
|
+
(value) => value.split(",").map((part) => part.trim())
|
|
1253
|
+
);
|
|
1254
|
+
}
|
|
1255
|
+
async function verifyRequestProfile(message, verifier, onRejected) {
|
|
1256
|
+
try {
|
|
1257
|
+
const profileHeader = singleValue(
|
|
1258
|
+
distinctValues(message, DEFAULT_PROFILE_KEY),
|
|
1259
|
+
"missing_profile"
|
|
1260
|
+
);
|
|
1261
|
+
const signatureHeader = singleValue(
|
|
1262
|
+
distinctValues(message, DEFAULT_PROFILE_SIGNATURE_KEY),
|
|
1263
|
+
"missing_signature"
|
|
1264
|
+
);
|
|
1265
|
+
const profile = await verifier.verifyAndDecode(
|
|
1266
|
+
profileHeader,
|
|
1267
|
+
signatureHeader
|
|
1268
|
+
);
|
|
1269
|
+
return { ok: true, profile };
|
|
1270
|
+
} catch (error) {
|
|
1271
|
+
if (error instanceof ProfileSignatureError) {
|
|
1272
|
+
if (!await reportRejection(onRejected, error.reason)) {
|
|
1273
|
+
return { ok: false, status: 500, detail: SIGNATURE_INTERNAL_DETAIL };
|
|
1274
|
+
}
|
|
1275
|
+
return { ok: false, status: 403, detail: SIGNATURE_REJECTION_DETAIL };
|
|
1276
|
+
}
|
|
1277
|
+
await reportRejection(onRejected, "internal_error");
|
|
1278
|
+
return { ok: false, status: 500, detail: SIGNATURE_INTERNAL_DETAIL };
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
var unverifiedSignatureWarned = false;
|
|
1282
|
+
function warnWhenSignatureIsIgnored(message) {
|
|
1283
|
+
if (unverifiedSignatureWarned) return;
|
|
1284
|
+
if (message.headers[DEFAULT_PROFILE_SIGNATURE_KEY] === void 0) return;
|
|
1285
|
+
unverifiedSignatureWarned = true;
|
|
1286
|
+
console.warn(
|
|
1287
|
+
"[mycelium-sdk] profile_signature.verify outcome=skipped: received a signed profile but MYCELIUM_JWKS_URL is not set; the signature is not verified"
|
|
1288
|
+
);
|
|
1289
|
+
}
|
|
1290
|
+
var sharedVerifier;
|
|
1291
|
+
function sharedProfileSignatureVerifier() {
|
|
1292
|
+
sharedVerifier ??= loadProfileSignatureVerifierFromEnv();
|
|
1293
|
+
return sharedVerifier;
|
|
1294
|
+
}
|
|
631
1295
|
|
|
632
1296
|
// src/express/index.ts
|
|
1297
|
+
function resolveVerifier(opts) {
|
|
1298
|
+
return opts.signatureVerifier ?? sharedProfileSignatureVerifier();
|
|
1299
|
+
}
|
|
1300
|
+
function signatureEnforcingHandler(verifier, onRejected) {
|
|
1301
|
+
return (req, res, next) => {
|
|
1302
|
+
verifyRequestProfile(req, verifier, onRejected).then((outcome) => {
|
|
1303
|
+
if (!outcome.ok) {
|
|
1304
|
+
res.status(outcome.status).json({ detail: outcome.detail });
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
req.profile = outcome.profile;
|
|
1308
|
+
next();
|
|
1309
|
+
}).catch(() => {
|
|
1310
|
+
if (!res.headersSent) {
|
|
1311
|
+
res.status(500).json({ detail: SIGNATURE_INTERNAL_DETAIL });
|
|
1312
|
+
}
|
|
1313
|
+
});
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
633
1316
|
function resolveEnvironment(opts) {
|
|
634
1317
|
return opts?.environment ?? process.env.NODE_ENV ?? "development";
|
|
635
1318
|
}
|
|
@@ -639,7 +1322,12 @@ function extractHeaderValue(req) {
|
|
|
639
1322
|
return value;
|
|
640
1323
|
}
|
|
641
1324
|
function profileMiddleware(opts = {}) {
|
|
1325
|
+
const verifier = resolveVerifier(opts);
|
|
1326
|
+
if (verifier !== void 0) {
|
|
1327
|
+
return signatureEnforcingHandler(verifier, opts.onSignatureRejected);
|
|
1328
|
+
}
|
|
642
1329
|
return (req, res, next) => {
|
|
1330
|
+
warnWhenSignatureIsIgnored(req);
|
|
643
1331
|
try {
|
|
644
1332
|
const isDev = resolveEnvironment(opts) === "development";
|
|
645
1333
|
const headerValue = extractHeaderValue(req);
|
|
@@ -674,8 +1362,13 @@ function profileMiddleware(opts = {}) {
|
|
|
674
1362
|
}
|
|
675
1363
|
};
|
|
676
1364
|
}
|
|
677
|
-
function getProfileFromHeaderRequired() {
|
|
1365
|
+
function getProfileFromHeaderRequired(opts = {}) {
|
|
1366
|
+
const verifier = resolveVerifier(opts);
|
|
1367
|
+
if (verifier !== void 0) {
|
|
1368
|
+
return signatureEnforcingHandler(verifier, opts.onSignatureRejected);
|
|
1369
|
+
}
|
|
678
1370
|
return (req, res, next) => {
|
|
1371
|
+
warnWhenSignatureIsIgnored(req);
|
|
679
1372
|
try {
|
|
680
1373
|
const headerValue = extractHeaderValue(req);
|
|
681
1374
|
if (headerValue === void 0) {
|