@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.
- package/README.md +54 -9
- package/action.yml +2 -2
- package/dist/hosts/github/run.d.ts +9 -1
- package/dist/hosts/github/run.js +64 -11
- package/dist/hosts/pi/index.d.ts +5 -3
- package/dist/hosts/pi/index.js +219 -14
- package/dist/src/admin.d.ts +140 -1
- package/dist/src/admin.js +328 -63
- package/dist/src/canonical-json.js +73 -28
- package/dist/src/certificate.js +23 -15
- package/dist/src/cli.js +590 -89
- package/dist/src/diff.d.ts +0 -4
- package/dist/src/diff.js +326 -70
- package/dist/src/dsse.d.ts +6 -4
- package/dist/src/dsse.js +22 -6
- package/dist/src/fs-safe.d.ts +32 -3
- package/dist/src/fs-safe.js +193 -31
- package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
- package/dist/src/gate/adapters/claude-code-hook.js +4 -0
- package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
- package/dist/src/gate/adapters/claude-code-settings.js +49 -0
- package/dist/src/gate/adapters/claude-code.d.ts +33 -0
- package/dist/src/gate/adapters/claude-code.js +193 -0
- package/dist/src/gate/adapters/client.d.ts +13 -0
- package/dist/src/gate/adapters/client.js +57 -0
- package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
- package/dist/src/gate/adapters/codex-hook.js +5 -0
- package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
- package/dist/src/gate/adapters/codex-requirements.js +56 -0
- package/dist/src/gate/adapters/codex.d.ts +16 -0
- package/dist/src/gate/adapters/codex.js +574 -0
- package/dist/src/gate/adapters/hook-main.d.ts +7 -0
- package/dist/src/gate/adapters/hook-main.js +35 -0
- package/dist/src/gate/adapters/host-pid.d.ts +1 -0
- package/dist/src/gate/adapters/host-pid.js +20 -0
- package/dist/src/gate/admission.d.ts +54 -0
- package/dist/src/gate/admission.js +490 -0
- package/dist/src/gate/contract.d.ts +51 -0
- package/dist/src/gate/contract.js +94 -0
- package/dist/src/gate/decision-log.d.ts +38 -0
- package/dist/src/gate/decision-log.js +251 -0
- package/dist/src/gate/generations.d.ts +67 -0
- package/dist/src/gate/generations.js +518 -0
- package/dist/src/gate/proc.d.ts +31 -0
- package/dist/src/gate/proc.js +79 -0
- package/dist/src/gate/refresh.d.ts +11 -0
- package/dist/src/gate/refresh.js +30 -0
- package/dist/src/gate/run-verifier.d.ts +23 -0
- package/dist/src/gate/run-verifier.js +89 -0
- package/dist/src/gate/service.d.ts +80 -0
- package/dist/src/gate/service.js +722 -0
- package/dist/src/gate/strict-json.d.ts +11 -0
- package/dist/src/gate/strict-json.js +190 -0
- package/dist/src/gate/trust-store.d.ts +36 -0
- package/dist/src/gate/trust-store.js +251 -0
- package/dist/src/gate/verifier-worker.d.ts +8 -0
- package/dist/src/gate/verifier-worker.js +66 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +2 -0
- package/dist/src/keys.d.ts +4 -0
- package/dist/src/keys.js +85 -30
- package/dist/src/main-module.js +1 -1
- package/dist/src/names.js +2 -4
- package/dist/src/policy.d.ts +173 -6
- package/dist/src/policy.js +685 -54
- package/dist/src/recovery-admin.d.ts +173 -0
- package/dist/src/recovery-admin.js +400 -0
- package/dist/src/revocations.js +3 -1
- package/dist/src/root-events.d.ts +107 -0
- package/dist/src/root-events.js +376 -0
- package/dist/src/time.d.ts +19 -3
- package/dist/src/time.js +50 -8
- package/dist/src/timestamp.d.ts +61 -0
- package/dist/src/timestamp.js +107 -0
- package/dist/src/tree-digest.d.ts +4 -0
- package/dist/src/tree-digest.js +41 -16
- package/dist/src/trust-root.d.ts +5 -0
- package/dist/src/trust-root.js +34 -13
- package/dist/src/verify.d.ts +69 -13
- package/dist/src/verify.js +309 -61
- package/docs/hosts/adapter-interface.md +8 -2
- package/docs/hosts/github-action.md +3 -3
- package/docs/hosts/pi.md +10 -3
- package/docs/spec/gui-admin-rack-v1.md +289 -0
- package/docs/spec/root-recovery-v1.md +451 -0
- package/docs/spec/skill-certificate-v1.md +1 -1
- package/docs/spec/skill-tree-v2.md +2 -2
- package/docs/spec/trust-documents-v1.md +12 -6
- package/docs/spec/verification.md +20 -3
- package/docs/threat-model.md +9 -6
- package/package.json +49 -44
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { type KeyObject } from 'node:crypto';
|
|
2
|
+
import { type PublicKeyInfo } from './keys.ts';
|
|
3
|
+
export declare const ROOT_EVENT_PAYLOAD_TYPE = "application/vnd.mago-ski.root-event+json";
|
|
4
|
+
export declare const ROOT_EVENT_TYPE = "mago.root-event/v1";
|
|
5
|
+
export declare const ROOT_EVENTS_TYPE = "mago.root-events/v1";
|
|
6
|
+
export declare const MAX_ROOT_EVENTS = 256;
|
|
7
|
+
export declare const MAX_ROOT_EVENTS_BYTES: number;
|
|
8
|
+
export declare const MAX_RECOVERY_KEYS = 16;
|
|
9
|
+
/** 16 current + 16 new recovery keys + the new root + the new timestamp key. */
|
|
10
|
+
export declare const MAX_EVENT_SIGNATURES: number;
|
|
11
|
+
export declare const MAX_ROOT_EVENT_REASON = 1024;
|
|
12
|
+
export interface RecoverySet {
|
|
13
|
+
/** Sorted, unique fingerprints. */
|
|
14
|
+
keyIds: string[];
|
|
15
|
+
rotateThreshold: number;
|
|
16
|
+
revokeThreshold: number;
|
|
17
|
+
}
|
|
18
|
+
export interface RootEvent {
|
|
19
|
+
sequence: number;
|
|
20
|
+
action: 'revoke' | 'rotate';
|
|
21
|
+
rootKeyId: string;
|
|
22
|
+
issuedAt: Date;
|
|
23
|
+
reason: string;
|
|
24
|
+
signers: PublicKeyInfo[];
|
|
25
|
+
newRoot?: PublicKeyInfo;
|
|
26
|
+
newRecovery?: RecoverySet;
|
|
27
|
+
newTimestamp?: PublicKeyInfo;
|
|
28
|
+
}
|
|
29
|
+
/** A DSSE envelope with one or more signatures, sorted by keyid. */
|
|
30
|
+
export interface MultiEnvelope {
|
|
31
|
+
payloadType: string;
|
|
32
|
+
payload: string;
|
|
33
|
+
signatures: Array<{
|
|
34
|
+
keyid: string;
|
|
35
|
+
sig: string;
|
|
36
|
+
}>;
|
|
37
|
+
}
|
|
38
|
+
/** Where a walk starts: the keys the policy pins and how many events they already reflect. */
|
|
39
|
+
export interface RootStart {
|
|
40
|
+
rootKeyId: string;
|
|
41
|
+
recovery: RecoverySet;
|
|
42
|
+
timestampKeyId: string | null;
|
|
43
|
+
eventsAfter: number;
|
|
44
|
+
}
|
|
45
|
+
export interface RootWalk {
|
|
46
|
+
activeRootKeyId: string;
|
|
47
|
+
recovery: RecoverySet;
|
|
48
|
+
timestampKeyId: string | null;
|
|
49
|
+
/** Set while the active root is revoked (only a rotate clears it). */
|
|
50
|
+
revoked: {
|
|
51
|
+
sequence: number;
|
|
52
|
+
reason: string;
|
|
53
|
+
} | null;
|
|
54
|
+
/** Number of events in the log. */
|
|
55
|
+
count: number;
|
|
56
|
+
/** `sha256:<hex>` of each event envelope as canonical JSON; index i is sequence i + 1. */
|
|
57
|
+
eventDigests: string[];
|
|
58
|
+
/** SHA-256 (hex) of the log file's bytes. */
|
|
59
|
+
logSha256: string;
|
|
60
|
+
/** Root and timestamp keys that left their role in the walked events (sorted); they never take another. */
|
|
61
|
+
retired: string[];
|
|
62
|
+
/** Keys that were in a recovery set and left it in the walked events (sorted). */
|
|
63
|
+
formerRecovery: string[];
|
|
64
|
+
}
|
|
65
|
+
/** True when the text has no control, line-separator, bidirectional or invisible formatting characters. */
|
|
66
|
+
export declare function isDisplaySafeText(text: string): boolean;
|
|
67
|
+
export declare function requireDisplaySafeText(value: unknown, label: string, maxLength: number): string;
|
|
68
|
+
/** Validates a recovery set as written in a policy or a rotate event (snake_case JSON). */
|
|
69
|
+
export declare function parseRecoverySet(value: unknown, label: string): RecoverySet;
|
|
70
|
+
export declare function recoverySetJson(set: RecoverySet): Record<string, unknown>;
|
|
71
|
+
export declare function rootEventPayload(event: RootEvent): Record<string, unknown>;
|
|
72
|
+
/** Reads and checks the shape of a root event payload. Signatures and the rules against host state are checked by the walk. */
|
|
73
|
+
export declare function parseRootEventPayload(bytes: Uint8Array): RootEvent;
|
|
74
|
+
/** Parses a DSSE envelope object with 0..max signatures (a proposal may have none yet). */
|
|
75
|
+
export declare function parseMultiEnvelope(value: unknown, label: string, options: {
|
|
76
|
+
minSignatures: number;
|
|
77
|
+
}): MultiEnvelope & {
|
|
78
|
+
payloadBytes: Buffer;
|
|
79
|
+
sigBytes: Buffer[];
|
|
80
|
+
};
|
|
81
|
+
/** Keys whose signatures a root event must carry, exactly: its signers, plus the new root and new timestamp key of a rotate. */
|
|
82
|
+
export declare function requiredSigners(event: RootEvent): PublicKeyInfo[];
|
|
83
|
+
/** Adds (or replaces) one signature on an envelope, keeping signatures sorted by keyid. */
|
|
84
|
+
export declare function addEnvelopeSignature(envelope: MultiEnvelope, keyId: string, privateKey: KeyObject): MultiEnvelope;
|
|
85
|
+
export declare function unsignedEventEnvelope(event: RootEvent): MultiEnvelope;
|
|
86
|
+
export declare function emptyRootEventLog(): Buffer;
|
|
87
|
+
export declare function rootEventLogBytes(envelopes: MultiEnvelope[]): Buffer;
|
|
88
|
+
/** `sha256:` + the SHA-256 of the envelope as canonical JSON with its trailing LF (the host state's event_digest). */
|
|
89
|
+
export declare function eventDigest(envelope: MultiEnvelope): string;
|
|
90
|
+
/** Parses the log file. Each envelope's structure is checked; signatures and rules are checked by the walk. */
|
|
91
|
+
export declare function parseRootEventLog(bytes: Uint8Array): Array<MultiEnvelope & {
|
|
92
|
+
payloadBytes: Buffer;
|
|
93
|
+
sigBytes: Buffer[];
|
|
94
|
+
}>;
|
|
95
|
+
/**
|
|
96
|
+
* Walks the root event log from the policy's starting point. Throws (the log is UNVERIFIABLE) if any event after
|
|
97
|
+
* `eventsAfter` breaks a rule; events are never skipped. Hashes every event so rollback and fork checks can use them.
|
|
98
|
+
*/
|
|
99
|
+
export declare function walkRootEvents(bytes: Uint8Array, start: RootStart, now: Date): RootWalk;
|
|
100
|
+
/**
|
|
101
|
+
* walkRootEvents with a cache of successful walks, keyed by the starting point and the log's SHA-256. A walk that
|
|
102
|
+
* succeeded stays valid as time passes (only "issued in the future" depends on the clock, and that only relaxes),
|
|
103
|
+
* so an unchanged log costs one hash. Failed walks are not cached.
|
|
104
|
+
*/
|
|
105
|
+
export declare function walkRootEventsCached(bytes: Uint8Array, start: RootStart, now: Date): RootWalk;
|
|
106
|
+
/** Tests only. */
|
|
107
|
+
export declare function clearRootWalkCache(): void;
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
// Root recovery (docs/spec/root-recovery-v1.md): a recovery set of offline keys, pinned by fingerprint in the host
|
|
2
|
+
// policy, signs numbered root events that revoke or replace the root key. Hosts walk the log from the policy's
|
|
3
|
+
// starting point at every trust check; one event that breaks a rule makes the whole log UNVERIFIABLE.
|
|
4
|
+
import { sign, verify } from 'node:crypto';
|
|
5
|
+
import { canonicalBytes, exactKeys, isRecord, parseCanonicalJsonBytes, requireArray, requirePositiveInteger, requireString } from "./canonical-json.js";
|
|
6
|
+
import { preAuthEncoding } from "./dsse.js";
|
|
7
|
+
import { parseSpki, validateKeyId } from "./keys.js";
|
|
8
|
+
import { CLOCK_SKEW_MS, formatTimestamp, parseTimestamp, requireValidDate } from "./time.js";
|
|
9
|
+
import { sha256Hex } from "./tree-digest.js";
|
|
10
|
+
export const ROOT_EVENT_PAYLOAD_TYPE = 'application/vnd.mago-ski.root-event+json';
|
|
11
|
+
export const ROOT_EVENT_TYPE = 'mago.root-event/v1';
|
|
12
|
+
export const ROOT_EVENTS_TYPE = 'mago.root-events/v1';
|
|
13
|
+
export const MAX_ROOT_EVENTS = 256;
|
|
14
|
+
export const MAX_ROOT_EVENTS_BYTES = 4 * 1024 * 1024;
|
|
15
|
+
export const MAX_RECOVERY_KEYS = 16;
|
|
16
|
+
/** 16 current + 16 new recovery keys + the new root + the new timestamp key. */
|
|
17
|
+
export const MAX_EVENT_SIGNATURES = 2 * MAX_RECOVERY_KEYS + 2;
|
|
18
|
+
export const MAX_ROOT_EVENT_REASON = 1024;
|
|
19
|
+
const MAX_EVENT_PAYLOAD_BYTES = 64 * 1024;
|
|
20
|
+
const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
|
|
21
|
+
/**
|
|
22
|
+
* Reasons are shown in verdicts, terminals, notifications, annotations and Pi block messages the model reads.
|
|
23
|
+
* Besides the C0 controls that requireString refuses, refuse every other control (Cc), format (Cf: bidirectional
|
|
24
|
+
* marks, zero-width characters, soft hyphens, tag characters), surrogate (Cs), private-use (Co) and unassigned (Cn)
|
|
25
|
+
* code point, line and paragraph separators, and variation selectors, so a reason cannot hide, reorder or smuggle
|
|
26
|
+
* text where it is displayed. One stolen recovery key can sign a revoke, so its reason must stay plain text.
|
|
27
|
+
*/
|
|
28
|
+
const UNSAFE_DISPLAY_PATTERN = /[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\u{FE00}-\u{FE0F}\u{E0100}-\u{E01EF}\u{180B}-\u{180F}]/u;
|
|
29
|
+
/** True when the text has no control, line-separator, bidirectional or invisible formatting characters. */
|
|
30
|
+
export function isDisplaySafeText(text) {
|
|
31
|
+
return !UNSAFE_DISPLAY_PATTERN.test(text);
|
|
32
|
+
}
|
|
33
|
+
export function requireDisplaySafeText(value, label, maxLength) {
|
|
34
|
+
const text = requireString(value, label, maxLength);
|
|
35
|
+
if (!isDisplaySafeText(text))
|
|
36
|
+
throw new Error(`${label} must not contain control, line-separator, bidirectional or invisible formatting characters`);
|
|
37
|
+
return text;
|
|
38
|
+
}
|
|
39
|
+
function requireSortedUnique(values, label) {
|
|
40
|
+
for (let index = 1; index < values.length; index += 1)
|
|
41
|
+
if (values[index - 1] >= values[index])
|
|
42
|
+
throw new Error(`${label} must be unique and sorted`);
|
|
43
|
+
}
|
|
44
|
+
function decodeBase64(value, label, maxLength) {
|
|
45
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > maxLength || !BASE64_PATTERN.test(value))
|
|
46
|
+
throw new Error(`${label} must be canonical base64`);
|
|
47
|
+
const bytes = Buffer.from(value, 'base64');
|
|
48
|
+
if (bytes.toString('base64') !== value)
|
|
49
|
+
throw new Error(`${label} must be canonical base64`);
|
|
50
|
+
return bytes;
|
|
51
|
+
}
|
|
52
|
+
/** Validates a recovery set as written in a policy or a rotate event (snake_case JSON). */
|
|
53
|
+
export function parseRecoverySet(value, label) {
|
|
54
|
+
const entry = exactKeys(value, ['key_ids', 'rotate_threshold', 'revoke_threshold'], label);
|
|
55
|
+
const keyIds = requireArray(entry.key_ids, `${label} key_ids`, MAX_RECOVERY_KEYS)
|
|
56
|
+
.map((item, index) => validateKeyId(item, `${label} key_ids[${index}]`));
|
|
57
|
+
if (keyIds.length === 0)
|
|
58
|
+
throw new Error(`${label} key_ids must list at least one key`);
|
|
59
|
+
requireSortedUnique(keyIds, `${label} key_ids`);
|
|
60
|
+
const rotateThreshold = requirePositiveInteger(entry.rotate_threshold, `${label} rotate_threshold`);
|
|
61
|
+
const revokeThreshold = requirePositiveInteger(entry.revoke_threshold, `${label} revoke_threshold`);
|
|
62
|
+
if (!(revokeThreshold <= rotateThreshold && rotateThreshold <= keyIds.length))
|
|
63
|
+
throw new Error(`${label} needs 1 <= revoke_threshold <= rotate_threshold <= number of key_ids`);
|
|
64
|
+
return { keyIds, rotateThreshold, revokeThreshold };
|
|
65
|
+
}
|
|
66
|
+
export function recoverySetJson(set) {
|
|
67
|
+
return { key_ids: [...set.keyIds], rotate_threshold: set.rotateThreshold, revoke_threshold: set.revokeThreshold };
|
|
68
|
+
}
|
|
69
|
+
const keyJson = (key) => ({ key_id: key.keyId, public_key: key.spki });
|
|
70
|
+
export function rootEventPayload(event) {
|
|
71
|
+
const payload = {
|
|
72
|
+
type: ROOT_EVENT_TYPE,
|
|
73
|
+
sequence: event.sequence,
|
|
74
|
+
action: event.action,
|
|
75
|
+
root_key_id: event.rootKeyId,
|
|
76
|
+
issued_at: formatTimestamp(event.issuedAt),
|
|
77
|
+
reason: event.reason,
|
|
78
|
+
signers: [...event.signers].sort((a, b) => (a.keyId < b.keyId ? -1 : 1)).map(keyJson),
|
|
79
|
+
};
|
|
80
|
+
if (event.action === 'rotate') {
|
|
81
|
+
if (!event.newRoot || !event.newRecovery)
|
|
82
|
+
throw new Error('a rotate event needs a new root and a new recovery set');
|
|
83
|
+
payload.new_root = keyJson(event.newRoot);
|
|
84
|
+
payload.new_recovery = recoverySetJson(event.newRecovery);
|
|
85
|
+
if (event.newTimestamp)
|
|
86
|
+
payload.new_timestamp = keyJson(event.newTimestamp);
|
|
87
|
+
}
|
|
88
|
+
return payload;
|
|
89
|
+
}
|
|
90
|
+
const EVENT_FIELDS = ['type', 'sequence', 'action', 'root_key_id', 'issued_at', 'reason', 'signers'];
|
|
91
|
+
const ROTATE_FIELDS = [...EVENT_FIELDS, 'new_root', 'new_recovery'];
|
|
92
|
+
function parseKey(value, label) {
|
|
93
|
+
const entry = exactKeys(value, ['key_id', 'public_key'], label);
|
|
94
|
+
return parseSpki(entry.public_key, `${label} public_key`, validateKeyId(entry.key_id, `${label} key_id`));
|
|
95
|
+
}
|
|
96
|
+
/** Reads and checks the shape of a root event payload. Signatures and the rules against host state are checked by the walk. */
|
|
97
|
+
export function parseRootEventPayload(bytes) {
|
|
98
|
+
const label = 'root event';
|
|
99
|
+
const raw = parseCanonicalJsonBytes(bytes, label);
|
|
100
|
+
if (!isRecord(raw))
|
|
101
|
+
throw new Error(`${label} must be a JSON object`);
|
|
102
|
+
const action = raw.action;
|
|
103
|
+
if (action !== 'revoke' && action !== 'rotate')
|
|
104
|
+
throw new Error(`${label} action must be "revoke" or "rotate"`);
|
|
105
|
+
const fields = action === 'revoke' ? EVENT_FIELDS : 'new_timestamp' in raw ? [...ROTATE_FIELDS, 'new_timestamp'] : ROTATE_FIELDS;
|
|
106
|
+
const value = exactKeys(raw, fields, label);
|
|
107
|
+
if (value.type !== ROOT_EVENT_TYPE)
|
|
108
|
+
throw new Error(`${label} has unsupported type`);
|
|
109
|
+
const signers = requireArray(value.signers, `${label} signers`, 2 * MAX_RECOVERY_KEYS)
|
|
110
|
+
.map((item, index) => parseKey(item, `${label} signers[${index}]`));
|
|
111
|
+
if (signers.length === 0)
|
|
112
|
+
throw new Error(`${label} needs at least one signer`);
|
|
113
|
+
requireSortedUnique(signers.map((key) => key.keyId), `${label} signers`);
|
|
114
|
+
const event = {
|
|
115
|
+
sequence: requirePositiveInteger(value.sequence, `${label} sequence`),
|
|
116
|
+
action,
|
|
117
|
+
rootKeyId: validateKeyId(value.root_key_id, `${label} root_key_id`),
|
|
118
|
+
issuedAt: parseTimestamp(value.issued_at, `${label} issued_at`),
|
|
119
|
+
reason: requireDisplaySafeText(value.reason, `${label} reason`, MAX_ROOT_EVENT_REASON),
|
|
120
|
+
signers,
|
|
121
|
+
};
|
|
122
|
+
if (action === 'rotate') {
|
|
123
|
+
event.newRoot = parseKey(value.new_root, `${label} new_root`);
|
|
124
|
+
event.newRecovery = parseRecoverySet(value.new_recovery, `${label} new_recovery`);
|
|
125
|
+
if (value.new_timestamp !== undefined)
|
|
126
|
+
event.newTimestamp = parseKey(value.new_timestamp, `${label} new_timestamp`);
|
|
127
|
+
}
|
|
128
|
+
return event;
|
|
129
|
+
}
|
|
130
|
+
/** Parses a DSSE envelope object with 0..max signatures (a proposal may have none yet). */
|
|
131
|
+
export function parseMultiEnvelope(value, label, options) {
|
|
132
|
+
const entry = exactKeys(value, ['payloadType', 'payload', 'signatures'], label);
|
|
133
|
+
const payloadType = requireString(entry.payloadType, `${label} payloadType`, 256);
|
|
134
|
+
const payloadBytes = decodeBase64(entry.payload, `${label} payload`, Math.ceil(MAX_EVENT_PAYLOAD_BYTES / 3) * 4);
|
|
135
|
+
const items = requireArray(entry.signatures, `${label} signatures`, MAX_EVENT_SIGNATURES);
|
|
136
|
+
if (items.length < options.minSignatures)
|
|
137
|
+
throw new Error(`${label} must carry at least ${options.minSignatures} signature(s)`);
|
|
138
|
+
const signatures = [];
|
|
139
|
+
const sigBytes = [];
|
|
140
|
+
for (const [index, item] of items.entries()) {
|
|
141
|
+
const signature = exactKeys(item, ['keyid', 'sig'], `${label} signatures[${index}]`);
|
|
142
|
+
const keyid = validateKeyId(signature.keyid, `${label} signatures[${index}] keyid`);
|
|
143
|
+
const bytes = decodeBase64(signature.sig, `${label} signatures[${index}] sig`, 128);
|
|
144
|
+
if (bytes.length !== 64)
|
|
145
|
+
throw new Error(`${label} signatures[${index}] must be a 64-byte Ed25519 signature`);
|
|
146
|
+
signatures.push({ keyid, sig: signature.sig });
|
|
147
|
+
sigBytes.push(bytes);
|
|
148
|
+
}
|
|
149
|
+
requireSortedUnique(signatures.map((item) => item.keyid), `${label} signatures`);
|
|
150
|
+
return { payloadType, payload: entry.payload, signatures, payloadBytes, sigBytes };
|
|
151
|
+
}
|
|
152
|
+
/** Keys whose signatures a root event must carry, exactly: its signers, plus the new root and new timestamp key of a rotate. */
|
|
153
|
+
export function requiredSigners(event) {
|
|
154
|
+
const keys = [...event.signers];
|
|
155
|
+
if (event.newRoot)
|
|
156
|
+
keys.push(event.newRoot);
|
|
157
|
+
if (event.newTimestamp)
|
|
158
|
+
keys.push(event.newTimestamp);
|
|
159
|
+
return keys.sort((a, b) => (a.keyId < b.keyId ? -1 : 1));
|
|
160
|
+
}
|
|
161
|
+
/** Adds (or replaces) one signature on an envelope, keeping signatures sorted by keyid. */
|
|
162
|
+
export function addEnvelopeSignature(envelope, keyId, privateKey) {
|
|
163
|
+
const payload = Buffer.from(envelope.payload, 'base64');
|
|
164
|
+
const sig = sign(null, preAuthEncoding(envelope.payloadType, payload), privateKey).toString('base64');
|
|
165
|
+
const signatures = [...envelope.signatures.filter((item) => item.keyid !== keyId), { keyid: keyId, sig }]
|
|
166
|
+
.sort((a, b) => (a.keyid < b.keyid ? -1 : 1));
|
|
167
|
+
return { payloadType: envelope.payloadType, payload: envelope.payload, signatures };
|
|
168
|
+
}
|
|
169
|
+
export function unsignedEventEnvelope(event) {
|
|
170
|
+
return {
|
|
171
|
+
payloadType: ROOT_EVENT_PAYLOAD_TYPE,
|
|
172
|
+
payload: canonicalBytes(rootEventPayload(event)).toString('base64'),
|
|
173
|
+
signatures: [],
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
export function emptyRootEventLog() {
|
|
177
|
+
return canonicalBytes({ events: [], type: ROOT_EVENTS_TYPE });
|
|
178
|
+
}
|
|
179
|
+
export function rootEventLogBytes(envelopes) {
|
|
180
|
+
return canonicalBytes({ events: envelopes, type: ROOT_EVENTS_TYPE });
|
|
181
|
+
}
|
|
182
|
+
/** `sha256:` + the SHA-256 of the envelope as canonical JSON with its trailing LF (the host state's event_digest). */
|
|
183
|
+
export function eventDigest(envelope) {
|
|
184
|
+
return `sha256:${sha256Hex(canonicalBytes({ payload: envelope.payload, payloadType: envelope.payloadType, signatures: envelope.signatures }))}`;
|
|
185
|
+
}
|
|
186
|
+
/** Parses the log file. Each envelope's structure is checked; signatures and rules are checked by the walk. */
|
|
187
|
+
export function parseRootEventLog(bytes) {
|
|
188
|
+
if (bytes.byteLength > MAX_ROOT_EVENTS_BYTES)
|
|
189
|
+
throw new Error(`root event log exceeds the ${MAX_ROOT_EVENTS_BYTES}-byte limit`);
|
|
190
|
+
const value = exactKeys(parseCanonicalJsonBytes(bytes, 'root event log'), ['events', 'type'], 'root event log');
|
|
191
|
+
if (value.type !== ROOT_EVENTS_TYPE)
|
|
192
|
+
throw new Error('root event log has unsupported type');
|
|
193
|
+
return requireArray(value.events, 'root event log events', MAX_ROOT_EVENTS)
|
|
194
|
+
.map((item, index) => parseMultiEnvelope(item, `root event ${index + 1}`, { minSignatures: 1 }));
|
|
195
|
+
}
|
|
196
|
+
function checkRoles(state, label) {
|
|
197
|
+
if (state.recovery.keyIds.includes(state.activeRootKeyId))
|
|
198
|
+
throw new Error(`${label}: the root key must not also be a recovery key`);
|
|
199
|
+
if (state.timestampKeyId !== null) {
|
|
200
|
+
if (state.timestampKeyId === state.activeRootKeyId)
|
|
201
|
+
throw new Error(`${label}: the timestamp key must not also be the root key`);
|
|
202
|
+
if (state.recovery.keyIds.includes(state.timestampKeyId))
|
|
203
|
+
throw new Error(`${label}: the timestamp key must not also be a recovery key`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/** Checks one event against the state just before it, including every signature, and returns the state after it. */
|
|
207
|
+
function applyEvent(state, envelope, sequence, now) {
|
|
208
|
+
const label = `root event ${sequence}`;
|
|
209
|
+
if (envelope.payloadType !== ROOT_EVENT_PAYLOAD_TYPE)
|
|
210
|
+
throw new Error(`${label} has the wrong payload type`);
|
|
211
|
+
let event;
|
|
212
|
+
try {
|
|
213
|
+
event = parseRootEventPayload(envelope.payloadBytes);
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
throw new Error(`${label}: ${error.message}`);
|
|
217
|
+
}
|
|
218
|
+
if (event.sequence !== sequence)
|
|
219
|
+
throw new Error(`${label} carries sequence ${event.sequence}`);
|
|
220
|
+
if (event.rootKeyId !== state.activeRootKeyId)
|
|
221
|
+
throw new Error(`${label} names root key ${event.rootKeyId}, but the active root key is ${state.activeRootKeyId}`);
|
|
222
|
+
if (event.issuedAt.getTime() > now.getTime() + CLOCK_SKEW_MS)
|
|
223
|
+
throw new Error(`${label} is issued in the future (${formatTimestamp(event.issuedAt)})`);
|
|
224
|
+
if (state.lastIssuedAt && event.issuedAt < state.lastIssuedAt)
|
|
225
|
+
throw new Error(`${label} is issued before the event before it`);
|
|
226
|
+
const current = state.recovery;
|
|
227
|
+
const inCurrent = (keyId) => current.keyIds.includes(keyId);
|
|
228
|
+
const signerIds = event.signers.map((key) => key.keyId);
|
|
229
|
+
let next;
|
|
230
|
+
if (event.action === 'revoke') {
|
|
231
|
+
if (state.revoked)
|
|
232
|
+
throw new Error(`${label} revokes root key ${event.rootKeyId}, which root event ${state.revoked.sequence} already revoked`);
|
|
233
|
+
if (!signerIds.every(inCurrent))
|
|
234
|
+
throw new Error(`${label} is signed by a key that is not in the current recovery set`);
|
|
235
|
+
if (signerIds.length < current.revokeThreshold)
|
|
236
|
+
throw new Error(`${label} has ${signerIds.length} recovery signature(s); a revoke needs ${current.revokeThreshold}`);
|
|
237
|
+
const retired = new Set(state.retired);
|
|
238
|
+
retired.add(state.activeRootKeyId);
|
|
239
|
+
next = { ...state, revoked: { sequence, reason: event.reason }, retired, lastIssuedAt: event.issuedAt };
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
const newRoot = event.newRoot;
|
|
243
|
+
const newRecovery = event.newRecovery;
|
|
244
|
+
const newTimestamp = event.newTimestamp;
|
|
245
|
+
const inNew = (keyId) => newRecovery.keyIds.includes(keyId);
|
|
246
|
+
if (inCurrent(newRoot.keyId) || inNew(newRoot.keyId))
|
|
247
|
+
throw new Error(`${label}: the new root key must not be a recovery key`);
|
|
248
|
+
if (newRoot.keyId === event.rootKeyId ? state.revoked !== null : state.retired.has(newRoot.keyId))
|
|
249
|
+
throw new Error(`${label}: the new root key ${newRoot.keyId} has left the root role and cannot return`);
|
|
250
|
+
if (newRoot.keyId === state.timestampKeyId || newRoot.keyId === newTimestamp?.keyId)
|
|
251
|
+
throw new Error(`${label}: the new root key must not also be a timestamp key`);
|
|
252
|
+
for (const keyId of newRecovery.keyIds)
|
|
253
|
+
if (state.retired.has(keyId) || keyId === state.activeRootKeyId || keyId === state.timestampKeyId)
|
|
254
|
+
throw new Error(`${label}: recovery key ${keyId} has held the root or timestamp role`);
|
|
255
|
+
if (newTimestamp) {
|
|
256
|
+
const id = newTimestamp.keyId;
|
|
257
|
+
if (id === event.rootKeyId || id === newRoot.keyId)
|
|
258
|
+
throw new Error(`${label}: the new timestamp key must not be a root key`);
|
|
259
|
+
if (inCurrent(id) || inNew(id))
|
|
260
|
+
throw new Error(`${label}: the new timestamp key must not be a recovery key`);
|
|
261
|
+
if (state.retired.has(id))
|
|
262
|
+
throw new Error(`${label}: the new timestamp key ${id} has left a role and cannot return`);
|
|
263
|
+
}
|
|
264
|
+
if (!signerIds.every((keyId) => inCurrent(keyId) || inNew(keyId)))
|
|
265
|
+
throw new Error(`${label} is signed by a key that is in neither the current nor the new recovery set`);
|
|
266
|
+
const fromCurrent = signerIds.filter(inCurrent).length;
|
|
267
|
+
const fromNew = signerIds.filter(inNew).length;
|
|
268
|
+
if (fromCurrent < current.rotateThreshold)
|
|
269
|
+
throw new Error(`${label} has ${fromCurrent} signature(s) from the current recovery set; a rotate needs ${current.rotateThreshold}`);
|
|
270
|
+
if (fromNew < newRecovery.rotateThreshold)
|
|
271
|
+
throw new Error(`${label} has ${fromNew} signature(s) from the new recovery set; it needs ${newRecovery.rotateThreshold}`);
|
|
272
|
+
const formerRecovery = new Set(state.formerRecovery);
|
|
273
|
+
for (const keyId of current.keyIds)
|
|
274
|
+
if (!inNew(keyId))
|
|
275
|
+
formerRecovery.add(keyId);
|
|
276
|
+
const retired = new Set(state.retired);
|
|
277
|
+
if (newRoot.keyId !== state.activeRootKeyId)
|
|
278
|
+
retired.add(state.activeRootKeyId);
|
|
279
|
+
if (newTimestamp && state.timestampKeyId !== null && newTimestamp.keyId !== state.timestampKeyId)
|
|
280
|
+
retired.add(state.timestampKeyId);
|
|
281
|
+
next = {
|
|
282
|
+
activeRootKeyId: newRoot.keyId,
|
|
283
|
+
recovery: newRecovery,
|
|
284
|
+
timestampKeyId: newTimestamp ? newTimestamp.keyId : state.timestampKeyId,
|
|
285
|
+
revoked: null,
|
|
286
|
+
retired,
|
|
287
|
+
formerRecovery,
|
|
288
|
+
lastIssuedAt: event.issuedAt,
|
|
289
|
+
};
|
|
290
|
+
checkRoles(next, label);
|
|
291
|
+
}
|
|
292
|
+
// Signatures last: exactly the required keys, each valid. An unknown or invalid signature rejects the event.
|
|
293
|
+
const required = requiredSigners(event);
|
|
294
|
+
if (envelope.signatures.length !== required.length || envelope.signatures.some((item, index) => item.keyid !== required[index].keyId))
|
|
295
|
+
throw new Error(`${label} must be signed by exactly ${required.map((key) => key.keyId).join(', ')}`);
|
|
296
|
+
const pae = preAuthEncoding(envelope.payloadType, envelope.payloadBytes);
|
|
297
|
+
for (const [index, key] of required.entries()) {
|
|
298
|
+
let valid = false;
|
|
299
|
+
try {
|
|
300
|
+
valid = verify(null, pae, key.publicKey, envelope.sigBytes[index]);
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
valid = false;
|
|
304
|
+
}
|
|
305
|
+
if (!valid)
|
|
306
|
+
throw new Error(`${label} has an invalid signature from ${key.keyId}`);
|
|
307
|
+
}
|
|
308
|
+
return next;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Walks the root event log from the policy's starting point. Throws (the log is UNVERIFIABLE) if any event after
|
|
312
|
+
* `eventsAfter` breaks a rule; events are never skipped. Hashes every event so rollback and fork checks can use them.
|
|
313
|
+
*/
|
|
314
|
+
export function walkRootEvents(bytes, start, now) {
|
|
315
|
+
requireValidDate(now, 'Verification time');
|
|
316
|
+
checkRoles({ activeRootKeyId: start.rootKeyId, recovery: start.recovery, timestampKeyId: start.timestampKeyId }, 'policy');
|
|
317
|
+
const envelopes = parseRootEventLog(bytes);
|
|
318
|
+
if (envelopes.length < start.eventsAfter)
|
|
319
|
+
throw new Error(`root event log has ${envelopes.length} event(s), fewer than root_events_after (${start.eventsAfter})`);
|
|
320
|
+
let state = {
|
|
321
|
+
activeRootKeyId: start.rootKeyId,
|
|
322
|
+
recovery: start.recovery,
|
|
323
|
+
timestampKeyId: start.timestampKeyId,
|
|
324
|
+
revoked: null,
|
|
325
|
+
retired: new Set(),
|
|
326
|
+
formerRecovery: new Set(),
|
|
327
|
+
lastIssuedAt: null,
|
|
328
|
+
};
|
|
329
|
+
for (let index = start.eventsAfter; index < envelopes.length; index += 1)
|
|
330
|
+
state = applyEvent(state, envelopes[index], index + 1, now);
|
|
331
|
+
return {
|
|
332
|
+
activeRootKeyId: state.activeRootKeyId,
|
|
333
|
+
recovery: { ...state.recovery, keyIds: [...state.recovery.keyIds] },
|
|
334
|
+
timestampKeyId: state.timestampKeyId,
|
|
335
|
+
revoked: state.revoked,
|
|
336
|
+
count: envelopes.length,
|
|
337
|
+
eventDigests: envelopes.map(eventDigest),
|
|
338
|
+
logSha256: sha256Hex(bytes),
|
|
339
|
+
retired: [...state.retired].sort(),
|
|
340
|
+
formerRecovery: [...state.formerRecovery].sort(),
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
const WALK_CACHE_LIMIT = 32;
|
|
344
|
+
const walkCache = new Map();
|
|
345
|
+
/**
|
|
346
|
+
* walkRootEvents with a cache of successful walks, keyed by the starting point and the log's SHA-256. A walk that
|
|
347
|
+
* succeeded stays valid as time passes (only "issued in the future" depends on the clock, and that only relaxes),
|
|
348
|
+
* so an unchanged log costs one hash. Failed walks are not cached.
|
|
349
|
+
*/
|
|
350
|
+
export function walkRootEventsCached(bytes, start, now) {
|
|
351
|
+
const key = JSON.stringify([start.rootKeyId, recoverySetJson(start.recovery), start.timestampKeyId, start.eventsAfter, sha256Hex(bytes)]);
|
|
352
|
+
const hit = walkCache.get(key);
|
|
353
|
+
if (hit) {
|
|
354
|
+
requireValidDate(now, 'Verification time');
|
|
355
|
+
return cloneWalk(hit);
|
|
356
|
+
}
|
|
357
|
+
const walk = walkRootEvents(bytes, start, now);
|
|
358
|
+
if (walkCache.size >= WALK_CACHE_LIMIT)
|
|
359
|
+
walkCache.delete(walkCache.keys().next().value);
|
|
360
|
+
walkCache.set(key, cloneWalk(walk));
|
|
361
|
+
return walk;
|
|
362
|
+
}
|
|
363
|
+
function cloneWalk(walk) {
|
|
364
|
+
return {
|
|
365
|
+
...walk,
|
|
366
|
+
recovery: { ...walk.recovery, keyIds: [...walk.recovery.keyIds] },
|
|
367
|
+
revoked: walk.revoked ? { ...walk.revoked } : null,
|
|
368
|
+
eventDigests: [...walk.eventDigests],
|
|
369
|
+
retired: [...walk.retired],
|
|
370
|
+
formerRecovery: [...walk.formerRecovery],
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/** Tests only. */
|
|
374
|
+
export function clearRootWalkCache() {
|
|
375
|
+
walkCache.clear();
|
|
376
|
+
}
|
package/dist/src/time.d.ts
CHANGED
|
@@ -1,9 +1,25 @@
|
|
|
1
1
|
/** Allowed clock skew when checking that a signed object was not issued in the future. */
|
|
2
2
|
export declare const CLOCK_SKEW_MS: number;
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Throws unless `date` is a Date that holds a real time.
|
|
5
|
+
* An invalid Date holds NaN, and every comparison with NaN is false,
|
|
6
|
+
* so an expiry check against it would silently pass.
|
|
7
|
+
* Every function that compares documents against the current time calls this on `now` first.
|
|
8
|
+
*/
|
|
9
|
+
export declare function requireValidDate(date: Date, label: string): void;
|
|
10
|
+
/**
|
|
11
|
+
* Writes a date as a UTC timestamp with whole seconds, e.g. 2026-10-09T12:00:00Z.
|
|
12
|
+
* Milliseconds are dropped.
|
|
13
|
+
*/
|
|
4
14
|
export declare function formatTimestamp(date: Date): string;
|
|
15
|
+
/**
|
|
16
|
+
* Reads a timestamp in the exact format formatTimestamp writes.
|
|
17
|
+
* Dates that do not exist (2026-02-30, 24:00:00) are rejected.
|
|
18
|
+
*/
|
|
5
19
|
export declare function parseTimestamp(value: unknown, label: string): Date;
|
|
6
|
-
/**
|
|
20
|
+
/** Reads a duration such as 90d, 12h or 30m and returns it in milliseconds. */
|
|
7
21
|
export declare function parseDuration(value: string, label?: string): number;
|
|
8
|
-
|
|
22
|
+
/** Returns `start` plus a duration such as 90d, rounded down to a whole second. */
|
|
23
|
+
export declare function addDuration(start: Date, duration: string, label?: string): Date;
|
|
24
|
+
/** Drops the milliseconds, so the date survives formatTimestamp and parseTimestamp unchanged. */
|
|
9
25
|
export declare function truncateToSecond(date: Date): Date;
|
package/dist/src/time.js
CHANGED
|
@@ -1,32 +1,74 @@
|
|
|
1
|
+
/** The only timestamp format accepted: UTC with whole seconds, e.g. 2026-10-09T12:00:00Z. */
|
|
1
2
|
const TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/u;
|
|
3
|
+
/** A duration is 1 to 5 digits plus a unit; 99999d (about 273 years) is the largest. */
|
|
4
|
+
const DURATION_PATTERN = /^(\d{1,5})([dhm])$/u;
|
|
5
|
+
const UNIT_MS = {
|
|
6
|
+
d: 24 * 60 * 60 * 1000,
|
|
7
|
+
h: 60 * 60 * 1000,
|
|
8
|
+
m: 60 * 1000,
|
|
9
|
+
};
|
|
2
10
|
/** Allowed clock skew when checking that a signed object was not issued in the future. */
|
|
3
11
|
export const CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
4
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* Throws unless `date` is a Date that holds a real time.
|
|
14
|
+
* An invalid Date holds NaN, and every comparison with NaN is false,
|
|
15
|
+
* so an expiry check against it would silently pass.
|
|
16
|
+
* Every function that compares documents against the current time calls this on `now` first.
|
|
17
|
+
*/
|
|
18
|
+
export function requireValidDate(date, label) {
|
|
19
|
+
if (!(date instanceof Date) || Number.isNaN(date.getTime()))
|
|
20
|
+
throw new Error(`${label} must be a valid date`);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Writes a date as a UTC timestamp with whole seconds, e.g. 2026-10-09T12:00:00Z.
|
|
24
|
+
* Milliseconds are dropped.
|
|
25
|
+
*/
|
|
5
26
|
export function formatTimestamp(date) {
|
|
6
|
-
|
|
27
|
+
requireValidDate(date, 'Date to format');
|
|
28
|
+
const text = date.toISOString().replace(/\.\d{3}Z$/u, 'Z');
|
|
29
|
+
// toISOString writes years outside 0000-9999 as "+010000-..." or "-000001-...".
|
|
30
|
+
// parseTimestamp rejects those, so a document signed with one could never be read back.
|
|
31
|
+
if (!TIMESTAMP_PATTERN.test(text))
|
|
32
|
+
throw new Error('Timestamp must fall between the years 0000 and 9999');
|
|
33
|
+
return text;
|
|
7
34
|
}
|
|
35
|
+
/**
|
|
36
|
+
* Reads a timestamp in the exact format formatTimestamp writes.
|
|
37
|
+
* Dates that do not exist (2026-02-30, 24:00:00) are rejected.
|
|
38
|
+
*/
|
|
8
39
|
export function parseTimestamp(value, label) {
|
|
9
40
|
if (typeof value !== 'string' || !TIMESTAMP_PATTERN.test(value))
|
|
10
41
|
throw new Error(`${label} must be a UTC timestamp like 2026-10-09T12:00:00Z`);
|
|
42
|
+
// Date quietly rolls impossible values over (2026-02-30 becomes March 2),
|
|
43
|
+
// so the parsed date must format back to exactly the same text.
|
|
11
44
|
const date = new Date(value);
|
|
12
45
|
if (Number.isNaN(date.getTime()) || formatTimestamp(date) !== value)
|
|
13
46
|
throw new Error(`${label} is not a valid timestamp`);
|
|
14
47
|
return date;
|
|
15
48
|
}
|
|
16
|
-
/**
|
|
49
|
+
/** Reads a duration such as 90d, 12h or 30m and returns it in milliseconds. */
|
|
17
50
|
export function parseDuration(value, label = 'duration') {
|
|
18
|
-
|
|
51
|
+
// The type says string, but this is a public export: plain JavaScript callers can pass anything.
|
|
52
|
+
const match = typeof value === 'string' ? DURATION_PATTERN.exec(value) : null;
|
|
19
53
|
if (!match)
|
|
20
54
|
throw new Error(`${label} must look like 90d, 12h or 30m`);
|
|
21
55
|
const amount = Number(match[1]);
|
|
22
56
|
if (amount < 1)
|
|
23
57
|
throw new Error(`${label} must be positive`);
|
|
24
|
-
|
|
25
|
-
|
|
58
|
+
// Five digits at most keeps the result (at most 8.64e12) well inside the safe integer range.
|
|
59
|
+
const unit = match[2];
|
|
60
|
+
return amount * UNIT_MS[unit];
|
|
26
61
|
}
|
|
27
|
-
|
|
28
|
-
|
|
62
|
+
/** Returns `start` plus a duration such as 90d, rounded down to a whole second. */
|
|
63
|
+
export function addDuration(start, duration, label = 'duration') {
|
|
64
|
+
requireValidDate(start, `${label} start`);
|
|
65
|
+
// Past the largest date JavaScript can hold (year 275760) the sum becomes an invalid Date.
|
|
66
|
+
const end = new Date(start.getTime() + parseDuration(duration, label));
|
|
67
|
+
requireValidDate(end, `${label} end`);
|
|
68
|
+
return truncateToSecond(end);
|
|
29
69
|
}
|
|
70
|
+
/** Drops the milliseconds, so the date survives formatTimestamp and parseTimestamp unchanged. */
|
|
30
71
|
export function truncateToSecond(date) {
|
|
72
|
+
requireValidDate(date, 'Date to truncate');
|
|
31
73
|
return new Date(Math.floor(date.getTime() / 1000) * 1000);
|
|
32
74
|
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { KeyObject } from 'node:crypto';
|
|
2
|
+
import { type PublicKeyInfo } from './keys.ts';
|
|
3
|
+
export declare const TIMESTAMP_PAYLOAD_TYPE = "application/vnd.mago-ski.timestamp+json";
|
|
4
|
+
export declare const TIMESTAMP_TYPE = "mago.timestamp/v1";
|
|
5
|
+
export declare const MAX_TIMESTAMP_BYTES: number;
|
|
6
|
+
export declare const DEFAULT_MAX_TIMESTAMP_LIFETIME = "24h";
|
|
7
|
+
export declare const MAX_TIMESTAMP_LIFETIME_MS: number;
|
|
8
|
+
/** The timestamp is older than one this host has already seen; callers match on the class, not the message. */
|
|
9
|
+
export declare class TimestampRollbackError extends Error {
|
|
10
|
+
}
|
|
11
|
+
/** The timestamp names other document digests than the files the host read. */
|
|
12
|
+
export declare class TimestampBindingError extends Error {
|
|
13
|
+
}
|
|
14
|
+
export interface Timestamp {
|
|
15
|
+
version: number;
|
|
16
|
+
issuedAt: Date;
|
|
17
|
+
expiresAt: Date;
|
|
18
|
+
key: PublicKeyInfo;
|
|
19
|
+
rootEvents: {
|
|
20
|
+
sha256: string;
|
|
21
|
+
count: number;
|
|
22
|
+
};
|
|
23
|
+
trustRoot: {
|
|
24
|
+
sha256: string;
|
|
25
|
+
version: number;
|
|
26
|
+
};
|
|
27
|
+
revocations: {
|
|
28
|
+
sha256: string;
|
|
29
|
+
version: number;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** What a host read, to compare against the timestamp. */
|
|
33
|
+
export interface FreshnessInputs {
|
|
34
|
+
rootEvents: {
|
|
35
|
+
sha256: string;
|
|
36
|
+
count: number;
|
|
37
|
+
};
|
|
38
|
+
trustRoot: {
|
|
39
|
+
sha256: string;
|
|
40
|
+
};
|
|
41
|
+
revocations: {
|
|
42
|
+
sha256: string;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export declare function timestampPayload(timestamp: Timestamp): Record<string, unknown>;
|
|
46
|
+
export declare function signTimestamp(timestamp: Timestamp, privateKey: KeyObject): Buffer;
|
|
47
|
+
export declare function parseTimestampPayload(bytes: Uint8Array): Timestamp;
|
|
48
|
+
/** Reads a timestamp signed by `keyId` without the time checks (for the signing job, to find the next version). */
|
|
49
|
+
export declare function readTimestampForUpdate(bytes: Uint8Array, keyId: string): Timestamp;
|
|
50
|
+
/**
|
|
51
|
+
* Verifies a timestamp against the active timestamp key, the clock, the policy's lifetime cap and the lowest version
|
|
52
|
+
* the host accepts, then checks that it names exactly the files the host read. Throws with the reason on any failure.
|
|
53
|
+
* The trust root and revocation list versions are compared by the caller once those documents are parsed.
|
|
54
|
+
*/
|
|
55
|
+
export declare function verifyTimestamp(bytes: Uint8Array, options: {
|
|
56
|
+
keyId: string;
|
|
57
|
+
now: Date;
|
|
58
|
+
maxLifetimeMs: number;
|
|
59
|
+
minimumVersion?: number | undefined;
|
|
60
|
+
inputs: FreshnessInputs;
|
|
61
|
+
}): Timestamp;
|