@arcblock/jwt 1.30.25 → 1.31.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/lib/index.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let node_crypto = require("node:crypto");
2
3
  let _arcblock_did = require("@arcblock/did");
3
4
  let _ocap_mcrypto = require("@ocap/mcrypto");
4
5
  let _ocap_util = require("@ocap/util");
@@ -510,17 +511,581 @@ function checkDelegationTokenScope(scope, { ops, deny }) {
510
511
  if (deny && deny.length > 0 && (0, _ocap_util.scopeMatchAny)(scope, deny)) return false;
511
512
  return (0, _ocap_util.scopeMatchAny)(scope, ops);
512
513
  }
514
+ const SD_JWT_HASH_ALG = "sha3-256";
515
+ const MAX_SD_DISCLOSURES = 128;
516
+ const MAX_DECOY_DIGESTS = 32;
517
+ const RESERVED_SD_CLAIM_KEYS = new Set([
518
+ "iss",
519
+ "sub",
520
+ "aud",
521
+ "exp",
522
+ "nbf",
523
+ "iat",
524
+ "version",
525
+ "_sd",
526
+ "_sd_alg",
527
+ "cnf",
528
+ "statusListIndex",
529
+ "statusListCredential"
530
+ ]);
531
+ /**
532
+ * Compute the canonical `sha3-256` digest of a base64url-encoded SD-JWT disclosure `[salt, key, value]`.
533
+ */
534
+ function computeSdJwtDisclosureDigest(disclosureB64u) {
535
+ return (0, _ocap_util.stripHexPrefix)(_ocap_mcrypto.Hasher.SHA3.hash256((0, _ocap_util.toHex)(disclosureB64u))).toLowerCase();
536
+ }
537
+ function encodeDisclosureTuple(salt, key, value) {
538
+ const json = JSON.stringify([
539
+ salt,
540
+ key,
541
+ value
542
+ ]);
543
+ return Buffer.from(json, "utf8").toString("base64url");
544
+ }
545
+ function decodeDisclosureTuple(disclosureB64u) {
546
+ if (!disclosureB64u || !/^[A-Za-z0-9_-]+$/.test(disclosureB64u)) throw new Error("Invalid base64url disclosure format");
547
+ const raw = Buffer.from(disclosureB64u, "base64url").toString("utf8");
548
+ const parsed = JSON.parse(raw);
549
+ if (!Array.isArray(parsed) || parsed.length !== 3 || typeof parsed[0] !== "string" || typeof parsed[1] !== "string") throw new Error("Disclosure must decode to a 3-element [salt, key, value] tuple");
550
+ return [
551
+ parsed[0],
552
+ parsed[1],
553
+ parsed[2]
554
+ ];
555
+ }
556
+ /**
557
+ * Compute the `sd_hash` over `<issuerJwt>~<disclosure1>~...~` bound inside the Holder Key-Binding JWT (`kb-jwt`).
558
+ */
559
+ function computeSdJwtPresentationHash(issuerJwtAndDisclosuresPrefix) {
560
+ return (0, _ocap_util.stripHexPrefix)(_ocap_mcrypto.Hasher.SHA3.hash256((0, _ocap_util.toHex)(issuerJwtAndDisclosuresPrefix))).toLowerCase();
561
+ }
562
+ /**
563
+ * Issue an `SD-JWT` (`<issuerJwt>~<disclosure1>~<disclosure2>~...~`) where sensitive claims
564
+ * listed in `options.selectiveClaims` are replaced by salted `sha3-256` digests in `_sd`.
565
+ */
566
+ async function signSdJwt(issuerDid, issuerSk, claims, options) {
567
+ if (!claims || typeof claims !== "object" || Array.isArray(claims)) throw new Error("claims must be a plain object");
568
+ const selectiveList = options?.selectiveClaims ?? [];
569
+ if (!Array.isArray(selectiveList) || selectiveList.length > MAX_SD_DISCLOSURES) throw new Error(`selectiveClaims must be an array of at most ${MAX_SD_DISCLOSURES} claim names`);
570
+ const decoyCount = options?.decoyCount ?? 0;
571
+ if (!Number.isSafeInteger(decoyCount) || decoyCount < 0 || decoyCount > MAX_DECOY_DIGESTS) throw new Error(`decoyCount must be an integer between 0 and ${MAX_DECOY_DIGESTS}`);
572
+ const selectiveSet = new Set(selectiveList);
573
+ for (const key of selectiveSet) {
574
+ if (RESERVED_SD_CLAIM_KEYS.has(key)) throw new Error(`Claim "${key}" is a reserved JWT claim and cannot be marked selective`);
575
+ if (!(key in claims)) throw new Error(`Selective claim "${key}" does not exist in claims payload`);
576
+ }
577
+ const publicPayload = {};
578
+ for (const [k, v] of Object.entries(claims)) if (!selectiveSet.has(k)) publicPayload[k] = v;
579
+ const disclosures = [];
580
+ const sdDigests = [];
581
+ for (const key of selectiveSet) {
582
+ const salt = options.customSalts?.[key] ?? (0, node_crypto.randomBytes)(16).toString("base64url");
583
+ if (!salt || typeof salt !== "string") throw new Error(`Invalid salt for selective claim "${key}"`);
584
+ const disclosureB64u = encodeDisclosureTuple(salt, key, claims[key]);
585
+ disclosures.push(disclosureB64u);
586
+ sdDigests.push(computeSdJwtDisclosureDigest(disclosureB64u));
587
+ }
588
+ for (let i = 0; i < decoyCount; i++) {
589
+ const decoyMaterial = (0, node_crypto.randomBytes)(32);
590
+ const decoyDigest = (0, _ocap_util.stripHexPrefix)(_ocap_mcrypto.Hasher.SHA3.hash256(decoyMaterial)).toLowerCase();
591
+ sdDigests.push(decoyDigest);
592
+ }
593
+ sdDigests.sort();
594
+ publicPayload._sd = sdDigests;
595
+ publicPayload._sd_alg = SD_JWT_HASH_ALG;
596
+ if (options.holderDid) {
597
+ if (!(0, _arcblock_did.isValid)(options.holderDid)) throw new Error(`Invalid holderDid: ${options.holderDid}`);
598
+ const normalizedHolder = (0, _arcblock_did.toDid)((0, _arcblock_did.toAddress)(options.holderDid), (0, _arcblock_did.extractMethod)(options.holderDid) || "abt");
599
+ publicPayload.sub = publicPayload.sub ?? normalizedHolder;
600
+ publicPayload.cnf = { did: normalizedHolder };
601
+ }
602
+ if (options.statusListIndex !== void 0) {
603
+ if (!Number.isSafeInteger(options.statusListIndex) || options.statusListIndex < 0) throw new Error("statusListIndex must be a non-negative integer");
604
+ publicPayload.statusListIndex = options.statusListIndex;
605
+ }
606
+ if (options.statusListCredential !== void 0) publicPayload.statusListCredential = options.statusListCredential;
607
+ if (options.exp !== void 0) publicPayload.exp = String(options.exp);
608
+ if (options.nbf !== void 0) publicPayload.nbf = String(options.nbf);
609
+ if (options.iat !== void 0) publicPayload.iat = String(options.iat);
610
+ const issuerJwt = await signV2(issuerDid, issuerSk, publicPayload);
611
+ if (disclosures.length === 0) return `${issuerJwt}~`;
612
+ return `${issuerJwt}~${disclosures.join("~")}~`;
613
+ }
614
+ /**
615
+ * Create a selective presentation from an `SD-JWT` revealing ONLY `options.discloseKeys`,
616
+ * and optionally attaching a Holder Key-Binding JWT (`kb-jwt`) bound to `audience`, `nonce`, and `sd_hash`.
617
+ */
618
+ async function presentSdJwt(sdJwtToken, options) {
619
+ if (!sdJwtToken || typeof sdJwtToken !== "string" || !sdJwtToken.includes("~")) throw new Error("Invalid SD-JWT token format");
620
+ const segments = sdJwtToken.split("~");
621
+ const issuerJwt = segments[0];
622
+ if (!issuerJwt) throw new Error("Missing issuer JWT in SD-JWT");
623
+ const rawDisclosures = segments.slice(1, -1).filter((s) => s.length > 0);
624
+ const discloseSet = new Set(options?.discloseKeys ?? []);
625
+ const selectedDisclosures = [];
626
+ for (const disc of rawDisclosures) {
627
+ const [, key] = decodeDisclosureTuple(disc);
628
+ if (discloseSet.has(key)) selectedDisclosures.push(disc);
629
+ }
630
+ const prefix = selectedDisclosures.length > 0 ? `${issuerJwt}~${selectedDisclosures.join("~")}~` : `${issuerJwt}~`;
631
+ if (options.holderDid && options.holderSk) {
632
+ const sdHash = computeSdJwtPresentationHash(prefix);
633
+ const now = options.iat ?? Math.floor(Date.now() / 1e3);
634
+ const kbPayload = {
635
+ typ: "kb+jwt",
636
+ sd_hash: sdHash,
637
+ iat: String(now),
638
+ exp: String(now + 300)
639
+ };
640
+ if (options.audience) kbPayload.aud = options.audience;
641
+ if (options.nonce) kbPayload.nonce = options.nonce;
642
+ return `${prefix}${await signV2(options.holderDid, options.holderSk, kbPayload)}`;
643
+ }
644
+ return prefix;
645
+ }
646
+ /**
647
+ * Verify an `SD-JWT` presentation (`<issuerJwt>~<disclosure1>~...~[<kbJwt>]`).
648
+ *
649
+ * Enforces:
650
+ * 1. Valid issuer signature and timestamp on `<issuerJwt>`;
651
+ * 2. Every presented disclosure hashes to a unique entry in `_sd` (rejects duplicate disclosures or unanchored injections);
652
+ * 3. Disclosed claim keys never collide with reserved or existing top-level claims (prevents claim shadowing);
653
+ * 4. Optional `BitstringStatusList` revocation callback check (`options.isStatusRevoked`);
654
+ * 5. Optional Holder Key-Binding JWT (`kb-jwt`) verification (`sd_hash`, `aud`, `nonce`, and `cnf.did` match).
655
+ */
656
+ async function verifySdJwt(presentation, issuerPk, options = {}) {
657
+ try {
658
+ if (!presentation || typeof presentation !== "string" || !presentation.includes("~")) return {
659
+ valid: false,
660
+ reason: "INVALID_SD_JWT_FORMAT"
661
+ };
662
+ const segments = presentation.split("~");
663
+ const issuerJwt = segments[0];
664
+ const kbJwt = segments[segments.length - 1] || "";
665
+ const disclosureSegments = segments.slice(1, -1).filter((s) => s.length > 0);
666
+ if (disclosureSegments.length > MAX_SD_DISCLOSURES) return {
667
+ valid: false,
668
+ reason: "TOO_MANY_DISCLOSURES"
669
+ };
670
+ if (!await verify(issuerJwt, issuerPk, options)) return {
671
+ valid: false,
672
+ reason: "INVALID_ISSUER_JWT_SIGNATURE_OR_EXPIRY"
673
+ };
674
+ const issuerBody = decode(issuerJwt, true);
675
+ if (issuerBody._sd_alg && issuerBody._sd_alg !== SD_JWT_HASH_ALG) return {
676
+ valid: false,
677
+ reason: `UNSUPPORTED_SD_ALG:${issuerBody._sd_alg}`
678
+ };
679
+ const sdArray = Array.isArray(issuerBody._sd) ? issuerBody._sd.map((d) => String(d).toLowerCase()) : [];
680
+ const sdSet = new Set(sdArray);
681
+ if (options.isStatusRevoked && issuerBody.statusListIndex !== void 0) {
682
+ if (await options.isStatusRevoked(Number(issuerBody.statusListIndex), issuerBody.statusListCredential ? String(issuerBody.statusListCredential) : void 0)) return {
683
+ valid: false,
684
+ reason: "CREDENTIAL_REVOKED_OR_SUSPENDED"
685
+ };
686
+ }
687
+ const seenDigests = /* @__PURE__ */ new Set();
688
+ const disclosedClaims = {};
689
+ for (const disc of disclosureSegments) {
690
+ const digest = computeSdJwtDisclosureDigest(disc);
691
+ if (seenDigests.has(digest)) return {
692
+ valid: false,
693
+ reason: "DUPLICATE_DISCLOSURE_PRESENTED"
694
+ };
695
+ if (!sdSet.has(digest)) return {
696
+ valid: false,
697
+ reason: "DISCLOSURE_DIGEST_NOT_IN_SD"
698
+ };
699
+ seenDigests.add(digest);
700
+ const [, claimKey, claimVal] = decodeDisclosureTuple(disc);
701
+ if (RESERVED_SD_CLAIM_KEYS.has(claimKey) || claimKey in issuerBody || claimKey in disclosedClaims) return {
702
+ valid: false,
703
+ reason: `CLAIM_COLLISION_OR_RESERVED_KEY:${claimKey}`
704
+ };
705
+ disclosedClaims[claimKey] = claimVal;
706
+ }
707
+ const hasCnfBinding = Boolean(issuerBody.cnf?.did);
708
+ const mustVerifyKb = options.requireKeyBinding !== void 0 ? Boolean(options.requireKeyBinding) : hasCnfBinding || options.expectedAudience !== void 0 || options.expectedNonce !== void 0 || kbJwt.length > 0;
709
+ let verifiedHolderDid;
710
+ if (mustVerifyKb) {
711
+ if (!kbJwt) return {
712
+ valid: false,
713
+ reason: "MISSING_KEY_BINDING_JWT"
714
+ };
715
+ if (!options.holderPk) return {
716
+ valid: false,
717
+ reason: "MISSING_HOLDER_PUBLIC_KEY"
718
+ };
719
+ if (!await verify(kbJwt, options.holderPk, {
720
+ enforceTimestamp: options.enforceTimestamp ?? true,
721
+ tolerance: options.tolerance ?? 5,
722
+ audience: options.expectedAudience,
723
+ nonce: options.expectedNonce
724
+ })) return {
725
+ valid: false,
726
+ reason: "INVALID_KEY_BINDING_JWT"
727
+ };
728
+ const kbBody = decode(kbJwt, true);
729
+ const expectedSdHash = computeSdJwtPresentationHash(disclosureSegments.length > 0 ? `${issuerJwt}~${disclosureSegments.join("~")}~` : `${issuerJwt}~`);
730
+ if (String(kbBody.sd_hash || "").toLowerCase() !== expectedSdHash) return {
731
+ valid: false,
732
+ reason: "KEY_BINDING_SD_HASH_MISMATCH"
733
+ };
734
+ const boundHolderDid = issuerBody.cnf?.did || issuerBody.sub;
735
+ if (boundHolderDid && (0, _arcblock_did.toAddress)(String(kbBody.iss)) !== (0, _arcblock_did.toAddress)(String(boundHolderDid))) return {
736
+ valid: false,
737
+ reason: "KEY_BINDING_HOLDER_MISMATCH"
738
+ };
739
+ verifiedHolderDid = String(kbBody.iss);
740
+ }
741
+ const mergedClaims = {
742
+ ...issuerBody,
743
+ ...disclosedClaims
744
+ };
745
+ delete mergedClaims._sd;
746
+ delete mergedClaims._sd_alg;
747
+ return {
748
+ valid: true,
749
+ issuerDid: issuerBody.iss,
750
+ ...verifiedHolderDid ? { holderDid: verifiedHolderDid } : {},
751
+ claims: mergedClaims,
752
+ disclosedClaims,
753
+ issuerBody
754
+ };
755
+ } catch (err) {
756
+ return {
757
+ valid: false,
758
+ reason: err?.message || "SD_JWT_VERIFY_ERROR"
759
+ };
760
+ }
761
+ }
762
+ /**
763
+ * Sign a short-lived `ARC` request/session token for `AFS`, `ArcSpace`, or multi-agent channel actions.
764
+ */
765
+ async function signArcRequestToken(params) {
766
+ const now = Math.floor(Date.now() / 1e3);
767
+ const ttl = params.ttlSeconds ?? 300;
768
+ return signV2(params.signerDid, params.signerSk, {
769
+ ...params.audience ? { aud: params.audience } : {},
770
+ ...params.scope ? { scope: params.scope } : {},
771
+ ...params.nonce ? { nonce: params.nonce } : {},
772
+ ...params.statusListIndex !== void 0 ? { statusListIndex: params.statusListIndex } : {},
773
+ iat: String(now),
774
+ nbf: String(now),
775
+ exp: String(now + ttl)
776
+ });
777
+ }
778
+ function doesJwtAlgMatchKeyType(alg, keyType) {
779
+ if (!alg || typeof alg !== "string") return false;
780
+ const lower = alg.toLowerCase();
781
+ if (keyType === _ocap_mcrypto.types.KeyType.ED25519) return lower === "ed25519";
782
+ if (keyType === _ocap_mcrypto.types.KeyType.SECP256K1) return lower === "es256k" || lower === "secp256k1";
783
+ if (keyType === _ocap_mcrypto.types.KeyType.ETHEREUM) return lower === "ethereum";
784
+ return false;
785
+ }
786
+ /**
787
+ * Verify an `ARC` principal across progressive enforcement modes (`permissive` -> `hybrid` -> `strict`).
788
+ * Designed so `ARC` can seamlessly tighten from unverified DID strings to full cryptographic + delegation + bitmap revocation enforcement.
789
+ */
790
+ async function verifyArcPrincipal(envelope, options = {}) {
791
+ const mode = options.mode ?? "strict";
792
+ const allowLegacyAgentId = options.allowLegacyAgentId ?? true;
793
+ if (!envelope || typeof envelope.principalDid !== "string" || !envelope.principalDid.trim()) return {
794
+ valid: false,
795
+ mode,
796
+ verificationLevel: "rejected",
797
+ reason: "MISSING_PRINCIPAL_DID"
798
+ };
799
+ const rawPrincipal = envelope.principalDid.trim();
800
+ const isChecksumValidDid = (0, _arcblock_did.isValid)(rawPrincipal);
801
+ const isLegacyAgentString = /^did:agent:[a-zA-Z0-9_-]+$/.test(rawPrincipal);
802
+ if (!isChecksumValidDid) {
803
+ if (mode === "permissive" && allowLegacyAgentId && isLegacyAgentString && !envelope.sessionJwt && !envelope.delegationToken && !options.requiredScope) return {
804
+ valid: true,
805
+ mode,
806
+ verificationLevel: "legacy_string",
807
+ principalDid: rawPrincipal,
808
+ warning: "UNVERIFIED_LEGACY_AGENT_DID_STRING_IN_PERMISSIVE_MODE"
809
+ };
810
+ return {
811
+ valid: false,
812
+ mode,
813
+ verificationLevel: "rejected",
814
+ reason: "INVALID_DID_CHECKSUM"
815
+ };
816
+ }
817
+ const canonicalPrincipal = (0, _arcblock_did.toDid)((0, _arcblock_did.toAddress)(rawPrincipal), (0, _arcblock_did.extractMethod)(rawPrincipal) || "abt");
818
+ if (options.isRevokedIndex && envelope.statusListIndex !== void 0) {
819
+ if (await options.isRevokedIndex(envelope.statusListIndex)) return {
820
+ valid: false,
821
+ mode,
822
+ verificationLevel: "rejected",
823
+ reason: "PRINCIPAL_REVOKED_IN_STATUS_LIST"
824
+ };
825
+ }
826
+ if (envelope.delegationToken) {
827
+ if (!await verifyDelegationToken(envelope.delegationToken, { subject: canonicalPrincipal })) return {
828
+ valid: false,
829
+ mode,
830
+ verificationLevel: "rejected",
831
+ reason: "INVALID_DELEGATION_TOKEN"
832
+ };
833
+ const decodedDel = decodeDelegationToken(envelope.delegationToken);
834
+ if (options.isRevokedIndex && decodedDel.body.statusListIndex !== void 0) {
835
+ if (await options.isRevokedIndex(Number(decodedDel.body.statusListIndex))) return {
836
+ valid: false,
837
+ mode,
838
+ verificationLevel: "rejected",
839
+ reason: "DELEGATION_TOKEN_REVOKED_IN_STATUS_LIST"
840
+ };
841
+ }
842
+ if (options.requiredScope && !checkDelegationTokenScope(options.requiredScope, decodedDel.body)) return {
843
+ valid: false,
844
+ mode,
845
+ verificationLevel: "rejected",
846
+ reason: "DELEGATION_SCOPE_DENIED"
847
+ };
848
+ let cursor = decodedDel;
849
+ while (cursor.body.delegation) {
850
+ cursor = decodeDelegationToken(cursor.body.delegation);
851
+ if (options.isRevokedIndex && cursor.body.statusListIndex !== void 0) {
852
+ if (await options.isRevokedIndex(Number(cursor.body.statusListIndex))) return {
853
+ valid: false,
854
+ mode,
855
+ verificationLevel: "rejected",
856
+ reason: "DELEGATION_TOKEN_REVOKED_IN_STATUS_LIST"
857
+ };
858
+ }
859
+ }
860
+ const rootAuthorityDid = (0, _arcblock_did.toDid)((0, _arcblock_did.toAddress)(cursor.body.iss), (0, _arcblock_did.extractMethod)(cursor.body.iss) || "abt");
861
+ if (envelope.sessionJwt) {
862
+ if (!envelope.publicKey) return {
863
+ valid: false,
864
+ mode,
865
+ verificationLevel: "rejected",
866
+ reason: "MISSING_PUBLIC_KEY_FOR_SESSION_JWT"
867
+ };
868
+ if (!await verify(envelope.sessionJwt, envelope.publicKey, {
869
+ audience: options.expectedAudience,
870
+ nonce: options.expectedNonce
871
+ })) return {
872
+ valid: false,
873
+ mode,
874
+ verificationLevel: "rejected",
875
+ reason: "INVALID_DELEGATED_SESSION_JWT"
876
+ };
877
+ const sessBody = decode(envelope.sessionJwt, true);
878
+ if ((0, _arcblock_did.toAddress)(sessBody.iss) !== (0, _arcblock_did.toAddress)(canonicalPrincipal)) return {
879
+ valid: false,
880
+ mode,
881
+ verificationLevel: "rejected",
882
+ reason: "SESSION_JWT_ISSUER_MISMATCH"
883
+ };
884
+ if (options.isRevokedIndex && sessBody.statusListIndex !== void 0) {
885
+ if (await options.isRevokedIndex(Number(sessBody.statusListIndex))) return {
886
+ valid: false,
887
+ mode,
888
+ verificationLevel: "rejected",
889
+ reason: "SESSION_JWT_REVOKED_IN_STATUS_LIST"
890
+ };
891
+ }
892
+ if (options.requiredScope && sessBody.scope !== void 0) {
893
+ const scopes = Array.isArray(sessBody.scope) ? sessBody.scope.map(String) : [String(sessBody.scope)];
894
+ if (!(0, _ocap_util.scopeMatchAny)(options.requiredScope, scopes)) return {
895
+ valid: false,
896
+ mode,
897
+ verificationLevel: "rejected",
898
+ reason: "SESSION_JWT_SCOPE_DENIED"
899
+ };
900
+ }
901
+ }
902
+ return {
903
+ valid: true,
904
+ mode,
905
+ verificationLevel: "delegated_cryptographic",
906
+ principalDid: canonicalPrincipal,
907
+ rootAuthorityDid
908
+ };
909
+ }
910
+ if (envelope.sessionJwt) {
911
+ if (!envelope.publicKey) return {
912
+ valid: false,
913
+ mode,
914
+ verificationLevel: "rejected",
915
+ reason: "MISSING_PUBLIC_KEY_FOR_SESSION_JWT"
916
+ };
917
+ let body;
918
+ if (envelope.keyRotationEvents && envelope.keyRotationEvents.length > 0) {
919
+ const rot = (0, _arcblock_did.verifyKeyRotationChain)({
920
+ did: canonicalPrincipal,
921
+ events: envelope.keyRotationEvents,
922
+ expectedCurrentPublicKey: envelope.publicKey
923
+ });
924
+ if (!rot.valid || rot.activeKeyType === null) return {
925
+ valid: false,
926
+ mode,
927
+ verificationLevel: "rejected",
928
+ reason: `INVALID_KEY_ROTATION:${rot.reason}`
929
+ };
930
+ const parts = envelope.sessionJwt.split(".");
931
+ if (parts.length !== 3) return {
932
+ valid: false,
933
+ mode,
934
+ verificationLevel: "rejected",
935
+ reason: "INVALID_SESSION_JWT"
936
+ };
937
+ const [hB64, bB64] = parts;
938
+ const decoded = decode(envelope.sessionJwt, false);
939
+ body = decoded.body;
940
+ if (!doesJwtAlgMatchKeyType(decoded.header?.alg, rot.activeKeyType)) return {
941
+ valid: false,
942
+ mode,
943
+ verificationLevel: "rejected",
944
+ reason: "SESSION_JWT_ALG_KEY_TYPE_MISMATCH"
945
+ };
946
+ if (!body.iss || (0, _arcblock_did.toAddress)(body.iss) !== (0, _arcblock_did.toAddress)(canonicalPrincipal)) return {
947
+ valid: false,
948
+ mode,
949
+ verificationLevel: "rejected",
950
+ reason: "SESSION_JWT_ISSUER_MISMATCH"
951
+ };
952
+ const now = Math.ceil(Date.now() / 1e3);
953
+ const tolerance = 5;
954
+ const exp = Number(body.exp);
955
+ const iat = body.iat !== void 0 && body.iat !== null ? Number(body.iat) : 0;
956
+ const nbf = body.nbf !== void 0 && body.nbf !== null ? Number(body.nbf) : 0;
957
+ if (!Number.isFinite(exp) || exp <= 0 || exp + tolerance < now) return {
958
+ valid: false,
959
+ mode,
960
+ verificationLevel: "rejected",
961
+ reason: "SESSION_JWT_EXPIRED"
962
+ };
963
+ if (Number.isNaN(iat) || iat && iat > now && iat - now > tolerance) return {
964
+ valid: false,
965
+ mode,
966
+ verificationLevel: "rejected",
967
+ reason: "SESSION_JWT_INVALID_IAT"
968
+ };
969
+ if (Number.isNaN(nbf) || nbf && nbf > now && nbf - now > tolerance) return {
970
+ valid: false,
971
+ mode,
972
+ verificationLevel: "rejected",
973
+ reason: "SESSION_JWT_NOT_BEFORE"
974
+ };
975
+ if (options.expectedAudience !== void 0) {
976
+ const expectedAud = Array.isArray(options.expectedAudience) ? options.expectedAudience : [options.expectedAudience];
977
+ if (!(Array.isArray(body.aud) ? body.aud.map(String) : body.aud ? [String(body.aud)] : []).some((a) => expectedAud.includes(a))) return {
978
+ valid: false,
979
+ mode,
980
+ verificationLevel: "rejected",
981
+ reason: "SESSION_JWT_AUDIENCE_MISMATCH"
982
+ };
983
+ }
984
+ if (options.expectedNonce !== void 0 && body.nonce !== options.expectedNonce) return {
985
+ valid: false,
986
+ mode,
987
+ verificationLevel: "rejected",
988
+ reason: "SESSION_JWT_NONCE_MISMATCH"
989
+ };
990
+ const msgHex = (0, _ocap_util.toHex)(`${hB64}.${bB64}`);
991
+ const version = (body.version ? coerceVersion(body.version) : null) || "";
992
+ const payloadToVerify = version && semverGte(version, JWT_VERSION_REQUIRE_HASH_BEFORE_SIGN) ? hasher(msgHex) : msgHex;
993
+ const sigOk = (0, _ocap_mcrypto.getSigner)(rot.activeKeyType).verify(payloadToVerify, decoded.signature, envelope.publicKey);
994
+ if (typeof sigOk !== "boolean" || sigOk !== true) return {
995
+ valid: false,
996
+ mode,
997
+ verificationLevel: "rejected",
998
+ reason: "INVALID_ROTATED_SESSION_JWT_SIGNATURE"
999
+ };
1000
+ } else {
1001
+ if (!await verify(envelope.sessionJwt, envelope.publicKey, {
1002
+ audience: options.expectedAudience,
1003
+ nonce: options.expectedNonce
1004
+ })) return {
1005
+ valid: false,
1006
+ mode,
1007
+ verificationLevel: "rejected",
1008
+ reason: "INVALID_SESSION_JWT"
1009
+ };
1010
+ body = decode(envelope.sessionJwt, true);
1011
+ if ((0, _arcblock_did.toAddress)(body.iss) !== (0, _arcblock_did.toAddress)(canonicalPrincipal)) return {
1012
+ valid: false,
1013
+ mode,
1014
+ verificationLevel: "rejected",
1015
+ reason: "SESSION_JWT_ISSUER_MISMATCH"
1016
+ };
1017
+ }
1018
+ if (options.isRevokedIndex && body.statusListIndex !== void 0) {
1019
+ if (await options.isRevokedIndex(Number(body.statusListIndex))) return {
1020
+ valid: false,
1021
+ mode,
1022
+ verificationLevel: "rejected",
1023
+ reason: "SESSION_JWT_REVOKED_IN_STATUS_LIST"
1024
+ };
1025
+ }
1026
+ if (options.requiredScope) {
1027
+ if (body.scope === void 0 || body.scope === null) return {
1028
+ valid: false,
1029
+ mode,
1030
+ verificationLevel: "rejected",
1031
+ reason: "SESSION_JWT_SCOPE_DENIED"
1032
+ };
1033
+ const scopes = Array.isArray(body.scope) ? body.scope.map(String) : [String(body.scope)];
1034
+ if (!(0, _ocap_util.scopeMatchAny)(options.requiredScope, scopes)) return {
1035
+ valid: false,
1036
+ mode,
1037
+ verificationLevel: "rejected",
1038
+ reason: "SESSION_JWT_SCOPE_DENIED"
1039
+ };
1040
+ }
1041
+ return {
1042
+ valid: true,
1043
+ mode,
1044
+ verificationLevel: "cryptographic",
1045
+ principalDid: canonicalPrincipal
1046
+ };
1047
+ }
1048
+ if (mode === "strict") return {
1049
+ valid: false,
1050
+ mode,
1051
+ verificationLevel: "rejected",
1052
+ reason: "CRYPTOGRAPHIC_PROOF_REQUIRED_IN_STRICT_MODE"
1053
+ };
1054
+ if (options.requiredScope) return {
1055
+ valid: false,
1056
+ mode,
1057
+ verificationLevel: "rejected",
1058
+ reason: "CRYPTOGRAPHIC_PROOF_REQUIRED_FOR_SCOPE"
1059
+ };
1060
+ return {
1061
+ valid: true,
1062
+ mode,
1063
+ verificationLevel: "checksum_only",
1064
+ principalDid: canonicalPrincipal,
1065
+ warning: `UNVERIFIED_DID_ACCEPTED_IN_${mode.toUpperCase()}_MODE`
1066
+ };
1067
+ }
513
1068
 
514
1069
  //#endregion
1070
+ exports.MAX_DECOY_DIGESTS = MAX_DECOY_DIGESTS;
1071
+ exports.MAX_SD_DISCLOSURES = MAX_SD_DISCLOSURES;
1072
+ exports.SD_JWT_HASH_ALG = SD_JWT_HASH_ALG;
515
1073
  exports.assemble = assemble;
516
1074
  exports.assembleDelegationToken = assembleDelegationToken;
517
1075
  exports.checkDelegationTokenScope = checkDelegationTokenScope;
1076
+ exports.computeSdJwtDisclosureDigest = computeSdJwtDisclosureDigest;
1077
+ exports.computeSdJwtPresentationHash = computeSdJwtPresentationHash;
518
1078
  exports.decode = decode;
519
1079
  exports.decodeDelegationToken = decodeDelegationToken;
520
1080
  exports.getChallenge = getChallenge;
1081
+ exports.presentSdJwt = presentSdJwt;
521
1082
  exports.sign = sign;
1083
+ exports.signArcRequestToken = signArcRequestToken;
522
1084
  exports.signDelegationToken = signDelegationToken;
523
1085
  exports.signDelegationTokenUnsigned = signDelegationTokenUnsigned;
1086
+ exports.signSdJwt = signSdJwt;
524
1087
  exports.signV2 = signV2;
525
1088
  exports.verify = verify;
526
- exports.verifyDelegationToken = verifyDelegationToken;
1089
+ exports.verifyArcPrincipal = verifyArcPrincipal;
1090
+ exports.verifyDelegationToken = verifyDelegationToken;
1091
+ exports.verifySdJwt = verifySdJwt;