@tik-choco/mistsign 0.0.0-stage → 0.1.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/LICENSE +373 -0
- package/README.ja.md +125 -0
- package/README.md +129 -2
- package/README.zh.md +122 -0
- package/dist/agreement/bundle.d.ts +23 -0
- package/dist/agreement/bundle.js +139 -0
- package/dist/agreement/decision.d.ts +7 -0
- package/dist/agreement/decision.js +77 -0
- package/dist/agreement/errors.d.ts +9 -0
- package/dist/agreement/errors.js +19 -0
- package/dist/agreement/evaluate.d.ts +5 -0
- package/dist/agreement/evaluate.js +112 -0
- package/dist/agreement/index.d.ts +9 -0
- package/dist/agreement/index.js +6 -0
- package/dist/agreement/policy.d.ts +31 -0
- package/dist/agreement/policy.js +113 -0
- package/dist/agreement/proposal.d.ts +4 -0
- package/dist/agreement/proposal.js +107 -0
- package/dist/agreement/schema.d.ts +16 -0
- package/dist/agreement/schema.js +93 -0
- package/dist/agreement/strict.d.ts +5 -0
- package/dist/agreement/strict.js +167 -0
- package/dist/agreement/types.d.ts +214 -0
- package/dist/agreement/types.js +3 -0
- package/dist/agreement/verify.d.ts +4 -0
- package/dist/agreement/verify.js +151 -0
- package/dist/bytes.d.ts +6 -0
- package/dist/bytes.js +19 -0
- package/dist/content.d.ts +10 -0
- package/dist/content.js +58 -0
- package/dist/didKey.d.ts +4 -0
- package/dist/didKey.js +48 -0
- package/dist/elements/index.d.ts +1 -0
- package/dist/elements/index.js +2 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +8 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +6 -0
- package/dist/json.d.ts +20 -0
- package/dist/json.js +170 -0
- package/dist/preact/index.d.ts +1 -0
- package/dist/preact/index.js +2 -0
- package/dist/preact/ui.css +0 -0
- package/dist/sha256.d.ts +11 -0
- package/dist/sha256.js +103 -0
- package/dist/sign.d.ts +33 -0
- package/dist/sign.js +61 -0
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.js +27 -0
- package/dist/time.d.ts +9 -0
- package/dist/time.js +36 -0
- package/dist/timestamp/asnTime.d.ts +2 -0
- package/dist/timestamp/asnTime.js +17 -0
- package/dist/timestamp/cms.d.ts +30 -0
- package/dist/timestamp/cms.js +126 -0
- package/dist/timestamp/constraints.d.ts +17 -0
- package/dist/timestamp/constraints.js +159 -0
- package/dist/timestamp/crypto.d.ts +6 -0
- package/dist/timestamp/crypto.js +101 -0
- package/dist/timestamp/der.d.ts +24 -0
- package/dist/timestamp/der.js +118 -0
- package/dist/timestamp/index.d.ts +2 -0
- package/dist/timestamp/index.js +1 -0
- package/dist/timestamp/name.d.ts +2 -0
- package/dist/timestamp/name.js +55 -0
- package/dist/timestamp/policy.d.ts +9 -0
- package/dist/timestamp/policy.js +56 -0
- package/dist/timestamp/verify.d.ts +33 -0
- package/dist/timestamp/verify.js +74 -0
- package/dist/timestamp/x509.d.ts +35 -0
- package/dist/timestamp/x509.js +232 -0
- package/dist/transport/index.d.ts +1 -0
- package/dist/transport/index.js +2 -0
- package/dist/trust/delegation.d.ts +15 -0
- package/dist/trust/delegation.js +40 -0
- package/dist/trust/index.d.ts +15 -0
- package/dist/trust/index.js +3 -0
- package/dist/trust/revocation.d.ts +33 -0
- package/dist/trust/revocation.js +78 -0
- package/dist/trust/signers.d.ts +31 -0
- package/dist/trust/signers.js +166 -0
- package/dist/verify.d.ts +88 -0
- package/dist/verify.js +195 -0
- package/dist/wire.d.ts +6 -0
- package/dist/wire.js +38 -0
- package/package.json +89 -4
package/README.zh.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
# mistsign
|
|
4
|
+
|
|
5
|
+
**面向 Web 应用的电子签名、信任评估与多方合议**
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@tik-choco/mistsign)
|
|
8
|
+
[](https://github.com/tik-choco-lab/mistsign/releases/latest)
|
|
9
|
+
[](https://github.com/tik-choco-lab/mistsign/actions/workflows/ci.yml)
|
|
10
|
+
[](LICENSE)
|
|
11
|
+
|
|
12
|
+
[English](README.md) · [日本語](README.ja.md) · 简体中文
|
|
13
|
+
|
|
14
|
+
</div>
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
mistsign 是基于 Go CLI [tc-sign](https://github.com/tik-choco/tc-sign) 的浏览器端
|
|
19
|
+
TypeScript 库,为 Web 应用提供文件和数据的电子签名、签名验证、信任评估以及多方合议。
|
|
20
|
+
|
|
21
|
+
本库接受与 [mistseed](https://www.npmjs.com/package/@tik-choco/mistseed) 兼容的
|
|
22
|
+
`DidSigner` 和 `DelegationV1` 类型,支持 Ed25519 `did:key` 和与 tc-sign 兼容的规范化 JSON。
|
|
23
|
+
|
|
24
|
+
## 特性
|
|
25
|
+
|
|
26
|
+
| | |
|
|
27
|
+
| --- | --- |
|
|
28
|
+
| **签名** | 创建和验证分离签名(`.tcsig` v1) |
|
|
29
|
+
| **信任** | 根据委托、撤销和允许签名者列表进行评估 |
|
|
30
|
+
| **时间戳** | 验证 RFC 3161 时间戳令牌 |
|
|
31
|
+
| **合议** | 创建提案、签署决定、打包证据,并按 M-of-N 等规则判定是否成立 |
|
|
32
|
+
| **传输** | 通过 mistlib 请求和收集签名(计划中) |
|
|
33
|
+
| **可移植 UI** | 不依赖框架的 Web Components 与可选的 Preact 集成(计划中) |
|
|
34
|
+
|
|
35
|
+
## 安装
|
|
36
|
+
|
|
37
|
+
`@tik-choco/mistsign` 0.1.0 已在 npm 上发布。
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
npm install @tik-choco/mistsign
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## 用法
|
|
44
|
+
|
|
45
|
+
分离签名采用 tc-sign 的 `.tcsig` v1 格式(`type: tc-sign:signature`)。
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { signFile, verify, type DidSigner } from '@tik-choco/mistsign'
|
|
49
|
+
|
|
50
|
+
async function signAndVerify(file: File, signer: DidSigner, expectedDid: string) {
|
|
51
|
+
const signature = await signFile(file, signer) // .tcsig bytes
|
|
52
|
+
const outcome = await verify({
|
|
53
|
+
signature,
|
|
54
|
+
content: file,
|
|
55
|
+
options: { expect: expectedDid },
|
|
56
|
+
})
|
|
57
|
+
return { signature, outcome }
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
宿主应用提供签名者(例如 mistseed 的 DidSigner),验证者通过独立的可信渠道获取
|
|
62
|
+
`expectedDid`。mistsign 不负责保存私钥。`signFile` 也支持 Blob、Uint8Array 和
|
|
63
|
+
ReadableStream<Uint8Array>,此时需显式传入 `{ name: 'report.pdf' }` 等文件名选项。
|
|
64
|
+
文件内容采用增量哈希计算。
|
|
65
|
+
|
|
66
|
+
`verify` 返回机器可读的 `status`(`verified`、`signer-unconfirmed`、`invalid` 或
|
|
67
|
+
`error`)、`exitCode`(0、2 或 1)和详细的 `result`(输入错误则返回 `diagnostic`)。
|
|
68
|
+
若未指定 `expect` 或允许签名者列表,即使签名有效,状态也是 `signer-unconfirmed`。
|
|
69
|
+
允许签名者列表、委托和撤销检查可通过 `@tik-choco/mistsign/trust` 使用。
|
|
70
|
+
|
|
71
|
+
支持提供 Web Crypto Ed25519 的浏览器和 Node.js 22 及以上版本。
|
|
72
|
+
|
|
73
|
+
要验证 RFC 3161 时间戳,请将 DER 编码的令牌通过 `options.timestamp` 传给 `verify`,
|
|
74
|
+
并通过 `options.tsaRoots` 提供时间戳机构(TSA)的受信任根证书。验证过程会检查 CMS 签名、
|
|
75
|
+
ESS 属性和 X.509 证书链,并以通过验证的 `genTime` 作为核查委托、撤销和允许签名者列表的时间依据。
|
|
76
|
+
如果令牌未能通过基于所提供信任根的验证,`verify` 会返回 `invalid`。默认情况下,省略令牌或信任根时,
|
|
77
|
+
`verify` 会使用签名者自行声明的签名时间。可设置 `requireTimestamp: true`,要求时间戳通过验证。
|
|
78
|
+
|
|
79
|
+
合议 API 支持创建 `mistsign:agreement` v1 提案,为接受、拒绝或撤回决定签名,将决定和相关证据
|
|
80
|
+
打包,再通过 `verifyAgreement` 判定是否满足提案的成立条件。详见 [合议规范](docs/AGREEMENT.md)。
|
|
81
|
+
|
|
82
|
+
## API
|
|
83
|
+
|
|
84
|
+
软件包入口
|
|
85
|
+
|
|
86
|
+
| 子路径 | 作用 |
|
|
87
|
+
| --- | --- |
|
|
88
|
+
| `.` | 签名、验证、Ed25519 `did:key` 和规范化 JSON |
|
|
89
|
+
| `./trust` | 委托、撤销和允许签名者列表 |
|
|
90
|
+
| `./agreement` | 提案、签署决定、证据打包和成立判定 |
|
|
91
|
+
| `./transport` | 签名请求与收集(计划中,仅预留入口) |
|
|
92
|
+
| `./timestamp` | RFC 3161 时间戳验证 |
|
|
93
|
+
| `./elements` | Web Components(计划中,仅预留入口) |
|
|
94
|
+
| `./preact` | 可选的 Preact UI 和 Hooks(计划中,仅预留入口) |
|
|
95
|
+
| `./testing` | 测试工具 |
|
|
96
|
+
| `./ui.css` | UI 样式(计划中,样式表为空) |
|
|
97
|
+
|
|
98
|
+
## 配置
|
|
99
|
+
|
|
100
|
+
核心功能不依赖 Web 框架。计划中的签名请求与收集功能将使用由宿主应用提供的
|
|
101
|
+
[mistlib](https://github.com/tik-choco-lab/mistlib) 节点。
|
|
102
|
+
|
|
103
|
+
## 从源码构建
|
|
104
|
+
|
|
105
|
+
```sh
|
|
106
|
+
npm ci
|
|
107
|
+
npm run typecheck
|
|
108
|
+
npm test
|
|
109
|
+
npm run build
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
仓库内置的共享测试向量无需检出 tc-sign 即可测试。要从相邻的
|
|
113
|
+
`../tc-sign` 仓库更新向量,请运行 `npm run vectors:sync`。
|
|
114
|
+
|
|
115
|
+
## 状态
|
|
116
|
+
|
|
117
|
+
仍在开发中。已实现分离签名的创建与验证、信任评估、RFC 3161 时间戳验证和合议。
|
|
118
|
+
传输与 UI 仍在计划中。
|
|
119
|
+
|
|
120
|
+
## 许可
|
|
121
|
+
|
|
122
|
+
[Mozilla Public License 2.0](LICENSE)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { JsonObject } from '../json.js';
|
|
2
|
+
import type { RevocationDocument } from '../trust/revocation.js';
|
|
3
|
+
import type { Attachments, Bundle, BundleInput, ContentAttachment, Decision, DecisionInput, ProofAttachment, Proposal, ProposalInput, TimestampAttachment } from './types.js';
|
|
4
|
+
type Evidence<T> = Map<string, T>;
|
|
5
|
+
export interface EvidenceSet {
|
|
6
|
+
decisions: Evidence<Decision>;
|
|
7
|
+
timestamps: Evidence<TimestampAttachment>;
|
|
8
|
+
contents: Evidence<ContentAttachment>;
|
|
9
|
+
proofs: Evidence<ProofAttachment>;
|
|
10
|
+
revocations: Evidence<JsonObject>;
|
|
11
|
+
}
|
|
12
|
+
/** All evidence keys are ASCII. Proposal/decision fields (including arrays) are never reordered. */
|
|
13
|
+
export declare function ordered<T>(map: Evidence<T>): [string, T][];
|
|
14
|
+
export declare function inspectBundle(input: BundleInput): Promise<{
|
|
15
|
+
proposal: Proposal;
|
|
16
|
+
agreementId: string;
|
|
17
|
+
evidence: EvidenceSet;
|
|
18
|
+
mismatches: Set<string>;
|
|
19
|
+
revocations: RevocationDocument[];
|
|
20
|
+
}>;
|
|
21
|
+
export declare function mergeBundles(inputs: readonly BundleInput[]): Promise<Bundle>;
|
|
22
|
+
export declare function createBundle(input: ProposalInput, decisions?: readonly DecisionInput[], attachments?: Attachments): Promise<Bundle>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { utf8 } from '../bytes.js';
|
|
2
|
+
import { canonicalJson } from '../json.js';
|
|
3
|
+
import { parseRevocation } from '../trust/revocation.js';
|
|
4
|
+
import { bindDecision, parseDecision, verifyDecisionSignature } from './decision.js';
|
|
5
|
+
import { AgreementError, check } from './errors.js';
|
|
6
|
+
import { parseProposal } from './proposal.js';
|
|
7
|
+
import { array, base64, contentId, digest, digestHex, fields, header, mediaType, namespaced, object } from './schema.js';
|
|
8
|
+
import { BUNDLE_LIMIT, PROPOSAL_LIMIT, readDocument } from './strict.js';
|
|
9
|
+
import { BUNDLE } from './types.js';
|
|
10
|
+
function emptySet() {
|
|
11
|
+
return { decisions: new Map(), timestamps: new Map(), contents: new Map(), proofs: new Map(), revocations: new Map() };
|
|
12
|
+
}
|
|
13
|
+
const limits = { decisions: 2048, timestamps: 2048, contents: 256, proofs: 256, revocations: 256 };
|
|
14
|
+
function add(map, key, value) {
|
|
15
|
+
if (map.has(key))
|
|
16
|
+
check(canonicalJson(map.get(key)) === canonicalJson(value), 'digest-collision');
|
|
17
|
+
else
|
|
18
|
+
map.set(key, value);
|
|
19
|
+
}
|
|
20
|
+
/** All evidence keys are ASCII. Proposal/decision fields (including arrays) are never reordered. */
|
|
21
|
+
export function ordered(map) {
|
|
22
|
+
return [...map].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
23
|
+
}
|
|
24
|
+
export async function inspectBundle(input) {
|
|
25
|
+
const wire = readDocument(input, BUNDLE_LIMIT);
|
|
26
|
+
header(wire, BUNDLE);
|
|
27
|
+
fields(wire, 'type v agreementId proposal decisions', 'contents timestamps revocations proofs');
|
|
28
|
+
object(wire.proposal);
|
|
29
|
+
const proposal = parseProposal(wire.proposal);
|
|
30
|
+
const agreementId = contentId(proposal);
|
|
31
|
+
check(wire.agreementId === agreementId, 'agreement-id-mismatch');
|
|
32
|
+
for (const [key, max] of Object.entries(limits))
|
|
33
|
+
if (key in wire)
|
|
34
|
+
array(wire[key], max);
|
|
35
|
+
const bundle = wire;
|
|
36
|
+
const evidence = emptySet();
|
|
37
|
+
for (const item of bundle.decisions) {
|
|
38
|
+
object(item);
|
|
39
|
+
const d = parseDecision(item);
|
|
40
|
+
bindDecision(proposal, agreementId, d);
|
|
41
|
+
add(evidence.decisions, contentId(d), d);
|
|
42
|
+
}
|
|
43
|
+
const mismatches = new Set();
|
|
44
|
+
for (const c of bundle.contents ?? []) {
|
|
45
|
+
fields(c, 'subjectId dataBase64');
|
|
46
|
+
const subject = proposal.subjects.find(s => s.id === c.subjectId);
|
|
47
|
+
check(subject, 'attachment-target-mismatch');
|
|
48
|
+
check(!evidence.contents.has(c.subjectId));
|
|
49
|
+
const data = base64(c.dataBase64);
|
|
50
|
+
if (data.length !== subject.size || digest(data) !== subject.sha256)
|
|
51
|
+
mismatches.add(subject.id);
|
|
52
|
+
evidence.contents.set(c.subjectId, c);
|
|
53
|
+
}
|
|
54
|
+
for (const t of bundle.timestamps ?? []) {
|
|
55
|
+
fields(t, 'decisionId tokenBase64');
|
|
56
|
+
check(evidence.decisions.has(t.decisionId), 'attachment-target-mismatch');
|
|
57
|
+
add(evidence.timestamps, t.decisionId + '/' + digest(base64(t.tokenBase64, 64 << 10)), t);
|
|
58
|
+
}
|
|
59
|
+
for (const p of bundle.proofs ?? []) {
|
|
60
|
+
fields(p, 'type v target mediaType sha256 dataBase64');
|
|
61
|
+
check(namespaced(p.type) && typeof p.v === 'number' && p.v > 0 && mediaType(p.mediaType) && digestHex(p.sha256));
|
|
62
|
+
fields(p.target, 'kind id');
|
|
63
|
+
check(p.target.kind === 'proposal' ? p.target.id === agreementId :
|
|
64
|
+
p.target.kind === 'decision' && evidence.decisions.has(p.target.id), 'attachment-target-mismatch');
|
|
65
|
+
check(digest(base64(p.dataBase64)) === p.sha256, 'content-mismatch');
|
|
66
|
+
add(evidence.proofs, contentId(p), p);
|
|
67
|
+
}
|
|
68
|
+
for (const r of bundle.revocations ?? []) {
|
|
69
|
+
object(r);
|
|
70
|
+
check(utf8.encode(canonicalJson(r)).length <= PROPOSAL_LIMIT, 'document-too-large');
|
|
71
|
+
if (Array.isArray(r.revoked))
|
|
72
|
+
array(r.revoked, 10000);
|
|
73
|
+
add(evidence.revocations, contentId(r), r);
|
|
74
|
+
}
|
|
75
|
+
const revocations = [];
|
|
76
|
+
for (const [, r] of ordered(evidence.revocations)) {
|
|
77
|
+
try {
|
|
78
|
+
revocations.push(await parseRevocation(canonicalJson(r)));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new AgreementError('invalid-revocation');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
for (const [id, d] of ordered(evidence.decisions))
|
|
85
|
+
await verifyDecisionSignature(d, id);
|
|
86
|
+
return { proposal, agreementId, evidence, mismatches, revocations };
|
|
87
|
+
}
|
|
88
|
+
export async function mergeBundles(inputs) {
|
|
89
|
+
check(inputs.length > 0);
|
|
90
|
+
const union = emptySet();
|
|
91
|
+
let proposal;
|
|
92
|
+
let agreementId = '';
|
|
93
|
+
let proposalBytes = '';
|
|
94
|
+
let size = 0;
|
|
95
|
+
function merge(target, source, max) {
|
|
96
|
+
for (const [id, value] of source) {
|
|
97
|
+
if (!target.has(id)) {
|
|
98
|
+
check(target.size < max, 'resource-limit');
|
|
99
|
+
size += utf8.encode(canonicalJson(value)).length;
|
|
100
|
+
check(size <= BUNDLE_LIMIT, 'document-too-large');
|
|
101
|
+
}
|
|
102
|
+
add(target, id, value);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const input of inputs) {
|
|
106
|
+
const b = await inspectBundle(input);
|
|
107
|
+
check(!b.mismatches.size, 'content-mismatch');
|
|
108
|
+
const canonical = canonicalJson(b.proposal);
|
|
109
|
+
if (!proposal) {
|
|
110
|
+
proposal = b.proposal;
|
|
111
|
+
agreementId = b.agreementId;
|
|
112
|
+
proposalBytes = canonical;
|
|
113
|
+
size = utf8.encode(canonical).length;
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
check(agreementId === b.agreementId, 'agreement-id-mismatch');
|
|
117
|
+
check(canonical === proposalBytes, 'digest-collision');
|
|
118
|
+
}
|
|
119
|
+
merge(union.decisions, b.evidence.decisions, limits.decisions);
|
|
120
|
+
merge(union.timestamps, b.evidence.timestamps, limits.timestamps);
|
|
121
|
+
merge(union.revocations, b.evidence.revocations, limits.revocations);
|
|
122
|
+
merge(union.contents, b.evidence.contents, limits.contents);
|
|
123
|
+
merge(union.proofs, b.evidence.proofs, limits.proofs);
|
|
124
|
+
}
|
|
125
|
+
const values = (m) => ordered(m).map(([, v]) => v);
|
|
126
|
+
const bundle = { type: BUNDLE, v: 1, agreementId, proposal: proposal,
|
|
127
|
+
decisions: values(union.decisions), contents: values(union.contents), proofs: values(union.proofs),
|
|
128
|
+
timestamps: values(union.timestamps), revocations: values(union.revocations) };
|
|
129
|
+
check(utf8.encode(canonicalJson(bundle)).length <= BUNDLE_LIMIT, 'document-too-large');
|
|
130
|
+
return bundle;
|
|
131
|
+
}
|
|
132
|
+
export async function createBundle(input, decisions = [], attachments = {}) {
|
|
133
|
+
const proposal = parseProposal(input);
|
|
134
|
+
array(decisions, limits.decisions);
|
|
135
|
+
const aux = readDocument(attachments, BUNDLE_LIMIT);
|
|
136
|
+
fields(aux, '', 'contents timestamps revocations proofs');
|
|
137
|
+
return mergeBundles([{ ...aux, type: BUNDLE, v: 1, agreementId: contentId(proposal), proposal,
|
|
138
|
+
decisions: decisions.map(parseDecision) }]);
|
|
139
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { DidSigner } from '../wire.js';
|
|
2
|
+
import type { Choice, Decision, DecisionInput, DecisionOptions, Proposal, ProposalInput } from './types.js';
|
|
3
|
+
export declare function parseDecision(input: DecisionInput): Decision;
|
|
4
|
+
export declare function bindDecision(proposal: Proposal, proposalId: string, d: Decision): void;
|
|
5
|
+
export declare function decisionId(input: DecisionInput): string;
|
|
6
|
+
export declare function verifyDecisionSignature(d: Decision, decisionId: string): Promise<void>;
|
|
7
|
+
export declare function signDecision(input: ProposalInput, decision: Choice, signer: DidSigner, options?: DecisionOptions): Promise<Decision>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { decodeEd25519Signature, utf8 } from '../bytes.js';
|
|
2
|
+
import { MistsignError } from '../errors.js';
|
|
3
|
+
import { formatTime, nowInstant } from '../time.js';
|
|
4
|
+
import { verifyDelegationAt } from '../trust/delegation.js';
|
|
5
|
+
import { signWire, verifyWire } from '../wire.js';
|
|
6
|
+
import { AgreementError, check } from './errors.js';
|
|
7
|
+
import { parseProposal } from './proposal.js';
|
|
8
|
+
import { contentId, did, extensions, fields, header, id, timestamp } from './schema.js';
|
|
9
|
+
import { DECISION_LIMIT, readDocument } from './strict.js';
|
|
10
|
+
import { DECISION } from './types.js';
|
|
11
|
+
export function parseDecision(input) {
|
|
12
|
+
const d = readDocument(input, DECISION_LIMIT);
|
|
13
|
+
header(d, DECISION);
|
|
14
|
+
check('signature' in d, 'missing-signature');
|
|
15
|
+
fields(d, 'type v agreementId party fromId decision signedAt signature', 'comment delegation extensions criticalExtensions');
|
|
16
|
+
check(id(d.agreementId) && (d.decision === 'accept' || d.decision === 'reject' || d.decision === 'withdraw'));
|
|
17
|
+
did(d.party);
|
|
18
|
+
did(d.fromId);
|
|
19
|
+
timestamp(d.signedAt);
|
|
20
|
+
check(decodeEd25519Signature(d.signature), 'signature-mismatch');
|
|
21
|
+
if ('comment' in d) {
|
|
22
|
+
check(typeof d.comment === 'string');
|
|
23
|
+
check(utf8.encode(d.comment).length <= 4096, 'resource-limit');
|
|
24
|
+
}
|
|
25
|
+
if ('delegation' in d) {
|
|
26
|
+
const g = d.delegation;
|
|
27
|
+
fields(g, 'v root leaf iat exp sig');
|
|
28
|
+
check(g.v === 1);
|
|
29
|
+
did(g.root);
|
|
30
|
+
did(g.leaf);
|
|
31
|
+
timestamp(g.iat);
|
|
32
|
+
timestamp(g.exp);
|
|
33
|
+
check(decodeEd25519Signature(g.sig));
|
|
34
|
+
}
|
|
35
|
+
extensions(d);
|
|
36
|
+
return d;
|
|
37
|
+
}
|
|
38
|
+
export function bindDecision(proposal, proposalId, d) {
|
|
39
|
+
check(d.agreementId === proposalId, 'decision-agreement-mismatch');
|
|
40
|
+
check(proposal.parties.some(p => p.did === d.party), 'party-unlisted');
|
|
41
|
+
check(d.delegation ? d.party === d.delegation.root && d.fromId === d.delegation.leaf : d.party === d.fromId, 'party-mismatch');
|
|
42
|
+
}
|
|
43
|
+
export function decisionId(input) { return contentId(parseDecision(input)); }
|
|
44
|
+
export async function verifyDecisionSignature(d, decisionId) {
|
|
45
|
+
check(globalThis.crypto?.subtle, 'crypto-error');
|
|
46
|
+
if (!await verifyWire({ ...d }))
|
|
47
|
+
throw new AgreementError('signature-mismatch', 'invalid', decisionId);
|
|
48
|
+
}
|
|
49
|
+
export async function signDecision(input, decision, signer, options = {}) {
|
|
50
|
+
const proposal = parseProposal(input);
|
|
51
|
+
const proposalId = contentId(proposal);
|
|
52
|
+
const { signedAt, ...optional } = options;
|
|
53
|
+
const fromId = signer.did;
|
|
54
|
+
check(signedAt === undefined || signedAt instanceof Date || Number.isSafeInteger(signedAt), 'invalid-time');
|
|
55
|
+
let at;
|
|
56
|
+
try {
|
|
57
|
+
at = nowInstant(signedAt);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
throw new AgreementError('invalid-time');
|
|
61
|
+
}
|
|
62
|
+
fields(optional, '', 'party comment delegation extensions criticalExtensions');
|
|
63
|
+
const d = parseDecision({ ...optional, type: DECISION, v: 1, agreementId: proposalId, decision, fromId,
|
|
64
|
+
party: 'party' in optional ? optional.party : optional.delegation?.root ?? fromId, signedAt: formatTime(at), signature: 'A'.repeat(86) });
|
|
65
|
+
bindDecision(proposal, proposalId, d);
|
|
66
|
+
if (proposal.expiresAt)
|
|
67
|
+
check(at <= timestamp(proposal.expiresAt), 'decision-after-deadline');
|
|
68
|
+
if (d.delegation)
|
|
69
|
+
check(await verifyDelegationAt(d.delegation, at, fromId), 'invalid-delegation');
|
|
70
|
+
try {
|
|
71
|
+
d.signature = await signWire({ ...d }, signer);
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
throw new AgreementError(err instanceof MistsignError && err.code === 'signature-mismatch' ? err.code : 'crypto-error');
|
|
75
|
+
}
|
|
76
|
+
return d;
|
|
77
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type AgreementCode = 'invalid-json' | 'invalid-utf8' | 'invalid-surrogate' | 'invalid-number' | 'duplicate-key' | 'document-too-large' | 'resource-limit' | 'unsupported-type' | 'unsupported-version' | 'unsupported-critical-extension' | 'invalid-format' | 'invalid-did' | 'invalid-time' | 'duplicate-party' | 'invalid-formation' | 'duplicate-subject' | 'invalid-reference' | 'agreement-id-mismatch' | 'decision-agreement-mismatch' | 'party-unlisted' | 'party-mismatch' | 'missing-signature' | 'signature-mismatch' | 'invalid-revocation' | 'attachment-target-mismatch' | 'content-mismatch' | 'digest-collision' | 'missing-content' | 'content-read-error' | 'expect-mismatch' | 'purpose-not-allowed' | 'invalid-signers' | 'invalid-policy' | 'crypto-error' | 'timestamp-unsupported' | 'timestamp-invalid' | 'timestamp-required' | 'timestamp-time-conflict' | 'future-signed-at' | 'invalid-delegation' | 'delegation-not-allowed' | 'revoked-without-timestamp' | 'revoked-at-or-after' | 'decision-after-deadline' | 'signer-root-required' | 'signer-type-mismatch' | 'signer-outside-period' | 'signer-unlisted' | 'extension-requirement-failed';
|
|
2
|
+
export type NoticeCode = 'conflicting-decisions' | 'self-declared-time' | 'identity-unchecked' | 'timestamp-late' | 'timestamp-token-rejected' | 'revocation-reported-by-other-root' | 'supersedes-unchecked' | 'unknown-noncritical-extension' | 'unverified-proof' | 'signer-period-self-declared';
|
|
3
|
+
export declare class AgreementError extends Error {
|
|
4
|
+
readonly code: AgreementCode;
|
|
5
|
+
readonly decisionId?: string | undefined;
|
|
6
|
+
readonly status: 'error' | 'invalid';
|
|
7
|
+
constructor(code: AgreementCode, status?: 'error' | 'invalid', decisionId?: string | undefined);
|
|
8
|
+
}
|
|
9
|
+
export declare function check(condition: unknown, code?: AgreementCode): asserts condition;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const operational = new Set(['document-too-large', 'resource-limit', 'unsupported-type',
|
|
2
|
+
'unsupported-version', 'unsupported-critical-extension', 'missing-content', 'content-read-error',
|
|
3
|
+
'invalid-signers', 'invalid-policy', 'crypto-error', 'timestamp-unsupported']);
|
|
4
|
+
export class AgreementError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
decisionId;
|
|
7
|
+
status;
|
|
8
|
+
constructor(code, status, decisionId) {
|
|
9
|
+
super(code);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.decisionId = decisionId;
|
|
12
|
+
this.name = 'AgreementError';
|
|
13
|
+
this.status = status ?? (operational.has(code) ? 'error' : 'invalid');
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function check(condition, code = 'invalid-format') {
|
|
17
|
+
if (!condition)
|
|
18
|
+
throw new AgreementError(code);
|
|
19
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { RevocationEvaluation } from '../trust/revocation.js';
|
|
2
|
+
import type { Policy } from './policy.js';
|
|
3
|
+
import type { Decision, DecisionResult, Proposal, TimestampAttachment } from './types.js';
|
|
4
|
+
export type Tokens = [string, TimestampAttachment][];
|
|
5
|
+
export declare function evaluateDecision(proposal: Proposal, decisionId: string, d: Decision, tokens: Tokens, p: Policy, revocations: RevocationEvaluation): Promise<DecisionResult>;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { CLOCK_SKEW, MS, parseTime } from '../time.js';
|
|
2
|
+
import { verifyDelegationAt } from '../trust/delegation.js';
|
|
3
|
+
import { matchSignerAt } from '../trust/signers.js';
|
|
4
|
+
import { AgreementError, check } from './errors.js';
|
|
5
|
+
import { base64 } from './schema.js';
|
|
6
|
+
import { DECISION } from './types.js';
|
|
7
|
+
async function evaluateTime(decisionId, d, tokens, p) {
|
|
8
|
+
const rejectedTokens = [];
|
|
9
|
+
if (!tokens.length || !p.roots.length) {
|
|
10
|
+
return { source: 'self-declared', at: d.signedAt, status: tokens.length ? 'unverified' : 'none', rejectedTokens };
|
|
11
|
+
}
|
|
12
|
+
const verify = p.opts.timestampVerifier;
|
|
13
|
+
check(verify, 'timestamp-unsupported');
|
|
14
|
+
const digest = Uint8Array.from(decisionId.slice(7).match(/../g), s => parseInt(s, 16));
|
|
15
|
+
let earliest;
|
|
16
|
+
for (const [key, t] of tokens) {
|
|
17
|
+
const tokenDigest = key.slice(key.indexOf('/') + 1);
|
|
18
|
+
// Infrastructure failures are distinct from an invalid CMS token.
|
|
19
|
+
const result = await verify(base64(t.tokenBase64), { digest: digest.slice(), roots: p.roots, now: p.nowMs });
|
|
20
|
+
check(result?.status === 'verified' || result?.status === 'unverified', 'crypto-error');
|
|
21
|
+
if (result.status === 'verified') {
|
|
22
|
+
const at = result.genTime;
|
|
23
|
+
check(typeof at === 'string' && !at.startsWith('0000') &&
|
|
24
|
+
/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(at), 'crypto-error');
|
|
25
|
+
let time;
|
|
26
|
+
try {
|
|
27
|
+
time = parseTime(at);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new AgreementError('crypto-error');
|
|
31
|
+
}
|
|
32
|
+
if (time <= p.now + CLOCK_SKEW) {
|
|
33
|
+
if (!earliest || time < earliest.time)
|
|
34
|
+
earliest = { time, at, tokenDigest };
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
rejectedTokens.push(tokenDigest);
|
|
39
|
+
}
|
|
40
|
+
return earliest ? { source: 'timestamp', status: 'verified', at: earliest.at, tokenDigest: earliest.tokenDigest, rejectedTokens }
|
|
41
|
+
: { source: 'none', status: 'invalid', rejectedTokens };
|
|
42
|
+
}
|
|
43
|
+
export async function evaluateDecision(proposal, decisionId, d, tokens, p, revocations) {
|
|
44
|
+
const time = await evaluateTime(decisionId, d, tokens, p);
|
|
45
|
+
const at = time.at === undefined ? undefined : parseTime(time.at);
|
|
46
|
+
const signed = parseTime(d.signedAt);
|
|
47
|
+
const reasons = new Set();
|
|
48
|
+
const notices = new Set();
|
|
49
|
+
if (time.rejectedTokens.length)
|
|
50
|
+
notices.add('timestamp-token-rejected');
|
|
51
|
+
if (time.source === 'self-declared')
|
|
52
|
+
notices.add('self-declared-time');
|
|
53
|
+
if (signed > p.now + CLOCK_SKEW)
|
|
54
|
+
reasons.add('future-signed-at');
|
|
55
|
+
if (time.status === 'invalid')
|
|
56
|
+
reasons.add('timestamp-invalid');
|
|
57
|
+
if (time.source === 'timestamp' && at !== undefined) {
|
|
58
|
+
if (signed > at + CLOCK_SKEW)
|
|
59
|
+
reasons.add('timestamp-time-conflict');
|
|
60
|
+
if (at - signed >= 3600000n * MS)
|
|
61
|
+
notices.add('timestamp-late');
|
|
62
|
+
}
|
|
63
|
+
else if (proposal.timePolicy === 'timestamp-required' || p.opts.requireTimestamp)
|
|
64
|
+
reasons.add('timestamp-required');
|
|
65
|
+
const g = d.delegation;
|
|
66
|
+
let delegation;
|
|
67
|
+
if (g) {
|
|
68
|
+
delegation = { root: g.root };
|
|
69
|
+
if (at !== undefined) {
|
|
70
|
+
delegation.valid = await verifyDelegationAt(g, at, d.fromId);
|
|
71
|
+
if (!delegation.valid)
|
|
72
|
+
reasons.add('invalid-delegation');
|
|
73
|
+
}
|
|
74
|
+
if (p.opts.directOnly)
|
|
75
|
+
reasons.add('delegation-not-allowed');
|
|
76
|
+
}
|
|
77
|
+
const revocation = revocations.revocation && { ...revocations.revocation };
|
|
78
|
+
if (revocation) {
|
|
79
|
+
revocation.beforeRevocation = time.source === 'timestamp' && at !== undefined && at < parseTime(revocation.revokedAt);
|
|
80
|
+
if (!revocation.beforeRevocation)
|
|
81
|
+
reasons.add(time.source === 'timestamp' ? 'revoked-at-or-after' : 'revoked-without-timestamp');
|
|
82
|
+
}
|
|
83
|
+
if (revocations.revocationNotices.length)
|
|
84
|
+
notices.add('revocation-reported-by-other-root');
|
|
85
|
+
if (proposal.expiresAt) {
|
|
86
|
+
const end = parseTime(proposal.expiresAt);
|
|
87
|
+
if (signed > end || (at !== undefined && at > end))
|
|
88
|
+
reasons.add('decision-after-deadline');
|
|
89
|
+
}
|
|
90
|
+
const identity = { checked: false };
|
|
91
|
+
if (p.signers && at !== undefined && (!g || delegation?.valid)) {
|
|
92
|
+
// Empty leaf for delegated votes prevents a leaf-only row authenticating the party.
|
|
93
|
+
const match = matchSignerAt(p.signers, g ? '' : d.party, d.party, DECISION, '', at);
|
|
94
|
+
if (match.matched) {
|
|
95
|
+
identity.checked = true;
|
|
96
|
+
identity.name = match.matched.name;
|
|
97
|
+
if (match.periodChecked && time.source === 'self-declared')
|
|
98
|
+
notices.add('signer-period-self-declared');
|
|
99
|
+
}
|
|
100
|
+
else
|
|
101
|
+
for (const code of match.reasons)
|
|
102
|
+
if (code !== 'signer-name-mismatch')
|
|
103
|
+
reasons.add(code);
|
|
104
|
+
}
|
|
105
|
+
if (!identity.checked)
|
|
106
|
+
notices.add('identity-unchecked');
|
|
107
|
+
if (Object.keys(d.extensions ?? {}).length)
|
|
108
|
+
notices.add('unknown-noncritical-extension');
|
|
109
|
+
return { decisionId, decision: d.decision, party: d.party, fromId: d.fromId, signatureValid: true,
|
|
110
|
+
eligible: !reasons.size, identity, time, ...(delegation && { delegation }), ...(revocation && { revocation }),
|
|
111
|
+
revocationNotices: revocations.revocationNotices, exclusions: [...reasons].sort(), notices: [...notices].sort() };
|
|
112
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from './types.js';
|
|
2
|
+
export { AgreementError } from './errors.js';
|
|
3
|
+
export type { AgreementCode, NoticeCode } from './errors.js';
|
|
4
|
+
export type { DidSigner } from '../wire.js';
|
|
5
|
+
export type { DelegationV1 } from '../trust/delegation.js';
|
|
6
|
+
export { agreementId, createProposal, parseProposal } from './proposal.js';
|
|
7
|
+
export { decisionId, parseDecision, signDecision } from './decision.js';
|
|
8
|
+
export { createBundle, mergeBundles } from './bundle.js';
|
|
9
|
+
export { verifyAgreement, verifyDecision } from './verify.js';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export * from './types.js';
|
|
2
|
+
export { AgreementError } from './errors.js';
|
|
3
|
+
export { agreementId, createProposal, parseProposal } from './proposal.js';
|
|
4
|
+
export { decisionId, parseDecision, signDecision } from './decision.js';
|
|
5
|
+
export { createBundle, mergeBundles } from './bundle.js';
|
|
6
|
+
export { verifyAgreement, verifyDecision } from './verify.js';
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { JsonInput } from '../json.js';
|
|
2
|
+
import type { AgreementOptions, Proposal } from './types.js';
|
|
3
|
+
/** Local inputs never come from the bundle. Snapshot policy before the first await. */
|
|
4
|
+
export declare function preparePolicy(options: AgreementOptions): {
|
|
5
|
+
opts: {
|
|
6
|
+
now?: import("../time.js").TimeInput;
|
|
7
|
+
expectedAgreementId?: string;
|
|
8
|
+
previousProposals?: Readonly<Record<string, import("./types.js").ProposalInput>>;
|
|
9
|
+
expectedParties?: readonly Pick<import("./types.js").Party, "did" | "role">[];
|
|
10
|
+
allowedPurposes?: readonly string[];
|
|
11
|
+
requireTimestamp?: boolean;
|
|
12
|
+
timestampVerifier?: import("./types.js").TimestampVerifier | null;
|
|
13
|
+
tsaRoots?: readonly JsonInput[];
|
|
14
|
+
signers?: JsonInput;
|
|
15
|
+
revocations?: readonly JsonInput[];
|
|
16
|
+
directOnly?: boolean;
|
|
17
|
+
requireContent?: boolean;
|
|
18
|
+
contents?: Readonly<Record<string, import("../content.js").FileInput>>;
|
|
19
|
+
};
|
|
20
|
+
now: bigint;
|
|
21
|
+
nowMs: number;
|
|
22
|
+
roots: JsonInput[];
|
|
23
|
+
signers: import("../trust/signers.js").AllowedSigner[] | undefined;
|
|
24
|
+
contents: Map<string, import("../content.js").FileInput>;
|
|
25
|
+
revocations: JsonInput[];
|
|
26
|
+
previous: Map<string, Proposal>;
|
|
27
|
+
};
|
|
28
|
+
export type Policy = ReturnType<typeof preparePolicy>;
|
|
29
|
+
export declare function checkedHistory(proposal: Proposal, agreementId: string, previous: ReadonlyMap<string, Proposal>): boolean;
|
|
30
|
+
export declare function localRevocations(policy: Policy): Promise<import("../trust/revocation.js").RevocationDocument[]>;
|
|
31
|
+
export declare function checkExpectations(proposal: Proposal, agreementId: string, p: Policy): void;
|