@oneaddress/partner-sdk 1.8.0 → 2.1.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,28 +3652,354 @@ 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
  });
3561
3686
 
3687
+ // ../crypto/src/verify-partner-keys.ts
3688
+ async function saysRootNotConfigured(res) {
3689
+ if (res.status !== 503) return false;
3690
+ try {
3691
+ const body = await res.json();
3692
+ return typeof body.error === "string" && body.error.includes("root not configured");
3693
+ } catch {
3694
+ return false;
3695
+ }
3696
+ }
3697
+ async function outcomeFor(partnerId, key, reg, bound) {
3698
+ if (!reg.head) return "head-unusable";
3699
+ if (!key.key_signature || !key.root_key_id) {
3700
+ if (!key.countersignature_exempt) return "unsigned";
3701
+ if (headNamesPartner(reg.head, partnerId)) return "exempt-in-head";
3702
+ return bound.has(partnerId) ? "exempt" : "exempt-unbound";
3703
+ }
3704
+ const attested = await verifyPartnerKeyAttestationWithRoots(
3705
+ {
3706
+ partnerId,
3707
+ keyId: key.key_id,
3708
+ algorithm: key.algorithm,
3709
+ publicKeyB64: key.public_key_b64
3710
+ },
3711
+ key.key_signature,
3712
+ key.root_key_id,
3713
+ reg.roots
3714
+ );
3715
+ if (!attested) return "bad-attestation";
3716
+ return headNamesKey(reg.head, partnerId, key.key_id) ? "ok" : "not-in-head";
3717
+ }
3718
+ async function crossoverOutcomeFor(partnerId, crossover, reg) {
3719
+ if (!reg.head) return "head-unusable";
3720
+ return await headNamesStagedKey(reg.head, partnerId, crossover.key_id, crossover.public_key_b64) ? "ok" : "not-authorised";
3721
+ }
3722
+ function createPartnerKeyVerifier(env = {}) {
3723
+ const baseUrl = env.baseUrl ?? "";
3724
+ const report = env.report ?? (() => {
3725
+ });
3726
+ let registryPromise = null;
3727
+ function worthCaching(load) {
3728
+ return load.ok && load.registry.head !== null;
3729
+ }
3730
+ async function loadRegistry() {
3731
+ try {
3732
+ const [rootsRes, headRes] = await Promise.all([
3733
+ fetch(baseUrl + "/.well-known/oneaddress-key-registry.json", { cache: "no-cache" }),
3734
+ fetch(baseUrl + "/.well-known/oneaddress-key-registry-head.json", { cache: "no-cache" })
3735
+ ]);
3736
+ if (!rootsRes.ok) {
3737
+ const configured = await saysRootNotConfigured(rootsRes);
3738
+ return {
3739
+ ok: false,
3740
+ failure: {
3741
+ reason: configured ? "roots-not-configured" : "roots-http",
3742
+ status: rootsRes.status
3743
+ }
3744
+ };
3745
+ }
3746
+ let roots;
3747
+ try {
3748
+ const rootsBody = await rootsRes.json();
3749
+ roots = rootsBody.keys ?? [];
3750
+ } catch {
3751
+ return { ok: false, failure: { reason: "roots-unreadable", status: rootsRes.status } };
3752
+ }
3753
+ if (roots.length === 0) {
3754
+ return { ok: false, failure: { reason: "roots-empty", status: rootsRes.status } };
3755
+ }
3756
+ let head = null;
3757
+ let headVerdict = "absent";
3758
+ if (headRes.ok) {
3759
+ head = await headRes.json();
3760
+ headVerdict = await verifyRegistryHead(head, roots);
3761
+ if (headVerdict !== "ok" && headVerdict !== "expired") head = null;
3762
+ }
3763
+ return { ok: true, registry: { roots, head, headVerdict } };
3764
+ } catch {
3765
+ return { ok: false, failure: { reason: "fetch-failed" } };
3766
+ }
3767
+ }
3768
+ async function verifyActivePartnerKeys(keys, context) {
3769
+ try {
3770
+ const pending = registryPromise ?? (registryPromise = loadRegistry());
3771
+ const load = await pending;
3772
+ if (!worthCaching(load)) registryPromise = null;
3773
+ if (!load.ok) {
3774
+ report(context, { registry: "unavailable", enforced: false, ...load.failure });
3775
+ return { blocked: {}, crossoverBlocked: {} };
3776
+ }
3777
+ const reg = load.registry;
3778
+ let bound = EMPTY_BOUND;
3779
+ if (env.bindSenderHeldKeys) {
3780
+ try {
3781
+ bound = await env.bindSenderHeldKeys(keys);
3782
+ } catch {
3783
+ report(context, { binder: "threw", enforced: true });
3784
+ }
3785
+ }
3786
+ const tally = {
3787
+ "ok": [],
3788
+ "exempt": [],
3789
+ "exempt-in-head": [],
3790
+ "exempt-unbound": [],
3791
+ "unsigned": [],
3792
+ "bad-attestation": [],
3793
+ "not-in-head": [],
3794
+ "head-unusable": [],
3795
+ "error": []
3796
+ };
3797
+ const blocked = {};
3798
+ const crossoverBlocked = {};
3799
+ const crossoverTally = { "ok": [], "not-authorised": [], "head-unusable": [], "error": [] };
3800
+ for (const [partnerId, key] of Object.entries(keys)) {
3801
+ let outcome;
3802
+ try {
3803
+ outcome = await outcomeFor(partnerId, key, reg, bound);
3804
+ } catch {
3805
+ outcome = "error";
3806
+ }
3807
+ tally[outcome].push(partnerId);
3808
+ if (!ACCEPTABLE.has(outcome)) blocked[partnerId] = outcome;
3809
+ if (!key?.crossover) continue;
3810
+ let xo;
3811
+ try {
3812
+ xo = await crossoverOutcomeFor(partnerId, key.crossover, reg);
3813
+ } catch {
3814
+ xo = "error";
3815
+ }
3816
+ crossoverTally[xo].push(partnerId);
3817
+ if (xo !== "ok") crossoverBlocked[partnerId] = xo;
3818
+ }
3819
+ if (Object.keys(crossoverBlocked).length > 0) {
3820
+ const failedXo = Object.keys(crossoverTally).filter((o) => o !== "ok" && crossoverTally[o].length > 0);
3821
+ report(context, {
3822
+ headVerdict: reg.headVerdict,
3823
+ enforced: true,
3824
+ surface: "crossover",
3825
+ ...Object.fromEntries(failedXo.map((o) => [`crossover-${o}`, crossoverTally[o]]))
3826
+ });
3827
+ }
3828
+ if (Object.keys(blocked).length > 0) {
3829
+ const failed = Object.keys(tally).filter((o) => !ACCEPTABLE.has(o) && tally[o].length > 0);
3830
+ report(context, {
3831
+ headVerdict: reg.headVerdict,
3832
+ enforced: true,
3833
+ total: Object.keys(keys).length,
3834
+ ok: tally.ok.length,
3835
+ // Counted, not listed: an operator reading a real finding needs to know
3836
+ // how many keys were skipped as exempt, without the ids adding noise.
3837
+ exempt: tally.exempt.length,
3838
+ ...Object.fromEntries(failed.map((o) => [o, tally[o]]))
3839
+ });
3840
+ }
3841
+ return { blocked, crossoverBlocked };
3842
+ } catch {
3843
+ report(context, { registry: "verifier-error", enforced: false });
3844
+ return { blocked: {}, crossoverBlocked: {} };
3845
+ }
3846
+ }
3847
+ function __resetRegistryCacheForTests() {
3848
+ registryPromise = null;
3849
+ }
3850
+ return { verifyActivePartnerKeys, __resetRegistryCacheForTests };
3851
+ }
3852
+ var ACCEPTABLE, EMPTY_BOUND, PARTNER_KEY_REFUSED_MESSAGE;
3853
+ var init_verify_partner_keys = __esm({
3854
+ "../crypto/src/verify-partner-keys.ts"() {
3855
+ "use strict";
3856
+ init_partner_key_attestation();
3857
+ init_registry_head();
3858
+ ACCEPTABLE = /* @__PURE__ */ new Set(["ok", "exempt"]);
3859
+ EMPTY_BOUND = /* @__PURE__ */ new Set();
3860
+ PARTNER_KEY_REFUSED_MESSAGE = "Some services are temporarily unavailable and were not updated. Please try again in a moment.";
3861
+ }
3862
+ });
3863
+
3864
+ // ../crypto/src/sender-held-keys.ts
3865
+ function memorySenderHeldKeyStore() {
3866
+ const keys = /* @__PURE__ */ new Map();
3867
+ return {
3868
+ all: async () => [...keys.values()],
3869
+ put: async (key) => {
3870
+ keys.set(key.keyId, key);
3871
+ }
3872
+ };
3873
+ }
3874
+ function toB64(bytes) {
3875
+ let s = "";
3876
+ for (const b of bytes) s += String.fromCharCode(b);
3877
+ return btoa(s);
3878
+ }
3879
+ async function keyIdForPublicKey(spki) {
3880
+ const d = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", spki)).slice(0, 16);
3881
+ d[6] = d[6] & 15 | 128;
3882
+ d[8] = d[8] & 63 | 128;
3883
+ const h = [...d].map((b) => b.toString(16).padStart(2, "0")).join("");
3884
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
3885
+ }
3886
+ function createSenderHeldKeyBinder(storeFor) {
3887
+ let pending = null;
3888
+ async function mint() {
3889
+ if (typeof globalThis.crypto === "undefined" || !globalThis.crypto.subtle) return null;
3890
+ let store = storeFor();
3891
+ try {
3892
+ const existing = await store.all();
3893
+ if (existing.length > 0) {
3894
+ return [...existing].sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0];
3895
+ }
3896
+ } catch {
3897
+ store = memorySenderHeldKeyStore();
3898
+ }
3899
+ const pair = await globalThis.crypto.subtle.generateKey(
3900
+ { name: "ECDH", namedCurve: "P-256" },
3901
+ false,
3902
+ ["deriveBits"]
3903
+ );
3904
+ const spki = new Uint8Array(await globalThis.crypto.subtle.exportKey("spki", pair.publicKey));
3905
+ const key = {
3906
+ keyId: await keyIdForPublicKey(spki),
3907
+ publicKeyB64: toB64(spki),
3908
+ privateKey: pair.privateKey,
3909
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
3910
+ };
3911
+ try {
3912
+ await store.put(key);
3913
+ } catch {
3914
+ }
3915
+ return key;
3916
+ }
3917
+ function getOrCreate() {
3918
+ pending ??= mint().catch(() => {
3919
+ pending = null;
3920
+ return null;
3921
+ });
3922
+ return pending;
3923
+ }
3924
+ const bind = async (keys) => {
3925
+ const bound = /* @__PURE__ */ new Set();
3926
+ const flagged = Object.entries(keys).filter(([, k]) => k?.countersignature_exempt === true);
3927
+ if (flagged.length === 0) return bound;
3928
+ const own = await getOrCreate();
3929
+ if (!own) return bound;
3930
+ for (const [partnerId, k] of flagged) {
3931
+ k.key_id = own.keyId;
3932
+ k.public_key_b64 = own.publicKeyB64;
3933
+ k.algorithm = SENDER_HELD_KEY_ALGORITHM;
3934
+ k.key_signature = null;
3935
+ k.root_key_id = null;
3936
+ delete k.crossover;
3937
+ bound.add(partnerId);
3938
+ }
3939
+ return bound;
3940
+ };
3941
+ return Object.assign(bind, { getOrCreate });
3942
+ }
3943
+ async function openSealedWithSenderHeldKey(share, envelope, partnerId, store) {
3944
+ let keys;
3945
+ try {
3946
+ keys = await store.all();
3947
+ } catch {
3948
+ return { ok: false, reason: "no-key" };
3949
+ }
3950
+ const key = keys.find((k) => k.keyId === share.key_id);
3951
+ if (!key) return { ok: false, reason: "no-key" };
3952
+ try {
3953
+ const data = await decryptSession(share, envelope, {
3954
+ name: "this device",
3955
+ async deriveSharedSecret(epkSpki) {
3956
+ const epk = await globalThis.crypto.subtle.importKey(
3957
+ "spki",
3958
+ epkSpki,
3959
+ { name: "ECDH", namedCurve: "P-256" },
3960
+ false,
3961
+ []
3962
+ );
3963
+ return new Uint8Array(
3964
+ await globalThis.crypto.subtle.deriveBits({ name: "ECDH", public: epk }, key.privateKey, 256)
3965
+ );
3966
+ }
3967
+ }, partnerId);
3968
+ return { ok: true, data };
3969
+ } catch {
3970
+ return { ok: false, reason: "unreadable" };
3971
+ }
3972
+ }
3973
+ var SENDER_HELD_KEY_ALGORITHM;
3974
+ var init_sender_held_keys = __esm({
3975
+ "../crypto/src/sender-held-keys.ts"() {
3976
+ "use strict";
3977
+ init_src();
3978
+ SENDER_HELD_KEY_ALGORITHM = "ECDH-P256-AES-GCM-256";
3979
+ }
3980
+ });
3981
+
3562
3982
  // ../crypto/src/index.ts
3563
3983
  var src_exports = {};
3564
3984
  __export(src_exports, {
3565
3985
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
3986
+ ENDPOINT_FAILURE_THRESHOLD: () => ENDPOINT_FAILURE_THRESHOLD,
3566
3987
  PARTNER_KEY_ATTESTATION_ALG: () => PARTNER_KEY_ATTESTATION_ALG,
3567
3988
  PARTNER_KEY_ATTESTATION_V1: () => PARTNER_KEY_ATTESTATION_V1,
3989
+ PARTNER_KEY_REFUSED_MESSAGE: () => PARTNER_KEY_REFUSED_MESSAGE,
3568
3990
  REGISTRY_HEAD_ALG: () => REGISTRY_HEAD_ALG,
3569
3991
  REGISTRY_HEAD_V1: () => REGISTRY_HEAD_V1,
3992
+ REGISTRY_HEAD_V2: () => REGISTRY_HEAD_V2,
3993
+ SENDER_HELD_KEY_ALGORITHM: () => SENDER_HELD_KEY_ALGORITHM,
3570
3994
  buildPartnerKeyAttestation: () => buildPartnerKeyAttestation,
3571
3995
  buildRegistryHeadStatement: () => buildRegistryHeadStatement,
3996
+ classifyEndpointProbe: () => classifyEndpointProbe,
3572
3997
  cleanNameAliases: () => cleanNameAliases,
3573
3998
  computeBlindIndex: () => computeBlindIndex,
3574
3999
  computeCustomerBlindIndex: () => computeCustomerBlindIndex,
4000
+ countsAsFailure: () => countsAsFailure,
4001
+ createPartnerKeyVerifier: () => createPartnerKeyVerifier,
4002
+ createSenderHeldKeyBinder: () => createSenderHeldKeyBinder,
3575
4003
  decryptAddress: () => decryptAddress,
3576
4004
  decryptSession: () => decryptSession,
3577
4005
  encryptAddressForAll: () => encryptAddressForAll,
@@ -3583,12 +4011,18 @@ __export(src_exports, {
3583
4011
  generateHybridPartnerKeyPair: () => generateHybridPartnerKeyPair,
3584
4012
  generatePartnerKeyPair: () => generatePartnerKeyPair,
3585
4013
  headNamesKey: () => headNamesKey,
4014
+ headNamesPartner: () => headNamesPartner,
4015
+ headNamesStagedKey: () => headNamesStagedKey,
3586
4016
  isEmailLike: () => isEmailLike,
3587
4017
  isFreshTimestamp: () => isFreshTimestamp,
3588
4018
  isIpLiteralHost: () => isIpLiteralHost,
3589
4019
  isSafeWebhookUrl: () => isSafeWebhookUrl,
4020
+ keyIdForPublicKey: () => keyIdForPublicKey,
4021
+ memorySenderHeldKeyStore: () => memorySenderHeldKeyStore,
3590
4022
  normaliseAddress: () => normaliseAddress,
3591
4023
  normalizeForBlindIndex: () => normalizeForBlindIndex,
4024
+ openSealedWithSenderHeldKey: () => openSealedWithSenderHeldKey,
4025
+ partnerKeyFingerprint: () => partnerKeyFingerprint,
3592
4026
  rootKeyIdFromSpki: () => rootKeyIdFromSpki,
3593
4027
  rootKeyIdFromSpkiB64: () => rootKeyIdFromSpkiB64,
3594
4028
  signWebhookPayload: () => signWebhookPayload,
@@ -3972,21 +4406,21 @@ async function encryptSessionForAll(partners) {
3972
4406
  );
3973
4407
  return Object.fromEntries(results.map((r) => [r.partner_id, r]));
3974
4408
  }
3975
- async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
4409
+ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expectedAlg) {
3976
4410
  if (share.alg !== "ECDH-ES+HKDF-SHA256+A256GCM" && share.alg !== "RSA-OAEP-256+A256GCM" && share.alg !== "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3977
4411
  throw new Error(`decryptSession: unsupported alg ${share.alg}`);
3978
4412
  }
3979
4413
  if (share.v !== 2) {
3980
4414
  throw new Error(`decryptSession: unsupported share version ${share.v}`);
3981
4415
  }
4416
+ if (expectedAlg && share.alg !== expectedAlg) {
4417
+ throw new Error(
4418
+ `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.`
4419
+ );
4420
+ }
3982
4421
  const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
3983
4422
  if (ops) {
3984
- if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3985
- throw new Error(
3986
- `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.`
3987
- );
3988
- }
3989
- const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : "deriveSharedSecret";
4423
+ const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM" ? "decapsulateXWing" : "deriveSharedSecret";
3990
4424
  if (typeof ops[needed] !== "function") {
3991
4425
  throw new Error(
3992
4426
  `decryptSession: key source "${ops.name}" cannot do ${needed}, which ${share.alg} requires.`
@@ -3998,7 +4432,13 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3998
4432
  if (!share.epk) {
3999
4433
  throw new Error("decryptSession: hybrid share missing epk (KEM ciphertext)");
4000
4434
  }
4001
- const sharedSecret = XWing.decapsulate(b64UrlToBytes(share.epk), b64ToBytes3(privateKeyB64));
4435
+ const kemCiphertext = b64UrlToBytes(share.epk);
4436
+ const sharedSecret = ops ? toArrayBuffer(await ops.decapsulateXWing(kemCiphertext)) : toArrayBuffer(XWing.decapsulate(kemCiphertext, b64ToBytes3(privateKeyB64)));
4437
+ if (ops && sharedSecret.byteLength !== 32) {
4438
+ throw new Error(
4439
+ `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; X-Wing decapsulation is 32 bytes with no KDF applied.`
4440
+ );
4441
+ }
4002
4442
  const wrappedBytes = b64UrlToBytes(share.wrapped_key);
4003
4443
  if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
4004
4444
  throw new Error("decryptSession: wrapped_key too short");
@@ -4213,9 +4653,20 @@ var init_src = __esm({
4213
4653
  init_hybrid();
4214
4654
  init_replay_window();
4215
4655
  init_safe_url();
4656
+ init_endpoint_health();
4216
4657
  init_partner_key_attestation();
4217
4658
  init_registry_head();
4218
- subtle = () => globalThis.crypto.subtle;
4659
+ init_verify_partner_keys();
4660
+ init_sender_held_keys();
4661
+ subtle = () => {
4662
+ const webcrypto = globalThis.crypto;
4663
+ if (!webcrypto?.subtle) {
4664
+ throw new Error(
4665
+ "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."
4666
+ );
4667
+ }
4668
+ return webcrypto.subtle;
4669
+ };
4219
4670
  AU_STATE_FULL = {
4220
4671
  "new south wales": "NSW",
4221
4672
  "victoria": "VIC",
@@ -4249,6 +4700,8 @@ __export(index_exports, {
4249
4700
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
4250
4701
  OUTBOX_LEASE_COLUMNS: () => OUTBOX_LEASE_COLUMNS,
4251
4702
  SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
4703
+ _resetOnceWarningsForTests: () => _resetOnceWarningsForTests,
4704
+ buildSignedTestWebhook: () => buildSignedTestWebhook,
4252
4705
  canonicalD5LoaForm: () => canonicalD5LoaForm,
4253
4706
  compareAddresses: () => compareAddresses,
4254
4707
  computeBlindIndex: () => computeBlindIndex,
@@ -4292,6 +4745,45 @@ init_src();
4292
4745
  var CURRENT_VERSION = "2026.1";
4293
4746
  var SUPPORTED_VERSIONS = ["2026.1"];
4294
4747
 
4748
+ // ../protocol/src/d5-body.ts
4749
+ var D5_BODY_ALWAYS = [
4750
+ "event",
4751
+ "id_verification",
4752
+ "key_share_expiry",
4753
+ "oneaddress_version",
4754
+ "partner_id",
4755
+ "session_envelope",
4756
+ "session_key_share",
4757
+ "stripe_session_id",
4758
+ "timestamp",
4759
+ "update_id",
4760
+ "user_id"
4761
+ ];
4762
+ var D5_BODY_CONDITIONAL = {
4763
+ /**
4764
+ * The signed Letter of Authority, sealed to the same key_id as the session.
4765
+ * Present whenever the partner has a usable key — i.e. on every dispatch a
4766
+ * live partner receives. Omitted best-effort when no key is available, which
4767
+ * is a state a live partner is never in.
4768
+ */
4769
+ loa_encrypted: "partner has a usable encryption key",
4770
+ /**
4771
+ * The shared webhook event id. Set ONLY on a key-crossover copy, where every
4772
+ * copy of one update carries the same id so a receiver holding more than one
4773
+ * rotation key applies it once. Absent on an ordinary dispatch, whose
4774
+ * receiver idempotency falls back to the `X-OneAddress-Dispatch` header.
4775
+ */
4776
+ id: "key-crossover copy only",
4777
+ /** The sibling marker naming the other key_ids this update was sealed to. */
4778
+ crossover_key_ids: "key-crossover copy only"
4779
+ };
4780
+ var D5_BODY_DRILL_ONLY = ["conformance"];
4781
+ var D5_BODY_ALL_ALLOWED = [
4782
+ ...D5_BODY_ALWAYS,
4783
+ ...Object.keys(D5_BODY_CONDITIONAL),
4784
+ ...D5_BODY_DRILL_ONLY
4785
+ ];
4786
+
4295
4787
  // src/index.ts
4296
4788
  init_src();
4297
4789
  init_src();
@@ -4418,9 +4910,17 @@ function createOutboxConsumer(opts2) {
4418
4910
  if (!Number.isFinite(batchSize) || batchSize < 1) {
4419
4911
  throw new Error(`[OneAddress SDK] batchSize must be a positive integer, got ${opts2.batchSize}`);
4420
4912
  }
4913
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 0) {
4914
+ throw new Error(`[OneAddress SDK] maxAttempts must be an integer >= 0, got ${opts2.maxAttempts}`);
4915
+ }
4421
4916
  const ph = d.ph;
4422
4917
  const token = () => (0, import_node_crypto.randomBytes)(16).toString("hex");
4423
4918
  const stamp = (at) => toOutboxTimestamp(dialect, at);
4919
+ const heldTokens = /* @__PURE__ */ new Map();
4920
+ const claimPredicate = (dispatchId, firstPh) => {
4921
+ const tok = heldTokens.get(dispatchId);
4922
+ return tok === void 0 ? { sql: `dispatch_id = ${ph(firstPh)}`, params: [dispatchId] } : { sql: `dispatch_id = ${ph(firstPh)} AND ${CLAIM_TOKEN} = ${ph(firstPh + 1)}`, params: [dispatchId, tok] };
4923
+ };
4424
4924
  const claimable = (cutoffPh) => `written_at IS NOT NULL AND processed_at IS NULL AND (${CLAIMED_AT} IS NULL OR ${CLAIMED_AT} < ${cutoffPh})` + (maxAttempts > 0 ? ` AND (${ATTEMPTS} IS NULL OR ${ATTEMPTS} < ${maxAttempts})` : "");
4425
4925
  const toRow = (r) => ({
4426
4926
  dispatchId: String(r.dispatch_id ?? r.dispatchId ?? ""),
@@ -4428,6 +4928,10 @@ function createOutboxConsumer(opts2) {
4428
4928
  attempts: Number(r[ATTEMPTS] ?? 0) || 0,
4429
4929
  fields: r
4430
4930
  });
4931
+ const claimed = (rows, tok) => rows.map(toRow).map((row) => {
4932
+ heldTokens.set(row.dispatchId, tok);
4933
+ return row;
4934
+ });
4431
4935
  async function claimBatch() {
4432
4936
  const at = now();
4433
4937
  const claimedAt = stamp(at);
@@ -4438,14 +4942,14 @@ function createOutboxConsumer(opts2) {
4438
4942
  `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize} FOR UPDATE SKIP LOCKED) RETURNING *`,
4439
4943
  [claimedAt, tok, cutoff]
4440
4944
  );
4441
- return rows2.map(toRow);
4945
+ return claimed(rows2, tok);
4442
4946
  }
4443
4947
  if (dialect === "mssql") {
4444
4948
  const rows2 = await opts2.query(
4445
4949
  `UPDATE TOP (${batchSize}) ${table} WITH (UPDLOCK, READPAST, ROWLOCK) SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} OUTPUT INSERTED.* WHERE ${claimable(ph(3))}`,
4446
4950
  [claimedAt, tok, cutoff]
4447
4951
  );
4448
- return rows2.map(toRow);
4952
+ return claimed(rows2, tok);
4449
4953
  }
4450
4954
  const claim = dialect === "mysql" ? `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize}` : `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize})`;
4451
4955
  await opts2.query(claim, [claimedAt, tok, cutoff]);
@@ -4453,7 +4957,7 @@ function createOutboxConsumer(opts2) {
4453
4957
  `SELECT * FROM ${table} WHERE ${CLAIM_TOKEN} = ${ph(1)} AND processed_at IS NULL`,
4454
4958
  [tok]
4455
4959
  );
4456
- return rows.map(toRow);
4960
+ return claimed(rows, tok);
4457
4961
  }
4458
4962
  return {
4459
4963
  async ensureSchema() {
@@ -4482,23 +4986,29 @@ function createOutboxConsumer(opts2) {
4482
4986
  },
4483
4987
  claimBatch,
4484
4988
  async markProcessed(dispatchId) {
4989
+ const where = claimPredicate(dispatchId, 2);
4485
4990
  await opts2.query(
4486
- `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
4487
- [stamp(now()), dispatchId]
4991
+ `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
4992
+ [stamp(now()), ...where.params]
4488
4993
  );
4994
+ heldTokens.delete(dispatchId);
4489
4995
  },
4490
4996
  async markFailed(dispatchId, error) {
4491
4997
  const message = error instanceof Error ? error.message : String(error);
4998
+ const where = claimPredicate(dispatchId, 2);
4492
4999
  await opts2.query(
4493
- `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
4494
- [message.slice(0, 500), dispatchId]
5000
+ `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
5001
+ [message.slice(0, 500), ...where.params]
4495
5002
  );
5003
+ heldTokens.delete(dispatchId);
4496
5004
  },
4497
5005
  async release(dispatchId) {
5006
+ const where = claimPredicate(dispatchId, 1);
4498
5007
  await opts2.query(
4499
- `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(1)}`,
4500
- [dispatchId]
5008
+ `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
5009
+ where.params
4501
5010
  );
5011
+ heldTokens.delete(dispatchId);
4502
5012
  },
4503
5013
  async process(handler) {
4504
5014
  const rows = await claimBatch();
@@ -4539,15 +5049,62 @@ function createOutboxConsumer(opts2) {
4539
5049
  }
4540
5050
 
4541
5051
  // src/index.ts
5052
+ var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
4542
5053
  function createSqlIdempotencyStore(opts2) {
4543
5054
  const table = opts2.table ?? "oneaddress_dispatches";
4544
- const ph = opts2.placeholder ?? ((n) => `$${n}`);
5055
+ const dialect = opts2.dialect ?? "postgres";
5056
+ if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
5057
+ throw new Error(
5058
+ `[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
5059
+ );
5060
+ }
5061
+ const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
5062
+ const ph = opts2.placeholder ?? defaultPh;
4545
5063
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
4546
5064
  throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
4547
5065
  }
4548
5066
  const completedOf = (row) => row?.completed_at ?? row?.completedAt ?? null;
5067
+ const tokenOf = (row) => row?.claim_token ?? row?.claimToken ?? null;
5068
+ async function claimByToken(dispatchId) {
5069
+ const token = import_crypto.default.randomBytes(16).toString("hex");
5070
+ await opts2.query(
5071
+ dialect === "mysql" ? `INSERT IGNORE INTO ${table} (dispatch_id, claim_token) VALUES (${ph(1)}, ${ph(2)})` : `INSERT INTO ${table} (dispatch_id, claim_token) SELECT ${ph(1)}, ${ph(2)} WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE dispatch_id = ${ph(1)})`,
5072
+ [dispatchId, token]
5073
+ );
5074
+ const rows = await opts2.query(
5075
+ `SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
5076
+ [dispatchId]
5077
+ );
5078
+ if (tokenOf(rows[0]) === token) return "fresh";
5079
+ return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
5080
+ }
5081
+ async function setByUpsert(dispatchId) {
5082
+ if (dialect === "mysql") {
5083
+ await opts2.query(
5084
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE completed_at = CURRENT_TIMESTAMP`,
5085
+ [dispatchId]
5086
+ );
5087
+ return;
5088
+ }
5089
+ if (dialect === "mssql") {
5090
+ await opts2.query(
5091
+ `UPDATE ${table} SET completed_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)}`,
5092
+ [dispatchId]
5093
+ );
5094
+ await opts2.query(
5095
+ `INSERT INTO ${table} (dispatch_id, completed_at) SELECT ${ph(1)}, CURRENT_TIMESTAMP WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE dispatch_id = ${ph(1)})`,
5096
+ [dispatchId]
5097
+ );
5098
+ return;
5099
+ }
5100
+ await opts2.query(
5101
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
5102
+ [dispatchId]
5103
+ );
5104
+ }
4549
5105
  return {
4550
5106
  async claim(dispatchId) {
5107
+ if (dialect === "mysql" || dialect === "mssql") return claimByToken(dispatchId);
4551
5108
  const inserted = await opts2.query(
4552
5109
  `INSERT INTO ${table} (dispatch_id) VALUES (${ph(1)}) ON CONFLICT (dispatch_id) DO NOTHING RETURNING dispatch_id`,
4553
5110
  [dispatchId]
@@ -4575,10 +5132,7 @@ function createSqlIdempotencyStore(opts2) {
4575
5132
  return rows.length > 0 && Boolean(completedOf(rows[0]));
4576
5133
  },
4577
5134
  async set(dispatchId) {
4578
- await opts2.query(
4579
- `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
4580
- [dispatchId]
4581
- );
5135
+ await setByUpsert(dispatchId);
4582
5136
  }
4583
5137
  };
4584
5138
  }
@@ -4604,7 +5158,8 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
4604
5158
  function base64urlToBuffer(b64) {
4605
5159
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
4606
5160
  }
4607
- function pemToBase64(pem) {
5161
+ function pemToBase64(pemRaw) {
5162
+ const pem = pemRaw.replace(/(?:\\r)?\\n/g, "\n");
4608
5163
  const begin = pem.indexOf("-----BEGIN");
4609
5164
  if (begin === -1) return pem.replace(/\s/g, "");
4610
5165
  const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
@@ -4664,13 +5219,14 @@ async function decryptAddress2(payload, privateKeyPem, partnerId) {
4664
5219
  );
4665
5220
  return JSON.parse(new TextDecoder().decode(plaintext));
4666
5221
  }
4667
- async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId) {
5222
+ async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
4668
5223
  const { decryptSession: decryptSessionCrypto } = await Promise.resolve().then(() => (init_src(), src_exports));
4669
5224
  return decryptSessionCrypto(
4670
5225
  share,
4671
5226
  envelopeB64,
4672
5227
  typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
4673
- partnerId
5228
+ partnerId,
5229
+ expectedAlg
4674
5230
  );
4675
5231
  }
4676
5232
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
@@ -4811,6 +5367,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
4811
5367
  `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
4812
5368
  );
4813
5369
  }
5370
+ const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
5371
+ if (parsedBase.protocol !== "https:" && !loopback) {
5372
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
5373
+ }
4814
5374
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
4815
5375
  const res = await fetch(url);
4816
5376
  if (!res.ok) {
@@ -4887,12 +5447,13 @@ async function verifyD5LOA(loa, publicKeyPem) {
4887
5447
  return false;
4888
5448
  }
4889
5449
  }
4890
- async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
5450
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expectedAlg) {
4891
5451
  const data = await decryptSession2(
4892
5452
  loaEncrypted.session_key_share,
4893
5453
  loaEncrypted.session_envelope,
4894
5454
  privateKeyPem,
4895
- partnerId
5455
+ partnerId,
5456
+ expectedAlg
4896
5457
  );
4897
5458
  return data;
4898
5459
  }
@@ -5002,12 +5563,32 @@ function compareAddresses(a, b) {
5002
5563
  if (aCountry && bCountry && aCountry !== bCountry) return false;
5003
5564
  return true;
5004
5565
  }
5566
+ function isAllowedCallbackHost(raw, extraHosts) {
5567
+ let host;
5568
+ try {
5569
+ const u = new URL(raw);
5570
+ if (u.protocol !== "https:") return false;
5571
+ host = u.hostname.toLowerCase();
5572
+ } catch {
5573
+ return false;
5574
+ }
5575
+ if (host === "oneaddress.io" || host.endsWith(".oneaddress.io")) return true;
5576
+ const envRaw = typeof process !== "undefined" ? process.env?.OA_CALLBACK_HOST_ALLOWLIST ?? "" : "";
5577
+ const allowed = [
5578
+ ...envRaw.split(",").map((h) => h.trim().toLowerCase()),
5579
+ ...(extraHosts ?? []).map((h) => h.trim().toLowerCase())
5580
+ ].filter(Boolean);
5581
+ return allowed.includes(host);
5582
+ }
5005
5583
  async function sendVerifyResult(params) {
5006
- const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
5584
+ const { callbackUrl, callbackToken, batchId, partnerId, match, note, allowedCallbackHosts } = params;
5007
5585
  const safe = isSafeWebhookUrl(callbackUrl);
5008
5586
  if (!safe.ok) {
5009
5587
  throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
5010
5588
  }
5589
+ if (!isAllowedCallbackHost(callbackUrl, allowedCallbackHosts)) {
5590
+ throw new Error(`[OneAddress SDK] refusing verify-result callback to non-OneAddress host: ${callbackUrl}`);
5591
+ }
5011
5592
  const res = await fetch(callbackUrl, {
5012
5593
  method: "POST",
5013
5594
  headers: { "Content-Type": "application/json" },
@@ -5024,33 +5605,159 @@ async function sendVerifyResult(params) {
5024
5605
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
5025
5606
  }
5026
5607
  }
5027
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
5608
+ var UPDATE_TYPE_ORDER = ["address", "phone", "email"];
5609
+ function normaliseAcceptedUpdateTypes(raw) {
5610
+ const kept = new Set(Array.isArray(raw) ? raw.filter((v) => typeof v === "string") : []);
5611
+ return UPDATE_TYPE_ORDER.filter((t) => t === "address" || kept.has(t));
5612
+ }
5613
+ function readUpdateTypes(raw) {
5614
+ if (raw === void 0 || raw === null) return ["address"];
5615
+ if (!Array.isArray(raw)) return null;
5616
+ if (raw.length === 0) return ["address"];
5617
+ const out = [];
5618
+ for (const v of raw) {
5619
+ if (typeof v !== "string" || !UPDATE_TYPE_ORDER.includes(v)) return null;
5620
+ if (!out.includes(v)) out.push(v);
5621
+ }
5622
+ return out;
5623
+ }
5624
+ var InvalidUpdateTypesError = class extends Error {
5625
+ constructor(raw) {
5626
+ super("[OneAddress SDK] update_types names a kind this build does not know");
5627
+ this.raw = raw;
5628
+ this.name = "InvalidUpdateTypesError";
5629
+ }
5630
+ };
5631
+ function requireContactValue(kind, value) {
5632
+ if (typeof value !== "string" || value === "") {
5633
+ throw new Error(
5634
+ `[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.`
5635
+ );
5636
+ }
5637
+ return value;
5638
+ }
5639
+ var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
5028
5640
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
5641
+ var warnedConsentUnverified = false;
5642
+ var warnedNoIdempotencyStore = false;
5643
+ function _resetOnceWarningsForTests() {
5644
+ warnedConsentUnverified = false;
5645
+ warnedNoIdempotencyStore = false;
5646
+ }
5647
+ var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
5648
+ var XWING_SEED_BYTES = 32;
5649
+ function assertUsablePrivateKey(privateKeyPem) {
5650
+ if (typeof privateKeyPem !== "string") {
5651
+ if (!privateKeyPem || typeof privateKeyPem !== "object" || typeof privateKeyPem.name !== "string") {
5652
+ throw new Error("[OneAddress SDK] privateKeyPem must be a PEM string or a PrivateKeyOperations delegate");
5653
+ }
5654
+ return;
5655
+ }
5656
+ if (privateKeyPem.trim() === "") {
5657
+ throw new Error("[OneAddress SDK] privateKeyPem is required: set it to your PKCS#8 private key from the Partner Portal");
5658
+ }
5659
+ const der = pemToBuffer(privateKeyPem);
5660
+ if (der.length === XWING_SEED_BYTES) return;
5661
+ try {
5662
+ import_crypto.default.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
5663
+ } catch (err) {
5664
+ const refused = new Error(
5665
+ `[OneAddress SDK] privateKeyPem does not import as a PKCS#8 private key (${err instanceof Error ? err.message : String(err)}). Paste the whole key including the BEGIN/END lines; a key stored as one line with literal \\n sequences is accepted, a truncated one is not.`
5666
+ );
5667
+ refused.cause = err;
5668
+ throw refused;
5669
+ }
5670
+ }
5671
+ function requirePemFor(purpose, key) {
5672
+ if (typeof key === "string") return key;
5673
+ throw new Error(
5674
+ `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
5675
+ );
5676
+ }
5677
+ function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
5678
+ if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
5679
+ if (loa.update_uid !== envelopeUpdateUid) {
5680
+ throw new Error(
5681
+ "[OneAddress SDK] D5 LOA is for a different update than the envelope it arrived with (update_uid mismatch); refusing rather than applying an address under someone else's consent"
5682
+ );
5683
+ }
5684
+ }
5029
5685
  function createOneAddressHandler(options) {
5030
5686
  const {
5031
5687
  webhookSecret,
5032
5688
  previousWebhookSecret,
5033
5689
  webhookSecretGraceUntil,
5034
5690
  privateKeyPem,
5691
+ expectedAlg,
5692
+ keyId,
5035
5693
  loaPublicKeyPem,
5694
+ requireLoa = Boolean(loaPublicKeyPem),
5695
+ confirm,
5036
5696
  onUpdate,
5037
5697
  onVerify,
5038
5698
  onAccountVerify,
5039
5699
  onTest,
5040
5700
  timestampToleranceSecs = 300,
5041
- idempotencyStore
5701
+ idempotencyStore,
5702
+ acceptedUpdateTypes: acceptedUpdateTypesRaw,
5703
+ allowedCallbackHosts
5042
5704
  } = options;
5705
+ if (typeof webhookSecret !== "string" || webhookSecret === "") {
5706
+ throw new Error("[OneAddress SDK] webhookSecret is required: an empty secret would verify no signature at all");
5707
+ }
5708
+ assertUsablePrivateKey(privateKeyPem);
5709
+ if (typeof timestampToleranceSecs !== "number" || !Number.isFinite(timestampToleranceSecs) || timestampToleranceSecs <= 0 || timestampToleranceSecs > MAX_TIMESTAMP_TOLERANCE_SECS) {
5710
+ throw new Error(
5711
+ `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
5712
+ );
5713
+ }
5714
+ if (webhookSecretGraceUntil !== void 0) {
5715
+ const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
5716
+ if (Number.isNaN(until)) {
5717
+ throw new Error(`[OneAddress SDK] webhookSecretGraceUntil is not a date: ${String(webhookSecretGraceUntil)}`);
5718
+ }
5719
+ }
5720
+ if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
5721
+ throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
5722
+ }
5723
+ function enforceLoaPresence(body) {
5724
+ const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
5725
+ if (present) return;
5726
+ if (requireLoa) {
5727
+ throw new Error(
5728
+ "[OneAddress SDK] dispatch carries no loa_encrypted and requireLoa is on: refusing to apply an update whose consent proof is missing"
5729
+ );
5730
+ }
5731
+ if (!warnedConsentUnverified) {
5732
+ warnedConsentUnverified = true;
5733
+ console.warn(
5734
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5735
+ "[OneAddress SDK] a dispatch arrived with no loa_encrypted and requireLoa is off, so consent for this update is UNVERIFIED. Set loaPublicKeyPem (which turns requireLoa on) to refuse such dispatches. Logged once per process."
5736
+ );
5737
+ }
5738
+ }
5739
+ const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
5740
+ function declared(status, payload) {
5741
+ return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
5742
+ status,
5743
+ headers: { "Content-Type": "application/json" }
5744
+ });
5745
+ }
5043
5746
  async function buildD5Pieces(body, partnerId) {
5044
5747
  const share = body.session_key_share;
5045
- const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId);
5046
- const address = validateAddress({
5748
+ const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
5749
+ const updateTypes = readUpdateTypes(data.update_types);
5750
+ if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
5751
+ const address = updateTypes.includes("address") ? validateAddress({
5047
5752
  street: data.new_address?.street,
5048
5753
  suburb: data.new_address?.suburb,
5049
5754
  state: data.new_address?.state,
5050
5755
  postcode: data.new_address?.postcode,
5051
5756
  country: data.new_address?.country,
5052
5757
  updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
5053
- });
5758
+ }) : void 0;
5759
+ const newPhone = updateTypes.includes("phone") ? requireContactValue("phone", data.new_phone) : void 0;
5760
+ const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
5054
5761
  const customer = {
5055
5762
  email: "",
5056
5763
  name: data.verified_name ?? "",
@@ -5063,19 +5770,29 @@ function createOneAddressHandler(options) {
5063
5770
  loa = await decryptLoaEncrypted(
5064
5771
  body.loa_encrypted,
5065
5772
  privateKeyPem,
5066
- partnerId
5773
+ partnerId,
5774
+ expectedAlg
5067
5775
  );
5068
5776
  loa_ref = d5LoaRef(loa);
5069
5777
  if (loaPublicKeyPem) {
5070
5778
  const valid = await verifyD5LOA(loa, loaPublicKeyPem);
5071
5779
  if (!valid) throw new Error("D5 LOA signature verification failed");
5072
5780
  }
5781
+ assertLoaBoundToEnvelope(loa, data.update_uid);
5073
5782
  }
5074
- return { address, customer, loa, loa_ref, raw: data };
5783
+ return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
5075
5784
  }
5076
5785
  function isD5Body(body) {
5077
5786
  return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
5078
5787
  }
5788
+ function isCrossoverSiblingToSkip(body) {
5789
+ if (!keyId || !isD5Body(body)) return false;
5790
+ const share = body.session_key_share;
5791
+ const shareKeyId = typeof share?.key_id === "string" ? share.key_id : "";
5792
+ if (!shareKeyId || shareKeyId === keyId) return false;
5793
+ const siblings = body.crossover_key_ids;
5794
+ return Array.isArray(siblings) && siblings.includes(keyId);
5795
+ }
5079
5796
  return async function handler(req) {
5080
5797
  const rawBody = await req.text();
5081
5798
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
@@ -5094,7 +5811,11 @@ function createOneAddressHandler(options) {
5094
5811
  }
5095
5812
  let body;
5096
5813
  try {
5097
- body = JSON.parse(rawBody);
5814
+ const parsed = JSON.parse(rawBody);
5815
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
5816
+ throw new TypeError("body is not a JSON object");
5817
+ }
5818
+ body = parsed;
5098
5819
  } catch {
5099
5820
  return new Response(JSON.stringify({ error: "Invalid JSON" }), {
5100
5821
  status: 400,
@@ -5111,51 +5832,86 @@ function createOneAddressHandler(options) {
5111
5832
  const partnerId = body.partner_id ?? "";
5112
5833
  const tsNum = Number(tsHeader);
5113
5834
  const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
5835
+ if (isCrossoverSiblingToSkip(body)) {
5836
+ return declared(200, { ok: true, skipped: true, crossover: true });
5837
+ }
5114
5838
  if (dispatchId) {
5115
5839
  if (!idempotencyStore) {
5116
- if (process.env.NODE_ENV === "test") {
5840
+ const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
5841
+ if (nodeEnv === "test") {
5117
5842
  throw new Error(
5118
5843
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
5119
5844
  );
5120
5845
  }
5846
+ if (!warnedNoIdempotencyStore) {
5847
+ warnedNoIdempotencyStore = true;
5848
+ console.warn(
5849
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5850
+ "[OneAddress SDK] a dispatch arrived with X-OneAddress-Dispatch and no idempotencyStore is wired, so a retried delivery will be processed again. Pass idempotencyStore: createSqlIdempotencyStore({ query }) to createOneAddressHandler. Logged once per process."
5851
+ );
5852
+ }
5121
5853
  } else if (idempotencyStore.claim) {
5122
5854
  const claim = await idempotencyStore.claim(dispatchId);
5123
5855
  if (claim === "duplicate") {
5124
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
5125
- status: 200,
5126
- headers: { "Content-Type": "application/json" }
5127
- });
5856
+ return declared(200, { ok: true, duplicate: true });
5128
5857
  }
5129
5858
  } else {
5130
5859
  const alreadySeen = await idempotencyStore.has(dispatchId);
5131
5860
  if (alreadySeen) {
5132
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
5133
- status: 200,
5134
- headers: { "Content-Type": "application/json" }
5135
- });
5861
+ return declared(200, { ok: true, duplicate: true });
5136
5862
  }
5137
5863
  }
5138
5864
  }
5139
5865
  try {
5140
- if (body.event === "address.updated") {
5866
+ if (body.event === "address.updated" || body.event === "contact.updated") {
5867
+ const wireEvent = body.event;
5141
5868
  let event;
5869
+ enforceLoaPresence(body);
5142
5870
  if (isD5Body(body)) {
5143
- const d5 = await buildD5Pieces(body, partnerId);
5871
+ let d5;
5872
+ try {
5873
+ d5 = await buildD5Pieces(body, partnerId);
5874
+ } catch (err) {
5875
+ if (err instanceof InvalidUpdateTypesError) {
5876
+ return declared(422, {
5877
+ error: "invalid_update_types",
5878
+ 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."
5879
+ });
5880
+ }
5881
+ throw err;
5882
+ }
5883
+ const notAccepted = d5.updateTypes.filter((t) => !acceptedUpdateTypes.includes(t));
5884
+ if (notAccepted.length > 0) {
5885
+ return declared(422, {
5886
+ error: "update_type_not_accepted",
5887
+ update_types: notAccepted,
5888
+ 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."
5889
+ });
5890
+ }
5144
5891
  event = {
5145
- event: "address.updated",
5892
+ event: wireEvent,
5146
5893
  version: body.oneaddress_version ?? body.version ?? "2.0",
5147
5894
  id: body.id ?? "",
5148
5895
  timestamp: tsNum,
5149
5896
  partner_id: partnerId,
5150
5897
  dispatchId,
5151
5898
  customer: d5.customer,
5899
+ update_types: d5.updateTypes,
5152
5900
  address: d5.address,
5901
+ new_phone: d5.newPhone,
5902
+ new_email: d5.newEmail,
5153
5903
  loa: d5.loa,
5154
5904
  loa_ref: d5.loa_ref,
5155
5905
  id_verification: body.id_verification,
5156
5906
  raw: d5.raw
5157
5907
  };
5158
5908
  } else {
5909
+ if (wireEvent === "contact.updated") {
5910
+ return declared(400, {
5911
+ error: "missing_session_envelope",
5912
+ detail: "contact.updated requires session_envelope + session_key_share"
5913
+ });
5914
+ }
5159
5915
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
5160
5916
  return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
5161
5917
  status: 400,
@@ -5163,19 +5919,25 @@ function createOneAddressHandler(options) {
5163
5919
  });
5164
5920
  }
5165
5921
  const encrypted = body.address_encrypted;
5166
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
5922
+ const rawAddress = await decryptAddress2(
5923
+ encrypted,
5924
+ requirePemFor("legacy address_encrypted decryption", privateKeyPem),
5925
+ partnerId
5926
+ );
5167
5927
  let loa;
5168
5928
  let loa_ref;
5169
5929
  if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
5170
5930
  loa = await decryptLoaEncrypted(
5171
5931
  body.loa_encrypted,
5172
5932
  privateKeyPem,
5173
- partnerId
5933
+ partnerId,
5934
+ expectedAlg
5174
5935
  );
5175
5936
  loa_ref = d5LoaRef(loa);
5176
5937
  if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
5177
5938
  throw new Error("D5 LOA signature verification failed");
5178
5939
  }
5940
+ assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
5179
5941
  }
5180
5942
  const customer = {
5181
5943
  email: "",
@@ -5191,6 +5953,8 @@ function createOneAddressHandler(options) {
5191
5953
  partner_id: partnerId,
5192
5954
  dispatchId,
5193
5955
  customer,
5956
+ // The legacy blob predates kinds and always carries an address.
5957
+ update_types: ["address"],
5194
5958
  address: validateAddress(rawAddress),
5195
5959
  loa,
5196
5960
  loa_ref,
@@ -5206,10 +5970,26 @@ function createOneAddressHandler(options) {
5206
5970
  // NOSONAR
5207
5971
  );
5208
5972
  }
5209
- return new Response(JSON.stringify({ ok: true, ...result }), {
5210
- status: 200,
5211
- headers: { "Content-Type": "application/json" }
5212
- });
5973
+ if (confirm && dispatchId) {
5974
+ const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
5975
+ void confirmUpdate({
5976
+ partnerId: confirm.partnerId,
5977
+ secret: confirm.confirmSecret,
5978
+ dispatchId,
5979
+ status,
5980
+ loaRef: event.loa_ref,
5981
+ ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
5982
+ ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
5983
+ }).then(
5984
+ (r) => {
5985
+ if (!r.ok) console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} failed: HTTP ${r.status} ${r.error ?? ""}`);
5986
+ },
5987
+ // NOSONAR
5988
+ (err) => console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} threw:`, err)
5989
+ // NOSONAR
5990
+ );
5991
+ }
5992
+ return declared(200, { ok: true, ...result });
5213
5993
  }
5214
5994
  if (body.event === "address.verify" && onVerify) {
5215
5995
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
@@ -5219,7 +5999,11 @@ function createOneAddressHandler(options) {
5219
5999
  });
5220
6000
  }
5221
6001
  const encrypted = body.address_encrypted;
5222
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
6002
+ const rawAddress = await decryptAddress2(
6003
+ encrypted,
6004
+ requirePemFor("address.verify decryption", privateKeyPem),
6005
+ partnerId
6006
+ );
5223
6007
  const event = {
5224
6008
  event: "address.verify",
5225
6009
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -5252,23 +6036,21 @@ function createOneAddressHandler(options) {
5252
6036
  batchId: body.batch_id ?? 0,
5253
6037
  partnerId,
5254
6038
  match: matched,
5255
- note: result && typeof result.note === "string" ? result.note : void 0
6039
+ note: result && typeof result.note === "string" ? result.note : void 0,
6040
+ allowedCallbackHosts
5256
6041
  });
5257
6042
  } catch (err) {
5258
6043
  console.error("[OneAddress SDK] verify-result callback failed:", err);
5259
6044
  }
5260
6045
  }
5261
- return new Response(JSON.stringify({ ok: true, match: matched }), {
5262
- status: 200,
5263
- headers: { "Content-Type": "application/json" }
5264
- });
6046
+ return declared(200, { ok: true, match: matched });
5265
6047
  }
5266
6048
  if (body.event === "account.verify" && onAccountVerify) {
5267
6049
  let customer;
5268
6050
  if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
5269
6051
  const raw = await decryptAddress2(
5270
6052
  body.customer_encrypted,
5271
- privateKeyPem,
6053
+ requirePemFor("account.verify decryption", privateKeyPem),
5272
6054
  partnerId
5273
6055
  );
5274
6056
  customer = {
@@ -5292,10 +6074,7 @@ function createOneAddressHandler(options) {
5292
6074
  raw: body
5293
6075
  };
5294
6076
  const result = await onAccountVerify(event);
5295
- return new Response(JSON.stringify({ ok: true, ...result }), {
5296
- status: 200,
5297
- headers: { "Content-Type": "application/json" }
5298
- });
6077
+ return declared(200, { ok: true, ...result });
5299
6078
  }
5300
6079
  if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
5301
6080
  if (!isD5Body(body)) {
@@ -5305,6 +6084,7 @@ function createOneAddressHandler(options) {
5305
6084
  });
5306
6085
  }
5307
6086
  const d5 = await buildD5Pieces(body, partnerId);
6087
+ if (!d5.address) throw new Error("[OneAddress SDK] test record carries no address");
5308
6088
  await onTest({
5309
6089
  event: body.event,
5310
6090
  index: typeof body.index === "number" ? body.index : void 0,
@@ -5316,9 +6096,11 @@ function createOneAddressHandler(options) {
5316
6096
  address: d5.address,
5317
6097
  raw: d5.raw
5318
6098
  });
5319
- return new Response(JSON.stringify({ ok: true, test: true }), {
5320
- status: 200,
5321
- headers: { "Content-Type": "application/json" }
6099
+ return declared(200, {
6100
+ ok: true,
6101
+ test: true,
6102
+ verification: true,
6103
+ index: typeof body.index === "number" ? body.index : void 0
5322
6104
  });
5323
6105
  }
5324
6106
  const evt = typeof body.event === "string" ? body.event : "(none)";
@@ -5345,7 +6127,7 @@ function createOneAddressHandler(options) {
5345
6127
  // NOSONAR
5346
6128
  );
5347
6129
  }
5348
- return new Response(JSON.stringify({ ok: true, skipped: true, event: evt }), {
6130
+ return new Response(JSON.stringify({ ok: true, skipped: true, event: evt, accepted_update_types: acceptedUpdateTypes }), {
5349
6131
  status: 200,
5350
6132
  headers: { "Content-Type": "application/json" }
5351
6133
  });
@@ -5392,12 +6174,120 @@ function toExpressHandler(handler) {
5392
6174
  res.send(bodyText);
5393
6175
  };
5394
6176
  }
6177
+ async function buildSignedTestWebhook(opts2) {
6178
+ const nowSecs = opts2.timestamp ?? Math.floor(Date.now() / 1e3);
6179
+ const nowIso = new Date(nowSecs * 1e3).toISOString();
6180
+ const updateIdNum = import_crypto.default.randomInt(9e8, 901e6);
6181
+ const updateUid = opts2.session?.update_uid ?? String(updateIdNum);
6182
+ const partnerKey = {
6183
+ partner_id: opts2.partnerId,
6184
+ key_id: opts2.keyId ?? "test-key-1",
6185
+ public_key_b64: pemToBase64(opts2.publicKey),
6186
+ algorithm: opts2.algorithm ?? "ECDH-P256-AES-GCM-256"
6187
+ };
6188
+ const kinds = readUpdateTypes(opts2.session?.update_types) ?? ["address"];
6189
+ const sessionData = {
6190
+ v: 2,
6191
+ update_uid: updateUid,
6192
+ dispatch_timestamp: nowIso,
6193
+ verified_name: "Test Person",
6194
+ ...kinds.includes("address") ? { new_address: { street: "42 Collins Street", suburb: "Melbourne", state: "VIC", postcode: "3000", country: "AU" } } : {},
6195
+ ...kinds.includes("phone") ? { new_phone: "+61412345678" } : {},
6196
+ ...kinds.includes("email") ? { new_email: "test.person@example.com" } : {},
6197
+ account_number: "TEST-0001",
6198
+ id_verification_ref: import_crypto.default.randomUUID(),
6199
+ known_names: [],
6200
+ ...opts2.session ?? {}
6201
+ };
6202
+ const envelope = await encryptSessionForPartner(sessionData, partnerKey);
6203
+ let loa;
6204
+ let loa_encrypted;
6205
+ if (opts2.loa !== false) {
6206
+ loa = {
6207
+ consumer_name: sessionData.verified_name,
6208
+ authorisation_date: nowIso,
6209
+ scope: "Authority to update address records on file.",
6210
+ update_uid: updateUid,
6211
+ oneaddress_acn: "696 078 869",
6212
+ oneaddress_signature: "00".repeat(64),
6213
+ signature_algorithm: "ECDSA-P256",
6214
+ ...opts2.loa ?? {}
6215
+ };
6216
+ if (opts2.loaSigningKeyPem) {
6217
+ const key = await import_crypto.default.subtle.importKey(
6218
+ "pkcs8",
6219
+ pemToBuffer(opts2.loaSigningKeyPem),
6220
+ { name: "ECDSA", namedCurve: "P-256" },
6221
+ false,
6222
+ ["sign"]
6223
+ );
6224
+ const sig2 = await import_crypto.default.subtle.sign(
6225
+ { name: "ECDSA", hash: "SHA-256" },
6226
+ key,
6227
+ new TextEncoder().encode(canonicalD5LoaForm(loa))
6228
+ );
6229
+ loa.oneaddress_signature = Buffer.from(sig2).toString("hex");
6230
+ }
6231
+ const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
6232
+ loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
6233
+ }
6234
+ const event = opts2.event ?? (kinds.includes("address") ? "address.updated" : "contact.updated");
6235
+ const body = JSON.stringify({
6236
+ event,
6237
+ oneaddress_version: CURRENT_VERSION,
6238
+ // A NUMBER. The relay sends `user_updates.id`; `update_uid` inside the
6239
+ // envelope and the LOA is its string form, which is the relationship a
6240
+ // receiver uses to bind the decrypted authorisation to the update.
6241
+ update_id: updateIdNum,
6242
+ partner_id: opts2.partnerId,
6243
+ user_id: opts2.userId ?? "test:consumer",
6244
+ timestamp: nowIso,
6245
+ session_envelope: envelope.session_envelope,
6246
+ session_key_share: envelope.session_key_share,
6247
+ key_share_expiry: new Date((nowSecs + 90 * 24 * 3600) * 1e3).toISOString(),
6248
+ id_verification: { method: "identity_document", verified_at: nowIso, verified: true, platform: "oneaddress/v1" },
6249
+ ...loa_encrypted ? { loa_encrypted } : {},
6250
+ // On the wire with a `null` value when no PaymentIntent backed the update,
6251
+ // so the KEY is present either way.
6252
+ stripe_session_id: opts2.stripeSessionId ?? null,
6253
+ // `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
6254
+ // by default. A test that needs them passes them through `extraBody`, which
6255
+ // is exactly the circumstance the relay emits them in.
6256
+ ...opts2.extraBody ?? {}
6257
+ });
6258
+ const ts = String(nowSecs);
6259
+ const sig = import_crypto.default.createHmac("sha256", opts2.webhookSecret).update(`${ts}.${body}`).digest("hex");
6260
+ const dispatchId = opts2.dispatchId ?? "1";
6261
+ const headers = {
6262
+ "Content-Type": "application/json",
6263
+ "X-OneAddress-Event": event,
6264
+ "X-OneAddress-Partner": opts2.partnerId,
6265
+ "X-OneAddress-Version": CURRENT_VERSION,
6266
+ "X-OneAddress-Timestamp": ts,
6267
+ "X-OneAddress-Signature": sig,
6268
+ ...dispatchId ? { "X-OneAddress-Dispatch": dispatchId } : {}
6269
+ };
6270
+ const lower = new Map(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
6271
+ return {
6272
+ body,
6273
+ headers,
6274
+ sessionData,
6275
+ loa,
6276
+ request: {
6277
+ text: async () => body,
6278
+ headers: { get: (name) => lower.get(name.toLowerCase()) ?? null }
6279
+ },
6280
+ toRequest: (url = "https://receiver.example/webhook") => new Request(url, { method: "POST", headers, body })
6281
+ };
6282
+ }
5395
6283
  // Annotate the CommonJS export names for ESM import in node:
5396
6284
  0 && (module.exports = {
5397
6285
  CURRENT_VERSION,
5398
6286
  DEFAULT_REPLAY_WINDOW_SECS,
5399
6287
  OUTBOX_LEASE_COLUMNS,
5400
6288
  SUPPORTED_VERSIONS,
6289
+ _resetOnceWarningsForTests,
6290
+ buildSignedTestWebhook,
5401
6291
  canonicalD5LoaForm,
5402
6292
  compareAddresses,
5403
6293
  computeBlindIndex,