@oneaddress/partner-sdk 1.1.1 → 1.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.
package/README.md CHANGED
@@ -39,6 +39,58 @@ export { handler as POST };
39
39
 
40
40
  ---
41
41
 
42
+ ## D5 — session-envelope decryption (added in v1.2.0)
43
+
44
+ OneAddress is rolling out a new dispatch architecture (D5 + D1 + D2 in the design doc) where each `address.updated` webhook carries:
45
+
46
+ - A per-partner `session_envelope` — AES-256-GCM ciphertext of the new address, account number, IDV reference, etc., encrypted under a fresh session key SK<sub>n</sub>.
47
+ - A structured `session_key_share` block — ECDH-ES wrap of SK<sub>n</sub> under your specific registered key, identified by a stable `key_id`.
48
+ - A reduced `letter_of_authority` — no address inside, just attestation fields.
49
+ - A cleartext `customer` block — name, email, your account_number, known_names (for record-matching only).
50
+
51
+ Decrypt via `decryptSession`:
52
+
53
+ ```typescript
54
+ import { decryptSession } from '@oneaddress/partner-sdk';
55
+
56
+ const data = await decryptSession(
57
+ body.session_key_share,
58
+ body.session_envelope,
59
+ myPrivateKeyForKeyId, // looked up by share.key_id from your key store
60
+ body.partner_id, // your partner UUID, used in HKDF info binding
61
+ );
62
+
63
+ // data.new_address.street, data.account_number, data.verified_name, etc.
64
+ ```
65
+
66
+ ### Key versioning + retention obligations
67
+
68
+ Under D5 your `partner_keys` registry holds your **active** key plus zero-or-more **retired** keys still within their 90-day retention window. Each envelope you receive tells you (via `session_key_share.key_id`) which retained key OneAddress used to wrap it.
69
+
70
+ **Your contractual obligations:**
71
+
72
+ 1. **Retain** the private key for any `key_id` whose paired public key has a `destroy_after` date in the future. You may destroy the private key on or after `destroy_after` — the corresponding session ciphertext on OneAddress's side has been purged by then.
73
+ 2. **Retain** the `session_key_share` object alongside the update record until `key_share_expiry`. After that date OneAddress will not request reconstruction.
74
+ 3. **Cooperate** in good faith with OneAddress reconstruction requests for in-window envelopes citing a legitimate `reason_code` — by decrypting the relevant share and returning SK<sub>n</sub> over the mutually-authenticated reconstruction channel.
75
+
76
+ See `docs/PARTNER_INTEGRATION.md` for the full integration spec.
77
+
78
+ ### Legacy ECDH still supported
79
+
80
+ The pre-D5 `decryptAddress` helper is unchanged and still works for any webhook carrying the legacy `address_encrypted` field. A webhook will carry **either** the legacy shape **or** the D5 shape — never both. Detect by checking for `session_envelope`:
81
+
82
+ ```typescript
83
+ if (body.session_envelope) {
84
+ const data = await decryptSession(body.session_key_share, body.session_envelope, myKey, body.partner_id);
85
+ } else {
86
+ const data = await decryptAddress(body.address_encrypted, myKey, body.partner_id);
87
+ }
88
+ ```
89
+
90
+ The legacy helper is deprecated and will be removed in v1.3.x after all OneAddress dispatches have migrated to D5.
91
+
92
+ ---
93
+
42
94
  ## Idempotency — handling retries
43
95
 
44
96
  If your handler takes longer than ~10 seconds OneAddress will time out and retry the webhook. Your `onUpdate` can be called more than once for the same address change. Use `event.dispatchId` (from the `X-OneAddress-Dispatch` header) as an idempotency key:
@@ -66,6 +118,40 @@ async onUpdate(event) {
66
118
 
67
119
  ---
68
120
 
121
+ ## Identity verification attestation
122
+
123
+ Every production dispatch carries an `id_verification` block — a server-built attestation that the customer completed identity verification (Global Data DVS + biometric) before the dispatch was authorised:
124
+
125
+ ```typescript
126
+ async onUpdate(event) {
127
+ if (event.id_verification) {
128
+ // Persist the verification_ref alongside your record of the update.
129
+ // It is the immutable handle for the IDV credit consumed by this
130
+ // dispatch — quote it back to OneAddress support to trace an update
131
+ // back to the underlying verification.
132
+ await db.updateAddress({
133
+ email: event.customer.email,
134
+ ...event.address,
135
+ verification_ref: event.id_verification.verification_ref,
136
+ verified_at: event.id_verification.verified_at,
137
+ });
138
+ }
139
+ }
140
+ ```
141
+
142
+ | Field | Description |
143
+ |---|---|
144
+ | `verification_ref` | UUID — immutable handle for the IDV credit. Survives partner key rotations and IDV table rewrites. |
145
+ | `method` | `global_data_idpass` for production, `mock` in sandbox builds. |
146
+ | `verified_at` | ISO-8601 timestamp the verification was completed. |
147
+ | `certificate_id` | Global Data `api_reference` (provider certificate id). May be `null` on legacy rows. |
148
+ | `verified` | Always `true` when the block is present. |
149
+ | `platform` | Format tag — currently `oneaddress/v1`. |
150
+
151
+ The block is absent on `BYPASS_STRIPE` test flows where no IDV credit was consumed. Production dispatches always include it.
152
+
153
+ ---
154
+
69
155
  ## Secret rotation grace window
70
156
 
71
157
  After rotating your webhook secret in the Partner Portal, OneAddress keeps dispatching webhooks signed with the **old** secret for up to 24 hours to cover in-flight requests. Pass both secrets to the handler during the transition:
@@ -129,6 +215,52 @@ export const handler = createOneAddressHandler({
129
215
 
130
216
  ---
131
217
 
218
+ ## Account verification (pre-payment, guest flow)
219
+
220
+ OneAddress runs an optional pre-payment existence check during the guest checkout flow. Implement `onAccountVerify` to participate — partners that don't implement it are silently skipped, the consumer is allowed to continue, and the regular `address.updated` event still arrives after payment.
221
+
222
+ The payload carries **no encrypted address** — just a cleartext customer block — and the consumer is waiting for your response, so reply synchronously within 10 seconds.
223
+
224
+ ```typescript
225
+ export const handler = createOneAddressHandler({
226
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
227
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
228
+
229
+ async onUpdate(event) { /* ... */ },
230
+
231
+ async onAccountVerify(event) {
232
+ // event.customer = { email, name, known_names, account_number }
233
+ const row = await db.findCustomer({
234
+ accountNumber: event.customer.account_number,
235
+ email: event.customer.email,
236
+ });
237
+
238
+ if (!row) return { status: 'no_account' };
239
+
240
+ const nameOk = row.full_name.toLowerCase() === event.customer.name.toLowerCase()
241
+ || event.customer.known_names.some(
242
+ (alias) => row.full_name.toLowerCase() === alias.toLowerCase(),
243
+ );
244
+
245
+ return nameOk ? { status: 'match' } : { status: 'no_match' };
246
+ },
247
+ });
248
+ ```
249
+
250
+ The three statuses surface to the consumer as:
251
+
252
+ | Returned | Consumer sees |
253
+ |----------|--------------|
254
+ | `{ status: 'match' }` | ✓ Account found |
255
+ | `{ status: 'no_match' }` | ⚠ Couldn't verify — check your account number (editable, retriable) |
256
+ | `{ status: 'no_account' }` | ✗ No account found (editable, retriable) |
257
+
258
+ Any other 2xx response — including the default behaviour when you don't supply `onAccountVerify` at all — surfaces as "—" (skipped). The consumer can still pay and dispatch.
259
+
260
+ Failure mode: `no_match` and `no_account` are **informational only**. The consumer is told and may correct their input, but the wizard does not block them from paying. After payment your usual `onUpdate` handler still fires — apply the same matching rules you would for an account-flow update.
261
+
262
+ ---
263
+
132
264
  ## Edge runtime (Cloudflare Workers, Next.js Edge)
133
265
 
134
266
  ```typescript
@@ -1,23 +1,17 @@
1
+ import {
2
+ isFreshTimestamp
3
+ } from "./chunk-TGLIJMGK.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,6 +83,11 @@ 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-NUBMOPDK.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));
@@ -132,8 +131,8 @@ async function transformAddress(payload, privateKeyPem, partnerId, recipientSpki
132
131
  hkdfSalt: Buffer.from(hkdfSaltBytes).toString("base64")
133
132
  };
134
133
  }
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"]);
134
+ var OA_APP_BASE_URL = "https://oneaddress.io";
135
+ var ALLOWED_LOA_HOSTS = /* @__PURE__ */ new Set(["oneaddress.io", "app.oneaddress.io", "localhost", "127.0.0.1"]);
137
136
  async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
138
137
  let parsedBase;
139
138
  try {
@@ -202,6 +201,63 @@ function validateAddress(raw) {
202
201
  }
203
202
  return obj;
204
203
  }
204
+ var STREET_SUFFIX_MAP = {
205
+ st: "street",
206
+ str: "street",
207
+ rd: "road",
208
+ ave: "avenue",
209
+ av: "avenue",
210
+ blvd: "boulevard",
211
+ dr: "drive",
212
+ ct: "court",
213
+ cres: "crescent",
214
+ cr: "crescent",
215
+ pl: "place",
216
+ ln: "lane",
217
+ hwy: "highway",
218
+ pde: "parade",
219
+ pkwy: "parkway",
220
+ ter: "terrace",
221
+ cl: "close"
222
+ };
223
+ function expandSuffixes(line) {
224
+ return line.split(/\s+/).map((tok) => {
225
+ const lower = tok.toLowerCase().replace(/[.,]$/, "");
226
+ return STREET_SUFFIX_MAP[lower] ?? tok.replace(/[.,]$/, "").toLowerCase();
227
+ }).join(" ");
228
+ }
229
+ function normaliseLine(value) {
230
+ if (!value) return "";
231
+ const collapsed = value.toLowerCase().trim().replace(/\s+/g, " ");
232
+ return expandSuffixes(collapsed);
233
+ }
234
+ function normaliseToken(value) {
235
+ return (value ?? "").toLowerCase().trim().replace(/\s+/g, " ");
236
+ }
237
+ function normalisePostcode(value) {
238
+ const trimmed = (value ?? "").trim();
239
+ if (!trimmed) return "";
240
+ if (/^\d{1,4}$/.test(trimmed)) return trimmed.padStart(4, "0");
241
+ return trimmed.toLowerCase();
242
+ }
243
+ function compareAddresses(a, b) {
244
+ const aStreet = normaliseLine(a.street ?? a.address_line1);
245
+ const bStreet = normaliseLine(b.street ?? b.address_line1);
246
+ if (!aStreet || !bStreet || aStreet !== bStreet) return false;
247
+ const aSuburb = normaliseToken(a.suburb);
248
+ const bSuburb = normaliseToken(b.suburb);
249
+ if (!aSuburb || !bSuburb || aSuburb !== bSuburb) return false;
250
+ const aState = normaliseToken(a.state);
251
+ const bState = normaliseToken(b.state);
252
+ if (!aState || !bState || aState !== bState) return false;
253
+ const aPost = normalisePostcode(a.postcode);
254
+ const bPost = normalisePostcode(b.postcode);
255
+ if (!aPost || !bPost || aPost !== bPost) return false;
256
+ const aCountry = normaliseToken(a.country);
257
+ const bCountry = normaliseToken(b.country);
258
+ if (aCountry && bCountry && aCountry !== bCountry) return false;
259
+ return true;
260
+ }
205
261
  function createOneAddressHandler(options) {
206
262
  const {
207
263
  webhookSecret,
@@ -210,6 +266,7 @@ function createOneAddressHandler(options) {
210
266
  privateKeyPem,
211
267
  onUpdate,
212
268
  onVerify,
269
+ onAccountVerify,
213
270
  timestampToleranceSecs = 300,
214
271
  idempotencyStore
215
272
  } = options;
@@ -285,6 +342,7 @@ function createOneAddressHandler(options) {
285
342
  customer: body.customer,
286
343
  address: validateAddress(rawAddress),
287
344
  loa: body.loa,
345
+ id_verification: body.id_verification,
288
346
  raw: rawAddress
289
347
  };
290
348
  const result = await onUpdate(event);
@@ -320,6 +378,7 @@ function createOneAddressHandler(options) {
320
378
  customer: body.customer ?? {},
321
379
  address: validateAddress(rawAddress),
322
380
  loa: body.loa,
381
+ id_verification: body.id_verification,
323
382
  raw: rawAddress
324
383
  };
325
384
  const result = await onVerify(event);
@@ -328,6 +387,24 @@ function createOneAddressHandler(options) {
328
387
  headers: { "Content-Type": "application/json" }
329
388
  });
330
389
  }
390
+ if (body.event === "account.verify" && onAccountVerify) {
391
+ const event = {
392
+ event: "account.verify",
393
+ version: body.oneaddress_version ?? body.version ?? "1",
394
+ id: body.id ?? "",
395
+ timestamp: tsNum,
396
+ partner_id: partnerId,
397
+ dispatchId,
398
+ user_id: body.user_id ?? "",
399
+ customer: body.customer ?? {},
400
+ raw: body
401
+ };
402
+ const result = await onAccountVerify(event);
403
+ return new Response(JSON.stringify({ ok: true, ...result }), {
404
+ status: 200,
405
+ headers: { "Content-Type": "application/json" }
406
+ });
407
+ }
331
408
  return new Response(JSON.stringify({ ok: true, skipped: true }), {
332
409
  status: 200,
333
410
  headers: { "Content-Type": "application/json" }
@@ -344,16 +421,16 @@ function createOneAddressHandler(options) {
344
421
  }
345
422
 
346
423
  export {
347
- DEFAULT_REPLAY_WINDOW_SECS,
348
- isFreshTimestamp,
349
424
  CURRENT_VERSION,
350
425
  SUPPORTED_VERSIONS,
351
426
  verifySignature,
352
427
  verifyWithGrace,
353
428
  decryptAddress,
429
+ decryptSession,
354
430
  transformAddress,
355
431
  fetchLoaPublicKey,
356
432
  verifyLOA,
357
433
  validateAddress,
434
+ compareAddresses,
358
435
  createOneAddressHandler
359
436
  };