@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,811 @@
|
|
|
1
|
+
// ADR-0090 D7 session lifecycle: one presentation opens a refreshable grant; each KEM decrypt is
|
|
2
|
+
// then authorized by a session-key proof instead of a fresh presentation.
|
|
3
|
+
//
|
|
4
|
+
// The client side of docs/plans/session-grants.md (network repo): the create-body fragment, the
|
|
5
|
+
// grant acceptance checks, background refresh before `exp` with a durably reserved monotonic
|
|
6
|
+
// `seq`, idle and absolute expiry (the application re-presents), and revocation.
|
|
7
|
+
import { ed25519 } from '@noble/curves/ed25519';
|
|
8
|
+
import { randomBytes } from '@noble/hashes/utils';
|
|
9
|
+
import { bytesToHex, hexToBytes } from '../crypto/hex.js';
|
|
10
|
+
import { TasraError } from '../errors.js';
|
|
11
|
+
import { DEFAULT_ACCESS_TTL_SECS, MAX_ABSOLUTE_TTL_SECS, MAX_ACCESS_TTL_SECS, MAX_IDLE_TIMEOUT_SECS, MAX_SESSION_SLOTS, SessionGrantError, decodeSessionGrant, parseSessionKeyJwk, toBase64Url, sessionControlHash, sessionGrantHash, sessionKeyThumbprint, verifySessionGrant } from '../committee/session-grant.js';
|
|
12
|
+
import { withCommit } from './store-commit.js';
|
|
13
|
+
import { validateServiceEndpoint } from '../chain/serviceIdentity.js';
|
|
14
|
+
const HEX32 = /^0x[0-9a-fA-F]{64}$/;
|
|
15
|
+
/**
|
|
16
|
+
* Create a fresh session key. Prefers a NON-EXTRACTABLE WebCrypto P-256 key (ES256), so the private
|
|
17
|
+
* key never exists as bytes in the page; without WebCrypto ECDSA it uses an in-memory Ed25519 key.
|
|
18
|
+
* A session key is per session: never reuse it across sessions.
|
|
19
|
+
* @param opts - Force `Ed25519` (tests, runtimes without WebCrypto) or `ES256`.
|
|
20
|
+
*/
|
|
21
|
+
export async function createSessionKey(opts = {}) {
|
|
22
|
+
const subtle = globalThis.crypto?.subtle;
|
|
23
|
+
if (opts.alg !== 'Ed25519' && subtle) {
|
|
24
|
+
try {
|
|
25
|
+
const pair = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']);
|
|
26
|
+
const pub = await subtle.exportKey('jwk', pair.publicKey);
|
|
27
|
+
const jwk = parseSessionKeyJwk({ kty: pub.kty, crv: pub.crv, x: pub.x, y: pub.y });
|
|
28
|
+
let key = pair.privateKey;
|
|
29
|
+
return Object.freeze({ jwk, dispose: () => { key = undefined; },
|
|
30
|
+
async sign(hash) {
|
|
31
|
+
if (!key)
|
|
32
|
+
throw new TasraError('Session key disposed');
|
|
33
|
+
if (hash.length !== 32)
|
|
34
|
+
throw new TasraError('Session key signs 32-byte hashes only');
|
|
35
|
+
// WebCrypto ECDSA = ECDSA over SHA-256(data), IEEE P1363 r ‖ s: exactly ES256.
|
|
36
|
+
return new Uint8Array(await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, hash.slice().buffer));
|
|
37
|
+
} });
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (opts.alg === 'ES256')
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const secret = randomBytes(32);
|
|
45
|
+
const x = ed25519.getPublicKey(secret);
|
|
46
|
+
const jwk = parseSessionKeyJwk({ kty: 'OKP', crv: 'Ed25519', x: toBase64Url(x) });
|
|
47
|
+
let live = true;
|
|
48
|
+
return Object.freeze({ jwk, dispose: () => { secret.fill(0); live = false; },
|
|
49
|
+
async sign(hash) {
|
|
50
|
+
if (!live)
|
|
51
|
+
throw new TasraError('Session key disposed');
|
|
52
|
+
if (hash.length !== 32)
|
|
53
|
+
throw new TasraError('Session key signs 32-byte hashes only');
|
|
54
|
+
return ed25519.sign(hash, secret);
|
|
55
|
+
} });
|
|
56
|
+
}
|
|
57
|
+
function positive(n, fallback, field) {
|
|
58
|
+
const v = n ?? fallback;
|
|
59
|
+
// A 0 or negative value is a 400 at the agent, never clamped up: refuse it before sending.
|
|
60
|
+
if (!Number.isSafeInteger(v) || v < 1)
|
|
61
|
+
throw new TasraError(`Session ${field} must be a positive whole number of seconds`);
|
|
62
|
+
return v;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Build the session-mode object for `POST /v1/sessions` (merge it into the create body). Slots are
|
|
66
|
+
* sorted ascending, as the agent canonicalizes them; requested lifetimes travel as requested and
|
|
67
|
+
* the agent clamps them to the platform caps.
|
|
68
|
+
* @param key - The session key whose public JWK the grant will bind.
|
|
69
|
+
* @param params - Slots and requested lifetimes.
|
|
70
|
+
*/
|
|
71
|
+
export function sessionGrantCreateFragment(key, params) {
|
|
72
|
+
const slots = [...new Set(params.slots.map(s => s.toLowerCase()))];
|
|
73
|
+
if (slots.length !== params.slots.length || slots.length === 0 || slots.length > MAX_SESSION_SLOTS || slots.some(s => !HEX32.test(s))) {
|
|
74
|
+
throw new TasraError(`A session grant names 1..${MAX_SESSION_SLOTS} distinct 32-byte slots`);
|
|
75
|
+
}
|
|
76
|
+
slots.sort();
|
|
77
|
+
return { session_grant: { session_key: parseSessionKeyJwk(key.jwk), slots,
|
|
78
|
+
access_ttl_secs: positive(params.accessTtlSecs, DEFAULT_ACCESS_TTL_SECS, 'access_ttl'),
|
|
79
|
+
idle_timeout_secs: positive(params.idleTimeoutSecs, 600, 'idle_timeout'),
|
|
80
|
+
absolute_ttl_secs: positive(params.absoluteTtlSecs, 3600, 'absolute_ttl') } };
|
|
81
|
+
}
|
|
82
|
+
/** A session that can no longer be refreshed: the application must present again. */
|
|
83
|
+
export class SessionEndedError extends TasraError {
|
|
84
|
+
/**
|
|
85
|
+
* A definite refusal ({@link SESSION_REFUSAL_CODES}), `unsupported` (a verifier-agent without
|
|
86
|
+
* session refresh) or `local-*` (`local-idle`, `local-absolute`, `local-expired`,
|
|
87
|
+
* `local-revoking`, `local-stale`: the beacon left the grant's window).
|
|
88
|
+
*/
|
|
89
|
+
code;
|
|
90
|
+
constructor(code, message) { super(message); this.code = code; }
|
|
91
|
+
}
|
|
92
|
+
/** A session control reply is a grant and a seq, or a typed refusal: a few KiB at most. */
|
|
93
|
+
const MAX_CONTROL_REPLY_BYTES = 65_536;
|
|
94
|
+
const recordKey = (sessionId) => `tasra.session-grant.${sessionId.toLowerCase()}`;
|
|
95
|
+
const now = () => Math.floor(Date.now() / 1000);
|
|
96
|
+
/**
|
|
97
|
+
* Refresh attempts in ONE follow run while the refresh stays on the old epoch (the new epoch's
|
|
98
|
+
* anchors are landing). A run that gives up is retried by a later observation, even at the same
|
|
99
|
+
* epoch, after a bounded backoff ({@link MAX_FOLLOW_BACKOFF_MS}).
|
|
100
|
+
*/
|
|
101
|
+
const FOLLOW_ATTEMPTS = 20;
|
|
102
|
+
/** Default {@link GrantedSessionOptions.contextRetryMs}: about one lab epoch plus its anchoring delay. */
|
|
103
|
+
const CONTEXT_RETRY_MS = 15_000;
|
|
104
|
+
/** Longest pause before an observation retries a failed follow run, ms. */
|
|
105
|
+
const MAX_FOLLOW_BACKOFF_MS = 30_000;
|
|
106
|
+
/**
|
|
107
|
+
* Accept the grant the agent returned for a session-mode presentation, after checking it against
|
|
108
|
+
* what was requested and against each slot's anchored committee, then persist it. The granted
|
|
109
|
+
* values may be lower than requested, never higher; the key thumbprint must be this key's.
|
|
110
|
+
* @param opts - Store, transport, session key and clock.
|
|
111
|
+
* @param fragment - The fragment sent at create.
|
|
112
|
+
* @param response - The agent's create/complete response carrying `session_grant` and `refresh_seq`.
|
|
113
|
+
*/
|
|
114
|
+
export async function acceptSessionGrant(opts, fragment, response) {
|
|
115
|
+
const clock = opts.clock ?? now;
|
|
116
|
+
const r = response;
|
|
117
|
+
if (!r || typeof r !== 'object' || !r.session_grant || r.refresh_seq !== 0)
|
|
118
|
+
throw new TasraError('Session create response carries no fresh session grant');
|
|
119
|
+
const requested = { accessTtlSecs: fragment.session_grant.access_ttl_secs, idleTimeoutSecs: fragment.session_grant.idle_timeout_secs,
|
|
120
|
+
absoluteTtlSecs: fragment.session_grant.absolute_ttl_secs, slots: fragment.session_grant.slots };
|
|
121
|
+
const grant = decodeSessionGrant(r.session_grant);
|
|
122
|
+
await checkGrant(opts, grant, requested, undefined, clock());
|
|
123
|
+
const sessionId = bytesToHex(grant.payload.sessionId);
|
|
124
|
+
const record = { schema: 1, sessionId, grant: structuredClone(r.session_grant), lastSeq: 0, lastRefresh: grant.payload.iat, requested };
|
|
125
|
+
// One commit: the lock and the record are published together (store-commit.ts).
|
|
126
|
+
await withCommit(opts.store, recordKey(sessionId), async (commit) => {
|
|
127
|
+
if (await opts.store.load(recordKey(sessionId)) !== undefined)
|
|
128
|
+
throw new TasraError('Session grant already accepted for this session');
|
|
129
|
+
commit.stage(recordKey(sessionId), record);
|
|
130
|
+
});
|
|
131
|
+
return new GrantedSession(opts, sessionId, record);
|
|
132
|
+
}
|
|
133
|
+
/** The grant must name the configured deployment chain (and the approved agent must serve it). */
|
|
134
|
+
function requireChain(opts, chainId) {
|
|
135
|
+
const t = opts.transport;
|
|
136
|
+
if (!Number.isSafeInteger(t.chainId) || t.chainId <= 0 || t.agent.profile.approval.chainId !== t.chainId)
|
|
137
|
+
throw new TasraError('Session transport names no single deployment chain');
|
|
138
|
+
if (BigInt(chainId) !== BigInt(t.chainId))
|
|
139
|
+
throw new SessionGrantError('wrong-chain', `Session grant names chain ${String(chainId)}, not the configured chain ${t.chainId}`);
|
|
140
|
+
}
|
|
141
|
+
async function checkGrant(opts, grant, requested, previous, at) {
|
|
142
|
+
const p = grant.payload;
|
|
143
|
+
requireChain(opts, p.chainId);
|
|
144
|
+
const mine = sessionKeyThumbprint(opts.key.jwk);
|
|
145
|
+
if (bytesToHex(p.sessionKeyThumbprint) !== bytesToHex(mine))
|
|
146
|
+
throw new SessionGrantError('wrong-key', 'Session grant binds another session key');
|
|
147
|
+
if (p.exp - p.iat > Math.min(requested.accessTtlSecs, MAX_ACCESS_TTL_SECS))
|
|
148
|
+
throw new SessionGrantError('lifetime', 'Session grant lifetime exceeds the requested access TTL');
|
|
149
|
+
if (p.idleTimeoutSecs > Math.min(requested.idleTimeoutSecs, MAX_IDLE_TIMEOUT_SECS))
|
|
150
|
+
throw new SessionGrantError('idle-timeout', 'Session grant idle timeout exceeds the request');
|
|
151
|
+
const slots = p.slots.map(s => bytesToHex(s.slotId).toLowerCase());
|
|
152
|
+
if (slots.some(s => !requested.slots.includes(s)))
|
|
153
|
+
throw new SessionGrantError('slot-not-granted', 'Session grant names a slot that was not requested');
|
|
154
|
+
if (previous) {
|
|
155
|
+
const q = previous.payload;
|
|
156
|
+
// A refresh keeps the session: same id, key, binding and absolute expiry; slots may only drop.
|
|
157
|
+
if (bytesToHex(p.sessionId) !== bytesToHex(q.sessionId) || bytesToHex(p.holderHash) !== bytesToHex(q.holderHash) || p.binding !== q.binding
|
|
158
|
+
|| p.absoluteExp !== q.absoluteExp || p.idleTimeoutSecs !== q.idleTimeoutSecs || p.chainId !== q.chainId)
|
|
159
|
+
throw new SessionGrantError('refresh-changed', 'Refreshed grant changed the session');
|
|
160
|
+
const before = new Set(q.slots.map(s => bytesToHex(s.slotId).toLowerCase()));
|
|
161
|
+
if (slots.some(s => !before.has(s)))
|
|
162
|
+
throw new SessionGrantError('refresh-changed', 'Refreshed grant added a slot');
|
|
163
|
+
if (p.iat < q.iat || p.epoch < q.epoch)
|
|
164
|
+
throw new SessionGrantError('refresh-changed', 'Refreshed grant is older than the current one');
|
|
165
|
+
// A refresh MOVES the grant (a later iat, or the next epoch): a reply equal to the held grant
|
|
166
|
+
// is no refresh, so a caller can never report success without the grant moving (C8 review F5).
|
|
167
|
+
if (p.iat === q.iat && p.epoch === q.epoch)
|
|
168
|
+
throw new SessionGrantError('refresh-unchanged', 'Refreshed grant does not move the current one');
|
|
169
|
+
}
|
|
170
|
+
else if (p.absoluteExp - p.iat > Math.min(requested.absoluteTtlSecs, MAX_ABSOLUTE_TTL_SECS)) {
|
|
171
|
+
throw new SessionGrantError('absolute-exp', 'Session grant absolute lifetime exceeds the request');
|
|
172
|
+
}
|
|
173
|
+
// Every granted slot verifies against ITS OWN draw and policy before the grant is used for anything.
|
|
174
|
+
const verified = [];
|
|
175
|
+
for (const slot of p.slots) {
|
|
176
|
+
const hex = bytesToHex(slot.slotId);
|
|
177
|
+
const trust = await opts.transport.trust(hex, p.epoch);
|
|
178
|
+
verified.push(verifySessionGrant({ grant, set: trust.set, slotId: slot.slotId, committee: trust.committee, quorum: trust.quorum, slotRuleHash: trust.ruleHash, seed: trust.seed, now: at }));
|
|
179
|
+
}
|
|
180
|
+
return verified;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Refresh refusals no retry of the same session can pass (keykeeper-verifier `session_grant.rs`,
|
|
184
|
+
* relayed by the verifier-agent): the session ends and the application presents again.
|
|
185
|
+
* `session_context_changed`: the verifiers' live draw no longer admits the grant's epoch or seed
|
|
186
|
+
* (the beacon left the grant's window, or the draw changed); `session_continuation`: the session
|
|
187
|
+
* cannot cross an epoch; `session_unknown`: no agent session holds this grant; `session_wrong_key`,
|
|
188
|
+
* `session_key_not_bound`, `session_mismatch`, `session_invalid_request`, `session_lifetime`: this
|
|
189
|
+
* session's own refresh is malformed or bound elsewhere, every retry the same. Everything else
|
|
190
|
+
* (`session_rate_limited`, `session_quorum_unmet`, `session_unavailable`, `session_status_window`,
|
|
191
|
+
* untyped answers) is transient: the held grant still serves and the refresh is retried, backing off.
|
|
192
|
+
*
|
|
193
|
+
* One exception: `session_context_changed` is also what a verifier answers when ITS beacon read lags
|
|
194
|
+
* the chain (the grant's epoch ahead of its live epoch) or the continuation epoch's seed is not
|
|
195
|
+
* anchored at it yet (keykeeper-verifier `validate_beacon_draw`), and the agent relays one such
|
|
196
|
+
* signer's code as final. With a `beacon` reader, the session ends on it only when the client's
|
|
197
|
+
* own chain read confirms the grant two epochs behind, or the refusal persists past
|
|
198
|
+
* `contextRetryMs`; until then it is retried as transient (the held grant still serves).
|
|
199
|
+
*/
|
|
200
|
+
export const SESSION_REFUSAL_CODES = new Set(['session_expired', 'session_idle', 'session_revoked', 'session_replayed', 'session_status',
|
|
201
|
+
'session_rule_changed', 'session_context_changed', 'session_continuation', 'session_unknown', 'session_wrong_key', 'session_key_not_bound', 'session_mismatch',
|
|
202
|
+
'session_invalid_request', 'session_lifetime']);
|
|
203
|
+
/**
|
|
204
|
+
* Session-route refusals the SAME request may pass later (verifier `session_grant.rs`, C24): the
|
|
205
|
+
* held grant still serves and the refresh is retried, never below the answer's `Retry-After`.
|
|
206
|
+
* `session_verifier_behind` (503, NEW): a verifier's chain view trails the grant (its live beacon
|
|
207
|
+
* is older than the grant's epoch, or that epoch's seed is not anchored at its head yet); it
|
|
208
|
+
* passes once the verifier catches up, with no new presentation. Before C24 a verifier answered
|
|
209
|
+
* that as `session_context_changed`, which an up-to-date server now sends only for a definite
|
|
210
|
+
* change (it stays in {@link SESSION_REFUSAL_CODES}, with the chain-confirmed exception for older
|
|
211
|
+
* servers). `session_rate_limited` (429), `session_unavailable`, `session_quorum_unmet` (503,
|
|
212
|
+
* the agent's mixed or older answers) and `session_status_window` are transient as before; any
|
|
213
|
+
* other non-refusal answer stays transient too.
|
|
214
|
+
*/
|
|
215
|
+
export const SESSION_RETRYABLE_CODES = new Set(['session_verifier_behind', 'session_rate_limited', 'session_unavailable',
|
|
216
|
+
'session_quorum_unmet', 'session_status_window']);
|
|
217
|
+
/**
|
|
218
|
+
* The pause before retrying a `session_verifier_behind` refusal that carries no `Retry-After`
|
|
219
|
+
* (the verifier sends 2 s and a current verifier-agent sets or relays it; an older agent relays the
|
|
220
|
+
* code without the header), ms. A Retry-After that is present always wins.
|
|
221
|
+
*/
|
|
222
|
+
export const SESSION_VERIFIER_BEHIND_RETRY_MS = 2_000;
|
|
223
|
+
/**
|
|
224
|
+
* A transient refresh failure: the held grant is unchanged and still serves until its `exp`.
|
|
225
|
+
* `retryAfterMs` is the agent's `Retry-After`, when it sends one: no verifier-agent or verifier
|
|
226
|
+
* sets it today (2026-11), so the backoff alone paces the retries; the support is kept for when
|
|
227
|
+
* one does.
|
|
228
|
+
*/
|
|
229
|
+
export class SessionRefreshError extends TasraError {
|
|
230
|
+
status;
|
|
231
|
+
code;
|
|
232
|
+
retryAfterMs;
|
|
233
|
+
/** Always true: a later refresh may pass. */
|
|
234
|
+
retryable = true;
|
|
235
|
+
constructor(
|
|
236
|
+
/** HTTP status of the agent's reply. */
|
|
237
|
+
status,
|
|
238
|
+
/** The agent's error code, when it sent one. */
|
|
239
|
+
code,
|
|
240
|
+
/** Milliseconds to wait before retrying, when known. */
|
|
241
|
+
retryAfterMs) {
|
|
242
|
+
super(`Session refresh failed (${status}${code ? ', ' + code : ''}); retry before the grant expires`);
|
|
243
|
+
this.status = status;
|
|
244
|
+
this.code = code;
|
|
245
|
+
this.retryAfterMs = retryAfterMs;
|
|
246
|
+
this.name = 'SessionRefreshError';
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/** The pause before the next transient refresh retry: exponential from `base` (at most 8×), never below a `Retry-After`, at most 30 s. */
|
|
250
|
+
function retryPause(base, attempt, error) {
|
|
251
|
+
const after = error instanceof SessionRefreshError ? error.retryAfterMs ?? 0 : 0;
|
|
252
|
+
return Math.min(MAX_FOLLOW_BACKOFF_MS, Math.max(after, base * 2 ** Math.min(attempt, 3)));
|
|
253
|
+
}
|
|
254
|
+
/** An accepted, refreshable session grant. */
|
|
255
|
+
export class GrantedSession {
|
|
256
|
+
/** Lowercase 0x-prefixed 32-byte session id. */
|
|
257
|
+
sessionId;
|
|
258
|
+
#opts;
|
|
259
|
+
#record;
|
|
260
|
+
#timer;
|
|
261
|
+
#beaconTimer;
|
|
262
|
+
#inflight;
|
|
263
|
+
#following;
|
|
264
|
+
/** Callers waiting in {@link followBeacon}; while any wait, the follow's pause holds the process. */
|
|
265
|
+
#waiters = 0;
|
|
266
|
+
/** The running follow's pause between attempts ({@link stop} wakes it). */
|
|
267
|
+
#pause;
|
|
268
|
+
/** Bumped by every {@link stop}: a follow started before it gives up at its next step. */
|
|
269
|
+
#stops = 0;
|
|
270
|
+
/** The newest beacon epoch observed on the chain (a payment's discovery, the beacon poll, a fresh read). */
|
|
271
|
+
#beacon;
|
|
272
|
+
/** The newest draw epoch observed on the chain ({@link observeDraw}); only with `beacon.drawState`. */
|
|
273
|
+
#draw;
|
|
274
|
+
/** Consecutive failed follow runs, and when (Date.now ms) an observation may start the next one. */
|
|
275
|
+
#followFailures = 0;
|
|
276
|
+
#followRetryAt = 0;
|
|
277
|
+
/** Consecutive failed expiry refreshes (their retry backs off). */
|
|
278
|
+
#expiryFailures = 0;
|
|
279
|
+
/** When (Date.now ms) the current run of unconfirmed `session_context_changed` refusals began. */
|
|
280
|
+
#contextSince;
|
|
281
|
+
/** The last `beacon.drawState` read failed: the poll and the follow behave as `latestEpoch`-only until one answers. */
|
|
282
|
+
#drawFallback = false;
|
|
283
|
+
#drawWarned = false;
|
|
284
|
+
/**
|
|
285
|
+
* Unix seconds of the last USE (a {@link current} read for a keeper request), at least the last
|
|
286
|
+
* refresh this process loaded. Background refreshes (the expiry timer, a beacon follow) never move
|
|
287
|
+
* it, so the D9 idle timeout still fires while {@link start} runs: idle is time without use.
|
|
288
|
+
*/
|
|
289
|
+
#lastUsed;
|
|
290
|
+
/** @internal Use {@link acceptSessionGrant} or {@link loadGrantedSession}. */
|
|
291
|
+
constructor(opts, sessionId, record) {
|
|
292
|
+
this.#opts = opts;
|
|
293
|
+
this.sessionId = sessionId;
|
|
294
|
+
this.#record = record;
|
|
295
|
+
this.#lastUsed = record.lastRefresh;
|
|
296
|
+
}
|
|
297
|
+
#clock() { return (this.#opts.clock ?? now)(); }
|
|
298
|
+
/**
|
|
299
|
+
* The current grant on the wire, for keeper requests. Throws once the session ended or the grant
|
|
300
|
+
* is past its deadline. A read is a USE: it keeps the session from going idle.
|
|
301
|
+
*/
|
|
302
|
+
current() {
|
|
303
|
+
const ended = this.#localEnd();
|
|
304
|
+
if (ended)
|
|
305
|
+
throw ended;
|
|
306
|
+
const t = this.#clock();
|
|
307
|
+
if (t > this.#record.grant.exp)
|
|
308
|
+
throw new SessionGrantError('expired', 'Session grant expired; refresh it first');
|
|
309
|
+
if (t > this.#lastUsed)
|
|
310
|
+
this.#lastUsed = t;
|
|
311
|
+
return structuredClone(this.#record.grant);
|
|
312
|
+
}
|
|
313
|
+
/** Verified grant for one slot (re-verified against the slot's anchored committee). */
|
|
314
|
+
async verifiedFor(slot) {
|
|
315
|
+
const grant = decodeSessionGrant(this.current());
|
|
316
|
+
requireChain(this.#opts, grant.payload.chainId);
|
|
317
|
+
const target = grant.payload.slots.find(s => bytesToHex(s.slotId).toLowerCase() === slot.toLowerCase());
|
|
318
|
+
if (!target)
|
|
319
|
+
throw new SessionGrantError('slot-not-granted', `slot ${slot} is not named by the session grant`);
|
|
320
|
+
const trust = await this.#opts.transport.trust(slot, grant.payload.epoch);
|
|
321
|
+
return verifySessionGrant({ grant, set: trust.set, slotId: target.slotId, committee: trust.committee, quorum: trust.quorum, slotRuleHash: trust.ruleHash, seed: trust.seed, now: this.#clock() });
|
|
322
|
+
}
|
|
323
|
+
/** The session key bound by this grant. */
|
|
324
|
+
get key() { return this.#opts.key; }
|
|
325
|
+
#localEnd() {
|
|
326
|
+
if (this.#record.ended)
|
|
327
|
+
return new SessionEndedError(this.#record.ended.code, `Session ended (${this.#record.ended.code}); present again`);
|
|
328
|
+
if (this.#record.revoking)
|
|
329
|
+
return new SessionEndedError('local-revoking', 'Session is being revoked; present again');
|
|
330
|
+
const t = this.#clock(), g = this.#record.grant;
|
|
331
|
+
if (t >= g.absolute_exp)
|
|
332
|
+
return new SessionEndedError('local-absolute', 'Session reached its absolute expiry; present again');
|
|
333
|
+
// Idle is judged from the last refresh (as the verifiers judge it) AND from the last use: a
|
|
334
|
+
// background refresh alone never keeps an unused session alive.
|
|
335
|
+
if (t - this.#record.lastRefresh > g.idle_timeout_secs || t - this.#lastUsed > g.idle_timeout_secs) {
|
|
336
|
+
return new SessionEndedError('local-idle', 'Session idle timeout passed; present again');
|
|
337
|
+
}
|
|
338
|
+
return undefined;
|
|
339
|
+
}
|
|
340
|
+
async #end(error) {
|
|
341
|
+
this.stop();
|
|
342
|
+
const key = recordKey(this.sessionId);
|
|
343
|
+
await withCommit(this.#opts.store, key, async (commit) => {
|
|
344
|
+
const stored = await this.#opts.store.load(key);
|
|
345
|
+
if (stored && !stored.ended)
|
|
346
|
+
commit.stage(key, { ...stored, ended: { code: error.code, at: this.#clock() } });
|
|
347
|
+
});
|
|
348
|
+
this.#record = { ...this.#record, ended: { code: error.code, at: this.#clock() } };
|
|
349
|
+
this.#opts.onEnded?.(error);
|
|
350
|
+
throw error;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Reserve the next seq durably before signing, so a crash never reuses one: the staged value is
|
|
354
|
+
* published with the lock's release (one commit), and this resolves only after it is durable.
|
|
355
|
+
*/
|
|
356
|
+
async #reserveSeq() {
|
|
357
|
+
const key = recordKey(this.sessionId);
|
|
358
|
+
const reserved = await withCommit(this.#opts.store, key, async (commit) => {
|
|
359
|
+
const stored = await this.#opts.store.load(key);
|
|
360
|
+
if (!stored || stored.schema !== 1)
|
|
361
|
+
throw new TasraError('Session grant journal missing');
|
|
362
|
+
const seq = stored.lastSeq + 1;
|
|
363
|
+
const updated = { ...stored, lastSeq: seq };
|
|
364
|
+
commit.stage(key, updated);
|
|
365
|
+
return { seq, grant: stored.grant, updated };
|
|
366
|
+
});
|
|
367
|
+
this.#record = reserved.updated;
|
|
368
|
+
return { seq: reserved.seq, grant: reserved.grant };
|
|
369
|
+
}
|
|
370
|
+
/** One POST through the approved agent's guarded transport and the shared request policy; never repeated here. */
|
|
371
|
+
async #post(path, body) {
|
|
372
|
+
const { profile, transport } = this.#opts.transport.agent;
|
|
373
|
+
validateServiceEndpoint(profile.endpoint);
|
|
374
|
+
const res = await transport.paidAgentRequest(profile.endpoint + path, { method: 'POST', body: new TextEncoder().encode(JSON.stringify(body)),
|
|
375
|
+
maxBytes: MAX_CONTROL_REPLY_BYTES, signal: AbortSignal.timeout(30_000) });
|
|
376
|
+
if (res.body.length > MAX_CONTROL_REPLY_BYTES)
|
|
377
|
+
throw new TasraError('Session reply exceeds its byte limit');
|
|
378
|
+
let json;
|
|
379
|
+
try {
|
|
380
|
+
json = res.body.length ? JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(res.body)) : undefined;
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
json = undefined;
|
|
384
|
+
}
|
|
385
|
+
return { status: res.status, json, ...res.retryAfterMs !== undefined ? { retryAfterMs: res.retryAfterMs } : {} };
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Refresh now: a session-key signature over `(grant_hash, seq, issued_at)` with a fresh seq;
|
|
389
|
+
* the verifiers re-check status, rules, idle and absolute limits and sign a new grant. A typed
|
|
390
|
+
* refusal, a 404 (verifiers without session support) or a local limit ends the session.
|
|
391
|
+
*/
|
|
392
|
+
refresh() {
|
|
393
|
+
this.#inflight ??= this.#refresh().finally(() => { this.#inflight = undefined; });
|
|
394
|
+
return this.#inflight;
|
|
395
|
+
}
|
|
396
|
+
async #refresh() {
|
|
397
|
+
const local = this.#localEnd();
|
|
398
|
+
if (local)
|
|
399
|
+
return this.#end(local);
|
|
400
|
+
const { seq, grant } = await this.#reserveSeq();
|
|
401
|
+
const previous = decodeSessionGrant(grant);
|
|
402
|
+
const issuedAt = this.#clock();
|
|
403
|
+
const signature = await this.#opts.key.sign(sessionControlHash('refresh', sessionGrantHash(previous.payload), seq, issuedAt));
|
|
404
|
+
const reply = await this.#post('/v1/sessions/refresh', { grant, seq, issued_at: issuedAt, signature: bytesToHex(signature) });
|
|
405
|
+
const r = reply.json;
|
|
406
|
+
const code = typeof r?.code === 'string' ? r.code : undefined;
|
|
407
|
+
if (reply.status >= 400 && code === 'session_context_changed' && await this.#contextUnconfirmed(BigInt(previous.payload.epoch))) {
|
|
408
|
+
throw new SessionRefreshError(reply.status, code, reply.retryAfterMs);
|
|
409
|
+
}
|
|
410
|
+
if (reply.status >= 400 && code !== undefined && SESSION_REFUSAL_CODES.has(code))
|
|
411
|
+
return this.#end(new SessionEndedError(code, `Session refresh refused: ${code}; present again`));
|
|
412
|
+
if (reply.status === 404)
|
|
413
|
+
return this.#end(new SessionEndedError('unsupported', 'Verifiers do not support session refresh; present again'));
|
|
414
|
+
if (reply.status >= 400)
|
|
415
|
+
throw new SessionRefreshError(reply.status, code, reply.retryAfterMs ?? (code === 'session_verifier_behind' ? SESSION_VERIFIER_BEHIND_RETRY_MS : undefined));
|
|
416
|
+
if (!r?.session_grant || r.refresh_seq !== seq)
|
|
417
|
+
throw new TasraError('Session refresh reply does not answer this seq');
|
|
418
|
+
this.#contextSince = undefined;
|
|
419
|
+
const next = decodeSessionGrant(r.session_grant);
|
|
420
|
+
await checkGrant(this.#opts, next, this.#record.requested, previous, this.#clock());
|
|
421
|
+
const key = recordKey(this.sessionId);
|
|
422
|
+
this.#record = await withCommit(this.#opts.store, key, async (commit) => {
|
|
423
|
+
const stored = await this.#opts.store.load(key);
|
|
424
|
+
if (!stored || stored.lastSeq < seq)
|
|
425
|
+
throw new TasraError('Session grant journal moved backwards');
|
|
426
|
+
const updated = { ...stored, grant: structuredClone(r.session_grant), lastRefresh: issuedAt };
|
|
427
|
+
commit.stage(key, updated);
|
|
428
|
+
return updated;
|
|
429
|
+
});
|
|
430
|
+
// A refresh outside the expiry timer (a beacon follow) moves `exp`: re-arm the armed timer on it.
|
|
431
|
+
if (this.#timer)
|
|
432
|
+
this.#armExpiry();
|
|
433
|
+
try {
|
|
434
|
+
this.#opts.onRefreshed?.(structuredClone(r.session_grant));
|
|
435
|
+
}
|
|
436
|
+
catch { /* a listener never fails the refresh */ }
|
|
437
|
+
return structuredClone(r.session_grant);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Whether a `session_context_changed` refresh refusal is NOT confirmed by the chain (so it is
|
|
441
|
+
* retried, not ended on): within `contextRetryMs` of the first such refusal in a row, the client's
|
|
442
|
+
* own fresh read (`beacon.latestEpoch`) shows the grant still admissible (its epoch the latest or
|
|
443
|
+
* previous: the refusing verifier's beacon or anchor is behind), or cannot be read. Without a
|
|
444
|
+
* `beacon` reader nothing can show the server is behind: the refusal ends the session.
|
|
445
|
+
*/
|
|
446
|
+
async #contextUnconfirmed(grantEpoch) {
|
|
447
|
+
const read = this.#opts.beacon?.latestEpoch;
|
|
448
|
+
if (!read)
|
|
449
|
+
return false;
|
|
450
|
+
const t = Date.now();
|
|
451
|
+
this.#contextSince ??= t;
|
|
452
|
+
if (t - this.#contextSince > (this.#opts.contextRetryMs ?? CONTEXT_RETRY_MS))
|
|
453
|
+
return false;
|
|
454
|
+
let latest;
|
|
455
|
+
try {
|
|
456
|
+
latest = await read();
|
|
457
|
+
}
|
|
458
|
+
catch {
|
|
459
|
+
return true;
|
|
460
|
+
}
|
|
461
|
+
if (typeof latest !== 'bigint' || latest < 0n)
|
|
462
|
+
return true;
|
|
463
|
+
// A fair chain observation; the follow (if any) judges it after this refresh settles.
|
|
464
|
+
if (this.#beacon === undefined || latest > this.#beacon)
|
|
465
|
+
this.#beacon = latest;
|
|
466
|
+
return grantEpoch + 1n >= latest;
|
|
467
|
+
}
|
|
468
|
+
/** The newest beacon epoch this session has observed, if any. */
|
|
469
|
+
get beaconEpoch() { return this.#beacon; }
|
|
470
|
+
/**
|
|
471
|
+
* Report the beacon's latest epoch AS READ FROM THE CHAIN (a payment discovery's `beaconEpoch`,
|
|
472
|
+
* the beacon poll, a fresh `readCurrentBeaconEpoch`). Never pass an epoch a keeper or any other
|
|
473
|
+
* service claims: observations never move backwards, so one inflated value would stall the
|
|
474
|
+
* session until it is presented again. Once it is past the grant's epoch the grant is refreshed in the BACKGROUND
|
|
475
|
+
* ({@link followBeacon}): keepers still admit the current grant for the whole next epoch, so the
|
|
476
|
+
* refresh lands well before the boundary that would end it, and no message waits for it. An
|
|
477
|
+
* observation never moves backwards.
|
|
478
|
+
*/
|
|
479
|
+
observeBeacon(epoch) {
|
|
480
|
+
if (typeof epoch !== 'bigint' || epoch < 0n)
|
|
481
|
+
return;
|
|
482
|
+
if (this.#beacon === undefined || epoch > this.#beacon)
|
|
483
|
+
this.#beacon = epoch;
|
|
484
|
+
// What was OBSERVED (#beacon) and what the grant has FOLLOWED to (its epoch) are separate: an
|
|
485
|
+
// observation at an epoch already seen still retries a follow that failed (after the backoff).
|
|
486
|
+
if (this.#record.ended || this.#record.revoking || this.#beacon <= BigInt(this.#record.grant.epoch))
|
|
487
|
+
return;
|
|
488
|
+
// A grant the beacon has left (two epochs behind) can never be continued: the follow ends the
|
|
489
|
+
// session at once, whatever the backoff, so the next use presents again instead of failing.
|
|
490
|
+
if (this.#stale() && !this.#following) {
|
|
491
|
+
void this.#startFollow().catch(() => undefined);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
if (this.#following || Date.now() < this.#followRetryAt)
|
|
495
|
+
return;
|
|
496
|
+
// Errors are the session's own outcome (an end calls onEnded); a later observation retries.
|
|
497
|
+
void this.#startFollow().catch(() => undefined);
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Report the beacon's latest epoch and its DRAW epoch AS READ FROM THE CHAIN at one head
|
|
501
|
+
* (`readBeaconDrawState`; the `beacon.drawState` poll does this). As {@link observeBeacon}, and a
|
|
502
|
+
* follow refreshes only once the draw epoch is past the grant's (the agent can continue the
|
|
503
|
+
* session onto it); until then nothing is sent. Observations never move backwards.
|
|
504
|
+
*/
|
|
505
|
+
observeDraw(state) {
|
|
506
|
+
const { latest, draw } = state ?? {};
|
|
507
|
+
if (typeof latest !== 'bigint' || latest < 0n)
|
|
508
|
+
return;
|
|
509
|
+
if (typeof draw === 'bigint' && draw >= 0n && draw <= latest && (this.#draw === undefined || draw > this.#draw))
|
|
510
|
+
this.#draw = draw;
|
|
511
|
+
this.observeBeacon(latest);
|
|
512
|
+
}
|
|
513
|
+
/** The newest draw epoch observed, if a `beacon.drawState` is configured and has answered. */
|
|
514
|
+
get drawEpoch() { return this.#draw; }
|
|
515
|
+
/** The held grant is two or more epochs behind the observed beacon: no keeper or verifier admits it again. */
|
|
516
|
+
#stale() {
|
|
517
|
+
return this.#beacon !== undefined && BigInt(this.#record.grant.epoch) + 1n < this.#beacon;
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Bring the grant up to the newest observed beacon epoch, one continuation per epoch (the agent
|
|
521
|
+
* continues a session exactly ONE epoch). A refresh that stays on the old epoch (the new epoch's
|
|
522
|
+
* anchors have not landed at the agent) is retried, bounded, while the held grant is still
|
|
523
|
+
* admissible (its epoch the beacon's latest or previous); never past that. Single-flight; resolves
|
|
524
|
+
* `true` when the grant moved, `false` when it was already current. Throws
|
|
525
|
+
* {@link SessionEndedError} when the session cannot continue (present again), and a
|
|
526
|
+
* {@link TasraError} when {@link stop} interrupts it.
|
|
527
|
+
*
|
|
528
|
+
* A caller of this method WAITS for the follow, so while it waits the follow's pauses keep the
|
|
529
|
+
* process alive (a background follow, started by {@link observeBeacon}, never does): a waiter
|
|
530
|
+
* whose only pending work is an unreferenced timer would be dropped when the event loop drains.
|
|
531
|
+
*/
|
|
532
|
+
followBeacon() {
|
|
533
|
+
const run = this.#startFollow();
|
|
534
|
+
this.#waiters++;
|
|
535
|
+
this.#pause?.timer?.ref?.();
|
|
536
|
+
return run.finally(() => { this.#waiters--; });
|
|
537
|
+
}
|
|
538
|
+
#startFollow() {
|
|
539
|
+
this.#following ??= this.#follow().then(moved => {
|
|
540
|
+
this.#followFailures = 0;
|
|
541
|
+
this.#followRetryAt = 0;
|
|
542
|
+
return moved;
|
|
543
|
+
}, (error) => {
|
|
544
|
+
// Back off exponentially from `followRetryMs` (bounded) before an observation tries again.
|
|
545
|
+
this.#followFailures++;
|
|
546
|
+
const base = this.#opts.followRetryMs ?? 1000;
|
|
547
|
+
this.#followRetryAt = Date.now() + Math.min(MAX_FOLLOW_BACKOFF_MS, base * 2 ** Math.min(this.#followFailures - 1, 16));
|
|
548
|
+
throw error;
|
|
549
|
+
}).finally(() => { this.#following = undefined; });
|
|
550
|
+
return this.#following;
|
|
551
|
+
}
|
|
552
|
+
async #follow() {
|
|
553
|
+
let moved = false;
|
|
554
|
+
const run = this.#stops;
|
|
555
|
+
for (let attempt = 0;; attempt++) {
|
|
556
|
+
// stop() (also every session end) interrupts the follow; its waiters are told why.
|
|
557
|
+
if (this.#stops !== run) {
|
|
558
|
+
const ended = this.#localEnd();
|
|
559
|
+
if (ended)
|
|
560
|
+
throw ended;
|
|
561
|
+
throw new TasraError('Session beacon follow stopped (GrantedSession.stop); the held grant is unchanged');
|
|
562
|
+
}
|
|
563
|
+
// A refresh already in flight (the expiry timer's) may move the grant: judge after it.
|
|
564
|
+
if (this.#inflight) {
|
|
565
|
+
await this.#inflight.catch(() => undefined);
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
const target = this.#beacon, at = BigInt(this.#record.grant.epoch);
|
|
569
|
+
if (target === undefined || at >= target)
|
|
570
|
+
return moved;
|
|
571
|
+
// Two epochs behind: the agent continues a session one epoch at a time and the verifiers judge
|
|
572
|
+
// the continuation at their live beacon, so no refresh can save it (C20: every such attempt
|
|
573
|
+
// was refused `session_context_changed` or `session_expired`). End now; present again.
|
|
574
|
+
if (this.#stale()) {
|
|
575
|
+
const local = this.#localEnd();
|
|
576
|
+
return this.#end(local ?? new SessionEndedError('local-stale', `Session grant epoch ${at} is two epochs behind the beacon (${target}); present again`));
|
|
577
|
+
}
|
|
578
|
+
// With a draw observation: until the agent can draw the next epoch, a refresh would only
|
|
579
|
+
// re-sign the grant on its own epoch. Wait for the poll to observe the anchor.
|
|
580
|
+
if (this.#opts.beacon?.drawState && !this.#drawFallback && (this.#draw === undefined || this.#draw <= at))
|
|
581
|
+
return moved;
|
|
582
|
+
let failure;
|
|
583
|
+
try {
|
|
584
|
+
if (await this.refreshForEpoch(target))
|
|
585
|
+
moved = true;
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
catch (error) {
|
|
589
|
+
if (error instanceof SessionEndedError)
|
|
590
|
+
throw error;
|
|
591
|
+
// Only while the held grant is still admissible is waiting worth it: past that, nothing
|
|
592
|
+
// this grant authorizes is served, and the caller presents again.
|
|
593
|
+
if (this.#stale() || attempt + 1 >= FOLLOW_ATTEMPTS)
|
|
594
|
+
throw error;
|
|
595
|
+
failure = error;
|
|
596
|
+
}
|
|
597
|
+
// Back off between attempts (each attempt that reaches the verifiers spends the holder's
|
|
598
|
+
// session quota there), never below the agent's Retry-After.
|
|
599
|
+
const pause = retryPause(this.#opts.followRetryMs ?? 1000, attempt, failure);
|
|
600
|
+
if (pause > 0)
|
|
601
|
+
await this.#followPause(pause);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* One pause between follow attempts. Unreferenced while nobody waits for the follow (a background
|
|
606
|
+
* follow never holds the process open); referenced while a {@link followBeacon} caller waits.
|
|
607
|
+
* {@link stop} wakes it at once.
|
|
608
|
+
*/
|
|
609
|
+
#followPause(ms) {
|
|
610
|
+
return new Promise(resolve => {
|
|
611
|
+
const done = () => { if (this.#pause?.timer === timer)
|
|
612
|
+
this.#pause = undefined; resolve(); };
|
|
613
|
+
const timer = setTimeout(done, ms);
|
|
614
|
+
if (this.#waiters === 0)
|
|
615
|
+
timer.unref?.();
|
|
616
|
+
this.#pause = { timer, wake: () => { clearTimeout(timer); done(); } };
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Refresh now if the beacon has moved past the grant's epoch (`beaconEpoch`, e.g.
|
|
621
|
+
* `PaidSessionDecrypt.beaconEpoch`). Keepers admit a grant only while its epoch is the beacon's
|
|
622
|
+
* latest or previous, and the agent continues a session ONE epoch at a time, so a grant must
|
|
623
|
+
* follow the beacon every epoch, not only before its `exp`: wait for a second move and the
|
|
624
|
+
* session needs a new presentation. Resolves `true` when it refreshed, `false` when the grant is
|
|
625
|
+
* already on (or ahead of) that epoch.
|
|
626
|
+
*/
|
|
627
|
+
async refreshForEpoch(beaconEpoch) {
|
|
628
|
+
const previous = BigInt(this.#record.grant.epoch);
|
|
629
|
+
if (previous >= beaconEpoch)
|
|
630
|
+
return false;
|
|
631
|
+
const next = await this.refresh();
|
|
632
|
+
// `true` means the grant MOVED to a later epoch; a refresh that stayed on the old draw (the
|
|
633
|
+
// latest snapshot not anchored yet) is not success: retry, the old grant is still valid.
|
|
634
|
+
if (BigInt(next.epoch) <= previous)
|
|
635
|
+
throw new TasraError(`Session refresh stayed on epoch ${previous}; retry once the beacon epoch is anchored`);
|
|
636
|
+
return true;
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Refresh in the background before each grant's `exp`, until stopped or the session ends. With
|
|
640
|
+
* `beacon` configured, also poll the beacon and follow it ({@link observeBeacon}). Background
|
|
641
|
+
* refreshes keep a session alive only while it is USED ({@link current}) within its idle timeout:
|
|
642
|
+
* an unused session reaches the idle timeout and ends (`local-idle`, `onEnded`), so the next use
|
|
643
|
+
* presents again.
|
|
644
|
+
*/
|
|
645
|
+
start() {
|
|
646
|
+
this.#armExpiry();
|
|
647
|
+
const beacon = this.#opts.beacon;
|
|
648
|
+
if (beacon && !this.#beaconTimer) {
|
|
649
|
+
const poll = () => {
|
|
650
|
+
const latest = () => beacon.latestEpoch().then(epoch => this.observeBeacon(epoch), () => undefined);
|
|
651
|
+
if (!beacon.drawState) {
|
|
652
|
+
void latest();
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
beacon.drawState().then(state => { this.#drawFallback = false; this.observeDraw(state); }, (error) => {
|
|
656
|
+
// A failing draw read never stops the follow: until it answers again, follow the latest
|
|
657
|
+
// epoch alone (a refresh may then re-sign the old epoch until the anchor lands).
|
|
658
|
+
this.#drawFallback = true;
|
|
659
|
+
if (!this.#drawWarned) {
|
|
660
|
+
this.#drawWarned = true;
|
|
661
|
+
console.warn(`tasra session ${this.sessionId}: beacon.drawState failed (${error instanceof Error ? error.message : String(error)}); following the latest epoch only until it answers`);
|
|
662
|
+
}
|
|
663
|
+
void latest();
|
|
664
|
+
});
|
|
665
|
+
};
|
|
666
|
+
this.#beaconTimer = setInterval(poll, Math.max(100, beacon.pollMs ?? 2000));
|
|
667
|
+
this.#beaconTimer.unref?.();
|
|
668
|
+
poll();
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
#armExpiry() {
|
|
672
|
+
if (this.#timer)
|
|
673
|
+
clearTimeout(this.#timer);
|
|
674
|
+
this.#timer = undefined;
|
|
675
|
+
const g = this.#record.grant;
|
|
676
|
+
const lead = this.#opts.refreshLeadSecs ?? Math.max(5, Math.floor((g.exp - g.iat) / 3));
|
|
677
|
+
const delay = Math.max(0, (g.exp - lead - this.#clock()) * 1000);
|
|
678
|
+
this.#timer = setTimeout(() => {
|
|
679
|
+
this.#timer = undefined;
|
|
680
|
+
this.refresh().then(() => { this.#expiryFailures = 0; this.#armExpiry(); }, error => {
|
|
681
|
+
if (error instanceof SessionEndedError)
|
|
682
|
+
return;
|
|
683
|
+
// Transient: retry while the current grant still has time left, backing off (never below
|
|
684
|
+
// the agent's Retry-After), so a busy or rate-limited agent is not asked every second.
|
|
685
|
+
if (this.#clock() < this.#record.grant.exp) {
|
|
686
|
+
this.#timer = setTimeout(() => this.#armExpiry(), retryPause(1000, this.#expiryFailures++, error));
|
|
687
|
+
this.#timer.unref?.();
|
|
688
|
+
}
|
|
689
|
+
else
|
|
690
|
+
void this.#end(new SessionEndedError('local-expired', 'Session grant expired before a refresh succeeded; present again')).catch(() => undefined);
|
|
691
|
+
});
|
|
692
|
+
}, delay);
|
|
693
|
+
this.#timer.unref?.();
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Stop background refresh and the beacon poll, and interrupt a running beacon follow: its
|
|
697
|
+
* {@link followBeacon} waiters reject at once (`SessionEndedError` when the session ended,
|
|
698
|
+
* otherwise a `TasraError`), never left waiting on a cleared timer.
|
|
699
|
+
*/
|
|
700
|
+
stop() {
|
|
701
|
+
if (this.#timer)
|
|
702
|
+
clearTimeout(this.#timer);
|
|
703
|
+
if (this.#beaconTimer)
|
|
704
|
+
clearInterval(this.#beaconTimer);
|
|
705
|
+
this.#timer = undefined;
|
|
706
|
+
this.#beaconTimer = undefined;
|
|
707
|
+
this.#stops++;
|
|
708
|
+
this.#pause?.wake();
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Revoke at the verifiers (effective at the next refresh; an issued grant runs to its `exp`, at
|
|
712
|
+
* most 45 s), then end locally. The agent answers 204 only once `n - k + 1` members of every draw
|
|
713
|
+
* that could hold the session acknowledged (so the rest can never form a quorum); `503
|
|
714
|
+
* session_revoke_partial` (and a 429/503 busy answer) is retried, each attempt under a fresh
|
|
715
|
+
* durably reserved seq, until `deadlineMs`. The session stops serving the moment revoke starts
|
|
716
|
+
* (journaled), even when the revoke has not completed; call `revoke()` again after a
|
|
717
|
+
* {@link SessionRevokeIncompleteError}. A 404 (the agent holds no session for this grant, so no
|
|
718
|
+
* verifier was asked) ends and disposes the session locally and throws
|
|
719
|
+
* {@link SessionRevokeUnconfirmedError}.
|
|
720
|
+
* @param options - `deadlineMs`: total retry budget (default 30 s, at most 120 s); `sleep` for tests.
|
|
721
|
+
*/
|
|
722
|
+
async revoke(options = {}) {
|
|
723
|
+
this.stop();
|
|
724
|
+
const budget = options.deadlineMs ?? 30_000;
|
|
725
|
+
if (!Number.isSafeInteger(budget) || budget < 0 || budget > 120_000)
|
|
726
|
+
throw new TasraError('Session revoke deadline must be 0..120000 ms');
|
|
727
|
+
const sleep = options.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
|
|
728
|
+
await this.#markRevoking();
|
|
729
|
+
const started = Date.now();
|
|
730
|
+
for (let attempt = 0;; attempt++) {
|
|
731
|
+
const { seq, grant } = await this.#reserveSeq();
|
|
732
|
+
const issuedAt = this.#clock();
|
|
733
|
+
const signature = await this.#opts.key.sign(sessionControlHash('revoke', sessionGrantHash(decodeSessionGrant(grant).payload), seq, issuedAt));
|
|
734
|
+
const reply = await this.#post('/v1/sessions/revoke', { grant, seq, issued_at: issuedAt, signature: bytesToHex(signature) });
|
|
735
|
+
// 204: n - k + 1 of every draw acknowledged.
|
|
736
|
+
if (reply.status === 204)
|
|
737
|
+
break;
|
|
738
|
+
// 404: the agent holds no session for this grant, so it relayed the revoke to NO verifier.
|
|
739
|
+
// The grant still lives at its signers until its `exp`; nothing confirmed the revoke. End
|
|
740
|
+
// and dispose locally (only this key could refresh it), then say so by type.
|
|
741
|
+
if (reply.status === 404) {
|
|
742
|
+
await this.#end(new SessionEndedError('session_revoked', 'Session revoked locally; the agent did not confirm it')).catch(() => undefined);
|
|
743
|
+
this.#opts.key.dispose();
|
|
744
|
+
throw new SessionRevokeUnconfirmedError();
|
|
745
|
+
}
|
|
746
|
+
const code = reply.json?.code;
|
|
747
|
+
const retryable = reply.status === 503 || reply.status === 429;
|
|
748
|
+
if (!retryable)
|
|
749
|
+
throw new TasraError(`Session revoke refused (${reply.status}${typeof code === 'string' ? ', ' + code : ''})`);
|
|
750
|
+
const wait = Math.min(Math.max(reply.retryAfterMs ?? 0, 500 * 2 ** Math.min(attempt, 4)), 10_000);
|
|
751
|
+
if (Date.now() - started + wait > budget) {
|
|
752
|
+
throw new SessionRevokeIncompleteError(typeof code === 'string' ? code : `status ${reply.status}`);
|
|
753
|
+
}
|
|
754
|
+
await sleep(wait);
|
|
755
|
+
}
|
|
756
|
+
await this.#end(new SessionEndedError('session_revoked', 'Session revoked')).catch(() => undefined);
|
|
757
|
+
this.#opts.key.dispose();
|
|
758
|
+
}
|
|
759
|
+
/** Journal that a revoke started: from now on the session serves nothing, across reloads too. */
|
|
760
|
+
async #markRevoking() {
|
|
761
|
+
const key = recordKey(this.sessionId);
|
|
762
|
+
this.#record = await withCommit(this.#opts.store, key, async (commit) => {
|
|
763
|
+
const stored = await this.#opts.store.load(key);
|
|
764
|
+
if (!stored || stored.schema !== 1)
|
|
765
|
+
throw new TasraError('Session grant journal missing');
|
|
766
|
+
const updated = { ...stored, revoking: true };
|
|
767
|
+
commit.stage(key, updated);
|
|
768
|
+
return updated;
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* A revoke that has not reached a quorum of every draw yet (`session_revoke_partial`, or the agent
|
|
774
|
+
* stayed busy) within its deadline. The session no longer serves locally; retry `revoke()`.
|
|
775
|
+
*/
|
|
776
|
+
export class SessionRevokeIncompleteError extends TasraError {
|
|
777
|
+
/** Always true: the same call may be repeated (each attempt signs a fresh seq). */
|
|
778
|
+
retryable = true;
|
|
779
|
+
/** The agent's last answer (`session_revoke_partial`, `session_rate_limited`, `status 503`, ...). */
|
|
780
|
+
code;
|
|
781
|
+
constructor(code) { super(`Session revoke incomplete (${code}); retry revoke()`); this.code = code; }
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* The agent answered 404 to a revoke: it holds no session for this grant, so no verifier was asked
|
|
785
|
+
* and nothing confirmed the revocation. The session was still ended and its key disposed locally,
|
|
786
|
+
* so it can never be refreshed (only this key could); the last issued grant runs to its `exp`.
|
|
787
|
+
*/
|
|
788
|
+
export class SessionRevokeUnconfirmedError extends TasraError {
|
|
789
|
+
/** Retrying cannot help: the agent has no session to relay it for. */
|
|
790
|
+
retryable = false;
|
|
791
|
+
/** Always `session_unknown`. */
|
|
792
|
+
code = 'session_unknown';
|
|
793
|
+
constructor() { super('Session revoke not confirmed: the agent holds no session for this grant (ended locally; the grant expires at its exp)'); }
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* Load a journaled session (same process, same key) after a restart of its owner, e.g. a tab reload with the key kept.
|
|
797
|
+
* @param opts - Lifecycle options; `key` must be the key the grant binds.
|
|
798
|
+
* @param sessionId - 0x-prefixed 32-byte session id.
|
|
799
|
+
*/
|
|
800
|
+
export async function loadGrantedSession(opts, sessionId) {
|
|
801
|
+
if (!HEX32.test(sessionId))
|
|
802
|
+
throw new TasraError('Invalid session id');
|
|
803
|
+
const record = await opts.store.load(recordKey(sessionId));
|
|
804
|
+
if (!record || record.schema !== 1)
|
|
805
|
+
throw new TasraError('No session grant journal for this session');
|
|
806
|
+
// Resume pins the chain too: a journal written for another deployment never serves this one.
|
|
807
|
+
requireChain(opts, record.grant.chain_id);
|
|
808
|
+
if (bytesToHex(sessionKeyThumbprint(opts.key.jwk)) !== bytesToHex(hexToBytes(record.grant.session_key_thumbprint)))
|
|
809
|
+
throw new SessionGrantError('wrong-key', 'Session grant binds another session key');
|
|
810
|
+
return new GrantedSession(opts, sessionId.toLowerCase(), record);
|
|
811
|
+
}
|