@kriya-ai/harness 0.2.5 → 2.0.1
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/RELEASE_NOTES.md +121 -0
- package/SAFETY.md +181 -0
- package/THIRD_PARTY_NOTICES.md +113 -0
- package/bin/kriya.js +188 -2
- package/bundle/cordis.patch.yml +60 -5
- package/contract/SOURCE.md +3 -3
- package/contract/contract.json +498 -3
- package/contract/schemas/api.json +64 -0
- package/contract/schemas/auth_matrix.json +44 -0
- package/contract/schemas/component_states.json +33 -0
- package/contract/schemas/design_tokens.json +34 -0
- package/contract/schemas/scene_direction.json +82 -0
- package/contract/schemas/threat_model.json +44 -0
- package/package.json +2 -1
- package/plugins/changes/client.js +5 -3
- package/plugins/deploy/index.js +215 -0
- package/plugins/deploy/package.json +13 -0
- package/plugins/grounding/index.js +81 -0
- package/plugins/grounding/lookup.js +373 -0
- package/plugins/grounding/package.json +13 -0
- package/plugins/kriya-tools/index.js +2 -1
- package/plugins/loop/index.js +381 -10
- package/plugins/mcp/index.js +79 -0
- package/plugins/mcp/package.json +13 -0
- package/plugins/mirror/index.js +17 -0
- package/plugins/overview/client.js +5 -2
- package/plugins/preview/client.js +12 -6
- package/plugins/progress/client.js +7 -4
- package/plugins/repo/index.js +230 -0
- package/plugins/repo/package.json +13 -0
- package/plugins/repo/repo.js +348 -0
- package/plugins/runstrip/client.js +436 -0
- package/plugins/runstrip/index.js +312 -0
- package/plugins/runstrip/package.json +23 -0
- package/src/cartridges.js +133 -0
- package/src/contracts.js +130 -0
- package/src/critic.js +78 -0
- package/src/daemon.js +7 -1
- package/src/doctor.js +67 -0
- package/src/edit/core/effects.js +185 -0
- package/src/edit/core/ffmpeg.js +65 -6
- package/src/edit/core/layout.js +46 -1
- package/src/edit/core/ops.js +169 -2
- package/src/edit/core/plan.js +65 -9
- package/src/edit/core/project.d.ts +24 -0
- package/src/edit/core/project.js +64 -0
- package/src/edit/core/solver.js +34 -6
- package/src/edit/core/style-brief.js +211 -0
- package/src/edit/core/style-packs.js +57 -0
- package/src/edit/core/type-kit.js +173 -0
- package/src/edit/director/ask.js +37 -3
- package/src/edit/director/assembly.js +829 -0
- package/src/edit/director/continuity.js +9 -1
- package/src/edit/director/custom-motion.js +88 -0
- package/src/edit/director/graphics.js +44 -10
- package/src/edit/director/intent.js +125 -0
- package/src/edit/director/mentions.js +52 -0
- package/src/edit/director/plan.js +43 -11
- package/src/edit/director/revise.js +132 -9
- package/src/edit/director/viewer.js +136 -0
- package/src/edit/director/watch-fix.js +119 -0
- package/src/edit/engine/captions.js +110 -5
- package/src/edit/engine/confine.js +81 -4
- package/src/edit/engine/custom.js +243 -0
- package/src/edit/engine/dna2.js +893 -0
- package/src/edit/engine/fonts.js +218 -0
- package/src/edit/engine/graphics.js +271 -10
- package/src/edit/engine/index.js +14 -5
- package/src/edit/engine/motion.js +148 -13
- package/src/edit/engine/music-bed.js +59 -1
- package/src/edit/engine/packs.js +11 -0
- package/src/edit/engine/reference2.js +26 -0
- package/src/edit/engine/sfx.js +56 -1
- package/src/edit/engine/tool.js +21 -5
- package/src/edit/gates/assembly.js +194 -0
- package/src/edit/gates/copy.js +7 -4
- package/src/edit/gates/index.js +72 -7
- package/src/edit/gates/reference.js +115 -0
- package/src/edit/gates/tile.js +96 -0
- package/src/edit/host/client.js +8 -3
- package/src/edit/host/clips.js +33 -0
- package/src/edit/host/jobs.js +9 -3
- package/src/edit/host/layers.js +134 -0
- package/src/edit/host/main.js +10 -3
- package/src/edit/host/paths.js +21 -3
- package/src/edit/host/preview.js +108 -0
- package/src/edit/host/projects.js +443 -34
- package/src/edit/host/server.js +235 -20
- package/src/edit/host/tavi.js +77 -0
- package/src/edit/index/index.js +3 -2
- package/src/edit/loop/make.js +28 -3
- package/src/edit/recipes/assembly.js +352 -0
- package/src/edit/recipes/graphic-clips.js +4 -2
- package/src/edit/recipes/openings.js +36 -0
- package/src/edit/recipes/reel.js +104 -14
- package/src/edit/recipes/reference-look.js +29 -0
- package/src/edit/recipes/short-from-long.js +3 -3
- package/src/edit/recipes/sound.js +71 -0
- package/src/edit/runtime/cli.js +26 -5
- package/src/edit/runtime/fetch.js +4 -4
- package/src/edit/runtime/licences.js +7 -1
- package/src/explore.js +103 -0
- package/src/failure.js +1 -1
- package/src/gate-commands.js +114 -0
- package/src/gates/api.js +127 -0
- package/src/gates/commands.js +111 -0
- package/src/gates/detectors.js +370 -0
- package/src/gates/http.js +62 -0
- package/src/gates/index.js +196 -0
- package/src/gates/page.js +264 -0
- package/src/gates/sast.js +64 -0
- package/src/gates/stack.js +110 -0
- package/src/gates/tenant.js +162 -0
- package/src/gates/three.js +431 -0
- package/src/gates/ui.js +111 -0
- package/src/gateway-proxy.js +20 -2
- package/src/launch.js +39 -5
- package/src/loop.js +199 -7
- package/src/mcp.js +126 -0
- package/src/milestones.js +188 -0
- package/src/modes.js +67 -0
- package/src/orchestra.js +50 -0
- package/src/outcomes.js +88 -0
- package/src/profiles.js +5 -0
- package/src/receipts.js +238 -0
- package/src/release.js +356 -0
- package/src/runstrip.js +122 -0
- package/src/stack.js +120 -0
- package/src/verify.js +67 -20
- package/studio/dist/fonts/fraunces.woff2 +0 -0
- package/studio/dist/fonts/geist.woff2 +0 -0
- package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
- package/studio/dist/studio.css +449 -1
- package/studio/dist/studio.js +3 -3
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { execFile } from "node:child_process"
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
|
|
3
|
+
import { dirname, join } from "node:path"
|
|
4
|
+
|
|
5
|
+
import { contractProblems, CONTRACT_NAMES, CONTRACTS_DIR, drifted, ownedHashes } from "../contracts.js"
|
|
6
|
+
import { DETECTORS, findSecrets } from "./detectors.js"
|
|
7
|
+
import { apiGate } from "./api.js"
|
|
8
|
+
import { commandGate, dataGate, evalGate, simHeadlessGate } from "./commands.js"
|
|
9
|
+
import { sastGate } from "./sast.js"
|
|
10
|
+
import { stackGate } from "./stack.js"
|
|
11
|
+
import { tenantGate } from "./tenant.js"
|
|
12
|
+
import { threeGate } from "./three.js"
|
|
13
|
+
import { judgeA11y, judgeUi, uiReports } from "./ui.js"
|
|
14
|
+
|
|
15
|
+
// Harness 2.0 W3: the gate catalogue's runner (Kriya-Tavi docs/kriya-harness/
|
|
16
|
+
// upgrade_2.0/GATES.md). A gate is code with fixed logic; its configuration
|
|
17
|
+
// is typed data (the step's cartridge, the contracts), never a command, a
|
|
18
|
+
// pattern or a pass condition a model wrote. Gates run only after the
|
|
19
|
+
// person's own check passed; the first failing gate turns the run into a
|
|
20
|
+
// failure the builder gets back, like any other. Off unless kriya was started
|
|
21
|
+
// with --gates (KRIYA_GATES=on): off, verifyStep never calls this.
|
|
22
|
+
|
|
23
|
+
/** The gates built so far; a cartridge naming another one reads `not_checked: not built yet`. */
|
|
24
|
+
export const BUILT = ["G-CONTRACT", "G-DETECT", "G-SECRETS", "G-SAST", "G-STACK", "G-API", "G-TENANT", "G-UI", "G-A11Y", "G-DATA", "G-EVAL", "G-SAN", "G-IAC", "G-SIM", "G-SIM-HEADLESS", "G-FLAKE", "G-TRACE", "G-3D"]
|
|
25
|
+
/** Run for every step with gates on, whatever its role. */
|
|
26
|
+
export const ALWAYS = ["G-SECRETS", "G-CONTRACT"]
|
|
27
|
+
/**
|
|
28
|
+
* Gates whose `not_checked` makes a step fail instead of passing with a note.
|
|
29
|
+
* Code, never data: a cartridge or a proposal can add gates, never remove one
|
|
30
|
+
* here. A required gate counts only once the person set up what it needs
|
|
31
|
+
* (a gate's `optional` not_checked, e.g. no app confirmed, stays a note).
|
|
32
|
+
*/
|
|
33
|
+
export const REQUIRED = Object.freeze({ frontend: Object.freeze(["G-UI"]), database: Object.freeze(["G-STACK"]), security: Object.freeze(["G-TENANT"]) })
|
|
34
|
+
|
|
35
|
+
const LIMIT = 300 * 1024
|
|
36
|
+
const git = (cwd, args) =>
|
|
37
|
+
new Promise((done) => execFile("git", args, { cwd, maxBuffer: 32 * 1024 * 1024 }, (error, stdout) => done(error ? null : stdout)))
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The files this work changed (vs HEAD), with their text and the lines it
|
|
41
|
+
* added. Untracked files count as all added. Binary or huge files are listed
|
|
42
|
+
* with no text. `changed` comes from verifyStep's work tree.
|
|
43
|
+
*/
|
|
44
|
+
export async function changedFiles(root, changed) {
|
|
45
|
+
const files = []
|
|
46
|
+
for (const rel of changed) {
|
|
47
|
+
const abs = join(root, rel)
|
|
48
|
+
if (!existsSync(abs) || !statSync(abs).isFile()) continue
|
|
49
|
+
const size = statSync(abs).size
|
|
50
|
+
const siblings = readdirSync(dirname(abs))
|
|
51
|
+
const tracked = (await git(root, ["ls-files", "--error-unmatch", "--", rel])) !== null
|
|
52
|
+
if (size > LIMIT) {
|
|
53
|
+
files.push({ path: rel, content: "", added: [], isNew: !tracked, siblings })
|
|
54
|
+
continue
|
|
55
|
+
}
|
|
56
|
+
const content = readFileSync(abs, "utf8")
|
|
57
|
+
let added
|
|
58
|
+
if (!tracked) added = content.split("\n").map((text, i) => ({ line: i + 1, text }))
|
|
59
|
+
else {
|
|
60
|
+
added = []
|
|
61
|
+
const diff = (await git(root, ["diff", "--no-color", "--no-ext-diff", "-U0", "HEAD", "--", rel])) ?? ""
|
|
62
|
+
let next = 0
|
|
63
|
+
for (const line of diff.split("\n")) {
|
|
64
|
+
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line)
|
|
65
|
+
if (hunk) next = Number(hunk[1])
|
|
66
|
+
else if (line.startsWith("+") && !line.startsWith("+++")) added.push({ line: next++, text: line.slice(1) })
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
files.push({ path: rel, content: content.includes("\u0000") ? "" : content, added: content.includes("\u0000") ? [] : added, isNew: !tracked, siblings })
|
|
70
|
+
}
|
|
71
|
+
return files
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const result = (id, status, extra = {}) => ({ id, status, ...extra })
|
|
75
|
+
|
|
76
|
+
/** G-DETECT: the cartridge's detectors on the added lines; `error` findings fail. */
|
|
77
|
+
export function detect(files, detectors, context = {}) {
|
|
78
|
+
const findings = []
|
|
79
|
+
for (const { id, severity } of detectors) {
|
|
80
|
+
const d = DETECTORS[id]
|
|
81
|
+
if (!d) continue
|
|
82
|
+
for (const f of files) {
|
|
83
|
+
if (!d.files(f.path)) continue
|
|
84
|
+
for (const hit of d.find({ ...f, others: files, tenantTables: context.tenantTables ?? (() => false), assetLicensed: context.assetLicensed ?? (() => false) })) findings.push({ id, severity, path: f.path, ...hit })
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return findings
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const where = (f) => `${f.path}:${f.line}`
|
|
91
|
+
const listed = (findings, n = 12) => findings.slice(0, n).map((f) => `- ${where(f)} ${f.id ? `${f.id}: ` : ""}${f.why}`).join("\n") + (findings.length > n ? `\n- … and ${findings.length - n} more` : "")
|
|
92
|
+
|
|
93
|
+
/** FE-ASSET-LICENCE: the asset paths scene_direction.json lists with a licence and a source. */
|
|
94
|
+
export function assetLicences(root) {
|
|
95
|
+
let listed = []
|
|
96
|
+
try {
|
|
97
|
+
listed = JSON.parse(readFileSync(join(root, CONTRACTS_DIR, "scene_direction.json"), "utf8")).assets ?? []
|
|
98
|
+
} catch {
|
|
99
|
+
// No direction: no asset is licensed
|
|
100
|
+
}
|
|
101
|
+
const paths = new Set((Array.isArray(listed) ? listed : []).filter((a) => a?.licence && a?.source).map((a) => String(a.path)))
|
|
102
|
+
return (path) => paths.has(path)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Tables that are tenant data, for DB-NO-RLS: the auth matrix's tenant-scoped
|
|
107
|
+
* resources, or every table in a Supabase project (its tables are exposed
|
|
108
|
+
* through the Data API unless RLS is on).
|
|
109
|
+
*/
|
|
110
|
+
export function tenantTables(root) {
|
|
111
|
+
let matrix = []
|
|
112
|
+
try {
|
|
113
|
+
matrix = JSON.parse(readFileSync(join(root, CONTRACTS_DIR, "auth_matrix.json"), "utf8"))
|
|
114
|
+
} catch {
|
|
115
|
+
// No matrix
|
|
116
|
+
}
|
|
117
|
+
const scoped = new Set((Array.isArray(matrix) ? matrix : []).filter((r) => r?.tenantScoped).map((r) => String(r.resource).toLowerCase()))
|
|
118
|
+
const supabase = existsSync(join(root, "supabase"))
|
|
119
|
+
return (name) => supabase || scoped.has(name.toLowerCase()) || scoped.has(name.toLowerCase().split(".").at(-1))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Two patterns: a /g one for match(), a plain one for test() (a /g regex keeps state between test calls)
|
|
123
|
+
const ACCEPTANCE = /\bAC-\d{1,3}\b/g
|
|
124
|
+
const ONE_ACCEPTANCE = /\bAC-\d{1,3}\b/
|
|
125
|
+
const PASSED = /(✔|✓|√|\bPASS(ED)?\b|\bok\b|\bpassed\b)/
|
|
126
|
+
const FAILED = /(✖|✗|✕|×|\bFAIL(ED)?\b|\bnot ok\b|\bfailed\b)/
|
|
127
|
+
|
|
128
|
+
/** G-TRACE: every AC-n named in the step's done-when has a passing test with that id in this run's output. */
|
|
129
|
+
export function trace(step, output) {
|
|
130
|
+
const ids = [...new Set(String(step?.doneWhen ?? "").match(ACCEPTANCE) ?? [])]
|
|
131
|
+
if (!ids.length) return result("G-TRACE", "not_checked", { reason: "the step's done-when names no acceptance criteria (AC-1, AC-2, …)" })
|
|
132
|
+
const lines = String(output ?? "").split("\n")
|
|
133
|
+
if (!lines.some((l) => ONE_ACCEPTANCE.test(l) && PASSED.test(l))) return result("G-TRACE", "not_checked", { reason: "the check's output doesn't list passing tests by name (use the runner's verbose or spec reporter)" })
|
|
134
|
+
const missing = ids.filter((id) => !lines.some((l) => new RegExp(`\\b${id}\\b`).test(l) && PASSED.test(l) && !FAILED.test(l)))
|
|
135
|
+
return missing.length ? result("G-TRACE", "fail", { kind: "gate", excerpt: `G-TRACE: no passing test is named for ${missing.join(", ")}. Name one test per criterion with its id, e.g. "${missing[0]}: …".` }) : result("G-TRACE", "pass")
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Runs the step's gates after a passing check, in catalogue order; stops at the first failure.
|
|
140
|
+
* @param {{ root: string, step?: { title: string, doneWhen: string }, cartridge?: { role: string, gates: string[], detectors: Array<{ id: string, severity: string }>, owns: string[] }, changed: string[], output: string, rerun: () => Promise<{ exitCode: number|null, timedOut: boolean, output: string }>, recorded?: Record<string, { sha: string }>, label: string }} input
|
|
141
|
+
* @returns {Promise<{ results: Array<{ id: string, status: string, reason?: string, kind?: string, excerpt?: string }>, failure?: { id: string, kind: string, excerpt: string }, contracts: Record<string, { sha: string, step: string }> }>}
|
|
142
|
+
*/
|
|
143
|
+
export async function runGates({ root, step, cartridge, changed, output, rerun, command, recorded = {}, label, launch, psql, request, exec }) {
|
|
144
|
+
const wanted = [...new Set([...ALWAYS, ...(cartridge?.gates ?? [])])]
|
|
145
|
+
const order = [...BUILT, ...wanted.filter((g) => !BUILT.includes(g))].filter((g) => wanted.includes(g))
|
|
146
|
+
const required = new Set(cartridge ? (REQUIRED[cartridge.role] ?? []) : [])
|
|
147
|
+
const results = []
|
|
148
|
+
let files
|
|
149
|
+
const load = async () => (files ??= await changedFiles(root, changed))
|
|
150
|
+
// One visit per route × viewport × scheme, shared by G-UI and G-A11Y
|
|
151
|
+
let ui
|
|
152
|
+
const pages = async () => (ui ??= await uiReports({ root, label, launch }))
|
|
153
|
+
for (const id of order) {
|
|
154
|
+
let r
|
|
155
|
+
if (id === "G-SECRETS") {
|
|
156
|
+
const found = (await load()).flatMap((f) => findSecrets(f).map((hit) => ({ path: f.path, ...hit })))
|
|
157
|
+
r = found.length ? result(id, "fail", { kind: "gate", excerpt: `G-SECRETS: secrets in the changes (values not shown):\n${listed(found)}\nMove them to the environment or a secret store.` }) : result(id, "pass")
|
|
158
|
+
} else if (id === "G-CONTRACT") {
|
|
159
|
+
const problems = CONTRACT_NAMES.flatMap((name) => contractProblems(root, name, { gates: BUILT }))
|
|
160
|
+
const moved = drifted(root, recorded, cartridge?.owns ?? [])
|
|
161
|
+
if (moved.length)
|
|
162
|
+
r = result(id, "fail", { kind: "contract changed", excerpt: `G-CONTRACT: ${moved.map((m) => `${m.file} ${m.removed ? "was removed" : "changed"}`).join("; ")}, but this step's role doesn't own ${moved.length === 1 ? "it" : "them"}. Build to the contract as written; if it is wrong, say so and stop instead of changing it.` })
|
|
163
|
+
else if (problems.length) r = result(id, "fail", { kind: "gate", excerpt: `G-CONTRACT:\n${problems.map((p) => `- ${p}`).join("\n")}` })
|
|
164
|
+
else r = result(id, "pass")
|
|
165
|
+
} else if (id === "G-DETECT") {
|
|
166
|
+
const found = detect(await load(), cartridge?.detectors ?? [], { tenantTables: tenantTables(root), assetLicensed: assetLicences(root) })
|
|
167
|
+
const errors = found.filter((f) => f.severity === "error")
|
|
168
|
+
const warnings = found.filter((f) => f.severity !== "error")
|
|
169
|
+
r = errors.length ? result(id, "fail", { kind: "gate", excerpt: `G-DETECT:\n${listed(errors)}${warnings.length ? `\nAlso worth fixing:\n${listed(warnings, 6)}` : ""}` }) : result(id, "pass", warnings.length ? { warnings: warnings.length, note: listed(warnings, 6) } : {})
|
|
170
|
+
} else if (id === "G-FLAKE") {
|
|
171
|
+
const runs = []
|
|
172
|
+
for (let i = 0; i < 2; i++) runs.push(await rerun())
|
|
173
|
+
const bad = runs.findIndex((x) => x.exitCode !== 0 || x.timedOut)
|
|
174
|
+
r = bad === -1 ? result(id, "pass") : result(id, "fail", { kind: "flaky", excerpt: `G-FLAKE: the check passed, then ${runs[bad].timedOut ? "timed out" : `exited ${runs[bad].exitCode}`} on run ${bad + 2} of 3 with no change. A flaky test is a bug: find the shared state, clock or race.\n${String(runs[bad].output ?? "").slice(-1500)}` })
|
|
175
|
+
} else if (id === "G-TRACE") r = trace(step, output)
|
|
176
|
+
else if (id === "G-UI") r = judgeUi(await pages())
|
|
177
|
+
else if (id === "G-A11Y") r = judgeA11y(await pages())
|
|
178
|
+
else if (id === "G-3D") r = await threeGate({ root, label, launch })
|
|
179
|
+
else if (id === "G-STACK") r = await stackGate({ root, changed, tenantTables: tenantTables(root), ...(psql && { run: psql }) })
|
|
180
|
+
else if (id === "G-API") r = await apiGate({ root, ...(request && { request }) })
|
|
181
|
+
else if (id === "G-TENANT") r = await tenantGate({ root, ...(request && { request }) })
|
|
182
|
+
else if (id === "G-SAST") r = await sastGate({ root, changed, ...(exec && { run: exec }) })
|
|
183
|
+
else if (["G-DATA", "G-EVAL", "G-SAN", "G-IAC", "G-SIM", "G-SIM-HEADLESS"].includes(id) && !command) r = result(id, "not_checked", { reason: "this check runs no command here" })
|
|
184
|
+
else if (id === "G-DATA") r = await dataGate({ root, command })
|
|
185
|
+
else if (id === "G-EVAL") r = await evalGate({ root, command, changed })
|
|
186
|
+
else if (id === "G-SAN") r = await commandGate({ root, command, gate: "san", id })
|
|
187
|
+
else if (id === "G-IAC") r = await commandGate({ root, command, gate: "iac", id })
|
|
188
|
+
else if (id === "G-SIM") r = await commandGate({ root, command, gate: "sim", id })
|
|
189
|
+
else if (id === "G-SIM-HEADLESS") r = await simHeadlessGate({ root, command })
|
|
190
|
+
else r = result(id, "not_checked", { reason: "not built yet" })
|
|
191
|
+
if (r.status === "not_checked" && !r.optional && required.has(id)) r = { ...r, status: "fail", kind: "not checked", excerpt: `${id} couldn't run (${r.reason}), and a ${cartridge.role} step needs it.` }
|
|
192
|
+
results.push(r)
|
|
193
|
+
if (r.status === "fail") return { results, failure: { id, kind: r.kind, excerpt: r.excerpt }, contracts: {} }
|
|
194
|
+
}
|
|
195
|
+
return { results, contracts: ownedHashes(root, cartridge?.owns ?? [], label) }
|
|
196
|
+
}
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { mkdirSync, writeFileSync } from "node:fs"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
import { inflateSync } from "node:zlib"
|
|
5
|
+
|
|
6
|
+
import { browserTarget, localUrl } from "../browser.js"
|
|
7
|
+
|
|
8
|
+
// Harness 2.0 W4: the gates' own browser (Kriya-Tavi docs/kriya-harness/
|
|
9
|
+
// upgrade_2.0/GATES.md G-UI, G-A11Y; REAUDIT RA-20). Never the agent's shared
|
|
10
|
+
// page: a short-lived headless browser of the same installed Chrome, one
|
|
11
|
+
// context per viewport and colour scheme, the same loopback rule on every
|
|
12
|
+
// navigation (src/browser.js localUrl), closed when the gate ends. It reads
|
|
13
|
+
// the rendered page; it clicks, types and submits nothing.
|
|
14
|
+
|
|
15
|
+
export const VIEWPORTS = [
|
|
16
|
+
{ name: "360", width: 360, height: 780 },
|
|
17
|
+
{ name: "390", width: 390, height: 844 },
|
|
18
|
+
{ name: "1440", width: 1440, height: 900 },
|
|
19
|
+
]
|
|
20
|
+
export const SCHEMES = ["light", "dark"]
|
|
21
|
+
|
|
22
|
+
const NAV_MS = 30_000
|
|
23
|
+
const IDLE_MS = 5_000
|
|
24
|
+
|
|
25
|
+
/** Runs `fn(open)` with a gate browser; `open(url, { viewport, scheme, reducedMotion })` gives a page report. Closes everything after. */
|
|
26
|
+
export async function withGateBrowser(fn, { launch } = {}) {
|
|
27
|
+
const target = browserTarget()
|
|
28
|
+
if (!target && !launch) return { unavailable: "no Chrome, Edge, Brave or Chromium on this computer" }
|
|
29
|
+
let browser
|
|
30
|
+
try {
|
|
31
|
+
if (launch) browser = await launch()
|
|
32
|
+
else {
|
|
33
|
+
const { chromium } = await import("playwright-core")
|
|
34
|
+
browser = await chromium.launch({ ...target, headless: true, args: ["--no-first-run", "--disable-sync", "--disable-extensions", "--disable-background-networking", "--disable-component-update"] })
|
|
35
|
+
}
|
|
36
|
+
} catch (error) {
|
|
37
|
+
return { unavailable: `the browser didn't start (${String(error?.message ?? error).split("\n")[0].slice(0, 160)})` }
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
// G-3D (W13) opens its own pages on the same browser, so it gets the browser too
|
|
41
|
+
return { value: await fn((url, options) => visit(browser, url, options), browser) }
|
|
42
|
+
} finally {
|
|
43
|
+
await browser.close().catch(() => {})
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Installed before the page's own scripts: layout shifts as they happen
|
|
48
|
+
const INIT = `(() => {
|
|
49
|
+
window.__kriyaCLS = 0
|
|
50
|
+
try {
|
|
51
|
+
new PerformanceObserver((list) => {
|
|
52
|
+
for (const e of list.getEntries()) if (!e.hadRecentInput) window.__kriyaCLS += e.value
|
|
53
|
+
}).observe({ type: "layout-shift", buffered: true })
|
|
54
|
+
} catch {}
|
|
55
|
+
})()`
|
|
56
|
+
|
|
57
|
+
async function visit(browser, url, { viewport, scheme = "light", reducedMotion = "no-preference" }) {
|
|
58
|
+
const target = localUrl(url)
|
|
59
|
+
if (target.error) throw new Error(target.error)
|
|
60
|
+
const origin = new URL(target.url).origin
|
|
61
|
+
const context = await browser.newContext({ viewport: { width: viewport.width, height: viewport.height }, colorScheme: scheme, reducedMotion, acceptDownloads: false, serviceWorkers: "block" })
|
|
62
|
+
try {
|
|
63
|
+
await context.route("**/*", (route) => {
|
|
64
|
+
const request = route.request()
|
|
65
|
+
if (request.isNavigationRequest() && localUrl(request.url()).error) return route.abort("blockedbyclient")
|
|
66
|
+
return route.continue()
|
|
67
|
+
})
|
|
68
|
+
await context.addInitScript(INIT)
|
|
69
|
+
const page = await context.newPage()
|
|
70
|
+
const consoleErrors = []
|
|
71
|
+
const failed = []
|
|
72
|
+
page.on("console", (m) => m.type() === "error" && consoleErrors.push(m.text().slice(0, 300)))
|
|
73
|
+
page.on("pageerror", (e) => consoleErrors.push(String(e?.message ?? e).slice(0, 300)))
|
|
74
|
+
page.on("response", (r) => {
|
|
75
|
+
const u = r.url()
|
|
76
|
+
if (r.status() >= 400 && u.startsWith(origin) && !/\/favicon\.ico$/.test(u)) failed.push(`${r.status()} ${u.slice(origin.length) || "/"}`)
|
|
77
|
+
})
|
|
78
|
+
page.on("requestfailed", (r) => r.url().startsWith(origin) && failed.push(`failed ${r.url().slice(origin.length) || "/"} (${r.failure()?.errorText ?? "error"})`))
|
|
79
|
+
let status = null
|
|
80
|
+
try {
|
|
81
|
+
status = (await page.goto(target.url, { waitUntil: "load", timeout: NAV_MS }))?.status() ?? null
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return { url: target.url, viewport: viewport.name, scheme, unreachable: /ERR_CONNECTION_REFUSED/.test(String(error?.message)) ? "nothing answers there" : String(error?.message ?? error).split("\n")[0].slice(0, 200) }
|
|
84
|
+
}
|
|
85
|
+
await page.waitForLoadState("networkidle", { timeout: IDLE_MS }).catch(() => {})
|
|
86
|
+
await page.waitForTimeout(250)
|
|
87
|
+
const facts = await page.evaluate(MEASURE)
|
|
88
|
+
const glass = []
|
|
89
|
+
for (const g of facts.glass.slice(0, 12)) {
|
|
90
|
+
const clip = { x: Math.max(0, g.box.x), y: Math.max(0, g.box.y), width: Math.max(1, Math.min(g.box.width, viewport.width - Math.max(0, g.box.x))), height: Math.max(1, Math.min(g.box.height, viewport.height - Math.max(0, g.box.y))) }
|
|
91
|
+
// The text hidden, the backdrop shot: contrast against its lightest and darkest pixel
|
|
92
|
+
await page.evaluate(({ i, hide }) => document.querySelectorAll("[data-kriya-glass]")[i]?.style.setProperty("color", hide ? "transparent" : "", hide ? "important" : ""), { i: g.index, hide: true })
|
|
93
|
+
const png = await page.screenshot({ clip, animations: "disabled" }).catch(() => null)
|
|
94
|
+
await page.evaluate(({ i }) => document.querySelectorAll("[data-kriya-glass]")[i]?.style.removeProperty("color"), { i: g.index })
|
|
95
|
+
if (!png) continue
|
|
96
|
+
const range = luminanceRange(png)
|
|
97
|
+
if (range) glass.push({ ...g, worst: Math.min(contrast(g.text, range.min), contrast(g.text, range.max)) })
|
|
98
|
+
}
|
|
99
|
+
const shot = await page.screenshot({ fullPage: false, animations: "disabled" }).catch(() => null)
|
|
100
|
+
return { url: target.url, viewport: viewport.name, scheme, status, consoleErrors, failed, ...facts, glass, shot }
|
|
101
|
+
} finally {
|
|
102
|
+
await context.close().catch(() => {})
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Runs in the page: overflow, layout shift, targets, names, headings, lang, text contrast and glass surfaces. */
|
|
107
|
+
const MEASURE = () => {
|
|
108
|
+
const parse = (c) => {
|
|
109
|
+
const m = /rgba?\(([\d.]+)[ ,]+([\d.]+)[ ,]+([\d.]+)(?:[ ,/]+([\d.]+%?))?\)/.exec(c || "")
|
|
110
|
+
if (!m) return null
|
|
111
|
+
const a = m[4] === undefined ? 1 : m[4].endsWith("%") ? Number.parseFloat(m[4]) / 100 : Number(m[4])
|
|
112
|
+
return [Number(m[1]), Number(m[2]), Number(m[3]), a]
|
|
113
|
+
}
|
|
114
|
+
const lum = ([r, g, b]) => {
|
|
115
|
+
const f = (v) => ((v /= 255) <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)
|
|
116
|
+
return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b)
|
|
117
|
+
}
|
|
118
|
+
const ratio = (a, b) => (Math.max(lum(a), lum(b)) + 0.05) / (Math.min(lum(a), lum(b)) + 0.05)
|
|
119
|
+
const visible = (el) => {
|
|
120
|
+
const r = el.getBoundingClientRect()
|
|
121
|
+
const s = getComputedStyle(el)
|
|
122
|
+
return r.width > 0 && r.height > 0 && s.visibility !== "hidden" && s.display !== "none" && Number(s.opacity) > 0
|
|
123
|
+
}
|
|
124
|
+
const backdrop = (el) => {
|
|
125
|
+
for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
|
|
126
|
+
const s = getComputedStyle(n)
|
|
127
|
+
if ((s.backdropFilter && s.backdropFilter !== "none") || (s.webkitBackdropFilter && s.webkitBackdropFilter !== "none")) return { glass: n }
|
|
128
|
+
const bg = parse(s.backgroundColor)
|
|
129
|
+
if (bg && bg[3] >= 0.95) return { color: bg }
|
|
130
|
+
if (bg && bg[3] > 0.05) return { glass: n }
|
|
131
|
+
if (s.backgroundImage && s.backgroundImage !== "none") return { image: true }
|
|
132
|
+
}
|
|
133
|
+
return { color: [255, 255, 255, 1] }
|
|
134
|
+
}
|
|
135
|
+
const overflow = document.scrollingElement.scrollWidth > window.innerWidth + 1
|
|
136
|
+
const small = []
|
|
137
|
+
const unnamed = []
|
|
138
|
+
const interactive = [...document.querySelectorAll("a[href], button, input:not([type=hidden]), select, textarea, [role=button], [role=link], [role=checkbox], [role=tab], [role=menuitem], [tabindex]:not([tabindex='-1'])")].filter(visible)
|
|
139
|
+
for (const el of interactive) {
|
|
140
|
+
const r = el.getBoundingClientRect()
|
|
141
|
+
if (Math.min(r.width, r.height) < 44) small.push({ what: el.tagName.toLowerCase() + (el.id ? `#${el.id}` : ""), size: [Math.round(r.width), Math.round(r.height)] })
|
|
142
|
+
const labelled = el.labels?.length || el.getAttribute("aria-label") || el.getAttribute("aria-labelledby") || el.getAttribute("title") || (el.textContent || "").trim() || el.querySelector("img[alt]:not([alt=''])") || (el.tagName === "INPUT" && ["submit", "button", "reset"].includes(el.type) && el.value)
|
|
143
|
+
if (!labelled) unnamed.push(el.tagName.toLowerCase() + (el.id ? `#${el.id}` : "") + (el.className && typeof el.className === "string" ? `.${el.className.split(/\s+/)[0]}` : ""))
|
|
144
|
+
}
|
|
145
|
+
const headings = [...document.querySelectorAll("h1,h2,h3,h4,h5,h6")].filter(visible).map((h) => Number(h.tagName[1]))
|
|
146
|
+
const skips = headings.filter((h, i) => i > 0 && h > headings[i - 1] + 1).length
|
|
147
|
+
const lowContrast = []
|
|
148
|
+
const glassText = []
|
|
149
|
+
const seen = new Set()
|
|
150
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, { acceptNode: (t) => ((t.textContent || "").trim().length > 1 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT) })
|
|
151
|
+
for (let t = walker.nextNode(), n = 0; t && n < 400; t = walker.nextNode(), n++) {
|
|
152
|
+
const el = t.parentElement
|
|
153
|
+
if (!el || seen.has(el) || !visible(el)) continue
|
|
154
|
+
seen.add(el)
|
|
155
|
+
const s = getComputedStyle(el)
|
|
156
|
+
const fg = parse(s.color)
|
|
157
|
+
if (!fg || fg[3] < 0.1) continue
|
|
158
|
+
const size = Number.parseFloat(s.fontSize)
|
|
159
|
+
const large = size >= 24 || (size >= 18.66 && Number(s.fontWeight) >= 700)
|
|
160
|
+
const need = large ? 3 : 4.5
|
|
161
|
+
const behind = backdrop(el)
|
|
162
|
+
if (behind.glass) {
|
|
163
|
+
if (glassText.length < 12) {
|
|
164
|
+
el.setAttribute("data-kriya-glass", "")
|
|
165
|
+
const r = el.getBoundingClientRect()
|
|
166
|
+
glassText.push({ index: glassText.length, text: fg, need, what: el.tagName.toLowerCase(), box: { x: r.x, y: r.y, width: r.width, height: r.height } })
|
|
167
|
+
}
|
|
168
|
+
} else if (behind.color) {
|
|
169
|
+
const value = ratio(fg, behind.color)
|
|
170
|
+
if (value < need) lowContrast.push({ what: el.tagName.toLowerCase(), text: (t.textContent || "").trim().slice(0, 40), ratio: Math.round(value * 100) / 100, need })
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return {
|
|
174
|
+
overflow,
|
|
175
|
+
cls: Math.round((window.__kriyaCLS ?? 0) * 1000) / 1000,
|
|
176
|
+
small,
|
|
177
|
+
unnamed: unnamed.slice(0, 20),
|
|
178
|
+
lang: Boolean(document.documentElement.getAttribute("lang")),
|
|
179
|
+
headingSkips: skips,
|
|
180
|
+
lowContrast: lowContrast.slice(0, 20),
|
|
181
|
+
glass: glassText,
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const relLum = (r, g, b) => {
|
|
186
|
+
const f = (v) => ((v /= 255) <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)
|
|
187
|
+
return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b)
|
|
188
|
+
}
|
|
189
|
+
/** WCAG contrast between an [r,g,b] colour and a relative luminance */
|
|
190
|
+
export const contrast = (rgb, luminance) => {
|
|
191
|
+
const a = relLum(rgb[0], rgb[1], rgb[2])
|
|
192
|
+
return (Math.max(a, luminance) + 0.05) / (Math.min(a, luminance) + 0.05)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The lightest and darkest relative luminance in a PNG (8-bit RGB/RGBA, any filter), or null. */
|
|
196
|
+
export function luminanceRange(png) {
|
|
197
|
+
const pixels = decodePng(png)
|
|
198
|
+
if (!pixels) return null
|
|
199
|
+
let min = 1
|
|
200
|
+
let max = 0
|
|
201
|
+
for (let i = 0; i < pixels.data.length; i += pixels.channels) {
|
|
202
|
+
const l = relLum(pixels.data[i], pixels.data[i + 1], pixels.data[i + 2])
|
|
203
|
+
if (l < min) min = l
|
|
204
|
+
if (l > max) max = l
|
|
205
|
+
}
|
|
206
|
+
return { min, max }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** A minimal PNG decoder for screenshots: 8-bit truecolour (2) or truecolour+alpha (6), not interlaced. */
|
|
210
|
+
export function decodePng(buf) {
|
|
211
|
+
if (!Buffer.isBuffer(buf) || buf.length < 33 || buf.readUInt32BE(0) !== 0x89504e47) return null
|
|
212
|
+
let width
|
|
213
|
+
let height
|
|
214
|
+
let type
|
|
215
|
+
const idat = []
|
|
216
|
+
for (let at = 8; at + 8 <= buf.length; ) {
|
|
217
|
+
const length = buf.readUInt32BE(at)
|
|
218
|
+
const name = buf.toString("ascii", at + 4, at + 8)
|
|
219
|
+
const body = buf.subarray(at + 8, at + 8 + length)
|
|
220
|
+
if (name === "IHDR") {
|
|
221
|
+
width = body.readUInt32BE(0)
|
|
222
|
+
height = body.readUInt32BE(4)
|
|
223
|
+
if (body[8] !== 8 || body[12] !== 0) return null
|
|
224
|
+
type = body[9]
|
|
225
|
+
} else if (name === "IDAT") idat.push(body)
|
|
226
|
+
else if (name === "IEND") break
|
|
227
|
+
at += 12 + length
|
|
228
|
+
}
|
|
229
|
+
const channels = type === 6 ? 4 : type === 2 ? 3 : 0
|
|
230
|
+
if (!channels || !width || !height) return null
|
|
231
|
+
const raw = inflateSync(Buffer.concat(idat))
|
|
232
|
+
const stride = width * channels
|
|
233
|
+
const out = Buffer.alloc(stride * height)
|
|
234
|
+
for (let y = 0; y < height; y++) {
|
|
235
|
+
const filter = raw[y * (stride + 1)]
|
|
236
|
+
const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1))
|
|
237
|
+
for (let x = 0; x < stride; x++) {
|
|
238
|
+
const left = x >= channels ? out[y * stride + x - channels] : 0
|
|
239
|
+
const up = y > 0 ? out[(y - 1) * stride + x] : 0
|
|
240
|
+
const ul = y > 0 && x >= channels ? out[(y - 1) * stride + x - channels] : 0
|
|
241
|
+
let v = line[x]
|
|
242
|
+
if (filter === 1) v += left
|
|
243
|
+
else if (filter === 2) v += up
|
|
244
|
+
else if (filter === 3) v += (left + up) >> 1
|
|
245
|
+
else if (filter === 4) {
|
|
246
|
+
const p = left + up - ul
|
|
247
|
+
const pa = Math.abs(p - left)
|
|
248
|
+
const pb = Math.abs(p - up)
|
|
249
|
+
const pc = Math.abs(p - ul)
|
|
250
|
+
v += pa <= pb && pa <= pc ? left : pb <= pc ? up : ul
|
|
251
|
+
}
|
|
252
|
+
out[y * stride + x] = v & 0xff
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return { width, height, channels, data: out }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Saves a screenshot as evidence outside the project; returns its sha256. */
|
|
259
|
+
export function keepShot(dir, name, png) {
|
|
260
|
+
if (!png) return undefined
|
|
261
|
+
mkdirSync(dir, { recursive: true })
|
|
262
|
+
writeFileSync(join(dir, name), png)
|
|
263
|
+
return createHash("sha256").update(png).digest("hex")
|
|
264
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { execFile } from "node:child_process"
|
|
2
|
+
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
|
3
|
+
import { tmpdir } from "node:os"
|
|
4
|
+
import { join } from "node:path"
|
|
5
|
+
|
|
6
|
+
// Harness 2.0 W5: G-SAST (Kriya-Tavi docs/kriya-harness/upgrade_2.0/GATES.md
|
|
7
|
+
// §3). Semgrep, only if installed, only with the rules the project committed
|
|
8
|
+
// (.semgrep.yml / .semgrep.yaml / .semgrep/), read as they are at HEAD so a
|
|
9
|
+
// builder can't weaken them (GATES rule 9). Never `--config auto` or a
|
|
10
|
+
// registry config: those fetch rules over the network. Metrics and the version
|
|
11
|
+
// check are off. ERROR findings in the changed files fail.
|
|
12
|
+
|
|
13
|
+
const MS = 5 * 60_000
|
|
14
|
+
|
|
15
|
+
const exec = (cmd, args, options = {}) =>
|
|
16
|
+
new Promise((done) =>
|
|
17
|
+
execFile(cmd, args, { timeout: MS, maxBuffer: 32 * 1024 * 1024, ...options }, (error, stdout, stderr) =>
|
|
18
|
+
done({ code: error ? (typeof error.code === "number" ? error.code : -1) : 0, missing: error?.code === "ENOENT", stdout: String(stdout ?? ""), stderr: String(stderr ?? "") })
|
|
19
|
+
)
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
/** The committed rules, copied out of HEAD into a temp folder; { path } or { reason } */
|
|
23
|
+
export async function committedRules(root, dir, run = exec) {
|
|
24
|
+
for (const name of [".semgrep.yml", ".semgrep.yaml"]) {
|
|
25
|
+
const shown = await run("git", ["show", `HEAD:${name}`], { cwd: root })
|
|
26
|
+
if (shown.code === 0 && shown.stdout.trim()) {
|
|
27
|
+
const path = join(dir, name)
|
|
28
|
+
writeFileSync(path, shown.stdout)
|
|
29
|
+
return { path }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const listed = await run("git", ["ls-tree", "-r", "--name-only", "HEAD", ".semgrep"], { cwd: root })
|
|
33
|
+
if (listed.code === 0 && listed.stdout.trim()) {
|
|
34
|
+
const archived = await run("sh", ["-c", 'git archive HEAD .semgrep | tar -x -C "$1"', "sh", dir], { cwd: root })
|
|
35
|
+
if (archived.code === 0 && existsSync(join(dir, ".semgrep"))) return { path: join(dir, ".semgrep") }
|
|
36
|
+
}
|
|
37
|
+
return { reason: "the project has no committed Semgrep rules (.semgrep.yml or .semgrep/)" }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** @param {{ root: string, changed: string[], run?: typeof exec }} input */
|
|
41
|
+
export async function sastGate({ root, changed, run = exec }) {
|
|
42
|
+
const id = "G-SAST"
|
|
43
|
+
const files = changed.filter((rel) => existsSync(join(root, rel))).slice(0, 200)
|
|
44
|
+
if (!files.length) return { id, status: "pass", note: "no changed file to scan" }
|
|
45
|
+
const version = await run("semgrep", ["--version"])
|
|
46
|
+
if (version.missing) return { id, status: "not_checked", reason: "Semgrep isn't installed" }
|
|
47
|
+
const dir = mkdtempSync(join(tmpdir(), "kriya-sast-"))
|
|
48
|
+
try {
|
|
49
|
+
const rules = await committedRules(root, dir, run)
|
|
50
|
+
if (!rules.path) return { id, status: "not_checked", reason: rules.reason }
|
|
51
|
+
const out = await run("semgrep", ["scan", "--config", rules.path, "--json", "--metrics", "off", "--disable-version-check", "--quiet", "--", ...files], { cwd: root, env: { ...process.env, SEMGREP_SEND_METRICS: "off", SEMGREP_ENABLE_VERSION_CHECK: "0" } })
|
|
52
|
+
let report
|
|
53
|
+
try {
|
|
54
|
+
report = JSON.parse(out.stdout)
|
|
55
|
+
} catch {
|
|
56
|
+
return { id, status: "not_checked", reason: `Semgrep didn't finish (exit ${out.code}): ${out.stderr.trim().split("\n").at(-1)?.slice(0, 160) ?? ""}` }
|
|
57
|
+
}
|
|
58
|
+
const errors = (report.results ?? []).filter((r) => String(r?.extra?.severity).toUpperCase() === "ERROR")
|
|
59
|
+
if (!errors.length) return { id, status: "pass", note: `${(report.results ?? []).length} finding(s), none at ERROR` }
|
|
60
|
+
return { id, status: "fail", kind: "gate", excerpt: `G-SAST (the project's committed Semgrep rules):\n${errors.slice(0, 12).map((r) => `- ${r.path}:${r.start?.line ?? "?"} ${r.check_id}: ${String(r.extra?.message ?? "").replace(/\s+/g, " ").slice(0, 160)}`).join("\n")}` }
|
|
61
|
+
} finally {
|
|
62
|
+
rmSync(dir, { recursive: true, force: true })
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { execFile } from "node:child_process"
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
|
3
|
+
import { tmpdir } from "node:os"
|
|
4
|
+
import { join } from "node:path"
|
|
5
|
+
|
|
6
|
+
import { hostedDatabase, isLocalDatabase, readStack } from "../stack.js"
|
|
7
|
+
|
|
8
|
+
// Harness 2.0 W4: G-STACK (Kriya-Tavi docs/kriya-harness/upgrade_2.0/GATES.md
|
|
9
|
+
// §3, WD-05). The migrations this work added or changed really apply to the
|
|
10
|
+
// person's local database, and every tenant table they create has row-level
|
|
11
|
+
// security with a policy. All of it runs inside one transaction that is
|
|
12
|
+
// always rolled back (Postgres DDL is transactional), so the database is left
|
|
13
|
+
// exactly as it was. Only a database the person confirmed with `kriya stack
|
|
14
|
+
// use --db`, only on this computer, and never while the project's own env
|
|
15
|
+
// files point at a hosted one.
|
|
16
|
+
|
|
17
|
+
export const MIGRATION = /(^|\/)(supabase\/migrations|migrations|db\/migrations|database\/migrations)\/[^/]+\.sql$|(^|\/)prisma\/migrations\/[^/]+\/migration\.sql$/
|
|
18
|
+
export const CONTRACT_SCHEMA = ".kriya/contracts/schema.sql"
|
|
19
|
+
const PSQL_MS = 5 * 60_000
|
|
20
|
+
const NO_TRANSACTION = /cannot run inside a transaction block|cannot be executed inside a transaction|ALTER TYPE \.\.\. ADD cannot run inside a transaction block/i
|
|
21
|
+
|
|
22
|
+
const psql = (args, input) =>
|
|
23
|
+
new Promise((done) => {
|
|
24
|
+
const child = execFile("psql", args, { timeout: PSQL_MS, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, PGCONNECT_TIMEOUT: "10" } }, (error, stdout, stderr) =>
|
|
25
|
+
done({ code: error ? (typeof error.code === "number" ? error.code : 127) : 0, missing: error?.code === "ENOENT", stdout: String(stdout), stderr: String(stderr) })
|
|
26
|
+
)
|
|
27
|
+
if (input !== undefined) child.stdin.end(input)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
/** Tables a migration creates, schema-qualified (public by default) */
|
|
31
|
+
export function createdTables(sql) {
|
|
32
|
+
return [...sql.matchAll(/\bcreate\s+table\s+(?:if\s+not\s+exists\s+)?((?:"?[\w]+"?\.)?"?[\w]+"?)/gi)].map((m) => {
|
|
33
|
+
const name = m[1].replace(/"/g, "")
|
|
34
|
+
return name.includes(".") ? name : `public.${name}`
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** True when SQL controls transactions itself or holds psql meta-commands (outside comments and dollar-quoted bodies). */
|
|
39
|
+
export function ownsTransaction(sql) {
|
|
40
|
+
const plain = sql
|
|
41
|
+
.replace(/\$(\w*)\$[\s\S]*?\$\1\$/g, "")
|
|
42
|
+
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
43
|
+
.replace(/--[^\n]*/g, "")
|
|
44
|
+
return /(^|;)\s*(begin|start\s+transaction|commit|end|rollback|savepoint|release)\b/im.test(plain) || /^\s*\\/m.test(plain)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const quote = (path) => `'${path.replace(/'/g, "''")}'`
|
|
48
|
+
|
|
49
|
+
/** The script psql runs: every file in one transaction, the RLS facts between markers, then ROLLBACK. Pure, for tests. */
|
|
50
|
+
export function stackScript(files, tables) {
|
|
51
|
+
const list = tables.map((t) => `'${t.replace(/'/g, "''")}'`).join(", ")
|
|
52
|
+
return [
|
|
53
|
+
"\\set ON_ERROR_STOP 1",
|
|
54
|
+
"\\pset format unaligned",
|
|
55
|
+
"\\pset tuples_only on",
|
|
56
|
+
"BEGIN;",
|
|
57
|
+
...files.map((f) => `\\i ${quote(f)}`),
|
|
58
|
+
"\\echo KRIYA-RLS-BEGIN",
|
|
59
|
+
...(tables.length
|
|
60
|
+
? [
|
|
61
|
+
`SELECT n.nspname || '.' || c.relname || '|' || c.relrowsecurity::text || '|' || (SELECT count(*) FROM pg_policies p WHERE p.schemaname = n.nspname AND p.tablename = c.relname)::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'p') AND n.nspname || '.' || c.relname IN (${list});`,
|
|
62
|
+
]
|
|
63
|
+
: []),
|
|
64
|
+
"\\echo KRIYA-RLS-END",
|
|
65
|
+
"ROLLBACK;",
|
|
66
|
+
"",
|
|
67
|
+
].join("\n")
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* G-STACK for one verify.
|
|
72
|
+
* @param {{ root: string, changed: string[], tenantTables: (name: string) => boolean, run?: typeof psql }} input
|
|
73
|
+
*/
|
|
74
|
+
export async function stackGate({ root, changed, tenantTables, run = psql }) {
|
|
75
|
+
const id = "G-STACK"
|
|
76
|
+
const files = changed.filter((rel) => MIGRATION.test(rel) || rel === CONTRACT_SCHEMA).sort()
|
|
77
|
+
if (!files.length) return { id, status: "pass", note: "no migration in this work" }
|
|
78
|
+
const { db } = readStack(root)
|
|
79
|
+
if (!db) return { id, status: "not_checked", optional: true, reason: "no local database is confirmed for this project (kriya stack use --db postgresql://…@127.0.0.1:<port>/<db>)" }
|
|
80
|
+
if (!isLocalDatabase(db)) return { id, status: "not_checked", reason: "the confirmed database isn't on this computer; confirm a local one" }
|
|
81
|
+
const hosted = hostedDatabase(root)
|
|
82
|
+
if (hosted) return { id, status: "not_checked", reason: `${hosted.variable} in ${hosted.file} points off this computer, so no migration is run from this project` }
|
|
83
|
+
const version = await run(["--version"])
|
|
84
|
+
if (version.missing) return { id, status: "not_checked", reason: "psql isn't installed" }
|
|
85
|
+
const texts = files.map((rel) => [rel, readFileSync(join(root, rel), "utf8")])
|
|
86
|
+
// A file that ends or starts transactions itself, or runs psql meta-commands (\\connect, \\i …),
|
|
87
|
+
// could commit inside ours and keep changes in the person's database: it isn't run
|
|
88
|
+
const own = texts.find(([, text]) => ownsTransaction(text))
|
|
89
|
+
if (own) return { id, status: "not_checked", reason: `${own[0]} manages its own transaction or uses psql commands, so it isn't applied here (nothing may be kept in your database)` }
|
|
90
|
+
const tables = [...new Set(texts.flatMap(([, text]) => createdTables(text)))]
|
|
91
|
+
const dir = mkdtempSync(join(tmpdir(), "kriya-stack-"))
|
|
92
|
+
try {
|
|
93
|
+
const script = join(dir, "gate.sql")
|
|
94
|
+
writeFileSync(script, stackScript(files.map((rel) => join(root, rel)), tables), { mode: 0o600 })
|
|
95
|
+
const out = await run([db, "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", script])
|
|
96
|
+
if (out.code !== 0) {
|
|
97
|
+
const error = (out.stderr || out.stdout).replace(/postgres(ql)?:\/\/[^\s]+/g, "<database>").trim().slice(-1500)
|
|
98
|
+
if (NO_TRANSACTION.test(error)) return { id, status: "not_checked", reason: "a migration can't run inside a transaction (e.g. CREATE INDEX CONCURRENTLY), so it isn't tried here" }
|
|
99
|
+
if (/could not connect|connection refused|timeout expired|no such file or directory/i.test(error)) return { id, status: "not_checked", reason: "the local database doesn't answer; start it, or confirm another with kriya stack use --db" }
|
|
100
|
+
return { id, status: "fail", kind: "gate", excerpt: `G-STACK: the migrations don't apply to the local database (rolled back, nothing kept):\n${error}` }
|
|
101
|
+
}
|
|
102
|
+
const between = /KRIYA-RLS-BEGIN\n([\s\S]*?)KRIYA-RLS-END/.exec(out.stdout)?.[1] ?? ""
|
|
103
|
+
const rows = between.split("\n").filter(Boolean).map((l) => l.split("|"))
|
|
104
|
+
const missing = rows.filter(([name, rls, policies]) => tenantTables(name) && (rls !== "true" || Number(policies) === 0)).map(([name, rls, policies]) => `${name}: ${rls !== "true" ? "row-level security is off" : "no policy"}${rls === "true" && Number(policies) === 0 ? " (every query is refused)" : ""}`)
|
|
105
|
+
if (missing.length) return { id, status: "fail", kind: "gate", excerpt: `G-STACK: tenant tables without row-level security and a policy (checked on the local database, rolled back):\n${missing.map((m) => `- ${m}`).join("\n")}` }
|
|
106
|
+
return { id, status: "pass", note: `${files.length} migration file(s) applied and rolled back; ${rows.length} table(s) checked` }
|
|
107
|
+
} finally {
|
|
108
|
+
rmSync(dir, { recursive: true, force: true })
|
|
109
|
+
}
|
|
110
|
+
}
|