@oneaddress/partner-sdk 2.0.0 → 2.1.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/CHANGELOG.md CHANGED
@@ -7,6 +7,141 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.1.0] - 2026-09-20
11
+
12
+ Unpublished as at this entry, and **still unpublished on 25 Sep 2026**, when the
13
+ dispatch-simulator correction below was folded into it rather than given a
14
+ version of its own — a version number is cheap until published and permanent
15
+ after, so work accumulates into the unpublished one.
16
+
17
+ A minor version: every change is additive or tightens a check that was
18
+ documented as already present. Two audits of the SDK on 20 Sep 2026 (one
19
+ security, one partner-usability) produced the original list; a
20
+ dashboard-to-receiver wiring audit on 25 Sep 2026 produced the addition.
21
+
22
+ ### Fixed (25 Sep 2026)
23
+
24
+ - **`buildSignedTestWebhook` sent a payload OneAddress does not send.** The
25
+ helper exists so you can unit-test your handler against "what the relay
26
+ sends", and measured against the relay's own composer it did not: it added
27
+ `version` and `encryption_status` — fields of the superseded
28
+ `address_encrypted` shape that never appear beside a `session_envelope` — it
29
+ always sent the body `id`, which the relay sends only on a key-crossover
30
+ copy, it sent `update_id` as a UUID where the relay sends the integer
31
+ `user_updates.id`, and it omitted `user_id` and `stripe_session_id`
32
+ altogether.
33
+
34
+ **This could make a correct-looking handler fail in production.** A handler
35
+ gated on `encryption_status === 'encrypted'`, pinned to `body.version`, or
36
+ keyed for idempotency on `body.id` went green against this helper and would
37
+ then have dropped — or double-written — every real update. **If your tests
38
+ assert on any of those three fields, they will now fail, and that failure is
39
+ the bug surfacing: production never carried them.** Deduplicate on the
40
+ `X-OneAddress-Dispatch` header, which is on every delivery.
41
+
42
+ The body's `timestamp` is ISO 8601; the `X-OneAddress-Timestamp` *header* is
43
+ Unix-epoch seconds. Both formats are in every dispatch, which is how two
44
+ separate conformance implementations came to put the header's format in the
45
+ body.
46
+
47
+ The field list now comes from an explicit contract that is verified by
48
+ EXECUTING the relay's own composer, so the helper cannot drift from the wire
49
+ again without a test failing.
50
+
51
+ ### Added (25 Sep 2026)
52
+
53
+ - `buildSignedTestWebhook` takes **`userId`** (default `test:consumer`) and
54
+ **`stripeSessionId`** (default `null` — the key is always present on the wire
55
+ even when the value is not). `id` and `crossover_key_ids` remain reachable
56
+ through `extraBody`, which is the circumstance the relay actually sends them
57
+ in. The helper also binds `update_id` to the envelope's `update_uid` as the
58
+ relay does, so a handler can bind a decrypted LOA to the update it arrived
59
+ with.
60
+
61
+ ### Security
62
+
63
+ - **The Letter of Authority must be PRESENT, not merely valid when present.**
64
+ With `loaPublicKeyPem` set, a dispatch that carried no `loa_encrypted` was
65
+ processed with no check at all: "verified" meant "verified if the relay
66
+ chose to include it". Such a dispatch is now refused with a 500, so
67
+ OneAddress retries and records the failure rather than being told a
68
+ delivery succeeded whose consent proof nobody saw. New option `requireLoa`
69
+ (default `true` when `loaPublicKeyPem` is set, `false` otherwise); set it
70
+ `false` to keep processing without a proof, in which case the handler warns
71
+ once per process that consent is unverified.
72
+ - **The LOA is bound to its envelope.** A decrypted LOA whose `update_uid`
73
+ differs from the session envelope's is refused, so a genuine consent for one
74
+ update cannot be replayed beside the envelope of another. Older dispatches
75
+ lacking the field on either side are unaffected.
76
+ - **`fetchLoaPublicKey` requires `https:`** except for `localhost` and
77
+ `127.0.0.1`. The key it fetches is what every consent signature is checked
78
+ against, and `http://oneaddress.io` passed the host allowlist.
79
+ - **`createOutboxConsumer`: `markProcessed`, `markFailed` and `release` now
80
+ match on the claim token this consumer holds as well as `dispatch_id`,** so
81
+ a write that lands after the lease expired and another consumer re-claimed
82
+ the row touches nothing. `maxAttempts` is validated (integer, zero or more)
83
+ before it is inlined into the statement, like `batchSize` already was.
84
+ - **Configuration is refused at construction, by name**: an empty
85
+ `webhookSecret`, a `privateKeyPem` that does not import, a
86
+ `timestampToleranceSecs` outside `(0, 86400]`, an unparseable
87
+ `webhookSecretGraceUntil`. Each used to surface on the first real delivery
88
+ as a 500 that OneAddress then retried for two days.
89
+ - A correctly signed body that is valid JSON but not an object (`null`, a
90
+ number, an array) is answered `400 Invalid JSON` instead of throwing out
91
+ of the handler.
92
+
93
+ ### Added
94
+
95
+ - **`confirm` option on `createOneAddressHandler`** (`{ partnerId,
96
+ confirmSecret, oneAddressApi? }`). When set, the handler calls
97
+ `confirmUpdate` after `onUpdate` returns, with the `status` it returned
98
+ (`confirmed` when omitted) and `event.loa_ref`. Fire-and-forget: a failed
99
+ confirm is logged and never fails the delivery. Exists because `onUpdate`'s
100
+ return value was only ever spread into the 200 body and reached nobody;
101
+ its docstring and the README said otherwise and are corrected.
102
+ - **`buildSignedTestWebhook`**: a correctly signed, correctly encrypted test
103
+ dispatch for your own unit tests, in the exact shape the relay sends,
104
+ lifted from the conformance suite. Optional real LOA signing with a key you
105
+ generate, so `loaPublicKeyPem` can be tested end to end. `HandlerRequest`
106
+ and `HandlerResponse` are exported alongside it.
107
+ - **`createSqlIdempotencyStore` takes `dialect`** (`postgres` | `sqlite` |
108
+ `mysql` | `mssql`). The claim statement was Postgres/SQLite-only
109
+ (`ON CONFLICT ... DO NOTHING RETURNING`) while the README said MySQL and
110
+ SQL Server "just change the placeholder". MySQL and SQL Server now get an
111
+ insert-if-absent under a per-call token; their table needs one extra
112
+ column, `claim_token VARCHAR(64) NULL`. An unknown dialect is refused with
113
+ the supported list.
114
+ - **`expectedAlg` option on `createOneAddressHandler`**, passed through to
115
+ `decryptSession` (and `decryptLoaEncrypted`, which gains the same optional
116
+ parameter) so the algorithm-downgrade pin is reachable from the handler.
117
+ - **A private key stored as one line with literal `\n` sequences is accepted**
118
+ everywhere a PEM is, which is what a secrets manager hands back when the key
119
+ was pasted as a single line.
120
+ - Outside test mode, a dispatch carrying `X-OneAddress-Dispatch` with no
121
+ `idempotencyStore` wired is processed and logged once per process, naming
122
+ `createSqlIdempotencyStore`. The test-mode throw is unchanged. The
123
+ `process.env` read is guarded for the edge build.
124
+
125
+ ### Changed
126
+
127
+ - **`privateKeyPem` on the handler accepts `string | PrivateKeyOperations`,
128
+ and so does `transformSession`.** The 1.8.0 entry below said the handler
129
+ already did; it did not, and `transformSession` was PEM-only. A delegate
130
+ covers the session-envelope paths; the legacy single-blob paths
131
+ (`address_encrypted`, `customer_encrypted`) still need the raw key and say
132
+ so by name.
133
+ - Documentation: `onUpdate`'s return value is stated NOT to reach OneAddress on
134
+ its own; the README's quick start returns `no_match` for an unknown customer
135
+ instead of throwing; all four confirm statuses are listed; a "Delivery
136
+ contract" section states our 10-second timeout, 28 attempts over 48 hours,
137
+ the `ok:false`-in-a-2xx rule and what each response status means to us; an
138
+ identifier table tells `event.id`, `dispatchId`, `update_uid`, `batch_id`
139
+ and `verification_id` apart; the `/edge` section lists what that entry
140
+ actually exports and says Cloudflare Workers need `nodejs_compat`; a
141
+ "Never do" list; `formatAddressParts` and `confirmUpdate`'s `note` no
142
+ longer suggest putting the address in a log or a note; `BYPASS_STRIPE` is
143
+ gone from partner-facing text in favour of "sandbox dispatches".
144
+
10
145
  ## [2.0.0] - 2026-09-16
11
146
 
12
147
  A major version because `OneAddressUpdateEvent.address` is now optional (see
@@ -64,8 +199,10 @@ Runtime behaviour for an integration that declares nothing is unchanged.
64
199
  ### Added
65
200
 
66
201
  - **Delegated private-key operations for a KMS/HSM-held key
67
- (`PrivateKeyOperations`).** `createOneAddressHandler`, `decryptSession` and
68
- `decryptLoaEncrypted` now accept `privateKeyPem: string | PrivateKeyOperations`.
202
+ (`PrivateKeyOperations`).** `decryptSession` and `decryptLoaEncrypted` now
203
+ accept `privateKeyPem: string | PrivateKeyOperations`. (Correction, 2.1.0:
204
+ this entry originally also named `createOneAddressHandler`, whose option
205
+ stayed `string` until 2.1.0 widened it.)
69
206
  A key held in a KMS or HSM is never exported as a PEM by design, so passing a
70
207
  raw key was impossible for those integrators; a `PrivateKeyOperations`
71
208
  delegate performs the private-key step (ECDH-ES derivation / RSA-OAEP unwrap)
package/README.md CHANGED
@@ -52,9 +52,21 @@ export const handler = createOneAddressHandler({
52
52
  const providedNames = [customer.name, ...customer.known_names];
53
53
  const record = await db.findByAccountNumber(customer.account_number);
54
54
  if (!record || !namePoolMatches(providedNames, record.fullName)) {
55
- throw new Error('No matching customer for this dispatch');
55
+ // Not a customer of yours: say so. Throwing here would be reported as
56
+ // YOUR system failing, which OneAddress retries and, after enough of
57
+ // them, refunds the consumer at your expense. See "Confirming back".
58
+ return { status: 'no_match' };
56
59
  }
57
60
  await db.updateAddress({ id: record.id, ...event.address });
61
+ return { status: 'confirmed' };
62
+ },
63
+
64
+ // The return value above reaches OneAddress ONLY because this is set: it
65
+ // makes the handler call confirmUpdate for you after onUpdate returns.
66
+ // Without it the status goes into the HTTP response body and no further.
67
+ confirm: {
68
+ partnerId: process.env.OA_PARTNER_ID!,
69
+ confirmSecret: process.env.OA_CONFIRM_SECRET!,
58
70
  },
59
71
  // Connection-verification test records. OneAddress sends five of these
60
72
  // before you go live: real signed, encrypted dispatches carrying FABRICATED
@@ -172,7 +184,7 @@ What the handler guarantees:
172
184
 
173
185
  ## D5 — session-envelope decryption (added in v1.3.0)
174
186
 
175
- OneAddress is rolling out a new dispatch architecture (D5 + D1 + D2 in the design doc) where each `address.updated` webhook carries:
187
+ A **session envelope** is the address and identity for ONE partner, encrypted under a one-time key that is itself wrapped to that partner's registered public key, so only that partner can open it and OneAddress never can. Each `address.updated` webhook carries:
176
188
 
177
189
  - A per-partner `session_envelope` — AES-256-GCM ciphertext of the new address, account number, IDV reference, verified name, known-names, etc., encrypted under a fresh session key SK<sub>n</sub>.
178
190
  - 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`.
@@ -227,6 +239,18 @@ await confirmUpdate({
227
239
 
228
240
  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).
229
241
 
242
+ ### LOA verification: present AND verified AND bound
243
+
244
+ With `loaPublicKeyPem` set, the handler checks three things on every `address.updated` / `contact.updated`, and refuses the dispatch (500, so OneAddress retries and records the failure) if any fails:
245
+
246
+ 1. **Present.** A dispatch with no `loa_encrypted` at all is refused. Until 2.1.0 it was processed with no check, so "verified" meant "verified if the relay chose to include it". This is `requireLoa`, which defaults to `true` when `loaPublicKeyPem` is set. Set `requireLoa: false` to keep processing without a proof; the handler then warns once per process that consent is unverified.
247
+ 2. **Verified.** The ECDSA P-256 signature over the canonical LOA form checks out against the key you fetched with `fetchLoaPublicKey` (which itself now insists on `https:` except for localhost).
248
+ 3. **Bound.** The LOA's `update_uid` equals the session envelope's. A genuine, correctly signed consent for one update is not consent for another, and without this check a relay holding one real LOA could reuse it. Older dispatches that lack the field on either side are let through: this is a binding, not a requirement.
249
+
250
+ The refusal is a 500 rather than a 200-and-skip on purpose: a 200 would tell OneAddress the delivery succeeded when nobody saw the consent proof.
251
+
252
+ `requireLoa: true` without `loaPublicKeyPem` enforces presence and binding only; verification needs the key.
253
+
230
254
  > **Post-quantum SDK availability.** The X-Wing (`MLKEM768X25519+…`) scheme is supported today in the **TypeScript** (this package) and **Go** SDKs. Python, Java, and C# X-Wing decapsulation is **available on request** — X-Wing is a 2024 draft without a mature drop-in library in those languages yet, so we build it per-SDK on demand (verified against the canonical `session_pq` test vector). Contact OneAddress engineering if you need a Python/Java/C# post-quantum build. ECDH-ES and RSA-OAEP are supported in all five SDKs.
231
255
 
232
256
  ### Key versioning + retention obligations
@@ -338,6 +362,25 @@ naming conventions, verify this assumption holds before relying on it.
338
362
 
339
363
  **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.
340
364
 
365
+ **`onUpdate`'s return value does NOT reach OneAddress on its own.** It is spread into the 200 response body, and OneAddress reads nothing from that body. Until 2.1.0 this README said the return value was "for the confirmation callback"; a receiver that believed it returned `{ status: 'confirmed' }` and left the consumer waiting forever. There are two ways to close the loop:
366
+
367
+ **Either** pass `confirm` to the handler and it calls `confirmUpdate` for you after `onUpdate` returns, with the `status` you returned (`confirmed` when omitted) and `event.loa_ref`. Fire-and-forget: a failed confirm is logged and never fails the delivery. A THROWING `onUpdate` confirms nothing, correctly, because the 500 makes OneAddress retry.
368
+
369
+ ```typescript
370
+ createOneAddressHandler({
371
+ webhookSecret, privateKeyPem,
372
+ confirm: { partnerId: process.env.OA_PARTNER_ID!, confirmSecret: process.env.OA_CONFIRM_SECRET! },
373
+ async onUpdate(event) {
374
+ const record = await db.findByAccountNumber(event.customer?.account_number);
375
+ if (!record) return { status: 'no_match' };
376
+ await db.updateAddress({ id: record.id, ...event.address });
377
+ return { status: 'confirmed' };
378
+ },
379
+ });
380
+ ```
381
+
382
+ **Or** call `confirmUpdate` yourself, from wherever the write actually completes (an outbox worker, a batch job):
383
+
341
384
  ```typescript
342
385
  import { confirmUpdate } from '@oneaddress/partner-sdk';
343
386
 
@@ -346,19 +389,22 @@ const res = await confirmUpdate({
346
389
  secret: process.env.OA_CONFIRM_SECRET!, // see "which secret" below
347
390
  dispatchId: event.dispatchId, // from X-OneAddress-Dispatch
348
391
  status: 'confirmed',
349
- note: 'Address updated in CRM',
392
+ note: 'Applied to CRM record', // never the address itself
350
393
  });
351
394
 
352
395
  if (!res.ok) console.error('[oneaddress] confirm failed', res.status, res.error);
353
396
  ```
354
397
 
355
- ### The three statuses mean different things
398
+ ### The four statuses mean different things
356
399
 
357
400
  | Status | Meaning |
358
401
  | --- | --- |
359
402
  | `confirmed` | You applied the change. |
360
403
  | `already_current` | You already held that address; nothing to write. **Not a failure** — return it honestly rather than reporting `confirmed`. |
361
- | `failed` | You could not apply it. Send a `note` saying why. |
404
+ | `failed` | Your system could not apply it. OneAddress retries, and a run of these makes the update our fault and refunds the consumer. Send a `note` saying why (what happened, never the address). |
405
+ | `no_match` | You looked, and this person is not a customer of yours. Nothing is broken and retrying cannot help, so the consumer is told to check their account reference with you. No refund is triggered. |
406
+
407
+ The last two cost different people money. `failed` for a stranger bills a refund against a receiver that behaved correctly; `no_match` during a real outage tells a genuine customer to fix an account number that was never wrong. **If you cannot tell the two apart, send `failed`**, which is the one that is safe to be wrong about.
362
408
 
363
409
  ### Which secret
364
410
 
@@ -378,9 +424,36 @@ It also refuses a missing or non-numeric `dispatchId` **before** sending, becaus
378
424
 
379
425
  ---
380
426
 
427
+ ## Delivery contract
428
+
429
+ What OneAddress does on its side of the wire, so you can size timeouts, retention and error handling against the real numbers rather than guesses. The figures are read from the dispatcher's own source.
430
+
431
+ | Fact | Value |
432
+ |---|---|
433
+ | Timeout per delivery attempt | **10 seconds**, on our side. Answer inside it; do slow work after the 200 (an outbox is the usual shape). |
434
+ | Retries | Up to **28 attempts over 48 hours**, whichever comes first. Backoff 30s, 2m, 8m, 32m, then every 2 hours. After that the dispatch is marked exhausted and stops; recovering it is a support request. |
435
+ | Duplicates | Retries can overlap with a slow response, so the same `dispatchId` can arrive more than once. **Keep your dedup record for at least 48 hours**, or a late retry re-applies an update you already processed. |
436
+ | `ok: false` in a 2xx body | Counts as a **failure** and is retried. The HTTP status says "received"; a body that says `ok: false` overrides it. The handler never does this by itself. |
437
+ | A redirect | Treated as an error. A 301/302 on a POST drops the body, so a redirecting webhook URL is a misconfiguration. |
438
+
439
+ What each response status means to us:
440
+
441
+ | You answer | We record | We do |
442
+ |---|---|---|
443
+ | `2xx` (and no `ok: false`) | delivered, awaiting your confirm | Wait for `confirmUpdate`. |
444
+ | `400` | auth failed | Retry on the backoff. A malformed request cannot be fixed by retrying, but the class of problem (a stale timestamp, a body that is not JSON) usually clears on the next attempt. |
445
+ | `401` | auth failed, our signature rejected | Retry. A run of these across partners is an alert on OUR side (a broken signing deploy or an unsynced secret). |
446
+ | `422` | auth failed (client-side refusal) | Retry. The handler sends this for a kind you have not declared in `acceptedUpdateTypes`; once you widen the declaration the retry is processed. |
447
+ | `500` | partner error | Retry. This is what the handler answers for a decrypt failure, a missing or invalid consent proof, or a throwing `onUpdate`, and it is the right answer for anything you want retried. |
448
+ | no response / timeout | unreachable | Retry. |
449
+
450
+ Every 4xx is filed under the same "auth failed" state on the consumer's dashboard, so a 4xx you send deliberately reads, to the consumer, as a problem between you and OneAddress. Prefer a 500 for "try again" and a confirm of `no_match` for "not my customer".
451
+
452
+ ---
453
+
381
454
  ## Idempotency — handling retries
382
455
 
383
- 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:
456
+ 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:
384
457
 
385
458
  ```typescript
386
459
  async onUpdate(event) {
@@ -415,6 +488,7 @@ CREATE TABLE oneaddress_dispatches (
415
488
  dispatch_id TEXT PRIMARY KEY,
416
489
  received_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
417
490
  completed_at TIMESTAMP
491
+ -- MySQL and SQL Server only: add claim_token VARCHAR(64) NULL
418
492
  );
419
493
  ```
420
494
 
@@ -426,7 +500,9 @@ export const handler = createOneAddressHandler({
426
500
  privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
427
501
 
428
502
  idempotencyStore: createSqlIdempotencyStore({
429
- // Postgres (node-postgres). For MySQL/SQLite/SQL Server add `placeholder: () => '?'`.
503
+ // Postgres (node-postgres). Pass `dialect: 'mysql' | 'sqlite' | 'mssql'`
504
+ // for the others: the placeholder AND the claim statement differ, since
505
+ // only Postgres and SQLite have `ON CONFLICT ... DO NOTHING RETURNING`.
430
506
  query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
431
507
  }),
432
508
 
@@ -441,6 +517,17 @@ cannot be made correct under concurrency: `has` and `set` are separate round-tri
441
517
  retries arriving at once both observe "not seen" and both apply the update. `claim` is a single
442
518
  atomic `INSERT … ON CONFLICT DO NOTHING` and has no such window.
443
519
 
520
+ **Per dialect.** Postgres and SQLite use that statement as written. MySQL uses `INSERT IGNORE`
521
+ and SQL Server `INSERT ... WHERE NOT EXISTS`, each carrying a per-call token in `claim_token`
522
+ and reading the row back to see whose token landed, which is what makes the claim atomic without
523
+ `RETURNING`. On SQL Server the loser of a genuine race gets a primary-key error rather than an
524
+ empty insert; the handler answers 500, OneAddress retries, and the retry reads the winner's row.
525
+ A dialect the store has no SQL for is refused at construction with the supported list.
526
+
527
+ **Not wiring a store at all.** In test mode (`NODE_ENV=test`) the handler throws on the first
528
+ dispatch that carries `X-OneAddress-Dispatch`, so the omission is caught in development.
529
+ Everywhere else it processes the dispatch and logs once per process, naming this function.
530
+
444
531
  It also distinguishes three states rather than two, and the third is the one that matters:
445
532
 
446
533
  | Claim | Meaning | Handler does |
@@ -511,6 +598,11 @@ running, the row can be claimed twice — and no timeout is long enough to make
511
598
  impossible. Set `leaseSeconds` comfortably longer than your slowest handler, and make the
512
599
  write itself safe to repeat.
513
600
 
601
+ A release is scoped to the claim this consumer holds: `markProcessed`, `markFailed` and
602
+ `release` match on the claim token as well as the id, so a slow consumer's late write after
603
+ its lease expired and another consumer re-claimed the row touches nothing. Until 2.1.0 it
604
+ cleared the other consumer's claim.
605
+
514
606
  ### Failure, and why nothing is given up on by default
515
607
 
516
608
  A handler that throws does not stop the batch: the row records its reason in
@@ -545,9 +637,9 @@ something.
545
637
  | `query` | — | Runs parameterised SQL, returns rows. Your pool, your driver. |
546
638
  | `dialect` | `postgres` | `postgres` \| `mysql` \| `sqlite` \| `mssql` |
547
639
  | `table` | `oneaddress_updates` | What the receiver writes to |
548
- | `batchSize` | `50` | Rows per claim |
640
+ | `batchSize` | `50` | Rows per claim. Positive integer; it is inlined into the statement, so it is validated. |
549
641
  | `leaseSeconds` | `300` | How long a claim is held |
550
- | `maxAttempts` | `0` | `0` = never give up |
642
+ | `maxAttempts` | `0` | `0` = never give up. Integer, zero or more; inlined and validated like `batchSize`. |
551
643
 
552
644
  ---
553
645
 
@@ -575,7 +667,7 @@ async onUpdate(event) {
575
667
  | `verified` | Always `true` when the block is present. |
576
668
  | `platform` | Format tag — currently `oneaddress/v1`. |
577
669
 
578
- The block is absent on `BYPASS_STRIPE` test flows where no IDV credit was consumed. Production dispatches always include it.
670
+ The block is absent on sandbox dispatches, where no identity-verification credit was consumed. Production dispatches always include it.
579
671
 
580
672
  ### The verification reference lives inside the encrypted envelope
581
673
 
@@ -763,6 +855,8 @@ The three statuses surface to the consumer as:
763
855
 
764
856
  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.
765
857
 
858
+ **`onAccountVerify` is never called unless `verifiesAccountReference` is declared on your portal profile**: the relay does not send `account.verify` to a partner that has not said it supports the check, so implementing the callback without ticking the box does nothing.
859
+
766
860
  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.
767
861
 
768
862
  ---
@@ -773,7 +867,13 @@ Failure mode: `no_match` and `no_account` are **informational only**. The consum
773
867
  import { createOneAddressHandler } from '@oneaddress/partner-sdk/edge';
774
868
  ```
775
869
 
776
- All exports are available on the `/edge` path. No Node.js-specific APIs are used.
870
+ The `/edge` entry is a **subset** of the main entry, and it is not free of Node.js APIs. Until 2.1.0 this section said "all exports, no Node.js-specific APIs", and neither half was true.
871
+
872
+ **What `/edge` exports:** `verifySignature`, `verifyWithGrace`, `decryptAddress`, `decryptSession`, `transformAddress`, `transformSession`, `validateAddress`, `verifyLOA`, `fetchLoaPublicKey`, `decryptLoaEncrypted`, `verifyD5LOA`, `d5LoaRef`, `canonicalD5LoaForm`, `createOneAddressHandler`, `isFreshTimestamp`, `DEFAULT_REPLAY_WINDOW_SECS`, `computeBlindIndex`, `normalizeForBlindIndex`, `CURRENT_VERSION`, `SUPPORTED_VERSIONS`, `namePoolMatches`, `findMatchingStoredName`, `isEmailLike`, `compareAddresses`, `sendVerifyResult`, plus the event, option and session types.
873
+
874
+ **Not on `/edge`:** `confirmUpdate`, `createSqlIdempotencyStore`, `createOutboxConsumer`, `toExpressHandler`, `readAddressParts`, `formatAddressParts`, `buildSignedTestWebhook`. Import those from the main entry.
875
+
876
+ **Node APIs.** The handler signs and verifies with `node:crypto` (`createHmac`, `timingSafeEqual`, `createPrivateKey` at construction) and decodes keys with `Buffer`. On **Cloudflare Workers** set `compatibility_flags = ["nodejs_compat"]` in `wrangler.toml`; without it the import fails at deploy. Next.js Edge Runtime and Deno provide these already. `decryptSession`, `decryptAddress` and the LOA verification use Web Crypto and run anywhere.
777
877
 
778
878
  ---
779
879
 
@@ -788,7 +888,7 @@ import {
788
888
  transformAddress, // decrypt legacy blob then re-encrypt to a different public key (e.g. KMS)
789
889
  transformSession, // decrypt D5 session then re-encrypt to a different public key (e.g. KMS)
790
890
  readAddressParts, // tolerant address field reader (street/line1/address_line1/…)
791
- formatAddressParts, // one-line summary of the parts above, for logs + notes
891
+ formatAddressParts, // one-line summary for a screen a person is entitled to see; NOT logs, NOT notes
792
892
  isFreshTimestamp, // ±5-minute replay-window check
793
893
  CURRENT_VERSION, // '2026.1'
794
894
  SUPPORTED_VERSIONS, // ['2026.1']
@@ -810,9 +910,11 @@ await db.updateAddress({
810
910
  suburb: parts.suburb || row.suburb,
811
911
  postcode: parts.postcode || row.postcode,
812
912
  });
813
- console.log(formatAddressParts(parts)); // "42 Collins Street, Melbourne, VIC, 3000"
913
+ reviewScreen.show(formatAddressParts(parts)); // "42 Collins Street, Melbourne, VIC, 3000"
814
914
  ```
815
915
 
916
+ `formatAddressParts` renders the decrypted address in the clear, so it belongs on a screen a person is entitled to see and nowhere else. Not in a log line (a plaintext copy at rest that outlives every retention rule you set for the record) and not in a confirm `note` (sent back to OneAddress). This README used to say "for logs + notes"; the reference receiver did exactly that.
917
+
816
918
  This is a **tolerant reader**, not a schema declaration: it describes what the helper accepts and
817
919
  says nothing about what OneAddress guarantees to send. Use it instead of hand-rolling the
818
920
  `?? ?? ??` ladder — we did that in three receivers and a fix to one silently left the others
@@ -882,6 +984,130 @@ async onUpdate(event) {
882
984
 
883
985
  ---
884
986
 
987
+ ## Never do
988
+
989
+ The address is encrypted to you and to nobody else. Four ways to undo that, each seen in a real integration:
990
+
991
+ - **Never log the plaintext address**, at any level, in any format. A log line is a copy at rest with no retention policy and a wider audience than your database.
992
+ - **Never persist the plaintext address anywhere but the record it belongs to.** Not a debug table, not a queue payload, not a crash dump. `transformSession` exists so an outbox can hold it re-encrypted to your own key.
993
+ - **Never put the address in a confirm `note`.** The note travels back to OneAddress in the clear and is stored there. Say what happened, not what the address was.
994
+ - **Never route a test record to `onUpdate`.** `address.test` and `address.test-dispatch` carry fabricated identities and go to `onTest`; the handler keeps them apart, and so must anything you build beside it.
995
+ - **Never skip the idempotency store in production.** Retries are normal (28 over 48 hours); without a store each one applies the update again. The handler will tell you once, in the log, and then keep going.
996
+
997
+ ---
998
+
999
+ ## Which identifier is which
1000
+
1001
+ Five identifiers arrive with a dispatch and they are easy to confuse. None of them identifies the consumer.
1002
+
1003
+ | Identifier | Where | What it identifies | Use it for |
1004
+ |---|---|---|---|
1005
+ | `event.id` | Body `id` | The webhook event. Shared by every copy of a key-crossover dispatch, so a receiver holding both rotation keys applies it once. Absent on an ordinary dispatch. | Nothing, unless you hold more than one key. |
1006
+ | `event.dispatchId` | Header `X-OneAddress-Dispatch` | This delivery attempt, and its retries. A positive integer as a string; `''` when the header is absent. | **Idempotency**, and the `dispatchId` you pass to `confirmUpdate`. |
1007
+ | `update_uid` | Body `update_id`, and inside the decrypted envelope and LOA | The consumer's update as a whole, across every partner it went to. The handler checks the LOA's copy against the envelope's. | Correlating one update across partners with OneAddress support. |
1008
+ | `batch_id` | Body, `address.verify` only | The verification batch a verify request belongs to. | Echo it in `sendVerifyResult`; the handler does this for you. |
1009
+ | `verification_id` | Body, `address.test` only | The connection-verification run a test record belongs to. | Counting the five test records. |
1010
+
1011
+ `id_verification_ref` (inside the decrypted envelope) is a sixth: the immutable handle of the identity verification that authorised the dispatch, for quoting to OneAddress support. It is not an identifier of the dispatch.
1012
+
1013
+ ---
1014
+
1015
+ ## Generating and registering your key
1016
+
1017
+ The default scheme is ECDH P-256. Generate a pair, register the PUBLIC half, keep the private half in your secret store:
1018
+
1019
+ ```bash
1020
+ openssl ecparam -name prime256v1 -genkey -noout | openssl pkcs8 -topk8 -nocrypt -out oa-private.pem
1021
+ openssl ec -in oa-private.pem -pubout -out oa-public.pem
1022
+ ```
1023
+
1024
+ Register `oa-public.pem` in the Partner Portal under **My Profile, Encryption Key** (the portal can also generate the pair for you and hand you the private key once). The portal shows the key's `key_id`; set it as `keyId` on the handler if you want rotation crossovers skipped cleanly. `oa-private.pem` is what `privateKeyPem` takes, as the file's contents or as one line with literal `\n` sequences. The same page is where an RSA or post-quantum public key is registered instead, and where `verifiesAccountReference` is declared.
1025
+
1026
+ ---
1027
+
1028
+ ## Recipes
1029
+
1030
+ ### Fastify
1031
+
1032
+ Fastify parses JSON by default, which destroys the bytes the signature covers. Register a content-type parser that keeps the raw string for this route:
1033
+
1034
+ ```typescript
1035
+ import Fastify from 'fastify';
1036
+ import { createOneAddressHandler, type HandlerRequest } from '@oneaddress/partner-sdk';
1037
+
1038
+ const app = Fastify();
1039
+ const handler = createOneAddressHandler({ /* ... */ });
1040
+
1041
+ app.addContentTypeParser('application/json', { parseAs: 'string' }, (_req, body, done) => done(null, body));
1042
+
1043
+ app.post('/webhook/oneaddress', async (req, reply) => {
1044
+ const fetchLike: HandlerRequest = {
1045
+ text: async () => req.body as string,
1046
+ headers: { get: (name) => {
1047
+ const v = req.headers[name.toLowerCase()];
1048
+ return v === undefined ? null : Array.isArray(v) ? v.join(', ') : v;
1049
+ } },
1050
+ };
1051
+ const res = await handler(fetchLike);
1052
+ reply.status(res.status);
1053
+ res.headers.forEach((value, key) => reply.header(key, value));
1054
+ return reply.send(await res.text());
1055
+ });
1056
+ ```
1057
+
1058
+ ### AWS Lambda (API Gateway / Function URL)
1059
+
1060
+ API Gateway may base64-encode the body; decode it before it reaches the handler, and never re-serialise it.
1061
+
1062
+ ```typescript
1063
+ import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda';
1064
+ import { createOneAddressHandler } from '@oneaddress/partner-sdk';
1065
+
1066
+ const handler = createOneAddressHandler({ /* ... */ });
1067
+
1068
+ export async function main(apiEvent: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
1069
+ const raw = apiEvent.isBase64Encoded
1070
+ ? Buffer.from(apiEvent.body ?? '', 'base64').toString('utf8')
1071
+ : (apiEvent.body ?? '');
1072
+ const res = await handler({
1073
+ text: async () => raw,
1074
+ headers: { get: (name) => apiEvent.headers[name.toLowerCase()] ?? null },
1075
+ });
1076
+ return { statusCode: res.status, headers: { 'content-type': 'application/json' }, body: await res.text() };
1077
+ }
1078
+ ```
1079
+
1080
+ Do your slow work after the response (an SQS queue, an outbox table) so the 10-second delivery timeout is never in play, and keep the idempotency store in a real database: a Lambda's memory is per instance and per cold start.
1081
+
1082
+ ### Testing your receiver without a network
1083
+
1084
+ ```typescript
1085
+ import { generateKeyPairSync } from 'node:crypto';
1086
+ import { createOneAddressHandler, buildSignedTestWebhook } from '@oneaddress/partner-sdk';
1087
+
1088
+ const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
1089
+ const handler = createOneAddressHandler({
1090
+ webhookSecret: 'test-secret',
1091
+ privateKeyPem: privateKey.export({ type: 'pkcs8', format: 'pem' }) as string,
1092
+ idempotencyStore: memoryStore,
1093
+ async onUpdate(event) { seen.push(event); },
1094
+ });
1095
+
1096
+ const hook = await buildSignedTestWebhook({
1097
+ webhookSecret: 'test-secret',
1098
+ partnerId: '11111111-1111-1111-1111-111111111111',
1099
+ publicKey: publicKey.export({ type: 'spki', format: 'pem' }) as string,
1100
+ session: { account_number: 'ACME-42' },
1101
+ });
1102
+ const res = await handler(hook.request); // or handler(hook.toRequest())
1103
+ expect(res.status).toBe(200);
1104
+ expect(seen[0].customer?.account_number).toBe('ACME-42');
1105
+ ```
1106
+
1107
+ `buildSignedTestWebhook` produces the exact shape the relay sends, signed and encrypted, lifted from the conformance suite. Pass `loa: false` to test `requireLoa`, `loaSigningKeyPem` (an ECDSA P-256 key you generate) to test `loaPublicKeyPem` for real, `session: { update_types: ['phone'] }` for a contact-only envelope, and `extraBody` for `crossover_key_ids` or the test-record `index` / `total`.
1108
+
1109
+ ---
1110
+
885
1111
  ## Protocol versioning
886
1112
 
887
1113
  The SDK warns (but does not reject) if it receives a protocol version it doesn't recognise:
@@ -902,10 +1128,17 @@ This ensures you keep receiving events while updating your SDK. See `SUPPORTED_V
902
1128
  **Full conformance suite** — run 10 checks against your endpoint using real crypto, no mocks:
903
1129
 
904
1130
  ```bash
905
- # Against a live endpoint
906
- npx @oneaddress/conformance test https://your-endpoint.com/webhook --secret whsec_...
907
-
908
- # Against a local server (run from the machine where the server is running)
1131
+ # Against a live endpoint: all three credentials, or none. A partial set is
1132
+ # REFUSED — it passes every signature check while the payload stays sealed to
1133
+ # the suite's built-in test key, so the failures land on the acceptance checks
1134
+ # and read as a decrypt fault in your own code.
1135
+ export ONEADDRESS_WEBHOOK_SECRET=whsec_...
1136
+ export ONEADDRESS_PARTNER_ID=...
1137
+ export ONEADDRESS_PUBLIC_KEY=...
1138
+ npx @oneaddress/conformance test https://your-endpoint.com/webhook
1139
+
1140
+ # Against a local wizard scaffold, which is built around those same test
1141
+ # values: no credentials at all, and the run still proves something.
909
1142
  npx @oneaddress/conformance test http://localhost:3001/webhook
910
1143
  ```
911
1144