@arcblock/jwt 1.33.6 → 1.33.8

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/esm/index.d.mts CHANGED
@@ -41,7 +41,21 @@ type JwtVerifyOptions = Partial<{
41
41
  * @return {*} {string} - hex encoded signature
42
42
  */
43
43
  declare function sign(signer: string, sk?: BytesType, payload?: {}, doSign?: boolean, version?: string): Promise<string>;
44
+ interface ExternalJwtSigningContext {
45
+ readonly header: JwtHeader | DelegationTokenHeader;
46
+ readonly body: JwtBody | DelegationTokenBody;
47
+ readonly unsignedToken: string;
48
+ readonly msgHex: string;
49
+ readonly signingDigestHex: string;
50
+ readonly prehashed: boolean;
51
+ readonly did: string;
52
+ readonly keyType: number;
53
+ readonly version: string;
54
+ }
55
+ type ExternalJwtSignerFn = (signingDigestHex: string, context: ExternalJwtSigningContext) => Promise<string> | string;
56
+ declare function signWithSigner(signer: string, signFn: ExternalJwtSignerFn, payload?: {}, version?: string): Promise<string>;
44
57
  declare function signV2(signer: string, sk?: BytesType, payload?: any): Promise<string>;
58
+ declare function signV2WithSigner(signer: string, signFn: ExternalJwtSignerFn, payload?: any): Promise<string>;
45
59
  type PasskeyAssertion = {
46
60
  authenticatorData: string;
47
61
  clientDataJSON: string;
@@ -131,6 +145,15 @@ declare function signDelegationTokenUnsigned(signer: string, pk: BytesType, payl
131
145
  nbf?: string;
132
146
  exp?: string;
133
147
  }): Promise<string>;
148
+ declare function signDelegationTokenWithSigner(signer: string, pk: BytesType, signFn: ExternalJwtSignerFn, payload: {
149
+ sub: string;
150
+ ops: string[];
151
+ deny?: string[];
152
+ delegation?: string;
153
+ iat?: string;
154
+ nbf?: string;
155
+ exp?: string;
156
+ }): Promise<string>;
134
157
  /**
135
158
  * Assemble a complete delegation token from an unsigned token and a passkey assertion.
136
159
  */
@@ -303,4 +326,4 @@ declare function signArcRequestToken(params: {
303
326
  */
304
327
  declare function verifyArcPrincipal(envelope: ArcPrincipalEnvelope, options?: VerifyArcPrincipalOptions): Promise<ArcPrincipalVerifyResult>;
305
328
  //#endregion
306
- export { ArcEnforcementMode, ArcPrincipalEnvelope, ArcPrincipalVerifyResult, DelegationToken, DelegationTokenBody, DelegationTokenHeader, DelegationVerifyOptions, JwtBody, JwtHeader, JwtToken, JwtVerifyOptions, MAX_DECOY_DIGESTS, MAX_SD_DISCLOSURES, PasskeyAssertion, SD_JWT_HASH_ALG, SdJwtPresentOptions, SdJwtSignOptions, SdJwtVerifyOptions, SdJwtVerifyResult, VerifyArcPrincipalOptions, assemble, assembleDelegationToken, checkDelegationTokenScope, computeSdJwtDisclosureDigest, computeSdJwtPresentationHash, decode, decodeDelegationToken, getChallenge, presentSdJwt, sign, signArcRequestToken, signDelegationToken, signDelegationTokenUnsigned, signSdJwt, signV2, verify, verifyArcPrincipal, verifyDelegationToken, verifySdJwt };
329
+ export { ArcEnforcementMode, ArcPrincipalEnvelope, ArcPrincipalVerifyResult, DelegationToken, DelegationTokenBody, DelegationTokenHeader, DelegationVerifyOptions, ExternalJwtSignerFn, ExternalJwtSigningContext, JwtBody, JwtHeader, JwtToken, JwtVerifyOptions, MAX_DECOY_DIGESTS, MAX_SD_DISCLOSURES, PasskeyAssertion, SD_JWT_HASH_ALG, SdJwtPresentOptions, SdJwtSignOptions, SdJwtVerifyOptions, SdJwtVerifyResult, VerifyArcPrincipalOptions, assemble, assembleDelegationToken, checkDelegationTokenScope, computeSdJwtDisclosureDigest, computeSdJwtPresentationHash, decode, decodeDelegationToken, getChallenge, presentSdJwt, sign, signArcRequestToken, signDelegationToken, signDelegationTokenUnsigned, signDelegationTokenWithSigner, signSdJwt, signV2, signV2WithSigner, signWithSigner, verify, verifyArcPrincipal, verifyDelegationToken, verifySdJwt };
package/esm/index.mjs CHANGED
@@ -1,4 +1,3 @@
1
- import { randomBytes } from "node:crypto";
2
1
  import { extractMethod, isFromPublicKey, isValid, toAddress, toDid, toStrictHex, toTypeInfo, verifyKeyRotationChain } from "@arcblock/did";
3
2
  import { Hasher, getSigner, types } from "@ocap/mcrypto";
4
3
  import { fromBase64, scopeMatchAny, stripHexPrefix, toBase64, toHex } from "@ocap/util";
@@ -7,6 +6,42 @@ import stringify from "fast-json-stable-stringify";
7
6
 
8
7
  //#region src/index.ts
9
8
  const debug = Debug("@arcblock/jwt");
9
+ const jwtTextEncoder = new TextEncoder();
10
+ const jwtTextDecoder = new TextDecoder();
11
+ function csprngBytes(length) {
12
+ const out = new Uint8Array(length);
13
+ globalThis.crypto.getRandomValues(out);
14
+ return out;
15
+ }
16
+ function bytesToHexLower(bytes) {
17
+ let out = "";
18
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
19
+ return out;
20
+ }
21
+ function decodeBase64Utf8(b64) {
22
+ return jwtTextDecoder.decode(Uint8Array.from(fromBase64(b64)));
23
+ }
24
+ const B64U_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
25
+ function bytesToBase64Url(bytes) {
26
+ let out = "";
27
+ let i = 0;
28
+ for (; i + 2 < bytes.length; i += 3) {
29
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
30
+ out += B64U_ALPHABET[n >>> 18 & 63] + B64U_ALPHABET[n >>> 12 & 63] + B64U_ALPHABET[n >>> 6 & 63] + B64U_ALPHABET[n & 63];
31
+ }
32
+ const rem = bytes.length - i;
33
+ if (rem === 1) {
34
+ const n = bytes[i] << 4;
35
+ out += B64U_ALPHABET[n >>> 6 & 63] + B64U_ALPHABET[n & 63];
36
+ } else if (rem === 2) {
37
+ const n = bytes[i] << 10 | bytes[i + 1] << 2;
38
+ out += B64U_ALPHABET[n >>> 12 & 63] + B64U_ALPHABET[n >>> 6 & 63] + B64U_ALPHABET[n & 63];
39
+ }
40
+ return out;
41
+ }
42
+ function base64UrlToBytes(b64u) {
43
+ return Uint8Array.from(fromBase64(b64u));
44
+ }
10
45
  const JWT_VERSION_REQUIRE_HASH_BEFORE_SIGN = "1.1.0";
11
46
  const hasher = Hasher.SHA3.hash256;
12
47
  function coerceVersion(str) {
@@ -82,9 +117,72 @@ async function sign(signer, sk, payload = {}, doSign = true, version = "1.0.0")
82
117
  toBase64(getSigner(type.pk).sign(msgHash, sk))
83
118
  ].join(".");
84
119
  }
120
+ async function signWithSigner(signer, signFn, payload = {}, version = "1.1.0") {
121
+ if (typeof signFn !== "function") throw new Error("signWithSigner requires a signer function");
122
+ if (isValid(signer) === false) throw new Error("Cannot do sign with invalid signer");
123
+ const type = toTypeInfo(signer);
124
+ if (type.pk === void 0) throw new Error("Cannot determine key type from signer");
125
+ const header = {
126
+ [types.KeyType.SECP256K1]: {
127
+ alg: "ES256K",
128
+ type: "JWT"
129
+ },
130
+ [types.KeyType.ED25519]: {
131
+ alg: "Ed25519",
132
+ type: "JWT"
133
+ },
134
+ [types.KeyType.ETHEREUM]: {
135
+ alg: "Ethereum",
136
+ type: "JWT"
137
+ },
138
+ [types.KeyType.PASSKEY]: {
139
+ alg: "Passkey",
140
+ type: "JWT"
141
+ }
142
+ }[type.pk];
143
+ if (!header) throw new Error(`Unsupported key type for JWT signing: ${String(type.pk)}`);
144
+ const headerB64 = toBase64(stringify(header));
145
+ const signerDid = toDid(signer, extractMethod(signer) || "abt");
146
+ const now = Math.floor(Date.now() / 1e3);
147
+ const body = {
148
+ iss: signerDid,
149
+ iat: String(now),
150
+ nbf: String(now),
151
+ exp: String(now + 300),
152
+ version,
153
+ ...payload || {}
154
+ };
155
+ Object.keys(body).forEach((x) => {
156
+ if (typeof body[x] === "undefined" || body[x] == null || body[x] === "") delete body[x];
157
+ });
158
+ const bodyB64 = toBase64(stringify(body));
159
+ const unsignedToken = `${headerB64}.${bodyB64}`;
160
+ const msgHex = toHex(unsignedToken);
161
+ const coercedVersion = coerceVersion(version);
162
+ const prehashed = Boolean(coercedVersion && semverGte(coercedVersion, JWT_VERSION_REQUIRE_HASH_BEFORE_SIGN));
163
+ const signingDigestHex = prehashed ? hasher(msgHex) : msgHex;
164
+ return [
165
+ headerB64,
166
+ bodyB64,
167
+ toBase64(await signFn(signingDigestHex, {
168
+ header,
169
+ body,
170
+ unsignedToken,
171
+ msgHex,
172
+ signingDigestHex,
173
+ prehashed,
174
+ did: signerDid,
175
+ keyType: type.pk,
176
+ version
177
+ }))
178
+ ].join(".");
179
+ }
85
180
  async function signV2(signer, sk, payload = {}) {
86
181
  return sign(signer, sk, payload, !!sk, "1.1.0");
87
182
  }
183
+ async function signV2WithSigner(signer, signFn, payload = {}) {
184
+ return signWithSigner(signer, signFn, payload, "1.1.0");
185
+ }
88
186
  /**
89
187
  * Compute the WebAuthn challenge for an unsigned JWT token.
90
188
  * Always uses SHA3 hash-before-sign (v1.1.0 semantics, required for passkey).
@@ -115,9 +213,9 @@ function decode(token, bodyOnly = true) {
115
213
  const parts = token.split(".");
116
214
  if (parts.length !== 3) throw new Error(`Cannot decode JWT: expected token with exactly 3 parts (header.body.signature), got ${parts.length}`);
117
215
  const [headerB64, bodyB64, sigB64] = parts;
118
- const header = JSON.parse(fromBase64(headerB64).toString());
119
- const body = JSON.parse(fromBase64(bodyB64).toString());
120
- const sig = Buffer.from(Uint8Array.from(fromBase64(sigB64))).toString("hex");
216
+ const header = JSON.parse(decodeBase64Utf8(headerB64));
217
+ const body = JSON.parse(decodeBase64Utf8(bodyB64));
218
+ const sig = bytesToHexLower(Uint8Array.from(fromBase64(sigB64)));
121
219
  if (bodyOnly) return body;
122
220
  return {
123
221
  header,
@@ -251,7 +349,7 @@ async function verify(token, signerPk, options) {
251
349
  const alg = header.alg.toLowerCase();
252
350
  if (alg === "passkey") {
253
351
  const [, , sigB64] = token.split(".");
254
- const assertionRaw = JSON.parse(fromBase64(sigB64).toString());
352
+ const assertionRaw = JSON.parse(decodeBase64Utf8(sigB64));
255
353
  if (!assertionRaw.authenticatorData || !assertionRaw.clientDataJSON || !assertionRaw.signature) {
256
354
  debug("verify.error.incompletePasskeyAssertion");
257
355
  return false;
@@ -363,6 +461,28 @@ async function signDelegationTokenUnsigned(signer, pk, payload) {
363
461
  if (payload.delegation) body.delegation = payload.delegation;
364
462
  return `${headerB64}.${toBase64(stringify(body))}`;
365
463
  }
464
+ async function signDelegationTokenWithSigner(signer, pk, signFn, payload) {
465
+ if (typeof signFn !== "function") throw new Error("signDelegationTokenWithSigner requires a signer function");
466
+ const unsignedToken = await signDelegationTokenUnsigned(signer, pk, payload);
467
+ const type = toTypeInfo(signer);
468
+ if (type.pk === void 0) throw new Error("Cannot determine key type from signer");
469
+ const [headerB64, bodyB64] = unsignedToken.split(".");
470
+ const header = JSON.parse(decodeBase64Utf8(headerB64));
471
+ const body = JSON.parse(decodeBase64Utf8(bodyB64));
472
+ const msgHex = toHex(unsignedToken);
473
+ const signingDigestHex = hasher(msgHex);
474
+ return `${unsignedToken}.${toBase64(await signFn(signingDigestHex, {
475
+ header,
476
+ body,
477
+ unsignedToken,
478
+ msgHex,
479
+ signingDigestHex,
480
+ prehashed: true,
481
+ did: body.iss,
482
+ keyType: type.pk,
483
+ version: DELEGATION_TOKEN_VERSION
484
+ }))}`;
485
+ }
366
486
  /**
367
487
  * Assemble a complete delegation token from an unsigned token and a passkey assertion.
368
488
  */
@@ -377,9 +497,9 @@ function decodeDelegationToken(token) {
377
497
  if (parts.length !== 3) throw new Error("Invalid delegation token format: expected 3 parts");
378
498
  const [headerB64, bodyB64, sigB64] = parts;
379
499
  return {
380
- header: JSON.parse(fromBase64(headerB64).toString()),
381
- body: JSON.parse(fromBase64(bodyB64).toString()),
382
- signature: `0x${toStrictHex(Buffer.from(Uint8Array.from(fromBase64(sigB64))).toString("hex"))}`
500
+ header: JSON.parse(decodeBase64Utf8(headerB64)),
501
+ body: JSON.parse(decodeBase64Utf8(bodyB64)),
502
+ signature: `0x${toStrictHex(bytesToHexLower(Uint8Array.from(fromBase64(sigB64))))}`
383
503
  };
384
504
  }
385
505
  async function verifyDelegationToken(token, options = {}) {
@@ -439,7 +559,7 @@ async function verifyDelegationToken(token, options = {}) {
439
559
  let sigValid = false;
440
560
  if (alg === "passkey") {
441
561
  const [, , sigB64] = token.split(".");
442
- const assertionRaw = JSON.parse(fromBase64(sigB64).toString());
562
+ const assertionRaw = JSON.parse(decodeBase64Utf8(sigB64));
443
563
  if (!assertionRaw.authenticatorData || !assertionRaw.clientDataJSON || !assertionRaw.signature) {
444
564
  debug("delegationToken.verify.error.incompletePasskeyAssertion");
445
565
  return false;
@@ -537,11 +657,11 @@ function encodeDisclosureTuple(salt, key, value) {
537
657
  key,
538
658
  value
539
659
  ]);
540
- return Buffer.from(json, "utf8").toString("base64url");
660
+ return bytesToBase64Url(jwtTextEncoder.encode(json));
541
661
  }
542
662
  function decodeDisclosureTuple(disclosureB64u) {
543
663
  if (!disclosureB64u || !/^[A-Za-z0-9_-]+$/.test(disclosureB64u)) throw new Error("Invalid base64url disclosure format");
544
- const raw = Buffer.from(disclosureB64u, "base64url").toString("utf8");
664
+ const raw = jwtTextDecoder.decode(base64UrlToBytes(disclosureB64u));
545
665
  const parsed = JSON.parse(raw);
546
666
  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");
547
667
  return [
@@ -576,14 +696,14 @@ async function signSdJwt(issuerDid, issuerSk, claims, options) {
576
696
  const disclosures = [];
577
697
  const sdDigests = [];
578
698
  for (const key of selectiveSet) {
579
- const salt = options.customSalts?.[key] ?? randomBytes(16).toString("base64url");
699
+ const salt = options.customSalts?.[key] ?? bytesToBase64Url(csprngBytes(16));
580
700
  if (!salt || typeof salt !== "string") throw new Error(`Invalid salt for selective claim "${key}"`);
581
701
  const disclosureB64u = encodeDisclosureTuple(salt, key, claims[key]);
582
702
  disclosures.push(disclosureB64u);
583
703
  sdDigests.push(computeSdJwtDisclosureDigest(disclosureB64u));
584
704
  }
585
705
  for (let i = 0; i < decoyCount; i++) {
586
- const decoyMaterial = randomBytes(32);
706
+ const decoyMaterial = csprngBytes(32);
587
707
  const decoyDigest = stripHexPrefix(Hasher.SHA3.hash256(decoyMaterial)).toLowerCase();
588
708
  sdDigests.push(decoyDigest);
589
709
  }
@@ -1064,4 +1184,4 @@ async function verifyArcPrincipal(envelope, options = {}) {
1064
1184
  }
1065
1185
 
1066
1186
  //#endregion
1067
- export { MAX_DECOY_DIGESTS, MAX_SD_DISCLOSURES, SD_JWT_HASH_ALG, assemble, assembleDelegationToken, checkDelegationTokenScope, computeSdJwtDisclosureDigest, computeSdJwtPresentationHash, decode, decodeDelegationToken, getChallenge, presentSdJwt, sign, signArcRequestToken, signDelegationToken, signDelegationTokenUnsigned, signSdJwt, signV2, verify, verifyArcPrincipal, verifyDelegationToken, verifySdJwt };
1187
+ export { MAX_DECOY_DIGESTS, MAX_SD_DISCLOSURES, SD_JWT_HASH_ALG, assemble, assembleDelegationToken, checkDelegationTokenScope, computeSdJwtDisclosureDigest, computeSdJwtPresentationHash, decode, decodeDelegationToken, getChallenge, presentSdJwt, sign, signArcRequestToken, signDelegationToken, signDelegationTokenUnsigned, signDelegationTokenWithSigner, signSdJwt, signV2, signV2WithSigner, signWithSigner, verify, verifyArcPrincipal, verifyDelegationToken, verifySdJwt };
package/lib/index.cjs CHANGED
@@ -1,5 +1,4 @@
1
1
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
- let node_crypto = require("node:crypto");
3
2
  let _arcblock_did = require("@arcblock/did");
4
3
  let _ocap_mcrypto = require("@ocap/mcrypto");
5
4
  let _ocap_util = require("@ocap/util");
@@ -10,6 +9,42 @@ fast_json_stable_stringify = require_rolldown_runtime.__toESM(fast_json_stable_s
10
9
 
11
10
  //#region src/index.ts
12
11
  const debug$1 = (0, debug.default)("@arcblock/jwt");
12
+ const jwtTextEncoder = new TextEncoder();
13
+ const jwtTextDecoder = new TextDecoder();
14
+ function csprngBytes(length) {
15
+ const out = new Uint8Array(length);
16
+ globalThis.crypto.getRandomValues(out);
17
+ return out;
18
+ }
19
+ function bytesToHexLower(bytes) {
20
+ let out = "";
21
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
22
+ return out;
23
+ }
24
+ function decodeBase64Utf8(b64) {
25
+ return jwtTextDecoder.decode(Uint8Array.from((0, _ocap_util.fromBase64)(b64)));
26
+ }
27
+ const B64U_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
28
+ function bytesToBase64Url(bytes) {
29
+ let out = "";
30
+ let i = 0;
31
+ for (; i + 2 < bytes.length; i += 3) {
32
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
33
+ out += B64U_ALPHABET[n >>> 18 & 63] + B64U_ALPHABET[n >>> 12 & 63] + B64U_ALPHABET[n >>> 6 & 63] + B64U_ALPHABET[n & 63];
34
+ }
35
+ const rem = bytes.length - i;
36
+ if (rem === 1) {
37
+ const n = bytes[i] << 4;
38
+ out += B64U_ALPHABET[n >>> 6 & 63] + B64U_ALPHABET[n & 63];
39
+ } else if (rem === 2) {
40
+ const n = bytes[i] << 10 | bytes[i + 1] << 2;
41
+ out += B64U_ALPHABET[n >>> 12 & 63] + B64U_ALPHABET[n >>> 6 & 63] + B64U_ALPHABET[n & 63];
42
+ }
43
+ return out;
44
+ }
45
+ function base64UrlToBytes(b64u) {
46
+ return Uint8Array.from((0, _ocap_util.fromBase64)(b64u));
47
+ }
13
48
  const JWT_VERSION_REQUIRE_HASH_BEFORE_SIGN = "1.1.0";
14
49
  const hasher = _ocap_mcrypto.Hasher.SHA3.hash256;
15
50
  function coerceVersion(str) {
@@ -85,9 +120,72 @@ async function sign(signer, sk, payload = {}, doSign = true, version = "1.0.0")
85
120
  (0, _ocap_util.toBase64)((0, _ocap_mcrypto.getSigner)(type.pk).sign(msgHash, sk))
86
121
  ].join(".");
87
122
  }
123
+ async function signWithSigner(signer, signFn, payload = {}, version = "1.1.0") {
124
+ if (typeof signFn !== "function") throw new Error("signWithSigner requires a signer function");
125
+ if ((0, _arcblock_did.isValid)(signer) === false) throw new Error("Cannot do sign with invalid signer");
126
+ const type = (0, _arcblock_did.toTypeInfo)(signer);
127
+ if (type.pk === void 0) throw new Error("Cannot determine key type from signer");
128
+ const header = {
129
+ [_ocap_mcrypto.types.KeyType.SECP256K1]: {
130
+ alg: "ES256K",
131
+ type: "JWT"
132
+ },
133
+ [_ocap_mcrypto.types.KeyType.ED25519]: {
134
+ alg: "Ed25519",
135
+ type: "JWT"
136
+ },
137
+ [_ocap_mcrypto.types.KeyType.ETHEREUM]: {
138
+ alg: "Ethereum",
139
+ type: "JWT"
140
+ },
141
+ [_ocap_mcrypto.types.KeyType.PASSKEY]: {
142
+ alg: "Passkey",
143
+ type: "JWT"
144
+ }
145
+ }[type.pk];
146
+ if (!header) throw new Error(`Unsupported key type for JWT signing: ${String(type.pk)}`);
147
+ const headerB64 = (0, _ocap_util.toBase64)((0, fast_json_stable_stringify.default)(header));
148
+ const signerDid = (0, _arcblock_did.toDid)(signer, (0, _arcblock_did.extractMethod)(signer) || "abt");
149
+ const now = Math.floor(Date.now() / 1e3);
150
+ const body = {
151
+ iss: signerDid,
152
+ iat: String(now),
153
+ nbf: String(now),
154
+ exp: String(now + 300),
155
+ version,
156
+ ...payload || {}
157
+ };
158
+ Object.keys(body).forEach((x) => {
159
+ if (typeof body[x] === "undefined" || body[x] == null || body[x] === "") delete body[x];
160
+ });
161
+ const bodyB64 = (0, _ocap_util.toBase64)((0, fast_json_stable_stringify.default)(body));
162
+ const unsignedToken = `${headerB64}.${bodyB64}`;
163
+ const msgHex = (0, _ocap_util.toHex)(unsignedToken);
164
+ const coercedVersion = coerceVersion(version);
165
+ const prehashed = Boolean(coercedVersion && semverGte(coercedVersion, JWT_VERSION_REQUIRE_HASH_BEFORE_SIGN));
166
+ const signingDigestHex = prehashed ? hasher(msgHex) : msgHex;
167
+ return [
168
+ headerB64,
169
+ bodyB64,
170
+ (0, _ocap_util.toBase64)(await signFn(signingDigestHex, {
171
+ header,
172
+ body,
173
+ unsignedToken,
174
+ msgHex,
175
+ signingDigestHex,
176
+ prehashed,
177
+ did: signerDid,
178
+ keyType: type.pk,
179
+ version
180
+ }))
181
+ ].join(".");
182
+ }
88
183
  async function signV2(signer, sk, payload = {}) {
89
184
  return sign(signer, sk, payload, !!sk, "1.1.0");
90
185
  }
186
+ async function signV2WithSigner(signer, signFn, payload = {}) {
187
+ return signWithSigner(signer, signFn, payload, "1.1.0");
188
+ }
91
189
  /**
92
190
  * Compute the WebAuthn challenge for an unsigned JWT token.
93
191
  * Always uses SHA3 hash-before-sign (v1.1.0 semantics, required for passkey).
@@ -118,9 +216,9 @@ function decode(token, bodyOnly = true) {
118
216
  const parts = token.split(".");
119
217
  if (parts.length !== 3) throw new Error(`Cannot decode JWT: expected token with exactly 3 parts (header.body.signature), got ${parts.length}`);
120
218
  const [headerB64, bodyB64, sigB64] = parts;
121
- const header = JSON.parse((0, _ocap_util.fromBase64)(headerB64).toString());
122
- const body = JSON.parse((0, _ocap_util.fromBase64)(bodyB64).toString());
123
- const sig = Buffer.from(Uint8Array.from((0, _ocap_util.fromBase64)(sigB64))).toString("hex");
219
+ const header = JSON.parse(decodeBase64Utf8(headerB64));
220
+ const body = JSON.parse(decodeBase64Utf8(bodyB64));
221
+ const sig = bytesToHexLower(Uint8Array.from((0, _ocap_util.fromBase64)(sigB64)));
124
222
  if (bodyOnly) return body;
125
223
  return {
126
224
  header,
@@ -254,7 +352,7 @@ async function verify(token, signerPk, options) {
254
352
  const alg = header.alg.toLowerCase();
255
353
  if (alg === "passkey") {
256
354
  const [, , sigB64] = token.split(".");
257
- const assertionRaw = JSON.parse((0, _ocap_util.fromBase64)(sigB64).toString());
355
+ const assertionRaw = JSON.parse(decodeBase64Utf8(sigB64));
258
356
  if (!assertionRaw.authenticatorData || !assertionRaw.clientDataJSON || !assertionRaw.signature) {
259
357
  debug$1("verify.error.incompletePasskeyAssertion");
260
358
  return false;
@@ -366,6 +464,28 @@ async function signDelegationTokenUnsigned(signer, pk, payload) {
366
464
  if (payload.delegation) body.delegation = payload.delegation;
367
465
  return `${headerB64}.${(0, _ocap_util.toBase64)((0, fast_json_stable_stringify.default)(body))}`;
368
466
  }
467
+ async function signDelegationTokenWithSigner(signer, pk, signFn, payload) {
468
+ if (typeof signFn !== "function") throw new Error("signDelegationTokenWithSigner requires a signer function");
469
+ const unsignedToken = await signDelegationTokenUnsigned(signer, pk, payload);
470
+ const type = (0, _arcblock_did.toTypeInfo)(signer);
471
+ if (type.pk === void 0) throw new Error("Cannot determine key type from signer");
472
+ const [headerB64, bodyB64] = unsignedToken.split(".");
473
+ const header = JSON.parse(decodeBase64Utf8(headerB64));
474
+ const body = JSON.parse(decodeBase64Utf8(bodyB64));
475
+ const msgHex = (0, _ocap_util.toHex)(unsignedToken);
476
+ const signingDigestHex = hasher(msgHex);
477
+ return `${unsignedToken}.${(0, _ocap_util.toBase64)(await signFn(signingDigestHex, {
478
+ header,
479
+ body,
480
+ unsignedToken,
481
+ msgHex,
482
+ signingDigestHex,
483
+ prehashed: true,
484
+ did: body.iss,
485
+ keyType: type.pk,
486
+ version: DELEGATION_TOKEN_VERSION
487
+ }))}`;
488
+ }
369
489
  /**
370
490
  * Assemble a complete delegation token from an unsigned token and a passkey assertion.
371
491
  */
@@ -380,9 +500,9 @@ function decodeDelegationToken(token) {
380
500
  if (parts.length !== 3) throw new Error("Invalid delegation token format: expected 3 parts");
381
501
  const [headerB64, bodyB64, sigB64] = parts;
382
502
  return {
383
- header: JSON.parse((0, _ocap_util.fromBase64)(headerB64).toString()),
384
- body: JSON.parse((0, _ocap_util.fromBase64)(bodyB64).toString()),
385
- signature: `0x${(0, _arcblock_did.toStrictHex)(Buffer.from(Uint8Array.from((0, _ocap_util.fromBase64)(sigB64))).toString("hex"))}`
503
+ header: JSON.parse(decodeBase64Utf8(headerB64)),
504
+ body: JSON.parse(decodeBase64Utf8(bodyB64)),
505
+ signature: `0x${(0, _arcblock_did.toStrictHex)(bytesToHexLower(Uint8Array.from((0, _ocap_util.fromBase64)(sigB64))))}`
386
506
  };
387
507
  }
388
508
  async function verifyDelegationToken(token, options = {}) {
@@ -442,7 +562,7 @@ async function verifyDelegationToken(token, options = {}) {
442
562
  let sigValid = false;
443
563
  if (alg === "passkey") {
444
564
  const [, , sigB64] = token.split(".");
445
- const assertionRaw = JSON.parse((0, _ocap_util.fromBase64)(sigB64).toString());
565
+ const assertionRaw = JSON.parse(decodeBase64Utf8(sigB64));
446
566
  if (!assertionRaw.authenticatorData || !assertionRaw.clientDataJSON || !assertionRaw.signature) {
447
567
  debug$1("delegationToken.verify.error.incompletePasskeyAssertion");
448
568
  return false;
@@ -540,11 +660,11 @@ function encodeDisclosureTuple(salt, key, value) {
540
660
  key,
541
661
  value
542
662
  ]);
543
- return Buffer.from(json, "utf8").toString("base64url");
663
+ return bytesToBase64Url(jwtTextEncoder.encode(json));
544
664
  }
545
665
  function decodeDisclosureTuple(disclosureB64u) {
546
666
  if (!disclosureB64u || !/^[A-Za-z0-9_-]+$/.test(disclosureB64u)) throw new Error("Invalid base64url disclosure format");
547
- const raw = Buffer.from(disclosureB64u, "base64url").toString("utf8");
667
+ const raw = jwtTextDecoder.decode(base64UrlToBytes(disclosureB64u));
548
668
  const parsed = JSON.parse(raw);
549
669
  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
670
  return [
@@ -579,14 +699,14 @@ async function signSdJwt(issuerDid, issuerSk, claims, options) {
579
699
  const disclosures = [];
580
700
  const sdDigests = [];
581
701
  for (const key of selectiveSet) {
582
- const salt = options.customSalts?.[key] ?? (0, node_crypto.randomBytes)(16).toString("base64url");
702
+ const salt = options.customSalts?.[key] ?? bytesToBase64Url(csprngBytes(16));
583
703
  if (!salt || typeof salt !== "string") throw new Error(`Invalid salt for selective claim "${key}"`);
584
704
  const disclosureB64u = encodeDisclosureTuple(salt, key, claims[key]);
585
705
  disclosures.push(disclosureB64u);
586
706
  sdDigests.push(computeSdJwtDisclosureDigest(disclosureB64u));
587
707
  }
588
708
  for (let i = 0; i < decoyCount; i++) {
589
- const decoyMaterial = (0, node_crypto.randomBytes)(32);
709
+ const decoyMaterial = csprngBytes(32);
590
710
  const decoyDigest = (0, _ocap_util.stripHexPrefix)(_ocap_mcrypto.Hasher.SHA3.hash256(decoyMaterial)).toLowerCase();
591
711
  sdDigests.push(decoyDigest);
592
712
  }
@@ -1083,8 +1203,11 @@ exports.sign = sign;
1083
1203
  exports.signArcRequestToken = signArcRequestToken;
1084
1204
  exports.signDelegationToken = signDelegationToken;
1085
1205
  exports.signDelegationTokenUnsigned = signDelegationTokenUnsigned;
1206
+ exports.signDelegationTokenWithSigner = signDelegationTokenWithSigner;
1086
1207
  exports.signSdJwt = signSdJwt;
1087
1208
  exports.signV2 = signV2;
1209
+ exports.signV2WithSigner = signV2WithSigner;
1210
+ exports.signWithSigner = signWithSigner;
1088
1211
  exports.verify = verify;
1089
1212
  exports.verifyArcPrincipal = verifyArcPrincipal;
1090
1213
  exports.verifyDelegationToken = verifyDelegationToken;
package/lib/index.d.cts CHANGED
@@ -41,7 +41,21 @@ type JwtVerifyOptions = Partial<{
41
41
  * @return {*} {string} - hex encoded signature
42
42
  */
43
43
  declare function sign(signer: string, sk?: BytesType, payload?: {}, doSign?: boolean, version?: string): Promise<string>;
44
+ interface ExternalJwtSigningContext {
45
+ readonly header: JwtHeader | DelegationTokenHeader;
46
+ readonly body: JwtBody | DelegationTokenBody;
47
+ readonly unsignedToken: string;
48
+ readonly msgHex: string;
49
+ readonly signingDigestHex: string;
50
+ readonly prehashed: boolean;
51
+ readonly did: string;
52
+ readonly keyType: number;
53
+ readonly version: string;
54
+ }
55
+ type ExternalJwtSignerFn = (signingDigestHex: string, context: ExternalJwtSigningContext) => Promise<string> | string;
56
+ declare function signWithSigner(signer: string, signFn: ExternalJwtSignerFn, payload?: {}, version?: string): Promise<string>;
44
57
  declare function signV2(signer: string, sk?: BytesType, payload?: any): Promise<string>;
58
+ declare function signV2WithSigner(signer: string, signFn: ExternalJwtSignerFn, payload?: any): Promise<string>;
45
59
  type PasskeyAssertion = {
46
60
  authenticatorData: string;
47
61
  clientDataJSON: string;
@@ -131,6 +145,15 @@ declare function signDelegationTokenUnsigned(signer: string, pk: BytesType, payl
131
145
  nbf?: string;
132
146
  exp?: string;
133
147
  }): Promise<string>;
148
+ declare function signDelegationTokenWithSigner(signer: string, pk: BytesType, signFn: ExternalJwtSignerFn, payload: {
149
+ sub: string;
150
+ ops: string[];
151
+ deny?: string[];
152
+ delegation?: string;
153
+ iat?: string;
154
+ nbf?: string;
155
+ exp?: string;
156
+ }): Promise<string>;
134
157
  /**
135
158
  * Assemble a complete delegation token from an unsigned token and a passkey assertion.
136
159
  */
@@ -303,4 +326,4 @@ declare function signArcRequestToken(params: {
303
326
  */
304
327
  declare function verifyArcPrincipal(envelope: ArcPrincipalEnvelope, options?: VerifyArcPrincipalOptions): Promise<ArcPrincipalVerifyResult>;
305
328
  //#endregion
306
- export { ArcEnforcementMode, ArcPrincipalEnvelope, ArcPrincipalVerifyResult, DelegationToken, DelegationTokenBody, DelegationTokenHeader, DelegationVerifyOptions, JwtBody, JwtHeader, JwtToken, JwtVerifyOptions, MAX_DECOY_DIGESTS, MAX_SD_DISCLOSURES, PasskeyAssertion, SD_JWT_HASH_ALG, SdJwtPresentOptions, SdJwtSignOptions, SdJwtVerifyOptions, SdJwtVerifyResult, VerifyArcPrincipalOptions, assemble, assembleDelegationToken, checkDelegationTokenScope, computeSdJwtDisclosureDigest, computeSdJwtPresentationHash, decode, decodeDelegationToken, getChallenge, presentSdJwt, sign, signArcRequestToken, signDelegationToken, signDelegationTokenUnsigned, signSdJwt, signV2, verify, verifyArcPrincipal, verifyDelegationToken, verifySdJwt };
329
+ export { ArcEnforcementMode, ArcPrincipalEnvelope, ArcPrincipalVerifyResult, DelegationToken, DelegationTokenBody, DelegationTokenHeader, DelegationVerifyOptions, ExternalJwtSignerFn, ExternalJwtSigningContext, JwtBody, JwtHeader, JwtToken, JwtVerifyOptions, MAX_DECOY_DIGESTS, MAX_SD_DISCLOSURES, PasskeyAssertion, SD_JWT_HASH_ALG, SdJwtPresentOptions, SdJwtSignOptions, SdJwtVerifyOptions, SdJwtVerifyResult, VerifyArcPrincipalOptions, assemble, assembleDelegationToken, checkDelegationTokenScope, computeSdJwtDisclosureDigest, computeSdJwtPresentationHash, decode, decodeDelegationToken, getChallenge, presentSdJwt, sign, signArcRequestToken, signDelegationToken, signDelegationTokenUnsigned, signDelegationTokenWithSigner, signSdJwt, signV2, signV2WithSigner, signWithSigner, verify, verifyArcPrincipal, verifyDelegationToken, verifySdJwt };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@arcblock/jwt",
3
3
  "description": "JSON Web Token variant for arcblock DID solutions",
4
4
  "type": "module",
5
- "version": "1.33.6",
5
+ "version": "1.33.8",
6
6
  "author": {
7
7
  "name": "wangshijun",
8
8
  "email": "shijun@arcblock.io",
@@ -19,9 +19,9 @@
19
19
  "access": "public"
20
20
  },
21
21
  "dependencies": {
22
- "@arcblock/did": "1.33.6",
23
- "@ocap/mcrypto": "1.33.6",
24
- "@ocap/util": "1.33.6",
22
+ "@arcblock/did": "1.33.8",
23
+ "@ocap/mcrypto": "1.33.8",
24
+ "@ocap/util": "1.33.8",
25
25
  "debug": "^4.4.3",
26
26
  "fast-json-stable-stringify": "^2.1.0"
27
27
  },