@dexterai/x402 3.16.0 → 3.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +142 -438
- package/dist/client/index.d.cts +2 -2
- package/dist/client/index.d.ts +2 -2
- package/dist/tab/adapters/solana/index.d.cts +1 -1
- package/dist/tab/adapters/solana/index.d.ts +1 -1
- package/dist/tab/index.cjs +4 -4
- package/dist/tab/index.d.cts +64 -5
- package/dist/tab/index.d.ts +64 -5
- package/dist/tab/index.js +2 -2
- package/dist/tab/seller/index.cjs +4 -4
- package/dist/tab/seller/index.d.cts +209 -8
- package/dist/tab/seller/index.d.ts +209 -8
- package/dist/tab/seller/index.js +4 -4
- package/dist/{types-ZjcxOAbW.d.ts → types-BL9QW1gf.d.ts} +1 -1
- package/dist/{types-B1wGPP7B.d.cts → types-DMzS_Rh2.d.cts} +1 -1
- package/dist/{types-DEnVPFxF.d.cts → types-DuoL3s8n.d.cts} +1 -1
- package/dist/{types-DEnVPFxF.d.ts → types-DuoL3s8n.d.ts} +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,123 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { SignedVoucher, AtomicAmount, TabNetworkId, HumanAmount } from '@dexterai/vault/types';
|
|
2
2
|
import { RequestHandler, Request, Response } from 'express';
|
|
3
3
|
import { Connection, PublicKey } from '@solana/web3.js';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Durable per-channel seller ledger for OTS tab streaming.
|
|
7
|
+
*
|
|
8
|
+
* Supersedes VoucherStore: it persists the latest accepted voucher AND the
|
|
9
|
+
* one quantity the chain never sees — `deliveredCumulativeAtomic`, the
|
|
10
|
+
* cumulative service the meter has actually delivered on this channel across
|
|
11
|
+
* ALL requests. Monotonic, never reset. This is what closes the channel-reuse
|
|
12
|
+
* metering leak: the meter budgets each request against
|
|
13
|
+
* `signedCumulative − deliveredCumulative`, not the lifetime cumulative.
|
|
14
|
+
*
|
|
15
|
+
* Shape mirrors the on-chain SessionRegistration money ledger
|
|
16
|
+
* (spent / crystallized_cumulative / current_outstanding / last_locked_sequence)
|
|
17
|
+
* that already ships in V6, via the optional `onChain` snapshot. That field is
|
|
18
|
+
* RESERVED for the Step-4 lock/LockedClaim model (lock_voucher reads/writes
|
|
19
|
+
* those on-chain) — the off-chain meter does not populate it today. Reserving
|
|
20
|
+
* it here keeps the ledger forward-compatible without a later breaking change.
|
|
21
|
+
*
|
|
22
|
+
* The same durable state is the substrate resumeTab / stranded-tab recovery
|
|
23
|
+
* needs (last voucher + delivered baseline per channel).
|
|
24
|
+
*
|
|
25
|
+
* Single-stream lease (multi-instance boundary): the per-channel `lease`
|
|
26
|
+
* (tryAcquireLease/releaseLease) enforces ONE live stream per channel, the
|
|
27
|
+
* defense against the concurrent-same-channel over-delivery rug. The default
|
|
28
|
+
* InMemoryChannelLedger / FileChannelLedger acquire it atomically WITHIN one
|
|
29
|
+
* seller process (via the per-channel async lock). A seller running MULTIPLE
|
|
30
|
+
* instances behind a load balancer MUST either back ChannelLedger with a store
|
|
31
|
+
* that makes acquire atomic across processes (Redis `SET NX PX`, Postgres
|
|
32
|
+
* advisory lock / `INSERT ... ON CONFLICT`) or route a channel's requests to a
|
|
33
|
+
* consistent instance — otherwise two instances can each acquire the lease and
|
|
34
|
+
* the rug reopens.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Read-through cache of the on-chain SessionRegistration money ledger.
|
|
39
|
+
* RESERVED for Step 4 (lock_voucher / LockedClaim). Not populated by the
|
|
40
|
+
* off-chain meter today. All amounts are atomic (base units) strings.
|
|
41
|
+
*/
|
|
42
|
+
interface OnChainLedgerSnapshot {
|
|
43
|
+
spentAtomic: AtomicAmount;
|
|
44
|
+
crystallizedCumulativeAtomic: AtomicAmount;
|
|
45
|
+
currentOutstandingAtomic: AtomicAmount;
|
|
46
|
+
lastLockedSequence: number;
|
|
47
|
+
/** Unix seconds when this snapshot was read from chain. */
|
|
48
|
+
fetchedAtUnixSec: number;
|
|
49
|
+
}
|
|
50
|
+
interface ChannelLedgerEntry {
|
|
51
|
+
/**
|
|
52
|
+
* Latest accepted voucher (`payload.cumulativeAmount` is the signedCumulative),
|
|
53
|
+
* or `null` for a lease-only entry created when the first request on a channel
|
|
54
|
+
* acquires its single-stream lease BEFORE any voucher is persisted. The
|
|
55
|
+
* middleware writes the real voucher immediately after acquiring the lease, so
|
|
56
|
+
* a null `lastVoucher` is only ever a transient pre-first-voucher state.
|
|
57
|
+
*/
|
|
58
|
+
lastVoucher: SignedVoucher | null;
|
|
59
|
+
/**
|
|
60
|
+
* Off-chain cumulative the meter has DELIVERED on this channel across all
|
|
61
|
+
* requests. Monotonic; never reset. The leak-fix field.
|
|
62
|
+
*/
|
|
63
|
+
deliveredCumulativeAtomic: AtomicAmount;
|
|
64
|
+
/**
|
|
65
|
+
* Delivered cumulative (atomic) that the seller has already crystallized into
|
|
66
|
+
* an on-chain LockedClaim via the keyless `/tab/lock` cadence (Step-4). The
|
|
67
|
+
* crystallization cadence fires when `deliveredCumulativeAtomic −
|
|
68
|
+
* lastCrystallizedCumulativeAtomic` crosses the configured threshold, then
|
|
69
|
+
* advances this on a successful lock so it can't double-fire. Treated as
|
|
70
|
+
* `'0'` when absent (older entries / lease-only entries). Optional so
|
|
71
|
+
* pre-Step-4 ledger constructors remain valid without a breaking change.
|
|
72
|
+
*/
|
|
73
|
+
lastCrystallizedCumulativeAtomic?: AtomicAmount;
|
|
74
|
+
/** RESERVED (Step 4): on-chain money ledger snapshot. Unset today. */
|
|
75
|
+
onChain?: OnChainLedgerSnapshot;
|
|
76
|
+
/**
|
|
77
|
+
* Active-stream lease. Set while a meter is live on this channel; cleared on
|
|
78
|
+
* the meter's terminal path. `heldUntilUnixMs` is a TTL so a crashed holder's
|
|
79
|
+
* lease auto-expires (a stuck lease would otherwise block the buyer's own
|
|
80
|
+
* next request on this tab). Enforces one live stream per channel — the
|
|
81
|
+
* defense against the concurrent-same-channel over-delivery rug.
|
|
82
|
+
*/
|
|
83
|
+
lease?: {
|
|
84
|
+
heldUntilUnixMs: number;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
interface ChannelLedger {
|
|
88
|
+
get(channelId: string): Promise<ChannelLedgerEntry | null>;
|
|
89
|
+
set(channelId: string, entry: ChannelLedgerEntry): Promise<void>;
|
|
90
|
+
delete(channelId: string): Promise<void>;
|
|
91
|
+
/**
|
|
92
|
+
* Atomically acquire the channel's single-stream lease if free or expired.
|
|
93
|
+
* Returns true if acquired, false if another live stream holds it. The
|
|
94
|
+
* in-process/file impls serialize via the per-channel lock (correct for a
|
|
95
|
+
* single seller process). A multi-instance seller MUST back this with a store
|
|
96
|
+
* that makes acquire atomic across processes (Redis SETNX, Postgres, ...).
|
|
97
|
+
*/
|
|
98
|
+
tryAcquireLease(channelId: string, ttlMs: number): Promise<boolean>;
|
|
99
|
+
/** Release the channel's lease (no-op if not held). */
|
|
100
|
+
releaseLease(channelId: string): Promise<void>;
|
|
101
|
+
}
|
|
102
|
+
declare class InMemoryChannelLedger implements ChannelLedger {
|
|
103
|
+
private map;
|
|
104
|
+
get(channelId: string): Promise<ChannelLedgerEntry | null>;
|
|
105
|
+
set(channelId: string, entry: ChannelLedgerEntry): Promise<void>;
|
|
106
|
+
delete(channelId: string): Promise<void>;
|
|
107
|
+
tryAcquireLease(channelId: string, ttlMs: number): Promise<boolean>;
|
|
108
|
+
releaseLease(channelId: string): Promise<void>;
|
|
109
|
+
}
|
|
110
|
+
declare class FileChannelLedger implements ChannelLedger {
|
|
111
|
+
private readonly dir;
|
|
112
|
+
constructor(dir: string);
|
|
113
|
+
private pathFor;
|
|
114
|
+
get(channelId: string): Promise<ChannelLedgerEntry | null>;
|
|
115
|
+
set(channelId: string, entry: ChannelLedgerEntry): Promise<void>;
|
|
116
|
+
delete(channelId: string): Promise<void>;
|
|
117
|
+
tryAcquireLease(channelId: string, ttlMs: number): Promise<boolean>;
|
|
118
|
+
releaseLease(channelId: string): Promise<void>;
|
|
119
|
+
}
|
|
120
|
+
|
|
5
121
|
/**
|
|
6
122
|
* @dexterai/x402/tab/seller — types for the seller side of OTS tab streaming.
|
|
7
123
|
*
|
|
@@ -17,6 +133,7 @@ import { Connection, PublicKey } from '@solana/web3.js';
|
|
|
17
133
|
* loses at most the last in-flight voucher's worth of revenue. Pluggable to
|
|
18
134
|
* match `batch-settlement/store`'s ChannelStore pattern.
|
|
19
135
|
*/
|
|
136
|
+
/** @deprecated Superseded by ChannelLedger (channel-ledger.ts), which also persists deliveredCumulative. */
|
|
20
137
|
interface VoucherStore {
|
|
21
138
|
get(channelId: string): Promise<SignedVoucher | null>;
|
|
22
139
|
set(channelId: string, voucher: SignedVoucher): Promise<void>;
|
|
@@ -39,6 +156,19 @@ interface SellerTab {
|
|
|
39
156
|
* monotonicity check fails. The middleware persists on success.
|
|
40
157
|
*/
|
|
41
158
|
charge(incrementHuman: HumanAmount): Promise<void>;
|
|
159
|
+
/**
|
|
160
|
+
* Off-chain cumulative (human amount) the meter has DELIVERED on this
|
|
161
|
+
* channel across ALL requests, read from the ChannelLedger at request start.
|
|
162
|
+
* The meter's per-request budget is `cumulative() − deliveredCumulative()`.
|
|
163
|
+
*/
|
|
164
|
+
deliveredCumulative(): HumanAmount;
|
|
165
|
+
/**
|
|
166
|
+
* Add `incrementAtomic` (this request's delivered amount, atomic) to the
|
|
167
|
+
* channel's durable lifetime delivered total, under a per-channel lock.
|
|
168
|
+
* Monotonic — a non-positive increment is a no-op. Called by the meter once
|
|
169
|
+
* per request on the terminal path (end / cap-reject / disconnect).
|
|
170
|
+
*/
|
|
171
|
+
recordDelivered(incrementAtomic: AtomicAmount): Promise<void>;
|
|
42
172
|
}
|
|
43
173
|
/** Options for `tabMiddleware`. */
|
|
44
174
|
interface TabMiddlewareOptions {
|
|
@@ -48,16 +178,42 @@ interface TabMiddlewareOptions {
|
|
|
48
178
|
network: TabNetworkId;
|
|
49
179
|
/** When to settle on chain: at tab close (the common case) vs periodically. */
|
|
50
180
|
settle: 'on-close' | 'periodic';
|
|
51
|
-
/** Facilitator base URL. Default: https://
|
|
181
|
+
/** Facilitator base URL. Default: DEFAULT_FACILITATOR_URL (https://x402.dexter.cash). */
|
|
52
182
|
facilitatorUrl?: string;
|
|
53
|
-
/**
|
|
54
|
-
|
|
183
|
+
/**
|
|
184
|
+
* Durable per-channel state (latest voucher + delivered cumulative).
|
|
185
|
+
* Default: in-memory (loses state on restart). Pass a FileChannelLedger or
|
|
186
|
+
* your own ChannelLedger for restart-safe revenue + resumeTab support.
|
|
187
|
+
*/
|
|
188
|
+
ledger?: ChannelLedger;
|
|
189
|
+
/**
|
|
190
|
+
* Max single-stream duration before a crashed holder's lease auto-expires.
|
|
191
|
+
* Default 300000 (5 min).
|
|
192
|
+
*/
|
|
193
|
+
leaseTtlMs?: number;
|
|
55
194
|
/**
|
|
56
195
|
* Hard cap on a single voucher's incremental amount. Protects the seller's
|
|
57
196
|
* middleware from accepting a buyer trying to slip in a giant single
|
|
58
197
|
* voucher. Default: 100x `perUnit`.
|
|
59
198
|
*/
|
|
60
199
|
maxPerVoucherAtomic?: AtomicAmount;
|
|
200
|
+
/**
|
|
201
|
+
* Keyless crystallization cadence (Step-4 lock-mode). On the configured
|
|
202
|
+
* delivered-amount threshold — and at tab close — the meter POSTs the
|
|
203
|
+
* buyer's already-stored signed voucher to `${facilitatorUrl}/tab/lock`,
|
|
204
|
+
* crystallizing it into an on-chain LockedClaim. BEST-EFFORT: a failed
|
|
205
|
+
* crystallize never blocks or errors the seller's response; a missed lock
|
|
206
|
+
* just widens the seller's unsecured window (their risk dial).
|
|
207
|
+
*
|
|
208
|
+
* Defaults when omitted: `{ thresholdAtomic: humanToAtomic('0.10'),
|
|
209
|
+
* onClose: true }`. Set `thresholdAtomic` higher to crystallize less often
|
|
210
|
+
* (cheaper, wider window) or lower to lock more aggressively. Set
|
|
211
|
+
* `onClose: false` to skip the close-time lock.
|
|
212
|
+
*/
|
|
213
|
+
lockCadence?: {
|
|
214
|
+
thresholdAtomic?: string;
|
|
215
|
+
onClose?: boolean;
|
|
216
|
+
};
|
|
61
217
|
}
|
|
62
218
|
/**
|
|
63
219
|
* Options for `openSse` — the Express response → SSE stream helper. Returns
|
|
@@ -76,12 +232,12 @@ interface OpenSseOptions {
|
|
|
76
232
|
interface SseMeter {
|
|
77
233
|
charge(units?: number): Promise<void>;
|
|
78
234
|
send(chunk: string | Uint8Array): void;
|
|
79
|
-
end(): void
|
|
235
|
+
end(): Promise<void>;
|
|
80
236
|
}
|
|
81
237
|
/** Errors thrown by the seller middleware on bad vouchers. */
|
|
82
238
|
declare class InvalidVoucherError extends Error {
|
|
83
|
-
readonly reason: 'signature_invalid' | 'registration_invalid' | 'cap_exceeded' | 'session_expired' | 'wrong_counterparty' | 'non_monotonic';
|
|
84
|
-
constructor(reason: 'signature_invalid' | 'registration_invalid' | 'cap_exceeded' | 'session_expired' | 'wrong_counterparty' | 'non_monotonic', detail?: string);
|
|
239
|
+
readonly reason: 'signature_invalid' | 'registration_invalid' | 'cap_exceeded' | 'session_expired' | 'wrong_counterparty' | 'non_monotonic' | 'channel_busy';
|
|
240
|
+
constructor(reason: 'signature_invalid' | 'registration_invalid' | 'cap_exceeded' | 'session_expired' | 'wrong_counterparty' | 'non_monotonic' | 'channel_busy', detail?: string);
|
|
85
241
|
}
|
|
86
242
|
|
|
87
243
|
/**
|
|
@@ -148,6 +304,16 @@ declare function requireTab(req: Request): SellerTab;
|
|
|
148
304
|
* left for Phase 4+; the v3 meter ships the simpler "one voucher bounds
|
|
149
305
|
* the whole request" model, which is correct for any reasonable chunk
|
|
150
306
|
* count under a single per-request increment.
|
|
307
|
+
*
|
|
308
|
+
* Concurrency note: delivered accounting is exact for requests that run
|
|
309
|
+
* sequentially per channel (the normal case — an agent streams one request at
|
|
310
|
+
* a time per tab). Two GENUINELY concurrent streams on the SAME channel each
|
|
311
|
+
* read the same delivered baseline, so they can over-deliver in-flight up to
|
|
312
|
+
* the sum of their budgets before either persists. The lifetime ledger stays
|
|
313
|
+
* correct (additive under a per-channel lock), so the over-delivery is bounded
|
|
314
|
+
* to the overlap and never compounds across future requests. Sellers needing
|
|
315
|
+
* exact metering under parallel same-channel streams should serialize requests
|
|
316
|
+
* per channel.
|
|
151
317
|
*/
|
|
152
318
|
|
|
153
319
|
declare function openSse(res: Response, options: OpenSseOptions): SseMeter;
|
|
@@ -306,4 +472,39 @@ interface TabChallengeConfig {
|
|
|
306
472
|
}
|
|
307
473
|
declare function tabChallengeMiddleware(config: TabChallengeConfig): RequestHandler;
|
|
308
474
|
|
|
309
|
-
|
|
475
|
+
/**
|
|
476
|
+
* Dual-rail tab seller: ONE middleware advertising BOTH payment rails in a
|
|
477
|
+
* single standard x402 v2 402 challenge —
|
|
478
|
+
*
|
|
479
|
+
* scheme 'tab' — agents open a freeze-protected tab and stream vouchers
|
|
480
|
+
* scheme 'exact' — one-shot buyers (and catalog verifiers, which cannot
|
|
481
|
+
* open tabs) pay per request
|
|
482
|
+
*
|
|
483
|
+
* Compose as the ONLY payment middleware on the route:
|
|
484
|
+
*
|
|
485
|
+
* app.get('/paid/x', tabOrExactMiddleware({ ... }), handler);
|
|
486
|
+
*
|
|
487
|
+
* In the handler: `(req as X402Request).x402` set -> the request was paid
|
|
488
|
+
* via exact (respond normally); otherwise `requireTab(req)` -> tab rail
|
|
489
|
+
* (charge via openSse meter).
|
|
490
|
+
*
|
|
491
|
+
* SECURITY: the exact rail passes requirements EXPLICITLY to verify/settle
|
|
492
|
+
* (built from OUR configured amount). X402Server's no-requirements fallback
|
|
493
|
+
* rebuilds them from the BUYER'S header amount on cache miss — an
|
|
494
|
+
* underpayment hole this middleware must never take (pinned in dual.test.ts).
|
|
495
|
+
*/
|
|
496
|
+
|
|
497
|
+
interface TabOrExactConfig {
|
|
498
|
+
/** For tab voucher verification (V6 session PDA reads). */
|
|
499
|
+
connection: Connection;
|
|
500
|
+
/** Seller pubkey — payTo on BOTH rails. */
|
|
501
|
+
sellerPubkey: string | PublicKey;
|
|
502
|
+
network: TabNetworkId;
|
|
503
|
+
/** Price per request, human units — identical on both rails. */
|
|
504
|
+
perUnit: HumanAmount;
|
|
505
|
+
facilitatorUrl?: string;
|
|
506
|
+
description?: string;
|
|
507
|
+
}
|
|
508
|
+
declare function tabOrExactMiddleware(config: TabOrExactConfig): RequestHandler;
|
|
509
|
+
|
|
510
|
+
export { type ChannelLedger, type ChannelLedgerEntry, FileChannelLedger, FileVoucherStore, InMemoryChannelLedger, InMemoryVoucherStore, InvalidRegistrationError, InvalidVoucherError, InvalidVoucherSignatureError, type OnChainLedgerSnapshot, OnChainVerificationError, type OpenSseOptions, type ParsedRegistration, ScopeViolationError, type SellerTab, type SseMeter, TAB_VOUCHER_HEADER, type TabChallengeConfig, type TabMiddlewareConfig, type TabMiddlewareOptions, type TabOrExactConfig, type VoucherStore, enforceScope, openSse, parseRegistration, requireTab, tabChallengeMiddleware, tabMiddleware, tabOrExactMiddleware, verifyRegistrationOnChain, verifyVoucherSignature };
|
|
@@ -1,7 +1,123 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { SignedVoucher, AtomicAmount, TabNetworkId, HumanAmount } from '@dexterai/vault/types';
|
|
2
2
|
import { RequestHandler, Request, Response } from 'express';
|
|
3
3
|
import { Connection, PublicKey } from '@solana/web3.js';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Durable per-channel seller ledger for OTS tab streaming.
|
|
7
|
+
*
|
|
8
|
+
* Supersedes VoucherStore: it persists the latest accepted voucher AND the
|
|
9
|
+
* one quantity the chain never sees — `deliveredCumulativeAtomic`, the
|
|
10
|
+
* cumulative service the meter has actually delivered on this channel across
|
|
11
|
+
* ALL requests. Monotonic, never reset. This is what closes the channel-reuse
|
|
12
|
+
* metering leak: the meter budgets each request against
|
|
13
|
+
* `signedCumulative − deliveredCumulative`, not the lifetime cumulative.
|
|
14
|
+
*
|
|
15
|
+
* Shape mirrors the on-chain SessionRegistration money ledger
|
|
16
|
+
* (spent / crystallized_cumulative / current_outstanding / last_locked_sequence)
|
|
17
|
+
* that already ships in V6, via the optional `onChain` snapshot. That field is
|
|
18
|
+
* RESERVED for the Step-4 lock/LockedClaim model (lock_voucher reads/writes
|
|
19
|
+
* those on-chain) — the off-chain meter does not populate it today. Reserving
|
|
20
|
+
* it here keeps the ledger forward-compatible without a later breaking change.
|
|
21
|
+
*
|
|
22
|
+
* The same durable state is the substrate resumeTab / stranded-tab recovery
|
|
23
|
+
* needs (last voucher + delivered baseline per channel).
|
|
24
|
+
*
|
|
25
|
+
* Single-stream lease (multi-instance boundary): the per-channel `lease`
|
|
26
|
+
* (tryAcquireLease/releaseLease) enforces ONE live stream per channel, the
|
|
27
|
+
* defense against the concurrent-same-channel over-delivery rug. The default
|
|
28
|
+
* InMemoryChannelLedger / FileChannelLedger acquire it atomically WITHIN one
|
|
29
|
+
* seller process (via the per-channel async lock). A seller running MULTIPLE
|
|
30
|
+
* instances behind a load balancer MUST either back ChannelLedger with a store
|
|
31
|
+
* that makes acquire atomic across processes (Redis `SET NX PX`, Postgres
|
|
32
|
+
* advisory lock / `INSERT ... ON CONFLICT`) or route a channel's requests to a
|
|
33
|
+
* consistent instance — otherwise two instances can each acquire the lease and
|
|
34
|
+
* the rug reopens.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Read-through cache of the on-chain SessionRegistration money ledger.
|
|
39
|
+
* RESERVED for Step 4 (lock_voucher / LockedClaim). Not populated by the
|
|
40
|
+
* off-chain meter today. All amounts are atomic (base units) strings.
|
|
41
|
+
*/
|
|
42
|
+
interface OnChainLedgerSnapshot {
|
|
43
|
+
spentAtomic: AtomicAmount;
|
|
44
|
+
crystallizedCumulativeAtomic: AtomicAmount;
|
|
45
|
+
currentOutstandingAtomic: AtomicAmount;
|
|
46
|
+
lastLockedSequence: number;
|
|
47
|
+
/** Unix seconds when this snapshot was read from chain. */
|
|
48
|
+
fetchedAtUnixSec: number;
|
|
49
|
+
}
|
|
50
|
+
interface ChannelLedgerEntry {
|
|
51
|
+
/**
|
|
52
|
+
* Latest accepted voucher (`payload.cumulativeAmount` is the signedCumulative),
|
|
53
|
+
* or `null` for a lease-only entry created when the first request on a channel
|
|
54
|
+
* acquires its single-stream lease BEFORE any voucher is persisted. The
|
|
55
|
+
* middleware writes the real voucher immediately after acquiring the lease, so
|
|
56
|
+
* a null `lastVoucher` is only ever a transient pre-first-voucher state.
|
|
57
|
+
*/
|
|
58
|
+
lastVoucher: SignedVoucher | null;
|
|
59
|
+
/**
|
|
60
|
+
* Off-chain cumulative the meter has DELIVERED on this channel across all
|
|
61
|
+
* requests. Monotonic; never reset. The leak-fix field.
|
|
62
|
+
*/
|
|
63
|
+
deliveredCumulativeAtomic: AtomicAmount;
|
|
64
|
+
/**
|
|
65
|
+
* Delivered cumulative (atomic) that the seller has already crystallized into
|
|
66
|
+
* an on-chain LockedClaim via the keyless `/tab/lock` cadence (Step-4). The
|
|
67
|
+
* crystallization cadence fires when `deliveredCumulativeAtomic −
|
|
68
|
+
* lastCrystallizedCumulativeAtomic` crosses the configured threshold, then
|
|
69
|
+
* advances this on a successful lock so it can't double-fire. Treated as
|
|
70
|
+
* `'0'` when absent (older entries / lease-only entries). Optional so
|
|
71
|
+
* pre-Step-4 ledger constructors remain valid without a breaking change.
|
|
72
|
+
*/
|
|
73
|
+
lastCrystallizedCumulativeAtomic?: AtomicAmount;
|
|
74
|
+
/** RESERVED (Step 4): on-chain money ledger snapshot. Unset today. */
|
|
75
|
+
onChain?: OnChainLedgerSnapshot;
|
|
76
|
+
/**
|
|
77
|
+
* Active-stream lease. Set while a meter is live on this channel; cleared on
|
|
78
|
+
* the meter's terminal path. `heldUntilUnixMs` is a TTL so a crashed holder's
|
|
79
|
+
* lease auto-expires (a stuck lease would otherwise block the buyer's own
|
|
80
|
+
* next request on this tab). Enforces one live stream per channel — the
|
|
81
|
+
* defense against the concurrent-same-channel over-delivery rug.
|
|
82
|
+
*/
|
|
83
|
+
lease?: {
|
|
84
|
+
heldUntilUnixMs: number;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
interface ChannelLedger {
|
|
88
|
+
get(channelId: string): Promise<ChannelLedgerEntry | null>;
|
|
89
|
+
set(channelId: string, entry: ChannelLedgerEntry): Promise<void>;
|
|
90
|
+
delete(channelId: string): Promise<void>;
|
|
91
|
+
/**
|
|
92
|
+
* Atomically acquire the channel's single-stream lease if free or expired.
|
|
93
|
+
* Returns true if acquired, false if another live stream holds it. The
|
|
94
|
+
* in-process/file impls serialize via the per-channel lock (correct for a
|
|
95
|
+
* single seller process). A multi-instance seller MUST back this with a store
|
|
96
|
+
* that makes acquire atomic across processes (Redis SETNX, Postgres, ...).
|
|
97
|
+
*/
|
|
98
|
+
tryAcquireLease(channelId: string, ttlMs: number): Promise<boolean>;
|
|
99
|
+
/** Release the channel's lease (no-op if not held). */
|
|
100
|
+
releaseLease(channelId: string): Promise<void>;
|
|
101
|
+
}
|
|
102
|
+
declare class InMemoryChannelLedger implements ChannelLedger {
|
|
103
|
+
private map;
|
|
104
|
+
get(channelId: string): Promise<ChannelLedgerEntry | null>;
|
|
105
|
+
set(channelId: string, entry: ChannelLedgerEntry): Promise<void>;
|
|
106
|
+
delete(channelId: string): Promise<void>;
|
|
107
|
+
tryAcquireLease(channelId: string, ttlMs: number): Promise<boolean>;
|
|
108
|
+
releaseLease(channelId: string): Promise<void>;
|
|
109
|
+
}
|
|
110
|
+
declare class FileChannelLedger implements ChannelLedger {
|
|
111
|
+
private readonly dir;
|
|
112
|
+
constructor(dir: string);
|
|
113
|
+
private pathFor;
|
|
114
|
+
get(channelId: string): Promise<ChannelLedgerEntry | null>;
|
|
115
|
+
set(channelId: string, entry: ChannelLedgerEntry): Promise<void>;
|
|
116
|
+
delete(channelId: string): Promise<void>;
|
|
117
|
+
tryAcquireLease(channelId: string, ttlMs: number): Promise<boolean>;
|
|
118
|
+
releaseLease(channelId: string): Promise<void>;
|
|
119
|
+
}
|
|
120
|
+
|
|
5
121
|
/**
|
|
6
122
|
* @dexterai/x402/tab/seller — types for the seller side of OTS tab streaming.
|
|
7
123
|
*
|
|
@@ -17,6 +133,7 @@ import { Connection, PublicKey } from '@solana/web3.js';
|
|
|
17
133
|
* loses at most the last in-flight voucher's worth of revenue. Pluggable to
|
|
18
134
|
* match `batch-settlement/store`'s ChannelStore pattern.
|
|
19
135
|
*/
|
|
136
|
+
/** @deprecated Superseded by ChannelLedger (channel-ledger.ts), which also persists deliveredCumulative. */
|
|
20
137
|
interface VoucherStore {
|
|
21
138
|
get(channelId: string): Promise<SignedVoucher | null>;
|
|
22
139
|
set(channelId: string, voucher: SignedVoucher): Promise<void>;
|
|
@@ -39,6 +156,19 @@ interface SellerTab {
|
|
|
39
156
|
* monotonicity check fails. The middleware persists on success.
|
|
40
157
|
*/
|
|
41
158
|
charge(incrementHuman: HumanAmount): Promise<void>;
|
|
159
|
+
/**
|
|
160
|
+
* Off-chain cumulative (human amount) the meter has DELIVERED on this
|
|
161
|
+
* channel across ALL requests, read from the ChannelLedger at request start.
|
|
162
|
+
* The meter's per-request budget is `cumulative() − deliveredCumulative()`.
|
|
163
|
+
*/
|
|
164
|
+
deliveredCumulative(): HumanAmount;
|
|
165
|
+
/**
|
|
166
|
+
* Add `incrementAtomic` (this request's delivered amount, atomic) to the
|
|
167
|
+
* channel's durable lifetime delivered total, under a per-channel lock.
|
|
168
|
+
* Monotonic — a non-positive increment is a no-op. Called by the meter once
|
|
169
|
+
* per request on the terminal path (end / cap-reject / disconnect).
|
|
170
|
+
*/
|
|
171
|
+
recordDelivered(incrementAtomic: AtomicAmount): Promise<void>;
|
|
42
172
|
}
|
|
43
173
|
/** Options for `tabMiddleware`. */
|
|
44
174
|
interface TabMiddlewareOptions {
|
|
@@ -48,16 +178,42 @@ interface TabMiddlewareOptions {
|
|
|
48
178
|
network: TabNetworkId;
|
|
49
179
|
/** When to settle on chain: at tab close (the common case) vs periodically. */
|
|
50
180
|
settle: 'on-close' | 'periodic';
|
|
51
|
-
/** Facilitator base URL. Default: https://
|
|
181
|
+
/** Facilitator base URL. Default: DEFAULT_FACILITATOR_URL (https://x402.dexter.cash). */
|
|
52
182
|
facilitatorUrl?: string;
|
|
53
|
-
/**
|
|
54
|
-
|
|
183
|
+
/**
|
|
184
|
+
* Durable per-channel state (latest voucher + delivered cumulative).
|
|
185
|
+
* Default: in-memory (loses state on restart). Pass a FileChannelLedger or
|
|
186
|
+
* your own ChannelLedger for restart-safe revenue + resumeTab support.
|
|
187
|
+
*/
|
|
188
|
+
ledger?: ChannelLedger;
|
|
189
|
+
/**
|
|
190
|
+
* Max single-stream duration before a crashed holder's lease auto-expires.
|
|
191
|
+
* Default 300000 (5 min).
|
|
192
|
+
*/
|
|
193
|
+
leaseTtlMs?: number;
|
|
55
194
|
/**
|
|
56
195
|
* Hard cap on a single voucher's incremental amount. Protects the seller's
|
|
57
196
|
* middleware from accepting a buyer trying to slip in a giant single
|
|
58
197
|
* voucher. Default: 100x `perUnit`.
|
|
59
198
|
*/
|
|
60
199
|
maxPerVoucherAtomic?: AtomicAmount;
|
|
200
|
+
/**
|
|
201
|
+
* Keyless crystallization cadence (Step-4 lock-mode). On the configured
|
|
202
|
+
* delivered-amount threshold — and at tab close — the meter POSTs the
|
|
203
|
+
* buyer's already-stored signed voucher to `${facilitatorUrl}/tab/lock`,
|
|
204
|
+
* crystallizing it into an on-chain LockedClaim. BEST-EFFORT: a failed
|
|
205
|
+
* crystallize never blocks or errors the seller's response; a missed lock
|
|
206
|
+
* just widens the seller's unsecured window (their risk dial).
|
|
207
|
+
*
|
|
208
|
+
* Defaults when omitted: `{ thresholdAtomic: humanToAtomic('0.10'),
|
|
209
|
+
* onClose: true }`. Set `thresholdAtomic` higher to crystallize less often
|
|
210
|
+
* (cheaper, wider window) or lower to lock more aggressively. Set
|
|
211
|
+
* `onClose: false` to skip the close-time lock.
|
|
212
|
+
*/
|
|
213
|
+
lockCadence?: {
|
|
214
|
+
thresholdAtomic?: string;
|
|
215
|
+
onClose?: boolean;
|
|
216
|
+
};
|
|
61
217
|
}
|
|
62
218
|
/**
|
|
63
219
|
* Options for `openSse` — the Express response → SSE stream helper. Returns
|
|
@@ -76,12 +232,12 @@ interface OpenSseOptions {
|
|
|
76
232
|
interface SseMeter {
|
|
77
233
|
charge(units?: number): Promise<void>;
|
|
78
234
|
send(chunk: string | Uint8Array): void;
|
|
79
|
-
end(): void
|
|
235
|
+
end(): Promise<void>;
|
|
80
236
|
}
|
|
81
237
|
/** Errors thrown by the seller middleware on bad vouchers. */
|
|
82
238
|
declare class InvalidVoucherError extends Error {
|
|
83
|
-
readonly reason: 'signature_invalid' | 'registration_invalid' | 'cap_exceeded' | 'session_expired' | 'wrong_counterparty' | 'non_monotonic';
|
|
84
|
-
constructor(reason: 'signature_invalid' | 'registration_invalid' | 'cap_exceeded' | 'session_expired' | 'wrong_counterparty' | 'non_monotonic', detail?: string);
|
|
239
|
+
readonly reason: 'signature_invalid' | 'registration_invalid' | 'cap_exceeded' | 'session_expired' | 'wrong_counterparty' | 'non_monotonic' | 'channel_busy';
|
|
240
|
+
constructor(reason: 'signature_invalid' | 'registration_invalid' | 'cap_exceeded' | 'session_expired' | 'wrong_counterparty' | 'non_monotonic' | 'channel_busy', detail?: string);
|
|
85
241
|
}
|
|
86
242
|
|
|
87
243
|
/**
|
|
@@ -148,6 +304,16 @@ declare function requireTab(req: Request): SellerTab;
|
|
|
148
304
|
* left for Phase 4+; the v3 meter ships the simpler "one voucher bounds
|
|
149
305
|
* the whole request" model, which is correct for any reasonable chunk
|
|
150
306
|
* count under a single per-request increment.
|
|
307
|
+
*
|
|
308
|
+
* Concurrency note: delivered accounting is exact for requests that run
|
|
309
|
+
* sequentially per channel (the normal case — an agent streams one request at
|
|
310
|
+
* a time per tab). Two GENUINELY concurrent streams on the SAME channel each
|
|
311
|
+
* read the same delivered baseline, so they can over-deliver in-flight up to
|
|
312
|
+
* the sum of their budgets before either persists. The lifetime ledger stays
|
|
313
|
+
* correct (additive under a per-channel lock), so the over-delivery is bounded
|
|
314
|
+
* to the overlap and never compounds across future requests. Sellers needing
|
|
315
|
+
* exact metering under parallel same-channel streams should serialize requests
|
|
316
|
+
* per channel.
|
|
151
317
|
*/
|
|
152
318
|
|
|
153
319
|
declare function openSse(res: Response, options: OpenSseOptions): SseMeter;
|
|
@@ -306,4 +472,39 @@ interface TabChallengeConfig {
|
|
|
306
472
|
}
|
|
307
473
|
declare function tabChallengeMiddleware(config: TabChallengeConfig): RequestHandler;
|
|
308
474
|
|
|
309
|
-
|
|
475
|
+
/**
|
|
476
|
+
* Dual-rail tab seller: ONE middleware advertising BOTH payment rails in a
|
|
477
|
+
* single standard x402 v2 402 challenge —
|
|
478
|
+
*
|
|
479
|
+
* scheme 'tab' — agents open a freeze-protected tab and stream vouchers
|
|
480
|
+
* scheme 'exact' — one-shot buyers (and catalog verifiers, which cannot
|
|
481
|
+
* open tabs) pay per request
|
|
482
|
+
*
|
|
483
|
+
* Compose as the ONLY payment middleware on the route:
|
|
484
|
+
*
|
|
485
|
+
* app.get('/paid/x', tabOrExactMiddleware({ ... }), handler);
|
|
486
|
+
*
|
|
487
|
+
* In the handler: `(req as X402Request).x402` set -> the request was paid
|
|
488
|
+
* via exact (respond normally); otherwise `requireTab(req)` -> tab rail
|
|
489
|
+
* (charge via openSse meter).
|
|
490
|
+
*
|
|
491
|
+
* SECURITY: the exact rail passes requirements EXPLICITLY to verify/settle
|
|
492
|
+
* (built from OUR configured amount). X402Server's no-requirements fallback
|
|
493
|
+
* rebuilds them from the BUYER'S header amount on cache miss — an
|
|
494
|
+
* underpayment hole this middleware must never take (pinned in dual.test.ts).
|
|
495
|
+
*/
|
|
496
|
+
|
|
497
|
+
interface TabOrExactConfig {
|
|
498
|
+
/** For tab voucher verification (V6 session PDA reads). */
|
|
499
|
+
connection: Connection;
|
|
500
|
+
/** Seller pubkey — payTo on BOTH rails. */
|
|
501
|
+
sellerPubkey: string | PublicKey;
|
|
502
|
+
network: TabNetworkId;
|
|
503
|
+
/** Price per request, human units — identical on both rails. */
|
|
504
|
+
perUnit: HumanAmount;
|
|
505
|
+
facilitatorUrl?: string;
|
|
506
|
+
description?: string;
|
|
507
|
+
}
|
|
508
|
+
declare function tabOrExactMiddleware(config: TabOrExactConfig): RequestHandler;
|
|
509
|
+
|
|
510
|
+
export { type ChannelLedger, type ChannelLedgerEntry, FileChannelLedger, FileVoucherStore, InMemoryChannelLedger, InMemoryVoucherStore, InvalidRegistrationError, InvalidVoucherError, InvalidVoucherSignatureError, type OnChainLedgerSnapshot, OnChainVerificationError, type OpenSseOptions, type ParsedRegistration, ScopeViolationError, type SellerTab, type SseMeter, TAB_VOUCHER_HEADER, type TabChallengeConfig, type TabMiddlewareConfig, type TabMiddlewareOptions, type TabOrExactConfig, type VoucherStore, enforceScope, openSse, parseRegistration, requireTab, tabChallengeMiddleware, tabMiddleware, tabOrExactMiddleware, verifyRegistrationOnChain, verifyVoucherSignature };
|