@imolko/ultra-event-signature 0.2.0-beta → 0.3.0-beta

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 (49) hide show
  1. package/README.md +84 -9
  2. package/bin/commands/build.mjs +119 -0
  3. package/bin/commands/generate.mjs +126 -0
  4. package/bin/commands/verify.mjs +70 -0
  5. package/bin/fact-key.mjs +75 -0
  6. package/bin/lib/constants.mjs +23 -0
  7. package/bin/lib/errors.mjs +25 -0
  8. package/bin/lib/help.mjs +84 -0
  9. package/bin/lib/io.mjs +130 -0
  10. package/bin/lib/keys.mjs +51 -0
  11. package/bin/lib/options.mjs +133 -0
  12. package/bin/lib/output.mjs +14 -0
  13. package/bin/lib/verify-options.mjs +31 -0
  14. package/dist-node/crypto.d.ts +8 -0
  15. package/dist-node/crypto.d.ts.map +1 -1
  16. package/dist-node/crypto.js +16 -0
  17. package/dist-node/crypto.js.map +1 -1
  18. package/dist-node/fact-key-bytes.d.ts +5 -0
  19. package/dist-node/fact-key-bytes.d.ts.map +1 -0
  20. package/dist-node/fact-key-bytes.js +37 -0
  21. package/dist-node/fact-key-bytes.js.map +1 -0
  22. package/dist-node/fact-key-digests.d.ts +8 -0
  23. package/dist-node/fact-key-digests.d.ts.map +1 -0
  24. package/dist-node/fact-key-digests.js +49 -0
  25. package/dist-node/fact-key-digests.js.map +1 -0
  26. package/dist-node/fact-key-document.d.ts +43 -0
  27. package/dist-node/fact-key-document.d.ts.map +1 -0
  28. package/dist-node/fact-key-document.js +138 -0
  29. package/dist-node/fact-key-document.js.map +1 -0
  30. package/dist-node/fact-key-verdict.d.ts +9 -0
  31. package/dist-node/fact-key-verdict.d.ts.map +1 -0
  32. package/dist-node/fact-key-verdict.js +13 -0
  33. package/dist-node/fact-key-verdict.js.map +1 -0
  34. package/dist-node/fact-key-verify.d.ts +12 -0
  35. package/dist-node/fact-key-verify.d.ts.map +1 -0
  36. package/dist-node/fact-key-verify.js +167 -0
  37. package/dist-node/fact-key-verify.js.map +1 -0
  38. package/dist-node/fact-key.d.ts +24 -0
  39. package/dist-node/fact-key.d.ts.map +1 -0
  40. package/dist-node/fact-key.js +145 -0
  41. package/dist-node/fact-key.js.map +1 -0
  42. package/dist-node/index.d.ts +9 -6
  43. package/dist-node/index.d.ts.map +1 -1
  44. package/dist-node/index.js +12 -6
  45. package/dist-node/index.js.map +1 -1
  46. package/dist-node/types.d.ts +77 -0
  47. package/dist-node/types.d.ts.map +1 -1
  48. package/docs/emitter-checklist.md +25 -4
  49. package/package.json +7 -2
package/README.md CHANGED
@@ -38,6 +38,78 @@ them can get them half-right. The only published derivation is
38
38
  entry point imports only `node:crypto`; the CLI lives in `bin/` and is imported
39
39
  by nothing in `dist-node/index.js`.
40
40
 
41
+ ## Fact-key bundle
42
+
43
+ An emitter publishes its public key as a **fact-key bundle**: a signed document
44
+ (`fact-key.v1.json`) and its detached 64-byte signature (`fact-key.v1.sig`). The
45
+ bundle proves the key is the one the emitter published and that the publisher
46
+ holds the private half ([07 §1](docs/spec/07-fact-key.md#1-why-a-bundle-at-all)).
47
+ The CLI under `bin/` produces and checks it; in this repository run it after
48
+ `npm run build` as `node bin/fact-key.mjs`, or as `fact-key` once the package is
49
+ installed.
50
+
51
+ ### `generate` — once per rotation, locally
52
+
53
+ ```sh
54
+ node bin/fact-key.mjs generate --kid landlord-2026a --out .keys
55
+ ```
56
+
57
+ Writes `.keys/landlord-2026a.private.pem` (PKCS#8, mode `0600`) and
58
+ `.keys/landlord-2026a.public.json`, then prints
59
+ `{kid, publicKeyJwk, fingerprintSha256, privateKeyPath}`. Keep `.keys` outside
60
+ the repository and the image. `--force` overwrites an existing pair.
61
+
62
+ ### `build` — document, signature and self-check
63
+
64
+ ```sh
65
+ node bin/fact-key.mjs build \
66
+ --emitter landlord \
67
+ --kid landlord-2026a \
68
+ --source landlord.imolko.com/tenants \
69
+ --type com.nixailabs.landlord.v1.infra-provisioned \
70
+ --type com.nixailabs.landlord.v1.infra-updated \
71
+ --key-file .keys/landlord-2026a.private.pem \
72
+ --out-dir dist/fact-key
73
+ ```
74
+
75
+ Writes `dist/fact-key/fact-key.v1.json` and `fact-key.v1.sig`, verifies the
76
+ result against `{source, types}` before writing, and prints
77
+ `{kid, documentSha256, fingerprintSha256}`. It exits `1` when the self-check is
78
+ not `verified`, so a pipeline cannot publish an unverified bundle.
79
+ Add `--expect-document-sha256` or `--expect-fingerprint-sha256` when the
80
+ reviewer already pinned them; a mismatch fails the same check.
81
+
82
+ ### `verify` — the reviewer's verdict
83
+
84
+ ```sh
85
+ node bin/fact-key.mjs verify \
86
+ --document dist/fact-key/fact-key.v1.json \
87
+ --signature dist/fact-key/fact-key.v1.sig \
88
+ --source landlord.imolko.com/tenants \
89
+ --type com.nixailabs.landlord.v1.infra-provisioned \
90
+ --type com.nixailabs.landlord.v1.infra-updated \
91
+ --expect-document-sha256 <sha256-hex> \
92
+ --expect-fingerprint-sha256 <sha256-hex>
93
+ ```
94
+
95
+ Prints one JSON verdict: `{kind: "verified", kid, documentSha256,
96
+ fingerprintSha256}` or `{kind: "rejected", reason, issues}`. Exit codes are `0`
97
+ for `verified`, `1` for `rejected` and `2` for a usage error.
98
+
99
+ ### Custody and pinning
100
+
101
+ The private key stays in the emitter's secret store or signing service: the CLI
102
+ receives its **path**, writes only into `--out-dir`, and never prints the private
103
+ key. `generate` creates key material once per rotation as a manual, protected
104
+ step; it is not the test seed from [04 §1](docs/spec/04-conformance.md#1-the-test-key),
105
+ which is public and must never reach production.
106
+
107
+ The consumer pins the **digest of the OCI manifest** that carries the bundle and
108
+ the bundle's `fingerprintSha256` ([07 §8](docs/spec/07-fact-key.md#8-publication)),
109
+ confirming the fingerprint over a second channel. Verification is offline: a
110
+ consumer never fetches the bundle at fact-verification time. A verified bundle is
111
+ evidence for the reviewed key-set change; it grants the key no authority.
112
+
41
113
  ## Interoperability helpers
42
114
 
43
115
  Two helpers convert a fact into the shapes the rest of the ecosystem speaks,
@@ -94,10 +166,11 @@ used in a production key set, policy or image.
94
166
 
95
167
  ## Delivery tools
96
168
 
97
- - **CLI** under `bin/` (spec 2): builds, signs, verifies and fingerprints a
98
- fact-key bundle, and reports the document digest and the key fingerprint.
99
- - **CI component** (spec 3): wraps the CLI in a reusable pipeline job. Its
100
- self-test accepts the published vector and rejects a mutated bundle.
169
+ - **CLI** under `bin/` (spec 2): `generate`, `build` and `verify` — the flow
170
+ above. It reports the document digest and the key fingerprint and writes the
171
+ two bundle files.
172
+ - **CI component** (spec 3): wraps `fact-key build` in a reusable pipeline job.
173
+ Its self-test accepts the published vector and rejects a mutated bundle.
101
174
 
102
175
  Both are delivery, not custody. They receive key material as arguments, never
103
176
  store it, and a valid bundle never grants the key any authority — the policy in
@@ -136,11 +209,13 @@ and [`vectors/fact-key.v1.json`](vectors/fact-key.v1.json).
136
209
 
137
210
  ## Status
138
211
 
139
- **Wave A implemented.** `src/index.ts` exports the format constants, `signFact`,
140
- `verifyFact`, the key-set and trust-policy parsers, and the interoperability
141
- helpers. The fact-key bundle, its CLI under `bin/` and the reusable CI component
142
- land in the next two specs. The wire format and its vectors are frozen, and the
143
- package still has zero runtime dependencies — the only runtime import is
212
+ **Waves A and B implemented.** `src/index.ts` exports the format constants,
213
+ `signFact`, `verifyFact`, the key-set and trust-policy parsers, the
214
+ interoperability helpers and the fact-key API (`signFactKey`,
215
+ `verifyFactKeyBundle`, `factKeyFingerprint`). The `fact-key` CLI ships under
216
+ `bin/`; the reusable CI component is the remaining spec (spec 3). The wire
217
+ format and its vectors are frozen, and the package still has zero runtime
218
+ dependencies — the only runtime import in `dist-node/index.js` is
144
219
  `node:crypto`.
145
220
 
146
221
  The decisions this package serves are recorded in the store platform's project
@@ -0,0 +1,119 @@
1
+ import { resolve } from "node:path";
2
+ import process from "node:process";
3
+
4
+ import { signFactKey, verifyFactKeyBundle } from "../../dist-node/index.js";
5
+ import { EXIT_OK } from "../lib/constants.mjs";
6
+ import { OperationError, UsageError } from "../lib/errors.mjs";
7
+ import { BUILD_HELP } from "../lib/help.mjs";
8
+ import { readPrivateKey, writeBundle } from "../lib/io.mjs";
9
+ import { publicJwkOfPrivate } from "../lib/keys.mjs";
10
+ import {
11
+ parseOptions,
12
+ required,
13
+ requiredOption,
14
+ } from "../lib/options.mjs";
15
+ import { printJson } from "../lib/output.mjs";
16
+ import { verifyOptionsOf } from "../lib/verify-options.mjs";
17
+
18
+ /**
19
+ * Subcomando `build`: construye, firma y autoverifica el bundle (07 §10).
20
+ *
21
+ * La API aplica todas las reglas del documento; la CLI solo traduce archivos y
22
+ * argumentos. El bundle se escribe únicamente después de que el autoveredicto
23
+ * es `verified`, de modo que un fallo no deja un par a medias.
24
+ */
25
+
26
+ /** Parsea las opciones de `build` y resuelve las rutas. */
27
+ function parseBuildArgs(args) {
28
+ const { values, multi } = parseOptions(args, {
29
+ values: [
30
+ "emitter",
31
+ "kid",
32
+ "source",
33
+ "key-file",
34
+ "out-dir",
35
+ "expect-document-sha256",
36
+ "expect-fingerprint-sha256",
37
+ ],
38
+ multi: ["type"],
39
+ });
40
+
41
+ const types = multi["type"] ?? [];
42
+ if (types.length === 0) {
43
+ throw new UsageError("falta al menos una opción --type");
44
+ }
45
+
46
+ return {
47
+ emitter: requiredOption(values, "emitter"),
48
+ kid: requiredOption(values, "kid"),
49
+ source: requiredOption(values, "source"),
50
+ types,
51
+ keyFile: resolve(required(values, "key-file")),
52
+ outDir: resolve(required(values, "out-dir")),
53
+ expect: {
54
+ documentSha256: values["expect-document-sha256"],
55
+ fingerprintSha256: values["expect-fingerprint-sha256"],
56
+ },
57
+ };
58
+ }
59
+
60
+ /** Firma los miembros con la privada o falla si el documento es inválido. */
61
+ function signedBundleOf(members, privateKey) {
62
+ const signed = signFactKey(members, privateKey);
63
+ if (signed.kind !== "signed") {
64
+ throw new OperationError(
65
+ `documento inválido: ${signed.issues.join(", ")}`,
66
+ );
67
+ }
68
+ return signed;
69
+ }
70
+
71
+ /** Autoverifica el bundle recién firmado y falla si no da `verified`. */
72
+ function autocheck({ signed, options }) {
73
+ const verdict = verifyFactKeyBundle(
74
+ {
75
+ documentBytes: signed.documentBytes,
76
+ signature: signed.signature,
77
+ },
78
+ options,
79
+ );
80
+ if (verdict.kind !== "verified") {
81
+ throw new OperationError(
82
+ `autoverificación ${verdict.reason}: ${verdict.issues.join(", ")}`,
83
+ );
84
+ }
85
+ return verdict;
86
+ }
87
+
88
+ /** Ejecuta `build` y devuelve el código de salida. */
89
+ export function runBuild(args) {
90
+ if (args.includes("--help") || args.includes("-h")) {
91
+ process.stdout.write(BUILD_HELP);
92
+ return EXIT_OK;
93
+ }
94
+
95
+ const { emitter, kid, source, types, keyFile, outDir, expect } =
96
+ parseBuildArgs(args);
97
+ const privateKey = readPrivateKey(keyFile);
98
+ const publicKeyJwk = publicJwkOfPrivate(privateKey);
99
+ const signed = signedBundleOf(
100
+ { emitter, kid, source, types, publicKeyJwk },
101
+ privateKey,
102
+ );
103
+ const verdict = autocheck({
104
+ signed,
105
+ options: verifyOptionsOf(expect, { source, types }),
106
+ });
107
+
108
+ writeBundle({
109
+ outDir,
110
+ documentBytes: signed.documentBytes,
111
+ signature: signed.signature,
112
+ });
113
+ printJson({
114
+ kid: verdict.kid,
115
+ documentSha256: verdict.documentSha256,
116
+ fingerprintSha256: verdict.fingerprintSha256,
117
+ });
118
+ return EXIT_OK;
119
+ }
@@ -0,0 +1,126 @@
1
+ import { generateKeyPairSync } from "node:crypto";
2
+ import { existsSync, mkdirSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import process from "node:process";
5
+
6
+ import { factKeyFingerprint } from "../../dist-node/index.js";
7
+ import { EXIT_OK, KID_PATTERN } from "../lib/constants.mjs";
8
+ import { OperationError, UsageError, messageOf } from "../lib/errors.mjs";
9
+ import { GENERATE_HELP } from "../lib/help.mjs";
10
+ import { writePrivateFile, writePublicFile } from "../lib/io.mjs";
11
+ import { publicJwkOf } from "../lib/keys.mjs";
12
+ import { parseOptions, required } from "../lib/options.mjs";
13
+ import { printJson } from "../lib/output.mjs";
14
+
15
+ /**
16
+ * Subcomando `generate`: crea la pareja Ed25519 y escribe los dos archivos.
17
+ *
18
+ * La generación es manual y protegida (07 §10). La clave privada se escribe en
19
+ * modo `0600` y nunca se imprime; el JSON de stdout solo lleva la mitad
20
+ * pública, su fingerprint y la ruta donde quedó la privada.
21
+ */
22
+
23
+ /** Parsea `--kid`, `--out` y `--force`. */
24
+ function parseGenerateArgs(args) {
25
+ const { values, flags } = parseOptions(args, {
26
+ values: ["kid", "out"],
27
+ flags: ["force"],
28
+ });
29
+ return {
30
+ kid: required(values, "kid"),
31
+ out: required(values, "out"),
32
+ force: flags.has("force"),
33
+ };
34
+ }
35
+
36
+ /** Genera una pareja Ed25519 o falla como error de operación. */
37
+ function createPair() {
38
+ try {
39
+ return generateKeyPairSync("ed25519");
40
+ } catch (error) {
41
+ throw new OperationError(
42
+ `no se pudo generar la pareja Ed25519: ${messageOf(error)}`,
43
+ );
44
+ }
45
+ }
46
+
47
+ /** Exporta la mitad privada en PKCS#8 PEM sin imprimirla. */
48
+ function privatePemOf(pair) {
49
+ try {
50
+ return pair.privateKey.export({ type: "pkcs8", format: "pem" });
51
+ } catch (error) {
52
+ throw new OperationError(
53
+ `no se pudo exportar la clave privada: ${messageOf(error)}`,
54
+ );
55
+ }
56
+ }
57
+
58
+ /** Falla si la pareja ya existe y no se pidió `--force`. */
59
+ function assertPairAbsent(paths, force) {
60
+ if (force) {
61
+ return;
62
+ }
63
+ const existing = paths.find((path) => existsSync(path));
64
+ if (existing !== undefined) {
65
+ throw new OperationError(
66
+ `ya existe ${existing}; usa --force para sobrescribir`,
67
+ );
68
+ }
69
+ }
70
+
71
+ /** Calcula el fingerprint del JWK o falla como error de operación. */
72
+ function fingerprintOf(publicKeyJwk) {
73
+ const fingerprint = factKeyFingerprint(publicKeyJwk);
74
+ if (fingerprint.kind !== "parsed") {
75
+ throw new OperationError(
76
+ `la clave pública generada no produce fingerprint: ${fingerprint.issues.join(", ")}`,
77
+ );
78
+ }
79
+ return fingerprint.value;
80
+ }
81
+
82
+ /** Crea el directorio de salida o falla como error de operación. */
83
+ function ensureDirectory(outDir) {
84
+ try {
85
+ mkdirSync(outDir, { recursive: true });
86
+ } catch (error) {
87
+ throw new OperationError(
88
+ `no se pudo crear ${outDir}: ${messageOf(error)}`,
89
+ );
90
+ }
91
+ }
92
+
93
+ /** Ejecuta `generate` y devuelve el código de salida. */
94
+ export function runGenerate(args) {
95
+ if (args.includes("--help") || args.includes("-h")) {
96
+ process.stdout.write(GENERATE_HELP);
97
+ return EXIT_OK;
98
+ }
99
+
100
+ const { kid, out, force } = parseGenerateArgs(args);
101
+ if (!KID_PATTERN.test(kid)) {
102
+ throw new UsageError(
103
+ `kid inválido: ${JSON.stringify(kid)}; debe cumplir ${KID_PATTERN}`,
104
+ );
105
+ }
106
+
107
+ const privateKeyPath = join(resolve(out), `${kid}.private.pem`);
108
+ const publicKeyPath = join(resolve(out), `${kid}.public.json`);
109
+ assertPairAbsent([privateKeyPath, publicKeyPath], force);
110
+ ensureDirectory(resolve(out));
111
+
112
+ const pair = createPair();
113
+ const publicKeyJwk = publicJwkOf(pair.publicKey);
114
+ const fingerprintSha256 = fingerprintOf(publicKeyJwk);
115
+ const privatePem = privatePemOf(pair);
116
+
117
+ writePrivateFile({ path: privateKeyPath, contents: privatePem, force });
118
+ writePublicFile({
119
+ path: publicKeyPath,
120
+ contents: `${JSON.stringify(publicKeyJwk)}\n`,
121
+ force,
122
+ });
123
+
124
+ printJson({ kid, publicKeyJwk, fingerprintSha256, privateKeyPath });
125
+ return EXIT_OK;
126
+ }
@@ -0,0 +1,70 @@
1
+ import { resolve } from "node:path";
2
+ import process from "node:process";
3
+
4
+ import { verifyFactKeyBundle } from "../../dist-node/index.js";
5
+ import { EXIT_FAILED, EXIT_OK } from "../lib/constants.mjs";
6
+ import { UsageError } from "../lib/errors.mjs";
7
+ import { VERIFY_HELP } from "../lib/help.mjs";
8
+ import { readRequiredFile } from "../lib/io.mjs";
9
+ import { parseOptions, required } from "../lib/options.mjs";
10
+ import { printJson } from "../lib/output.mjs";
11
+ import { verifyOptionsOf } from "../lib/verify-options.mjs";
12
+
13
+ /**
14
+ * Subcomando `verify`: presenta el veredicto de un bundle recibido (07 §6).
15
+ *
16
+ * La CLI solo lee los dos archivos y arma el bundle; el orden de los cinco
17
+ * pasos, el prefijo, el contrato y el fingerprint los decide la API. El código
18
+ * de salida traduce el veredicto sin obligar al pipeline a parsear prosa:
19
+ * 0 para `verified`, 1 para `rejected` y 2 para un error de uso.
20
+ */
21
+
22
+ /** Parsea las opciones de `verify` y resuelve las rutas. */
23
+ function parseVerifyArgs(args) {
24
+ const { values, multi } = parseOptions(args, {
25
+ values: [
26
+ "document",
27
+ "signature",
28
+ "source",
29
+ "expect-document-sha256",
30
+ "expect-fingerprint-sha256",
31
+ ],
32
+ multi: ["type"],
33
+ });
34
+
35
+ const types = multi["type"] ?? [];
36
+ if (types.length === 0) {
37
+ throw new UsageError("falta al menos una opción --type");
38
+ }
39
+
40
+ return {
41
+ documentPath: resolve(required(values, "document")),
42
+ signaturePath: resolve(required(values, "signature")),
43
+ source: required(values, "source"),
44
+ types,
45
+ expect: {
46
+ documentSha256: values["expect-document-sha256"],
47
+ fingerprintSha256: values["expect-fingerprint-sha256"],
48
+ },
49
+ };
50
+ }
51
+
52
+ /** Ejecuta `verify` y devuelve el código de salida del veredicto. */
53
+ export function runVerify(args) {
54
+ if (args.includes("--help") || args.includes("-h")) {
55
+ process.stdout.write(VERIFY_HELP);
56
+ return EXIT_OK;
57
+ }
58
+
59
+ const { documentPath, signaturePath, source, types, expect } =
60
+ parseVerifyArgs(args);
61
+ const documentBytes = readRequiredFile(documentPath, "el documento");
62
+ const signature = readRequiredFile(signaturePath, "la firma");
63
+ const verdict = verifyFactKeyBundle(
64
+ { documentBytes, signature },
65
+ verifyOptionsOf(expect, { source, types }),
66
+ );
67
+
68
+ printJson(verdict);
69
+ return verdict.kind === "verified" ? EXIT_OK : EXIT_FAILED;
70
+ }
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ import process from "node:process";
3
+
4
+ import { runBuild } from "./commands/build.mjs";
5
+ import { runGenerate } from "./commands/generate.mjs";
6
+ import { runVerify } from "./commands/verify.mjs";
7
+ import { EXIT_FAILED, EXIT_OK, EXIT_USAGE } from "./lib/constants.mjs";
8
+ import {
9
+ OperationError,
10
+ UsageError,
11
+ fail,
12
+ messageOf,
13
+ } from "./lib/errors.mjs";
14
+ import { USAGE } from "./lib/help.mjs";
15
+
16
+ /**
17
+ * CLI del bundle de clave pública `fact-key.v1` (07 §8, 07 §10).
18
+ *
19
+ * Es una herramienta de entrega, no de custodia: recibe rutas como argumentos,
20
+ * escribe solo en el directorio que se le indica y nunca imprime el contenido
21
+ * de la clave privada. Vive en `bin/`, fuera del entry point puro de la
22
+ * librería (02 §3), y usa `dist-node` ya construido.
23
+ *
24
+ * Códigos de salida: 0 éxito, 1 operación fallida, 2 uso incorrecto.
25
+ */
26
+
27
+ const COMMANDS = new Map([
28
+ ["generate", runGenerate],
29
+ ["build", runBuild],
30
+ ["verify", runVerify],
31
+ ]);
32
+
33
+ /** Resuelve el subcomando y lo ejecuta. */
34
+ function dispatch(command, args) {
35
+ if (command === "--help" || command === "-h" || command === "help") {
36
+ process.stdout.write(USAGE);
37
+ return EXIT_OK;
38
+ }
39
+ if (command === undefined) {
40
+ throw new UsageError("falta el subcomando");
41
+ }
42
+
43
+ const run = COMMANDS.get(command);
44
+ if (run === undefined) {
45
+ throw new UsageError(`subcomando desconocido: ${command}`);
46
+ }
47
+ return run(args);
48
+ }
49
+
50
+ /** Traduce un error a su código de salida y a un mensaje por stderr. */
51
+ function report(error) {
52
+ if (error instanceof UsageError) {
53
+ fail(error.message);
54
+ process.stderr.write(`\n${USAGE}`);
55
+ return EXIT_USAGE;
56
+ }
57
+ if (error instanceof OperationError) {
58
+ fail(error.message);
59
+ return EXIT_FAILED;
60
+ }
61
+ fail(messageOf(error));
62
+ return EXIT_FAILED;
63
+ }
64
+
65
+ /** Despacha el subcomando y traduce errores a códigos de salida. */
66
+ function main(argv) {
67
+ const [command, ...args] = argv;
68
+ try {
69
+ return dispatch(command, args);
70
+ } catch (error) {
71
+ return report(error);
72
+ }
73
+ }
74
+
75
+ process.exitCode = main(process.argv.slice(2));
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Constantes compartidas de la CLI `fact-key` (07 §2, 07 §10).
3
+ *
4
+ * Los códigos de salida traducen el resultado para el pipeline: 0 éxito, 1
5
+ * operación fallida y 2 uso incorrecto (02 §8). Los nombres de archivo son los
6
+ * del bundle v1 y no se negocian con el consumidor.
7
+ */
8
+
9
+ export const EXIT_OK = 0;
10
+ export const EXIT_FAILED = 1;
11
+ export const EXIT_USAGE = 2;
12
+
13
+ /**
14
+ * Forma canónica de un `kid` (03 §1), copia de `src/patterns.ts`.
15
+ *
16
+ * La CLI se ejecuta como JavaScript sobre `dist-node`, así que no puede leer el
17
+ * patrón del paquete: la copia es deliberada y se comprueba en `generate` antes
18
+ * de construir una ruta de archivo, no como validación del documento (esa vive
19
+ * en la API). Si el patrón cambia, cambian los dos.
20
+ */
21
+ export const KID_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;
22
+ export const DOCUMENT_NAME = "fact-key.v1.json";
23
+ export const SIGNATURE_NAME = "fact-key.v1.sig";
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Errores de la CLI y su presentación por stderr.
3
+ *
4
+ * La distinción es la del código de salida: un error de uso no llegó a operar
5
+ * (2) y un error de operación recibió material que no pudo procesar (1). El
6
+ * mensaje nunca incluye la clave privada ni el contenido de los archivos.
7
+ */
8
+
9
+ import process from "node:process";
10
+
11
+ /** Error de uso: se reporta con el código 2 y la ayuda. */
12
+ export class UsageError extends Error {}
13
+
14
+ /** Error de operación: se reporta con el código 1. */
15
+ export class OperationError extends Error {}
16
+
17
+ /** Extrae un mensaje sin volcar el objeto de error completo. */
18
+ export function messageOf(error) {
19
+ return error instanceof Error ? error.message : String(error);
20
+ }
21
+
22
+ /** Escribe un mensaje en stderr sin exponer material de clave. */
23
+ export function fail(message) {
24
+ process.stderr.write(`fact-key: ${message}\n`);
25
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Textos de ayuda de la CLI `fact-key` (07 §10).
3
+ *
4
+ * La ayuda es parte del contrato de uso: nombra las opciones obligatorias, los
5
+ * archivos que cada comando escribe y los códigos de salida. Vive separada del
6
+ * despacho para que `--help` no dependa del parser.
7
+ */
8
+
9
+ export const USAGE = `Uso: fact-key <comando> [opciones]
10
+
11
+ Comandos:
12
+ generate genera una pareja Ed25519 y reporta la clave pública
13
+ build construye, firma y autoverifica un bundle fact-key
14
+ verify verifica un bundle recibido y presenta el veredicto
15
+ --help muestra esta ayuda
16
+
17
+ Ejecuta "fact-key <comando> --help" para las opciones de cada comando.
18
+ `;
19
+
20
+ export const GENERATE_HELP = `Uso: fact-key generate --kid <kid> --out <dir> [--force]
21
+
22
+ Genera una pareja Ed25519 y escribe:
23
+ <dir>/<kid>.private.pem clave privada PKCS#8 en modo 0600
24
+ <dir>/<kid>.public.json JWK público (kty, crv, x, use, alg)
25
+
26
+ Opciones:
27
+ --kid <kid> identificador de la clave; ^[A-Za-z0-9_.-]{1,128}$
28
+ --out <dir> directorio donde escribir la pareja
29
+ --force sobrescribe una pareja existente
30
+ --help muestra esta ayuda
31
+
32
+ Imprime por stdout {kid, publicKeyJwk, fingerprintSha256, privateKeyPath} y
33
+ nunca imprime la clave privada. La generación es manual y protegida: mueve la
34
+ mitad privada a tu almacén de secretos y no la publiques.
35
+ `;
36
+
37
+ export const BUILD_HELP = `Uso: fact-key build --emitter <e> --kid <k> --source <s> --type <t>... \
38
+ --key-file <priv> --out-dir <dir> \
39
+ [--expect-document-sha256 <hex>] [--expect-fingerprint-sha256 <hex>]
40
+
41
+ Construye el documento de 07 §3, lo firma con la clave privada recibida y
42
+ verifica el resultado con el contrato {source, types} antes de escribir nada.
43
+
44
+ Escribe:
45
+ <dir>/fact-key.v1.json los bytes exactos firmados
46
+ <dir>/fact-key.v1.sig la firma Ed25519 detached de 64 bytes
47
+
48
+ Opciones:
49
+ --emitter <e> nombre público del emisor
50
+ --kid <k> identificador de la clave
51
+ --source <s> source congelado que la clave firma
52
+ --type <t> type que la clave puede firmar; repetible
53
+ --key-file <priv> clave privada Ed25519 en PKCS#8
54
+ --out-dir <dir> directorio donde escribir el bundle
55
+ --expect-document-sha256 <hex> digest que el revisor fijó, si existe
56
+ --expect-fingerprint-sha256 <hex> fingerprint que el revisor fijó, si existe
57
+ --help muestra esta ayuda
58
+
59
+ Imprime por stdout {kid, documentSha256, fingerprintSha256}. Si el autoveredicto
60
+ no es "verified", no escribe archivos y sale con 1. La clave privada nunca se
61
+ imprime ni se incluye en el bundle.
62
+ `;
63
+
64
+ export const VERIFY_HELP = `Uso: fact-key verify --document <file> --signature <file> \
65
+ --source <s> --type <t>... \
66
+ [--expect-document-sha256 <hex>] [--expect-fingerprint-sha256 <hex>]
67
+
68
+ Verifica un bundle recibido con el contrato congelado {source, types} y, si el
69
+ revisor los fijó, el digest del documento y el fingerprint de la clave. Lee el
70
+ documento y la firma como bytes, sin normalizar, y delega el orden de 07 §6 en
71
+ la API: la CLI no reimplementa la verificación.
72
+
73
+ Opciones:
74
+ --document <file> fact-key.v1.json recibido
75
+ --signature <file> fact-key.v1.sig recibido
76
+ --source <s> source congelado que el consumidor espera
77
+ --type <t> type congelado; repetible
78
+ --expect-document-sha256 <hex> digest que el revisor fijó, si existe
79
+ --expect-fingerprint-sha256 <hex> fingerprint que el revisor fijó, si existe
80
+ --help muestra esta ayuda
81
+
82
+ Imprime por stdout el veredicto completo como JSON. Sale con 0 solo para
83
+ "verified" y con 1 para un bundle rechazado, incluido un fallo de estructura.
84
+ `;