@oneaddress/partner-sdk 1.1.1 → 1.3.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,23 +1,17 @@
1
+ import {
2
+ isFreshTimestamp
3
+ } from "./chunk-2QGC7BHC.mjs";
4
+
1
5
  // src/index.ts
2
6
  import crypto from "crypto";
3
7
 
4
- // ../crypto/src/replay-window.ts
5
- var DEFAULT_REPLAY_WINDOW_SECS = 300;
6
- function isFreshTimestamp(timestampHeader, toleranceSecs = DEFAULT_REPLAY_WINDOW_SECS, nowSecs) {
7
- if (typeof timestampHeader !== "string" || timestampHeader.length === 0) return false;
8
- if (!/^\d+$/.test(timestampHeader)) return false;
9
- const ts = Number(timestampHeader);
10
- if (!Number.isFinite(ts) || ts < 0) return false;
11
- const now = typeof nowSecs === "number" ? nowSecs : Math.floor(Date.now() / 1e3);
12
- return Math.abs(now - ts) <= toleranceSecs;
13
- }
14
-
15
8
  // ../protocol/src/types.ts
16
9
  var CURRENT_VERSION = "2026.1";
17
10
  var SUPPORTED_VERSIONS = ["2026.1"];
18
11
 
19
12
  // src/index.ts
20
13
  function verifySignature(rawBody, signature, timestamp, secret) {
14
+ if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
21
15
  const sigPayload = `${timestamp}.${rawBody}`;
22
16
  const expected = crypto.createHmac("sha256", secret).update(sigPayload).digest("hex");
23
17
  const sigBuffer = Buffer.from(signature, "hex");
@@ -73,7 +67,7 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
73
67
  }
74
68
  salt = saltBytes;
75
69
  } else {
76
- salt = new Uint8Array(0);
70
+ salt = new Uint8Array(32);
77
71
  }
78
72
  const info = new TextEncoder().encode(`oneaddress:${partnerId}`);
79
73
  const aesKeyBits = await crypto.subtle.deriveBits(
@@ -89,9 +83,21 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
89
83
  );
90
84
  return JSON.parse(new TextDecoder().decode(plaintext));
91
85
  }
86
+ 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);
90
+ }
92
91
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
93
92
  const plaintext = await decryptAddress(payload, privateKeyPem, partnerId);
94
93
  const plaintextBytes = new TextEncoder().encode(JSON.stringify(plaintext));
94
+ return reEncryptForRecipient(
95
+ plaintextBytes,
96
+ recipientSpkiPem,
97
+ new TextEncoder().encode(`oneaddress:transform:${partnerId}`)
98
+ );
99
+ }
100
+ async function reEncryptForRecipient(plaintextBytes, recipientSpkiPem, info) {
95
101
  const recipientKey = await crypto.subtle.importKey(
96
102
  "spki",
97
103
  pemToBuffer(recipientSpkiPem),
@@ -111,7 +117,6 @@ async function transformAddress(payload, privateKeyPem, partnerId, recipientSpki
111
117
  );
112
118
  const hkdfSaltBytes = crypto.getRandomValues(new Uint8Array(32));
113
119
  const hkdfKey = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
114
- const info = new TextEncoder().encode(`oneaddress:transform:${partnerId}`);
115
120
  const aesKeyBits = await crypto.subtle.deriveBits(
116
121
  { name: "HKDF", hash: "SHA-256", salt: hkdfSaltBytes, info },
117
122
  hkdfKey,
@@ -132,8 +137,17 @@ async function transformAddress(payload, privateKeyPem, partnerId, recipientSpki
132
137
  hkdfSalt: Buffer.from(hkdfSaltBytes).toString("base64")
133
138
  };
134
139
  }
135
- var OA_APP_BASE_URL = "https://app.oneaddress.io";
136
- var ALLOWED_LOA_HOSTS = /* @__PURE__ */ new Set(["app.oneaddress.io", "localhost", "127.0.0.1"]);
140
+ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, recipientSpkiPem) {
141
+ const sessionData = await decryptSession(share, envelopeB64, privateKeyPem, partnerId);
142
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(sessionData));
143
+ return reEncryptForRecipient(
144
+ plaintextBytes,
145
+ recipientSpkiPem,
146
+ new TextEncoder().encode(`oneaddress:transform-session:${partnerId}`)
147
+ );
148
+ }
149
+ 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"]);
137
151
  async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
138
152
  let parsedBase;
139
153
  try {
@@ -181,6 +195,56 @@ async function verifyLOA(loa, publicKeyPem) {
181
195
  return false;
182
196
  }
183
197
  }
198
+ function canonicalD5LoaForm(loa) {
199
+ return [
200
+ loa.consumer_name,
201
+ loa.authorisation_date,
202
+ loa.scope,
203
+ loa.update_uid,
204
+ loa.oneaddress_acn
205
+ ].join("|");
206
+ }
207
+ function toB64Url(buf) {
208
+ return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
209
+ }
210
+ function d5LoaRef(loa) {
211
+ return toB64Url(crypto.createHash("sha256").update(canonicalD5LoaForm(loa), "utf8").digest());
212
+ }
213
+ async function verifyD5LOA(loa, publicKeyPem) {
214
+ if (loa.signature_algorithm !== "ECDSA-P256") {
215
+ console.warn(
216
+ // NOSONAR — intentional SDK diagnostic, not user-controlled data
217
+ "[OneAddress SDK] D5 LOA algorithm is HMAC-SHA256 (deprecated) \u2014 cannot be verified by partners."
218
+ );
219
+ return false;
220
+ }
221
+ try {
222
+ const key = await crypto.subtle.importKey(
223
+ "spki",
224
+ pemToBuffer(publicKeyPem),
225
+ { name: "ECDSA", namedCurve: "P-256" },
226
+ false,
227
+ ["verify"]
228
+ );
229
+ return await crypto.subtle.verify(
230
+ { name: "ECDSA", hash: "SHA-256" },
231
+ key,
232
+ Buffer.from(loa.oneaddress_signature, "hex"),
233
+ new TextEncoder().encode(canonicalD5LoaForm(loa))
234
+ );
235
+ } catch {
236
+ return false;
237
+ }
238
+ }
239
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
240
+ const data = await decryptSession(
241
+ loaEncrypted.session_key_share,
242
+ loaEncrypted.session_envelope,
243
+ privateKeyPem,
244
+ partnerId
245
+ );
246
+ return data;
247
+ }
184
248
  var ADDRESS_REQUIRED_FIELDS = [
185
249
  "street",
186
250
  "suburb",
@@ -202,17 +266,112 @@ function validateAddress(raw) {
202
266
  }
203
267
  return obj;
204
268
  }
269
+ var STREET_SUFFIX_MAP = {
270
+ st: "street",
271
+ str: "street",
272
+ rd: "road",
273
+ ave: "avenue",
274
+ av: "avenue",
275
+ blvd: "boulevard",
276
+ dr: "drive",
277
+ ct: "court",
278
+ cres: "crescent",
279
+ cr: "crescent",
280
+ pl: "place",
281
+ ln: "lane",
282
+ hwy: "highway",
283
+ pde: "parade",
284
+ pkwy: "parkway",
285
+ ter: "terrace",
286
+ cl: "close"
287
+ };
288
+ function expandSuffixes(line) {
289
+ return line.split(/\s+/).map((tok) => {
290
+ const lower = tok.toLowerCase().replace(/[.,]$/, "");
291
+ return STREET_SUFFIX_MAP[lower] ?? tok.replace(/[.,]$/, "").toLowerCase();
292
+ }).join(" ");
293
+ }
294
+ function normaliseLine(value) {
295
+ if (!value) return "";
296
+ const collapsed = value.toLowerCase().trim().replace(/\s+/g, " ");
297
+ return expandSuffixes(collapsed);
298
+ }
299
+ function normaliseToken(value) {
300
+ return (value ?? "").toLowerCase().trim().replace(/\s+/g, " ");
301
+ }
302
+ function normalisePostcode(value) {
303
+ const trimmed = (value ?? "").trim();
304
+ if (!trimmed) return "";
305
+ if (/^\d{1,4}$/.test(trimmed)) return trimmed.padStart(4, "0");
306
+ return trimmed.toLowerCase();
307
+ }
308
+ function compareAddresses(a, b) {
309
+ const aStreet = normaliseLine(a.street ?? a.address_line1);
310
+ const bStreet = normaliseLine(b.street ?? b.address_line1);
311
+ if (!aStreet || !bStreet || aStreet !== bStreet) return false;
312
+ const aSuburb = normaliseToken(a.suburb);
313
+ const bSuburb = normaliseToken(b.suburb);
314
+ if (!aSuburb || !bSuburb || aSuburb !== bSuburb) return false;
315
+ const aState = normaliseToken(a.state);
316
+ const bState = normaliseToken(b.state);
317
+ if (!aState || !bState || aState !== bState) return false;
318
+ const aPost = normalisePostcode(a.postcode);
319
+ const bPost = normalisePostcode(b.postcode);
320
+ if (!aPost || !bPost || aPost !== bPost) return false;
321
+ const aCountry = normaliseToken(a.country);
322
+ const bCountry = normaliseToken(b.country);
323
+ if (aCountry && bCountry && aCountry !== bCountry) return false;
324
+ return true;
325
+ }
205
326
  function createOneAddressHandler(options) {
206
327
  const {
207
328
  webhookSecret,
208
329
  previousWebhookSecret,
209
330
  webhookSecretGraceUntil,
210
331
  privateKeyPem,
332
+ loaPublicKeyPem,
211
333
  onUpdate,
212
334
  onVerify,
335
+ onAccountVerify,
213
336
  timestampToleranceSecs = 300,
214
337
  idempotencyStore
215
338
  } = options;
339
+ async function buildD5Pieces(body, partnerId) {
340
+ const share = body.session_key_share;
341
+ const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId);
342
+ const address = validateAddress({
343
+ street: data.new_address?.street,
344
+ suburb: data.new_address?.suburb,
345
+ state: data.new_address?.state,
346
+ postcode: data.new_address?.postcode,
347
+ country: data.new_address?.country,
348
+ updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
349
+ });
350
+ const customer = {
351
+ email: "",
352
+ name: data.verified_name ?? "",
353
+ account_number: data.account_number ?? null,
354
+ known_names: Array.isArray(data.known_names) ? data.known_names : []
355
+ };
356
+ let loa;
357
+ let loa_ref;
358
+ if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
359
+ loa = await decryptLoaEncrypted(
360
+ body.loa_encrypted,
361
+ privateKeyPem,
362
+ partnerId
363
+ );
364
+ loa_ref = d5LoaRef(loa);
365
+ if (loaPublicKeyPem) {
366
+ const valid = await verifyD5LOA(loa, loaPublicKeyPem);
367
+ if (!valid) throw new Error("D5 LOA signature verification failed");
368
+ }
369
+ }
370
+ return { address, customer, loa, loa_ref, raw: data };
371
+ }
372
+ function isD5Body(body) {
373
+ return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
374
+ }
216
375
  return async function handler(req) {
217
376
  const rawBody = await req.text();
218
377
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
@@ -267,26 +426,66 @@ function createOneAddressHandler(options) {
267
426
  }
268
427
  try {
269
428
  if (body.event === "address.updated") {
270
- if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
271
- return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
272
- status: 400,
273
- headers: { "Content-Type": "application/json" }
274
- });
429
+ let event;
430
+ if (isD5Body(body)) {
431
+ const d5 = await buildD5Pieces(body, partnerId);
432
+ event = {
433
+ event: "address.updated",
434
+ version: body.oneaddress_version ?? body.version ?? "2.0",
435
+ id: body.id ?? "",
436
+ timestamp: tsNum,
437
+ partner_id: partnerId,
438
+ dispatchId,
439
+ customer: d5.customer,
440
+ address: d5.address,
441
+ loa: d5.loa,
442
+ loa_ref: d5.loa_ref,
443
+ id_verification: body.id_verification,
444
+ raw: d5.raw
445
+ };
446
+ } else {
447
+ if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
448
+ return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
449
+ status: 400,
450
+ headers: { "Content-Type": "application/json" }
451
+ });
452
+ }
453
+ const encrypted = body.address_encrypted;
454
+ const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
455
+ let loa;
456
+ let loa_ref;
457
+ if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
458
+ loa = await decryptLoaEncrypted(
459
+ body.loa_encrypted,
460
+ privateKeyPem,
461
+ partnerId
462
+ );
463
+ loa_ref = d5LoaRef(loa);
464
+ if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
465
+ throw new Error("D5 LOA signature verification failed");
466
+ }
467
+ }
468
+ const customer = {
469
+ email: "",
470
+ name: rawAddress.fullName ?? "",
471
+ account_number: rawAddress.accountReference ?? null,
472
+ known_names: Array.isArray(rawAddress.knownNames) ? rawAddress.knownNames : []
473
+ };
474
+ event = {
475
+ event: "address.updated",
476
+ version: body.oneaddress_version ?? body.version ?? "1",
477
+ id: body.id ?? "",
478
+ timestamp: tsNum,
479
+ partner_id: partnerId,
480
+ dispatchId,
481
+ customer,
482
+ address: validateAddress(rawAddress),
483
+ loa,
484
+ loa_ref,
485
+ id_verification: body.id_verification,
486
+ raw: rawAddress
487
+ };
275
488
  }
276
- const encrypted = body.address_encrypted;
277
- const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
278
- const event = {
279
- event: "address.updated",
280
- version: body.oneaddress_version ?? body.version ?? "1",
281
- id: body.id ?? "",
282
- timestamp: tsNum,
283
- partner_id: partnerId,
284
- dispatchId,
285
- customer: body.customer,
286
- address: validateAddress(rawAddress),
287
- loa: body.loa,
288
- raw: rawAddress
289
- };
290
489
  const result = await onUpdate(event);
291
490
  if (dispatchId && idempotencyStore) {
292
491
  await idempotencyStore.set(dispatchId).catch(
@@ -317,9 +516,11 @@ function createOneAddressHandler(options) {
317
516
  dispatchId,
318
517
  batch_id: body.batch_id ?? 0,
319
518
  user_id: body.user_id ?? "",
320
- customer: body.customer ?? {},
519
+ customer: body.customer,
520
+ customer_match: body.customer_match,
321
521
  address: validateAddress(rawAddress),
322
522
  loa: body.loa,
523
+ id_verification: body.id_verification,
323
524
  raw: rawAddress
324
525
  };
325
526
  const result = await onVerify(event);
@@ -328,6 +529,40 @@ function createOneAddressHandler(options) {
328
529
  headers: { "Content-Type": "application/json" }
329
530
  });
330
531
  }
532
+ if (body.event === "account.verify" && onAccountVerify) {
533
+ let customer;
534
+ if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
535
+ const raw = await decryptAddress(
536
+ body.customer_encrypted,
537
+ privateKeyPem,
538
+ partnerId
539
+ );
540
+ customer = {
541
+ email: raw.email ?? "",
542
+ name: raw.name ?? "",
543
+ account_number: raw.account_number ?? null,
544
+ known_names: Array.isArray(raw.known_names) ? raw.known_names : []
545
+ };
546
+ } else {
547
+ customer = body.customer ?? {};
548
+ }
549
+ const event = {
550
+ event: "account.verify",
551
+ version: body.oneaddress_version ?? body.version ?? "1",
552
+ id: body.id ?? "",
553
+ timestamp: tsNum,
554
+ partner_id: partnerId,
555
+ dispatchId,
556
+ user_id: body.user_id ?? "",
557
+ customer,
558
+ raw: body
559
+ };
560
+ const result = await onAccountVerify(event);
561
+ return new Response(JSON.stringify({ ok: true, ...result }), {
562
+ status: 200,
563
+ headers: { "Content-Type": "application/json" }
564
+ });
565
+ }
331
566
  return new Response(JSON.stringify({ ok: true, skipped: true }), {
332
567
  status: 200,
333
568
  headers: { "Content-Type": "application/json" }
@@ -344,16 +579,21 @@ function createOneAddressHandler(options) {
344
579
  }
345
580
 
346
581
  export {
347
- DEFAULT_REPLAY_WINDOW_SECS,
348
- isFreshTimestamp,
349
582
  CURRENT_VERSION,
350
583
  SUPPORTED_VERSIONS,
351
584
  verifySignature,
352
585
  verifyWithGrace,
353
586
  decryptAddress,
587
+ decryptSession,
354
588
  transformAddress,
589
+ transformSession,
355
590
  fetchLoaPublicKey,
356
591
  verifyLOA,
592
+ canonicalD5LoaForm,
593
+ d5LoaRef,
594
+ verifyD5LOA,
595
+ decryptLoaEncrypted,
357
596
  validateAddress,
597
+ compareAddresses,
358
598
  createOneAddressHandler
359
599
  };
package/dist/edge.d.mts CHANGED
@@ -1,3 +1 @@
1
- export { EncryptedPayload, OneAddressAddress, OneAddressCustomer, OneAddressHandlerOptions, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, createOneAddressHandler, decrypt as decryptAddress, fetchLoaPublicKey, transform as transformAddress, validateAddress, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.mjs';
2
- export { CURRENT_VERSION, SUPPORTED_VERSIONS } from '@oneaddress/protocol';
3
- export { DEFAULT_REPLAY_WINDOW_SECS, isFreshTimestamp } from '@oneaddress/crypto';
1
+ export { BlindIndexField, CURRENT_VERSION, DEFAULT_REPLAY_WINDOW_SECS, EncryptedPayload, OneAddressAddress, OneAddressCustomer, OneAddressCustomerMatch, OneAddressD5LOA, OneAddressHandlerOptions, OneAddressIdVerification, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, SUPPORTED_VERSIONS, SessionData, SessionKeyShare, canonicalD5LoaForm, computeBlindIndex, createOneAddressHandler, d5LoaRef, decrypt as decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, isFreshTimestamp, normalizeForBlindIndex, transform as transformAddress, transformSession, validateAddress, verifyD5LOA, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.mjs';
package/dist/edge.d.ts CHANGED
@@ -1,3 +1 @@
1
- export { EncryptedPayload, OneAddressAddress, OneAddressCustomer, OneAddressHandlerOptions, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, createOneAddressHandler, decrypt as decryptAddress, fetchLoaPublicKey, transform as transformAddress, validateAddress, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.js';
2
- export { CURRENT_VERSION, SUPPORTED_VERSIONS } from '@oneaddress/protocol';
3
- export { DEFAULT_REPLAY_WINDOW_SECS, isFreshTimestamp } from '@oneaddress/crypto';
1
+ export { BlindIndexField, CURRENT_VERSION, DEFAULT_REPLAY_WINDOW_SECS, EncryptedPayload, OneAddressAddress, OneAddressCustomer, OneAddressCustomerMatch, OneAddressD5LOA, OneAddressHandlerOptions, OneAddressIdVerification, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, SUPPORTED_VERSIONS, SessionData, SessionKeyShare, canonicalD5LoaForm, computeBlindIndex, createOneAddressHandler, d5LoaRef, decrypt as decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, isFreshTimestamp, normalizeForBlindIndex, transform as transformAddress, transformSession, validateAddress, verifyD5LOA, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.js';