@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.
Files changed (86) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +125 -0
  3. package/README.md +129 -2
  4. package/README.zh.md +122 -0
  5. package/dist/agreement/bundle.d.ts +23 -0
  6. package/dist/agreement/bundle.js +139 -0
  7. package/dist/agreement/decision.d.ts +7 -0
  8. package/dist/agreement/decision.js +77 -0
  9. package/dist/agreement/errors.d.ts +9 -0
  10. package/dist/agreement/errors.js +19 -0
  11. package/dist/agreement/evaluate.d.ts +5 -0
  12. package/dist/agreement/evaluate.js +112 -0
  13. package/dist/agreement/index.d.ts +9 -0
  14. package/dist/agreement/index.js +6 -0
  15. package/dist/agreement/policy.d.ts +31 -0
  16. package/dist/agreement/policy.js +113 -0
  17. package/dist/agreement/proposal.d.ts +4 -0
  18. package/dist/agreement/proposal.js +107 -0
  19. package/dist/agreement/schema.d.ts +16 -0
  20. package/dist/agreement/schema.js +93 -0
  21. package/dist/agreement/strict.d.ts +5 -0
  22. package/dist/agreement/strict.js +167 -0
  23. package/dist/agreement/types.d.ts +214 -0
  24. package/dist/agreement/types.js +3 -0
  25. package/dist/agreement/verify.d.ts +4 -0
  26. package/dist/agreement/verify.js +151 -0
  27. package/dist/bytes.d.ts +6 -0
  28. package/dist/bytes.js +19 -0
  29. package/dist/content.d.ts +10 -0
  30. package/dist/content.js +58 -0
  31. package/dist/didKey.d.ts +4 -0
  32. package/dist/didKey.js +48 -0
  33. package/dist/elements/index.d.ts +1 -0
  34. package/dist/elements/index.js +2 -0
  35. package/dist/errors.d.ts +7 -0
  36. package/dist/errors.js +8 -0
  37. package/dist/index.d.ts +13 -0
  38. package/dist/index.js +6 -0
  39. package/dist/json.d.ts +20 -0
  40. package/dist/json.js +170 -0
  41. package/dist/preact/index.d.ts +1 -0
  42. package/dist/preact/index.js +2 -0
  43. package/dist/preact/ui.css +0 -0
  44. package/dist/sha256.d.ts +11 -0
  45. package/dist/sha256.js +103 -0
  46. package/dist/sign.d.ts +33 -0
  47. package/dist/sign.js +61 -0
  48. package/dist/testing/index.d.ts +5 -0
  49. package/dist/testing/index.js +27 -0
  50. package/dist/time.d.ts +9 -0
  51. package/dist/time.js +36 -0
  52. package/dist/timestamp/asnTime.d.ts +2 -0
  53. package/dist/timestamp/asnTime.js +17 -0
  54. package/dist/timestamp/cms.d.ts +30 -0
  55. package/dist/timestamp/cms.js +126 -0
  56. package/dist/timestamp/constraints.d.ts +17 -0
  57. package/dist/timestamp/constraints.js +159 -0
  58. package/dist/timestamp/crypto.d.ts +6 -0
  59. package/dist/timestamp/crypto.js +101 -0
  60. package/dist/timestamp/der.d.ts +24 -0
  61. package/dist/timestamp/der.js +118 -0
  62. package/dist/timestamp/index.d.ts +2 -0
  63. package/dist/timestamp/index.js +1 -0
  64. package/dist/timestamp/name.d.ts +2 -0
  65. package/dist/timestamp/name.js +55 -0
  66. package/dist/timestamp/policy.d.ts +9 -0
  67. package/dist/timestamp/policy.js +56 -0
  68. package/dist/timestamp/verify.d.ts +33 -0
  69. package/dist/timestamp/verify.js +74 -0
  70. package/dist/timestamp/x509.d.ts +35 -0
  71. package/dist/timestamp/x509.js +232 -0
  72. package/dist/transport/index.d.ts +1 -0
  73. package/dist/transport/index.js +2 -0
  74. package/dist/trust/delegation.d.ts +15 -0
  75. package/dist/trust/delegation.js +40 -0
  76. package/dist/trust/index.d.ts +15 -0
  77. package/dist/trust/index.js +3 -0
  78. package/dist/trust/revocation.d.ts +33 -0
  79. package/dist/trust/revocation.js +78 -0
  80. package/dist/trust/signers.d.ts +31 -0
  81. package/dist/trust/signers.js +166 -0
  82. package/dist/verify.d.ts +88 -0
  83. package/dist/verify.js +195 -0
  84. package/dist/wire.d.ts +6 -0
  85. package/dist/wire.js +38 -0
  86. package/package.json +89 -4
@@ -0,0 +1,214 @@
1
+ import type { FileInput } from '../content.js';
2
+ import type { JsonInput, JsonObject, JsonValue } from '../json.js';
3
+ import type { TimeInput } from '../time.js';
4
+ import type { DelegationV1 } from '../trust/delegation.js';
5
+ import type { RevocationEvaluation } from '../trust/revocation.js';
6
+ import type { AgreementCode, NoticeCode } from './errors.js';
7
+ export declare const PROPOSAL = "mistsign:agreement";
8
+ export declare const DECISION = "mistsign:agreement-decision";
9
+ export declare const BUNDLE = "mistsign:agreement-bundle";
10
+ export interface Extensions {
11
+ extensions?: Record<string, {
12
+ v: number;
13
+ data: JsonValue;
14
+ }>;
15
+ criticalExtensions?: string[];
16
+ }
17
+ export interface Subject {
18
+ id: string;
19
+ sha256: string;
20
+ size: number;
21
+ mediaType: string;
22
+ name?: string;
23
+ inlineBase64?: string;
24
+ }
25
+ export interface Party {
26
+ did: string;
27
+ role: string;
28
+ displayName?: string;
29
+ }
30
+ export type Formation = {
31
+ mode: 'all';
32
+ } | {
33
+ mode: 'threshold';
34
+ minAccept: number;
35
+ } | {
36
+ mode: 'roles';
37
+ required: Record<string, number>;
38
+ };
39
+ export type Terms = {
40
+ mode: 'inline';
41
+ mediaType: 'text/plain' | 'text/markdown';
42
+ text: string;
43
+ } | {
44
+ mode: 'subject';
45
+ subjectId: string;
46
+ };
47
+ export interface Proposal extends Extensions {
48
+ type: typeof PROPOSAL;
49
+ v: 1;
50
+ nonce: string;
51
+ purpose: string;
52
+ createdAt: string;
53
+ expiresAt?: string;
54
+ proposer?: string;
55
+ subjects: Subject[];
56
+ terms: Terms;
57
+ parties: Party[];
58
+ formation: Formation;
59
+ timePolicy: 'self-declared-ok' | 'timestamp-required';
60
+ supersedes?: string;
61
+ }
62
+ export type ProposalFields = Omit<Proposal, 'type' | 'v' | 'nonce'>;
63
+ export type ProposalInput = Proposal | JsonInput;
64
+ export type Choice = 'accept' | 'reject' | 'withdraw';
65
+ export interface Decision extends Extensions {
66
+ type: typeof DECISION;
67
+ v: 1;
68
+ agreementId: string;
69
+ decision: Choice;
70
+ party: string;
71
+ fromId: string;
72
+ signedAt: string;
73
+ signature: string;
74
+ comment?: string;
75
+ delegation?: DelegationV1;
76
+ }
77
+ export interface DecisionOptions extends Extensions {
78
+ signedAt?: TimeInput;
79
+ party?: string;
80
+ comment?: string;
81
+ delegation?: DelegationV1;
82
+ }
83
+ export type DecisionInput = Decision | JsonInput;
84
+ export interface TimestampAttachment {
85
+ decisionId: string;
86
+ tokenBase64: string;
87
+ }
88
+ export interface ContentAttachment {
89
+ subjectId: string;
90
+ dataBase64: string;
91
+ }
92
+ export interface ProofAttachment {
93
+ type: string;
94
+ v: number;
95
+ target: {
96
+ kind: 'proposal' | 'decision';
97
+ id: string;
98
+ };
99
+ mediaType: string;
100
+ sha256: string;
101
+ dataBase64: string;
102
+ }
103
+ export interface Attachments {
104
+ timestamps?: TimestampAttachment[];
105
+ proofs?: ProofAttachment[];
106
+ contents?: ContentAttachment[];
107
+ revocations?: JsonObject[];
108
+ }
109
+ export interface Bundle extends Attachments {
110
+ type: typeof BUNDLE;
111
+ v: 1;
112
+ agreementId: string;
113
+ proposal: Proposal;
114
+ decisions: Decision[];
115
+ }
116
+ export type BundleInput = Bundle | JsonInput;
117
+ /** The /timestamp verifyTimestamp entry point satisfies this interface directly. */
118
+ export type TimestampVerifier = (token: Uint8Array, options: {
119
+ digest: Uint8Array;
120
+ roots: readonly JsonInput[];
121
+ now: number;
122
+ }) => Promise<{
123
+ status: 'verified';
124
+ genTime: string;
125
+ } | {
126
+ status: 'unverified';
127
+ reason: string;
128
+ }>;
129
+ export interface AgreementOptions {
130
+ now?: TimeInput;
131
+ expectedAgreementId?: string;
132
+ /** Locally available revision history, indexed by the expected proposal ID. */
133
+ previousProposals?: Readonly<Record<string, ProposalInput>>;
134
+ expectedParties?: readonly Pick<Party, 'did' | 'role'>[];
135
+ allowedPurposes?: readonly string[];
136
+ requireTimestamp?: boolean;
137
+ /** Defaults to the built-in RFC 3161 verifier. null denotes unavailable capability. */
138
+ timestampVerifier?: TimestampVerifier | null;
139
+ tsaRoots?: readonly JsonInput[];
140
+ signers?: JsonInput;
141
+ revocations?: readonly JsonInput[];
142
+ directOnly?: boolean;
143
+ requireContent?: boolean;
144
+ contents?: Readonly<Record<string, FileInput>>;
145
+ }
146
+ export interface ContentResult {
147
+ subjectId: string;
148
+ status: 'verified' | 'missing' | 'mismatch';
149
+ }
150
+ export interface DecisionTime {
151
+ source: 'self-declared' | 'timestamp' | 'none';
152
+ status: 'none' | 'unverified' | 'invalid' | 'verified';
153
+ at?: string;
154
+ tokenDigest?: string;
155
+ rejectedTokens: string[];
156
+ }
157
+ export interface DecisionResult extends RevocationEvaluation {
158
+ decisionId: string;
159
+ decision: Choice;
160
+ party: string;
161
+ fromId: string;
162
+ signatureValid: true;
163
+ eligible: boolean;
164
+ time: DecisionTime;
165
+ delegation?: {
166
+ valid?: boolean;
167
+ root: string;
168
+ };
169
+ identity: {
170
+ checked: boolean;
171
+ name?: string;
172
+ };
173
+ exclusions: AgreementCode[];
174
+ notices: NoticeCode[];
175
+ }
176
+ export interface Counts {
177
+ total: number;
178
+ accepted: number;
179
+ negative: number;
180
+ unanswered: number;
181
+ }
182
+ export interface PartyResult {
183
+ did: string;
184
+ role: string;
185
+ vote: 'accepted' | 'negative' | 'unanswered';
186
+ decisionIds: string[];
187
+ negatives: ('reject' | 'withdraw')[];
188
+ conflict: boolean;
189
+ }
190
+ export interface EvaluatedAgreement {
191
+ status: 'formed' | 'pending' | 'rejected' | 'expired';
192
+ agreementId: string;
193
+ evaluatedAt: string;
194
+ deadlinePassed: boolean;
195
+ counts: Counts;
196
+ roleCounts: Record<string, Counts>;
197
+ parties: PartyResult[];
198
+ decisions: DecisionResult[];
199
+ contents: ContentResult[];
200
+ contentStatus: 'missing' | 'verified';
201
+ missingRequirements: number | Record<string, number>;
202
+ timeAssurance: 'none' | 'self-declared' | 'timestamp' | 'mixed';
203
+ identityAssurance: 'none' | 'checked' | 'unchecked' | 'mixed';
204
+ errors: AgreementCode[];
205
+ notices: NoticeCode[];
206
+ }
207
+ export interface AgreementFailure {
208
+ status: 'invalid' | 'error';
209
+ errors: AgreementCode[];
210
+ decisionId?: string;
211
+ contents?: ContentResult[];
212
+ contentStatus?: ContentResult['status'];
213
+ }
214
+ export type AgreementResult = EvaluatedAgreement | AgreementFailure;
@@ -0,0 +1,3 @@
1
+ export const PROPOSAL = 'mistsign:agreement';
2
+ export const DECISION = 'mistsign:agreement-decision';
3
+ export const BUNDLE = 'mistsign:agreement-bundle';
@@ -0,0 +1,4 @@
1
+ import type { AgreementOptions, AgreementResult, Attachments, BundleInput, DecisionInput, DecisionResult, ProposalInput } from './types.js';
2
+ export declare function verifyAgreement(input: BundleInput, options?: AgreementOptions): Promise<AgreementResult>;
3
+ /** Return the individual eligibility report. Fatal bundle/policy errors throw AgreementError. */
4
+ export declare function verifyDecision(input: ProposalInput, decision: DecisionInput, options?: AgreementOptions, attachments?: Attachments): Promise<DecisionResult>;
@@ -0,0 +1,151 @@
1
+ import { hashContent } from '../content.js';
2
+ import { MistsignError } from '../errors.js';
3
+ import { canonicalJson } from '../json.js';
4
+ import { formatTime, parseTime } from '../time.js';
5
+ import { evaluateRevocations } from '../trust/revocation.js';
6
+ import { inspectBundle, ordered } from './bundle.js';
7
+ import { parseDecision } from './decision.js';
8
+ import { AgreementError, check } from './errors.js';
9
+ import { evaluateDecision } from './evaluate.js';
10
+ import { checkedHistory, checkExpectations, localRevocations, preparePolicy } from './policy.js';
11
+ import { parseProposal } from './proposal.js';
12
+ import { contentId } from './schema.js';
13
+ import { BUNDLE } from './types.js';
14
+ async function inspectContents(b, p) {
15
+ const contents = [];
16
+ for (const s of b.proposal.subjects) {
17
+ let present = s.inlineBase64 !== undefined || b.evidence.contents.has(s.id);
18
+ let mismatch = b.mismatches.has(s.id);
19
+ if (p.contents.has(s.id)) {
20
+ present = true;
21
+ try {
22
+ const h = await hashContent(p.contents.get(s.id), s.size);
23
+ mismatch ||= h.size !== s.size || h.sha256 !== s.sha256;
24
+ }
25
+ catch {
26
+ throw new AgreementError('content-read-error');
27
+ }
28
+ }
29
+ contents.push({ subjectId: s.id, status: mismatch ? 'mismatch' : present ? 'verified' : 'missing' });
30
+ }
31
+ return contents;
32
+ }
33
+ function tally(proposal, decisions) {
34
+ const counts = () => ({ total: 0, accepted: 0, negative: 0, unanswered: 0 });
35
+ const total = counts();
36
+ const roleCounts = Object.create(null);
37
+ const parties = proposal.parties.map(({ did, role }) => {
38
+ const eligible = decisions.filter(d => d.party === did && d.eligible);
39
+ const choices = new Set(eligible.map(d => d.decision));
40
+ const negatives = ['reject', 'withdraw'].filter(choice => choices.has(choice));
41
+ const vote = negatives.length ? 'negative' : choices.has('accept') ? 'accepted' : 'unanswered';
42
+ const roleCount = roleCounts[role] ??= counts();
43
+ roleCount.total++;
44
+ roleCount[vote]++;
45
+ total.total++;
46
+ total[vote]++;
47
+ return { did, role, vote, decisionIds: eligible.map(d => d.decisionId), negatives,
48
+ conflict: choices.has('accept') && negatives.length > 0 };
49
+ });
50
+ const f = proposal.formation;
51
+ let missingRequirements;
52
+ let satisfied = true, possible = true;
53
+ function shortfall(min, c) {
54
+ satisfied &&= c.accepted >= min;
55
+ possible &&= c.accepted + c.unanswered >= min;
56
+ return Math.max(0, min - c.accepted);
57
+ }
58
+ if (f.mode === 'roles') {
59
+ missingRequirements = Object.fromEntries(Object.entries(f.required).map(([r, n]) => [r, shortfall(n, roleCounts[r])]));
60
+ }
61
+ else
62
+ missingRequirements = shortfall(f.mode === 'all' ? total.total : f.minAccept, total);
63
+ return { counts: total, roleCounts, parties, missingRequirements, satisfied, possible };
64
+ }
65
+ function assurance(values, yes, no) {
66
+ if (!values.length)
67
+ return 'none';
68
+ if (values.every(Boolean))
69
+ return yes;
70
+ return values.some(Boolean) ? 'mixed' : no;
71
+ }
72
+ function indexRevocations(docs) {
73
+ // The same signed evidence may arrive through both channels. Stable traversal
74
+ // also fixes the displayed reason when two issuances report the same instant.
75
+ const byLeaf = new Map();
76
+ for (const [, doc] of ordered(new Map(docs.map(r => [canonicalJson(r), r])))) {
77
+ for (const entry of doc.revoked) {
78
+ const rows = byLeaf.get(entry.leaf) ?? [];
79
+ rows.push({ issuer: doc.issuer, issuedAt: doc.issuedAt, revoked: [entry] });
80
+ byLeaf.set(entry.leaf, rows);
81
+ }
82
+ }
83
+ return byLeaf;
84
+ }
85
+ export async function verifyAgreement(input, options = {}) {
86
+ try {
87
+ const p = preparePolicy(options);
88
+ const b = await inspectBundle(input);
89
+ const byLeaf = indexRevocations([...b.revocations, ...await localRevocations(p)]);
90
+ const { proposal, agreementId, evidence } = b;
91
+ checkExpectations(proposal, agreementId, p);
92
+ if (proposal.timePolicy === 'timestamp-required' || p.opts.requireTimestamp || (p.roots.length && evidence.timestamps.size)) {
93
+ check(p.opts.timestampVerifier, 'timestamp-unsupported');
94
+ }
95
+ const contents = await inspectContents(b, p);
96
+ if (contents.some(c => c.status === 'mismatch')) {
97
+ return { status: 'invalid', errors: ['content-mismatch'], contentStatus: 'mismatch', contents };
98
+ }
99
+ const contentStatus = contents.some(c => c.status === 'missing') ? 'missing' : 'verified';
100
+ if (contentStatus === 'missing' && p.opts.requireContent)
101
+ return { status: 'error', errors: ['missing-content'], contentStatus, contents };
102
+ const tokens = new Map();
103
+ for (const entry of ordered(evidence.timestamps)) {
104
+ const id = entry[1].decisionId;
105
+ const list = tokens.get(id) ?? [];
106
+ list.push(entry);
107
+ tokens.set(id, list);
108
+ }
109
+ const decisions = [];
110
+ const notices = new Set();
111
+ for (const [id, d] of ordered(evidence.decisions)) {
112
+ const rev = evaluateRevocations(byLeaf.get(d.fromId) ?? [], d.delegation?.root ?? '', d.fromId);
113
+ const result = await evaluateDecision(proposal, id, d, tokens.get(id) ?? [], p, rev);
114
+ decisions.push(result);
115
+ for (const n of result.notices)
116
+ notices.add(n);
117
+ }
118
+ const eligible = decisions.filter(d => d.eligible);
119
+ const { possible, satisfied, ...votes } = tally(proposal, decisions);
120
+ const deadlinePassed = !!proposal.expiresAt && p.now > parseTime(proposal.expiresAt);
121
+ if (!checkedHistory(proposal, agreementId, p.previous))
122
+ notices.add('supersedes-unchecked');
123
+ if (Object.keys(proposal.extensions ?? {}).length)
124
+ notices.add('unknown-noncritical-extension');
125
+ if (evidence.proofs.size)
126
+ notices.add('unverified-proof');
127
+ if (votes.parties.some(party => party.conflict))
128
+ notices.add('conflicting-decisions');
129
+ return { status: satisfied ? 'formed' : !possible ? 'rejected' : deadlinePassed ? 'expired' : 'pending',
130
+ agreementId, evaluatedAt: formatTime(p.now), deadlinePassed, ...votes, decisions, contents, contentStatus,
131
+ timeAssurance: assurance(eligible.map(d => d.time.source === 'timestamp'), 'timestamp', 'self-declared'),
132
+ identityAssurance: assurance(eligible.map(d => d.identity.checked), 'checked', 'unchecked'),
133
+ errors: [], notices: [...notices].sort() };
134
+ }
135
+ catch (err) {
136
+ if (err instanceof AgreementError)
137
+ return { status: err.status, errors: [err.code], ...(err.decisionId && { decisionId: err.decisionId }) };
138
+ if (err instanceof MistsignError && err.code === 'invalid-signers')
139
+ return { status: 'error', errors: [err.code] };
140
+ return { status: 'error', errors: ['crypto-error'] };
141
+ }
142
+ }
143
+ /** Return the individual eligibility report. Fatal bundle/policy errors throw AgreementError. */
144
+ export async function verifyDecision(input, decision, options, attachments) {
145
+ const proposal = parseProposal(input);
146
+ const result = await verifyAgreement({ ...attachments, type: BUNDLE, v: 1, agreementId: contentId(proposal),
147
+ proposal, decisions: [parseDecision(decision)] }, options);
148
+ if (!('decisions' in result))
149
+ throw new AgreementError(result.errors[0], result.status, result.decisionId);
150
+ return result.decisions[0];
151
+ }
@@ -0,0 +1,6 @@
1
+ export declare const utf8: TextEncoder;
2
+ export declare function hex(bytes: Uint8Array): string;
3
+ export declare function base64url(bytes: Uint8Array): string;
4
+ /** Strict raw Base64URL, including canonical trailing bits, for Ed25519. */
5
+ export declare function decodeEd25519Signature(value: unknown): Uint8Array | undefined;
6
+ export declare function sha256(bytes: Uint8Array): Promise<Uint8Array>;
package/dist/bytes.js ADDED
@@ -0,0 +1,19 @@
1
+ export const utf8 = new TextEncoder();
2
+ export function hex(bytes) {
3
+ return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
4
+ }
5
+ export function base64url(bytes) {
6
+ return btoa(Array.from(bytes, b => String.fromCharCode(b)).join(''))
7
+ .replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
8
+ }
9
+ /** Strict raw Base64URL, including canonical trailing bits, for Ed25519. */
10
+ export function decodeEd25519Signature(value) {
11
+ if (typeof value !== 'string' || value.length !== 86 || !/^[A-Za-z0-9_-]+$/.test(value))
12
+ return;
13
+ const decoded = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/') + '=='), c => c.charCodeAt(0));
14
+ if (decoded.length === 64 && base64url(decoded) === value)
15
+ return decoded;
16
+ }
17
+ export async function sha256(bytes) {
18
+ return new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', new Uint8Array(bytes)));
19
+ }
@@ -0,0 +1,10 @@
1
+ export type FileInput = Blob | File | Uint8Array | ReadableStream<Uint8Array>;
2
+ export type ProgressCallback = (bytesRead: number) => void;
3
+ export interface FileHash {
4
+ size: number;
5
+ sha256: string;
6
+ }
7
+ /** A File supplies its own name; other inputs need an explicit name. */
8
+ export declare function inputName(input: FileInput | undefined): string | undefined;
9
+ export declare function basename(name: string): string;
10
+ export declare function hashContent(input: FileInput, maxSize?: number, progress?: ProgressCallback): Promise<FileHash>;
@@ -0,0 +1,58 @@
1
+ import { hex } from './bytes.js';
2
+ import { MistsignError } from './errors.js';
3
+ import { Sha256 } from './sha256.js';
4
+ /** A File supplies its own name; other inputs need an explicit name. */
5
+ export function inputName(input) {
6
+ if (input && 'name' in input && typeof input.name === 'string')
7
+ return input.name;
8
+ }
9
+ export function basename(name) {
10
+ return name.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || '';
11
+ }
12
+ export async function hashContent(input, maxSize = Number.MAX_SAFE_INTEGER, progress) {
13
+ const hash = new Sha256();
14
+ let size = 0;
15
+ const consume = (bytes) => {
16
+ if (!(bytes instanceof Uint8Array))
17
+ throw new MistsignError('content-read-error');
18
+ size += bytes.byteLength;
19
+ if (!Number.isSafeInteger(size))
20
+ throw new MistsignError('invalid-file-size');
21
+ if (bytes.byteLength)
22
+ progress?.(size);
23
+ if (size > maxSize)
24
+ return false;
25
+ hash.update(bytes);
26
+ return true;
27
+ };
28
+ if (input instanceof Uint8Array) {
29
+ if (!consume(input))
30
+ return { size, sha256: '' };
31
+ }
32
+ else {
33
+ const stream = 'stream' in input ? input.stream() : input;
34
+ const reader = stream.getReader();
35
+ let complete = false;
36
+ try {
37
+ while (true) {
38
+ const chunk = await reader.read();
39
+ if (chunk.done) {
40
+ complete = true;
41
+ break;
42
+ }
43
+ if (!consume(chunk.value))
44
+ return { size, sha256: '' };
45
+ }
46
+ }
47
+ finally {
48
+ try {
49
+ if (!complete)
50
+ await reader.cancel();
51
+ }
52
+ finally {
53
+ reader.releaseLock();
54
+ }
55
+ }
56
+ }
57
+ return { size, sha256: hex(hash.digest()) };
58
+ }
@@ -0,0 +1,4 @@
1
+ export declare function didKeyFromEd25519PublicKey(publicKey: Uint8Array): string;
2
+ /** Decode a canonical Ed25519 did:key, or throw invalid-did. */
3
+ export declare function ed25519PublicKeyFromDidKey(did: string): Uint8Array;
4
+ export declare function isEd25519DidKey(did: unknown): did is string;
package/dist/didKey.js ADDED
@@ -0,0 +1,48 @@
1
+ import { MistsignError } from './errors.js';
2
+ const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
3
+ const prefix = 'did:key:z';
4
+ export function didKeyFromEd25519PublicKey(publicKey) {
5
+ if (publicKey.length !== 32)
6
+ throw new MistsignError('invalid-did');
7
+ let n = 0xed01n;
8
+ for (const b of publicKey)
9
+ n = (n << 8n) | BigInt(b);
10
+ let encoded = '';
11
+ while (n > 0n) {
12
+ encoded = alphabet[Number(n % 58n)] + encoded;
13
+ n /= 58n;
14
+ }
15
+ return prefix + encoded;
16
+ }
17
+ /** Decode a canonical Ed25519 did:key, or throw invalid-did. */
18
+ export function ed25519PublicKeyFromDidKey(did) {
19
+ if (typeof did !== 'string' || did.length !== 56 || !did.startsWith(prefix)) {
20
+ throw new MistsignError('invalid-did');
21
+ }
22
+ let n = 0n;
23
+ for (const c of did.slice(prefix.length)) {
24
+ const digit = alphabet.indexOf(c);
25
+ if (digit < 0)
26
+ throw new MistsignError('invalid-did');
27
+ n = n * 58n + BigInt(digit);
28
+ }
29
+ const publicKey = new Uint8Array(32);
30
+ for (let i = 31; i >= 0; i--) {
31
+ publicKey[i] = Number(n & 255n);
32
+ n >>= 8n;
33
+ }
34
+ if (n !== 0xed01n || didKeyFromEd25519PublicKey(publicKey) !== did)
35
+ throw new MistsignError('invalid-did');
36
+ return publicKey;
37
+ }
38
+ export function isEd25519DidKey(did) {
39
+ try {
40
+ if (typeof did !== 'string')
41
+ return false;
42
+ ed25519PublicKeyFromDidKey(did);
43
+ return true;
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ // Framework-independent Web Components and their registration.
2
+ export {};
@@ -0,0 +1,7 @@
1
+ export type TimestampFailureCode = 'timestamp-unsupported' | 'timestamp-too-large' | 'timestamp-malformed' | 'timestamp-imprint' | 'timestamp-algorithm' | 'timestamp-attributes' | 'timestamp-signer' | 'timestamp-ess' | 'timestamp-eku' | 'timestamp-signature' | 'timestamp-future' | 'timestamp-chain' | 'timestamp-roots' | 'invalid-time';
2
+ /** Machine-readable error codes, independent of UI language. */
3
+ export type ErrorCode = 'invalid-json' | 'invalid-utf8' | 'invalid-surrogate' | 'invalid-number' | 'document-too-large' | 'invalid-did' | 'invalid-format' | 'missing-signature' | 'invalid-file-info' | 'invalid-file-size' | 'invalid-sha256' | 'invalid-time' | 'signature-mismatch' | 'file-mismatch' | 'future-signed-at' | 'invalid-delegation' | 'invalid-revocation' | 'invalid-signers' | 'signer-name-without-signers' | 'signer-name-mismatch' | 'signer-root-required' | 'signer-type-mismatch' | 'signer-outside-period' | 'signer-unlisted' | 'expect-mismatch' | 'revoked-without-timestamp' | 'timestamp-required' | TimestampFailureCode | 'timestamp-no-roots' | 'signed-at-after-timestamp' | 'revoked-at-timestamp' | 'missing-content' | 'content-read-error' | 'crypto-error';
4
+ export declare class MistsignError extends Error {
5
+ readonly code: ErrorCode;
6
+ constructor(code: ErrorCode, options?: ErrorOptions);
7
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,8 @@
1
+ export class MistsignError extends Error {
2
+ code;
3
+ constructor(code, options) {
4
+ super(code, options);
5
+ this.code = code;
6
+ this.name = 'MistsignError';
7
+ }
8
+ }
@@ -0,0 +1,13 @@
1
+ export { signFile, timestampDigest, SIGNATURE_TYPE } from './sign.js';
2
+ export type { SignOptions, SignatureV1, SignatureFileInfo } from './sign.js';
3
+ export { verify } from './verify.js';
4
+ export type { VerifyInput, VerifyOptions, VerifyOutcome, VerificationResult, VerificationStatus, ResultSigner, ResultIdentity, ResultTime, ResultTimestamp, ResultDelegation, NoticeCode } from './verify.js';
5
+ export { didKeyFromEd25519PublicKey, ed25519PublicKeyFromDidKey, isEd25519DidKey } from './didKey.js';
6
+ export { canonicalJson, parseStrictJson, prettyJson, MAX_SIGNATURE_SIZE } from './json.js';
7
+ export type { JsonValue, JsonObject, JsonInput, JsonMode } from './json.js';
8
+ export { signingPayload } from './wire.js';
9
+ export type { DidSigner } from './wire.js';
10
+ export type { FileInput, ProgressCallback } from './content.js';
11
+ export type { TimeInput } from './time.js';
12
+ export { MistsignError } from './errors.js';
13
+ export type { ErrorCode } from './errors.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { signFile, timestampDigest, SIGNATURE_TYPE } from './sign.js';
2
+ export { verify } from './verify.js';
3
+ export { didKeyFromEd25519PublicKey, ed25519PublicKeyFromDidKey, isEd25519DidKey } from './didKey.js';
4
+ export { canonicalJson, parseStrictJson, prettyJson, MAX_SIGNATURE_SIZE } from './json.js';
5
+ export { signingPayload } from './wire.js';
6
+ export { MistsignError } from './errors.js';
package/dist/json.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject;
2
+ export type JsonObject = {
3
+ [key: string]: JsonValue;
4
+ };
5
+ export type JsonInput = string | Uint8Array;
6
+ export type JsonMode = 'canonical' | 'signature';
7
+ export declare const MAX_SIGNATURE_SIZE: number;
8
+ export declare function assertScalarString(value: string): void;
9
+ /** Decode without replacing invalid UTF-8 or silently stripping a BOM. */
10
+ export declare function decodeText(input: JsonInput, limit?: number): string;
11
+ /**
12
+ * tc-sign JSON input rules, before JSON.parse can lose duplicate tokens or
13
+ * normalize number spellings. Duplicate keys are intentionally last-wins.
14
+ */
15
+ export declare function parseStrictJson(input: JsonInput, mode?: JsonMode): JsonValue;
16
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
17
+ /** Go stablejson-compatible canonical JSON (UTF-8 key order, finite binary64). */
18
+ export declare function canonicalJson(value: unknown): string;
19
+ /** Sorted JSON with two-space indentation and a final LF, as in Go PrettySignature. */
20
+ export declare function prettyJson(value: unknown): string;