@imolko/ultra-event-signature 0.1.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.
- package/README.md +178 -7
- package/bin/commands/build.mjs +119 -0
- package/bin/commands/generate.mjs +126 -0
- package/bin/commands/verify.mjs +70 -0
- package/bin/fact-key.mjs +75 -0
- package/bin/lib/constants.mjs +23 -0
- package/bin/lib/errors.mjs +25 -0
- package/bin/lib/help.mjs +84 -0
- package/bin/lib/io.mjs +130 -0
- package/bin/lib/keys.mjs +51 -0
- package/bin/lib/options.mjs +133 -0
- package/bin/lib/output.mjs +14 -0
- package/bin/lib/verify-options.mjs +31 -0
- package/dist-node/canonical-json.d.ts +10 -0
- package/dist-node/canonical-json.d.ts.map +1 -0
- package/dist-node/canonical-json.js +148 -0
- package/dist-node/canonical-json.js.map +1 -0
- package/dist-node/crypto.d.ts +34 -0
- package/dist-node/crypto.d.ts.map +1 -0
- package/dist-node/crypto.js +64 -0
- package/dist-node/crypto.js.map +1 -0
- package/dist-node/dsse.d.ts +11 -0
- package/dist-node/dsse.d.ts.map +1 -0
- package/dist-node/dsse.js +67 -0
- package/dist-node/dsse.js.map +1 -0
- package/dist-node/errors.d.ts +26 -0
- package/dist-node/errors.d.ts.map +1 -0
- package/dist-node/errors.js +52 -0
- package/dist-node/errors.js.map +1 -0
- package/dist-node/fact-key-bytes.d.ts +5 -0
- package/dist-node/fact-key-bytes.d.ts.map +1 -0
- package/dist-node/fact-key-bytes.js +37 -0
- package/dist-node/fact-key-bytes.js.map +1 -0
- package/dist-node/fact-key-digests.d.ts +8 -0
- package/dist-node/fact-key-digests.d.ts.map +1 -0
- package/dist-node/fact-key-digests.js +49 -0
- package/dist-node/fact-key-digests.js.map +1 -0
- package/dist-node/fact-key-document.d.ts +43 -0
- package/dist-node/fact-key-document.d.ts.map +1 -0
- package/dist-node/fact-key-document.js +138 -0
- package/dist-node/fact-key-document.js.map +1 -0
- package/dist-node/fact-key-verdict.d.ts +9 -0
- package/dist-node/fact-key-verdict.d.ts.map +1 -0
- package/dist-node/fact-key-verdict.js +13 -0
- package/dist-node/fact-key-verdict.js.map +1 -0
- package/dist-node/fact-key-verify.d.ts +12 -0
- package/dist-node/fact-key-verify.d.ts.map +1 -0
- package/dist-node/fact-key-verify.js +167 -0
- package/dist-node/fact-key-verify.js.map +1 -0
- package/dist-node/fact-key.d.ts +24 -0
- package/dist-node/fact-key.d.ts.map +1 -0
- package/dist-node/fact-key.js +145 -0
- package/dist-node/fact-key.js.map +1 -0
- package/dist-node/index.d.ts +18 -8
- package/dist-node/index.d.ts.map +1 -1
- package/dist-node/index.js +28 -9
- package/dist-node/index.js.map +1 -1
- package/dist-node/key-set.d.ts +9 -0
- package/dist-node/key-set.d.ts.map +1 -0
- package/dist-node/key-set.js +120 -0
- package/dist-node/key-set.js.map +1 -0
- package/dist-node/pae.d.ts +18 -0
- package/dist-node/pae.d.ts.map +1 -0
- package/dist-node/pae.js +30 -0
- package/dist-node/pae.js.map +1 -0
- package/dist-node/patterns.d.ts +13 -0
- package/dist-node/patterns.d.ts.map +1 -0
- package/dist-node/patterns.js +16 -0
- package/dist-node/patterns.js.map +1 -0
- package/dist-node/payload-type.d.ts +10 -0
- package/dist-node/payload-type.d.ts.map +1 -0
- package/dist-node/payload-type.js +49 -0
- package/dist-node/payload-type.js.map +1 -0
- package/dist-node/policy-evaluation.d.ts +34 -0
- package/dist-node/policy-evaluation.d.ts.map +1 -0
- package/dist-node/policy-evaluation.js +121 -0
- package/dist-node/policy-evaluation.js.map +1 -0
- package/dist-node/policy.d.ts +13 -0
- package/dist-node/policy.d.ts.map +1 -0
- package/dist-node/policy.js +156 -0
- package/dist-node/policy.js.map +1 -0
- package/dist-node/sign.d.ts +13 -0
- package/dist-node/sign.d.ts.map +1 -0
- package/dist-node/sign.js +94 -0
- package/dist-node/sign.js.map +1 -0
- package/dist-node/types.d.ts +199 -0
- package/dist-node/types.d.ts.map +1 -0
- package/dist-node/types.js +3 -0
- package/dist-node/types.js.map +1 -0
- package/dist-node/verify.d.ts +10 -0
- package/dist-node/verify.d.ts.map +1 -0
- package/dist-node/verify.js +171 -0
- package/dist-node/verify.js.map +1 -0
- package/docs/emitter-checklist.md +141 -0
- package/package.json +16 -5
package/README.md
CHANGED
|
@@ -22,6 +22,160 @@ Custody never enters this package: private keys and key sets arrive as arguments
|
|
|
22
22
|
A library that can read a key from disk or from the environment is a library that
|
|
23
23
|
will.
|
|
24
24
|
|
|
25
|
+
## Public surface
|
|
26
|
+
|
|
27
|
+
| Export | Status |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `SIGNATURE_FORMAT_VERSION`, `DSSE_PREAMBLE`, `SIGNATURE_ALGORITHM`, `PAE_DIGEST_ALGORITHM` | exported |
|
|
30
|
+
| `signFact`, `verifyFact` | spec 1, S2 |
|
|
31
|
+
| `parseKeySet`, `parseTrustPolicy` | spec 1, S3 |
|
|
32
|
+
| `factPayloadType`, `toDsseEnvelope` | spec 1, S4 |
|
|
33
|
+
| `signFactKey`, `verifyFactKeyBundle`, `factKeyFingerprint` | spec 2, S6 |
|
|
34
|
+
|
|
35
|
+
The canonical JSON and the PAE are internal on purpose: a consumer that can call
|
|
36
|
+
them can get them half-right. The only published derivation is
|
|
37
|
+
`factPayloadType`, which returns the `payloadType` the format signs. The pure
|
|
38
|
+
entry point imports only `node:crypto`; the CLI lives in `bin/` and is imported
|
|
39
|
+
by nothing in `dist-node/index.js`.
|
|
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
|
+
|
|
113
|
+
## Interoperability helpers
|
|
114
|
+
|
|
115
|
+
Two helpers convert a fact into the shapes the rest of the ecosystem speaks,
|
|
116
|
+
without turning the converter into a verdict:
|
|
117
|
+
|
|
118
|
+
- `factPayloadType(envelope)` derives
|
|
119
|
+
`application/vnd.nixailabs.fact.<type>.<dataVersion>+json`, where `dataVersion`
|
|
120
|
+
is the last path segment of `dataschema`. A missing `type`/`dataschema`, an
|
|
121
|
+
empty version or a version containing `?`/`#` is `invalid`.
|
|
122
|
+
- `toDsseEnvelope(signed)` emits the DSSE statement of [05 §6](docs/spec/05-integration.md):
|
|
123
|
+
`payload` is base64 **standard** of the canonical covered content and `sig` is
|
|
124
|
+
base64 **standard** of the same 64 signature bytes. It does not verify the
|
|
125
|
+
signature, consult the key set or evaluate the policy.
|
|
126
|
+
|
|
127
|
+
Both return a flat `ParseResult` (`{ kind: 'parsed', value }` or
|
|
128
|
+
`{ kind: 'invalid', issues }`) and never throw.
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
import { factPayloadType, toDsseEnvelope } from "@imolko/ultra-event-signature";
|
|
132
|
+
|
|
133
|
+
const payloadType = factPayloadType(signedEnvelope);
|
|
134
|
+
if (payloadType.kind === "parsed") {
|
|
135
|
+
console.log(payloadType.value);
|
|
136
|
+
// application/vnd.nixailabs.fact.com.example.v1.ping.1.0.0+json
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const dsse = toDsseEnvelope(signedEnvelope);
|
|
140
|
+
if (dsse.kind === "parsed") {
|
|
141
|
+
console.log(dsse.value.signatures[0].keyid); // securityKeyId
|
|
142
|
+
console.log(dsse.value.payload); // base64(canonicalJson(covered))
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Because the payload and the signature are the ones the fact already carries,
|
|
147
|
+
stock DSSE tooling, `cosign` and a transparency log consume a fact without a
|
|
148
|
+
custom verifier.
|
|
149
|
+
|
|
150
|
+
## Emitter kit
|
|
151
|
+
|
|
152
|
+
The flow an emitter needs before its first production fact is written down so it
|
|
153
|
+
can be handed over without the surrounding conversation:
|
|
154
|
+
|
|
155
|
+
- [**Emitter checklist**](docs/emitter-checklist.md) — the ten items of
|
|
156
|
+
[05 §1](docs/spec/05-integration.md#1-the-emitter-kit), the integer-only rule
|
|
157
|
+
for `data`, add-then-cut rotation and the custody warning.
|
|
158
|
+
- [**Runnable signer**](examples/emitter-sign.mjs) — signs the `minimal-ping`
|
|
159
|
+
vector, verifies it against a test key set and policy, and prints the verdict,
|
|
160
|
+
the `securityKeyId` and the signature. Run it after `npm run build` with
|
|
161
|
+
`npm run example:sign`.
|
|
162
|
+
|
|
163
|
+
The signer uses the test key from [04 §1](docs/spec/04-conformance.md#1-the-test-key).
|
|
164
|
+
That key is **publicly known**: it exists to compare bytes and must never be
|
|
165
|
+
used in a production key set, policy or image.
|
|
166
|
+
|
|
167
|
+
## Delivery tools
|
|
168
|
+
|
|
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.
|
|
174
|
+
|
|
175
|
+
Both are delivery, not custody. They receive key material as arguments, never
|
|
176
|
+
store it, and a valid bundle never grants the key any authority — the policy in
|
|
177
|
+
[03 — trust policy](docs/spec/03-trust-policy.md) decides what a key may sign.
|
|
178
|
+
|
|
25
179
|
## Why a separate package
|
|
26
180
|
|
|
27
181
|
`@imolko/ultra-ddd` already has the two insertion points for event signing
|
|
@@ -55,16 +209,33 @@ and [`vectors/fact-key.v1.json`](vectors/fact-key.v1.json).
|
|
|
55
209
|
|
|
56
210
|
## Status
|
|
57
211
|
|
|
58
|
-
**
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
`
|
|
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
|
|
219
|
+
`node:crypto`.
|
|
220
|
+
|
|
221
|
+
The decisions this package serves are recorded in the store platform's project
|
|
222
|
+
tier: `PJ-049` (a fact is trusted by the key that signed it) and `PJ-050`
|
|
223
|
+
(Sentinel is the admission point and forwards the emitter's signature), in
|
|
224
|
+
`imolko/nixai-stores/generator` under `docs/adr/`. This repository keeps its own
|
|
225
|
+
project decisions in [docs/adr/](docs/adr/): [PJ-001](docs/adr/PJ-001-modulo-commonjs-libreria-desde-ultra-tsconfig.md)
|
|
226
|
+
(CommonJS build), [PJ-002](docs/adr/PJ-002-sin-capa-domain-release-fuera-del-paquete.md)
|
|
227
|
+
(no domain layer), [PJ-003](docs/adr/PJ-003-fact-key-cli-componente-ci-producto-lockstep.md)
|
|
228
|
+
(fact-key, CLI and CI component as product), [PJ-004](docs/adr/PJ-004-resultados-planos-sin-dependencias-runtime.md)
|
|
229
|
+
(flat results, zero runtime dependencies), [PJ-005](docs/adr/PJ-005-regla-tenencia-politica.md)
|
|
230
|
+
(the tenancy rule) and [PJ-006](docs/adr/PJ-006-orden-de-pasos-en-verifyfact.md)
|
|
231
|
+
(the key is resolved before the digest in `verifyFact`).
|
|
63
232
|
|
|
64
233
|
## Engineering rules
|
|
65
234
|
|
|
66
|
-
- Zero runtime dependencies. `node:crypto` only. Node
|
|
67
|
-
-
|
|
235
|
+
- Zero runtime dependencies. `node:crypto` only. Node 22.14+.
|
|
236
|
+
- The library entry point is pure: no I/O, no environment, no filesystem, no
|
|
237
|
+
network, no clock. The CLI is the only file-reading surface and lives outside
|
|
238
|
+
the built entry point's import graph.
|
|
68
239
|
- Deterministic: the same envelope and key produce the same signature bytes
|
|
69
240
|
(Ed25519 per RFC 8032), which is what makes the vectors assertable.
|
|
70
241
|
- Test-first. Every test carries `@name` / `@scenario` JSDoc.
|
|
@@ -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
|
+
}
|
package/bin/fact-key.mjs
ADDED
|
@@ -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
|
+
}
|