@imolko/ultra-event-signature 0.2.0-beta → 0.4.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 +219 -10
  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 +65 -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,15 +166,147 @@ 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** (`templates/fact-key.yml`, spec 3): a reusable GitLab job
173
+ that builds and self-checks the bundle and, with `publish: true`, pushes it
174
+ as an OCI artifact and reports its manifest digest. Its self-test reproduces
175
+ the published vector with `publish: false` and needs no registry credentials.
101
176
 
102
177
  Both are delivery, not custody. They receive key material as arguments, never
103
178
  store it, and a valid bundle never grants the key any authority — the policy in
104
179
  [03 — trust policy](docs/spec/03-trust-policy.md) decides what a key may sign.
105
180
 
181
+ ## CI component for fact-keys
182
+
183
+ `templates/fact-key.yml` is a GitLab CI component that runs the publish step of
184
+ [07 §10](docs/spec/07-fact-key.md#10-emitter-pipeline) inside an emitter's
185
+ pipeline: it builds the bundle, re-runs the contract check a consumer will run,
186
+ optionally publishes the pair as an OCI artifact and reports the digests. It is
187
+ released with the package under the same tag (PJ-003), so the component and the
188
+ CLI that understands the format always travel together.
189
+
190
+ ### Include
191
+
192
+ ```yaml
193
+ include:
194
+ - component: $CI_SERVER_FQDN/imolko/ultra-stack/ultra-event-signature/fact-key@<tag>
195
+ inputs:
196
+ stage: deploy
197
+ library-package: "@imolko/ultra-event-signature@<tag>"
198
+ emitter: landlord
199
+ kid: landlord-2026a
200
+ source: landlord.imolko.com/tenants
201
+ types: com.nixailabs.landlord.v1.infra-provisioned,com.nixailabs.landlord.v1.infra-updated
202
+ # key-variable: FACT_KEY_PRIVATE_KEY
203
+ # registry-repository: "" # empty means $CI_REGISTRY_IMAGE
204
+ # publish: true
205
+ ```
206
+
207
+ ### Inputs
208
+
209
+ | Input | Required | Default | Meaning |
210
+ |---|---|---|---|
211
+ | `stage` | no | `deploy` | Stage that runs the job |
212
+ | `library-package` | **yes** | — | Exact npm spec or local tarball of the library |
213
+ | `emitter` | **yes** | — | Name the emitter publishes under |
214
+ | `kid` | **yes** | — | Key id, `^[A-Za-z0-9_.-]{1,128}$`; at most 119 when publishing (OCI tag limit) |
215
+ | `source` | **yes** | — | Frozen `source` the key signs for |
216
+ | `types` | **yes** | — | Comma-separated types, no wildcards |
217
+ | `key-variable` | no | `FACT_KEY_PRIVATE_KEY` | Name of the CI variable holding the PEM (multiline, base64 or a File variable) |
218
+ | `registry-repository` | no | `""` → `$CI_REGISTRY_IMAGE` | OCI repository to publish into |
219
+ | `publish` | no | `true` | Push the pair on a tag pipeline; `false` only leaves job artifacts |
220
+ | `oras-version` | no | `1.2.3` | `oras` release downloaded and verified against that release's checksums |
221
+ | `expected-document-sha256` | no | `""` | Pin the document digest; a mismatch fails the build |
222
+ | `expected-signature-hex` | no | `""` | Pin the raw signature in hex; used by the self-test |
223
+
224
+ `library-package` is also the version input of the component: the YAML fixes no
225
+ version of its own. Use the **exact spec of the same tag as the component**
226
+ (`fact-key@<tag>` with `@imolko/ultra-event-signature@<tag>`), or a local tarball
227
+ in the self-test. The repository publishes with `npm version` in memory, and the
228
+ tag points at the integration commit where `package.json` still says `0.0.0`, so
229
+ a default derived from the repository would not describe what was published.
230
+ `scripts/component.test.mjs` fails if the template pins a version or gives
231
+ `library-package` a default.
232
+
233
+ `types` is a comma-separated string because GitLab array inputs do not
234
+ interpolate reliably into `script`; the job splits it and passes one `--type` per
235
+ element.
236
+
237
+ ### The key variable
238
+
239
+ The job never receives the key as an input. `key-variable` names the CI variable
240
+ that holds the private key; the job copies it into a `mktemp -d` directory
241
+ outside the workspace, sets mode `0600` under `umask 077`, passes the file path
242
+ to the CLI and deletes the directory with a `trap`. The key is never printed,
243
+ never put on a command line and never lands in the artifacts; a missing or
244
+ empty variable stops the job with a message before the CLI runs.
245
+
246
+ GitLab requires a **masked** variable to be a single line with no spaces, so a
247
+ multiline PEM cannot be masked directly. The component accepts three forms:
248
+
249
+ - a multiline PEM (handy for local runs and this repository's self-test);
250
+ - a base64-encoded PEM on one line — the form to use for a `masked` and
251
+ `protected` variable (`base64 -w0 key.pem`);
252
+ - a GitLab **File** variable: the value is the path to the file that holds the
253
+ PEM, which the job copies into its temporary directory.
254
+
255
+ The test key from [04 §1](docs/spec/04-conformance.md#1-the-test-key) is publicly
256
+ known and only belongs in the component's self-test. This repository does **not**
257
+ configure it as a GitLab variable: the job rebuilds it from `testKey.pkcs8Hex` in
258
+ [the vector](vectors/fact-signature.v1.json) with
259
+ [`scripts/test-key-fixture.mjs`](scripts/test-key-fixture.mjs) and exports it
260
+ under the name `key-variable` points to. The self-test therefore travels with
261
+ the commit — no project setting to provision, nothing to leak, and it runs on a
262
+ fork. The component still reads it as a variable, which is the interface an
263
+ emitter uses; in an emitter's project that variable holds a real key and is
264
+ masked **and** protected. The job exits non-zero when `fact-key build`'s
265
+ self-check is not `verified`, so an unverified bundle never reaches the registry.
266
+
267
+ ### Publication, rotation and pinning
268
+
269
+ With `publish: true` the job runs only on a tag pipeline, as [07
270
+ §10](docs/spec/07-fact-key.md#10-emitter-pipeline) describes, and pushes
271
+ `fact-key.v1.json` and `fact-key.v1.sig` with the media types of [07
272
+ §2](docs/spec/07-fact-key.md#2-the-artifact) to
273
+ `<registry-repository>:fact-key-<kid>`, then reports the descriptor. `oras` is
274
+ downloaded from its official release and verified against the checksums that
275
+ release publishes, which protects the download, not the provenance of the
276
+ release: the version is pinned by `oras-version` and approved at review. A new key is
277
+ a new `kid` and therefore a new tag; **add-then-cut** rotation in
278
+ [03 §6](docs/spec/03-trust-policy.md#6-rotation-and-revocation) still applies, and
279
+ a `kid` is never reused for a different key.
280
+
281
+ Every run leaves `fact-key/fact-key.v1.json`, `fact-key.v1.sig` and
282
+ `digests.json` as job artifacts. `digests.json` carries `{kid, documentSha256,
283
+ fingerprintSha256, manifestDigest, package}`; with `publish: false`,
284
+ `manifestDigest` is `null`.
285
+
286
+ The consumer pins the **manifest digest** — the `manifestDigest` the job reports,
287
+ or `oras manifest fetch <repo>:fact-key-<kid> --descriptor` — together with the
288
+ bundle's `documentSha256` and `fingerprintSha256`, confirmed over a second
289
+ channel. Never pin the tag: a re-tag can move the name, not the digest already
290
+ reviewed. `oras` stamps a creation annotation on every push, so republishing the
291
+ same bundle under the same tag yields a different manifest digest; pin the digest
292
+ of the review that was actually approved. A consumer never fetches the bundle at
293
+ fact-verification time.
294
+
295
+ The component is consumed by tag from this repository. It is not published to
296
+ the GitLab CI/CD Catalog: that would require a `release:` job on a tag pipeline,
297
+ which this repository deliberately does not create.
298
+
299
+ ### `generate` is not a job
300
+
301
+ The component builds, verifies and publishes; it never creates key material. The
302
+ pair comes from `fact-key generate` run once per rotation, locally or on a
303
+ protected ref ([07 §10](docs/spec/07-fact-key.md#10-emitter-pipeline)), and the
304
+ private half is moved into the emitter's secret store by the operator. CI has no
305
+ step that generates or rotates keys ([PJ-003](docs/adr/PJ-003-fact-key-cli-componente-ci-producto-lockstep.md)).
306
+ The bundle this job publishes is delivery, not custody: it proves the key is the
307
+ one the emitter published and that the publisher holds the private half, and it
308
+ grants no authority beyond the consumer's policy.
309
+
106
310
  ## Why a separate package
107
311
 
108
312
  `@imolko/ultra-ddd` already has the two insertion points for event signing
@@ -131,17 +335,22 @@ emitters ──▶ @imolko/ultra-event-signature ◀── consumers
131
335
  | [06 — delivery](docs/spec/06-delivery.md) | slices, test-first plan, gates, definition of done |
132
336
  | [07 — the fact-key bundle](docs/spec/07-fact-key.md) | how an emitter publishes its public key, and how a consumer verifies the publication |
133
337
 
338
+ Delivery surfaces: the `fact-key` CLI in `bin/` (spec 2) and the GitLab CI
339
+ component in [`templates/fact-key.yml`](templates/fact-key.yml) (spec 3).
340
+
134
341
  Machine-readable vectors: [`vectors/fact-signature.v1.json`](vectors/fact-signature.v1.json)
135
342
  and [`vectors/fact-key.v1.json`](vectors/fact-key.v1.json).
136
343
 
137
344
  ## Status
138
345
 
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
144
- `node:crypto`.
346
+ **Waves A and B implemented.** `src/index.ts` exports the format constants,
347
+ `signFact`, `verifyFact`, the key-set and trust-policy parsers, the
348
+ interoperability helpers and the fact-key API (`signFactKey`,
349
+ `verifyFactKeyBundle`, `factKeyFingerprint`). The `fact-key` CLI ships under
350
+ `bin/` and the reusable CI component lives in `templates/fact-key.yml`; both are
351
+ released with the package (PJ-003). The wire format and its vectors are frozen,
352
+ and the package still has zero runtime dependencies — the only runtime import in
353
+ `dist-node/index.js` is `node:crypto`.
145
354
 
146
355
  The decisions this package serves are recorded in the store platform's project
147
356
  tier: `PJ-049` (a fact is trusted by the key that signed it) and `PJ-050`
@@ -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";