@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.
- package/CHANGELOG.md +148 -0
- package/LICENSE +202 -0
- package/NOTICE +94 -0
- package/README.md +137 -2
- package/SECURITY.md +115 -0
- package/dist/app/approvals.d.ts +50 -0
- package/dist/app/approvals.js +90 -0
- package/dist/app/authorization.d.ts +19 -0
- package/dist/app/authorization.js +20 -0
- package/dist/app/client.d.ts +231 -0
- package/dist/app/client.js +272 -0
- package/dist/app/creation.d.ts +73 -0
- package/dist/app/creation.js +77 -0
- package/dist/app/deployment.d.ts +36 -0
- package/dist/app/deployment.js +18 -0
- package/dist/app/identity.d.ts +211 -0
- package/dist/app/identity.js +287 -0
- package/dist/app/index.d.ts +22 -0
- package/dist/app/index.js +12 -0
- package/dist/app/manifest.d.ts +74 -0
- package/dist/app/manifest.js +120 -0
- package/dist/app/node.d.ts +30 -0
- package/dist/app/node.js +159 -0
- package/dist/app/ready-slot.d.ts +157 -0
- package/dist/app/ready-slot.js +199 -0
- package/dist/app/tasra-client.d.ts +125 -0
- package/dist/app/tasra-client.js +79 -0
- package/dist/app/viem.d.ts +10 -0
- package/dist/app/viem.js +32 -0
- package/dist/app/wallet.d.ts +126 -0
- package/dist/app/wallet.js +137 -0
- package/dist/auth/dpop.d.ts +86 -0
- package/dist/auth/dpop.js +142 -0
- package/dist/auth/holderProof.d.ts +102 -0
- package/dist/auth/holderProof.js +161 -0
- package/dist/auth/identityScope.d.ts +19 -0
- package/dist/auth/identityScope.js +82 -0
- package/dist/auth/index.d.ts +11 -0
- package/dist/auth/index.js +13 -0
- package/dist/auth/oid4vp.d.ts +230 -0
- package/dist/auth/oid4vp.js +780 -0
- package/dist/auth/rego/wasm/PINS.json +11 -0
- package/dist/auth/rego/wasm/keykeeper_rego_wasm.d.ts +76 -0
- package/dist/auth/rego/wasm/keykeeper_rego_wasm.js +379 -0
- package/dist/auth/rego/wasm/keykeeper_rego_wasm_bg.wasm +0 -0
- package/dist/auth/rego.d.ts +192 -0
- package/dist/auth/rego.js +492 -0
- package/dist/auth/verifier.d.ts +166 -0
- package/dist/auth/verifier.js +211 -0
- package/dist/chain/abis/accountantSetRegistry.d.ts +441 -0
- package/dist/chain/abis/accountantSetRegistry.js +574 -0
- package/dist/chain/abis/accountantSlashing.d.ts +2071 -0
- package/dist/chain/abis/accountantSlashing.js +2670 -0
- package/dist/chain/abis/bondingCurve.d.ts +398 -0
- package/dist/chain/abis/bondingCurve.js +521 -0
- package/dist/chain/abis/equivocationSlasher.d.ts +292 -0
- package/dist/chain/abis/equivocationSlasher.js +379 -0
- package/dist/chain/abis/fixedTasraPriceOracle.d.ts +52 -0
- package/dist/chain/abis/fixedTasraPriceOracle.js +72 -0
- package/dist/chain/abis/index.d.ts +12801 -0
- package/dist/chain/abis/index.js +64 -0
- package/dist/chain/abis/keeperShareRegistry.d.ts +519 -0
- package/dist/chain/abis/keeperShareRegistry.js +675 -0
- package/dist/chain/abis/keyRegistry.d.ts +2421 -0
- package/dist/chain/abis/keyRegistry.js +3114 -0
- package/dist/chain/abis/livenessRegistry.d.ts +402 -0
- package/dist/chain/abis/livenessRegistry.js +524 -0
- package/dist/chain/abis/mockEurc.d.ts +210 -0
- package/dist/chain/abis/mockEurc.js +276 -0
- package/dist/chain/abis/nodeRegistry.d.ts +1630 -0
- package/dist/chain/abis/nodeRegistry.js +2113 -0
- package/dist/chain/abis/platformExecutor.d.ts +328 -0
- package/dist/chain/abis/platformExecutor.js +429 -0
- package/dist/chain/abis/prevrandaoSaltBeacon.d.ts +16 -0
- package/dist/chain/abis/prevrandaoSaltBeacon.js +24 -0
- package/dist/chain/abis/serviceRegistry.d.ts +556 -0
- package/dist/chain/abis/serviceRegistry.js +719 -0
- package/dist/chain/abis/settlement.d.ts +1624 -0
- package/dist/chain/abis/settlement.js +2096 -0
- package/dist/chain/abis/tasraSwapRouter.d.ts +92 -0
- package/dist/chain/abis/tasraSwapRouter.js +122 -0
- package/dist/chain/abis/tasraToken.d.ts +455 -0
- package/dist/chain/abis/tasraToken.js +599 -0
- package/dist/chain/abis/tasraVestingVault.d.ts +165 -0
- package/dist/chain/abis/tasraVestingVault.js +215 -0
- package/dist/chain/abis/thresholdRandomBeacon.d.ts +378 -0
- package/dist/chain/abis/thresholdRandomBeacon.js +494 -0
- package/dist/chain/abis/treasury.d.ts +301 -0
- package/dist/chain/abis/treasury.js +390 -0
- package/dist/chain/abis/verifierSetRegistry.d.ts +445 -0
- package/dist/chain/abis/verifierSetRegistry.js +579 -0
- package/dist/chain/client.d.ts +212 -0
- package/dist/chain/client.js +576 -0
- package/dist/chain/commitmentRecovery.d.ts +21 -0
- package/dist/chain/commitmentRecovery.js +44 -0
- package/dist/chain/committeeClient.d.ts +102 -0
- package/dist/chain/committeeClient.js +137 -0
- package/dist/chain/deployments.d.ts +56 -0
- package/dist/chain/deployments.js +269 -0
- package/dist/chain/discovery.d.ts +49 -0
- package/dist/chain/discovery.js +107 -0
- package/dist/chain/events.d.ts +58 -0
- package/dist/chain/events.js +125 -0
- package/dist/chain/format.d.ts +25 -0
- package/dist/chain/format.js +51 -0
- package/dist/chain/index.d.ts +41 -0
- package/dist/chain/index.js +56 -0
- package/dist/chain/manifest.d.ts +165 -0
- package/dist/chain/manifest.js +132 -0
- package/dist/chain/network-profiles.json +75 -0
- package/dist/chain/networks.d.ts +73 -0
- package/dist/chain/networks.js +62 -0
- package/dist/chain/node.d.ts +44 -0
- package/dist/chain/node.js +176 -0
- package/dist/chain/offchain.d.ts +149 -0
- package/dist/chain/offchain.js +73 -0
- package/dist/chain/provisionRule.d.ts +164 -0
- package/dist/chain/provisionRule.js +212 -0
- package/dist/chain/registeredAgent.d.ts +64 -0
- package/dist/chain/registeredAgent.js +140 -0
- package/dist/chain/registeredOperation.d.ts +49 -0
- package/dist/chain/registeredOperation.js +136 -0
- package/dist/chain/registeredRelay.d.ts +206 -0
- package/dist/chain/registeredRelay.js +312 -0
- package/dist/chain/revertReason.d.ts +14 -0
- package/dist/chain/revertReason.js +62 -0
- package/dist/chain/ruleAmendment.d.ts +80 -0
- package/dist/chain/ruleAmendment.js +195 -0
- package/dist/chain/ruleAmendmentCore.d.ts +129 -0
- package/dist/chain/ruleAmendmentCore.js +152 -0
- package/dist/chain/ruleInput.d.ts +10 -0
- package/dist/chain/ruleInput.js +13 -0
- package/dist/chain/serviceIdentity.d.ts +176 -0
- package/dist/chain/serviceIdentity.js +237 -0
- package/dist/chain/serviceProfiles.d.ts +39 -0
- package/dist/chain/serviceProfiles.js +74 -0
- package/dist/chain/services.d.ts +141 -0
- package/dist/chain/services.js +79 -0
- package/dist/chain/slotClient.d.ts +55 -0
- package/dist/chain/slotClient.js +62 -0
- package/dist/chain/slotSeed.d.ts +31 -0
- package/dist/chain/slotSeed.js +98 -0
- package/dist/chain/write.d.ts +431 -0
- package/dist/chain/write.js +958 -0
- package/dist/client/client.d.ts +112 -0
- package/dist/client/client.js +111 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +2 -0
- package/dist/client/session.d.ts +67 -0
- package/dist/client/session.js +238 -0
- package/dist/committee/client.d.ts +284 -0
- package/dist/committee/client.js +351 -0
- package/dist/committee/dual-sign.d.ts +110 -0
- package/dist/committee/dual-sign.js +202 -0
- package/dist/committee/ecdsa.d.ts +36 -0
- package/dist/committee/ecdsa.js +45 -0
- package/dist/committee/extraction.d.ts +82 -0
- package/dist/committee/extraction.js +96 -0
- package/dist/committee/index.d.ts +19 -0
- package/dist/committee/index.js +13 -0
- package/dist/committee/oauth.d.ts +51 -0
- package/dist/committee/oauth.js +90 -0
- package/dist/committee/receipts.d.ts +51 -0
- package/dist/committee/receipts.js +59 -0
- package/dist/committee/request.d.ts +264 -0
- package/dist/committee/request.js +305 -0
- package/dist/committee/token.d.ts +274 -0
- package/dist/committee/token.js +418 -0
- package/dist/crypto/constants.d.ts +10 -0
- package/dist/crypto/constants.js +32 -0
- package/dist/crypto/detect.d.ts +20 -0
- package/dist/crypto/detect.js +44 -0
- package/dist/crypto/envelope.d.ts +60 -0
- package/dist/crypto/envelope.js +243 -0
- package/dist/crypto/frost.d.ts +49 -0
- package/dist/crypto/frost.js +152 -0
- package/dist/crypto/hex.d.ts +7 -0
- package/dist/crypto/hex.js +24 -0
- package/dist/crypto/ibe-blob.d.ts +114 -0
- package/dist/crypto/ibe-blob.js +208 -0
- package/dist/crypto/ibe.d.ts +88 -0
- package/dist/crypto/ibe.js +262 -0
- package/dist/crypto/index.d.ts +12 -0
- package/dist/crypto/index.js +12 -0
- package/dist/crypto/kem.d.ts +55 -0
- package/dist/crypto/kem.js +241 -0
- package/dist/decryption/client.d.ts +64 -0
- package/dist/decryption/client.js +82 -0
- package/dist/decryption/index.d.ts +2 -0
- package/dist/decryption/index.js +2 -0
- package/dist/errors.d.ts +124 -0
- package/dist/errors.js +167 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.js +98 -0
- package/dist/keys/index.d.ts +1 -0
- package/dist/keys/index.js +4 -0
- package/dist/keys/node-client.d.ts +27 -0
- package/dist/keys/node-client.js +97 -0
- package/dist/oid4vp/binding.d.ts +76 -0
- package/dist/oid4vp/binding.js +118 -0
- package/dist/oid4vp/did-web.d.ts +49 -0
- package/dist/oid4vp/did-web.js +57 -0
- package/dist/oid4vp/index.d.ts +9 -0
- package/dist/oid4vp/index.js +10 -0
- package/dist/oid4vp/jose.d.ts +166 -0
- package/dist/oid4vp/jose.js +242 -0
- package/dist/oid4vp/jwe.d.ts +30 -0
- package/dist/oid4vp/jwe.js +93 -0
- package/dist/oid4vp/oid4vci.d.ts +84 -0
- package/dist/oid4vp/oid4vci.js +85 -0
- package/dist/oid4vp/request-object.d.ts +109 -0
- package/dist/oid4vp/request-object.js +96 -0
- package/dist/oid4vp/sd-jwt.d.ts +177 -0
- package/dist/oid4vp/sd-jwt.js +208 -0
- package/dist/oid4vp/verifier-agent.d.ts +161 -0
- package/dist/oid4vp/verifier-agent.js +132 -0
- package/dist/oid4vp/wallet.d.ts +116 -0
- package/dist/oid4vp/wallet.js +108 -0
- package/dist/recipient/store.d.ts +67 -0
- package/dist/recipient/store.js +98 -0
- package/dist/signing/ecdsa.d.ts +49 -0
- package/dist/signing/ecdsa.js +79 -0
- package/dist/signing/frost.d.ts +88 -0
- package/dist/signing/frost.js +145 -0
- package/dist/signing/index.d.ts +4 -0
- package/dist/signing/index.js +3 -0
- package/dist/slots/faucet.d.ts +23 -0
- package/dist/slots/faucet.js +35 -0
- package/dist/slots/index.d.ts +2 -0
- package/dist/slots/index.js +4 -0
- package/dist/verifier-agent/index.d.ts +241 -0
- package/dist/verifier-agent/index.js +411 -0
- package/docs/DEVELOPER-EXPERIENCE.md +62 -0
- package/docs/README.md +33 -0
- package/docs/access-control.md +76 -0
- package/docs/ai-development.md +292 -0
- package/docs/api.md +338 -0
- package/docs/application-api.md +335 -0
- package/docs/architecture.md +65 -0
- package/docs/basics.md +48 -0
- package/docs/capabilities.md +86 -0
- package/docs/chain.md +153 -0
- package/docs/compatibility.md +36 -0
- package/docs/consumer-migrations.md +80 -0
- package/docs/create-slot.md +104 -0
- package/docs/document-signing.md +243 -0
- package/docs/encrypted-notes.md +129 -0
- package/docs/encryption.md +100 -0
- package/docs/errors.md +76 -0
- package/docs/flows.md +289 -0
- package/docs/fuji.md +127 -0
- package/docs/funding.md +126 -0
- package/docs/getting-started.md +94 -0
- package/docs/glossary.md +44 -0
- package/docs/installation.md +132 -0
- package/docs/manage-slot.md +95 -0
- package/docs/native-approvals.md +124 -0
- package/docs/prerequisites.md +137 -0
- package/docs/read-slot.md +41 -0
- package/docs/reference/README.md +30 -0
- package/docs/reference/app-node.md +102 -0
- package/docs/reference/app.md +1737 -0
- package/docs/reference/chain-node.md +159 -0
- package/docs/reference/chain.md +3609 -0
- package/docs/reference/committee.md +2176 -0
- package/docs/reference/main.md +4068 -0
- package/docs/reference/oid4vp.md +2547 -0
- package/docs/reference/verifier-agent.md +498 -0
- package/docs/shared-account.md +168 -0
- package/docs/signing-and-encryption.md +52 -0
- package/docs/signing.md +172 -0
- package/examples/committee-slot.ts +16 -0
- package/examples/connect-fuji.ts +41 -0
- package/examples/connect-network.ts +14 -0
- package/examples/credential-approvals.ts +46 -0
- package/examples/document-signing/README.md +59 -0
- package/examples/document-signing/backend.ts +132 -0
- package/examples/document-signing/build.mjs +19 -0
- package/examples/document-signing/config.ts +34 -0
- package/examples/document-signing/gitignore.template +9 -0
- package/examples/document-signing/model.ts +140 -0
- package/examples/document-signing/network.ts +58 -0
- package/examples/document-signing/package.json +25 -0
- package/examples/document-signing/public/index.html +27 -0
- package/examples/document-signing/public/sample.pdf +31 -0
- package/examples/document-signing/public/styles.css +531 -0
- package/examples/document-signing/server.ts +358 -0
- package/examples/document-signing/setup.ts +111 -0
- package/examples/document-signing/store.ts +105 -0
- package/examples/document-signing/tsconfig.json +24 -0
- package/examples/document-signing/verify.ts +24 -0
- package/examples/document-signing/web/app.ts +312 -0
- package/examples/document-signing/web/preview.ts +67 -0
- package/examples/document-signing/web/wallet.ts +146 -0
- package/examples/document-signing/workflow.test.ts +228 -0
- package/examples/document-signing/workflow.ts +241 -0
- package/examples/document-signing.ts +96 -0
- package/examples/encrypted-notes.ts +86 -0
- package/examples/ethers-signer.ts +204 -0
- package/examples/fund-slot.ts +73 -0
- package/examples/getting-started.ts +25 -0
- package/examples/learning-authorize.ts +23 -0
- package/examples/learning-cancel-slot.ts +11 -0
- package/examples/learning-context.ts +28 -0
- package/examples/learning-create-slot.ts +25 -0
- package/examples/learning-read-slot.ts +8 -0
- package/examples/learning-renew-slot.ts +12 -0
- package/examples/learning-sign.ts +8 -0
- package/examples/live-config.ts +71 -0
- package/examples/minimal.ts +6 -0
- package/examples/native-approvals.ts +57 -0
- package/examples/network.ts +58 -0
- package/examples/offline.ts +16 -0
- package/examples/personal-vault.ts +20 -0
- package/examples/provision-slot.ts +47 -0
- package/examples/shared-account.ts +46 -0
- package/examples/slot-address.ts +13 -0
- package/examples/slot-creation.ts +9 -0
- package/examples/tutorial-negative.ts +26 -0
- package/examples/tutorial-support.ts +76 -0
- package/examples/viem-account.ts +203 -0
- package/package.json +303 -4
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { createIdentity, issueCredential } from '@t3foundry/tasra-sdk/app'
|
|
2
|
+
import { importWallet } from './web/wallet.js'
|
|
3
|
+
import { test } from 'node:test'
|
|
4
|
+
import assert from 'node:assert/strict'
|
|
5
|
+
import { mkdtempSync, rmSync } from 'node:fs'
|
|
6
|
+
import { tmpdir } from 'node:os'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
import {
|
|
10
|
+
Workflow,
|
|
11
|
+
type SigningBackend,
|
|
12
|
+
type RequestRecord,
|
|
13
|
+
type SessionRecord,
|
|
14
|
+
} from './workflow.js'
|
|
15
|
+
import { Store, lockDirectory } from './store.js'
|
|
16
|
+
import { type Proof, digest, toHex } from './model.js'
|
|
17
|
+
const pdf = new TextEncoder().encode('%PDF-1.4\ntest')
|
|
18
|
+
const alice = `0x${'11'.repeat(32)}` as const,
|
|
19
|
+
bob = `0x${'22'.repeat(32)}` as const
|
|
20
|
+
const network = {
|
|
21
|
+
chainId: 43112,
|
|
22
|
+
keyRegistry: `0x${'33'.repeat(20)}` as const,
|
|
23
|
+
slots: { alice, bob },
|
|
24
|
+
}
|
|
25
|
+
function fixture(t: { after: (fn: () => void) => void }) {
|
|
26
|
+
const root = mkdtempSync(join(tmpdir(), 'tasra-sign-test-'))
|
|
27
|
+
t.after(() => rmSync(root, { recursive: true, force: true }))
|
|
28
|
+
let submitted = 0
|
|
29
|
+
const backend: SigningBackend = {
|
|
30
|
+
async open() {
|
|
31
|
+
return {
|
|
32
|
+
sessionId: 'test',
|
|
33
|
+
pollSecret: 'private',
|
|
34
|
+
requestUri: 'https://example.test/request',
|
|
35
|
+
qrPayload: 'test',
|
|
36
|
+
requestHash: alice,
|
|
37
|
+
operation: {},
|
|
38
|
+
} as SessionRecord
|
|
39
|
+
},
|
|
40
|
+
async sign(_, person, __, before) {
|
|
41
|
+
before()
|
|
42
|
+
submitted++
|
|
43
|
+
return {
|
|
44
|
+
name: person,
|
|
45
|
+
slotId: network.slots[person],
|
|
46
|
+
publicKey: alice,
|
|
47
|
+
epoch: 1,
|
|
48
|
+
r: alice,
|
|
49
|
+
z: alice,
|
|
50
|
+
receiptStatus: 'verified',
|
|
51
|
+
} as Proof
|
|
52
|
+
},
|
|
53
|
+
async verify() {},
|
|
54
|
+
}
|
|
55
|
+
const store = new Store<RequestRecord>(root),
|
|
56
|
+
workflow = new Workflow(store, backend, network)
|
|
57
|
+
return {
|
|
58
|
+
root,
|
|
59
|
+
store,
|
|
60
|
+
backend,
|
|
61
|
+
workflow,
|
|
62
|
+
count: () => submitted,
|
|
63
|
+
create: () =>
|
|
64
|
+
workflow.create({
|
|
65
|
+
id: randomUUID(),
|
|
66
|
+
title: 'Agreement',
|
|
67
|
+
version: 1,
|
|
68
|
+
pdf,
|
|
69
|
+
}),
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
void test('creation is idempotent, freezes bytes and hides sessions', async (t) => {
|
|
73
|
+
const f = fixture(t),
|
|
74
|
+
r = await f.create(),
|
|
75
|
+
id = r.manifest.requestId
|
|
76
|
+
assert.deepEqual(
|
|
77
|
+
await f.workflow.create({ id, title: 'Agreement', version: 1, pdf }),
|
|
78
|
+
r,
|
|
79
|
+
)
|
|
80
|
+
await assert.rejects(
|
|
81
|
+
f.workflow.create({ id, title: 'Changed', version: 1, pdf }),
|
|
82
|
+
/different content/,
|
|
83
|
+
)
|
|
84
|
+
await assert.rejects(f.workflow.prepare(id, 'alice', 'wrong'), /differs/)
|
|
85
|
+
const p = await f.workflow.prepare(id, 'alice', await digest(pdf))
|
|
86
|
+
assert.ok(!('sessions' in p))
|
|
87
|
+
assert.ok(!JSON.stringify(p).includes('private'))
|
|
88
|
+
})
|
|
89
|
+
void test('Alice then Bob; concurrent retries sign once; state survives restart', async (t) => {
|
|
90
|
+
const f = fixture(t),
|
|
91
|
+
r = await f.create(),
|
|
92
|
+
id = r.manifest.requestId,
|
|
93
|
+
hash = r.manifest.documentSha256
|
|
94
|
+
await assert.rejects(f.workflow.prepare(id, 'bob', hash), /Alice must/)
|
|
95
|
+
const prepared = await f.workflow.prepare(id, 'alice', hash),
|
|
96
|
+
attempt = prepared.signers.alice.attemptId!
|
|
97
|
+
const [a, b] = await Promise.all([
|
|
98
|
+
f.workflow.complete(id, 'alice', attempt),
|
|
99
|
+
f.workflow.complete(id, 'alice', attempt),
|
|
100
|
+
])
|
|
101
|
+
assert.deepEqual(a, b)
|
|
102
|
+
assert.equal(f.count(), 1)
|
|
103
|
+
const restarted = new Workflow(
|
|
104
|
+
new Store<RequestRecord>(f.root),
|
|
105
|
+
f.backend,
|
|
106
|
+
network,
|
|
107
|
+
)
|
|
108
|
+
restarted.recover()
|
|
109
|
+
assert.deepEqual(await restarted.complete(id, 'alice', attempt), a)
|
|
110
|
+
assert.equal(f.count(), 1)
|
|
111
|
+
await assert.rejects(
|
|
112
|
+
restarted.complete(id, 'alice', 'old'),
|
|
113
|
+
/another attempt/,
|
|
114
|
+
)
|
|
115
|
+
const pb = await restarted.prepare(id, 'bob', hash)
|
|
116
|
+
assert.equal(
|
|
117
|
+
(await restarted.complete(id, 'bob', pb.signers.bob.attemptId!)).status,
|
|
118
|
+
'completed',
|
|
119
|
+
)
|
|
120
|
+
assert.equal(f.count(), 2)
|
|
121
|
+
await assert.rejects(restarted.close(id, 'cancelled'), /Cannot close/)
|
|
122
|
+
})
|
|
123
|
+
void test('post-submission failure is uncertain and never automatically retried', async (t) => {
|
|
124
|
+
const f = fixture(t),
|
|
125
|
+
r = await f.create(),
|
|
126
|
+
id = r.manifest.requestId
|
|
127
|
+
f.backend.verify = async () => {
|
|
128
|
+
throw new Error('Bad signature')
|
|
129
|
+
}
|
|
130
|
+
const p = await f.workflow.prepare(id, 'alice', r.manifest.documentSha256)
|
|
131
|
+
await assert.rejects(
|
|
132
|
+
f.workflow.complete(id, 'alice', p.signers.alice.attemptId!),
|
|
133
|
+
/Bad signature/,
|
|
134
|
+
)
|
|
135
|
+
assert.equal(f.store.get(id).signers.alice.phase, 'uncertain')
|
|
136
|
+
await assert.rejects(
|
|
137
|
+
f.workflow.prepare(id, 'alice', r.manifest.documentSha256),
|
|
138
|
+
/reconciliation/,
|
|
139
|
+
)
|
|
140
|
+
await assert.rejects(f.workflow.close(id, 'cancelled'), /Cannot close/)
|
|
141
|
+
assert.equal(f.count(), 1)
|
|
142
|
+
})
|
|
143
|
+
void test('crash during opening or signing is preserved; active writer cannot be duplicated', async (t) => {
|
|
144
|
+
const f = fixture(t),
|
|
145
|
+
r = await f.create(),
|
|
146
|
+
saved = f.store.get(r.manifest.requestId)
|
|
147
|
+
saved.signers.alice.phase = 'signing'
|
|
148
|
+
saved.signers.bob.phase = 'opening'
|
|
149
|
+
f.store.save(saved)
|
|
150
|
+
f.workflow.recover()
|
|
151
|
+
const after = f.store.get(r.manifest.requestId)
|
|
152
|
+
assert.equal(after.signers.alice.phase, 'uncertain')
|
|
153
|
+
assert.equal(after.signers.bob.phase, 'uncertain')
|
|
154
|
+
const unlock = lockDirectory(f.root)
|
|
155
|
+
try {
|
|
156
|
+
assert.throws(() => lockDirectory(f.root), /Another writer/)
|
|
157
|
+
} finally {
|
|
158
|
+
unlock()
|
|
159
|
+
}
|
|
160
|
+
})
|
|
161
|
+
void test('credential refusal precedes submission and permits a fresh attempt', async (t) => {
|
|
162
|
+
const f = fixture(t),
|
|
163
|
+
r = await f.create(),
|
|
164
|
+
id = r.manifest.requestId
|
|
165
|
+
f.backend.sign = async () => {
|
|
166
|
+
const e = new Error('Denied')
|
|
167
|
+
e.name = 'AuthorizationRefused'
|
|
168
|
+
throw e
|
|
169
|
+
}
|
|
170
|
+
const p = await f.workflow.prepare(id, 'alice', r.manifest.documentSha256)
|
|
171
|
+
await assert.rejects(
|
|
172
|
+
f.workflow.complete(id, 'alice', p.signers.alice.attemptId!),
|
|
173
|
+
/Denied/,
|
|
174
|
+
)
|
|
175
|
+
assert.equal(f.store.get(id).signers.alice.phase, 'refused')
|
|
176
|
+
assert.equal(f.count(), 0)
|
|
177
|
+
const next = await f.workflow.prepare(id, 'alice', r.manifest.documentSha256)
|
|
178
|
+
assert.notEqual(next.signers.alice.attemptId, p.signers.alice.attemptId)
|
|
179
|
+
await assert.rejects(
|
|
180
|
+
f.workflow.complete(id, 'alice', p.signers.alice.attemptId!),
|
|
181
|
+
/another attempt/,
|
|
182
|
+
)
|
|
183
|
+
})
|
|
184
|
+
void test('cancel and decline close unsigned work permanently', async (t) => {
|
|
185
|
+
for (const state of ['cancelled', 'declined'] as const) {
|
|
186
|
+
const f = fixture(t),
|
|
187
|
+
r = await f.create()
|
|
188
|
+
await f.workflow.close(
|
|
189
|
+
r.manifest.requestId,
|
|
190
|
+
state,
|
|
191
|
+
state === 'declined' ? 'alice' : undefined,
|
|
192
|
+
)
|
|
193
|
+
await assert.rejects(
|
|
194
|
+
f.workflow.prepare(
|
|
195
|
+
r.manifest.requestId,
|
|
196
|
+
'alice',
|
|
197
|
+
r.manifest.documentSha256,
|
|
198
|
+
),
|
|
199
|
+
/closed/,
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
test('generated credential wallet imports with its identity and rejects swapped keys or subjects', () => {
|
|
205
|
+
const issuer = createIdentity(), aliceIdentity = createIdentity(), otherIdentity = createIdentity()
|
|
206
|
+
const credential = issueCredential({
|
|
207
|
+
issuer, holder: aliceIdentity, type: 'DocumentSigner',
|
|
208
|
+
subject: 'did:demo:alice', claims: { role: 'document-signer' },
|
|
209
|
+
})
|
|
210
|
+
const walletFile = {
|
|
211
|
+
schema: 'tasra-demo-wallet/v1', name: 'alice',
|
|
212
|
+
seed: toHex(aliceIdentity.exportPrivateKey()), credential,
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
const wallet = importWallet(JSON.stringify(walletFile))
|
|
216
|
+
assert.equal(wallet.identity.did, aliceIdentity.did)
|
|
217
|
+
assert.equal(wallet.credential, credential)
|
|
218
|
+
wallet.identity.destroy()
|
|
219
|
+
assert.throws(() => importWallet(JSON.stringify({
|
|
220
|
+
...walletFile, seed: toHex(otherIdentity.exportPrivateKey()),
|
|
221
|
+
})), /holder mismatch/)
|
|
222
|
+
assert.throws(() => importWallet(JSON.stringify({
|
|
223
|
+
...walletFile, name: 'bob',
|
|
224
|
+
})), /subject mismatch/)
|
|
225
|
+
} finally {
|
|
226
|
+
issuer.destroy(); aliceIdentity.destroy(); otherIdentity.destroy()
|
|
227
|
+
}
|
|
228
|
+
})
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import type { Hex } from './model.js'
|
|
3
|
+
import type { OpenedVerifierAgentSession } from '@t3foundry/tasra-sdk/oid4vp'
|
|
4
|
+
import { Store } from './store.js'
|
|
5
|
+
import {
|
|
6
|
+
digest,
|
|
7
|
+
statement,
|
|
8
|
+
people,
|
|
9
|
+
type Person,
|
|
10
|
+
type Manifest,
|
|
11
|
+
type Proof,
|
|
12
|
+
type PublicRequest,
|
|
13
|
+
} from './model.js'
|
|
14
|
+
|
|
15
|
+
export type SessionRecord = {
|
|
16
|
+
sessionId: string
|
|
17
|
+
pollSecret: string
|
|
18
|
+
requestUri: string
|
|
19
|
+
qrPayload: string
|
|
20
|
+
requestHash: Hex
|
|
21
|
+
operation: OpenedVerifierAgentSession['operation']
|
|
22
|
+
}
|
|
23
|
+
export type RequestRecord = PublicRequest & {
|
|
24
|
+
pdfBase64: string
|
|
25
|
+
sessions: Partial<Record<Person, SessionRecord>>
|
|
26
|
+
}
|
|
27
|
+
export interface SigningBackend {
|
|
28
|
+
open(manifest: Manifest, person: Person): Promise<SessionRecord>
|
|
29
|
+
sign(
|
|
30
|
+
manifest: Manifest,
|
|
31
|
+
person: Person,
|
|
32
|
+
session: SessionRecord,
|
|
33
|
+
beforeSubmit: () => void,
|
|
34
|
+
): Promise<Proof>
|
|
35
|
+
verify(manifest: Manifest, proof: Proof): Promise<void>
|
|
36
|
+
}
|
|
37
|
+
export class Conflict extends Error {}
|
|
38
|
+
export function publicView(record: RequestRecord): PublicRequest {
|
|
39
|
+
const { manifest, status, signers, history } = record
|
|
40
|
+
return structuredClone({ manifest, status, signers, history })
|
|
41
|
+
}
|
|
42
|
+
export class Workflow {
|
|
43
|
+
constructor(
|
|
44
|
+
readonly store: Store<RequestRecord>,
|
|
45
|
+
readonly backend: SigningBackend,
|
|
46
|
+
readonly network: {
|
|
47
|
+
chainId: number
|
|
48
|
+
keyRegistry: Hex
|
|
49
|
+
slots: Record<Person, Hex>
|
|
50
|
+
},
|
|
51
|
+
) {}
|
|
52
|
+
private event(r: RequestRecord, event: string, person?: Person) {
|
|
53
|
+
r.history.push({
|
|
54
|
+
at: new Date().toISOString(),
|
|
55
|
+
event,
|
|
56
|
+
...(person ? { person } : {}),
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
private active(r: RequestRecord) {
|
|
60
|
+
if (['cancelled', 'declined'].includes(r.status))
|
|
61
|
+
throw new Conflict('This request is closed')
|
|
62
|
+
}
|
|
63
|
+
async create(input: {
|
|
64
|
+
id: string
|
|
65
|
+
title: string
|
|
66
|
+
version: number
|
|
67
|
+
pdf: Uint8Array
|
|
68
|
+
}) {
|
|
69
|
+
if (
|
|
70
|
+
!input.title.trim() ||
|
|
71
|
+
input.title.length > 120 ||
|
|
72
|
+
input.pdf.length > 8 * 1024 * 1024 ||
|
|
73
|
+
new TextDecoder().decode(input.pdf.slice(0, 5)) !== '%PDF-' ||
|
|
74
|
+
!Number.isSafeInteger(input.version) ||
|
|
75
|
+
input.version < 1
|
|
76
|
+
)
|
|
77
|
+
throw new Error(
|
|
78
|
+
'Provide a PDF up to 8 MB, a title and a positive version',
|
|
79
|
+
)
|
|
80
|
+
const manifest: Manifest = {
|
|
81
|
+
schema: 'tasra-sign/v1',
|
|
82
|
+
requestId: input.id,
|
|
83
|
+
version: input.version,
|
|
84
|
+
title: input.title.trim(),
|
|
85
|
+
documentSha256: await digest(input.pdf),
|
|
86
|
+
chainId: this.network.chainId,
|
|
87
|
+
keyRegistry: this.network.keyRegistry,
|
|
88
|
+
signers: people.map((name) => ({
|
|
89
|
+
name,
|
|
90
|
+
slotId: this.network.slots[name],
|
|
91
|
+
})),
|
|
92
|
+
}
|
|
93
|
+
return this.store.exclusive(input.id, () => {
|
|
94
|
+
if (this.store.has(input.id)) {
|
|
95
|
+
const existing = this.store.get(input.id)
|
|
96
|
+
if (
|
|
97
|
+
Buffer.compare(
|
|
98
|
+
Buffer.from(statement(existing.manifest)),
|
|
99
|
+
Buffer.from(statement(manifest)),
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
throw new Conflict('Request ID already belongs to different content')
|
|
103
|
+
return publicView(existing)
|
|
104
|
+
}
|
|
105
|
+
const record: RequestRecord = {
|
|
106
|
+
manifest,
|
|
107
|
+
status: 'awaiting_alice',
|
|
108
|
+
signers: { alice: { phase: 'pending' }, bob: { phase: 'pending' } },
|
|
109
|
+
history: [],
|
|
110
|
+
pdfBase64: Buffer.from(input.pdf).toString('base64'),
|
|
111
|
+
sessions: {},
|
|
112
|
+
}
|
|
113
|
+
this.event(record, 'Request created')
|
|
114
|
+
this.store.save(record)
|
|
115
|
+
return publicView(record)
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
async prepare(id: string, person: Person, documentSha256: string) {
|
|
119
|
+
return this.store.exclusive(id, async () => {
|
|
120
|
+
const r = this.store.get(id)
|
|
121
|
+
this.active(r)
|
|
122
|
+
if (documentSha256 !== r.manifest.documentSha256)
|
|
123
|
+
throw new Conflict('Reviewed document differs')
|
|
124
|
+
const signer = r.signers[person]
|
|
125
|
+
if (signer.phase === 'signed') return publicView(r)
|
|
126
|
+
if (person === 'bob' && r.signers.alice.phase !== 'signed')
|
|
127
|
+
throw new Conflict('Alice must sign first')
|
|
128
|
+
if (signer.phase === 'awaiting_wallet') return publicView(r)
|
|
129
|
+
if (signer.phase !== 'pending' && signer.phase !== 'refused')
|
|
130
|
+
throw new Conflict(
|
|
131
|
+
'Operation requires reconciliation; do not submit another signature',
|
|
132
|
+
)
|
|
133
|
+
// Persist before opening. A crash with no returned session is explicitly uncertain.
|
|
134
|
+
signer.phase = 'opening'
|
|
135
|
+
signer.attemptId = randomUUID()
|
|
136
|
+
delete signer.error
|
|
137
|
+
this.store.save(r)
|
|
138
|
+
try {
|
|
139
|
+
r.sessions[person] = await this.backend.open(r.manifest, person)
|
|
140
|
+
signer.phase = 'awaiting_wallet'
|
|
141
|
+
this.event(r, 'Wallet request opened', person)
|
|
142
|
+
this.store.save(r)
|
|
143
|
+
return publicView(r)
|
|
144
|
+
} catch {
|
|
145
|
+
signer.phase = 'uncertain'
|
|
146
|
+
signer.error = 'Session opening outcome unknown'
|
|
147
|
+
this.store.save(r)
|
|
148
|
+
throw new Conflict(signer.error)
|
|
149
|
+
}
|
|
150
|
+
})
|
|
151
|
+
}
|
|
152
|
+
async complete(id: string, person: Person, attemptId: string) {
|
|
153
|
+
return this.store.exclusive(id, async () => {
|
|
154
|
+
const r = this.store.get(id)
|
|
155
|
+
this.active(r)
|
|
156
|
+
const signer = r.signers[person]
|
|
157
|
+
if (attemptId !== signer.attemptId)
|
|
158
|
+
throw new Conflict('Completion belongs to another attempt')
|
|
159
|
+
if (signer.phase === 'signed') return publicView(r) // duplicate completion returns the saved proof
|
|
160
|
+
if (signer.phase !== 'awaiting_wallet' || !r.sessions[person])
|
|
161
|
+
throw new Conflict('Request is not awaiting this wallet')
|
|
162
|
+
try {
|
|
163
|
+
const proof = await this.backend.sign(
|
|
164
|
+
r.manifest,
|
|
165
|
+
person,
|
|
166
|
+
r.sessions[person]!,
|
|
167
|
+
() => {
|
|
168
|
+
signer.phase = 'signing'
|
|
169
|
+
this.store.save(r) // flush before keeper submission
|
|
170
|
+
},
|
|
171
|
+
)
|
|
172
|
+
await this.backend.verify(r.manifest, proof)
|
|
173
|
+
signer.signature = proof
|
|
174
|
+
signer.phase = 'signed'
|
|
175
|
+
delete signer.error
|
|
176
|
+
delete r.sessions[person]
|
|
177
|
+
r.status = person === 'alice' ? 'awaiting_bob' : 'completed'
|
|
178
|
+
this.event(r, 'Signature verified', person)
|
|
179
|
+
this.store.save(r)
|
|
180
|
+
return publicView(r)
|
|
181
|
+
} catch (e) {
|
|
182
|
+
// A verifier refusal precedes signing and is safe to correct with a new presentation.
|
|
183
|
+
// A transport/verification failure after submission may hide a completed signature.
|
|
184
|
+
if (
|
|
185
|
+
signer.phase === 'awaiting_wallet' &&
|
|
186
|
+
e instanceof Error &&
|
|
187
|
+
e.name === 'AuthorizationRefused'
|
|
188
|
+
) {
|
|
189
|
+
signer.phase = 'refused'
|
|
190
|
+
signer.error = 'The verifier refused this credential'
|
|
191
|
+
delete r.sessions[person]
|
|
192
|
+
this.event(r, 'Credential refused', person)
|
|
193
|
+
} else if ((signer.phase as string) === 'signing') {
|
|
194
|
+
signer.phase = 'uncertain'
|
|
195
|
+
signer.error = 'Signing outcome unknown; preserve this request'
|
|
196
|
+
this.event(r, 'Reconciliation required', person)
|
|
197
|
+
}
|
|
198
|
+
this.store.save(r)
|
|
199
|
+
throw e
|
|
200
|
+
}
|
|
201
|
+
})
|
|
202
|
+
}
|
|
203
|
+
async close(id: string, status: 'cancelled' | 'declined', person?: Person) {
|
|
204
|
+
return this.store.exclusive(id, () => {
|
|
205
|
+
const r = this.store.get(id)
|
|
206
|
+
this.active(r)
|
|
207
|
+
if (
|
|
208
|
+
(person && r.signers[person].phase === 'signed') ||
|
|
209
|
+
r.status === 'completed' ||
|
|
210
|
+
people.some((p) =>
|
|
211
|
+
['opening', 'signing', 'uncertain'].includes(r.signers[p].phase),
|
|
212
|
+
)
|
|
213
|
+
)
|
|
214
|
+
throw new Conflict('Cannot close completed or uncertain work')
|
|
215
|
+
r.status = status
|
|
216
|
+
this.event(
|
|
217
|
+
r,
|
|
218
|
+
status === 'cancelled' ? 'Sender cancelled' : 'Signer declined',
|
|
219
|
+
person,
|
|
220
|
+
)
|
|
221
|
+
r.sessions = {}
|
|
222
|
+
this.store.save(r)
|
|
223
|
+
return publicView(r)
|
|
224
|
+
})
|
|
225
|
+
}
|
|
226
|
+
recover() {
|
|
227
|
+
for (const r of this.store.list()) {
|
|
228
|
+
let changed = false
|
|
229
|
+
for (const p of people)
|
|
230
|
+
if (['opening', 'signing'].includes(r.signers[p].phase)) {
|
|
231
|
+
r.signers[p].phase = 'uncertain'
|
|
232
|
+
r.signers[p].error = 'Interrupted operation; reconciliation required'
|
|
233
|
+
changed = true
|
|
234
|
+
}
|
|
235
|
+
if (changed) {
|
|
236
|
+
this.event(r, 'Interrupted operation preserved')
|
|
237
|
+
this.store.save(r)
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** Two people independently sign the exact same document and request. */
|
|
2
|
+
import {writeFileSync} from 'node:fs'
|
|
3
|
+
import {createHash, randomUUID} from 'node:crypto'
|
|
4
|
+
import {verifyFrostSignature, hexToBytes} from '@t3foundry/tasra-sdk'
|
|
5
|
+
import type {ReadySlotJournal} from '@t3foundry/tasra-sdk/app'
|
|
6
|
+
import {createTutorial} from './tutorial-support.js'
|
|
7
|
+
|
|
8
|
+
type Hex = `0x${string}`
|
|
9
|
+
const toHex = (bytes: Uint8Array): Hex => `0x${Buffer.from(bytes).toString('hex')}`
|
|
10
|
+
|
|
11
|
+
async function main() {
|
|
12
|
+
// 1. Read the public manifest and create fresh local wallets, identities and credentials.
|
|
13
|
+
const {tasra, awaitUsageCredit, policy, authorize, proveServerRefusal, directory, save, store} =
|
|
14
|
+
await createTutorial('document-signing', 'DocumentSigner', 'document-signer')
|
|
15
|
+
const {chainId, addresses} = tasra.deployment
|
|
16
|
+
|
|
17
|
+
// 2. Give each signer a slot; the SDK persists creation, waits for keys and provisions policy.
|
|
18
|
+
const signers: Array<{name: string; slotId: Hex}> = []
|
|
19
|
+
const creations = []
|
|
20
|
+
for (const name of ['alice', 'bob']) {
|
|
21
|
+
const slot = await tasra.slots.create({name: `${name}-documents`, mode: 'frost', policy: policy([name]),
|
|
22
|
+
threshold: {k: 2, n: 3}, verifiers: {committee: 3, quorum: 2}})
|
|
23
|
+
await awaitUsageCredit(slot.slotId)
|
|
24
|
+
signers.push({name, slotId: slot.slotId})
|
|
25
|
+
const journal = await store.load<ReadySlotJournal>(`slot-${name}-documents`)
|
|
26
|
+
if (!journal?.creation.result) throw new Error('Missing creation evidence')
|
|
27
|
+
const {commitTx, revealTx, targetEpoch, seeded} = journal.creation.result
|
|
28
|
+
creations.push({slotId: slot.slotId, commitTx, revealTx, targetEpoch, seeded})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// 3. Freeze the document bytes and signer assignments before requesting either signature.
|
|
32
|
+
// A tiny PDF fixture. Applications freeze the exact uploaded PDF bytes at this point.
|
|
33
|
+
const objects = ['<</Type/Catalog/Pages 2 0 R>>', '<</Type/Pages/Count 1/Kids[3 0 R]>>',
|
|
34
|
+
'<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]/Resources<</Font<</F1 4 0 R>>>>/Contents 5 0 R>>',
|
|
35
|
+
'<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>']
|
|
36
|
+
const content = 'BT /F1 18 Tf 72 700 Td (Synthetic agreement: Alice and Bob approve.) Tj ET\n'
|
|
37
|
+
objects.push(`<</Length ${content.length}>>\nstream\n${content}endstream`)
|
|
38
|
+
let pdfText = '%PDF-1.4\n'; const offsets = [0]
|
|
39
|
+
for (const [index, object] of objects.entries()) { offsets.push(pdfText.length); pdfText += `${index + 1} 0 obj\n${object}\nendobj\n` }
|
|
40
|
+
const xref = pdfText.length
|
|
41
|
+
pdfText += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n` + offsets.slice(1).map(o => `${String(o).padStart(10, '0')} 00000 n \n`).join('')
|
|
42
|
+
pdfText += `trailer<</Size ${objects.length + 1}/Root 1 0 R>>\nstartxref\n${xref}\n%%EOF\n`
|
|
43
|
+
const pdf = new TextEncoder().encode(pdfText)
|
|
44
|
+
writeFileSync(`${directory}/document.pdf`, pdf, {mode: 0o600})
|
|
45
|
+
const manifest = {schema: 'tasra-document/v1', requestId: randomUUID(), version: 1,
|
|
46
|
+
documentSha256: createHash('sha256').update(pdf).digest('hex'), chainId,
|
|
47
|
+
keyRegistry: addresses.KeyRegistry, signers}
|
|
48
|
+
const message = new TextEncoder().encode(JSON.stringify(manifest))
|
|
49
|
+
save('request.json', manifest)
|
|
50
|
+
const signatures: Array<{name: string; slotId: Hex; r: Hex; z: Hex; receiptStatus: string; epoch: number}> = []
|
|
51
|
+
for (const signer of signers) {
|
|
52
|
+
const handle = await tasra.slots.frost(signer.slotId)
|
|
53
|
+
const result = await handle.sign(message, {authorize: authorize(signer.name), requireReceipt: true,
|
|
54
|
+
signal: AbortSignal.timeout(120_000)})
|
|
55
|
+
const proof = {name: signer.name, slotId: signer.slotId, r: toHex(result.signature.r), z: toHex(result.signature.z),
|
|
56
|
+
receiptStatus: result.receiptStatus, epoch: result.epoch}
|
|
57
|
+
signatures.push(proof)
|
|
58
|
+
save(`${signer.name}-signature.json`, proof)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// 4. Read public keys independently and reject altered documents, replay and duplicate signers.
|
|
62
|
+
// A verifier receives its expected request and independently reads signer keys from chain.
|
|
63
|
+
// Never accept arbitrary public keys or signer assignments merely because a bundle carries them.
|
|
64
|
+
const verifyBundle = async (bytes: Uint8Array, expected: typeof manifest, proofs: typeof signatures) => {
|
|
65
|
+
if (createHash('sha256').update(bytes).digest('hex') !== expected.documentSha256 || proofs.length !== 2 ||
|
|
66
|
+
new Set(proofs.map(p => p.name)).size !== 2 || new Set(proofs.map(p => p.slotId)).size !== 2) return false
|
|
67
|
+
const payload = new TextEncoder().encode(JSON.stringify(expected))
|
|
68
|
+
for (const person of expected.signers) {
|
|
69
|
+
const proof = proofs.find(p => p.name === person.name && p.slotId === person.slotId)
|
|
70
|
+
if (!proof) return false
|
|
71
|
+
const key = await tasra.chain.readers.keyRegistry.getKeySlot(person.slotId)
|
|
72
|
+
if (!key.exists || key.cancelled || key.mode !== 0 || Number(key.epoch) !== proof.epoch ||
|
|
73
|
+
!verifyFrostSignature(hexToBytes(key.publicKey), payload, {r: hexToBytes(proof.r), z: hexToBytes(proof.z)})) return false
|
|
74
|
+
}
|
|
75
|
+
return true
|
|
76
|
+
}
|
|
77
|
+
if (!await verifyBundle(pdf, manifest, signatures)) throw new Error('Independent verification failed')
|
|
78
|
+
const changedPdf = pdf.slice(); changedPdf[0] = changedPdf[0]! ^ 1
|
|
79
|
+
const checks = {changedPdf: !await verifyBundle(changedPdf, manifest, signatures),
|
|
80
|
+
anotherRequest: !await verifyBundle(pdf, {...manifest, requestId: randomUUID()}, signatures),
|
|
81
|
+
anotherVersion: !await verifyBundle(pdf, {...manifest, version: 2}, signatures),
|
|
82
|
+
duplicateSigner: !await verifyBundle(pdf, manifest, [signatures[0]!, signatures[0]!])}
|
|
83
|
+
if (Object.values(checks).some(ok => !ok)) throw new Error('Negative document check failed')
|
|
84
|
+
const bobCannotSignAlice = await proveServerRefusal(signers[0]!.slotId, 'bob', 'sign', {message})
|
|
85
|
+
save('signature-bundle.json', {manifest, signatures})
|
|
86
|
+
save('evidence.json', {chainId, addresses, createdAt: new Date().toISOString(), manifest, signatures,
|
|
87
|
+
creations, independentVerification: true, checks, bobCannotSignAlice})
|
|
88
|
+
console.log(`PASS: Alice AND Bob signed; document tampering, replay and duplicate signer rejected. Evidence: ${directory}/evidence.json`)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
main().catch((error: unknown) => {
|
|
92
|
+
// Keep credential-bearing error objects out of terminal output.
|
|
93
|
+
const message = (error instanceof Error ? error.message : String(error)).replace(/eyJ[\w-]+\.[\w-]+\.[\w-]+(?:~[\w.-]*)*/g, '[credential omitted]')
|
|
94
|
+
console.error(`Stopped: ${message}`)
|
|
95
|
+
process.exitCode = 1
|
|
96
|
+
})
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** Encrypt a private note; only Alice's credential may unlock it. */
|
|
2
|
+
import {randomUUID, webcrypto as nodeWebCrypto} from 'node:crypto'
|
|
3
|
+
import {sha256} from '@noble/hashes/sha256'
|
|
4
|
+
import {utf8ToBytes} from '@noble/hashes/utils'
|
|
5
|
+
import {decryptPayloadDigest} from '@t3foundry/tasra-sdk/oid4vp'
|
|
6
|
+
import type {ReadySlotJournal} from '@t3foundry/tasra-sdk/app'
|
|
7
|
+
import {createTutorial} from './tutorial-support.js'
|
|
8
|
+
|
|
9
|
+
async function main() {
|
|
10
|
+
// 1. Connect from the public manifest and create fresh identities with the SDK.
|
|
11
|
+
const {tasra, awaitUsageCredit, issuer, users, policy, authorize, proveServerRefusal, directory, save, store} =
|
|
12
|
+
await createTutorial('encrypted-notes', 'DocumentReader', 'document-reader')
|
|
13
|
+
const recordId = randomUUID()
|
|
14
|
+
const aad = sha256(utf8ToBytes(`tasra-encrypt/v2:${recordId}`))
|
|
15
|
+
for (const user of Object.values(users)) {
|
|
16
|
+
user.credential = tasra.credentials.issue({issuer, holder: user.identity, type: 'DocumentReader',
|
|
17
|
+
claims: {role: 'document-reader', documents: [recordId]}})
|
|
18
|
+
}
|
|
19
|
+
await store.save('credentials', Object.fromEntries(Object.entries(users).map(([name, user]) => [name, user.credential])))
|
|
20
|
+
|
|
21
|
+
// 2. Commit Alice's document-scoped policy; the SDK creates and provisions a ready slot.
|
|
22
|
+
const notes = await tasra.slots.create({name: 'private-notes', mode: 'bls',
|
|
23
|
+
policy: policy(['alice'], {claim: 'documents'}), threshold: {k: 2, n: 3},
|
|
24
|
+
verifiers: {committee: 3, quorum: 2}})
|
|
25
|
+
await awaitUsageCredit(notes.slotId)
|
|
26
|
+
|
|
27
|
+
// 3. Generate an AES-256 data key, encrypt the payload, and wrap the key with the BLS KEM.
|
|
28
|
+
const plaintext = new TextEncoder().encode('A synthetic private note')
|
|
29
|
+
const dataKey = nodeWebCrypto.getRandomValues(new Uint8Array(32))
|
|
30
|
+
const iv = nodeWebCrypto.getRandomValues(new Uint8Array(12))
|
|
31
|
+
const aesKey = await nodeWebCrypto.subtle.importKey('raw', dataKey, 'AES-GCM', false, ['encrypt'])
|
|
32
|
+
const aesCt = new Uint8Array(await nodeWebCrypto.subtle.encrypt(
|
|
33
|
+
{name: 'AES-GCM', iv, additionalData: aad}, aesKey, plaintext))
|
|
34
|
+
const kemCt = await notes.encrypt(aad, dataKey)
|
|
35
|
+
dataKey.fill(0)
|
|
36
|
+
await store.save('encrypted-document', {recordId, aad, kemCt, aesCt, iv})
|
|
37
|
+
|
|
38
|
+
// Alice presents her credential to authorize decryption.
|
|
39
|
+
const opened = await notes.decrypt(aad, kemCt, {authorize: authorize('alice'),
|
|
40
|
+
signal: AbortSignal.timeout(120_000), requireReceipts: true})
|
|
41
|
+
let openedNote: Uint8Array | undefined
|
|
42
|
+
try {
|
|
43
|
+
const decryptKey = await nodeWebCrypto.subtle.importKey('raw', opened.plaintext, 'AES-GCM', false, ['decrypt'])
|
|
44
|
+
const decrypted = new Uint8Array(await nodeWebCrypto.subtle.decrypt(
|
|
45
|
+
{name: 'AES-GCM', iv, additionalData: aad}, decryptKey, aesCt))
|
|
46
|
+
if (new TextDecoder().decode(decrypted) !== 'A synthetic private note') throw new Error('Decryption differs')
|
|
47
|
+
openedNote = decrypted
|
|
48
|
+
} finally { opened.plaintext.fill(0) }
|
|
49
|
+
|
|
50
|
+
// 4. Test server refusal separately from ciphertext authentication, with a positive control.
|
|
51
|
+
const refusal = await proveServerRefusal(notes.slotId, 'bob', 'decrypt',
|
|
52
|
+
{payloadDigest: decryptPayloadDigest(kemCt.u, kemCt.aeadCt)})
|
|
53
|
+
let tamperRejected = false
|
|
54
|
+
try {
|
|
55
|
+
// Positive control: the main decrypt (step 3) already authenticated the original ct.
|
|
56
|
+
const tamperedAead = kemCt.aeadCt.slice() as Uint8Array
|
|
57
|
+
tamperedAead[0]! ^= 1
|
|
58
|
+
const tampered = {u: kemCt.u.slice(), nonce: kemCt.nonce.slice(), aeadCt: tamperedAead}
|
|
59
|
+
const bad = await notes.decrypt(aad, tampered, {authorize: authorize('alice'),
|
|
60
|
+
signal: AbortSignal.timeout(120_000), requireReceipts: true})
|
|
61
|
+
bad.plaintext.fill(0) // unreachable; throw before zeroizing
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error instanceof Error && /authentication|invalid tag/i.test(error.message)) tamperRejected = true
|
|
64
|
+
else throw error
|
|
65
|
+
}
|
|
66
|
+
if (!tamperRejected) throw new Error('Tampered ciphertext was accepted')
|
|
67
|
+
try { openedNote?.fill(0); plaintext.fill(0) } catch { /* best-effort */ }
|
|
68
|
+
|
|
69
|
+
// Evidence exposes transaction and receipt references, never the private creation journal.
|
|
70
|
+
const journal = await store.load<ReadySlotJournal>('slot-private-notes')
|
|
71
|
+
if (!journal?.creation.result) throw new Error('Missing creation evidence')
|
|
72
|
+
const {commitTx, revealTx, targetEpoch, seeded} = journal.creation.result
|
|
73
|
+
save('evidence.json', {chainId: tasra.deployment.chainId, addresses: tasra.deployment.addresses,
|
|
74
|
+
slotId: notes.slotId, creation: {slotId: notes.slotId, commitTx, revealTx, targetEpoch, seeded},
|
|
75
|
+
createdAt: new Date().toISOString(), alice: 'decrypted', bob: refusal, tamperRejected,
|
|
76
|
+
shareTrust: opened.shareTrust, receipts: opened.evidence.map(e => ({operator: e.operator, identifier: e.identifier,
|
|
77
|
+
status: e.receiptStatus}))})
|
|
78
|
+
console.log(`PASS: Alice decrypted, Bob refused by verifier, tamper rejected. Evidence: ${directory}/evidence.json`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
main().catch((error: unknown) => {
|
|
82
|
+
// Keep credential-bearing error objects out of terminal output.
|
|
83
|
+
const message = (error instanceof Error ? error.message : String(error)).replace(/eyJ[\w-]+\.[\w-]+\.[\w-]+(?:~[\w.-]*)*/g, '[credential omitted]')
|
|
84
|
+
console.error(`Stopped: ${message}`)
|
|
85
|
+
process.exitCode = 1
|
|
86
|
+
})
|