@oneaddress/partner-sdk 1.7.0 → 1.8.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/CHANGELOG.md CHANGED
@@ -7,6 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.8.0] - 2026-08-25
11
+
12
+ ### Added
13
+
14
+ - **Delegated private-key operations for a KMS/HSM-held key
15
+ (`PrivateKeyOperations`).** `createOneAddressHandler`, `decryptSession` and
16
+ `decryptLoaEncrypted` now accept `privateKeyPem: string | PrivateKeyOperations`.
17
+ A key held in a KMS or HSM is never exported as a PEM by design, so passing a
18
+ raw key was impossible for those integrators; a `PrivateKeyOperations`
19
+ delegate performs the private-key step (ECDH-ES derivation / RSA-OAEP unwrap)
20
+ without surrendering the key. Passing a PEM string is unchanged, so this is
21
+ additive — existing code compiles and runs as before.
22
+
23
+ - **`address.test-dispatch` is now handled as a test event.** The admin stress
24
+ test sends `address.test-dispatch` — the same fabricated, encrypted shape as a
25
+ connection-verification `address.test` record, only the label differs. It was
26
+ in no prior SDK version's handled set, so every stress test ack-200-skipped and
27
+ logged as "unhandled" — a warning that read like the partner's bug and was
28
+ ours. It now rides the exact same branch as `address.test`: decrypted and
29
+ handed to `onTest`, **never** `onUpdate` (the identity and address inside are
30
+ fabricated). `OneAddressTestEvent.event` widened to
31
+ `'address.test' | 'address.test-dispatch'` so a handler can count stress
32
+ dispatches separately; `HANDLED_EVENTS` extended to match.
33
+
34
+ ### Fixed
35
+
36
+ - **The unhandled-event warning now names `onTest` for an unwired
37
+ `address.test-dispatch` too.** When `onTest` is not supplied, a
38
+ `address.test-dispatch` event falls through to the unhandled branch. It was
39
+ taking the "this event is unknown — upgrade the SDK" message, which cannot
40
+ help (the build already supports it); it now takes the same "add an `onTest`
41
+ callback" message as `address.test`.
42
+
10
43
  ## [1.7.0] - 2026-08-21
11
44
 
12
45
  ### Added
package/README.md CHANGED
@@ -59,11 +59,13 @@ export const handler = createOneAddressHandler({
59
59
  // fictitious, and writing them into real customer records is exactly what a
60
60
  // separate event type exists to prevent.
61
61
  //
62
- // Leave it out and address.test is acknowledged with 200, skipped, and
63
- // logged as skipped. You will not be able to complete connection
62
+ // Handles both address.test (connection verification) and address.test-dispatch
63
+ // (the admin stress test) - same fabricated, encrypted test record, only the
64
+ // event label differs. Leave it out and both are acknowledged with 200,
65
+ // skipped, and logged as skipped; you will not be able to complete connection
64
66
  // verification through the SDK.
65
67
  async onTest(event) {
66
- console.log(`test record ${event.index}/${event.total}`,
68
+ console.log(`test record (${event.event}) ${event.index}/${event.total}`,
67
69
  event.customer.name, event.address);
68
70
  },
69
71
  });
@@ -3642,6 +3642,9 @@ function b64UrlToBytes(b64url) {
3642
3642
  const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
3643
3643
  return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
3644
3644
  }
3645
+ function toArrayBuffer(bytes) {
3646
+ return bytes.slice().buffer;
3647
+ }
3645
3648
  async function encryptSessionForPartner(session_data, partner) {
3646
3649
  return encryptEnvelopeForPartner(session_data, partner);
3647
3650
  }
@@ -3765,6 +3768,20 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3765
3768
  if (share.v !== 2) {
3766
3769
  throw new Error(`decryptSession: unsupported share version ${share.v}`);
3767
3770
  }
3771
+ const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
3772
+ if (ops) {
3773
+ if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3774
+ throw new Error(
3775
+ `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.`
3776
+ );
3777
+ }
3778
+ const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : "deriveSharedSecret";
3779
+ if (typeof ops[needed] !== "function") {
3780
+ throw new Error(
3781
+ `decryptSession: key source "${ops.name}" cannot do ${needed}, which ${share.alg} requires.`
3782
+ );
3783
+ }
3784
+ }
3768
3785
  let skRawBuf;
3769
3786
  if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3770
3787
  if (!share.epk) {
@@ -3786,41 +3803,55 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3786
3803
  const wrapKey = await subtle().importKey("raw", wrapKeyRaw, { name: "AES-GCM" }, false, ["decrypt"]);
3787
3804
  skRawBuf = await subtle().decrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, wrappedSkBytes);
3788
3805
  } else if (share.alg === "RSA-OAEP-256+A256GCM") {
3789
- const rsaPrivateKey = await subtle().importKey(
3790
- "pkcs8",
3791
- keyB64ToBytes(privateKeyB64),
3792
- { name: "RSA-OAEP", hash: "SHA-256" },
3793
- false,
3794
- ["decrypt"]
3795
- );
3796
- skRawBuf = await subtle().decrypt(
3797
- { name: "RSA-OAEP" },
3798
- rsaPrivateKey,
3799
- b64UrlToBytes(share.wrapped_key)
3800
- );
3806
+ if (ops) {
3807
+ skRawBuf = toArrayBuffer(await ops.decryptRsaOaep(b64UrlToBytes(share.wrapped_key)));
3808
+ } else {
3809
+ const rsaPrivateKey = await subtle().importKey(
3810
+ "pkcs8",
3811
+ keyB64ToBytes(privateKeyB64),
3812
+ { name: "RSA-OAEP", hash: "SHA-256" },
3813
+ false,
3814
+ ["decrypt"]
3815
+ );
3816
+ skRawBuf = await subtle().decrypt(
3817
+ { name: "RSA-OAEP" },
3818
+ rsaPrivateKey,
3819
+ b64UrlToBytes(share.wrapped_key)
3820
+ );
3821
+ }
3801
3822
  } else {
3802
3823
  if (!share.epk) {
3803
3824
  throw new Error("decryptSession: ECDH-ES share missing epk");
3804
3825
  }
3805
- const privateKey = await subtle().importKey(
3806
- "pkcs8",
3807
- keyB64ToBytes(privateKeyB64),
3808
- { name: "ECDH", namedCurve: "P-256" },
3809
- false,
3810
- ["deriveBits"]
3811
- );
3812
- const ephemeralPub = await subtle().importKey(
3813
- "spki",
3814
- b64UrlToBytes(share.epk),
3815
- { name: "ECDH", namedCurve: "P-256" },
3816
- false,
3817
- []
3818
- );
3819
- const sharedSecret = await subtle().deriveBits(
3820
- { name: "ECDH", public: ephemeralPub },
3821
- privateKey,
3822
- 256
3823
- );
3826
+ let sharedSecret;
3827
+ if (ops) {
3828
+ sharedSecret = toArrayBuffer(await ops.deriveSharedSecret(b64UrlToBytes(share.epk)));
3829
+ if (sharedSecret.byteLength !== 32) {
3830
+ throw new Error(
3831
+ `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; P-256 ECDH is 32 bytes with no KDF applied.`
3832
+ );
3833
+ }
3834
+ } else {
3835
+ const privateKey = await subtle().importKey(
3836
+ "pkcs8",
3837
+ keyB64ToBytes(privateKeyB64),
3838
+ { name: "ECDH", namedCurve: "P-256" },
3839
+ false,
3840
+ ["deriveBits"]
3841
+ );
3842
+ const ephemeralPub = await subtle().importKey(
3843
+ "spki",
3844
+ b64UrlToBytes(share.epk),
3845
+ { name: "ECDH", namedCurve: "P-256" },
3846
+ false,
3847
+ []
3848
+ );
3849
+ sharedSecret = await subtle().deriveBits(
3850
+ { name: "ECDH", public: ephemeralPub },
3851
+ privateKey,
3852
+ 256
3853
+ );
3854
+ }
3824
3855
  const wrappedBytes = b64UrlToBytes(share.wrapped_key);
3825
3856
  if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
3826
3857
  throw new Error("decryptSession: wrapped_key too short");
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  isFreshTimestamp,
3
3
  isSafeWebhookUrl
4
- } from "./chunk-TAZD6PFZ.mjs";
4
+ } from "./chunk-O2D5XGSN.mjs";
5
5
 
6
6
  // src/index.ts
7
7
  import crypto from "crypto";
@@ -379,8 +379,13 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
379
379
  return JSON.parse(new TextDecoder().decode(plaintext));
380
380
  }
381
381
  async function decryptSession(share, envelopeB64, privateKeyPem, partnerId) {
382
- const { decryptSession: decryptSessionCrypto } = await import("./src-ESYTJ2EY.mjs");
383
- return decryptSessionCrypto(share, envelopeB64, pemToBase64(privateKeyPem), partnerId);
382
+ const { decryptSession: decryptSessionCrypto } = await import("./src-UOJOUUGB.mjs");
383
+ return decryptSessionCrypto(
384
+ share,
385
+ envelopeB64,
386
+ typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
387
+ partnerId
388
+ );
384
389
  }
385
390
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
386
391
  const plaintext = await decryptAddress(payload, privateKeyPem, partnerId);
@@ -733,7 +738,7 @@ async function sendVerifyResult(params) {
733
738
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
734
739
  }
735
740
  }
736
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
741
+ var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
737
742
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
738
743
  function createOneAddressHandler(options) {
739
744
  const {
@@ -1006,16 +1011,16 @@ function createOneAddressHandler(options) {
1006
1011
  headers: { "Content-Type": "application/json" }
1007
1012
  });
1008
1013
  }
1009
- if (body.event === "address.test" && onTest) {
1014
+ if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
1010
1015
  if (!isD5Body(body)) {
1011
- return new Response(JSON.stringify({ error: "address.test requires a session envelope" }), {
1016
+ return new Response(JSON.stringify({ error: "a test dispatch requires a session envelope" }), {
1012
1017
  status: 400,
1013
1018
  headers: { "Content-Type": "application/json" }
1014
1019
  });
1015
1020
  }
1016
1021
  const d5 = await buildD5Pieces(body, partnerId);
1017
1022
  await onTest({
1018
- event: "address.test",
1023
+ event: body.event,
1019
1024
  index: typeof body.index === "number" ? body.index : void 0,
1020
1025
  total: typeof body.total === "number" ? body.total : void 0,
1021
1026
  verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
@@ -1034,12 +1039,17 @@ function createOneAddressHandler(options) {
1034
1039
  const callbackFor = {
1035
1040
  "address.verify": onVerify,
1036
1041
  "account.verify": onAccountVerify,
1037
- "address.test": onTest
1042
+ "address.test": onTest,
1043
+ // Same callback as address.test: both test variants route to onTest, so
1044
+ // an unwired stress-test event must name onTest too — not fall through
1045
+ // to the "upgrade the SDK" remedy, which cannot help (marlowe-reports#126).
1046
+ "address.test-dispatch": onTest
1038
1047
  };
1039
1048
  const callbackNameFor = {
1040
1049
  "address.verify": "onVerify",
1041
1050
  "account.verify": "onAccountVerify",
1042
- "address.test": "onTest"
1051
+ "address.test": "onTest",
1052
+ "address.test-dispatch": "onTest"
1043
1053
  };
1044
1054
  const unwired = evt in callbackFor && !callbackFor[evt] ? callbackNameFor[evt] : null;
1045
1055
  if (!warnedUnhandledEvents.has(evt)) {
package/dist/edge.js CHANGED
@@ -3853,6 +3853,9 @@ function b64UrlToBytes(b64url) {
3853
3853
  const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
3854
3854
  return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
3855
3855
  }
3856
+ function toArrayBuffer(bytes) {
3857
+ return bytes.slice().buffer;
3858
+ }
3856
3859
  async function encryptSessionForPartner(session_data, partner) {
3857
3860
  return encryptEnvelopeForPartner(session_data, partner);
3858
3861
  }
@@ -3976,6 +3979,20 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3976
3979
  if (share.v !== 2) {
3977
3980
  throw new Error(`decryptSession: unsupported share version ${share.v}`);
3978
3981
  }
3982
+ const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
3983
+ 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";
3990
+ if (typeof ops[needed] !== "function") {
3991
+ throw new Error(
3992
+ `decryptSession: key source "${ops.name}" cannot do ${needed}, which ${share.alg} requires.`
3993
+ );
3994
+ }
3995
+ }
3979
3996
  let skRawBuf;
3980
3997
  if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3981
3998
  if (!share.epk) {
@@ -3997,41 +4014,55 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3997
4014
  const wrapKey = await subtle().importKey("raw", wrapKeyRaw, { name: "AES-GCM" }, false, ["decrypt"]);
3998
4015
  skRawBuf = await subtle().decrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, wrappedSkBytes);
3999
4016
  } 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
- );
4017
+ if (ops) {
4018
+ skRawBuf = toArrayBuffer(await ops.decryptRsaOaep(b64UrlToBytes(share.wrapped_key)));
4019
+ } else {
4020
+ const rsaPrivateKey = await subtle().importKey(
4021
+ "pkcs8",
4022
+ keyB64ToBytes(privateKeyB64),
4023
+ { name: "RSA-OAEP", hash: "SHA-256" },
4024
+ false,
4025
+ ["decrypt"]
4026
+ );
4027
+ skRawBuf = await subtle().decrypt(
4028
+ { name: "RSA-OAEP" },
4029
+ rsaPrivateKey,
4030
+ b64UrlToBytes(share.wrapped_key)
4031
+ );
4032
+ }
4012
4033
  } else {
4013
4034
  if (!share.epk) {
4014
4035
  throw new Error("decryptSession: ECDH-ES share missing epk");
4015
4036
  }
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
- );
4037
+ let sharedSecret;
4038
+ if (ops) {
4039
+ sharedSecret = toArrayBuffer(await ops.deriveSharedSecret(b64UrlToBytes(share.epk)));
4040
+ if (sharedSecret.byteLength !== 32) {
4041
+ throw new Error(
4042
+ `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; P-256 ECDH is 32 bytes with no KDF applied.`
4043
+ );
4044
+ }
4045
+ } else {
4046
+ const privateKey = await subtle().importKey(
4047
+ "pkcs8",
4048
+ keyB64ToBytes(privateKeyB64),
4049
+ { name: "ECDH", namedCurve: "P-256" },
4050
+ false,
4051
+ ["deriveBits"]
4052
+ );
4053
+ const ephemeralPub = await subtle().importKey(
4054
+ "spki",
4055
+ b64UrlToBytes(share.epk),
4056
+ { name: "ECDH", namedCurve: "P-256" },
4057
+ false,
4058
+ []
4059
+ );
4060
+ sharedSecret = await subtle().deriveBits(
4061
+ { name: "ECDH", public: ephemeralPub },
4062
+ privateKey,
4063
+ 256
4064
+ );
4065
+ }
4035
4066
  const wrappedBytes = b64UrlToBytes(share.wrapped_key);
4036
4067
  if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
4037
4068
  throw new Error("decryptSession: wrapped_key too short");
@@ -4384,7 +4415,12 @@ async function decryptAddress2(payload, privateKeyPem, partnerId) {
4384
4415
  }
4385
4416
  async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId) {
4386
4417
  const { decryptSession: decryptSessionCrypto } = await Promise.resolve().then(() => (init_src(), src_exports));
4387
- return decryptSessionCrypto(share, envelopeB64, pemToBase64(privateKeyPem), partnerId);
4418
+ return decryptSessionCrypto(
4419
+ share,
4420
+ envelopeB64,
4421
+ typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
4422
+ partnerId
4423
+ );
4388
4424
  }
4389
4425
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
4390
4426
  const plaintext = await decryptAddress2(payload, privateKeyPem, partnerId);
@@ -4650,7 +4686,7 @@ async function sendVerifyResult(params) {
4650
4686
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
4651
4687
  }
4652
4688
  }
4653
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
4689
+ var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
4654
4690
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
4655
4691
  function createOneAddressHandler(options) {
4656
4692
  const {
@@ -4923,16 +4959,16 @@ function createOneAddressHandler(options) {
4923
4959
  headers: { "Content-Type": "application/json" }
4924
4960
  });
4925
4961
  }
4926
- if (body.event === "address.test" && onTest) {
4962
+ if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
4927
4963
  if (!isD5Body(body)) {
4928
- return new Response(JSON.stringify({ error: "address.test requires a session envelope" }), {
4964
+ return new Response(JSON.stringify({ error: "a test dispatch requires a session envelope" }), {
4929
4965
  status: 400,
4930
4966
  headers: { "Content-Type": "application/json" }
4931
4967
  });
4932
4968
  }
4933
4969
  const d5 = await buildD5Pieces(body, partnerId);
4934
4970
  await onTest({
4935
- event: "address.test",
4971
+ event: body.event,
4936
4972
  index: typeof body.index === "number" ? body.index : void 0,
4937
4973
  total: typeof body.total === "number" ? body.total : void 0,
4938
4974
  verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
@@ -4951,12 +4987,17 @@ function createOneAddressHandler(options) {
4951
4987
  const callbackFor = {
4952
4988
  "address.verify": onVerify,
4953
4989
  "account.verify": onAccountVerify,
4954
- "address.test": onTest
4990
+ "address.test": onTest,
4991
+ // Same callback as address.test: both test variants route to onTest, so
4992
+ // an unwired stress-test event must name onTest too — not fall through
4993
+ // to the "upgrade the SDK" remedy, which cannot help (marlowe-reports#126).
4994
+ "address.test-dispatch": onTest
4955
4995
  };
4956
4996
  const callbackNameFor = {
4957
4997
  "address.verify": "onVerify",
4958
4998
  "account.verify": "onAccountVerify",
4959
- "address.test": "onTest"
4999
+ "address.test": "onTest",
5000
+ "address.test-dispatch": "onTest"
4960
5001
  };
4961
5002
  const unwired = evt in callbackFor && !callbackFor[evt] ? callbackNameFor[evt] : null;
4962
5003
  if (!warnedUnhandledEvents.has(evt)) {
package/dist/edge.mjs CHANGED
@@ -20,13 +20,13 @@ import {
20
20
  verifyLOA,
21
21
  verifySignature,
22
22
  verifyWithGrace
23
- } from "./chunk-MNVGYXWH.mjs";
23
+ } from "./chunk-PUB6ZVJ2.mjs";
24
24
  import {
25
25
  DEFAULT_REPLAY_WINDOW_SECS,
26
26
  computeBlindIndex,
27
27
  isFreshTimestamp,
28
28
  normalizeForBlindIndex
29
- } from "./chunk-TAZD6PFZ.mjs";
29
+ } from "./chunk-O2D5XGSN.mjs";
30
30
  export {
31
31
  CURRENT_VERSION,
32
32
  DEFAULT_REPLAY_WINDOW_SECS,
package/dist/index.d.mts CHANGED
@@ -37,6 +37,73 @@ declare const DEFAULT_REPLAY_WINDOW_SECS = 300;
37
37
  */
38
38
  declare function isFreshTimestamp(timestampHeader: string | null | undefined, toleranceSecs?: number, nowSecs?: number): boolean;
39
39
 
40
+ /**
41
+ * The private-key half of `decryptSession`, delegated to whatever holds the key.
42
+ *
43
+ * ── WHY THIS EXISTS, AND WHY IT IS NOT SIMPLY "RETURN THE KEY" ──────────────
44
+ *
45
+ * A recipient large enough to have a security review will not put an unwrapped
46
+ * private key in an environment variable or on a disk, which is what a PEM is.
47
+ * They keep it in a KMS or an HSM, and the entire value of doing so is that the
48
+ * key **cannot be exported**. So a key source that answers "here is the PEM"
49
+ * cannot be backed by a KMS at all: the two designs are mutually exclusive, not
50
+ * merely inconvenient together.
51
+ *
52
+ * What a KMS DOES offer is the operation rather than the key, so that is what
53
+ * this interface asks for. The cut is deliberately at the smallest possible
54
+ * step - the one operation that genuinely requires the private key - and
55
+ * everything after it (HKDF, the AES-GCM unwrap, the envelope decrypt) stays
56
+ * here, in one implementation, exercised by the canonical vectors.
57
+ *
58
+ * The tempting alternative is to let the delegate return SK_n and be done. It
59
+ * is worse: the ECDH path would then have to reproduce the HKDF derivation and
60
+ * the unwrap on the far side of the interface, so every implementer would be
61
+ * re-implementing this file's crypto from its docstring, and a mistake there
62
+ * fails as an auth-tag error indistinguishable from a wrong key.
63
+ *
64
+ * ── WHAT EACH METHOD COSTS THE HOLDER ──────────────────────────────────────
65
+ *
66
+ * These are not equally protective, and a recipient choosing between wrap
67
+ * algorithms should know which they are buying:
68
+ *
69
+ * - `decryptRsaOaep` is the strongest. SK_n is recovered INSIDE the KMS and
70
+ * only SK_n comes back. Neither the private key nor any long-lived secret
71
+ * ever exists in the receiver's memory.
72
+ * - `deriveSharedSecret` is weaker but still sound. The private key never
73
+ * leaves the KMS, but the per-dispatch ECDH shared secret does come back,
74
+ * and anyone holding it can derive that one dispatch's wrap key. It is
75
+ * scoped to a single dispatch and useless for any other.
76
+ *
77
+ * There is deliberately no method for the post-quantum X-Wing path. No
78
+ * mainstream KMS implements ML-KEM decapsulation, so a delegate cannot honestly
79
+ * offer it, and `decryptSession` refuses that combination with a message saying
80
+ * so rather than falling back to something the operator did not ask for.
81
+ *
82
+ * Implementations MUST NOT log, cache or persist anything they return.
83
+ */
84
+ interface PrivateKeyOperations {
85
+ /** Names the backing source, for error messages only. Never a credential. */
86
+ readonly name: string;
87
+ /**
88
+ * ECDH-ES: the raw shared secret for `epkSpki`, exactly as WebCrypto's
89
+ * `deriveBits({name:'ECDH', public}, priv, 256)` would return it - the X
90
+ * coordinate of the shared point, 32 bytes for P-256, with NO KDF applied.
91
+ *
92
+ * AWS KMS `DeriveSharedSecret` returns precisely this, which is what makes
93
+ * the two interchangeable. A KMS that applied its own KDF first would not be
94
+ * usable here and would fail as an auth-tag error, so the "no KDF" part is a
95
+ * requirement rather than a description.
96
+ *
97
+ * @param epkSpki The ephemeral public key from the share, DER SPKI encoded.
98
+ */
99
+ deriveSharedSecret?(epkSpki: Uint8Array): Promise<Uint8Array>;
100
+ /**
101
+ * RSA-OAEP-SHA256: unwrap `wrappedKey` to SK_n directly.
102
+ *
103
+ * @param wrappedKey The raw `wrapped_key` bytes from the share.
104
+ */
105
+ decryptRsaOaep?(wrappedKey: Uint8Array): Promise<Uint8Array>;
106
+ }
40
107
  /** Fields that can be turned into a blind index. */
41
108
  type BlindIndexField = 'email' | 'name' | 'account_number';
42
109
  /**
@@ -580,11 +647,15 @@ interface OneAddressHandlerOptions {
580
647
  note?: string;
581
648
  }>;
582
649
  /**
583
- * Connection-verification test records (`address.test`).
650
+ * Connection-verification and stress-test records (`address.test` and
651
+ * `address.test-dispatch`).
584
652
  *
585
- * OneAddress sends five of these before a partner goes live: real signed,
586
- * ECDH-encrypted dispatches carrying fabricated TEST identities, which you
587
- * decrypt and relay back so both sides can confirm the pipe works end to end.
653
+ * OneAddress sends five `address.test` records before a partner goes live:
654
+ * real signed, ECDH-encrypted dispatches carrying fabricated TEST identities,
655
+ * which you decrypt and relay back so both sides can confirm the pipe works
656
+ * end to end. The admin stress test sends `address.test-dispatch`, which is
657
+ * the SAME shape (a fabricated, encrypted test record) — both arrive here, and
658
+ * `event` tells them apart if you want to count stress dispatches separately.
588
659
  *
589
660
  * ── WHY THIS IS A SEPARATE CALLBACK AND NOT `onUpdate` ─────────────────────
590
661
  *
@@ -595,11 +666,11 @@ interface OneAddressHandlerOptions {
595
666
  *
596
667
  * ── IF YOU DO NOT IMPLEMENT IT ─────────────────────────────────────────────
597
668
  *
598
- * `address.test` is acknowledged with 200 and skipped, and the SDK logs a
599
- * warning naming this option. That combination was the defect in
600
- * marlowe-reports#125: the skip was correct, the silence was not. Five test
601
- * records were skipped, the partner saw five clean 200s, and the only way it
602
- * surfaced was somebody decrypting the raw bodies by hand.
669
+ * `address.test` / `address.test-dispatch` are acknowledged with 200 and
670
+ * skipped, and the SDK logs a warning naming this option. That combination was
671
+ * the defect in marlowe-reports#125: the skip was correct, the silence was
672
+ * not. Five test records were skipped, the partner saw five clean 200s, and
673
+ * the only way it surfaced was somebody decrypting the raw bodies by hand.
603
674
  *
604
675
  * Implement it if you intend to complete connection verification through the
605
676
  * SDK rather than by hand.
@@ -944,7 +1015,7 @@ interface SessionData {
944
1015
  * );
945
1016
  * // data.new_address.street, data.account_number, etc.
946
1017
  */
947
- declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string, partnerId: string): Promise<SessionData>;
1018
+ declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string | PrivateKeyOperations, partnerId: string): Promise<SessionData>;
948
1019
  /**
949
1020
  * Decrypt a OneAddress payload and immediately re-encrypt it to a different
950
1021
  * ECDH P-256 public key — for example, your internal KMS or HSM public key.
@@ -1212,7 +1283,7 @@ declare function verifyD5LOA(loa: OneAddressD5LOA, publicKeyPem: string): Promis
1212
1283
  declare function decryptLoaEncrypted(loaEncrypted: {
1213
1284
  session_envelope: string;
1214
1285
  session_key_share: SessionKeyShare;
1215
- }, privateKeyPem: string, partnerId: string): Promise<OneAddressD5LOA>;
1286
+ }, privateKeyPem: string | PrivateKeyOperations, partnerId: string): Promise<OneAddressD5LOA>;
1216
1287
  /**
1217
1288
  * Validate and narrow the decrypted address payload to `OneAddressAddress`.
1218
1289
  *
@@ -1357,7 +1428,14 @@ type HandlerResponse = Response;
1357
1428
  * of these, and the compiler is a better guard against that than a comment.
1358
1429
  */
1359
1430
  interface OneAddressTestEvent {
1360
- event: 'address.test';
1431
+ /**
1432
+ * `address.test` is a single-partner connection-verification ping;
1433
+ * `address.test-dispatch` is the same fabricated, encrypted test record sent
1434
+ * by the admin stress test. Both route here — NEVER to `onUpdate` — because
1435
+ * the identity and address inside are fabricated. The field tells them apart
1436
+ * for a handler that wants to (e.g. count stress dispatches separately).
1437
+ */
1438
+ event: 'address.test' | 'address.test-dispatch';
1361
1439
  /** 1-based position within this verification run. */
1362
1440
  index?: number;
1363
1441
  /** How many records this run sends in total. */
@@ -1445,4 +1523,4 @@ interface ExpressLikeResponse {
1445
1523
  */
1446
1524
  declare function toExpressHandler(handler: (req: HandlerRequest) => Promise<HandlerResponse>): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
1447
1525
 
1448
- export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, OUTBOX_LEASE_COLUMNS, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, type OutboxBacklog, type OutboxConsumer, type OutboxConsumerOptions, type OutboxDialect, type OutboxQueryFn, type OutboxRow, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
1526
+ export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, OUTBOX_LEASE_COLUMNS, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, type OutboxBacklog, type OutboxConsumer, type OutboxConsumerOptions, type OutboxDialect, type OutboxQueryFn, type OutboxRow, type PrivateKeyOperations, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
package/dist/index.d.ts CHANGED
@@ -37,6 +37,73 @@ declare const DEFAULT_REPLAY_WINDOW_SECS = 300;
37
37
  */
38
38
  declare function isFreshTimestamp(timestampHeader: string | null | undefined, toleranceSecs?: number, nowSecs?: number): boolean;
39
39
 
40
+ /**
41
+ * The private-key half of `decryptSession`, delegated to whatever holds the key.
42
+ *
43
+ * ── WHY THIS EXISTS, AND WHY IT IS NOT SIMPLY "RETURN THE KEY" ──────────────
44
+ *
45
+ * A recipient large enough to have a security review will not put an unwrapped
46
+ * private key in an environment variable or on a disk, which is what a PEM is.
47
+ * They keep it in a KMS or an HSM, and the entire value of doing so is that the
48
+ * key **cannot be exported**. So a key source that answers "here is the PEM"
49
+ * cannot be backed by a KMS at all: the two designs are mutually exclusive, not
50
+ * merely inconvenient together.
51
+ *
52
+ * What a KMS DOES offer is the operation rather than the key, so that is what
53
+ * this interface asks for. The cut is deliberately at the smallest possible
54
+ * step - the one operation that genuinely requires the private key - and
55
+ * everything after it (HKDF, the AES-GCM unwrap, the envelope decrypt) stays
56
+ * here, in one implementation, exercised by the canonical vectors.
57
+ *
58
+ * The tempting alternative is to let the delegate return SK_n and be done. It
59
+ * is worse: the ECDH path would then have to reproduce the HKDF derivation and
60
+ * the unwrap on the far side of the interface, so every implementer would be
61
+ * re-implementing this file's crypto from its docstring, and a mistake there
62
+ * fails as an auth-tag error indistinguishable from a wrong key.
63
+ *
64
+ * ── WHAT EACH METHOD COSTS THE HOLDER ──────────────────────────────────────
65
+ *
66
+ * These are not equally protective, and a recipient choosing between wrap
67
+ * algorithms should know which they are buying:
68
+ *
69
+ * - `decryptRsaOaep` is the strongest. SK_n is recovered INSIDE the KMS and
70
+ * only SK_n comes back. Neither the private key nor any long-lived secret
71
+ * ever exists in the receiver's memory.
72
+ * - `deriveSharedSecret` is weaker but still sound. The private key never
73
+ * leaves the KMS, but the per-dispatch ECDH shared secret does come back,
74
+ * and anyone holding it can derive that one dispatch's wrap key. It is
75
+ * scoped to a single dispatch and useless for any other.
76
+ *
77
+ * There is deliberately no method for the post-quantum X-Wing path. No
78
+ * mainstream KMS implements ML-KEM decapsulation, so a delegate cannot honestly
79
+ * offer it, and `decryptSession` refuses that combination with a message saying
80
+ * so rather than falling back to something the operator did not ask for.
81
+ *
82
+ * Implementations MUST NOT log, cache or persist anything they return.
83
+ */
84
+ interface PrivateKeyOperations {
85
+ /** Names the backing source, for error messages only. Never a credential. */
86
+ readonly name: string;
87
+ /**
88
+ * ECDH-ES: the raw shared secret for `epkSpki`, exactly as WebCrypto's
89
+ * `deriveBits({name:'ECDH', public}, priv, 256)` would return it - the X
90
+ * coordinate of the shared point, 32 bytes for P-256, with NO KDF applied.
91
+ *
92
+ * AWS KMS `DeriveSharedSecret` returns precisely this, which is what makes
93
+ * the two interchangeable. A KMS that applied its own KDF first would not be
94
+ * usable here and would fail as an auth-tag error, so the "no KDF" part is a
95
+ * requirement rather than a description.
96
+ *
97
+ * @param epkSpki The ephemeral public key from the share, DER SPKI encoded.
98
+ */
99
+ deriveSharedSecret?(epkSpki: Uint8Array): Promise<Uint8Array>;
100
+ /**
101
+ * RSA-OAEP-SHA256: unwrap `wrappedKey` to SK_n directly.
102
+ *
103
+ * @param wrappedKey The raw `wrapped_key` bytes from the share.
104
+ */
105
+ decryptRsaOaep?(wrappedKey: Uint8Array): Promise<Uint8Array>;
106
+ }
40
107
  /** Fields that can be turned into a blind index. */
41
108
  type BlindIndexField = 'email' | 'name' | 'account_number';
42
109
  /**
@@ -580,11 +647,15 @@ interface OneAddressHandlerOptions {
580
647
  note?: string;
581
648
  }>;
582
649
  /**
583
- * Connection-verification test records (`address.test`).
650
+ * Connection-verification and stress-test records (`address.test` and
651
+ * `address.test-dispatch`).
584
652
  *
585
- * OneAddress sends five of these before a partner goes live: real signed,
586
- * ECDH-encrypted dispatches carrying fabricated TEST identities, which you
587
- * decrypt and relay back so both sides can confirm the pipe works end to end.
653
+ * OneAddress sends five `address.test` records before a partner goes live:
654
+ * real signed, ECDH-encrypted dispatches carrying fabricated TEST identities,
655
+ * which you decrypt and relay back so both sides can confirm the pipe works
656
+ * end to end. The admin stress test sends `address.test-dispatch`, which is
657
+ * the SAME shape (a fabricated, encrypted test record) — both arrive here, and
658
+ * `event` tells them apart if you want to count stress dispatches separately.
588
659
  *
589
660
  * ── WHY THIS IS A SEPARATE CALLBACK AND NOT `onUpdate` ─────────────────────
590
661
  *
@@ -595,11 +666,11 @@ interface OneAddressHandlerOptions {
595
666
  *
596
667
  * ── IF YOU DO NOT IMPLEMENT IT ─────────────────────────────────────────────
597
668
  *
598
- * `address.test` is acknowledged with 200 and skipped, and the SDK logs a
599
- * warning naming this option. That combination was the defect in
600
- * marlowe-reports#125: the skip was correct, the silence was not. Five test
601
- * records were skipped, the partner saw five clean 200s, and the only way it
602
- * surfaced was somebody decrypting the raw bodies by hand.
669
+ * `address.test` / `address.test-dispatch` are acknowledged with 200 and
670
+ * skipped, and the SDK logs a warning naming this option. That combination was
671
+ * the defect in marlowe-reports#125: the skip was correct, the silence was
672
+ * not. Five test records were skipped, the partner saw five clean 200s, and
673
+ * the only way it surfaced was somebody decrypting the raw bodies by hand.
603
674
  *
604
675
  * Implement it if you intend to complete connection verification through the
605
676
  * SDK rather than by hand.
@@ -944,7 +1015,7 @@ interface SessionData {
944
1015
  * );
945
1016
  * // data.new_address.street, data.account_number, etc.
946
1017
  */
947
- declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string, partnerId: string): Promise<SessionData>;
1018
+ declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string | PrivateKeyOperations, partnerId: string): Promise<SessionData>;
948
1019
  /**
949
1020
  * Decrypt a OneAddress payload and immediately re-encrypt it to a different
950
1021
  * ECDH P-256 public key — for example, your internal KMS or HSM public key.
@@ -1212,7 +1283,7 @@ declare function verifyD5LOA(loa: OneAddressD5LOA, publicKeyPem: string): Promis
1212
1283
  declare function decryptLoaEncrypted(loaEncrypted: {
1213
1284
  session_envelope: string;
1214
1285
  session_key_share: SessionKeyShare;
1215
- }, privateKeyPem: string, partnerId: string): Promise<OneAddressD5LOA>;
1286
+ }, privateKeyPem: string | PrivateKeyOperations, partnerId: string): Promise<OneAddressD5LOA>;
1216
1287
  /**
1217
1288
  * Validate and narrow the decrypted address payload to `OneAddressAddress`.
1218
1289
  *
@@ -1357,7 +1428,14 @@ type HandlerResponse = Response;
1357
1428
  * of these, and the compiler is a better guard against that than a comment.
1358
1429
  */
1359
1430
  interface OneAddressTestEvent {
1360
- event: 'address.test';
1431
+ /**
1432
+ * `address.test` is a single-partner connection-verification ping;
1433
+ * `address.test-dispatch` is the same fabricated, encrypted test record sent
1434
+ * by the admin stress test. Both route here — NEVER to `onUpdate` — because
1435
+ * the identity and address inside are fabricated. The field tells them apart
1436
+ * for a handler that wants to (e.g. count stress dispatches separately).
1437
+ */
1438
+ event: 'address.test' | 'address.test-dispatch';
1361
1439
  /** 1-based position within this verification run. */
1362
1440
  index?: number;
1363
1441
  /** How many records this run sends in total. */
@@ -1445,4 +1523,4 @@ interface ExpressLikeResponse {
1445
1523
  */
1446
1524
  declare function toExpressHandler(handler: (req: HandlerRequest) => Promise<HandlerResponse>): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
1447
1525
 
1448
- export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, OUTBOX_LEASE_COLUMNS, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, type OutboxBacklog, type OutboxConsumer, type OutboxConsumerOptions, type OutboxDialect, type OutboxQueryFn, type OutboxRow, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
1526
+ export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, OUTBOX_LEASE_COLUMNS, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, type OutboxBacklog, type OutboxConsumer, type OutboxConsumerOptions, type OutboxDialect, type OutboxQueryFn, type OutboxRow, type PrivateKeyOperations, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
package/dist/index.js CHANGED
@@ -3853,6 +3853,9 @@ function b64UrlToBytes(b64url) {
3853
3853
  const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
3854
3854
  return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
3855
3855
  }
3856
+ function toArrayBuffer(bytes) {
3857
+ return bytes.slice().buffer;
3858
+ }
3856
3859
  async function encryptSessionForPartner(session_data, partner) {
3857
3860
  return encryptEnvelopeForPartner(session_data, partner);
3858
3861
  }
@@ -3976,6 +3979,20 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3976
3979
  if (share.v !== 2) {
3977
3980
  throw new Error(`decryptSession: unsupported share version ${share.v}`);
3978
3981
  }
3982
+ const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
3983
+ 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";
3990
+ if (typeof ops[needed] !== "function") {
3991
+ throw new Error(
3992
+ `decryptSession: key source "${ops.name}" cannot do ${needed}, which ${share.alg} requires.`
3993
+ );
3994
+ }
3995
+ }
3979
3996
  let skRawBuf;
3980
3997
  if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3981
3998
  if (!share.epk) {
@@ -3997,41 +4014,55 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3997
4014
  const wrapKey = await subtle().importKey("raw", wrapKeyRaw, { name: "AES-GCM" }, false, ["decrypt"]);
3998
4015
  skRawBuf = await subtle().decrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, wrappedSkBytes);
3999
4016
  } 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
- );
4017
+ if (ops) {
4018
+ skRawBuf = toArrayBuffer(await ops.decryptRsaOaep(b64UrlToBytes(share.wrapped_key)));
4019
+ } else {
4020
+ const rsaPrivateKey = await subtle().importKey(
4021
+ "pkcs8",
4022
+ keyB64ToBytes(privateKeyB64),
4023
+ { name: "RSA-OAEP", hash: "SHA-256" },
4024
+ false,
4025
+ ["decrypt"]
4026
+ );
4027
+ skRawBuf = await subtle().decrypt(
4028
+ { name: "RSA-OAEP" },
4029
+ rsaPrivateKey,
4030
+ b64UrlToBytes(share.wrapped_key)
4031
+ );
4032
+ }
4012
4033
  } else {
4013
4034
  if (!share.epk) {
4014
4035
  throw new Error("decryptSession: ECDH-ES share missing epk");
4015
4036
  }
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
- );
4037
+ let sharedSecret;
4038
+ if (ops) {
4039
+ sharedSecret = toArrayBuffer(await ops.deriveSharedSecret(b64UrlToBytes(share.epk)));
4040
+ if (sharedSecret.byteLength !== 32) {
4041
+ throw new Error(
4042
+ `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; P-256 ECDH is 32 bytes with no KDF applied.`
4043
+ );
4044
+ }
4045
+ } else {
4046
+ const privateKey = await subtle().importKey(
4047
+ "pkcs8",
4048
+ keyB64ToBytes(privateKeyB64),
4049
+ { name: "ECDH", namedCurve: "P-256" },
4050
+ false,
4051
+ ["deriveBits"]
4052
+ );
4053
+ const ephemeralPub = await subtle().importKey(
4054
+ "spki",
4055
+ b64UrlToBytes(share.epk),
4056
+ { name: "ECDH", namedCurve: "P-256" },
4057
+ false,
4058
+ []
4059
+ );
4060
+ sharedSecret = await subtle().deriveBits(
4061
+ { name: "ECDH", public: ephemeralPub },
4062
+ privateKey,
4063
+ 256
4064
+ );
4065
+ }
4035
4066
  const wrappedBytes = b64UrlToBytes(share.wrapped_key);
4036
4067
  if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
4037
4068
  throw new Error("decryptSession: wrapped_key too short");
@@ -4635,7 +4666,12 @@ async function decryptAddress2(payload, privateKeyPem, partnerId) {
4635
4666
  }
4636
4667
  async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId) {
4637
4668
  const { decryptSession: decryptSessionCrypto } = await Promise.resolve().then(() => (init_src(), src_exports));
4638
- return decryptSessionCrypto(share, envelopeB64, pemToBase64(privateKeyPem), partnerId);
4669
+ return decryptSessionCrypto(
4670
+ share,
4671
+ envelopeB64,
4672
+ typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
4673
+ partnerId
4674
+ );
4639
4675
  }
4640
4676
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
4641
4677
  const plaintext = await decryptAddress2(payload, privateKeyPem, partnerId);
@@ -4988,7 +5024,7 @@ async function sendVerifyResult(params) {
4988
5024
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
4989
5025
  }
4990
5026
  }
4991
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
5027
+ var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
4992
5028
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
4993
5029
  function createOneAddressHandler(options) {
4994
5030
  const {
@@ -5261,16 +5297,16 @@ function createOneAddressHandler(options) {
5261
5297
  headers: { "Content-Type": "application/json" }
5262
5298
  });
5263
5299
  }
5264
- if (body.event === "address.test" && onTest) {
5300
+ if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
5265
5301
  if (!isD5Body(body)) {
5266
- return new Response(JSON.stringify({ error: "address.test requires a session envelope" }), {
5302
+ return new Response(JSON.stringify({ error: "a test dispatch requires a session envelope" }), {
5267
5303
  status: 400,
5268
5304
  headers: { "Content-Type": "application/json" }
5269
5305
  });
5270
5306
  }
5271
5307
  const d5 = await buildD5Pieces(body, partnerId);
5272
5308
  await onTest({
5273
- event: "address.test",
5309
+ event: body.event,
5274
5310
  index: typeof body.index === "number" ? body.index : void 0,
5275
5311
  total: typeof body.total === "number" ? body.total : void 0,
5276
5312
  verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
@@ -5289,12 +5325,17 @@ function createOneAddressHandler(options) {
5289
5325
  const callbackFor = {
5290
5326
  "address.verify": onVerify,
5291
5327
  "account.verify": onAccountVerify,
5292
- "address.test": onTest
5328
+ "address.test": onTest,
5329
+ // Same callback as address.test: both test variants route to onTest, so
5330
+ // an unwired stress-test event must name onTest too — not fall through
5331
+ // to the "upgrade the SDK" remedy, which cannot help (marlowe-reports#126).
5332
+ "address.test-dispatch": onTest
5293
5333
  };
5294
5334
  const callbackNameFor = {
5295
5335
  "address.verify": "onVerify",
5296
5336
  "account.verify": "onAccountVerify",
5297
- "address.test": "onTest"
5337
+ "address.test": "onTest",
5338
+ "address.test-dispatch": "onTest"
5298
5339
  };
5299
5340
  const unwired = evt in callbackFor && !callbackFor[evt] ? callbackNameFor[evt] : null;
5300
5341
  if (!warnedUnhandledEvents.has(evt)) {
package/dist/index.mjs CHANGED
@@ -29,13 +29,13 @@ import {
29
29
  verifyLOA,
30
30
  verifySignature,
31
31
  verifyWithGrace
32
- } from "./chunk-MNVGYXWH.mjs";
32
+ } from "./chunk-PUB6ZVJ2.mjs";
33
33
  import {
34
34
  DEFAULT_REPLAY_WINDOW_SECS,
35
35
  computeBlindIndex,
36
36
  isFreshTimestamp,
37
37
  normalizeForBlindIndex
38
- } from "./chunk-TAZD6PFZ.mjs";
38
+ } from "./chunk-O2D5XGSN.mjs";
39
39
  export {
40
40
  CURRENT_VERSION,
41
41
  DEFAULT_REPLAY_WINDOW_SECS,
@@ -33,7 +33,7 @@ import {
33
33
  verifyPartnerKeyAttestationWithRoots,
34
34
  verifyRegistryHead,
35
35
  verifyWebhookSignature
36
- } from "./chunk-TAZD6PFZ.mjs";
36
+ } from "./chunk-O2D5XGSN.mjs";
37
37
  export {
38
38
  DEFAULT_REPLAY_WINDOW_SECS,
39
39
  PARTNER_KEY_ATTESTATION_ALG,
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "@oneaddress/partner-sdk",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "Official OneAddress partner integration SDK — webhook verification, address decryption (legacy + D5 session-envelope), LOA validation",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/OneAddress-AU/oneaddress-app.git",
8
+ "directory": "packages/partner-sdk"
9
+ },
5
10
  "main": "dist/index.js",
6
11
  "types": "dist/index.d.ts",
7
12
  "exports": {