ShtukbaseStandard
файл пакета→ .shtukbase/packages/std-owasp-secrets/checks/lib/std.ts

checks/lib/std.ts

236 строк, 10.2 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // Shared helpers of the std-* packages (each package carries its own copy, so a package installs alone).
  2. // Run with the project root as the working directory. Read only: files are read, git is only asked
  3. // (ls-files, log, show, tag, check-ignore); nothing is written.
  4. import { spawnSync } from 'node:child_process';
  5. import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
  6. import { basename, isAbsolute, join, relative, resolve } from 'node:path';
  7. export const ROOT = process.cwd();
  8. export type Head = Record<string, unknown>;
  9. /** The front matter of a page (empty when the page or its front matter is missing or unreadable). */
  10. export function frontMatter(path: string): Head {
  11. if (!existsSync(path)) return {};
  12. const text = readFileSync(path, 'utf8');
  13. const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
  14. if (!m) return {};
  15. try {
  16. const v = Bun.YAML.parse(m[1]);
  17. return v && typeof v === 'object' && !Array.isArray(v) ? (v as Head) : {};
  18. } catch {
  19. return {};
  20. }
  21. }
  22. /** Settings from the project page /norms/standards/<page>.md over the package defaults. */
  23. export function settings<T extends Head>(page: string, defaults: T): T {
  24. const fm = frontMatter(join(ROOT, 'norms', 'standards', `${page}.md`));
  25. const out: Head = { ...defaults };
  26. for (const k of Object.keys(defaults)) if (fm[k] !== undefined && fm[k] !== null) out[k] = fm[k];
  27. return out as T;
  28. }
  29. export function list(v: unknown): string[] {
  30. if (v === undefined || v === null || v === '') return [];
  31. return (Array.isArray(v) ? v : [v]).map((x) => String(x).trim()).filter(Boolean);
  32. }
  33. export type Norm = { id: string; pkg: string; mode: string; active: boolean };
  34. // Each check action selects its norm before scanning files.
  35. let ruleExceptions: string[] = [];
  36. /** The norm as the project holds it: its mode (observe, warn, enforce) and whether it is in force. A missing page
  37. * (for example, the check runs on a repository without the package) falls back to the package default. */
  38. export function norm(pkg: string, id: string, fallbackMode: string): Norm {
  39. const path = join(ROOT, 'norms', 'rules', pkg, `${id}.md`);
  40. if (!existsSync(path)) {
  41. ruleExceptions = [];
  42. return { id, pkg, mode: fallbackMode, active: true };
  43. }
  44. const fm = frontMatter(path);
  45. ruleExceptions = Array.isArray(fm.except) ? list(fm.except) : [];
  46. const status = String(fm.status ?? 'active').trim();
  47. return { id, pkg, mode: String(fm.mode ?? fallbackMode).trim(), active: status === 'active' };
  48. }
  49. /** Prints the findings and sets the exit code: only a norm in `enforce` mode fails; observe and warn report. */
  50. export function finish(n: Norm, findings: string[]): void {
  51. if (!n.active) {
  52. process.exitCode = 0;
  53. return;
  54. }
  55. const soft = n.mode !== 'enforce';
  56. if (findings.length) {
  57. console.log(findings.map((f) => (soft ? `(${n.mode}) ${f}` : f)).join('\n'));
  58. if (soft) console.log(`(${n.mode}) ${n.id}: findings ${findings.length}; the mode is not "enforce", the check does not fail`);
  59. }
  60. process.exitCode = findings.length && !soft ? 1 : 0;
  61. }
  62. /** Runs git read-only in the project root; null when git is missing or the command fails. */
  63. export function git(args: string[], opts: { okCodes?: number[]; cwd?: string } = {}): string | null {
  64. const r = spawnSync('git', args, { cwd: opts.cwd ?? ROOT, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
  65. if (r.error) return null;
  66. if (r.status !== 0 && !(opts.okCodes ?? []).includes(r.status ?? -1)) return null;
  67. return r.stdout;
  68. }
  69. export function inGit(cwd = ROOT): boolean {
  70. return git(['rev-parse', '--is-inside-work-tree'], { cwd })?.trim() === 'true';
  71. }
  72. const SKIP_DIRS = new Set(['.git', 'node_modules', '.shtukbase', 'target', 'dist', 'build', '.venv', 'venv', '__pycache__', '.cache', '.next', '.turbo', '.pnpm-store']);
  73. function placeFolder(root: string, place: string): string | undefined {
  74. if (!place.trim() || isAbsolute(place)) return;
  75. const dir = resolve(root, place.trim());
  76. const rel = relative(root, dir);
  77. if (rel !== '..' && !rel.startsWith('../')) return dir;
  78. }
  79. /** Folders of matching nested projects and their repo-relative places, returned as absolute paths. */
  80. export function excludedFolders(projectDir: string, root: string, names: readonly string[]): string[] {
  81. const excluded = new Set<string>();
  82. if (!names.length) return [];
  83. function visit(dir: string, nested: boolean): void {
  84. const entries = readdirSync(dir, { withFileTypes: true });
  85. if (nested && entries.some((e) => e.name === '.shtukbase' && e.isDirectory())) {
  86. const { name, folder } = frontMatter(join(dir, 'base', 'packages.md'));
  87. if ([basename(dir), name, folder].some((value) => typeof value === 'string' && names.includes(value))) {
  88. excluded.add(dir);
  89. const places = frontMatter(join(dir, 'index.md')).places;
  90. if (Array.isArray(places)) {
  91. for (const place of places) {
  92. const full = typeof place === 'string' ? placeFolder(root, place) : undefined;
  93. if (full !== undefined) excluded.add(full);
  94. }
  95. }
  96. }
  97. }
  98. for (const e of entries) {
  99. if (!e.isDirectory() || ['.git', 'node_modules', '.shtukbase'].includes(e.name)) continue;
  100. if (e.name === 'worktrees' && basename(dir) === '.claude') continue;
  101. visit(join(dir, e.name), true);
  102. }
  103. }
  104. visit(resolve(projectDir), false);
  105. return [...excluded];
  106. }
  107. function filesAt(dir: string, excluded: (path: string) => boolean): string[] {
  108. if (excluded(dir)) return [];
  109. let files: string[] = [];
  110. if (inGit(dir)) {
  111. const out = git(['ls-files', '-z', '--cached', '--others', '--exclude-standard'], { cwd: dir });
  112. if (out !== null) files = [...new Set(out.split('\0').filter(Boolean))];
  113. } else {
  114. const walk = (rel: string) => {
  115. let names: string[] = [];
  116. try {
  117. names = readdirSync(join(dir, rel));
  118. } catch {
  119. return;
  120. }
  121. for (const name of names) {
  122. const r = rel ? `${rel}/${name}` : name;
  123. let st;
  124. try {
  125. st = statSync(join(dir, r));
  126. } catch {
  127. continue;
  128. }
  129. if (st.isDirectory()) {
  130. if (!SKIP_DIRS.has(name) && !excluded(join(dir, r))) walk(r);
  131. } else if (st.isFile()) files.push(r);
  132. }
  133. };
  134. walk('');
  135. }
  136. return files.filter((f) => !f.startsWith('.shtukbase/') && !f.includes('/.shtukbase/') &&
  137. !f.split('/').includes('node_modules') && !excluded(join(dir, f)));
  138. }
  139. // Keep the reported names usable by the text readers when they refer to places outside ROOT.
  140. const reportedPaths = new Map<string, string>();
  141. /** Project-relative files plus repo-relative files from declared places. In Git, ignored files are left out.
  142. * Skip folders can be absolute or relative to the project. */
  143. export function projectFiles(skip?: readonly string[]): string[] {
  144. const configuredRoot = process.env.SHTUK_ROOT;
  145. const repo = configuredRoot && existsSync(configuredRoot) ? realpathSync(configuredRoot) : undefined;
  146. const places = process.env.SHTUK_PLACES;
  147. const folders = skip ?? (ruleExceptions.length
  148. ? excludedFolders(ROOT, repo || git(['rev-parse', '--show-toplevel'])?.trim() || ROOT, ruleExceptions)
  149. : []);
  150. const excludedPaths = folders.map((folder) => resolve(ROOT, folder));
  151. const excluded = (path: string) => excludedPaths.some((folder) => path === folder || path.startsWith(join(folder, '/')));
  152. const project = filesAt(ROOT, excluded);
  153. reportedPaths.clear();
  154. if (!repo || !places) return project;
  155. const placeFiles = new Set<string>();
  156. for (const place of places.split(':')) {
  157. const dir = placeFolder(repo, place);
  158. if (dir === undefined) continue;
  159. for (const file of filesAt(dir, excluded)) placeFiles.add(join(dir, file));
  160. }
  161. const local = project.filter((file) => !placeFiles.has(join(ROOT, file)));
  162. const placeNames = new Set([...placeFiles].map((file) => relative(repo, file)));
  163. // If labels collide, repo-relative paths distinguish the two files.
  164. const rebase = local.some((file) => placeNames.has(file));
  165. const localNames = local.map((file) => {
  166. if (!rebase) return file;
  167. const full = join(ROOT, file);
  168. const label = relative(repo, full);
  169. reportedPaths.set(label, full);
  170. return label;
  171. });
  172. for (const file of placeFiles) reportedPaths.set(relative(repo, file), file);
  173. return [...localNames, ...placeNames];
  174. }
  175. /** Glob filter from settings (`exclude: [glob, ...]`, Bun glob syntax, paths from the project root). */
  176. export function excluder(globs: string[]): (path: string) => boolean {
  177. const gs = globs.map((g) => new Bun.Glob(g));
  178. return (p) => gs.some((g) => g.match(p));
  179. }
  180. const BINARY_EXT = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'icns', 'pdf', 'zip', 'gz', 'tgz', 'xz', 'bz2', '7z', 'jar', 'class', 'so', 'dylib', 'dll', 'exe', 'o', 'a', 'wasm', 'mp4', 'mov', 'mp3', 'wav', 'ogg', 'woff', 'woff2', 'ttf', 'otf', 'eot', 'sqlite', 'db', 'bin', 'lockb', 'heic', 'psd', 'avif', 'tiff', 'bmp']);
  181. /** A text file's bytes, or null for a missing, large (over `maxBytes`) or binary file. */
  182. export function readTextBuffer(rel: string, maxBytes = 1024 * 1024): Buffer | null {
  183. const ext = rel.split('.').pop()?.toLowerCase() ?? '';
  184. if (BINARY_EXT.has(ext)) return null;
  185. const path = reportedPaths.get(rel) ?? join(ROOT, rel);
  186. let st;
  187. try {
  188. st = statSync(path);
  189. } catch {
  190. return null;
  191. }
  192. if (!st.isFile() || st.size > maxBytes) return null;
  193. const buf = readFileSync(path);
  194. if (buf.subarray(0, 8000).includes(0)) return null;
  195. return buf;
  196. }
  197. /** A text file's content, or null for a missing, large (over `maxBytes`) or binary file. */
  198. export function readTextFile(rel: string, maxBytes = 1024 * 1024): string | null {
  199. return readTextBuffer(rel, maxBytes)?.toString('utf8') ?? null;
  200. }
  201. /** Named flags of an action: `--name value` and bare `--flag`. */
  202. export function flags(argv: string[] = process.argv.slice(2)): Record<string, string | true> {
  203. const out: Record<string, string | true> = {};
  204. for (let i = 0; i < argv.length; i++) {
  205. const a = argv[i];
  206. if (!a.startsWith('--')) continue;
  207. const eq = a.indexOf('=');
  208. if (eq > 0) out[a.slice(2, eq)] = a.slice(eq + 1);
  209. else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) out[a.slice(2)] = argv[++i];
  210. else out[a.slice(2)] = true;
  211. }
  212. return out;
  213. }