@vaultcompass/conductor 0.4.0 → 0.4.6

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.
@@ -0,0 +1,127 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ export const MANIFEST_RELATIVE_PATH = '.guardrails/manifest.json';
5
+ export function sha256(content) {
6
+ return createHash('sha256').update(content).digest('hex');
7
+ }
8
+ /**
9
+ * Whether a path the manifest names is contained to the repository.
10
+ *
11
+ * The manifest is committed input, so a path in it is whatever a commit put
12
+ * there. Revert and apply run this over every path they would write to or
13
+ * delete before touching anything, and refuse the whole operation if any one
14
+ * of them is not contained.
15
+ *
16
+ * Two conditions, because a path can escape two ways. The resolved path,
17
+ * treated as plain strings, must be inside the root: this refuses an absolute
18
+ * path and one that climbs out with ../. And no component of the path may be a
19
+ * SYMLINK. A committed dangling symlink (its target does not exist) is the case
20
+ * that broke an earlier version of this: existsSync FOLLOWS the link, finds the
21
+ * missing target, and reports the link absent, so a walk that resolved only the
22
+ * deepest existing ancestor judged the link a plain not-yet-existing leaf and
23
+ * let writeFileSync and chmodSync, which DO follow the final link, land the
24
+ * write on the outside target. lstatSync does not follow, so it catches a
25
+ * symlink component even when its target is gone. init never writes through a
26
+ * symlink, so a symlink anywhere along the path means this is not a path init
27
+ * wrote, and it is refused whatever it points at.
28
+ *
29
+ * Paths here need not exist yet: an adopted hook is restored to a path revert
30
+ * has just removed, and a recorded file may be legitimately gone. The scan
31
+ * stops at the first component that does not exist, because nothing below a
32
+ * missing component exists either, so there is no symlink left to find. A
33
+ * relative candidate is taken against the repository root, which is how the
34
+ * real attack lands: a person running revert has cd'd into the checkout.
35
+ */
36
+ export function manifestPathInsideRepo(repoRoot, candidate) {
37
+ try {
38
+ const root = realpathSync(repoRoot);
39
+ const abs = path.resolve(root, candidate);
40
+ // Deepest ancestor of abs that exists on disk. realpathSync on the whole
41
+ // path throws when the leaf is not there, so resolve the part that exists
42
+ // and keep the rest as a tail. existsSync FOLLOWS symlinks, which is why a
43
+ // dangling symlink is not trusted here; the tail is scanned with lstatSync
44
+ // below.
45
+ let ancestor = abs;
46
+ while (!existsSync(ancestor)) {
47
+ const parent = path.dirname(ancestor);
48
+ if (parent === ancestor) {
49
+ break;
50
+ }
51
+ ancestor = parent;
52
+ }
53
+ const realAncestor = realpathSync(ancestor);
54
+ const tail = path.relative(ancestor, abs);
55
+ // Containment, on resolved paths so a macOS temp dir reached through
56
+ // /var -> /private/var does not read as an escape, and so an existing
57
+ // symlink directory that points outside is caught by its resolved target.
58
+ const resolved = tail === '' ? realAncestor : path.join(realAncestor, tail);
59
+ const inside = path.relative(root, resolved);
60
+ if (inside === '' ||
61
+ inside === '..' ||
62
+ inside.startsWith(`..${path.sep}`) ||
63
+ path.isAbsolute(inside)) {
64
+ return false;
65
+ }
66
+ // No component of the tail may be a symlink. lstatSync does not follow, so
67
+ // a committed DANGLING symlink is caught even though existsSync reported it
68
+ // absent: existsSync followed the link to its missing target, which let an
69
+ // earlier version treat the link as a plain not-yet-existing leaf and then
70
+ // let writeFileSync and chmodSync, which DO follow the final link, land the
71
+ // write on the outside target. init never writes through a symlink, so any
72
+ // symlink component means this is not a path init wrote. The scan starts at
73
+ // the resolved ancestor, whose own components are already real, and walks
74
+ // to the leaf, stopping at the first component that does not exist.
75
+ let current = realAncestor;
76
+ for (const segment of tail === '' ? [] : tail.split(path.sep)) {
77
+ current = path.join(current, segment);
78
+ let entry;
79
+ try {
80
+ entry = lstatSync(current);
81
+ }
82
+ catch {
83
+ break;
84
+ }
85
+ if (entry.isSymbolicLink()) {
86
+ return false;
87
+ }
88
+ }
89
+ return true;
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ export function readIfExists(file) {
96
+ try {
97
+ return readFileSync(file, 'utf8');
98
+ }
99
+ catch {
100
+ return undefined;
101
+ }
102
+ }
103
+ /**
104
+ * The manifest a previous init left, or null when there is none or it will
105
+ * not parse.
106
+ *
107
+ * An unreadable manifest is deliberately the same answer as a missing one:
108
+ * everything that consults it here is deciding whether a file on disk is
109
+ * one the umbrella wrote, and "the record is unreadable" is not evidence
110
+ * that it was.
111
+ */
112
+ export function readManifest(root) {
113
+ const raw = readIfExists(path.join(root, MANIFEST_RELATIVE_PATH));
114
+ if (raw === undefined) {
115
+ return null;
116
+ }
117
+ try {
118
+ return JSON.parse(raw);
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ }
124
+ /** The hook digest a previous init recorded, or null when there is none. */
125
+ export function recordedHookSha(root) {
126
+ return readManifest(root)?.files.find((file) => file.kind === 'hook')?.sha256 ?? null;
127
+ }
@@ -0,0 +1,12 @@
1
+ import { POLICY_FILE_NAME } from './policy.js';
2
+ import type { GateRole } from './policy.js';
3
+ export { POLICY_FILE_NAME };
4
+ /** Names of the gates whose binary resolves right now. */
5
+ export declare function detectGates(root: string, pathValue: string): Set<GateRole>;
6
+ /**
7
+ * The policy file, written by hand rather than serialised, because the
8
+ * comments are half the point: a first-run policy file that explains what
9
+ * each key is for is most of a first-run experience, and a YAML emitter
10
+ * cannot carry them.
11
+ */
12
+ export declare function renderPolicy(detected: Set<GateRole>): string;
@@ -0,0 +1,103 @@
1
+ import { statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { DEFAULT_STAGE_FOR_ROLE, GATE_ROLES, POLICY_FILE_NAME, PRODUCT_FOR_ROLE } from './policy.js';
4
+ import { CANDIDATES } from './resolve.js';
5
+ export { POLICY_FILE_NAME };
6
+ /** Names of the gates whose binary resolves right now. */
7
+ export function detectGates(root, pathValue) {
8
+ const found = new Set();
9
+ for (const role of GATE_ROLES) {
10
+ const product = PRODUCT_FOR_ROLE[role];
11
+ for (const candidate of CANDIDATES[product]) {
12
+ // Same order as resolve.ts, though only the answer matters here:
13
+ // detection asks whether a gate is installed at all, not which copy
14
+ // of it would run.
15
+ const local = isExecutable(path.join(root, 'node_modules', '.bin', candidate.name));
16
+ const onPath = pathValue
17
+ .split(path.delimiter)
18
+ .filter((dir) => dir.length > 0)
19
+ .some((dir) => isExecutable(path.join(dir, candidate.name)));
20
+ if (local || onPath) {
21
+ found.add(role);
22
+ break;
23
+ }
24
+ }
25
+ }
26
+ return found;
27
+ }
28
+ function isExecutable(file) {
29
+ try {
30
+ const stats = statSync(file);
31
+ return stats.isFile() && (stats.mode & 0o111) !== 0;
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ const ROLE_DESCRIPTION = {
38
+ dependencies: 'what comes in: hallucinated names, typosquats, tampered lockfile entries',
39
+ secrets: 'what goes out: credentials about to be committed',
40
+ intent: 'what was approved: drift from a frozen intent contract, and change budgets',
41
+ };
42
+ /**
43
+ * The policy file, written by hand rather than serialised, because the
44
+ * comments are half the point: a first-run policy file that explains what
45
+ * each key is for is most of a first-run experience, and a YAML emitter
46
+ * cannot carry them.
47
+ */
48
+ export function renderPolicy(detected) {
49
+ const lines = [
50
+ '# Guardrail policy. One file for every gate this repository runs.',
51
+ '#',
52
+ '# Gates are keyed by the ROLE they fill, and the product filling that role',
53
+ '# is one line inside it. Swapping or renaming a product is a one-line edit',
54
+ '# rather than a rename of the key your CI reads.',
55
+ '#',
56
+ '# There is deliberately no shared severity threshold. Each gate keeps its',
57
+ '# own, spelled the way that gate spells it, inside its own options block.',
58
+ '#',
59
+ '# stage says when a gate runs: commit, push, or ci. Stages are cumulative,',
60
+ '# so a gate runs at its own stage and at every later one, and a run at ci',
61
+ '# runs everything enabled. The values below are the defaults.',
62
+ '#',
63
+ '# enforce says whether a gate can change the exit code. A gate with',
64
+ '# enforce: false runs and reports exactly as an enforced one does and',
65
+ '# never fails the run, which is how a gate is adopted before anybody is',
66
+ '# ready to have it refuse a commit. It is written out below for every',
67
+ '# gate, for the same reason stage is: a default that lives only in the',
68
+ '# parser is a default nobody can find.',
69
+ 'version: 1',
70
+ '',
71
+ 'gates:',
72
+ ];
73
+ for (const role of GATE_ROLES) {
74
+ const product = PRODUCT_FOR_ROLE[role];
75
+ const enabled = detected.has(role);
76
+ lines.push(` # ${ROLE_DESCRIPTION[role]}`);
77
+ if (!enabled) {
78
+ lines.push(` # not found in node_modules/.bin or on PATH. Install ${product}, then set enabled: true.`);
79
+ }
80
+ lines.push(` ${role}:`);
81
+ lines.push(` product: ${product}`);
82
+ lines.push(` enabled: ${enabled ? 'true' : 'false'}`);
83
+ lines.push(` stage: ${DEFAULT_STAGE_FOR_ROLE[role]}`);
84
+ // The intent gate is the one with ceremony, and the ramp is what makes
85
+ // that ceremony adoptable: it reports for a few pull requests before it
86
+ // is allowed to refuse anybody's merge. Writing that here rather than
87
+ // describing it in a comment is the difference between a fresh init
88
+ // producing the ramp and three repositories being hand-edited into it.
89
+ if (role === 'intent') {
90
+ lines.push(' # It runs and reports in CI without failing the run. Flip it to');
91
+ lines.push(' # true once a few pull requests show the signal is worth blocking on.');
92
+ lines.push(' enforce: false');
93
+ }
94
+ else {
95
+ lines.push(' enforce: true');
96
+ }
97
+ lines.push(' # Handed to this gate unchanged. Keys are its own long flags,');
98
+ lines.push(' # without the leading dashes. Example: fail-on: high');
99
+ lines.push(' options: {}');
100
+ }
101
+ lines.push('', 'report:', ' format: text', '');
102
+ return lines.join('\n');
103
+ }
package/dist/init.d.ts CHANGED
@@ -1,38 +1,10 @@
1
- import { POLICY_FILE_NAME } from './policy.js';
2
- import type { GateRole, Product } from './policy.js';
3
- export { POLICY_FILE_NAME };
4
- /** The one string that says "conductor init wrote this". */
5
- export declare const MANAGED_HOOK_MARKER = "guardrails-managed-hook: v1";
6
- export declare const MANIFEST_RELATIVE_PATH = ".guardrails/manifest.json";
7
- /**
8
- * Markers each gate's own installer writes, so a collision is recognised
9
- * rather than clobbered. Two of these are literal marker comments the other
10
- * tools write on purpose; the third has no marker at all and is matched on
11
- * the two strings its hook always contains, which is exactly how that
12
- * tool's own installer recognises its own hook.
13
- */
14
- export declare const DEP_GUARD_HOOK_MARKER = "dep-guard-managed-hook: v1";
15
- export declare const INTENT_GUARD_HOOK_MARKER = "conductor-managed-pre-commit";
16
- /**
17
- * Hook managers whose installed pre-commit file is GENERATED rather than
18
- * written by a human. Every one of these rewrites that file on install, so
19
- * it is never the file the umbrella may write into.
20
- *
21
- * The same four names dep-guard's and vault-guard's inits use, so the
22
- * family says one thing. The difference is that those take the manager as
23
- * a flag, and this one detects it: the umbrella's whole job is to be run
24
- * once in a repository somebody else already wired up.
25
- */
26
- export type HookManager = 'native' | 'husky' | 'lefthook' | 'precommit' | 'simple-git-hooks' | 'yorkie';
27
- /**
28
- * The two managers whose pre-commit TEXT lives in package.json rather than
29
- * in a config file of their own or in the hook file.
30
- *
31
- * They are kept apart from lefthook and the pre-commit framework because
32
- * the refusal is different: there is no manager-owned config file to point
33
- * somebody at, only a key in the file conductor deliberately never writes.
34
- */
35
- export type ManagedHookManager = 'simple-git-hooks' | 'yorkie';
1
+ import type { Product } from './policy.js';
2
+ import { DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, MANAGED_HOOK_MARKER } from './init-hook-detect.js';
3
+ import type { HookManager, ManagedHookManager } from './init-hook-detect.js';
4
+ import { MANIFEST_RELATIVE_PATH } from './init-manifest.js';
5
+ import { POLICY_FILE_NAME, renderPolicy } from './init-policy.js';
6
+ export { MANAGED_HOOK_MARKER, MANIFEST_RELATIVE_PATH, DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, POLICY_FILE_NAME, renderPolicy, };
7
+ export type { HookManager, ManagedHookManager };
36
8
  export type ConflictReason = 'not-a-git-repository' | 'foreign-hook' | 'gate-hook' | 'generated-hook'
37
9
  /**
38
10
  * A manager whose hook text lives in package.json owns this file:
@@ -115,13 +87,6 @@ export interface InitOptions {
115
87
  */
116
88
  force?: boolean;
117
89
  }
118
- /**
119
- * The policy file, written by hand rather than serialised, because the
120
- * comments are half the point: a first-run policy file that explains what
121
- * each key is for is most of a first-run experience, and a YAML emitter
122
- * cannot carry them.
123
- */
124
- export declare function renderPolicy(detected: Set<GateRole>): string;
125
90
  export declare function planInit(options: InitOptions): InitResult;
126
91
  export declare function applyInit(plan: InitResult, options: InitOptions): InitResult;
127
92
  export interface RevertResult {