@t3foundry/tasra-sdk 0.3.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.
Files changed (255) hide show
  1. package/CHANGELOG.md +1067 -28
  2. package/README.md +15 -0
  3. package/dist/app/approvals.d.ts +66 -4
  4. package/dist/app/approvals.js +153 -16
  5. package/dist/app/authorization.d.ts +1 -1
  6. package/dist/app/authorization.js +1 -1
  7. package/dist/app/browser.d.ts +63 -0
  8. package/dist/app/browser.js +242 -0
  9. package/dist/app/client.d.ts +114 -13
  10. package/dist/app/client.js +302 -76
  11. package/dist/app/identity.js +21 -9
  12. package/dist/app/index.d.ts +28 -3
  13. package/dist/app/index.js +16 -1
  14. package/dist/app/memory-store.d.ts +7 -0
  15. package/dist/app/memory-store.js +55 -0
  16. package/dist/app/node.d.ts +34 -6
  17. package/dist/app/node.js +387 -64
  18. package/dist/app/paid-allowance.d.ts +325 -0
  19. package/dist/app/paid-allowance.js +1290 -0
  20. package/dist/app/paid-approval.d.ts +122 -0
  21. package/dist/app/paid-approval.js +379 -0
  22. package/dist/app/paid-journal.d.ts +51 -0
  23. package/dist/app/paid-journal.js +117 -0
  24. package/dist/app/paid-keys.d.ts +12 -0
  25. package/dist/app/paid-keys.js +20 -0
  26. package/dist/app/paid-operation.d.ts +821 -0
  27. package/dist/app/paid-operation.js +1720 -0
  28. package/dist/app/paid-reservation.d.ts +157 -0
  29. package/dist/app/paid-reservation.js +323 -0
  30. package/dist/app/paid-session.d.ts +147 -0
  31. package/dist/app/paid-session.js +578 -0
  32. package/dist/app/payer-queue.d.ts +11 -0
  33. package/dist/app/payer-queue.js +27 -0
  34. package/dist/app/policy-bootstrap.d.ts +342 -0
  35. package/dist/app/policy-bootstrap.js +365 -0
  36. package/dist/app/policy-operation.d.ts +47 -0
  37. package/dist/app/policy-operation.js +101 -0
  38. package/dist/app/ready-slot.d.ts +12 -0
  39. package/dist/app/ready-slot.js +5 -2
  40. package/dist/app/rotation-lock.d.ts +38 -0
  41. package/dist/app/rotation-lock.js +42 -0
  42. package/dist/app/session-decrypt.d.ts +135 -0
  43. package/dist/app/session-decrypt.js +335 -0
  44. package/dist/app/session-grants.d.ts +349 -0
  45. package/dist/app/session-grants.js +811 -0
  46. package/dist/app/signing-intents.d.ts +78 -0
  47. package/dist/app/signing-intents.js +95 -0
  48. package/dist/app/store-commit.d.ts +63 -0
  49. package/dist/app/store-commit.js +126 -0
  50. package/dist/app/store-errors.d.ts +8 -0
  51. package/dist/app/store-errors.js +11 -0
  52. package/dist/app/tasra-client.d.ts +2 -0
  53. package/dist/app/tasra-client.js +1 -1
  54. package/dist/app/wallet.js +4 -1
  55. package/dist/auth/holderProof.d.ts +3 -0
  56. package/dist/auth/holderProof.js +8 -7
  57. package/dist/auth/verifier.d.ts +4 -2
  58. package/dist/auth/verifier.js +5 -2
  59. package/dist/chain/abis/index.d.ts +6178 -4101
  60. package/dist/chain/abis/index.js +3 -0
  61. package/dist/chain/abis/keyRegistry.d.ts +256 -0
  62. package/dist/chain/abis/keyRegistry.js +333 -0
  63. package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
  64. package/dist/chain/abis/prepaidFaultOracle.js +413 -0
  65. package/dist/chain/abis/settlement.d.ts +2203 -703
  66. package/dist/chain/abis/settlement.js +2685 -764
  67. package/dist/chain/allowance.d.ts +358 -0
  68. package/dist/chain/allowance.js +800 -0
  69. package/dist/chain/billing.d.ts +85 -0
  70. package/dist/chain/billing.js +197 -0
  71. package/dist/chain/chainId.d.ts +13 -0
  72. package/dist/chain/chainId.js +26 -0
  73. package/dist/chain/client.d.ts +15 -1
  74. package/dist/chain/client.js +57 -1
  75. package/dist/chain/commitmentRecovery.d.ts +51 -0
  76. package/dist/chain/commitmentRecovery.js +38 -0
  77. package/dist/chain/committeeClient.d.ts +17 -10
  78. package/dist/chain/committeeClient.js +64 -16
  79. package/dist/chain/committeeDraw.d.ts +12 -0
  80. package/dist/chain/committeeDraw.js +56 -0
  81. package/dist/chain/custodyHealth.d.ts +212 -0
  82. package/dist/chain/custodyHealth.js +365 -0
  83. package/dist/chain/deployments.js +2 -0
  84. package/dist/chain/events.js +2 -0
  85. package/dist/chain/headFollower.d.ts +77 -0
  86. package/dist/chain/headFollower.js +219 -0
  87. package/dist/chain/headPrefetch.d.ts +23 -0
  88. package/dist/chain/headPrefetch.js +67 -0
  89. package/dist/chain/index.d.ts +50 -8
  90. package/dist/chain/index.js +28 -3
  91. package/dist/chain/keeperExecution.d.ts +44 -0
  92. package/dist/chain/keeperExecution.js +127 -0
  93. package/dist/chain/keeperRecovery.d.ts +78 -0
  94. package/dist/chain/keeperRecovery.js +91 -0
  95. package/dist/chain/node.d.ts +24 -1
  96. package/dist/chain/node.js +88 -43
  97. package/dist/chain/offchain.d.ts +2 -0
  98. package/dist/chain/paidAgentTransport.d.ts +38 -0
  99. package/dist/chain/paidAgentTransport.js +1 -0
  100. package/dist/chain/paidEpoch.d.ts +66 -0
  101. package/dist/chain/paidEpoch.js +139 -0
  102. package/dist/chain/paidPacing.d.ts +81 -0
  103. package/dist/chain/paidPacing.js +136 -0
  104. package/dist/chain/pinnedReads.d.ts +49 -0
  105. package/dist/chain/pinnedReads.js +218 -0
  106. package/dist/chain/prepaid.d.ts +383 -0
  107. package/dist/chain/prepaid.js +1046 -0
  108. package/dist/chain/prepaidEscape.d.ts +274 -0
  109. package/dist/chain/prepaidEscape.js +432 -0
  110. package/dist/chain/prepaidFault.d.ts +94 -0
  111. package/dist/chain/prepaidFault.js +148 -0
  112. package/dist/chain/receipt.d.ts +24 -0
  113. package/dist/chain/receipt.js +82 -0
  114. package/dist/chain/registeredAgent.d.ts +68 -3
  115. package/dist/chain/registeredAgent.js +143 -42
  116. package/dist/chain/registeredOperation.d.ts +10 -1
  117. package/dist/chain/registeredOperation.js +18 -3
  118. package/dist/chain/registeredPaidAgent.d.ts +254 -0
  119. package/dist/chain/registeredPaidAgent.js +889 -0
  120. package/dist/chain/registeredRelay.d.ts +31 -1
  121. package/dist/chain/registeredRelay.js +164 -43
  122. package/dist/chain/relayVoucher.d.ts +64 -0
  123. package/dist/chain/relayVoucher.js +69 -0
  124. package/dist/chain/reservation.d.ts +239 -0
  125. package/dist/chain/reservation.js +746 -0
  126. package/dist/chain/reshareRoster.d.ts +64 -0
  127. package/dist/chain/reshareRoster.js +85 -0
  128. package/dist/chain/revertReason.d.ts +8 -0
  129. package/dist/chain/revertReason.js +2 -1
  130. package/dist/chain/rotationLock.d.ts +130 -0
  131. package/dist/chain/rotationLock.js +168 -0
  132. package/dist/chain/serviceRequestPolicy.d.ts +47 -0
  133. package/dist/chain/serviceRequestPolicy.js +86 -0
  134. package/dist/chain/services.d.ts +7 -0
  135. package/dist/chain/services.js +44 -4
  136. package/dist/chain/slotClient.js +11 -2
  137. package/dist/chain/slotHandoff.d.ts +81 -0
  138. package/dist/chain/slotHandoff.js +166 -0
  139. package/dist/chain/slotSeed.d.ts +47 -5
  140. package/dist/chain/slotSeed.js +173 -42
  141. package/dist/chain/verifierSnapshot.d.ts +36 -0
  142. package/dist/chain/verifierSnapshot.js +197 -0
  143. package/dist/chain/write.d.ts +111 -21
  144. package/dist/chain/write.js +378 -146
  145. package/dist/committee/blsSharing.d.ts +53 -0
  146. package/dist/committee/blsSharing.js +90 -0
  147. package/dist/committee/client.d.ts +62 -23
  148. package/dist/committee/client.js +288 -72
  149. package/dist/committee/dual-operation.d.ts +165 -0
  150. package/dist/committee/dual-operation.js +229 -0
  151. package/dist/committee/dual-sign.d.ts +26 -1
  152. package/dist/committee/dual-sign.js +85 -7
  153. package/dist/committee/ecdsa.d.ts +38 -0
  154. package/dist/committee/ecdsa.js +87 -15
  155. package/dist/committee/evidence.d.ts +30 -0
  156. package/dist/committee/evidence.js +65 -0
  157. package/dist/committee/execution.d.ts +414 -0
  158. package/dist/committee/execution.js +446 -0
  159. package/dist/committee/extraction.js +33 -26
  160. package/dist/committee/index.d.ts +30 -7
  161. package/dist/committee/index.js +18 -6
  162. package/dist/committee/keeperExecution.d.ts +37 -0
  163. package/dist/committee/keeperExecution.js +141 -0
  164. package/dist/committee/oauth.d.ts +14 -4
  165. package/dist/committee/oauth.js +17 -5
  166. package/dist/committee/payment.d.ts +369 -0
  167. package/dist/committee/payment.js +339 -0
  168. package/dist/committee/recovery.d.ts +136 -0
  169. package/dist/committee/recovery.js +204 -0
  170. package/dist/committee/recoveryJson.d.ts +2 -0
  171. package/dist/committee/recoveryJson.js +87 -0
  172. package/dist/committee/request.d.ts +63 -27
  173. package/dist/committee/request.js +77 -66
  174. package/dist/committee/session-grant.d.ts +320 -0
  175. package/dist/committee/session-grant.js +397 -0
  176. package/dist/committee/status-refresh.d.ts +257 -0
  177. package/dist/committee/status-refresh.js +619 -0
  178. package/dist/committee/token.d.ts +163 -15
  179. package/dist/committee/token.js +247 -10
  180. package/dist/crypto/bn254.d.ts +70 -0
  181. package/dist/crypto/bn254.js +222 -0
  182. package/dist/crypto/ibe.d.ts +32 -0
  183. package/dist/crypto/ibe.js +56 -8
  184. package/dist/crypto/index.d.ts +1 -1
  185. package/dist/crypto/index.js +1 -1
  186. package/dist/crypto/kem.d.ts +31 -0
  187. package/dist/crypto/kem.js +113 -7
  188. package/dist/crypto/recipient.d.ts +75 -0
  189. package/dist/crypto/recipient.js +107 -0
  190. package/dist/decryption/client.d.ts +10 -16
  191. package/dist/decryption/client.js +8 -76
  192. package/dist/decryption/index.d.ts +2 -0
  193. package/dist/decryption/index.js +2 -0
  194. package/dist/decryption/sealed.d.ts +72 -0
  195. package/dist/decryption/sealed.js +147 -0
  196. package/dist/decryption/session.d.ts +115 -0
  197. package/dist/decryption/session.js +358 -0
  198. package/dist/errors.d.ts +406 -1
  199. package/dist/errors.js +400 -5
  200. package/dist/index.d.ts +9 -2
  201. package/dist/index.js +6 -1
  202. package/dist/internal/bounded.d.ts +66 -0
  203. package/dist/internal/bounded.js +126 -0
  204. package/dist/internal/network.d.ts +4 -0
  205. package/dist/internal/network.js +40 -0
  206. package/dist/internal/retryAfter.d.ts +8 -0
  207. package/dist/internal/retryAfter.js +28 -0
  208. package/dist/internal/sleep.d.ts +6 -0
  209. package/dist/internal/sleep.js +15 -0
  210. package/dist/internal/typedData.d.ts +13 -0
  211. package/dist/internal/typedData.js +77 -0
  212. package/dist/internal/viemErrors.d.ts +26 -0
  213. package/dist/internal/viemErrors.js +49 -0
  214. package/dist/oid4vp/binding.d.ts +27 -1
  215. package/dist/oid4vp/binding.js +36 -1
  216. package/dist/oid4vp/jose.d.ts +4 -2
  217. package/dist/oid4vp/jose.js +39 -7
  218. package/dist/oid4vp/request-object.d.ts +61 -4
  219. package/dist/oid4vp/request-object.js +140 -5
  220. package/dist/oid4vp/verifier-agent.d.ts +18 -8
  221. package/dist/oid4vp/verifier-agent.js +48 -6
  222. package/dist/oid4vp/wallet.d.ts +2 -4
  223. package/dist/oid4vp/wallet.js +1 -0
  224. package/dist/retry.d.ts +78 -0
  225. package/dist/retry.js +137 -0
  226. package/dist/signing/frost.d.ts +1 -1
  227. package/dist/verifier-agent/index.d.ts +41 -5
  228. package/dist/verifier-agent/index.js +124 -9
  229. package/dist/verifier-agent/payment.d.ts +7 -0
  230. package/dist/verifier-agent/payment.js +17 -0
  231. package/docs/api.md +8 -2
  232. package/docs/application-api.md +25 -2
  233. package/docs/chain.md +155 -9
  234. package/docs/consumer-migrations.md +61 -0
  235. package/docs/encrypted-notes.md +3 -2
  236. package/docs/encryption.md +4 -2
  237. package/docs/errors.md +14 -1
  238. package/docs/flows.md +2 -2
  239. package/docs/funding.md +902 -0
  240. package/docs/native-approvals.md +63 -0
  241. package/docs/reference/README.md +9 -8
  242. package/docs/reference/app-browser.md +232 -0
  243. package/docs/reference/app-node.md +38 -8
  244. package/docs/reference/app.md +4621 -805
  245. package/docs/reference/chain-node.md +74 -16
  246. package/docs/reference/chain.md +6740 -1592
  247. package/docs/reference/committee.md +5630 -987
  248. package/docs/reference/main.md +1439 -140
  249. package/docs/reference/oid4vp.md +297 -144
  250. package/docs/reference/verifier-agent.md +77 -35
  251. package/docs/signing.md +6 -0
  252. package/examples/encrypted-notes.ts +21 -6
  253. package/examples/getting-started.ts +2 -7
  254. package/examples/live-config.ts +24 -17
  255. package/package.json +17 -5
@@ -10,7 +10,7 @@ export interface SignCustodyOpts {
10
10
  slotId: string;
11
11
  /** Raw message bytes to sign. */
12
12
  message: Uint8Array;
13
- /** Explicit signer set (u16 ids). Omit to node uses 1..k. Passing MORE than k
13
+ /** Explicit signer set (u16 ids). Omit to let the keeper select responsive eligible signers. Passing MORE than k
14
14
  * ids makes the node use the robust ROAST coordinator. */
15
15
  signingSet?: number[];
16
16
  /** 64-byte Ed25519 user signature - required iff the slot has a registered
@@ -1,4 +1,7 @@
1
+ import type { DecryptionBindingWire } from '../crypto/recipient.js';
1
2
  import { TasraError } from '../errors.js';
3
+ import { type PaymentIntentWire } from '../committee/payment.js';
4
+ import type { SessionGrantWire } from '../committee/session-grant.js';
2
5
  /** The operation the holder is authorizing - signed by the creator's EIP-712 key. */
3
6
  import type { DpopSigner } from '../auth/dpop.js';
4
7
  /** Operation details signed by a slot creator or delegate for credential authorization. */
@@ -35,6 +38,12 @@ export interface PresentationDelegation {
35
38
  }
36
39
  /** Signed operation, optional delegation and payload submitted to the verifier agent. */
37
40
  export interface CreateSessionParams {
41
+ /** Public decryption binding committed by the signed operation; never include private recipient material. */
42
+ decryption?: DecryptionBindingWire;
43
+ /** Creator-signed intent for an already reserved TASRA payment. Requires random. */
44
+ payment?: PaymentIntentWire;
45
+ /** Fixed 32-byte hex presentation random committed before reservation. */
46
+ random?: string;
38
47
  /** Signed operation details presented for authorization. */
39
48
  operation: PresentationOperation;
40
49
  /** 0x-hex 65-byte EIP-712 signature over the operation */
@@ -72,6 +81,9 @@ export interface CreateOauthSessionResult {
72
81
  export type SessionPhase = 'awaiting_wallet' | 'verifying' | 'done' | 'failed';
73
82
  /** Authorization session progress and optional committee result or failure detail. */
74
83
  export interface SessionStatusResult {
84
+ /** Sealed presentation (base64url `bincode(Ciphertext)`) the token's `evidence_hash` names,
85
+ * retained unchanged and posted to the keeper beside the token as `evidence_ct`. */
86
+ evidenceCt?: string;
75
87
  /** Pending, completed or failed authorization state. */
76
88
  status: 'pending' | 'done' | 'failed';
77
89
  /** Displayable progress within the authorization lifecycle. */
@@ -84,9 +96,17 @@ export interface SessionStatusResult {
84
96
  bindingPreimage?: Record<string, unknown>;
85
97
  /** Optional failure detail reported by the verifier agent. */
86
98
  error?: string;
87
- /** the sealed presentation (base64url `bincode(Ciphertext)`) the token's
88
- * `evidence_hash` names — post it to the keeper beside the token as `evidence_ct`. */
89
- evidenceCt?: string;
99
+ /**
100
+ * Session mode, once `done`: the grant the paid session client verified against the
101
+ * anchored draw (`refresh_seq` 0), or why none came with the token. Absent otherwise.
102
+ */
103
+ sessionGrant?: {
104
+ grant?: {
105
+ session_grant: SessionGrantWire;
106
+ refresh_seq: 0;
107
+ };
108
+ error?: string;
109
+ };
90
110
  }
91
111
  /** Why a session did not yield a token - the class the UI explains, with a NON-SECRET
92
112
  * correlation reference (the session id; the poll secret is never part of an error). */
@@ -186,14 +206,24 @@ export declare function submitOauthResponse(verifierAgentUrl: string, args: {
186
206
  dpopHtu: string;
187
207
  signer: DpopSigner;
188
208
  }): Promise<void>;
209
+ /** Options for one session status request. */
210
+ export interface PollSessionOpts {
211
+ /** Ask the verifier-agent to hold the reply until the session status or phase changes (`?wait=1`, up to 20 s). A server without that support answers at once. */
212
+ wait?: boolean;
213
+ /** Cancel the request: rejects with `cancelled`. */
214
+ signal?: AbortSignal;
215
+ /** Per-request ceiling in milliseconds (default 30000, which covers the 20 s hold); a reply that does not arrive in time is `unavailable`. */
216
+ timeoutMs?: number;
217
+ }
189
218
  /**
190
- * Fetch and validate one authorization session status. Transport failures and HTTP 502, 503 or 504 produce an unavailable error; malformed or other failed replies produce a protocol error. The polling secret is sent in the Authorization header.
219
+ * Fetch and validate one authorization session status. Transport failures, a request that exceeds its timeout and HTTP 502, 503 or 504 produce an unavailable error; malformed or other failed replies produce a protocol error; an aborted signal produces a cancelled error. The polling secret is sent in the Authorization header.
191
220
  *
192
221
  * @param verifierAgentUrl - Verifier-agent HTTP base URL.
193
222
  * @param sessionId - Opened session identifier.
194
223
  * @param pollSecret - Secret returned at session creation; do not expose it in logs.
224
+ * @param opts - Long-poll request, cancellation and per-request timeout.
195
225
  */
196
- export declare function pollOid4vpSession(verifierAgentUrl: string, sessionId: string, pollSecret: string): Promise<SessionStatusResult>;
226
+ export declare function pollOid4vpSession(verifierAgentUrl: string, sessionId: string, pollSecret: string, opts?: PollSessionOpts): Promise<SessionStatusResult>;
197
227
  /**
198
228
  * Shared validation for the explicit-URL and registered-agent transports.
199
229
  *
@@ -225,6 +255,12 @@ export declare function nextPollDelay(previousMs: number, baseMs: number, maxMs:
225
255
  /**
226
256
  * Poll until the session reaches a terminal state (done or failed) - bounded by
227
257
  * `timeoutMs`, with a growing jittered interval so many clients never poll in lock-step.
258
+ * Every request asks the verifier-agent to hold its reply until the session moves
259
+ * (`?wait=1`). A reply whose phase moved forward is followed by the next request at once;
260
+ * an unchanged reply is followed by the backoff sleep, unless it took 15 s or more (the
261
+ * server's hold ended), when the next request also goes at once. A server without long-poll
262
+ * support answers at once and is polled on the backoff schedule. Any phase change resets the
263
+ * backoff to `intervalMs`.
228
264
  * A transient `unavailable` answer (a 503, a dropped connection) is retried within the
229
265
  * deadline; a `protocol` answer stops at once; the deadline is a `timeout` error; the
230
266
  * caller's `signal` is a `cancelled` error. A terminal `failed` is RETURNED (the caller
@@ -1,3 +1,4 @@
1
+ import { assertEvidenceBinding, evidenceBody } from '../committee/evidence.js';
1
2
  // Verifier Agent client - creates OID4VP sessions on the platform verifier-agent and
2
3
  // polls for the compound token result.
3
4
  //
@@ -13,6 +14,10 @@
13
14
  import { sha256 } from '@noble/hashes/sha256';
14
15
  import { bytesToHex } from '@noble/hashes/utils';
15
16
  import { TasraError } from '../errors.js';
17
+ import { dpopHtu, platformAudience } from '../committee/oauth.js';
18
+ import { assertPaymentIntentWire, paymentIntentHash } from '../committee/payment.js';
19
+ import { sessionPaymentFields } from './payment.js';
20
+ import { assertStatusAttestationsWire } from '../committee/token.js';
16
21
  /**
17
22
  * A Verifier Agent session did not produce a compound token. `kind` says why;
18
23
  * `retryable` is true only for `timeout` and `unavailable` - the session may
@@ -53,7 +58,7 @@ export function assertCompoundTokenWire(raw, correlation) {
53
58
  const t = { ...raw };
54
59
  // Reference-side optional fields are serialized as null for non-IBE operations. Normalize
55
60
  // absence before consumers decode the token; never replace it with a zero hash.
56
- for (const key of ['identity_hash', 'request_hash'])
61
+ for (const key of ['identity_hash', 'request_hash', 'payment_hash', 'payment', 'status_attestations', 'evidence_hash', 'evidence_key_id', 'evidence_signatures'])
57
62
  if (t[key] === null)
58
63
  delete t[key];
59
64
  for (const k of ['seed', 'slot_id', 'vp_hash', 'holder_hash', 'rule_hash']) {
@@ -72,6 +77,18 @@ export function assertCompoundTokenWire(raw, correlation) {
72
77
  bad('request_hash is not a 32-byte hex string');
73
78
  if (t.identity_hash !== undefined && (typeof t.identity_hash !== 'string' || !HEX32.test(t.identity_hash)))
74
79
  bad('identity_hash is not a 32-byte hex string');
80
+ if (t.payment_hash !== undefined && (typeof t.payment_hash !== 'string' || !HEX32.test(t.payment_hash)))
81
+ bad('payment_hash is not a 32-byte hex string');
82
+ if (t.payment !== undefined) {
83
+ try {
84
+ assertPaymentIntentWire(t.payment);
85
+ if (paymentIntentHash(t.payment).toLowerCase() !== (typeof t.payment_hash === 'string' ? t.payment_hash.toLowerCase() : undefined))
86
+ bad('payment preimage differs from payment_hash');
87
+ }
88
+ catch {
89
+ bad('invalid payment preimage or commitment');
90
+ }
91
+ }
75
92
  if (t.binding !== undefined && !['unbound', 'holder_key', 'issuer_asserted'].includes(t.binding))
76
93
  bad('binding is not a known strength');
77
94
  if (!Array.isArray(t.verifier_indexes) || !t.verifier_indexes.every(i => Number.isInteger(i) && i >= 0))
@@ -104,6 +121,22 @@ export function assertCompoundTokenWire(raw, correlation) {
104
121
  bad('evidence_signatures missing');
105
122
  checkSignatures(t.evidence_signatures, 'evidence signature');
106
123
  }
124
+ // Revocation-status freshness attestations travel beside `signatures`, outside the token hash.
125
+ // Keepers verify them; here the shape is checked strictly and the value carried unchanged.
126
+ if (t.status_attestations !== undefined) {
127
+ try {
128
+ t.status_attestations = assertStatusAttestationsWire(t.status_attestations, t.verifier_indexes.length);
129
+ }
130
+ catch (e) {
131
+ bad(e instanceof Error ? e.message : String(e));
132
+ }
133
+ }
134
+ try {
135
+ assertEvidenceBinding(t);
136
+ }
137
+ catch {
138
+ bad('invalid sealed evidence binding');
139
+ }
107
140
  return t;
108
141
  }
109
142
  /**
@@ -139,10 +172,12 @@ export async function createOid4vpSession(verifierAgentUrl, params) {
139
172
  method: 'POST',
140
173
  headers: { 'Content-Type': 'application/json' },
141
174
  body: JSON.stringify({
175
+ ...sessionPaymentFields(params),
142
176
  operation: params.operation,
143
177
  operation_sig: params.operationSig,
144
178
  delegation: params.delegation,
145
179
  message_hex: params.messageHex,
180
+ decryption: params.decryption,
146
181
  }),
147
182
  });
148
183
  if (!resp.ok) {
@@ -177,6 +212,7 @@ export async function createOauthSession(verifierAgentUrl, params) {
177
212
  method: 'POST',
178
213
  headers: { 'Content-Type': 'application/json' },
179
214
  body: JSON.stringify({
215
+ ...sessionPaymentFields(params),
180
216
  operation: params.operation,
181
217
  operation_sig: params.operationSig,
182
218
  delegation: params.delegation,
@@ -201,6 +237,10 @@ export async function createOauthSession(verifierAgentUrl, params) {
201
237
  throw new Error('createOauthSession: the agent returned a wallet session (qr_payload present) — it ' +
202
238
  'predates and does not support the oauth session kind');
203
239
  }
240
+ if (data.dpop_htu !== dpopHtu(verifierAgentUrl, data.session_id)
241
+ || data.platform_audience !== platformAudience(verifierAgentUrl, params.operation.chain_id)) {
242
+ throw new Error('createOauthSession: reply changed the original session target or audience');
243
+ }
204
244
  return {
205
245
  sessionId: data.session_id,
206
246
  pollSecret: data.poll_secret,
@@ -280,18 +320,51 @@ export async function submitOauthResponse(verifierAgentUrl, args) {
280
320
  throw new VerifierAgentSessionError(kind, args.sessionId, `submitOauthResponse: HTTP ${resp.status}${body ? `: ${body.slice(0, 300)}` : ''}`, resp.status);
281
321
  }
282
322
  }
323
+ /** How long a verifier-agent may hold a `?wait=1` status request before answering unchanged. */
324
+ const LONG_POLL_HOLD_MS = 20_000;
325
+ /** A long poll that took at least this long ended on the server's hold timer, not on a change. */
326
+ const LONG_POLL_TIMEOUT_THRESHOLD_MS = 15_000;
327
+ /** Per-request ceiling for one status request: the server hold plus network headroom. */
328
+ const POLL_REQUEST_TIMEOUT_MS = LONG_POLL_HOLD_MS + 10_000;
283
329
  /**
284
- * Fetch and validate one authorization session status. Transport failures and HTTP 502, 503 or 504 produce an unavailable error; malformed or other failed replies produce a protocol error. The polling secret is sent in the Authorization header.
330
+ * Fetch and validate one authorization session status. Transport failures, a request that exceeds its timeout and HTTP 502, 503 or 504 produce an unavailable error; malformed or other failed replies produce a protocol error; an aborted signal produces a cancelled error. The polling secret is sent in the Authorization header.
285
331
  *
286
332
  * @param verifierAgentUrl - Verifier-agent HTTP base URL.
287
333
  * @param sessionId - Opened session identifier.
288
334
  * @param pollSecret - Secret returned at session creation; do not expose it in logs.
335
+ * @param opts - Long-poll request, cancellation and per-request timeout.
289
336
  */
290
- export async function pollOid4vpSession(verifierAgentUrl, sessionId, pollSecret) {
291
- const url = `${verifierAgentUrl.replace(/\/$/, '')}/v1/sessions/${encodeURIComponent(sessionId)}`;
337
+ export async function pollOid4vpSession(verifierAgentUrl, sessionId, pollSecret, opts = {}) {
338
+ const url = `${verifierAgentUrl.replace(/\/$/, '')}/v1/sessions/${encodeURIComponent(sessionId)}${opts.wait ? '?wait=1' : ''}`;
339
+ const timeoutMs = opts.timeoutMs ?? POLL_REQUEST_TIMEOUT_MS;
340
+ // One timer and one listener per request, both released when it settles: thousands of
341
+ // concurrent waits leave nothing behind.
342
+ const controller = new AbortController();
343
+ let timedOut = false;
344
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, Math.max(1, timeoutMs));
345
+ const cancel = () => controller.abort();
346
+ opts.signal?.addEventListener('abort', cancel, { once: true });
347
+ try {
348
+ if (opts.signal?.aborted)
349
+ throw new VerifierAgentSessionError('cancelled', sessionId, 'polling cancelled');
350
+ return await readSessionStatus(url, sessionId, pollSecret, controller.signal);
351
+ }
352
+ catch (e) {
353
+ if (opts.signal?.aborted)
354
+ throw new VerifierAgentSessionError('cancelled', sessionId, 'polling cancelled');
355
+ if (timedOut)
356
+ throw new VerifierAgentSessionError('unavailable', sessionId, `poll: no reply within ${timeoutMs} ms`);
357
+ throw e;
358
+ }
359
+ finally {
360
+ clearTimeout(timer);
361
+ opts.signal?.removeEventListener('abort', cancel);
362
+ }
363
+ }
364
+ async function readSessionStatus(url, sessionId, pollSecret, signal) {
292
365
  let resp;
293
366
  try {
294
- resp = await fetch(url, { headers: { 'Authorization': `Bearer ${pollSecret}` } });
367
+ resp = await fetch(url, { headers: { 'Authorization': `Bearer ${pollSecret}` }, signal });
295
368
  }
296
369
  catch (e) {
297
370
  throw new VerifierAgentSessionError('unavailable', sessionId, `poll: ${e instanceof Error ? e.message : String(e)}`);
@@ -330,16 +403,29 @@ export function parseVerifierAgentSessionStatus(data, sessionId) {
330
403
  // Absent optional fields arrive as JSON `null` from the verifier-agent (serde `Option`): null = absent.
331
404
  if (data.error != null && typeof data.error !== 'string')
332
405
  throw new VerifierAgentSessionError('protocol', sessionId, 'poll: error is not a string');
406
+ // Cheap shape refusal first (a named protocol error), then the binding check proper: the
407
+ // ciphertext must be canonical base64url and hash to the token's `evidence_hash`, and a
408
+ // sealed token without its ciphertext (or a ciphertext without a token) is refused.
333
409
  if (data.evidence_ct != null && (typeof data.evidence_ct !== 'string' || !/^[A-Za-z0-9_-]+$/.test(data.evidence_ct)))
334
410
  throw new VerifierAgentSessionError('protocol', sessionId, 'poll: evidence_ct is not base64url');
411
+ let evidenceCt;
412
+ try {
413
+ if (data.compound_token != null)
414
+ evidenceCt = evidenceBody(assertCompoundTokenWire(data.compound_token, sessionId), data.evidence_ct == null ? undefined : data.evidence_ct).evidence_ct;
415
+ else if (data.evidence_ct != null)
416
+ throw new Error('ciphertext without a token');
417
+ }
418
+ catch {
419
+ throw new VerifierAgentSessionError('protocol', sessionId, 'poll: invalid sealed evidence');
420
+ }
335
421
  return {
422
+ ...(evidenceCt !== undefined ? { evidenceCt } : {}),
336
423
  status,
337
424
  phase,
338
425
  compoundToken: (data.compound_token ?? undefined),
339
426
  verifierProofs: data.verifier_proofs ?? undefined,
340
427
  bindingPreimage: (data.binding_preimage ?? undefined),
341
428
  error: (data.error ?? undefined),
342
- ...(typeof data.evidence_ct === 'string' ? { evidenceCt: data.evidence_ct } : {}),
343
429
  };
344
430
  }
345
431
  /**
@@ -356,9 +442,17 @@ export function nextPollDelay(previousMs, baseMs, maxMs, random = Math.random) {
356
442
  const jitter = (random() * 2 - 1) * 0.2 * grown;
357
443
  return Math.max(1, Math.round(grown + jitter));
358
444
  }
445
+ /** Progress order of the non-terminal phases; a long poll that answers with a later one saw a change. */
446
+ const PHASE_RANK = { awaiting_wallet: 0, verifying: 1, done: 2, failed: 2 };
359
447
  /**
360
448
  * Poll until the session reaches a terminal state (done or failed) - bounded by
361
449
  * `timeoutMs`, with a growing jittered interval so many clients never poll in lock-step.
450
+ * Every request asks the verifier-agent to hold its reply until the session moves
451
+ * (`?wait=1`). A reply whose phase moved forward is followed by the next request at once;
452
+ * an unchanged reply is followed by the backoff sleep, unless it took 15 s or more (the
453
+ * server's hold ended), when the next request also goes at once. A server without long-poll
454
+ * support answers at once and is polled on the backoff schedule. Any phase change resets the
455
+ * backoff to `intervalMs`.
362
456
  * A transient `unavailable` answer (a 503, a dropped connection) is retried within the
363
457
  * deadline; a `protocol` answer stops at once; the deadline is a `timeout` error; the
364
458
  * caller's `signal` is a `cancelled` error. A terminal `failed` is RETURNED (the caller
@@ -377,18 +471,37 @@ export async function waitForSession(verifierAgentUrl, sessionId, pollSecret, in
377
471
  const max = opts.maxIntervalMs ?? intervalMs * 4;
378
472
  let delay = 0;
379
473
  let lastUnavailable;
474
+ // A session opens awaiting the wallet; a reply in a later phase is a change.
475
+ let lastPhase = 'awaiting_wallet';
380
476
  while (true) {
381
477
  if (opts.signal?.aborted)
382
478
  throw new VerifierAgentSessionError('cancelled', sessionId, 'polling cancelled');
383
479
  if (Date.now() >= deadline) {
384
480
  throw new VerifierAgentSessionError('timeout', sessionId, lastUnavailable ? `no answer within ${timeoutMs} ms (last: ${lastUnavailable.message})` : `still pending after ${timeoutMs} ms`);
385
481
  }
482
+ let immediate = false, holdJitter = 0;
483
+ const started = Date.now();
386
484
  try {
387
- const result = await pollOid4vpSession(verifierAgentUrl, sessionId, pollSecret);
485
+ // The request never outlives the overall deadline.
486
+ const requestTimeout = Math.min(POLL_REQUEST_TIMEOUT_MS, deadline - started);
487
+ const result = await pollOid4vpSession(verifierAgentUrl, sessionId, pollSecret, { wait: true, timeoutMs: requestTimeout, ...(opts.signal ? { signal: opts.signal } : {}) });
388
488
  opts.onPhase?.(result.phase);
389
489
  if (result.status !== 'pending')
390
490
  return result;
391
491
  lastUnavailable = undefined;
492
+ if (result.phase !== lastPhase) {
493
+ // Progress (the wallet answered): the result is near, so restart the backoff.
494
+ // Only a FORWARD move skips the sleep, which bounds the immediate requests.
495
+ immediate = PHASE_RANK[result.phase] > PHASE_RANK[lastPhase];
496
+ lastPhase = result.phase;
497
+ delay = 0;
498
+ }
499
+ else if (Date.now() - started >= LONG_POLL_TIMEOUT_THRESHOLD_MS) {
500
+ // The server's hold ended. Re-poll now, spread by a small jitter so waits that began
501
+ // together do not keep re-polling in lock-step.
502
+ immediate = true;
503
+ holdJitter = Math.round((opts.random ?? Math.random)() * 0.1 * intervalMs);
504
+ }
392
505
  }
393
506
  catch (e) {
394
507
  if (e instanceof VerifierAgentSessionError && e.kind === 'unavailable') {
@@ -398,12 +511,14 @@ export async function waitForSession(verifierAgentUrl, sessionId, pollSecret, in
398
511
  throw e;
399
512
  }
400
513
  }
401
- delay = nextPollDelay(delay, intervalMs, max, opts.random);
514
+ if (immediate && holdJitter === 0)
515
+ continue;
516
+ const wait = immediate ? holdJitter : (delay = nextPollDelay(delay, intervalMs, max, opts.random));
402
517
  const remaining = deadline - Date.now();
403
518
  if (remaining <= 0)
404
519
  continue;
405
520
  await new Promise((resolve) => {
406
- const t = setTimeout(() => { opts.signal?.removeEventListener('abort', onAbort); resolve(); }, Math.min(delay, remaining));
521
+ const t = setTimeout(() => { opts.signal?.removeEventListener('abort', onAbort); resolve(); }, Math.min(wait, remaining));
407
522
  const onAbort = () => { clearTimeout(t); resolve(); };
408
523
  opts.signal?.addEventListener('abort', onAbort, { once: true });
409
524
  });
@@ -0,0 +1,7 @@
1
+ import { type PaymentIntentWire } from '../committee/payment.js';
2
+ import type { CreateSessionParams } from './index.js';
3
+ /** Internal shared wire validation for URL and authenticated-provider sessions. */
4
+ export declare function sessionPaymentFields(params: CreateSessionParams, clientId?: string): {
5
+ payment?: PaymentIntentWire;
6
+ random?: string;
7
+ };
@@ -0,0 +1,17 @@
1
+ import { assertPaymentIntentWire, paymentSessionCommitment } from '../committee/payment.js';
2
+ /** Internal shared wire validation for URL and authenticated-provider sessions. */
3
+ export function sessionPaymentFields(params, clientId) {
4
+ if (params.payment === undefined && params.random === undefined)
5
+ return {};
6
+ if (!params.payment || typeof params.random !== 'string' || !/^0x[0-9a-f]{64}$/i.test(params.random))
7
+ throw new Error('payment and its 32-byte random are required together');
8
+ assertPaymentIntentWire(params.payment);
9
+ const p = params.payment, op = params.operation;
10
+ const action = p.action === 'eoa-sign' ? 'sign' : p.action;
11
+ if (p.chain_id !== op.chain_id || p.slot.toLowerCase() !== op.slot_id.toLowerCase() || action !== op.action
12
+ || p.payload_digest.toLowerCase() !== op.payload_digest.toLowerCase() || p.expires !== op.exp)
13
+ throw new Error('payment differs from session operation or expiry');
14
+ if (clientId !== undefined && paymentSessionCommitment(params.random, clientId, op.exp).toLowerCase() !== p.session_commitment.toLowerCase())
15
+ throw new Error('payment does not bind the approved agent audience and random');
16
+ return { payment: p, random: params.random };
17
+ }
package/docs/api.md CHANGED
@@ -18,6 +18,7 @@ Install the latest SDK with `npm install @t3foundry/tasra-sdk@latest`; see
18
18
  |---|---|---|---|
19
19
  | `new TasraClient({manifest})` / `TasraClient.fromManifest(url)` | `@t3foundry/tasra-sdk/app` | Create slots, use wallets and credentials, encrypt and sign | Public deployment manifest; wallet and durable store for slot creation |
20
20
  | `createFileStore` | `@t3foundry/tasra-sdk/app/node` | Private durable state for a Node application | A private local directory |
21
+ | `createIndexedDbStore` | `@t3foundry/tasra-sdk/app/browser` | Durable browser state with cross-tab locks, plus fetch transports for paid flows | IndexedDB and the Web Locks API |
21
22
  | `createTasraChainClient` | `@t3foundry/tasra-sdk/chain` | Read contracts and discover the network | RPC, chain ID, deployment addresses |
22
23
  | `createTasraWriteClient` | `@t3foundry/tasra-sdk/chain` | Create slots, fund them, change on-chain state | Deployment configuration and funded transaction signer |
23
24
  | `createCommitteeSlotClient` | `@t3foundry/tasra-sdk/chain` | Credential-gated threshold encryption/decryption and FROST signing | Chain client, slot, holder, credentials and verifier proofs |
@@ -52,7 +53,9 @@ For Ethereum signatures, see [`signEoaDigest`](signing.md), not committee FROST
52
53
  `@t3foundry/tasra-sdk/app` provides `TasraClient`, the manifest loader, wallet and identity
53
54
  adapters, credential helpers, slot creation and native approval helpers.
54
55
  `@t3foundry/tasra-sdk/app/node` provides `createFileStore`; keep this Node-only import out of
55
- browser bundles. See the [application guide](application-api.md) for the normal
56
+ browser bundles. `@t3foundry/tasra-sdk/app/browser` provides `createIndexedDbStore` and the
57
+ fetch-based `createBrowserPaidAgentTransport`, `createBrowserKeeperRecoveryTransport`
58
+ and `createBrowserRelayTransport`. See the [application guide](application-api.md) for the normal
56
59
  workflow and [generated application reference](reference/app.md) for complete signatures.
57
60
 
58
61
  ## Main entry exports
@@ -321,7 +324,10 @@ import {verifyCompoundToken, selectVerifierCommittee} from '@t3foundry/tasra-sdk
321
324
  It also carries the derivations `platformAudience(origin, chainId)` and
322
325
  `dpopHtu(origin, sessionId)` (+ `normalizeOrigin`, `isValidSessionId`,
323
326
  `OAUTH_RESPONSE_PATH_PREFIX`/`_SUFFIX`), vector-pinned byte for byte
324
- against `keykeeper-committee`'s `oauth` module (`test/dpop.ts`).
327
+ against `keykeeper-committee`'s `oauth` module (`test/dpop.ts`). Use these helpers
328
+ to preserve the deployment protocol's exact audience and URI binding. `legacyDpopHtu` and
329
+ `OAUTH_RESPONSE_PATH` name the pre-remediation session-independent target; new paid sessions
330
+ never accept it as a fallback.
325
331
 
326
332
  **Most consumers never need it.** Typed slots on `TasraClient` handle these
327
333
  operations. Advanced integrations can use `createCommitteeSlotClient` from
@@ -9,6 +9,12 @@ credentials. Existing `createTasra` and lower-level APIs remain available. The a
9
9
  chooses its policy, consent behavior and private storage; the SDK handles network
10
10
  operations and cryptographic checks.
11
11
 
12
+ For a prepaid deployment, reserve the creator-signed operation with
13
+ `reserveApplicationPayment` and retain its original session. Use one durable store and a
14
+ dedicated gas payer across operations; recover uncertain submissions with
15
+ `reconcileApplicationPayment` before spending again. See [slot funding](funding.md) for
16
+ the required discovery, fee limits, journal guarantees and recovery limits.
17
+
12
18
  Install the latest SDK from npm as your application dependency. TypeScript and
13
19
  `tsx` are development tools:
14
20
 
@@ -125,6 +131,8 @@ or change the slot name to force a retry.
125
131
 
126
132
  An abrupt process kill can leave a `createFileStore` lock behind. The SDK deliberately
127
133
  does not expire or steal locks, and currently has no public stale-lock recovery method.
134
+ A later call waits up to the store's `lockWaitMs` (default 10 s) for such a lock and then
135
+ refuses with `StoreLockedError`; calls within one process queue and never refuse each other.
128
136
  Stop, preserve the private store, establish that the owning process has ended, and
129
137
  reconcile outstanding transactions before any manual intervention. Do not infer that
130
138
  an old lock is safe to remove from its age alone.
@@ -241,10 +249,18 @@ it; after a lost response, look up that hash before considering another submissi
241
249
  const notes = await tasra.slots.bls(slotId)
242
250
  // issuerDid is the trusted credential issuer pinned by this slot's rule.
243
251
  const identity = `${issuerDid}/notes/${crypto.randomUUID()}/version/1`
244
- const ciphertext = await notes.encrypt(identity, new TextEncoder().encode('Hello'))
245
- const {plaintext, evidence} = await notes.decrypt(identity, ciphertext, {authorize})
252
+ const ciphertext = await notes.encryptForIdentity(identity, new TextEncoder().encode('Hello'))
253
+ // recipient: createDecryptionRecipient(); verifyingShares: discoverBlsSharing(...).verifyingShares
254
+ const {plaintext, evidence} = await notes.decryptForIdentity(identity, ciphertext, {recipient, verifyingShares, authorize})
246
255
  ```
247
256
 
257
+ The handle offers two schemes. `encryptForIdentity` / `decryptForIdentity` / `extractIdentityKey`
258
+ are identity-based encryption (IBE): encrypt to an identity string before anyone holds a key,
259
+ and decryption is scoped to that identity. `encrypt(aad, dataKey)` / `decrypt(aad, kemCt, ...)`
260
+ wrap a 32-byte data key with BLS KEM under the slot itself; see the
261
+ [encrypted-notes guide](encrypted-notes.md). Both decrypt on the client from verified,
262
+ recipient-sealed threshold shares.
263
+
248
264
  This uses `kk_scope_namespace: 'issuer'`: the credential must grant this identity,
249
265
  and the committed rule must require the scope claim. The complete
250
266
  [encrypted-notes app](../examples/encrypted-notes.ts) shows issuer, rule and credential setup.
@@ -254,6 +270,13 @@ assigned keeper quorum, one epoch, valid shares and a combined identity key matc
254
270
  the chain-anchored group key. Temporary extraction shares and the intermediate
255
271
  identity key are cleared. The returned plaintext belongs to your app.
256
272
 
273
+ Extraction completes after the first verified quorum and cancels remaining keeper
274
+ requests. Invalid replies and duplicate share identifiers do not count. A stalled
275
+ fetch, approval or response body cannot hold the fan-out past its deadline (10 seconds
276
+ by default; pass `timeoutMs` in the identity operation options to change it).
277
+ This deadline starts after wallet authorization. Replies are limited to 16 KiB.
278
+ Cancelling a request does not undo paid work a keeper already started.
279
+
257
280
  Use a fresh identity for every immutable document version. An extracted identity
258
281
  key is a durable capability: token expiry does not revoke it. `extractIdentity`
259
282
  returns that capability only when your app explicitly needs custody.