файл пакета→ .shtukbase/packages/std-owasp-secrets/checks/lib/std.ts
checks/lib/std.ts
236 строк, 10.2 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Shared helpers of the std-* packages (each package carries its own copy, so a package installs alone).
- // Run with the project root as the working directory. Read only: files are read, git is only asked
- // (ls-files, log, show, tag, check-ignore); nothing is written.
- import { spawnSync } from 'node:child_process';
- import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
- import { basename, isAbsolute, join, relative, resolve } from 'node:path';
- export const ROOT = process.cwd();
- export type Head = Record<string, unknown>;
- /** The front matter of a page (empty when the page or its front matter is missing or unreadable). */
- export function frontMatter(path: string): Head {
- if (!existsSync(path)) return {};
- const text = readFileSync(path, 'utf8');
- const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
- if (!m) return {};
- try {
- const v = Bun.YAML.parse(m[1]);
- return v && typeof v === 'object' && !Array.isArray(v) ? (v as Head) : {};
- } catch {
- return {};
- }
- }
- /** Settings from the project page /norms/standards/<page>.md over the package defaults. */
- export function settings<T extends Head>(page: string, defaults: T): T {
- const fm = frontMatter(join(ROOT, 'norms', 'standards', `${page}.md`));
- const out: Head = { ...defaults };
- for (const k of Object.keys(defaults)) if (fm[k] !== undefined && fm[k] !== null) out[k] = fm[k];
- return out as T;
- }
- export function list(v: unknown): string[] {
- if (v === undefined || v === null || v === '') return [];
- return (Array.isArray(v) ? v : [v]).map((x) => String(x).trim()).filter(Boolean);
- }
- export type Norm = { id: string; pkg: string; mode: string; active: boolean };
- // Each check action selects its norm before scanning files.
- let ruleExceptions: string[] = [];
- /** The norm as the project holds it: its mode (observe, warn, enforce) and whether it is in force. A missing page
- * (for example, the check runs on a repository without the package) falls back to the package default. */
- export function norm(pkg: string, id: string, fallbackMode: string): Norm {
- const path = join(ROOT, 'norms', 'rules', pkg, `${id}.md`);
- if (!existsSync(path)) {
- ruleExceptions = [];
- return { id, pkg, mode: fallbackMode, active: true };
- }
- const fm = frontMatter(path);
- ruleExceptions = Array.isArray(fm.except) ? list(fm.except) : [];
- const status = String(fm.status ?? 'active').trim();
- return { id, pkg, mode: String(fm.mode ?? fallbackMode).trim(), active: status === 'active' };
- }
- /** Prints the findings and sets the exit code: only a norm in `enforce` mode fails; observe and warn report. */
- export function finish(n: Norm, findings: string[]): void {
- if (!n.active) {
- process.exitCode = 0;
- return;
- }
- const soft = n.mode !== 'enforce';
- if (findings.length) {
- console.log(findings.map((f) => (soft ? `(${n.mode}) ${f}` : f)).join('\n'));
- if (soft) console.log(`(${n.mode}) ${n.id}: findings ${findings.length}; the mode is not "enforce", the check does not fail`);
- }
- process.exitCode = findings.length && !soft ? 1 : 0;
- }
- /** Runs git read-only in the project root; null when git is missing or the command fails. */
- export function git(args: string[], opts: { okCodes?: number[]; cwd?: string } = {}): string | null {
- const r = spawnSync('git', args, { cwd: opts.cwd ?? ROOT, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
- if (r.error) return null;
- if (r.status !== 0 && !(opts.okCodes ?? []).includes(r.status ?? -1)) return null;
- return r.stdout;
- }
- export function inGit(cwd = ROOT): boolean {
- return git(['rev-parse', '--is-inside-work-tree'], { cwd })?.trim() === 'true';
- }
- const SKIP_DIRS = new Set(['.git', 'node_modules', '.shtukbase', 'target', 'dist', 'build', '.venv', 'venv', '__pycache__', '.cache', '.next', '.turbo', '.pnpm-store']);
- function placeFolder(root: string, place: string): string | undefined {
- if (!place.trim() || isAbsolute(place)) return;
- const dir = resolve(root, place.trim());
- const rel = relative(root, dir);
- if (rel !== '..' && !rel.startsWith('../')) return dir;
- }
- /** Folders of matching nested projects and their repo-relative places, returned as absolute paths. */
- export function excludedFolders(projectDir: string, root: string, names: readonly string[]): string[] {
- const excluded = new Set<string>();
- if (!names.length) return [];
- function visit(dir: string, nested: boolean): void {
- const entries = readdirSync(dir, { withFileTypes: true });
- if (nested && entries.some((e) => e.name === '.shtukbase' && e.isDirectory())) {
- const { name, folder } = frontMatter(join(dir, 'base', 'packages.md'));
- if ([basename(dir), name, folder].some((value) => typeof value === 'string' && names.includes(value))) {
- excluded.add(dir);
- const places = frontMatter(join(dir, 'index.md')).places;
- if (Array.isArray(places)) {
- for (const place of places) {
- const full = typeof place === 'string' ? placeFolder(root, place) : undefined;
- if (full !== undefined) excluded.add(full);
- }
- }
- }
- }
- for (const e of entries) {
- if (!e.isDirectory() || ['.git', 'node_modules', '.shtukbase'].includes(e.name)) continue;
- if (e.name === 'worktrees' && basename(dir) === '.claude') continue;
- visit(join(dir, e.name), true);
- }
- }
- visit(resolve(projectDir), false);
- return [...excluded];
- }
- function filesAt(dir: string, excluded: (path: string) => boolean): string[] {
- if (excluded(dir)) return [];
- let files: string[] = [];
- if (inGit(dir)) {
- const out = git(['ls-files', '-z', '--cached', '--others', '--exclude-standard'], { cwd: dir });
- if (out !== null) files = [...new Set(out.split('\0').filter(Boolean))];
- } else {
- const walk = (rel: string) => {
- let names: string[] = [];
- try {
- names = readdirSync(join(dir, rel));
- } catch {
- return;
- }
- for (const name of names) {
- const r = rel ? `${rel}/${name}` : name;
- let st;
- try {
- st = statSync(join(dir, r));
- } catch {
- continue;
- }
- if (st.isDirectory()) {
- if (!SKIP_DIRS.has(name) && !excluded(join(dir, r))) walk(r);
- } else if (st.isFile()) files.push(r);
- }
- };
- walk('');
- }
- return files.filter((f) => !f.startsWith('.shtukbase/') && !f.includes('/.shtukbase/') &&
- !f.split('/').includes('node_modules') && !excluded(join(dir, f)));
- }
- // Keep the reported names usable by the text readers when they refer to places outside ROOT.
- const reportedPaths = new Map<string, string>();
- /** Project-relative files plus repo-relative files from declared places. In Git, ignored files are left out.
- * Skip folders can be absolute or relative to the project. */
- export function projectFiles(skip?: readonly string[]): string[] {
- const configuredRoot = process.env.SHTUK_ROOT;
- const repo = configuredRoot && existsSync(configuredRoot) ? realpathSync(configuredRoot) : undefined;
- const places = process.env.SHTUK_PLACES;
- const folders = skip ?? (ruleExceptions.length
- ? excludedFolders(ROOT, repo || git(['rev-parse', '--show-toplevel'])?.trim() || ROOT, ruleExceptions)
- : []);
- const excludedPaths = folders.map((folder) => resolve(ROOT, folder));
- const excluded = (path: string) => excludedPaths.some((folder) => path === folder || path.startsWith(join(folder, '/')));
- const project = filesAt(ROOT, excluded);
- reportedPaths.clear();
- if (!repo || !places) return project;
- const placeFiles = new Set<string>();
- for (const place of places.split(':')) {
- const dir = placeFolder(repo, place);
- if (dir === undefined) continue;
- for (const file of filesAt(dir, excluded)) placeFiles.add(join(dir, file));
- }
- const local = project.filter((file) => !placeFiles.has(join(ROOT, file)));
- const placeNames = new Set([...placeFiles].map((file) => relative(repo, file)));
- // If labels collide, repo-relative paths distinguish the two files.
- const rebase = local.some((file) => placeNames.has(file));
- const localNames = local.map((file) => {
- if (!rebase) return file;
- const full = join(ROOT, file);
- const label = relative(repo, full);
- reportedPaths.set(label, full);
- return label;
- });
- for (const file of placeFiles) reportedPaths.set(relative(repo, file), file);
- return [...localNames, ...placeNames];
- }
- /** Glob filter from settings (`exclude: [glob, ...]`, Bun glob syntax, paths from the project root). */
- export function excluder(globs: string[]): (path: string) => boolean {
- const gs = globs.map((g) => new Bun.Glob(g));
- return (p) => gs.some((g) => g.match(p));
- }
- 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']);
- /** A text file's bytes, or null for a missing, large (over `maxBytes`) or binary file. */
- export function readTextBuffer(rel: string, maxBytes = 1024 * 1024): Buffer | null {
- const ext = rel.split('.').pop()?.toLowerCase() ?? '';
- if (BINARY_EXT.has(ext)) return null;
- const path = reportedPaths.get(rel) ?? join(ROOT, rel);
- let st;
- try {
- st = statSync(path);
- } catch {
- return null;
- }
- if (!st.isFile() || st.size > maxBytes) return null;
- const buf = readFileSync(path);
- if (buf.subarray(0, 8000).includes(0)) return null;
- return buf;
- }
- /** A text file's content, or null for a missing, large (over `maxBytes`) or binary file. */
- export function readTextFile(rel: string, maxBytes = 1024 * 1024): string | null {
- return readTextBuffer(rel, maxBytes)?.toString('utf8') ?? null;
- }
- /** Named flags of an action: `--name value` and bare `--flag`. */
- export function flags(argv: string[] = process.argv.slice(2)): Record<string, string | true> {
- const out: Record<string, string | true> = {};
- for (let i = 0; i < argv.length; i++) {
- const a = argv[i];
- if (!a.startsWith('--')) continue;
- const eq = a.indexOf('=');
- if (eq > 0) out[a.slice(2, eq)] = a.slice(eq + 1);
- else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) out[a.slice(2)] = argv[++i];
- else out[a.slice(2)] = true;
- }
- return out;
- }