@oneaddress/partner-sdk 1.7.0 → 2.0.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.
@@ -3178,6 +3178,64 @@ function isSafeWebhookUrl(url, opts2 = {}) {
3178
3178
  return { ok: true };
3179
3179
  }
3180
3180
 
3181
+ // ../crypto/src/endpoint-health.ts
3182
+ var ENDPOINT_FAILURE_THRESHOLD = 3;
3183
+ var MISSING_STATUSES = /* @__PURE__ */ new Set([404, 405, 410]);
3184
+ function classifyEndpointProbe(input) {
3185
+ const status = typeof input.httpStatus === "number" && Number.isFinite(input.httpStatus) ? input.httpStatus : null;
3186
+ if (status === null || status === 0) {
3187
+ const detail = input.error ? `: ${input.error}` : "";
3188
+ return {
3189
+ health: "unreachable",
3190
+ dispatchable: false,
3191
+ summary: `No response from the endpoint${detail}. Check the host is running and reachable.`
3192
+ };
3193
+ }
3194
+ if (status >= 200 && status < 300) {
3195
+ return {
3196
+ health: "healthy",
3197
+ dispatchable: true,
3198
+ summary: `Receiver accepted a signed test request (HTTP ${status}).`
3199
+ };
3200
+ }
3201
+ if (status === 401 || status === 403) {
3202
+ return {
3203
+ health: "auth",
3204
+ dispatchable: false,
3205
+ summary: `Receiver rejected our signature (HTTP ${status}). Check the signing secret matches on both sides.`
3206
+ };
3207
+ }
3208
+ if (MISSING_STATUSES.has(status)) {
3209
+ return {
3210
+ health: "missing",
3211
+ dispatchable: false,
3212
+ summary: `Host answered but no receiver is listening at this path (HTTP ${status}). A stopped tunnel or a stale URL looks exactly like this.`
3213
+ };
3214
+ }
3215
+ if (status === 429) {
3216
+ return {
3217
+ health: "throttled",
3218
+ dispatchable: false,
3219
+ summary: `Receiver is up and rate-limiting us (HTTP 429). Back off and retry, or raise the ceiling; nothing is wrong with the URL.`
3220
+ };
3221
+ }
3222
+ if (status >= 500) {
3223
+ return {
3224
+ health: "degraded",
3225
+ dispatchable: false,
3226
+ summary: `Receiver is present but erroring (HTTP ${status}).`
3227
+ };
3228
+ }
3229
+ return {
3230
+ health: "rejected",
3231
+ dispatchable: false,
3232
+ summary: `Receiver refused the request (HTTP ${status}).`
3233
+ };
3234
+ }
3235
+ function countsAsFailure(verdict) {
3236
+ return !verdict.dispatchable;
3237
+ }
3238
+
3181
3239
  // ../crypto/src/partner-key-attestation.ts
3182
3240
  var PARTNER_KEY_ATTESTATION_V1 = "oneaddress-partner-key-attestation:v1";
3183
3241
  var PARTNER_KEY_ATTESTATION_ALG = "ECDSA-P256";
@@ -3259,6 +3317,8 @@ async function verifyPartnerKeyAttestationWithRoots(input, signatureHex, rootKey
3259
3317
 
3260
3318
  // ../crypto/src/registry-head.ts
3261
3319
  var REGISTRY_HEAD_V1 = "oneaddress-partner-key-registry-head:v1";
3320
+ var REGISTRY_HEAD_V2 = "oneaddress-partner-key-registry-head:v2";
3321
+ var KNOWN_VERSIONS = /* @__PURE__ */ new Set([REGISTRY_HEAD_V1, REGISTRY_HEAD_V2]);
3262
3322
  var REGISTRY_HEAD_ALG = "ECDSA-P256";
3263
3323
  function assertNoLineBreak(field, value) {
3264
3324
  if (typeof value !== "string" || value.length === 0) {
@@ -3275,6 +3335,9 @@ function assertMapSafe(field, value) {
3275
3335
  }
3276
3336
  }
3277
3337
  function buildRegistryHeadStatement(payload) {
3338
+ if (!KNOWN_VERSIONS.has(payload.version)) {
3339
+ throw new Error(`[registry-head] unknown head version: ${String(payload.version)}`);
3340
+ }
3278
3341
  assertNoLineBreak("issued_at", payload.issued_at);
3279
3342
  assertNoLineBreak("expires_at", payload.expires_at);
3280
3343
  assertMapSafe("root_key_id", payload.root_key_id);
@@ -3291,14 +3354,42 @@ function buildRegistryHeadStatement(payload) {
3291
3354
  }
3292
3355
  seen.add(partnerId);
3293
3356
  }
3294
- return [
3295
- REGISTRY_HEAD_V1,
3357
+ const lines = [
3358
+ payload.version,
3296
3359
  `issued_at:${payload.issued_at}`,
3297
3360
  `expires_at:${payload.expires_at}`,
3298
3361
  `root_key_id:${payload.root_key_id}`,
3299
3362
  `heads:${entries.length}`,
3300
3363
  ...entries.map(([partnerId, keyId]) => `${partnerId}:${keyId}`)
3301
- ].join("\n");
3364
+ ];
3365
+ if (payload.version === REGISTRY_HEAD_V1) {
3366
+ if (payload.staged && Object.keys(payload.staged).length > 0) {
3367
+ throw new Error("[registry-head] v1 statement cannot carry staged entries");
3368
+ }
3369
+ return lines.join("\n");
3370
+ }
3371
+ const stagedEntries = Object.entries(payload.staged ?? {}).map(([partnerId, entry]) => {
3372
+ assertMapSafe("staged partner_id", partnerId);
3373
+ assertMapSafe("staged key_id", entry?.key_id);
3374
+ assertMapSafe("staged key_sha256", entry?.key_sha256);
3375
+ if (!/^[0-9a-f]{64}$/i.test(entry.key_sha256)) {
3376
+ throw new Error(`[registry-head] staged key_sha256 must be 64 hex chars: ${partnerId}`);
3377
+ }
3378
+ return [partnerId.toLowerCase(), entry.key_id.toLowerCase(), entry.key_sha256.toLowerCase()];
3379
+ });
3380
+ stagedEntries.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
3381
+ const stagedSeen = /* @__PURE__ */ new Set();
3382
+ for (const [partnerId] of stagedEntries) {
3383
+ if (stagedSeen.has(partnerId)) {
3384
+ throw new Error(`[registry-head] duplicate partner_id in staged: ${partnerId}`);
3385
+ }
3386
+ stagedSeen.add(partnerId);
3387
+ }
3388
+ lines.push(`staged:${stagedEntries.length}`);
3389
+ for (const [partnerId, keyId, digest] of stagedEntries) {
3390
+ lines.push(`${partnerId}:${keyId}:${digest}`);
3391
+ }
3392
+ return lines.join("\n");
3302
3393
  }
3303
3394
  function b64ToBytes2(b64) {
3304
3395
  const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
@@ -3319,7 +3410,7 @@ function hexToBytes4(hex) {
3319
3410
  }
3320
3411
  async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date()) {
3321
3412
  try {
3322
- if (doc?.version !== REGISTRY_HEAD_V1) return "malformed";
3413
+ if (!doc || !KNOWN_VERSIONS.has(doc.version)) return "malformed";
3323
3414
  if (doc.algorithm !== REGISTRY_HEAD_ALG) return "malformed";
3324
3415
  if (typeof doc.signature !== "string" || !/^[0-9a-f]{128}$/i.test(doc.signature)) return "malformed";
3325
3416
  if (!doc.heads || typeof doc.heads !== "object") return "malformed";
@@ -3334,7 +3425,14 @@ async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date())
3334
3425
  issued_at: doc.issued_at,
3335
3426
  expires_at: doc.expires_at,
3336
3427
  root_key_id: doc.root_key_id,
3337
- heads: doc.heads
3428
+ heads: doc.heads,
3429
+ // Passed through rather than dropped: the staged map is part of what the
3430
+ // root signed on a v2 head, so omitting it here would rebuild different
3431
+ // bytes and report `bad-signature` on a perfectly good document. On a v1
3432
+ // head the builder REFUSES a non-empty map, which lands here as
3433
+ // `malformed` — the right answer for a document claiming staged keys its
3434
+ // signature does not cover.
3435
+ staged: doc.staged
3338
3436
  });
3339
3437
  const rootKey = await crypto.subtle.importKey(
3340
3438
  "spki",
@@ -3360,6 +3458,27 @@ function headNamesKey(doc, partnerId, keyId) {
3360
3458
  const named = doc.heads?.[partnerId.toLowerCase()];
3361
3459
  return typeof named === "string" && named.toLowerCase() === keyId.toLowerCase();
3362
3460
  }
3461
+ function headNamesPartner(doc, partnerId) {
3462
+ return typeof doc.heads?.[partnerId.toLowerCase()] === "string";
3463
+ }
3464
+ async function partnerKeyFingerprint(publicKeyB64) {
3465
+ const digest = await crypto.subtle.digest(
3466
+ "SHA-256",
3467
+ b64ToBytes2(publicKeyB64)
3468
+ );
3469
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
3470
+ }
3471
+ async function headNamesStagedKey(doc, partnerId, keyId, publicKeyB64) {
3472
+ try {
3473
+ const entry = doc.staged?.[partnerId.toLowerCase()];
3474
+ if (!entry || typeof entry.key_id !== "string" || typeof entry.key_sha256 !== "string") return false;
3475
+ if (entry.key_id.toLowerCase() !== keyId.toLowerCase()) return false;
3476
+ if (!/^[0-9a-f]{64}$/i.test(entry.key_sha256)) return false;
3477
+ return await partnerKeyFingerprint(publicKeyB64) === entry.key_sha256.toLowerCase();
3478
+ } catch {
3479
+ return false;
3480
+ }
3481
+ }
3363
3482
 
3364
3483
  // ../crypto/src/index.ts
3365
3484
  function b64ToBytes3(b64) {
@@ -3381,7 +3500,15 @@ function keyB64ToBytes(key) {
3381
3500
  function bytesToB64(bytes) {
3382
3501
  return btoa(String.fromCodePoint(...bytes));
3383
3502
  }
3384
- var subtle = () => globalThis.crypto.subtle;
3503
+ var subtle = () => {
3504
+ const webcrypto = globalThis.crypto;
3505
+ if (!webcrypto?.subtle) {
3506
+ throw new Error(
3507
+ "Web Crypto is unavailable in this runtime, so no encryption or key operation can run. In Node this needs version 19 or later, where globalThis.crypto is enabled by default (Node 18 has it behind --experimental-global-webcrypto, and is itself end-of-life). Check with `node -v` and upgrade, or re-run with NODE_OPTIONS=--experimental-global-webcrypto as a one-off."
3508
+ );
3509
+ }
3510
+ return webcrypto.subtle;
3511
+ };
3385
3512
  async function importP256PublicKey(keyBytes) {
3386
3513
  if (keyBytes.length === 65 && keyBytes[0] === 4) {
3387
3514
  return subtle().importKey(
@@ -3642,6 +3769,9 @@ function b64UrlToBytes(b64url) {
3642
3769
  const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
3643
3770
  return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
3644
3771
  }
3772
+ function toArrayBuffer(bytes) {
3773
+ return bytes.slice().buffer;
3774
+ }
3645
3775
  async function encryptSessionForPartner(session_data, partner) {
3646
3776
  return encryptEnvelopeForPartner(session_data, partner);
3647
3777
  }
@@ -3758,13 +3888,32 @@ async function encryptSessionForAll(partners) {
3758
3888
  );
3759
3889
  return Object.fromEntries(results.map((r) => [r.partner_id, r]));
3760
3890
  }
3761
- async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3891
+ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expectedAlg) {
3762
3892
  if (share.alg !== "ECDH-ES+HKDF-SHA256+A256GCM" && share.alg !== "RSA-OAEP-256+A256GCM" && share.alg !== "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3763
3893
  throw new Error(`decryptSession: unsupported alg ${share.alg}`);
3764
3894
  }
3765
3895
  if (share.v !== 2) {
3766
3896
  throw new Error(`decryptSession: unsupported share version ${share.v}`);
3767
3897
  }
3898
+ if (expectedAlg && share.alg !== expectedAlg) {
3899
+ throw new Error(
3900
+ `decryptSession: algorithm downgrade - the dispatch wraps SK_n as ${share.alg}, but this key is provisioned for ${expectedAlg}. Refusing rather than attempting a different wrap than the recipient chose.`
3901
+ );
3902
+ }
3903
+ const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
3904
+ if (ops) {
3905
+ if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3906
+ throw new Error(
3907
+ `decryptSession: key source "${ops.name}" performs private-key operations without releasing the key, which no KMS offers for ML-KEM. Use an exportable key source for post-quantum shares.`
3908
+ );
3909
+ }
3910
+ const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : "deriveSharedSecret";
3911
+ if (typeof ops[needed] !== "function") {
3912
+ throw new Error(
3913
+ `decryptSession: key source "${ops.name}" cannot do ${needed}, which ${share.alg} requires.`
3914
+ );
3915
+ }
3916
+ }
3768
3917
  let skRawBuf;
3769
3918
  if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3770
3919
  if (!share.epk) {
@@ -3786,41 +3935,55 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3786
3935
  const wrapKey = await subtle().importKey("raw", wrapKeyRaw, { name: "AES-GCM" }, false, ["decrypt"]);
3787
3936
  skRawBuf = await subtle().decrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, wrappedSkBytes);
3788
3937
  } else if (share.alg === "RSA-OAEP-256+A256GCM") {
3789
- const rsaPrivateKey = await subtle().importKey(
3790
- "pkcs8",
3791
- keyB64ToBytes(privateKeyB64),
3792
- { name: "RSA-OAEP", hash: "SHA-256" },
3793
- false,
3794
- ["decrypt"]
3795
- );
3796
- skRawBuf = await subtle().decrypt(
3797
- { name: "RSA-OAEP" },
3798
- rsaPrivateKey,
3799
- b64UrlToBytes(share.wrapped_key)
3800
- );
3938
+ if (ops) {
3939
+ skRawBuf = toArrayBuffer(await ops.decryptRsaOaep(b64UrlToBytes(share.wrapped_key)));
3940
+ } else {
3941
+ const rsaPrivateKey = await subtle().importKey(
3942
+ "pkcs8",
3943
+ keyB64ToBytes(privateKeyB64),
3944
+ { name: "RSA-OAEP", hash: "SHA-256" },
3945
+ false,
3946
+ ["decrypt"]
3947
+ );
3948
+ skRawBuf = await subtle().decrypt(
3949
+ { name: "RSA-OAEP" },
3950
+ rsaPrivateKey,
3951
+ b64UrlToBytes(share.wrapped_key)
3952
+ );
3953
+ }
3801
3954
  } else {
3802
3955
  if (!share.epk) {
3803
3956
  throw new Error("decryptSession: ECDH-ES share missing epk");
3804
3957
  }
3805
- const privateKey = await subtle().importKey(
3806
- "pkcs8",
3807
- keyB64ToBytes(privateKeyB64),
3808
- { name: "ECDH", namedCurve: "P-256" },
3809
- false,
3810
- ["deriveBits"]
3811
- );
3812
- const ephemeralPub = await subtle().importKey(
3813
- "spki",
3814
- b64UrlToBytes(share.epk),
3815
- { name: "ECDH", namedCurve: "P-256" },
3816
- false,
3817
- []
3818
- );
3819
- const sharedSecret = await subtle().deriveBits(
3820
- { name: "ECDH", public: ephemeralPub },
3821
- privateKey,
3822
- 256
3823
- );
3958
+ let sharedSecret;
3959
+ if (ops) {
3960
+ sharedSecret = toArrayBuffer(await ops.deriveSharedSecret(b64UrlToBytes(share.epk)));
3961
+ if (sharedSecret.byteLength !== 32) {
3962
+ throw new Error(
3963
+ `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; P-256 ECDH is 32 bytes with no KDF applied.`
3964
+ );
3965
+ }
3966
+ } else {
3967
+ const privateKey = await subtle().importKey(
3968
+ "pkcs8",
3969
+ keyB64ToBytes(privateKeyB64),
3970
+ { name: "ECDH", namedCurve: "P-256" },
3971
+ false,
3972
+ ["deriveBits"]
3973
+ );
3974
+ const ephemeralPub = await subtle().importKey(
3975
+ "spki",
3976
+ b64UrlToBytes(share.epk),
3977
+ { name: "ECDH", namedCurve: "P-256" },
3978
+ false,
3979
+ []
3980
+ );
3981
+ sharedSecret = await subtle().deriveBits(
3982
+ { name: "ECDH", public: ephemeralPub },
3983
+ privateKey,
3984
+ 256
3985
+ );
3986
+ }
3824
3987
  const wrappedBytes = b64UrlToBytes(share.wrapped_key);
3825
3988
  if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
3826
3989
  throw new Error("decryptSession: wrapped_key too short");
@@ -3970,6 +4133,9 @@ export {
3970
4133
  isFreshTimestamp,
3971
4134
  isIpLiteralHost,
3972
4135
  isSafeWebhookUrl,
4136
+ ENDPOINT_FAILURE_THRESHOLD,
4137
+ classifyEndpointProbe,
4138
+ countsAsFailure,
3973
4139
  PARTNER_KEY_ATTESTATION_V1,
3974
4140
  PARTNER_KEY_ATTESTATION_ALG,
3975
4141
  buildPartnerKeyAttestation,
@@ -3978,10 +4144,14 @@ export {
3978
4144
  verifyPartnerKeyAttestation,
3979
4145
  verifyPartnerKeyAttestationWithRoots,
3980
4146
  REGISTRY_HEAD_V1,
4147
+ REGISTRY_HEAD_V2,
3981
4148
  REGISTRY_HEAD_ALG,
3982
4149
  buildRegistryHeadStatement,
3983
4150
  verifyRegistryHead,
3984
4151
  headNamesKey,
4152
+ headNamesPartner,
4153
+ partnerKeyFingerprint,
4154
+ headNamesStagedKey,
3985
4155
  normaliseAddress,
3986
4156
  generatePartnerKeyPair,
3987
4157
  generateHybridPartnerKeyPair,