@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/index.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",
@@ -4633,9 +4810,15 @@ async function decryptAddress2(payload, privateKeyPem, partnerId) {
4633
4810
  );
4634
4811
  return JSON.parse(new TextDecoder().decode(plaintext));
4635
4812
  }
4636
- async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId) {
4813
+ async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
4637
4814
  const { decryptSession: decryptSessionCrypto } = await Promise.resolve().then(() => (init_src(), src_exports));
4638
- return decryptSessionCrypto(share, envelopeB64, pemToBase64(privateKeyPem), partnerId);
4815
+ return decryptSessionCrypto(
4816
+ share,
4817
+ envelopeB64,
4818
+ typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
4819
+ partnerId,
4820
+ expectedAlg
4821
+ );
4639
4822
  }
4640
4823
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
4641
4824
  const plaintext = await decryptAddress2(payload, privateKeyPem, partnerId);
@@ -4966,12 +5149,32 @@ function compareAddresses(a, b) {
4966
5149
  if (aCountry && bCountry && aCountry !== bCountry) return false;
4967
5150
  return true;
4968
5151
  }
5152
+ function isAllowedCallbackHost(raw, extraHosts) {
5153
+ let host;
5154
+ try {
5155
+ const u = new URL(raw);
5156
+ if (u.protocol !== "https:") return false;
5157
+ host = u.hostname.toLowerCase();
5158
+ } catch {
5159
+ return false;
5160
+ }
5161
+ if (host === "oneaddress.io" || host.endsWith(".oneaddress.io")) return true;
5162
+ const envRaw = typeof process !== "undefined" ? process.env?.OA_CALLBACK_HOST_ALLOWLIST ?? "" : "";
5163
+ const allowed = [
5164
+ ...envRaw.split(",").map((h) => h.trim().toLowerCase()),
5165
+ ...(extraHosts ?? []).map((h) => h.trim().toLowerCase())
5166
+ ].filter(Boolean);
5167
+ return allowed.includes(host);
5168
+ }
4969
5169
  async function sendVerifyResult(params) {
4970
- const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
5170
+ const { callbackUrl, callbackToken, batchId, partnerId, match, note, allowedCallbackHosts } = params;
4971
5171
  const safe = isSafeWebhookUrl(callbackUrl);
4972
5172
  if (!safe.ok) {
4973
5173
  throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
4974
5174
  }
5175
+ if (!isAllowedCallbackHost(callbackUrl, allowedCallbackHosts)) {
5176
+ throw new Error(`[OneAddress SDK] refusing verify-result callback to non-OneAddress host: ${callbackUrl}`);
5177
+ }
4975
5178
  const res = await fetch(callbackUrl, {
4976
5179
  method: "POST",
4977
5180
  headers: { "Content-Type": "application/json" },
@@ -4988,7 +5191,38 @@ async function sendVerifyResult(params) {
4988
5191
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
4989
5192
  }
4990
5193
  }
4991
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
5194
+ var UPDATE_TYPE_ORDER = ["address", "phone", "email"];
5195
+ function normaliseAcceptedUpdateTypes(raw) {
5196
+ const kept = new Set(Array.isArray(raw) ? raw.filter((v) => typeof v === "string") : []);
5197
+ return UPDATE_TYPE_ORDER.filter((t) => t === "address" || kept.has(t));
5198
+ }
5199
+ function readUpdateTypes(raw) {
5200
+ if (raw === void 0 || raw === null) return ["address"];
5201
+ if (!Array.isArray(raw)) return null;
5202
+ if (raw.length === 0) return ["address"];
5203
+ const out = [];
5204
+ for (const v of raw) {
5205
+ if (typeof v !== "string" || !UPDATE_TYPE_ORDER.includes(v)) return null;
5206
+ if (!out.includes(v)) out.push(v);
5207
+ }
5208
+ return out;
5209
+ }
5210
+ var InvalidUpdateTypesError = class extends Error {
5211
+ constructor(raw) {
5212
+ super("[OneAddress SDK] update_types names a kind this build does not know");
5213
+ this.raw = raw;
5214
+ this.name = "InvalidUpdateTypesError";
5215
+ }
5216
+ };
5217
+ function requireContactValue(kind, value) {
5218
+ if (typeof value !== "string" || value === "") {
5219
+ throw new Error(
5220
+ `[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.`
5221
+ );
5222
+ }
5223
+ return value;
5224
+ }
5225
+ var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
4992
5226
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
4993
5227
  function createOneAddressHandler(options) {
4994
5228
  const {
@@ -4996,25 +5230,39 @@ function createOneAddressHandler(options) {
4996
5230
  previousWebhookSecret,
4997
5231
  webhookSecretGraceUntil,
4998
5232
  privateKeyPem,
5233
+ keyId,
4999
5234
  loaPublicKeyPem,
5000
5235
  onUpdate,
5001
5236
  onVerify,
5002
5237
  onAccountVerify,
5003
5238
  onTest,
5004
5239
  timestampToleranceSecs = 300,
5005
- idempotencyStore
5240
+ idempotencyStore,
5241
+ acceptedUpdateTypes: acceptedUpdateTypesRaw,
5242
+ allowedCallbackHosts
5006
5243
  } = options;
5244
+ const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
5245
+ function declared(status, payload) {
5246
+ return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
5247
+ status,
5248
+ headers: { "Content-Type": "application/json" }
5249
+ });
5250
+ }
5007
5251
  async function buildD5Pieces(body, partnerId) {
5008
5252
  const share = body.session_key_share;
5009
5253
  const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId);
5010
- const address = validateAddress({
5254
+ const updateTypes = readUpdateTypes(data.update_types);
5255
+ if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
5256
+ const address = updateTypes.includes("address") ? validateAddress({
5011
5257
  street: data.new_address?.street,
5012
5258
  suburb: data.new_address?.suburb,
5013
5259
  state: data.new_address?.state,
5014
5260
  postcode: data.new_address?.postcode,
5015
5261
  country: data.new_address?.country,
5016
5262
  updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
5017
- });
5263
+ }) : void 0;
5264
+ const newPhone = updateTypes.includes("phone") ? requireContactValue("phone", data.new_phone) : void 0;
5265
+ const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
5018
5266
  const customer = {
5019
5267
  email: "",
5020
5268
  name: data.verified_name ?? "",
@@ -5035,11 +5283,19 @@ function createOneAddressHandler(options) {
5035
5283
  if (!valid) throw new Error("D5 LOA signature verification failed");
5036
5284
  }
5037
5285
  }
5038
- return { address, customer, loa, loa_ref, raw: data };
5286
+ return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
5039
5287
  }
5040
5288
  function isD5Body(body) {
5041
5289
  return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
5042
5290
  }
5291
+ function isCrossoverSiblingToSkip(body) {
5292
+ if (!keyId || !isD5Body(body)) return false;
5293
+ const share = body.session_key_share;
5294
+ const shareKeyId = typeof share?.key_id === "string" ? share.key_id : "";
5295
+ if (!shareKeyId || shareKeyId === keyId) return false;
5296
+ const siblings = body.crossover_key_ids;
5297
+ return Array.isArray(siblings) && siblings.includes(keyId);
5298
+ }
5043
5299
  return async function handler(req) {
5044
5300
  const rawBody = await req.text();
5045
5301
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
@@ -5075,6 +5331,9 @@ function createOneAddressHandler(options) {
5075
5331
  const partnerId = body.partner_id ?? "";
5076
5332
  const tsNum = Number(tsHeader);
5077
5333
  const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
5334
+ if (isCrossoverSiblingToSkip(body)) {
5335
+ return declared(200, { ok: true, skipped: true, crossover: true });
5336
+ }
5078
5337
  if (dispatchId) {
5079
5338
  if (!idempotencyStore) {
5080
5339
  if (process.env.NODE_ENV === "test") {
@@ -5085,41 +5344,64 @@ function createOneAddressHandler(options) {
5085
5344
  } else if (idempotencyStore.claim) {
5086
5345
  const claim = await idempotencyStore.claim(dispatchId);
5087
5346
  if (claim === "duplicate") {
5088
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
5089
- status: 200,
5090
- headers: { "Content-Type": "application/json" }
5091
- });
5347
+ return declared(200, { ok: true, duplicate: true });
5092
5348
  }
5093
5349
  } else {
5094
5350
  const alreadySeen = await idempotencyStore.has(dispatchId);
5095
5351
  if (alreadySeen) {
5096
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
5097
- status: 200,
5098
- headers: { "Content-Type": "application/json" }
5099
- });
5352
+ return declared(200, { ok: true, duplicate: true });
5100
5353
  }
5101
5354
  }
5102
5355
  }
5103
5356
  try {
5104
- if (body.event === "address.updated") {
5357
+ if (body.event === "address.updated" || body.event === "contact.updated") {
5358
+ const wireEvent = body.event;
5105
5359
  let event;
5106
5360
  if (isD5Body(body)) {
5107
- const d5 = await buildD5Pieces(body, partnerId);
5361
+ let d5;
5362
+ try {
5363
+ d5 = await buildD5Pieces(body, partnerId);
5364
+ } catch (err) {
5365
+ if (err instanceof InvalidUpdateTypesError) {
5366
+ return declared(422, {
5367
+ error: "invalid_update_types",
5368
+ 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."
5369
+ });
5370
+ }
5371
+ throw err;
5372
+ }
5373
+ const notAccepted = d5.updateTypes.filter((t) => !acceptedUpdateTypes.includes(t));
5374
+ if (notAccepted.length > 0) {
5375
+ return declared(422, {
5376
+ error: "update_type_not_accepted",
5377
+ update_types: notAccepted,
5378
+ 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."
5379
+ });
5380
+ }
5108
5381
  event = {
5109
- event: "address.updated",
5382
+ event: wireEvent,
5110
5383
  version: body.oneaddress_version ?? body.version ?? "2.0",
5111
5384
  id: body.id ?? "",
5112
5385
  timestamp: tsNum,
5113
5386
  partner_id: partnerId,
5114
5387
  dispatchId,
5115
5388
  customer: d5.customer,
5389
+ update_types: d5.updateTypes,
5116
5390
  address: d5.address,
5391
+ new_phone: d5.newPhone,
5392
+ new_email: d5.newEmail,
5117
5393
  loa: d5.loa,
5118
5394
  loa_ref: d5.loa_ref,
5119
5395
  id_verification: body.id_verification,
5120
5396
  raw: d5.raw
5121
5397
  };
5122
5398
  } else {
5399
+ if (wireEvent === "contact.updated") {
5400
+ return declared(400, {
5401
+ error: "missing_session_envelope",
5402
+ detail: "contact.updated requires session_envelope + session_key_share"
5403
+ });
5404
+ }
5123
5405
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
5124
5406
  return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
5125
5407
  status: 400,
@@ -5155,6 +5437,8 @@ function createOneAddressHandler(options) {
5155
5437
  partner_id: partnerId,
5156
5438
  dispatchId,
5157
5439
  customer,
5440
+ // The legacy blob predates kinds and always carries an address.
5441
+ update_types: ["address"],
5158
5442
  address: validateAddress(rawAddress),
5159
5443
  loa,
5160
5444
  loa_ref,
@@ -5170,10 +5454,7 @@ function createOneAddressHandler(options) {
5170
5454
  // NOSONAR
5171
5455
  );
5172
5456
  }
5173
- return new Response(JSON.stringify({ ok: true, ...result }), {
5174
- status: 200,
5175
- headers: { "Content-Type": "application/json" }
5176
- });
5457
+ return declared(200, { ok: true, ...result });
5177
5458
  }
5178
5459
  if (body.event === "address.verify" && onVerify) {
5179
5460
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
@@ -5216,16 +5497,14 @@ function createOneAddressHandler(options) {
5216
5497
  batchId: body.batch_id ?? 0,
5217
5498
  partnerId,
5218
5499
  match: matched,
5219
- note: result && typeof result.note === "string" ? result.note : void 0
5500
+ note: result && typeof result.note === "string" ? result.note : void 0,
5501
+ allowedCallbackHosts
5220
5502
  });
5221
5503
  } catch (err) {
5222
5504
  console.error("[OneAddress SDK] verify-result callback failed:", err);
5223
5505
  }
5224
5506
  }
5225
- return new Response(JSON.stringify({ ok: true, match: matched }), {
5226
- status: 200,
5227
- headers: { "Content-Type": "application/json" }
5228
- });
5507
+ return declared(200, { ok: true, match: matched });
5229
5508
  }
5230
5509
  if (body.event === "account.verify" && onAccountVerify) {
5231
5510
  let customer;
@@ -5256,21 +5535,19 @@ function createOneAddressHandler(options) {
5256
5535
  raw: body
5257
5536
  };
5258
5537
  const result = await onAccountVerify(event);
5259
- return new Response(JSON.stringify({ ok: true, ...result }), {
5260
- status: 200,
5261
- headers: { "Content-Type": "application/json" }
5262
- });
5538
+ return declared(200, { ok: true, ...result });
5263
5539
  }
5264
- if (body.event === "address.test" && onTest) {
5540
+ if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
5265
5541
  if (!isD5Body(body)) {
5266
- return new Response(JSON.stringify({ error: "address.test requires a session envelope" }), {
5542
+ return new Response(JSON.stringify({ error: "a test dispatch requires a session envelope" }), {
5267
5543
  status: 400,
5268
5544
  headers: { "Content-Type": "application/json" }
5269
5545
  });
5270
5546
  }
5271
5547
  const d5 = await buildD5Pieces(body, partnerId);
5548
+ if (!d5.address) throw new Error("[OneAddress SDK] test record carries no address");
5272
5549
  await onTest({
5273
- event: "address.test",
5550
+ event: body.event,
5274
5551
  index: typeof body.index === "number" ? body.index : void 0,
5275
5552
  total: typeof body.total === "number" ? body.total : void 0,
5276
5553
  verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
@@ -5280,21 +5557,23 @@ function createOneAddressHandler(options) {
5280
5557
  address: d5.address,
5281
5558
  raw: d5.raw
5282
5559
  });
5283
- return new Response(JSON.stringify({ ok: true, test: true }), {
5284
- status: 200,
5285
- headers: { "Content-Type": "application/json" }
5286
- });
5560
+ return declared(200, { ok: true, test: true });
5287
5561
  }
5288
5562
  const evt = typeof body.event === "string" ? body.event : "(none)";
5289
5563
  const callbackFor = {
5290
5564
  "address.verify": onVerify,
5291
5565
  "account.verify": onAccountVerify,
5292
- "address.test": onTest
5566
+ "address.test": onTest,
5567
+ // Same callback as address.test: both test variants route to onTest, so
5568
+ // an unwired stress-test event must name onTest too — not fall through
5569
+ // to the "upgrade the SDK" remedy, which cannot help (marlowe-reports#126).
5570
+ "address.test-dispatch": onTest
5293
5571
  };
5294
5572
  const callbackNameFor = {
5295
5573
  "address.verify": "onVerify",
5296
5574
  "account.verify": "onAccountVerify",
5297
- "address.test": "onTest"
5575
+ "address.test": "onTest",
5576
+ "address.test-dispatch": "onTest"
5298
5577
  };
5299
5578
  const unwired = evt in callbackFor && !callbackFor[evt] ? callbackNameFor[evt] : null;
5300
5579
  if (!warnedUnhandledEvents.has(evt)) {
@@ -5304,7 +5583,7 @@ function createOneAddressHandler(options) {
5304
5583
  // NOSONAR
5305
5584
  );
5306
5585
  }
5307
- return new Response(JSON.stringify({ ok: true, skipped: true, event: evt }), {
5586
+ return new Response(JSON.stringify({ ok: true, skipped: true, event: evt, accepted_update_types: acceptedUpdateTypes }), {
5308
5587
  status: 200,
5309
5588
  headers: { "Content-Type": "application/json" }
5310
5589
  });