@oneaddress/partner-sdk 1.6.2 → 1.7.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,85 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.7.0] - 2026-08-21
11
+
12
+ ### Added
13
+
14
+ - **`createOutboxConsumer` — draining the outbox, correctly, on all four
15
+ dialects.** The receiver writes each delivered update to a table and stamps
16
+ `written_at`; `processed_at` is the partner's to stamp. Until now the SDK
17
+ gave no help crossing that gap, so every integrator wrote their own polling
18
+ loop and rediscovered the same problems.
19
+
20
+ The one worth naming: `SELECT … WHERE processed_at IS NULL` is correct with
21
+ one consumer and quietly wrong with two. Both read the same rows, both apply
22
+ the same address, and whichever finishes second overwrites the first — which
23
+ on a CRM that fires side effects on write is visible to the customer. There
24
+ is no error, and it appears on the day a second replica is added.
25
+
26
+ Claiming atomically is dialect territory, and that is what this removes:
27
+ `FOR UPDATE SKIP LOCKED` on postgres, `UPDLOCK, READPAST` on SQL Server, an
28
+ `ORDER BY … LIMIT` plus a read-back token on MySQL (which cannot reference
29
+ the target table in a subquery, error 1093, and has no `RETURNING`), and a
30
+ plain subquery on SQLite, which has one writer and nothing to skip.
31
+
32
+ A claim is a **lease**, not a lock: it expires after `leaseSeconds` so a
33
+ consumer that dies strands nothing. Your handler must therefore be
34
+ idempotent — no timeout is long enough to make a double-claim impossible.
35
+
36
+ `maxAttempts` defaults to `0`, meaning never give up. Giving up on a row is
37
+ an address that never reaches the partner's system, which is worse than a
38
+ loop they can see; the cap is opt-in once `backlog().stuck` is alerted on.
39
+
40
+ Also exported: `toOutboxTimestamp` / `fromOutboxTimestamp`, because binding
41
+ and reading a timestamp are both dialect traps. A MySQL `DATETIME` rejects an
42
+ ISO-8601 string outright in strict mode, and `Date.parse` on a zone-less
43
+ value applies the LOCAL zone per ECMA-262 — which skews a backlog age by the
44
+ deployment's whole UTC offset, and to the west of Greenwich makes it negative
45
+ so a threshold alert can never fire at all.
46
+
47
+ ## [1.6.3] - 2026-08-21
48
+
49
+ ### Fixed
50
+
51
+ - **A CommonJS TypeScript project could not resolve the types at all.** Found
52
+ by scaffolding `npx @oneaddress/setup`'s own `ts-node` template and running
53
+ `tsc` on what it produced:
54
+
55
+ ```
56
+ src/server.ts(32,8): error TS1479: The current file is a CommonJS module
57
+ whose imports will produce 'require' calls; however, the referenced file is
58
+ an ECMAScript module and cannot be imported with 'require'.
59
+ ```
60
+
61
+ The cause was the SHAPE of the exports map, not a missing file. `types` sat
62
+ at the top of the `"."` condition pointing at `index.d.mts`, so a `require`
63
+ consumer matched the runtime on `index.js` (correct, CommonJS) and the types
64
+ on `index.d.mts` (ESM). **`dist/index.d.ts` was being built and published the
65
+ whole time and was simply unreachable.** Conditions now nest, with `types`
66
+ inside `import` and `require`, one declaration file per format.
67
+
68
+ Runtime was never affected: `require('@oneaddress/partner-sdk')` returned all
69
+ 34 exports before this change and returns them after. Only type resolution
70
+ was broken, which is why it survived — and our own setup wizard emits a
71
+ CommonJS project, so the scaffolded happy path produced the one configuration
72
+ that fails.
73
+
74
+ Note TS1479's own suggested remedies make it worse here. "Use a dynamic
75
+ `import()`" and "add `type: module`" are advice for a package that is
76
+ genuinely ESM-only, and this one is dual-format.
77
+
78
+ **This is the second time the published declarations have been unusable to
79
+ TypeScript partners while every runtime path worked** (the first was
80
+ `TS2307` on unresolved workspace re-exports, 27 Jul 2026). Both were
81
+ invisible from inside the monorepo, where every test imports from source and
82
+ both apps are ESM. `src/dist-exports.test.ts` now compiles a real CommonJS
83
+ consumer and a real ESM consumer against the built artifacts, rather than
84
+ asserting on the shape of the JSON — the resolution rules connecting an
85
+ exports map to "a partner can type-check" are precisely the part that was got
86
+ wrong. Mutation-checked: restoring the old map reproduces TS1479 on the
87
+ CommonJS case and leaves the ESM case green.
88
+
10
89
  ## [1.6.2] - 2026-08-21
11
90
 
12
91
  ### Fixed
package/README.md CHANGED
@@ -5,7 +5,8 @@ Official Node.js SDK for OneAddress partner webhook integrations.
5
5
  Handles signature verification, replay-window enforcement, ECDH address decryption, and secret-rotation grace windows in a single call.
6
6
 
7
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) —
8
+ > [OneAddress partner protocol specification](https://partners.oneaddress.io), in the Docs tab of
9
+ > the partner portal once you have signed up —
9
10
  > headers, signing, replay rules, all three key-unwrap procedures with exact HKDF parameters and
10
11
  > byte layouts, both callbacks, and an implementation checklist. It is written so a conforming
11
12
  > receiver can be built on any platform with no OneAddress code at all. This SDK is the fast path,
@@ -382,6 +383,98 @@ side and ours both reporting success.
382
383
 
383
384
  ---
384
385
 
386
+ ## Draining the outbox — `createOutboxConsumer`
387
+
388
+ If you run the drop-in receiver, every delivered update lands in a table and is stamped
389
+ `written_at`. The receiver never stamps `processed_at` — that column is yours, and the gap
390
+ between the two is what makes the backlog metric mean anything.
391
+
392
+ `createOutboxConsumer` crosses that gap for you, correctly, on all four databases the
393
+ receiver supports.
394
+
395
+ ```typescript
396
+ import { createOutboxConsumer } from '@oneaddress/partner-sdk';
397
+
398
+ const outbox = createOutboxConsumer({
399
+ query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
400
+ dialect: 'postgres',
401
+ });
402
+
403
+ await outbox.ensureSchema(); // once, on boot — adds its lease columns
404
+
405
+ setInterval(async () => {
406
+ await outbox.process(async (row) => {
407
+ await crm.applyAddress(row.fields); // your work
408
+ }); // marked processed, or failed and retried
409
+ }, 5_000);
410
+ ```
411
+
412
+ ### Why not just `SELECT … WHERE processed_at IS NULL`
413
+
414
+ Because that is correct with one consumer and quietly wrong with two. Both read the same
415
+ rows, both apply the same address, and whichever finishes second overwrites the first. On a
416
+ CRM that fires side effects on write — a confirmation email, an audit entry, a downstream
417
+ sync — the duplicate is visible to your customer.
418
+
419
+ Claiming atomically is dialect-specific, and that is the part this saves you:
420
+
421
+ | Database | How a batch is claimed |
422
+ |------------|------------------------|
423
+ | PostgreSQL | `FOR UPDATE SKIP LOCKED` in a subquery, `RETURNING *` — one statement |
424
+ | SQL Server | `UPDATE TOP (n) … WITH (UPDLOCK, READPAST, ROWLOCK) … OUTPUT INSERTED.*` |
425
+ | MySQL | `UPDATE … ORDER BY … LIMIT`, then read back by claim token — MySQL cannot reference the target table in a subquery (error 1093) and has no `RETURNING` |
426
+ | SQLite | Subquery without a lock hint — one writer, so there is nothing to skip |
427
+
428
+ ### A claim is a lease, not a lock
429
+
430
+ A consumer that dies mid-batch must not strand its rows. A claim expires after
431
+ `leaseSeconds` (default 300) and the row becomes claimable again.
432
+
433
+ **Your handler must therefore be idempotent.** If a lease expires while the handler is still
434
+ running, the row can be claimed twice — and no timeout is long enough to make that
435
+ impossible. Set `leaseSeconds` comfortably longer than your slowest handler, and make the
436
+ write itself safe to repeat.
437
+
438
+ ### Failure, and why nothing is given up on by default
439
+
440
+ A handler that throws does not stop the batch: the row records its reason in
441
+ `processing_error`, counts an attempt, releases its claim and is retried on the next pass.
442
+ The rest of the claimed batch still runs.
443
+
444
+ `maxAttempts` defaults to `0`, meaning **never stop trying**, and that default is deliberate.
445
+ Giving up on a row is an address that never reaches your system, which is worse than a loop
446
+ you can see. Set a cap only once you are alerting on `backlog().stuck`.
447
+
448
+ ### The numbers to watch
449
+
450
+ ```typescript
451
+ const { pending, oldestPendingAgeSeconds, stuck } = await outbox.backlog();
452
+ ```
453
+
454
+ `oldestPendingAgeSeconds` is the one to alert on. A rising value means the receiver is
455
+ healthy and your consuming job is not — a state that is otherwise silent on both sides until
456
+ someone asks why an address never appeared.
457
+
458
+ ### Columns it adds
459
+
460
+ `ensureSchema()` adds `oa_claimed_at`, `oa_claim_token` and `oa_attempts` if they are absent,
461
+ and is safe to call on every boot. They carry the `oa_` prefix because this consumer is also
462
+ useful over a table you wrote yourself, where a bare `claimed_at` might already mean
463
+ something.
464
+
465
+ ### Options
466
+
467
+ | Option | Default | |
468
+ |---|---|---|
469
+ | `query` | — | Runs parameterised SQL, returns rows. Your pool, your driver. |
470
+ | `dialect` | `postgres` | `postgres` \| `mysql` \| `sqlite` \| `mssql` |
471
+ | `table` | `oneaddress_updates` | What the receiver writes to |
472
+ | `batchSize` | `50` | Rows per claim |
473
+ | `leaseSeconds` | `300` | How long a claim is held |
474
+ | `maxAttempts` | `0` | `0` = never give up |
475
+
476
+ ---
477
+
385
478
  ## Identity verification attestation
386
479
 
387
480
  Every production dispatch carries a **cleartext** `id_verification` block — a server-built attestation that the customer completed identity verification (Global Data DVS + biometric) before the dispatch was authorised. Under the zero-knowledge dispatch rules this outer block carries **no customer identity** — only the fact and format of the verification:
@@ -434,7 +527,9 @@ await db.updateAddress({
434
527
 
435
528
  ## Secret rotation grace window
436
529
 
437
- 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:
530
+ **Rotate with an overlap.** Staging a new secret in the Partner Portal does **not** change what we sign with: we keep using your current secret until you press *Switch over*. So the safe sequence is stage, deploy the new secret alongside the current one, verify with both, then switch. At every point the secret we sign with is one your receiver already holds.
531
+
532
+ Pass both to the handler for the whole overlap, and for 24 hours after switching — the old secret stays valid for the callbacks you send us during that window:
438
533
 
439
534
  ```typescript
440
535
  export const handler = createOneAddressHandler({
@@ -52,6 +52,206 @@ function findMatchingStoredName(providedNames, storedCandidates) {
52
52
  return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
53
53
  }
54
54
 
55
+ // src/outbox.ts
56
+ import { randomBytes } from "crypto";
57
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
58
+ var CLAIMED_AT = "oa_claimed_at";
59
+ var CLAIM_TOKEN = "oa_claim_token";
60
+ var ATTEMPTS = "oa_attempts";
61
+ var OUTBOX_LEASE_COLUMNS = [CLAIMED_AT, CLAIM_TOKEN, ATTEMPTS];
62
+ var SPECS = {
63
+ postgres: {
64
+ ph: (n) => `$${n}`,
65
+ timestamp: "TIMESTAMPTZ",
66
+ text: "TEXT",
67
+ int: "INTEGER",
68
+ // Scoped to the schema this connection actually resolves the bare table
69
+ // name in. Without that, a same-named table on another search-path schema
70
+ // returns a superset and a genuinely missing column looks present.
71
+ existingColumns: (t) => ({
72
+ sql: "SELECT column_name FROM information_schema.columns WHERE table_name = $1 AND table_schema = current_schema()",
73
+ params: [t]
74
+ }),
75
+ addColumn: (t, c, type) => `ALTER TABLE ${t} ADD COLUMN ${c} ${type} NULL`
76
+ },
77
+ mysql: {
78
+ ph: () => "?",
79
+ timestamp: "DATETIME",
80
+ text: "TEXT",
81
+ int: "INTEGER",
82
+ existingColumns: (t) => ({
83
+ sql: "SELECT column_name FROM information_schema.columns WHERE table_name = ? AND table_schema = DATABASE()",
84
+ params: [t]
85
+ }),
86
+ addColumn: (t, c, type) => `ALTER TABLE ${t} ADD COLUMN ${c} ${type} NULL`
87
+ },
88
+ sqlite: {
89
+ ph: () => "?",
90
+ timestamp: "TEXT",
91
+ text: "TEXT",
92
+ int: "INTEGER",
93
+ existingColumns: (t) => ({ sql: `PRAGMA table_info(${t})`, params: [] }),
94
+ addColumn: (t, c, type) => `ALTER TABLE ${t} ADD COLUMN ${c} ${type} NULL`
95
+ },
96
+ mssql: {
97
+ ph: (n) => `@p${n}`,
98
+ timestamp: "DATETIMEOFFSET",
99
+ text: "NVARCHAR(MAX)",
100
+ int: "INT",
101
+ existingColumns: (t) => ({
102
+ sql: "SELECT column_name FROM information_schema.columns WHERE table_name = @p1",
103
+ params: [t]
104
+ }),
105
+ addColumn: (t, c, type) => `ALTER TABLE ${t} ADD ${c} ${type} NULL`
106
+ }
107
+ };
108
+ function toOutboxTimestamp(dialect, when) {
109
+ const iso = new Date(when).toISOString();
110
+ return dialect === "mysql" ? iso.slice(0, 19).replace("T", " ") : iso;
111
+ }
112
+ function fromOutboxTimestamp(raw) {
113
+ if (raw instanceof Date) return raw.getTime();
114
+ if (typeof raw === "number") return raw;
115
+ if (typeof raw !== "string") return null;
116
+ const s = raw.trim();
117
+ if (s === "") return null;
118
+ const zoned = /(?:[Zz]|[+-]\d{2}:?\d{2})$/.test(s);
119
+ const parsed = Date.parse(zoned ? s : `${s.replace(" ", "T")}Z`);
120
+ return Number.isNaN(parsed) ? null : parsed;
121
+ }
122
+ function createOutboxConsumer(opts) {
123
+ const dialect = opts.dialect ?? "postgres";
124
+ const table = opts.table ?? "oneaddress_updates";
125
+ const leaseSeconds = opts.leaseSeconds ?? 300;
126
+ const maxAttempts = opts.maxAttempts ?? 0;
127
+ const now = opts.now ?? Date.now;
128
+ const d = SPECS[dialect];
129
+ if (!d) throw new Error(`[OneAddress SDK] unknown dialect: ${dialect}`);
130
+ if (!IDENTIFIER.test(table)) throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
131
+ const batchSize = Math.floor(opts.batchSize ?? 50);
132
+ if (!Number.isFinite(batchSize) || batchSize < 1) {
133
+ throw new Error(`[OneAddress SDK] batchSize must be a positive integer, got ${opts.batchSize}`);
134
+ }
135
+ const ph = d.ph;
136
+ const token = () => randomBytes(16).toString("hex");
137
+ const stamp = (at) => toOutboxTimestamp(dialect, at);
138
+ const claimable = (cutoffPh) => `written_at IS NOT NULL AND processed_at IS NULL AND (${CLAIMED_AT} IS NULL OR ${CLAIMED_AT} < ${cutoffPh})` + (maxAttempts > 0 ? ` AND (${ATTEMPTS} IS NULL OR ${ATTEMPTS} < ${maxAttempts})` : "");
139
+ const toRow = (r) => ({
140
+ dispatchId: String(r.dispatch_id ?? r.dispatchId ?? ""),
141
+ event: String(r.event ?? ""),
142
+ attempts: Number(r[ATTEMPTS] ?? 0) || 0,
143
+ fields: r
144
+ });
145
+ async function claimBatch() {
146
+ const at = now();
147
+ const claimedAt = stamp(at);
148
+ const cutoff = stamp(at - leaseSeconds * 1e3);
149
+ const tok = token();
150
+ if (dialect === "postgres") {
151
+ const rows2 = await opts.query(
152
+ `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize} FOR UPDATE SKIP LOCKED) RETURNING *`,
153
+ [claimedAt, tok, cutoff]
154
+ );
155
+ return rows2.map(toRow);
156
+ }
157
+ if (dialect === "mssql") {
158
+ const rows2 = await opts.query(
159
+ `UPDATE TOP (${batchSize}) ${table} WITH (UPDLOCK, READPAST, ROWLOCK) SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} OUTPUT INSERTED.* WHERE ${claimable(ph(3))}`,
160
+ [claimedAt, tok, cutoff]
161
+ );
162
+ return rows2.map(toRow);
163
+ }
164
+ const claim = dialect === "mysql" ? `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize}` : `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize})`;
165
+ await opts.query(claim, [claimedAt, tok, cutoff]);
166
+ const rows = await opts.query(
167
+ `SELECT * FROM ${table} WHERE ${CLAIM_TOKEN} = ${ph(1)} AND processed_at IS NULL`,
168
+ [tok]
169
+ );
170
+ return rows.map(toRow);
171
+ }
172
+ return {
173
+ async ensureSchema() {
174
+ const wanted = [
175
+ [CLAIMED_AT, d.timestamp],
176
+ [CLAIM_TOKEN, d.text],
177
+ [ATTEMPTS, d.int]
178
+ ];
179
+ const q = d.existingColumns(table);
180
+ const rows = await opts.query(q.sql, q.params);
181
+ const have = new Set(
182
+ rows.map((r) => r.column_name ?? r.COLUMN_NAME ?? r.name).filter((v) => typeof v === "string").map((v) => v.toLowerCase())
183
+ );
184
+ if (have.size === 0) {
185
+ throw new Error(
186
+ `[OneAddress SDK] table ${table} has no visible columns. Is the receiver pointed at this database, and can this connection see the table?`
187
+ );
188
+ }
189
+ const added = [];
190
+ for (const [col, type] of wanted) {
191
+ if (have.has(col)) continue;
192
+ await opts.query(d.addColumn(table, col, type), []);
193
+ added.push(col);
194
+ }
195
+ return { added };
196
+ },
197
+ claimBatch,
198
+ async markProcessed(dispatchId) {
199
+ await opts.query(
200
+ `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
201
+ [stamp(now()), dispatchId]
202
+ );
203
+ },
204
+ async markFailed(dispatchId, error) {
205
+ const message = error instanceof Error ? error.message : String(error);
206
+ await opts.query(
207
+ `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
208
+ [message.slice(0, 500), dispatchId]
209
+ );
210
+ },
211
+ async release(dispatchId) {
212
+ await opts.query(
213
+ `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(1)}`,
214
+ [dispatchId]
215
+ );
216
+ },
217
+ async process(handler) {
218
+ const rows = await claimBatch();
219
+ let processed = 0;
220
+ let failed = 0;
221
+ for (const row of rows) {
222
+ try {
223
+ await handler(row);
224
+ await this.markProcessed(row.dispatchId);
225
+ processed++;
226
+ } catch (err) {
227
+ await this.markFailed(row.dispatchId, err);
228
+ failed++;
229
+ }
230
+ }
231
+ return { processed, failed };
232
+ },
233
+ async backlog() {
234
+ const rows = await opts.query(
235
+ `SELECT received_at, ${ATTEMPTS} FROM ${table} WHERE written_at IS NOT NULL AND processed_at IS NULL`,
236
+ []
237
+ );
238
+ let oldest = null;
239
+ let stuck = 0;
240
+ const at = now();
241
+ for (const r of rows) {
242
+ const t = fromOutboxTimestamp(r.received_at ?? r.receivedAt);
243
+ if (t !== null && (oldest === null || t < oldest)) oldest = t;
244
+ if (maxAttempts > 0 && (Number(r[ATTEMPTS] ?? 0) || 0) >= maxAttempts) stuck++;
245
+ }
246
+ return {
247
+ pending: rows.length,
248
+ oldestPendingAgeSeconds: oldest === null ? null : Math.max(0, Math.round((at - oldest) / 1e3)),
249
+ stuck
250
+ };
251
+ }
252
+ };
253
+ }
254
+
55
255
  // src/index.ts
56
256
  function createSqlIdempotencyStore(opts) {
57
257
  const table = opts.table ?? "oneaddress_dispatches";
@@ -903,6 +1103,10 @@ export {
903
1103
  isEmailLike,
904
1104
  namePoolMatches,
905
1105
  findMatchingStoredName,
1106
+ OUTBOX_LEASE_COLUMNS,
1107
+ toOutboxTimestamp,
1108
+ fromOutboxTimestamp,
1109
+ createOutboxConsumer,
906
1110
  createSqlIdempotencyStore,
907
1111
  verifySignature,
908
1112
  verifyWithGrace,
package/dist/edge.js CHANGED
@@ -4296,6 +4296,9 @@ function findMatchingStoredName(providedNames, storedCandidates) {
4296
4296
  return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
4297
4297
  }
4298
4298
 
4299
+ // src/outbox.ts
4300
+ var import_node_crypto = require("crypto");
4301
+
4299
4302
  // src/index.ts
4300
4303
  function verifySignature(rawBody, signature, timestamp, secret) {
4301
4304
  if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
package/dist/edge.mjs CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  verifyLOA,
21
21
  verifySignature,
22
22
  verifyWithGrace
23
- } from "./chunk-3VG6MTRH.mjs";
23
+ } from "./chunk-MNVGYXWH.mjs";
24
24
  import {
25
25
  DEFAULT_REPLAY_WINDOW_SECS,
26
26
  computeBlindIndex,
package/dist/index.d.mts CHANGED
@@ -89,6 +89,142 @@ declare const CURRENT_VERSION: "2026.1";
89
89
  /** All protocol versions this build of the SDK recognises. */
90
90
  declare const SUPPORTED_VERSIONS: readonly ["2026.1"];
91
91
 
92
+ /**
93
+ * Draining the outbox.
94
+ *
95
+ * The receiver writes each delivered update into a table and stamps
96
+ * `written_at`. It never stamps `processed_at` — that column belongs to you,
97
+ * and the gap between the two is what makes the backlog metric mean anything.
98
+ * Until now the SDK gave you no help crossing that gap, so every integrator
99
+ * wrote their own polling loop and rediscovered the same three problems.
100
+ *
101
+ * ── WHY THIS IS NOT A `SELECT ... WHERE processed_at IS NULL` ────────────────
102
+ *
103
+ * That query is correct with exactly one consumer and quietly wrong with two.
104
+ * Both read the same rows, both apply the same address, and whichever finishes
105
+ * second overwrites the first. On a CRM that fires side effects on write — a
106
+ * confirmation email, an audit entry, a downstream sync — the duplicate is
107
+ * visible to the customer.
108
+ *
109
+ * So a claim has to be atomic against other consumers, which is dialect
110
+ * territory: `FOR UPDATE SKIP LOCKED` on postgres, `READPAST` on SQL Server,
111
+ * a lock-and-reread on MySQL (whose UPDATE cannot reference its own table in a
112
+ * subquery, and has no RETURNING). Getting that right is the work, and it is
113
+ * the part an integrator should not have to do twice.
114
+ *
115
+ * ── A CLAIM IS A LEASE, NOT A LOCK ──────────────────────────────────────────
116
+ *
117
+ * A consumer that dies mid-batch must not strand its rows forever. So a claim
118
+ * writes `oa_claimed_at` and expires: once `leaseSeconds` have passed the row
119
+ * is claimable again. That is why the handler must be idempotent — a lease that
120
+ * expires while the handler is still running means the row can be claimed
121
+ * twice, and no timeout is long enough to make that impossible.
122
+ *
123
+ * ── THE COLUMNS ARE OURS AND ARE PREFIXED ───────────────────────────────────
124
+ *
125
+ * `oa_claimed_at`, `oa_claim_token` and `oa_attempts` are added by
126
+ * {@link OutboxConsumer.ensureSchema}. They carry the `oa_` prefix because this
127
+ * consumer is also useful over a table you wrote yourself, where a bare
128
+ * `claimed_at` could already mean something.
129
+ */
130
+ /** The databases the receiver supports, and therefore the ones this drains. */
131
+ type OutboxDialect = 'postgres' | 'mysql' | 'sqlite' | 'mssql';
132
+ /** Run parameterised SQL and return the result rows. Your pool, your driver. */
133
+ type OutboxQueryFn = (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
134
+ interface OutboxRow {
135
+ dispatchId: string;
136
+ event: string;
137
+ /** Every column the row carries, as the driver returned it. */
138
+ fields: Record<string, unknown>;
139
+ /** How many times a handler has already failed on this row. */
140
+ attempts: number;
141
+ }
142
+ interface OutboxBacklog {
143
+ /** Written, not yet processed. The number to graph. */
144
+ pending: number;
145
+ /** Age of the oldest unprocessed row. The number to alert on. */
146
+ oldestPendingAgeSeconds: number | null;
147
+ /** Rows parked because they hit `maxAttempts`. Zero unless you set it. */
148
+ stuck: number;
149
+ }
150
+ /** The lease columns, in the order `ensureSchema` adds them. */
151
+ declare const OUTBOX_LEASE_COLUMNS: readonly ["oa_claimed_at", "oa_claim_token", "oa_attempts"];
152
+ /**
153
+ * Bind a timestamp in the form the column will accept.
154
+ *
155
+ * An ISO-8601 string is the obvious thing and it is wrong on MySQL: a
156
+ * `DATETIME` rejects `2026-08-01T19:13:40.590Z` outright in strict mode,
157
+ * because it wants `YYYY-MM-DD HH:MM:SS` with a space and no zone. Everything
158
+ * is normalised to UTC first — a zone-less column carries no offset, so the
159
+ * only way two processes agree on what a stored value means is to agree that
160
+ * it is always UTC.
161
+ *
162
+ * This is deliberately identical to the receiver's own `toDbTimestamp`, and a
163
+ * guard in this repo fails if the two ever disagree. They cannot be one module:
164
+ * the receiver is not published and this package is.
165
+ */
166
+ declare function toOutboxTimestamp(dialect: OutboxDialect, when: Date | number): string;
167
+ /**
168
+ * Read a timestamp back, and the reason this is not `Date.parse`.
169
+ *
170
+ * The binder above agrees that a zone-less column is always UTC. `Date.parse`
171
+ * does not hold up the other half of that agreement: ECMA-262 mandates that a
172
+ * date-time form with NO offset is read as LOCAL time. So a row stamped in UTC
173
+ * and read on a UTC+8 host comes back eight hours in the past, which skews the
174
+ * oldest-pending age by the deployment's whole offset — inflating it east of
175
+ * Greenwich (the alert screams and gets muted) and making it negative to the
176
+ * west (the alert can never fire, and a stuck outbox looks permanently
177
+ * healthy). CI never catches it, because CI runs UTC and the skew is exactly
178
+ * zero there.
179
+ */
180
+ declare function fromOutboxTimestamp(raw: unknown): number | null;
181
+ interface OutboxConsumerOptions {
182
+ query: OutboxQueryFn;
183
+ /** Defaults to `postgres`, matching the rest of this SDK. */
184
+ dialect?: OutboxDialect;
185
+ /** Defaults to `oneaddress_updates`, which is what the receiver writes. */
186
+ table?: string;
187
+ /** Rows per claim. Defaults to 50. */
188
+ batchSize?: number;
189
+ /**
190
+ * How long a claim is held before another consumer may take the row.
191
+ * Defaults to 300 (five minutes). Set it comfortably longer than your
192
+ * slowest handler: an expired lease means the row gets processed twice.
193
+ */
194
+ leaseSeconds?: number;
195
+ /**
196
+ * Stop claiming a row after this many failed handler runs. Defaults to `0`,
197
+ * meaning never stop, and that default is deliberate — giving up on a row is
198
+ * an address that never reaches your system, which is worse than a loop you
199
+ * can see. Set it only once you are alerting on `backlog().stuck`.
200
+ */
201
+ maxAttempts?: number;
202
+ /** Injectable clock, for tests. */
203
+ now?: () => number;
204
+ }
205
+ interface OutboxConsumer {
206
+ /** Add the lease columns if they are absent. Safe to call on every boot. */
207
+ ensureSchema(): Promise<{
208
+ added: string[];
209
+ }>;
210
+ /** Atomically take up to `batchSize` rows. Other consumers skip them. */
211
+ claimBatch(): Promise<OutboxRow[]>;
212
+ /** Done. Stamps `processed_at` and releases the claim. */
213
+ markProcessed(dispatchId: string): Promise<void>;
214
+ /** Failed. Records the reason, counts the attempt, releases for a retry. */
215
+ markFailed(dispatchId: string, error: unknown): Promise<void>;
216
+ /** Put a row back untouched — for a clean shutdown mid-batch. */
217
+ release(dispatchId: string): Promise<void>;
218
+ /** Claim a batch, run `handler` per row, and mark each one. */
219
+ process(handler: (row: OutboxRow) => Promise<void> | void): Promise<{
220
+ processed: number;
221
+ failed: number;
222
+ }>;
223
+ /** The numbers to graph and alert on. */
224
+ backlog(): Promise<OutboxBacklog>;
225
+ }
226
+ declare function createOutboxConsumer(opts: OutboxConsumerOptions): OutboxConsumer;
227
+
92
228
  /**
93
229
  * @oneaddress/partner-sdk
94
230
  *
@@ -545,6 +681,7 @@ interface IdempotencyStore {
545
681
  */
546
682
  complete?(dispatchId: string): Promise<void>;
547
683
  }
684
+
548
685
  /**
549
686
  * A SQL-backed {@link IdempotencyStore} with an atomic claim, over whatever
550
687
  * driver you already use.
@@ -1308,4 +1445,4 @@ interface ExpressLikeResponse {
1308
1445
  */
1309
1446
  declare function toExpressHandler(handler: (req: HandlerRequest) => Promise<HandlerResponse>): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
1310
1447
 
1311
- export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
1448
+ export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, OUTBOX_LEASE_COLUMNS, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, type OutboxBacklog, type OutboxConsumer, type OutboxConsumerOptions, type OutboxDialect, type OutboxQueryFn, type OutboxRow, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
package/dist/index.d.ts CHANGED
@@ -89,6 +89,142 @@ declare const CURRENT_VERSION: "2026.1";
89
89
  /** All protocol versions this build of the SDK recognises. */
90
90
  declare const SUPPORTED_VERSIONS: readonly ["2026.1"];
91
91
 
92
+ /**
93
+ * Draining the outbox.
94
+ *
95
+ * The receiver writes each delivered update into a table and stamps
96
+ * `written_at`. It never stamps `processed_at` — that column belongs to you,
97
+ * and the gap between the two is what makes the backlog metric mean anything.
98
+ * Until now the SDK gave you no help crossing that gap, so every integrator
99
+ * wrote their own polling loop and rediscovered the same three problems.
100
+ *
101
+ * ── WHY THIS IS NOT A `SELECT ... WHERE processed_at IS NULL` ────────────────
102
+ *
103
+ * That query is correct with exactly one consumer and quietly wrong with two.
104
+ * Both read the same rows, both apply the same address, and whichever finishes
105
+ * second overwrites the first. On a CRM that fires side effects on write — a
106
+ * confirmation email, an audit entry, a downstream sync — the duplicate is
107
+ * visible to the customer.
108
+ *
109
+ * So a claim has to be atomic against other consumers, which is dialect
110
+ * territory: `FOR UPDATE SKIP LOCKED` on postgres, `READPAST` on SQL Server,
111
+ * a lock-and-reread on MySQL (whose UPDATE cannot reference its own table in a
112
+ * subquery, and has no RETURNING). Getting that right is the work, and it is
113
+ * the part an integrator should not have to do twice.
114
+ *
115
+ * ── A CLAIM IS A LEASE, NOT A LOCK ──────────────────────────────────────────
116
+ *
117
+ * A consumer that dies mid-batch must not strand its rows forever. So a claim
118
+ * writes `oa_claimed_at` and expires: once `leaseSeconds` have passed the row
119
+ * is claimable again. That is why the handler must be idempotent — a lease that
120
+ * expires while the handler is still running means the row can be claimed
121
+ * twice, and no timeout is long enough to make that impossible.
122
+ *
123
+ * ── THE COLUMNS ARE OURS AND ARE PREFIXED ───────────────────────────────────
124
+ *
125
+ * `oa_claimed_at`, `oa_claim_token` and `oa_attempts` are added by
126
+ * {@link OutboxConsumer.ensureSchema}. They carry the `oa_` prefix because this
127
+ * consumer is also useful over a table you wrote yourself, where a bare
128
+ * `claimed_at` could already mean something.
129
+ */
130
+ /** The databases the receiver supports, and therefore the ones this drains. */
131
+ type OutboxDialect = 'postgres' | 'mysql' | 'sqlite' | 'mssql';
132
+ /** Run parameterised SQL and return the result rows. Your pool, your driver. */
133
+ type OutboxQueryFn = (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
134
+ interface OutboxRow {
135
+ dispatchId: string;
136
+ event: string;
137
+ /** Every column the row carries, as the driver returned it. */
138
+ fields: Record<string, unknown>;
139
+ /** How many times a handler has already failed on this row. */
140
+ attempts: number;
141
+ }
142
+ interface OutboxBacklog {
143
+ /** Written, not yet processed. The number to graph. */
144
+ pending: number;
145
+ /** Age of the oldest unprocessed row. The number to alert on. */
146
+ oldestPendingAgeSeconds: number | null;
147
+ /** Rows parked because they hit `maxAttempts`. Zero unless you set it. */
148
+ stuck: number;
149
+ }
150
+ /** The lease columns, in the order `ensureSchema` adds them. */
151
+ declare const OUTBOX_LEASE_COLUMNS: readonly ["oa_claimed_at", "oa_claim_token", "oa_attempts"];
152
+ /**
153
+ * Bind a timestamp in the form the column will accept.
154
+ *
155
+ * An ISO-8601 string is the obvious thing and it is wrong on MySQL: a
156
+ * `DATETIME` rejects `2026-08-01T19:13:40.590Z` outright in strict mode,
157
+ * because it wants `YYYY-MM-DD HH:MM:SS` with a space and no zone. Everything
158
+ * is normalised to UTC first — a zone-less column carries no offset, so the
159
+ * only way two processes agree on what a stored value means is to agree that
160
+ * it is always UTC.
161
+ *
162
+ * This is deliberately identical to the receiver's own `toDbTimestamp`, and a
163
+ * guard in this repo fails if the two ever disagree. They cannot be one module:
164
+ * the receiver is not published and this package is.
165
+ */
166
+ declare function toOutboxTimestamp(dialect: OutboxDialect, when: Date | number): string;
167
+ /**
168
+ * Read a timestamp back, and the reason this is not `Date.parse`.
169
+ *
170
+ * The binder above agrees that a zone-less column is always UTC. `Date.parse`
171
+ * does not hold up the other half of that agreement: ECMA-262 mandates that a
172
+ * date-time form with NO offset is read as LOCAL time. So a row stamped in UTC
173
+ * and read on a UTC+8 host comes back eight hours in the past, which skews the
174
+ * oldest-pending age by the deployment's whole offset — inflating it east of
175
+ * Greenwich (the alert screams and gets muted) and making it negative to the
176
+ * west (the alert can never fire, and a stuck outbox looks permanently
177
+ * healthy). CI never catches it, because CI runs UTC and the skew is exactly
178
+ * zero there.
179
+ */
180
+ declare function fromOutboxTimestamp(raw: unknown): number | null;
181
+ interface OutboxConsumerOptions {
182
+ query: OutboxQueryFn;
183
+ /** Defaults to `postgres`, matching the rest of this SDK. */
184
+ dialect?: OutboxDialect;
185
+ /** Defaults to `oneaddress_updates`, which is what the receiver writes. */
186
+ table?: string;
187
+ /** Rows per claim. Defaults to 50. */
188
+ batchSize?: number;
189
+ /**
190
+ * How long a claim is held before another consumer may take the row.
191
+ * Defaults to 300 (five minutes). Set it comfortably longer than your
192
+ * slowest handler: an expired lease means the row gets processed twice.
193
+ */
194
+ leaseSeconds?: number;
195
+ /**
196
+ * Stop claiming a row after this many failed handler runs. Defaults to `0`,
197
+ * meaning never stop, and that default is deliberate — giving up on a row is
198
+ * an address that never reaches your system, which is worse than a loop you
199
+ * can see. Set it only once you are alerting on `backlog().stuck`.
200
+ */
201
+ maxAttempts?: number;
202
+ /** Injectable clock, for tests. */
203
+ now?: () => number;
204
+ }
205
+ interface OutboxConsumer {
206
+ /** Add the lease columns if they are absent. Safe to call on every boot. */
207
+ ensureSchema(): Promise<{
208
+ added: string[];
209
+ }>;
210
+ /** Atomically take up to `batchSize` rows. Other consumers skip them. */
211
+ claimBatch(): Promise<OutboxRow[]>;
212
+ /** Done. Stamps `processed_at` and releases the claim. */
213
+ markProcessed(dispatchId: string): Promise<void>;
214
+ /** Failed. Records the reason, counts the attempt, releases for a retry. */
215
+ markFailed(dispatchId: string, error: unknown): Promise<void>;
216
+ /** Put a row back untouched — for a clean shutdown mid-batch. */
217
+ release(dispatchId: string): Promise<void>;
218
+ /** Claim a batch, run `handler` per row, and mark each one. */
219
+ process(handler: (row: OutboxRow) => Promise<void> | void): Promise<{
220
+ processed: number;
221
+ failed: number;
222
+ }>;
223
+ /** The numbers to graph and alert on. */
224
+ backlog(): Promise<OutboxBacklog>;
225
+ }
226
+ declare function createOutboxConsumer(opts: OutboxConsumerOptions): OutboxConsumer;
227
+
92
228
  /**
93
229
  * @oneaddress/partner-sdk
94
230
  *
@@ -545,6 +681,7 @@ interface IdempotencyStore {
545
681
  */
546
682
  complete?(dispatchId: string): Promise<void>;
547
683
  }
684
+
548
685
  /**
549
686
  * A SQL-backed {@link IdempotencyStore} with an atomic claim, over whatever
550
687
  * driver you already use.
@@ -1308,4 +1445,4 @@ interface ExpressLikeResponse {
1308
1445
  */
1309
1446
  declare function toExpressHandler(handler: (req: HandlerRequest) => Promise<HandlerResponse>): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
1310
1447
 
1311
- export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
1448
+ export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, OUTBOX_LEASE_COLUMNS, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, type OutboxBacklog, type OutboxConsumer, type OutboxConsumerOptions, type OutboxDialect, type OutboxQueryFn, type OutboxRow, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
package/dist/index.js CHANGED
@@ -4216,12 +4216,14 @@ var index_exports = {};
4216
4216
  __export(index_exports, {
4217
4217
  CURRENT_VERSION: () => CURRENT_VERSION,
4218
4218
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
4219
+ OUTBOX_LEASE_COLUMNS: () => OUTBOX_LEASE_COLUMNS,
4219
4220
  SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
4220
4221
  canonicalD5LoaForm: () => canonicalD5LoaForm,
4221
4222
  compareAddresses: () => compareAddresses,
4222
4223
  computeBlindIndex: () => computeBlindIndex,
4223
4224
  confirmUpdate: () => confirmUpdate,
4224
4225
  createOneAddressHandler: () => createOneAddressHandler,
4226
+ createOutboxConsumer: () => createOutboxConsumer,
4225
4227
  createSqlIdempotencyStore: () => createSqlIdempotencyStore,
4226
4228
  d5LoaRef: () => d5LoaRef,
4227
4229
  decrypt: () => decryptAddress2,
@@ -4231,6 +4233,7 @@ __export(index_exports, {
4231
4233
  fetchLoaPublicKey: () => fetchLoaPublicKey,
4232
4234
  findMatchingStoredName: () => findMatchingStoredName,
4233
4235
  formatAddressParts: () => formatAddressParts,
4236
+ fromOutboxTimestamp: () => fromOutboxTimestamp,
4234
4237
  isEmailLike: () => isEmailLike2,
4235
4238
  isFreshTimestamp: () => isFreshTimestamp,
4236
4239
  namePoolMatches: () => namePoolMatches,
@@ -4238,6 +4241,7 @@ __export(index_exports, {
4238
4241
  readAddressParts: () => readAddressParts,
4239
4242
  sendVerifyResult: () => sendVerifyResult,
4240
4243
  toExpressHandler: () => toExpressHandler,
4244
+ toOutboxTimestamp: () => toOutboxTimestamp,
4241
4245
  transform: () => transformAddress,
4242
4246
  transformAddress: () => transformAddress,
4243
4247
  transformSession: () => transformSession,
@@ -4303,6 +4307,206 @@ function findMatchingStoredName(providedNames, storedCandidates) {
4303
4307
  return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
4304
4308
  }
4305
4309
 
4310
+ // src/outbox.ts
4311
+ var import_node_crypto = require("crypto");
4312
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
4313
+ var CLAIMED_AT = "oa_claimed_at";
4314
+ var CLAIM_TOKEN = "oa_claim_token";
4315
+ var ATTEMPTS = "oa_attempts";
4316
+ var OUTBOX_LEASE_COLUMNS = [CLAIMED_AT, CLAIM_TOKEN, ATTEMPTS];
4317
+ var SPECS = {
4318
+ postgres: {
4319
+ ph: (n) => `$${n}`,
4320
+ timestamp: "TIMESTAMPTZ",
4321
+ text: "TEXT",
4322
+ int: "INTEGER",
4323
+ // Scoped to the schema this connection actually resolves the bare table
4324
+ // name in. Without that, a same-named table on another search-path schema
4325
+ // returns a superset and a genuinely missing column looks present.
4326
+ existingColumns: (t) => ({
4327
+ sql: "SELECT column_name FROM information_schema.columns WHERE table_name = $1 AND table_schema = current_schema()",
4328
+ params: [t]
4329
+ }),
4330
+ addColumn: (t, c, type) => `ALTER TABLE ${t} ADD COLUMN ${c} ${type} NULL`
4331
+ },
4332
+ mysql: {
4333
+ ph: () => "?",
4334
+ timestamp: "DATETIME",
4335
+ text: "TEXT",
4336
+ int: "INTEGER",
4337
+ existingColumns: (t) => ({
4338
+ sql: "SELECT column_name FROM information_schema.columns WHERE table_name = ? AND table_schema = DATABASE()",
4339
+ params: [t]
4340
+ }),
4341
+ addColumn: (t, c, type) => `ALTER TABLE ${t} ADD COLUMN ${c} ${type} NULL`
4342
+ },
4343
+ sqlite: {
4344
+ ph: () => "?",
4345
+ timestamp: "TEXT",
4346
+ text: "TEXT",
4347
+ int: "INTEGER",
4348
+ existingColumns: (t) => ({ sql: `PRAGMA table_info(${t})`, params: [] }),
4349
+ addColumn: (t, c, type) => `ALTER TABLE ${t} ADD COLUMN ${c} ${type} NULL`
4350
+ },
4351
+ mssql: {
4352
+ ph: (n) => `@p${n}`,
4353
+ timestamp: "DATETIMEOFFSET",
4354
+ text: "NVARCHAR(MAX)",
4355
+ int: "INT",
4356
+ existingColumns: (t) => ({
4357
+ sql: "SELECT column_name FROM information_schema.columns WHERE table_name = @p1",
4358
+ params: [t]
4359
+ }),
4360
+ addColumn: (t, c, type) => `ALTER TABLE ${t} ADD ${c} ${type} NULL`
4361
+ }
4362
+ };
4363
+ function toOutboxTimestamp(dialect, when) {
4364
+ const iso = new Date(when).toISOString();
4365
+ return dialect === "mysql" ? iso.slice(0, 19).replace("T", " ") : iso;
4366
+ }
4367
+ function fromOutboxTimestamp(raw) {
4368
+ if (raw instanceof Date) return raw.getTime();
4369
+ if (typeof raw === "number") return raw;
4370
+ if (typeof raw !== "string") return null;
4371
+ const s = raw.trim();
4372
+ if (s === "") return null;
4373
+ const zoned = /(?:[Zz]|[+-]\d{2}:?\d{2})$/.test(s);
4374
+ const parsed = Date.parse(zoned ? s : `${s.replace(" ", "T")}Z`);
4375
+ return Number.isNaN(parsed) ? null : parsed;
4376
+ }
4377
+ function createOutboxConsumer(opts2) {
4378
+ const dialect = opts2.dialect ?? "postgres";
4379
+ const table = opts2.table ?? "oneaddress_updates";
4380
+ const leaseSeconds = opts2.leaseSeconds ?? 300;
4381
+ const maxAttempts = opts2.maxAttempts ?? 0;
4382
+ const now = opts2.now ?? Date.now;
4383
+ const d = SPECS[dialect];
4384
+ if (!d) throw new Error(`[OneAddress SDK] unknown dialect: ${dialect}`);
4385
+ if (!IDENTIFIER.test(table)) throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
4386
+ const batchSize = Math.floor(opts2.batchSize ?? 50);
4387
+ if (!Number.isFinite(batchSize) || batchSize < 1) {
4388
+ throw new Error(`[OneAddress SDK] batchSize must be a positive integer, got ${opts2.batchSize}`);
4389
+ }
4390
+ const ph = d.ph;
4391
+ const token = () => (0, import_node_crypto.randomBytes)(16).toString("hex");
4392
+ const stamp = (at) => toOutboxTimestamp(dialect, at);
4393
+ const claimable = (cutoffPh) => `written_at IS NOT NULL AND processed_at IS NULL AND (${CLAIMED_AT} IS NULL OR ${CLAIMED_AT} < ${cutoffPh})` + (maxAttempts > 0 ? ` AND (${ATTEMPTS} IS NULL OR ${ATTEMPTS} < ${maxAttempts})` : "");
4394
+ const toRow = (r) => ({
4395
+ dispatchId: String(r.dispatch_id ?? r.dispatchId ?? ""),
4396
+ event: String(r.event ?? ""),
4397
+ attempts: Number(r[ATTEMPTS] ?? 0) || 0,
4398
+ fields: r
4399
+ });
4400
+ async function claimBatch() {
4401
+ const at = now();
4402
+ const claimedAt = stamp(at);
4403
+ const cutoff = stamp(at - leaseSeconds * 1e3);
4404
+ const tok = token();
4405
+ if (dialect === "postgres") {
4406
+ const rows2 = await opts2.query(
4407
+ `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize} FOR UPDATE SKIP LOCKED) RETURNING *`,
4408
+ [claimedAt, tok, cutoff]
4409
+ );
4410
+ return rows2.map(toRow);
4411
+ }
4412
+ if (dialect === "mssql") {
4413
+ const rows2 = await opts2.query(
4414
+ `UPDATE TOP (${batchSize}) ${table} WITH (UPDLOCK, READPAST, ROWLOCK) SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} OUTPUT INSERTED.* WHERE ${claimable(ph(3))}`,
4415
+ [claimedAt, tok, cutoff]
4416
+ );
4417
+ return rows2.map(toRow);
4418
+ }
4419
+ const claim = dialect === "mysql" ? `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize}` : `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize})`;
4420
+ await opts2.query(claim, [claimedAt, tok, cutoff]);
4421
+ const rows = await opts2.query(
4422
+ `SELECT * FROM ${table} WHERE ${CLAIM_TOKEN} = ${ph(1)} AND processed_at IS NULL`,
4423
+ [tok]
4424
+ );
4425
+ return rows.map(toRow);
4426
+ }
4427
+ return {
4428
+ async ensureSchema() {
4429
+ const wanted = [
4430
+ [CLAIMED_AT, d.timestamp],
4431
+ [CLAIM_TOKEN, d.text],
4432
+ [ATTEMPTS, d.int]
4433
+ ];
4434
+ const q = d.existingColumns(table);
4435
+ const rows = await opts2.query(q.sql, q.params);
4436
+ const have = new Set(
4437
+ rows.map((r) => r.column_name ?? r.COLUMN_NAME ?? r.name).filter((v) => typeof v === "string").map((v) => v.toLowerCase())
4438
+ );
4439
+ if (have.size === 0) {
4440
+ throw new Error(
4441
+ `[OneAddress SDK] table ${table} has no visible columns. Is the receiver pointed at this database, and can this connection see the table?`
4442
+ );
4443
+ }
4444
+ const added = [];
4445
+ for (const [col, type] of wanted) {
4446
+ if (have.has(col)) continue;
4447
+ await opts2.query(d.addColumn(table, col, type), []);
4448
+ added.push(col);
4449
+ }
4450
+ return { added };
4451
+ },
4452
+ claimBatch,
4453
+ async markProcessed(dispatchId) {
4454
+ await opts2.query(
4455
+ `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
4456
+ [stamp(now()), dispatchId]
4457
+ );
4458
+ },
4459
+ async markFailed(dispatchId, error) {
4460
+ const message = error instanceof Error ? error.message : String(error);
4461
+ await opts2.query(
4462
+ `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
4463
+ [message.slice(0, 500), dispatchId]
4464
+ );
4465
+ },
4466
+ async release(dispatchId) {
4467
+ await opts2.query(
4468
+ `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(1)}`,
4469
+ [dispatchId]
4470
+ );
4471
+ },
4472
+ async process(handler) {
4473
+ const rows = await claimBatch();
4474
+ let processed = 0;
4475
+ let failed = 0;
4476
+ for (const row of rows) {
4477
+ try {
4478
+ await handler(row);
4479
+ await this.markProcessed(row.dispatchId);
4480
+ processed++;
4481
+ } catch (err) {
4482
+ await this.markFailed(row.dispatchId, err);
4483
+ failed++;
4484
+ }
4485
+ }
4486
+ return { processed, failed };
4487
+ },
4488
+ async backlog() {
4489
+ const rows = await opts2.query(
4490
+ `SELECT received_at, ${ATTEMPTS} FROM ${table} WHERE written_at IS NOT NULL AND processed_at IS NULL`,
4491
+ []
4492
+ );
4493
+ let oldest = null;
4494
+ let stuck = 0;
4495
+ const at = now();
4496
+ for (const r of rows) {
4497
+ const t = fromOutboxTimestamp(r.received_at ?? r.receivedAt);
4498
+ if (t !== null && (oldest === null || t < oldest)) oldest = t;
4499
+ if (maxAttempts > 0 && (Number(r[ATTEMPTS] ?? 0) || 0) >= maxAttempts) stuck++;
4500
+ }
4501
+ return {
4502
+ pending: rows.length,
4503
+ oldestPendingAgeSeconds: oldest === null ? null : Math.max(0, Math.round((at - oldest) / 1e3)),
4504
+ stuck
4505
+ };
4506
+ }
4507
+ };
4508
+ }
4509
+
4306
4510
  // src/index.ts
4307
4511
  function createSqlIdempotencyStore(opts2) {
4308
4512
  const table = opts2.table ?? "oneaddress_dispatches";
@@ -5151,12 +5355,14 @@ function toExpressHandler(handler) {
5151
5355
  0 && (module.exports = {
5152
5356
  CURRENT_VERSION,
5153
5357
  DEFAULT_REPLAY_WINDOW_SECS,
5358
+ OUTBOX_LEASE_COLUMNS,
5154
5359
  SUPPORTED_VERSIONS,
5155
5360
  canonicalD5LoaForm,
5156
5361
  compareAddresses,
5157
5362
  computeBlindIndex,
5158
5363
  confirmUpdate,
5159
5364
  createOneAddressHandler,
5365
+ createOutboxConsumer,
5160
5366
  createSqlIdempotencyStore,
5161
5367
  d5LoaRef,
5162
5368
  decrypt,
@@ -5166,6 +5372,7 @@ function toExpressHandler(handler) {
5166
5372
  fetchLoaPublicKey,
5167
5373
  findMatchingStoredName,
5168
5374
  formatAddressParts,
5375
+ fromOutboxTimestamp,
5169
5376
  isEmailLike,
5170
5377
  isFreshTimestamp,
5171
5378
  namePoolMatches,
@@ -5173,6 +5380,7 @@ function toExpressHandler(handler) {
5173
5380
  readAddressParts,
5174
5381
  sendVerifyResult,
5175
5382
  toExpressHandler,
5383
+ toOutboxTimestamp,
5176
5384
  transform,
5177
5385
  transformAddress,
5178
5386
  transformSession,
package/dist/index.mjs CHANGED
@@ -1,10 +1,12 @@
1
1
  import {
2
2
  CURRENT_VERSION,
3
+ OUTBOX_LEASE_COLUMNS,
3
4
  SUPPORTED_VERSIONS,
4
5
  canonicalD5LoaForm,
5
6
  compareAddresses,
6
7
  confirmUpdate,
7
8
  createOneAddressHandler,
9
+ createOutboxConsumer,
8
10
  createSqlIdempotencyStore,
9
11
  d5LoaRef,
10
12
  decryptAddress,
@@ -13,11 +15,13 @@ import {
13
15
  fetchLoaPublicKey,
14
16
  findMatchingStoredName,
15
17
  formatAddressParts,
18
+ fromOutboxTimestamp,
16
19
  isEmailLike,
17
20
  namePoolMatches,
18
21
  readAddressParts,
19
22
  sendVerifyResult,
20
23
  toExpressHandler,
24
+ toOutboxTimestamp,
21
25
  transformAddress,
22
26
  transformSession,
23
27
  validateAddress,
@@ -25,7 +29,7 @@ import {
25
29
  verifyLOA,
26
30
  verifySignature,
27
31
  verifyWithGrace
28
- } from "./chunk-3VG6MTRH.mjs";
32
+ } from "./chunk-MNVGYXWH.mjs";
29
33
  import {
30
34
  DEFAULT_REPLAY_WINDOW_SECS,
31
35
  computeBlindIndex,
@@ -35,12 +39,14 @@ import {
35
39
  export {
36
40
  CURRENT_VERSION,
37
41
  DEFAULT_REPLAY_WINDOW_SECS,
42
+ OUTBOX_LEASE_COLUMNS,
38
43
  SUPPORTED_VERSIONS,
39
44
  canonicalD5LoaForm,
40
45
  compareAddresses,
41
46
  computeBlindIndex,
42
47
  confirmUpdate,
43
48
  createOneAddressHandler,
49
+ createOutboxConsumer,
44
50
  createSqlIdempotencyStore,
45
51
  d5LoaRef,
46
52
  decryptAddress as decrypt,
@@ -50,6 +56,7 @@ export {
50
56
  fetchLoaPublicKey,
51
57
  findMatchingStoredName,
52
58
  formatAddressParts,
59
+ fromOutboxTimestamp,
53
60
  isEmailLike,
54
61
  isFreshTimestamp,
55
62
  namePoolMatches,
@@ -57,6 +64,7 @@ export {
57
64
  readAddressParts,
58
65
  sendVerifyResult,
59
66
  toExpressHandler,
67
+ toOutboxTimestamp,
60
68
  transformAddress as transform,
61
69
  transformAddress,
62
70
  transformSession,
package/package.json CHANGED
@@ -1,18 +1,25 @@
1
1
  {
2
2
  "name": "@oneaddress/partner-sdk",
3
- "version": "1.6.2",
3
+ "version": "1.7.0",
4
4
  "description": "Official OneAddress partner integration SDK — webhook verification, address decryption (legacy + D5 session-envelope), LOA validation",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "exports": {
8
8
  ".": {
9
- "types": "./dist/index.d.mts",
10
- "import": "./dist/index.mjs",
11
- "require": "./dist/index.js"
9
+ "import": {
10
+ "types": "./dist/index.d.mts",
11
+ "default": "./dist/index.mjs"
12
+ },
13
+ "require": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ }
12
17
  },
13
18
  "./edge": {
14
- "types": "./dist/edge.d.mts",
15
- "import": "./dist/edge.mjs"
19
+ "import": {
20
+ "types": "./dist/edge.d.mts",
21
+ "default": "./dist/edge.mjs"
22
+ }
16
23
  }
17
24
  },
18
25
  "files": [