fwdloop 0.3.0 → 0.4.0
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/package.json +18 -4
- package/src/catalogue.js +350 -0
- package/src/catalogue.json +61 -0
- package/src/declaration.js +583 -0
- package/src/flow.js +312 -0
- package/src/index.js +12 -0
- package/src/signature.js +258 -0
- package/src/signed-text.js +419 -0
- package/src/types.js +233 -0
- package/types/catalogue.d.ts +76 -0
- package/types/declaration.d.ts +28 -0
- package/types/flow.d.ts +55 -0
- package/types/index.d.ts +5 -0
- package/types/signature.d.ts +78 -0
- package/types/signed-text.d.ts +14 -0
- package/types/types.d.ts +237 -0
package/src/flow.js
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// M1 piece 5 (docs/wiki/the-module-ladder.md, "M1 — scope, exit, negative —
|
|
2
|
+
// SIGNED", item 7 and item 4): the on-disk flow directory —
|
|
3
|
+
//
|
|
4
|
+
// flows/<flow-name>/
|
|
5
|
+
// prose.txt the signed text: numbered lines + guardrails + arbiter block
|
|
6
|
+
// declaration.json the drafter's half, validated
|
|
7
|
+
// signature.json sha256 of both, signed-by, signed-at
|
|
8
|
+
// runs/<run-id>/ (M2's — M1 only creates the empty runs/ directory)
|
|
9
|
+
//
|
|
10
|
+
// "The M2 runner will refuse a run whose files do not hash to the signature,
|
|
11
|
+
// naming the file. In M1 the check exists and is tested; nothing runs yet."
|
|
12
|
+
//
|
|
13
|
+
// This module is the ONLY reader and the ONLY writer of a flow directory
|
|
14
|
+
// (project rule: one writer per piece of state). It composes the pieces
|
|
15
|
+
// already built — parseSignedText (piece 1), signFlow/verifyFlow (piece 2),
|
|
16
|
+
// validateDeclaration (piece 3), the catalogue as data (piece 4) — it does
|
|
17
|
+
// not reimplement any of their checks.
|
|
18
|
+
//
|
|
19
|
+
// Never throws on bad input or a filesystem error: every failure path is
|
|
20
|
+
// caught and returned as a red naming the file or path involved.
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync,
|
|
24
|
+
} from 'node:fs';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
|
|
27
|
+
import { parseSignedText } from './signed-text.js';
|
|
28
|
+
import { signFlow, verifyFlow } from './signature.js';
|
|
29
|
+
import { validateDeclaration } from './declaration.js';
|
|
30
|
+
|
|
31
|
+
/** @typedef {import('./types.js').WriteFlowResult} WriteFlowResult */
|
|
32
|
+
/** @typedef {import('./types.js').ReadFlowResult} ReadFlowResult */
|
|
33
|
+
/** @typedef {import('./types.js').CheckFlowNameResult} CheckFlowNameResult */
|
|
34
|
+
|
|
35
|
+
/** The three files a signed flow directory carries. Every place in this
|
|
36
|
+
* module that names a flow file uses this — never a literal string. */
|
|
37
|
+
export const FLOW_FILES = Object.freeze(['prose.txt', 'declaration.json', 'signature.json']);
|
|
38
|
+
|
|
39
|
+
const RUNS_DIR = 'runs';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Check a flow name against the allowed shape: 1..64 characters, lowercase
|
|
43
|
+
* a-z, 0-9, `-`, `_`, starting with a letter or digit. Walked character by
|
|
44
|
+
* character — never a regex — so a name that would escape the flows
|
|
45
|
+
* directory (`..`, a `/` or `\` segment, a leading dot, an absolute path)
|
|
46
|
+
* or is simply empty is refused by the same loop that refuses a bad
|
|
47
|
+
* character, not a separate ad-hoc check.
|
|
48
|
+
*
|
|
49
|
+
* @param {unknown} name
|
|
50
|
+
* @returns {CheckFlowNameResult}
|
|
51
|
+
*/
|
|
52
|
+
export function checkFlowName(name) {
|
|
53
|
+
if (typeof name !== 'string') {
|
|
54
|
+
return { ok: false, red: 'flow: name must be a string' };
|
|
55
|
+
}
|
|
56
|
+
if (name.length === 0) {
|
|
57
|
+
return { ok: false, red: 'flow: name must not be empty' };
|
|
58
|
+
}
|
|
59
|
+
if (name.length > 64) {
|
|
60
|
+
return { ok: false, red: `flow: name is ${name.length} characters, must be 1..64` };
|
|
61
|
+
}
|
|
62
|
+
for (let i = 0; i < name.length; i += 1) {
|
|
63
|
+
const ch = name[i];
|
|
64
|
+
const isDigit = ch >= '0' && ch <= '9';
|
|
65
|
+
const isLower = ch >= 'a' && ch <= 'z';
|
|
66
|
+
const isDashUnderscore = ch === '-' || ch === '_';
|
|
67
|
+
if (i === 0) {
|
|
68
|
+
if (!isDigit && !isLower) {
|
|
69
|
+
return { ok: false, red: `flow: name must start with a letter or digit, got "${ch}"` };
|
|
70
|
+
}
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (!isDigit && !isLower && !isDashUnderscore) {
|
|
74
|
+
return { ok: false, red: `flow: name character ${i} ("${ch}") is not one of a-z, 0-9, "-", "_"` };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { ok: true };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function readTextFile(filePath, label, reds) {
|
|
81
|
+
let stat;
|
|
82
|
+
try {
|
|
83
|
+
stat = lstatSync(filePath);
|
|
84
|
+
} catch {
|
|
85
|
+
reds.push(`flow: ${label} is missing`);
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
if (stat.isSymbolicLink()) {
|
|
89
|
+
reds.push(`flow: ${label} is a symlink, refused`);
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
if (!stat.isFile()) {
|
|
93
|
+
reds.push(`flow: ${label} is not a regular file`);
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
let text;
|
|
97
|
+
try {
|
|
98
|
+
text = readFileSync(filePath, 'utf8');
|
|
99
|
+
} catch (err) {
|
|
100
|
+
reds.push(`flow: ${label} could not be read — ${err.message}`);
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
if (text.length === 0) {
|
|
104
|
+
reds.push(`flow: ${label} is empty`);
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
return text;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Write a signed flow to `<root>/<name>/`. Refuses (writing nothing) if the
|
|
112
|
+
* flow name is invalid, if `proseText`/`declaration` don't parse/validate,
|
|
113
|
+
* if `signFlow` refuses, or if any of the three files already exists.
|
|
114
|
+
* Otherwise writes `prose.txt`, `declaration.json`, then `signature.json`
|
|
115
|
+
* last (each via a temp file + rename in the same directory), creates an
|
|
116
|
+
* empty `runs/`, and proves the result by reading it back with `readFlow`.
|
|
117
|
+
*
|
|
118
|
+
* @param {{root: unknown, name: unknown, proseText: unknown, declaration: unknown, signedBy: unknown, signedAt: unknown, catalogue: unknown}} input
|
|
119
|
+
* @returns {WriteFlowResult}
|
|
120
|
+
*/
|
|
121
|
+
export function writeFlow({
|
|
122
|
+
root, name, proseText, declaration, signedBy, signedAt, catalogue,
|
|
123
|
+
}) {
|
|
124
|
+
const nameCheck = checkFlowName(name);
|
|
125
|
+
if (!nameCheck.ok) return { ok: false, reds: [nameCheck.red] };
|
|
126
|
+
const safeName = /** @type {string} */ (name);
|
|
127
|
+
|
|
128
|
+
if (typeof root !== 'string' || root.length === 0) {
|
|
129
|
+
return { ok: false, reds: ['flow: "root" must be a non-empty string'] };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const signed = parseSignedText(proseText);
|
|
133
|
+
if (!signed.ok) return { ok: false, reds: signed.reds };
|
|
134
|
+
|
|
135
|
+
const validated = validateDeclaration(declaration, {
|
|
136
|
+
arbiter: signed.arbiter, lines: signed.lines, catalogue,
|
|
137
|
+
});
|
|
138
|
+
if (!validated.ok) return { ok: false, reds: validated.reds };
|
|
139
|
+
|
|
140
|
+
let declarationText;
|
|
141
|
+
try {
|
|
142
|
+
declarationText = `${JSON.stringify(declaration, null, 2)}\n`;
|
|
143
|
+
} catch (err) {
|
|
144
|
+
return { ok: false, reds: [`flow: declaration could not be serialised — ${err.message}`] };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const signResult = signFlow({
|
|
148
|
+
proseText, declarationText, signedBy, signedAt,
|
|
149
|
+
});
|
|
150
|
+
if (!signResult.ok) return { ok: false, reds: signResult.reds };
|
|
151
|
+
|
|
152
|
+
const dir = path.join(root, safeName);
|
|
153
|
+
|
|
154
|
+
// Refuse if any of the three files already exists — M1 never overwrites a
|
|
155
|
+
// signed flow (versions are M4).
|
|
156
|
+
for (const fileName of FLOW_FILES) {
|
|
157
|
+
const filePath = path.join(dir, fileName);
|
|
158
|
+
let exists;
|
|
159
|
+
try {
|
|
160
|
+
exists = existsSync(filePath);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
return { ok: false, reds: [`flow: could not check "${filePath}" — ${err.message}`] };
|
|
163
|
+
}
|
|
164
|
+
if (exists) {
|
|
165
|
+
return { ok: false, reds: [`flow: "${fileName}" already exists at ${filePath}`] };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Track what THIS call creates so a failure partway through can be rolled
|
|
170
|
+
// back — a directory must never be left with a signature but a missing
|
|
171
|
+
// file.
|
|
172
|
+
const createdDir = !existsSync(dir);
|
|
173
|
+
const written = [];
|
|
174
|
+
|
|
175
|
+
const rollback = () => {
|
|
176
|
+
try {
|
|
177
|
+
if (createdDir) {
|
|
178
|
+
rmSync(dir, { recursive: true, force: true });
|
|
179
|
+
} else {
|
|
180
|
+
for (const p of written) rmSync(p, { force: true });
|
|
181
|
+
}
|
|
182
|
+
} catch {
|
|
183
|
+
// best-effort cleanup; the red already reports the real failure
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
try {
|
|
188
|
+
mkdirSync(dir, { recursive: true });
|
|
189
|
+
} catch (err) {
|
|
190
|
+
return { ok: false, reds: [`flow: could not create directory ${dir} — ${err.message}`] };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const writeOne = (fileName, contents) => {
|
|
194
|
+
const finalPath = path.join(dir, fileName);
|
|
195
|
+
const tmpPath = path.join(dir, `.${fileName}.tmp-${process.pid}-${Date.now()}`);
|
|
196
|
+
try {
|
|
197
|
+
writeFileSync(tmpPath, contents, 'utf8');
|
|
198
|
+
renameSync(tmpPath, finalPath);
|
|
199
|
+
} catch (err) {
|
|
200
|
+
try { rmSync(tmpPath, { force: true }); } catch { /* best-effort */ }
|
|
201
|
+
throw new Error(`could not write ${finalPath} — ${err.message}`);
|
|
202
|
+
}
|
|
203
|
+
written.push(finalPath);
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
try {
|
|
207
|
+
writeOne('prose.txt', proseText);
|
|
208
|
+
writeOne('declaration.json', declarationText);
|
|
209
|
+
writeOne('signature.json', `${JSON.stringify(signResult.signature, null, 2)}\n`);
|
|
210
|
+
|
|
211
|
+
const runsDir = path.join(dir, RUNS_DIR);
|
|
212
|
+
mkdirSync(runsDir, { recursive: true });
|
|
213
|
+
} catch (err) {
|
|
214
|
+
rollback();
|
|
215
|
+
return { ok: false, reds: [`flow: ${err.message}`] };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// The mechanical "it happened" check: the artifact exists, is non-empty,
|
|
219
|
+
// and verifies — read our own write back through the one reader.
|
|
220
|
+
const proof = readFlow({ root, name, catalogue });
|
|
221
|
+
if (!proof.ok) {
|
|
222
|
+
rollback();
|
|
223
|
+
return { ok: false, reds: proof.reds };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
ok: true, dir, signature: signResult.signature,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Read and verify a signed flow from `<root>/<name>/`. Verifies the bytes on
|
|
233
|
+
* disk against the signature FIRST — before anything in the flow is
|
|
234
|
+
* trusted — then parses the signed text, then validates the declaration.
|
|
235
|
+
* Never throws; every failure is a red naming the file or path.
|
|
236
|
+
*
|
|
237
|
+
* @param {{root: unknown, name: unknown, catalogue: unknown}} input
|
|
238
|
+
* @returns {ReadFlowResult}
|
|
239
|
+
*/
|
|
240
|
+
export function readFlow({ root, name, catalogue }) {
|
|
241
|
+
const nameCheck = checkFlowName(name);
|
|
242
|
+
if (!nameCheck.ok) return { ok: false, reds: [nameCheck.red] };
|
|
243
|
+
const safeName = /** @type {string} */ (name);
|
|
244
|
+
|
|
245
|
+
if (typeof root !== 'string' || root.length === 0) {
|
|
246
|
+
return { ok: false, reds: ['flow: "root" must be a non-empty string'] };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const dir = path.join(root, safeName);
|
|
250
|
+
|
|
251
|
+
let dirStat;
|
|
252
|
+
try {
|
|
253
|
+
dirStat = lstatSync(dir);
|
|
254
|
+
} catch {
|
|
255
|
+
return { ok: false, reds: [`flow: directory "${dir}" is missing`] };
|
|
256
|
+
}
|
|
257
|
+
if (dirStat.isSymbolicLink()) {
|
|
258
|
+
return { ok: false, reds: [`flow: directory "${dir}" is a symlink, refused`] };
|
|
259
|
+
}
|
|
260
|
+
if (!dirStat.isDirectory()) {
|
|
261
|
+
return { ok: false, reds: [`flow: "${dir}" is not a directory`] };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const reds = [];
|
|
265
|
+
const proseText = readTextFile(path.join(dir, 'prose.txt'), 'prose.txt', reds);
|
|
266
|
+
const declarationText = readTextFile(path.join(dir, 'declaration.json'), 'declaration.json', reds);
|
|
267
|
+
const signatureText = readTextFile(path.join(dir, 'signature.json'), 'signature.json', reds);
|
|
268
|
+
|
|
269
|
+
let declarationJson;
|
|
270
|
+
if (declarationText !== null) {
|
|
271
|
+
try {
|
|
272
|
+
declarationJson = JSON.parse(declarationText);
|
|
273
|
+
} catch {
|
|
274
|
+
reds.push('flow: declaration.json is not valid JSON');
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
let signatureJson;
|
|
279
|
+
if (signatureText !== null) {
|
|
280
|
+
try {
|
|
281
|
+
signatureJson = JSON.parse(signatureText);
|
|
282
|
+
} catch {
|
|
283
|
+
reds.push('flow: signature.json is not valid JSON');
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if (reds.length > 0) return { ok: false, reds };
|
|
288
|
+
|
|
289
|
+
// Verify against the bytes on disk, not a re-serialised object.
|
|
290
|
+
const verified = verifyFlow({
|
|
291
|
+
proseText, declarationText, signature: signatureJson,
|
|
292
|
+
});
|
|
293
|
+
if (!verified.ok) return { ok: false, reds: verified.reds };
|
|
294
|
+
|
|
295
|
+
const signed = parseSignedText(proseText);
|
|
296
|
+
if (!signed.ok) return { ok: false, reds: signed.reds };
|
|
297
|
+
|
|
298
|
+
const validated = validateDeclaration(declarationJson, {
|
|
299
|
+
arbiter: signed.arbiter, lines: signed.lines, catalogue,
|
|
300
|
+
});
|
|
301
|
+
if (!validated.ok) return { ok: false, reds: validated.reds };
|
|
302
|
+
|
|
303
|
+
return {
|
|
304
|
+
ok: true,
|
|
305
|
+
dir,
|
|
306
|
+
lines: signed.lines,
|
|
307
|
+
arbiter: signed.arbiter,
|
|
308
|
+
declaration: declarationJson,
|
|
309
|
+
signature: signatureJson,
|
|
310
|
+
classes: validated.classes,
|
|
311
|
+
};
|
|
312
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Public API. Re-exports only — the entry point an adopter (or the M2/M3
|
|
2
|
+
// pieces still to come) imports from.
|
|
3
|
+
|
|
4
|
+
export { parseSignedText, ARBITER_FIELDS } from './signed-text.js';
|
|
5
|
+
export { signFlow, verifyFlow, canonicalBytes, SIGNATURE_FIELDS } from './signature.js';
|
|
6
|
+
export { validateDeclaration, DECLARATION_FIELDS } from './declaration.js';
|
|
7
|
+
export {
|
|
8
|
+
parseCatalogue, loadCatalogue, menu, primitiveFor, resolveEntry, CATALOGUE_FIELDS,
|
|
9
|
+
} from './catalogue.js';
|
|
10
|
+
export {
|
|
11
|
+
checkFlowName, writeFlow, readFlow, FLOW_FILES,
|
|
12
|
+
} from './flow.js';
|
package/src/signature.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// M1 piece — signature.js: the hash pinning `prose.txt` + `declaration.json`
|
|
2
|
+
// (docs/wiki/the-module-ladder.md, "M1 — scope, exit, negative — SIGNED",
|
|
3
|
+
// scope item 4: "A hash that flips on any edit"; flow directory item 7).
|
|
4
|
+
//
|
|
5
|
+
// The M2 runner will refuse a run whose files do not hash to the signature,
|
|
6
|
+
// naming the file. In M1 the check exists and is tested; nothing runs yet.
|
|
7
|
+
// This module never reads the clock, never touches disk — the caller (a
|
|
8
|
+
// human-signing step, later) passes signedAt and the file contents.
|
|
9
|
+
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
|
|
12
|
+
/** @typedef {import('./types.js').CanonicalBytesResult} CanonicalBytesResult */
|
|
13
|
+
/** @typedef {import('./types.js').SignFlowResult} SignFlowResult */
|
|
14
|
+
/** @typedef {import('./types.js').VerifyFlowResult} VerifyFlowResult */
|
|
15
|
+
|
|
16
|
+
/** The signature.json fields the mutation suite is required to cover —
|
|
17
|
+
* kept in sync with signFlow/verifyFlow below. */
|
|
18
|
+
export const SIGNATURE_FIELDS = Object.freeze([
|
|
19
|
+
'version',
|
|
20
|
+
'algorithm',
|
|
21
|
+
'files.prose.txt',
|
|
22
|
+
'files.declaration.json',
|
|
23
|
+
'flow',
|
|
24
|
+
'signedBy',
|
|
25
|
+
'signedAt',
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
const KNOWN_FILES = Object.freeze(['prose.txt', 'declaration.json']);
|
|
29
|
+
const HEX64_RE = /^[0-9a-f]{64}$/;
|
|
30
|
+
// Strict-enough ISO-8601: date, "T", time, optional fractional seconds, and
|
|
31
|
+
// either "Z" or a numeric UTC offset. Fixed literal, no nested quantifiers.
|
|
32
|
+
const ISO8601_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The canonical bytes hashed for one of the two signed files. Never throws.
|
|
36
|
+
*
|
|
37
|
+
* `prose.txt`: the exact file bytes with CRLF normalised to LF and nothing
|
|
38
|
+
* else changed — no trimming, no Unicode normalisation. The human signs the
|
|
39
|
+
* text as written; a Windows checkout (CRLF line endings) must not flip the
|
|
40
|
+
* hash, but anything the human actually wrote — a trailing space, a changed
|
|
41
|
+
* character — must.
|
|
42
|
+
*
|
|
43
|
+
* `declaration.json`: parsed then re-serialised with object keys sorted
|
|
44
|
+
* recursively, no whitespace, arrays left in their original order. So
|
|
45
|
+
* key order and indentation (cosmetic) can never flip the hash, while any
|
|
46
|
+
* value or structural change (including reordering an array — order is
|
|
47
|
+
* meaning for `steps`) always does. Unparseable JSON is a red, never a
|
|
48
|
+
* throw.
|
|
49
|
+
*
|
|
50
|
+
* @param {'prose.txt'|'declaration.json'} kind
|
|
51
|
+
* @param {unknown} content
|
|
52
|
+
* @returns {CanonicalBytesResult}
|
|
53
|
+
*/
|
|
54
|
+
export function canonicalBytes(kind, content) {
|
|
55
|
+
if (typeof content !== 'string') {
|
|
56
|
+
return { ok: false, red: `${kind}: content must be a string` };
|
|
57
|
+
}
|
|
58
|
+
if (kind === 'prose.txt') {
|
|
59
|
+
const normalised = content.replace(/\r\n/g, '\n');
|
|
60
|
+
return { ok: true, bytes: Buffer.from(normalised, 'utf8') };
|
|
61
|
+
}
|
|
62
|
+
if (kind === 'declaration.json') {
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
parsed = JSON.parse(content);
|
|
66
|
+
} catch {
|
|
67
|
+
return { ok: false, red: 'declaration.json: is not valid JSON' };
|
|
68
|
+
}
|
|
69
|
+
const canonical = JSON.stringify(sortKeysDeep(parsed));
|
|
70
|
+
return { ok: true, bytes: Buffer.from(canonical, 'utf8') };
|
|
71
|
+
}
|
|
72
|
+
return { ok: false, red: `${kind}: unknown canonical file kind` };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sortKeysDeep(value) {
|
|
76
|
+
if (Array.isArray(value)) return value.map(sortKeysDeep);
|
|
77
|
+
if (value && typeof value === 'object') {
|
|
78
|
+
const sorted = {};
|
|
79
|
+
for (const key of Object.keys(value).sort()) sorted[key] = sortKeysDeep(value[key]);
|
|
80
|
+
return sorted;
|
|
81
|
+
}
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function hashHex(bytes) {
|
|
86
|
+
return createHash('sha256').update(bytes).digest('hex');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The one function that computes `signature.flow` — called by both signFlow
|
|
91
|
+
* and verifyFlow, never duplicated (one writer per piece of state).
|
|
92
|
+
*
|
|
93
|
+
* Hashes sha256 over `JSON.stringify([proseHash, declHash, signedBy,
|
|
94
|
+
* signedAt])`, in that fixed order. `flow` pins WHAT was signed (the two
|
|
95
|
+
* file hashes) AND WHO/WHEN (signedBy/signedAt) — editing any of the four
|
|
96
|
+
* afterwards changes the bytes hashed. A JSON array of strings is used
|
|
97
|
+
* instead of a bare `join('some-separator')` specifically because signedBy
|
|
98
|
+
* is a human-chosen name that could itself contain any separator character;
|
|
99
|
+
* `JSON.stringify` quotes and escapes each element, so the byte position of
|
|
100
|
+
* every element's boundary is unambiguous and no two distinct 4-tuples can
|
|
101
|
+
* ever serialise to the same bytes. This function does not itself validate
|
|
102
|
+
* shape (that is signFlow's/verifyFlow's job) — it only encodes and hashes
|
|
103
|
+
* whatever four values it is given.
|
|
104
|
+
*
|
|
105
|
+
* @param {string} proseHash
|
|
106
|
+
* @param {string} declHash
|
|
107
|
+
* @param {unknown} signedBy
|
|
108
|
+
* @param {unknown} signedAt
|
|
109
|
+
* @returns {string} sha256 hex digest
|
|
110
|
+
*/
|
|
111
|
+
export function computeFlowHash(proseHash, declHash, signedBy, signedAt) {
|
|
112
|
+
const encoded = JSON.stringify([proseHash, declHash, signedBy, signedAt]);
|
|
113
|
+
return hashHex(Buffer.from(encoded, 'utf8'));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Sign a flow: hash `proseText` and `declarationText` (canonically) and pin
|
|
118
|
+
* who signed and when. Pure — never reads the clock, never touches disk.
|
|
119
|
+
*
|
|
120
|
+
* @param {{proseText: unknown, declarationText: unknown, signedBy: unknown, signedAt: unknown}} input
|
|
121
|
+
* @returns {SignFlowResult}
|
|
122
|
+
*/
|
|
123
|
+
export function signFlow({ proseText, declarationText, signedBy, signedAt }) {
|
|
124
|
+
const reds = [];
|
|
125
|
+
|
|
126
|
+
if (typeof signedBy !== 'string' || signedBy.trim().length === 0) {
|
|
127
|
+
reds.push('signature: field "signedBy" is required and must be a non-empty string');
|
|
128
|
+
}
|
|
129
|
+
if (typeof signedAt !== 'string' || !ISO8601_RE.test(signedAt)) {
|
|
130
|
+
reds.push('signature: field "signedAt" is required and must be an ISO-8601 string');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const prose = canonicalBytes('prose.txt', proseText);
|
|
134
|
+
if (!prose.ok) reds.push(`signature: ${prose.red}`);
|
|
135
|
+
const declaration = canonicalBytes('declaration.json', declarationText);
|
|
136
|
+
if (!declaration.ok) reds.push(`signature: ${declaration.red}`);
|
|
137
|
+
|
|
138
|
+
if (reds.length > 0 || !prose.ok || !declaration.ok) return deepFreeze({ ok: false, reds });
|
|
139
|
+
|
|
140
|
+
const proseHash = hashHex(prose.bytes);
|
|
141
|
+
const declarationHash = hashHex(declaration.bytes);
|
|
142
|
+
const flowHash = computeFlowHash(proseHash, declarationHash, signedBy, signedAt);
|
|
143
|
+
|
|
144
|
+
return deepFreeze({
|
|
145
|
+
ok: true,
|
|
146
|
+
signature: {
|
|
147
|
+
version: 2,
|
|
148
|
+
algorithm: 'sha256',
|
|
149
|
+
files: { 'prose.txt': proseHash, 'declaration.json': declarationHash },
|
|
150
|
+
flow: flowHash,
|
|
151
|
+
signedBy,
|
|
152
|
+
signedAt,
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Verify a flow against its signature. Collects every red found — never
|
|
159
|
+
* throws, never stops at the first problem.
|
|
160
|
+
*
|
|
161
|
+
* @param {{proseText: unknown, declarationText: unknown, signature: unknown}} input
|
|
162
|
+
* @returns {VerifyFlowResult}
|
|
163
|
+
*/
|
|
164
|
+
export function verifyFlow({ proseText, declarationText, signature }) {
|
|
165
|
+
const reds = [];
|
|
166
|
+
|
|
167
|
+
if (typeof signature !== 'object' || signature === null || Array.isArray(signature)) {
|
|
168
|
+
return deepFreeze({ ok: false, reds: ['signature: signature must be an object'] });
|
|
169
|
+
}
|
|
170
|
+
/** @type {any} */
|
|
171
|
+
const sig = signature;
|
|
172
|
+
|
|
173
|
+
if (sig.version !== 2) {
|
|
174
|
+
reds.push(`signature: field "version" is unknown (expected 2, got ${JSON.stringify(sig.version)})`);
|
|
175
|
+
}
|
|
176
|
+
if (sig.algorithm !== 'sha256') {
|
|
177
|
+
reds.push(`signature: field "algorithm" is unknown (expected "sha256", got ${JSON.stringify(sig.algorithm)})`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const files = sig.files;
|
|
181
|
+
let filesOk = true;
|
|
182
|
+
if (typeof files !== 'object' || files === null || Array.isArray(files)) {
|
|
183
|
+
reds.push('signature: field "files" must be an object with "prose.txt" and "declaration.json"');
|
|
184
|
+
filesOk = false;
|
|
185
|
+
} else {
|
|
186
|
+
for (const name of KNOWN_FILES) {
|
|
187
|
+
if (!(name in files)) {
|
|
188
|
+
reds.push(`signature: field "files.${name}" is missing`);
|
|
189
|
+
filesOk = false;
|
|
190
|
+
} else if (typeof files[name] !== 'string' || !HEX64_RE.test(files[name])) {
|
|
191
|
+
reds.push(`signature: field "files.${name}" is not a valid sha256 hex digest`);
|
|
192
|
+
filesOk = false;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const extra = Object.keys(files).filter((k) => !KNOWN_FILES.includes(k));
|
|
196
|
+
if (extra.length > 0) {
|
|
197
|
+
reds.push(`signature: field "files" has unexpected entries: ${extra.join(', ')}`);
|
|
198
|
+
filesOk = false;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const signedByOk = typeof sig.signedBy === 'string' && sig.signedBy.trim().length > 0;
|
|
203
|
+
if (!signedByOk) {
|
|
204
|
+
reds.push('signature: field "signedBy" is required and must be a non-empty string');
|
|
205
|
+
}
|
|
206
|
+
const signedAtOk = typeof sig.signedAt === 'string' && ISO8601_RE.test(sig.signedAt);
|
|
207
|
+
if (!signedAtOk) {
|
|
208
|
+
reds.push('signature: field "signedAt" is required and must be an ISO-8601 string');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (typeof sig.flow !== 'string' || !HEX64_RE.test(sig.flow)) {
|
|
212
|
+
reds.push('signature: field "flow" is not a valid sha256 hex digest');
|
|
213
|
+
} else if (filesOk) {
|
|
214
|
+
const expectedFlow = computeFlowHash(files['prose.txt'], files['declaration.json'], sig.signedBy, sig.signedAt);
|
|
215
|
+
if (expectedFlow !== sig.flow) {
|
|
216
|
+
reds.push(
|
|
217
|
+
'signature: field "flow" does not match signedBy/signedAt/the file hashes — signature.json was changed after signing',
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (filesOk) {
|
|
223
|
+
const prose = canonicalBytes('prose.txt', proseText);
|
|
224
|
+
if (!prose.ok) {
|
|
225
|
+
reds.push(`signature: ${prose.red}`);
|
|
226
|
+
} else {
|
|
227
|
+
const found = hashHex(prose.bytes);
|
|
228
|
+
if (found !== files['prose.txt']) {
|
|
229
|
+
reds.push(
|
|
230
|
+
`signature: prose.txt does not match its signed hash (signed ${files['prose.txt'].slice(0, 12)}…, found ${found.slice(0, 12)}…)`,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const declaration = canonicalBytes('declaration.json', declarationText);
|
|
236
|
+
if (!declaration.ok) {
|
|
237
|
+
reds.push(`signature: ${declaration.red}`);
|
|
238
|
+
} else {
|
|
239
|
+
const found = hashHex(declaration.bytes);
|
|
240
|
+
if (found !== files['declaration.json']) {
|
|
241
|
+
reds.push(
|
|
242
|
+
`signature: declaration.json does not match its signed hash (signed ${files['declaration.json'].slice(0, 12)}…, found ${found.slice(0, 12)}…)`,
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (reds.length > 0) return deepFreeze({ ok: false, reds });
|
|
249
|
+
return deepFreeze({ ok: true });
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function deepFreeze(value) {
|
|
253
|
+
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
254
|
+
Object.freeze(value);
|
|
255
|
+
for (const key of Object.keys(value)) deepFreeze(value[key]);
|
|
256
|
+
}
|
|
257
|
+
return value;
|
|
258
|
+
}
|