code-guardian-ai 0.0.0-stage → 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 (70) hide show
  1. package/.env.example +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +774 -2
  4. package/bin/cli.js +2 -0
  5. package/dist/build-manifest.json +136 -0
  6. package/dist/cli/commands/check.js +56 -0
  7. package/dist/cli/commands/doctor.js +55 -0
  8. package/dist/cli/commands/find.js +31 -0
  9. package/dist/cli/commands/init-files.js +13 -0
  10. package/dist/cli/commands/init.js +50 -0
  11. package/dist/cli/commands/optimize.js +53 -0
  12. package/dist/cli/commands/scan.js +47 -0
  13. package/dist/cli/index.js +62 -0
  14. package/dist/cli/output.js +4 -0
  15. package/dist/context.js +11 -0
  16. package/dist/core/ast/analysis.js +455 -0
  17. package/dist/core/ast/cached-info.js +46 -0
  18. package/dist/core/ast/discovery.js +485 -0
  19. package/dist/core/ast/extract-js.js +531 -0
  20. package/dist/core/ast/extract-py.js +298 -0
  21. package/dist/core/ast/graph.js +92 -0
  22. package/dist/core/ast/health.js +338 -0
  23. package/dist/core/ast/indexer.js +286 -0
  24. package/dist/core/ast/packages.js +343 -0
  25. package/dist/core/ast/parser.js +91 -0
  26. package/dist/core/ast/report.js +154 -0
  27. package/dist/core/ast/resolver.js +392 -0
  28. package/dist/core/ast/rules.js +37 -0
  29. package/dist/core/ast/scope-js.js +191 -0
  30. package/dist/core/ast/shared-index.js +131 -0
  31. package/dist/core/ast/tsconfig.js +301 -0
  32. package/dist/core/ast/types.js +1 -0
  33. package/dist/core/ast/util.js +156 -0
  34. package/dist/core/git/git.js +430 -0
  35. package/dist/core/llm/policy.js +35 -0
  36. package/dist/core/llm/provider.js +199 -0
  37. package/dist/core/prompt/compressor.js +118 -0
  38. package/dist/core/prompt/criteria.js +36 -0
  39. package/dist/core/prompt/find.js +47 -0
  40. package/dist/core/prompt/guidelines.js +22 -0
  41. package/dist/core/prompt/model-output.js +178 -0
  42. package/dist/core/prompt/refiner.js +194 -0
  43. package/dist/core/prompt/relevance.js +265 -0
  44. package/dist/core/prompt/untrusted.js +57 -0
  45. package/dist/core/security/masker.js +330 -0
  46. package/dist/core/security/outbound.js +40 -0
  47. package/dist/core/security/safe-file.js +396 -0
  48. package/dist/core/security/sandbox.js +181 -0
  49. package/dist/core/validation/baseline.js +121 -0
  50. package/dist/core/validation/delta.js +243 -0
  51. package/dist/core/validation/policy.js +123 -0
  52. package/dist/db/cache-key.js +221 -0
  53. package/dist/db/client.js +563 -0
  54. package/dist/db/schema-check.js +149 -0
  55. package/dist/db/schema.js +36 -0
  56. package/dist/db/windows-acl.js +150 -0
  57. package/dist/index.js +55 -0
  58. package/dist/mcp/server.js +20 -0
  59. package/dist/mcp/tools/find-reusable.js +22 -0
  60. package/dist/mcp/tools/get-context.js +39 -0
  61. package/dist/mcp/tools/optimize-prompt.js +31 -0
  62. package/dist/mcp/tools/result.js +31 -0
  63. package/dist/mcp/tools/validate-rules.js +28 -0
  64. package/dist/utils/config.js +117 -0
  65. package/dist/utils/errors.js +9 -0
  66. package/dist/utils/logger.js +19 -0
  67. package/dist/utils/pace.js +19 -0
  68. package/dist/utils/text.js +22 -0
  69. package/dist/utils/tokens.js +14 -0
  70. package/package.json +69 -4
@@ -0,0 +1,221 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { UnsafeFileError, createFileExclusive, hardLinkMessage, isHardLinked, regularFileIdentity } from '../core/security/safe-file.js';
6
+ import { errorMessage } from '../utils/errors.js';
7
+ import { log } from '../utils/logger.js';
8
+ import { CACHE_LIMITS } from './schema.js';
9
+ import { checkWindowsAcls } from './windows-acl.js';
10
+ // Cache integrity. A repository can ship its own .guardian/cache.db, and the cache is trusted when a file's content hash
11
+ // matches, so a crafted database could hand the analysis fabricated symbols and imports for files it names. Every stored
12
+ // result is therefore signed with a key that lives on this machine, outside any workspace: a row that was not written by
13
+ // this installation, or was changed afterwards, or was moved to another path or content, does not verify and is ignored.
14
+ //
15
+ // The key is 32 random bytes in a file only the current user can read, created exclusively. A workspace never contains it,
16
+ // so a repository cannot know it, and the cache of one machine is worthless on another (which is intended).
17
+ //
18
+ // "Only the current user" is established differently per platform. On POSIX systems it is the owner and the mode bits. Windows
19
+ // ignores both (0700 and 0600 mean nothing there), so the directory and the file are checked against their real ACLs
20
+ // (windows-acl.ts): no principal other than the user, SYSTEM and Administrators may have access. A directory or file that fails
21
+ // the check, or whose ACL cannot be inspected, is not used, which includes a custom GUARDIAN_STATE_HOME that is shared or
22
+ // inherits broad permissions: the key is then not established and the cache stays in memory. Files on network (UNC) paths are
23
+ // refused outright, because their effective permissions are decided by the server.
24
+ const KEY_DIR = 'guardian';
25
+ const KEY_FILE = 'cache-key';
26
+ const KEY_BYTES = 32;
27
+ const TAG = 'g1';
28
+ const MAC_HEX = 64;
29
+ // Where the key lives. GUARDIAN_STATE_HOME overrides it (tests, unusual setups); it must be an absolute path.
30
+ export function machineStateDir() {
31
+ const override = process.env.GUARDIAN_STATE_HOME;
32
+ if (override && path.isAbsolute(override))
33
+ return override;
34
+ const home = os.homedir();
35
+ if (process.platform === 'win32')
36
+ return path.join(process.env.LOCALAPPDATA && path.isAbsolute(process.env.LOCALAPPDATA) ? process.env.LOCALAPPDATA : path.join(home, 'AppData', 'Local'), KEY_DIR);
37
+ if (process.platform === 'darwin')
38
+ return path.join(home, 'Library', 'Application Support', KEY_DIR);
39
+ const state = process.env.XDG_STATE_HOME && path.isAbsolute(process.env.XDG_STATE_HOME) ? process.env.XDG_STATE_HOME : path.join(home, '.local', 'state');
40
+ return path.join(state, KEY_DIR);
41
+ }
42
+ const inside = (parent, child) => {
43
+ const rel = path.relative(parent, child);
44
+ // Only a real parent step leaves `parent`: a child named `..state` is inside it.
45
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
46
+ };
47
+ const pause = (ms) => void Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
48
+ // POSIX only: Windows is checked through its ACLs (see windows-acl.ts), never through these bits.
49
+ function checkOwner(stat, what, forbidden, platform) {
50
+ if (platform === 'win32')
51
+ return;
52
+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
53
+ throw new UnsafeFileError(`${what} is not owned by the current user`);
54
+ if ((stat.mode & forbidden) !== 0)
55
+ throw new UnsafeFileError(`${what} is accessible to other users`);
56
+ }
57
+ // The key file is 64 lowercase hexadecimal characters, optionally followed by one line ending (the file is written with "\n"; a
58
+ // text editor on Windows may leave "\r\n"). Nothing else is part of a key: no other whitespace, no second line, no prefix.
59
+ const MAX_KEY_FILE_BYTES = KEY_BYTES * 2 + 2;
60
+ const KEY_TEXT = new RegExp(`^[0-9a-f]{${KEY_BYTES * 2}}(?:\\r?\\n)?$`);
61
+ const NOFOLLOW = fs.constants.O_NOFOLLOW ?? 0;
62
+ const NONBLOCK = fs.constants.O_NONBLOCK ?? 0;
63
+ const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
64
+ // Reads the key through one descriptor and never reads more than MAX_KEY_FILE_BYTES + 1 bytes: the size is checked on the
65
+ // descriptor before anything is read, and the read itself is capped, so a file that grows afterwards cannot make this read more.
66
+ // The descriptor is opened with O_NOFOLLOW (a link in the final position is refused, not followed), and it must be a regular file
67
+ // with one hard link that is the very file the path named a moment ago (dev/ino). After the read the same is established again,
68
+ // from the descriptor and from the path, so a file that was replaced, linked or resized while it was read is not used.
69
+ // `expected` is the identity that an earlier check (the Windows ACL inspection) was made on: another file is refused.
70
+ function readKey(file, platform, expected, hooks = {}) {
71
+ const changed = () => new UnsafeFileError(`${KEY_FILE} changed while it was being read`);
72
+ // Another process may have just created the file and not written it yet: wait briefly for an empty file, nothing else.
73
+ for (let attempt = 0;; attempt++) {
74
+ const named = regularFileIdentity(file);
75
+ if (named === null)
76
+ throw new UnsafeFileError(`${KEY_FILE} is missing`);
77
+ if (expected && !sameFile(expected, named))
78
+ throw changed();
79
+ hooks.beforeOpen?.();
80
+ let fd = null;
81
+ let text;
82
+ try {
83
+ try {
84
+ fd = fs.openSync(file, fs.constants.O_RDONLY | NOFOLLOW | NONBLOCK);
85
+ }
86
+ catch (err) {
87
+ // ELOOP: the final component is (now) a symbolic link. Anything else is just as unusable.
88
+ throw err instanceof UnsafeFileError ? err : new UnsafeFileError(`${KEY_FILE} cannot be opened safely (${err.code ?? 'unknown error'})`);
89
+ }
90
+ const held = fs.fstatSync(fd, { bigint: true });
91
+ if (!held.isFile())
92
+ throw new UnsafeFileError(`${KEY_FILE} is not a regular file`);
93
+ if (!sameFile(named, held))
94
+ throw changed();
95
+ if (isHardLinked(held))
96
+ throw new UnsafeFileError(hardLinkMessage(KEY_FILE));
97
+ if (held.size > BigInt(MAX_KEY_FILE_BYTES))
98
+ throw new UnsafeFileError(`${KEY_FILE} is larger than a key can be (${MAX_KEY_FILE_BYTES} bytes at most)`);
99
+ checkOwner(fs.fstatSync(fd), KEY_FILE, 0o077, platform);
100
+ hooks.afterOpen?.();
101
+ const buffer = Buffer.alloc(MAX_KEY_FILE_BYTES + 1);
102
+ let got = 0;
103
+ while (got < buffer.length) {
104
+ const n = fs.readSync(fd, buffer, got, buffer.length - got, got);
105
+ if (n === 0)
106
+ break;
107
+ got += n;
108
+ }
109
+ hooks.afterRead?.();
110
+ // The same file, still singly linked and not grown or cut, from the descriptor and from the path.
111
+ const after = fs.fstatSync(fd, { bigint: true });
112
+ if (!after.isFile() || !sameFile(held, after) || after.size !== held.size || got !== Number(held.size))
113
+ throw changed();
114
+ if (isHardLinked(after))
115
+ throw new UnsafeFileError(hardLinkMessage(KEY_FILE));
116
+ const still = regularFileIdentity(file);
117
+ if (still === null || !sameFile(held, still))
118
+ throw changed();
119
+ checkOwner(fs.fstatSync(fd), KEY_FILE, 0o077, platform);
120
+ text = buffer.subarray(0, got);
121
+ }
122
+ finally {
123
+ if (fd !== null) {
124
+ try {
125
+ fs.closeSync(fd);
126
+ }
127
+ catch {
128
+ // nothing useful to do
129
+ }
130
+ }
131
+ }
132
+ if (KEY_TEXT.test(text.toString('utf8')))
133
+ return Buffer.from(text.toString('utf8').slice(0, KEY_BYTES * 2), 'hex');
134
+ if (text.length > 0 || attempt >= 20)
135
+ throw new UnsafeFileError(`${KEY_FILE} does not hold a valid key`);
136
+ pause(25);
137
+ }
138
+ }
139
+ // A network path (\\server\share, \\?\UNC\...) has permissions decided by another machine; a `\\?\C:\` path is local.
140
+ const isNetworkPath = (p) => p.startsWith('\\') && !/^\\\?\[A-Za-z]:\\/.test(p);
141
+ export function loadMachineKey(workspaceRoot, options = {}) {
142
+ const platform = options.platform ?? process.platform;
143
+ const acl = options.acl ?? checkWindowsAcls;
144
+ const requirePrivate = (targets) => {
145
+ const problem = acl(targets);
146
+ if (problem)
147
+ throw new UnsafeFileError(problem);
148
+ };
149
+ try {
150
+ const dir = machineStateDir();
151
+ if (platform === 'win32' && isNetworkPath(dir))
152
+ throw new UnsafeFileError('the key directory is on a network path');
153
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
154
+ const real = fs.realpathSync.native(dir);
155
+ if (platform === 'win32' && isNetworkPath(real))
156
+ throw new UnsafeFileError('the key directory is on a network path');
157
+ if (inside(fs.realpathSync.native(workspaceRoot), real))
158
+ throw new UnsafeFileError('the key directory is inside the workspace');
159
+ const stat = fs.statSync(real);
160
+ if (!stat.isDirectory())
161
+ throw new UnsafeFileError('the key directory is not a directory');
162
+ checkOwner(stat, 'the key directory', 0o022, platform);
163
+ const keyFile = path.join(real, KEY_FILE);
164
+ const directory = { path: real, what: 'the key directory' };
165
+ const file = { path: keyFile, what: KEY_FILE };
166
+ if (platform === 'win32') {
167
+ // regularFileIdentity also refuses a symbolic link or a hard link in the key's place. An existing key is checked together with
168
+ // its directory (one inspection); a new one is created only after the directory has passed, then checked.
169
+ let inspected = regularFileIdentity(keyFile);
170
+ requirePrivate(inspected !== null ? [directory, file] : [directory]);
171
+ if (inspected === null) {
172
+ createFileExclusive(real, KEY_FILE, `${crypto.randomBytes(KEY_BYTES).toString('hex')}\n`, 0o600);
173
+ inspected = regularFileIdentity(keyFile);
174
+ requirePrivate([file]);
175
+ }
176
+ // The ACLs were read from the path; the key is read only if it is still the file that was inspected.
177
+ return readKey(keyFile, platform, inspected ?? undefined, options.hooks);
178
+ }
179
+ createFileExclusive(real, KEY_FILE, `${crypto.randomBytes(KEY_BYTES).toString('hex')}\n`, 0o600);
180
+ return readKey(keyFile, platform, undefined, options.hooks);
181
+ }
182
+ catch (err) {
183
+ log.warn(`No machine-owned cache key (${errorMessage(err)}); the cache stays in memory for this session`);
184
+ return null;
185
+ }
186
+ }
187
+ // Binds a result to its path and to the hash of the content it was computed from, so a genuine row cannot be moved to
188
+ // another file, and a changed one does not verify. JSON encoding keeps the fields unambiguous.
189
+ function mac(key, filePath, hash, info) {
190
+ return crypto.createHmac('sha256', key).update(JSON.stringify(['guardian-cache', 1, filePath, hash, info])).digest('hex');
191
+ }
192
+ // What a sealed value adds to the result it carries: the tag, the signature and the separators around the signature.
193
+ export const SEALED_OVERHEAD = TAG.length + 1 + MAC_HEX + 1;
194
+ // A hash is a SHA-256 hex digest; the bound is looser only because callers and tests use shorter stand-ins. It exists so that no
195
+ // field that is fed to the signature can be arbitrarily long.
196
+ const MAX_HASH_CHARS = 128;
197
+ export function sealInfo(key, filePath, hash, info) {
198
+ if (Buffer.byteLength(info) > CACHE_LIMITS.maxInfoBytes)
199
+ throw new RangeError('the result is too large to be stored in the cache');
200
+ return `${TAG}.${mac(key, filePath, hash, info)}.${info}`;
201
+ }
202
+ // The stored text when it is a genuine sealed result for exactly this path and hash, otherwise null. Every input is bounded
203
+ // first: the signature costs time proportional to the size of what it covers, and the stored text comes from a file that a
204
+ // repository can supply, so nothing oversized reaches the HMAC.
205
+ export function openInfo(key, filePath, hash, stored) {
206
+ if (typeof stored !== 'string' || typeof filePath !== 'string' || typeof hash !== 'string')
207
+ return null;
208
+ // .length is O(1) and never exceeds the byte length, so it rejects the huge values without scanning them; the byte count then enforces the exact bound.
209
+ if (hash.length > MAX_HASH_CHARS || filePath.length === 0 || filePath.length > CACHE_LIMITS.maxPathBytes || Buffer.byteLength(filePath) > CACHE_LIMITS.maxPathBytes)
210
+ return null;
211
+ const maxStored = CACHE_LIMITS.maxInfoBytes + SEALED_OVERHEAD;
212
+ if (stored.length > maxStored || Buffer.byteLength(stored) > maxStored)
213
+ return null;
214
+ if (!stored.startsWith(`${TAG}.`) || stored[TAG.length + 1 + MAC_HEX] !== '.')
215
+ return null;
216
+ const given = stored.slice(TAG.length + 1, TAG.length + 1 + MAC_HEX);
217
+ if (!/^[0-9a-f]+$/.test(given))
218
+ return null;
219
+ const info = stored.slice(TAG.length + 2 + MAC_HEX);
220
+ return crypto.timingSafeEqual(Buffer.from(given, 'hex'), Buffer.from(mac(key, filePath, hash, info), 'hex')) ? info : null;
221
+ }