@oneaddress/partner-sdk 2.0.0 → 2.2.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.
@@ -1,7 +1,9 @@
1
1
  import {
2
+ encryptEnvelopeForPartner,
3
+ encryptSessionForPartner,
2
4
  isFreshTimestamp,
3
5
  isSafeWebhookUrl
4
- } from "./chunk-DUVPNFU6.mjs";
6
+ } from "./chunk-LIHXDUUA.mjs";
5
7
 
6
8
  // src/index.ts
7
9
  import crypto from "crypto";
@@ -10,6 +12,63 @@ import crypto from "crypto";
10
12
  var CURRENT_VERSION = "2026.1";
11
13
  var SUPPORTED_VERSIONS = ["2026.1"];
12
14
 
15
+ // ../protocol/src/d5-body.ts
16
+ var D5_BODY_ALWAYS = [
17
+ "event",
18
+ "id_verification",
19
+ "key_share_expiry",
20
+ "oneaddress_version",
21
+ "partner_id",
22
+ "session_envelope",
23
+ "session_key_share",
24
+ "stripe_session_id",
25
+ "timestamp",
26
+ "update_id",
27
+ "user_id"
28
+ ];
29
+ var D5_BODY_CONDITIONAL = {
30
+ /**
31
+ * The signed Letter of Authority, sealed to the same key_id as the session.
32
+ * Present whenever the partner has a usable key — i.e. on every dispatch a
33
+ * live partner receives. Omitted best-effort when no key is available, which
34
+ * is a state a live partner is never in.
35
+ */
36
+ loa_encrypted: "partner has a usable encryption key",
37
+ /**
38
+ * The shared webhook event id. Set ONLY on a key-crossover copy, where every
39
+ * copy of one update carries the same id so a receiver holding more than one
40
+ * rotation key applies it once. Absent on an ordinary dispatch, whose
41
+ * receiver idempotency falls back to the `X-OneAddress-Dispatch` header.
42
+ */
43
+ id: "key-crossover copy only",
44
+ /** The sibling marker naming the other key_ids this update was sealed to. */
45
+ crossover_key_ids: "key-crossover copy only"
46
+ };
47
+ var D5_BODY_DRILL_ONLY = ["conformance"];
48
+ var D5_BODY_ALL_ALLOWED = [
49
+ ...D5_BODY_ALWAYS,
50
+ ...Object.keys(D5_BODY_CONDITIONAL),
51
+ ...D5_BODY_DRILL_ONLY
52
+ ];
53
+
54
+ // ../protocol/src/retention.ts
55
+ var MIN_RETENTION_DAYS = 14;
56
+ var MAX_RETENTION_DAYS = 365;
57
+ var DEFAULT_RETENTION_DAYS = 90;
58
+ function resolveRetentionDays(retentionPeriodDays) {
59
+ if (typeof retentionPeriodDays !== "number" || !Number.isFinite(retentionPeriodDays)) {
60
+ return DEFAULT_RETENTION_DAYS;
61
+ }
62
+ const days = Math.trunc(retentionPeriodDays);
63
+ if (days < MIN_RETENTION_DAYS || days > MAX_RETENTION_DAYS) return DEFAULT_RETENTION_DAYS;
64
+ return days;
65
+ }
66
+ var DAY_MS = 24 * 60 * 60 * 1e3;
67
+ function keyShareExpiryIso(dispatchAt, retentionPeriodDays) {
68
+ const days = resolveRetentionDays(retentionPeriodDays);
69
+ return new Date(dispatchAt.getTime() + days * DAY_MS).toISOString();
70
+ }
71
+
13
72
  // ../name-match/src/index.ts
14
73
  function isEmailLike(value) {
15
74
  return value.includes("@");
@@ -132,9 +191,17 @@ function createOutboxConsumer(opts) {
132
191
  if (!Number.isFinite(batchSize) || batchSize < 1) {
133
192
  throw new Error(`[OneAddress SDK] batchSize must be a positive integer, got ${opts.batchSize}`);
134
193
  }
194
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 0) {
195
+ throw new Error(`[OneAddress SDK] maxAttempts must be an integer >= 0, got ${opts.maxAttempts}`);
196
+ }
135
197
  const ph = d.ph;
136
198
  const token = () => randomBytes(16).toString("hex");
137
199
  const stamp = (at) => toOutboxTimestamp(dialect, at);
200
+ const heldTokens = /* @__PURE__ */ new Map();
201
+ const claimPredicate = (dispatchId, firstPh) => {
202
+ const tok = heldTokens.get(dispatchId);
203
+ 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] };
204
+ };
138
205
  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})` : "");
139
206
  const toRow = (r) => ({
140
207
  dispatchId: String(r.dispatch_id ?? r.dispatchId ?? ""),
@@ -142,6 +209,10 @@ function createOutboxConsumer(opts) {
142
209
  attempts: Number(r[ATTEMPTS] ?? 0) || 0,
143
210
  fields: r
144
211
  });
212
+ const claimed = (rows, tok) => rows.map(toRow).map((row) => {
213
+ heldTokens.set(row.dispatchId, tok);
214
+ return row;
215
+ });
145
216
  async function claimBatch() {
146
217
  const at = now();
147
218
  const claimedAt = stamp(at);
@@ -152,14 +223,14 @@ function createOutboxConsumer(opts) {
152
223
  `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 *`,
153
224
  [claimedAt, tok, cutoff]
154
225
  );
155
- return rows2.map(toRow);
226
+ return claimed(rows2, tok);
156
227
  }
157
228
  if (dialect === "mssql") {
158
229
  const rows2 = await opts.query(
159
230
  `UPDATE TOP (${batchSize}) ${table} WITH (UPDLOCK, READPAST, ROWLOCK) SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} OUTPUT INSERTED.* WHERE ${claimable(ph(3))}`,
160
231
  [claimedAt, tok, cutoff]
161
232
  );
162
- return rows2.map(toRow);
233
+ return claimed(rows2, tok);
163
234
  }
164
235
  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})`;
165
236
  await opts.query(claim, [claimedAt, tok, cutoff]);
@@ -167,7 +238,7 @@ function createOutboxConsumer(opts) {
167
238
  `SELECT * FROM ${table} WHERE ${CLAIM_TOKEN} = ${ph(1)} AND processed_at IS NULL`,
168
239
  [tok]
169
240
  );
170
- return rows.map(toRow);
241
+ return claimed(rows, tok);
171
242
  }
172
243
  return {
173
244
  async ensureSchema() {
@@ -196,23 +267,29 @@ function createOutboxConsumer(opts) {
196
267
  },
197
268
  claimBatch,
198
269
  async markProcessed(dispatchId) {
270
+ const where = claimPredicate(dispatchId, 2);
199
271
  await opts.query(
200
- `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
201
- [stamp(now()), dispatchId]
272
+ `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
273
+ [stamp(now()), ...where.params]
202
274
  );
275
+ heldTokens.delete(dispatchId);
203
276
  },
204
277
  async markFailed(dispatchId, error) {
205
278
  const message = error instanceof Error ? error.message : String(error);
279
+ const where = claimPredicate(dispatchId, 2);
206
280
  await opts.query(
207
- `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
208
- [message.slice(0, 500), dispatchId]
281
+ `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
282
+ [message.slice(0, 500), ...where.params]
209
283
  );
284
+ heldTokens.delete(dispatchId);
210
285
  },
211
286
  async release(dispatchId) {
287
+ const where = claimPredicate(dispatchId, 1);
212
288
  await opts.query(
213
- `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(1)}`,
214
- [dispatchId]
289
+ `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
290
+ where.params
215
291
  );
292
+ heldTokens.delete(dispatchId);
216
293
  },
217
294
  async process(handler) {
218
295
  const rows = await claimBatch();
@@ -253,15 +330,62 @@ function createOutboxConsumer(opts) {
253
330
  }
254
331
 
255
332
  // src/index.ts
333
+ var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
256
334
  function createSqlIdempotencyStore(opts) {
257
335
  const table = opts.table ?? "oneaddress_dispatches";
258
- const ph = opts.placeholder ?? ((n) => `$${n}`);
336
+ const dialect = opts.dialect ?? "postgres";
337
+ if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
338
+ throw new Error(
339
+ `[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
340
+ );
341
+ }
342
+ const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
343
+ const ph = opts.placeholder ?? defaultPh;
259
344
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
260
345
  throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
261
346
  }
262
347
  const completedOf = (row) => row?.completed_at ?? row?.completedAt ?? null;
348
+ const tokenOf = (row) => row?.claim_token ?? row?.claimToken ?? null;
349
+ async function claimByToken(dispatchId) {
350
+ const token = crypto.randomBytes(16).toString("hex");
351
+ await opts.query(
352
+ 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)})`,
353
+ [dispatchId, token]
354
+ );
355
+ const rows = await opts.query(
356
+ `SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
357
+ [dispatchId]
358
+ );
359
+ if (tokenOf(rows[0]) === token) return "fresh";
360
+ return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
361
+ }
362
+ async function setByUpsert(dispatchId) {
363
+ if (dialect === "mysql") {
364
+ await opts.query(
365
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE completed_at = CURRENT_TIMESTAMP`,
366
+ [dispatchId]
367
+ );
368
+ return;
369
+ }
370
+ if (dialect === "mssql") {
371
+ await opts.query(
372
+ `UPDATE ${table} SET completed_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)}`,
373
+ [dispatchId]
374
+ );
375
+ await opts.query(
376
+ `INSERT INTO ${table} (dispatch_id, completed_at) SELECT ${ph(1)}, CURRENT_TIMESTAMP WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE dispatch_id = ${ph(1)})`,
377
+ [dispatchId]
378
+ );
379
+ return;
380
+ }
381
+ await opts.query(
382
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
383
+ [dispatchId]
384
+ );
385
+ }
263
386
  return {
264
387
  async claim(dispatchId) {
388
+ if (dialect === "mysql" || dialect === "mssql") return claimByToken(dispatchId);
265
389
  const inserted = await opts.query(
266
390
  `INSERT INTO ${table} (dispatch_id) VALUES (${ph(1)}) ON CONFLICT (dispatch_id) DO NOTHING RETURNING dispatch_id`,
267
391
  [dispatchId]
@@ -289,10 +413,7 @@ function createSqlIdempotencyStore(opts) {
289
413
  return rows.length > 0 && Boolean(completedOf(rows[0]));
290
414
  },
291
415
  async set(dispatchId) {
292
- await opts.query(
293
- `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
294
- [dispatchId]
295
- );
416
+ await setByUpsert(dispatchId);
296
417
  }
297
418
  };
298
419
  }
@@ -318,7 +439,8 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
318
439
  function base64urlToBuffer(b64) {
319
440
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
320
441
  }
321
- function pemToBase64(pem) {
442
+ function pemToBase64(pemRaw) {
443
+ const pem = pemRaw.replace(/(?:\\r)?\\n/g, "\n");
322
444
  const begin = pem.indexOf("-----BEGIN");
323
445
  if (begin === -1) return pem.replace(/\s/g, "");
324
446
  const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
@@ -379,7 +501,7 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
379
501
  return JSON.parse(new TextDecoder().decode(plaintext));
380
502
  }
381
503
  async function decryptSession(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
382
- const { decryptSession: decryptSessionCrypto } = await import("./src-UACTYQGX.mjs");
504
+ const { decryptSession: decryptSessionCrypto } = await import("./src-ENJJ6YZU.mjs");
383
505
  return decryptSessionCrypto(
384
506
  share,
385
507
  envelopeB64,
@@ -526,6 +648,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
526
648
  `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
527
649
  );
528
650
  }
651
+ const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
652
+ if (parsedBase.protocol !== "https:" && !loopback) {
653
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
654
+ }
529
655
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
530
656
  const res = await fetch(url);
531
657
  if (!res.ok) {
@@ -602,12 +728,13 @@ async function verifyD5LOA(loa, publicKeyPem) {
602
728
  return false;
603
729
  }
604
730
  }
605
- async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
731
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expectedAlg) {
606
732
  const data = await decryptSession(
607
733
  loaEncrypted.session_key_share,
608
734
  loaEncrypted.session_envelope,
609
735
  privateKeyPem,
610
- partnerId
736
+ partnerId,
737
+ expectedAlg
611
738
  );
612
739
  return data;
613
740
  }
@@ -792,14 +919,61 @@ function requireContactValue(kind, value) {
792
919
  }
793
920
  var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
794
921
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
922
+ var warnedConsentUnverified = false;
923
+ var warnedNoIdempotencyStore = false;
924
+ function _resetOnceWarningsForTests() {
925
+ warnedConsentUnverified = false;
926
+ warnedNoIdempotencyStore = false;
927
+ }
928
+ var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
929
+ var XWING_SEED_BYTES = 32;
930
+ function assertUsablePrivateKey(privateKeyPem) {
931
+ if (typeof privateKeyPem !== "string") {
932
+ if (!privateKeyPem || typeof privateKeyPem !== "object" || typeof privateKeyPem.name !== "string") {
933
+ throw new Error("[OneAddress SDK] privateKeyPem must be a PEM string or a PrivateKeyOperations delegate");
934
+ }
935
+ return;
936
+ }
937
+ if (privateKeyPem.trim() === "") {
938
+ throw new Error("[OneAddress SDK] privateKeyPem is required: set it to your PKCS#8 private key from the Partner Portal");
939
+ }
940
+ const der = pemToBuffer(privateKeyPem);
941
+ if (der.length === XWING_SEED_BYTES) return;
942
+ try {
943
+ crypto.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
944
+ } catch (err) {
945
+ const refused = new Error(
946
+ `[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.`
947
+ );
948
+ refused.cause = err;
949
+ throw refused;
950
+ }
951
+ }
952
+ function requirePemFor(purpose, key) {
953
+ if (typeof key === "string") return key;
954
+ throw new Error(
955
+ `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
956
+ );
957
+ }
958
+ function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
959
+ if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
960
+ if (loa.update_uid !== envelopeUpdateUid) {
961
+ throw new Error(
962
+ "[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"
963
+ );
964
+ }
965
+ }
795
966
  function createOneAddressHandler(options) {
796
967
  const {
797
968
  webhookSecret,
798
969
  previousWebhookSecret,
799
970
  webhookSecretGraceUntil,
800
971
  privateKeyPem,
972
+ expectedAlg,
801
973
  keyId,
802
974
  loaPublicKeyPem,
975
+ requireLoa = Boolean(loaPublicKeyPem),
976
+ confirm,
803
977
  onUpdate,
804
978
  onVerify,
805
979
  onAccountVerify,
@@ -809,6 +983,40 @@ function createOneAddressHandler(options) {
809
983
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
810
984
  allowedCallbackHosts
811
985
  } = options;
986
+ if (typeof webhookSecret !== "string" || webhookSecret === "") {
987
+ throw new Error("[OneAddress SDK] webhookSecret is required: an empty secret would verify no signature at all");
988
+ }
989
+ assertUsablePrivateKey(privateKeyPem);
990
+ if (typeof timestampToleranceSecs !== "number" || !Number.isFinite(timestampToleranceSecs) || timestampToleranceSecs <= 0 || timestampToleranceSecs > MAX_TIMESTAMP_TOLERANCE_SECS) {
991
+ throw new Error(
992
+ `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
993
+ );
994
+ }
995
+ if (webhookSecretGraceUntil !== void 0) {
996
+ const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
997
+ if (Number.isNaN(until)) {
998
+ throw new Error(`[OneAddress SDK] webhookSecretGraceUntil is not a date: ${String(webhookSecretGraceUntil)}`);
999
+ }
1000
+ }
1001
+ if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
1002
+ throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
1003
+ }
1004
+ function enforceLoaPresence(body) {
1005
+ const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
1006
+ if (present) return;
1007
+ if (requireLoa) {
1008
+ throw new Error(
1009
+ "[OneAddress SDK] dispatch carries no loa_encrypted and requireLoa is on: refusing to apply an update whose consent proof is missing"
1010
+ );
1011
+ }
1012
+ if (!warnedConsentUnverified) {
1013
+ warnedConsentUnverified = true;
1014
+ console.warn(
1015
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
1016
+ "[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."
1017
+ );
1018
+ }
1019
+ }
812
1020
  const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
813
1021
  function declared(status, payload) {
814
1022
  return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
@@ -818,7 +1026,7 @@ function createOneAddressHandler(options) {
818
1026
  }
819
1027
  async function buildD5Pieces(body, partnerId) {
820
1028
  const share = body.session_key_share;
821
- const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId);
1029
+ const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
822
1030
  const updateTypes = readUpdateTypes(data.update_types);
823
1031
  if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
824
1032
  const address = updateTypes.includes("address") ? validateAddress({
@@ -843,13 +1051,15 @@ function createOneAddressHandler(options) {
843
1051
  loa = await decryptLoaEncrypted(
844
1052
  body.loa_encrypted,
845
1053
  privateKeyPem,
846
- partnerId
1054
+ partnerId,
1055
+ expectedAlg
847
1056
  );
848
1057
  loa_ref = d5LoaRef(loa);
849
1058
  if (loaPublicKeyPem) {
850
1059
  const valid = await verifyD5LOA(loa, loaPublicKeyPem);
851
1060
  if (!valid) throw new Error("D5 LOA signature verification failed");
852
1061
  }
1062
+ assertLoaBoundToEnvelope(loa, data.update_uid);
853
1063
  }
854
1064
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
855
1065
  }
@@ -882,7 +1092,11 @@ function createOneAddressHandler(options) {
882
1092
  }
883
1093
  let body;
884
1094
  try {
885
- body = JSON.parse(rawBody);
1095
+ const parsed = JSON.parse(rawBody);
1096
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1097
+ throw new TypeError("body is not a JSON object");
1098
+ }
1099
+ body = parsed;
886
1100
  } catch {
887
1101
  return new Response(JSON.stringify({ error: "Invalid JSON" }), {
888
1102
  status: 400,
@@ -904,11 +1118,19 @@ function createOneAddressHandler(options) {
904
1118
  }
905
1119
  if (dispatchId) {
906
1120
  if (!idempotencyStore) {
907
- if (process.env.NODE_ENV === "test") {
1121
+ const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
1122
+ if (nodeEnv === "test") {
908
1123
  throw new Error(
909
1124
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
910
1125
  );
911
1126
  }
1127
+ if (!warnedNoIdempotencyStore) {
1128
+ warnedNoIdempotencyStore = true;
1129
+ console.warn(
1130
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
1131
+ "[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."
1132
+ );
1133
+ }
912
1134
  } else if (idempotencyStore.claim) {
913
1135
  const claim = await idempotencyStore.claim(dispatchId);
914
1136
  if (claim === "duplicate") {
@@ -925,6 +1147,7 @@ function createOneAddressHandler(options) {
925
1147
  if (body.event === "address.updated" || body.event === "contact.updated") {
926
1148
  const wireEvent = body.event;
927
1149
  let event;
1150
+ enforceLoaPresence(body);
928
1151
  if (isD5Body(body)) {
929
1152
  let d5;
930
1153
  try {
@@ -977,19 +1200,25 @@ function createOneAddressHandler(options) {
977
1200
  });
978
1201
  }
979
1202
  const encrypted = body.address_encrypted;
980
- const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
1203
+ const rawAddress = await decryptAddress(
1204
+ encrypted,
1205
+ requirePemFor("legacy address_encrypted decryption", privateKeyPem),
1206
+ partnerId
1207
+ );
981
1208
  let loa;
982
1209
  let loa_ref;
983
1210
  if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
984
1211
  loa = await decryptLoaEncrypted(
985
1212
  body.loa_encrypted,
986
1213
  privateKeyPem,
987
- partnerId
1214
+ partnerId,
1215
+ expectedAlg
988
1216
  );
989
1217
  loa_ref = d5LoaRef(loa);
990
1218
  if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
991
1219
  throw new Error("D5 LOA signature verification failed");
992
1220
  }
1221
+ assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
993
1222
  }
994
1223
  const customer = {
995
1224
  email: "",
@@ -1022,6 +1251,25 @@ function createOneAddressHandler(options) {
1022
1251
  // NOSONAR
1023
1252
  );
1024
1253
  }
1254
+ if (confirm && dispatchId) {
1255
+ const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
1256
+ void confirmUpdate({
1257
+ partnerId: confirm.partnerId,
1258
+ secret: confirm.confirmSecret,
1259
+ dispatchId,
1260
+ status,
1261
+ loaRef: event.loa_ref,
1262
+ ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
1263
+ ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
1264
+ }).then(
1265
+ (r) => {
1266
+ if (!r.ok) console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} failed: HTTP ${r.status} ${r.error ?? ""}`);
1267
+ },
1268
+ // NOSONAR
1269
+ (err) => console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} threw:`, err)
1270
+ // NOSONAR
1271
+ );
1272
+ }
1025
1273
  return declared(200, { ok: true, ...result });
1026
1274
  }
1027
1275
  if (body.event === "address.verify" && onVerify) {
@@ -1032,7 +1280,11 @@ function createOneAddressHandler(options) {
1032
1280
  });
1033
1281
  }
1034
1282
  const encrypted = body.address_encrypted;
1035
- const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
1283
+ const rawAddress = await decryptAddress(
1284
+ encrypted,
1285
+ requirePemFor("address.verify decryption", privateKeyPem),
1286
+ partnerId
1287
+ );
1036
1288
  const event = {
1037
1289
  event: "address.verify",
1038
1290
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -1079,7 +1331,7 @@ function createOneAddressHandler(options) {
1079
1331
  if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
1080
1332
  const raw = await decryptAddress(
1081
1333
  body.customer_encrypted,
1082
- privateKeyPem,
1334
+ requirePemFor("account.verify decryption", privateKeyPem),
1083
1335
  partnerId
1084
1336
  );
1085
1337
  customer = {
@@ -1125,7 +1377,12 @@ function createOneAddressHandler(options) {
1125
1377
  address: d5.address,
1126
1378
  raw: d5.raw
1127
1379
  });
1128
- return declared(200, { ok: true, test: true });
1380
+ return declared(200, {
1381
+ ok: true,
1382
+ test: true,
1383
+ verification: true,
1384
+ index: typeof body.index === "number" ? body.index : void 0
1385
+ });
1129
1386
  }
1130
1387
  const evt = typeof body.event === "string" ? body.event : "(none)";
1131
1388
  const callbackFor = {
@@ -1198,6 +1455,113 @@ function toExpressHandler(handler) {
1198
1455
  res.send(bodyText);
1199
1456
  };
1200
1457
  }
1458
+ async function buildSignedTestWebhook(opts) {
1459
+ const nowSecs = opts.timestamp ?? Math.floor(Date.now() / 1e3);
1460
+ const nowIso = new Date(nowSecs * 1e3).toISOString();
1461
+ const updateIdNum = crypto.randomInt(9e8, 901e6);
1462
+ const updateUid = opts.session?.update_uid ?? String(updateIdNum);
1463
+ const partnerKey = {
1464
+ partner_id: opts.partnerId,
1465
+ key_id: opts.keyId ?? "test-key-1",
1466
+ public_key_b64: pemToBase64(opts.publicKey),
1467
+ algorithm: opts.algorithm ?? "ECDH-P256-AES-GCM-256"
1468
+ };
1469
+ const kinds = readUpdateTypes(opts.session?.update_types) ?? ["address"];
1470
+ const sessionData = {
1471
+ v: 2,
1472
+ update_uid: updateUid,
1473
+ dispatch_timestamp: nowIso,
1474
+ verified_name: "Test Person",
1475
+ ...kinds.includes("address") ? { new_address: { street: "42 Collins Street", suburb: "Melbourne", state: "VIC", postcode: "3000", country: "AU" } } : {},
1476
+ ...kinds.includes("phone") ? { new_phone: "+61412345678" } : {},
1477
+ ...kinds.includes("email") ? { new_email: "test.person@example.com" } : {},
1478
+ account_number: "TEST-0001",
1479
+ id_verification_ref: crypto.randomUUID(),
1480
+ known_names: [],
1481
+ ...opts.session ?? {}
1482
+ };
1483
+ const envelope = await encryptSessionForPartner(sessionData, partnerKey);
1484
+ let loa;
1485
+ let loa_encrypted;
1486
+ if (opts.loa !== false) {
1487
+ loa = {
1488
+ consumer_name: sessionData.verified_name,
1489
+ authorisation_date: nowIso,
1490
+ scope: "Authority to update address records on file.",
1491
+ update_uid: updateUid,
1492
+ oneaddress_acn: "696 078 869",
1493
+ oneaddress_signature: "00".repeat(64),
1494
+ signature_algorithm: "ECDSA-P256",
1495
+ ...opts.loa ?? {}
1496
+ };
1497
+ if (opts.loaSigningKeyPem) {
1498
+ const key = await crypto.subtle.importKey(
1499
+ "pkcs8",
1500
+ pemToBuffer(opts.loaSigningKeyPem),
1501
+ { name: "ECDSA", namedCurve: "P-256" },
1502
+ false,
1503
+ ["sign"]
1504
+ );
1505
+ const sig2 = await crypto.subtle.sign(
1506
+ { name: "ECDSA", hash: "SHA-256" },
1507
+ key,
1508
+ new TextEncoder().encode(canonicalD5LoaForm(loa))
1509
+ );
1510
+ loa.oneaddress_signature = Buffer.from(sig2).toString("hex");
1511
+ }
1512
+ const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
1513
+ loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
1514
+ }
1515
+ const event = opts.event ?? (kinds.includes("address") ? "address.updated" : "contact.updated");
1516
+ const body = JSON.stringify({
1517
+ event,
1518
+ oneaddress_version: CURRENT_VERSION,
1519
+ // A NUMBER. The relay sends `user_updates.id`; `update_uid` inside the
1520
+ // envelope and the LOA is its string form, which is the relationship a
1521
+ // receiver uses to bind the decrypted authorisation to the update.
1522
+ update_id: updateIdNum,
1523
+ partner_id: opts.partnerId,
1524
+ user_id: opts.userId ?? "test:consumer",
1525
+ timestamp: nowIso,
1526
+ session_envelope: envelope.session_envelope,
1527
+ session_key_share: envelope.session_key_share,
1528
+ // Per RECIPIENT, from the same resolver the relay uses, not a constant.
1529
+ key_share_expiry: keyShareExpiryIso(new Date(nowSecs * 1e3), opts.retentionPeriodDays),
1530
+ id_verification: { method: "identity_document", verified_at: nowIso, verified: true, platform: "oneaddress/v1" },
1531
+ ...loa_encrypted ? { loa_encrypted } : {},
1532
+ // On the wire with a `null` value when no PaymentIntent backed the update,
1533
+ // so the KEY is present either way.
1534
+ stripe_session_id: opts.stripeSessionId ?? null,
1535
+ // `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
1536
+ // by default. A test that needs them passes them through `extraBody`, which
1537
+ // is exactly the circumstance the relay emits them in.
1538
+ ...opts.extraBody ?? {}
1539
+ });
1540
+ const ts = String(nowSecs);
1541
+ const sig = crypto.createHmac("sha256", opts.webhookSecret).update(`${ts}.${body}`).digest("hex");
1542
+ const dispatchId = opts.dispatchId ?? "1";
1543
+ const headers = {
1544
+ "Content-Type": "application/json",
1545
+ "X-OneAddress-Event": event,
1546
+ "X-OneAddress-Partner": opts.partnerId,
1547
+ "X-OneAddress-Version": CURRENT_VERSION,
1548
+ "X-OneAddress-Timestamp": ts,
1549
+ "X-OneAddress-Signature": sig,
1550
+ ...dispatchId ? { "X-OneAddress-Dispatch": dispatchId } : {}
1551
+ };
1552
+ const lower = new Map(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
1553
+ return {
1554
+ body,
1555
+ headers,
1556
+ sessionData,
1557
+ loa,
1558
+ request: {
1559
+ text: async () => body,
1560
+ headers: { get: (name) => lower.get(name.toLowerCase()) ?? null }
1561
+ },
1562
+ toRequest: (url = "https://receiver.example/webhook") => new Request(url, { method: "POST", headers, body })
1563
+ };
1564
+ }
1201
1565
 
1202
1566
  export {
1203
1567
  CURRENT_VERSION,
@@ -1228,6 +1592,8 @@ export {
1228
1592
  formatAddressParts,
1229
1593
  compareAddresses,
1230
1594
  sendVerifyResult,
1595
+ _resetOnceWarningsForTests,
1231
1596
  createOneAddressHandler,
1232
- toExpressHandler
1597
+ toExpressHandler,
1598
+ buildSignedTestWebhook
1233
1599
  };