@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.
package/dist/edge.js CHANGED
@@ -3364,6 +3364,70 @@ var init_safe_url = __esm({
3364
3364
  }
3365
3365
  });
3366
3366
 
3367
+ // ../crypto/src/endpoint-health.ts
3368
+ function classifyEndpointProbe(input) {
3369
+ const status = typeof input.httpStatus === "number" && Number.isFinite(input.httpStatus) ? input.httpStatus : null;
3370
+ if (status === null || status === 0) {
3371
+ const detail = input.error ? `: ${input.error}` : "";
3372
+ return {
3373
+ health: "unreachable",
3374
+ dispatchable: false,
3375
+ summary: `No response from the endpoint${detail}. Check the host is running and reachable.`
3376
+ };
3377
+ }
3378
+ if (status >= 200 && status < 300) {
3379
+ return {
3380
+ health: "healthy",
3381
+ dispatchable: true,
3382
+ summary: `Receiver accepted a signed test request (HTTP ${status}).`
3383
+ };
3384
+ }
3385
+ if (status === 401 || status === 403) {
3386
+ return {
3387
+ health: "auth",
3388
+ dispatchable: false,
3389
+ summary: `Receiver rejected our signature (HTTP ${status}). Check the signing secret matches on both sides.`
3390
+ };
3391
+ }
3392
+ if (MISSING_STATUSES.has(status)) {
3393
+ return {
3394
+ health: "missing",
3395
+ dispatchable: false,
3396
+ summary: `Host answered but no receiver is listening at this path (HTTP ${status}). A stopped tunnel or a stale URL looks exactly like this.`
3397
+ };
3398
+ }
3399
+ if (status === 429) {
3400
+ return {
3401
+ health: "throttled",
3402
+ dispatchable: false,
3403
+ summary: `Receiver is up and rate-limiting us (HTTP 429). Back off and retry, or raise the ceiling; nothing is wrong with the URL.`
3404
+ };
3405
+ }
3406
+ if (status >= 500) {
3407
+ return {
3408
+ health: "degraded",
3409
+ dispatchable: false,
3410
+ summary: `Receiver is present but erroring (HTTP ${status}).`
3411
+ };
3412
+ }
3413
+ return {
3414
+ health: "rejected",
3415
+ dispatchable: false,
3416
+ summary: `Receiver refused the request (HTTP ${status}).`
3417
+ };
3418
+ }
3419
+ function countsAsFailure(verdict) {
3420
+ return !verdict.dispatchable;
3421
+ }
3422
+ var ENDPOINT_FAILURE_THRESHOLD, MISSING_STATUSES;
3423
+ var init_endpoint_health = __esm({
3424
+ "../crypto/src/endpoint-health.ts"() {
3425
+ "use strict";
3426
+ ENDPOINT_FAILURE_THRESHOLD = 3;
3427
+ MISSING_STATUSES = /* @__PURE__ */ new Set([404, 405, 410]);
3428
+ }
3429
+ });
3430
+
3367
3431
  // ../crypto/src/partner-key-attestation.ts
3368
3432
  function assertNoDelimiter(field, value) {
3369
3433
  if (typeof value !== "string" || value.length === 0) {
@@ -3465,6 +3529,9 @@ function assertMapSafe(field, value) {
3465
3529
  }
3466
3530
  }
3467
3531
  function buildRegistryHeadStatement(payload) {
3532
+ if (!KNOWN_VERSIONS.has(payload.version)) {
3533
+ throw new Error(`[registry-head] unknown head version: ${String(payload.version)}`);
3534
+ }
3468
3535
  assertNoLineBreak("issued_at", payload.issued_at);
3469
3536
  assertNoLineBreak("expires_at", payload.expires_at);
3470
3537
  assertMapSafe("root_key_id", payload.root_key_id);
@@ -3481,14 +3548,42 @@ function buildRegistryHeadStatement(payload) {
3481
3548
  }
3482
3549
  seen.add(partnerId);
3483
3550
  }
3484
- return [
3485
- REGISTRY_HEAD_V1,
3551
+ const lines = [
3552
+ payload.version,
3486
3553
  `issued_at:${payload.issued_at}`,
3487
3554
  `expires_at:${payload.expires_at}`,
3488
3555
  `root_key_id:${payload.root_key_id}`,
3489
3556
  `heads:${entries.length}`,
3490
3557
  ...entries.map(([partnerId, keyId]) => `${partnerId}:${keyId}`)
3491
- ].join("\n");
3558
+ ];
3559
+ if (payload.version === REGISTRY_HEAD_V1) {
3560
+ if (payload.staged && Object.keys(payload.staged).length > 0) {
3561
+ throw new Error("[registry-head] v1 statement cannot carry staged entries");
3562
+ }
3563
+ return lines.join("\n");
3564
+ }
3565
+ const stagedEntries = Object.entries(payload.staged ?? {}).map(([partnerId, entry]) => {
3566
+ assertMapSafe("staged partner_id", partnerId);
3567
+ assertMapSafe("staged key_id", entry?.key_id);
3568
+ assertMapSafe("staged key_sha256", entry?.key_sha256);
3569
+ if (!/^[0-9a-f]{64}$/i.test(entry.key_sha256)) {
3570
+ throw new Error(`[registry-head] staged key_sha256 must be 64 hex chars: ${partnerId}`);
3571
+ }
3572
+ return [partnerId.toLowerCase(), entry.key_id.toLowerCase(), entry.key_sha256.toLowerCase()];
3573
+ });
3574
+ stagedEntries.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
3575
+ const stagedSeen = /* @__PURE__ */ new Set();
3576
+ for (const [partnerId] of stagedEntries) {
3577
+ if (stagedSeen.has(partnerId)) {
3578
+ throw new Error(`[registry-head] duplicate partner_id in staged: ${partnerId}`);
3579
+ }
3580
+ stagedSeen.add(partnerId);
3581
+ }
3582
+ lines.push(`staged:${stagedEntries.length}`);
3583
+ for (const [partnerId, keyId, digest] of stagedEntries) {
3584
+ lines.push(`${partnerId}:${keyId}:${digest}`);
3585
+ }
3586
+ return lines.join("\n");
3492
3587
  }
3493
3588
  function b64ToBytes2(b64) {
3494
3589
  const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
@@ -3509,7 +3604,7 @@ function hexToBytes4(hex) {
3509
3604
  }
3510
3605
  async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date()) {
3511
3606
  try {
3512
- if (doc?.version !== REGISTRY_HEAD_V1) return "malformed";
3607
+ if (!doc || !KNOWN_VERSIONS.has(doc.version)) return "malformed";
3513
3608
  if (doc.algorithm !== REGISTRY_HEAD_ALG) return "malformed";
3514
3609
  if (typeof doc.signature !== "string" || !/^[0-9a-f]{128}$/i.test(doc.signature)) return "malformed";
3515
3610
  if (!doc.heads || typeof doc.heads !== "object") return "malformed";
@@ -3524,7 +3619,14 @@ async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date())
3524
3619
  issued_at: doc.issued_at,
3525
3620
  expires_at: doc.expires_at,
3526
3621
  root_key_id: doc.root_key_id,
3527
- heads: doc.heads
3622
+ heads: doc.heads,
3623
+ // Passed through rather than dropped: the staged map is part of what the
3624
+ // root signed on a v2 head, so omitting it here would rebuild different
3625
+ // bytes and report `bad-signature` on a perfectly good document. On a v1
3626
+ // head the builder REFUSES a non-empty map, which lands here as
3627
+ // `malformed` — the right answer for a document claiming staged keys its
3628
+ // signature does not cover.
3629
+ staged: doc.staged
3528
3630
  });
3529
3631
  const rootKey = await crypto.subtle.importKey(
3530
3632
  "spki",
@@ -3550,11 +3652,34 @@ function headNamesKey(doc, partnerId, keyId) {
3550
3652
  const named = doc.heads?.[partnerId.toLowerCase()];
3551
3653
  return typeof named === "string" && named.toLowerCase() === keyId.toLowerCase();
3552
3654
  }
3553
- var REGISTRY_HEAD_V1, REGISTRY_HEAD_ALG;
3655
+ function headNamesPartner(doc, partnerId) {
3656
+ return typeof doc.heads?.[partnerId.toLowerCase()] === "string";
3657
+ }
3658
+ async function partnerKeyFingerprint(publicKeyB64) {
3659
+ const digest = await crypto.subtle.digest(
3660
+ "SHA-256",
3661
+ b64ToBytes2(publicKeyB64)
3662
+ );
3663
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
3664
+ }
3665
+ async function headNamesStagedKey(doc, partnerId, keyId, publicKeyB64) {
3666
+ try {
3667
+ const entry = doc.staged?.[partnerId.toLowerCase()];
3668
+ if (!entry || typeof entry.key_id !== "string" || typeof entry.key_sha256 !== "string") return false;
3669
+ if (entry.key_id.toLowerCase() !== keyId.toLowerCase()) return false;
3670
+ if (!/^[0-9a-f]{64}$/i.test(entry.key_sha256)) return false;
3671
+ return await partnerKeyFingerprint(publicKeyB64) === entry.key_sha256.toLowerCase();
3672
+ } catch {
3673
+ return false;
3674
+ }
3675
+ }
3676
+ var REGISTRY_HEAD_V1, REGISTRY_HEAD_V2, KNOWN_VERSIONS, REGISTRY_HEAD_ALG;
3554
3677
  var init_registry_head = __esm({
3555
3678
  "../crypto/src/registry-head.ts"() {
3556
3679
  "use strict";
3557
3680
  REGISTRY_HEAD_V1 = "oneaddress-partner-key-registry-head:v1";
3681
+ REGISTRY_HEAD_V2 = "oneaddress-partner-key-registry-head:v2";
3682
+ KNOWN_VERSIONS = /* @__PURE__ */ new Set([REGISTRY_HEAD_V1, REGISTRY_HEAD_V2]);
3558
3683
  REGISTRY_HEAD_ALG = "ECDSA-P256";
3559
3684
  }
3560
3685
  });
@@ -3563,15 +3688,19 @@ var init_registry_head = __esm({
3563
3688
  var src_exports = {};
3564
3689
  __export(src_exports, {
3565
3690
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
3691
+ ENDPOINT_FAILURE_THRESHOLD: () => ENDPOINT_FAILURE_THRESHOLD,
3566
3692
  PARTNER_KEY_ATTESTATION_ALG: () => PARTNER_KEY_ATTESTATION_ALG,
3567
3693
  PARTNER_KEY_ATTESTATION_V1: () => PARTNER_KEY_ATTESTATION_V1,
3568
3694
  REGISTRY_HEAD_ALG: () => REGISTRY_HEAD_ALG,
3569
3695
  REGISTRY_HEAD_V1: () => REGISTRY_HEAD_V1,
3696
+ REGISTRY_HEAD_V2: () => REGISTRY_HEAD_V2,
3570
3697
  buildPartnerKeyAttestation: () => buildPartnerKeyAttestation,
3571
3698
  buildRegistryHeadStatement: () => buildRegistryHeadStatement,
3699
+ classifyEndpointProbe: () => classifyEndpointProbe,
3572
3700
  cleanNameAliases: () => cleanNameAliases,
3573
3701
  computeBlindIndex: () => computeBlindIndex,
3574
3702
  computeCustomerBlindIndex: () => computeCustomerBlindIndex,
3703
+ countsAsFailure: () => countsAsFailure,
3575
3704
  decryptAddress: () => decryptAddress,
3576
3705
  decryptSession: () => decryptSession,
3577
3706
  encryptAddressForAll: () => encryptAddressForAll,
@@ -3583,12 +3712,15 @@ __export(src_exports, {
3583
3712
  generateHybridPartnerKeyPair: () => generateHybridPartnerKeyPair,
3584
3713
  generatePartnerKeyPair: () => generatePartnerKeyPair,
3585
3714
  headNamesKey: () => headNamesKey,
3715
+ headNamesPartner: () => headNamesPartner,
3716
+ headNamesStagedKey: () => headNamesStagedKey,
3586
3717
  isEmailLike: () => isEmailLike,
3587
3718
  isFreshTimestamp: () => isFreshTimestamp,
3588
3719
  isIpLiteralHost: () => isIpLiteralHost,
3589
3720
  isSafeWebhookUrl: () => isSafeWebhookUrl,
3590
3721
  normaliseAddress: () => normaliseAddress,
3591
3722
  normalizeForBlindIndex: () => normalizeForBlindIndex,
3723
+ partnerKeyFingerprint: () => partnerKeyFingerprint,
3592
3724
  rootKeyIdFromSpki: () => rootKeyIdFromSpki,
3593
3725
  rootKeyIdFromSpkiB64: () => rootKeyIdFromSpkiB64,
3594
3726
  signWebhookPayload: () => signWebhookPayload,
@@ -3853,6 +3985,9 @@ function b64UrlToBytes(b64url) {
3853
3985
  const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
3854
3986
  return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
3855
3987
  }
3988
+ function toArrayBuffer(bytes) {
3989
+ return bytes.slice().buffer;
3990
+ }
3856
3991
  async function encryptSessionForPartner(session_data, partner) {
3857
3992
  return encryptEnvelopeForPartner(session_data, partner);
3858
3993
  }
@@ -3969,13 +4104,32 @@ async function encryptSessionForAll(partners) {
3969
4104
  );
3970
4105
  return Object.fromEntries(results.map((r) => [r.partner_id, r]));
3971
4106
  }
3972
- async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
4107
+ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expectedAlg) {
3973
4108
  if (share.alg !== "ECDH-ES+HKDF-SHA256+A256GCM" && share.alg !== "RSA-OAEP-256+A256GCM" && share.alg !== "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3974
4109
  throw new Error(`decryptSession: unsupported alg ${share.alg}`);
3975
4110
  }
3976
4111
  if (share.v !== 2) {
3977
4112
  throw new Error(`decryptSession: unsupported share version ${share.v}`);
3978
4113
  }
4114
+ if (expectedAlg && share.alg !== expectedAlg) {
4115
+ throw new Error(
4116
+ `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.`
4117
+ );
4118
+ }
4119
+ const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
4120
+ if (ops) {
4121
+ if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
4122
+ throw new Error(
4123
+ `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.`
4124
+ );
4125
+ }
4126
+ const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : "deriveSharedSecret";
4127
+ if (typeof ops[needed] !== "function") {
4128
+ throw new Error(
4129
+ `decryptSession: key source "${ops.name}" cannot do ${needed}, which ${share.alg} requires.`
4130
+ );
4131
+ }
4132
+ }
3979
4133
  let skRawBuf;
3980
4134
  if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3981
4135
  if (!share.epk) {
@@ -3997,41 +4151,55 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3997
4151
  const wrapKey = await subtle().importKey("raw", wrapKeyRaw, { name: "AES-GCM" }, false, ["decrypt"]);
3998
4152
  skRawBuf = await subtle().decrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, wrappedSkBytes);
3999
4153
  } else if (share.alg === "RSA-OAEP-256+A256GCM") {
4000
- const rsaPrivateKey = await subtle().importKey(
4001
- "pkcs8",
4002
- keyB64ToBytes(privateKeyB64),
4003
- { name: "RSA-OAEP", hash: "SHA-256" },
4004
- false,
4005
- ["decrypt"]
4006
- );
4007
- skRawBuf = await subtle().decrypt(
4008
- { name: "RSA-OAEP" },
4009
- rsaPrivateKey,
4010
- b64UrlToBytes(share.wrapped_key)
4011
- );
4154
+ if (ops) {
4155
+ skRawBuf = toArrayBuffer(await ops.decryptRsaOaep(b64UrlToBytes(share.wrapped_key)));
4156
+ } else {
4157
+ const rsaPrivateKey = await subtle().importKey(
4158
+ "pkcs8",
4159
+ keyB64ToBytes(privateKeyB64),
4160
+ { name: "RSA-OAEP", hash: "SHA-256" },
4161
+ false,
4162
+ ["decrypt"]
4163
+ );
4164
+ skRawBuf = await subtle().decrypt(
4165
+ { name: "RSA-OAEP" },
4166
+ rsaPrivateKey,
4167
+ b64UrlToBytes(share.wrapped_key)
4168
+ );
4169
+ }
4012
4170
  } else {
4013
4171
  if (!share.epk) {
4014
4172
  throw new Error("decryptSession: ECDH-ES share missing epk");
4015
4173
  }
4016
- const privateKey = await subtle().importKey(
4017
- "pkcs8",
4018
- keyB64ToBytes(privateKeyB64),
4019
- { name: "ECDH", namedCurve: "P-256" },
4020
- false,
4021
- ["deriveBits"]
4022
- );
4023
- const ephemeralPub = await subtle().importKey(
4024
- "spki",
4025
- b64UrlToBytes(share.epk),
4026
- { name: "ECDH", namedCurve: "P-256" },
4027
- false,
4028
- []
4029
- );
4030
- const sharedSecret = await subtle().deriveBits(
4031
- { name: "ECDH", public: ephemeralPub },
4032
- privateKey,
4033
- 256
4034
- );
4174
+ let sharedSecret;
4175
+ if (ops) {
4176
+ sharedSecret = toArrayBuffer(await ops.deriveSharedSecret(b64UrlToBytes(share.epk)));
4177
+ if (sharedSecret.byteLength !== 32) {
4178
+ throw new Error(
4179
+ `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; P-256 ECDH is 32 bytes with no KDF applied.`
4180
+ );
4181
+ }
4182
+ } else {
4183
+ const privateKey = await subtle().importKey(
4184
+ "pkcs8",
4185
+ keyB64ToBytes(privateKeyB64),
4186
+ { name: "ECDH", namedCurve: "P-256" },
4187
+ false,
4188
+ ["deriveBits"]
4189
+ );
4190
+ const ephemeralPub = await subtle().importKey(
4191
+ "spki",
4192
+ b64UrlToBytes(share.epk),
4193
+ { name: "ECDH", namedCurve: "P-256" },
4194
+ false,
4195
+ []
4196
+ );
4197
+ sharedSecret = await subtle().deriveBits(
4198
+ { name: "ECDH", public: ephemeralPub },
4199
+ privateKey,
4200
+ 256
4201
+ );
4202
+ }
4035
4203
  const wrappedBytes = b64UrlToBytes(share.wrapped_key);
4036
4204
  if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
4037
4205
  throw new Error("decryptSession: wrapped_key too short");
@@ -4182,9 +4350,18 @@ var init_src = __esm({
4182
4350
  init_hybrid();
4183
4351
  init_replay_window();
4184
4352
  init_safe_url();
4353
+ init_endpoint_health();
4185
4354
  init_partner_key_attestation();
4186
4355
  init_registry_head();
4187
- subtle = () => globalThis.crypto.subtle;
4356
+ subtle = () => {
4357
+ const webcrypto = globalThis.crypto;
4358
+ if (!webcrypto?.subtle) {
4359
+ throw new Error(
4360
+ "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."
4361
+ );
4362
+ }
4363
+ return webcrypto.subtle;
4364
+ };
4188
4365
  AU_STATE_FULL = {
4189
4366
  "new south wales": "NSW",
4190
4367
  "victoria": "VIC",
@@ -4382,9 +4559,15 @@ async function decryptAddress2(payload, privateKeyPem, partnerId) {
4382
4559
  );
4383
4560
  return JSON.parse(new TextDecoder().decode(plaintext));
4384
4561
  }
4385
- async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId) {
4562
+ async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
4386
4563
  const { decryptSession: decryptSessionCrypto } = await Promise.resolve().then(() => (init_src(), src_exports));
4387
- return decryptSessionCrypto(share, envelopeB64, pemToBase64(privateKeyPem), partnerId);
4564
+ return decryptSessionCrypto(
4565
+ share,
4566
+ envelopeB64,
4567
+ typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
4568
+ partnerId,
4569
+ expectedAlg
4570
+ );
4388
4571
  }
4389
4572
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
4390
4573
  const plaintext = await decryptAddress2(payload, privateKeyPem, partnerId);
@@ -4628,12 +4811,32 @@ function compareAddresses(a, b) {
4628
4811
  if (aCountry && bCountry && aCountry !== bCountry) return false;
4629
4812
  return true;
4630
4813
  }
4814
+ function isAllowedCallbackHost(raw, extraHosts) {
4815
+ let host;
4816
+ try {
4817
+ const u = new URL(raw);
4818
+ if (u.protocol !== "https:") return false;
4819
+ host = u.hostname.toLowerCase();
4820
+ } catch {
4821
+ return false;
4822
+ }
4823
+ if (host === "oneaddress.io" || host.endsWith(".oneaddress.io")) return true;
4824
+ const envRaw = typeof process !== "undefined" ? process.env?.OA_CALLBACK_HOST_ALLOWLIST ?? "" : "";
4825
+ const allowed = [
4826
+ ...envRaw.split(",").map((h) => h.trim().toLowerCase()),
4827
+ ...(extraHosts ?? []).map((h) => h.trim().toLowerCase())
4828
+ ].filter(Boolean);
4829
+ return allowed.includes(host);
4830
+ }
4631
4831
  async function sendVerifyResult(params) {
4632
- const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
4832
+ const { callbackUrl, callbackToken, batchId, partnerId, match, note, allowedCallbackHosts } = params;
4633
4833
  const safe = isSafeWebhookUrl(callbackUrl);
4634
4834
  if (!safe.ok) {
4635
4835
  throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
4636
4836
  }
4837
+ if (!isAllowedCallbackHost(callbackUrl, allowedCallbackHosts)) {
4838
+ throw new Error(`[OneAddress SDK] refusing verify-result callback to non-OneAddress host: ${callbackUrl}`);
4839
+ }
4637
4840
  const res = await fetch(callbackUrl, {
4638
4841
  method: "POST",
4639
4842
  headers: { "Content-Type": "application/json" },
@@ -4650,7 +4853,38 @@ async function sendVerifyResult(params) {
4650
4853
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
4651
4854
  }
4652
4855
  }
4653
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
4856
+ var UPDATE_TYPE_ORDER = ["address", "phone", "email"];
4857
+ function normaliseAcceptedUpdateTypes(raw) {
4858
+ const kept = new Set(Array.isArray(raw) ? raw.filter((v) => typeof v === "string") : []);
4859
+ return UPDATE_TYPE_ORDER.filter((t) => t === "address" || kept.has(t));
4860
+ }
4861
+ function readUpdateTypes(raw) {
4862
+ if (raw === void 0 || raw === null) return ["address"];
4863
+ if (!Array.isArray(raw)) return null;
4864
+ if (raw.length === 0) return ["address"];
4865
+ const out = [];
4866
+ for (const v of raw) {
4867
+ if (typeof v !== "string" || !UPDATE_TYPE_ORDER.includes(v)) return null;
4868
+ if (!out.includes(v)) out.push(v);
4869
+ }
4870
+ return out;
4871
+ }
4872
+ var InvalidUpdateTypesError = class extends Error {
4873
+ constructor(raw) {
4874
+ super("[OneAddress SDK] update_types names a kind this build does not know");
4875
+ this.raw = raw;
4876
+ this.name = "InvalidUpdateTypesError";
4877
+ }
4878
+ };
4879
+ function requireContactValue(kind, value) {
4880
+ if (typeof value !== "string" || value === "") {
4881
+ throw new Error(
4882
+ `[OneAddress SDK] Decrypted envelope declares update_types "${kind}" but carries no new_${kind}. This may indicate a decryption error or a schema change. Update @oneaddress/partner-sdk.`
4883
+ );
4884
+ }
4885
+ return value;
4886
+ }
4887
+ var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
4654
4888
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
4655
4889
  function createOneAddressHandler(options) {
4656
4890
  const {
@@ -4658,25 +4892,39 @@ function createOneAddressHandler(options) {
4658
4892
  previousWebhookSecret,
4659
4893
  webhookSecretGraceUntil,
4660
4894
  privateKeyPem,
4895
+ keyId,
4661
4896
  loaPublicKeyPem,
4662
4897
  onUpdate,
4663
4898
  onVerify,
4664
4899
  onAccountVerify,
4665
4900
  onTest,
4666
4901
  timestampToleranceSecs = 300,
4667
- idempotencyStore
4902
+ idempotencyStore,
4903
+ acceptedUpdateTypes: acceptedUpdateTypesRaw,
4904
+ allowedCallbackHosts
4668
4905
  } = options;
4906
+ const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
4907
+ function declared(status, payload) {
4908
+ return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
4909
+ status,
4910
+ headers: { "Content-Type": "application/json" }
4911
+ });
4912
+ }
4669
4913
  async function buildD5Pieces(body, partnerId) {
4670
4914
  const share = body.session_key_share;
4671
4915
  const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId);
4672
- const address = validateAddress({
4916
+ const updateTypes = readUpdateTypes(data.update_types);
4917
+ if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
4918
+ const address = updateTypes.includes("address") ? validateAddress({
4673
4919
  street: data.new_address?.street,
4674
4920
  suburb: data.new_address?.suburb,
4675
4921
  state: data.new_address?.state,
4676
4922
  postcode: data.new_address?.postcode,
4677
4923
  country: data.new_address?.country,
4678
4924
  updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
4679
- });
4925
+ }) : void 0;
4926
+ const newPhone = updateTypes.includes("phone") ? requireContactValue("phone", data.new_phone) : void 0;
4927
+ const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
4680
4928
  const customer = {
4681
4929
  email: "",
4682
4930
  name: data.verified_name ?? "",
@@ -4697,11 +4945,19 @@ function createOneAddressHandler(options) {
4697
4945
  if (!valid) throw new Error("D5 LOA signature verification failed");
4698
4946
  }
4699
4947
  }
4700
- return { address, customer, loa, loa_ref, raw: data };
4948
+ return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
4701
4949
  }
4702
4950
  function isD5Body(body) {
4703
4951
  return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
4704
4952
  }
4953
+ function isCrossoverSiblingToSkip(body) {
4954
+ if (!keyId || !isD5Body(body)) return false;
4955
+ const share = body.session_key_share;
4956
+ const shareKeyId = typeof share?.key_id === "string" ? share.key_id : "";
4957
+ if (!shareKeyId || shareKeyId === keyId) return false;
4958
+ const siblings = body.crossover_key_ids;
4959
+ return Array.isArray(siblings) && siblings.includes(keyId);
4960
+ }
4705
4961
  return async function handler(req) {
4706
4962
  const rawBody = await req.text();
4707
4963
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
@@ -4737,6 +4993,9 @@ function createOneAddressHandler(options) {
4737
4993
  const partnerId = body.partner_id ?? "";
4738
4994
  const tsNum = Number(tsHeader);
4739
4995
  const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
4996
+ if (isCrossoverSiblingToSkip(body)) {
4997
+ return declared(200, { ok: true, skipped: true, crossover: true });
4998
+ }
4740
4999
  if (dispatchId) {
4741
5000
  if (!idempotencyStore) {
4742
5001
  if (process.env.NODE_ENV === "test") {
@@ -4747,41 +5006,64 @@ function createOneAddressHandler(options) {
4747
5006
  } else if (idempotencyStore.claim) {
4748
5007
  const claim = await idempotencyStore.claim(dispatchId);
4749
5008
  if (claim === "duplicate") {
4750
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
4751
- status: 200,
4752
- headers: { "Content-Type": "application/json" }
4753
- });
5009
+ return declared(200, { ok: true, duplicate: true });
4754
5010
  }
4755
5011
  } else {
4756
5012
  const alreadySeen = await idempotencyStore.has(dispatchId);
4757
5013
  if (alreadySeen) {
4758
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
4759
- status: 200,
4760
- headers: { "Content-Type": "application/json" }
4761
- });
5014
+ return declared(200, { ok: true, duplicate: true });
4762
5015
  }
4763
5016
  }
4764
5017
  }
4765
5018
  try {
4766
- if (body.event === "address.updated") {
5019
+ if (body.event === "address.updated" || body.event === "contact.updated") {
5020
+ const wireEvent = body.event;
4767
5021
  let event;
4768
5022
  if (isD5Body(body)) {
4769
- const d5 = await buildD5Pieces(body, partnerId);
5023
+ let d5;
5024
+ try {
5025
+ d5 = await buildD5Pieces(body, partnerId);
5026
+ } catch (err) {
5027
+ if (err instanceof InvalidUpdateTypesError) {
5028
+ return declared(422, {
5029
+ error: "invalid_update_types",
5030
+ detail: "update_types must be an array of " + UPDATE_TYPE_ORDER.join("|") + ". A name this build does not know was refused rather than dropped. Update @oneaddress/partner-sdk."
5031
+ });
5032
+ }
5033
+ throw err;
5034
+ }
5035
+ const notAccepted = d5.updateTypes.filter((t) => !acceptedUpdateTypes.includes(t));
5036
+ if (notAccepted.length > 0) {
5037
+ return declared(422, {
5038
+ error: "update_type_not_accepted",
5039
+ update_types: notAccepted,
5040
+ detail: "This receiver declares acceptedUpdateTypes " + JSON.stringify(acceptedUpdateTypes) + " and the dispatch carries " + JSON.stringify(d5.updateTypes) + ". Nothing was processed. Widen acceptedUpdateTypes once onUpdate stores the new kind, then re-run conformance."
5041
+ });
5042
+ }
4770
5043
  event = {
4771
- event: "address.updated",
5044
+ event: wireEvent,
4772
5045
  version: body.oneaddress_version ?? body.version ?? "2.0",
4773
5046
  id: body.id ?? "",
4774
5047
  timestamp: tsNum,
4775
5048
  partner_id: partnerId,
4776
5049
  dispatchId,
4777
5050
  customer: d5.customer,
5051
+ update_types: d5.updateTypes,
4778
5052
  address: d5.address,
5053
+ new_phone: d5.newPhone,
5054
+ new_email: d5.newEmail,
4779
5055
  loa: d5.loa,
4780
5056
  loa_ref: d5.loa_ref,
4781
5057
  id_verification: body.id_verification,
4782
5058
  raw: d5.raw
4783
5059
  };
4784
5060
  } else {
5061
+ if (wireEvent === "contact.updated") {
5062
+ return declared(400, {
5063
+ error: "missing_session_envelope",
5064
+ detail: "contact.updated requires session_envelope + session_key_share"
5065
+ });
5066
+ }
4785
5067
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
4786
5068
  return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
4787
5069
  status: 400,
@@ -4817,6 +5099,8 @@ function createOneAddressHandler(options) {
4817
5099
  partner_id: partnerId,
4818
5100
  dispatchId,
4819
5101
  customer,
5102
+ // The legacy blob predates kinds and always carries an address.
5103
+ update_types: ["address"],
4820
5104
  address: validateAddress(rawAddress),
4821
5105
  loa,
4822
5106
  loa_ref,
@@ -4832,10 +5116,7 @@ function createOneAddressHandler(options) {
4832
5116
  // NOSONAR
4833
5117
  );
4834
5118
  }
4835
- return new Response(JSON.stringify({ ok: true, ...result }), {
4836
- status: 200,
4837
- headers: { "Content-Type": "application/json" }
4838
- });
5119
+ return declared(200, { ok: true, ...result });
4839
5120
  }
4840
5121
  if (body.event === "address.verify" && onVerify) {
4841
5122
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
@@ -4878,16 +5159,14 @@ function createOneAddressHandler(options) {
4878
5159
  batchId: body.batch_id ?? 0,
4879
5160
  partnerId,
4880
5161
  match: matched,
4881
- note: result && typeof result.note === "string" ? result.note : void 0
5162
+ note: result && typeof result.note === "string" ? result.note : void 0,
5163
+ allowedCallbackHosts
4882
5164
  });
4883
5165
  } catch (err) {
4884
5166
  console.error("[OneAddress SDK] verify-result callback failed:", err);
4885
5167
  }
4886
5168
  }
4887
- return new Response(JSON.stringify({ ok: true, match: matched }), {
4888
- status: 200,
4889
- headers: { "Content-Type": "application/json" }
4890
- });
5169
+ return declared(200, { ok: true, match: matched });
4891
5170
  }
4892
5171
  if (body.event === "account.verify" && onAccountVerify) {
4893
5172
  let customer;
@@ -4918,21 +5197,19 @@ function createOneAddressHandler(options) {
4918
5197
  raw: body
4919
5198
  };
4920
5199
  const result = await onAccountVerify(event);
4921
- return new Response(JSON.stringify({ ok: true, ...result }), {
4922
- status: 200,
4923
- headers: { "Content-Type": "application/json" }
4924
- });
5200
+ return declared(200, { ok: true, ...result });
4925
5201
  }
4926
- if (body.event === "address.test" && onTest) {
5202
+ if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
4927
5203
  if (!isD5Body(body)) {
4928
- return new Response(JSON.stringify({ error: "address.test requires a session envelope" }), {
5204
+ return new Response(JSON.stringify({ error: "a test dispatch requires a session envelope" }), {
4929
5205
  status: 400,
4930
5206
  headers: { "Content-Type": "application/json" }
4931
5207
  });
4932
5208
  }
4933
5209
  const d5 = await buildD5Pieces(body, partnerId);
5210
+ if (!d5.address) throw new Error("[OneAddress SDK] test record carries no address");
4934
5211
  await onTest({
4935
- event: "address.test",
5212
+ event: body.event,
4936
5213
  index: typeof body.index === "number" ? body.index : void 0,
4937
5214
  total: typeof body.total === "number" ? body.total : void 0,
4938
5215
  verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
@@ -4942,21 +5219,23 @@ function createOneAddressHandler(options) {
4942
5219
  address: d5.address,
4943
5220
  raw: d5.raw
4944
5221
  });
4945
- return new Response(JSON.stringify({ ok: true, test: true }), {
4946
- status: 200,
4947
- headers: { "Content-Type": "application/json" }
4948
- });
5222
+ return declared(200, { ok: true, test: true });
4949
5223
  }
4950
5224
  const evt = typeof body.event === "string" ? body.event : "(none)";
4951
5225
  const callbackFor = {
4952
5226
  "address.verify": onVerify,
4953
5227
  "account.verify": onAccountVerify,
4954
- "address.test": onTest
5228
+ "address.test": onTest,
5229
+ // Same callback as address.test: both test variants route to onTest, so
5230
+ // an unwired stress-test event must name onTest too — not fall through
5231
+ // to the "upgrade the SDK" remedy, which cannot help (marlowe-reports#126).
5232
+ "address.test-dispatch": onTest
4955
5233
  };
4956
5234
  const callbackNameFor = {
4957
5235
  "address.verify": "onVerify",
4958
5236
  "account.verify": "onAccountVerify",
4959
- "address.test": "onTest"
5237
+ "address.test": "onTest",
5238
+ "address.test-dispatch": "onTest"
4960
5239
  };
4961
5240
  const unwired = evt in callbackFor && !callbackFor[evt] ? callbackNameFor[evt] : null;
4962
5241
  if (!warnedUnhandledEvents.has(evt)) {
@@ -4966,7 +5245,7 @@ function createOneAddressHandler(options) {
4966
5245
  // NOSONAR
4967
5246
  );
4968
5247
  }
4969
- return new Response(JSON.stringify({ ok: true, skipped: true, event: evt }), {
5248
+ return new Response(JSON.stringify({ ok: true, skipped: true, event: evt, accepted_update_types: acceptedUpdateTypes }), {
4970
5249
  status: 200,
4971
5250
  headers: { "Content-Type": "application/json" }
4972
5251
  });