@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.
package/README.md CHANGED
@@ -4,6 +4,13 @@ Official Node.js SDK for OneAddress partner webhook integrations.
4
4
 
5
5
  Handles signature verification, replay-window enforcement, ECDH address decryption, and secret-rotation grace windows in a single call.
6
6
 
7
+ > **Not using Node?** You do not need this SDK. The full wire protocol is documented in the
8
+ > [OneAddress partner protocol specification](../../docs/integrations/partner-protocol-spec.md) —
9
+ > headers, signing, replay rules, all three key-unwrap procedures with exact HKDF parameters and
10
+ > byte layouts, both callbacks, and an implementation checklist. It is written so a conforming
11
+ > receiver can be built on any platform with no OneAddress code at all. This SDK is the fast path,
12
+ > not the only path.
13
+
7
14
  ---
8
15
 
9
16
  ## Installation
@@ -17,24 +24,62 @@ npm install @oneaddress/partner-sdk
17
24
  ## Quick start
18
25
 
19
26
  ```typescript
20
- import { createOneAddressHandler } from '@oneaddress/partner-sdk';
27
+ import { createOneAddressHandler, namePoolMatches } from '@oneaddress/partner-sdk';
21
28
 
22
29
  export const handler = createOneAddressHandler({
23
30
  webhookSecret: process.env.OA_WEBHOOK_SECRET!,
24
31
  privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
25
32
 
26
33
  async onUpdate(event) {
27
- // event.address is already decrypted
28
- console.log(`Address updated for ${event.customer.email}:`, event.address);
29
- await db.updateAddress({ email: event.customer.email, ...event.address });
34
+ // event.address is already decrypted. event.customer.email is always ''
35
+ // on this event (OneAddress never learns a consumer's email for a
36
+ // dispatch it isn't sent for) - match on account_number and/or name.
37
+ const providedNames = [event.customer.name, ...event.customer.known_names];
38
+ const record = await db.findByAccountNumber(event.customer.account_number);
39
+ if (!record || !namePoolMatches(providedNames, record.fullName)) {
40
+ throw new Error('No matching customer for this dispatch');
41
+ }
42
+ await db.updateAddress({ id: record.id, ...event.address });
43
+ },
44
+ // Connection-verification test records. OneAddress sends five of these
45
+ // before you go live: real signed, encrypted dispatches carrying FABRICATED
46
+ // identities, which you decrypt and relay back.
47
+ //
48
+ // Deliberately NOT routed through onUpdate - the names and addresses are
49
+ // fictitious, and writing them into real customer records is exactly what a
50
+ // separate event type exists to prevent.
51
+ //
52
+ // Leave it out and address.test is acknowledged with 200, skipped, and
53
+ // logged as skipped. You will not be able to complete connection
54
+ // verification through the SDK.
55
+ async onTest(event) {
56
+ console.log(`test record ${event.index}/${event.total}`,
57
+ event.customer.name, event.address);
30
58
  },
31
59
  });
32
60
 
33
61
  // Next.js App Router
34
62
  export { handler as POST };
35
63
 
36
- // Express (requires express.raw middleware on this route)
37
- // app.post('/webhook/oneaddress', express.raw({ type: 'application/json' }), handler);
64
+ // Express — wrap with toExpressHandler. The handler itself is Fetch-shaped
65
+ // (it reads req.text() and returns a Response), which is what lets the same
66
+ // code run on App Router, Workers, Deno and Bun. Express gives neither, so it
67
+ // needs the adapter — passing `handler` straight in throws
68
+ // "req.text is not a function" on your first delivery.
69
+ //
70
+ // import { createOneAddressHandler, toExpressHandler } from '@oneaddress/partner-sdk';
71
+ //
72
+ // app.post(
73
+ // '/webhook/oneaddress',
74
+ // express.raw({ type: 'application/json' }), // required, see below
75
+ // toExpressHandler(handler),
76
+ // );
77
+ //
78
+ // express.raw on THIS route is not optional and not merely a body-parser
79
+ // preference: the signature is an HMAC over the raw request bytes, so if
80
+ // express.json() has already parsed the body those bytes are gone and no
81
+ // re-serialisation reproduces them. toExpressHandler refuses a parsed body
82
+ // with a named error rather than letting it become a confusing 401.
38
83
  ```
39
84
 
40
85
  ---
@@ -77,16 +122,21 @@ In all schemes the `session_envelope` is identical (AES-256-GCM under SK<sub>n</
77
122
  The signed LOA travels as `loa_encrypted` (same `{ session_envelope, session_key_share }` shape, wrapped to the same `key_id`). Decrypt it, verify the signature, and echo the reference back in your confirm callback:
78
123
 
79
124
  ```typescript
80
- import { decryptLoaEncrypted, verifyD5LOA, d5LoaRef, fetchLoaPublicKey } from '@oneaddress/partner-sdk';
125
+ import {
126
+ decryptLoaEncrypted, verifyD5LOA, d5LoaRef, fetchLoaPublicKey, confirmUpdate,
127
+ } from '@oneaddress/partner-sdk';
81
128
 
82
129
  const loa = await decryptLoaEncrypted(body.loa_encrypted, myPrivateKeyForKeyId, body.partner_id);
83
130
  const loaKey = await fetchLoaPublicKey(); // cache this
84
131
  if (!(await verifyD5LOA(loa, loaKey))) throw new Error('LOA signature invalid');
85
132
 
86
- // Echo the ref in your /api/confirm POST so OneAddress can confirm you decrypted
133
+ // Echo the ref in your confirm callback so OneAddress can confirm you decrypted
87
134
  // a valid signed consent. It carries no name in the clear.
88
- await fetch(confirmUrl, { method: 'POST', /* …auth… */,
89
- body: JSON.stringify({ dispatch_id, partner_id, status: 'confirmed', loa_ref: d5LoaRef(loa) }) });
135
+ await confirmUpdate({
136
+ partnerId, secret: process.env.OA_CONFIRM_SECRET!,
137
+ dispatchId: event.dispatch_id,
138
+ status: 'confirmed', loaRef: d5LoaRef(loa),
139
+ });
90
140
  ```
91
141
 
92
142
  If you use `createOneAddressHandler`, this is done for you: pass `loaPublicKeyPem` and the handler decrypts + verifies + rejects on failure, and exposes `event.loa` (the decrypted LOA) and `event.loa_ref` (echo it in your confirm callback).
@@ -95,7 +145,7 @@ If you use `createOneAddressHandler`, this is done for you: pass `loaPublicKeyPe
95
145
 
96
146
  ### Key versioning + retention obligations
97
147
 
98
- 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.
148
+ Under D5 your `partner_keys` registry holds your **active** key plus zero-or-more **retired** keys still within their retention window (your configured retention period, minimum 14 days; the authoritative horizon for each key is its `destroy_after` date, not a fixed number of days). Each envelope you receive tells you (via `session_key_share.key_id`) which retained key OneAddress used to wrap it.
99
149
 
100
150
  **Your contractual obligations:**
101
151
 
@@ -103,7 +153,7 @@ Under D5 your `partner_keys` registry holds your **active** key plus zero-or-mor
103
153
  2. **Retain** the `session_key_share` object alongside the update record until `key_share_expiry`. After that date OneAddress will not request reconstruction.
104
154
  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.
105
155
 
106
- See `docs/PARTNER_INTEGRATION.md` for the full integration spec.
156
+ See the partner portal documentation at partners.oneaddress.io for the full integration spec.
107
157
 
108
158
  ### Legacy ECDH still supported
109
159
 
@@ -117,64 +167,128 @@ if (body.session_envelope) {
117
167
  }
118
168
  ```
119
169
 
120
- The legacy helper is deprecated and will be removed in v1.3.x after all OneAddress dispatches have migrated to D5.
170
+ The legacy helper is deprecated and will be removed in a future major version once all OneAddress dispatches have migrated to D5 - no removal is scheduled yet.
121
171
 
122
172
  ---
123
173
 
124
174
  ## Blind-index matching (zero-plaintext record matching)
125
175
 
126
- > **Superseded by the "no cleartext" mandate.** OneAddress no longer emits a
127
- > cleartext `customer` block **or** a `customer_match` block on `address.updated`
128
- > dispatches — identity now travels only inside the encrypted `session_envelope`.
129
- > The `computeBlindIndex` / `normalizeForBlindIndex` helpers remain exported for
130
- > partners who still use blind indexes for their own internal matching, but the
131
- > dispatch payload no longer carries `customer_match`. Match on the decrypted
132
- > `verified_name` / `known_names` / `account_number` instead. The section below
133
- > is retained for historical reference.
134
-
135
- By default each webhook carries a cleartext `customer` block (`name` / `email` /
136
- `account_number` / `known_names`) so you can locate your record before
137
- decrypting the address. If you enable **blind-index matching** in the partner
138
- portal, OneAddress sends a `customer_match` block **instead** — each value is
139
- `base64url(HMAC-SHA256(yourBlindIndexSecret, normalize(field)))`. No plaintext
140
- name/email/account crosses the wire, and you can still match **without
141
- decrypting** the envelope.
176
+ > **Superseded by the "no cleartext" mandate: no event type carries
177
+ > `customer_match` any more.** OneAddress emits neither a cleartext `customer`
178
+ > block nor a `customer_match` block on any dispatch or verification webhook:
179
+ > identity travels only inside the encrypted payload (`session_envelope` on
180
+ > `address.updated`; `address_encrypted` on `address.verify`;
181
+ > `customer_encrypted` on `account.verify`). `event.customer_match` is always
182
+ > `undefined`. Match on the decrypted `verified_name` / `known_names` /
183
+ > `account_number` instead; if you use `createOneAddressHandler`,
184
+ > `event.customer` is populated for you after decryption. The section below is
185
+ > retained for partners who adopted blind indexes while the feature was live
186
+ > and still use them for their **own internal** matching columns; nothing in it
187
+ > arrives on the wire.
188
+
189
+ The `computeBlindIndex` / `normalizeForBlindIndex` helpers remain exported.
190
+ Each index is `base64url(HMAC-SHA256(yourBlindIndexSecret, normalize(field)))`,
191
+ and if you keep blind-index columns on your own records the normalisation
192
+ contract below still governs how they must be computed.
193
+
194
+ **Normalisation is part of the contract**: always compute indexes with the
195
+ SDK's `computeBlindIndex` (or `normalizeForBlindIndex`), never by hand:
196
+
197
+ | Field | Normalisation |
198
+ | --- | --- |
199
+ | `email` | NFKC · trim · lowercase |
200
+ | `name` | NFKC · trim · lowercase · collapse internal whitespace |
201
+ | `account_number` | NFKC · trim · remove all whitespace · **case preserved** |
202
+
203
+ (Historical note: while the wire feature was live, `customer_match.names` held
204
+ one index per name (legal name plus each known-name alias) and a record
205
+ matched if any stored name index appeared in it. No event carries that block
206
+ today.)
207
+
208
+ ---
209
+
210
+ ## Name matching (added in v1.4.0)
211
+
212
+ Once you've decrypted the envelope (or resolved a blind-index hit), you still
213
+ need to confirm the customer's name matches your stored record before
214
+ accepting an address change. **Don't write this comparison yourself.** A naive
215
+ approach - substring or prefix matching on whitespace-split tokens - treats an
216
+ email address as just another name token, and an email's local part can
217
+ satisfy that comparison against an unrelated customer's first name. That's a
218
+ real failure mode we found and fixed in our own systems: it lets a stray email
219
+ address stored in a name-shaped field act as a false-positive match.
220
+
221
+ The SDK re-exports the same component-aware matcher OneAddress's own
222
+ reference receivers run:
142
223
 
143
224
  ```typescript
144
- import { computeBlindIndex } from '@oneaddress/partner-sdk';
145
-
146
- // One-time: backfill a blind-index column on your records.
147
- // email_bidx = computeBlindIndex(secret, 'email', record.email)
148
- // Then, on each webhook:
149
- async function onUpdate(event) {
150
- const m = event.customer_match; // present when blind-index is enabled
151
- if (m) {
152
- const emailIdx = await computeBlindIndex(process.env.OA_BLIND_INDEX_SECRET!, 'email', '' /* n/a — you query by index */);
153
- const record =
154
- m.email ? await db.findByEmailBidx(m.email)
155
- : m.account_number ? await db.findByAccountBidx(m.account_number)
156
- : await db.findByAnyNameBidx(m.names); // match if ANY name index hits
157
- // ... then decryptSession(...) to get the new address.
158
- } else {
159
- // Cleartext path (default): match on event.customer.
160
- }
225
+ import { namePoolMatches } from '@oneaddress/partner-sdk';
226
+
227
+ const data = await decryptSession(/* ... */);
228
+ const providedNames = [data.verified_name, ...(data.known_names ?? [])];
229
+
230
+ const record = await db.findAccount(/* by account_number, etc. */);
231
+ if (!namePoolMatches(providedNames, record.name)) {
232
+ // Names don't line up - do not apply the address change.
161
233
  }
162
234
  ```
163
235
 
164
- **The blind-index secret** is generated and shown in the portal (Encryption Key →
165
- Blind-index matching). It is distinct from your webhook/confirm/setup secrets.
236
+ `namePoolMatches(providedNames, storedName)` returns `true` when `storedName`'s
237
+ surname is one of the surnames implied by `providedNames`, and every one of
238
+ `storedName`'s given-name tokens is explained by the pool (an exact token, or a
239
+ single-letter initial matching a pool token). It rejects email-shaped entries
240
+ on **both** sides outright - an email can never satisfy the match, however
241
+ permissive the rest of the pool is. `findMatchingStoredName(providedNames,
242
+ candidates)` does the same over a list of candidate stored names and returns
243
+ the first match, if any.
166
244
 
167
- **Normalisation is part of the contract** — always compute indexes with the
168
- SDK's `computeBlindIndex` (or `normalizeForBlindIndex`), never by hand:
245
+ Note: `namePoolMatches` assumes given-name-then-surname ordering (it treats the
246
+ *last* token as the surname). If your customer base includes surname-first
247
+ naming conventions, verify this assumption holds before relying on it.
169
248
 
170
- | Field | Normalisation |
249
+ ---
250
+
251
+ ## Confirming back — `confirmUpdate`
252
+
253
+ **Receiving a dispatch is only half the protocol.** Until you call back, the consumer's dashboard shows your business stuck on "dispatched" indefinitely — no matter how correctly you applied the change.
254
+
255
+ ```typescript
256
+ import { confirmUpdate } from '@oneaddress/partner-sdk';
257
+
258
+ const res = await confirmUpdate({
259
+ partnerId: process.env.OA_PARTNER_ID!,
260
+ secret: process.env.OA_CONFIRM_SECRET!, // see "which secret" below
261
+ dispatchId: event.dispatch_id, // from X-OneAddress-Dispatch
262
+ status: 'confirmed',
263
+ note: 'Address updated in CRM',
264
+ });
265
+
266
+ if (!res.ok) console.error('[oneaddress] confirm failed', res.status, res.error);
267
+ ```
268
+
269
+ ### The three statuses mean different things
270
+
271
+ | Status | Meaning |
171
272
  | --- | --- |
172
- | `email` | NFKC · trim · lowercase |
173
- | `name` | NFKC · trim · lowercase · collapse internal whitespace |
174
- | `account_number` | NFKC · trim · remove all whitespace · **case preserved** |
273
+ | `confirmed` | You applied the change. |
274
+ | `already_current` | You already held that address; nothing to write. **Not a failure** — return it honestly rather than reporting `confirmed`. |
275
+ | `failed` | You could not apply it. Send a `note` saying why. |
276
+
277
+ ### Which secret
278
+
279
+ If you have minted a **confirm secret** in the Partner Portal, use that one — once it exists it is the only secret `/api/confirm` accepts, so that a leaked webhook secret cannot forge confirmations. If you have not, use your webhook signing secret. The same secret authenticates the request and signs the body.
280
+
281
+ ### Why this helper exists
282
+
283
+ The endpoint requires a Bearer token, a fresh unix-**seconds** timestamp, and an HMAC-SHA256 over `` `${timestamp}.${rawBody}` ``. Hand-rolling that has three failure modes which all surface as an indistinguishable `401`:
284
+
285
+ - **Signing a string and then sending a re-serialised object.** A byte of whitespace or a different key order breaks the signature. `confirmUpdate` serialises once and sends exactly what it signed.
286
+ - **Milliseconds instead of seconds.** That is outside the ±300s replay window by a factor of a thousand, and the error reads "stale or future request", which sounds like an auth problem.
287
+ - **Clock drift on your host.** Same error, same confusion. If confirms fail and nothing else has changed, check your clock.
288
+
289
+ `confirmUpdate` never throws on an HTTP status — it returns `{ ok, status, error }`. **Log that result.** If a confirm fails and nothing inspects it, the update looks applied on your side and the consumer never sees it land: the same silent-success shape as an unhandled event, in the other direction.
175
290
 
176
- `customer_match.names` holds one index per name (legal name + each known-name
177
- alias); match if **any** of your stored name indexes appears in it.
291
+ It also refuses a missing or non-numeric `dispatchId` **before** sending, because `/api/confirm` treats an absent `dispatch_id` as a no-op for the dispatch record — so posting one would return `200` having closed no loop at all.
178
292
 
179
293
  ---
180
294
 
@@ -189,7 +303,7 @@ async onUpdate(event) {
189
303
  if (seen) return; // idempotent no-op
190
304
  }
191
305
 
192
- await db.updateAddress({ email: event.customer.email, ...event.address });
306
+ await db.updateAddress({ accountNumber: event.customer.account_number, ...event.address });
193
307
 
194
308
  if (event.dispatchId) {
195
309
  await db.dispatches.insert({ dispatchId: event.dispatchId });
@@ -203,6 +317,60 @@ async onUpdate(event) {
203
317
  >
204
318
  > **Recommendation:** Make your database write idempotent (e.g. `INSERT … ON CONFLICT DO UPDATE`) rather than relying solely on the dispatchId check. That way a duplicate delivery is harmless even if the ID was never recorded.
205
319
 
320
+ ### Let the handler do it — `createSqlIdempotencyStore`
321
+
322
+ Rather than hand-rolling the above, pass an `idempotencyStore` and the handler manages
323
+ deduplication for you. The SDK ships a SQL-backed implementation that works over whatever driver
324
+ you already use — it takes a `query` function, so the SDK stays dependency-free and you reuse
325
+ your existing pool and credentials:
326
+
327
+ ```sql
328
+ CREATE TABLE oneaddress_dispatches (
329
+ dispatch_id TEXT PRIMARY KEY,
330
+ received_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
331
+ completed_at TIMESTAMP
332
+ );
333
+ ```
334
+
335
+ ```typescript
336
+ import { createOneAddressHandler, createSqlIdempotencyStore } from '@oneaddress/partner-sdk';
337
+
338
+ export const handler = createOneAddressHandler({
339
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
340
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
341
+
342
+ idempotencyStore: createSqlIdempotencyStore({
343
+ // Postgres (node-postgres). For MySQL/SQLite/SQL Server add `placeholder: () => '?'`.
344
+ query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
345
+ }),
346
+
347
+ async onUpdate(event) {
348
+ await db.updateAddress({ accountNumber: event.customer.account_number, ...event.address });
349
+ },
350
+ });
351
+ ```
352
+
353
+ **Why a `claim`, not a `has`/`set` pair.** The older two-method interface still works, but it
354
+ cannot be made correct under concurrency: `has` and `set` are separate round-trips, so two
355
+ retries arriving at once both observe "not seen" and both apply the update. `claim` is a single
356
+ atomic `INSERT … ON CONFLICT DO NOTHING` and has no such window.
357
+
358
+ It also distinguishes three states rather than two, and the third is the one that matters:
359
+
360
+ | Claim | Meaning | Handler does |
361
+ |---|---|---|
362
+ | `fresh` | Never seen | Process it |
363
+ | `retry-after-incomplete` | Seen, but the previous attempt never reported completion | **Process it again** |
364
+ | `duplicate` | Seen and completed | Skip, respond `200 { duplicate: true }` |
365
+
366
+ A store that only knows "seen / not seen" has to guess at the middle row. Guess "duplicate" and
367
+ you lose a paid address update permanently the first time a process dies mid-write — with your
368
+ side and ours both reporting success.
369
+
370
+ > **Do not use an in-memory `Set`** beyond local development. It is per-process (so it does
371
+ > nothing behind a load balancer), unbounded (so it leaks), and lost on restart (so it re-opens
372
+ > the duplicate window on every deploy).
373
+
206
374
  ---
207
375
 
208
376
  ## Identity verification attestation
@@ -298,9 +466,19 @@ if (!ok) return res.status(401).json({ error: 'Invalid signature' });
298
466
 
299
467
  ## Address verification events
300
468
 
301
- Implement `onVerify` to respond to consumer address-match checks:
469
+ `address.verify` asks whether a consumer's **new** address already matches what you
470
+ hold on file. On a **match**, OneAddress marks the service "already in sync" and
471
+ **skips the `address.updated` dispatch** — there is nothing to update. On a
472
+ **mismatch**, the normal `address.updated` event follows after the check.
473
+
474
+ The address travels encrypted as `address_encrypted` (per-partner ECDH, no
475
+ cleartext); `createOneAddressHandler` decrypts it into `event.address` for you.
476
+ Return `{ match }` and the SDK reports the result back to OneAddress for you —
477
+ use the `compareAddresses` helper for a strict baseline comparison:
302
478
 
303
479
  ```typescript
480
+ import { createOneAddressHandler, compareAddresses } from '@oneaddress/partner-sdk';
481
+
304
482
  export const handler = createOneAddressHandler({
305
483
  webhookSecret: process.env.OA_WEBHOOK_SECRET!,
306
484
  privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
@@ -308,21 +486,49 @@ export const handler = createOneAddressHandler({
308
486
  async onUpdate(event) { /* ... */ },
309
487
 
310
488
  async onVerify(event) {
311
- const stored = await db.getAddress({ email: event.customer.email });
312
- const match = stored?.street === event.address.street &&
313
- stored?.postcode === event.address.postcode;
314
- return { match, note: match ? undefined : 'Address does not match our records' };
489
+ const stored = await db.getStoredAddress(event); // look up by your account reference
490
+ if (!stored) return { match: false, note: 'No address on file' };
491
+ return { match: compareAddresses(stored, event.address) };
315
492
  },
316
493
  });
317
494
  ```
318
495
 
496
+ **How the loop closes.** Unlike `account.verify` (which OneAddress reads from your
497
+ synchronous HTTP response), `address.verify` results are ingested from a **callback**
498
+ the SDK POSTs to the webhook's `callback_url` (`/api/verify-result`), carrying
499
+ `{ batch_id, partner_id, result, address_match, token }`. `createOneAddressHandler`
500
+ sends this **automatically** whenever you provide `onVerify`. Simply returning from
501
+ the handler without this callback would leave the verify batch to time out.
502
+
503
+ If you handle `address.verify` **without** the SDK handler, call `sendVerifyResult`
504
+ yourself after verifying the HMAC signature and decrypting the address:
505
+
506
+ ```typescript
507
+ import { sendVerifyResult, compareAddresses, decryptAddress } from '@oneaddress/partner-sdk';
508
+
509
+ const address = await decryptAddress(body.address_encrypted, privateKeyPem, partnerId);
510
+ const match = compareAddresses(await db.getStoredAddress(body), address);
511
+
512
+ await sendVerifyResult({
513
+ callbackUrl: body.callback_url,
514
+ callbackToken: body.callback_token,
515
+ batchId: body.batch_id,
516
+ partnerId,
517
+ match,
518
+ });
519
+ ```
520
+
521
+ `sendVerifyResult` maps `match: true → result 'match' + address_match true`
522
+ (OneAddress skips the dispatch) and `match: false → 'mismatch' + address_match false`
523
+ (the update proceeds). It throws if the callback POST returns a non-2xx status.
524
+
319
525
  ---
320
526
 
321
527
  ## Account verification (pre-payment, guest flow)
322
528
 
323
529
  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.
324
530
 
325
- 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.
531
+ The payload carries **no address** — only the customer identity block (name / known-names / account number), and it travels **encrypted** as `customer_encrypted` (per-partner ECDH, same scheme as the address payload), never in cleartext. `createOneAddressHandler` decrypts it for you and populates `event.customer`. The consumer is waiting for your response, so reply synchronously within 10 seconds.
326
532
 
327
533
  ```typescript
328
534
  export const handler = createOneAddressHandler({
@@ -340,10 +546,9 @@ export const handler = createOneAddressHandler({
340
546
 
341
547
  if (!row) return { status: 'no_account' };
342
548
 
343
- const nameOk = row.full_name.toLowerCase() === event.customer.name.toLowerCase()
344
- || event.customer.known_names.some(
345
- (alias) => row.full_name.toLowerCase() === alias.toLowerCase(),
346
- );
549
+ // Use namePoolMatches, not a naive string comparison - see "Name matching" above.
550
+ const providedNames = [event.customer.name, ...event.customer.known_names];
551
+ const nameOk = namePoolMatches(providedNames, row.full_name);
347
552
 
348
553
  return nameOk ? { status: 'match' } : { status: 'no_match' };
349
554
  },
@@ -384,12 +589,37 @@ import {
384
589
  decryptSession, // D5 session-envelope decryption
385
590
  transformAddress, // decrypt legacy blob then re-encrypt to a different public key (e.g. KMS)
386
591
  transformSession, // decrypt D5 session then re-encrypt to a different public key (e.g. KMS)
592
+ readAddressParts, // tolerant address field reader (street/line1/address_line1/…)
593
+ formatAddressParts, // one-line summary of the parts above, for logs + notes
387
594
  isFreshTimestamp, // ±5-minute replay-window check
388
595
  CURRENT_VERSION, // '2026.1'
389
596
  SUPPORTED_VERSIONS, // ['2026.1']
390
597
  } from '@oneaddress/partner-sdk';
391
598
  ```
392
599
 
600
+ ### `readAddressParts(raw)` / `formatAddressParts(parts)`
601
+
602
+ Pulls `line1` / `suburb` / `state` / `postcode` / `country` out of a decrypted address regardless
603
+ of which field-name spelling it carries — `street`, `address_line1`, `streetAddress`; `city`,
604
+ `locality`, `town`; `region`, `province`; `postalCode`, `postal_code`, `zip`. Missing parts come
605
+ back as `''` (`country` defaults to `'AU'`), so you can `||` straight into a fallback:
606
+
607
+ ```typescript
608
+ const parts = readAddressParts(data.new_address);
609
+ await db.updateAddress({
610
+ id: row.id,
611
+ line1: parts.line1 || row.line1,
612
+ suburb: parts.suburb || row.suburb,
613
+ postcode: parts.postcode || row.postcode,
614
+ });
615
+ console.log(formatAddressParts(parts)); // "42 Collins Street, Melbourne, VIC, 3000"
616
+ ```
617
+
618
+ This is a **tolerant reader**, not a schema declaration: it describes what the helper accepts and
619
+ says nothing about what OneAddress guarantees to send. Use it instead of hand-rolling the
620
+ `?? ?? ??` ladder — we did that in three receivers and a fix to one silently left the others
621
+ behind.
622
+
393
623
  ### `verifySignature(rawBody, signature, timestamp, secret)`
394
624
 
395
625
  Returns `true` if the HMAC-SHA256 signature is valid. Signing formula: `HMAC-SHA256("${timestamp}.${rawBody}")`.
@@ -417,7 +647,7 @@ async onUpdate(event) {
417
647
  event.partner_id,
418
648
  process.env.KMS_PUBLIC_KEY_SPKI_PEM!, // your KMS/HSM SPKI PEM public key
419
649
  );
420
- await db.storeEncryptedAddress(event.customer.email, kmsBlob);
650
+ await db.storeEncryptedAddress(event.customer.account_number, kmsBlob);
421
651
  }
422
652
  ```
423
653
 
@@ -444,7 +674,9 @@ async onUpdate(event) {
444
674
  body.partner_id,
445
675
  process.env.KMS_PUBLIC_KEY_SPKI_PEM!, // your KMS/HSM SPKI PEM public key
446
676
  );
447
- await db.storeEncryptedAddress(body.customer.email, kmsBlob);
677
+ // Use event.customer (decrypted by the handler), not body.customer - under
678
+ // D5 the raw webhook body carries no cleartext customer block at all.
679
+ await db.storeEncryptedAddress(event.customer.account_number, kmsBlob);
448
680
  }
449
681
  ```
450
682