@oneaddress/partner-sdk 1.3.0 → 1.6.1

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,6 +1,7 @@
1
1
  import {
2
- isFreshTimestamp
3
- } from "./chunk-2QGC7BHC.mjs";
2
+ isFreshTimestamp,
3
+ isSafeWebhookUrl
4
+ } from "./chunk-TAZD6PFZ.mjs";
4
5
 
5
6
  // src/index.ts
6
7
  import crypto from "crypto";
@@ -9,7 +10,92 @@ import crypto from "crypto";
9
10
  var CURRENT_VERSION = "2026.1";
10
11
  var SUPPORTED_VERSIONS = ["2026.1"];
11
12
 
13
+ // ../name-match/src/index.ts
14
+ function isEmailLike(value) {
15
+ return value.includes("@");
16
+ }
17
+ function stripDiacritics(s) {
18
+ return s.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
19
+ }
20
+ function norm(s) {
21
+ return stripDiacritics(s).toLowerCase().replaceAll(".", "").trim().replaceAll(/\s+/g, " ");
22
+ }
23
+ function tokenize(name) {
24
+ return norm(name).split(" ").filter(Boolean);
25
+ }
26
+ function surnameVariants(token) {
27
+ if (!token.includes("-")) return [token];
28
+ return [token, ...token.split("-").filter(Boolean)];
29
+ }
30
+ function namePoolMatches(providedNames, storedName) {
31
+ if (isEmailLike(storedName)) return false;
32
+ const provided = providedNames.filter((n) => Boolean(n) && !isEmailLike(n));
33
+ const primary = tokenize(provided[0] ?? "");
34
+ if (primary.length === 0) return false;
35
+ const surnames = new Set(surnameVariants(primary[primary.length - 1]));
36
+ for (let i = 1; i < provided.length; i++) {
37
+ const t = tokenize(provided[i]);
38
+ if (t.length >= 2) for (const v of surnameVariants(t[t.length - 1])) surnames.add(v);
39
+ }
40
+ const all = /* @__PURE__ */ new Set();
41
+ for (const n of provided) for (const t of tokenize(n)) all.add(t);
42
+ const given = [...all].filter((t) => !surnames.has(t));
43
+ const stored = tokenize(storedName);
44
+ if (stored.length === 0) return false;
45
+ const storedSurname = stored[stored.length - 1];
46
+ const storedGiven = stored.slice(0, -1);
47
+ if (!surnameVariants(storedSurname).some((v) => surnames.has(v))) return false;
48
+ const covered = (tok) => given.includes(tok) || tok.length === 1 && given.some((g) => g[0] === tok) || given.some((g) => g.length === 1 && g === tok[0]);
49
+ return storedGiven.every(covered);
50
+ }
51
+ function findMatchingStoredName(providedNames, storedCandidates) {
52
+ return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
53
+ }
54
+
12
55
  // src/index.ts
56
+ function createSqlIdempotencyStore(opts) {
57
+ const table = opts.table ?? "oneaddress_dispatches";
58
+ const ph = opts.placeholder ?? ((n) => `$${n}`);
59
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
60
+ throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
61
+ }
62
+ const completedOf = (row) => row?.completed_at ?? row?.completedAt ?? null;
63
+ return {
64
+ async claim(dispatchId) {
65
+ const inserted = await opts.query(
66
+ `INSERT INTO ${table} (dispatch_id) VALUES (${ph(1)}) ON CONFLICT (dispatch_id) DO NOTHING RETURNING dispatch_id`,
67
+ [dispatchId]
68
+ );
69
+ if (inserted.length > 0) return "fresh";
70
+ const rows = await opts.query(
71
+ `SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
72
+ [dispatchId]
73
+ );
74
+ return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
75
+ },
76
+ async complete(dispatchId) {
77
+ await opts.query(
78
+ `UPDATE ${table} SET completed_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)}`,
79
+ [dispatchId]
80
+ );
81
+ },
82
+ // Legacy surface, implemented over the same table so a store built here
83
+ // still satisfies callers (or SDK versions) that only know has/set.
84
+ async has(dispatchId) {
85
+ const rows = await opts.query(
86
+ `SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
87
+ [dispatchId]
88
+ );
89
+ return rows.length > 0 && Boolean(completedOf(rows[0]));
90
+ },
91
+ async set(dispatchId) {
92
+ await opts.query(
93
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
94
+ [dispatchId]
95
+ );
96
+ }
97
+ };
98
+ }
13
99
  function verifySignature(rawBody, signature, timestamp, secret) {
14
100
  if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
15
101
  const sigPayload = `${timestamp}.${rawBody}`;
@@ -32,8 +118,17 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
32
118
  function base64urlToBuffer(b64) {
33
119
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
34
120
  }
121
+ function pemToBase64(pem) {
122
+ const begin = pem.indexOf("-----BEGIN");
123
+ if (begin === -1) return pem.replace(/\s/g, "");
124
+ const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
125
+ if (armourEnd === -1) return pem.replace(/\s/g, "");
126
+ const bodyStart = armourEnd + "-----".length;
127
+ const end = pem.indexOf("-----END", bodyStart);
128
+ return (end === -1 ? pem.slice(bodyStart) : pem.slice(bodyStart, end)).replace(/\s/g, "");
129
+ }
35
130
  function pemToBuffer(pem) {
36
- return Buffer.from(pem.replace(/-----[^-]+-----/g, "").replace(/\s/g, ""), "base64");
131
+ return Buffer.from(pemToBase64(pem), "base64");
37
132
  }
38
133
  async function decryptAddress(payload, privateKeyPem, partnerId) {
39
134
  const { ephemeralPublicKey, iv, ciphertext, hkdfSalt } = payload;
@@ -84,9 +179,8 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
84
179
  return JSON.parse(new TextDecoder().decode(plaintext));
85
180
  }
86
181
  async function decryptSession(share, envelopeB64, privateKeyPem, partnerId) {
87
- const { decryptSession: decryptSessionCrypto } = await import("./src-DYGFEKX6.mjs");
88
- const privateKeyB64 = privateKeyPem.replace(/-----[^-]+-----/g, "").replace(/\s/g, "");
89
- return decryptSessionCrypto(share, envelopeB64, privateKeyB64, partnerId);
182
+ const { decryptSession: decryptSessionCrypto } = await import("./src-ESYTJ2EY.mjs");
183
+ return decryptSessionCrypto(share, envelopeB64, pemToBase64(privateKeyPem), partnerId);
90
184
  }
91
185
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
92
186
  const plaintext = await decryptAddress(payload, privateKeyPem, partnerId);
@@ -147,7 +241,72 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
147
241
  );
148
242
  }
149
243
  var OA_APP_BASE_URL = "https://oneaddress.io";
150
- var ALLOWED_LOA_HOSTS = /* @__PURE__ */ new Set(["oneaddress.io", "app.oneaddress.io", "localhost", "127.0.0.1"]);
244
+ async function confirmUpdate(opts) {
245
+ const {
246
+ partnerId,
247
+ secret,
248
+ dispatchId,
249
+ status = "confirmed",
250
+ note,
251
+ loaRef,
252
+ memberName,
253
+ appBaseUrl = OA_APP_BASE_URL,
254
+ fetchImpl = fetch
255
+ } = opts;
256
+ if (!partnerId) return { ok: false, status: 0, error: "partnerId is required" };
257
+ if (!secret) return { ok: false, status: 0, error: "secret is required" };
258
+ const id = typeof dispatchId === "string" ? Number(dispatchId) : dispatchId;
259
+ if (!Number.isInteger(id) || id <= 0) {
260
+ return {
261
+ ok: false,
262
+ status: 0,
263
+ error: `dispatchId must be a positive integer, received ${JSON.stringify(dispatchId)} \u2014 it comes from the X-OneAddress-Dispatch header on the webhook you are confirming`
264
+ };
265
+ }
266
+ const body = JSON.stringify({
267
+ dispatch_id: id,
268
+ partner_id: partnerId,
269
+ status,
270
+ ...note !== void 0 ? { note } : {},
271
+ ...loaRef !== void 0 ? { loa_ref: loaRef } : {},
272
+ ...memberName !== void 0 ? { member_name: memberName } : {}
273
+ });
274
+ const timestamp = String(Math.floor(Date.now() / 1e3));
275
+ const signature = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
276
+ let base = appBaseUrl;
277
+ while (base.endsWith("/")) base = base.slice(0, -1);
278
+ let res;
279
+ try {
280
+ res = await fetchImpl(`${base}/api/confirm`, {
281
+ method: "POST",
282
+ headers: {
283
+ "Content-Type": "application/json",
284
+ "Authorization": `Bearer ${secret}`,
285
+ "X-OneAddress-Timestamp": timestamp,
286
+ "X-OneAddress-Signature": signature
287
+ },
288
+ // The SAME string that was signed. Not an object, and not re-stringified.
289
+ body
290
+ });
291
+ } catch (err) {
292
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
293
+ }
294
+ if (res.ok) return { ok: true, status: res.status };
295
+ let error;
296
+ try {
297
+ const parsed = await res.json();
298
+ if (typeof parsed?.error === "string") error = parsed.error;
299
+ } catch {
300
+ }
301
+ return { ok: false, status: res.status, error };
302
+ }
303
+ function allowedLoaHosts() {
304
+ const hosts = ["oneaddress.io", "app.oneaddress.io"];
305
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
306
+ hosts.push("localhost", "127.0.0.1");
307
+ }
308
+ return new Set(hosts);
309
+ }
151
310
  async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
152
311
  let parsedBase;
153
312
  try {
@@ -155,9 +314,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
155
314
  } catch {
156
315
  throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl is not a valid URL");
157
316
  }
158
- if (!ALLOWED_LOA_HOSTS.has(parsedBase.hostname)) {
317
+ const allowedHosts = allowedLoaHosts();
318
+ if (!allowedHosts.has(parsedBase.hostname)) {
159
319
  throw new Error(
160
- `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...ALLOWED_LOA_HOSTS].join(", ")}`
320
+ `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
161
321
  );
162
322
  }
163
323
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
@@ -266,6 +426,34 @@ function validateAddress(raw) {
266
426
  }
267
427
  return obj;
268
428
  }
429
+ var ADDRESS_ALIASES = {
430
+ line1: ["line1", "address_line1", "street", "streetAddress"],
431
+ suburb: ["suburb", "city", "locality", "town"],
432
+ state: ["state", "region", "province"],
433
+ postcode: ["postcode", "postalCode", "postal_code", "zip"],
434
+ country: ["country"]
435
+ };
436
+ function readAddressParts(raw) {
437
+ const a = raw && typeof raw === "object" ? raw : {};
438
+ const read = (part) => {
439
+ for (const key of ADDRESS_ALIASES[part]) {
440
+ const v = a[key];
441
+ if (typeof v === "string" && v.trim() !== "") return v.trim();
442
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
443
+ }
444
+ return "";
445
+ };
446
+ return {
447
+ line1: read("line1"),
448
+ suburb: read("suburb"),
449
+ state: read("state"),
450
+ postcode: read("postcode"),
451
+ country: read("country") || "AU"
452
+ };
453
+ }
454
+ function formatAddressParts(parts) {
455
+ return [parts.line1, parts.suburb, parts.state, parts.postcode].filter(Boolean).join(", ");
456
+ }
269
457
  var STREET_SUFFIX_MAP = {
270
458
  st: "street",
271
459
  str: "street",
@@ -323,6 +511,30 @@ function compareAddresses(a, b) {
323
511
  if (aCountry && bCountry && aCountry !== bCountry) return false;
324
512
  return true;
325
513
  }
514
+ async function sendVerifyResult(params) {
515
+ const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
516
+ const safe = isSafeWebhookUrl(callbackUrl);
517
+ if (!safe.ok) {
518
+ throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
519
+ }
520
+ const res = await fetch(callbackUrl, {
521
+ method: "POST",
522
+ headers: { "Content-Type": "application/json" },
523
+ body: JSON.stringify({
524
+ batch_id: batchId,
525
+ partner_id: partnerId,
526
+ result: match ? "match" : "mismatch",
527
+ address_match: match,
528
+ ...note ? { note } : {},
529
+ token: callbackToken
530
+ })
531
+ });
532
+ if (!res.ok) {
533
+ throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
534
+ }
535
+ }
536
+ var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
537
+ var warnedUnhandledEvents = /* @__PURE__ */ new Set();
326
538
  function createOneAddressHandler(options) {
327
539
  const {
328
540
  webhookSecret,
@@ -333,6 +545,7 @@ function createOneAddressHandler(options) {
333
545
  onUpdate,
334
546
  onVerify,
335
547
  onAccountVerify,
548
+ onTest,
336
549
  timestampToleranceSecs = 300,
337
550
  idempotencyStore
338
551
  } = options;
@@ -414,6 +627,14 @@ function createOneAddressHandler(options) {
414
627
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
415
628
  );
416
629
  }
630
+ } else if (idempotencyStore.claim) {
631
+ const claim = await idempotencyStore.claim(dispatchId);
632
+ if (claim === "duplicate") {
633
+ return new Response(JSON.stringify({ ok: true, duplicate: true }), {
634
+ status: 200,
635
+ headers: { "Content-Type": "application/json" }
636
+ });
637
+ }
417
638
  } else {
418
639
  const alreadySeen = await idempotencyStore.has(dispatchId);
419
640
  if (alreadySeen) {
@@ -488,8 +709,9 @@ function createOneAddressHandler(options) {
488
709
  }
489
710
  const result = await onUpdate(event);
490
711
  if (dispatchId && idempotencyStore) {
491
- await idempotencyStore.set(dispatchId).catch(
492
- (err) => console.error("[OneAddress SDK] idempotencyStore.set failed:", err)
712
+ const record = idempotencyStore.complete ? idempotencyStore.complete(dispatchId) : idempotencyStore.set(dispatchId);
713
+ await record.catch(
714
+ (err) => console.error("[OneAddress SDK] idempotency completion failed:", err)
493
715
  // NOSONAR
494
716
  );
495
717
  }
@@ -524,7 +746,28 @@ function createOneAddressHandler(options) {
524
746
  raw: rawAddress
525
747
  };
526
748
  const result = await onVerify(event);
527
- return new Response(JSON.stringify({ ok: true, ...result }), {
749
+ const matched = result && typeof result.match === "boolean" ? result.match : void 0;
750
+ const callbackUrl = typeof body.callback_url === "string" ? body.callback_url : "";
751
+ const callbackToken = typeof body.callback_token === "string" ? body.callback_token : "";
752
+ if (matched === void 0) {
753
+ console.error("[OneAddress SDK] onVerify must return { match: boolean } to close the verify loop; result dropped.");
754
+ } else if (!callbackUrl || !callbackToken) {
755
+ console.error("[OneAddress SDK] address.verify webhook is missing callback_url/callback_token; cannot report the result.");
756
+ } else {
757
+ try {
758
+ await sendVerifyResult({
759
+ callbackUrl,
760
+ callbackToken,
761
+ batchId: body.batch_id ?? 0,
762
+ partnerId,
763
+ match: matched,
764
+ note: result && typeof result.note === "string" ? result.note : void 0
765
+ });
766
+ } catch (err) {
767
+ console.error("[OneAddress SDK] verify-result callback failed:", err);
768
+ }
769
+ }
770
+ return new Response(JSON.stringify({ ok: true, match: matched }), {
528
771
  status: 200,
529
772
  headers: { "Content-Type": "application/json" }
530
773
  });
@@ -563,7 +806,50 @@ function createOneAddressHandler(options) {
563
806
  headers: { "Content-Type": "application/json" }
564
807
  });
565
808
  }
566
- return new Response(JSON.stringify({ ok: true, skipped: true }), {
809
+ if (body.event === "address.test" && onTest) {
810
+ if (!isD5Body(body)) {
811
+ return new Response(JSON.stringify({ error: "address.test requires a session envelope" }), {
812
+ status: 400,
813
+ headers: { "Content-Type": "application/json" }
814
+ });
815
+ }
816
+ const d5 = await buildD5Pieces(body, partnerId);
817
+ await onTest({
818
+ event: "address.test",
819
+ index: typeof body.index === "number" ? body.index : void 0,
820
+ total: typeof body.total === "number" ? body.total : void 0,
821
+ verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
822
+ timestamp: tsNum,
823
+ partner_id: partnerId,
824
+ customer: d5.customer,
825
+ address: d5.address,
826
+ raw: d5.raw
827
+ });
828
+ return new Response(JSON.stringify({ ok: true, test: true }), {
829
+ status: 200,
830
+ headers: { "Content-Type": "application/json" }
831
+ });
832
+ }
833
+ const evt = typeof body.event === "string" ? body.event : "(none)";
834
+ const callbackFor = {
835
+ "address.verify": onVerify,
836
+ "account.verify": onAccountVerify,
837
+ "address.test": onTest
838
+ };
839
+ const callbackNameFor = {
840
+ "address.verify": "onVerify",
841
+ "account.verify": "onAccountVerify",
842
+ "address.test": "onTest"
843
+ };
844
+ const unwired = evt in callbackFor && !callbackFor[evt] ? callbackNameFor[evt] : null;
845
+ if (!warnedUnhandledEvents.has(evt)) {
846
+ warnedUnhandledEvents.add(evt);
847
+ console.warn(
848
+ unwired ? `[OneAddress SDK] Event "${evt}" was SKIPPED because you did not pass a \`${unwired}\` callback to createOneAddressHandler. This build supports "${evt}" - upgrading the SDK will NOT fix it. It was acknowledged with 200 so OneAddress does not retry, which means the sender sees a clean delivery and nothing was processed. Add \`${unwired}\` to your handler options.` : `[OneAddress SDK] Event "${evt}" is not handled by this build and was SKIPPED. It was acknowledged with 200 so OneAddress does not retry, but your onUpdate callback did NOT run. This build handles: ${HANDLED_EVENTS.join(", ")}. If you expected this event to be processed, update @oneaddress/partner-sdk.`
849
+ // NOSONAR
850
+ );
851
+ }
852
+ return new Response(JSON.stringify({ ok: true, skipped: true, event: evt }), {
567
853
  status: 200,
568
854
  headers: { "Content-Type": "application/json" }
569
855
  });
@@ -577,16 +863,54 @@ function createOneAddressHandler(options) {
577
863
  }
578
864
  };
579
865
  }
866
+ function toExpressHandler(handler) {
867
+ return async function expressHandler(req, res) {
868
+ const raw = req.body;
869
+ const isBuffer = typeof raw === "object" && raw !== null && typeof raw.copy === "function" && typeof raw.toString === "function";
870
+ if (!isBuffer && typeof raw !== "string") {
871
+ const detail = raw === void 0 ? "the body was not read at all" : `the body arrived as ${raw === null ? "null" : typeof raw}, already parsed`;
872
+ console.error(
873
+ `[OneAddress SDK] toExpressHandler: raw request body required, but ${detail}. Add express.raw({ type: 'application/json' }) to THIS route, before the handler, and make sure no global express.json() runs first. The webhook signature is computed over the raw bytes, so a parsed body cannot be verified.`
874
+ // NOSONAR
875
+ );
876
+ res.status(500).send(JSON.stringify({ error: "Receiver misconfigured: raw body required" }));
877
+ return;
878
+ }
879
+ const text = typeof raw === "string" ? raw : String(raw);
880
+ const fetchLike = {
881
+ text: async () => text,
882
+ headers: {
883
+ get(name) {
884
+ const v = req.headers[name.toLowerCase()];
885
+ if (v === void 0) return null;
886
+ return Array.isArray(v) ? v.join(", ") : v;
887
+ }
888
+ }
889
+ };
890
+ const out = await handler(fetchLike);
891
+ const bodyText = await out.text();
892
+ res.status(out.status);
893
+ out.headers.forEach((value, key) => {
894
+ res.setHeader(key, value);
895
+ });
896
+ res.send(bodyText);
897
+ };
898
+ }
580
899
 
581
900
  export {
582
901
  CURRENT_VERSION,
583
902
  SUPPORTED_VERSIONS,
903
+ isEmailLike,
904
+ namePoolMatches,
905
+ findMatchingStoredName,
906
+ createSqlIdempotencyStore,
584
907
  verifySignature,
585
908
  verifyWithGrace,
586
909
  decryptAddress,
587
910
  decryptSession,
588
911
  transformAddress,
589
912
  transformSession,
913
+ confirmUpdate,
590
914
  fetchLoaPublicKey,
591
915
  verifyLOA,
592
916
  canonicalD5LoaForm,
@@ -594,6 +918,10 @@ export {
594
918
  verifyD5LOA,
595
919
  decryptLoaEncrypted,
596
920
  validateAddress,
921
+ readAddressParts,
922
+ formatAddressParts,
597
923
  compareAddresses,
598
- createOneAddressHandler
924
+ sendVerifyResult,
925
+ createOneAddressHandler,
926
+ toExpressHandler
599
927
  };