@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.
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
package/README.md CHANGED
@@ -136,3 +136,18 @@ The package has [not had an independent cryptographic audit](SECURITY.md#cryptog
136
136
 
137
137
  [Contributing](https://github.com/t3foundry/tasra-sdk/blob/develop/CONTRIBUTING.md) · [Changelog](CHANGELOG.md) ·
138
138
  [Security](SECURITY.md) · [Apache-2.0 license](LICENSE)
139
+ ## Sealed committee evidence
140
+
141
+ When an authorization includes sealed presentation evidence, retain its `evidenceCt`
142
+ alongside the token and verifier proofs. Low-level sign, decrypt, IBE, ECDSA and
143
+ credentialed dual-approval calls accept this same `evidenceCt`; they check its
144
+ ciphertext hash before requesting execution approval or submitting a keeper body.
145
+ Application authorizers must return it in `OperationGrant`. Paid operations retain
146
+ it in their original journal and expose `PaidOperation.evidenceCt` for keeper calls.
147
+
148
+ `requestCommitteeToken` and the one-call committee helpers retain and forward this
149
+ field automatically. Direct `gatherCommitteeToken` callers must provide `onEvidence`
150
+ to retain the ciphertext beside the returned token. Mixed or conflicting sealed
151
+ replies refuse; the SDK never strips evidence to assemble an unsealed fallback.
152
+ Keep ciphertext and journals private. Production sealing acceptance still requires
153
+ a fleet configured to require evidence and an actual native test.
@@ -1,9 +1,11 @@
1
1
  import { type Hex } from 'viem';
2
2
  import { type DualSignApprover, type DualSignRequest } from '../committee/dual-sign.js';
3
3
  import type { TasraApplication, OperationAuthorizer } from './client.js';
4
+ import { type PaymentIntentWire } from '../committee/payment.js';
4
5
  import type { TasraIdentity } from './identity.js';
5
6
  import type { ApplicationStore } from './ready-slot.js';
6
- import type { TasraWallet } from './wallet.js';
7
+ import type { TasraWallet, WalletTransactionJournal } from './wallet.js';
8
+ import { type DualOperationApprovalRecord, type DualOperationProof, type PreparedDualOperation } from '../committee/dual-operation.js';
7
9
  /**
8
10
  * Required approval count and either trusted Ed25519 keys or a credential rule.
9
11
  */
@@ -17,10 +19,39 @@ export interface ApprovalPolicy {
17
19
  /** Exact raw DCQL rule whose unsalted hash the network must enforce. */
18
20
  credentialPolicy?: string;
19
21
  }
22
+ /** A slot's installed native approval policy, as `KeyRegistry` holds it. */
23
+ export interface InstalledApprovalPolicy {
24
+ /** Required distinct approvals; 0 means no policy is installed. */
25
+ quorum: number;
26
+ /** keccak256 of the raw credential rule, or zero for static approvers. */
27
+ ruleHash: Hex;
28
+ /** Static Ed25519 approver keys (lowercase hex), empty for a credential policy. */
29
+ approvers: Hex[];
30
+ }
31
+ /** The policy was already on chain exactly as requested: nothing was sent (the policy is set-once). */
32
+ export interface ApprovalPolicyAlreadyInstalled {
33
+ /** Nothing was sent: the requested policy is the installed one. */
34
+ phase: 'already-installed';
35
+ /** The slot whose policy was found installed. */
36
+ slotId: Hex;
37
+ /** No transaction: kept so code reading `.hash` of a journal still compiles. */
38
+ hash?: undefined;
39
+ }
40
+ /**
41
+ * Read a slot's native approval policy (`KeyRegistry.dualControlPolicy` / `dualControlApprovers`).
42
+ * @param app Application client for the slot deployment.
43
+ * @param slotId Slot to read.
44
+ */
45
+ export declare function readApprovalPolicy(app: Pick<TasraApplication, 'deployment' | 'chain'>, slotId: Hex): Promise<InstalledApprovalPolicy>;
20
46
  /**
21
- * Install an explicit native FROST approval policy using a durable named transaction.
47
+ * Install an explicit native approval policy using a durable named transaction, on a FROST, BLS or
48
+ * threshold ECDSA (secp256k1 or P-256) slot. The slot creator's wallet sends it
49
+ * (`KeyRegistry.setDualControlPolicy`); no slot-key signature is involved. The policy is SET-ONCE:
50
+ * an identical policy already on chain resolves `already-installed` without sending, a different
51
+ * one refuses before sending. A transaction whose outcome was unknown is reconciled by calling this
52
+ * again with the same name (the wallet's journal), never by a replacement.
22
53
  * @param app Application client for the slot deployment.
23
- * @param slotId FROST slot whose approval policy is being installed.
54
+ * @param slotId Slot whose approval policy is being installed.
24
55
  * @param input Required quorum and either approver keys or a credential rule.
25
56
  * @param options Creator wallet and durable store for the named policy transaction.
26
57
  */
@@ -28,7 +59,7 @@ export declare function setApprovalPolicy(app: Pick<TasraApplication, 'deploymen
28
59
  wallet: TasraWallet;
29
60
  store: ApplicationStore;
30
61
  name?: string;
31
- }): Promise<import("./wallet.js").WalletTransactionJournal>;
62
+ }): Promise<WalletTransactionJournal | ApprovalPolicyAlreadyInstalled>;
32
63
  /**
33
64
  * Adapt an SDK Ed25519 identity to native approval signatures without exporting its key.
34
65
  * @param identity Live Ed25519 identity used to sign approval payloads.
@@ -47,4 +78,35 @@ export declare function approveWithCredential(app: Pick<TasraApplication, 'deplo
47
78
  authorize: OperationAuthorizer;
48
79
  signal?: AbortSignal;
49
80
  description?: string;
81
+ /** Separate reserved credential approval intent; never the final keeper Sign intent. */
82
+ payment?: PaymentIntentWire;
83
+ /** Fixed presentation random committed by the approval payment. */
84
+ random?: string;
50
85
  }): Promise<import("../committee/dual-sign.js").DualSignStatus>;
86
+ /**
87
+ * Prepare the approval statement for ONE final paid operation (a threshold ECDSA `eoa-sign`, a
88
+ * KEM decrypt or an IBE extraction), bound to its slot, payload digest, key epoch, request ID and
89
+ * payment hash, current for at most 300 s. Reads the slot (mode, epoch, readiness) and the policy;
90
+ * sends nothing. Hand the result to each approver (`approveDualOperation`), then assemble.
91
+ * @param app Application client for the slot deployment.
92
+ * @param input The final payment (as reserved; a debit voucher is allowed), IBE identity and lifetime.
93
+ */
94
+ export declare function prepareOperationApproval(app: Pick<TasraApplication, 'deployment' | 'chain' | 'slots'>, input: {
95
+ payment: PaymentIntentWire;
96
+ identity?: string;
97
+ ttlSecs?: number;
98
+ nowSecs?: number;
99
+ }): Promise<PreparedDualOperation>;
100
+ /**
101
+ * Assemble independent approvals of one prepared statement into the `dual_control` bundle, judged
102
+ * against the slot's ON-CHAIN policy before any paid send: its quorum, and for a static policy every
103
+ * approver's membership. Signatures verify strictly; duplicates and approvals of another statement
104
+ * refuse. The keeper and every ECDSA member re-check all of it.
105
+ * @param app Application client for the slot deployment.
106
+ * @param input Prepared statement and approval records.
107
+ */
108
+ export declare function assembleOperationApproval(app: Pick<TasraApplication, 'deployment' | 'chain'>, input: {
109
+ prepared: PreparedDualOperation;
110
+ approvals: DualOperationApprovalRecord[];
111
+ nowSecs?: number;
112
+ }): Promise<DualOperationProof>;
@@ -4,13 +4,52 @@ import { sha256 } from '@noble/hashes/sha256';
4
4
  import { encodeFunctionData, keccak256, toHex } from 'viem';
5
5
  import { validate } from '../auth/oid4vp.js';
6
6
  import { keyRegistryAbi } from '../chain/abis/index.js';
7
- import { dualSignApprovalPayload } from '../committee/dual-sign.js';
7
+ import { dualSignApprovalPayload, paidDualSignApprovalPayload } from '../committee/dual-sign.js';
8
8
  import { protocolHex } from '../committee/receipts.js';
9
9
  import { b64urlDecode } from '../oid4vp/jose.js';
10
+ import { assertPaymentIntentWire, paymentIntentHash } from '../committee/payment.js';
11
+ import { TasraApplicationError } from './client.js';
12
+ import { assembleDualOperation, prepareDualOperation } from '../committee/dual-operation.js';
13
+ /** Key modes the network enforces operation approvals on: FROST (collector), BLS (KEM/IBE), secp256k1 and P-256 tECDSA. */
14
+ const POLICY_MODES = [0, 1, 2, 4];
15
+ const ZERO32 = `0x${'00'.repeat(32)}`;
10
16
  /**
11
- * Install an explicit native FROST approval policy using a durable named transaction.
17
+ * Read a slot's native approval policy (`KeyRegistry.dualControlPolicy` / `dualControlApprovers`).
12
18
  * @param app Application client for the slot deployment.
13
- * @param slotId FROST slot whose approval policy is being installed.
19
+ * @param slotId Slot to read.
20
+ */
21
+ export async function readApprovalPolicy(app, slotId) {
22
+ protocolHex(slotId, 32, 'slot id');
23
+ const registry = app.deployment.addresses.KeyRegistry;
24
+ const [policy, keys] = await Promise.all([
25
+ app.chain.client.readContract({ address: registry, abi: keyRegistryAbi, functionName: 'dualControlPolicy', args: [slotId] }),
26
+ app.chain.client.readContract({ address: registry, abi: keyRegistryAbi, functionName: 'dualControlApprovers', args: [slotId] }),
27
+ ]);
28
+ return { quorum: Number(policy[0]), ruleHash: policy[1].toLowerCase(), approvers: keys.map(key => key.toLowerCase()) };
29
+ }
30
+ function samePolicy(observed, quorum, ruleHash, keys) {
31
+ const expected = keys.map(key => key.toLowerCase()).sort(), actual = [...observed.approvers].sort();
32
+ return observed.quorum === quorum && observed.ruleHash === ruleHash.toLowerCase()
33
+ && expected.length === actual.length && expected.every((key, i) => key === actual[i]);
34
+ }
35
+ /** A ready slot in a mode the network enforces approvals on; the same errors `app.slots.frost` gave. */
36
+ async function policySlot(app, slotId) {
37
+ const slot = await app.slots.get(slotId);
38
+ if (!POLICY_MODES.includes(slot.mode))
39
+ throw new TasraApplicationError('WRONG_SLOT_MODE', `Slot mode ${slot.mode} does not support native approvals`);
40
+ if (!slot.ready)
41
+ throw new TasraApplicationError('KEY_NOT_READY', 'Slot key generation has not completed');
42
+ return slot;
43
+ }
44
+ /**
45
+ * Install an explicit native approval policy using a durable named transaction, on a FROST, BLS or
46
+ * threshold ECDSA (secp256k1 or P-256) slot. The slot creator's wallet sends it
47
+ * (`KeyRegistry.setDualControlPolicy`); no slot-key signature is involved. The policy is SET-ONCE:
48
+ * an identical policy already on chain resolves `already-installed` without sending, a different
49
+ * one refuses before sending. A transaction whose outcome was unknown is reconciled by calling this
50
+ * again with the same name (the wallet's journal), never by a replacement.
51
+ * @param app Application client for the slot deployment.
52
+ * @param slotId Slot whose approval policy is being installed.
14
53
  * @param input Required quorum and either approver keys or a credential rule.
15
54
  * @param options Creator wallet and durable store for the named policy transaction.
16
55
  */
@@ -31,21 +70,24 @@ export async function setApprovalPolicy(app, slotId, input, options) {
31
70
  }
32
71
  if (credentialPolicy !== undefined)
33
72
  validate(credentialPolicy);
34
- const ruleHash = credentialPolicy === undefined ? `0x${'00'.repeat(32)}` : keccak256(toHex(credentialPolicy));
35
- const data = encodeFunctionData({ abi: keyRegistryAbi, functionName: 'setDualControlPolicy', args: [slotId, quorum, ruleHash, (approvers ?? []).map(key => toHex(key))] });
36
- await app.slots.frost(slotId);
73
+ const ruleHash = credentialPolicy === undefined ? ZERO32 : keccak256(toHex(credentialPolicy));
74
+ const keys = (approvers ?? []).map(key => toHex(key));
75
+ const data = encodeFunctionData({ abi: keyRegistryAbi, functionName: 'setDualControlPolicy', args: [slotId, quorum, ruleHash, keys] });
76
+ await policySlot(app, slotId);
37
77
  if (wallet.wallet.chain.id !== app.deployment.chainId)
38
78
  throw new Error('Approval wallet uses a different chain');
79
+ // Set-once: judge what is on chain before anything is signed or sent.
80
+ const before = await readApprovalPolicy(app, slotId);
81
+ if (before.quorum !== 0) {
82
+ if (samePolicy(before, quorum, ruleHash, keys))
83
+ return { phase: 'already-installed', slotId };
84
+ throw new Error('A different approval policy is already installed on this slot; policies are set-once');
85
+ }
39
86
  const transaction = await wallet.transfer(name, { to: app.deployment.addresses.KeyRegistry, data }, store);
40
- const [observed, observedKeys] = await Promise.all([
41
- app.chain.client.readContract({ address: app.deployment.addresses.KeyRegistry, abi: keyRegistryAbi, functionName: 'dualControlPolicy', args: [slotId] }),
42
- app.chain.client.readContract({ address: app.deployment.addresses.KeyRegistry, abi: keyRegistryAbi, functionName: 'dualControlApprovers', args: [slotId] }),
43
- ]);
44
- if (observed[0] !== quorum || observed[1].toLowerCase() !== ruleHash.toLowerCase())
87
+ const observed = await readApprovalPolicy(app, slotId);
88
+ if (observed.quorum !== quorum || observed.ruleHash !== ruleHash.toLowerCase())
45
89
  throw new Error('On-chain approval policy differs from the requested policy');
46
- const expectedKeys = (approvers ?? []).map(key => toHex(key)).sort();
47
- const actualKeys = observedKeys.map(key => key.toLowerCase()).sort();
48
- if (expectedKeys.length !== actualKeys.length || expectedKeys.some((key, i) => key !== actualKeys[i]))
90
+ if (!samePolicy(observed, quorum, ruleHash, keys))
49
91
  throw new Error('On-chain approval keys differ from the requested policy');
50
92
  return transaction;
51
93
  }
@@ -79,12 +121,107 @@ export function identityApprover(identity) {
79
121
  */
80
122
  export async function approveWithCredential(app, request, message, options) {
81
123
  const { identity, authorize, signal, description } = options;
82
- const slotId = request.slotId, canonical = dualSignApprovalPayload(slotId, message.slice(), request.requestId);
124
+ const slotId = request.slotId, payment = request.payment;
125
+ const canonical = payment ? paidDualSignApprovalPayload(app.deployment.chainId, slotId, message.slice(), request.requestId, payment)
126
+ : dualSignApprovalPayload(slotId, message.slice(), request.requestId);
127
+ signal?.throwIfAborted();
128
+ const current = await request.status({ signal });
129
+ if (current.status !== 'pending')
130
+ return current;
131
+ const approvalPayment = options.payment && structuredClone(options.payment);
132
+ const nowSecs = Math.floor(Date.now() / 1000);
133
+ if (payment && (!approvalPayment || !options.random))
134
+ throw new Error('Paid credential approval needs its own reservation and presentation random');
135
+ if ((approvalPayment === undefined) !== (options.random === undefined))
136
+ throw new Error('Approval payment and presentation random are required together');
137
+ if (options.random !== undefined && !/^0x[0-9a-f]{64}$/i.test(options.random))
138
+ throw new Error('Approval presentation random must contain 32 bytes');
139
+ if (approvalPayment) {
140
+ assertPaymentIntentWire(approvalPayment);
141
+ if (approvalPayment.action !== 'dual-approve' || approvalPayment.chain_id !== app.deployment.chainId || approvalPayment.expires <= nowSecs ||
142
+ approvalPayment.key_registry.toLowerCase() !== app.deployment.addresses.KeyRegistry.toLowerCase() ||
143
+ (payment && approvalPayment.settlement.toLowerCase() !== payment.settlement.toLowerCase()) ||
144
+ approvalPayment.slot.toLowerCase() !== slotId.toLowerCase() || !equalBytes(protocolHex(approvalPayment.payload_digest, 32, 'approval digest'), sha256(canonical))) {
145
+ throw new Error('Approval reservation differs from requested credential work');
146
+ }
147
+ }
83
148
  const signer = identityApprover(identity);
84
149
  signal?.throwIfAborted();
85
150
  await app.slots.frost(slotId);
86
151
  const authorization = await authorize({ chainId: app.deployment.chainId, keyRegistry: app.deployment.addresses.KeyRegistry,
87
- slotId, action: 'dual-approve', payloadDigest: sha256(canonical), description: description ?? 'Approve exact document request', signal });
152
+ slotId, action: 'dual-approve', payloadDigest: sha256(canonical), description: description ?? 'Approve exact document request', signal,
153
+ ...(approvalPayment ? { payment: structuredClone(approvalPayment), random: options.random, nowSecs, ttlSecs: approvalPayment.expires - nowSecs } : {}) });
88
154
  signal?.throwIfAborted();
155
+ if (approvalPayment) {
156
+ assertPaymentIntentWire(authorization.token.payment);
157
+ const expected = paymentIntentHash(approvalPayment);
158
+ if (paymentIntentHash(authorization.token.payment) !== expected ||
159
+ !equalBytes(protocolHex(authorization.token.payment_hash, 32, 'approval payment hash'), protocolHex(expected, 32, 'payment hash')) ||
160
+ !Number.isSafeInteger(authorization.token.exp) || authorization.token.exp > approvalPayment.expires)
161
+ throw new Error('Credential authorization changed the reserved approval payment');
162
+ }
89
163
  return request.approve({ signer, authorization, signal });
90
164
  }
165
+ /** The operation a slot mode's approvals name: FROST signs through the keeper's collector instead. */
166
+ function operationKind(mode, action) {
167
+ if (action === 'eoa-sign' && mode === 2)
168
+ return 'secp256k1-sign';
169
+ if (action === 'eoa-sign' && mode === 4)
170
+ return 'p256-sign';
171
+ if (action === 'decrypt' && mode === 1)
172
+ return 'kem-decrypt';
173
+ if (action === 'ibe-extract' && mode === 1)
174
+ return 'ibe-extract';
175
+ if (mode === 0)
176
+ throw new TasraApplicationError('WRONG_SLOT_MODE', 'FROST signatures collect approvals through slot.approvals(), not an operation bundle');
177
+ throw new TasraApplicationError('WRONG_SLOT_MODE', `Slot mode ${mode} has no operation approvals for action ${action}`);
178
+ }
179
+ /**
180
+ * Prepare the approval statement for ONE final paid operation (a threshold ECDSA `eoa-sign`, a
181
+ * KEM decrypt or an IBE extraction), bound to its slot, payload digest, key epoch, request ID and
182
+ * payment hash, current for at most 300 s. Reads the slot (mode, epoch, readiness) and the policy;
183
+ * sends nothing. Hand the result to each approver (`approveDualOperation`), then assemble.
184
+ * @param app Application client for the slot deployment.
185
+ * @param input The final payment (as reserved; a debit voucher is allowed), IBE identity and lifetime.
186
+ */
187
+ export async function prepareOperationApproval(app, input) {
188
+ const payment = structuredClone(input.payment);
189
+ assertPaymentIntentWire(payment);
190
+ if (payment.chain_id !== app.deployment.chainId || payment.key_registry.toLowerCase() !== app.deployment.addresses.KeyRegistry.toLowerCase()) {
191
+ throw new TasraApplicationError('INVALID_AUTHORIZATION', 'Payment names another chain or registry');
192
+ }
193
+ const slotId = payment.slot.toLowerCase();
194
+ const [slot, policy] = await Promise.all([policySlot(app, slotId), readApprovalPolicy(app, slotId)]);
195
+ if (policy.quorum === 0)
196
+ throw new TasraApplicationError('INVALID_AUTHORIZATION', 'Slot has no native approval policy');
197
+ if (payment.keeper_assignment.key_epoch !== slot.epoch)
198
+ throw new TasraApplicationError('SLOT_CHANGED', 'Payment names another key epoch than the slot');
199
+ return prepareDualOperation({ payment, operation: operationKind(slot.mode, payment.action), epoch: slot.epoch,
200
+ ...(input.identity !== undefined ? { identity: input.identity } : {}), ...(input.ttlSecs !== undefined ? { ttlSecs: input.ttlSecs } : {}),
201
+ ...(input.nowSecs !== undefined ? { nowSecs: input.nowSecs } : {}) });
202
+ }
203
+ /**
204
+ * Assemble independent approvals of one prepared statement into the `dual_control` bundle, judged
205
+ * against the slot's ON-CHAIN policy before any paid send: its quorum, and for a static policy every
206
+ * approver's membership. Signatures verify strictly; duplicates and approvals of another statement
207
+ * refuse. The keeper and every ECDSA member re-check all of it.
208
+ * @param app Application client for the slot deployment.
209
+ * @param input Prepared statement and approval records.
210
+ */
211
+ export async function assembleOperationApproval(app, input) {
212
+ const slotId = toHex(Uint8Array.from(input.prepared.statement.slot));
213
+ const policy = await readApprovalPolicy(app, slotId);
214
+ if (policy.quorum === 0)
215
+ throw new TasraApplicationError('INVALID_AUTHORIZATION', 'Slot has no native approval policy');
216
+ if (policy.ruleHash === ZERO32) {
217
+ const members = new Set(policy.approvers.map(key => key.slice(2)));
218
+ for (const record of input.approvals) {
219
+ if (!members.has(String(record.approval?.approver_pubkey ?? '').replace(/^0x/, '').toLowerCase()))
220
+ throw new TasraApplicationError('INVALID_AUTHORIZATION', 'Approver is not in the slot\'s approver set');
221
+ }
222
+ }
223
+ else if (input.approvals.some(record => record.approval?.committee_token === undefined)) {
224
+ throw new TasraApplicationError('INVALID_AUTHORIZATION', 'Credential-gated approvals need each approver\'s holder-bound grant');
225
+ }
226
+ return assembleDualOperation({ prepared: input.prepared, approvals: input.approvals, quorum: policy.quorum, ...(input.nowSecs !== undefined ? { nowSecs: input.nowSecs } : {}) });
227
+ }
@@ -10,7 +10,7 @@ import type { OperationAuthorizer } from './client.js';
10
10
  * @param config Approved agent client, operation signer, wallet presentation callback and polling controls.
11
11
  */
12
12
  export declare function registeredWalletAuthorization(config: {
13
- client: ReturnType<typeof createRegisteredAgentClient>;
13
+ client: Pick<ReturnType<typeof createRegisteredAgentClient>, 'createSession'>;
14
14
  signer: TypedDataSigner;
15
15
  delegation?: PresentationDelegation;
16
16
  present: (session: RegisteredVerifierAgentSession, signal?: AbortSignal) => Promise<void>;
@@ -15,6 +15,6 @@ export function registeredWalletAuthorization(config) {
15
15
  const result = await awaitRegisteredVerifierAgentResult(session, { signal: request.signal, onPhase, timeoutMs });
16
16
  if (!result.verifierProofs?.length)
17
17
  throw new Error('Authorization did not include verifier membership proofs');
18
- return { token: result.token, verifierProofs: result.verifierProofs };
18
+ return { token: result.token, verifierProofs: result.verifierProofs, ...(result.evidenceCt !== undefined ? { evidenceCt: result.evidenceCt } : {}) };
19
19
  };
20
20
  }
@@ -0,0 +1,63 @@
1
+ /** Browser durable state and paid-flow transports. Import from tasra-sdk/app/browser. */
2
+ import type { PaidAgentTransport } from '../chain/paidAgentTransport.js';
3
+ import type { KeeperRecoveryTransport } from '../chain/keeperRecovery.js';
4
+ import type { RelayTransport } from '../chain/registeredRelay.js';
5
+ import type { ApplicationStore } from './ready-slot.js';
6
+ import { StoreLockedError } from './store-errors.js';
7
+ export { StoreLockedError };
8
+ export type { ApplicationStore };
9
+ /** Options for {@link createIndexedDbStore}. */
10
+ export interface IndexedDbStoreOptions {
11
+ /** Database name; one per application and deployment (default `tasra-sdk-state`). */
12
+ name?: string;
13
+ /** IndexedDB factory (default `globalThis.indexedDB`). */
14
+ indexedDB?: IDBFactory;
15
+ /** Web Locks manager (default `navigator.locks`). Required: tabs must share exclusive locks. */
16
+ locks?: LockManager;
17
+ /** Fail with StoreLockedError instead of waiting when another tab holds the lock (default false: wait). */
18
+ failIfLocked?: boolean;
19
+ }
20
+ /**
21
+ * Durable private state for browser applications: IndexedDB records committed with strict
22
+ * durability before `save` resolves, and Web Locks (exclusive, shared by every tab, worker and
23
+ * extension service worker of this origin) for `withLock`. Values must be plain data (strings,
24
+ * finite numbers, booleans, bigints, Uint8Array, arrays and plain objects).
25
+ * @param options Database name, factory/lock overrides and lock-wait behavior.
26
+ */
27
+ export declare function createIndexedDbStore(options?: IndexedDbStoreOptions): ApplicationStore;
28
+ /** Options shared by the browser transports. */
29
+ export interface BrowserTransportOptions {
30
+ /** Fetch implementation (default global fetch). */
31
+ fetch?: typeof fetch;
32
+ /** Exact loopback names or private IP literals the application approves (e.g. `localhost` during local development). */
33
+ allowedPrivateHosts?: readonly string[];
34
+ /** Absolute per-request deadline in ms (default 30000). */
35
+ timeoutMs?: number;
36
+ }
37
+ /**
38
+ * Browser transport for registered paid sessions: authenticated discovery plus owner-only
39
+ * session control, with the same route, method, bearer and bound checks as the Node transport.
40
+ * @param options Fetch override, approved private hosts and request deadline.
41
+ */
42
+ export declare function createBrowserPaidAgentTransport(options?: BrowserTransportOptions): PaidAgentTransport;
43
+ /** Options for {@link createBrowserKeeperRecoveryTransport}. */
44
+ export interface BrowserKeeperRecoveryTransportOptions extends BrowserTransportOptions {
45
+ /**
46
+ * Local development fleet: also permit plain HTTP to loopback names and private IP literals
47
+ * (and only those), like the keepers of a local chain. Default false: HTTPS only. The recovery
48
+ * reads separately permit HTTP only on the local development chain (43112) with the paid
49
+ * operation's `allowLocalHttp`.
50
+ */
51
+ allowLocalHttp?: boolean;
52
+ }
53
+ /**
54
+ * Browser transport for reading a keeper's retained paid result (the two POST recovery reads only).
55
+ * @param options Fetch override, approved private hosts, local development HTTP and request deadline.
56
+ */
57
+ export declare function createBrowserKeeperRecoveryTransport(options?: BrowserKeeperRecoveryTransportOptions): KeeperRecoveryTransport;
58
+ /**
59
+ * Browser transport for registered relayers: discovery, forward and status, with
60
+ * `relayExchange` reporting busy refusals and their `Retry-After`.
61
+ * @param options Fetch override, approved private hosts and request deadline.
62
+ */
63
+ export declare function createBrowserRelayTransport(options?: BrowserTransportOptions): RelayTransport;
@@ -0,0 +1,242 @@
1
+ /** Browser durable state and paid-flow transports. Import from tasra-sdk/app/browser. */
2
+ //
3
+ // The paid flow needs two things a page, an extension service worker or a PWA must supply:
4
+ // state that survives a crash and is exclusive across tabs (a reservation's gas payer, a
5
+ // session's journaled writes), and HTTP transports that never follow redirects, never send
6
+ // cookies and bound every reply. IndexedDB with a strict-durability commit gives the first,
7
+ // the Web Locks API (navigator.locks) the exclusivity, and fetch the transports.
8
+ //
9
+ // ⚠ A browser cannot check where a hostname resolves, so unlike the Node transports these
10
+ // cannot refuse a public name that points at a private address. They require HTTPS (as every
11
+ // registered service endpoint does) and refuse loopback names and private IP literals unless
12
+ // the application approves them; rely on the browser's private-network protections for the rest. Services must allow
13
+ // this origin through CORS (and expose `Retry-After` for retry hints).
14
+ import { TasraError } from '../errors.js';
15
+ import { parseRetryAfter } from '../internal/retryAfter.js';
16
+ import { acceptsServiceResponse, serviceRequestShape } from '../chain/serviceRequestPolicy.js';
17
+ import { StoreLockedError } from './store-errors.js';
18
+ export { StoreLockedError };
19
+ const KEY = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
20
+ function assertPlain(value, seen = new Set()) {
21
+ if (value === null || value === undefined || typeof value === 'string' || typeof value === 'boolean' || typeof value === 'bigint')
22
+ return;
23
+ if (typeof value === 'number') {
24
+ if (Number.isFinite(value))
25
+ return;
26
+ throw new TasraError('State must contain finite numbers');
27
+ }
28
+ if (value instanceof Uint8Array)
29
+ return;
30
+ if (typeof value !== 'object' || seen.has(value))
31
+ throw new TasraError('State must contain finite plain data without cycles');
32
+ seen.add(value);
33
+ try {
34
+ if (Array.isArray(value)) {
35
+ for (const item of value)
36
+ assertPlain(item, seen);
37
+ return;
38
+ }
39
+ const proto = Object.getPrototypeOf(value);
40
+ if (proto !== Object.prototype && proto !== null)
41
+ throw new TasraError('State must contain plain objects');
42
+ for (const item of Object.values(value))
43
+ assertPlain(item, seen);
44
+ }
45
+ finally {
46
+ seen.delete(value);
47
+ }
48
+ }
49
+ function request(r) {
50
+ return new Promise((resolve, reject) => { r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error ?? new TasraError('IndexedDB request failed')); });
51
+ }
52
+ /**
53
+ * Durable private state for browser applications: IndexedDB records committed with strict
54
+ * durability before `save` resolves, and Web Locks (exclusive, shared by every tab, worker and
55
+ * extension service worker of this origin) for `withLock`. Values must be plain data (strings,
56
+ * finite numbers, booleans, bigints, Uint8Array, arrays and plain objects).
57
+ * @param options Database name, factory/lock overrides and lock-wait behavior.
58
+ */
59
+ export function createIndexedDbStore(options = {}) {
60
+ const name = options.name ?? 'tasra-sdk-state';
61
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name))
62
+ throw new TasraError('Invalid IndexedDB store name');
63
+ const factory = options.indexedDB ?? globalThis.indexedDB;
64
+ const locks = options.locks ?? globalThis.navigator?.locks;
65
+ if (!factory)
66
+ throw new TasraError('IndexedDB is unavailable; paid state needs durable browser storage');
67
+ if (!locks || typeof locks.request !== 'function')
68
+ throw new TasraError('Web Locks are unavailable; paid state needs locks shared across tabs');
69
+ let opened;
70
+ const db = () => opened ??= new Promise((resolve, reject) => {
71
+ const open = factory.open(name, 1);
72
+ open.onupgradeneeded = () => { if (!open.result.objectStoreNames.contains('state'))
73
+ open.result.createObjectStore('state'); };
74
+ open.onsuccess = () => resolve(open.result);
75
+ open.onerror = () => { opened = undefined; reject(open.error ?? new TasraError('IndexedDB open failed')); };
76
+ open.onblocked = () => { opened = undefined; reject(new TasraError('IndexedDB open blocked by another version')); };
77
+ });
78
+ const check = (key) => { if (typeof key !== 'string' || !KEY.test(key))
79
+ throw new TasraError('Invalid state key'); };
80
+ return {
81
+ async load(key) {
82
+ check(key);
83
+ const tx = (await db()).transaction('state', 'readonly');
84
+ return await request(tx.objectStore('state').get(key));
85
+ },
86
+ async save(key, value) {
87
+ check(key);
88
+ assertPlain(value);
89
+ const tx = (await db()).transaction('state', 'readwrite', { durability: 'strict' });
90
+ const done = new Promise((resolve, reject) => {
91
+ tx.oncomplete = () => resolve();
92
+ tx.onerror = () => reject(tx.error ?? new TasraError('IndexedDB write failed'));
93
+ tx.onabort = () => reject(tx.error ?? new TasraError('IndexedDB write aborted'));
94
+ });
95
+ tx.objectStore('state').put(value, key);
96
+ // Resolve only after the commit: an uncertain write must never look persisted.
97
+ await done;
98
+ },
99
+ async list(prefix) {
100
+ const tx = (await db()).transaction('state', 'readonly');
101
+ const keys = await request(tx.objectStore('state').getAllKeys());
102
+ return keys.filter((key) => typeof key === 'string' && key.startsWith(prefix));
103
+ },
104
+ async withLock(key, operation) {
105
+ check(key);
106
+ return locks.request(`${name}:${key}`, { mode: 'exclusive', ifAvailable: options.failIfLocked === true }, async (lock) => {
107
+ if (lock === null)
108
+ throw new StoreLockedError(key);
109
+ return operation();
110
+ });
111
+ },
112
+ async claim(key) {
113
+ check(key);
114
+ // An exclusive Web Lock on the claim name (shared by every tab and worker of the origin), and
115
+ // inside it ONE strict-durability transaction that inserts the record only when absent:
116
+ // `add` fails with ConstraintError on an existing key, aborting the transaction. Either way
117
+ // exactly one caller wins; the winner's record is committed before this resolves.
118
+ return await locks.request(`${name}:claim:${key}`, { mode: 'exclusive' }, async () => {
119
+ const tx = (await db()).transaction('state', 'readwrite', { durability: 'strict' });
120
+ let exists = false;
121
+ const done = new Promise((resolve, reject) => {
122
+ tx.oncomplete = () => resolve(true);
123
+ tx.onerror = () => { };
124
+ tx.onabort = () => exists ? resolve(false) : reject(tx.error ?? new TasraError('IndexedDB claim aborted'));
125
+ });
126
+ const insert = tx.objectStore('state').add({ claimed: true }, key);
127
+ insert.onerror = () => { exists = insert.error?.name === 'ConstraintError'; };
128
+ return await done;
129
+ });
130
+ },
131
+ };
132
+ }
133
+ function privateLiteral(host) {
134
+ if (host === 'localhost' || host.endsWith('.localhost'))
135
+ return true;
136
+ const v4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
137
+ if (v4) {
138
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
139
+ return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b < 128) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b < 32)
140
+ || (a === 192 && b === 168) || (a === 198 && (b === 18 || b === 19)) || a >= 224;
141
+ }
142
+ // Every IPv6 literal needs explicit approval; a browser cannot classify the rest.
143
+ return host.startsWith('[');
144
+ }
145
+ function browserTransport(mode, options, localHttp = false) {
146
+ const doFetch = options.fetch ?? globalThis.fetch, timeout = options.timeoutMs ?? 30_000;
147
+ const privateHosts = new Set(options.allowedPrivateHosts ?? []);
148
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 120_000)
149
+ throw new TasraError('Invalid browser transport timeout');
150
+ if (typeof doFetch !== 'function')
151
+ throw new TasraError('fetch is unavailable');
152
+ return async (url, request) => {
153
+ request.signal.throwIfAborted();
154
+ const parsed = new URL(url);
155
+ // Local development HTTP: only to a loopback name or private IP literal, checked with the same
156
+ // route policy as its HTTPS form. Every other destination still needs HTTPS.
157
+ const plain = localHttp && parsed.protocol === 'http:' && privateLiteral(parsed.hostname);
158
+ const shape = serviceRequestShape(mode, plain ? 'https:' + url.slice('http:'.length) : url, request);
159
+ if (parsed.protocol !== 'https:' && !plain)
160
+ throw new Error('Service destination policy requires HTTPS');
161
+ if (privateLiteral(parsed.hostname) && !privateHosts.has(parsed.hostname) && !plain)
162
+ throw new Error('Service destination policy refuses address');
163
+ const response = await doFetch(url, { method: shape.method, headers: shape.headers, body: request.body?.slice(),
164
+ redirect: 'error', credentials: 'omit', cache: 'no-store', referrerPolicy: 'no-referrer', mode: 'cors',
165
+ signal: AbortSignal.any([request.signal, AbortSignal.timeout(timeout)]) });
166
+ const type = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() ?? '';
167
+ const noContent = mode === 'paid-agent' && response.status === 204;
168
+ if (!acceptsServiceResponse(mode, shape, Boolean(request.body), response.status, type)) {
169
+ await response.body?.cancel().catch(() => { });
170
+ throw new Error(`Service HTTP status, content type or encoding refused (HTTP ${response.status}, ${type || 'no content type'})`);
171
+ }
172
+ const advertised = response.headers.get('content-length');
173
+ if (advertised && !response.headers.get('content-encoding') && (!/^\d+$/.test(advertised) || Number(advertised) > request.maxBytes)) {
174
+ await response.body?.cancel().catch(() => { });
175
+ throw new Error('Service response too large');
176
+ }
177
+ // Bound the decoded bytes; the browser may have decompressed the body.
178
+ const chunks = [];
179
+ let size = 0;
180
+ if (response.body) {
181
+ const reader = response.body.getReader();
182
+ try {
183
+ for (;;) {
184
+ const { done, value } = await reader.read();
185
+ if (done)
186
+ break;
187
+ size += value.length;
188
+ if (size > request.maxBytes)
189
+ throw new Error('Service response too large');
190
+ chunks.push(value);
191
+ }
192
+ }
193
+ finally {
194
+ await reader.cancel().catch(() => { });
195
+ }
196
+ }
197
+ if (noContent && size !== 0)
198
+ throw new Error('Unexpected paid agent response body');
199
+ const body = new Uint8Array(size);
200
+ let offset = 0;
201
+ for (const chunk of chunks) {
202
+ body.set(chunk, offset);
203
+ offset += chunk.length;
204
+ }
205
+ const retryAfter = response.headers.get('retry-after'), retryAfterMs = parseRetryAfter(retryAfter);
206
+ // Paid replies also carry the raw wait headers for the strict paid pacer (CORS must expose them).
207
+ const rateLimitAfter = mode === 'paid-agent' ? response.headers.get('x-ratelimit-after') : null;
208
+ return { status: response.status, body, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
209
+ ...(mode === 'paid-agent' && retryAfter !== null ? { retryAfter } : {}), ...(rateLimitAfter !== null ? { rateLimitAfter } : {}) };
210
+ };
211
+ }
212
+ function discovery(options) {
213
+ const send = browserTransport('discovery', options);
214
+ return { request: async (url, opts) => (await send(url, opts)).body };
215
+ }
216
+ /**
217
+ * Browser transport for registered paid sessions: authenticated discovery plus owner-only
218
+ * session control, with the same route, method, bearer and bound checks as the Node transport.
219
+ * @param options Fetch override, approved private hosts and request deadline.
220
+ */
221
+ export function createBrowserPaidAgentTransport(options = {}) {
222
+ const paid = browserTransport('paid-agent', options);
223
+ return { ...discovery(options), paidAgentRequest: (url, opts) => paid(url, opts) };
224
+ }
225
+ /**
226
+ * Browser transport for reading a keeper's retained paid result (the two POST recovery reads only).
227
+ * @param options Fetch override, approved private hosts, local development HTTP and request deadline.
228
+ */
229
+ export function createBrowserKeeperRecoveryTransport(options = {}) {
230
+ const recovery = browserTransport('keeper-recovery', options, options.allowLocalHttp === true);
231
+ return { keeperRecoveryRequest: (url, opts) => recovery(url, { ...opts, method: 'POST' }) };
232
+ }
233
+ /**
234
+ * Browser transport for registered relayers: discovery, forward and status, with
235
+ * `relayExchange` reporting busy refusals and their `Retry-After`.
236
+ * @param options Fetch override, approved private hosts and request deadline.
237
+ */
238
+ export function createBrowserRelayTransport(options = {}) {
239
+ const relay = browserTransport('relay', options);
240
+ return { ...discovery(options), relayRequest: async (url, opts) => (await relay(url, opts)).body,
241
+ relayExchange: (url, opts) => relay(url, opts) };
242
+ }