@specdest/devkit 0.4.12 → 0.4.14
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/dist/npm/automation-policy.d.ts +2 -0
- package/dist/npm/automation-policy.js +30 -0
- package/dist/npm/cli.js +4 -0
- package/dist/npm/host-automation.d.ts +9 -0
- package/dist/npm/host-automation.js +52 -0
- package/dist/npm/index.js +4 -1
- package/dist/npm/project-check.js +17 -0
- package/dist/npm/snapshot/config.d.ts +10 -0
- package/dist/npm/snapshot/config.js +24 -0
- package/dist/npm/snapshot/policy.d.ts +1 -0
- package/dist/npm/snapshot/policy.js +64 -0
- package/dist/npm/snapshot/restore.d.ts +10 -0
- package/dist/npm/snapshot/restore.js +19 -0
- package/dist/npm/snapshot/sql.d.ts +2 -0
- package/dist/npm/snapshot/sql.js +113 -0
- package/dist/npm/snapshot/storage.d.ts +8 -0
- package/dist/npm/snapshot/storage.js +70 -0
- package/dist/npm/snapshot/verify.d.ts +11 -0
- package/dist/npm/snapshot/verify.js +13 -0
- package/dist/npm/snapshot-cli.d.ts +5 -0
- package/dist/npm/snapshot-cli.js +46 -0
- package/package.json +3 -2
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
const FORBIDDEN = /(?:\b(?:pnpm\s+exec|npx|npm\s+exec|yarn\s+exec|bunx)\s+(?:agent-device|agent-browser|jev-browser)\b|\bhost-cli\s+(?:agent-device|agent-browser|jev-browser)\b|\b(?:SPECDEST_AGENT_DEVICE_BIN|node_modules\/\.bin\/(?:agent-device|agent-browser|jev-browser))\b)/u;
|
|
4
|
+
const DIRECT = new Set(['agent-device', 'agent-browser', 'jev-browser']);
|
|
5
|
+
/** Check project-owned entrypoints; Controller and Devkit are intentionally exempt. */
|
|
6
|
+
export function automationPolicyFindings(root, files) {
|
|
7
|
+
const findings = [];
|
|
8
|
+
const manifestPath = join(root, 'package.json');
|
|
9
|
+
if (existsSync(manifestPath)) {
|
|
10
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
11
|
+
for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {
|
|
12
|
+
for (const name of Object.keys(manifest[field] ?? {})) {
|
|
13
|
+
if (DIRECT.has(name))
|
|
14
|
+
findings.push(`package.json: ${name} must be accessed via Devkit`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
for (const file of files) {
|
|
19
|
+
if (!/^(?:scripts\/.*\.(?:sh|js|cjs|mjs|ts|py)|package-scripts\.yml)$/u.test(file))
|
|
20
|
+
continue;
|
|
21
|
+
if (/(?:^|\/)(?:test[^/]*|[^/]*\.test\.[^/]*)$/u.test(file))
|
|
22
|
+
continue;
|
|
23
|
+
const full = join(root, file);
|
|
24
|
+
if (!existsSync(full))
|
|
25
|
+
continue;
|
|
26
|
+
if (FORBIDDEN.test(readFileSync(full, 'utf8')))
|
|
27
|
+
findings.push(`${file}: invoke through specdest device/browser instead of direct host tools`);
|
|
28
|
+
}
|
|
29
|
+
return findings;
|
|
30
|
+
}
|
package/dist/npm/cli.js
CHANGED
|
@@ -3,12 +3,16 @@ import { createFlowCommandHandler, runCli } from "./index.js";
|
|
|
3
3
|
import { createCanonicalCommandHandlers } from "./canonical-project-operations.js";
|
|
4
4
|
import { runSupabaseLocal } from "./supabase-local.js";
|
|
5
5
|
import { sendSlackFiles } from "./slack.js";
|
|
6
|
+
import { runHostAutomation } from "./host-automation.js";
|
|
6
7
|
try {
|
|
7
8
|
const exitCode = await runCli(process.argv.slice(2), process, {
|
|
8
9
|
...createCanonicalCommandHandlers(),
|
|
9
10
|
flow: createFlowCommandHandler(),
|
|
10
11
|
supabase: async (args) => runSupabaseLocal(args),
|
|
11
12
|
slack: async (args) => sendSlackFiles(args),
|
|
13
|
+
device: async (args) => runHostAutomation('device', args),
|
|
14
|
+
browser: async (args) => runHostAutomation('browser', args),
|
|
15
|
+
'jev-browser': async (args) => runHostAutomation('jev-browser', args),
|
|
12
16
|
});
|
|
13
17
|
process.exitCode = exitCode;
|
|
14
18
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
declare const TOOLS: {
|
|
3
|
+
readonly device: "agent-device";
|
|
4
|
+
readonly browser: "agent-browser";
|
|
5
|
+
readonly 'jev-browser': "jev-browser";
|
|
6
|
+
};
|
|
7
|
+
/** Forward unchanged arguments through Controller's queue, or its trusted NPS host context. */
|
|
8
|
+
export declare function runHostAutomation(command: keyof typeof TOOLS, args: string[], cwd?: string, invoke?: typeof spawnSync, gatewayExists?: (path: string) => boolean, env?: Record<string, string | undefined>): number;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { projectFromCwd } from "./supabase-local.js";
|
|
4
|
+
const TOOLS = {
|
|
5
|
+
device: 'agent-device',
|
|
6
|
+
browser: 'agent-browser',
|
|
7
|
+
'jev-browser': 'jev-browser',
|
|
8
|
+
};
|
|
9
|
+
const NPS_BIN_ENV = {
|
|
10
|
+
device: 'SPECDEST_DEVKIT_AGENT_DEVICE_BIN',
|
|
11
|
+
browser: 'SPECDEST_DEVKIT_AGENT_BROWSER_BIN',
|
|
12
|
+
'jev-browser': 'SPECDEST_DEVKIT_JEV_BROWSER_BIN',
|
|
13
|
+
};
|
|
14
|
+
/** Forward unchanged arguments through Controller's queue, or its trusted NPS host context. */
|
|
15
|
+
export function runHostAutomation(command, args, cwd = process.cwd(), invoke = spawnSync, gatewayExists = existsSync, env = process.env) {
|
|
16
|
+
const project = projectFromCwd(cwd);
|
|
17
|
+
if (!project) {
|
|
18
|
+
process.stderr.write('Controller project registration required.\n');
|
|
19
|
+
return 2;
|
|
20
|
+
}
|
|
21
|
+
if (!args.length) {
|
|
22
|
+
process.stderr.write(`Usage: specdest ${command} <subcommand> [args...]\n`);
|
|
23
|
+
return 2;
|
|
24
|
+
}
|
|
25
|
+
// NPS executes inside the Mac gateway worker. Re-enqueuing to that worker
|
|
26
|
+
// would deadlock, so use the trusted host path injected by Controller.
|
|
27
|
+
if (env.SPECDEST_DEVKIT_GATEWAY_NPS === '1') {
|
|
28
|
+
const binary = env[NPS_BIN_ENV[command]];
|
|
29
|
+
if (!binary?.startsWith('/') || !gatewayExists(binary)) {
|
|
30
|
+
process.stderr.write('Controller did not authorize this host automation binary.\n');
|
|
31
|
+
return 1;
|
|
32
|
+
}
|
|
33
|
+
const result = invoke(binary, args, { stdio: 'inherit', shell: false });
|
|
34
|
+
if (result.error)
|
|
35
|
+
process.stderr.write(`${result.error.message}\n`);
|
|
36
|
+
return result.error ? 1 : (result.status ?? 1);
|
|
37
|
+
}
|
|
38
|
+
const client = '/usr/local/bin/host-cli';
|
|
39
|
+
if (!gatewayExists(client)) {
|
|
40
|
+
process.stderr.write('Controller gateway client unavailable.\n');
|
|
41
|
+
return 1;
|
|
42
|
+
}
|
|
43
|
+
const result = invoke(client, ['devkit-automation', project, TOOLS[command], ...args], {
|
|
44
|
+
stdio: 'inherit',
|
|
45
|
+
shell: false,
|
|
46
|
+
});
|
|
47
|
+
if (result.error) {
|
|
48
|
+
process.stderr.write(`${result.error.message}\n`);
|
|
49
|
+
return 1;
|
|
50
|
+
}
|
|
51
|
+
return result.status ?? 1;
|
|
52
|
+
}
|
package/dist/npm/index.js
CHANGED
|
@@ -11,8 +11,11 @@ export const COMMAND_NAMES = [
|
|
|
11
11
|
'flow',
|
|
12
12
|
'supabase',
|
|
13
13
|
'slack',
|
|
14
|
+
'device',
|
|
15
|
+
'browser',
|
|
16
|
+
'jev-browser',
|
|
14
17
|
];
|
|
15
|
-
const HELP = `Usage: specdest <command> [options]\n\nCommands:\n status [--refresh] [--json] Show canonical applicability/install status\n add <package> Adopt/install a predefined package\n sync Refresh catalog/cache and install/update applicable rules\n check [--refresh] [--json] [--details] [--staged | --files <path...>] Run canonical checks, optionally targeted\n rules [options] Load applicable rule guidance for AI/task context\n ai-instruction Print the minimal AI bootstrap instruction\n doctor Diagnose project/cache setup\n flow <command> Manage local resumable development flow state\n supabase <status|start|stop> Local Supabase through restricted Controller\n slack send <files...> Upload files to configured Slack channel\n`;
|
|
18
|
+
const HELP = `Usage: specdest <command> [options]\n\nCommands:\n status [--refresh] [--json] Show canonical applicability/install status\n add <package> Adopt/install a predefined package\n sync Refresh catalog/cache and install/update applicable rules\n check [--refresh] [--json] [--details] [--staged | --files <path...>] Run canonical checks, optionally targeted\n rules [options] Load applicable rule guidance for AI/task context\n ai-instruction Print the minimal AI bootstrap instruction\n doctor Diagnose project/cache setup\n flow <command> Manage local resumable development flow state\n supabase <status|start|stop> Local Supabase through restricted Controller\n slack send <files...> Upload files to configured Slack channel\n device <args...> Forward to Controller agent-device\n browser <args...> Forward to Controller agent-browser\n jev-browser <args...> Forward to Controller jev-browser (if configured)\n`;
|
|
16
19
|
export async function runCli(argv, io = process, handlers = {}) {
|
|
17
20
|
const [command, ...args] = argv;
|
|
18
21
|
if (!command || command === 'help' || command === '--help' || command === '-h') {
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
+
import { readdirSync } from 'node:fs';
|
|
3
|
+
import { automationPolicyFindings } from "./automation-policy.js";
|
|
4
|
+
import { projectFromCwd } from "./supabase-local.js";
|
|
2
5
|
import { clientOnlyBoundaryViolations } from "./client-only-boundary.js";
|
|
3
6
|
import { readRuleProfile } from "./project-context.js";
|
|
4
7
|
import { loadCanonicalProjectContext, prepareCanonicalManifest } from "./project-runtime.js";
|
|
@@ -80,6 +83,20 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
|
80
83
|
}
|
|
81
84
|
const normalizedTargetFiles = (targetFiles ?? []).map((file) => String(file).replaceAll('\\', '/'));
|
|
82
85
|
let exitCode = 0;
|
|
86
|
+
if (projectFromCwd(projectRoot)) {
|
|
87
|
+
const scripts = readdirSync(`${projectRoot}/scripts`, { recursive: true, withFileTypes: true })
|
|
88
|
+
.filter((entry) => entry.isFile())
|
|
89
|
+
.map((entry) => `scripts/${entry.parentPath.replace(`${projectRoot}/scripts/`, '')}/${entry.name}`.replace('scripts//', 'scripts/'));
|
|
90
|
+
const violations = automationPolicyFindings(projectRoot, ['package-scripts.yml', ...scripts]);
|
|
91
|
+
results['automation-gateway'] = {
|
|
92
|
+
status: violations.length ? 'fail' : 'pass',
|
|
93
|
+
exitCode: violations.length ? 1 : 0,
|
|
94
|
+
stderr: violations.join('\n'),
|
|
95
|
+
diagnostics: violations.map((message) => ({ message })),
|
|
96
|
+
};
|
|
97
|
+
if (violations.length)
|
|
98
|
+
exitCode = 1;
|
|
99
|
+
}
|
|
83
100
|
const profile = await readRuleProfile(projectRoot);
|
|
84
101
|
if (profile.capabilities.includes('client-only')) {
|
|
85
102
|
const findings = await clientOnlyBoundaryViolations(projectRoot);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Declarative, non-secret project configuration. Never authorizes a host operation. */
|
|
2
|
+
export interface SnapshotConfig {
|
|
3
|
+
version: 1;
|
|
4
|
+
project: string;
|
|
5
|
+
policyFile: string;
|
|
6
|
+
storage: {
|
|
7
|
+
buckets: string[];
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
export declare function validateSnapshotConfig(input: unknown): SnapshotConfig;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const identifier = /^[a-z][a-z0-9_-]*$/;
|
|
2
|
+
export function validateSnapshotConfig(input) {
|
|
3
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
4
|
+
throw new Error('config must be an object');
|
|
5
|
+
const config = input;
|
|
6
|
+
if (Object.keys(config).some((key) => !['version', 'project', 'policyFile', 'storage'].includes(key)))
|
|
7
|
+
throw new Error('unknown config field');
|
|
8
|
+
if (config.version !== 1)
|
|
9
|
+
throw new Error('unsupported config version');
|
|
10
|
+
if (typeof config.project !== 'string' || !identifier.test(config.project))
|
|
11
|
+
throw new Error('invalid project');
|
|
12
|
+
if (typeof config.policyFile !== 'string' || !/^[a-z][a-z0-9_.-]*\.json$/.test(config.policyFile))
|
|
13
|
+
throw new Error('invalid policyFile');
|
|
14
|
+
const storage = config.storage;
|
|
15
|
+
if (!storage || typeof storage !== 'object' || Array.isArray(storage))
|
|
16
|
+
throw new Error('invalid storage');
|
|
17
|
+
const s = storage;
|
|
18
|
+
if (Object.keys(s).some((key) => key !== 'buckets') ||
|
|
19
|
+
!Array.isArray(s.buckets) ||
|
|
20
|
+
s.buckets.some((v) => typeof v !== 'string' || !identifier.test(v)) ||
|
|
21
|
+
new Set(s.buckets).size !== s.buckets.length)
|
|
22
|
+
throw new Error('invalid storage buckets');
|
|
23
|
+
return input;
|
|
24
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function validateMaskPolicy(policy: unknown, observed: Record<string, string[]>, project: string): true;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Fail-closed policy coverage checks. These do not constitute privacy approval. */
|
|
2
|
+
const safeName = /^[a-z_][a-z0-9_]*$/;
|
|
3
|
+
const sensitive = /(token(?!_expires_at)|secret|password|email|phone|credential|oauth|api_key|authorization|auth_data|refresh_key|access_key)/i;
|
|
4
|
+
const transforms = new Set([
|
|
5
|
+
'keep',
|
|
6
|
+
'null',
|
|
7
|
+
'pseudonym',
|
|
8
|
+
'email',
|
|
9
|
+
'phone',
|
|
10
|
+
'constant',
|
|
11
|
+
'json_object',
|
|
12
|
+
'json_array',
|
|
13
|
+
'uuid_array',
|
|
14
|
+
'empty_text_array',
|
|
15
|
+
'empty_uuid_array',
|
|
16
|
+
'allow_values',
|
|
17
|
+
'disable',
|
|
18
|
+
]);
|
|
19
|
+
const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
20
|
+
const equalKeys = (a, b) => a.length === b.length && a.every((v) => b.includes(v));
|
|
21
|
+
export function validateMaskPolicy(policy, observed, project) {
|
|
22
|
+
if (!object(policy) ||
|
|
23
|
+
!equalKeys(Object.keys(policy), ['format', 'project', 'tables']) ||
|
|
24
|
+
policy.format !== 1 ||
|
|
25
|
+
policy.project !== project)
|
|
26
|
+
throw new Error('invalid policy format or project');
|
|
27
|
+
if (!object(policy.tables) ||
|
|
28
|
+
!Object.keys(policy.tables).length ||
|
|
29
|
+
!equalKeys(Object.keys(policy.tables), Object.keys(observed)))
|
|
30
|
+
throw new Error('table coverage mismatch');
|
|
31
|
+
for (const [table, columns] of Object.entries(observed)) {
|
|
32
|
+
if (!safeName.test(table) || !columns.length || columns.some((c) => !safeName.test(c)))
|
|
33
|
+
throw new Error('invalid inventory');
|
|
34
|
+
const def = policy.tables[table];
|
|
35
|
+
if (!object(def) ||
|
|
36
|
+
!equalKeys(Object.keys(def), ['columns']) ||
|
|
37
|
+
!object(def.columns) ||
|
|
38
|
+
!equalKeys(Object.keys(def.columns), columns))
|
|
39
|
+
throw new Error(`column coverage mismatch: ${table}`);
|
|
40
|
+
for (const [column, raw] of Object.entries(def.columns)) {
|
|
41
|
+
if (!object(raw) ||
|
|
42
|
+
typeof raw.transform !== 'string' ||
|
|
43
|
+
!transforms.has(raw.transform) ||
|
|
44
|
+
Object.keys(raw).some((k) => !['transform', 'value', 'values'].includes(k)))
|
|
45
|
+
throw new Error(`invalid transform: ${table}.${column}`);
|
|
46
|
+
if (raw.transform === 'allow_values'
|
|
47
|
+
? !Array.isArray(raw.values) ||
|
|
48
|
+
raw.values.length < 1 ||
|
|
49
|
+
raw.values.length > 64 ||
|
|
50
|
+
raw.values.some((v) => typeof v !== 'string' || !v || v.length > 100) ||
|
|
51
|
+
new Set(raw.values).size !== raw.values.length ||
|
|
52
|
+
'value' in raw
|
|
53
|
+
: 'values' in raw)
|
|
54
|
+
throw new Error(`invalid transform allowlist: ${table}.${column}`);
|
|
55
|
+
if (raw.transform === 'constant'
|
|
56
|
+
? typeof raw.value !== 'string' || raw.value.length > 256
|
|
57
|
+
: 'value' in raw)
|
|
58
|
+
throw new Error(`invalid transform options: ${table}.${column}`);
|
|
59
|
+
if (raw.transform === 'keep' && sensitive.test(column))
|
|
60
|
+
throw new Error(`sensitive column cannot be kept: ${table}.${column}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** A plan is descriptive only. Controller must independently authorize every step. */
|
|
2
|
+
export interface RestorePreflight {
|
|
3
|
+
config: unknown;
|
|
4
|
+
snapshotProject: string;
|
|
5
|
+
targetProject: string;
|
|
6
|
+
targetKind: 'local' | 'remote';
|
|
7
|
+
targetPopulated: boolean;
|
|
8
|
+
backupAvailable: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare function planLocalRestore(input: RestorePreflight): readonly string[];
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { validateSnapshotConfig } from "./config.js";
|
|
2
|
+
export function planLocalRestore(input) {
|
|
3
|
+
const config = validateSnapshotConfig(input.config);
|
|
4
|
+
if (input.snapshotProject !== config.project)
|
|
5
|
+
throw new Error('wrong snapshot project');
|
|
6
|
+
if (input.targetProject !== config.project)
|
|
7
|
+
throw new Error('mismatched restore target');
|
|
8
|
+
if (input.targetKind !== 'local')
|
|
9
|
+
throw new Error('remote restore forbidden');
|
|
10
|
+
if (input.targetPopulated && !input.backupAvailable)
|
|
11
|
+
throw new Error('populated target requires backup');
|
|
12
|
+
return Object.freeze([
|
|
13
|
+
'verify approved sanitized snapshot and target identity on trusted host',
|
|
14
|
+
'capture verified local-target backup before any mutation',
|
|
15
|
+
'restore to isolated local staging with transactional SQL validation',
|
|
16
|
+
'verify database and Storage referential integrity',
|
|
17
|
+
'promote only after approval; on failure roll back from verified backup',
|
|
18
|
+
]);
|
|
19
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/** Fixture-only allowlist for sanitized INSERT-format SQL; never executes SQL. */
|
|
2
|
+
const sessions = new Set([
|
|
3
|
+
'SET statement_timeout = 0;',
|
|
4
|
+
'SET lock_timeout = 0;',
|
|
5
|
+
'SET transaction_timeout = 0;',
|
|
6
|
+
'SET idle_in_transaction_session_timeout = 0;',
|
|
7
|
+
"SET client_encoding = 'UTF8';",
|
|
8
|
+
'SET standard_conforming_strings = on;',
|
|
9
|
+
'SET check_function_bodies = false;',
|
|
10
|
+
'SET xmloption = content;',
|
|
11
|
+
'SET client_min_messages = warning;',
|
|
12
|
+
'SET row_security = off;',
|
|
13
|
+
"SET default_tablespace = '';",
|
|
14
|
+
'SET default_table_access_method = heap;',
|
|
15
|
+
"SET search_path = '';",
|
|
16
|
+
]);
|
|
17
|
+
const insert = /^INSERT INTO public\."?[a-z_][a-z0-9_]*"?\s*(?:\([^;]*\)\s*)?(?:OVERRIDING SYSTEM VALUE\s+)?VALUES\s*\(.+\);$/is;
|
|
18
|
+
const sequence = /^SELECT pg_catalog\.setval\('public\.(?:[a-z_][a-z0-9_]*|"[a-z_][a-z0-9_]*")'(?:::regclass)?,\s*-?[0-9]+,\s*(?:true|false)\);$/i;
|
|
19
|
+
/** Replace quoted text while preserving all unquoted syntax. */
|
|
20
|
+
function neutralize(source) {
|
|
21
|
+
let result = '';
|
|
22
|
+
for (let i = 0; i < source.length; i++) {
|
|
23
|
+
if (source[i] !== "'") {
|
|
24
|
+
result += source[i];
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
result += "'text'";
|
|
28
|
+
let closed = false;
|
|
29
|
+
while (++i < source.length) {
|
|
30
|
+
if (source[i] !== "'")
|
|
31
|
+
continue;
|
|
32
|
+
if (source[i + 1] === "'") {
|
|
33
|
+
i++;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
closed = true;
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
if (!closed)
|
|
40
|
+
throw new Error('unclosed SQL string literal');
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
function statements(source, native) {
|
|
45
|
+
const found = [];
|
|
46
|
+
let buffer = [];
|
|
47
|
+
for (const raw of source.split(/\r?\n/)) {
|
|
48
|
+
const line = raw.trim();
|
|
49
|
+
if (!buffer.length &&
|
|
50
|
+
(!line ||
|
|
51
|
+
line.startsWith('--') ||
|
|
52
|
+
(native && (line.startsWith('\\restrict ') || line.startsWith('\\unrestrict ')))))
|
|
53
|
+
continue;
|
|
54
|
+
buffer.push(raw);
|
|
55
|
+
const statement = buffer.join('\n').trim();
|
|
56
|
+
let syntax;
|
|
57
|
+
try {
|
|
58
|
+
syntax = neutralize(statement);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (error instanceof Error && error.message === 'unclosed SQL string literal')
|
|
62
|
+
continue;
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
const semicolons = syntax.match(/;/g)?.length ?? 0;
|
|
66
|
+
if (semicolons > 1 || (semicolons === 1 && !syntax.endsWith(';')))
|
|
67
|
+
throw new Error('extra SQL statement');
|
|
68
|
+
if (semicolons === 1) {
|
|
69
|
+
found.push(statement);
|
|
70
|
+
buffer = [];
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (buffer.length)
|
|
74
|
+
throw new Error('unterminated SQL statement');
|
|
75
|
+
return found;
|
|
76
|
+
}
|
|
77
|
+
function assertInsert(statement) {
|
|
78
|
+
if (!insert.test(statement))
|
|
79
|
+
throw new Error('unsupported restore SQL');
|
|
80
|
+
const syntax = neutralize(statement);
|
|
81
|
+
if ((syntax.match(/;/g)?.length ?? 0) !== 1 ||
|
|
82
|
+
/\\|\$\$|\/\*|\*\/|--|\b(SELECT|DO|COPY|ALTER|CREATE|DROP|EXECUTE|PERFORM)\b/i.test(syntax))
|
|
83
|
+
throw new Error('unsafe restore SQL');
|
|
84
|
+
const values = syntax.split(/\bVALUES\s*\(/i);
|
|
85
|
+
if (values.length !== 2 || /\b[a-z_][a-z0-9_]*\s*\(/i.test(values[1]))
|
|
86
|
+
throw new Error('nonliteral restore SQL');
|
|
87
|
+
}
|
|
88
|
+
export function validateRestoreSql(source) {
|
|
89
|
+
let count = 0;
|
|
90
|
+
for (const statement of statements(source, false)) {
|
|
91
|
+
if (sessions.has(statement) || sequence.test(statement))
|
|
92
|
+
continue;
|
|
93
|
+
assertInsert(statement);
|
|
94
|
+
count++;
|
|
95
|
+
}
|
|
96
|
+
if (!count)
|
|
97
|
+
throw new Error('no INSERT statements');
|
|
98
|
+
return count;
|
|
99
|
+
}
|
|
100
|
+
export function normalizePgDump(source) {
|
|
101
|
+
const kept = [];
|
|
102
|
+
for (const statement of statements(source, true)) {
|
|
103
|
+
if (sessions.has(statement) ||
|
|
104
|
+
statement === "SELECT pg_catalog.set_config('search_path', '', false);")
|
|
105
|
+
continue;
|
|
106
|
+
if (!insert.test(statement) && !sequence.test(statement))
|
|
107
|
+
throw new Error('unsupported native dump statement');
|
|
108
|
+
kept.push(statement);
|
|
109
|
+
}
|
|
110
|
+
const normalized = kept.join('\n') + '\n';
|
|
111
|
+
validateRestoreSql(normalized);
|
|
112
|
+
return normalized;
|
|
113
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare function validateStorageManifest(input: unknown, allowedBuckets: readonly string[], project: string): true;
|
|
2
|
+
/** Compare trusted-runner digest inventories without reading Storage objects. */
|
|
3
|
+
export declare function reconcileStorageObjects(expected: unknown, actual: unknown, allowedBuckets: readonly string[], project: string): true;
|
|
4
|
+
/** Cross-check sanitized Storage metadata against the object bundle. */
|
|
5
|
+
export declare function reconcileStorageMetadata(manifest: unknown, references: readonly {
|
|
6
|
+
bucket: string;
|
|
7
|
+
path: string;
|
|
8
|
+
}[], allowedBuckets: readonly string[], project: string): true;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
2
|
+
const keys = (value, expected) => Object.keys(value).length === expected.length &&
|
|
3
|
+
Object.keys(value).every((key) => expected.includes(key));
|
|
4
|
+
const validPath = (path) => path.length > 0 &&
|
|
5
|
+
path.length <= 1024 &&
|
|
6
|
+
!path.startsWith('/') &&
|
|
7
|
+
!path.includes('\\') &&
|
|
8
|
+
![...path].some((ch) => ch.charCodeAt(0) < 32 || ch.charCodeAt(0) === 127 || '?#%'.includes(ch)) &&
|
|
9
|
+
!path.split('/').some((part) => part === '' || part === '.' || part === '..');
|
|
10
|
+
export function validateStorageManifest(input, allowedBuckets, project) {
|
|
11
|
+
if (!isRecord(input) || !keys(input, ['version', 'project', 'objects']))
|
|
12
|
+
throw new Error('invalid manifest fields');
|
|
13
|
+
if (input.version !== 1 || input.project !== project)
|
|
14
|
+
throw new Error('manifest project/version mismatch');
|
|
15
|
+
if (!Array.isArray(input.objects) || input.objects.length > 3000)
|
|
16
|
+
throw new Error('invalid objects');
|
|
17
|
+
const seen = new Set();
|
|
18
|
+
for (const value of input.objects) {
|
|
19
|
+
if (!isRecord(value) || !keys(value, ['bucket', 'path', 'sha256', 'bytes']))
|
|
20
|
+
throw new Error('invalid object fields');
|
|
21
|
+
const entry = value;
|
|
22
|
+
if (typeof entry.bucket !== 'string' || !allowedBuckets.includes(entry.bucket))
|
|
23
|
+
throw new Error('unapproved bucket');
|
|
24
|
+
if (typeof entry.path !== 'string' || !validPath(entry.path))
|
|
25
|
+
throw new Error('unsafe object path');
|
|
26
|
+
if (typeof entry.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(entry.sha256))
|
|
27
|
+
throw new Error('invalid hash');
|
|
28
|
+
if (!Number.isSafeInteger(entry.bytes) || entry.bytes < 0)
|
|
29
|
+
throw new Error('invalid byte length');
|
|
30
|
+
const key = JSON.stringify([entry.bucket, entry.path]);
|
|
31
|
+
if (seen.has(key))
|
|
32
|
+
throw new Error('duplicate storage object');
|
|
33
|
+
seen.add(key);
|
|
34
|
+
}
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
/** Compare trusted-runner digest inventories without reading Storage objects. */
|
|
38
|
+
export function reconcileStorageObjects(expected, actual, allowedBuckets, project) {
|
|
39
|
+
validateStorageManifest(expected, allowedBuckets, project);
|
|
40
|
+
validateStorageManifest(actual, allowedBuckets, project);
|
|
41
|
+
if (!isRecord(expected) || !isRecord(actual))
|
|
42
|
+
throw new Error('invalid manifest');
|
|
43
|
+
const planned = expected.objects;
|
|
44
|
+
const observed = actual.objects;
|
|
45
|
+
const byKey = new Map(observed.map((entry) => [JSON.stringify([entry.bucket, entry.path]), entry]));
|
|
46
|
+
if (planned.length !== observed.length)
|
|
47
|
+
throw new Error('storage object count mismatch');
|
|
48
|
+
for (const entry of planned) {
|
|
49
|
+
const match = byKey.get(JSON.stringify([entry.bucket, entry.path]));
|
|
50
|
+
if (!match)
|
|
51
|
+
throw new Error('missing storage object');
|
|
52
|
+
if (entry.sha256 !== match.sha256 || entry.bytes !== match.bytes)
|
|
53
|
+
throw new Error('modified storage object');
|
|
54
|
+
}
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
/** Cross-check sanitized Storage metadata against the object bundle. */
|
|
58
|
+
export function reconcileStorageMetadata(manifest, references, allowedBuckets, project) {
|
|
59
|
+
validateStorageManifest(manifest, allowedBuckets, project);
|
|
60
|
+
if (!isRecord(manifest))
|
|
61
|
+
throw new Error('invalid manifest');
|
|
62
|
+
const objects = manifest.objects;
|
|
63
|
+
const expected = new Set(objects.map((item) => JSON.stringify([item.bucket, item.path])));
|
|
64
|
+
const observed = new Set(references.map((item) => JSON.stringify([item.bucket, item.path])));
|
|
65
|
+
if (observed.size !== references.length)
|
|
66
|
+
throw new Error('duplicate storage metadata');
|
|
67
|
+
if (observed.size !== expected.size || [...expected].some((key) => !observed.has(key)))
|
|
68
|
+
throw new Error('storage DB manifest mismatch');
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface SnapshotVerificationInput {
|
|
2
|
+
config: unknown;
|
|
3
|
+
policy: unknown;
|
|
4
|
+
inventory: Record<string, string[]>;
|
|
5
|
+
storageManifest: unknown;
|
|
6
|
+
sanitizedSql: string;
|
|
7
|
+
}
|
|
8
|
+
export declare function verifySnapshotArtifacts(input: SnapshotVerificationInput): {
|
|
9
|
+
project: string;
|
|
10
|
+
verifiedInserts: number;
|
|
11
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Nonprivileged, offline snapshot artifact verification. Never connects to production. */
|
|
2
|
+
import { validateSnapshotConfig } from "./config.js";
|
|
3
|
+
import { validateMaskPolicy } from "./policy.js";
|
|
4
|
+
import { validateStorageManifest } from "./storage.js";
|
|
5
|
+
import { validateRestoreSql } from "./sql.js";
|
|
6
|
+
export function verifySnapshotArtifacts(input) {
|
|
7
|
+
const config = validateSnapshotConfig(input.config);
|
|
8
|
+
// Policy must explicitly cover every observed table and column; partial policies fail.
|
|
9
|
+
validateMaskPolicy(input.policy, input.inventory, config.project);
|
|
10
|
+
validateStorageManifest(input.storageManifest, config.storage.buckets, config.project);
|
|
11
|
+
const verifiedInserts = validateRestoreSql(input.sanitizedSql);
|
|
12
|
+
return { project: config.project, verifiedInserts };
|
|
13
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Offline validation of a trusted-runner-produced sanitized artifact bundle. */
|
|
3
|
+
import { readFileSync, lstatSync } from 'node:fs';
|
|
4
|
+
import { resolve, join } from 'node:path';
|
|
5
|
+
import { verifySnapshotArtifacts } from "./snapshot/verify.js";
|
|
6
|
+
import { reconcileStorageObjects, reconcileStorageMetadata } from "./snapshot/storage.js";
|
|
7
|
+
import { validateSnapshotConfig } from "./snapshot/config.js";
|
|
8
|
+
export function verifyBundle(directory) {
|
|
9
|
+
const root = resolve(directory);
|
|
10
|
+
function read(name) {
|
|
11
|
+
const path = join(root, name);
|
|
12
|
+
if (lstatSync(path).isSymbolicLink())
|
|
13
|
+
throw new Error('symlinked snapshot input');
|
|
14
|
+
return readFileSync(path, 'utf8');
|
|
15
|
+
}
|
|
16
|
+
function json(name) {
|
|
17
|
+
return JSON.parse(read(name));
|
|
18
|
+
}
|
|
19
|
+
const config = validateSnapshotConfig(json('config.json'));
|
|
20
|
+
const input = {
|
|
21
|
+
config,
|
|
22
|
+
policy: json(config.policyFile),
|
|
23
|
+
inventory: json('inventory.json'),
|
|
24
|
+
storageManifest: json('storage-manifest.json'),
|
|
25
|
+
sanitizedSql: read('sanitized.sql'),
|
|
26
|
+
};
|
|
27
|
+
const result = verifySnapshotArtifacts(input);
|
|
28
|
+
reconcileStorageObjects(input.storageManifest, json('storage-observed.json'), config.storage.buckets, config.project);
|
|
29
|
+
reconcileStorageMetadata(input.storageManifest, json('storage-references.json'), config.storage.buckets, config.project);
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
if (process.argv[1] && /(?:^|\/)snapshot-cli\.(?:ts|js)$/.test(process.argv[1])) {
|
|
33
|
+
if (process.argv.length !== 4 || process.argv[2] !== 'verify') {
|
|
34
|
+
process.stderr.write('Usage: snapshot-cli verify <offline-bundle-directory>\n');
|
|
35
|
+
process.exitCode = 2;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
try {
|
|
39
|
+
process.stdout.write(JSON.stringify(verifyBundle(process.argv[3])) + '\n');
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
process.stderr.write('Snapshot verification rejected\n');
|
|
43
|
+
process.exitCode = 1;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
package/package.json
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@specdest/devkit",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.14",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
|
-
"specdest": "dist/npm/cli.js"
|
|
6
|
+
"specdest": "dist/npm/cli.js",
|
|
7
|
+
"specdest-snapshot": "dist/npm/snapshot-cli.js"
|
|
7
8
|
},
|
|
8
9
|
"exports": {
|
|
9
10
|
".": "./dist/npm/index.js"
|