@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
package/dist/json.js ADDED
@@ -0,0 +1,170 @@
1
+ import { MistsignError } from './errors.js';
2
+ export const MAX_SIGNATURE_SIZE = 1 << 20;
3
+ const encoder = new TextEncoder();
4
+ export function assertScalarString(value) {
5
+ for (let i = 0; i < value.length; i++) {
6
+ const c = value.charCodeAt(i);
7
+ if (c >= 0xd800 && c <= 0xdbff) {
8
+ const low = value.charCodeAt(++i);
9
+ if (!(low >= 0xdc00 && low <= 0xdfff))
10
+ throw new MistsignError('invalid-surrogate');
11
+ }
12
+ else if (c >= 0xdc00 && c <= 0xdfff) {
13
+ throw new MistsignError('invalid-surrogate');
14
+ }
15
+ }
16
+ }
17
+ /** Decode without replacing invalid UTF-8 or silently stripping a BOM. */
18
+ export function decodeText(input, limit) {
19
+ if (typeof input === 'string') {
20
+ if (limit !== undefined && (input.length > limit || encoder.encode(input).length > limit)) {
21
+ throw new MistsignError('document-too-large');
22
+ }
23
+ assertScalarString(input);
24
+ return input;
25
+ }
26
+ if (limit !== undefined && input.byteLength > limit)
27
+ throw new MistsignError('document-too-large');
28
+ try {
29
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(input);
30
+ }
31
+ catch (cause) {
32
+ throw new MistsignError('invalid-utf8', { cause });
33
+ }
34
+ }
35
+ /**
36
+ * tc-sign JSON input rules, before JSON.parse can lose duplicate tokens or
37
+ * normalize number spellings. Duplicate keys are intentionally last-wins.
38
+ */
39
+ export function parseStrictJson(input, mode = 'canonical') {
40
+ const source = decodeText(input, mode === 'signature' ? MAX_SIGNATURE_SIZE : undefined);
41
+ const numberToken = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
42
+ let inString = false;
43
+ let depth = 0;
44
+ const unicodeEscape = (position) => {
45
+ const hex = source.slice(position, position + 4);
46
+ if (!/^[0-9a-fA-F]{4}$/.test(hex))
47
+ throw new MistsignError('invalid-surrogate');
48
+ return Number.parseInt(hex, 16);
49
+ };
50
+ for (let i = 0; i < source.length; i++) {
51
+ const c = source[i];
52
+ if (c === '"') {
53
+ inString = !inString;
54
+ continue;
55
+ }
56
+ if (inString) {
57
+ if (c !== '\\')
58
+ continue;
59
+ if (source[++i] !== 'u')
60
+ continue;
61
+ const high = unicodeEscape(i + 1);
62
+ i += 4;
63
+ if (high >= 0xdc00 && high <= 0xdfff)
64
+ throw new MistsignError('invalid-surrogate');
65
+ if (high >= 0xd800 && high <= 0xdbff) {
66
+ if (source.slice(i + 1, i + 3) !== '\\u')
67
+ throw new MistsignError('invalid-surrogate');
68
+ const low = unicodeEscape(i + 3);
69
+ if (low < 0xdc00 || low > 0xdfff)
70
+ throw new MistsignError('invalid-surrogate');
71
+ i += 6;
72
+ }
73
+ continue;
74
+ }
75
+ if (c === '{' || c === '[') {
76
+ if (++depth > 10000)
77
+ throw new MistsignError('invalid-json');
78
+ }
79
+ else if (c === '}' || c === ']')
80
+ depth--;
81
+ if (c === '-' || (c >= '0' && c <= '9')) {
82
+ numberToken.lastIndex = i;
83
+ const token = numberToken.exec(source)?.[0];
84
+ if (!token)
85
+ throw new MistsignError('invalid-json');
86
+ const n = Number(token);
87
+ if (!Number.isFinite(n) || (mode === 'signature' && (/[.eE]/.test(token) || !Number.isSafeInteger(n)))) {
88
+ throw new MistsignError('invalid-number');
89
+ }
90
+ i += token.length - 1;
91
+ }
92
+ }
93
+ try {
94
+ return JSON.parse(source);
95
+ }
96
+ catch (cause) {
97
+ throw new MistsignError('invalid-json', { cause });
98
+ }
99
+ }
100
+ export function isObject(value) {
101
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
102
+ }
103
+ function compareBytes(a, b) {
104
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
105
+ if (a[i] !== b[i])
106
+ return a[i] - b[i];
107
+ }
108
+ return a.length - b.length;
109
+ }
110
+ /** Emit JSON directly: object enumeration would reorder integer-like keys. */
111
+ function stringify(value, pretty) {
112
+ const chunks = [];
113
+ const ancestors = new Set();
114
+ const stack = [{ value, depth: 0 }];
115
+ const whitespace = (depth) => pretty ? '\n' + ' '.repeat(depth) : '';
116
+ while (stack.length) {
117
+ const task = stack.pop();
118
+ if ('text' in task) {
119
+ chunks.push(task.text);
120
+ continue;
121
+ }
122
+ if ('end' in task) {
123
+ ancestors.delete(task.end);
124
+ continue;
125
+ }
126
+ const { value: v, depth } = task;
127
+ if (typeof v === 'string') {
128
+ assertScalarString(v);
129
+ chunks.push(JSON.stringify(v));
130
+ }
131
+ else if (v === null || typeof v === 'boolean') {
132
+ chunks.push(String(v));
133
+ }
134
+ else if (typeof v === 'number') {
135
+ if (!Number.isFinite(v))
136
+ throw new MistsignError('invalid-number');
137
+ chunks.push(JSON.stringify(v));
138
+ }
139
+ else if (typeof v === 'object') {
140
+ if (ancestors.has(v))
141
+ throw new MistsignError('invalid-json');
142
+ ancestors.add(v);
143
+ const array = Array.isArray(v);
144
+ if (!array && Object.getPrototypeOf(v) !== null && Object.getPrototypeOf(v) !== Object.prototype) {
145
+ throw new MistsignError('invalid-json');
146
+ }
147
+ const keys = array ? Array.from({ length: v.length }, (_, i) => String(i)) :
148
+ Object.keys(v).map(key => {
149
+ assertScalarString(key);
150
+ return { key, bytes: encoder.encode(key) };
151
+ }).sort((a, b) => compareBytes(a.bytes, b.bytes)).map(({ key }) => key);
152
+ chunks.push(array ? '[' : '{');
153
+ stack.push({ end: v }, { text: (keys.length ? whitespace(depth) : '') + (array ? ']' : '}') });
154
+ for (let i = keys.length - 1; i >= 0; i--) {
155
+ const key = keys[i];
156
+ stack.push({ value: v[key], depth: depth + 1 });
157
+ stack.push({ text: (i ? ',' : '') + whitespace(depth + 1) +
158
+ (array ? '' : JSON.stringify(key) + (pretty ? ': ' : ':')) });
159
+ }
160
+ }
161
+ else {
162
+ throw new MistsignError('invalid-json');
163
+ }
164
+ }
165
+ return chunks.join('');
166
+ }
167
+ /** Go stablejson-compatible canonical JSON (UTF-8 key order, finite binary64). */
168
+ export function canonicalJson(value) { return stringify(value, false); }
169
+ /** Sorted JSON with two-space indentation and a final LF, as in Go PrettySignature. */
170
+ export function prettyJson(value) { return stringify(value, true) + '\n'; }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ // Optional Preact components and hooks for signature and agreement workflows.
2
+ export {};
File without changes
@@ -0,0 +1,11 @@
1
+ export declare class Sha256 {
2
+ private readonly state;
3
+ private readonly block;
4
+ private readonly w;
5
+ private used;
6
+ private length;
7
+ private finished;
8
+ update(data: Uint8Array): this;
9
+ digest(): Uint8Array;
10
+ private compress;
11
+ }
package/dist/sha256.js ADDED
@@ -0,0 +1,103 @@
1
+ // FIPS 180-4 SHA-256. Only the current 64-byte block and message schedule
2
+ // are retained, so file size does not determine memory consumption.
3
+ const K = new Uint32Array([
4
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
5
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
6
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
7
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
8
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
9
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
10
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
11
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
12
+ ]);
13
+ const rotr = (v, n) => (v >>> n) | (v << (32 - n));
14
+ export class Sha256 {
15
+ state = new Uint32Array([
16
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
17
+ ]);
18
+ block = new Uint8Array(64);
19
+ w = new Uint32Array(64);
20
+ used = 0;
21
+ length = 0n;
22
+ finished = false;
23
+ update(data) {
24
+ if (this.finished)
25
+ throw new Error('SHA-256 already finalized');
26
+ this.length += BigInt(data.byteLength);
27
+ let offset = 0;
28
+ if (this.used) {
29
+ const n = Math.min(64 - this.used, data.length);
30
+ this.block.set(data.subarray(0, n), this.used);
31
+ this.used += n;
32
+ offset = n;
33
+ if (this.used === 64) {
34
+ this.compress(this.block, 0);
35
+ this.used = 0;
36
+ }
37
+ }
38
+ while (offset + 64 <= data.length) {
39
+ this.compress(data, offset);
40
+ offset += 64;
41
+ }
42
+ if (offset < data.length) {
43
+ this.block.set(data.subarray(offset), 0);
44
+ this.used = data.length - offset;
45
+ }
46
+ return this;
47
+ }
48
+ digest() {
49
+ if (this.finished)
50
+ throw new Error('SHA-256 already finalized');
51
+ this.finished = true;
52
+ this.block[this.used++] = 0x80;
53
+ this.block.fill(0, this.used);
54
+ if (this.used > 56) {
55
+ this.compress(this.block, 0);
56
+ this.block.fill(0);
57
+ }
58
+ new DataView(this.block.buffer).setBigUint64(56, this.length * 8n, false);
59
+ this.compress(this.block, 0);
60
+ const bytes = new Uint8Array(32);
61
+ const view = new DataView(bytes.buffer);
62
+ this.state.forEach((word, i) => view.setUint32(i * 4, word, false));
63
+ return bytes;
64
+ }
65
+ compress(bytes, offset) {
66
+ const w = this.w;
67
+ for (let i = 0; i < 16; i++, offset += 4) {
68
+ w[i] = (bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3];
69
+ }
70
+ for (let i = 16; i < 64; i++) {
71
+ const x = w[i - 15], y = w[i - 2];
72
+ const s0 = rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3);
73
+ const s1 = rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10);
74
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
75
+ }
76
+ let [a, b, c, d, e, f, g, h] = this.state;
77
+ for (let i = 0; i < 64; i++) {
78
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
79
+ const ch = (e & f) ^ (~e & g);
80
+ const t1 = (h + s1 + ch + K[i] + w[i]) >>> 0;
81
+ const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
82
+ const maj = (a & b) ^ (a & c) ^ (b & c);
83
+ const t2 = (s0 + maj) >>> 0;
84
+ h = g;
85
+ g = f;
86
+ f = e;
87
+ e = (d + t1) >>> 0;
88
+ d = c;
89
+ c = b;
90
+ b = a;
91
+ a = (t1 + t2) >>> 0;
92
+ }
93
+ const s = this.state;
94
+ s[0] += a;
95
+ s[1] += b;
96
+ s[2] += c;
97
+ s[3] += d;
98
+ s[4] += e;
99
+ s[5] += f;
100
+ s[6] += g;
101
+ s[7] += h;
102
+ }
103
+ }
package/dist/sign.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import type { FileInput, ProgressCallback } from './content.js';
2
+ import type { JsonInput } from './json.js';
3
+ import type { TimeInput } from './time.js';
4
+ import type { DelegationV1 } from './trust/delegation.js';
5
+ import type { DidSigner } from './wire.js';
6
+ export declare const SIGNATURE_TYPE = "tc-sign:signature";
7
+ export interface SignatureFileInfo {
8
+ name: string;
9
+ size: number;
10
+ sha256: string;
11
+ }
12
+ export interface SignatureV1 {
13
+ type: typeof SIGNATURE_TYPE;
14
+ v: 1;
15
+ fromId: string;
16
+ file: SignatureFileInfo;
17
+ signedAt: string;
18
+ comment?: string;
19
+ delegation?: DelegationV1;
20
+ signature: string;
21
+ }
22
+ export interface SignOptions {
23
+ /** File.name by default; required for inputs without a name. */
24
+ name?: string;
25
+ signedAt?: TimeInput;
26
+ comment?: string;
27
+ delegation?: DelegationV1;
28
+ progress?: ProgressCallback;
29
+ }
30
+ /** Produce a detached tc-sign v1 signature without buffering file contents. */
31
+ export declare function signFile(input: FileInput, signer: DidSigner, options?: SignOptions): Promise<Uint8Array>;
32
+ /** The SHA-256 of the entire canonical signed document, not its pretty bytes. */
33
+ export declare function timestampDigest(signature: JsonInput): Promise<Uint8Array>;
package/dist/sign.js ADDED
@@ -0,0 +1,61 @@
1
+ import { sha256, utf8 } from './bytes.js';
2
+ import { basename, hashContent, inputName } from './content.js';
3
+ import { isEd25519DidKey } from './didKey.js';
4
+ import { MistsignError } from './errors.js';
5
+ import { canonicalJson, isObject, MAX_SIGNATURE_SIZE, parseStrictJson, prettyJson } from './json.js';
6
+ import { formatTime, nowInstant, parseTime } from './time.js';
7
+ import { delegationFields, verifyDelegationAt } from './trust/delegation.js';
8
+ import { signWire, verifyWire } from './wire.js';
9
+ export const SIGNATURE_TYPE = 'tc-sign:signature';
10
+ /** Produce a detached tc-sign v1 signature without buffering file contents. */
11
+ export async function signFile(input, signer, options = {}) {
12
+ const name = options.name ?? inputName(input);
13
+ if (name === undefined)
14
+ throw new MistsignError('invalid-file-info');
15
+ const did = signer.did;
16
+ if (!isEd25519DidKey(did))
17
+ throw new MistsignError('invalid-did');
18
+ const at = nowInstant(options.signedAt);
19
+ // Snapshot the signed fields before waiting for file I/O or an external signer.
20
+ const comment = options.comment;
21
+ let delegation;
22
+ if (options.delegation !== undefined) {
23
+ delegation = delegationFields(options.delegation);
24
+ if (!await verifyDelegationAt(delegation, at, did))
25
+ throw new MistsignError('invalid-delegation');
26
+ }
27
+ const file = { name: basename(name), ...await hashContent(input, Number.MAX_SAFE_INTEGER, options.progress) };
28
+ const wire = { type: SIGNATURE_TYPE, v: 1, fromId: did, file, signedAt: formatTime(at) };
29
+ if (comment !== undefined)
30
+ wire.comment = comment;
31
+ if (delegation !== undefined)
32
+ wire.delegation = delegation;
33
+ wire.signature = await signWire(wire, signer);
34
+ const data = utf8.encode(prettyJson(wire));
35
+ if (data.length > MAX_SIGNATURE_SIZE)
36
+ throw new MistsignError('document-too-large');
37
+ parseStrictJson(data, 'signature');
38
+ return data;
39
+ }
40
+ /** The SHA-256 of the entire canonical signed document, not its pretty bytes. */
41
+ export async function timestampDigest(signature) {
42
+ const wire = parseStrictJson(signature, 'signature');
43
+ if (!isObject(wire) || wire.type !== SIGNATURE_TYPE || wire.v !== 1)
44
+ throw new MistsignError('invalid-format');
45
+ if (!isEd25519DidKey(wire.fromId))
46
+ throw new MistsignError('invalid-did');
47
+ if (typeof wire.signature !== 'string')
48
+ throw new MistsignError('missing-signature');
49
+ if (!isObject(wire.file))
50
+ throw new MistsignError('invalid-file-info');
51
+ if (typeof wire.file.size !== 'number' || !Number.isSafeInteger(wire.file.size) || wire.file.size < 0) {
52
+ throw new MistsignError('invalid-file-size');
53
+ }
54
+ if (typeof wire.file.sha256 !== 'string' || !/^[0-9a-fA-F]{64}$/.test(wire.file.sha256)) {
55
+ throw new MistsignError('invalid-sha256');
56
+ }
57
+ parseTime(wire.signedAt);
58
+ if (!await verifyWire(wire))
59
+ throw new MistsignError('signature-mismatch');
60
+ return sha256(utf8.encode(canonicalJson(wire)));
61
+ }
@@ -0,0 +1,5 @@
1
+ import type { DidSigner } from '../wire.js';
2
+ /** Test-only deterministic in-memory signer. Never use public fixture seeds in production. */
3
+ export declare function createTestSigner(seed: Uint8Array): Promise<DidSigner>;
4
+ /** Derive a 32-byte test seed from SHA-256(UTF-8(label)), as in tc-sign vectors. */
5
+ export declare function createTestSignerFromLabel(label: string): Promise<DidSigner>;
@@ -0,0 +1,27 @@
1
+ import { didKeyFromEd25519PublicKey } from '../didKey.js';
2
+ import { sha256, utf8 } from '../bytes.js';
3
+ /** Test-only deterministic in-memory signer. Never use public fixture seeds in production. */
4
+ export async function createTestSigner(seed) {
5
+ if (seed.length !== 32)
6
+ throw new RangeError('Expected 32-byte Ed25519 seed');
7
+ // RFC 8410 PKCS#8 encoding of an Ed25519 seed only.
8
+ const pkcs8 = new Uint8Array(48);
9
+ pkcs8.set([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20]);
10
+ pkcs8.set(seed, 16);
11
+ const subtle = globalThis.crypto.subtle;
12
+ const key = await subtle.importKey('pkcs8', pkcs8, 'Ed25519', true, ['sign']);
13
+ const jwk = await subtle.exportKey('jwk', key);
14
+ if (!jwk.x)
15
+ throw new Error('Ed25519 public key not available');
16
+ const publicKey = Uint8Array.from(atob(jwk.x.replaceAll('-', '+').replaceAll('_', '/') + '='), c => c.charCodeAt(0));
17
+ return {
18
+ did: didKeyFromEd25519PublicKey(publicKey),
19
+ async sign(bytes) {
20
+ return new Uint8Array(await subtle.sign('Ed25519', key, new Uint8Array(bytes)));
21
+ },
22
+ };
23
+ }
24
+ /** Derive a 32-byte test seed from SHA-256(UTF-8(label)), as in tc-sign vectors. */
25
+ export async function createTestSignerFromLabel(label) {
26
+ return createTestSigner(await sha256(utf8.encode(label)));
27
+ }
package/dist/time.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ export type TimeInput = Date | number;
2
+ export type Instant = bigint;
3
+ export declare const MS = 1000000n;
4
+ export declare const CLOCK_SKEW: bigint;
5
+ export declare const MAX_DELEGATION_DURATION: bigint;
6
+ export declare function nowInstant(now?: TimeInput): Instant;
7
+ /** Match Go time.Parse(RFC3339Nano), without Date.parse's calendar normalization. */
8
+ export declare function parseTime(value: unknown): Instant;
9
+ export declare function formatTime(at: Instant): string;
package/dist/time.js ADDED
@@ -0,0 +1,36 @@
1
+ import { MistsignError } from './errors.js';
2
+ export const MS = 1000000n;
3
+ export const CLOCK_SKEW = 300000n * MS;
4
+ export const MAX_DELEGATION_DURATION = 400n * 24n * 60n * 60n * 1000n * MS;
5
+ export function nowInstant(now = Date.now()) {
6
+ const ms = new Date(now instanceof Date ? now.getTime() : now).getTime();
7
+ if (!Number.isFinite(ms))
8
+ throw new MistsignError('invalid-time');
9
+ return BigInt(ms) * MS;
10
+ }
11
+ /** Match Go time.Parse(RFC3339Nano), without Date.parse's calendar normalization. */
12
+ export function parseTime(value) {
13
+ if (typeof value !== 'string')
14
+ throw new MistsignError('invalid-time');
15
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{1,2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|([+-])(\d{2}):(\d{2}))$/.exec(value);
16
+ if (!match)
17
+ throw new MistsignError('invalid-time');
18
+ const [, y, mo, d, h, mi, s, frac = '', zone, sign, zh = '0', zm = '0'] = match;
19
+ const [year, month, day, hour, minute, second, zoneHour, zoneMinute] = [y, mo, d, h, mi, s, zh, zm].map(Number);
20
+ if (month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 59 ||
21
+ zoneHour > 24 || zoneMinute > 60)
22
+ throw new MistsignError('invalid-time');
23
+ const date = new Date(0);
24
+ date.setUTCFullYear(year, month - 1, day);
25
+ date.setUTCHours(hour, minute, second, 0);
26
+ if (date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day)
27
+ throw new MistsignError('invalid-time');
28
+ const offset = zone === 'Z' ? 0 : (sign === '-' ? -1 : 1) * (zoneHour * 60 + zoneMinute) * 60_000;
29
+ return BigInt(date.getTime() - offset) * MS + BigInt(frac.slice(0, 9).padEnd(9, '0'));
30
+ }
31
+ export function formatTime(at) {
32
+ const millis = at / MS - (at < 0n && at % MS !== 0n ? 1n : 0n);
33
+ const iso = new Date(Number(millis)).toISOString();
34
+ // Go permits year 0000; normal phase-1 timestamps are exactly four digits.
35
+ return iso.replace(/^([+-])(\d{6})(?=-)/, (_, sign, year) => (sign === '-' ? '-' : '') + Number(year).toString().padStart(4, '0'));
36
+ }
@@ -0,0 +1,2 @@
1
+ import type { Der } from './der.js';
2
+ export declare function asnTime(value: Der, tst?: boolean): bigint;
@@ -0,0 +1,17 @@
1
+ import { parseTime } from '../time.js';
2
+ import { check } from './der.js';
3
+ export function asnTime(value, tst = false) {
4
+ let s = new TextDecoder('utf-8', { fatal: true }).decode(value.body);
5
+ if (value.tag === 23 && !tst) {
6
+ s = (Number(s.slice(0, 2)) >= 50 ? '19' : '20') + s;
7
+ }
8
+ else {
9
+ check(value.tag === 24);
10
+ }
11
+ const m = /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)?(\.\d+)?(Z|[+-]\d{4})$/.exec(s);
12
+ check(m && (!tst || (m[6] && m[8] === 'Z')) && (value.tag === 23 || m[6]));
13
+ if (value.tag === 23)
14
+ check(!m[7]);
15
+ const zone = m[8] === 'Z' ? 'Z' : m[8].slice(0, 3) + ':' + m[8].slice(3);
16
+ return parseTime(m[1] + '-' + m[2] + '-' + m[3] + 'T' + m[4] + ':' + m[5] + ':' + (m[6] ?? '00') + (m[7] ?? '') + zone);
17
+ }
@@ -0,0 +1,30 @@
1
+ import type { Hash } from './crypto.js';
2
+ import type { Der } from './der.js';
3
+ import type { Certificate } from './x509.js';
4
+ export declare function signedData(token: Uint8Array<ArrayBuffer>): {
5
+ eContent: Uint8Array<ArrayBuffer>;
6
+ certs: Certificate[];
7
+ signer: Der;
8
+ };
9
+ export declare function tstInfo(bytes: Uint8Array<ArrayBuffer>): {
10
+ at: bigint;
11
+ accuracyNs: bigint | undefined;
12
+ imprintAlgorithm: import("./der.js").Algorithm;
13
+ digest: Uint8Array<ArrayBuffer>;
14
+ };
15
+ export declare function signerInfo(value: Der): {
16
+ matches: (cert: Certificate) => boolean;
17
+ digest: import("./der.js").Algorithm;
18
+ attrs: Der;
19
+ sigAlg: import("./der.js").Algorithm;
20
+ sig: Uint8Array<ArrayBuffer>;
21
+ };
22
+ export declare function signingAttributes(attrs: Der, eContent: Uint8Array<ArrayBuffer>, hash: Hash): Promise<{
23
+ v1: Der | undefined;
24
+ v2: Der | undefined;
25
+ }>;
26
+ export declare function selectSigner(certs: Certificate[], matches: (c: Certificate) => boolean): Certificate;
27
+ export declare function verifyESS(attrs: {
28
+ v1?: Der;
29
+ v2?: Der;
30
+ }, cert: Certificate): Promise<void>;
@@ -0,0 +1,126 @@
1
+ import { asnTime } from './asnTime.js';
2
+ import { digestAlgorithm, hashBytes } from './crypto.js';
3
+ import { algorithm, bool, check, decode, equal, fields, intBytes, oid, only, tagged, uint } from './der.js';
4
+ import { certificate } from './x509.js';
5
+ const tstInfoOID = '1.2.840.113549.1.9.16.1.4';
6
+ const contentType = '1.2.840.113549.1.9.3';
7
+ const messageDigest = '1.2.840.113549.1.9.4';
8
+ const essV1 = '1.2.840.113549.1.9.16.2.12';
9
+ const essV2 = '1.2.840.113549.1.9.16.2.47';
10
+ export function signedData(token) {
11
+ const [type, content] = fields(decode(token), 0x30, 2, 2);
12
+ check(oid(type) === '1.2.840.113549.1.7.2');
13
+ const [version, algorithms, encap, ...rest] = fields(only(content, 0xa0), 0x30, 4, 6);
14
+ uint(version);
15
+ tagged(algorithms, 0x31);
16
+ const [eType, wrapper] = fields(encap, 0x30, 2, 2);
17
+ check(oid(eType) === tstInfoOID);
18
+ const eContent = tagged(only(wrapper, 0xa0), 4).body;
19
+ const certs = rest[0]?.tag === 0xa0 ? rest.shift().children.filter(c => c.tag === 0x30).map(certificate) : [];
20
+ if (rest[0]?.tag === 0xa1)
21
+ rest.shift(); // CRLs
22
+ check(rest.length === 1);
23
+ return { eContent, certs, signer: only(rest[0], 0x31) };
24
+ }
25
+ function accuracy(value) {
26
+ const parts = fields(value, 0x30, 0, 3);
27
+ let ns = 0n;
28
+ let i = 0;
29
+ if (parts[i]?.tag === 2)
30
+ ns = BigInt(uint(parts[i++])) * 1000000000n;
31
+ for (const tag of [0x80, 0x81]) {
32
+ if (parts[i]?.tag === tag) {
33
+ const n = uint(parts[i++], tag);
34
+ check(n <= 999);
35
+ ns += BigInt(n) * (tag === 0x80 ? 1000000n : 1000n);
36
+ }
37
+ }
38
+ check(i === parts.length && ns <= 0x7fffffffffffffffn);
39
+ return ns;
40
+ }
41
+ export function tstInfo(bytes) {
42
+ const [version, policy, imprint, serial, time, ...optional] = fields(decode(bytes), 0x30, 5, 10);
43
+ check(uint(version) === 1);
44
+ oid(policy);
45
+ const [hashAlgorithm, digest] = fields(imprint, 0x30, 2, 2);
46
+ intBytes(serial);
47
+ const at = asnTime(time, true);
48
+ let i = 0;
49
+ const accuracyNs = optional[i]?.tag === 0x30 ? accuracy(optional[i++]) : undefined;
50
+ if (optional[i]?.tag === 1)
51
+ bool(optional[i++]);
52
+ if (optional[i]?.tag === 2)
53
+ intBytes(optional[i++]);
54
+ if (optional[i]?.tag === 0xa0)
55
+ i++;
56
+ if (optional[i]?.tag === 0xa1)
57
+ i++;
58
+ check(i === optional.length);
59
+ return { at, accuracyNs, imprintAlgorithm: algorithm(hashAlgorithm), digest: tagged(digest, 4).body };
60
+ }
61
+ export function signerInfo(value) {
62
+ const [version, sid, digest, attrs, sigAlg, sig, unsigned] = fields(value, 0x30, 6, 7);
63
+ uint(version);
64
+ let matches;
65
+ if (sid.tag === 0x80) {
66
+ check(sid.body.length > 0);
67
+ matches = c => c.ski !== undefined && equal(c.ski, sid.body);
68
+ }
69
+ else {
70
+ const [issuer, id] = fields(sid, 0x30, 2, 2);
71
+ const serial = intBytes(id);
72
+ matches = c => equal(c.serial, serial) && equal(c.issuer, issuer.raw);
73
+ }
74
+ if (unsigned)
75
+ tagged(unsigned, 0xa1);
76
+ return { matches, digest: algorithm(digest), attrs: tagged(attrs, 0xa0), sigAlg: algorithm(sigAlg), sig: tagged(sig, 4).body };
77
+ }
78
+ export async function signingAttributes(attrs, eContent, hash) {
79
+ const seen = new Map();
80
+ const attributes = attrs.children.map(attr => {
81
+ const [type, set] = fields(attr, 0x30, 2, 2);
82
+ return { id: oid(type), set: tagged(set, 0x31) };
83
+ });
84
+ for (const { id, set } of attributes) {
85
+ if (![contentType, messageDigest, essV1, essV2].includes(id))
86
+ continue;
87
+ check(!seen.has(id));
88
+ const single = only(set, 0x31);
89
+ seen.set(id, single);
90
+ if (id === contentType)
91
+ check(oid(single) === tstInfoOID);
92
+ if (id === messageDigest)
93
+ check(equal(tagged(single, 4).body, await hashBytes(hash, eContent)));
94
+ }
95
+ check(seen.has(contentType) && seen.has(messageDigest) && (seen.has(essV1) || seen.has(essV2)));
96
+ return { v1: seen.get(essV1), v2: seen.get(essV2) };
97
+ }
98
+ export function selectSigner(certs, matches) {
99
+ const candidates = certs.filter(matches);
100
+ check(candidates.length && candidates.every(c => equal(c.raw, candidates[0].raw)));
101
+ return candidates[0];
102
+ }
103
+ async function essCertificate(attr, cert, v2) {
104
+ const [ids, policies] = fields(attr, 0x30, 1, 2);
105
+ if (policies)
106
+ fields(policies);
107
+ const parts = fields(fields(ids, 0x30, 1)[0], 0x30, 1, v2 ? 3 : 2);
108
+ let i = 0;
109
+ let hash = v2 ? 'SHA-256' : 'SHA-1';
110
+ if (v2 && parts[i].tag === 0x30)
111
+ hash = digestAlgorithm(algorithm(parts[i++]));
112
+ check(equal(tagged(parts[i++], 4).body, await hashBytes(hash, cert.raw)));
113
+ if (parts[i]) {
114
+ const [issuer, serial] = fields(parts[i++], 0x30, 2, 2);
115
+ check(equal(intBytes(serial), cert.serial));
116
+ const names = fields(issuer).filter(v => v.tag === 0xa4);
117
+ check(names.length && names.every(v => equal(v.body, cert.issuer)));
118
+ }
119
+ check(i === parts.length);
120
+ }
121
+ export async function verifyESS(attrs, cert) {
122
+ if (attrs.v1)
123
+ await essCertificate(attrs.v1, cert, false);
124
+ if (attrs.v2)
125
+ await essCertificate(attrs.v2, cert, true);
126
+ }
@@ -0,0 +1,17 @@
1
+ import type { Der } from './der.js';
2
+ type Name = {
3
+ tag: number;
4
+ text: string;
5
+ ip: Uint8Array;
6
+ };
7
+ export interface NameConstraints {
8
+ permitted: Name[];
9
+ excluded: Name[];
10
+ unhandled: boolean;
11
+ }
12
+ export declare function subjectAltNames(v: Der): Name[];
13
+ export declare function nameConstraints(v: Der): NameConstraints;
14
+ export declare function permitsNames(nc: NameConstraints, names: Name[], budget: {
15
+ remaining: number;
16
+ }): boolean;
17
+ export {};