@oneaddress/partner-sdk 1.6.3 → 1.8.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 +70 -0
- package/README.md +102 -5
- package/dist/{chunk-TAZD6PFZ.mjs → chunk-O2D5XGSN.mjs} +62 -31
- package/dist/{chunk-3VG6MTRH.mjs → chunk-PUB6ZVJ2.mjs} +223 -9
- package/dist/edge.js +82 -38
- package/dist/edge.mjs +2 -2
- package/dist/index.d.mts +228 -13
- package/dist/index.d.ts +228 -13
- package/dist/index.js +287 -38
- package/dist/index.mjs +10 -2
- package/dist/{src-ESYTJ2EY.mjs → src-UOJOUUGB.mjs} +1 -1
- package/package.json +6 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,76 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.8.0] - 2026-08-25
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Delegated private-key operations for a KMS/HSM-held key
|
|
15
|
+
(`PrivateKeyOperations`).** `createOneAddressHandler`, `decryptSession` and
|
|
16
|
+
`decryptLoaEncrypted` now accept `privateKeyPem: string | PrivateKeyOperations`.
|
|
17
|
+
A key held in a KMS or HSM is never exported as a PEM by design, so passing a
|
|
18
|
+
raw key was impossible for those integrators; a `PrivateKeyOperations`
|
|
19
|
+
delegate performs the private-key step (ECDH-ES derivation / RSA-OAEP unwrap)
|
|
20
|
+
without surrendering the key. Passing a PEM string is unchanged, so this is
|
|
21
|
+
additive — existing code compiles and runs as before.
|
|
22
|
+
|
|
23
|
+
- **`address.test-dispatch` is now handled as a test event.** The admin stress
|
|
24
|
+
test sends `address.test-dispatch` — the same fabricated, encrypted shape as a
|
|
25
|
+
connection-verification `address.test` record, only the label differs. It was
|
|
26
|
+
in no prior SDK version's handled set, so every stress test ack-200-skipped and
|
|
27
|
+
logged as "unhandled" — a warning that read like the partner's bug and was
|
|
28
|
+
ours. It now rides the exact same branch as `address.test`: decrypted and
|
|
29
|
+
handed to `onTest`, **never** `onUpdate` (the identity and address inside are
|
|
30
|
+
fabricated). `OneAddressTestEvent.event` widened to
|
|
31
|
+
`'address.test' | 'address.test-dispatch'` so a handler can count stress
|
|
32
|
+
dispatches separately; `HANDLED_EVENTS` extended to match.
|
|
33
|
+
|
|
34
|
+
### Fixed
|
|
35
|
+
|
|
36
|
+
- **The unhandled-event warning now names `onTest` for an unwired
|
|
37
|
+
`address.test-dispatch` too.** When `onTest` is not supplied, a
|
|
38
|
+
`address.test-dispatch` event falls through to the unhandled branch. It was
|
|
39
|
+
taking the "this event is unknown — upgrade the SDK" message, which cannot
|
|
40
|
+
help (the build already supports it); it now takes the same "add an `onTest`
|
|
41
|
+
callback" message as `address.test`.
|
|
42
|
+
|
|
43
|
+
## [1.7.0] - 2026-08-21
|
|
44
|
+
|
|
45
|
+
### Added
|
|
46
|
+
|
|
47
|
+
- **`createOutboxConsumer` — draining the outbox, correctly, on all four
|
|
48
|
+
dialects.** The receiver writes each delivered update to a table and stamps
|
|
49
|
+
`written_at`; `processed_at` is the partner's to stamp. Until now the SDK
|
|
50
|
+
gave no help crossing that gap, so every integrator wrote their own polling
|
|
51
|
+
loop and rediscovered the same problems.
|
|
52
|
+
|
|
53
|
+
The one worth naming: `SELECT … WHERE processed_at IS NULL` is correct with
|
|
54
|
+
one consumer and quietly wrong with two. Both read the same rows, both apply
|
|
55
|
+
the same address, and whichever finishes second overwrites the first — which
|
|
56
|
+
on a CRM that fires side effects on write is visible to the customer. There
|
|
57
|
+
is no error, and it appears on the day a second replica is added.
|
|
58
|
+
|
|
59
|
+
Claiming atomically is dialect territory, and that is what this removes:
|
|
60
|
+
`FOR UPDATE SKIP LOCKED` on postgres, `UPDLOCK, READPAST` on SQL Server, an
|
|
61
|
+
`ORDER BY … LIMIT` plus a read-back token on MySQL (which cannot reference
|
|
62
|
+
the target table in a subquery, error 1093, and has no `RETURNING`), and a
|
|
63
|
+
plain subquery on SQLite, which has one writer and nothing to skip.
|
|
64
|
+
|
|
65
|
+
A claim is a **lease**, not a lock: it expires after `leaseSeconds` so a
|
|
66
|
+
consumer that dies strands nothing. Your handler must therefore be
|
|
67
|
+
idempotent — no timeout is long enough to make a double-claim impossible.
|
|
68
|
+
|
|
69
|
+
`maxAttempts` defaults to `0`, meaning never give up. Giving up on a row is
|
|
70
|
+
an address that never reaches the partner's system, which is worse than a
|
|
71
|
+
loop they can see; the cap is opt-in once `backlog().stuck` is alerted on.
|
|
72
|
+
|
|
73
|
+
Also exported: `toOutboxTimestamp` / `fromOutboxTimestamp`, because binding
|
|
74
|
+
and reading a timestamp are both dialect traps. A MySQL `DATETIME` rejects an
|
|
75
|
+
ISO-8601 string outright in strict mode, and `Date.parse` on a zone-less
|
|
76
|
+
value applies the LOCAL zone per ECMA-262 — which skews a backlog age by the
|
|
77
|
+
deployment's whole UTC offset, and to the west of Greenwich makes it negative
|
|
78
|
+
so a threshold alert can never fire at all.
|
|
79
|
+
|
|
10
80
|
## [1.6.3] - 2026-08-21
|
|
11
81
|
|
|
12
82
|
### 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](
|
|
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,
|
|
@@ -58,11 +59,13 @@ export const handler = createOneAddressHandler({
|
|
|
58
59
|
// fictitious, and writing them into real customer records is exactly what a
|
|
59
60
|
// separate event type exists to prevent.
|
|
60
61
|
//
|
|
61
|
-
//
|
|
62
|
-
//
|
|
62
|
+
// Handles both address.test (connection verification) and address.test-dispatch
|
|
63
|
+
// (the admin stress test) - same fabricated, encrypted test record, only the
|
|
64
|
+
// event label differs. Leave it out and both are acknowledged with 200,
|
|
65
|
+
// skipped, and logged as skipped; you will not be able to complete connection
|
|
63
66
|
// verification through the SDK.
|
|
64
67
|
async onTest(event) {
|
|
65
|
-
console.log(`test record ${event.index}/${event.total}`,
|
|
68
|
+
console.log(`test record (${event.event}) ${event.index}/${event.total}`,
|
|
66
69
|
event.customer.name, event.address);
|
|
67
70
|
},
|
|
68
71
|
});
|
|
@@ -382,6 +385,98 @@ side and ours both reporting success.
|
|
|
382
385
|
|
|
383
386
|
---
|
|
384
387
|
|
|
388
|
+
## Draining the outbox — `createOutboxConsumer`
|
|
389
|
+
|
|
390
|
+
If you run the drop-in receiver, every delivered update lands in a table and is stamped
|
|
391
|
+
`written_at`. The receiver never stamps `processed_at` — that column is yours, and the gap
|
|
392
|
+
between the two is what makes the backlog metric mean anything.
|
|
393
|
+
|
|
394
|
+
`createOutboxConsumer` crosses that gap for you, correctly, on all four databases the
|
|
395
|
+
receiver supports.
|
|
396
|
+
|
|
397
|
+
```typescript
|
|
398
|
+
import { createOutboxConsumer } from '@oneaddress/partner-sdk';
|
|
399
|
+
|
|
400
|
+
const outbox = createOutboxConsumer({
|
|
401
|
+
query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
|
|
402
|
+
dialect: 'postgres',
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
await outbox.ensureSchema(); // once, on boot — adds its lease columns
|
|
406
|
+
|
|
407
|
+
setInterval(async () => {
|
|
408
|
+
await outbox.process(async (row) => {
|
|
409
|
+
await crm.applyAddress(row.fields); // your work
|
|
410
|
+
}); // marked processed, or failed and retried
|
|
411
|
+
}, 5_000);
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
### Why not just `SELECT … WHERE processed_at IS NULL`
|
|
415
|
+
|
|
416
|
+
Because that is correct with one consumer and quietly wrong with two. Both read the same
|
|
417
|
+
rows, both apply the same address, and whichever finishes second overwrites the first. On a
|
|
418
|
+
CRM that fires side effects on write — a confirmation email, an audit entry, a downstream
|
|
419
|
+
sync — the duplicate is visible to your customer.
|
|
420
|
+
|
|
421
|
+
Claiming atomically is dialect-specific, and that is the part this saves you:
|
|
422
|
+
|
|
423
|
+
| Database | How a batch is claimed |
|
|
424
|
+
|------------|------------------------|
|
|
425
|
+
| PostgreSQL | `FOR UPDATE SKIP LOCKED` in a subquery, `RETURNING *` — one statement |
|
|
426
|
+
| SQL Server | `UPDATE TOP (n) … WITH (UPDLOCK, READPAST, ROWLOCK) … OUTPUT INSERTED.*` |
|
|
427
|
+
| 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` |
|
|
428
|
+
| SQLite | Subquery without a lock hint — one writer, so there is nothing to skip |
|
|
429
|
+
|
|
430
|
+
### A claim is a lease, not a lock
|
|
431
|
+
|
|
432
|
+
A consumer that dies mid-batch must not strand its rows. A claim expires after
|
|
433
|
+
`leaseSeconds` (default 300) and the row becomes claimable again.
|
|
434
|
+
|
|
435
|
+
**Your handler must therefore be idempotent.** If a lease expires while the handler is still
|
|
436
|
+
running, the row can be claimed twice — and no timeout is long enough to make that
|
|
437
|
+
impossible. Set `leaseSeconds` comfortably longer than your slowest handler, and make the
|
|
438
|
+
write itself safe to repeat.
|
|
439
|
+
|
|
440
|
+
### Failure, and why nothing is given up on by default
|
|
441
|
+
|
|
442
|
+
A handler that throws does not stop the batch: the row records its reason in
|
|
443
|
+
`processing_error`, counts an attempt, releases its claim and is retried on the next pass.
|
|
444
|
+
The rest of the claimed batch still runs.
|
|
445
|
+
|
|
446
|
+
`maxAttempts` defaults to `0`, meaning **never stop trying**, and that default is deliberate.
|
|
447
|
+
Giving up on a row is an address that never reaches your system, which is worse than a loop
|
|
448
|
+
you can see. Set a cap only once you are alerting on `backlog().stuck`.
|
|
449
|
+
|
|
450
|
+
### The numbers to watch
|
|
451
|
+
|
|
452
|
+
```typescript
|
|
453
|
+
const { pending, oldestPendingAgeSeconds, stuck } = await outbox.backlog();
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
`oldestPendingAgeSeconds` is the one to alert on. A rising value means the receiver is
|
|
457
|
+
healthy and your consuming job is not — a state that is otherwise silent on both sides until
|
|
458
|
+
someone asks why an address never appeared.
|
|
459
|
+
|
|
460
|
+
### Columns it adds
|
|
461
|
+
|
|
462
|
+
`ensureSchema()` adds `oa_claimed_at`, `oa_claim_token` and `oa_attempts` if they are absent,
|
|
463
|
+
and is safe to call on every boot. They carry the `oa_` prefix because this consumer is also
|
|
464
|
+
useful over a table you wrote yourself, where a bare `claimed_at` might already mean
|
|
465
|
+
something.
|
|
466
|
+
|
|
467
|
+
### Options
|
|
468
|
+
|
|
469
|
+
| Option | Default | |
|
|
470
|
+
|---|---|---|
|
|
471
|
+
| `query` | — | Runs parameterised SQL, returns rows. Your pool, your driver. |
|
|
472
|
+
| `dialect` | `postgres` | `postgres` \| `mysql` \| `sqlite` \| `mssql` |
|
|
473
|
+
| `table` | `oneaddress_updates` | What the receiver writes to |
|
|
474
|
+
| `batchSize` | `50` | Rows per claim |
|
|
475
|
+
| `leaseSeconds` | `300` | How long a claim is held |
|
|
476
|
+
| `maxAttempts` | `0` | `0` = never give up |
|
|
477
|
+
|
|
478
|
+
---
|
|
479
|
+
|
|
385
480
|
## Identity verification attestation
|
|
386
481
|
|
|
387
482
|
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 +529,9 @@ await db.updateAddress({
|
|
|
434
529
|
|
|
435
530
|
## Secret rotation grace window
|
|
436
531
|
|
|
437
|
-
|
|
532
|
+
**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.
|
|
533
|
+
|
|
534
|
+
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
535
|
|
|
439
536
|
```typescript
|
|
440
537
|
export const handler = createOneAddressHandler({
|
|
@@ -3642,6 +3642,9 @@ function b64UrlToBytes(b64url) {
|
|
|
3642
3642
|
const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
|
|
3643
3643
|
return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
|
|
3644
3644
|
}
|
|
3645
|
+
function toArrayBuffer(bytes) {
|
|
3646
|
+
return bytes.slice().buffer;
|
|
3647
|
+
}
|
|
3645
3648
|
async function encryptSessionForPartner(session_data, partner) {
|
|
3646
3649
|
return encryptEnvelopeForPartner(session_data, partner);
|
|
3647
3650
|
}
|
|
@@ -3765,6 +3768,20 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
|
|
|
3765
3768
|
if (share.v !== 2) {
|
|
3766
3769
|
throw new Error(`decryptSession: unsupported share version ${share.v}`);
|
|
3767
3770
|
}
|
|
3771
|
+
const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
|
|
3772
|
+
if (ops) {
|
|
3773
|
+
if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
|
|
3774
|
+
throw new Error(
|
|
3775
|
+
`decryptSession: key source "${ops.name}" performs private-key operations without releasing the key, which no KMS offers for ML-KEM. Use an exportable key source for post-quantum shares.`
|
|
3776
|
+
);
|
|
3777
|
+
}
|
|
3778
|
+
const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : "deriveSharedSecret";
|
|
3779
|
+
if (typeof ops[needed] !== "function") {
|
|
3780
|
+
throw new Error(
|
|
3781
|
+
`decryptSession: key source "${ops.name}" cannot do ${needed}, which ${share.alg} requires.`
|
|
3782
|
+
);
|
|
3783
|
+
}
|
|
3784
|
+
}
|
|
3768
3785
|
let skRawBuf;
|
|
3769
3786
|
if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
|
|
3770
3787
|
if (!share.epk) {
|
|
@@ -3786,41 +3803,55 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
|
|
|
3786
3803
|
const wrapKey = await subtle().importKey("raw", wrapKeyRaw, { name: "AES-GCM" }, false, ["decrypt"]);
|
|
3787
3804
|
skRawBuf = await subtle().decrypt({ name: "AES-GCM", iv: wrapIv }, wrapKey, wrappedSkBytes);
|
|
3788
3805
|
} else if (share.alg === "RSA-OAEP-256+A256GCM") {
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
3806
|
+
if (ops) {
|
|
3807
|
+
skRawBuf = toArrayBuffer(await ops.decryptRsaOaep(b64UrlToBytes(share.wrapped_key)));
|
|
3808
|
+
} else {
|
|
3809
|
+
const rsaPrivateKey = await subtle().importKey(
|
|
3810
|
+
"pkcs8",
|
|
3811
|
+
keyB64ToBytes(privateKeyB64),
|
|
3812
|
+
{ name: "RSA-OAEP", hash: "SHA-256" },
|
|
3813
|
+
false,
|
|
3814
|
+
["decrypt"]
|
|
3815
|
+
);
|
|
3816
|
+
skRawBuf = await subtle().decrypt(
|
|
3817
|
+
{ name: "RSA-OAEP" },
|
|
3818
|
+
rsaPrivateKey,
|
|
3819
|
+
b64UrlToBytes(share.wrapped_key)
|
|
3820
|
+
);
|
|
3821
|
+
}
|
|
3801
3822
|
} else {
|
|
3802
3823
|
if (!share.epk) {
|
|
3803
3824
|
throw new Error("decryptSession: ECDH-ES share missing epk");
|
|
3804
3825
|
}
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
|
|
3808
|
-
|
|
3809
|
-
|
|
3810
|
-
|
|
3811
|
-
|
|
3812
|
-
|
|
3813
|
-
|
|
3814
|
-
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
|
|
3822
|
-
|
|
3823
|
-
|
|
3826
|
+
let sharedSecret;
|
|
3827
|
+
if (ops) {
|
|
3828
|
+
sharedSecret = toArrayBuffer(await ops.deriveSharedSecret(b64UrlToBytes(share.epk)));
|
|
3829
|
+
if (sharedSecret.byteLength !== 32) {
|
|
3830
|
+
throw new Error(
|
|
3831
|
+
`decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; P-256 ECDH is 32 bytes with no KDF applied.`
|
|
3832
|
+
);
|
|
3833
|
+
}
|
|
3834
|
+
} else {
|
|
3835
|
+
const privateKey = await subtle().importKey(
|
|
3836
|
+
"pkcs8",
|
|
3837
|
+
keyB64ToBytes(privateKeyB64),
|
|
3838
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
3839
|
+
false,
|
|
3840
|
+
["deriveBits"]
|
|
3841
|
+
);
|
|
3842
|
+
const ephemeralPub = await subtle().importKey(
|
|
3843
|
+
"spki",
|
|
3844
|
+
b64UrlToBytes(share.epk),
|
|
3845
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
3846
|
+
false,
|
|
3847
|
+
[]
|
|
3848
|
+
);
|
|
3849
|
+
sharedSecret = await subtle().deriveBits(
|
|
3850
|
+
{ name: "ECDH", public: ephemeralPub },
|
|
3851
|
+
privateKey,
|
|
3852
|
+
256
|
|
3853
|
+
);
|
|
3854
|
+
}
|
|
3824
3855
|
const wrappedBytes = b64UrlToBytes(share.wrapped_key);
|
|
3825
3856
|
if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
|
|
3826
3857
|
throw new Error("decryptSession: wrapped_key too short");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
isFreshTimestamp,
|
|
3
3
|
isSafeWebhookUrl
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-O2D5XGSN.mjs";
|
|
5
5
|
|
|
6
6
|
// src/index.ts
|
|
7
7
|
import crypto from "crypto";
|
|
@@ -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";
|
|
@@ -179,8 +379,13 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
|
|
|
179
379
|
return JSON.parse(new TextDecoder().decode(plaintext));
|
|
180
380
|
}
|
|
181
381
|
async function decryptSession(share, envelopeB64, privateKeyPem, partnerId) {
|
|
182
|
-
const { decryptSession: decryptSessionCrypto } = await import("./src-
|
|
183
|
-
return decryptSessionCrypto(
|
|
382
|
+
const { decryptSession: decryptSessionCrypto } = await import("./src-UOJOUUGB.mjs");
|
|
383
|
+
return decryptSessionCrypto(
|
|
384
|
+
share,
|
|
385
|
+
envelopeB64,
|
|
386
|
+
typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
|
|
387
|
+
partnerId
|
|
388
|
+
);
|
|
184
389
|
}
|
|
185
390
|
async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
|
|
186
391
|
const plaintext = await decryptAddress(payload, privateKeyPem, partnerId);
|
|
@@ -533,7 +738,7 @@ async function sendVerifyResult(params) {
|
|
|
533
738
|
throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
|
|
534
739
|
}
|
|
535
740
|
}
|
|
536
|
-
var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
|
|
741
|
+
var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
|
|
537
742
|
var warnedUnhandledEvents = /* @__PURE__ */ new Set();
|
|
538
743
|
function createOneAddressHandler(options) {
|
|
539
744
|
const {
|
|
@@ -806,16 +1011,16 @@ function createOneAddressHandler(options) {
|
|
|
806
1011
|
headers: { "Content-Type": "application/json" }
|
|
807
1012
|
});
|
|
808
1013
|
}
|
|
809
|
-
if (body.event === "address.test" && onTest) {
|
|
1014
|
+
if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
|
|
810
1015
|
if (!isD5Body(body)) {
|
|
811
|
-
return new Response(JSON.stringify({ error: "
|
|
1016
|
+
return new Response(JSON.stringify({ error: "a test dispatch requires a session envelope" }), {
|
|
812
1017
|
status: 400,
|
|
813
1018
|
headers: { "Content-Type": "application/json" }
|
|
814
1019
|
});
|
|
815
1020
|
}
|
|
816
1021
|
const d5 = await buildD5Pieces(body, partnerId);
|
|
817
1022
|
await onTest({
|
|
818
|
-
event:
|
|
1023
|
+
event: body.event,
|
|
819
1024
|
index: typeof body.index === "number" ? body.index : void 0,
|
|
820
1025
|
total: typeof body.total === "number" ? body.total : void 0,
|
|
821
1026
|
verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
|
|
@@ -834,12 +1039,17 @@ function createOneAddressHandler(options) {
|
|
|
834
1039
|
const callbackFor = {
|
|
835
1040
|
"address.verify": onVerify,
|
|
836
1041
|
"account.verify": onAccountVerify,
|
|
837
|
-
"address.test": onTest
|
|
1042
|
+
"address.test": onTest,
|
|
1043
|
+
// Same callback as address.test: both test variants route to onTest, so
|
|
1044
|
+
// an unwired stress-test event must name onTest too — not fall through
|
|
1045
|
+
// to the "upgrade the SDK" remedy, which cannot help (marlowe-reports#126).
|
|
1046
|
+
"address.test-dispatch": onTest
|
|
838
1047
|
};
|
|
839
1048
|
const callbackNameFor = {
|
|
840
1049
|
"address.verify": "onVerify",
|
|
841
1050
|
"account.verify": "onAccountVerify",
|
|
842
|
-
"address.test": "onTest"
|
|
1051
|
+
"address.test": "onTest",
|
|
1052
|
+
"address.test-dispatch": "onTest"
|
|
843
1053
|
};
|
|
844
1054
|
const unwired = evt in callbackFor && !callbackFor[evt] ? callbackNameFor[evt] : null;
|
|
845
1055
|
if (!warnedUnhandledEvents.has(evt)) {
|
|
@@ -903,6 +1113,10 @@ export {
|
|
|
903
1113
|
isEmailLike,
|
|
904
1114
|
namePoolMatches,
|
|
905
1115
|
findMatchingStoredName,
|
|
1116
|
+
OUTBOX_LEASE_COLUMNS,
|
|
1117
|
+
toOutboxTimestamp,
|
|
1118
|
+
fromOutboxTimestamp,
|
|
1119
|
+
createOutboxConsumer,
|
|
906
1120
|
createSqlIdempotencyStore,
|
|
907
1121
|
verifySignature,
|
|
908
1122
|
verifyWithGrace,
|