@t3foundry/tasra-sdk 0.0.0-stage → 0.3.0-next.1

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 (322) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +94 -0
  4. package/README.md +137 -2
  5. package/SECURITY.md +115 -0
  6. package/dist/app/approvals.d.ts +50 -0
  7. package/dist/app/approvals.js +90 -0
  8. package/dist/app/authorization.d.ts +19 -0
  9. package/dist/app/authorization.js +20 -0
  10. package/dist/app/client.d.ts +231 -0
  11. package/dist/app/client.js +272 -0
  12. package/dist/app/creation.d.ts +73 -0
  13. package/dist/app/creation.js +77 -0
  14. package/dist/app/deployment.d.ts +36 -0
  15. package/dist/app/deployment.js +18 -0
  16. package/dist/app/identity.d.ts +211 -0
  17. package/dist/app/identity.js +287 -0
  18. package/dist/app/index.d.ts +22 -0
  19. package/dist/app/index.js +12 -0
  20. package/dist/app/manifest.d.ts +74 -0
  21. package/dist/app/manifest.js +120 -0
  22. package/dist/app/node.d.ts +30 -0
  23. package/dist/app/node.js +159 -0
  24. package/dist/app/ready-slot.d.ts +157 -0
  25. package/dist/app/ready-slot.js +199 -0
  26. package/dist/app/tasra-client.d.ts +125 -0
  27. package/dist/app/tasra-client.js +79 -0
  28. package/dist/app/viem.d.ts +10 -0
  29. package/dist/app/viem.js +32 -0
  30. package/dist/app/wallet.d.ts +126 -0
  31. package/dist/app/wallet.js +137 -0
  32. package/dist/auth/dpop.d.ts +86 -0
  33. package/dist/auth/dpop.js +142 -0
  34. package/dist/auth/holderProof.d.ts +102 -0
  35. package/dist/auth/holderProof.js +161 -0
  36. package/dist/auth/identityScope.d.ts +19 -0
  37. package/dist/auth/identityScope.js +82 -0
  38. package/dist/auth/index.d.ts +11 -0
  39. package/dist/auth/index.js +13 -0
  40. package/dist/auth/oid4vp.d.ts +230 -0
  41. package/dist/auth/oid4vp.js +780 -0
  42. package/dist/auth/rego/wasm/PINS.json +11 -0
  43. package/dist/auth/rego/wasm/keykeeper_rego_wasm.d.ts +76 -0
  44. package/dist/auth/rego/wasm/keykeeper_rego_wasm.js +379 -0
  45. package/dist/auth/rego/wasm/keykeeper_rego_wasm_bg.wasm +0 -0
  46. package/dist/auth/rego.d.ts +192 -0
  47. package/dist/auth/rego.js +492 -0
  48. package/dist/auth/verifier.d.ts +166 -0
  49. package/dist/auth/verifier.js +211 -0
  50. package/dist/chain/abis/accountantSetRegistry.d.ts +441 -0
  51. package/dist/chain/abis/accountantSetRegistry.js +574 -0
  52. package/dist/chain/abis/accountantSlashing.d.ts +2071 -0
  53. package/dist/chain/abis/accountantSlashing.js +2670 -0
  54. package/dist/chain/abis/bondingCurve.d.ts +398 -0
  55. package/dist/chain/abis/bondingCurve.js +521 -0
  56. package/dist/chain/abis/equivocationSlasher.d.ts +292 -0
  57. package/dist/chain/abis/equivocationSlasher.js +379 -0
  58. package/dist/chain/abis/fixedTasraPriceOracle.d.ts +52 -0
  59. package/dist/chain/abis/fixedTasraPriceOracle.js +72 -0
  60. package/dist/chain/abis/index.d.ts +12801 -0
  61. package/dist/chain/abis/index.js +64 -0
  62. package/dist/chain/abis/keeperShareRegistry.d.ts +519 -0
  63. package/dist/chain/abis/keeperShareRegistry.js +675 -0
  64. package/dist/chain/abis/keyRegistry.d.ts +2421 -0
  65. package/dist/chain/abis/keyRegistry.js +3114 -0
  66. package/dist/chain/abis/livenessRegistry.d.ts +402 -0
  67. package/dist/chain/abis/livenessRegistry.js +524 -0
  68. package/dist/chain/abis/mockEurc.d.ts +210 -0
  69. package/dist/chain/abis/mockEurc.js +276 -0
  70. package/dist/chain/abis/nodeRegistry.d.ts +1630 -0
  71. package/dist/chain/abis/nodeRegistry.js +2113 -0
  72. package/dist/chain/abis/platformExecutor.d.ts +328 -0
  73. package/dist/chain/abis/platformExecutor.js +429 -0
  74. package/dist/chain/abis/prevrandaoSaltBeacon.d.ts +16 -0
  75. package/dist/chain/abis/prevrandaoSaltBeacon.js +24 -0
  76. package/dist/chain/abis/serviceRegistry.d.ts +556 -0
  77. package/dist/chain/abis/serviceRegistry.js +719 -0
  78. package/dist/chain/abis/settlement.d.ts +1624 -0
  79. package/dist/chain/abis/settlement.js +2096 -0
  80. package/dist/chain/abis/tasraSwapRouter.d.ts +92 -0
  81. package/dist/chain/abis/tasraSwapRouter.js +122 -0
  82. package/dist/chain/abis/tasraToken.d.ts +455 -0
  83. package/dist/chain/abis/tasraToken.js +599 -0
  84. package/dist/chain/abis/tasraVestingVault.d.ts +165 -0
  85. package/dist/chain/abis/tasraVestingVault.js +215 -0
  86. package/dist/chain/abis/thresholdRandomBeacon.d.ts +378 -0
  87. package/dist/chain/abis/thresholdRandomBeacon.js +494 -0
  88. package/dist/chain/abis/treasury.d.ts +301 -0
  89. package/dist/chain/abis/treasury.js +390 -0
  90. package/dist/chain/abis/verifierSetRegistry.d.ts +445 -0
  91. package/dist/chain/abis/verifierSetRegistry.js +579 -0
  92. package/dist/chain/client.d.ts +212 -0
  93. package/dist/chain/client.js +576 -0
  94. package/dist/chain/commitmentRecovery.d.ts +21 -0
  95. package/dist/chain/commitmentRecovery.js +44 -0
  96. package/dist/chain/committeeClient.d.ts +102 -0
  97. package/dist/chain/committeeClient.js +137 -0
  98. package/dist/chain/deployments.d.ts +56 -0
  99. package/dist/chain/deployments.js +269 -0
  100. package/dist/chain/discovery.d.ts +49 -0
  101. package/dist/chain/discovery.js +107 -0
  102. package/dist/chain/events.d.ts +58 -0
  103. package/dist/chain/events.js +125 -0
  104. package/dist/chain/format.d.ts +25 -0
  105. package/dist/chain/format.js +51 -0
  106. package/dist/chain/index.d.ts +41 -0
  107. package/dist/chain/index.js +56 -0
  108. package/dist/chain/manifest.d.ts +165 -0
  109. package/dist/chain/manifest.js +132 -0
  110. package/dist/chain/network-profiles.json +75 -0
  111. package/dist/chain/networks.d.ts +73 -0
  112. package/dist/chain/networks.js +62 -0
  113. package/dist/chain/node.d.ts +44 -0
  114. package/dist/chain/node.js +176 -0
  115. package/dist/chain/offchain.d.ts +149 -0
  116. package/dist/chain/offchain.js +73 -0
  117. package/dist/chain/provisionRule.d.ts +164 -0
  118. package/dist/chain/provisionRule.js +212 -0
  119. package/dist/chain/registeredAgent.d.ts +64 -0
  120. package/dist/chain/registeredAgent.js +140 -0
  121. package/dist/chain/registeredOperation.d.ts +49 -0
  122. package/dist/chain/registeredOperation.js +136 -0
  123. package/dist/chain/registeredRelay.d.ts +206 -0
  124. package/dist/chain/registeredRelay.js +312 -0
  125. package/dist/chain/revertReason.d.ts +14 -0
  126. package/dist/chain/revertReason.js +62 -0
  127. package/dist/chain/ruleAmendment.d.ts +80 -0
  128. package/dist/chain/ruleAmendment.js +195 -0
  129. package/dist/chain/ruleAmendmentCore.d.ts +129 -0
  130. package/dist/chain/ruleAmendmentCore.js +152 -0
  131. package/dist/chain/ruleInput.d.ts +10 -0
  132. package/dist/chain/ruleInput.js +13 -0
  133. package/dist/chain/serviceIdentity.d.ts +176 -0
  134. package/dist/chain/serviceIdentity.js +237 -0
  135. package/dist/chain/serviceProfiles.d.ts +39 -0
  136. package/dist/chain/serviceProfiles.js +74 -0
  137. package/dist/chain/services.d.ts +141 -0
  138. package/dist/chain/services.js +79 -0
  139. package/dist/chain/slotClient.d.ts +55 -0
  140. package/dist/chain/slotClient.js +62 -0
  141. package/dist/chain/slotSeed.d.ts +31 -0
  142. package/dist/chain/slotSeed.js +98 -0
  143. package/dist/chain/write.d.ts +431 -0
  144. package/dist/chain/write.js +958 -0
  145. package/dist/client/client.d.ts +112 -0
  146. package/dist/client/client.js +111 -0
  147. package/dist/client/index.d.ts +3 -0
  148. package/dist/client/index.js +2 -0
  149. package/dist/client/session.d.ts +67 -0
  150. package/dist/client/session.js +238 -0
  151. package/dist/committee/client.d.ts +284 -0
  152. package/dist/committee/client.js +351 -0
  153. package/dist/committee/dual-sign.d.ts +110 -0
  154. package/dist/committee/dual-sign.js +202 -0
  155. package/dist/committee/ecdsa.d.ts +36 -0
  156. package/dist/committee/ecdsa.js +45 -0
  157. package/dist/committee/extraction.d.ts +82 -0
  158. package/dist/committee/extraction.js +96 -0
  159. package/dist/committee/index.d.ts +19 -0
  160. package/dist/committee/index.js +13 -0
  161. package/dist/committee/oauth.d.ts +51 -0
  162. package/dist/committee/oauth.js +90 -0
  163. package/dist/committee/receipts.d.ts +51 -0
  164. package/dist/committee/receipts.js +59 -0
  165. package/dist/committee/request.d.ts +264 -0
  166. package/dist/committee/request.js +305 -0
  167. package/dist/committee/token.d.ts +274 -0
  168. package/dist/committee/token.js +418 -0
  169. package/dist/crypto/constants.d.ts +10 -0
  170. package/dist/crypto/constants.js +32 -0
  171. package/dist/crypto/detect.d.ts +20 -0
  172. package/dist/crypto/detect.js +44 -0
  173. package/dist/crypto/envelope.d.ts +60 -0
  174. package/dist/crypto/envelope.js +243 -0
  175. package/dist/crypto/frost.d.ts +49 -0
  176. package/dist/crypto/frost.js +152 -0
  177. package/dist/crypto/hex.d.ts +7 -0
  178. package/dist/crypto/hex.js +24 -0
  179. package/dist/crypto/ibe-blob.d.ts +114 -0
  180. package/dist/crypto/ibe-blob.js +208 -0
  181. package/dist/crypto/ibe.d.ts +88 -0
  182. package/dist/crypto/ibe.js +262 -0
  183. package/dist/crypto/index.d.ts +12 -0
  184. package/dist/crypto/index.js +12 -0
  185. package/dist/crypto/kem.d.ts +55 -0
  186. package/dist/crypto/kem.js +241 -0
  187. package/dist/decryption/client.d.ts +64 -0
  188. package/dist/decryption/client.js +82 -0
  189. package/dist/decryption/index.d.ts +2 -0
  190. package/dist/decryption/index.js +2 -0
  191. package/dist/errors.d.ts +124 -0
  192. package/dist/errors.js +167 -0
  193. package/dist/index.d.ts +43 -0
  194. package/dist/index.js +98 -0
  195. package/dist/keys/index.d.ts +1 -0
  196. package/dist/keys/index.js +4 -0
  197. package/dist/keys/node-client.d.ts +27 -0
  198. package/dist/keys/node-client.js +97 -0
  199. package/dist/oid4vp/binding.d.ts +76 -0
  200. package/dist/oid4vp/binding.js +118 -0
  201. package/dist/oid4vp/did-web.d.ts +49 -0
  202. package/dist/oid4vp/did-web.js +57 -0
  203. package/dist/oid4vp/index.d.ts +9 -0
  204. package/dist/oid4vp/index.js +10 -0
  205. package/dist/oid4vp/jose.d.ts +166 -0
  206. package/dist/oid4vp/jose.js +242 -0
  207. package/dist/oid4vp/jwe.d.ts +30 -0
  208. package/dist/oid4vp/jwe.js +93 -0
  209. package/dist/oid4vp/oid4vci.d.ts +84 -0
  210. package/dist/oid4vp/oid4vci.js +85 -0
  211. package/dist/oid4vp/request-object.d.ts +109 -0
  212. package/dist/oid4vp/request-object.js +96 -0
  213. package/dist/oid4vp/sd-jwt.d.ts +177 -0
  214. package/dist/oid4vp/sd-jwt.js +208 -0
  215. package/dist/oid4vp/verifier-agent.d.ts +161 -0
  216. package/dist/oid4vp/verifier-agent.js +132 -0
  217. package/dist/oid4vp/wallet.d.ts +116 -0
  218. package/dist/oid4vp/wallet.js +108 -0
  219. package/dist/recipient/store.d.ts +67 -0
  220. package/dist/recipient/store.js +98 -0
  221. package/dist/signing/ecdsa.d.ts +49 -0
  222. package/dist/signing/ecdsa.js +79 -0
  223. package/dist/signing/frost.d.ts +88 -0
  224. package/dist/signing/frost.js +145 -0
  225. package/dist/signing/index.d.ts +4 -0
  226. package/dist/signing/index.js +3 -0
  227. package/dist/slots/faucet.d.ts +23 -0
  228. package/dist/slots/faucet.js +35 -0
  229. package/dist/slots/index.d.ts +2 -0
  230. package/dist/slots/index.js +4 -0
  231. package/dist/verifier-agent/index.d.ts +241 -0
  232. package/dist/verifier-agent/index.js +411 -0
  233. package/docs/DEVELOPER-EXPERIENCE.md +62 -0
  234. package/docs/README.md +33 -0
  235. package/docs/access-control.md +76 -0
  236. package/docs/ai-development.md +292 -0
  237. package/docs/api.md +338 -0
  238. package/docs/application-api.md +335 -0
  239. package/docs/architecture.md +65 -0
  240. package/docs/basics.md +48 -0
  241. package/docs/capabilities.md +86 -0
  242. package/docs/chain.md +153 -0
  243. package/docs/compatibility.md +36 -0
  244. package/docs/consumer-migrations.md +80 -0
  245. package/docs/create-slot.md +104 -0
  246. package/docs/document-signing.md +243 -0
  247. package/docs/encrypted-notes.md +129 -0
  248. package/docs/encryption.md +100 -0
  249. package/docs/errors.md +76 -0
  250. package/docs/flows.md +289 -0
  251. package/docs/fuji.md +127 -0
  252. package/docs/funding.md +126 -0
  253. package/docs/getting-started.md +94 -0
  254. package/docs/glossary.md +44 -0
  255. package/docs/installation.md +132 -0
  256. package/docs/manage-slot.md +95 -0
  257. package/docs/native-approvals.md +124 -0
  258. package/docs/prerequisites.md +137 -0
  259. package/docs/read-slot.md +41 -0
  260. package/docs/reference/README.md +30 -0
  261. package/docs/reference/app-node.md +102 -0
  262. package/docs/reference/app.md +1737 -0
  263. package/docs/reference/chain-node.md +159 -0
  264. package/docs/reference/chain.md +3609 -0
  265. package/docs/reference/committee.md +2176 -0
  266. package/docs/reference/main.md +4068 -0
  267. package/docs/reference/oid4vp.md +2547 -0
  268. package/docs/reference/verifier-agent.md +498 -0
  269. package/docs/shared-account.md +168 -0
  270. package/docs/signing-and-encryption.md +52 -0
  271. package/docs/signing.md +172 -0
  272. package/examples/committee-slot.ts +16 -0
  273. package/examples/connect-fuji.ts +41 -0
  274. package/examples/connect-network.ts +14 -0
  275. package/examples/credential-approvals.ts +46 -0
  276. package/examples/document-signing/README.md +59 -0
  277. package/examples/document-signing/backend.ts +132 -0
  278. package/examples/document-signing/build.mjs +19 -0
  279. package/examples/document-signing/config.ts +34 -0
  280. package/examples/document-signing/gitignore.template +9 -0
  281. package/examples/document-signing/model.ts +140 -0
  282. package/examples/document-signing/network.ts +58 -0
  283. package/examples/document-signing/package.json +25 -0
  284. package/examples/document-signing/public/index.html +27 -0
  285. package/examples/document-signing/public/sample.pdf +31 -0
  286. package/examples/document-signing/public/styles.css +531 -0
  287. package/examples/document-signing/server.ts +358 -0
  288. package/examples/document-signing/setup.ts +111 -0
  289. package/examples/document-signing/store.ts +105 -0
  290. package/examples/document-signing/tsconfig.json +24 -0
  291. package/examples/document-signing/verify.ts +24 -0
  292. package/examples/document-signing/web/app.ts +312 -0
  293. package/examples/document-signing/web/preview.ts +67 -0
  294. package/examples/document-signing/web/wallet.ts +146 -0
  295. package/examples/document-signing/workflow.test.ts +228 -0
  296. package/examples/document-signing/workflow.ts +241 -0
  297. package/examples/document-signing.ts +96 -0
  298. package/examples/encrypted-notes.ts +86 -0
  299. package/examples/ethers-signer.ts +204 -0
  300. package/examples/fund-slot.ts +73 -0
  301. package/examples/getting-started.ts +25 -0
  302. package/examples/learning-authorize.ts +23 -0
  303. package/examples/learning-cancel-slot.ts +11 -0
  304. package/examples/learning-context.ts +28 -0
  305. package/examples/learning-create-slot.ts +25 -0
  306. package/examples/learning-read-slot.ts +8 -0
  307. package/examples/learning-renew-slot.ts +12 -0
  308. package/examples/learning-sign.ts +8 -0
  309. package/examples/live-config.ts +71 -0
  310. package/examples/minimal.ts +6 -0
  311. package/examples/native-approvals.ts +57 -0
  312. package/examples/network.ts +58 -0
  313. package/examples/offline.ts +16 -0
  314. package/examples/personal-vault.ts +20 -0
  315. package/examples/provision-slot.ts +47 -0
  316. package/examples/shared-account.ts +46 -0
  317. package/examples/slot-address.ts +13 -0
  318. package/examples/slot-creation.ts +9 -0
  319. package/examples/tutorial-negative.ts +26 -0
  320. package/examples/tutorial-support.ts +76 -0
  321. package/examples/viem-account.ts +203 -0
  322. package/package.json +303 -4
@@ -0,0 +1,358 @@
1
+ import { createServer, type IncomingMessage } from 'node:http'
2
+ import { readFileSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { timingSafeEqual } from 'node:crypto'
5
+ import { pollOid4vpSession } from '@t3foundry/tasra-sdk/verifier-agent'
6
+ import { verifyCompactJws } from '@t3foundry/tasra-sdk/oid4vp'
7
+ import { loadService, liveBackend, readKey } from './backend.js'
8
+ import { deployment, verifierAgentUrl } from './config.js'
9
+ import { Store, lockDirectory } from './store.js'
10
+ import {
11
+ Workflow,
12
+ publicView,
13
+ Conflict,
14
+ type RequestRecord,
15
+ } from './workflow.js'
16
+ import {
17
+ people,
18
+ verifyBundle,
19
+ type Person,
20
+ type Manifest,
21
+ type Bundle,
22
+ } from './model.js'
23
+
24
+ const port = Number(process.env.PORT ?? 4177)
25
+ if (!Number.isSafeInteger(port) || port < 1024 || port > 65535)
26
+ throw new Error('Invalid PORT')
27
+ const origin = `http://127.0.0.1:${port}`,
28
+ host = `127.0.0.1:${port}`
29
+ const config = loadService(),
30
+ store = new Store<RequestRecord>(),
31
+ unlock = lockDirectory()
32
+ const workflow = new Workflow(store, liveBackend(config), {
33
+ chainId: deployment.chainId,
34
+ keyRegistry: deployment.addresses.KeyRegistry!,
35
+ slots: config.slots,
36
+ })
37
+ workflow.recover()
38
+ function owner(req: IncomingMessage) {
39
+ const supplied = Buffer.from(
40
+ req.headers.authorization?.replace(/^Bearer /, '') ?? '',
41
+ ),
42
+ expected = Buffer.from(config.senderToken)
43
+ if (
44
+ supplied.length !== expected.length ||
45
+ !timingSafeEqual(supplied, expected)
46
+ )
47
+ throw new Conflict(
48
+ 'Open the private sender-console link printed by the server',
49
+ )
50
+ }
51
+ async function body(
52
+ req: IncomingMessage,
53
+ limit = 12 * 1024 * 1024,
54
+ ): Promise<Record<string, unknown>> {
55
+ if (!req.headers['content-type']?.startsWith('application/json'))
56
+ throw new Error('Expected JSON')
57
+ const chunks: Buffer[] = []
58
+ let length = 0
59
+ for await (const chunk of req) {
60
+ length += (chunk as Buffer).length
61
+ if (length > limit) throw new Error('Request too large')
62
+ chunks.push(chunk as Buffer)
63
+ }
64
+ const value: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))
65
+ if (!value || typeof value !== 'object' || Array.isArray(value))
66
+ throw new Error('Expected JSON object')
67
+ return value as Record<string, unknown>
68
+ }
69
+ const text = (v: unknown) => {
70
+ if (typeof v !== 'string') throw new Error('Expected text')
71
+ return v
72
+ }
73
+ const server = createServer((req, res) => {
74
+ void (async () => {
75
+ res.setHeader('X-Content-Type-Options', 'nosniff')
76
+ res.setHeader('Referrer-Policy', 'no-referrer')
77
+ res.setHeader('Cache-Control', 'no-store')
78
+ res.setHeader(
79
+ 'Content-Security-Policy',
80
+ "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-src 'self' blob:; object-src 'self' blob:; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'",
81
+ )
82
+ const json = (value: unknown, status = 200) => {
83
+ res.writeHead(status, { 'content-type': 'application/json' })
84
+ res.end(JSON.stringify(value))
85
+ }
86
+ try {
87
+ if (req.headers.host !== host)
88
+ throw new Conflict('Unexpected host; use the printed loopback URL')
89
+ if (req.method !== 'GET' && req.headers.origin !== origin)
90
+ throw new Conflict('Unexpected request origin')
91
+ const url = new URL(req.url ?? '/', origin),
92
+ path = url.pathname
93
+ if (req.method === 'GET' && path === '/api/config')
94
+ return json({
95
+ chainId: deployment.chainId,
96
+ keyRegistry: deployment.addresses.KeyRegistry,
97
+ verifierAgentUrl,
98
+ slots: config.slots,
99
+ })
100
+ if (path === '/api/requests') {
101
+ owner(req)
102
+ if (req.method === 'GET')
103
+ return json(store.list().map(publicView).reverse())
104
+ if (req.method === 'POST') {
105
+ const b = await body(req)
106
+ return json(
107
+ await workflow.create({
108
+ id: text(b.id),
109
+ title: text(b.title),
110
+ version: Number(b.version),
111
+ pdf: Buffer.from(text(b.pdfBase64), 'base64'),
112
+ }),
113
+ 201,
114
+ )
115
+ }
116
+ }
117
+ if (req.method === 'POST' && path === '/api/verify') {
118
+ const b = await body(req)
119
+ // The caller supplies its independently saved expected request, not one inferred from the bundle.
120
+ const expected = b.expected as Manifest
121
+ if (
122
+ expected.chainId !== deployment.chainId ||
123
+ expected.keyRegistry !== deployment.addresses.KeyRegistry
124
+ )
125
+ throw new Error('Unexpected deployment')
126
+ await verifyBundle(
127
+ Buffer.from(text(b.pdfBase64), 'base64'),
128
+ expected,
129
+ b.bundle as Bundle,
130
+ readKey,
131
+ )
132
+ return json({
133
+ verified: true,
134
+ policy: 'Current anchored signer keys; not an archival timestamp',
135
+ })
136
+ }
137
+ const match = /^\/api\/requests\/([0-9a-f-]{36})(?:\/(.*))?$/i.exec(path)
138
+ if (match) {
139
+ const id = match[1]!,
140
+ action = match[2] ?? '',
141
+ record = store.get(id)
142
+ if (req.method === 'GET') {
143
+ if (!action) return json(publicView(record))
144
+ if (action === 'pdf') {
145
+ res.setHeader('Content-Security-Policy', "frame-ancestors 'self'")
146
+ res.writeHead(200, {
147
+ 'content-type': 'application/pdf',
148
+ 'content-disposition': 'inline; filename="document.pdf"',
149
+ })
150
+ res.end(Buffer.from(record.pdfBase64, 'base64'))
151
+ return
152
+ }
153
+ if (action === 'request') {
154
+ res.writeHead(200, {
155
+ 'content-type': 'application/json',
156
+ 'content-disposition': 'attachment; filename="request.json"',
157
+ })
158
+ res.end(JSON.stringify(record.manifest, null, 2))
159
+ return
160
+ }
161
+ if (action === 'bundle') {
162
+ if (record.status !== 'completed')
163
+ throw new Conflict('Both signatures are required')
164
+ const bundle = {
165
+ manifest: record.manifest,
166
+ signatures: people.map((p) => record.signers[p].signature!),
167
+ }
168
+ await verifyBundle(
169
+ Buffer.from(record.pdfBase64, 'base64'),
170
+ record.manifest,
171
+ bundle,
172
+ readKey,
173
+ )
174
+ res.writeHead(200, {
175
+ 'content-type': 'application/json',
176
+ 'content-disposition': 'attachment; filename="signatures.json"',
177
+ })
178
+ res.end(JSON.stringify(bundle, null, 2))
179
+ return
180
+ }
181
+ }
182
+ if (req.method === 'POST' && action === 'cancel') {
183
+ owner(req)
184
+ return json(await workflow.close(id, 'cancelled'))
185
+ }
186
+ const signerMatch =
187
+ /^(alice|bob)\/(prepare|session|transport|complete|decline)$/.exec(
188
+ action,
189
+ )
190
+ if (req.method === 'POST' && signerMatch) {
191
+ const person = signerMatch[1] as Person,
192
+ verb = signerMatch[2],
193
+ b = await body(req, 2 * 1024 * 1024)
194
+ if (verb === 'prepare')
195
+ return json(
196
+ await workflow.prepare(id, person, text(b.documentSha256)),
197
+ )
198
+ if (verb === 'decline') {
199
+ const { header, payload } = verifyCompactJws(
200
+ text(b.proof),
201
+ config.holderKeys[person],
202
+ )
203
+ if (
204
+ header.typ !== 'tasra-decline+jwt' ||
205
+ payload.aud !== 'tasra-sign-decline/v1' ||
206
+ payload.requestId !== id ||
207
+ payload.documentSha256 !== record.manifest.documentSha256 ||
208
+ payload.person !== person ||
209
+ typeof payload.exp !== 'number' ||
210
+ !Number.isSafeInteger(payload.exp) ||
211
+ payload.exp < Date.now() / 1000 ||
212
+ payload.exp > Date.now() / 1000 + 180
213
+ )
214
+ throw new Conflict('Invalid decline authorization')
215
+ return json(await workflow.close(id, 'declined', person))
216
+ }
217
+ const attemptId = text(b.attemptId)
218
+ if (verb === 'complete')
219
+ return json(await workflow.complete(id, person, attemptId))
220
+ const saved = record.sessions[person]
221
+ if (
222
+ record.signers[person].attemptId !== attemptId ||
223
+ !saved ||
224
+ record.signers[person].phase !== 'awaiting_wallet'
225
+ )
226
+ throw new Conflict('Wallet session is no longer active')
227
+ if (verb === 'session') {
228
+ const status = await pollOid4vpSession(
229
+ verifierAgentUrl,
230
+ saved.sessionId,
231
+ saved.pollSecret,
232
+ )
233
+ return json({
234
+ sessionId: saved.sessionId,
235
+ requestUri: saved.requestUri,
236
+ qrPayload: saved.qrPayload,
237
+ operation: saved.operation,
238
+ requestHash: saved.requestHash,
239
+ bindingPreimage: status.bindingPreimage,
240
+ status: status.status,
241
+ })
242
+ }
243
+ if (verb === 'transport') {
244
+ const target = new URL(text(b.url)),
245
+ method = b.method === 'POST' ? 'POST' : 'GET'
246
+ const allowed =
247
+ target.origin === new URL(verifierAgentUrl).origin &&
248
+ ((method === 'GET' &&
249
+ (target.href === saved.requestUri ||
250
+ (target.pathname === '/.well-known/did.json' &&
251
+ !target.search))) ||
252
+ (method === 'POST' &&
253
+ target.href ===
254
+ verifierAgentUrl +
255
+ '/v1/response?session=' +
256
+ saved.sessionId))
257
+ if (!allowed)
258
+ throw new Conflict(
259
+ 'Wallet transport is outside the configured session',
260
+ )
261
+ const response = await fetch(target, {
262
+ method,
263
+ redirect: 'error',
264
+ signal: AbortSignal.timeout(15000),
265
+ headers:
266
+ method === 'POST'
267
+ ? { 'content-type': 'application/x-www-form-urlencoded' }
268
+ : {
269
+ accept:
270
+ 'application/json, application/oauth-authz-req+jwt',
271
+ },
272
+ body: method === 'POST' ? text(b.body) : undefined,
273
+ })
274
+ return json({
275
+ status: response.status,
276
+ contentType: response.headers.get('content-type'),
277
+ body: await response.text(),
278
+ })
279
+ }
280
+ }
281
+ }
282
+ if (req.method === 'GET') {
283
+ if (
284
+ /^\/pdf-assets\/(?:pdf\.worker\.mjs|(?:cmaps|standard_fonts|wasm)\/[a-zA-Z0-9_.-]+)$/.test(
285
+ path,
286
+ )
287
+ ) {
288
+ res.writeHead(200, {
289
+ 'content-type': path.endsWith('.mjs')
290
+ ? 'text/javascript'
291
+ : path.endsWith('.wasm')
292
+ ? 'application/wasm'
293
+ : 'application/octet-stream',
294
+ })
295
+ res.end(readFileSync(join(import.meta.dirname, 'public', path)))
296
+ return
297
+ }
298
+ const assets: Record<string, [string, string]> = {
299
+ '/app.js': ['app.js', 'text/javascript'],
300
+ '/styles.css': ['styles.css', 'text/css'],
301
+ '/sample.pdf': ['sample.pdf', 'application/pdf'],
302
+ }
303
+ const asset = assets[path]
304
+ if (asset) {
305
+ res.writeHead(200, { 'content-type': asset[1] })
306
+ res.end(readFileSync(join(import.meta.dirname, 'public', asset[0])))
307
+ return
308
+ }
309
+ if (
310
+ path === '/' ||
311
+ path === '/verify' ||
312
+ /^\/sign\/[0-9a-f-]{36}\/(alice|bob)$/i.test(path)
313
+ ) {
314
+ res.writeHead(200, { 'content-type': 'text/html' })
315
+ res.end(readFileSync(join(import.meta.dirname, 'public/index.html')))
316
+ return
317
+ }
318
+ }
319
+ json({ error: 'Not found' }, 404)
320
+ } catch (e) {
321
+ // Never return raw transport errors that could embed a presentation or token.
322
+ const message =
323
+ e instanceof Conflict
324
+ ? e.message
325
+ : e instanceof Error && e.name === 'AuthorizationRefused'
326
+ ? 'The verifier refused this credential'
327
+ : 'Request failed; inspect the request status and local configuration'
328
+ json(
329
+ { error: message },
330
+ e instanceof Conflict
331
+ ? 409
332
+ : e instanceof Error && e.name === 'AuthorizationRefused'
333
+ ? 403
334
+ : 400,
335
+ )
336
+ }
337
+ })().catch(() => {
338
+ if (!res.headersSent) res.writeHead(500)
339
+ res.end()
340
+ })
341
+ })
342
+ server.listen(port, '127.0.0.1', () =>
343
+ console.log(
344
+ `Sender console (private): ${origin}/#sender=${config.senderToken}`,
345
+ ),
346
+ )
347
+ let stopped = false
348
+ function stop() {
349
+ if (stopped) return
350
+ stopped = true
351
+ server.close(() => {
352
+ unlock()
353
+ process.exit(0)
354
+ })
355
+ setTimeout(() => process.exit(1), 5000).unref()
356
+ }
357
+ process.on('SIGTERM', stop)
358
+ process.on('SIGINT', stop)
@@ -0,0 +1,111 @@
1
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { randomBytes } from 'node:crypto'
4
+ import { hexToBytes } from '@t3foundry/tasra-sdk'
5
+ import { createFileStore } from '@t3foundry/tasra-sdk/app/node'
6
+ import { deployment, verifierAgentUrl, tasra, networkIdentity, assertSameNetwork, type NetworkIdentity } from './config.js'
7
+ import { stateDirectory, atomicSave, lockDirectory } from './store.js'
8
+ import { people, toHex, type Hex, type Person } from './model.js'
9
+
10
+ export type Setup = {
11
+ schema: 'tasra-document-setup/v2'
12
+ network: NetworkIdentity
13
+ creatorKey: Hex
14
+ issuerSeed: Hex
15
+ holders: Record<string, Hex>
16
+ slots: Partial<Record<Person, Hex>>
17
+ }
18
+ export function loadSetup(): Setup {
19
+ const state = JSON.parse(readFileSync(join(stateDirectory, 'setup.json'), 'utf8')) as Setup
20
+ if (state.schema !== 'tasra-document-setup/v2')
21
+ throw new Error('Older setup state requires reconciliation. Preserve it; use a fresh TASRA_SIGN_DATA directory for this tutorial.')
22
+ assertSameNetwork(state.network)
23
+ return state
24
+ }
25
+ const unlock = lockDirectory()
26
+ try {
27
+ if (!(await tasra.check()).ready)
28
+ throw new Error('Network registries unavailable; check the downloaded manifest')
29
+ const health = await fetch(verifierAgentUrl + '/health', { signal: AbortSignal.timeout(10000) })
30
+ if (!health.ok) throw new Error('Verifier unavailable')
31
+
32
+ // Save fresh creator and identity keys before funding or creating any slots.
33
+ const file = join(stateDirectory, 'setup.json')
34
+ const newIdentitySeed = () => {
35
+ const identity = tasra.identities.create()
36
+ try { return toHex(identity.exportPrivateKey()) } finally { identity.destroy() }
37
+ }
38
+ const state: Setup = existsSync(file) ? loadSetup() : {
39
+ schema: 'tasra-document-setup/v2',
40
+ network: networkIdentity,
41
+ creatorKey: tasra.wallets.create().exportPrivateKey(),
42
+ issuerSeed: newIdentitySeed(),
43
+ holders: Object.fromEntries(['alice', 'bob', 'mallory'].map(name => [name, newIdentitySeed()])),
44
+ slots: {},
45
+ }
46
+ const save = () => atomicSave(file, state)
47
+ save()
48
+ const store = createFileStore(join(stateDirectory, 'sdk'))
49
+ const creator = tasra.wallets.create({ privateKey: state.creatorKey })
50
+ await store.save('creator-key', creator.exportPrivateKey())
51
+ await store.save('network-pin', networkIdentity.manifestSha256)
52
+ console.log(`Creator: ${creator.address} on chain ${deployment.chainId}.`)
53
+ if (await tasra.chain.client.getBalance({address: creator.address}) < 5n * 10n ** 16n) {
54
+ throw new Error('Fund this address with at least 0.05 AVAX using the official Fuji C-Chain faucet or your wallet, then rerun npm run setup. Saved creator state will be reused.')
55
+ }
56
+
57
+ // Each signer receives a separate identity and holder-bound credential.
58
+ const issuer = tasra.identities.create({ seed: hexToBytes(state.issuerSeed) })
59
+ mkdirSync(join(stateDirectory, 'wallets'), { recursive: true, mode: 0o700 })
60
+ for (const [name, seed] of Object.entries(state.holders)) {
61
+ const holder = tasra.identities.create({ seed: hexToBytes(seed) })
62
+ const credential = tasra.credentials.issue({
63
+ issuer, holder, type: 'DocumentSigner', subject: 'did:demo:' + name,
64
+ claims: { role: 'document-signer' }, ttlSecs: 86400,
65
+ })
66
+ atomicSave(join(stateDirectory, 'wallets', name + '.json'), {
67
+ schema: 'tasra-demo-wallet/v1', name, seed, credential,
68
+ })
69
+ holder.destroy()
70
+ }
71
+
72
+ // A stable name lets the SDK resume creation, rule delivery, and verifier setup.
73
+ for (const person of people) {
74
+ const slot = await tasra.slots.create({
75
+ name: 'document-' + person, mode: 'frost',
76
+ policy: tasra.credentials.policy({
77
+ issuer, type: 'DocumentSigner', subjects: ['did:demo:' + person],
78
+ claims: { role: ['document-signer'] },
79
+ }),
80
+ threshold: { k: 2, n: 3 }, verifiers: { committee: 3, quorum: 2 },
81
+ }, { wallet: creator, store })
82
+ state.slots[person] = slot.slotId
83
+ save()
84
+ console.log(person + ' key ready: ' + slot.slotId)
85
+ console.log(`Before starting the app, buy TSRA with EURC and fund this slot using the funding guide. Status: npx tsx fund-slot.ts ${JSON.stringify(join(stateDirectory, 'sdk'))} status --slot ${slot.slotId}`)
86
+ }
87
+
88
+ // Application records remain separate from the SDK's durable operation journals.
89
+ const serviceFile = join(stateDirectory, 'service.json')
90
+ const existing = existsSync(serviceFile)
91
+ ? JSON.parse(readFileSync(serviceFile, 'utf8')) as { senderToken: string }
92
+ : undefined
93
+ const holderKeys = Object.fromEntries(people.map(name => {
94
+ const identity = tasra.identities.create({ seed: hexToBytes(state.holders[name]!) })
95
+ const publicKey = identity.holder.publicJwk
96
+ identity.destroy()
97
+ return [name, publicKey]
98
+ }))
99
+ atomicSave(serviceFile, {
100
+ network: networkIdentity,
101
+ creatorKey: state.creatorKey, slots: state.slots,
102
+ senderToken: existing?.senderToken ?? randomBytes(32).toString('hex'), holderKeys,
103
+ })
104
+ atomicSave(join(stateDirectory, 'public.json'), {
105
+ deployment, verifierAgentUrl, issuerDid: issuer.did, slots: state.slots,
106
+ })
107
+ issuer.destroy()
108
+ console.log('Setup complete. Fund both slots with TSRA usage credit before npm start. Import .tasra/wallets/alice.json and bob.json into separate browser contexts. Wallet files are private.')
109
+ } finally {
110
+ unlock()
111
+ }
@@ -0,0 +1,105 @@
1
+ import {
2
+ mkdirSync,
3
+ readFileSync,
4
+ writeFileSync,
5
+ renameSync,
6
+ openSync,
7
+ closeSync,
8
+ fsyncSync,
9
+ existsSync,
10
+ unlinkSync,
11
+ readdirSync,
12
+ rmdirSync,
13
+ } from 'node:fs'
14
+ import { join, resolve } from 'node:path'
15
+ import { randomUUID } from 'node:crypto'
16
+
17
+ export const stateDirectory = resolve(process.env.TASRA_SIGN_DATA ?? '.tasra')
18
+ export function atomicSave(path: string, value: unknown) {
19
+ const temporary = path + '.' + randomUUID() + '.tmp'
20
+ writeFileSync(
21
+ temporary,
22
+ JSON.stringify(
23
+ value,
24
+ (_, v: unknown) => (typeof v === 'bigint' ? v.toString() : v),
25
+ 2,
26
+ ) + '\n',
27
+ { mode: 0o600, flag: 'wx' },
28
+ )
29
+ const fd = openSync(temporary, 'r')
30
+ try {
31
+ fsyncSync(fd)
32
+ } finally {
33
+ closeSync(fd)
34
+ }
35
+ renameSync(temporary, path)
36
+ const dir = openSync(resolve(path, '..'), 'r')
37
+ try {
38
+ fsyncSync(dir)
39
+ } finally {
40
+ closeSync(dir)
41
+ }
42
+ }
43
+ export class Store<T extends { manifest: { requestId: string } }> {
44
+ readonly directory: string
45
+ private queues = new Map<string, Promise<unknown>>()
46
+ constructor(root = stateDirectory) {
47
+ this.directory = join(root, 'requests')
48
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 })
49
+ }
50
+ private file(id: string) {
51
+ if (!/^[0-9a-f-]{36}$/i.test(id)) throw new Error('Invalid request ID')
52
+ return join(this.directory, id + '.json')
53
+ }
54
+ get(id: string): T {
55
+ return JSON.parse(readFileSync(this.file(id), 'utf8')) as T
56
+ }
57
+ has(id: string) {
58
+ return existsSync(this.file(id))
59
+ }
60
+ save(value: T) {
61
+ atomicSave(this.file(value.manifest.requestId), value)
62
+ }
63
+ list(): T[] {
64
+ return readdirSync(this.directory)
65
+ .filter((n) => n.endsWith('.json'))
66
+ .map((n) => this.get(n.slice(0, -5)))
67
+ }
68
+ async exclusive<R>(id: string, work: () => Promise<R> | R): Promise<R> {
69
+ const before = this.queues.get(id) ?? Promise.resolve()
70
+ const running = before.catch(() => {}).then(work)
71
+ this.queues.set(id, running)
72
+ try {
73
+ return await running
74
+ } finally {
75
+ if (this.queues.get(id) === running) this.queues.delete(id)
76
+ }
77
+ }
78
+ }
79
+ // This tutorial runs one Node writer. A second process must never mutate the same store.
80
+ export function lockDirectory(root = stateDirectory) {
81
+ mkdirSync(root, { recursive: true, mode: 0o700 })
82
+ const dir = join(root, 'writer.lock')
83
+ if (existsSync(dir)) {
84
+ const pid = Number(readFileSync(join(dir, 'pid'), 'utf8'))
85
+ if (!Number.isSafeInteger(pid) || pid < 1)
86
+ throw new Error('Invalid writer lock; inspect before recovering')
87
+ try {
88
+ process.kill(pid, 0)
89
+ throw new Error('Another writer is active')
90
+ } catch (e) {
91
+ if ((e as NodeJS.ErrnoException).code !== 'ESRCH') throw e
92
+ }
93
+ unlinkSync(join(dir, 'pid'))
94
+ rmdirSync(dir)
95
+ }
96
+ mkdirSync(dir)
97
+ writeFileSync(join(dir, 'pid'), String(process.pid), {
98
+ mode: 0o600,
99
+ flag: 'wx',
100
+ })
101
+ return () => {
102
+ unlinkSync(join(dir, 'pid'))
103
+ rmdirSync(dir)
104
+ }
105
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": [
7
+ "ES2022",
8
+ "DOM",
9
+ "DOM.Iterable"
10
+ ],
11
+ "strict": true,
12
+ "noUncheckedIndexedAccess": true,
13
+ "skipLibCheck": true,
14
+ "noEmit": true,
15
+ "types": [
16
+ "node"
17
+ ],
18
+ "resolveJsonModule": true
19
+ },
20
+ "include": [
21
+ "*.ts",
22
+ "web/*.ts"
23
+ ]
24
+ }
@@ -0,0 +1,24 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { verifyBundle, type Manifest, type Bundle } from './model.js'
3
+ import { readKey } from './backend.js'
4
+ import { deployment } from './config.js'
5
+ const [pdfFile, expectedFile, bundleFile] = process.argv.slice(2)
6
+ if (!pdfFile || !expectedFile || !bundleFile)
7
+ throw new Error(
8
+ 'Usage: npm run verify -- document.pdf expected-request.json signatures.json',
9
+ )
10
+ const expected = JSON.parse(readFileSync(expectedFile, 'utf8')) as Manifest
11
+ if (
12
+ expected.chainId !== deployment.chainId ||
13
+ expected.keyRegistry !== deployment.addresses.KeyRegistry
14
+ )
15
+ throw new Error('Unexpected deployment')
16
+ await verifyBundle(
17
+ readFileSync(pdfFile),
18
+ expected,
19
+ JSON.parse(readFileSync(bundleFile, 'utf8')) as Bundle,
20
+ readKey,
21
+ )
22
+ console.log(
23
+ 'VERIFIED: exact PDF, expected request, Alice and Bob signatures against current anchored keys.',
24
+ )