@mago-foundation/mago-ski 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +54 -9
  2. package/action.yml +2 -2
  3. package/dist/hosts/github/run.d.ts +9 -1
  4. package/dist/hosts/github/run.js +64 -11
  5. package/dist/hosts/pi/index.d.ts +5 -3
  6. package/dist/hosts/pi/index.js +219 -14
  7. package/dist/src/admin.d.ts +140 -1
  8. package/dist/src/admin.js +328 -63
  9. package/dist/src/canonical-json.js +73 -28
  10. package/dist/src/certificate.js +23 -15
  11. package/dist/src/cli.js +590 -89
  12. package/dist/src/diff.d.ts +0 -4
  13. package/dist/src/diff.js +326 -70
  14. package/dist/src/dsse.d.ts +6 -4
  15. package/dist/src/dsse.js +22 -6
  16. package/dist/src/fs-safe.d.ts +32 -3
  17. package/dist/src/fs-safe.js +193 -31
  18. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  20. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  21. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  22. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  23. package/dist/src/gate/adapters/claude-code.js +193 -0
  24. package/dist/src/gate/adapters/client.d.ts +13 -0
  25. package/dist/src/gate/adapters/client.js +57 -0
  26. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  27. package/dist/src/gate/adapters/codex-hook.js +5 -0
  28. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  29. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  30. package/dist/src/gate/adapters/codex.d.ts +16 -0
  31. package/dist/src/gate/adapters/codex.js +574 -0
  32. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  33. package/dist/src/gate/adapters/hook-main.js +35 -0
  34. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  35. package/dist/src/gate/adapters/host-pid.js +20 -0
  36. package/dist/src/gate/admission.d.ts +54 -0
  37. package/dist/src/gate/admission.js +490 -0
  38. package/dist/src/gate/contract.d.ts +51 -0
  39. package/dist/src/gate/contract.js +94 -0
  40. package/dist/src/gate/decision-log.d.ts +38 -0
  41. package/dist/src/gate/decision-log.js +251 -0
  42. package/dist/src/gate/generations.d.ts +67 -0
  43. package/dist/src/gate/generations.js +518 -0
  44. package/dist/src/gate/proc.d.ts +31 -0
  45. package/dist/src/gate/proc.js +79 -0
  46. package/dist/src/gate/refresh.d.ts +11 -0
  47. package/dist/src/gate/refresh.js +30 -0
  48. package/dist/src/gate/run-verifier.d.ts +23 -0
  49. package/dist/src/gate/run-verifier.js +89 -0
  50. package/dist/src/gate/service.d.ts +80 -0
  51. package/dist/src/gate/service.js +722 -0
  52. package/dist/src/gate/strict-json.d.ts +11 -0
  53. package/dist/src/gate/strict-json.js +190 -0
  54. package/dist/src/gate/trust-store.d.ts +36 -0
  55. package/dist/src/gate/trust-store.js +251 -0
  56. package/dist/src/gate/verifier-worker.d.ts +8 -0
  57. package/dist/src/gate/verifier-worker.js +66 -0
  58. package/dist/src/index.d.ts +2 -0
  59. package/dist/src/index.js +2 -0
  60. package/dist/src/keys.d.ts +4 -0
  61. package/dist/src/keys.js +85 -30
  62. package/dist/src/main-module.js +1 -1
  63. package/dist/src/names.js +2 -4
  64. package/dist/src/policy.d.ts +173 -6
  65. package/dist/src/policy.js +685 -54
  66. package/dist/src/recovery-admin.d.ts +173 -0
  67. package/dist/src/recovery-admin.js +400 -0
  68. package/dist/src/revocations.js +3 -1
  69. package/dist/src/root-events.d.ts +107 -0
  70. package/dist/src/root-events.js +376 -0
  71. package/dist/src/time.d.ts +19 -3
  72. package/dist/src/time.js +50 -8
  73. package/dist/src/timestamp.d.ts +61 -0
  74. package/dist/src/timestamp.js +107 -0
  75. package/dist/src/tree-digest.d.ts +4 -0
  76. package/dist/src/tree-digest.js +41 -16
  77. package/dist/src/trust-root.d.ts +5 -0
  78. package/dist/src/trust-root.js +34 -13
  79. package/dist/src/verify.d.ts +69 -13
  80. package/dist/src/verify.js +309 -61
  81. package/docs/hosts/adapter-interface.md +8 -2
  82. package/docs/hosts/github-action.md +3 -3
  83. package/docs/hosts/pi.md +10 -3
  84. package/docs/spec/gui-admin-rack-v1.md +289 -0
  85. package/docs/spec/root-recovery-v1.md +451 -0
  86. package/docs/spec/skill-certificate-v1.md +1 -1
  87. package/docs/spec/skill-tree-v2.md +2 -2
  88. package/docs/spec/trust-documents-v1.md +12 -6
  89. package/docs/spec/verification.md +20 -3
  90. package/docs/threat-model.md +9 -6
  91. package/package.json +49 -44
@@ -0,0 +1,173 @@
1
+ import { type PrivateKeyInfo, type PublicKeyInfo } from './keys.ts';
2
+ import type { Policy } from './policy.ts';
3
+ import { recoverySetJson, type RecoverySet, type RootEvent, type RootWalk } from './root-events.ts';
4
+ import { type Timestamp } from './timestamp.ts';
5
+ import { type TrustRoot } from './trust-root.ts';
6
+ /** Builds and validates a recovery set from public key files. */
7
+ export declare function buildRecoverySet(options: {
8
+ publicKeyPaths: string[];
9
+ rotateThreshold: number;
10
+ revokeThreshold: number;
11
+ }): Promise<RecoverySet>;
12
+ export declare function initRootEventLog(out: string): Promise<string>;
13
+ /** Walks the policy's log the way a host does and returns the current root state. */
14
+ export declare function currentRootState(policy: Policy, now: Date): Promise<RootWalk>;
15
+ export interface PreparedEvent {
16
+ path: string;
17
+ event: RootEvent;
18
+ /** Keys that must sign before the event can be appended. */
19
+ required: string[];
20
+ }
21
+ /**
22
+ * Writes an unsigned proposal for the next root event. Every signer is fixed now, because the signatures cover the
23
+ * list of signers; trustees then sign the same proposal file, and `appendRootEvent` adds it to the log.
24
+ */
25
+ export declare function prepareRootEvent(options: {
26
+ policy: Policy;
27
+ action: 'revoke' | 'rotate';
28
+ reason: string;
29
+ signerPublicPaths: string[];
30
+ out: string;
31
+ now: Date;
32
+ newRootPublicPath?: string | undefined;
33
+ newRecoveryPublicPaths?: string[] | undefined;
34
+ rotateThreshold?: number | undefined;
35
+ revokeThreshold?: number | undefined;
36
+ newTimestampPublicPath?: string | undefined;
37
+ }): Promise<PreparedEvent>;
38
+ /** What a trustee should compare with what was agreed before signing. */
39
+ export declare function describeRootEvent(event: RootEvent): Record<string, unknown>;
40
+ /** Reads a proposal and, with a policy, checks that it extends the published log. Signs nothing. */
41
+ export declare function showRootEvent(options: {
42
+ proposalPath: string;
43
+ policy?: Policy | undefined;
44
+ now: Date;
45
+ }): Promise<{
46
+ event: RootEvent;
47
+ signed: string[];
48
+ missing: string[];
49
+ }>;
50
+ /**
51
+ * Adds one signature to a proposal. Refuses a key the event does not name as a signer, new root or new timestamp key,
52
+ * and, with a policy, a proposal that does not extend the published log. Returns the event so it can be shown.
53
+ */
54
+ export declare function signRootEvent(options: {
55
+ proposalPath: string;
56
+ keyPath: string;
57
+ policy?: Policy | undefined;
58
+ now?: Date | undefined;
59
+ }): Promise<{
60
+ keyId: string;
61
+ event: RootEvent;
62
+ signed: string[];
63
+ missing: string[];
64
+ }>;
65
+ /**
66
+ * Appends a fully signed proposal to the policy's root event log, after walking the whole new log exactly as a host
67
+ * would. Nothing is written if any rule fails.
68
+ */
69
+ export declare function appendRootEvent(options: {
70
+ policy: Policy;
71
+ proposalPath: string;
72
+ now: Date;
73
+ }): Promise<{
74
+ path: string;
75
+ walk: RootWalk;
76
+ event: RootEvent;
77
+ }>;
78
+ export interface PreparedTimestamp {
79
+ kind: 'timestamp';
80
+ path: string;
81
+ /** `sha256:<hex>` of the timestamp file as read; null when it did not exist. */
82
+ baseSha256: string | null;
83
+ keyId: string;
84
+ /** Exactly what commit signs. */
85
+ payload: Timestamp;
86
+ /** The documents the payload names, `sha256:<hex>` as read at prepare. */
87
+ documents: {
88
+ rootEvents: {
89
+ path: string;
90
+ sha256: string;
91
+ count: number;
92
+ };
93
+ trustRoot: {
94
+ path: string;
95
+ sha256: string;
96
+ version: number;
97
+ };
98
+ revocations: {
99
+ path: string;
100
+ sha256: string;
101
+ version: number;
102
+ };
103
+ };
104
+ /** An existing timestamp signed by another key (a rotated timestamp key), when it could be parsed. */
105
+ previousByOtherKey: {
106
+ keyId: string;
107
+ version: number;
108
+ } | null;
109
+ }
110
+ /** The existing timestamp could not be read and no version was given (GUI path). The GUI maps it by class. */
111
+ export declare class TimestampUnreadableError extends Error {
112
+ constructor(reason: string);
113
+ }
114
+ /**
115
+ * Builds the policy's next timestamp without signing or writing: the digests of the root event log, trust root and
116
+ * revocation list as read now, with the next version. With `minimumVersions` (the GUI), the trust root and revocation
117
+ * list must not be older than the minimums, must load under the active root with expiry checked, and the version is
118
+ * `max(own version if signed by this key, minimums.timestamp) + 1`. Without it (the CLI), the rules of old.
119
+ * `walk`, when given, must be the walk of the log as it is now (the GUI passes its memory-checked one).
120
+ */
121
+ export declare function prepareTimestamp(o: {
122
+ policy: Policy;
123
+ key: PublicKeyInfo;
124
+ now: Date;
125
+ expires?: string | undefined;
126
+ version?: number | undefined;
127
+ minimumVersions?: {
128
+ trustRoot: number;
129
+ revocations: number;
130
+ timestamp: number;
131
+ } | undefined;
132
+ walk?: RootWalk | undefined;
133
+ }): Promise<PreparedTimestamp>;
134
+ export declare function signPreparedTimestamp(p: PreparedTimestamp, key: PrivateKeyInfo): Buffer;
135
+ /** Re-hashes the three named documents and the timestamp file, signs `p.payload` unchanged, and writes it. */
136
+ export declare function commitTimestamp(p: PreparedTimestamp, key: PrivateKeyInfo, o?: {
137
+ beforeWrite?: () => void | Promise<void>;
138
+ }): Promise<{
139
+ path: string;
140
+ timestamp: Timestamp;
141
+ }>;
142
+ /**
143
+ * Signs the policy's timestamp: the digests of the root event log, trust root and revocation list as published now,
144
+ * with the next version. Run by the timestamp job, with the active timestamp key.
145
+ */
146
+ export declare function signPolicyTimestamp(options: {
147
+ policy: Policy;
148
+ keyPath: string;
149
+ now: Date;
150
+ expires?: string | undefined;
151
+ version?: number | undefined;
152
+ }): Promise<{
153
+ path: string;
154
+ timestamp: Timestamp;
155
+ }>;
156
+ /**
157
+ * After a rotate: re-signs the trust root and revocation list with the new root key, keeping every approver and
158
+ * revocation entry, each with the next version. The current documents must be signed by `fromRootKeyId`.
159
+ */
160
+ export declare function adoptTrustDocuments(options: {
161
+ rootKeyPath: string;
162
+ fromRootKeyId: string;
163
+ trustRootPath: string;
164
+ revocationsPath: string;
165
+ now: Date;
166
+ trustRootExpires?: string | undefined;
167
+ revocationsExpires?: string | undefined;
168
+ }): Promise<{
169
+ trustRoot: TrustRoot;
170
+ trustRootVersion: number;
171
+ revocationsVersion: number;
172
+ }>;
173
+ export { recoverySetJson };
@@ -0,0 +1,400 @@
1
+ // Organization-side commands for root recovery: build the recovery set, prepare, sign and append root events,
2
+ // sign timestamps, and move the trust documents to a new root key after a rotation.
3
+ // `append` runs the same walk a host runs, so a log that append accepts is a log hosts accept.
4
+ import { DocumentChangedError, StaleDocumentError } from "./admin.js";
5
+ import { readRegularFile, writeFileAtomic, writeNewFile } from "./fs-safe.js";
6
+ import { loadPrivateKey, loadPublicKey } from "./keys.js";
7
+ import { readRevocationsForUpdate, signRevocations } from "./revocations.js";
8
+ import { addEnvelopeSignature, emptyRootEventLog, MAX_ROOT_EVENT_REASON, MAX_ROOT_EVENTS_BYTES, parseMultiEnvelope, parseRecoverySet, parseRootEventLog, parseRootEventPayload, recoverySetJson, requireDisplaySafeText, requiredSigners, ROOT_EVENT_PAYLOAD_TYPE, rootEventLogBytes, unsignedEventEnvelope, walkRootEvents, } from "./root-events.js";
9
+ import { addDuration, formatTimestamp, parseDuration, truncateToSecond } from "./time.js";
10
+ import { MAX_TIMESTAMP_BYTES, parseTimestampPayload, readTimestampForUpdate, signTimestamp } from "./timestamp.js";
11
+ import { sha256Hex } from "./tree-digest.js";
12
+ import { readTrustRootForUpdate, signTrustRoot } from "./trust-root.js";
13
+ import { canonicalBytes, parseCanonicalJsonBytes } from "./canonical-json.js";
14
+ import { parseEnvelope } from "./dsse.js";
15
+ import { loadTrustContext } from "./verify.js";
16
+ const MAX_PROPOSAL_BYTES = 256 * 1024;
17
+ function requireRecovery(policy) {
18
+ if (!policy.recovery)
19
+ throw new Error(`Policy ${policy.path} has no "recovery" block; root events need policy_version "mago.policy/v2" with recovery`);
20
+ return policy.recovery;
21
+ }
22
+ async function uniqueKeys(paths, label) {
23
+ const keys = await Promise.all(paths.map((file) => loadPublicKey(file)));
24
+ const ids = new Set(keys.map((key) => key.keyId));
25
+ if (ids.size !== keys.length)
26
+ throw new Error(`${label}: the same key is given more than once`);
27
+ return keys.sort((a, b) => (a.keyId < b.keyId ? -1 : 1));
28
+ }
29
+ /** Builds and validates a recovery set from public key files. */
30
+ export async function buildRecoverySet(options) {
31
+ const keys = await uniqueKeys(options.publicKeyPaths, 'Recovery keys');
32
+ return parseRecoverySet({
33
+ key_ids: keys.map((key) => key.keyId), rotate_threshold: options.rotateThreshold, revoke_threshold: options.revokeThreshold,
34
+ }, 'Recovery set');
35
+ }
36
+ export async function initRootEventLog(out) {
37
+ return await writeNewFile(out, emptyRootEventLog());
38
+ }
39
+ async function readLog(policy) {
40
+ return await readRegularFile(requireRecovery(policy).rootEventsPath, 'Root event log', MAX_ROOT_EVENTS_BYTES);
41
+ }
42
+ function walkFromPolicy(policy, bytes, now) {
43
+ const recovery = requireRecovery(policy);
44
+ return walkRootEvents(bytes, {
45
+ rootKeyId: policy.rootKeyId, recovery: recovery.set, timestampKeyId: recovery.freshness?.keyId ?? null, eventsAfter: recovery.eventsAfter,
46
+ }, now);
47
+ }
48
+ /** Walks the policy's log the way a host does and returns the current root state. */
49
+ export async function currentRootState(policy, now) {
50
+ try {
51
+ return walkFromPolicy(policy, await readLog(policy), now);
52
+ }
53
+ catch (error) {
54
+ throw new Error(`root event log: ${error.message}`);
55
+ }
56
+ }
57
+ /**
58
+ * Writes an unsigned proposal for the next root event. Every signer is fixed now, because the signatures cover the
59
+ * list of signers; trustees then sign the same proposal file, and `appendRootEvent` adds it to the log.
60
+ */
61
+ export async function prepareRootEvent(options) {
62
+ const state = await currentRootState(options.policy, options.now);
63
+ const reason = requireDisplaySafeText(options.reason, 'Reason', MAX_ROOT_EVENT_REASON);
64
+ const signers = await uniqueKeys(options.signerPublicPaths, 'Signers');
65
+ if (signers.length === 0)
66
+ throw new Error('At least one --signer-public key is required');
67
+ const event = {
68
+ sequence: state.count + 1,
69
+ action: options.action,
70
+ rootKeyId: state.activeRootKeyId,
71
+ issuedAt: truncateToSecond(options.now),
72
+ reason,
73
+ signers,
74
+ };
75
+ if (options.action === 'revoke') {
76
+ if (state.revoked)
77
+ throw new Error(`Root key ${state.activeRootKeyId} is already revoked (root event ${state.revoked.sequence}); prepare a rotate`);
78
+ if (options.newRootPublicPath || options.newRecoveryPublicPaths?.length || options.newTimestampPublicPath
79
+ || options.rotateThreshold !== undefined || options.revokeThreshold !== undefined)
80
+ throw new Error('A revoke takes only --reason and --signer-public');
81
+ const outside = signers.find((key) => !state.recovery.keyIds.includes(key.keyId));
82
+ if (outside)
83
+ throw new Error(`Signer ${outside.keyId} is not in the current recovery set`);
84
+ if (signers.length < state.recovery.revokeThreshold)
85
+ throw new Error(`A revoke needs ${state.recovery.revokeThreshold} recovery signer(s); ${signers.length} given`);
86
+ }
87
+ else {
88
+ if (!options.newRootPublicPath)
89
+ throw new Error('A rotate needs --new-root-public');
90
+ event.newRoot = await loadPublicKey(options.newRootPublicPath);
91
+ const newKeys = options.newRecoveryPublicPaths?.length ? (await uniqueKeys(options.newRecoveryPublicPaths, 'New recovery keys')).map((key) => key.keyId) : state.recovery.keyIds;
92
+ const changingKeys = Boolean(options.newRecoveryPublicPaths?.length);
93
+ if (changingKeys && (options.rotateThreshold === undefined || options.revokeThreshold === undefined))
94
+ throw new Error('A new recovery set needs --rotate-threshold and --revoke-threshold');
95
+ event.newRecovery = parseRecoverySet({
96
+ key_ids: newKeys,
97
+ rotate_threshold: options.rotateThreshold ?? state.recovery.rotateThreshold,
98
+ revoke_threshold: options.revokeThreshold ?? state.recovery.revokeThreshold,
99
+ }, 'New recovery set');
100
+ if (options.newTimestampPublicPath)
101
+ event.newTimestamp = await loadPublicKey(options.newTimestampPublicPath);
102
+ const outside = signers.find((key) => !state.recovery.keyIds.includes(key.keyId) && !event.newRecovery.keyIds.includes(key.keyId));
103
+ if (outside)
104
+ throw new Error(`Signer ${outside.keyId} is in neither the current nor the new recovery set`);
105
+ }
106
+ const written = await writeNewFile(options.out, canonicalBytes(unsignedEventEnvelope(event)));
107
+ return { path: written, event, required: requiredSigners(event).map((key) => key.keyId) };
108
+ }
109
+ async function readProposal(file) {
110
+ const bytes = await readRegularFile(file, 'Root event proposal', MAX_PROPOSAL_BYTES);
111
+ const parsed = parseMultiEnvelope(parseCanonicalJsonBytes(bytes, 'root event proposal'), 'root event proposal', { minSignatures: 0 });
112
+ if (parsed.payloadType !== ROOT_EVENT_PAYLOAD_TYPE)
113
+ throw new Error('root event proposal has the wrong payload type');
114
+ const event = parseRootEventPayload(parsed.payloadBytes);
115
+ return { envelope: { payloadType: parsed.payloadType, payload: parsed.payload, signatures: parsed.signatures }, event };
116
+ }
117
+ /** What a trustee should compare with what was agreed before signing. */
118
+ export function describeRootEvent(event) {
119
+ return {
120
+ sequence: event.sequence,
121
+ action: event.action,
122
+ root_key_id: event.rootKeyId,
123
+ issued_at: formatTimestamp(event.issuedAt),
124
+ reason: event.reason,
125
+ signers: event.signers.map((key) => key.keyId),
126
+ ...(event.newRoot ? { new_root: event.newRoot.keyId } : {}),
127
+ ...(event.newRecovery ? { new_recovery: recoverySetJson(event.newRecovery) } : {}),
128
+ ...(event.newTimestamp ? { new_timestamp: event.newTimestamp.keyId } : {}),
129
+ };
130
+ }
131
+ /** Refuses a proposal that does not extend the policy's log as it is now (wrong number or root key). */
132
+ async function checkExtendsLog(policy, event, now) {
133
+ const state = await currentRootState(policy, now);
134
+ if (event.sequence !== state.count + 1)
135
+ throw new Error(`The proposal is event ${event.sequence}, but the log has ${state.count} event(s); prepare it again against the published log`);
136
+ if (event.rootKeyId !== state.activeRootKeyId)
137
+ throw new Error(`The proposal names root key ${event.rootKeyId}, but the active root key is ${state.activeRootKeyId}`);
138
+ }
139
+ /** Reads a proposal and, with a policy, checks that it extends the published log. Signs nothing. */
140
+ export async function showRootEvent(options) {
141
+ const { envelope, event } = await readProposal(options.proposalPath);
142
+ if (options.policy)
143
+ await checkExtendsLog(options.policy, event, options.now);
144
+ const signed = envelope.signatures.map((item) => item.keyid);
145
+ return { event, signed, missing: requiredSigners(event).map((key) => key.keyId).filter((keyId) => !signed.includes(keyId)) };
146
+ }
147
+ /**
148
+ * Adds one signature to a proposal. Refuses a key the event does not name as a signer, new root or new timestamp key,
149
+ * and, with a policy, a proposal that does not extend the published log. Returns the event so it can be shown.
150
+ */
151
+ export async function signRootEvent(options) {
152
+ const { envelope, event } = await readProposal(options.proposalPath);
153
+ if (options.policy)
154
+ await checkExtendsLog(options.policy, event, options.now ?? new Date());
155
+ const key = await loadPrivateKey(options.keyPath);
156
+ const required = requiredSigners(event).map((item) => item.keyId);
157
+ if (!required.includes(key.keyId))
158
+ throw new Error(`Key ${key.keyId} is not one of the keys this event must be signed by (${required.join(', ')})`);
159
+ const next = addEnvelopeSignature(envelope, key.keyId, key.privateKey);
160
+ await writeFileAtomic(options.proposalPath, canonicalBytes(next));
161
+ const signed = next.signatures.map((item) => item.keyid);
162
+ return { keyId: key.keyId, event, signed, missing: required.filter((keyId) => !signed.includes(keyId)) };
163
+ }
164
+ /**
165
+ * Appends a fully signed proposal to the policy's root event log, after walking the whole new log exactly as a host
166
+ * would. Nothing is written if any rule fails.
167
+ */
168
+ export async function appendRootEvent(options) {
169
+ const recovery = requireRecovery(options.policy);
170
+ const { envelope, event } = await readProposal(options.proposalPath);
171
+ const required = requiredSigners(event).map((key) => key.keyId);
172
+ const missing = required.filter((keyId) => !envelope.signatures.some((item) => item.keyid === keyId));
173
+ if (missing.length > 0)
174
+ throw new Error(`The proposal is missing signatures from ${missing.join(', ')}`);
175
+ const current = await readLog(options.policy);
176
+ const existing = parseRootEventLog(current).map((item) => ({ payloadType: item.payloadType, payload: item.payload, signatures: item.signatures }));
177
+ const nextLog = rootEventLogBytes([...existing, envelope]);
178
+ if (nextLog.byteLength > MAX_ROOT_EVENTS_BYTES)
179
+ throw new Error('The root event log would exceed its size limit');
180
+ let walk;
181
+ try {
182
+ walk = walkFromPolicy(options.policy, nextLog, options.now);
183
+ }
184
+ catch (error) {
185
+ throw new Error(`Refusing to append: ${error.message}`);
186
+ }
187
+ // The log only grows, and must not have changed since it was read.
188
+ const again = await readLog(options.policy);
189
+ if (sha256Hex(again) !== sha256Hex(current))
190
+ throw new Error('The root event log changed while appending; run append again');
191
+ const written = await writeFileAtomic(recovery.rootEventsPath, nextLog);
192
+ return { path: written, walk, event };
193
+ }
194
+ /** The existing timestamp could not be read and no version was given (GUI path). The GUI maps it by class. */
195
+ export class TimestampUnreadableError extends Error {
196
+ constructor(reason) {
197
+ super(`The current timestamp cannot be read (${reason})`);
198
+ this.name = 'TimestampUnreadableError';
199
+ }
200
+ }
201
+ const prefixed = (hex) => `sha256:${hex}`;
202
+ /**
203
+ * Builds the policy's next timestamp without signing or writing: the digests of the root event log, trust root and
204
+ * revocation list as read now, with the next version. With `minimumVersions` (the GUI), the trust root and revocation
205
+ * list must not be older than the minimums, must load under the active root with expiry checked, and the version is
206
+ * `max(own version if signed by this key, minimums.timestamp) + 1`. Without it (the CLI), the rules of old.
207
+ * `walk`, when given, must be the walk of the log as it is now (the GUI passes its memory-checked one).
208
+ */
209
+ export async function prepareTimestamp(o) {
210
+ const recovery = requireRecovery(o.policy);
211
+ const freshness = recovery.freshness;
212
+ if (!freshness)
213
+ throw new Error(`Policy ${o.policy.path} has no "freshness" block`);
214
+ const logBytes = await readLog(o.policy);
215
+ let walk;
216
+ if (o.walk) {
217
+ if (o.walk.logSha256 !== sha256Hex(logBytes))
218
+ throw new DocumentChangedError('Root event log');
219
+ walk = o.walk;
220
+ }
221
+ else {
222
+ try {
223
+ walk = walkFromPolicy(o.policy, logBytes, o.now);
224
+ }
225
+ catch (error) {
226
+ throw new Error(`root event log: ${error.message}`);
227
+ }
228
+ }
229
+ const keyId = o.key.keyId;
230
+ if (keyId !== walk.timestampKeyId)
231
+ throw new Error(`Key ${keyId} is not the active timestamp key ${walk.timestampKeyId}`);
232
+ const trustRootBytes = await readRegularFile(o.policy.trustRootPath, 'Trust root', 4 * 1024 * 1024);
233
+ const revocationsBytes = await readRegularFile(o.policy.revocationsPath, 'Revocation list', 8 * 1024 * 1024);
234
+ // Only documents hosts would accept from the active root are timestamped.
235
+ const trustRoot = readTrustRootForUpdate(trustRootBytes, walk.activeRootKeyId);
236
+ const revocations = readRevocationsForUpdate(revocationsBytes, walk.activeRootKeyId, trustRoot.root.publicKey);
237
+ const minimums = o.minimumVersions;
238
+ if (minimums) {
239
+ if (trustRoot.version < minimums.trustRoot)
240
+ throw new StaleDocumentError('Trust root', trustRoot.version, minimums.trustRoot);
241
+ if (revocations.version < minimums.revocations)
242
+ throw new StaleDocumentError('Revocation list', revocations.version, minimums.revocations);
243
+ const loaded = loadTrustContext({ trustRootBytes, revocationsBytes, rootKeyId: walk.activeRootKeyId, now: o.now });
244
+ if (!loaded.ok)
245
+ throw new Error(loaded.reason);
246
+ }
247
+ // Versions are per timestamp key: a missing timestamp, or one by an earlier timestamp key, starts at 1.
248
+ let ownVersion = 0;
249
+ let previousBytes = null;
250
+ let previousByOtherKey = null;
251
+ try {
252
+ previousBytes = await readRegularFile(freshness.timestampPath, 'Timestamp', MAX_TIMESTAMP_BYTES);
253
+ }
254
+ catch (error) {
255
+ if (error?.code !== 'ENOENT') {
256
+ if (!minimums)
257
+ throw error;
258
+ throw new TimestampUnreadableError(error.message);
259
+ }
260
+ }
261
+ if (previousBytes) {
262
+ try {
263
+ ownVersion = readTimestampForUpdate(previousBytes, keyId).version;
264
+ }
265
+ catch (error) {
266
+ let byOtherKey = false;
267
+ try {
268
+ const envelope = parseEnvelope(previousBytes, 'timestamp');
269
+ byOtherKey = envelope.signatures[0].keyid !== keyId;
270
+ if (byOtherKey) {
271
+ try {
272
+ previousByOtherKey = { keyId: envelope.signatures[0].keyid, version: parseTimestampPayload(envelope.payloadBytes).version };
273
+ }
274
+ catch {
275
+ previousByOtherKey = null;
276
+ }
277
+ }
278
+ }
279
+ catch {
280
+ byOtherKey = false;
281
+ }
282
+ if (!byOtherKey && o.version === undefined) {
283
+ if (minimums)
284
+ throw new TimestampUnreadableError(error.message);
285
+ throw new Error(`The current timestamp cannot be read (${error.message}); pass --version with a number above the last one published`);
286
+ }
287
+ }
288
+ }
289
+ let version = ownVersion + 1;
290
+ if (minimums)
291
+ version = Math.max(ownVersion, minimums.timestamp) + 1;
292
+ if (o.version !== undefined) {
293
+ if (!Number.isSafeInteger(o.version) || o.version < 1)
294
+ throw new Error('--version must be a positive integer');
295
+ if (o.version < version)
296
+ throw new Error(`--version ${o.version} is lower than the next version ${version}`);
297
+ version = o.version;
298
+ }
299
+ const issuedAt = truncateToSecond(o.now);
300
+ const lifetime = o.expires ?? '24h';
301
+ if (parseDuration(lifetime, 'timestamp lifetime') > freshness.maxLifetimeMs)
302
+ throw new Error('The timestamp lifetime is longer than the policy\'s freshness max_lifetime');
303
+ const rootEventsHex = sha256Hex(logBytes);
304
+ const payload = {
305
+ version,
306
+ issuedAt,
307
+ expiresAt: addDuration(issuedAt, lifetime, 'timestamp lifetime'),
308
+ key: o.key,
309
+ rootEvents: { sha256: rootEventsHex, count: walk.count },
310
+ trustRoot: { sha256: sha256Hex(trustRootBytes), version: trustRoot.version },
311
+ revocations: { sha256: sha256Hex(revocationsBytes), version: revocations.version },
312
+ };
313
+ return {
314
+ kind: 'timestamp',
315
+ path: freshness.timestampPath,
316
+ baseSha256: previousBytes ? prefixed(sha256Hex(previousBytes)) : null,
317
+ keyId,
318
+ payload,
319
+ documents: {
320
+ rootEvents: { path: recovery.rootEventsPath, sha256: prefixed(rootEventsHex), count: walk.count },
321
+ trustRoot: { path: o.policy.trustRootPath, sha256: prefixed(payload.trustRoot.sha256), version: trustRoot.version },
322
+ revocations: { path: o.policy.revocationsPath, sha256: prefixed(payload.revocations.sha256), version: revocations.version },
323
+ },
324
+ previousByOtherKey,
325
+ };
326
+ }
327
+ export function signPreparedTimestamp(p, key) {
328
+ return signTimestamp(p.payload, key.privateKey);
329
+ }
330
+ async function hashOrNull(filePath, label, maxBytes) {
331
+ try {
332
+ return prefixed(sha256Hex(await readRegularFile(filePath, label, maxBytes)));
333
+ }
334
+ catch (error) {
335
+ if (error?.code === 'ENOENT')
336
+ return null;
337
+ throw error;
338
+ }
339
+ }
340
+ /** Re-hashes the three named documents and the timestamp file, signs `p.payload` unchanged, and writes it. */
341
+ export async function commitTimestamp(p, key, o = {}) {
342
+ if (key.keyId !== p.keyId)
343
+ throw new Error(`Key ${key.keyId} is not the prepared timestamp key ${p.keyId}`);
344
+ const checks = [
345
+ ['Root event log', p.documents.rootEvents.path, MAX_ROOT_EVENTS_BYTES, p.documents.rootEvents.sha256],
346
+ ['Trust root', p.documents.trustRoot.path, 4 * 1024 * 1024, p.documents.trustRoot.sha256],
347
+ ['Revocation list', p.documents.revocations.path, 8 * 1024 * 1024, p.documents.revocations.sha256],
348
+ ['Timestamp', p.path, MAX_TIMESTAMP_BYTES, p.baseSha256],
349
+ ];
350
+ for (const [label, file, max, expected] of checks)
351
+ if ((await hashOrNull(file, label, max)) !== expected)
352
+ throw new DocumentChangedError(label);
353
+ const bytes = signPreparedTimestamp(p, key);
354
+ await o.beforeWrite?.();
355
+ const written = await writeFileAtomic(p.path, bytes, 0o644, { expectSha256: p.baseSha256 });
356
+ return { path: written, timestamp: p.payload };
357
+ }
358
+ /**
359
+ * Signs the policy's timestamp: the digests of the root event log, trust root and revocation list as published now,
360
+ * with the next version. Run by the timestamp job, with the active timestamp key.
361
+ */
362
+ export async function signPolicyTimestamp(options) {
363
+ const key = await loadPrivateKey(options.keyPath);
364
+ const prepared = await prepareTimestamp({ policy: options.policy, key, now: options.now, expires: options.expires, version: options.version });
365
+ return await commitTimestamp(prepared, key);
366
+ }
367
+ /**
368
+ * After a rotate: re-signs the trust root and revocation list with the new root key, keeping every approver and
369
+ * revocation entry, each with the next version. The current documents must be signed by `fromRootKeyId`.
370
+ */
371
+ export async function adoptTrustDocuments(options) {
372
+ const root = await loadPrivateKey(options.rootKeyPath);
373
+ if (root.keyId === options.fromRootKeyId)
374
+ throw new Error('The new root key is the same as the current one; nothing to adopt');
375
+ const currentTrust = readTrustRootForUpdate(await readRegularFile(options.trustRootPath, 'Trust root', 4 * 1024 * 1024), options.fromRootKeyId);
376
+ const currentList = readRevocationsForUpdate(await readRegularFile(options.revocationsPath, 'Revocation list', 8 * 1024 * 1024), options.fromRootKeyId, currentTrust.root.publicKey);
377
+ if (currentTrust.approvers.some((approver) => approver.keyId === root.keyId))
378
+ throw new Error('The new root key is listed as an approver; remove it first');
379
+ const issuedAt = truncateToSecond(options.now);
380
+ const trustRoot = {
381
+ ...currentTrust,
382
+ version: currentTrust.version + 1,
383
+ issuedAt,
384
+ expiresAt: addDuration(issuedAt, options.trustRootExpires ?? '365d', 'trust root expiry'),
385
+ root,
386
+ };
387
+ const revocations = {
388
+ ...currentList,
389
+ version: currentList.version + 1,
390
+ issuedAt,
391
+ expiresAt: addDuration(issuedAt, options.revocationsExpires ?? '30d', 'revocation list expiry'),
392
+ rootKeyId: root.keyId,
393
+ };
394
+ const trustBytes = signTrustRoot(trustRoot, root.privateKey);
395
+ const listBytes = signRevocations(revocations, root.privateKey);
396
+ await writeFileAtomic(options.trustRootPath, trustBytes);
397
+ await writeFileAtomic(options.revocationsPath, listBytes);
398
+ return { trustRoot, trustRootVersion: trustRoot.version, revocationsVersion: revocations.version };
399
+ }
400
+ export { recoverySetJson };
@@ -2,7 +2,7 @@ import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requi
2
2
  import { envelopeBytes, parseEnvelope, signEnvelope, verifyEnvelopeSignature } from "./dsse.js";
3
3
  import { validateKeyId } from "./keys.js";
4
4
  import { validateDigest } from "./names.js";
5
- import { formatTimestamp, parseTimestamp } from "./time.js";
5
+ import { formatTimestamp, parseTimestamp, requireValidDate } from "./time.js";
6
6
  import { TrustDocumentError } from "./trust-root.js";
7
7
  export const REVOCATIONS_PAYLOAD_TYPE = 'application/vnd.mago-ski.revocations+json';
8
8
  export const REVOCATIONS_TYPE = 'mago.revocations/v1';
@@ -63,6 +63,8 @@ export function parseRevocationsPayload(bytes) {
63
63
  };
64
64
  }
65
65
  export function verifyRevocations(bytes, trustRoot, now) {
66
+ // The freshness check below compares against `now`; an invalid Date would let an expired list through.
67
+ requireValidDate(now, 'Verification time');
66
68
  let revocations;
67
69
  try {
68
70
  revocations = readRevocationsForUpdate(bytes, trustRoot.root.keyId, trustRoot.root.publicKey);