@t3foundry/tasra-sdk 0.3.1-next.1 → 0.4.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 +1067 -28
- package/README.md +15 -0
- package/dist/app/approvals.d.ts +66 -4
- package/dist/app/approvals.js +153 -16
- package/dist/app/authorization.d.ts +1 -1
- package/dist/app/authorization.js +1 -1
- package/dist/app/browser.d.ts +63 -0
- package/dist/app/browser.js +242 -0
- package/dist/app/client.d.ts +114 -13
- package/dist/app/client.js +302 -76
- package/dist/app/identity.js +21 -9
- package/dist/app/index.d.ts +28 -3
- package/dist/app/index.js +16 -1
- package/dist/app/memory-store.d.ts +7 -0
- package/dist/app/memory-store.js +55 -0
- package/dist/app/node.d.ts +34 -6
- package/dist/app/node.js +387 -64
- package/dist/app/paid-allowance.d.ts +325 -0
- package/dist/app/paid-allowance.js +1290 -0
- package/dist/app/paid-approval.d.ts +122 -0
- package/dist/app/paid-approval.js +379 -0
- package/dist/app/paid-journal.d.ts +51 -0
- package/dist/app/paid-journal.js +117 -0
- package/dist/app/paid-keys.d.ts +12 -0
- package/dist/app/paid-keys.js +20 -0
- package/dist/app/paid-operation.d.ts +821 -0
- package/dist/app/paid-operation.js +1720 -0
- package/dist/app/paid-reservation.d.ts +157 -0
- package/dist/app/paid-reservation.js +323 -0
- package/dist/app/paid-session.d.ts +147 -0
- package/dist/app/paid-session.js +578 -0
- package/dist/app/payer-queue.d.ts +11 -0
- package/dist/app/payer-queue.js +27 -0
- package/dist/app/policy-bootstrap.d.ts +342 -0
- package/dist/app/policy-bootstrap.js +365 -0
- package/dist/app/policy-operation.d.ts +47 -0
- package/dist/app/policy-operation.js +101 -0
- package/dist/app/ready-slot.d.ts +12 -0
- package/dist/app/ready-slot.js +5 -2
- package/dist/app/rotation-lock.d.ts +38 -0
- package/dist/app/rotation-lock.js +42 -0
- package/dist/app/session-decrypt.d.ts +135 -0
- package/dist/app/session-decrypt.js +335 -0
- package/dist/app/session-grants.d.ts +349 -0
- package/dist/app/session-grants.js +811 -0
- package/dist/app/signing-intents.d.ts +78 -0
- package/dist/app/signing-intents.js +95 -0
- package/dist/app/store-commit.d.ts +63 -0
- package/dist/app/store-commit.js +126 -0
- package/dist/app/store-errors.d.ts +8 -0
- package/dist/app/store-errors.js +11 -0
- package/dist/app/tasra-client.d.ts +2 -0
- package/dist/app/tasra-client.js +1 -1
- package/dist/app/wallet.js +4 -1
- package/dist/auth/holderProof.d.ts +3 -0
- package/dist/auth/holderProof.js +8 -7
- package/dist/auth/verifier.d.ts +4 -2
- package/dist/auth/verifier.js +5 -2
- package/dist/chain/abis/index.d.ts +6178 -4101
- package/dist/chain/abis/index.js +3 -0
- package/dist/chain/abis/keyRegistry.d.ts +256 -0
- package/dist/chain/abis/keyRegistry.js +333 -0
- package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
- package/dist/chain/abis/prepaidFaultOracle.js +413 -0
- package/dist/chain/abis/settlement.d.ts +2203 -703
- package/dist/chain/abis/settlement.js +2685 -764
- package/dist/chain/allowance.d.ts +358 -0
- package/dist/chain/allowance.js +800 -0
- package/dist/chain/billing.d.ts +85 -0
- package/dist/chain/billing.js +197 -0
- package/dist/chain/chainId.d.ts +13 -0
- package/dist/chain/chainId.js +26 -0
- package/dist/chain/client.d.ts +15 -1
- package/dist/chain/client.js +57 -1
- package/dist/chain/commitmentRecovery.d.ts +51 -0
- package/dist/chain/commitmentRecovery.js +38 -0
- package/dist/chain/committeeClient.d.ts +17 -10
- package/dist/chain/committeeClient.js +64 -16
- package/dist/chain/committeeDraw.d.ts +12 -0
- package/dist/chain/committeeDraw.js +56 -0
- package/dist/chain/custodyHealth.d.ts +212 -0
- package/dist/chain/custodyHealth.js +365 -0
- package/dist/chain/deployments.js +2 -0
- package/dist/chain/events.js +2 -0
- package/dist/chain/headFollower.d.ts +77 -0
- package/dist/chain/headFollower.js +219 -0
- package/dist/chain/headPrefetch.d.ts +23 -0
- package/dist/chain/headPrefetch.js +67 -0
- package/dist/chain/index.d.ts +50 -8
- package/dist/chain/index.js +28 -3
- package/dist/chain/keeperExecution.d.ts +44 -0
- package/dist/chain/keeperExecution.js +127 -0
- package/dist/chain/keeperRecovery.d.ts +78 -0
- package/dist/chain/keeperRecovery.js +91 -0
- package/dist/chain/node.d.ts +24 -1
- package/dist/chain/node.js +88 -43
- package/dist/chain/offchain.d.ts +2 -0
- package/dist/chain/paidAgentTransport.d.ts +38 -0
- package/dist/chain/paidAgentTransport.js +1 -0
- package/dist/chain/paidEpoch.d.ts +66 -0
- package/dist/chain/paidEpoch.js +139 -0
- package/dist/chain/paidPacing.d.ts +81 -0
- package/dist/chain/paidPacing.js +136 -0
- package/dist/chain/pinnedReads.d.ts +49 -0
- package/dist/chain/pinnedReads.js +218 -0
- package/dist/chain/prepaid.d.ts +383 -0
- package/dist/chain/prepaid.js +1046 -0
- package/dist/chain/prepaidEscape.d.ts +274 -0
- package/dist/chain/prepaidEscape.js +432 -0
- package/dist/chain/prepaidFault.d.ts +94 -0
- package/dist/chain/prepaidFault.js +148 -0
- package/dist/chain/receipt.d.ts +24 -0
- package/dist/chain/receipt.js +82 -0
- package/dist/chain/registeredAgent.d.ts +68 -3
- package/dist/chain/registeredAgent.js +143 -42
- package/dist/chain/registeredOperation.d.ts +10 -1
- package/dist/chain/registeredOperation.js +18 -3
- package/dist/chain/registeredPaidAgent.d.ts +254 -0
- package/dist/chain/registeredPaidAgent.js +889 -0
- package/dist/chain/registeredRelay.d.ts +31 -1
- package/dist/chain/registeredRelay.js +164 -43
- package/dist/chain/relayVoucher.d.ts +64 -0
- package/dist/chain/relayVoucher.js +69 -0
- package/dist/chain/reservation.d.ts +239 -0
- package/dist/chain/reservation.js +746 -0
- package/dist/chain/reshareRoster.d.ts +64 -0
- package/dist/chain/reshareRoster.js +85 -0
- package/dist/chain/revertReason.d.ts +8 -0
- package/dist/chain/revertReason.js +2 -1
- package/dist/chain/rotationLock.d.ts +130 -0
- package/dist/chain/rotationLock.js +168 -0
- package/dist/chain/serviceRequestPolicy.d.ts +47 -0
- package/dist/chain/serviceRequestPolicy.js +86 -0
- package/dist/chain/services.d.ts +7 -0
- package/dist/chain/services.js +44 -4
- package/dist/chain/slotClient.js +11 -2
- package/dist/chain/slotHandoff.d.ts +81 -0
- package/dist/chain/slotHandoff.js +166 -0
- package/dist/chain/slotSeed.d.ts +47 -5
- package/dist/chain/slotSeed.js +173 -42
- package/dist/chain/verifierSnapshot.d.ts +36 -0
- package/dist/chain/verifierSnapshot.js +197 -0
- package/dist/chain/write.d.ts +111 -21
- package/dist/chain/write.js +378 -146
- package/dist/committee/blsSharing.d.ts +53 -0
- package/dist/committee/blsSharing.js +90 -0
- package/dist/committee/client.d.ts +62 -23
- package/dist/committee/client.js +288 -72
- package/dist/committee/dual-operation.d.ts +165 -0
- package/dist/committee/dual-operation.js +229 -0
- package/dist/committee/dual-sign.d.ts +26 -1
- package/dist/committee/dual-sign.js +85 -7
- package/dist/committee/ecdsa.d.ts +38 -0
- package/dist/committee/ecdsa.js +87 -15
- package/dist/committee/evidence.d.ts +30 -0
- package/dist/committee/evidence.js +65 -0
- package/dist/committee/execution.d.ts +414 -0
- package/dist/committee/execution.js +446 -0
- package/dist/committee/extraction.js +33 -26
- package/dist/committee/index.d.ts +30 -7
- package/dist/committee/index.js +18 -6
- package/dist/committee/keeperExecution.d.ts +37 -0
- package/dist/committee/keeperExecution.js +141 -0
- package/dist/committee/oauth.d.ts +14 -4
- package/dist/committee/oauth.js +17 -5
- package/dist/committee/payment.d.ts +369 -0
- package/dist/committee/payment.js +339 -0
- package/dist/committee/recovery.d.ts +136 -0
- package/dist/committee/recovery.js +204 -0
- package/dist/committee/recoveryJson.d.ts +2 -0
- package/dist/committee/recoveryJson.js +87 -0
- package/dist/committee/request.d.ts +63 -27
- package/dist/committee/request.js +77 -66
- package/dist/committee/session-grant.d.ts +320 -0
- package/dist/committee/session-grant.js +397 -0
- package/dist/committee/status-refresh.d.ts +257 -0
- package/dist/committee/status-refresh.js +619 -0
- package/dist/committee/token.d.ts +163 -15
- package/dist/committee/token.js +247 -10
- package/dist/crypto/bn254.d.ts +70 -0
- package/dist/crypto/bn254.js +222 -0
- package/dist/crypto/ibe.d.ts +32 -0
- package/dist/crypto/ibe.js +56 -8
- package/dist/crypto/index.d.ts +1 -1
- package/dist/crypto/index.js +1 -1
- package/dist/crypto/kem.d.ts +31 -0
- package/dist/crypto/kem.js +113 -7
- package/dist/crypto/recipient.d.ts +75 -0
- package/dist/crypto/recipient.js +107 -0
- package/dist/decryption/client.d.ts +10 -16
- package/dist/decryption/client.js +8 -76
- package/dist/decryption/index.d.ts +2 -0
- package/dist/decryption/index.js +2 -0
- package/dist/decryption/sealed.d.ts +72 -0
- package/dist/decryption/sealed.js +147 -0
- package/dist/decryption/session.d.ts +115 -0
- package/dist/decryption/session.js +358 -0
- package/dist/errors.d.ts +406 -1
- package/dist/errors.js +400 -5
- package/dist/index.d.ts +9 -2
- package/dist/index.js +6 -1
- package/dist/internal/bounded.d.ts +66 -0
- package/dist/internal/bounded.js +126 -0
- package/dist/internal/network.d.ts +4 -0
- package/dist/internal/network.js +40 -0
- package/dist/internal/retryAfter.d.ts +8 -0
- package/dist/internal/retryAfter.js +28 -0
- package/dist/internal/sleep.d.ts +6 -0
- package/dist/internal/sleep.js +15 -0
- package/dist/internal/typedData.d.ts +13 -0
- package/dist/internal/typedData.js +77 -0
- package/dist/internal/viemErrors.d.ts +26 -0
- package/dist/internal/viemErrors.js +49 -0
- package/dist/oid4vp/binding.d.ts +27 -1
- package/dist/oid4vp/binding.js +36 -1
- package/dist/oid4vp/jose.d.ts +4 -2
- package/dist/oid4vp/jose.js +39 -7
- package/dist/oid4vp/request-object.d.ts +61 -4
- package/dist/oid4vp/request-object.js +140 -5
- package/dist/oid4vp/verifier-agent.d.ts +18 -8
- package/dist/oid4vp/verifier-agent.js +48 -6
- package/dist/oid4vp/wallet.d.ts +2 -4
- package/dist/oid4vp/wallet.js +1 -0
- package/dist/retry.d.ts +78 -0
- package/dist/retry.js +137 -0
- package/dist/signing/frost.d.ts +1 -1
- package/dist/verifier-agent/index.d.ts +41 -5
- package/dist/verifier-agent/index.js +124 -9
- package/dist/verifier-agent/payment.d.ts +7 -0
- package/dist/verifier-agent/payment.js +17 -0
- package/docs/api.md +8 -2
- package/docs/application-api.md +25 -2
- package/docs/chain.md +155 -9
- package/docs/consumer-migrations.md +61 -0
- package/docs/encrypted-notes.md +3 -2
- package/docs/encryption.md +4 -2
- package/docs/errors.md +14 -1
- package/docs/flows.md +2 -2
- package/docs/funding.md +902 -0
- package/docs/native-approvals.md +63 -0
- package/docs/reference/README.md +9 -8
- package/docs/reference/app-browser.md +232 -0
- package/docs/reference/app-node.md +38 -8
- package/docs/reference/app.md +4621 -805
- package/docs/reference/chain-node.md +74 -16
- package/docs/reference/chain.md +6740 -1592
- package/docs/reference/committee.md +5630 -987
- package/docs/reference/main.md +1439 -140
- package/docs/reference/oid4vp.md +297 -144
- package/docs/reference/verifier-agent.md +77 -35
- package/docs/signing.md +6 -0
- package/examples/encrypted-notes.ts +21 -6
- package/examples/getting-started.ts +2 -7
- package/examples/live-config.ts +24 -17
- package/package.json +17 -5
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
// Client-side driver for one registered paid verifier-agent session.
|
|
2
|
+
//
|
|
3
|
+
// Every billable write (session creation, each operator-stage approval, the wallet
|
|
4
|
+
// presentation, each continuation) is journaled `prepared` in the application store before
|
|
5
|
+
// it is sent and `confirmed` after its reply. A write whose reply was lost stays `prepared`
|
|
6
|
+
// and is never sent again by this driver: the caller reconciles it. Creation's and an approval's
|
|
7
|
+
// `confirmed` are re-derived by a resume from what it reads anyway, so they ride on the drive's
|
|
8
|
+
// next durable write. Every other `confirmed` is published durably before the drive waits or
|
|
9
|
+
// polls after its send, or with the next commit when one follows at once; only a crash inside
|
|
10
|
+
// that short window leaves its write `prepared` (a resume then refuses it, as it does a write
|
|
11
|
+
// whose reply was lost).
|
|
12
|
+
// Services supply proposals, never client intent; every proposal is checked against the anchored draw.
|
|
13
|
+
//
|
|
14
|
+
// One exception, for operator-stage approvals only, when the store implements `claim`: the signed
|
|
15
|
+
// approval body is retained BEFORE its first send and, after a definite 429/503 (not processed),
|
|
16
|
+
// resent byte-identically under a durable generation-bound permit, inside the approval's signed
|
|
17
|
+
// expiry (paid-approval.ts). Repeatable reads are paced the same way by the session itself.
|
|
18
|
+
import { executionBodyHash } from '../committee/execution.js';
|
|
19
|
+
import { MAX_PROPOSAL_WAIT_MS, PaidAgentControlError } from '../chain/registeredPaidAgent.js';
|
|
20
|
+
import { reconcileRetainedApproval, retainAndDeliverApproval, retainAndDeliverApprovals, supportsDurableApproval } from './paid-approval.js';
|
|
21
|
+
import { isPaidBackoffError } from '../errors.js';
|
|
22
|
+
import { VerifierAgentSessionError } from '../verifier-agent/index.js';
|
|
23
|
+
import { Rederivable, withCommit } from './store-commit.js';
|
|
24
|
+
/** A retained write's outcome is unknown, or a resumed write differs from its original. */
|
|
25
|
+
export class PaidSessionRecoveryError extends Error {
|
|
26
|
+
key;
|
|
27
|
+
constructor(/** Journal entry that blocks the drive. */ key, message) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.key = key;
|
|
30
|
+
this.name = 'PaidSessionRecoveryError';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* SDK-internal: entries the caller journals with the drive's FIRST durable write (creation's
|
|
35
|
+
* `prepared`), under the extra locks and after the check, in the same commit. paid-operation.ts
|
|
36
|
+
* publishes the execution consent (`certified`) this way: a session's identity derives from that
|
|
37
|
+
* consent, so creation's record and the consent are useful only together, and nothing bound to the
|
|
38
|
+
* consent is sent before that commit. `published` is set once the commit resolved.
|
|
39
|
+
*/
|
|
40
|
+
export const FIRST_COMMIT = Symbol('paid-session-first-commit');
|
|
41
|
+
/** A held status poll that took this long ended on the agent's hold timer (20 s), not on a change. */
|
|
42
|
+
const HELD_POLL_ENDED_MS = 15_000;
|
|
43
|
+
const ABSENT_ANCHORS = ['no anchored verifier and accountant snapshots', 'no current or previous anchored verifier and accountant snapshots'];
|
|
44
|
+
/**
|
|
45
|
+
* Retry a read-only discovery while the verifier and accountant snapshots for the current epoch
|
|
46
|
+
* are not yet anchored. Only those two explicit outcomes are retried, before any reservation,
|
|
47
|
+
* consent or delivery; every other failure is final.
|
|
48
|
+
* @param read Discovery to run.
|
|
49
|
+
* @param signal Bounds the total wait.
|
|
50
|
+
* @param wait Delay between attempts.
|
|
51
|
+
*/
|
|
52
|
+
export async function waitForPaidSnapshot(read, signal, wait) {
|
|
53
|
+
for (;;) {
|
|
54
|
+
signal.throwIfAborted();
|
|
55
|
+
try {
|
|
56
|
+
return await read();
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
signal.throwIfAborted();
|
|
60
|
+
if (!(error instanceof Error) || !ABSENT_ANCHORS.includes(error.message))
|
|
61
|
+
throw error;
|
|
62
|
+
await wait();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function same(a, b) {
|
|
67
|
+
try {
|
|
68
|
+
return executionBodyHash(a) === executionBodyHash(b);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Drive one prepared paid session to a completed, verified committee token.
|
|
76
|
+
* Creation, request-object approval, presentation, continuation and credential approvals are
|
|
77
|
+
* each journaled before sending; an unknown outcome is never redelivered.
|
|
78
|
+
* @param options Session, anchored witnesses, store, holder strategy and pacing.
|
|
79
|
+
*/
|
|
80
|
+
export async function drivePaidSession(options) {
|
|
81
|
+
const { session, store, signal, wait, holder } = options;
|
|
82
|
+
const members = structuredClone([...options.members]), prefix = (options.journalPrefix ?? 'wallet-') + session.sessionId;
|
|
83
|
+
const resume = options.resume === true;
|
|
84
|
+
const first = options[FIRST_COMMIT];
|
|
85
|
+
if (!/^[0-9a-f]{64}$/.test(session.sessionId))
|
|
86
|
+
throw new Error('Invalid original SDK session');
|
|
87
|
+
if (!members.length || new Set(members.map(m => m.publicKey.toLowerCase())).size !== members.length)
|
|
88
|
+
throw new Error('Original drawn witnesses must be distinct');
|
|
89
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,40}$/.test(options.journalPrefix ?? 'wallet-'))
|
|
90
|
+
throw new Error('Invalid paid session journal prefix');
|
|
91
|
+
// Confirmations of this drive's writes, published with its next durable write (or at its end).
|
|
92
|
+
// Creation's and an approval's are re-derived by a resume from what it reads anyway (creation:
|
|
93
|
+
// the authenticated read every resumed drive makes; an approval: its delivery state). Every
|
|
94
|
+
// other write's is OWED (Rederivable): a resume does NOT re-derive it, and a crash before it is
|
|
95
|
+
// durable leaves the write `prepared`, which a resume refuses. It rides on the next commit only
|
|
96
|
+
// when that commit follows its send at once (the external acceptance's on its continuation's
|
|
97
|
+
// `prepared`; a first continuation's on the credential approval, after only the listing of the
|
|
98
|
+
// proposals its 425 created; when nothing is listed yet, the loop's `owed()` publishes it before
|
|
99
|
+
// the drive waits). Before any wait or poll that follows a send (a wallet callback can take
|
|
100
|
+
// minutes) `owed()` publishes it in one durable commit, so no wait leaves a sent write's
|
|
101
|
+
// outcome only in memory.
|
|
102
|
+
const later = new Rederivable();
|
|
103
|
+
/** Publish owed confirmations durably now: before a wait or poll that follows a send. */
|
|
104
|
+
const owed = () => later.flushOwed(store);
|
|
105
|
+
/** The record of `key` as this drive will publish it: a pending confirmation, else the store's. */
|
|
106
|
+
const journaled = async (key) => later.peek(key) ?? await store.load(key);
|
|
107
|
+
// Every read of a journal record this drive may have written goes through `journaled`: a
|
|
108
|
+
// confirmation still pending in memory is the record's current state (reading the store instead
|
|
109
|
+
// would see its `prepared` and refuse the drive's own confirmed write).
|
|
110
|
+
/**
|
|
111
|
+
* Journal, send once, confirm. Returns false when a resumed drive skipped a confirmed original.
|
|
112
|
+
* `prepared` is committed with the unlock (one commit: its data flushed, renamed, the lock
|
|
113
|
+
* removed, the directory synced once), together with the confirmations pending from earlier
|
|
114
|
+
* writes; only then is the write sent, outside the lock. That is safe because the durable record
|
|
115
|
+
* itself now refuses every other driver (a first drive refuses any retained record; a resumed
|
|
116
|
+
* one refuses a `prepared` record it cannot recover), so nothing the lock guarded is ever
|
|
117
|
+
* repeated or replaced. A send that failed leaves `prepared`. `confirmed` is put on `later`.
|
|
118
|
+
*
|
|
119
|
+
* Creation (the only write with a read-only `recover`) journals the caller's first-commit
|
|
120
|
+
* entries with its `prepared`, and its confirmation is re-derivable.
|
|
121
|
+
*/
|
|
122
|
+
const attempt = async (name, original, work, recover,
|
|
123
|
+
/** Only for writes the agent provably did not process (a paced 429 run out): journal `unsent`, resendable byte-identically on resume. */
|
|
124
|
+
unsent) => {
|
|
125
|
+
signal.throwIfAborted();
|
|
126
|
+
const key = prefix + '-' + name;
|
|
127
|
+
const recoverable = recover !== undefined, journal = recoverable && first && !first.published ? first : undefined;
|
|
128
|
+
const ride = later.take();
|
|
129
|
+
let send = false, skipped;
|
|
130
|
+
try {
|
|
131
|
+
skipped = await withCommit(store, [key, ...journal?.lock ?? []], async (commit) => {
|
|
132
|
+
if (journal) {
|
|
133
|
+
await journal.check();
|
|
134
|
+
for (const [k, v] of journal.entries)
|
|
135
|
+
commit.stage(k, v);
|
|
136
|
+
}
|
|
137
|
+
const pending = ride.find(([k]) => k === key);
|
|
138
|
+
const retained = (pending ? structuredClone(pending[1]) : await store.load(key));
|
|
139
|
+
if (retained !== undefined) {
|
|
140
|
+
if (resume && retained?.phase === 'confirmed' && same(retained.original, original))
|
|
141
|
+
return false;
|
|
142
|
+
// Provably never processed: the same original bytes may go out once more (the record
|
|
143
|
+
// turns `prepared` in this commit first, so a concurrent drive refuses it).
|
|
144
|
+
const resendable = resume && unsent !== undefined && retained?.phase === 'unsent' && same(retained.original, original);
|
|
145
|
+
if (resume && retained?.phase === 'prepared' && same(retained.original, original) && recover) {
|
|
146
|
+
// Only creation supplies this read-only recovery. It checks the original
|
|
147
|
+
// provider, bearer and full context; no POST is repeated or replaced.
|
|
148
|
+
await recover();
|
|
149
|
+
signal.throwIfAborted();
|
|
150
|
+
commit.stage(key, { original: retained.original, phase: 'confirmed' });
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
if (!resendable)
|
|
154
|
+
throw new PaidSessionRecoveryError(key, retained?.phase === 'confirmed' && !resume
|
|
155
|
+
? 'Original paid write already attempted; reconcile it without redelivery'
|
|
156
|
+
: 'Original paid write already attempted with an unknown or different outcome; reconcile it without redelivery');
|
|
157
|
+
}
|
|
158
|
+
// Committed with the unlock: the record now refuses or recovers any other driver, so the
|
|
159
|
+
// send needs no lock (nothing it guards is ever repeated or replaced).
|
|
160
|
+
for (const [k, v] of ride)
|
|
161
|
+
commit.stage(k, v);
|
|
162
|
+
commit.stage(key, { original, phase: 'prepared' });
|
|
163
|
+
send = true;
|
|
164
|
+
return true;
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
later.restore(ride);
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
if (!send)
|
|
172
|
+
later.restore(ride);
|
|
173
|
+
if (journal)
|
|
174
|
+
journal.published = true;
|
|
175
|
+
if (!send)
|
|
176
|
+
return skipped;
|
|
177
|
+
signal.throwIfAborted();
|
|
178
|
+
// A crash or uncertain response retains prepared. No catch/retry deletes it.
|
|
179
|
+
try {
|
|
180
|
+
await work();
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
if (unsent?.(error)) {
|
|
184
|
+
// Established non-processing only: the record keeps the exact original, now `unsent`.
|
|
185
|
+
await withCommit(store, [key], async (commit) => {
|
|
186
|
+
const current = await store.load(key);
|
|
187
|
+
if (current?.phase === 'prepared' && same(current.original, original))
|
|
188
|
+
commit.stage(key, { original, phase: 'unsent' });
|
|
189
|
+
}).catch(() => { });
|
|
190
|
+
}
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
later.put(key, { original, phase: 'confirmed' }, { owed: !recoverable });
|
|
194
|
+
return true;
|
|
195
|
+
};
|
|
196
|
+
/** First durable approval of a stage; refuses, sending nothing, when a record appeared concurrently. */
|
|
197
|
+
const firstApproval = async (ctx, original, sign) => {
|
|
198
|
+
signal.throwIfAborted();
|
|
199
|
+
if (!await retainAndDeliverApproval(ctx, original, sign)) {
|
|
200
|
+
throw new PaidSessionRecoveryError(ctx.key, 'Original paid write already attempted with an unknown or different outcome; reconcile it without redelivery');
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
const approve = async (presentation, listed) => {
|
|
204
|
+
// Every proposal is judged before any is sent: an operator outside the draw or an invalid stage
|
|
205
|
+
// refuses the whole batch with nothing delivered. `listed` is a listing read beside a status poll.
|
|
206
|
+
const planned = (listed ?? await session.proposals(signal)).map(proposed => {
|
|
207
|
+
const member = members.find(m => m.publicKey.toLowerCase() === proposed.operator_key.toLowerCase());
|
|
208
|
+
if (!member)
|
|
209
|
+
throw new Error('Agent proposed an operator outside the original anchored draw');
|
|
210
|
+
if (!['presentation_sign', 'presentation_attest', 'credential'].includes(proposed.stage))
|
|
211
|
+
throw new Error('Invalid agent operator stage');
|
|
212
|
+
if (proposed.stage === 'credential' && !presentation)
|
|
213
|
+
throw new Error('Credential work requires the original locally accepted presentation');
|
|
214
|
+
if (proposed.stage !== 'credential' && presentation)
|
|
215
|
+
throw new Error('Unexpected new request-signing stage after credential disclosure');
|
|
216
|
+
return { proposed, member, name: proposed.stage + '-' + member.index };
|
|
217
|
+
});
|
|
218
|
+
// Distinct stages have distinct journal keys, signers and agent delivery rows: their approvals are
|
|
219
|
+
// independent and go out together (one round trip per batch, not one per operator). A batch that
|
|
220
|
+
// names one stage twice keeps the one-by-one order, where the second sees the first's journal.
|
|
221
|
+
const one = (item) => approveOne(item.proposed, item.member, item.name, presentation);
|
|
222
|
+
if (new Set(planned.map(p => p.name)).size !== planned.length) {
|
|
223
|
+
let count = 0;
|
|
224
|
+
for (const item of planned) {
|
|
225
|
+
signal.throwIfAborted();
|
|
226
|
+
count += await one(item);
|
|
227
|
+
}
|
|
228
|
+
return count;
|
|
229
|
+
}
|
|
230
|
+
signal.throwIfAborted();
|
|
231
|
+
// An agent advertising batch approvals takes a batch of FIRST approvals in one request. Each
|
|
232
|
+
// keeps its own signing, journal entry, permit and outcome (paid-approval.ts); only the send is
|
|
233
|
+
// shared. Anything else (one proposal, a retained record to reconcile, a store or session
|
|
234
|
+
// without durable approvals) goes one by one, as before.
|
|
235
|
+
if (planned.length > 1 && session.batchApprovals === true && typeof session.sendRetainedApprovals === 'function'
|
|
236
|
+
&& planned.every(p => supportsDurableApproval(store, session, prefix + '-' + p.name))
|
|
237
|
+
&& (await Promise.all(planned.map(p => journaled(prefix + '-' + p.name)))).every(r => r === undefined)) {
|
|
238
|
+
const kept = await retainAndDeliverApprovals(planned.map(({ proposed, member, name }) => {
|
|
239
|
+
const key = prefix + '-' + name;
|
|
240
|
+
const original = { stage: proposed.stage, operator_key: member.publicKey, unsigned_body: proposed.unsigned_body };
|
|
241
|
+
const stage = proposed.stage === 'presentation_sign' ? 'presentation_sign' : 'presentation_attest';
|
|
242
|
+
return { ctx: { store, session, key, signal, rederivable: later }, original, sign: proposed.stage === 'credential'
|
|
243
|
+
? () => session.prepareCredentialApproval(proposed, member, presentation, signal)
|
|
244
|
+
: () => session.prepareRequestApproval(proposed, stage, member, signal) };
|
|
245
|
+
}));
|
|
246
|
+
const raced = kept.findIndex(k => !k);
|
|
247
|
+
if (raced !== -1)
|
|
248
|
+
throw new PaidSessionRecoveryError(prefix + '-' + planned[raced].name, 'Original paid write already attempted with an unknown or different outcome; reconcile it without redelivery');
|
|
249
|
+
return planned.length;
|
|
250
|
+
}
|
|
251
|
+
const results = await Promise.allSettled(planned.map(one));
|
|
252
|
+
// Every send has settled (none is left in flight); report the first refusal in proposal order.
|
|
253
|
+
for (const result of results)
|
|
254
|
+
if (result.status === 'rejected')
|
|
255
|
+
throw result.reason;
|
|
256
|
+
return results.reduce((sum, result) => sum + (result.status === 'fulfilled' ? result.value : 0), 0);
|
|
257
|
+
};
|
|
258
|
+
/** Approve one judged proposal; 1 when it sent or reconciled an approval, 0 when already confirmed. */
|
|
259
|
+
const approveOne = async (proposed, member, name, presentation) => {
|
|
260
|
+
const key = prefix + '-' + name;
|
|
261
|
+
const retained = await journaled(key);
|
|
262
|
+
// A stage belongs to one operator and one original body. A new proposal ID
|
|
263
|
+
// cannot authorize another billable attempt on the same paid stage.
|
|
264
|
+
const original = { stage: proposed.stage, operator_key: member.publicKey, unsigned_body: proposed.unsigned_body };
|
|
265
|
+
// Durable approvals: the signed body is retained before the first send and resent only
|
|
266
|
+
// byte-identically under a generation-bound, exclusively claimed permit (see paid-approval.ts).
|
|
267
|
+
const durable = supportsDurableApproval(store, session, key);
|
|
268
|
+
const ctx = { store, session, key, signal, rederivable: later };
|
|
269
|
+
if (retained) {
|
|
270
|
+
if (!same(retained.original, original))
|
|
271
|
+
throw new PaidSessionRecoveryError(key, 'Agent changed an already approved operator stage');
|
|
272
|
+
if (retained.phase === 'confirmed')
|
|
273
|
+
return 0;
|
|
274
|
+
// A retained body may be reconciled on resume: confirmed if the agent already holds it,
|
|
275
|
+
// resent identically only while the agent shows it pending under a durable permit.
|
|
276
|
+
// A record without a retained body (an older SDK) or any unknown outcome still refuses.
|
|
277
|
+
if (!(resume && durable && retained.phase === 'prepared' && retained.approval !== undefined)) {
|
|
278
|
+
throw new PaidSessionRecoveryError(key, 'Original operator approval outcome is unknown; reconcile it');
|
|
279
|
+
}
|
|
280
|
+
await reconcileRetainedApproval(ctx, retained);
|
|
281
|
+
return 1;
|
|
282
|
+
}
|
|
283
|
+
if (proposed.stage === 'credential') {
|
|
284
|
+
if (durable)
|
|
285
|
+
await firstApproval(ctx, original, () => session.prepareCredentialApproval(proposed, member, presentation, signal));
|
|
286
|
+
else
|
|
287
|
+
await attempt(name, original, () => session.approveCredentials(proposed, member, presentation, signal));
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
const stage = proposed.stage === 'presentation_sign' ? 'presentation_sign' : 'presentation_attest';
|
|
291
|
+
if (durable)
|
|
292
|
+
await firstApproval(ctx, original, () => session.prepareRequestApproval(proposed, stage, member, signal));
|
|
293
|
+
else
|
|
294
|
+
await attempt(name, original, () => session.approveRequest(proposed, stage, member, signal));
|
|
295
|
+
}
|
|
296
|
+
return 1;
|
|
297
|
+
};
|
|
298
|
+
const pendingConsent = (error) => error instanceof PaidAgentControlError
|
|
299
|
+
&& error.sessionId === session.sessionId && error.httpStatus === 425;
|
|
300
|
+
const checkedPoll = async (held = false) => {
|
|
301
|
+
signal.throwIfAborted();
|
|
302
|
+
const status = await (held ? session.poll(signal, { wait: true }) : session.poll(signal));
|
|
303
|
+
if (status.status === 'failed')
|
|
304
|
+
throw new VerifierAgentSessionError('refused', session.sessionId, 'Original paid credential verification refused' + (status.error ? ': ' + status.error.slice(0, 500) : ''));
|
|
305
|
+
return status;
|
|
306
|
+
};
|
|
307
|
+
/**
|
|
308
|
+
* Wait, when this drive has nothing to send, until the session may have moved past `last`.
|
|
309
|
+
* While committee work is in flight (`verifying`) its end is a status or phase change the agent
|
|
310
|
+
* announces, so one held poll waits for it (O(1) on the agent) and its answer is returned for the
|
|
311
|
+
* drive to continue on at once. A held answer that came back at once unchanged (an agent without
|
|
312
|
+
* long-poll support) falls back to the caller's pacing, so no agent is polled in a loop; a held
|
|
313
|
+
* request that failed in transport returns nothing and the caller's next plain poll decides, as
|
|
314
|
+
* before. In any other phase (waiting for a wallet callback, which the agent does not announce)
|
|
315
|
+
* the caller's pacing applies unchanged. Returns the held answer, or undefined when it did not poll.
|
|
316
|
+
*/
|
|
317
|
+
const settle = async (last, hint) => {
|
|
318
|
+
if (last.phase === 'verifying') {
|
|
319
|
+
const started = Date.now();
|
|
320
|
+
let next;
|
|
321
|
+
try {
|
|
322
|
+
next = await checkedPoll(true);
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
if (signal.aborted || error instanceof VerifierAgentSessionError || error instanceof PaidAgentControlError)
|
|
326
|
+
throw error;
|
|
327
|
+
return undefined;
|
|
328
|
+
}
|
|
329
|
+
if (next.status !== 'pending' || next.phase !== last.phase || Date.now() - started >= HELD_POLL_ENDED_MS)
|
|
330
|
+
return next;
|
|
331
|
+
}
|
|
332
|
+
await wait(hint);
|
|
333
|
+
return undefined;
|
|
334
|
+
};
|
|
335
|
+
const resumeCallback = async (callback, approved) => {
|
|
336
|
+
try {
|
|
337
|
+
await session.resumePresentation(callback, approved, signal);
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
if (pendingConsent(error))
|
|
341
|
+
return;
|
|
342
|
+
// Admission can reject an expired credential with 400; a failed verifier run
|
|
343
|
+
// returns 409. Only the authenticated original session's terminal state proves
|
|
344
|
+
// refusal. Other errors stay unresolved and never cause another POST.
|
|
345
|
+
if (error instanceof PaidAgentControlError && error.sessionId === session.sessionId
|
|
346
|
+
&& (error.httpStatus === 400 || error.httpStatus === 409))
|
|
347
|
+
await checkedPoll();
|
|
348
|
+
throw error;
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
let drove;
|
|
352
|
+
try {
|
|
353
|
+
drove = await drive();
|
|
354
|
+
}
|
|
355
|
+
catch (error) {
|
|
356
|
+
// Best effort: each pending write is re-derivable, and the drive's own failure is what matters.
|
|
357
|
+
await later.flush(store).catch(() => { });
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
360
|
+
await later.flush(store);
|
|
361
|
+
return drove;
|
|
362
|
+
async function drive() {
|
|
363
|
+
let creationRecovered = false;
|
|
364
|
+
const created = await attempt('create', { sessionId: session.sessionId, paymentHash: session.paymentHash, initialization: session.initialization }, () => session.create(signal), async () => {
|
|
365
|
+
try {
|
|
366
|
+
await session.reconcile(signal);
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
signal.throwIfAborted();
|
|
370
|
+
// A failed read (including 404) does not prove that the original POST
|
|
371
|
+
// was refused. Preserve the uncertain creation and its application fence.
|
|
372
|
+
throw new Error('Original session creation cannot be verified; resume only this session', { cause: error });
|
|
373
|
+
}
|
|
374
|
+
creationRecovered = true;
|
|
375
|
+
});
|
|
376
|
+
// A resumed drive recovers the original public context by an authenticated read instead.
|
|
377
|
+
if (!created && !creationRecovered)
|
|
378
|
+
await session.reconcile(signal);
|
|
379
|
+
// An OAuth session has no request object and no JAR stages: the client presents its token.
|
|
380
|
+
const oauth = holder.kind === 'oauth' ? await presentOAuth(holder) : undefined;
|
|
381
|
+
const wallet = oauth ? undefined : await presentWallet();
|
|
382
|
+
const accepted = oauth ?? wallet.accepted;
|
|
383
|
+
const request = wallet?.request;
|
|
384
|
+
return observeCallbacks(accepted, request);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* The OAuth presentation, exactly once: a resumed drive continues with the retained original
|
|
388
|
+
* (confirmed, or reconciled by a read showing the agent retained it); a `prepared` one that no
|
|
389
|
+
* read accounts for refuses, and only a provably unprocessed (`unsent`) one is resent, with the
|
|
390
|
+
* same bytes. The holder's credential callback runs only when no presentation is journaled.
|
|
391
|
+
*/
|
|
392
|
+
async function presentOAuth(oauthHolder) {
|
|
393
|
+
const key = prefix + '-presentation';
|
|
394
|
+
const retained = await journaled(key);
|
|
395
|
+
const submit = (approved) => attempt('presentation', { oauth: approved }, async () => {
|
|
396
|
+
try {
|
|
397
|
+
await session.submitOAuthPresentation(approved, signal);
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
// A definite refusal of this session: its authenticated state says whether it failed.
|
|
401
|
+
if (error instanceof PaidAgentControlError && error.sessionId === session.sessionId && [400, 403, 409, 410].includes(error.httpStatus))
|
|
402
|
+
await checkedPoll();
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
405
|
+
}, undefined, isPaidBackoffError);
|
|
406
|
+
if (retained !== undefined) {
|
|
407
|
+
const original = retained.original?.oauth;
|
|
408
|
+
if (!resume || !original || original.oauth === null || original.oauth?.session_id !== session.sessionId) {
|
|
409
|
+
throw new PaidSessionRecoveryError(key, 'Original OAuth presentation already attempted; reconcile it without redelivery');
|
|
410
|
+
}
|
|
411
|
+
if (retained.phase === 'confirmed')
|
|
412
|
+
return structuredClone(original);
|
|
413
|
+
if (retained.phase === 'unsent') {
|
|
414
|
+
await submit(structuredClone(original));
|
|
415
|
+
return structuredClone(original);
|
|
416
|
+
}
|
|
417
|
+
// `prepared`: its reply was lost. Only a read that shows the agent holding exactly this
|
|
418
|
+
// presentation (or a session already past it) confirms it; nothing is ever sent again.
|
|
419
|
+
const [status, candidates] = await Promise.all([checkedPoll(), session.presentations(signal)]);
|
|
420
|
+
if (status.status === 'done' || candidates.some(c => same(c.presentation, original))) {
|
|
421
|
+
later.put(key, { original: retained.original, phase: 'confirmed' }, { owed: true });
|
|
422
|
+
return structuredClone(original);
|
|
423
|
+
}
|
|
424
|
+
throw new PaidSessionRecoveryError(key, 'Original OAuth presentation outcome is unknown; reconcile it without redelivery');
|
|
425
|
+
}
|
|
426
|
+
const context = session.oauthContext;
|
|
427
|
+
const credential = await oauthHolder.credential({ sessionId: session.sessionId, nonce: context.nonce, dpopHtu: context.dpopHtu, platformAudience: context.platformAudience });
|
|
428
|
+
signal.throwIfAborted();
|
|
429
|
+
// Verified locally (audience, time, cnf.jkt, nonce, htm, htu, ath, signature) before it is kept or sent.
|
|
430
|
+
const approved = structuredClone(await session.prepareOAuthPresentation(credential.accessToken, credential.signer, signal));
|
|
431
|
+
if (approved.oauth === null || approved.oauth.session_id !== session.sessionId || approved.credentials.length !== 0)
|
|
432
|
+
throw new Error('Invalid original OAuth presentation');
|
|
433
|
+
await submit(approved);
|
|
434
|
+
return approved;
|
|
435
|
+
}
|
|
436
|
+
/** The wallet paths: request-object approvals, then the local or external presentation. */
|
|
437
|
+
async function presentWallet() {
|
|
438
|
+
let opened;
|
|
439
|
+
for (;;) {
|
|
440
|
+
signal.throwIfAborted();
|
|
441
|
+
// A fetch after approvals waits for the signer: an approval sent without a durable body
|
|
442
|
+
// (an owed confirmation) is published first.
|
|
443
|
+
await owed();
|
|
444
|
+
try {
|
|
445
|
+
opened = await session.requestObject(signal);
|
|
446
|
+
break;
|
|
447
|
+
}
|
|
448
|
+
catch (error) {
|
|
449
|
+
if (!pendingConsent(error))
|
|
450
|
+
throw error;
|
|
451
|
+
// The status poll and the proposal listing are independent reads: read them together and
|
|
452
|
+
// judge the status first, so a failed session still refuses before anything is approved.
|
|
453
|
+
const [polled, listed] = await Promise.allSettled([checkedPoll(), session.proposals(signal)]);
|
|
454
|
+
if (polled.status === 'rejected')
|
|
455
|
+
throw polled.reason;
|
|
456
|
+
if (listed.status === 'rejected')
|
|
457
|
+
throw listed.reason;
|
|
458
|
+
const status = polled.value;
|
|
459
|
+
// Nothing listed yet from an agent that can hold the listing: ask it to answer when one is
|
|
460
|
+
// pending instead of pacing locally (the same owner-only read, judged the same way).
|
|
461
|
+
if (listed.value.length === 0 && session.proposalWait === true) {
|
|
462
|
+
const held = await session.proposals(signal, { waitMs: MAX_PROPOSAL_WAIT_MS });
|
|
463
|
+
if (await approve(undefined, held) > 0)
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
// 425 with proposals: once they are approved the next request-object fetch dispatches them
|
|
467
|
+
// (and waits for the signer), so fetch again at once. Otherwise wait for the session to move.
|
|
468
|
+
if (await approve(undefined, listed.value) > 0)
|
|
469
|
+
continue;
|
|
470
|
+
await settle(status, error.retryAfterMs);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
const request = opened.request;
|
|
474
|
+
// An optional observation completes before credential disclosure, on a detached copy.
|
|
475
|
+
await options.observeRequest?.(structuredClone(request));
|
|
476
|
+
signal.throwIfAborted();
|
|
477
|
+
let accepted;
|
|
478
|
+
const link = { requestUri: opened.requestUri, qrPayload: opened.qrPayload };
|
|
479
|
+
if (holder.kind === 'local') {
|
|
480
|
+
await holder.present?.({ request: structuredClone(request), ...link });
|
|
481
|
+
const retained = await store.load(prefix + '-presentation');
|
|
482
|
+
if (retained !== undefined && resume) {
|
|
483
|
+
// Never build or post a second presentation; continue with the original once it is confirmed.
|
|
484
|
+
if (retained?.phase !== 'confirmed' || !retained.original?.presentation?.approved)
|
|
485
|
+
throw new PaidSessionRecoveryError(prefix + '-presentation', 'Original presentation outcome is unknown; reconcile it without redelivery');
|
|
486
|
+
accepted = structuredClone(retained.original.presentation.approved);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (holder.kind === 'local' && !accepted) {
|
|
490
|
+
const presentation = structuredClone(await holder.makePresentation(structuredClone(request), { ...link }));
|
|
491
|
+
// Validate canonical plain JSON before persisting or disclosing credentials.
|
|
492
|
+
executionBodyHash(presentation.approved);
|
|
493
|
+
const keys = Object.keys(presentation.approved).sort();
|
|
494
|
+
if (keys.join(',') !== 'credentials,holder,holder_proof,iat,oauth' || presentation.approved.oauth !== null
|
|
495
|
+
|| !presentation.approved.credentials.length || !presentation.form.response)
|
|
496
|
+
throw new Error('Paid wallet requires the original encrypted credential presentation');
|
|
497
|
+
await attempt('presentation', { request: request.claims, presentation }, () => holder.submit(request, presentation));
|
|
498
|
+
accepted = presentation.approved;
|
|
499
|
+
}
|
|
500
|
+
else if (holder.kind === 'external') {
|
|
501
|
+
// Showing the request is not billable; a resumed drive shows it again.
|
|
502
|
+
await holder.present(structuredClone(opened));
|
|
503
|
+
const retained = await store.load(prefix + '-accepted');
|
|
504
|
+
if (retained) {
|
|
505
|
+
if (retained.phase !== 'confirmed' || !retained.original.presentation)
|
|
506
|
+
throw new PaidSessionRecoveryError(prefix + '-accepted', 'Original presentation acceptance is unknown; reconcile it');
|
|
507
|
+
accepted = retained.original.presentation;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return { accepted, request };
|
|
511
|
+
}
|
|
512
|
+
/** Accept the retained callback, continue it and approve the drawn verifiers' credential work until done. */
|
|
513
|
+
async function observeCallbacks(accepted, request) {
|
|
514
|
+
let callback;
|
|
515
|
+
let approvedCredentialCount = 0;
|
|
516
|
+
// The session status and the retained presentations are independent reads: each round reads them
|
|
517
|
+
// together and judges the status first (a done or failed session ends the drive before any write).
|
|
518
|
+
const observe = async (polled) => {
|
|
519
|
+
const [status, candidates] = await Promise.allSettled([polled ?? checkedPoll(), session.presentations(signal)]);
|
|
520
|
+
if (status.status === 'rejected')
|
|
521
|
+
throw status.reason;
|
|
522
|
+
return { status: status.value, candidates };
|
|
523
|
+
};
|
|
524
|
+
// The presentation was just sent; observing it can wait for the wallet callback.
|
|
525
|
+
await owed();
|
|
526
|
+
let observed = await observe();
|
|
527
|
+
for (;;) {
|
|
528
|
+
signal.throwIfAborted();
|
|
529
|
+
const status = observed.status;
|
|
530
|
+
if (status.status === 'done')
|
|
531
|
+
return status;
|
|
532
|
+
// Whether this round sent a write: its effect is read back at once instead of after a wait.
|
|
533
|
+
let progressed = false;
|
|
534
|
+
if (observed.candidates.status === 'rejected')
|
|
535
|
+
throw observed.candidates.reason;
|
|
536
|
+
const retainedCandidates = observed.candidates.value;
|
|
537
|
+
for (const candidate of retainedCandidates) {
|
|
538
|
+
if (!accepted) {
|
|
539
|
+
// External wallet: the client decides on the complete retained body, once.
|
|
540
|
+
if (holder.kind !== 'external' || !request)
|
|
541
|
+
throw new Error('Agent retained a presentation this client did not make');
|
|
542
|
+
if (!await holder.accept(structuredClone(candidate), structuredClone(request))) {
|
|
543
|
+
throw new VerifierAgentSessionError('refused', session.sessionId, 'Client refused the retained wallet presentation');
|
|
544
|
+
}
|
|
545
|
+
const chosen = structuredClone(candidate.presentation);
|
|
546
|
+
await attempt('accepted', { presentation: chosen, callback: candidate.id }, async () => { });
|
|
547
|
+
accepted = chosen;
|
|
548
|
+
}
|
|
549
|
+
if (!same(candidate.presentation, accepted))
|
|
550
|
+
throw new Error('Agent callback changed the original client presentation');
|
|
551
|
+
if (callback && callback !== candidate.id)
|
|
552
|
+
throw new Error('Agent changed the original retained callback');
|
|
553
|
+
callback = candidate.id;
|
|
554
|
+
}
|
|
555
|
+
if (callback && accepted) {
|
|
556
|
+
const approved = accepted;
|
|
557
|
+
const initial = await journaled(prefix + '-resume-initial');
|
|
558
|
+
if (!initial) {
|
|
559
|
+
// HTTP 425 is an explicit refusal to dispatch without client approval. It creates
|
|
560
|
+
// credential proposals; unknown transport outcomes still stop here.
|
|
561
|
+
progressed = await attempt('resume-initial', { callback, approved }, () => resumeCallback(callback, approved));
|
|
562
|
+
}
|
|
563
|
+
else if (initial.phase !== 'confirmed')
|
|
564
|
+
throw new PaidSessionRecoveryError(prefix + '-resume-initial', 'Original continuation outcome is unknown; reconcile it');
|
|
565
|
+
const approvals = await approve(approved);
|
|
566
|
+
if (approvals > 0) {
|
|
567
|
+
approvedCredentialCount += approvals;
|
|
568
|
+
await attempt('resume-' + approvedCredentialCount, { callback, approved }, () => resumeCallback(callback, approved));
|
|
569
|
+
progressed = true;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
// Each write is sent once, so `progressed` is true a bounded number of times. A continuation
|
|
573
|
+
// sent this round is confirmed durably before the next poll or wait.
|
|
574
|
+
await owed();
|
|
575
|
+
observed = await observe(progressed ? undefined : await settle(status));
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run `work` after every earlier call for the same payer identity has settled.
|
|
3
|
+
* @param identity Chain and payer, e.g. `43112-0xabc…`.
|
|
4
|
+
* @param work Reservation submission.
|
|
5
|
+
*/
|
|
6
|
+
export declare function withDedicatedPayer<T>(identity: string, work: () => Promise<T>): Promise<T>;
|
|
7
|
+
/**
|
|
8
|
+
* Whether this process has reservation work queued or running for a payer identity.
|
|
9
|
+
* @param identity Chain and payer, as passed to withDedicatedPayer.
|
|
10
|
+
*/
|
|
11
|
+
export declare function dedicatedPayerBusy(identity: string): boolean;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Serialize reservation submissions from one gas payer within this process. The durable
|
|
2
|
+
// payer lock in the application store still fences other processes and every unresolved
|
|
3
|
+
// original nonce; this only keeps two local callers from racing to that lock.
|
|
4
|
+
const tails = new Map();
|
|
5
|
+
/**
|
|
6
|
+
* Run `work` after every earlier call for the same payer identity has settled.
|
|
7
|
+
* @param identity Chain and payer, e.g. `43112-0xabc…`.
|
|
8
|
+
* @param work Reservation submission.
|
|
9
|
+
*/
|
|
10
|
+
export async function withDedicatedPayer(identity, work) {
|
|
11
|
+
const previous = tails.get(identity) ?? Promise.resolve();
|
|
12
|
+
const running = previous.then(work);
|
|
13
|
+
const tail = running.then(() => { }, () => { });
|
|
14
|
+
tails.set(identity, tail);
|
|
15
|
+
try {
|
|
16
|
+
return await running;
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
if (tails.get(identity) === tail)
|
|
20
|
+
tails.delete(identity);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Whether this process has reservation work queued or running for a payer identity.
|
|
25
|
+
* @param identity Chain and payer, as passed to withDedicatedPayer.
|
|
26
|
+
*/
|
|
27
|
+
export function dedicatedPayerBusy(identity) { return tails.has(identity); }
|