@kriya-ai/harness 0.2.4 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +49 -0
- package/contract/SOURCE.md +3 -3
- package/contract/contract.json +504 -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 +376 -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 +426 -0
- package/plugins/runstrip/index.js +301 -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 +82 -5
- package/src/edit/core/layout.js +46 -1
- package/src/edit/core/ops.js +175 -3
- package/src/edit/core/plan.js +95 -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/transitions.js +17 -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 +137 -0
- package/src/edit/director/custom-motion.js +88 -0
- package/src/edit/director/graphics.js +186 -0
- package/src/edit/director/intent.js +125 -0
- package/src/edit/director/mentions.js +52 -0
- package/src/edit/director/plan.js +89 -12
- package/src/edit/director/revise.js +172 -7
- 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 +439 -0
- package/src/edit/engine/index.js +14 -5
- package/src/edit/engine/motion.js +153 -14
- 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 +76 -8
- package/src/edit/gates/picture.js +6 -3
- package/src/edit/gates/reference.js +115 -0
- package/src/edit/gates/tile.js +96 -0
- package/src/edit/host/client.js +4 -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 +17 -7
- package/src/edit/host/paths.js +34 -3
- package/src/edit/host/preview.js +108 -0
- package/src/edit/host/projects.js +494 -29
- package/src/edit/host/server.js +263 -19
- package/src/edit/host/tavi.js +77 -0
- package/src/edit/loop/make.js +44 -3
- package/src/edit/recipes/assembly.js +352 -0
- package/src/edit/recipes/graphic-clips.js +59 -0
- package/src/edit/recipes/openings.js +36 -0
- package/src/edit/recipes/reel.js +138 -17
- 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 -3
- 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 +407 -0
- package/src/gates/ui.js +111 -0
- package/src/launch.js +15 -3
- package/src/loop.js +199 -7
- package/src/mcp.js +126 -0
- package/src/milestones.js +188 -0
- package/src/modes.js +32 -0
- package/src/orchestra.js +43 -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 +452 -3
- package/studio/dist/studio.js +3 -3
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
|
|
4
|
+
import { Ajv2020 } from "ajv/dist/2020.js"
|
|
5
|
+
|
|
6
|
+
import { CONTRACTS_DIR } from "../contracts.js"
|
|
7
|
+
import { readStack } from "../stack.js"
|
|
8
|
+
import { Budget, fill, local } from "./http.js"
|
|
9
|
+
|
|
10
|
+
// Harness 2.0 W5: G-TENANT (Kriya-Tavi docs/kriya-harness/upgrade_2.0/GATES.md
|
|
11
|
+
// §3). For every tenant-scoped resource of .kriya/contracts/auth_matrix.json:
|
|
12
|
+
// two local test identities A and B, proved different first; B creates an
|
|
13
|
+
// object (control), B reads it (control), then A tries to read, change,
|
|
14
|
+
// delete and list it, as the matrix allows, and each must be refused
|
|
15
|
+
// (403/404) with B's object unchanged. A server that refuses everything fails
|
|
16
|
+
// its controls, so it can't pass. How to sign in and call each resource is in
|
|
17
|
+
// .kriya/gates/tenants.json (written by the security step; test identities of
|
|
18
|
+
// the local app only). Credentials and tokens never appear in an excerpt.
|
|
19
|
+
|
|
20
|
+
export const TENANTS_FILE = join(".kriya", "gates", "tenants.json")
|
|
21
|
+
|
|
22
|
+
const call = { type: "object", required: ["path"], additionalProperties: false, properties: { path: { type: "string", pattern: "^/\\S{0,300}$" }, method: { enum: ["GET", "POST", "PUT", "PATCH", "DELETE"] }, body: {}, idField: { type: "string", maxLength: 80 } } }
|
|
23
|
+
const SCHEMA = {
|
|
24
|
+
type: "object",
|
|
25
|
+
required: ["signIn", "tenants", "token", "whoami", "resources"],
|
|
26
|
+
additionalProperties: false,
|
|
27
|
+
properties: {
|
|
28
|
+
signIn: call,
|
|
29
|
+
tenants: { type: "object", required: ["A", "B"], additionalProperties: false, properties: { A: { type: "object", properties: { body: {} } }, B: { type: "object", properties: { body: {} } } } },
|
|
30
|
+
token: {
|
|
31
|
+
oneOf: [
|
|
32
|
+
{ type: "object", required: ["from", "field"], additionalProperties: false, properties: { from: { const: "json" }, field: { type: "string", maxLength: 80 } } },
|
|
33
|
+
{ type: "object", required: ["from", "name"], additionalProperties: false, properties: { from: { const: "cookie" }, name: { type: "string", pattern: "^[\\w.-]{1,80}$" } } },
|
|
34
|
+
],
|
|
35
|
+
},
|
|
36
|
+
whoami: { type: "object", required: ["path"], additionalProperties: false, properties: { path: { type: "string", pattern: "^/\\S{0,300}$" }, field: { type: "string", maxLength: 80 } } },
|
|
37
|
+
resources: { type: "object", maxProperties: 50, additionalProperties: { type: "object", additionalProperties: false, properties: { create: call, read: call, update: call, delete: call, list: call } } },
|
|
38
|
+
},
|
|
39
|
+
}
|
|
40
|
+
const validate = new Ajv2020({ strict: false, allErrors: true }).compile(SCHEMA)
|
|
41
|
+
|
|
42
|
+
/** The project's tenants.json, checked: { config } or { problem } */
|
|
43
|
+
export function tenantConfig(root) {
|
|
44
|
+
const file = join(root, TENANTS_FILE)
|
|
45
|
+
if (!existsSync(file)) return { problem: `${TENANTS_FILE} is missing: the security step writes how two local test identities sign in and how each tenant-scoped resource is called` }
|
|
46
|
+
let value
|
|
47
|
+
try {
|
|
48
|
+
value = JSON.parse(readFileSync(file, "utf8"))
|
|
49
|
+
} catch {
|
|
50
|
+
return { problem: `${TENANTS_FILE} isn't valid JSON` }
|
|
51
|
+
}
|
|
52
|
+
if (!validate(value)) return { problem: `${TENANTS_FILE}: ${validate.errors.slice(0, 3).map((e) => `${e.instancePath || "/"} ${e.message}`).join("; ")}` }
|
|
53
|
+
return { config: value }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** "data.user.id" → the value in a JSON body */
|
|
57
|
+
export const pick = (value, field = "id") => String(field).split(".").reduce((v, k) => (v === null || v === undefined ? undefined : v[k]), value)
|
|
58
|
+
|
|
59
|
+
/** Signs one test identity in; its request headers (never shown) */
|
|
60
|
+
export async function signIn(app, config, who, budget, request) {
|
|
61
|
+
const res = await local(app, config.signIn.path, { method: config.signIn.method ?? "POST", body: config.tenants[who].body, budget, request })
|
|
62
|
+
if (res.status < 200 || res.status >= 300) throw new Error(`signing in as ${who} answered ${res.status || res.error}`)
|
|
63
|
+
if (config.token.from === "json") {
|
|
64
|
+
const token = pick(res.json, config.token.field)
|
|
65
|
+
if (typeof token !== "string" || !token) throw new Error(`signing in as ${who} returned no token at "${config.token.field}"`)
|
|
66
|
+
return { headers: { authorization: `Bearer ${token}` } }
|
|
67
|
+
}
|
|
68
|
+
const cookie = (res.headers?.getSetCookie?.() ?? []).map((c) => c.split(";")[0]).find((c) => c.startsWith(`${config.token.name}=`))
|
|
69
|
+
if (!cookie) throw new Error(`signing in as ${who} set no "${config.token.name}" cookie`)
|
|
70
|
+
return { headers: { cookie } }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** True when any object in a JSON value has `field` equal to `id` */
|
|
74
|
+
const holds = (value, field, id) => {
|
|
75
|
+
if (Array.isArray(value)) return value.some((v) => holds(v, field, id))
|
|
76
|
+
if (value && typeof value === "object") return String(pick(value, field)) === String(id) || Object.values(value).some((v) => holds(v, field, id))
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
const refused = (s) => s === 403 || s === 404
|
|
80
|
+
|
|
81
|
+
/** Tenant-scoped resources and the actions the matrix allows on each */
|
|
82
|
+
export function scopedResources(root) {
|
|
83
|
+
const file = join(root, CONTRACTS_DIR, "auth_matrix.json")
|
|
84
|
+
if (!existsSync(file)) return new Map()
|
|
85
|
+
let rows = []
|
|
86
|
+
try {
|
|
87
|
+
rows = JSON.parse(readFileSync(file, "utf8"))
|
|
88
|
+
} catch {
|
|
89
|
+
return new Map()
|
|
90
|
+
}
|
|
91
|
+
const out = new Map()
|
|
92
|
+
for (const r of Array.isArray(rows) ? rows : []) if (r?.tenantScoped) out.set(r.resource, new Set([...(out.get(r.resource) ?? []), r.action]))
|
|
93
|
+
return out
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** @param {{ root: string, request?: typeof fetch }} input */
|
|
97
|
+
export async function tenantGate({ root, request }) {
|
|
98
|
+
const id = "G-TENANT"
|
|
99
|
+
const scoped = scopedResources(root)
|
|
100
|
+
if (!scoped.size) return { id, status: "pass", note: "nothing in the auth matrix is tenant-scoped" }
|
|
101
|
+
const { app } = readStack(root)
|
|
102
|
+
if (!app) return { id, status: "not_checked", optional: true, reason: "no app is confirmed for this project (kriya stack use --app http://localhost:<port>)" }
|
|
103
|
+
const { config, problem } = tenantConfig(root)
|
|
104
|
+
if (problem) return { id, status: "not_checked", reason: problem }
|
|
105
|
+
const budget = new Budget()
|
|
106
|
+
const leaks = []
|
|
107
|
+
const broken = []
|
|
108
|
+
try {
|
|
109
|
+
const A = await signIn(app, config, "A", budget, request)
|
|
110
|
+
const B = await signIn(app, config, "B", budget, request)
|
|
111
|
+
const [whoA, whoB] = [await local(app, config.whoami.path, { headers: A.headers, budget, request }), await local(app, config.whoami.path, { headers: B.headers, budget, request })]
|
|
112
|
+
const [idA, idB] = [pick(whoA.json, config.whoami.field), pick(whoB.json, config.whoami.field)]
|
|
113
|
+
if (whoA.status !== 200 || whoB.status !== 200 || idA === undefined || idB === undefined) return { id, status: "fail", kind: "gate", excerpt: `G-TENANT: ${config.whoami.path} must answer 200 with "${config.whoami.field ?? "id"}" for both test identities (answered ${whoA.status}, ${whoB.status})` }
|
|
114
|
+
if (String(idA) === String(idB)) return { id, status: "fail", kind: "gate", excerpt: "G-TENANT: test identities A and B are the same user, so isolation can't be proved; give them different accounts in tenants.json" }
|
|
115
|
+
for (const [name, actions] of scoped) {
|
|
116
|
+
const r = config.resources[name]
|
|
117
|
+
if (!r?.create) {
|
|
118
|
+
broken.push(`${name}: tenants.json has no "create" call for it, so there's no object of B's to probe`)
|
|
119
|
+
continue
|
|
120
|
+
}
|
|
121
|
+
const made = await local(app, r.create.path, { method: r.create.method ?? "POST", body: r.create.body, headers: B.headers, budget, request })
|
|
122
|
+
const objectId = pick(made.json, r.create.idField ?? "id")
|
|
123
|
+
if (made.status < 200 || made.status >= 300 || objectId === undefined) {
|
|
124
|
+
broken.push(`${name}: control failed: B couldn't create one (${made.status || made.error})`)
|
|
125
|
+
continue
|
|
126
|
+
}
|
|
127
|
+
const path = (c) => fill(c.path, { id: objectId })
|
|
128
|
+
const ownRead = r.read && (await local(app, path(r.read), { headers: B.headers, budget, request }))
|
|
129
|
+
if (r.read && ownRead.status !== 200) {
|
|
130
|
+
broken.push(`${name}: control failed: B couldn't read its own #${objectId} (${ownRead.status || ownRead.error})`)
|
|
131
|
+
continue
|
|
132
|
+
}
|
|
133
|
+
const still = async () => r.read && (await local(app, path(r.read), { headers: B.headers, budget, request }))
|
|
134
|
+
if (actions.has("read") && r.read) {
|
|
135
|
+
const probe = await local(app, path(r.read), { headers: A.headers, budget, request })
|
|
136
|
+
if (!refused(probe.status)) leaks.push(`${name}: tenant A read B's #${objectId} (expected 403/404, got ${probe.status})`)
|
|
137
|
+
}
|
|
138
|
+
if (actions.has("update") && r.update) {
|
|
139
|
+
const probe = await local(app, path(r.update), { method: r.update.method ?? "PATCH", body: r.update.body, headers: A.headers, budget, request })
|
|
140
|
+
if (!refused(probe.status)) leaks.push(`${name}: tenant A changed B's #${objectId} (expected 403/404, got ${probe.status})`)
|
|
141
|
+
const after = await still()
|
|
142
|
+
if (after && after.text !== ownRead.text) leaks.push(`${name}: B's #${objectId} is different after A's refused update`)
|
|
143
|
+
}
|
|
144
|
+
if (actions.has("delete") && r.delete) {
|
|
145
|
+
const probe = await local(app, path(r.delete), { method: "DELETE", headers: A.headers, budget, request })
|
|
146
|
+
if (!refused(probe.status)) leaks.push(`${name}: tenant A deleted B's #${objectId} (expected 403/404, got ${probe.status})`)
|
|
147
|
+
const after = await still()
|
|
148
|
+
if (after && after.status !== 200) leaks.push(`${name}: B's #${objectId} is gone after A's delete`)
|
|
149
|
+
}
|
|
150
|
+
if (actions.has("list") && r.list) {
|
|
151
|
+
const probe = await local(app, r.list.path, { headers: A.headers, budget, request })
|
|
152
|
+
if (probe.status === 200 && holds(probe.json, r.create.idField ?? "id", objectId)) leaks.push(`${name}: tenant A's list includes B's #${objectId}`)
|
|
153
|
+
}
|
|
154
|
+
for (const action of actions) if (!r[action] && action !== "create") broken.push(`${name}: the matrix allows "${action}" but tenants.json has no call for it to probe`)
|
|
155
|
+
}
|
|
156
|
+
} catch (error) {
|
|
157
|
+
return { id, status: "fail", kind: "gate", excerpt: `G-TENANT: ${String(error?.message ?? error).slice(0, 300)}` }
|
|
158
|
+
}
|
|
159
|
+
if (leaks.length || broken.length)
|
|
160
|
+
return { id, status: "fail", kind: "gate", excerpt: `G-TENANT (against ${app}):\n${[...leaks, ...broken].slice(0, 15).map((p) => `- ${p}`).join("\n")}${leaks.length ? "\nEnforce ownership from the verified session in the service and with row-level security, not from ids the client sends." : ""}` }
|
|
161
|
+
return { id, status: "pass", note: `${scoped.size} tenant-scoped resource(s) probed with paired controls` }
|
|
162
|
+
}
|