@palettelab/cli 0.3.70 → 0.3.72
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/README.md +117 -0
- package/backend-sdk/palette_sdk/__init__.py +3 -2
- package/backend-sdk/palette_sdk/jobs.py +18 -0
- package/backend-sdk/pyproject.toml +1 -1
- package/lib/acp.js +267 -0
- package/lib/agent-client.js +167 -0
- package/lib/bundler.js +32 -1
- package/lib/cli.js +8 -1
- package/lib/commands/agent.js +662 -0
- package/lib/commands/build.js +27 -12
- package/lib/commands/check.js +106 -0
- package/lib/css-scope.js +90 -18
- package/lib/migration_lint.py +128 -0
- package/package.json +1 -1
- package/template-fallback/package.json +1 -1
- package/template-fallback/templates/consumer-app/package.json +1 -1
- package/template-fallback/templates/dashboard/package.json +1 -1
- package/template-fallback/templates/database/package.json +1 -1
- package/template-fallback/templates/external-service/package.json +1 -1
- package/template-fallback/templates/frontend-only/package.json +1 -1
- package/template-fallback/templates/next/package.json +1 -1
- package/template-fallback/templates/palette-app/package.json +1 -1
- package/template-fallback/templates/provider-app/package.json +1 -1
package/lib/commands/build.js
CHANGED
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
const fs = require("fs")
|
|
4
4
|
const path = require("path")
|
|
5
|
+
const { spawnSync } = require("child_process")
|
|
5
6
|
const { loadManifest, validateManifest } = require("../manifest")
|
|
6
7
|
|
|
7
|
-
//
|
|
8
|
-
//
|
|
8
|
+
// What a migration may not run is decided by the platform's own lint, lib/migration_lint.py (a byte-identical
|
|
9
|
+
// copy of the server's), run with python3 so `pltt check` and publish agree — GRANT counts only as a SQL
|
|
10
|
+
// statement, never as a word. Without a usable python3 these word patterns stand in: stricter, never laxer.
|
|
11
|
+
const LINT_PY = path.join(__dirname, "..", "migration_lint.py")
|
|
9
12
|
const BANNED_PATTERNS = [
|
|
10
13
|
{ re: /DROP\s+POLICY/i, reason: "DROP POLICY weakens RLS" },
|
|
11
14
|
{ re: /DISABLE\s+ROW\s+LEVEL\s+SECURITY/i, reason: "DISABLE ROW LEVEL SECURITY removes tenant isolation" },
|
|
@@ -59,17 +62,31 @@ function crossPluginSchemaRefs(src, allowedSchema) {
|
|
|
59
62
|
return [...refs].sort()
|
|
60
63
|
}
|
|
61
64
|
|
|
62
|
-
|
|
65
|
+
// { absPath: [[line, reason], ...] } from the platform lint, or null when python3 cannot run it.
|
|
66
|
+
function bannedOperations(files) {
|
|
67
|
+
if (!files.length) return {}
|
|
68
|
+
const res = spawnSync(process.env.PALETTE_PYTHON || "python3", ["-I", LINT_PY, ...files], { encoding: "utf8" })
|
|
69
|
+
try {
|
|
70
|
+
return res.status === 0 ? JSON.parse(res.stdout) : null
|
|
71
|
+
} catch {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function lintMigrationFile(absPath, pluginId, sharedTables = [], banned = bannedOperations([absPath])) {
|
|
63
77
|
const issues = []
|
|
64
78
|
const src = fs.readFileSync(absPath, "utf8")
|
|
65
79
|
const requiredPrefix = pluginId ? pluginTablePrefix(pluginId) : null
|
|
66
80
|
const allowedSchema = pluginId ? pluginSchema(pluginId) : null
|
|
67
81
|
const sharedTableNames = new Set(sharedTables || [])
|
|
68
82
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
83
|
+
const hits = banned?.[absPath] || BANNED_PATTERNS.flatMap(({ re, reason }) => {
|
|
84
|
+
const match = re.exec(src)
|
|
85
|
+
return match ? [[src.slice(0, match.index).split("\n").length, reason]] : []
|
|
86
|
+
})
|
|
87
|
+
for (const [line, reason] of hits) {
|
|
88
|
+
const file = path.basename(absPath)
|
|
89
|
+
issues.push(makeIssue(`${file} line ${line}: ${reason}`, null, { code: "banned_operation", file, line }))
|
|
73
90
|
}
|
|
74
91
|
|
|
75
92
|
for (const schema of crossPluginSchemaRefs(src, allowedSchema)) {
|
|
@@ -138,11 +155,9 @@ function lintMigrationsDir(migrationsDir, pluginId, sharedTables = []) {
|
|
|
138
155
|
errors.push(`migrations directory has no versions/ subfolder: ${migrationsDir}`)
|
|
139
156
|
return errors
|
|
140
157
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
errors.push(...lintMigrationFile(abs, pluginId, sharedTables))
|
|
145
|
-
}
|
|
158
|
+
const files = fs.readdirSync(versionsDir).filter((entry) => entry.endsWith(".py")).map((entry) => path.join(versionsDir, entry))
|
|
159
|
+
const banned = bannedOperations(files)
|
|
160
|
+
for (const abs of files) errors.push(...lintMigrationFile(abs, pluginId, sharedTables, banned))
|
|
146
161
|
return errors
|
|
147
162
|
}
|
|
148
163
|
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
// `pltt check`: the contract gate of `pltt test` as structured diagnostics — one entry per problem, with a stable id,
|
|
4
|
+
// severity, file, line and column where the check knows them — for coding agents and editors. It runs `pltt test
|
|
5
|
+
// --json` (the same child `pltt publish` runs as its preflight) and splits what that report holds as text: each
|
|
6
|
+
// esbuild error ("file:line:col: ERROR: text") becomes its own diagnostic, a Python traceback's innermost project
|
|
7
|
+
// frame gives the file and line of an import failure, and migration-lint and forbidden-import entries keep the file
|
|
8
|
+
// they name. `--files a b` keeps the diagnostics about those files (and the project-wide ones).
|
|
9
|
+
|
|
10
|
+
const path = require("path")
|
|
11
|
+
const { spawnSync } = require("child_process")
|
|
12
|
+
|
|
13
|
+
const USAGE = "usage: pltt check [--json] [--publish-type preview|release] [--files <path> ...]"
|
|
14
|
+
|
|
15
|
+
const IDS = [
|
|
16
|
+
[/^could not (create Python|install pyproject)/i, "toolchain.python"],
|
|
17
|
+
[/^manifest invalid/i, "manifest.invalid"],
|
|
18
|
+
[/^frontend bundle failed/i, "bundle.syntax"],
|
|
19
|
+
[/^backend import failed/i, "py.import"],
|
|
20
|
+
[/^forbidden platform import/i, "import.forbidden"],
|
|
21
|
+
[/has no require_permission/i, "route.ungated"],
|
|
22
|
+
[/^route uses undeclared permission/i, "permission.undeclared"],
|
|
23
|
+
[/^unknown permission/i, "permission.unknown"],
|
|
24
|
+
[/unused backend permissions/i, "permission.unused"],
|
|
25
|
+
[/capabilit|agent-exposable/i, "capability.parity"],
|
|
26
|
+
[/migration/i, "migration.lint"],
|
|
27
|
+
[/contains local secret/i, "secret.leak"],
|
|
28
|
+
[/secret .* (is missing|has no local value)|no local \.env/i, "secret.missing"],
|
|
29
|
+
[/lifecycle script|unsafe spec|broad spec|^pyproject dependency|package\.json/i, "deps.policy"],
|
|
30
|
+
[/SDK compatibility|platform compatibility/i, "compat.sdk"],
|
|
31
|
+
[/bundle exceeds size limit/i, "bundle.size"],
|
|
32
|
+
[/must be sandboxed|public route must start|backend entry not found/i, "manifest.invalid"],
|
|
33
|
+
[/is not newer than last release|semver bump/i, "version.bump"],
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
function idFor(result) {
|
|
37
|
+
if (result.code) return `migration.${result.code}`
|
|
38
|
+
const message = String(result.message || "")
|
|
39
|
+
const match = IDS.find(([pattern]) => pattern.test(message))
|
|
40
|
+
return match ? match[1] : "contract.check"
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const ESBUILD = /([\w./@-]+\.(?:tsx|ts|jsx|js|css)):(\d+):(\d+): (?:ERROR|error): ([^\n]+)/g
|
|
44
|
+
const PY_FRAME = /File "([^"]+)", line (\d+)/g
|
|
45
|
+
|
|
46
|
+
function diagnosticsFor(result, cwd) {
|
|
47
|
+
const severity = result.status === "fail" ? "error" : result.status === "warn" ? "warning" : null
|
|
48
|
+
if (!severity) return []
|
|
49
|
+
const base = { id: idFor(result), severity, message: String(result.message || ""), ...(result.fix ? { fix: result.fix } : {}) }
|
|
50
|
+
const text = `${result.message || ""}\n${result.details || ""}`
|
|
51
|
+
const bundle = [...text.matchAll(ESBUILD)]
|
|
52
|
+
if (bundle.length) {
|
|
53
|
+
return bundle.map((m) => ({ ...base, file: m[1], line: Number(m[2]), column: Number(m[3]), message: m[4].trim() }))
|
|
54
|
+
}
|
|
55
|
+
if (base.id === "py.import" && result.stderr) {
|
|
56
|
+
const frames = [...String(result.stderr).matchAll(PY_FRAME)]
|
|
57
|
+
.map((m) => ({ file: path.relative(cwd, m[1]), line: Number(m[2]) }))
|
|
58
|
+
.filter((f) => !f.file.startsWith("..") && !f.file.includes("site-packages") && !path.isAbsolute(f.file))
|
|
59
|
+
const inner = frames[frames.length - 1]
|
|
60
|
+
const last = String(result.stderr).trim().split("\n").pop()
|
|
61
|
+
return [{ ...base, ...(inner || {}), message: last ? `${base.message}: ${last}` : base.message }]
|
|
62
|
+
}
|
|
63
|
+
if (result.file) {
|
|
64
|
+
const file = String(result.file).includes("/") || !result.code ? String(result.file) : `backend/migrations/versions/${result.file}`
|
|
65
|
+
return [{ ...base, file, ...(result.line ? { line: Number(result.line) } : {}) }]
|
|
66
|
+
}
|
|
67
|
+
return [base]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function runTest(cwd, publishType) {
|
|
71
|
+
const cliBin = path.resolve(__dirname, "..", "..", "bin", "pltt.js")
|
|
72
|
+
const res = spawnSync(process.execPath, [cliBin, "test", "--json", "--publish-type", publishType], { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 })
|
|
73
|
+
const out = res.stdout || ""
|
|
74
|
+
const start = out.indexOf("{")
|
|
75
|
+
if (start < 0) {
|
|
76
|
+
return { ok: false, results: [{ status: "fail", message: (res.stderr || out || "pltt test produced no report").trim().split("\n")[0] }] }
|
|
77
|
+
}
|
|
78
|
+
return JSON.parse(out.slice(start, out.lastIndexOf("}") + 1))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function run(argv, { cwd = process.cwd(), log = console.log, test = runTest } = {}) {
|
|
82
|
+
const json = argv.includes("--json")
|
|
83
|
+
const typeAt = argv.indexOf("--publish-type")
|
|
84
|
+
const publishType = typeAt >= 0 ? argv[typeAt + 1] : "preview"
|
|
85
|
+
if (!["preview", "release"].includes(publishType)) throw new Error(USAGE)
|
|
86
|
+
const filesAt = argv.indexOf("--files")
|
|
87
|
+
const files = filesAt >= 0 ? argv.slice(filesAt + 1).filter((a) => !a.startsWith("--")) : null
|
|
88
|
+
const report = test(cwd, publishType)
|
|
89
|
+
let diagnostics = (report.results || []).flatMap((result) => diagnosticsFor(result, cwd))
|
|
90
|
+
if (files && files.length) diagnostics = diagnostics.filter((d) => !d.file || files.includes(d.file))
|
|
91
|
+
const errors = diagnostics.filter((d) => d.severity === "error").length
|
|
92
|
+
const summary = { errors, warnings: diagnostics.length - errors }
|
|
93
|
+
if (json) {
|
|
94
|
+
log(JSON.stringify({ ok: errors === 0, diagnostics, summary }, null, 2))
|
|
95
|
+
} else {
|
|
96
|
+
for (const d of diagnostics) {
|
|
97
|
+
const where = d.file ? `${d.file}${d.line ? `:${d.line}${d.column ? `:${d.column}` : ""}` : ""}: ` : ""
|
|
98
|
+
log(`${where}${d.severity} ${d.id}: ${d.message}${d.fix ? `\n fix: ${d.fix}` : ""}`)
|
|
99
|
+
}
|
|
100
|
+
log(errors ? `[pltt] ${errors} error(s), ${summary.warnings} warning(s)` : `[pltt] check passed (${summary.warnings} warning(s))`)
|
|
101
|
+
}
|
|
102
|
+
if (errors) process.exitCode = 1
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
module.exports = run
|
|
106
|
+
module.exports.diagnosticsFor = diagnosticsFor
|
package/lib/css-scope.js
CHANGED
|
@@ -31,28 +31,80 @@ function isRootLike(node) {
|
|
|
31
31
|
)
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
// Selector lists that match when any branch matches (`:where(html)`, `:is(html, body)`).
|
|
35
|
+
const MATCHES_ANY = /^:(is|where|matches|-webkit-any|-moz-any)$/i
|
|
36
|
+
|
|
37
|
+
// Only this plugin's own root counts: a hand-written `[data-palette-plugin-root]` may be
|
|
38
|
+
// another app's root and keeps its prefix.
|
|
39
|
+
function isPluginRoot(node, root) {
|
|
40
|
+
return node.type === "attribute" && node.attribute === root.attribute && node.value === root.value
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isChildStep(node) {
|
|
44
|
+
return node?.type === "combinator" && (node.value === " " || node.value === ">")
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function splitCompounds(selector) {
|
|
48
|
+
const compounds = [[]]
|
|
49
|
+
const combinators = []
|
|
50
|
+
for (const node of selector.nodes) {
|
|
51
|
+
if (node.type === "combinator") {
|
|
52
|
+
combinators.push(node)
|
|
53
|
+
compounds.push([])
|
|
54
|
+
} else {
|
|
55
|
+
compounds[compounds.length - 1].push(node)
|
|
56
|
+
}
|
|
37
57
|
}
|
|
58
|
+
return { compounds, combinators }
|
|
38
59
|
}
|
|
39
60
|
|
|
40
|
-
function
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
61
|
+
function isRootCompound(nodes, root) {
|
|
62
|
+
return nodes.some(
|
|
63
|
+
(node) =>
|
|
64
|
+
isPluginRoot(node, root) ||
|
|
65
|
+
(node.type === "pseudo" &&
|
|
66
|
+
MATCHES_ANY.test(node.value) &&
|
|
67
|
+
node.nodes.length > 0 &&
|
|
68
|
+
node.nodes.every((branch) => isInsideRoot(branch, root))),
|
|
69
|
+
)
|
|
48
70
|
}
|
|
49
71
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
72
|
+
// True when the subject can only be the plugin root or a descendant of it: walking left
|
|
73
|
+
// over descendant/child steps reaches a root compound. A root that only appears inside
|
|
74
|
+
// `:not(body)` or before `~`/`+` confines nothing, so such selectors still get prefixed.
|
|
75
|
+
function isInsideRoot(selector, root) {
|
|
76
|
+
const { compounds, combinators } = splitCompounds(selector)
|
|
77
|
+
for (let i = compounds.length - 1; i >= 0; i--) {
|
|
78
|
+
if (isRootCompound(compounds[i], root)) return true
|
|
79
|
+
if (!isChildStep(combinators[i - 1])) return false
|
|
80
|
+
}
|
|
81
|
+
return false
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// html, body and :root all become the one plugin root element, so `html body` or
|
|
85
|
+
// `:root[data-theme=x] > body` must merge into a single compound: a plugin root nested
|
|
86
|
+
// inside itself never matches.
|
|
87
|
+
function collapseRootChains(selector, root) {
|
|
88
|
+
const { compounds, combinators } = splitCompounds(selector)
|
|
89
|
+
for (let i = combinators.length - 1; i >= 0; i--) {
|
|
90
|
+
if (!isChildStep(combinators[i]) || !isRootCompound(compounds[i], root) || !isRootCompound(compounds[i + 1], root)) continue
|
|
91
|
+
combinators[i].remove()
|
|
92
|
+
for (const node of compounds[i + 1]) if (isPluginRoot(node, root)) node.remove()
|
|
55
93
|
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function confineSelector(selector, rootNode) {
|
|
97
|
+
if (!selector.nodes.length) return
|
|
98
|
+
collapseRootChains(selector, rootNode)
|
|
99
|
+
if (isInsideRoot(selector, rootNode)) return
|
|
100
|
+
// `body, .x { .card {} }` flattens to `:is(body, .x) .card`: scope each branch, since
|
|
101
|
+
// one outer prefix would need the root inside itself for the `body` branch.
|
|
102
|
+
const lists = splitCompounds(selector).compounds[0].filter(
|
|
103
|
+
(node) =>
|
|
104
|
+
node.type === "pseudo" && MATCHES_ANY.test(node.value) && node.nodes.some((branch) => isInsideRoot(branch, rootNode)),
|
|
105
|
+
)
|
|
106
|
+
for (const list of lists) list.each((branch) => confineSelector(branch, rootNode))
|
|
107
|
+
if (lists.length && isInsideRoot(selector, rootNode)) return
|
|
56
108
|
selector.prepend(selectorParser.combinator({ value: " " }))
|
|
57
109
|
selector.prepend(rootNode.clone())
|
|
58
110
|
}
|
|
@@ -66,10 +118,30 @@ function scopeSelectors(selector, pluginId) {
|
|
|
66
118
|
})
|
|
67
119
|
|
|
68
120
|
return selectorParser((selectors) => {
|
|
69
|
-
selectors.
|
|
121
|
+
selectors.walk((node) => {
|
|
122
|
+
if (isRootLike(node)) node.replaceWith(rootNode.clone())
|
|
123
|
+
})
|
|
124
|
+
selectors.each((sel) => confineSelector(sel, rootNode))
|
|
70
125
|
}).processSync(selector)
|
|
71
126
|
}
|
|
72
127
|
|
|
128
|
+
// A nested rule is matched relative to its parent, so scoping every level would ask for
|
|
129
|
+
// a plugin root inside the plugin root (`[root] .a { [root] .b {} }` never matches).
|
|
130
|
+
// Flatten nesting first with esbuild, which already bundles this CSS.
|
|
131
|
+
function flattenNesting(css, root) {
|
|
132
|
+
let nested = false
|
|
133
|
+
root.walk((node) => {
|
|
134
|
+
if (node.parent?.type === "rule" && (node.type === "rule" || node.type === "atrule")) nested = true
|
|
135
|
+
})
|
|
136
|
+
if (!nested) return root
|
|
137
|
+
const flat = require("esbuild").transformSync(css, {
|
|
138
|
+
loader: "css",
|
|
139
|
+
minifyWhitespace: true,
|
|
140
|
+
supported: { nesting: false },
|
|
141
|
+
})
|
|
142
|
+
return postcss.parse(flat.code)
|
|
143
|
+
}
|
|
144
|
+
|
|
73
145
|
function renameKeyframes(root, pluginId) {
|
|
74
146
|
const prefix = `palette-${cssIdentifier(pluginId)}-`
|
|
75
147
|
const names = new Map()
|
|
@@ -97,7 +169,7 @@ function renameKeyframes(root, pluginId) {
|
|
|
97
169
|
|
|
98
170
|
function scopePluginCss(css, pluginId) {
|
|
99
171
|
if (!css || !String(css).trim()) return ""
|
|
100
|
-
const root = postcss.parse(css)
|
|
172
|
+
const root = flattenNesting(String(css), postcss.parse(css))
|
|
101
173
|
|
|
102
174
|
renameKeyframes(root, pluginId)
|
|
103
175
|
root.walkRules((rule) => {
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""What an app migration may not do.
|
|
2
|
+
|
|
3
|
+
One file, two copies kept byte-identical: the platform's
|
|
4
|
+
(backend/app/plugins/migration_lint.py — install-time lint, App Store review,
|
|
5
|
+
App Builder guard) and the CLI's (sdk/cli-npm/lib/migration_lint.py, run with
|
|
6
|
+
the developer's python3), so `pltt check` and publish agree. Standard library
|
|
7
|
+
only; run as a script it prints {path: [[line, reason], ...]} as JSON.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ast
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
GRANT_REASON = "GRANT is reserved for the platform"
|
|
18
|
+
|
|
19
|
+
BANNED_MIGRATION_PATTERNS = [
|
|
20
|
+
(re.compile(r"\bpublic\.", re.I), "plugin migrations must not reference public schema"),
|
|
21
|
+
(re.compile(r"\bDROP\s+POLICY\b", re.I), "DROP POLICY weakens RLS"),
|
|
22
|
+
(
|
|
23
|
+
re.compile(r"\bDISABLE\s+ROW\s+LEVEL\s+SECURITY\b", re.I),
|
|
24
|
+
"DISABLE ROW LEVEL SECURITY removes tenant isolation",
|
|
25
|
+
),
|
|
26
|
+
(
|
|
27
|
+
re.compile(r"\bNO\s+FORCE\s+ROW\s+LEVEL\s+SECURITY\b", re.I),
|
|
28
|
+
"NO FORCE ROW LEVEL SECURITY lets table owners bypass RLS",
|
|
29
|
+
),
|
|
30
|
+
(re.compile(r"\bSET\s+ROLE\b", re.I), "SET ROLE is reserved for the platform"),
|
|
31
|
+
(re.compile(r"\bALTER\s+ROLE\b", re.I), "ALTER ROLE is reserved for the platform"),
|
|
32
|
+
(re.compile(r"\bCREATE\s+EXTENSION\b", re.I), "CREATE EXTENSION is reserved for the platform"),
|
|
33
|
+
(re.compile(r"\bALTER\s+DATABASE\b", re.I), "ALTER DATABASE is not allowed"),
|
|
34
|
+
(re.compile(r"\bDROP\s+SCHEMA\b", re.I), "DROP SCHEMA is not allowed"),
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
# "grant" is everyday vocabulary — a leave grant, MONTHS_AFTER_GRANT, def
|
|
38
|
+
# grant(), "Grant of Copyright License" — so GRANT counts only as a SQL
|
|
39
|
+
# statement: in a Python string (docstrings skipped), after the string's SQL
|
|
40
|
+
# comments and quoted literals are blanked (RAISE messages, enum values; the
|
|
41
|
+
# dynamic SQL an EXECUTE runs stays code), at the start of a statement, and
|
|
42
|
+
# shaped like one: privileges ON objects TO roles, or roles TO roles, ending
|
|
43
|
+
# the statement.
|
|
44
|
+
_START = r"(?:^|;|\$\w*\$|\b(?:BEGIN|THEN|ELSE|LOOP|EXECUTE)\b(?:\s+format\s*\()?)\s*"
|
|
45
|
+
_ROLE = r'(?:"[^"]*"|[\w$%{}.]+)'
|
|
46
|
+
_ROLES = rf"{_ROLE}(?:\s*,\s*{_ROLE})*"
|
|
47
|
+
_PRIVILEGES = (
|
|
48
|
+
r"(?:ALL|SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|USAGE|CREATE|CONNECT"
|
|
49
|
+
r"|TEMP(?:ORARY)?|EXECUTE|SET|ALTER\s+SYSTEM|MAINTAIN)\b[^;]*?\bON\b[^;]*?"
|
|
50
|
+
)
|
|
51
|
+
GRANT_STATEMENT = re.compile(
|
|
52
|
+
rf"{_START}(GRANT\s+(?:{_PRIVILEGES}|{_ROLES})\s+TO\s+{_ROLES}"
|
|
53
|
+
rf"\s*(?:WITH\s+[\w\s,]+?)?(?:GRANTED\s+BY\s+{_ROLE}\s*)?(?:;|\)|$))"
|
|
54
|
+
r"|(\bALTER\s+DEFAULT\s+PRIVILEGES\b)",
|
|
55
|
+
re.I,
|
|
56
|
+
)
|
|
57
|
+
_DYNAMIC_SQL = re.compile(r"\bEXECUTE\b(?:'(?:[^']|'')*'|[^;'])*", re.I)
|
|
58
|
+
_SQL_PROSE = re.compile(r"--[^\n]*|/\*.*?\*/|'(?:[^']|'')*'", re.S)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _python_strings(tree: ast.AST):
|
|
62
|
+
"""(line, text) of each string expression, docstrings skipped; f-string and
|
|
63
|
+
`+` parts are joined, with x standing in for each expression."""
|
|
64
|
+
seen = {
|
|
65
|
+
id(node.body[0].value)
|
|
66
|
+
for node in ast.walk(tree)
|
|
67
|
+
if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))
|
|
68
|
+
and node.body
|
|
69
|
+
and isinstance(node.body[0], ast.Expr)
|
|
70
|
+
and isinstance(node.body[0].value, ast.Constant)
|
|
71
|
+
and isinstance(node.body[0].value.value, str)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
def text(node: ast.AST) -> str:
|
|
75
|
+
seen.add(id(node))
|
|
76
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
77
|
+
return node.value
|
|
78
|
+
if isinstance(node, ast.JoinedStr):
|
|
79
|
+
return "".join(text(part) for part in node.values)
|
|
80
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
|
81
|
+
return text(node.left) + text(node.right)
|
|
82
|
+
return " x "
|
|
83
|
+
|
|
84
|
+
for node in ast.walk(tree):
|
|
85
|
+
if id(node) not in seen and (
|
|
86
|
+
isinstance(node, ast.JoinedStr)
|
|
87
|
+
or (isinstance(node, ast.Constant) and isinstance(node.value, str))
|
|
88
|
+
or (isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add))
|
|
89
|
+
):
|
|
90
|
+
yield node.lineno, text(node)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _blank(match: re.Match) -> str:
|
|
94
|
+
return re.sub(r"[^\n]+", " ", match.group())
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _grant_line(source: str) -> int | None:
|
|
98
|
+
try:
|
|
99
|
+
strings = list(_python_strings(ast.parse(source)))
|
|
100
|
+
except (SyntaxError, ValueError): # unreadable as Python: every GRANT word counts
|
|
101
|
+
match = re.search(r"\bGRANT\b", source, re.I)
|
|
102
|
+
return source.count("\n", 0, match.start()) + 1 if match else None
|
|
103
|
+
for line, value in strings:
|
|
104
|
+
sql = _SQL_PROSE.sub(_blank, _DYNAMIC_SQL.sub(lambda m: m.group().replace("'", " "), value))
|
|
105
|
+
if match := GRANT_STATEMENT.search(sql):
|
|
106
|
+
# An escaped "\n" in a one-line string is a newline here, not in the file.
|
|
107
|
+
return min(line + sql.count("\n", 0, match.start(match.lastindex)), source.count("\n") + 1)
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def migration_lint_hits(source: str) -> list[tuple[int, str]]:
|
|
112
|
+
"""(line, reason) for each operation one migration file must not run."""
|
|
113
|
+
hits = [
|
|
114
|
+
(source.count("\n", 0, match.start()) + 1, reason)
|
|
115
|
+
for pattern, reason in BANNED_MIGRATION_PATTERNS
|
|
116
|
+
if (match := pattern.search(source))
|
|
117
|
+
]
|
|
118
|
+
if (line := _grant_line(source)) is not None:
|
|
119
|
+
hits.append((line, GRANT_REASON))
|
|
120
|
+
return sorted(hits)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__ == "__main__":
|
|
124
|
+
report = {}
|
|
125
|
+
for path in sys.argv[1:]:
|
|
126
|
+
with open(path, encoding="utf-8", errors="ignore") as handle:
|
|
127
|
+
report[path] = migration_lint_hits(handle.read())
|
|
128
|
+
print(json.dumps(report))
|
package/package.json
CHANGED