@fabrika/check 0.0.0-stage → 0.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/package.json +48 -5
- package/src/ast.ts +268 -0
- package/src/bun-plugin.ts +63 -0
- package/src/check.ts +183 -0
- package/src/cli.ts +88 -0
- package/src/contract.ts +254 -0
- package/src/endpoint-fixtures.ts +221 -0
- package/src/finding.ts +88 -0
- package/src/graph.ts +206 -0
- package/src/index.ts +15 -0
- package/src/inputs.ts +88 -0
- package/src/jsonc.ts +63 -0
- package/src/layout.ts +115 -0
- package/src/limits.ts +15 -0
- package/src/packed.ts +66 -0
- package/src/reader/problems.ts +11 -0
- package/src/reader/schema.ts +551 -0
- package/src/reader/surface.ts +1087 -0
- package/src/reader/tables.ts +116 -0
- package/src/reader/value.ts +644 -0
- package/src/references.ts +95 -0
- package/src/resolution.ts +178 -0
- package/src/rules/contract.ts +78 -0
- package/src/rules/crontab.ts +147 -0
- package/src/rules/framework.ts +177 -0
- package/src/rules/identity.ts +80 -0
- package/src/rules/isolation.ts +79 -0
- package/src/rules/json.ts +28 -0
- package/src/rules/literal.ts +736 -0
- package/src/rules/migrations.ts +87 -0
- package/src/rules/modules.ts +226 -0
- package/src/rules/packages.ts +168 -0
- package/src/rules/runtime.ts +507 -0
- package/src/rules/structure.ts +299 -0
- package/src/rules/tests.ts +208 -0
- package/src/rules/types.ts +62 -0
- package/src/scaffold-sample.ts +108 -0
- package/src/scaffold.ts +605 -0
- package/src/scope.ts +108 -0
- package/src/slice.ts +339 -0
- package/src/toml.ts +159 -0
- package/src/trust.ts +189 -0
- package/src/version.ts +4 -0
- package/README.md +0 -3
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { fileTableScanReady } from '@fabrika/platform-node/sql'
|
|
2
|
+
import type { Finding } from '../finding'
|
|
3
|
+
import { MIGRATIONS_DIR } from '../layout'
|
|
4
|
+
|
|
5
|
+
const MIGRATION_NAME = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})_[a-z0-9]+(?:_[a-z0-9]+)*\.sql$/
|
|
6
|
+
const ALLOWED = 'db/migrations/YYYYMMDDHHMMSS_slug.sql with a lowercase snake_case slug, as fabrika db new <slug> writes it'
|
|
7
|
+
|
|
8
|
+
const isValidTimestamp = (parts: readonly string[]): boolean => {
|
|
9
|
+
const [year, month, day, hour, minute, second] = parts.map(Number)
|
|
10
|
+
if (year === undefined || month === undefined || day === undefined || hour === undefined || minute === undefined || second === undefined) {
|
|
11
|
+
return false
|
|
12
|
+
}
|
|
13
|
+
const date = new Date(Date.UTC(year, month - 1, day, hour, minute, second))
|
|
14
|
+
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day && hour < 24 && minute < 60 && second < 60
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Migration file names sort by creation time, so parallel worktrees never claim the same name. */
|
|
18
|
+
export const checkMigrationNames = (paths: readonly string[]): Finding[] => {
|
|
19
|
+
const findings: Finding[] = []
|
|
20
|
+
for (const path of paths) {
|
|
21
|
+
if (!path.startsWith(MIGRATIONS_DIR)) continue
|
|
22
|
+
const name = path.slice(MIGRATIONS_DIR.length)
|
|
23
|
+
const match = MIGRATION_NAME.exec(name)
|
|
24
|
+
if (match !== null && isValidTimestamp(match.slice(1, 7))) continue
|
|
25
|
+
const message = name.includes('/')
|
|
26
|
+
? `'${name}' is in a subdirectory of db/migrations`
|
|
27
|
+
: match === null
|
|
28
|
+
? `'${name}' is not a migration file name`
|
|
29
|
+
: `'${name}' does not start with a real UTC timestamp`
|
|
30
|
+
findings.push({ file: path, line: 1, column: 1, severity: 'refusal', rule: 'migration-name', message, allowed: ALLOWED })
|
|
31
|
+
}
|
|
32
|
+
return findings
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A `scan: true` collection whose table no migration lets hold the scan states — the earlier `fileTableSql` DDL, which
|
|
37
|
+
* admits only `pending` and `live`, without `fileScanSql` after it — would fail every upload at its `quarantined`
|
|
38
|
+
* row. Only the named check of every state with the scan columns, or the exact `fileScanSql` statement, counts
|
|
39
|
+
* (`fileTableScanReady`). A collection whose table no migration creates is not this rule's.
|
|
40
|
+
*/
|
|
41
|
+
export const checkScanMigrations = (
|
|
42
|
+
files: ReadonlyMap<string, string>,
|
|
43
|
+
scanning: readonly string[],
|
|
44
|
+
): Finding[] => {
|
|
45
|
+
const migrations = [...files.entries()]
|
|
46
|
+
.filter(
|
|
47
|
+
([path]) => path.startsWith(MIGRATIONS_DIR) && path.endsWith('.sql'),
|
|
48
|
+
)
|
|
49
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
50
|
+
const findings: Finding[] = []
|
|
51
|
+
for (const name of scanning) {
|
|
52
|
+
const table = `fabrika_files_${name}`
|
|
53
|
+
if (
|
|
54
|
+
fileTableScanReady(
|
|
55
|
+
migrations.map(([, sql]) => sql),
|
|
56
|
+
table,
|
|
57
|
+
) !== false
|
|
58
|
+
) {
|
|
59
|
+
continue
|
|
60
|
+
}
|
|
61
|
+
const creating = migrations.find(
|
|
62
|
+
([, sql]) => fileTableScanReady([sql], table) !== undefined,
|
|
63
|
+
)
|
|
64
|
+
const path = creating?.[0] ?? MIGRATIONS_DIR
|
|
65
|
+
const line = creating === undefined ? 1 : lineOf(creating[1], table)
|
|
66
|
+
findings.push({
|
|
67
|
+
file: path,
|
|
68
|
+
line,
|
|
69
|
+
column: 1,
|
|
70
|
+
severity: 'refusal',
|
|
71
|
+
rule: 'file-scan-migration',
|
|
72
|
+
message: `files '${name}' sets scan: true, and no migration lets ${table} hold a quarantined file`,
|
|
73
|
+
allowed:
|
|
74
|
+
`a new migration holding fileScanSql('${name}') of @fabrika/db, exactly as it writes it: ALTER TABLE ${table} DROP CONSTRAINT IF EXISTS …, ADD CONSTRAINT ${table}_status CHECK (…), ADD COLUMN object_version TEXT, …`,
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
return findings
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The line of the `CREATE TABLE` of `table` in `sql`. */
|
|
81
|
+
function lineOf(sql: string, table: string): number {
|
|
82
|
+
const match = new RegExp(
|
|
83
|
+
`create\\s+table\\s+(?:if\\s+not\\s+exists\\s+)?${table}\\b`,
|
|
84
|
+
'i',
|
|
85
|
+
).exec(sql)
|
|
86
|
+
return match === null ? 1 : sql.slice(0, match.index).split('\n').length
|
|
87
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import type { Report } from '../finding'
|
|
2
|
+
import { isIgnoredSegment, isRelativeSpecifier, isTestFile, joinRelative, resolveRelative } from '../layout'
|
|
3
|
+
import type { ModuleReference } from '../references'
|
|
4
|
+
import { type ImportMappings, mappedTargets } from '../resolution'
|
|
5
|
+
|
|
6
|
+
interface Forbidden {
|
|
7
|
+
readonly what: string
|
|
8
|
+
readonly allowed: string
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const DATABASE: Forbidden = { what: 'a database driver', allowed: 'the scoped data layer of @fabrika/db, reached through ctx' }
|
|
12
|
+
const STORAGE: Forbidden = { what: 'an S3 client', allowed: 'a file collection declared in the contract (c.files)' }
|
|
13
|
+
const TOKENS: Forbidden = { what: 'a token library', allowed: 'the principal the framework verified, on ctx' }
|
|
14
|
+
const NETWORK: Forbidden = {
|
|
15
|
+
what: 'a raw network module',
|
|
16
|
+
allowed: 'endpoints declared in the contract; another application through a connector import',
|
|
17
|
+
}
|
|
18
|
+
const PROCESSES: Forbidden = { what: 'a process-spawning module', allowed: 'a job declared in the contract (c.cron)' }
|
|
19
|
+
|
|
20
|
+
const FORBIDDEN_PACKAGES: ReadonlyMap<string, Forbidden> = new Map([
|
|
21
|
+
...[
|
|
22
|
+
'pg',
|
|
23
|
+
'pg-native',
|
|
24
|
+
'postgres',
|
|
25
|
+
'@neondatabase/serverless',
|
|
26
|
+
'@vercel/postgres',
|
|
27
|
+
'@electric-sql/pglite',
|
|
28
|
+
'mysql',
|
|
29
|
+
'mysql2',
|
|
30
|
+
'mariadb',
|
|
31
|
+
'sqlite',
|
|
32
|
+
'sqlite3',
|
|
33
|
+
'better-sqlite3',
|
|
34
|
+
'bun:sqlite',
|
|
35
|
+
'@libsql/client',
|
|
36
|
+
'mongodb',
|
|
37
|
+
'mongoose',
|
|
38
|
+
'redis',
|
|
39
|
+
'ioredis',
|
|
40
|
+
'kysely',
|
|
41
|
+
'kysely-postgres-js',
|
|
42
|
+
'drizzle-orm',
|
|
43
|
+
'@prisma/client',
|
|
44
|
+
'knex',
|
|
45
|
+
'typeorm',
|
|
46
|
+
'sequelize',
|
|
47
|
+
].map((name): [string, Forbidden] => [name, DATABASE]),
|
|
48
|
+
...['@aws-sdk/client-s3', '@aws-sdk/lib-storage', '@aws-sdk/s3-request-presigner', 'aws-sdk', 'minio', 'aws4fetch'].map((
|
|
49
|
+
name,
|
|
50
|
+
): [string, Forbidden] => [name, STORAGE]),
|
|
51
|
+
['jose', TOKENS],
|
|
52
|
+
...['http', 'https', 'http2', 'net', 'tls', 'dgram'].map((name): [string, Forbidden] => [name, NETWORK]),
|
|
53
|
+
['child_process', PROCESSES],
|
|
54
|
+
])
|
|
55
|
+
|
|
56
|
+
/** Subpaths only the framework or the installation's own services import; an application never does. */
|
|
57
|
+
const FRAMEWORK_ONLY: ReadonlyMap<string, Forbidden> = new Map([
|
|
58
|
+
['@fabrika/db/framework', {
|
|
59
|
+
what: "the framework's binding of the data layer to its connection",
|
|
60
|
+
allowed: 'serve(contract, { database: scoped(tables) }); boot binds it',
|
|
61
|
+
}],
|
|
62
|
+
['@fabrika/app/service', {
|
|
63
|
+
what: "the installation services' own router, which bypasses the contract",
|
|
64
|
+
allowed: 'endpoints declared in the slices and fabrika.contract.ts, served by serve(contract, { database })',
|
|
65
|
+
}],
|
|
66
|
+
])
|
|
67
|
+
|
|
68
|
+
/** Exports only the runtime adapters and the test kits call: a second runtime the application boots serves no contract. */
|
|
69
|
+
const FRAMEWORK_ONLY_EXPORTS: ReadonlyMap<string, ReadonlyMap<string, Forbidden>> = new Map([
|
|
70
|
+
[
|
|
71
|
+
'@fabrika/app/implement',
|
|
72
|
+
new Map([['boot', { what: "the runtime adapters' boot", allowed: 'the generated entrypoint boots the application; tests use testKit' }]]),
|
|
73
|
+
],
|
|
74
|
+
])
|
|
75
|
+
|
|
76
|
+
/** The `Bun` globals that open a server, a socket, a database, a bucket or a process; imported by name from `bun`, the same bypass. */
|
|
77
|
+
export const FORBIDDEN_BUN_MEMBERS: ReadonlyMap<string, Forbidden> = new Map([
|
|
78
|
+
...['sql', 'SQL'].map((name): [string, Forbidden] => [name, DATABASE]),
|
|
79
|
+
...['S3Client', 's3'].map((name): [string, Forbidden] => [name, STORAGE]),
|
|
80
|
+
...['serve', 'connect', 'listen', 'udpSocket'].map((name): [string, Forbidden] => [name, NETWORK]),
|
|
81
|
+
...['spawn', 'spawnSync', '$'].map((name): [string, Forbidden] => [name, PROCESSES]),
|
|
82
|
+
])
|
|
83
|
+
|
|
84
|
+
/** `node:http` and `http` name one module; `pg/lib/client` belongs to `pg`. */
|
|
85
|
+
const packageName = (specifier: string): string => {
|
|
86
|
+
const bare = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier
|
|
87
|
+
const segments = bare.split('/')
|
|
88
|
+
return bare.startsWith('@') ? segments.slice(0, 2).join('/') : (segments[0] ?? bare)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const ALLOWED_ENV = 'values the framework hands the handler through deps or ctx'
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The test kits: the application's signs tokens with its own key and boots the application a second way; the
|
|
95
|
+
* database's reaches tables by name and seeds rows past the data layer. Production never loads either.
|
|
96
|
+
*/
|
|
97
|
+
const TEST_KITS = ['@fabrika/app/testing', '@fabrika/db/testing']
|
|
98
|
+
const TEST_ONLY_ALLOWED = 'the kit in a test file (*.test.ts, *.spec.ts or a __tests__ directory) only'
|
|
99
|
+
|
|
100
|
+
export const isTestKit = (specifier: string): boolean => TEST_KITS.some((kit) => specifier === kit || specifier.startsWith(`${kit}/`))
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A non-test module may reach neither the kit nor a test module: a test helper may load the kit, so a production
|
|
104
|
+
* import of one would reach it too.
|
|
105
|
+
*/
|
|
106
|
+
const checkTestOnly = (reference: ModuleReference, target: string, report: Report): void => {
|
|
107
|
+
if (isTestKit(target)) {
|
|
108
|
+
report(reference.node, 'test-only-import', `'${reference.specifier}' is the test kit, loaded outside a test file`, TEST_ONLY_ALLOWED)
|
|
109
|
+
} else if (isTestFile(target)) {
|
|
110
|
+
report(reference.node, 'test-only-import', `'${reference.specifier}' is a test module, loaded outside a test file`, TEST_ONLY_ALLOWED)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** A path from the root that a mapping or an import lands on, judged by where the checker reads. */
|
|
115
|
+
const containmentProblem = (target: string | undefined): string | undefined => {
|
|
116
|
+
if (target === undefined) return 'resolves outside the application root, where the checker does not look'
|
|
117
|
+
if (target.split('/').some(isIgnoredSegment)) return 'resolves into a directory the checker skips'
|
|
118
|
+
return undefined
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const checkPackage = (reference: ModuleReference, specifier: string, report: Report, isGeneratedEntry: boolean, isTest: boolean): void => {
|
|
122
|
+
const { node } = reference
|
|
123
|
+
const name = packageName(specifier)
|
|
124
|
+
const forbidden = FRAMEWORK_ONLY.get(specifier) ?? FORBIDDEN_PACKAGES.get(name)
|
|
125
|
+
if (forbidden !== undefined) {
|
|
126
|
+
report(node, 'forbidden-import', `'${specifier}' is ${forbidden.what}`, forbidden.allowed)
|
|
127
|
+
return
|
|
128
|
+
}
|
|
129
|
+
const exports = isTest || isGeneratedEntry ? undefined : FRAMEWORK_ONLY_EXPORTS.get(specifier)
|
|
130
|
+
for (const imported of reference.names) {
|
|
131
|
+
const only = exports?.get(imported)
|
|
132
|
+
if (only !== undefined) report(node, 'forbidden-import', `'${imported}' from '${specifier}' is ${only.what}`, only.allowed)
|
|
133
|
+
}
|
|
134
|
+
if (name === 'module') {
|
|
135
|
+
report(node, 'unchecked-import', `'${specifier}' loads modules by path (createRequire), past what the checker reads`, 'a static import')
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
if (name === 'bun') {
|
|
139
|
+
for (const imported of reference.names) {
|
|
140
|
+
const member = FORBIDDEN_BUN_MEMBERS.get(imported)
|
|
141
|
+
if (member !== undefined) report(node, 'forbidden-global', `'${imported}' from 'bun' is ${member.what}`, member.allowed)
|
|
142
|
+
else if (imported === 'resolve' || imported === 'resolveSync') {
|
|
143
|
+
report(node, 'unchecked-import', `'${imported}' from 'bun' names a module by its file, past what the checker reads`, 'a static import')
|
|
144
|
+
} else if (imported === '*' || imported === 'default') {
|
|
145
|
+
report(node, 'forbidden-global', `'bun' loaded whole hides which of its members is used`, 'named imports from bun')
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const takesEnvironment = reference.names.some((imported) => imported === 'env' || imported === '*' || imported === 'default')
|
|
150
|
+
if (name === 'process' && takesEnvironment && !isGeneratedEntry) report(node, 'env-read', `'${specifier}' loaded for its environment`, ALLOWED_ENV)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export const checkModuleReferences = (
|
|
154
|
+
file: string,
|
|
155
|
+
references: readonly ModuleReference[],
|
|
156
|
+
mappings: ImportMappings,
|
|
157
|
+
exists: (path: string) => boolean,
|
|
158
|
+
report: Report,
|
|
159
|
+
isGeneratedEntry: boolean,
|
|
160
|
+
isTest: boolean,
|
|
161
|
+
): void => {
|
|
162
|
+
const testOnly = (reference: ModuleReference, target: string): void => {
|
|
163
|
+
if (!isTest && !reference.typeOnly) checkTestOnly(reference, target, report)
|
|
164
|
+
}
|
|
165
|
+
for (const reference of references) {
|
|
166
|
+
const { specifier, node } = reference
|
|
167
|
+
if (specifier.startsWith('/') || /^file:/i.test(specifier)) {
|
|
168
|
+
report(
|
|
169
|
+
node,
|
|
170
|
+
'unchecked-import',
|
|
171
|
+
`'${specifier}' is an absolute path, outside what the checker reads`,
|
|
172
|
+
'a relative import of a module inside the application',
|
|
173
|
+
)
|
|
174
|
+
continue
|
|
175
|
+
}
|
|
176
|
+
if (isRelativeSpecifier(specifier)) {
|
|
177
|
+
const problem = containmentProblem(joinRelative(file, specifier))
|
|
178
|
+
if (problem !== undefined) {
|
|
179
|
+
report(node, 'unchecked-import', `'${specifier}' ${problem}`, 'a module inside the application, outside node_modules, dist and dot-directories')
|
|
180
|
+
continue
|
|
181
|
+
}
|
|
182
|
+
const resolution = resolveRelative(exists, file, specifier)
|
|
183
|
+
if (resolution.kind === 'file') testOnly(reference, resolution.path)
|
|
184
|
+
// A directory import loads its index, and an ambiguous one may load any candidate.
|
|
185
|
+
else if (resolution.kind !== 'missing') { for (const path of resolution.paths) testOnly(reference, path) }
|
|
186
|
+
const packageEntry = resolution.kind === 'directory' && resolution.paths.some((path) => path.endsWith('/package.json'))
|
|
187
|
+
if (resolution.kind === 'ambiguous' || packageEntry) {
|
|
188
|
+
const what = packageEntry
|
|
189
|
+
? 'is a directory with a package.json, whose entry point Bun follows'
|
|
190
|
+
: `resolves to each of ${resolution.paths.join(', ')}`
|
|
191
|
+
report(
|
|
192
|
+
node,
|
|
193
|
+
'unchecked-import',
|
|
194
|
+
`'${specifier}' ${what}, which the checker does not resolve as Bun does`,
|
|
195
|
+
'a relative import that names the module file, extension included',
|
|
196
|
+
)
|
|
197
|
+
}
|
|
198
|
+
continue
|
|
199
|
+
}
|
|
200
|
+
const targets = mappedTargets(mappings, file, specifier)
|
|
201
|
+
if (targets === undefined) {
|
|
202
|
+
testOnly(reference, specifier)
|
|
203
|
+
if (!reference.typeOnly) checkPackage(reference, specifier, report, isGeneratedEntry, isTest)
|
|
204
|
+
continue
|
|
205
|
+
}
|
|
206
|
+
for (const target of targets) {
|
|
207
|
+
if (!isRelativeSpecifier(target) && !target.startsWith('/')) {
|
|
208
|
+
testOnly(reference, target)
|
|
209
|
+
if (!reference.typeOnly) checkPackage(reference, target, report, isGeneratedEntry, isTest)
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
212
|
+
// Mapping targets are relative to the root, where both package.json and tsconfig.json live.
|
|
213
|
+
const mapped = target.startsWith('/') ? undefined : joinRelative('package.json', target)
|
|
214
|
+
if (mapped !== undefined) {
|
|
215
|
+
const resolved = resolveRelative(exists, 'package.json', `./${mapped}`)
|
|
216
|
+
if (resolved.kind === 'file') testOnly(reference, resolved.path)
|
|
217
|
+
else if (resolved.kind !== 'missing') { for (const path of resolved.paths) testOnly(reference, path) }
|
|
218
|
+
else testOnly(reference, mapped)
|
|
219
|
+
}
|
|
220
|
+
const problem = containmentProblem(mapped)
|
|
221
|
+
if (problem !== undefined) {
|
|
222
|
+
report(node, 'unchecked-import', `'${specifier}' is mapped to '${target}', which ${problem}`, 'a mapping onto a module inside the application')
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The routine ways to replace a package the platform trusts by name (ADR-0043): a manifest override or patch, a
|
|
2
|
+
// specifier that does not name a registry version, a lockfile entry without the registry's integrity hash, another
|
|
3
|
+
// registry, and an ambient module declaration that retypes it. The platform build installs from the lockfile with
|
|
4
|
+
// `--frozen-lockfile`, so a trusted entry that resolves from the registry with its hash is the package itself.
|
|
5
|
+
// Only a packed set the caller names (`--packed`, never the platform build) admits its own tarballs and overrides.
|
|
6
|
+
|
|
7
|
+
import { posix } from 'node:path'
|
|
8
|
+
import { type AstNode, child, staticString } from '../ast'
|
|
9
|
+
import type { Finding, Report } from '../finding'
|
|
10
|
+
import { parseJsonc } from '../jsonc'
|
|
11
|
+
import type { PackedSet } from '../packed'
|
|
12
|
+
import { isKey, parseToml } from '../toml'
|
|
13
|
+
import { BUNFIG_FILE, isTrustedSpecifier } from '../trust'
|
|
14
|
+
|
|
15
|
+
export const LOCKFILE = 'bun.lock'
|
|
16
|
+
export const NPMRC_FILE = '.npmrc'
|
|
17
|
+
|
|
18
|
+
const REPLACEMENT_FIELDS = ['patchedDependencies', 'overrides', 'resolutions'] as const
|
|
19
|
+
const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'] as const
|
|
20
|
+
/** An exact version or a caret/tilde range of one: what `bun add` writes for a registry package. */
|
|
21
|
+
const REGISTRY_RANGE = /^[~^]?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
|
|
22
|
+
const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
|
|
23
|
+
|
|
24
|
+
const REGISTRY_ALLOWED = 'a registry version of the package, such as "^1.2.3", resolved by bun install from the npm registry'
|
|
25
|
+
|
|
26
|
+
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
27
|
+
|
|
28
|
+
const baseName = (path: string): string => path.slice(path.lastIndexOf('/') + 1)
|
|
29
|
+
|
|
30
|
+
/** Where `needle` first appears in `text`, as a finding position; the start of the file when it does not. */
|
|
31
|
+
const positionIn = (text: string, needle: string): { readonly line: number; readonly column: number } => {
|
|
32
|
+
const index = text.indexOf(needle)
|
|
33
|
+
if (index === -1) return { line: 1, column: 1 }
|
|
34
|
+
const before = text.slice(0, index)
|
|
35
|
+
return { line: before.split('\n').length, column: index - (before.lastIndexOf('\n') + 1) + 1 }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The package a lockfile key names: `@fabrika/app` for both `@fabrika/app` and `some-dep/@fabrika/app`. */
|
|
39
|
+
const lockfilePackage = (key: string): string => {
|
|
40
|
+
const segments = key.split('/')
|
|
41
|
+
const last = segments.at(-1) ?? ''
|
|
42
|
+
const scope = segments.at(-2)
|
|
43
|
+
return scope?.startsWith('@') === true ? `${scope}/${last}` : last
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether `target`, a path relative to the root, is the tarball of `name` in the packed set: named as the pack named
|
|
48
|
+
* it, with the bytes the pack hashed.
|
|
49
|
+
*/
|
|
50
|
+
const isPackedTarball = (packed: PackedSet | undefined, name: string, target: string): boolean => {
|
|
51
|
+
const tarball = packed?.packages.get(name)
|
|
52
|
+
const path = posix.normalize(target)
|
|
53
|
+
return tarball !== undefined && posix.basename(path) === tarball.filename && packed?.tarballs.get(path) === tarball.integrity
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether a manifest's `file:` specifier for `name` names its packed tarball; relative to the manifest's directory. */
|
|
57
|
+
const isPackedSpecifier = (packed: PackedSet | undefined, name: string, specifier: unknown, manifest: string): boolean =>
|
|
58
|
+
typeof specifier === 'string' && specifier.startsWith('file:')
|
|
59
|
+
&& isPackedTarball(packed, name, posix.join(posix.dirname(manifest), specifier.slice('file:'.length)))
|
|
60
|
+
|
|
61
|
+
export const checkPackageReplacement = (files: ReadonlyMap<string, string>, packed?: PackedSet): Finding[] => {
|
|
62
|
+
const findings: Finding[] = []
|
|
63
|
+
const finding = (file: string, needle: string, message: string, allowed: string): void => {
|
|
64
|
+
findings.push({ file, ...positionIn(files.get(file) ?? '', needle), severity: 'refusal', rule: 'package-replacement', message, allowed })
|
|
65
|
+
}
|
|
66
|
+
for (const [path, text] of files) {
|
|
67
|
+
if (baseName(path) === 'package.json') checkManifest(path, text, finding, packed)
|
|
68
|
+
else if (path === LOCKFILE) checkLockfile(text, finding, packed)
|
|
69
|
+
else if (path === BUNFIG_FILE) checkRegistryConfiguration(path, text, finding)
|
|
70
|
+
else if (path === NPMRC_FILE) checkNpmrc(text, finding)
|
|
71
|
+
}
|
|
72
|
+
return findings
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
type Finder = (file: string, needle: string, message: string, allowed: string) => void
|
|
76
|
+
|
|
77
|
+
function checkManifest(path: string, text: string, finding: Finder, packed: PackedSet | undefined): void {
|
|
78
|
+
const manifest = parseJsonc(text)
|
|
79
|
+
if (!isRecord(manifest)) return
|
|
80
|
+
// Bun resolves a package's own name to itself: an application named `@fabrika/app` imports its own files as it.
|
|
81
|
+
const name = manifest['name']
|
|
82
|
+
if (typeof name === 'string' && isTrustedSpecifier(name)) {
|
|
83
|
+
finding(
|
|
84
|
+
path,
|
|
85
|
+
'"name"',
|
|
86
|
+
`the package is named ${name}, so an import of ${name} loads the application's own files`,
|
|
87
|
+
'a name outside @fabrika/* and zod',
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
if (path === 'package.json' && manifest['exports'] !== undefined) {
|
|
91
|
+
finding(path, '"exports"', 'an exports map lets the application stand in for a package by self-reference', 'no exports in the root package.json')
|
|
92
|
+
}
|
|
93
|
+
for (const field of REPLACEMENT_FIELDS) {
|
|
94
|
+
const replacements = manifest[field]
|
|
95
|
+
if (replacements === undefined) continue
|
|
96
|
+
const packedOverrides = field === 'overrides' && isRecord(replacements)
|
|
97
|
+
&& Object.entries(replacements).every(([name, specifier]) => isPackedSpecifier(packed, name, specifier, path))
|
|
98
|
+
if (!packedOverrides) {
|
|
99
|
+
finding(path, `"${field}"`, `${field} can replace any package, the ones the platform trusts by name included`, `no ${field} in package.json`)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
for (const field of DEPENDENCY_FIELDS) {
|
|
103
|
+
const dependencies = manifest[field]
|
|
104
|
+
if (!isRecord(dependencies)) continue
|
|
105
|
+
for (const [name, specifier] of Object.entries(dependencies)) {
|
|
106
|
+
if (!isTrustedSpecifier(name) || isPackedSpecifier(packed, name, specifier, path)) continue
|
|
107
|
+
if (typeof specifier !== 'string' || !REGISTRY_RANGE.test(specifier)) {
|
|
108
|
+
finding(path, `"${name}":`, `${field} names ${name} as '${String(specifier)}', which is not a registry version`, REGISTRY_ALLOWED)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function checkLockfile(text: string, finding: Finder, packed: PackedSet | undefined): void {
|
|
115
|
+
const lockfile = parseJsonc(text)
|
|
116
|
+
const packages = isRecord(lockfile) ? lockfile['packages'] : undefined
|
|
117
|
+
if (!isRecord(packages)) {
|
|
118
|
+
finding(LOCKFILE, '', `${LOCKFILE} has no packages the check can read`, 'a bun.lock written by bun install')
|
|
119
|
+
return
|
|
120
|
+
}
|
|
121
|
+
for (const [key, entry] of Object.entries(packages)) {
|
|
122
|
+
const name = lockfilePackage(key)
|
|
123
|
+
if (!isTrustedSpecifier(name)) continue
|
|
124
|
+
const resolution = Array.isArray(entry) ? entry[0] : undefined
|
|
125
|
+
const registry = Array.isArray(entry) ? entry[1] : undefined
|
|
126
|
+
const integrity = Array.isArray(entry) ? entry.at(-1) : undefined
|
|
127
|
+
const version = typeof resolution === 'string' && resolution.startsWith(`${name}@`) ? resolution.slice(name.length + 1) : ''
|
|
128
|
+
// Bun records a tarball as `<name>@<path>`, its dependencies and the sha512 of its bytes, with no registry.
|
|
129
|
+
if (isPackedTarball(packed, name, version) && integrity === packed?.packages.get(name)?.integrity) continue
|
|
130
|
+
if (!EXACT_VERSION.test(version) || registry !== '' || typeof integrity !== 'string' || !integrity.startsWith('sha512-')) {
|
|
131
|
+
finding(
|
|
132
|
+
LOCKFILE,
|
|
133
|
+
`"${key}"`,
|
|
134
|
+
`the lockfile entry of ${name} does not resolve from the npm registry with an integrity hash`,
|
|
135
|
+
'a registry version in package.json and a bun.lock written by bun install',
|
|
136
|
+
)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Another registry serves its own build of a trusted package under the same name and version. */
|
|
142
|
+
function checkRegistryConfiguration(path: string, text: string, finding: Finder): void {
|
|
143
|
+
const document = parseToml(text)
|
|
144
|
+
if (!document.ok) return
|
|
145
|
+
const lines = text.split('\n')
|
|
146
|
+
for (const entry of document.entries) {
|
|
147
|
+
if (isKey(entry, 'install', 'registry') || (entry.key[0] === 'install' && entry.key[1] === 'scopes')) {
|
|
148
|
+
finding(path, lines[entry.line - 1]?.trim() ?? '', 'another registry can serve a package the platform trusts by name', 'the default npm registry')
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function checkNpmrc(text: string, finding: Finder): void {
|
|
154
|
+
for (const line of text.split('\n')) {
|
|
155
|
+
if (/registry\s*=/.test(line)) {
|
|
156
|
+
finding(NPMRC_FILE, line.trim(), 'another registry can serve a package the platform trusts by name', 'the default npm registry')
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** `declare module '@fabrika/app'` retypes a trusted package for the type check without changing what runs. */
|
|
162
|
+
export const checkAmbientModule = (node: AstNode, report: Report): void => {
|
|
163
|
+
if (node.type !== 'TSModuleDeclaration') return
|
|
164
|
+
const name = staticString(child(node, 'id'))
|
|
165
|
+
if (name !== undefined && isTrustedSpecifier(name)) {
|
|
166
|
+
report(node, 'package-replacement', `declare module '${name}' retypes a package the platform trusts by name`, 'no module declaration for it')
|
|
167
|
+
}
|
|
168
|
+
}
|