gencow 0.1.299 → 0.2.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/bin/gencow.mjs +0 -6
- package/core/package.json +1 -1
- package/docs/packaging.md +14 -4
- package/lib/cli-artifact-guard.mjs +53 -3
- package/lib/cli-dev-runtime.mjs +1 -0
- package/lib/cli-project-runtime.mjs +26 -14
- package/lib/codegen-command.mjs +16 -0
- package/lib/coding-guardrails.mjs +2 -0
- package/lib/dashboard-artifact.mjs +65 -0
- package/lib/dashboard-assets.mjs +20 -0
- package/lib/db-command.mjs +121 -80
- package/lib/db-migration-command-steps.mjs +19 -16
- package/lib/db-push-command.mjs +1 -1
- package/lib/deploy-codegen-preflight.mjs +1 -0
- package/lib/dev-cloud-command.mjs +1 -1
- package/lib/dev-local-command.mjs +19 -56
- package/lib/document-local-converter.mjs +11 -0
- package/lib/local-dashboard-plan.mjs +60 -0
- package/lib/local-database-commands.mjs +127 -0
- package/lib/local-development-migrations.mjs +157 -0
- package/lib/local-drizzle-database.config.mjs +10 -0
- package/lib/local-runtime-features.mjs +12 -0
- package/lib/rag-selection.mjs +7 -0
- package/lib/runtime-local-worker.mjs +116 -0
- package/lib/runtime-mode.mjs +3 -0
- package/lib/standalone-codegen-adapter.mjs +91 -0
- package/lib/ts-codegen-import-extension.mjs +228 -19
- package/package.json +15 -8
- package/runtime/config.mjs +218 -2
- package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
- package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
- package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
- package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
- package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
- package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
- package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
- package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
- package/runtime/engine/chunk-5575APCJ.mjs +215 -0
- package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
- package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
- package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
- package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
- package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
- package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
- package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
- package/runtime/engine/chunk-6W653LXI.mjs +13 -0
- package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
- package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
- package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
- package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
- package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
- package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
- package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
- package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
- package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
- package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
- package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
- package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
- package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
- package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
- package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
- package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
- package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
- package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
- package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
- package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
- package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
- package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
- package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
- package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
- package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
- package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
- package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
- package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
- package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
- package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
- package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
- package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
- package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
- package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
- package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
- package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
- package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
- package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
- package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
- package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
- package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
- package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
- package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
- package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
- package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
- package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
- package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
- package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
- package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
- package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
- package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
- package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
- package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
- package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
- package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
- package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
- package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
- package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
- package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
- package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
- package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
- package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
- package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
- package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
- package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
- package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
- package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
- package/runtime/engine/chunk-YRHM272W.mjs +528 -0
- package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
- package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
- package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
- package/runtime/engine/composition.mjs +325 -0
- package/runtime/engine/document-local.mjs +504 -0
- package/runtime/engine/graph.json +4134 -0
- package/runtime/engine/index.mjs +265 -0
- package/runtime/engine/local-postgres-support.mjs +69 -0
- package/runtime/engine/local.mjs +3275 -0
- package/runtime/engine/pglite-directory-lock.mjs +8 -0
- package/runtime/engine/rag.mjs +11 -0
- package/runtime/engine/search.mjs +18 -0
- package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
- package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
- package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
- package/runtime/framework-migrations/manifest.json +56 -0
- package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
- package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
- package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
- package/runtime/runtime-metadata.json +27 -0
- package/runtime/tooling.mjs +10399 -8951
- package/scripts/bundle-runtime-config.mjs +23 -0
- package/scripts/bundle-runtime.mjs +100 -0
- package/scripts/bundle-runtime.test.mjs +33 -0
- package/scripts/bundle-shared.mjs +3 -0
- package/scripts/copy-dashboard.mjs +16 -0
- package/scripts/pre-publish-check.mjs +23 -11
- package/templateFeature/ai/ai-facade.ts +38 -15
- package/templateFeature/ai/manifest.json +1 -0
- package/templateFeature/sso/sso-auth-callback.tsx +37 -5
- package/templateFeature/tools/manifest.json +5 -2
- package/templateFeature/tools/tools.ts +3 -3
- package/runtime/server.mjs +0 -14389
- package/scripts/bundle-server.mjs +0 -223
- package/server/config.js +0 -1
- package/server/index.js +0 -1
- package/server/package.json +0 -6
|
@@ -0,0 +1,3275 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createConsoleRuntimeLogSink,
|
|
3
|
+
createLocalRuntimeApplicationLoader,
|
|
4
|
+
resolveAuthSchemaPaths,
|
|
5
|
+
resolveServerCodegenDirAbs
|
|
6
|
+
} from "./chunk-TCN3ZASV.mjs";
|
|
7
|
+
import {
|
|
8
|
+
createRuntimeJobActivation,
|
|
9
|
+
resolveRuntimeProjectIdentity
|
|
10
|
+
} from "./chunk-5575APCJ.mjs";
|
|
11
|
+
import {
|
|
12
|
+
admitStandaloneProfile,
|
|
13
|
+
assertLocalDashboardRequest,
|
|
14
|
+
captureLocalDashboardOptions,
|
|
15
|
+
captureRuntimeWorkflowEnvironment,
|
|
16
|
+
composeRuntime,
|
|
17
|
+
createLocalDashboardObservations,
|
|
18
|
+
isLocalDashboardSurface,
|
|
19
|
+
localDashboardDenial,
|
|
20
|
+
localDashboardIdentity,
|
|
21
|
+
realtimeHttpDiagnostic,
|
|
22
|
+
realtimeHttpResponse,
|
|
23
|
+
startRuntimeBunListener
|
|
24
|
+
} from "./chunk-JODRNM3S.mjs";
|
|
25
|
+
import {
|
|
26
|
+
assertRuntimeHost
|
|
27
|
+
} from "./chunk-DPWXSMWO.mjs";
|
|
28
|
+
import "./chunk-2JLO3KMM.mjs";
|
|
29
|
+
import "./chunk-N4LTCKJP.mjs";
|
|
30
|
+
import {
|
|
31
|
+
authStartupError,
|
|
32
|
+
createRuntimeHostContext,
|
|
33
|
+
resolveServerCompatibleAccessTokenKey
|
|
34
|
+
} from "./chunk-67YO53WW.mjs";
|
|
35
|
+
import "./chunk-2SR2M7SR.mjs";
|
|
36
|
+
import "./chunk-ADF3UR6L.mjs";
|
|
37
|
+
import "./chunk-A5BMQ5IC.mjs";
|
|
38
|
+
import "./chunk-YRHM272W.mjs";
|
|
39
|
+
import "./chunk-GSLM44EF.mjs";
|
|
40
|
+
import "./chunk-RW65MPVY.mjs";
|
|
41
|
+
import "./chunk-P5IIXAIE.mjs";
|
|
42
|
+
import "./chunk-RITT2RSJ.mjs";
|
|
43
|
+
import "./chunk-AGPQ5XIV.mjs";
|
|
44
|
+
import "./chunk-Y3HSBJ3I.mjs";
|
|
45
|
+
import "./chunk-GYAJ7OX2.mjs";
|
|
46
|
+
import "./chunk-GDWYAGWV.mjs";
|
|
47
|
+
import "./chunk-5GUJZQF3.mjs";
|
|
48
|
+
import "./chunk-XNFVL2OY.mjs";
|
|
49
|
+
import "./chunk-5TACQ2US.mjs";
|
|
50
|
+
import "./chunk-JUDKX53X.mjs";
|
|
51
|
+
import "./chunk-KVLTJFCH.mjs";
|
|
52
|
+
import "./chunk-7KUJ2H2S.mjs";
|
|
53
|
+
import "./chunk-ZXMM7QFP.mjs";
|
|
54
|
+
import "./chunk-PZFMKFHO.mjs";
|
|
55
|
+
import "./chunk-LINVSJEM.mjs";
|
|
56
|
+
import "./chunk-GOLP7OSG.mjs";
|
|
57
|
+
import "./chunk-ZQUZAGIQ.mjs";
|
|
58
|
+
import "./chunk-QL2TQX2N.mjs";
|
|
59
|
+
import "./chunk-LEW5ZMLR.mjs";
|
|
60
|
+
import {
|
|
61
|
+
captureRagEmbeddingEnvironment
|
|
62
|
+
} from "./chunk-3R7COBWG.mjs";
|
|
63
|
+
import "./chunk-4MLRXO7F.mjs";
|
|
64
|
+
import {
|
|
65
|
+
captureApplicationMigrationOutcome,
|
|
66
|
+
getRuntimeStartupCleanup,
|
|
67
|
+
withStartupMigrationImpacts
|
|
68
|
+
} from "./chunk-6GQRM7XY.mjs";
|
|
69
|
+
import {
|
|
70
|
+
captureTrustedLocalDatabaseSecurityPolicy
|
|
71
|
+
} from "./chunk-ZZJSIPV2.mjs";
|
|
72
|
+
import "./chunk-FM23RGVI.mjs";
|
|
73
|
+
import "./chunk-U2NRG6KC.mjs";
|
|
74
|
+
import "./chunk-ITH2NEKM.mjs";
|
|
75
|
+
import "./chunk-KEZJUXEE.mjs";
|
|
76
|
+
import "./chunk-N2TA2IK2.mjs";
|
|
77
|
+
import {
|
|
78
|
+
snapshotRuntimeBinding
|
|
79
|
+
} from "./chunk-WDTKPPMU.mjs";
|
|
80
|
+
import "./chunk-EAIELFKU.mjs";
|
|
81
|
+
import "./chunk-KX2PRQPS.mjs";
|
|
82
|
+
import "./chunk-NAG2OXS5.mjs";
|
|
83
|
+
import "./chunk-3D7MHEUC.mjs";
|
|
84
|
+
import "./chunk-SVJCOUI3.mjs";
|
|
85
|
+
import "./chunk-IKQKBE2G.mjs";
|
|
86
|
+
import {
|
|
87
|
+
runtimeStartupError
|
|
88
|
+
} from "./chunk-IFMOTJNU.mjs";
|
|
89
|
+
import "./chunk-6JO72SPP.mjs";
|
|
90
|
+
import {
|
|
91
|
+
RuntimeDiagnosticError,
|
|
92
|
+
runtimeDiagnostic
|
|
93
|
+
} from "./chunk-AEBW7XZJ.mjs";
|
|
94
|
+
|
|
95
|
+
// ../runtime/dist/local.js
|
|
96
|
+
import { existsSync as existsSync7 } from "node:fs";
|
|
97
|
+
import { resolve as resolve7 } from "node:path";
|
|
98
|
+
import { pathToFileURL } from "node:url";
|
|
99
|
+
|
|
100
|
+
// ../shared/dist/src/analyzer/consumers/auditor/source-auditor.js
|
|
101
|
+
import { existsSync as existsSync4 } from "fs";
|
|
102
|
+
import { basename as basename3, dirname as dirname4, extname, resolve as resolve4 } from "path";
|
|
103
|
+
|
|
104
|
+
// ../shared/dist/src/analyzer/adapters/app-project.js
|
|
105
|
+
import { existsSync as existsSync2, statSync as statSync2 } from "fs";
|
|
106
|
+
import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
|
|
107
|
+
|
|
108
|
+
// ../shared/dist/src/analyzer/internal/source-files.js
|
|
109
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "fs";
|
|
110
|
+
import { dirname, join, relative, resolve } from "path";
|
|
111
|
+
var SOURCE_FILE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"];
|
|
112
|
+
function findSourceFiles(dir) {
|
|
113
|
+
if (!existsSync(dir))
|
|
114
|
+
return [];
|
|
115
|
+
try {
|
|
116
|
+
if (statSync(dir).isFile()) {
|
|
117
|
+
return /\.(?:[cm]?[jt]sx?)$/.test(dir) ? [dir] : [];
|
|
118
|
+
}
|
|
119
|
+
} catch {
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
122
|
+
const files = [];
|
|
123
|
+
try {
|
|
124
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
125
|
+
if (entry.name === "node_modules" || entry.name.startsWith("."))
|
|
126
|
+
continue;
|
|
127
|
+
const fullPath = join(dir, entry.name);
|
|
128
|
+
if (entry.isDirectory()) {
|
|
129
|
+
files.push(...findSourceFiles(fullPath));
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (entry.isFile() && /\.(?:[cm]?[jt]sx?)$/.test(entry.name)) {
|
|
133
|
+
files.push(fullPath);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
} catch {
|
|
137
|
+
return [];
|
|
138
|
+
}
|
|
139
|
+
return files;
|
|
140
|
+
}
|
|
141
|
+
function parseModuleSpecifiers(source) {
|
|
142
|
+
const imports = /* @__PURE__ */ new Set();
|
|
143
|
+
const patterns = [
|
|
144
|
+
/\bimport\s+[^'"]*?\s+from\s+["']([^"']+)["']/g,
|
|
145
|
+
/\bexport\s+[^'"]*?\s+from\s+["']([^"']+)["']/g,
|
|
146
|
+
/\bimport\s+["']([^"']+)["']/g,
|
|
147
|
+
/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,
|
|
148
|
+
/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g
|
|
149
|
+
];
|
|
150
|
+
for (const pattern of patterns) {
|
|
151
|
+
let match = pattern.exec(source);
|
|
152
|
+
while (match) {
|
|
153
|
+
if (match[1])
|
|
154
|
+
imports.add(match[1]);
|
|
155
|
+
match = pattern.exec(source);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return [...imports];
|
|
159
|
+
}
|
|
160
|
+
function findStaticRelativeImports(filePath) {
|
|
161
|
+
let source = "";
|
|
162
|
+
try {
|
|
163
|
+
source = readFileSync(filePath, "utf8");
|
|
164
|
+
} catch {
|
|
165
|
+
return [];
|
|
166
|
+
}
|
|
167
|
+
const imports = /* @__PURE__ */ new Set();
|
|
168
|
+
for (const specifier of parseModuleSpecifiers(source)) {
|
|
169
|
+
if (!specifier.startsWith("."))
|
|
170
|
+
continue;
|
|
171
|
+
const resolved = resolveRelativeModule(filePath, specifier);
|
|
172
|
+
if (resolved)
|
|
173
|
+
imports.add(resolved);
|
|
174
|
+
}
|
|
175
|
+
return [...imports];
|
|
176
|
+
}
|
|
177
|
+
function resolveRelativeModule(fromPath, specifier) {
|
|
178
|
+
if (!specifier.startsWith("."))
|
|
179
|
+
return null;
|
|
180
|
+
const base = resolve(dirname(fromPath), specifier);
|
|
181
|
+
return resolveSourceFileCandidate(base);
|
|
182
|
+
}
|
|
183
|
+
function toProjectPath(projectRootAbs, absPath) {
|
|
184
|
+
const relPath = relative(projectRootAbs, absPath).replace(/\\/g, "/");
|
|
185
|
+
return relPath.startsWith(".") ? relPath : `./${relPath}`;
|
|
186
|
+
}
|
|
187
|
+
function resolveSourceFileCandidate(base) {
|
|
188
|
+
const typescriptSubstitutions = [];
|
|
189
|
+
if (base.endsWith(".js")) {
|
|
190
|
+
const stem = base.slice(0, -3);
|
|
191
|
+
typescriptSubstitutions.push(`${stem}.ts`, `${stem}.tsx`);
|
|
192
|
+
} else if (base.endsWith(".mjs")) {
|
|
193
|
+
typescriptSubstitutions.push(`${base.slice(0, -4)}.mts`);
|
|
194
|
+
} else if (base.endsWith(".cjs")) {
|
|
195
|
+
typescriptSubstitutions.push(`${base.slice(0, -4)}.cts`);
|
|
196
|
+
}
|
|
197
|
+
const candidates = [
|
|
198
|
+
base,
|
|
199
|
+
...typescriptSubstitutions,
|
|
200
|
+
...SOURCE_FILE_EXTENSIONS.map((extension) => `${base}${extension}`),
|
|
201
|
+
...SOURCE_FILE_EXTENSIONS.map((extension) => join(base, `index${extension}`))
|
|
202
|
+
];
|
|
203
|
+
return candidates.find((candidate) => existsSync(candidate)) ?? null;
|
|
204
|
+
}
|
|
205
|
+
function stripJsonComments(source) {
|
|
206
|
+
let result = "";
|
|
207
|
+
let inString = false;
|
|
208
|
+
let stringQuote = "";
|
|
209
|
+
let escaping = false;
|
|
210
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
211
|
+
const char = source[index];
|
|
212
|
+
const next = source[index + 1];
|
|
213
|
+
if (inString) {
|
|
214
|
+
result += char;
|
|
215
|
+
if (escaping) {
|
|
216
|
+
escaping = false;
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (char === "\\") {
|
|
220
|
+
escaping = true;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (char === stringQuote) {
|
|
224
|
+
inString = false;
|
|
225
|
+
stringQuote = "";
|
|
226
|
+
}
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (char === '"' || char === "'") {
|
|
230
|
+
inString = true;
|
|
231
|
+
stringQuote = char;
|
|
232
|
+
result += char;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
if (char === "/" && next === "/") {
|
|
236
|
+
while (index < source.length && source[index] !== "\n")
|
|
237
|
+
index += 1;
|
|
238
|
+
if (index < source.length)
|
|
239
|
+
result += source[index];
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
if (char === "/" && next === "*") {
|
|
243
|
+
index += 2;
|
|
244
|
+
while (index < source.length && !(source[index] === "*" && source[index + 1] === "/"))
|
|
245
|
+
index += 1;
|
|
246
|
+
index += 1;
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
result += char;
|
|
250
|
+
}
|
|
251
|
+
return result;
|
|
252
|
+
}
|
|
253
|
+
function stripTrailingCommas(source) {
|
|
254
|
+
return source.replace(/,\s*([}\]])/g, "$1");
|
|
255
|
+
}
|
|
256
|
+
function parseJsoncObject(filePath) {
|
|
257
|
+
try {
|
|
258
|
+
const source = readFileSync(filePath, "utf8");
|
|
259
|
+
const normalized = stripTrailingCommas(stripJsonComments(source)).trim();
|
|
260
|
+
if (!normalized)
|
|
261
|
+
return null;
|
|
262
|
+
const parsed = JSON.parse(normalized);
|
|
263
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
264
|
+
} catch {
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function resolveTsConfigExtendsPath(configFile, extendsValue) {
|
|
269
|
+
if (!extendsValue.startsWith(".") && !extendsValue.startsWith("/"))
|
|
270
|
+
return null;
|
|
271
|
+
const configDir = dirname(configFile);
|
|
272
|
+
const rawPath = extendsValue.startsWith("/") ? extendsValue : resolve(configDir, extendsValue);
|
|
273
|
+
const candidates = rawPath.endsWith(".json") ? [rawPath] : [rawPath, `${rawPath}.json`, join(rawPath, "tsconfig.json")];
|
|
274
|
+
return candidates.find((candidate) => existsSync(candidate)) ?? null;
|
|
275
|
+
}
|
|
276
|
+
function loadTsConfigCompilerOptions(configFile, seen = /* @__PURE__ */ new Set()) {
|
|
277
|
+
const resolvedConfigFile = resolve(configFile);
|
|
278
|
+
if (seen.has(resolvedConfigFile))
|
|
279
|
+
return {};
|
|
280
|
+
seen.add(resolvedConfigFile);
|
|
281
|
+
const parsed = parseJsoncObject(resolvedConfigFile);
|
|
282
|
+
if (!parsed)
|
|
283
|
+
return {};
|
|
284
|
+
const localCompilerOptions = parsed.compilerOptions && typeof parsed.compilerOptions === "object" ? parsed.compilerOptions : {};
|
|
285
|
+
let inherited = {};
|
|
286
|
+
if (typeof parsed.extends === "string") {
|
|
287
|
+
const extendsPath = resolveTsConfigExtendsPath(resolvedConfigFile, parsed.extends);
|
|
288
|
+
if (extendsPath) {
|
|
289
|
+
inherited = loadTsConfigCompilerOptions(extendsPath, seen);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const baseUrl = typeof localCompilerOptions.baseUrl === "string" && localCompilerOptions.baseUrl.trim().length > 0 ? localCompilerOptions.baseUrl : inherited.baseUrl;
|
|
293
|
+
const mergedPaths = { ...inherited.paths ?? {} };
|
|
294
|
+
const localPaths = localCompilerOptions.paths && typeof localCompilerOptions.paths === "object" ? localCompilerOptions.paths : null;
|
|
295
|
+
if (localPaths) {
|
|
296
|
+
for (const [key, value] of Object.entries(localPaths)) {
|
|
297
|
+
if (Array.isArray(value)) {
|
|
298
|
+
mergedPaths[key] = value.filter((entry) => typeof entry === "string");
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
...baseUrl ? { baseUrl } : {},
|
|
304
|
+
...Object.keys(mergedPaths).length > 0 ? { paths: mergedPaths } : {}
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
function findNearestProjectConfigFiles(startDir) {
|
|
308
|
+
const configFiles = [];
|
|
309
|
+
let currentDir = resolve(startDir);
|
|
310
|
+
const visited = /* @__PURE__ */ new Set();
|
|
311
|
+
while (!visited.has(currentDir)) {
|
|
312
|
+
visited.add(currentDir);
|
|
313
|
+
const discovered = /* @__PURE__ */ new Set();
|
|
314
|
+
for (const filename of ["tsconfig.json", "jsconfig.json"]) {
|
|
315
|
+
const configPath = join(currentDir, filename);
|
|
316
|
+
if (!existsSync(configPath))
|
|
317
|
+
continue;
|
|
318
|
+
configFiles.push(configPath);
|
|
319
|
+
discovered.add(filename);
|
|
320
|
+
}
|
|
321
|
+
try {
|
|
322
|
+
const extraConfigFiles = readdirSync(currentDir).filter((filename) => !discovered.has(filename) && /^tsconfig\.[^.]+\.json$/i.test(filename)).sort();
|
|
323
|
+
for (const filename of extraConfigFiles) {
|
|
324
|
+
configFiles.push(join(currentDir, filename));
|
|
325
|
+
}
|
|
326
|
+
} catch {
|
|
327
|
+
}
|
|
328
|
+
const parentDir = dirname(currentDir);
|
|
329
|
+
if (parentDir === currentDir)
|
|
330
|
+
break;
|
|
331
|
+
currentDir = parentDir;
|
|
332
|
+
}
|
|
333
|
+
return configFiles;
|
|
334
|
+
}
|
|
335
|
+
function matchTsconfigPathPattern(specifier, pattern) {
|
|
336
|
+
if (!pattern.includes("*")) {
|
|
337
|
+
return specifier === pattern ? "" : null;
|
|
338
|
+
}
|
|
339
|
+
if ((pattern.match(/\*/g) ?? []).length !== 1)
|
|
340
|
+
return null;
|
|
341
|
+
const [prefix, suffix] = pattern.split("*");
|
|
342
|
+
if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix))
|
|
343
|
+
return null;
|
|
344
|
+
return specifier.slice(prefix.length, specifier.length - suffix.length);
|
|
345
|
+
}
|
|
346
|
+
function substituteTsconfigPathTarget(target, wildcardValue) {
|
|
347
|
+
if (!target.includes("*"))
|
|
348
|
+
return target;
|
|
349
|
+
if ((target.match(/\*/g) ?? []).length !== 1)
|
|
350
|
+
return null;
|
|
351
|
+
return target.replace("*", wildcardValue);
|
|
352
|
+
}
|
|
353
|
+
function resolveTsconfigAliasImportFile(importerFile, specifier) {
|
|
354
|
+
for (const configFile of findNearestProjectConfigFiles(dirname(importerFile))) {
|
|
355
|
+
const compilerOptions = loadTsConfigCompilerOptions(configFile);
|
|
356
|
+
const configDir = dirname(configFile);
|
|
357
|
+
const baseDir = compilerOptions.baseUrl ? resolve(configDir, compilerOptions.baseUrl) : configDir;
|
|
358
|
+
for (const [pattern, targets] of Object.entries(compilerOptions.paths ?? {})) {
|
|
359
|
+
const wildcardValue = matchTsconfigPathPattern(specifier, pattern);
|
|
360
|
+
if (wildcardValue === null)
|
|
361
|
+
continue;
|
|
362
|
+
for (const target of targets) {
|
|
363
|
+
const substituted = substituteTsconfigPathTarget(target, wildcardValue);
|
|
364
|
+
if (!substituted)
|
|
365
|
+
continue;
|
|
366
|
+
const resolvedTarget = substituted.startsWith("/") ? substituted : resolve(baseDir, substituted);
|
|
367
|
+
const candidate = resolveSourceFileCandidate(resolvedTarget);
|
|
368
|
+
if (candidate)
|
|
369
|
+
return candidate;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (compilerOptions.baseUrl) {
|
|
373
|
+
const candidate = resolveSourceFileCandidate(resolve(baseDir, specifier));
|
|
374
|
+
if (candidate)
|
|
375
|
+
return candidate;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
function resolveImportedSourceFile(importerFile, specifier) {
|
|
381
|
+
if (specifier.startsWith(".")) {
|
|
382
|
+
return resolveRelativeModule(importerFile, specifier);
|
|
383
|
+
}
|
|
384
|
+
if (specifier.startsWith("/")) {
|
|
385
|
+
return resolveSourceFileCandidate(specifier);
|
|
386
|
+
}
|
|
387
|
+
return resolveTsconfigAliasImportFile(importerFile, specifier);
|
|
388
|
+
}
|
|
389
|
+
function collectReachableSourceFiles(entryPoint) {
|
|
390
|
+
const results = [];
|
|
391
|
+
const queue = [entryPoint];
|
|
392
|
+
const visited = /* @__PURE__ */ new Set();
|
|
393
|
+
while (queue.length > 0) {
|
|
394
|
+
const current = queue.shift();
|
|
395
|
+
if (!current || visited.has(current) || !existsSync(current))
|
|
396
|
+
continue;
|
|
397
|
+
visited.add(current);
|
|
398
|
+
results.push(current);
|
|
399
|
+
try {
|
|
400
|
+
const source = readFileSync(current, "utf8");
|
|
401
|
+
for (const specifier of parseModuleSpecifiers(source)) {
|
|
402
|
+
const localFile = resolveImportedSourceFile(current, specifier);
|
|
403
|
+
if (localFile && !visited.has(localFile))
|
|
404
|
+
queue.push(localFile);
|
|
405
|
+
}
|
|
406
|
+
} catch {
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return results;
|
|
411
|
+
}
|
|
412
|
+
function resolveSourceEntrypoint(basePath) {
|
|
413
|
+
try {
|
|
414
|
+
if (existsSync(basePath) && statSync(basePath).isFile() && /\.(?:[cm]?[jt]sx?)$/.test(basePath)) {
|
|
415
|
+
return basePath;
|
|
416
|
+
}
|
|
417
|
+
} catch {
|
|
418
|
+
}
|
|
419
|
+
const directFileCandidates = SOURCE_FILE_EXTENSIONS.map((extension) => `${basePath}${extension}`);
|
|
420
|
+
for (const candidate of directFileCandidates) {
|
|
421
|
+
if (existsSync(candidate))
|
|
422
|
+
return candidate;
|
|
423
|
+
}
|
|
424
|
+
const indexCandidate = resolveSourceFileCandidate(join(basePath, "index"));
|
|
425
|
+
if (indexCandidate)
|
|
426
|
+
return indexCandidate;
|
|
427
|
+
return join(basePath, "index.ts");
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// ../shared/dist/src/analyzer/adapters/app-project.js
|
|
431
|
+
function resolveAppProject(input) {
|
|
432
|
+
const projectRootAbs = resolve2(input.projectRoot);
|
|
433
|
+
const rootDir = input.rootDir ?? input.functionsDir ?? "gencow";
|
|
434
|
+
const functionsDirAbs = isAbsolute(rootDir) ? rootDir : resolve2(projectRootAbs, rootDir);
|
|
435
|
+
const entryPointAbs = input.entryPath ? resolve2(projectRootAbs, input.entryPath) : resolveSourceEntrypoint(functionsDirAbs);
|
|
436
|
+
const sourceBaseAbs = isExistingDirectory(functionsDirAbs) ? functionsDirAbs : dirname2(entryPointAbs);
|
|
437
|
+
const sourceFilesAbs = existsSync2(entryPointAbs) ? collectReachableSourceFiles(entryPointAbs) : isExistingDirectory(functionsDirAbs) ? findSourceFiles(functionsDirAbs) : [];
|
|
438
|
+
const serverCodegenDirAbs = resolveServerCodegenDirAbs(projectRootAbs, functionsDirAbs, input.serverPublishDir);
|
|
439
|
+
const clientCodegenDirAbs = input.clientOutDir === false ? null : resolve2(projectRootAbs, input.clientOutDir ?? "./src/gencow");
|
|
440
|
+
const configuredSchemaPathsAbs = resolveAuthSchemaPaths(projectRootAbs, functionsDirAbs, input.schema, serverCodegenDirAbs);
|
|
441
|
+
const rootSchemaPathAbs = configuredSchemaPathsAbs.find((path) => path.replace(/\\/g, "/").endsWith("/schema.ts")) ?? configuredSchemaPathsAbs[0] ?? resolve2(functionsDirAbs, "schema.ts");
|
|
442
|
+
return {
|
|
443
|
+
projectRootAbs,
|
|
444
|
+
functionsDirAbs,
|
|
445
|
+
entryPointAbs,
|
|
446
|
+
sourceBaseAbs,
|
|
447
|
+
sourceFilesAbs,
|
|
448
|
+
serverCodegenDirAbs,
|
|
449
|
+
clientCodegenDirAbs,
|
|
450
|
+
configuredSchemaPathsAbs,
|
|
451
|
+
rootSchemaPathAbs
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function isExistingDirectory(pathValue) {
|
|
455
|
+
try {
|
|
456
|
+
return statSync2(pathValue).isDirectory();
|
|
457
|
+
} catch {
|
|
458
|
+
return false;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// ../shared/dist/src/analyzer/adapters/app-schema-graph.js
|
|
463
|
+
import { basename, dirname as dirname3, join as join2, resolve as resolve3 } from "path";
|
|
464
|
+
import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
|
|
465
|
+
function safeReadText(file) {
|
|
466
|
+
try {
|
|
467
|
+
return readFileSync2(file, "utf8");
|
|
468
|
+
} catch {
|
|
469
|
+
return null;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
function collectReachableSchemaModules(project) {
|
|
473
|
+
const visited = /* @__PURE__ */ new Set();
|
|
474
|
+
const queue = [...project.configuredSchemaPathsAbs];
|
|
475
|
+
while (queue.length > 0) {
|
|
476
|
+
const current = queue.shift();
|
|
477
|
+
if (!current || visited.has(current) || !existsSync3(current))
|
|
478
|
+
continue;
|
|
479
|
+
visited.add(current);
|
|
480
|
+
for (const next of findStaticRelativeImports(current)) {
|
|
481
|
+
if (!visited.has(next))
|
|
482
|
+
queue.push(next);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return [...visited].map((path) => toProjectPath(project.projectRootAbs, path));
|
|
486
|
+
}
|
|
487
|
+
function collectSchemaOwners(project, modulePaths) {
|
|
488
|
+
const owners = [];
|
|
489
|
+
for (const modulePath of modulePaths) {
|
|
490
|
+
const absPath = resolve3(project.projectRootAbs, modulePath);
|
|
491
|
+
if (!existsSync3(absPath))
|
|
492
|
+
continue;
|
|
493
|
+
const source = safeReadText(absPath);
|
|
494
|
+
if (source === null)
|
|
495
|
+
continue;
|
|
496
|
+
const publicOwnerPath = toProjectPath(project.projectRootAbs, absPath);
|
|
497
|
+
for (const table of parsePgTableExports(source)) {
|
|
498
|
+
owners.push({
|
|
499
|
+
tableName: table.tableName,
|
|
500
|
+
publicOwnerPath,
|
|
501
|
+
implementationPath: publicOwnerPath,
|
|
502
|
+
sourceKind: classifySchemaSourceKind(absPath)
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
if (basename(absPath) !== "schema-auth.ts" || !schemaAuthReexportsGeneratedSource(source))
|
|
506
|
+
continue;
|
|
507
|
+
const generatedTarget = resolveSchemaAuthGeneratedTarget(absPath, source);
|
|
508
|
+
if (!generatedTarget || !existsSync3(generatedTarget))
|
|
509
|
+
continue;
|
|
510
|
+
const generatedSource = safeReadText(generatedTarget);
|
|
511
|
+
if (generatedSource === null)
|
|
512
|
+
continue;
|
|
513
|
+
for (const table of parsePgTableExports(generatedSource)) {
|
|
514
|
+
owners.push({
|
|
515
|
+
tableName: table.tableName,
|
|
516
|
+
publicOwnerPath,
|
|
517
|
+
implementationPath: toProjectPath(project.projectRootAbs, generatedTarget),
|
|
518
|
+
sourceKind: "generated"
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return dedupeOwners(owners);
|
|
523
|
+
}
|
|
524
|
+
function collectHiddenSchemaOwners(project, reachableModules) {
|
|
525
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
526
|
+
for (const file of findSourceFiles(project.sourceBaseAbs)) {
|
|
527
|
+
const relPath = toProjectPath(project.projectRootAbs, file);
|
|
528
|
+
if (reachableModules.has(relPath))
|
|
529
|
+
continue;
|
|
530
|
+
const source = safeReadText(file);
|
|
531
|
+
if (source === null || parsePgTableExports(source).length === 0)
|
|
532
|
+
continue;
|
|
533
|
+
hidden.add(relPath);
|
|
534
|
+
}
|
|
535
|
+
return [...hidden].sort();
|
|
536
|
+
}
|
|
537
|
+
function collectDynamicSchemaEdges(project, modulePaths) {
|
|
538
|
+
const dynamic = /* @__PURE__ */ new Set();
|
|
539
|
+
for (const modulePath of modulePaths) {
|
|
540
|
+
const absPath = resolve3(project.projectRootAbs, modulePath);
|
|
541
|
+
if (!existsSync3(absPath))
|
|
542
|
+
continue;
|
|
543
|
+
const source = safeReadText(absPath);
|
|
544
|
+
if (source === null)
|
|
545
|
+
continue;
|
|
546
|
+
if (/\bimport\s*\(/.test(source) || /\brequire\s*\(/.test(source)) {
|
|
547
|
+
dynamic.add(modulePath);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return [...dynamic].sort();
|
|
551
|
+
}
|
|
552
|
+
function detectAuthBoundary(project) {
|
|
553
|
+
const userAuthPath = join2(project.functionsDirAbs, "schema-auth.ts");
|
|
554
|
+
if (existsSync3(userAuthPath)) {
|
|
555
|
+
const source = safeReadText(userAuthPath);
|
|
556
|
+
if (source === null) {
|
|
557
|
+
return {
|
|
558
|
+
mode: "forked",
|
|
559
|
+
publicPath: toProjectPath(project.projectRootAbs, userAuthPath)
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
const generatedTarget = resolveSchemaAuthGeneratedTarget(userAuthPath, source);
|
|
563
|
+
if (schemaAuthReexportsGeneratedSource(source) && generatedTarget) {
|
|
564
|
+
return {
|
|
565
|
+
mode: "re-export-shim",
|
|
566
|
+
publicPath: toProjectPath(project.projectRootAbs, userAuthPath),
|
|
567
|
+
generatedPath: toProjectPath(project.projectRootAbs, generatedTarget)
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
return {
|
|
571
|
+
mode: "forked",
|
|
572
|
+
publicPath: toProjectPath(project.projectRootAbs, userAuthPath)
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
const legacyAuthPath = project.configuredSchemaPathsAbs.find((path) => path.replace(/\\/g, "/").endsWith("/auth-schema.ts"));
|
|
576
|
+
if (legacyAuthPath) {
|
|
577
|
+
return {
|
|
578
|
+
mode: "legacy-auth-schema",
|
|
579
|
+
path: toProjectPath(project.projectRootAbs, legacyAuthPath)
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
return { mode: "none" };
|
|
583
|
+
}
|
|
584
|
+
function collectModuleImports(project) {
|
|
585
|
+
return collectReachableSourceFiles(project.entryPointAbs).map((filePath) => {
|
|
586
|
+
const source = safeReadText(filePath);
|
|
587
|
+
return source ? {
|
|
588
|
+
file: toProjectPath(project.projectRootAbs, filePath),
|
|
589
|
+
imports: parseModuleSpecifiers(source)
|
|
590
|
+
} : null;
|
|
591
|
+
}).filter((entry) => entry !== null).filter((entry) => entry.imports.length > 0).sort((a, b) => a.file.localeCompare(b.file));
|
|
592
|
+
}
|
|
593
|
+
function schemaAuthReexportsGeneratedSource(source) {
|
|
594
|
+
return /(?:^|[^\S\n])(?:export|import)\b[^\n;]*\bfrom\s+['"][^'"]*schema-auth\.gen(?:\.tsx?)?['"]/m.test(source);
|
|
595
|
+
}
|
|
596
|
+
function resolveSchemaAuthGeneratedTarget(schemaAuthPathAbs, source) {
|
|
597
|
+
const match = source.match(/(?:export|import)\s+[^;\n]*\bfrom\s+["']([^"']*schema-auth\.gen(?:\.[cm]?[jt]sx?)?)["']/m);
|
|
598
|
+
if (!match) {
|
|
599
|
+
return resolve3(dirname3(schemaAuthPathAbs), "./generated/schema-auth.gen.ts");
|
|
600
|
+
}
|
|
601
|
+
return resolve3(dirname3(schemaAuthPathAbs), match[1]);
|
|
602
|
+
}
|
|
603
|
+
function classifySchemaSourceKind(pathValue) {
|
|
604
|
+
const normalized = pathValue.replace(/\\/g, "/");
|
|
605
|
+
if (normalized.endsWith("/auth-schema.ts"))
|
|
606
|
+
return "legacy-generated";
|
|
607
|
+
if (normalized.endsWith("/schema-auth.gen.ts") || normalized.endsWith("/generated/auth-schema.ts")) {
|
|
608
|
+
return "generated";
|
|
609
|
+
}
|
|
610
|
+
return "user";
|
|
611
|
+
}
|
|
612
|
+
function parsePgTableExports(source) {
|
|
613
|
+
const tables = [];
|
|
614
|
+
const pattern = /export\s+const\s+(\w+)\s*=\s*pgTable\s*\(\s*["']([^"']+)["']/g;
|
|
615
|
+
let match = pattern.exec(source);
|
|
616
|
+
while (match) {
|
|
617
|
+
tables.push({
|
|
618
|
+
exportName: match[1],
|
|
619
|
+
tableName: match[2]
|
|
620
|
+
});
|
|
621
|
+
match = pattern.exec(source);
|
|
622
|
+
}
|
|
623
|
+
return tables;
|
|
624
|
+
}
|
|
625
|
+
function dedupeOwners(owners) {
|
|
626
|
+
const seen = /* @__PURE__ */ new Set();
|
|
627
|
+
const result = [];
|
|
628
|
+
for (const owner of owners) {
|
|
629
|
+
const key = [owner.tableName, owner.publicOwnerPath, owner.implementationPath, owner.sourceKind].join("::");
|
|
630
|
+
if (seen.has(key))
|
|
631
|
+
continue;
|
|
632
|
+
seen.add(key);
|
|
633
|
+
result.push(owner);
|
|
634
|
+
}
|
|
635
|
+
return result;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// ../shared/dist/src/analyzer/shared/db-operation-inspector.js
|
|
639
|
+
import { basename as basename2, relative as relative2 } from "path";
|
|
640
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
641
|
+
var ALLOW_COMMENT = "gencow-allow-unsafe-db";
|
|
642
|
+
var SYSTEM_TABLE_PATTERN = /\b_(?:system|gencow)_[a-zA-Z0-9_]*\b/;
|
|
643
|
+
var UNSAFE_PATTERNS = [
|
|
644
|
+
{ type: "unsafe-db", pattern: /\b(?:ctx\.)?unsafeDb\b/ },
|
|
645
|
+
{ type: "raw-sql", pattern: /\brawSql\b|\bSQL\.unsafe\b|\bclient\.unsafe\b|(?:^|[^\w])\.unsafe\s*\(/ },
|
|
646
|
+
{ type: "system-table", pattern: SYSTEM_TABLE_PATTERN }
|
|
647
|
+
];
|
|
648
|
+
function collectDbOperations(project) {
|
|
649
|
+
const operations = collectUnsafeDbIssues(project).map((issue) => ({
|
|
650
|
+
file: issue.file,
|
|
651
|
+
line: issue.line,
|
|
652
|
+
operation: issue.operation,
|
|
653
|
+
visibility: issue.operation ? "public" : "protected",
|
|
654
|
+
allowCommentComplete: issue.allowlisted,
|
|
655
|
+
hazards: [
|
|
656
|
+
{
|
|
657
|
+
kind: issue.type,
|
|
658
|
+
referencedTables: extractReferencedTables(issue.snippet)
|
|
659
|
+
}
|
|
660
|
+
]
|
|
661
|
+
}));
|
|
662
|
+
for (const file of findSourceFiles(project.sourceBaseAbs)) {
|
|
663
|
+
const relPath = relative2(project.sourceBaseAbs, file);
|
|
664
|
+
if (!isSeedFile(relPath))
|
|
665
|
+
continue;
|
|
666
|
+
const content = safeReadText2(file);
|
|
667
|
+
if (content === null)
|
|
668
|
+
continue;
|
|
669
|
+
if (!UNSAFE_PATTERNS.some((unsafePattern) => unsafePattern.pattern.test(maskComments(content))))
|
|
670
|
+
continue;
|
|
671
|
+
operations.push({
|
|
672
|
+
file: toProjectPath(project.projectRootAbs, file),
|
|
673
|
+
line: 1,
|
|
674
|
+
operation: "mutation",
|
|
675
|
+
visibility: "seed",
|
|
676
|
+
allowCommentComplete: false,
|
|
677
|
+
hazards: [{ kind: "unsafe-db", referencedTables: [] }]
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
return operations;
|
|
681
|
+
}
|
|
682
|
+
function collectUnsafeDbIssues(project) {
|
|
683
|
+
const issues = [];
|
|
684
|
+
for (const file of findSourceFiles(project.sourceBaseAbs)) {
|
|
685
|
+
const content = safeReadText2(file);
|
|
686
|
+
if (content === null)
|
|
687
|
+
continue;
|
|
688
|
+
const relPath = relative2(project.sourceBaseAbs, file);
|
|
689
|
+
if (isSeedFile(relPath))
|
|
690
|
+
continue;
|
|
691
|
+
const operations = findPublicOperationRanges(content);
|
|
692
|
+
const executableLines = maskComments(content).split("\n");
|
|
693
|
+
const originalLines = content.split("\n");
|
|
694
|
+
for (let index = 0; index < executableLines.length; index += 1) {
|
|
695
|
+
const executableLine = executableLines[index];
|
|
696
|
+
if (!executableLine?.trim())
|
|
697
|
+
continue;
|
|
698
|
+
for (const unsafePattern of UNSAFE_PATTERNS) {
|
|
699
|
+
if (!unsafePattern.pattern.test(executableLine))
|
|
700
|
+
continue;
|
|
701
|
+
const line = index + 1;
|
|
702
|
+
const operation = operations.find((range) => range.startLine <= line && line <= range.endLine);
|
|
703
|
+
issues.push({
|
|
704
|
+
file: toProjectPath(project.projectRootAbs, file),
|
|
705
|
+
line,
|
|
706
|
+
snippet: originalLines[index].trim().slice(0, 160),
|
|
707
|
+
type: unsafePattern.type,
|
|
708
|
+
operation: operation?.kind,
|
|
709
|
+
allowlisted: hasCompleteAllowComment(originalLines, index)
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return issues;
|
|
715
|
+
}
|
|
716
|
+
function safeReadText2(file) {
|
|
717
|
+
try {
|
|
718
|
+
return readFileSync3(file, "utf-8");
|
|
719
|
+
} catch {
|
|
720
|
+
return null;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
function findPublicOperationRanges(content) {
|
|
724
|
+
const masked = maskCommentsAndStrings(content);
|
|
725
|
+
const ranges = [];
|
|
726
|
+
const operationPattern = /\b(query|mutation|httpAction)\s*\(/g;
|
|
727
|
+
let match;
|
|
728
|
+
while ((match = operationPattern.exec(masked)) !== null) {
|
|
729
|
+
const openParen = masked.indexOf("(", match.index);
|
|
730
|
+
const closeParen = findMatchingParen(masked, openParen);
|
|
731
|
+
if (closeParen === -1)
|
|
732
|
+
continue;
|
|
733
|
+
const block = masked.slice(match.index, closeParen + 1);
|
|
734
|
+
if (!/\bpublic\s*:\s*true\b/.test(block))
|
|
735
|
+
continue;
|
|
736
|
+
ranges.push({
|
|
737
|
+
kind: match[1],
|
|
738
|
+
startLine: lineNumberAt(content, match.index),
|
|
739
|
+
endLine: lineNumberAt(content, closeParen)
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
const httpRoutePattern = /\bhttpRoute\s*\.\s*(get|post|put|delete|patch)\b/g;
|
|
743
|
+
let cursor = 0;
|
|
744
|
+
while ((match = httpRoutePattern.exec(masked)) !== null) {
|
|
745
|
+
if (match.index < cursor)
|
|
746
|
+
continue;
|
|
747
|
+
const handlerIdx = masked.indexOf(".handler", match.index);
|
|
748
|
+
if (handlerIdx === -1)
|
|
749
|
+
continue;
|
|
750
|
+
const openParen = masked.indexOf("(", handlerIdx);
|
|
751
|
+
if (openParen === -1)
|
|
752
|
+
continue;
|
|
753
|
+
const closeParen = findMatchingParen(masked, openParen);
|
|
754
|
+
if (closeParen === -1)
|
|
755
|
+
continue;
|
|
756
|
+
const block = masked.slice(match.index, closeParen + 1);
|
|
757
|
+
cursor = closeParen + 1;
|
|
758
|
+
if (!/\.allowAnonymous\s*\(\s*\)/.test(block))
|
|
759
|
+
continue;
|
|
760
|
+
ranges.push({
|
|
761
|
+
kind: "httpRoute",
|
|
762
|
+
startLine: lineNumberAt(content, match.index),
|
|
763
|
+
endLine: lineNumberAt(content, closeParen)
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
return ranges;
|
|
767
|
+
}
|
|
768
|
+
function findMatchingParen(content, openParen) {
|
|
769
|
+
let depth = 0;
|
|
770
|
+
for (let index = openParen; index < content.length; index += 1) {
|
|
771
|
+
const ch = content[index];
|
|
772
|
+
if (ch === "(")
|
|
773
|
+
depth += 1;
|
|
774
|
+
if (ch === ")") {
|
|
775
|
+
depth -= 1;
|
|
776
|
+
if (depth === 0)
|
|
777
|
+
return index;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
return -1;
|
|
781
|
+
}
|
|
782
|
+
function lineNumberAt(content, index) {
|
|
783
|
+
let line = 1;
|
|
784
|
+
for (let cursor = 0; cursor < index; cursor += 1) {
|
|
785
|
+
if (content[cursor] === "\n")
|
|
786
|
+
line += 1;
|
|
787
|
+
}
|
|
788
|
+
return line;
|
|
789
|
+
}
|
|
790
|
+
function hasCompleteAllowComment(lines, lineIndex) {
|
|
791
|
+
const start = Math.max(0, lineIndex - 4);
|
|
792
|
+
const nearby = lines.slice(start, lineIndex + 1).join("\n");
|
|
793
|
+
return nearby.includes(ALLOW_COMMENT) && /\breason\s*:/i.test(nearby) && /\bscope\s*:/i.test(nearby) && /\bowner\s*:/i.test(nearby) && /\btest\s*:/i.test(nearby);
|
|
794
|
+
}
|
|
795
|
+
function isSeedFile(file) {
|
|
796
|
+
return basename2(file) === "seed.ts" || basename2(file) === "seed.js";
|
|
797
|
+
}
|
|
798
|
+
function maskComments(content) {
|
|
799
|
+
let output = "";
|
|
800
|
+
let inBlock = false;
|
|
801
|
+
for (let i = 0; i < content.length; i += 1) {
|
|
802
|
+
const ch = content[i];
|
|
803
|
+
const next = content[i + 1];
|
|
804
|
+
if (inBlock) {
|
|
805
|
+
if (ch === "*" && next === "/") {
|
|
806
|
+
output += " ";
|
|
807
|
+
i += 1;
|
|
808
|
+
inBlock = false;
|
|
809
|
+
} else {
|
|
810
|
+
output += ch === "\n" ? "\n" : " ";
|
|
811
|
+
}
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
if (ch === "/" && next === "*") {
|
|
815
|
+
output += " ";
|
|
816
|
+
i += 1;
|
|
817
|
+
inBlock = true;
|
|
818
|
+
continue;
|
|
819
|
+
}
|
|
820
|
+
if (ch === "/" && next === "/") {
|
|
821
|
+
while (i < content.length && content[i] !== "\n") {
|
|
822
|
+
output += " ";
|
|
823
|
+
i += 1;
|
|
824
|
+
}
|
|
825
|
+
if (i < content.length)
|
|
826
|
+
output += "\n";
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
output += ch;
|
|
830
|
+
}
|
|
831
|
+
return output;
|
|
832
|
+
}
|
|
833
|
+
function maskCommentsAndStrings(content) {
|
|
834
|
+
const withoutComments = maskComments(content);
|
|
835
|
+
let output = "";
|
|
836
|
+
let quote = null;
|
|
837
|
+
let escaped = false;
|
|
838
|
+
for (const ch of withoutComments) {
|
|
839
|
+
if (quote) {
|
|
840
|
+
output += ch === "\n" ? "\n" : " ";
|
|
841
|
+
if (!escaped && ch === quote)
|
|
842
|
+
quote = null;
|
|
843
|
+
escaped = !escaped && ch === "\\";
|
|
844
|
+
if (ch !== "\\")
|
|
845
|
+
escaped = false;
|
|
846
|
+
continue;
|
|
847
|
+
}
|
|
848
|
+
if (ch === "'" || ch === '"' || ch === "`") {
|
|
849
|
+
quote = ch;
|
|
850
|
+
output += " ";
|
|
851
|
+
continue;
|
|
852
|
+
}
|
|
853
|
+
output += ch;
|
|
854
|
+
}
|
|
855
|
+
return output;
|
|
856
|
+
}
|
|
857
|
+
function extractReferencedTables(snippet) {
|
|
858
|
+
const tables = /* @__PURE__ */ new Set();
|
|
859
|
+
for (const match of snippet.matchAll(/\b_(?:system|gencow)_[a-zA-Z0-9_]*\b/g)) {
|
|
860
|
+
tables.add(match[0]);
|
|
861
|
+
}
|
|
862
|
+
for (const match of snippet.matchAll(/\.from\(\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\)/g)) {
|
|
863
|
+
tables.add(match[1]);
|
|
864
|
+
}
|
|
865
|
+
for (const match of snippet.matchAll(/\bfrom\s+([a-zA-Z_][a-zA-Z0-9_]*)\b/gi)) {
|
|
866
|
+
tables.add(match[1]);
|
|
867
|
+
}
|
|
868
|
+
return [...tables];
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// ../shared/dist/src/analyzer/consumers/auditor/source-auditor-shared.js
|
|
872
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
873
|
+
var FORBIDDEN_MODULES = /* @__PURE__ */ new Set([
|
|
874
|
+
"child_process",
|
|
875
|
+
"node:child_process",
|
|
876
|
+
"dgram",
|
|
877
|
+
"node:dgram",
|
|
878
|
+
"os",
|
|
879
|
+
"node:os",
|
|
880
|
+
"cluster",
|
|
881
|
+
"node:cluster",
|
|
882
|
+
"worker_threads",
|
|
883
|
+
"node:worker_threads",
|
|
884
|
+
"v8",
|
|
885
|
+
"node:v8",
|
|
886
|
+
"vm",
|
|
887
|
+
"node:vm"
|
|
888
|
+
]);
|
|
889
|
+
var ALLOWED_NODE_MODULES = /* @__PURE__ */ new Set([
|
|
890
|
+
"node:crypto",
|
|
891
|
+
"node:path",
|
|
892
|
+
"node:url",
|
|
893
|
+
"node:buffer",
|
|
894
|
+
"node:stream",
|
|
895
|
+
"node:events",
|
|
896
|
+
"node:util",
|
|
897
|
+
"node:assert",
|
|
898
|
+
"node:querystring",
|
|
899
|
+
"node:string_decoder",
|
|
900
|
+
"node:timers",
|
|
901
|
+
"node:timers/promises",
|
|
902
|
+
"node:zlib",
|
|
903
|
+
"node:http",
|
|
904
|
+
"node:https",
|
|
905
|
+
"node:http2",
|
|
906
|
+
"node:net",
|
|
907
|
+
"node:tls",
|
|
908
|
+
"node:readline",
|
|
909
|
+
"crypto",
|
|
910
|
+
"path",
|
|
911
|
+
"url",
|
|
912
|
+
"buffer",
|
|
913
|
+
"stream",
|
|
914
|
+
"events",
|
|
915
|
+
"util",
|
|
916
|
+
"assert",
|
|
917
|
+
"querystring",
|
|
918
|
+
"string_decoder",
|
|
919
|
+
"timers",
|
|
920
|
+
"zlib",
|
|
921
|
+
"http",
|
|
922
|
+
"https",
|
|
923
|
+
"http2",
|
|
924
|
+
"net",
|
|
925
|
+
"tls",
|
|
926
|
+
"readline"
|
|
927
|
+
]);
|
|
928
|
+
var WORKFLOW_SHADOW_FILENAMES = /* @__PURE__ */ new Set(["workflow.ts", "workflow.tsx", "workflow.js", "workflow.jsx"]);
|
|
929
|
+
var WORKFLOW_SHADOW_RUNTIME_MARKERS = [
|
|
930
|
+
"__gencow_workflowRegistry",
|
|
931
|
+
"WORKFLOW_RESUME_ACTION_PREFIX",
|
|
932
|
+
"registerWorkflowsApi(",
|
|
933
|
+
'query("workflows.get"',
|
|
934
|
+
'query("workflows.list"',
|
|
935
|
+
'mutation("workflows.signal"',
|
|
936
|
+
'mutation("workflows.cancel"',
|
|
937
|
+
"getWorkflowResumeActionName("
|
|
938
|
+
];
|
|
939
|
+
var WORKFLOW_RELATIVE_IMPORT_PATTERN = /from\s+["'](?:\.\.\/|\.\/)workflow(?:\.(?:[cm]?[jt]sx?))?["']/;
|
|
940
|
+
var SELF_FETCH_PATTERN = /\/api\/(query|mutation)/;
|
|
941
|
+
var UNSAFE_DB_ALLOW_COMMENT = "gencow-allow-unsafe-db";
|
|
942
|
+
function lineForIndex(content, index) {
|
|
943
|
+
return content.slice(0, index).split("\n").length;
|
|
944
|
+
}
|
|
945
|
+
function snippetFor(content, index) {
|
|
946
|
+
return (content.slice(index).split("\n")[0] ?? "").trim().slice(0, 180);
|
|
947
|
+
}
|
|
948
|
+
function safeReadText3(file) {
|
|
949
|
+
try {
|
|
950
|
+
return readFileSync4(file, "utf8");
|
|
951
|
+
} catch {
|
|
952
|
+
return null;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
function toAnalyzerReportPath(project, file) {
|
|
956
|
+
return toProjectPath(project.projectRootAbs, file);
|
|
957
|
+
}
|
|
958
|
+
function listAuditedSourceFiles(project) {
|
|
959
|
+
const isFileStyleRoot = project.sourceBaseAbs !== project.functionsDirAbs || project.entryPointAbs === project.functionsDirAbs;
|
|
960
|
+
if (isFileStyleRoot && project.sourceBaseAbs === project.projectRootAbs && project.sourceFilesAbs.length > 0) {
|
|
961
|
+
return project.sourceFilesAbs;
|
|
962
|
+
}
|
|
963
|
+
return findSourceFiles(project.sourceBaseAbs);
|
|
964
|
+
}
|
|
965
|
+
var DATA_ISOLATION_SYSTEM_TABLES = /* @__PURE__ */ new Set([
|
|
966
|
+
"user",
|
|
967
|
+
"session",
|
|
968
|
+
"account",
|
|
969
|
+
"verification",
|
|
970
|
+
"_system_files",
|
|
971
|
+
"_system_settings",
|
|
972
|
+
"usage_snapshots",
|
|
973
|
+
"credits"
|
|
974
|
+
]);
|
|
975
|
+
function findMatchingParen2(content, openParen) {
|
|
976
|
+
let depth = 0;
|
|
977
|
+
for (let index = openParen; index < content.length; index += 1) {
|
|
978
|
+
const ch = content[index];
|
|
979
|
+
if (ch === "(")
|
|
980
|
+
depth += 1;
|
|
981
|
+
if (ch === ")") {
|
|
982
|
+
depth -= 1;
|
|
983
|
+
if (depth === 0)
|
|
984
|
+
return index;
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
return -1;
|
|
988
|
+
}
|
|
989
|
+
function parsePgTableDefinitions(content) {
|
|
990
|
+
const tables = [];
|
|
991
|
+
const pattern = /export\s+const\s+\w+\s*=\s*pgTable\s*\(/g;
|
|
992
|
+
let match;
|
|
993
|
+
while ((match = pattern.exec(content)) !== null) {
|
|
994
|
+
const openParen = content.indexOf("(", match.index);
|
|
995
|
+
if (openParen === -1)
|
|
996
|
+
continue;
|
|
997
|
+
const closeParen = findMatchingParen2(content, openParen);
|
|
998
|
+
if (closeParen === -1)
|
|
999
|
+
continue;
|
|
1000
|
+
const declaration = content.slice(match.index, closeParen + 1);
|
|
1001
|
+
const tableNameMatch = declaration.match(/pgTable\s*\(\s*["']([^"']+)["']/);
|
|
1002
|
+
const columnsMatch = declaration.match(/pgTable\s*\(\s*["'][^"']+["']\s*,\s*\{([\s\S]*?)\}\s*(?:,|\))/);
|
|
1003
|
+
if (!tableNameMatch)
|
|
1004
|
+
continue;
|
|
1005
|
+
tables.push({
|
|
1006
|
+
tableName: tableNameMatch[1],
|
|
1007
|
+
columnsBody: columnsMatch?.[1] ?? "",
|
|
1008
|
+
declaration
|
|
1009
|
+
});
|
|
1010
|
+
pattern.lastIndex = closeParen + 1;
|
|
1011
|
+
}
|
|
1012
|
+
return tables;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// ../shared/dist/src/analyzer/consumers/auditor/source-auditor.js
|
|
1016
|
+
function analyzeModuleImportEntries(entries) {
|
|
1017
|
+
const violations = [];
|
|
1018
|
+
for (const entry of entries) {
|
|
1019
|
+
for (const moduleName of entry.imports) {
|
|
1020
|
+
if (moduleName.startsWith("node:") && !ALLOWED_NODE_MODULES.has(moduleName)) {
|
|
1021
|
+
violations.push({ module: moduleName, importedFrom: entry.file });
|
|
1022
|
+
continue;
|
|
1023
|
+
}
|
|
1024
|
+
if (FORBIDDEN_MODULES.has(moduleName)) {
|
|
1025
|
+
violations.push({ module: moduleName, importedFrom: entry.file });
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
return { passed: violations.length === 0, violations };
|
|
1030
|
+
}
|
|
1031
|
+
function describeAnalyzerFunctionsLabel(entryPoint) {
|
|
1032
|
+
const normalized = entryPoint.replace(/\\/g, "/");
|
|
1033
|
+
const fileName = normalized.split("/").pop() ?? normalized;
|
|
1034
|
+
if (/^index\.[cm]?[jt]sx?$/.test(fileName)) {
|
|
1035
|
+
return `${basename3(dirname4(normalized))}/`;
|
|
1036
|
+
}
|
|
1037
|
+
return extname(fileName) ? fileName : `${fileName}/`;
|
|
1038
|
+
}
|
|
1039
|
+
function isGeneratedFrontendClientPath(project, file) {
|
|
1040
|
+
if (project.clientCodegenDirAbs === null)
|
|
1041
|
+
return false;
|
|
1042
|
+
const normalizedFile = resolve4(file).replace(/\\/g, "/");
|
|
1043
|
+
const normalizedClientOutDir = project.clientCodegenDirAbs.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
1044
|
+
return normalizedFile === normalizedClientOutDir || normalizedFile.startsWith(`${normalizedClientOutDir}/`);
|
|
1045
|
+
}
|
|
1046
|
+
function printAnalyzerModuleAuditReport(result, entryPoint) {
|
|
1047
|
+
if (result.passed) {
|
|
1048
|
+
console.log("[auditor] \u2705 Module audit passed \u2014 no forbidden APIs detected");
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
console.error(`
|
|
1052
|
+
\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
|
|
1053
|
+
\u2551 \u26D4 GENCOW AUDIT FAILED \u2014 Production Constraint Violation \u2551
|
|
1054
|
+
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D`);
|
|
1055
|
+
console.error(`
|
|
1056
|
+
Functions: ${entryPoint}`);
|
|
1057
|
+
console.error("\n The following modules are BLOCKED in production (Firecracker microVM)");
|
|
1058
|
+
console.error(` but are used in your ${describeAnalyzerFunctionsLabel(entryPoint)} functions:
|
|
1059
|
+
`);
|
|
1060
|
+
for (const violation of result.violations) {
|
|
1061
|
+
console.error(` \u2717 import "${violation.module}"`);
|
|
1062
|
+
console.error(` in ${violation.importedFrom}`);
|
|
1063
|
+
}
|
|
1064
|
+
console.error("\n Fix: Replace direct module access with ctx API:");
|
|
1065
|
+
console.error(" ctx.db \u2014 database queries (Drizzle)");
|
|
1066
|
+
console.error(" ctx.storage \u2014 file storage");
|
|
1067
|
+
console.error(" ctx.scheduler \u2014 background jobs");
|
|
1068
|
+
console.error(" ctx.auth \u2014 authentication\n");
|
|
1069
|
+
}
|
|
1070
|
+
function auditAnalyzerSchemaPatterns(project) {
|
|
1071
|
+
const schemaPaths = [...new Set(project.configuredSchemaPathsAbs)].filter((schemaPath) => existsSync4(schemaPath));
|
|
1072
|
+
if (schemaPaths.length === 0) {
|
|
1073
|
+
return { fileName: null, warnings: [] };
|
|
1074
|
+
}
|
|
1075
|
+
const warnings = [];
|
|
1076
|
+
const auditedSchemaPaths = schemaPaths.filter((schemaPath) => {
|
|
1077
|
+
const fileName2 = basename3(schemaPath);
|
|
1078
|
+
return fileName2 !== "auth-schema.ts" && fileName2 !== "auth-schema.js" && fileName2 !== "schema-auth.ts" && fileName2 !== "schema-auth.js";
|
|
1079
|
+
});
|
|
1080
|
+
const includeFilePrefix = auditedSchemaPaths.length > 1;
|
|
1081
|
+
for (const schemaPath of auditedSchemaPaths) {
|
|
1082
|
+
const content = safeReadText3(schemaPath);
|
|
1083
|
+
if (content === null)
|
|
1084
|
+
continue;
|
|
1085
|
+
const tableRegex = /export\s+const\s+(\w+)\s*=\s*pgTable\s*\(\s*"([^"]+)"\s*,\s*\{([^}]+(?:\{[^}]*\}[^}]*)*)\}/g;
|
|
1086
|
+
const systemTables = /* @__PURE__ */ new Set([
|
|
1087
|
+
"user",
|
|
1088
|
+
"session",
|
|
1089
|
+
"account",
|
|
1090
|
+
"verification",
|
|
1091
|
+
"_system_files",
|
|
1092
|
+
"_system_settings",
|
|
1093
|
+
"usage_snapshots",
|
|
1094
|
+
"credits"
|
|
1095
|
+
]);
|
|
1096
|
+
const warningPrefix = includeFilePrefix ? `[${basename3(schemaPath)}] ` : "";
|
|
1097
|
+
let match;
|
|
1098
|
+
while ((match = tableRegex.exec(content)) !== null) {
|
|
1099
|
+
const [, , tableName, body] = match;
|
|
1100
|
+
if (systemTables.has(tableName))
|
|
1101
|
+
continue;
|
|
1102
|
+
const hasUserId = /user_id|userId/.test(body);
|
|
1103
|
+
if (!hasUserId) {
|
|
1104
|
+
warnings.push(`${warningPrefix}\u26A0\uFE0F "${tableName}" \u2014 userId \uCEEC\uB7FC \uC5C6\uC74C \u2192 \uC0AC\uC6A9\uC790\uBCC4 \uB370\uC774\uD130 \uACA9\uB9AC \uBD88\uAC00`);
|
|
1105
|
+
continue;
|
|
1106
|
+
}
|
|
1107
|
+
if (!/\.references\s*\(/.test(body)) {
|
|
1108
|
+
warnings.push(`${warningPrefix}\u26A0\uFE0F "${tableName}" \u2014 userId\uC5D0 .references() \uC5C6\uC74C \u2192 FK \uBB34\uACB0\uC131 \uBBF8\uBCF4\uC7A5`);
|
|
1109
|
+
}
|
|
1110
|
+
const userIdLine = body.split("\n").find((line) => /user_id|userId/.test(line)) || "";
|
|
1111
|
+
if (!userIdLine.includes("notNull")) {
|
|
1112
|
+
warnings.push(`${warningPrefix}\u{1F4A1} "${tableName}" \u2014 userId\uAC00 nullable \u2192 \uC18C\uC720\uC790 \uC5C6\uB294 \uB370\uC774\uD130 \uBC1C\uC0DD \uAC00\uB2A5`);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
const fileName = auditedSchemaPaths.length === 0 ? basename3(schemaPaths[0] ?? project.rootSchemaPathAbs) : auditedSchemaPaths.length === 1 ? basename3(auditedSchemaPaths[0]) : `${auditedSchemaPaths.length} schema files`;
|
|
1117
|
+
return { fileName, warnings };
|
|
1118
|
+
}
|
|
1119
|
+
function printAnalyzerSchemaPatternReport(report) {
|
|
1120
|
+
if (!report.fileName || report.warnings.length === 0)
|
|
1121
|
+
return;
|
|
1122
|
+
console.log(`
|
|
1123
|
+
[auditor] \u{1F50D} \uC2A4\uD0A4\uB9C8 \uBCF4\uC548 \uD328\uD134 \uC810\uAC80 (${report.fileName}):`);
|
|
1124
|
+
for (const warning of report.warnings) {
|
|
1125
|
+
console.log(`[auditor] ${warning}`);
|
|
1126
|
+
}
|
|
1127
|
+
console.log("[auditor] \u2192 \uC801\uC808\uD55C \uD589 \uC218\uC900 \uBCF4\uC548(RLS) \uC815\uCC45\uC744 \uCD94\uAC00\uD558\uACE0, \uAC00\uB2A5\uD55C \uACBD\uC6B0 \uC18C\uC720\uC790 \uCEEC\uB7FC\uC774 null\uC744 \uD5C8\uC6A9\uD558\uC9C0 \uC54A\uB3C4\uB85D \uC124\uC815\uD55C \uB4A4 \uC678\uB798 \uD0A4\uB97C \uCD94\uAC00\uD558\uC138\uC694.");
|
|
1128
|
+
console.log("");
|
|
1129
|
+
}
|
|
1130
|
+
function auditAnalyzerSelfFetch(project, sourceFiles) {
|
|
1131
|
+
const usages = [];
|
|
1132
|
+
for (const file of sourceFiles ?? listAuditedSourceFiles(project)) {
|
|
1133
|
+
const content = safeReadText3(file);
|
|
1134
|
+
if (content === null)
|
|
1135
|
+
continue;
|
|
1136
|
+
const lines = content.split("\n");
|
|
1137
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
1138
|
+
const line = lines[index] ?? "";
|
|
1139
|
+
const trimmed = line.trim();
|
|
1140
|
+
if (trimmed.startsWith("//") || trimmed.startsWith("*"))
|
|
1141
|
+
continue;
|
|
1142
|
+
if (line.includes("fetch") && SELF_FETCH_PATTERN.test(line)) {
|
|
1143
|
+
usages.push({
|
|
1144
|
+
file: toAnalyzerReportPath(project, file),
|
|
1145
|
+
line: index + 1,
|
|
1146
|
+
snippet: trimmed
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
return { usages };
|
|
1152
|
+
}
|
|
1153
|
+
function printAnalyzerSelfFetchReport(result) {
|
|
1154
|
+
if (result.usages.length === 0)
|
|
1155
|
+
return;
|
|
1156
|
+
console.log(`
|
|
1157
|
+
[auditor] \u26A0\uFE0F Self-fetch detected in ${result.usages.length} location(s):`);
|
|
1158
|
+
for (const usage of result.usages) {
|
|
1159
|
+
console.log(`[auditor] ${usage.file}:${usage.line} \u2192 ${usage.snippet}`);
|
|
1160
|
+
}
|
|
1161
|
+
console.log("[auditor] \u2192 \uAC19\uC740 \uC11C\uBC84\uC758 \uD568\uC218\uB294 \uC9C1\uC811 import\uD558\uC138\uC694:");
|
|
1162
|
+
console.log('[auditor] import { fetchNews } from "./crawler";');
|
|
1163
|
+
console.log("[auditor] const result = await fetchNews.handler(ctx, { keyword });");
|
|
1164
|
+
console.log('[auditor] \u2192 fetch("/api/mutation") \uD328\uD134\uC740 \uBD88\uD544\uC694\uD55C \uB124\uD2B8\uC6CC\uD06C \uC6B0\uD68C\uC785\uB2C8\uB2E4.\n');
|
|
1165
|
+
}
|
|
1166
|
+
function auditAnalyzerDataIsolation(project) {
|
|
1167
|
+
const tablesMissingAccessControl = [];
|
|
1168
|
+
const schemaPaths = [...new Set(project.configuredSchemaPathsAbs)].filter((schemaPath) => existsSync4(schemaPath));
|
|
1169
|
+
const unsafeDb = auditAnalyzerUnsafeDbUsage(project);
|
|
1170
|
+
for (const schemaPath of schemaPaths) {
|
|
1171
|
+
const content = safeReadText3(schemaPath);
|
|
1172
|
+
if (content === null)
|
|
1173
|
+
continue;
|
|
1174
|
+
for (const table of parsePgTableDefinitions(content)) {
|
|
1175
|
+
if (DATA_ISOLATION_SYSTEM_TABLES.has(table.tableName))
|
|
1176
|
+
continue;
|
|
1177
|
+
if (!/user_id|userId/.test(table.columnsBody))
|
|
1178
|
+
continue;
|
|
1179
|
+
if (/\bownerRls\s*\(|\btableRls\s*\(|\bpgPolicy\s*\(/.test(table.declaration))
|
|
1180
|
+
continue;
|
|
1181
|
+
tablesMissingAccessControl.push({
|
|
1182
|
+
file: toAnalyzerReportPath(project, schemaPath),
|
|
1183
|
+
tableName: table.tableName
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
return {
|
|
1188
|
+
passed: tablesMissingAccessControl.length === 0 && !unsafeDb.blocked,
|
|
1189
|
+
tablesMissingAccessControl,
|
|
1190
|
+
unsafeDbUsages: unsafeDb.issues.length,
|
|
1191
|
+
blockedUnsafeDbUsages: unsafeDb.issues.filter((issue) => issue.blocked).length
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
function auditAnalyzerFrontendAntiPatterns(project) {
|
|
1195
|
+
const srcDir = resolve4(project.projectRootAbs, "src");
|
|
1196
|
+
const issues = [];
|
|
1197
|
+
if (!existsSync4(srcDir)) {
|
|
1198
|
+
return { issues };
|
|
1199
|
+
}
|
|
1200
|
+
const suspectNames = /* @__PURE__ */ new Set([
|
|
1201
|
+
"api.ts",
|
|
1202
|
+
"api.tsx",
|
|
1203
|
+
"api-client.ts",
|
|
1204
|
+
"api-client.tsx",
|
|
1205
|
+
"rpc.ts",
|
|
1206
|
+
"rpc.tsx",
|
|
1207
|
+
"client.ts",
|
|
1208
|
+
"client.tsx"
|
|
1209
|
+
]);
|
|
1210
|
+
for (const file of findSourceFiles(srcDir)) {
|
|
1211
|
+
const relPath = toAnalyzerReportPath(project, file);
|
|
1212
|
+
if (isGeneratedFrontendClientPath(project, file))
|
|
1213
|
+
continue;
|
|
1214
|
+
if (!suspectNames.has(basename3(file)))
|
|
1215
|
+
continue;
|
|
1216
|
+
const content = safeReadText3(file);
|
|
1217
|
+
if (content === null)
|
|
1218
|
+
continue;
|
|
1219
|
+
if (SELF_FETCH_PATTERN.test(content)) {
|
|
1220
|
+
issues.push({
|
|
1221
|
+
file: relPath,
|
|
1222
|
+
reason: 'fetch("/api/query" \uB610\uB294 "/api/mutation") \uC9C1\uC811 \uD638\uCD9C \uAC10\uC9C0 \u2014 \uC0DD\uC131\uB41C API \uC815\uC758\uC640 \uC774 \uD504\uB85C\uC81D\uD2B8\uC5D0\uC11C \uC120\uD0DD\uD55C React \uB610\uB294 TanStack Query \uC5B4\uB311\uD130\uB97C \uC0AC\uC6A9\uD558\uC138\uC694'
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
return { issues };
|
|
1227
|
+
}
|
|
1228
|
+
function printAnalyzerFrontendAntiPatternReport(result) {
|
|
1229
|
+
if (result.issues.length === 0)
|
|
1230
|
+
return;
|
|
1231
|
+
console.log("\n[auditor] \u26A0\uFE0F Custom API client detected:");
|
|
1232
|
+
for (const issue of result.issues) {
|
|
1233
|
+
console.log(`[auditor] ${issue.file} \u2014 ${issue.reason}`);
|
|
1234
|
+
}
|
|
1235
|
+
console.log("[auditor] \u2192 generated API client\uC640 useQuery/useMutation\uC744 \uC0AC\uC6A9\uD558\uC138\uC694");
|
|
1236
|
+
console.log("[auditor] \u2192 /api/query \uB610\uB294 /api/mutation \uC9C1\uC811 \uD638\uCD9C\uC740 \uC0DD\uC131\uB41C API \uC815\uC758\uC640 \uC120\uD0DD\uD55C \uC5B4\uB311\uD130\uB85C \uBC14\uAFB8\uC138\uC694: @gencow/react \uB610\uB294 @gencow/tanstack-query. \uAC19\uC740 \uB370\uC774\uD130\uC5D0 \uB450 \uC5B4\uB311\uD130\uB97C \uD568\uAED8 \uC0AC\uC6A9\uD558\uC9C0 \uB9C8\uC138\uC694.\n");
|
|
1237
|
+
}
|
|
1238
|
+
function auditAnalyzerEmbeddingProfiles(project, sourceFileOverride) {
|
|
1239
|
+
const issues = [];
|
|
1240
|
+
const profileRegex = /export\s+const\s+([A-Z0-9_]+EMBEDDING_PROFILE)\s*(?::\s*EmbeddingProfile)?\s*=\s*\{[\s\S]*?dimensions:\s*(\d+)/g;
|
|
1241
|
+
const vectorRegex = /vector\(\s*["']embedding["']\s*,\s*\{\s*dimensions:\s*([^}]+)\}\s*\)/g;
|
|
1242
|
+
const factoryRegex = /create(Rag|Memory)\s*\(\s*\{([\s\S]*?)\}\s*\)/g;
|
|
1243
|
+
const featureProfileOptIn = /* @__PURE__ */ new Map();
|
|
1244
|
+
const sourceFiles = sourceFileOverride ?? listAuditedSourceFiles(project);
|
|
1245
|
+
for (const file of sourceFiles) {
|
|
1246
|
+
const content = safeReadText3(file);
|
|
1247
|
+
if (content === null)
|
|
1248
|
+
continue;
|
|
1249
|
+
if (/\bRAG_EMBEDDING_PROFILE\b|\bembeddingProfile\b/.test(content)) {
|
|
1250
|
+
featureProfileOptIn.set("Rag", true);
|
|
1251
|
+
}
|
|
1252
|
+
if (/\bMEMORY_EMBEDDING_PROFILE\b|\bembeddingProfile\b/.test(content)) {
|
|
1253
|
+
featureProfileOptIn.set("Memory", true);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
for (const file of sourceFiles) {
|
|
1257
|
+
const relPath = toAnalyzerReportPath(project, file);
|
|
1258
|
+
const content = safeReadText3(file);
|
|
1259
|
+
if (content === null)
|
|
1260
|
+
continue;
|
|
1261
|
+
for (const match of content.matchAll(factoryRegex)) {
|
|
1262
|
+
const [, featureName, body] = match;
|
|
1263
|
+
const hasEmbeddingModel = /\bembeddingModel\b/.test(body);
|
|
1264
|
+
const hasEmbeddingProfile = /\bembeddingProfile\b/.test(body);
|
|
1265
|
+
if (!hasEmbeddingModel && !hasEmbeddingProfile)
|
|
1266
|
+
continue;
|
|
1267
|
+
const index = match.index ?? 0;
|
|
1268
|
+
if (hasEmbeddingModel && hasEmbeddingProfile) {
|
|
1269
|
+
issues.push({
|
|
1270
|
+
file: relPath,
|
|
1271
|
+
line: lineForIndex(content, index),
|
|
1272
|
+
snippet: snippetFor(content, index),
|
|
1273
|
+
type: "dual-source",
|
|
1274
|
+
severity: "error",
|
|
1275
|
+
reason: `create${featureName}() must not receive both embeddingModel and embeddingProfile.`
|
|
1276
|
+
});
|
|
1277
|
+
} else if (hasEmbeddingModel && featureProfileOptIn.get(featureName)) {
|
|
1278
|
+
issues.push({
|
|
1279
|
+
file: relPath,
|
|
1280
|
+
line: lineForIndex(content, index),
|
|
1281
|
+
snippet: snippetFor(content, index),
|
|
1282
|
+
type: "legacy-model-only",
|
|
1283
|
+
severity: "warning",
|
|
1284
|
+
reason: `create${featureName}() still uses embeddingModel-only composition after embeddingProfile adoption was detected; prefer embeddingProfile.`
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
const profiles = [...content.matchAll(profileRegex)].map((match) => ({
|
|
1289
|
+
name: match[1] ?? "EMBEDDING_PROFILE",
|
|
1290
|
+
dimensions: Number(match[2]),
|
|
1291
|
+
index: match.index ?? 0
|
|
1292
|
+
}));
|
|
1293
|
+
if (profiles.length === 0)
|
|
1294
|
+
continue;
|
|
1295
|
+
const firstProfile = profiles[0];
|
|
1296
|
+
for (const match of content.matchAll(vectorRegex)) {
|
|
1297
|
+
const raw = (match[1] ?? "").trim();
|
|
1298
|
+
const index = match.index ?? 0;
|
|
1299
|
+
if (/^\d+$/.test(raw)) {
|
|
1300
|
+
const literal = Number(raw);
|
|
1301
|
+
if (literal !== firstProfile.dimensions) {
|
|
1302
|
+
issues.push({
|
|
1303
|
+
file: relPath,
|
|
1304
|
+
line: lineForIndex(content, index),
|
|
1305
|
+
snippet: snippetFor(content, index),
|
|
1306
|
+
type: "schema-profile-mismatch",
|
|
1307
|
+
severity: "error",
|
|
1308
|
+
reason: `Schema vector dimension ${literal} does not match ${firstProfile.name}.dimensions ${firstProfile.dimensions}.`
|
|
1309
|
+
});
|
|
1310
|
+
} else {
|
|
1311
|
+
issues.push({
|
|
1312
|
+
file: relPath,
|
|
1313
|
+
line: lineForIndex(content, index),
|
|
1314
|
+
snippet: snippetFor(content, index),
|
|
1315
|
+
type: "raw-dimension-literal",
|
|
1316
|
+
severity: "warning",
|
|
1317
|
+
reason: `Raw vector dimension literal ${literal} duplicates ${firstProfile.name}.dimensions; prefer the profile constant.`
|
|
1318
|
+
});
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
return { issues };
|
|
1324
|
+
}
|
|
1325
|
+
function printAnalyzerEmbeddingProfileReport(result) {
|
|
1326
|
+
if (result.issues.length === 0)
|
|
1327
|
+
return;
|
|
1328
|
+
console.log(`
|
|
1329
|
+
[auditor] \u26A0\uFE0F Embedding profile guardrails detected ${result.issues.length} issue(s):`);
|
|
1330
|
+
for (const issue of result.issues) {
|
|
1331
|
+
const level = issue.severity === "error" ? "ERROR" : "WARN";
|
|
1332
|
+
console.log(`[auditor] ${level} ${issue.type} \u2014 ${issue.file}:${issue.line}`);
|
|
1333
|
+
console.log(`[auditor] ${issue.reason}`);
|
|
1334
|
+
if (issue.snippet) {
|
|
1335
|
+
console.log(`[auditor] ${issue.snippet}`);
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
console.log("[auditor] \u2192 Use one embedding profile per vector column and keep schema dimensions derived from that profile.\n");
|
|
1339
|
+
}
|
|
1340
|
+
function auditAnalyzerWorkflowShadowing(project, sourceFiles) {
|
|
1341
|
+
const issues = [];
|
|
1342
|
+
for (const file of sourceFiles ?? listAuditedSourceFiles(project)) {
|
|
1343
|
+
const content = safeReadText3(file);
|
|
1344
|
+
if (content === null)
|
|
1345
|
+
continue;
|
|
1346
|
+
const relPath = toAnalyzerReportPath(project, file);
|
|
1347
|
+
const fileName = basename3(file);
|
|
1348
|
+
if (WORKFLOW_SHADOW_FILENAMES.has(fileName)) {
|
|
1349
|
+
const markers = WORKFLOW_SHADOW_RUNTIME_MARKERS.filter((marker) => content.includes(marker));
|
|
1350
|
+
if (markers.length > 0) {
|
|
1351
|
+
issues.push({
|
|
1352
|
+
file: relPath,
|
|
1353
|
+
line: 1,
|
|
1354
|
+
snippet: `framework runtime markers: ${markers.slice(0, 3).join(", ")}`,
|
|
1355
|
+
type: "shadow-file",
|
|
1356
|
+
reason: "\uC571 \uB85C\uCEEC workflow runtime \uD3EC\uD06C\uB294 framework/server \uACC4\uC57D\uACFC drift \uB0A9\uB2C8\uB2E4."
|
|
1357
|
+
});
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
const lines = content.split("\n");
|
|
1361
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
1362
|
+
const trimmed = lines[index]?.trim() ?? "";
|
|
1363
|
+
if (trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*") || trimmed.startsWith("*/")) {
|
|
1364
|
+
continue;
|
|
1365
|
+
}
|
|
1366
|
+
if (WORKFLOW_RELATIVE_IMPORT_PATTERN.test(trimmed)) {
|
|
1367
|
+
issues.push({
|
|
1368
|
+
file: relPath,
|
|
1369
|
+
line: index + 1,
|
|
1370
|
+
snippet: trimmed.slice(0, 140),
|
|
1371
|
+
type: "relative-import",
|
|
1372
|
+
reason: "Import the pure workflow builder from app-owned gencow/runtime.ts; do not import a local workflow.ts fork."
|
|
1373
|
+
});
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
return { passed: issues.length === 0, issues };
|
|
1378
|
+
}
|
|
1379
|
+
function printAnalyzerWorkflowShadowingReport(result) {
|
|
1380
|
+
if (result.issues.length === 0)
|
|
1381
|
+
return;
|
|
1382
|
+
const typeLabels = {
|
|
1383
|
+
"shadow-file": "\u{1F9EC} \uB85C\uCEEC workflow runtime \uD3EC\uD06C",
|
|
1384
|
+
"relative-import": "\u{1F501} \uC0C1\uB300 workflow import"
|
|
1385
|
+
};
|
|
1386
|
+
console.log(`
|
|
1387
|
+
[auditor] \u26A0\uFE0F Workflow shadowing detected (${result.issues.length}\uAC74):`);
|
|
1388
|
+
for (const issue of result.issues) {
|
|
1389
|
+
const label = typeLabels[issue.type] || "\u26A0\uFE0F \uAE30\uD0C0";
|
|
1390
|
+
const location = issue.line > 0 ? `${issue.file}:${issue.line}` : issue.file;
|
|
1391
|
+
console.log(`[auditor] ${label} \u2014 ${location}`);
|
|
1392
|
+
console.log(`[auditor] ${issue.snippet}`);
|
|
1393
|
+
}
|
|
1394
|
+
console.log("[auditor] \u2192 import the pure workflow builder from app-owned gencow/runtime.ts.");
|
|
1395
|
+
console.log("[auditor] \u2192 the @gencow/core constructor is retained only for legacy compatibility.");
|
|
1396
|
+
console.log("[auditor] \u2192 local workflow.ts shadow file\uC740 \uC9C0\uC6D0\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.");
|
|
1397
|
+
console.log("[auditor] \u2192 helper\uAC00 \uD544\uC694\uD558\uBA74 \uB2E4\uB978 \uD30C\uC77C\uBA85\uC73C\uB85C \uB9CC\uB4E4\uACE0 core workflow\uB97C \uAC10\uC2F8\uC138\uC694.\n");
|
|
1398
|
+
}
|
|
1399
|
+
function auditAnalyzerAIBypass(project, sourceFiles) {
|
|
1400
|
+
const issues = [];
|
|
1401
|
+
const suspectFileNames = /* @__PURE__ */ new Set([
|
|
1402
|
+
"openai-direct.ts",
|
|
1403
|
+
"openai-direct.tsx",
|
|
1404
|
+
"ai-wrapper.ts",
|
|
1405
|
+
"ai-wrapper.tsx",
|
|
1406
|
+
"ai-helper.ts",
|
|
1407
|
+
"ai-helper.tsx",
|
|
1408
|
+
"ai-client.ts",
|
|
1409
|
+
"ai-client.tsx",
|
|
1410
|
+
"gpt.ts",
|
|
1411
|
+
"gpt.tsx",
|
|
1412
|
+
"openai.ts",
|
|
1413
|
+
"openai.tsx",
|
|
1414
|
+
"llm.ts",
|
|
1415
|
+
"llm.tsx"
|
|
1416
|
+
]);
|
|
1417
|
+
const directOpenAiFetch = /fetch\s*\(\s*[`"']https?:\/\/api\.openai\.com/;
|
|
1418
|
+
const directOpenAiConstructor = /new\s+OpenAI\s*\(/;
|
|
1419
|
+
const inlineAiFunc = /(?:async\s+)?function\s+(?:callGPT|callOpenAI|callAI|fetchGPT|aiCall|directAI)\s*\(/;
|
|
1420
|
+
const openAiImport = /(?:import|require)\s*\(?.*['"]openai['"]/;
|
|
1421
|
+
for (const file of sourceFiles ?? listAuditedSourceFiles(project)) {
|
|
1422
|
+
const relPath = toAnalyzerReportPath(project, file);
|
|
1423
|
+
const fileName = basename3(file);
|
|
1424
|
+
if (fileName === "ai.ts")
|
|
1425
|
+
continue;
|
|
1426
|
+
if (suspectFileNames.has(fileName)) {
|
|
1427
|
+
issues.push({
|
|
1428
|
+
file: relPath,
|
|
1429
|
+
line: 0,
|
|
1430
|
+
snippet: `\uD30C\uC77C\uBA85 "${fileName}" \u2014 AI \uC6B0\uD68C \uB798\uD37C \uC758\uC2EC`,
|
|
1431
|
+
type: "suspect-file"
|
|
1432
|
+
});
|
|
1433
|
+
}
|
|
1434
|
+
const content = safeReadText3(file);
|
|
1435
|
+
if (content === null)
|
|
1436
|
+
continue;
|
|
1437
|
+
const lines = content.split("\n");
|
|
1438
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
1439
|
+
const line = lines[index] ?? "";
|
|
1440
|
+
const trimmed = line.trim();
|
|
1441
|
+
if (trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*"))
|
|
1442
|
+
continue;
|
|
1443
|
+
if (directOpenAiFetch.test(line)) {
|
|
1444
|
+
issues.push({ file: relPath, line: index + 1, snippet: trimmed.slice(0, 100), type: "direct-fetch" });
|
|
1445
|
+
}
|
|
1446
|
+
if (directOpenAiConstructor.test(line)) {
|
|
1447
|
+
issues.push({
|
|
1448
|
+
file: relPath,
|
|
1449
|
+
line: index + 1,
|
|
1450
|
+
snippet: trimmed.slice(0, 100),
|
|
1451
|
+
type: "openai-constructor"
|
|
1452
|
+
});
|
|
1453
|
+
}
|
|
1454
|
+
if (inlineAiFunc.test(line)) {
|
|
1455
|
+
issues.push({
|
|
1456
|
+
file: relPath,
|
|
1457
|
+
line: index + 1,
|
|
1458
|
+
snippet: trimmed.slice(0, 100),
|
|
1459
|
+
type: "inline-ai-func"
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
if (openAiImport.test(line)) {
|
|
1463
|
+
issues.push({
|
|
1464
|
+
file: relPath,
|
|
1465
|
+
line: index + 1,
|
|
1466
|
+
snippet: trimmed.slice(0, 100),
|
|
1467
|
+
type: "openai-import"
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
return { issues };
|
|
1473
|
+
}
|
|
1474
|
+
function printAnalyzerAIBypassReport(result) {
|
|
1475
|
+
if (result.issues.length === 0)
|
|
1476
|
+
return;
|
|
1477
|
+
const typeLabels = {
|
|
1478
|
+
"suspect-file": "\u{1F5C2}\uFE0F AI \uC6B0\uD68C \uB798\uD37C \uD30C\uC77C",
|
|
1479
|
+
"direct-fetch": "\u{1F534} OpenAI API \uC9C1\uC811 \uD638\uCD9C",
|
|
1480
|
+
"openai-constructor": "\u{1F534} OpenAI \uC0DD\uC131\uC790 \uC9C1\uC811 \uC0AC\uC6A9",
|
|
1481
|
+
"inline-ai-func": "\u26A0\uFE0F \uC778\uB77C\uC778 AI \uD568\uC218 \uC815\uC758",
|
|
1482
|
+
"openai-import": "\u26A0\uFE0F openai \uD328\uD0A4\uC9C0 \uC9C1\uC811 import"
|
|
1483
|
+
};
|
|
1484
|
+
console.log(`
|
|
1485
|
+
[auditor] \u{1F916} AI \uC6B0\uD68C \uD328\uD134 \uAC10\uC9C0 (${result.issues.length}\uAC74):`);
|
|
1486
|
+
for (const issue of result.issues) {
|
|
1487
|
+
const label = typeLabels[issue.type] || "\u26A0\uFE0F \uAE30\uD0C0";
|
|
1488
|
+
const location = issue.line > 0 ? `${issue.file}:${issue.line}` : issue.file;
|
|
1489
|
+
console.log(`[auditor] ${label} \u2014 ${location}`);
|
|
1490
|
+
console.log(`[auditor] ${issue.snippet}`);
|
|
1491
|
+
}
|
|
1492
|
+
console.log('[auditor] \u2192 AI \uD638\uCD9C\uC740 \uBC18\uB4DC\uC2DC import { ai } from "./ai" \uB97C \uC0AC\uC6A9\uD558\uC138\uC694.');
|
|
1493
|
+
console.log("[auditor] \u2192 ai.ts\uB294 \uB85C\uCEEC/\uD074\uB77C\uC6B0\uB4DC \uC790\uB3D9 \uC804\uD658\uC744 \uC9C0\uC6D0\uD569\uB2C8\uB2E4.");
|
|
1494
|
+
console.log("[auditor] \u2192 fetch()\uB85C OpenAI\uB97C \uC9C1\uC811 \uD638\uCD9C\uD558\uBA74 \uD074\uB77C\uC6B0\uB4DC\uC5D0\uC11C \uACFC\uAE08\uC774 \uC548 \uB429\uB2C8\uB2E4.\n");
|
|
1495
|
+
}
|
|
1496
|
+
function auditAnalyzerUnsafeDbUsage(project) {
|
|
1497
|
+
const issues = [];
|
|
1498
|
+
const seedWarnings = [];
|
|
1499
|
+
const sourceLines = /* @__PURE__ */ new Map();
|
|
1500
|
+
for (const file of listAuditedSourceFiles(project)) {
|
|
1501
|
+
const content = safeReadText3(file);
|
|
1502
|
+
if (content === null)
|
|
1503
|
+
continue;
|
|
1504
|
+
sourceLines.set(toAnalyzerReportPath(project, file), content.split("\n"));
|
|
1505
|
+
}
|
|
1506
|
+
for (const operation of collectDbOperations(project)) {
|
|
1507
|
+
const file = operation.file;
|
|
1508
|
+
if (operation.visibility === "seed") {
|
|
1509
|
+
seedWarnings.push({
|
|
1510
|
+
file,
|
|
1511
|
+
reason: "seed.ts may use unsafe database access for seeding, but it must not be shipped or used in production"
|
|
1512
|
+
});
|
|
1513
|
+
continue;
|
|
1514
|
+
}
|
|
1515
|
+
for (const hazard of operation.hazards) {
|
|
1516
|
+
const isSystemTable = hazard.kind === "system-table";
|
|
1517
|
+
const blocked = operation.visibility === "public" && (isSystemTable || !operation.allowCommentComplete);
|
|
1518
|
+
const operationLabel = operation.operation ?? "handler";
|
|
1519
|
+
issues.push({
|
|
1520
|
+
file,
|
|
1521
|
+
line: operation.line,
|
|
1522
|
+
snippet: sourceLines.get(file)?.[operation.line - 1]?.trim().slice(0, 160) ?? "",
|
|
1523
|
+
type: hazard.kind,
|
|
1524
|
+
operation: operation.operation,
|
|
1525
|
+
allowlisted: operation.allowCommentComplete,
|
|
1526
|
+
blocked,
|
|
1527
|
+
reason: blocked ? isSystemTable ? `public ${operationLabel} must not expose framework-owned system tables` : `public ${operationLabel} uses an unreviewed database escape hatch` : isSystemTable ? "_system_* and _gencow_* tables are framework-owned" : hazard.kind === "unsafe-db" ? "ctx.unsafeDb uses the audited system-plane database handle" : "raw SQL escape hatches need explicit review"
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
return {
|
|
1532
|
+
usages: issues.map((issue) => ({ file: issue.file, line: issue.line, snippet: issue.snippet })),
|
|
1533
|
+
issues,
|
|
1534
|
+
seedWarnings,
|
|
1535
|
+
blocked: issues.some((issue) => issue.blocked)
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
function printAnalyzerUnsafeDbReport(result) {
|
|
1539
|
+
if (result.issues.length === 0 && result.seedWarnings.length === 0)
|
|
1540
|
+
return;
|
|
1541
|
+
const blocked = result.issues.filter((issue) => issue.blocked);
|
|
1542
|
+
const warnings = result.issues.filter((issue) => !issue.blocked);
|
|
1543
|
+
const log = blocked.length > 0 ? console.error : console.warn;
|
|
1544
|
+
if (result.issues.length > 0) {
|
|
1545
|
+
log(`
|
|
1546
|
+
[auditor] \u26A0\uFE0F unsafe/raw database access detected in ${result.issues.length} location(s):`);
|
|
1547
|
+
}
|
|
1548
|
+
for (const issue of result.issues) {
|
|
1549
|
+
const marker = issue.blocked ? "\u2717" : issue.allowlisted ? "\u2713 allowlisted" : "\u26A0 review";
|
|
1550
|
+
const operation = issue.operation ? ` public ${issue.operation}` : " protected/internal code";
|
|
1551
|
+
log(`[auditor] ${marker} ${issue.file}:${issue.line} \u2014 ${issue.type}${operation}`);
|
|
1552
|
+
log(`[auditor] ${issue.snippet}`);
|
|
1553
|
+
log(`[auditor] \u2192 ${issue.reason}`);
|
|
1554
|
+
}
|
|
1555
|
+
for (const seedWarning of result.seedWarnings) {
|
|
1556
|
+
log(`
|
|
1557
|
+
[auditor] \u26A0\uFE0F ${seedWarning.file} is a seeding-only file`);
|
|
1558
|
+
log(`[auditor] \u2192 ${seedWarning.reason}`);
|
|
1559
|
+
}
|
|
1560
|
+
if (blocked.length > 0) {
|
|
1561
|
+
log("[auditor] \u2192 public handlers must use ctx.db, scoped helpers, or a complete allow comment.");
|
|
1562
|
+
log(`[auditor] \u2192 allow comment format: // ${UNSAFE_DB_ALLOW_COMMENT} reason: ... scope: ... owner: ... test: ...`);
|
|
1563
|
+
} else if (warnings.length > 0 || result.seedWarnings.length > 0) {
|
|
1564
|
+
log("[auditor] \u2192 keep these reviewed and prefer ctx.db unless this is explicit infra/admin code.");
|
|
1565
|
+
}
|
|
1566
|
+
log("");
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
// ../shared/dist/src/analyzer/consumers/auditor/module-auditor-plugin.js
|
|
1570
|
+
function createModuleAuditPlugin() {
|
|
1571
|
+
return {
|
|
1572
|
+
name: "module-auditor",
|
|
1573
|
+
version: 1,
|
|
1574
|
+
description: "Audits user bundle imports against runtime production constraints.",
|
|
1575
|
+
executionKind: "verification",
|
|
1576
|
+
phases: ["graph-analysis"],
|
|
1577
|
+
requiredEvidence: ["source-files", "resolved-graph"],
|
|
1578
|
+
requiredUtilities: ["bundle-inspector"],
|
|
1579
|
+
providesContracts: ["auditor/module-report"],
|
|
1580
|
+
run({ utilities, emitContract }) {
|
|
1581
|
+
const inspector = utilities.require("bundle-inspector");
|
|
1582
|
+
const { violations } = analyzeModuleImportEntries(inspector.listModuleImports());
|
|
1583
|
+
const diagnostics = violations.map((violation) => ({
|
|
1584
|
+
code: "AUD_FORBIDDEN_MODULE",
|
|
1585
|
+
severity: "error",
|
|
1586
|
+
summary: `Forbidden module "${violation.module}" imported from ${violation.importedFrom}.`,
|
|
1587
|
+
source: { file: violation.importedFrom }
|
|
1588
|
+
}));
|
|
1589
|
+
emitContract({
|
|
1590
|
+
name: "auditor/module-report",
|
|
1591
|
+
version: 1,
|
|
1592
|
+
producer: "module-auditor",
|
|
1593
|
+
freshness: {
|
|
1594
|
+
phase: "graph-analysis",
|
|
1595
|
+
evidence: ["source-files", "resolved-graph"]
|
|
1596
|
+
},
|
|
1597
|
+
value: { violations }
|
|
1598
|
+
});
|
|
1599
|
+
return { diagnostics };
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
// ../shared/dist/src/analyzer/consumers/auditor/run-app-analysis.js
|
|
1605
|
+
import { existsSync as existsSync5, readFileSync as readFileSync5, readdirSync as readdirSync2, statSync as statSync3 } from "fs";
|
|
1606
|
+
import { join as join3 } from "path";
|
|
1607
|
+
|
|
1608
|
+
// ../shared/dist/src/analyzer/core/analyzer-types.js
|
|
1609
|
+
var AnalyzerRuntimeError = class extends Error {
|
|
1610
|
+
execution;
|
|
1611
|
+
pluginName;
|
|
1612
|
+
cause;
|
|
1613
|
+
constructor(message, input) {
|
|
1614
|
+
super(message);
|
|
1615
|
+
this.name = "AnalyzerRuntimeError";
|
|
1616
|
+
this.execution = input?.execution ?? [];
|
|
1617
|
+
this.pluginName = input?.pluginName;
|
|
1618
|
+
this.cause = input?.cause;
|
|
1619
|
+
}
|
|
1620
|
+
};
|
|
1621
|
+
|
|
1622
|
+
// ../shared/dist/src/analyzer/core/analyzer-fix-flow.js
|
|
1623
|
+
function getActionableFixPlans(plans, policy) {
|
|
1624
|
+
const fixPolicy = policy?.fixPolicy;
|
|
1625
|
+
const allowKinds = new Set(fixPolicy?.allowKinds ?? []);
|
|
1626
|
+
const filterByKind = allowKinds.size > 0;
|
|
1627
|
+
const blockedByDefault = fixPolicy?.blockedByDefault ?? false;
|
|
1628
|
+
const allowedPlans = [];
|
|
1629
|
+
const blockedResults = [];
|
|
1630
|
+
for (const plan of plans) {
|
|
1631
|
+
const allowedByKind = filterByKind ? allowKinds.has(plan.proposal.kind) : !blockedByDefault;
|
|
1632
|
+
if (allowedByKind) {
|
|
1633
|
+
allowedPlans.push(plan);
|
|
1634
|
+
continue;
|
|
1635
|
+
}
|
|
1636
|
+
blockedResults.push({
|
|
1637
|
+
proposalId: plan.proposal.id,
|
|
1638
|
+
status: "blocked",
|
|
1639
|
+
touchedFiles: plan.proposal.targetFiles,
|
|
1640
|
+
message: `Fix kind "${plan.proposal.kind}" is not allowed by current fix policy.`
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
return { allowedPlans, blockedResults };
|
|
1644
|
+
}
|
|
1645
|
+
function createFixExecutionRecord(mode, durationMs, results, artifacts) {
|
|
1646
|
+
return {
|
|
1647
|
+
kind: "fix",
|
|
1648
|
+
mode,
|
|
1649
|
+
durationMs,
|
|
1650
|
+
proposalIds: results.map((result) => result.proposalId),
|
|
1651
|
+
resultStatuses: results.map((result) => ({
|
|
1652
|
+
proposalId: result.proposalId,
|
|
1653
|
+
status: result.status
|
|
1654
|
+
})),
|
|
1655
|
+
artifactPaths: artifacts.map((artifact) => artifact.path)
|
|
1656
|
+
};
|
|
1657
|
+
}
|
|
1658
|
+
async function runFixFlow(input) {
|
|
1659
|
+
if (input.mode === "none") {
|
|
1660
|
+
return { results: [], artifacts: [], execution: [] };
|
|
1661
|
+
}
|
|
1662
|
+
const startedAt = Date.now();
|
|
1663
|
+
const { allowedPlans, blockedResults } = getActionableFixPlans(input.plans, input.policy);
|
|
1664
|
+
if (input.mode === "plan") {
|
|
1665
|
+
const results2 = [
|
|
1666
|
+
...allowedPlans.map((plan) => ({
|
|
1667
|
+
proposalId: plan.proposal.id,
|
|
1668
|
+
status: "planned",
|
|
1669
|
+
touchedFiles: plan.proposal.targetFiles
|
|
1670
|
+
})),
|
|
1671
|
+
...blockedResults
|
|
1672
|
+
];
|
|
1673
|
+
return {
|
|
1674
|
+
results: results2,
|
|
1675
|
+
artifacts: [],
|
|
1676
|
+
execution: [createFixExecutionRecord("plan", Date.now() - startedAt, results2, [])]
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
if (input.blocked) {
|
|
1680
|
+
const results2 = [
|
|
1681
|
+
...allowedPlans.map((plan) => ({
|
|
1682
|
+
proposalId: plan.proposal.id,
|
|
1683
|
+
status: "blocked",
|
|
1684
|
+
touchedFiles: plan.proposal.targetFiles,
|
|
1685
|
+
message: "Run is blocked; fix execution was not attempted."
|
|
1686
|
+
})),
|
|
1687
|
+
...blockedResults
|
|
1688
|
+
];
|
|
1689
|
+
return {
|
|
1690
|
+
results: results2,
|
|
1691
|
+
artifacts: [],
|
|
1692
|
+
execution: [createFixExecutionRecord(input.mode, Date.now() - startedAt, results2, [])]
|
|
1693
|
+
};
|
|
1694
|
+
}
|
|
1695
|
+
if (input.mode === "diff") {
|
|
1696
|
+
if (!input.fixApplier?.diff) {
|
|
1697
|
+
const results3 = [
|
|
1698
|
+
...allowedPlans.map((plan) => ({
|
|
1699
|
+
proposalId: plan.proposal.id,
|
|
1700
|
+
status: "skipped",
|
|
1701
|
+
touchedFiles: plan.proposal.targetFiles,
|
|
1702
|
+
message: "Fix diff output is not available because no diff applier was configured."
|
|
1703
|
+
})),
|
|
1704
|
+
...blockedResults
|
|
1705
|
+
];
|
|
1706
|
+
return {
|
|
1707
|
+
results: results3,
|
|
1708
|
+
artifacts: [],
|
|
1709
|
+
execution: [createFixExecutionRecord("diff", Date.now() - startedAt, results3, [])]
|
|
1710
|
+
};
|
|
1711
|
+
}
|
|
1712
|
+
const artifacts2 = (await input.fixApplier.diff({
|
|
1713
|
+
plans: allowedPlans,
|
|
1714
|
+
projectRoot: input.projectRoot
|
|
1715
|
+
})).map((artifact) => ({
|
|
1716
|
+
...artifact,
|
|
1717
|
+
provenance: artifact.provenance ?? {
|
|
1718
|
+
kind: "fix",
|
|
1719
|
+
producer: "fix-applier"
|
|
1720
|
+
}
|
|
1721
|
+
}));
|
|
1722
|
+
const artifactPaths2 = artifacts2.map((artifact) => artifact.path);
|
|
1723
|
+
const results2 = [
|
|
1724
|
+
...allowedPlans.map((plan) => ({
|
|
1725
|
+
proposalId: plan.proposal.id,
|
|
1726
|
+
status: "diffed",
|
|
1727
|
+
touchedFiles: plan.proposal.targetFiles,
|
|
1728
|
+
artifactPaths: artifactPaths2
|
|
1729
|
+
})),
|
|
1730
|
+
...blockedResults
|
|
1731
|
+
];
|
|
1732
|
+
return {
|
|
1733
|
+
results: results2,
|
|
1734
|
+
artifacts: artifacts2,
|
|
1735
|
+
execution: [createFixExecutionRecord("diff", Date.now() - startedAt, results2, artifacts2)]
|
|
1736
|
+
};
|
|
1737
|
+
}
|
|
1738
|
+
if (!input.policy?.fixPolicy?.allowApply) {
|
|
1739
|
+
const results2 = [
|
|
1740
|
+
...allowedPlans.map((plan) => ({
|
|
1741
|
+
proposalId: plan.proposal.id,
|
|
1742
|
+
status: "blocked",
|
|
1743
|
+
touchedFiles: plan.proposal.targetFiles,
|
|
1744
|
+
message: "Fix application is not allowed by current fix policy."
|
|
1745
|
+
})),
|
|
1746
|
+
...blockedResults
|
|
1747
|
+
];
|
|
1748
|
+
return {
|
|
1749
|
+
results: results2,
|
|
1750
|
+
artifacts: [],
|
|
1751
|
+
execution: [createFixExecutionRecord("apply", Date.now() - startedAt, results2, [])]
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
if (!input.fixApplier?.apply) {
|
|
1755
|
+
const results2 = [
|
|
1756
|
+
...allowedPlans.map((plan) => ({
|
|
1757
|
+
proposalId: plan.proposal.id,
|
|
1758
|
+
status: "skipped",
|
|
1759
|
+
touchedFiles: plan.proposal.targetFiles,
|
|
1760
|
+
message: "Fix application is not available because no apply applier was configured."
|
|
1761
|
+
})),
|
|
1762
|
+
...blockedResults
|
|
1763
|
+
];
|
|
1764
|
+
return {
|
|
1765
|
+
results: results2,
|
|
1766
|
+
artifacts: [],
|
|
1767
|
+
execution: [createFixExecutionRecord("apply", Date.now() - startedAt, results2, [])]
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
const artifacts = input.fixApplier.diff ? (await input.fixApplier.diff({
|
|
1771
|
+
plans: allowedPlans,
|
|
1772
|
+
projectRoot: input.projectRoot
|
|
1773
|
+
})).map((artifact) => ({
|
|
1774
|
+
...artifact,
|
|
1775
|
+
provenance: artifact.provenance ?? {
|
|
1776
|
+
kind: "fix",
|
|
1777
|
+
producer: "fix-applier"
|
|
1778
|
+
}
|
|
1779
|
+
})) : [];
|
|
1780
|
+
const artifactPaths = artifacts.map((artifact) => artifact.path);
|
|
1781
|
+
const appliedResults = await input.fixApplier.apply({
|
|
1782
|
+
plans: allowedPlans,
|
|
1783
|
+
projectRoot: input.projectRoot
|
|
1784
|
+
});
|
|
1785
|
+
const results = [
|
|
1786
|
+
...appliedResults.map((result) => ({
|
|
1787
|
+
...result,
|
|
1788
|
+
artifactPaths: result.artifactPaths ?? artifactPaths
|
|
1789
|
+
})),
|
|
1790
|
+
...blockedResults
|
|
1791
|
+
];
|
|
1792
|
+
return {
|
|
1793
|
+
results,
|
|
1794
|
+
artifacts,
|
|
1795
|
+
execution: [
|
|
1796
|
+
createFixExecutionRecord("apply", Date.now() - startedAt, results, artifacts)
|
|
1797
|
+
]
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
// ../shared/dist/src/analyzer/core/analyzer-materialization.js
|
|
1802
|
+
function collectMaterializerContractWarnings(materializers, contracts) {
|
|
1803
|
+
const contractNames = new Set(contracts.map((contract) => contract.name));
|
|
1804
|
+
return materializers.filter((materializer) => !contractNames.has(materializer.consumesContract)).map((materializer) => ({
|
|
1805
|
+
code: "DOCTOR_MATERIALIZER_INPUT_MISSING",
|
|
1806
|
+
severity: "warning",
|
|
1807
|
+
summary: `Materializer "${materializer.name}" was skipped because required contract "${materializer.consumesContract}" was not available.`,
|
|
1808
|
+
tags: ["analyzer:materializer-skipped"]
|
|
1809
|
+
}));
|
|
1810
|
+
}
|
|
1811
|
+
async function materializeAnalyzerContracts(materializers, contracts, projectRoot) {
|
|
1812
|
+
const artifacts = [];
|
|
1813
|
+
const execution = [];
|
|
1814
|
+
for (const materializer of materializers) {
|
|
1815
|
+
const contract = contracts.find((candidate) => candidate.name === materializer.consumesContract);
|
|
1816
|
+
if (!contract) {
|
|
1817
|
+
execution.push({
|
|
1818
|
+
kind: "materializer",
|
|
1819
|
+
name: materializer.name,
|
|
1820
|
+
consumesContract: materializer.consumesContract,
|
|
1821
|
+
status: "skipped",
|
|
1822
|
+
durationMs: 0,
|
|
1823
|
+
artifactPaths: [],
|
|
1824
|
+
message: `Required contract "${materializer.consumesContract}" was not available.`
|
|
1825
|
+
});
|
|
1826
|
+
continue;
|
|
1827
|
+
}
|
|
1828
|
+
const startedAt = Date.now();
|
|
1829
|
+
const produced = await materializer.materialize({
|
|
1830
|
+
contract,
|
|
1831
|
+
projectRoot
|
|
1832
|
+
});
|
|
1833
|
+
const enrichedArtifacts = produced.map((artifact) => ({
|
|
1834
|
+
...artifact,
|
|
1835
|
+
provenance: artifact.provenance ?? {
|
|
1836
|
+
kind: "materializer",
|
|
1837
|
+
producer: materializer.name,
|
|
1838
|
+
sourceContract: {
|
|
1839
|
+
name: contract.name,
|
|
1840
|
+
version: contract.version,
|
|
1841
|
+
producer: contract.producer
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
}));
|
|
1845
|
+
artifacts.push(...enrichedArtifacts);
|
|
1846
|
+
execution.push({
|
|
1847
|
+
kind: "materializer",
|
|
1848
|
+
name: materializer.name,
|
|
1849
|
+
consumesContract: materializer.consumesContract,
|
|
1850
|
+
status: "produced",
|
|
1851
|
+
durationMs: Date.now() - startedAt,
|
|
1852
|
+
artifactPaths: enrichedArtifacts.map((artifact) => artifact.path)
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
return { artifacts, execution };
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
// ../shared/dist/src/analyzer/core/analyzer-policy.js
|
|
1859
|
+
var DIAGNOSTIC_SEVERITY_ORDER = {
|
|
1860
|
+
info: 0,
|
|
1861
|
+
warning: 1,
|
|
1862
|
+
error: 2
|
|
1863
|
+
};
|
|
1864
|
+
var DEFAULT_PHASE_EVIDENCE_POLICY = {
|
|
1865
|
+
"source-analysis": ["source-files"],
|
|
1866
|
+
"graph-analysis": ["source-files", "resolved-graph"],
|
|
1867
|
+
"artifact-analysis": ["artifacts"],
|
|
1868
|
+
"loaded-analysis": ["loaded-runtime"],
|
|
1869
|
+
"live-analysis": ["live-state"]
|
|
1870
|
+
};
|
|
1871
|
+
function policyInputsMatch(expected, actual) {
|
|
1872
|
+
if (!expected) {
|
|
1873
|
+
return true;
|
|
1874
|
+
}
|
|
1875
|
+
for (const [key, value] of Object.entries(expected)) {
|
|
1876
|
+
if (actual?.[key] !== value) {
|
|
1877
|
+
return false;
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
return true;
|
|
1881
|
+
}
|
|
1882
|
+
function overrideMatches(diagnostic, override, options) {
|
|
1883
|
+
if (override.code && override.code !== diagnostic.code) {
|
|
1884
|
+
return false;
|
|
1885
|
+
}
|
|
1886
|
+
if (override.pluginName && override.pluginName !== diagnostic.pluginName) {
|
|
1887
|
+
return false;
|
|
1888
|
+
}
|
|
1889
|
+
const when = override.when;
|
|
1890
|
+
if (!when) {
|
|
1891
|
+
return true;
|
|
1892
|
+
}
|
|
1893
|
+
if (when.profile && when.profile !== options.context.profile) {
|
|
1894
|
+
return false;
|
|
1895
|
+
}
|
|
1896
|
+
if (when.phase && when.phase !== options.context.phase) {
|
|
1897
|
+
return false;
|
|
1898
|
+
}
|
|
1899
|
+
if (when.command && when.command !== options.context.command) {
|
|
1900
|
+
return false;
|
|
1901
|
+
}
|
|
1902
|
+
if (when.trustMode && when.trustMode !== options.context.trustMode) {
|
|
1903
|
+
return false;
|
|
1904
|
+
}
|
|
1905
|
+
return policyInputsMatch(when.policyInputs, options.context.policyInputs);
|
|
1906
|
+
}
|
|
1907
|
+
function shouldBlockAnalyzerRun(diagnostics, policy, phase) {
|
|
1908
|
+
const threshold = policy?.minimumSeverityToBlockByPhase?.[phase];
|
|
1909
|
+
const minimumRank = DIAGNOSTIC_SEVERITY_ORDER[threshold ?? "error"];
|
|
1910
|
+
return diagnostics.some((diagnostic) => DIAGNOSTIC_SEVERITY_ORDER[diagnostic.severity] >= minimumRank);
|
|
1911
|
+
}
|
|
1912
|
+
function evaluateDiagnostics(diagnostics, options) {
|
|
1913
|
+
const overrides = options.policy?.diagnosticOverrides ?? [];
|
|
1914
|
+
const threshold = options.policy?.minimumSeverityToBlockByPhase?.[options.context.phase] ?? "error";
|
|
1915
|
+
const thresholdRank = DIAGNOSTIC_SEVERITY_ORDER[threshold];
|
|
1916
|
+
return diagnostics.map((diagnostic) => {
|
|
1917
|
+
const originalSeverity = diagnostic.severity;
|
|
1918
|
+
let nextDiagnostic = { ...diagnostic };
|
|
1919
|
+
let forcedBlocked;
|
|
1920
|
+
for (const override of overrides) {
|
|
1921
|
+
if (!overrideMatches(nextDiagnostic, override, options)) {
|
|
1922
|
+
continue;
|
|
1923
|
+
}
|
|
1924
|
+
if (override.severity) {
|
|
1925
|
+
nextDiagnostic = {
|
|
1926
|
+
...nextDiagnostic,
|
|
1927
|
+
severity: override.severity
|
|
1928
|
+
};
|
|
1929
|
+
}
|
|
1930
|
+
if (override.blocked !== void 0) {
|
|
1931
|
+
forcedBlocked = override.blocked;
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
return {
|
|
1935
|
+
diagnostic: nextDiagnostic,
|
|
1936
|
+
originalSeverity,
|
|
1937
|
+
blocked: forcedBlocked ?? DIAGNOSTIC_SEVERITY_ORDER[nextDiagnostic.severity] >= thresholdRank
|
|
1938
|
+
};
|
|
1939
|
+
});
|
|
1940
|
+
}
|
|
1941
|
+
function ensurePhaseEvidenceCompatible(phase, availableEvidence, phaseEvidencePolicy) {
|
|
1942
|
+
const expectedEvidence = phaseEvidencePolicy?.[phase] ?? DEFAULT_PHASE_EVIDENCE_POLICY[phase] ?? [];
|
|
1943
|
+
const missingEvidence = expectedEvidence.filter((evidence) => !availableEvidence.includes(evidence));
|
|
1944
|
+
if (missingEvidence.length > 0) {
|
|
1945
|
+
throw new Error(`Analyzer phase "${phase}" requires evidence kinds [${expectedEvidence.join(", ")}] but run context is missing [${missingEvidence.join(", ")}] from provided [${availableEvidence.join(", ")}].`);
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
// ../shared/dist/src/analyzer/core/analyzer-plugin-utils.js
|
|
1950
|
+
function dedupeArray(values) {
|
|
1951
|
+
return [...new Set(values)];
|
|
1952
|
+
}
|
|
1953
|
+
function formatContractVersionConstraint(constraint) {
|
|
1954
|
+
if (constraint === void 0) {
|
|
1955
|
+
return "any";
|
|
1956
|
+
}
|
|
1957
|
+
if (typeof constraint === "number") {
|
|
1958
|
+
return `=${constraint}`;
|
|
1959
|
+
}
|
|
1960
|
+
const parts = [
|
|
1961
|
+
constraint.min !== void 0 ? `>=${constraint.min}` : void 0,
|
|
1962
|
+
constraint.max !== void 0 ? `<=${constraint.max}` : void 0
|
|
1963
|
+
].filter((part) => Boolean(part));
|
|
1964
|
+
return parts.join(" and ");
|
|
1965
|
+
}
|
|
1966
|
+
function contractVersionMatches(version, constraint) {
|
|
1967
|
+
if (constraint === void 0) {
|
|
1968
|
+
return true;
|
|
1969
|
+
}
|
|
1970
|
+
if (typeof constraint === "number") {
|
|
1971
|
+
return version === constraint;
|
|
1972
|
+
}
|
|
1973
|
+
if (constraint.min !== void 0 && version < constraint.min) {
|
|
1974
|
+
return false;
|
|
1975
|
+
}
|
|
1976
|
+
if (constraint.max !== void 0 && version > constraint.max) {
|
|
1977
|
+
return false;
|
|
1978
|
+
}
|
|
1979
|
+
return true;
|
|
1980
|
+
}
|
|
1981
|
+
function resolvePhaseRequirements(plugin, phase) {
|
|
1982
|
+
const phaseRequirements = plugin.phaseRequirements?.[phase];
|
|
1983
|
+
return {
|
|
1984
|
+
requiredEvidence: dedupeArray([
|
|
1985
|
+
...plugin.requiredEvidence ?? [],
|
|
1986
|
+
...phaseRequirements?.requiredEvidence ?? []
|
|
1987
|
+
]),
|
|
1988
|
+
requiredUtilities: dedupeArray([
|
|
1989
|
+
...plugin.requiredUtilities ?? [],
|
|
1990
|
+
...phaseRequirements?.requiredUtilities ?? []
|
|
1991
|
+
]),
|
|
1992
|
+
providesContracts: dedupeArray([
|
|
1993
|
+
...plugin.providesContracts ?? [],
|
|
1994
|
+
...phaseRequirements?.providesContracts ?? []
|
|
1995
|
+
]),
|
|
1996
|
+
consumesContracts: dedupeArray([
|
|
1997
|
+
...plugin.consumesContracts ?? [],
|
|
1998
|
+
...phaseRequirements?.consumesContracts ?? []
|
|
1999
|
+
]),
|
|
2000
|
+
contractRequirements: [
|
|
2001
|
+
...plugin.contractRequirements ?? [],
|
|
2002
|
+
...phaseRequirements?.contractRequirements ?? []
|
|
2003
|
+
]
|
|
2004
|
+
};
|
|
2005
|
+
}
|
|
2006
|
+
function validatePluginOptions(invocation, analyzer) {
|
|
2007
|
+
if (!invocation.plugin.validateOptions) {
|
|
2008
|
+
return invocation;
|
|
2009
|
+
}
|
|
2010
|
+
return {
|
|
2011
|
+
...invocation,
|
|
2012
|
+
options: invocation.plugin.validateOptions(invocation.options, analyzer)
|
|
2013
|
+
};
|
|
2014
|
+
}
|
|
2015
|
+
function createAnalyzerUtilityRegistry(utilities) {
|
|
2016
|
+
return {
|
|
2017
|
+
has(name) {
|
|
2018
|
+
return Object.prototype.hasOwnProperty.call(utilities, name);
|
|
2019
|
+
},
|
|
2020
|
+
get(name) {
|
|
2021
|
+
return utilities[name];
|
|
2022
|
+
},
|
|
2023
|
+
require(name) {
|
|
2024
|
+
const utility = utilities[name];
|
|
2025
|
+
if (utility === void 0) {
|
|
2026
|
+
throw new Error(`Analyzer utility "${name}" is not registered.`);
|
|
2027
|
+
}
|
|
2028
|
+
return utility;
|
|
2029
|
+
},
|
|
2030
|
+
list() {
|
|
2031
|
+
return Object.keys(utilities);
|
|
2032
|
+
}
|
|
2033
|
+
};
|
|
2034
|
+
}
|
|
2035
|
+
function activateAnalyzerPlugin(plugin, input) {
|
|
2036
|
+
return {
|
|
2037
|
+
plugin,
|
|
2038
|
+
provider: input?.provider ?? plugin.name,
|
|
2039
|
+
sourceKind: input?.sourceKind ?? "core",
|
|
2040
|
+
sourcePath: input?.sourcePath,
|
|
2041
|
+
mode: input?.mode ?? "configured",
|
|
2042
|
+
options: {
|
|
2043
|
+
...plugin.defaultOptions ?? {},
|
|
2044
|
+
...input?.options ?? {}
|
|
2045
|
+
}
|
|
2046
|
+
};
|
|
2047
|
+
}
|
|
2048
|
+
function createAnalyzerContractStore(initialContracts = []) {
|
|
2049
|
+
const contracts = /* @__PURE__ */ new Map();
|
|
2050
|
+
for (const contract of initialContracts) {
|
|
2051
|
+
if (contracts.has(contract.name)) {
|
|
2052
|
+
throw new Error(`Analyzer contract "${contract.name}" was provided more than once in initial contracts.`);
|
|
2053
|
+
}
|
|
2054
|
+
contracts.set(contract.name, contract);
|
|
2055
|
+
}
|
|
2056
|
+
return {
|
|
2057
|
+
has(name) {
|
|
2058
|
+
return contracts.has(name);
|
|
2059
|
+
},
|
|
2060
|
+
get(name) {
|
|
2061
|
+
const contract = contracts.get(name);
|
|
2062
|
+
return contract;
|
|
2063
|
+
},
|
|
2064
|
+
require(name) {
|
|
2065
|
+
const contract = contracts.get(name);
|
|
2066
|
+
if (!contract) {
|
|
2067
|
+
throw new Error(`Analyzer contract "${name}" is required but was not produced.`);
|
|
2068
|
+
}
|
|
2069
|
+
return contract;
|
|
2070
|
+
},
|
|
2071
|
+
list() {
|
|
2072
|
+
return Array.from(contracts.values());
|
|
2073
|
+
},
|
|
2074
|
+
set(contract) {
|
|
2075
|
+
if (contracts.has(contract.name)) {
|
|
2076
|
+
throw new Error(`Analyzer contract "${contract.name}" was produced more than once.`);
|
|
2077
|
+
}
|
|
2078
|
+
contracts.set(contract.name, contract);
|
|
2079
|
+
}
|
|
2080
|
+
};
|
|
2081
|
+
}
|
|
2082
|
+
function mergeAnalyzerPlugins(defaultPlugins, configuredPlugins, overrides) {
|
|
2083
|
+
const configuredNames = new Set(configuredPlugins.map(({ plugin }) => plugin.name));
|
|
2084
|
+
const merged = [
|
|
2085
|
+
...defaultPlugins.filter(({ plugin }) => !configuredNames.has(plugin.name)),
|
|
2086
|
+
...configuredPlugins
|
|
2087
|
+
];
|
|
2088
|
+
return merged.map((invocation) => ({
|
|
2089
|
+
...invocation,
|
|
2090
|
+
options: {
|
|
2091
|
+
...invocation.plugin.defaultOptions ?? {},
|
|
2092
|
+
...invocation.options ?? {},
|
|
2093
|
+
...overrides[invocation.plugin.name] ?? {}
|
|
2094
|
+
}
|
|
2095
|
+
}));
|
|
2096
|
+
}
|
|
2097
|
+
function topologicallyOrderAnalyzerPlugins(input) {
|
|
2098
|
+
const providedAtStart = new Set(input.initialContracts ?? []);
|
|
2099
|
+
const unscheduled = [...input.plugins];
|
|
2100
|
+
const ordered = [];
|
|
2101
|
+
const provided = new Set(providedAtStart);
|
|
2102
|
+
while (unscheduled.length > 0) {
|
|
2103
|
+
const readyIndex = unscheduled.findIndex(({ plugin }) => {
|
|
2104
|
+
const consumed = input.phase !== void 0 ? resolvePhaseRequirements(plugin, input.phase).consumesContracts : plugin.consumesContracts ?? [];
|
|
2105
|
+
return consumed.every((contractName) => provided.has(contractName));
|
|
2106
|
+
});
|
|
2107
|
+
if (readyIndex === -1) {
|
|
2108
|
+
const unresolved = unscheduled.map(({ plugin }) => plugin.name).join(", ");
|
|
2109
|
+
throw new Error(`Analyzer plugins cannot be ordered because dependencies are unresolved: ${unresolved}`);
|
|
2110
|
+
}
|
|
2111
|
+
const [invocation] = unscheduled.splice(readyIndex, 1);
|
|
2112
|
+
ordered.push(invocation);
|
|
2113
|
+
const providedContracts = input.phase !== void 0 ? resolvePhaseRequirements(invocation.plugin, input.phase).providesContracts : invocation.plugin.providesContracts ?? [];
|
|
2114
|
+
for (const providedContract of providedContracts) {
|
|
2115
|
+
provided.add(providedContract);
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
return ordered;
|
|
2119
|
+
}
|
|
2120
|
+
function normalizePluginDiagnostics(diagnostics, invocation) {
|
|
2121
|
+
return diagnostics.map((diagnostic) => ({
|
|
2122
|
+
...diagnostic,
|
|
2123
|
+
pluginName: diagnostic.pluginName ?? invocation.plugin.name,
|
|
2124
|
+
provider: diagnostic.provider ?? invocation.provider
|
|
2125
|
+
}));
|
|
2126
|
+
}
|
|
2127
|
+
function normalizePluginFixPlans(plans, invocation) {
|
|
2128
|
+
return plans.map((plan) => ({
|
|
2129
|
+
...plan,
|
|
2130
|
+
proposal: {
|
|
2131
|
+
...plan.proposal,
|
|
2132
|
+
pluginName: plan.proposal.pluginName ?? invocation.plugin.name,
|
|
2133
|
+
provider: plan.proposal.provider ?? invocation.provider
|
|
2134
|
+
}
|
|
2135
|
+
}));
|
|
2136
|
+
}
|
|
2137
|
+
function ensurePluginEvidenceAvailable(invocation, phase, availableEvidence) {
|
|
2138
|
+
for (const evidence of resolvePhaseRequirements(invocation.plugin, phase).requiredEvidence) {
|
|
2139
|
+
if (!availableEvidence.includes(evidence)) {
|
|
2140
|
+
throw new Error(`Analyzer plugin "${invocation.plugin.name}" requires evidence "${evidence}" but it is not available in this run context.`);
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
function validatePluginContractDeclarations(invocation, phase, emittedContracts) {
|
|
2145
|
+
const declaredContracts = new Set(resolvePhaseRequirements(invocation.plugin, phase).providesContracts);
|
|
2146
|
+
const emittedContractsSet = new Set(emittedContracts);
|
|
2147
|
+
for (const contractName of emittedContractsSet) {
|
|
2148
|
+
if (!declaredContracts.has(contractName)) {
|
|
2149
|
+
throw new Error(`Analyzer plugin "${invocation.plugin.name}" emitted undeclared contract "${contractName}".`);
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
const missingContracts = [...declaredContracts].filter((contractName) => !emittedContractsSet.has(contractName));
|
|
2153
|
+
if (missingContracts.length > 0) {
|
|
2154
|
+
throw new Error(`Analyzer plugin "${invocation.plugin.name}" declared contracts that were not emitted: ${missingContracts.join(", ")}.`);
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
function ensurePluginContractRequirements(invocation, phase, contracts) {
|
|
2158
|
+
const requirements = resolvePhaseRequirements(invocation.plugin, phase).contractRequirements;
|
|
2159
|
+
for (const requirement of requirements) {
|
|
2160
|
+
const contract = contracts.require(requirement.name);
|
|
2161
|
+
if (!contractVersionMatches(contract.version, requirement.version)) {
|
|
2162
|
+
throw new Error(`Analyzer plugin "${invocation.plugin.name}" requires contract "${requirement.name}" version ${formatContractVersionConstraint(requirement.version)} but received version ${contract.version}.`);
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
// ../shared/dist/src/analyzer/core/analyzer-runtime.js
|
|
2168
|
+
function resolveUtilitiesRegistry(utilities) {
|
|
2169
|
+
return typeof utilities.require === "function" ? utilities : createAnalyzerUtilityRegistry(utilities);
|
|
2170
|
+
}
|
|
2171
|
+
function ensureRequiredPluginsPresent(options, pluginsForPhase) {
|
|
2172
|
+
const requiredByCommand = new Set(options.policy?.requiredPluginsByCommand?.[options.context.command] ?? []);
|
|
2173
|
+
const requiredByPhase = new Set(options.policy?.requiredPluginsByPhase?.[options.context.phase] ?? []);
|
|
2174
|
+
for (const pluginName of requiredByCommand) {
|
|
2175
|
+
if (!pluginsForPhase.some(({ plugin }) => plugin.name === pluginName)) {
|
|
2176
|
+
throw new Error(`Analyzer command "${options.context.command}" requires plugin "${pluginName}" for phase "${options.context.phase}".`);
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
for (const pluginName of requiredByPhase) {
|
|
2180
|
+
if (!pluginsForPhase.some(({ plugin }) => plugin.name === pluginName)) {
|
|
2181
|
+
throw new Error(`Analyzer phase "${options.context.phase}" requires plugin "${pluginName}".`);
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
async function executeOrderedPlugins(input) {
|
|
2186
|
+
const rawDiagnostics = [];
|
|
2187
|
+
const fixPlans = [];
|
|
2188
|
+
const execution = [];
|
|
2189
|
+
for (const invocation of input.orderedPlugins) {
|
|
2190
|
+
const { plugin } = invocation;
|
|
2191
|
+
const phaseRequirements = resolvePhaseRequirements(plugin, input.options.context.phase);
|
|
2192
|
+
ensurePluginEvidenceAvailable(invocation, input.options.context.phase, input.options.context.availableEvidence);
|
|
2193
|
+
for (const utilityName of phaseRequirements.requiredUtilities) {
|
|
2194
|
+
input.utilities.require(utilityName);
|
|
2195
|
+
}
|
|
2196
|
+
for (const contractName of phaseRequirements.consumesContracts) {
|
|
2197
|
+
input.contracts.require(contractName);
|
|
2198
|
+
}
|
|
2199
|
+
ensurePluginContractRequirements(invocation, input.options.context.phase, input.contracts);
|
|
2200
|
+
const startedAt = Date.now();
|
|
2201
|
+
const emittedContracts = [];
|
|
2202
|
+
try {
|
|
2203
|
+
const result = await plugin.run({
|
|
2204
|
+
analyzer: input.options.context,
|
|
2205
|
+
plugin: invocation,
|
|
2206
|
+
options: invocation.options,
|
|
2207
|
+
utilities: input.utilities,
|
|
2208
|
+
contracts: input.contracts,
|
|
2209
|
+
emitContract(contract) {
|
|
2210
|
+
input.contracts.set(contract);
|
|
2211
|
+
emittedContracts.push(contract.name);
|
|
2212
|
+
}
|
|
2213
|
+
});
|
|
2214
|
+
validatePluginContractDeclarations(invocation, input.options.context.phase, emittedContracts);
|
|
2215
|
+
rawDiagnostics.push(...normalizePluginDiagnostics(result.diagnostics, invocation));
|
|
2216
|
+
const normalizedFixPlans = normalizePluginFixPlans(result.fixPlans ?? [], invocation);
|
|
2217
|
+
fixPlans.push(...normalizedFixPlans);
|
|
2218
|
+
execution.push({
|
|
2219
|
+
kind: "plugin",
|
|
2220
|
+
name: plugin.name,
|
|
2221
|
+
provider: invocation.provider,
|
|
2222
|
+
sourceKind: invocation.sourceKind,
|
|
2223
|
+
mode: invocation.mode,
|
|
2224
|
+
executionKind: plugin.executionKind ?? "analysis",
|
|
2225
|
+
status: "completed",
|
|
2226
|
+
durationMs: Date.now() - startedAt,
|
|
2227
|
+
emittedContracts,
|
|
2228
|
+
diagnosticCodes: result.diagnostics.map((diagnostic) => diagnostic.code),
|
|
2229
|
+
plannedFixes: normalizedFixPlans.map((plan) => plan.proposal.id)
|
|
2230
|
+
});
|
|
2231
|
+
} catch (error) {
|
|
2232
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2233
|
+
execution.push({
|
|
2234
|
+
kind: "plugin",
|
|
2235
|
+
name: plugin.name,
|
|
2236
|
+
provider: invocation.provider,
|
|
2237
|
+
sourceKind: invocation.sourceKind,
|
|
2238
|
+
mode: invocation.mode,
|
|
2239
|
+
executionKind: plugin.executionKind ?? "analysis",
|
|
2240
|
+
status: "failed",
|
|
2241
|
+
durationMs: Date.now() - startedAt,
|
|
2242
|
+
emittedContracts,
|
|
2243
|
+
diagnosticCodes: [],
|
|
2244
|
+
plannedFixes: [],
|
|
2245
|
+
message
|
|
2246
|
+
});
|
|
2247
|
+
throw new AnalyzerRuntimeError(`Analyzer plugin "${plugin.name}" failed: ${message}`, {
|
|
2248
|
+
execution,
|
|
2249
|
+
pluginName: plugin.name,
|
|
2250
|
+
cause: error
|
|
2251
|
+
});
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
return { rawDiagnostics, fixPlans, execution };
|
|
2255
|
+
}
|
|
2256
|
+
async function executePostAnalysisFlows(input) {
|
|
2257
|
+
const fixMode = input.options.context.fixMode ?? "none";
|
|
2258
|
+
const fixFlow = await runFixFlow({
|
|
2259
|
+
blocked: input.blocked,
|
|
2260
|
+
mode: fixMode,
|
|
2261
|
+
plans: input.fixPlans,
|
|
2262
|
+
policy: input.options.policy,
|
|
2263
|
+
projectRoot: input.options.context.projectRoot,
|
|
2264
|
+
fixApplier: input.options.fixApplier
|
|
2265
|
+
});
|
|
2266
|
+
const materializationResult = input.blocked ? { artifacts: [], execution: [] } : await materializeAnalyzerContracts(input.options.materializers ?? [], input.contracts.list(), input.options.context.projectRoot);
|
|
2267
|
+
const artifacts = fixMode === "diff" || fixMode === "apply" ? [...fixFlow.artifacts, ...materializationResult.artifacts] : [...materializationResult.artifacts, ...fixFlow.artifacts];
|
|
2268
|
+
return {
|
|
2269
|
+
fixResults: fixFlow.results,
|
|
2270
|
+
artifacts,
|
|
2271
|
+
execution: [...materializationResult.execution, ...fixFlow.execution]
|
|
2272
|
+
};
|
|
2273
|
+
}
|
|
2274
|
+
function sanitizeRunResult(input) {
|
|
2275
|
+
const sanitizer = input.options.outputSanitizer;
|
|
2276
|
+
const diagnostics = input.evaluatedDiagnostics.map((entry) => sanitizer?.sanitizeDiagnostic ? sanitizer.sanitizeDiagnostic(entry.diagnostic) : entry.diagnostic);
|
|
2277
|
+
return {
|
|
2278
|
+
diagnostics,
|
|
2279
|
+
evaluatedDiagnostics: input.evaluatedDiagnostics.map((entry, index) => ({
|
|
2280
|
+
...entry,
|
|
2281
|
+
diagnostic: diagnostics[index]
|
|
2282
|
+
})),
|
|
2283
|
+
contracts: input.contracts.map((contract) => sanitizer?.sanitizeContract ? sanitizer.sanitizeContract(contract) : contract),
|
|
2284
|
+
materializedArtifacts: input.artifacts.map((artifact) => sanitizer?.sanitizeArtifact ? sanitizer.sanitizeArtifact(artifact) : artifact),
|
|
2285
|
+
execution: input.execution.map((record) => sanitizer?.sanitizeExecutionRecord ? sanitizer.sanitizeExecutionRecord(record) : record)
|
|
2286
|
+
};
|
|
2287
|
+
}
|
|
2288
|
+
async function runAnalyzerPlugins(options) {
|
|
2289
|
+
const utilities = resolveUtilitiesRegistry(options.utilities);
|
|
2290
|
+
ensurePhaseEvidenceCompatible(options.context.phase, options.context.availableEvidence, options.phaseEvidencePolicy);
|
|
2291
|
+
const contracts = createAnalyzerContractStore(options.initialContracts ?? []);
|
|
2292
|
+
const mergedPlugins = mergeAnalyzerPlugins(options.defaultPlugins ?? [], options.plugins, options.pluginOptionOverrides ?? {}).map((invocation) => validatePluginOptions(invocation, options.context));
|
|
2293
|
+
const pluginsForPhase = mergedPlugins.filter(({ plugin }) => plugin.phases.includes(options.context.phase));
|
|
2294
|
+
ensureRequiredPluginsPresent(options, pluginsForPhase);
|
|
2295
|
+
const orderedPlugins = topologicallyOrderAnalyzerPlugins({
|
|
2296
|
+
plugins: pluginsForPhase,
|
|
2297
|
+
initialContracts: contracts.list().map((contract) => contract.name),
|
|
2298
|
+
phase: options.context.phase
|
|
2299
|
+
});
|
|
2300
|
+
const pluginRun = await executeOrderedPlugins({
|
|
2301
|
+
options,
|
|
2302
|
+
utilities,
|
|
2303
|
+
contracts,
|
|
2304
|
+
orderedPlugins
|
|
2305
|
+
});
|
|
2306
|
+
pluginRun.rawDiagnostics.push(...collectMaterializerContractWarnings(options.materializers ?? [], contracts.list()));
|
|
2307
|
+
const evaluatedDiagnostics = evaluateDiagnostics(pluginRun.rawDiagnostics, options);
|
|
2308
|
+
const blocked = evaluatedDiagnostics.some((diagnostic) => diagnostic.blocked) || shouldBlockAnalyzerRun(evaluatedDiagnostics.map((diagnostic) => diagnostic.diagnostic), options.policy, options.context.phase);
|
|
2309
|
+
const postAnalysis = await executePostAnalysisFlows({
|
|
2310
|
+
options,
|
|
2311
|
+
contracts,
|
|
2312
|
+
fixPlans: pluginRun.fixPlans,
|
|
2313
|
+
blocked
|
|
2314
|
+
});
|
|
2315
|
+
const sanitized = sanitizeRunResult({
|
|
2316
|
+
options,
|
|
2317
|
+
evaluatedDiagnostics,
|
|
2318
|
+
contracts: contracts.list(),
|
|
2319
|
+
artifacts: postAnalysis.artifacts,
|
|
2320
|
+
execution: [...pluginRun.execution, ...postAnalysis.execution]
|
|
2321
|
+
});
|
|
2322
|
+
return {
|
|
2323
|
+
...sanitized,
|
|
2324
|
+
blocked,
|
|
2325
|
+
fixPlans: pluginRun.fixPlans,
|
|
2326
|
+
fixResults: postAnalysis.fixResults,
|
|
2327
|
+
pluginOrder: orderedPlugins.map(({ plugin }) => plugin.name)
|
|
2328
|
+
};
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
// ../shared/dist/src/analyzer/shared/db-access-plugin.js
|
|
2332
|
+
function createDbAccessPlugin() {
|
|
2333
|
+
return {
|
|
2334
|
+
name: "db-access-doctor",
|
|
2335
|
+
version: 1,
|
|
2336
|
+
description: "Scans handler operations for unsafe database escape hatches.",
|
|
2337
|
+
statusText: "Auditing database access",
|
|
2338
|
+
defaultOptions: {
|
|
2339
|
+
allowReviewedPublicRawSql: true
|
|
2340
|
+
},
|
|
2341
|
+
executionKind: "analysis",
|
|
2342
|
+
phases: ["source-analysis", "graph-analysis"],
|
|
2343
|
+
requiredEvidence: ["source-files"],
|
|
2344
|
+
requiredUtilities: ["db-operation-inspector"],
|
|
2345
|
+
consumesContracts: ["schema/canonical"],
|
|
2346
|
+
providesContracts: ["db-access/findings"],
|
|
2347
|
+
run({ utilities, contracts, emitContract, options }) {
|
|
2348
|
+
const inspector = utilities.require("db-operation-inspector");
|
|
2349
|
+
const schemaContract = contracts.require("schema/canonical").value;
|
|
2350
|
+
const applicationTables = new Set(schemaContract.canonicalOwners.map((owner) => owner.tableName));
|
|
2351
|
+
const findings = [];
|
|
2352
|
+
const diagnostics = [];
|
|
2353
|
+
for (const operation of inspector.listOperations()) {
|
|
2354
|
+
for (const hazard of operation.hazards) {
|
|
2355
|
+
const operationLabel = operation.operation ?? "handler";
|
|
2356
|
+
const frameworkTables = hazard.referencedTables.filter((tableName) => tableName.startsWith("_system_") || tableName.startsWith("_gencow_"));
|
|
2357
|
+
const applicationTablesUsed = hazard.referencedTables.filter((tableName) => applicationTables.has(tableName));
|
|
2358
|
+
const isSystemTable = hazard.kind === "system-table" || frameworkTables.length > 0;
|
|
2359
|
+
const isPublic = operation.visibility === "public";
|
|
2360
|
+
const isProtected = operation.visibility === "protected";
|
|
2361
|
+
const blocked = isSystemTable ? isPublic : isPublic ? hazard.kind === "raw-sql" ? !(operation.allowCommentComplete && options.allowReviewedPublicRawSql) : !operation.allowCommentComplete : false;
|
|
2362
|
+
const severity = blocked ? "error" : isProtected || operation.visibility === "seed" ? "warning" : "info";
|
|
2363
|
+
const code = isSystemTable ? "DBD_PUBLIC_SYSTEM_TABLE" : hazard.kind === "unsafe-db" ? isPublic ? "DBD_PUBLIC_UNSAFE_DB" : operation.visibility === "seed" ? "DBD_SEED_ESCAPE_HATCH" : "DBD_PROTECTED_UNSAFE_DB" : isPublic ? "DBD_PUBLIC_RAW_SQL" : operation.visibility === "seed" ? "DBD_SEED_ESCAPE_HATCH" : "DBD_PROTECTED_RAW_SQL";
|
|
2364
|
+
findings.push({
|
|
2365
|
+
file: operation.file,
|
|
2366
|
+
line: operation.line,
|
|
2367
|
+
kind: isSystemTable ? "system-table" : hazard.kind,
|
|
2368
|
+
visibility: operation.visibility,
|
|
2369
|
+
allowlisted: operation.allowCommentComplete,
|
|
2370
|
+
blocked,
|
|
2371
|
+
applicationTables: applicationTablesUsed,
|
|
2372
|
+
frameworkTables
|
|
2373
|
+
});
|
|
2374
|
+
if (isPublic && !operation.allowCommentComplete && !isSystemTable) {
|
|
2375
|
+
diagnostics.push({
|
|
2376
|
+
code: "DBD_INCOMPLETE_ALLOW_COMMENT",
|
|
2377
|
+
severity: "warning",
|
|
2378
|
+
summary: `Public ${operationLabel} uses ${hazard.kind} without complete review metadata.`,
|
|
2379
|
+
source: { file: operation.file, line: operation.line }
|
|
2380
|
+
});
|
|
2381
|
+
}
|
|
2382
|
+
diagnostics.push({
|
|
2383
|
+
code,
|
|
2384
|
+
severity,
|
|
2385
|
+
summary: `${operation.visibility} ${operationLabel} uses ${isSystemTable ? "framework tables" : hazard.kind}.`,
|
|
2386
|
+
source: { file: operation.file, line: operation.line }
|
|
2387
|
+
});
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
emitContract({
|
|
2391
|
+
name: "db-access/findings",
|
|
2392
|
+
version: 1,
|
|
2393
|
+
producer: "db-access-doctor",
|
|
2394
|
+
value: { findings }
|
|
2395
|
+
});
|
|
2396
|
+
return { diagnostics };
|
|
2397
|
+
}
|
|
2398
|
+
};
|
|
2399
|
+
}
|
|
2400
|
+
|
|
2401
|
+
// ../shared/dist/src/analyzer/shared/schema-plugin.js
|
|
2402
|
+
function createSchemaPlugin() {
|
|
2403
|
+
return {
|
|
2404
|
+
name: "schema-doctor",
|
|
2405
|
+
version: 1,
|
|
2406
|
+
description: "Computes the canonical schema contract for downstream Doctor consumers.",
|
|
2407
|
+
statusText: "Analyzing schema graph",
|
|
2408
|
+
defaultOptions: {
|
|
2409
|
+
includeGeneratedOwners: true,
|
|
2410
|
+
allowLegacyAuthBoundary: false
|
|
2411
|
+
},
|
|
2412
|
+
executionKind: "analysis",
|
|
2413
|
+
phases: ["source-analysis", "graph-analysis"],
|
|
2414
|
+
requiredEvidence: ["source-files"],
|
|
2415
|
+
requiredUtilities: ["config-loader", "schema-graph", "manifest-diff"],
|
|
2416
|
+
providesContracts: ["schema/canonical"],
|
|
2417
|
+
run({ utilities, emitContract, options }) {
|
|
2418
|
+
const config = utilities.require("config-loader");
|
|
2419
|
+
const graph = utilities.require("schema-graph");
|
|
2420
|
+
const manifestDiff = utilities.require("manifest-diff");
|
|
2421
|
+
const rootSchemaPath = config.loadSchemaConfig().rootSchemaPath;
|
|
2422
|
+
const reachableModules = graph.getReachableModules(rootSchemaPath);
|
|
2423
|
+
const authBoundary = graph.getAuthBoundary();
|
|
2424
|
+
const diagnostics = [];
|
|
2425
|
+
for (const modulePath of graph.getHiddenOwners(reachableModules)) {
|
|
2426
|
+
diagnostics.push({
|
|
2427
|
+
code: "SD_HIDDEN_OWNER",
|
|
2428
|
+
severity: "error",
|
|
2429
|
+
summary: `Schema owner is hidden outside the reachable graph: ${modulePath}`,
|
|
2430
|
+
source: { file: modulePath }
|
|
2431
|
+
});
|
|
2432
|
+
}
|
|
2433
|
+
for (const modulePath of graph.getDynamicEdges(reachableModules)) {
|
|
2434
|
+
diagnostics.push({
|
|
2435
|
+
code: "SD_NON_PROVABLE_WIRING",
|
|
2436
|
+
severity: "error",
|
|
2437
|
+
summary: `Schema wiring is dynamic and cannot be proven statically: ${modulePath}`,
|
|
2438
|
+
source: { file: modulePath }
|
|
2439
|
+
});
|
|
2440
|
+
}
|
|
2441
|
+
if (authBoundary.mode === "legacy-auth-schema" && !options.allowLegacyAuthBoundary) {
|
|
2442
|
+
diagnostics.push({
|
|
2443
|
+
code: "SD_LEGACY_AUTH_CONFLICT",
|
|
2444
|
+
severity: "warning",
|
|
2445
|
+
summary: `Legacy auth schema boundary requires explicit compatibility opt-in: ${authBoundary.path}`,
|
|
2446
|
+
source: { file: authBoundary.path }
|
|
2447
|
+
});
|
|
2448
|
+
}
|
|
2449
|
+
const owners = graph.getTableOwners(reachableModules);
|
|
2450
|
+
const canonicalOwners = options.includeGeneratedOwners ? owners : owners.filter((owner) => owner.sourceKind === "user");
|
|
2451
|
+
const tableCounts = /* @__PURE__ */ new Map();
|
|
2452
|
+
for (const owner of canonicalOwners) {
|
|
2453
|
+
tableCounts.set(owner.tableName, (tableCounts.get(owner.tableName) ?? 0) + 1);
|
|
2454
|
+
}
|
|
2455
|
+
for (const owner of canonicalOwners) {
|
|
2456
|
+
if ((tableCounts.get(owner.tableName) ?? 0) > 1) {
|
|
2457
|
+
diagnostics.push({
|
|
2458
|
+
code: "SD_DUPLICATE_OWNER",
|
|
2459
|
+
severity: "error",
|
|
2460
|
+
summary: `Table "${owner.tableName}" has multiple canonical owners.`,
|
|
2461
|
+
source: { file: owner.publicOwnerPath }
|
|
2462
|
+
});
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
for (const tableName of manifestDiff.getMissingTables(canonicalOwners.map((owner) => owner.tableName))) {
|
|
2466
|
+
diagnostics.push({
|
|
2467
|
+
code: "SD_TABLE_DISAPPEARANCE",
|
|
2468
|
+
severity: "error",
|
|
2469
|
+
summary: `Table "${tableName}" disappeared compared with the prior manifest.`
|
|
2470
|
+
});
|
|
2471
|
+
}
|
|
2472
|
+
emitContract({
|
|
2473
|
+
name: "schema/canonical",
|
|
2474
|
+
version: 1,
|
|
2475
|
+
producer: "schema-doctor",
|
|
2476
|
+
freshness: {
|
|
2477
|
+
phase: "source-analysis",
|
|
2478
|
+
evidence: ["source-files"]
|
|
2479
|
+
},
|
|
2480
|
+
value: {
|
|
2481
|
+
rootSchemaPath,
|
|
2482
|
+
reachableModules,
|
|
2483
|
+
canonicalOwners,
|
|
2484
|
+
exportRows: canonicalOwners.map((owner) => ({
|
|
2485
|
+
exportName: owner.tableName,
|
|
2486
|
+
from: owner.publicOwnerPath.replace(/\.ts$/, "")
|
|
2487
|
+
})),
|
|
2488
|
+
authBoundary
|
|
2489
|
+
}
|
|
2490
|
+
});
|
|
2491
|
+
return { diagnostics };
|
|
2492
|
+
}
|
|
2493
|
+
};
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
// ../shared/dist/src/analyzer/shared/source-patterns-plugin.js
|
|
2497
|
+
function stripLeadingMarker(message) {
|
|
2498
|
+
return message.replace(/^[^\p{L}\p{N}"']+/u, "").trim();
|
|
2499
|
+
}
|
|
2500
|
+
function createSourcePatternsPlugin() {
|
|
2501
|
+
return {
|
|
2502
|
+
name: "source-patterns-doctor",
|
|
2503
|
+
version: 1,
|
|
2504
|
+
description: "Runs source-level auditor checks that complement graph/module analysis.",
|
|
2505
|
+
statusText: "Scanning backend source patterns",
|
|
2506
|
+
defaultOptions: {
|
|
2507
|
+
includeFrontend: false
|
|
2508
|
+
},
|
|
2509
|
+
executionKind: "analysis",
|
|
2510
|
+
phases: ["source-analysis", "graph-analysis"],
|
|
2511
|
+
requiredEvidence: ["source-files"],
|
|
2512
|
+
requiredUtilities: ["source-auditor"],
|
|
2513
|
+
providesContracts: ["auditor/source-report"],
|
|
2514
|
+
run({ analyzer, utilities, options, emitContract }) {
|
|
2515
|
+
const report = utilities.require("source-auditor").runSourceAudit();
|
|
2516
|
+
const diagnostics = [];
|
|
2517
|
+
for (const warning of report.schemaPatterns.warnings) {
|
|
2518
|
+
diagnostics.push({
|
|
2519
|
+
code: "AUD_SCHEMA_PATTERN",
|
|
2520
|
+
severity: "warning",
|
|
2521
|
+
summary: stripLeadingMarker(warning),
|
|
2522
|
+
source: report.schemaPatterns.fileName ? { file: report.schemaPatterns.fileName } : void 0
|
|
2523
|
+
});
|
|
2524
|
+
}
|
|
2525
|
+
for (const usage of report.selfFetch.usages) {
|
|
2526
|
+
diagnostics.push({
|
|
2527
|
+
code: "AUD_SELF_FETCH",
|
|
2528
|
+
severity: "warning",
|
|
2529
|
+
summary: "Self-fetch through /api/query or /api/mutation is deprecated; import the handler directly.",
|
|
2530
|
+
detail: usage.snippet,
|
|
2531
|
+
source: { file: usage.file, line: usage.line }
|
|
2532
|
+
});
|
|
2533
|
+
}
|
|
2534
|
+
for (const issue of report.workflowShadowing.issues) {
|
|
2535
|
+
diagnostics.push({
|
|
2536
|
+
code: "AUD_WORKFLOW_SHADOWING",
|
|
2537
|
+
severity: "error",
|
|
2538
|
+
summary: issue.reason,
|
|
2539
|
+
detail: issue.snippet,
|
|
2540
|
+
source: { file: issue.file, line: issue.line },
|
|
2541
|
+
tags: [issue.type]
|
|
2542
|
+
});
|
|
2543
|
+
}
|
|
2544
|
+
for (const issue of report.aiBypass.issues) {
|
|
2545
|
+
diagnostics.push({
|
|
2546
|
+
code: "AUD_AI_BYPASS",
|
|
2547
|
+
severity: "warning",
|
|
2548
|
+
summary: "Deprecated AI bypass pattern detected; use the local ai wrapper instead of direct provider access.",
|
|
2549
|
+
detail: issue.snippet,
|
|
2550
|
+
source: { file: issue.file, line: issue.line },
|
|
2551
|
+
tags: [issue.type]
|
|
2552
|
+
});
|
|
2553
|
+
}
|
|
2554
|
+
if (options.includeFrontend) {
|
|
2555
|
+
for (const issue of report.frontendAntiPatterns.issues) {
|
|
2556
|
+
diagnostics.push({
|
|
2557
|
+
code: "AUD_FRONTEND_API_CLIENT",
|
|
2558
|
+
severity: "warning",
|
|
2559
|
+
summary: issue.reason,
|
|
2560
|
+
source: { file: issue.file }
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2564
|
+
for (const issue of report.embeddingProfiles.issues) {
|
|
2565
|
+
const code = issue.type === "legacy-model-only" ? "AUD_EMBEDDING_PROFILE_LEGACY_FACTORY" : issue.type === "dual-source" ? "AUD_EMBEDDING_PROFILE_DUAL_SOURCE" : issue.type === "schema-profile-mismatch" ? "AUD_EMBEDDING_PROFILE_SCHEMA_MISMATCH" : "AUD_EMBEDDING_PROFILE_LITERAL";
|
|
2566
|
+
diagnostics.push({
|
|
2567
|
+
code,
|
|
2568
|
+
severity: issue.severity,
|
|
2569
|
+
summary: issue.reason,
|
|
2570
|
+
detail: issue.snippet,
|
|
2571
|
+
source: { file: issue.file, line: issue.line },
|
|
2572
|
+
tags: [issue.type]
|
|
2573
|
+
});
|
|
2574
|
+
}
|
|
2575
|
+
emitContract({
|
|
2576
|
+
name: "auditor/source-report",
|
|
2577
|
+
version: 1,
|
|
2578
|
+
producer: "source-patterns-doctor",
|
|
2579
|
+
freshness: {
|
|
2580
|
+
phase: analyzer.phase,
|
|
2581
|
+
evidence: ["source-files"]
|
|
2582
|
+
},
|
|
2583
|
+
value: report
|
|
2584
|
+
});
|
|
2585
|
+
return { diagnostics };
|
|
2586
|
+
}
|
|
2587
|
+
};
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
// ../shared/dist/src/analyzer/consumers/auditor/security-auditor-plugin.js
|
|
2591
|
+
function publicOperationSecurityNotice(hasPublicQueries) {
|
|
2592
|
+
const access = hasPublicQueries ? "These operations are accessible without authentication. Check that public queries do not expose personal data." : "These operations are accessible without authentication.";
|
|
2593
|
+
return `${access} Remove { public: true } (legacy) or .allowAnonymous() (fluent) if authentication is intended.`;
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2596
|
+
// ../shared/dist/src/analyzer/consumers/auditor/run-app-analysis.js
|
|
2597
|
+
function safeReadText4(filePath) {
|
|
2598
|
+
try {
|
|
2599
|
+
return readFileSync5(filePath, "utf8");
|
|
2600
|
+
} catch {
|
|
2601
|
+
return null;
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
function legacyTypeScriptFiles(directory) {
|
|
2605
|
+
try {
|
|
2606
|
+
return readdirSync2(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
2607
|
+
const path = join3(directory, entry.name);
|
|
2608
|
+
if (entry.isDirectory() && entry.name !== "node_modules" && !entry.name.startsWith("."))
|
|
2609
|
+
return legacyTypeScriptFiles(path);
|
|
2610
|
+
return entry.isFile() && /\.tsx?$/.test(entry.name) ? [path] : [];
|
|
2611
|
+
});
|
|
2612
|
+
} catch {
|
|
2613
|
+
return [];
|
|
2614
|
+
}
|
|
2615
|
+
}
|
|
2616
|
+
function createAppAnalyzerUtilities(input) {
|
|
2617
|
+
const project = resolveAppProject(input);
|
|
2618
|
+
const loadedProcedures = input.loadedProcedures ?? { queries: [], mutations: [] };
|
|
2619
|
+
const reachableModules = collectReachableSchemaModules(project);
|
|
2620
|
+
const moduleImports = collectModuleImports(project);
|
|
2621
|
+
let legacyDirectory = !input.legacyStartupScope;
|
|
2622
|
+
if (input.legacyStartupScope && existsSync5(project.functionsDirAbs)) {
|
|
2623
|
+
try {
|
|
2624
|
+
legacyDirectory = statSync3(project.functionsDirAbs).isDirectory();
|
|
2625
|
+
} catch {
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2628
|
+
const legacyFiles = input.legacyStartupScope ? legacyDirectory ? legacyTypeScriptFiles(project.functionsDirAbs) : [] : void 0;
|
|
2629
|
+
const sourceAuditReport = {
|
|
2630
|
+
schemaPatterns: auditAnalyzerSchemaPatterns(project),
|
|
2631
|
+
selfFetch: auditAnalyzerSelfFetch(project, legacyFiles),
|
|
2632
|
+
dataIsolation: auditAnalyzerDataIsolation(project),
|
|
2633
|
+
unsafeDb: legacyDirectory ? auditAnalyzerUnsafeDbUsage(project) : { usages: [], issues: [], seedWarnings: [], blocked: false },
|
|
2634
|
+
workflowShadowing: auditAnalyzerWorkflowShadowing(project, legacyFiles),
|
|
2635
|
+
aiBypass: auditAnalyzerAIBypass(project, legacyFiles),
|
|
2636
|
+
frontendAntiPatterns: auditAnalyzerFrontendAntiPatterns(project),
|
|
2637
|
+
embeddingProfiles: auditAnalyzerEmbeddingProfiles(project, legacyFiles)
|
|
2638
|
+
};
|
|
2639
|
+
const sourceFiles = listAuditedSourceFiles(project).map((filePath) => {
|
|
2640
|
+
const content = safeReadText4(filePath);
|
|
2641
|
+
return content === null ? null : {
|
|
2642
|
+
file: toProjectPath(project.projectRootAbs, filePath),
|
|
2643
|
+
content
|
|
2644
|
+
};
|
|
2645
|
+
}).filter((entry) => entry !== null);
|
|
2646
|
+
return {
|
|
2647
|
+
project,
|
|
2648
|
+
utilities: {
|
|
2649
|
+
"config-loader": {
|
|
2650
|
+
loadSchemaConfig: () => ({
|
|
2651
|
+
rootSchemaPath: toProjectPath(project.projectRootAbs, project.rootSchemaPathAbs)
|
|
2652
|
+
})
|
|
2653
|
+
},
|
|
2654
|
+
"schema-graph": {
|
|
2655
|
+
getReachableModules: () => [...reachableModules],
|
|
2656
|
+
getTableOwners: (modulePaths) => collectSchemaOwners(project, modulePaths),
|
|
2657
|
+
getHiddenOwners: (modulePaths) => collectHiddenSchemaOwners(project, new Set(modulePaths)),
|
|
2658
|
+
getDynamicEdges: (modulePaths) => collectDynamicSchemaEdges(project, modulePaths),
|
|
2659
|
+
getAuthBoundary: () => detectAuthBoundary(project)
|
|
2660
|
+
},
|
|
2661
|
+
"manifest-diff": {
|
|
2662
|
+
getMissingTables: () => []
|
|
2663
|
+
},
|
|
2664
|
+
"db-operation-inspector": {
|
|
2665
|
+
listOperations: () => collectDbOperations(project)
|
|
2666
|
+
},
|
|
2667
|
+
"bundle-inspector": {
|
|
2668
|
+
listModuleImports: () => moduleImports
|
|
2669
|
+
},
|
|
2670
|
+
"procedure-registry": {
|
|
2671
|
+
listQueries: () => loadedProcedures.queries,
|
|
2672
|
+
listMutations: () => loadedProcedures.mutations
|
|
2673
|
+
},
|
|
2674
|
+
"source-auditor": {
|
|
2675
|
+
runSourceAudit: () => sourceAuditReport
|
|
2676
|
+
},
|
|
2677
|
+
"source-file-catalog": {
|
|
2678
|
+
listFiles: () => sourceFiles
|
|
2679
|
+
},
|
|
2680
|
+
"builtin-operation-registry": {
|
|
2681
|
+
listBuiltinOperations: () => []
|
|
2682
|
+
},
|
|
2683
|
+
"user-operation-index": {
|
|
2684
|
+
listUserOperations: () => ({
|
|
2685
|
+
queries: [],
|
|
2686
|
+
mutations: [],
|
|
2687
|
+
namespaceImportPaths: {},
|
|
2688
|
+
singleFileImportPath: "./index.ts",
|
|
2689
|
+
coreGeneratedNamespaces: []
|
|
2690
|
+
})
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
};
|
|
2694
|
+
}
|
|
2695
|
+
async function runAppSourceAndGraphAnalysis(input) {
|
|
2696
|
+
const { project, utilities } = createAppAnalyzerUtilities(input);
|
|
2697
|
+
const profile = input.profile ?? "auditor";
|
|
2698
|
+
const command = input.command ?? profile;
|
|
2699
|
+
const trustMode = input.trustMode ?? "local";
|
|
2700
|
+
const sourceResult = await runAnalyzerPlugins({
|
|
2701
|
+
context: {
|
|
2702
|
+
profile,
|
|
2703
|
+
phase: "source-analysis",
|
|
2704
|
+
command,
|
|
2705
|
+
trustMode,
|
|
2706
|
+
projectRoot: project.projectRootAbs,
|
|
2707
|
+
functionsDir: project.functionsDirAbs,
|
|
2708
|
+
cwd: project.projectRootAbs,
|
|
2709
|
+
featureFlags: {},
|
|
2710
|
+
envKeys: [],
|
|
2711
|
+
availableEvidence: ["source-files"],
|
|
2712
|
+
fixMode: "none"
|
|
2713
|
+
},
|
|
2714
|
+
utilities,
|
|
2715
|
+
plugins: input.sourcePlugins ?? [
|
|
2716
|
+
activateAnalyzerPlugin(createSourcePatternsPlugin(), {
|
|
2717
|
+
options: { includeFrontend: input.includeFrontend === true }
|
|
2718
|
+
})
|
|
2719
|
+
],
|
|
2720
|
+
policy: {
|
|
2721
|
+
minimumSeverityToBlockByPhase: {
|
|
2722
|
+
"source-analysis": "error"
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
});
|
|
2726
|
+
const graphResult = await runAnalyzerPlugins({
|
|
2727
|
+
context: {
|
|
2728
|
+
profile,
|
|
2729
|
+
phase: "graph-analysis",
|
|
2730
|
+
command,
|
|
2731
|
+
trustMode,
|
|
2732
|
+
projectRoot: project.projectRootAbs,
|
|
2733
|
+
functionsDir: project.functionsDirAbs,
|
|
2734
|
+
cwd: project.projectRootAbs,
|
|
2735
|
+
featureFlags: {},
|
|
2736
|
+
envKeys: [],
|
|
2737
|
+
availableEvidence: ["source-files", "resolved-graph"],
|
|
2738
|
+
fixMode: "none"
|
|
2739
|
+
},
|
|
2740
|
+
utilities,
|
|
2741
|
+
plugins: [
|
|
2742
|
+
activateAnalyzerPlugin(createSchemaPlugin()),
|
|
2743
|
+
activateAnalyzerPlugin(createDbAccessPlugin()),
|
|
2744
|
+
activateAnalyzerPlugin(createModuleAuditPlugin())
|
|
2745
|
+
],
|
|
2746
|
+
policy: {
|
|
2747
|
+
minimumSeverityToBlockByPhase: {
|
|
2748
|
+
"graph-analysis": "error"
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
});
|
|
2752
|
+
return {
|
|
2753
|
+
projectRoot: project.projectRootAbs,
|
|
2754
|
+
diagnostics: [...sourceResult.diagnostics, ...graphResult.diagnostics],
|
|
2755
|
+
blocked: sourceResult.blocked || graphResult.blocked,
|
|
2756
|
+
fixPlans: [...sourceResult.fixPlans, ...graphResult.fixPlans],
|
|
2757
|
+
sourceResult,
|
|
2758
|
+
graphResult
|
|
2759
|
+
};
|
|
2760
|
+
}
|
|
2761
|
+
function findContract(contracts, name) {
|
|
2762
|
+
return contracts.find((contract) => contract.name === name);
|
|
2763
|
+
}
|
|
2764
|
+
function getAnalyzerModuleAuditReport(result) {
|
|
2765
|
+
const contract = findContract(result.contracts, "auditor/module-report");
|
|
2766
|
+
const violations = contract?.value.violations ?? [];
|
|
2767
|
+
return {
|
|
2768
|
+
passed: violations.length === 0,
|
|
2769
|
+
violations
|
|
2770
|
+
};
|
|
2771
|
+
}
|
|
2772
|
+
function getAnalyzerSourceAuditReport(result) {
|
|
2773
|
+
const contract = findContract(result.contracts, "auditor/source-report");
|
|
2774
|
+
return contract?.value ?? null;
|
|
2775
|
+
}
|
|
2776
|
+
|
|
2777
|
+
// ../shared/dist/src/analyzer/consumers/auditor/startup-audit.js
|
|
2778
|
+
import { existsSync as existsSync6, statSync as statSync4 } from "node:fs";
|
|
2779
|
+
import { resolve as resolve5 } from "node:path";
|
|
2780
|
+
function resolveStartupAuditEntry(root) {
|
|
2781
|
+
const isFile = existsSync6(root) && statSync4(root).isFile();
|
|
2782
|
+
return (isFile ? [root] : [resolve5(root, "index.js"), resolve5(root, "index.ts"), `${root}.ts`, `${root}.js`]).find(existsSync6);
|
|
2783
|
+
}
|
|
2784
|
+
async function runLocalStartupAudit(input) {
|
|
2785
|
+
const root = resolve5(input.projectRoot, input.rootDir);
|
|
2786
|
+
const entry = input.entryPath === void 0 ? resolveStartupAuditEntry(root) : resolve5(input.projectRoot, input.entryPath);
|
|
2787
|
+
if (!entry)
|
|
2788
|
+
return { blocked: null };
|
|
2789
|
+
const legacy = input.implementation !== "analyzer";
|
|
2790
|
+
const schema = legacy ? [resolve5(root, "schema.ts")] : input.schema;
|
|
2791
|
+
const analysis = await runAppSourceAndGraphAnalysis({
|
|
2792
|
+
...input,
|
|
2793
|
+
entryPath: entry,
|
|
2794
|
+
schema,
|
|
2795
|
+
legacyStartupScope: legacy
|
|
2796
|
+
});
|
|
2797
|
+
const moduleReport = getAnalyzerModuleAuditReport(analysis.graphResult);
|
|
2798
|
+
printAnalyzerModuleAuditReport(moduleReport, entry);
|
|
2799
|
+
if (!moduleReport.passed && input.strict)
|
|
2800
|
+
return { blocked: "module" };
|
|
2801
|
+
const source = getAnalyzerSourceAuditReport(analysis.sourceResult) ?? getAnalyzerSourceAuditReport(analysis.graphResult);
|
|
2802
|
+
if (!source)
|
|
2803
|
+
throw new Error("Local startup audit report unavailable");
|
|
2804
|
+
printAnalyzerSchemaPatternReport(source.schemaPatterns);
|
|
2805
|
+
printAnalyzerSelfFetchReport(source.selfFetch);
|
|
2806
|
+
if (legacy)
|
|
2807
|
+
printAnalyzerEmbeddingProfileReport(source.embeddingProfiles);
|
|
2808
|
+
printAnalyzerUnsafeDbReport(source.unsafeDb);
|
|
2809
|
+
if (source.unsafeDb.blocked && input.strict)
|
|
2810
|
+
return { blocked: "unsafe-db" };
|
|
2811
|
+
printAnalyzerWorkflowShadowingReport(source.workflowShadowing);
|
|
2812
|
+
if (!source.workflowShadowing.passed && input.strict)
|
|
2813
|
+
return { blocked: "workflow-shadowing" };
|
|
2814
|
+
printAnalyzerAIBypassReport(source.aiBypass);
|
|
2815
|
+
printAnalyzerFrontendAntiPatternReport(source.frontendAntiPatterns);
|
|
2816
|
+
return { blocked: null };
|
|
2817
|
+
}
|
|
2818
|
+
|
|
2819
|
+
// ../runtime/dist/realtime/listener-bridge.js
|
|
2820
|
+
function wiringFailure() {
|
|
2821
|
+
return new RuntimeDiagnosticError({
|
|
2822
|
+
code: "RUNTIME_REALTIME_CONFIG_INVALID",
|
|
2823
|
+
stage: "startup",
|
|
2824
|
+
capability: "realtime",
|
|
2825
|
+
servingStarted: false,
|
|
2826
|
+
dataImpact: "none",
|
|
2827
|
+
retryable: false,
|
|
2828
|
+
retryPrecondition: "Register the generation endpoint once before binding its target listener.",
|
|
2829
|
+
nextAction: "Regenerate the launcher; do not override a bound listener or create another Runtime root."
|
|
2830
|
+
});
|
|
2831
|
+
}
|
|
2832
|
+
function unavailable(request) {
|
|
2833
|
+
return {
|
|
2834
|
+
ok: false,
|
|
2835
|
+
response: realtimeHttpResponse(new Response("Realtime listener unavailable", { status: 503 }), realtimeHttpDiagnostic(request, "RUNTIME_GENERATION_CLOSING", "Wait for the current app listener and replacement generation to be ready before reconnecting."))
|
|
2836
|
+
};
|
|
2837
|
+
}
|
|
2838
|
+
function createRuntimeRealtimeListenerBridge() {
|
|
2839
|
+
let endpoint;
|
|
2840
|
+
let state = "unbound";
|
|
2841
|
+
return Object.freeze({
|
|
2842
|
+
register(value) {
|
|
2843
|
+
if (endpoint || state !== "unbound")
|
|
2844
|
+
throw wiringFailure();
|
|
2845
|
+
endpoint = value;
|
|
2846
|
+
},
|
|
2847
|
+
bind() {
|
|
2848
|
+
if (!endpoint || state !== "unbound")
|
|
2849
|
+
throw wiringFailure();
|
|
2850
|
+
state = "bound";
|
|
2851
|
+
},
|
|
2852
|
+
fence() {
|
|
2853
|
+
if (state !== "closed")
|
|
2854
|
+
state = "closing";
|
|
2855
|
+
},
|
|
2856
|
+
finish() {
|
|
2857
|
+
state = "closed";
|
|
2858
|
+
},
|
|
2859
|
+
async admit(request) {
|
|
2860
|
+
if (state !== "bound" || !endpoint)
|
|
2861
|
+
return unavailable(request);
|
|
2862
|
+
const result = await endpoint.admit(request);
|
|
2863
|
+
if (state !== "bound") {
|
|
2864
|
+
if (result.ok)
|
|
2865
|
+
await endpoint.closed(result.connection);
|
|
2866
|
+
return unavailable(request);
|
|
2867
|
+
}
|
|
2868
|
+
return result;
|
|
2869
|
+
},
|
|
2870
|
+
opened(connection, socket) {
|
|
2871
|
+
if (state !== "bound" || !endpoint) {
|
|
2872
|
+
try {
|
|
2873
|
+
socket.close(1001, "realtime_listener_closing");
|
|
2874
|
+
} catch {
|
|
2875
|
+
}
|
|
2876
|
+
return endpoint?.closed(connection) ?? Promise.resolve();
|
|
2877
|
+
}
|
|
2878
|
+
return endpoint.opened(connection, socket);
|
|
2879
|
+
},
|
|
2880
|
+
message(connection, frame) {
|
|
2881
|
+
return state === "bound" && endpoint ? endpoint.message(connection, frame) : Promise.resolve();
|
|
2882
|
+
},
|
|
2883
|
+
closed(connection) {
|
|
2884
|
+
return endpoint?.closed(connection) ?? Promise.resolve();
|
|
2885
|
+
}
|
|
2886
|
+
});
|
|
2887
|
+
}
|
|
2888
|
+
|
|
2889
|
+
// ../runtime/dist/realtime/bun-bridge.js
|
|
2890
|
+
function createBunRealtimeListenerOptions(generation, bridge) {
|
|
2891
|
+
return {
|
|
2892
|
+
async fetch(request, server) {
|
|
2893
|
+
if (new URL(request.url).pathname !== "/ws" || request.headers.get("upgrade")?.toLowerCase() !== "websocket")
|
|
2894
|
+
return generation.fetch(request, { peerAddress: server.requestIP(request)?.address ?? null });
|
|
2895
|
+
const admission = await bridge.admit(request);
|
|
2896
|
+
if (!admission.ok)
|
|
2897
|
+
return admission.response;
|
|
2898
|
+
if (server.upgrade(request, { data: { connection: admission.connection } }))
|
|
2899
|
+
return void 0;
|
|
2900
|
+
await bridge.closed(admission.connection);
|
|
2901
|
+
return new Response("WebSocket upgrade required", { status: 426 });
|
|
2902
|
+
},
|
|
2903
|
+
websocket: {
|
|
2904
|
+
open(socket) {
|
|
2905
|
+
void bridge.opened(socket.data.connection, {
|
|
2906
|
+
send: (message) => {
|
|
2907
|
+
socket.send(message);
|
|
2908
|
+
},
|
|
2909
|
+
bufferedBytes: () => socket.getBufferedAmount(),
|
|
2910
|
+
close: (code, reason) => {
|
|
2911
|
+
socket.close(code, reason);
|
|
2912
|
+
}
|
|
2913
|
+
}).catch(() => {
|
|
2914
|
+
socket.close(1001, "realtime_unavailable");
|
|
2915
|
+
});
|
|
2916
|
+
},
|
|
2917
|
+
message(socket, frame) {
|
|
2918
|
+
void bridge.message(socket.data.connection, frame).catch(() => {
|
|
2919
|
+
socket.close(1001, "realtime_unavailable");
|
|
2920
|
+
});
|
|
2921
|
+
},
|
|
2922
|
+
close(socket) {
|
|
2923
|
+
void bridge.closed(socket.data.connection).catch(() => {
|
|
2924
|
+
});
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
};
|
|
2928
|
+
}
|
|
2929
|
+
|
|
2930
|
+
// ../runtime/dist/adapters/auth/better-auth/local-credentials.js
|
|
2931
|
+
import { createHmac, randomBytes, randomUUID } from "node:crypto";
|
|
2932
|
+
import { link, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
|
2933
|
+
import { isAbsolute as isAbsolute2, resolve as resolve6 } from "node:path";
|
|
2934
|
+
async function prepareLocalAuthEnvironment(environment) {
|
|
2935
|
+
if (environment.GENCOW_INTERNAL_TOKEN === void 0 && environment.GENCOW_SECRET_KEY_PATH === void 0) {
|
|
2936
|
+
const root = environment.GENCOW_APP_DATA_DIR;
|
|
2937
|
+
if (!root || !isAbsolute2(root)) {
|
|
2938
|
+
throw authStartupError("RUNTIME_AUTH_ACCESS_TOKEN_KEY_UNAVAILABLE", "Configure an absolute local app data directory before starting auth.");
|
|
2939
|
+
}
|
|
2940
|
+
const directory = resolve6(root, ".gencow");
|
|
2941
|
+
const keyPath = resolve6(directory, "secret.key");
|
|
2942
|
+
let existing;
|
|
2943
|
+
try {
|
|
2944
|
+
existing = await readFile(keyPath);
|
|
2945
|
+
} catch (error) {
|
|
2946
|
+
if (error.code !== "ENOENT") {
|
|
2947
|
+
throw authStartupError("RUNTIME_AUTH_ACCESS_TOKEN_KEY_UNAVAILABLE", "Make the existing local auth key readable before restarting.");
|
|
2948
|
+
}
|
|
2949
|
+
}
|
|
2950
|
+
if (existing === void 0) {
|
|
2951
|
+
const temporary = resolve6(directory, `.secret.key.${randomUUID()}.tmp`);
|
|
2952
|
+
try {
|
|
2953
|
+
await mkdir(directory, { recursive: true, mode: 448 });
|
|
2954
|
+
await writeFile(temporary, randomBytes(32), { flag: "wx", mode: 384 });
|
|
2955
|
+
try {
|
|
2956
|
+
await link(temporary, keyPath);
|
|
2957
|
+
} catch (error) {
|
|
2958
|
+
if (error.code !== "EEXIST")
|
|
2959
|
+
throw error;
|
|
2960
|
+
}
|
|
2961
|
+
} catch {
|
|
2962
|
+
throw authStartupError("RUNTIME_AUTH_ACCESS_TOKEN_KEY_UNAVAILABLE", "Make the project-local auth key directory writable before restarting.");
|
|
2963
|
+
} finally {
|
|
2964
|
+
await unlink(temporary).catch(() => {
|
|
2965
|
+
});
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
const accessTokenKey = await resolveServerCompatibleAccessTokenKey(environment);
|
|
2970
|
+
const betterAuthSecret = environment.BETTER_AUTH_SECRET === void 0 ? createHmac("sha256", accessTokenKey).update("gencow-local-better-auth-v1").digest("base64url") : environment.BETTER_AUTH_SECRET;
|
|
2971
|
+
return Object.freeze({ ...environment, BETTER_AUTH_SECRET: betterAuthSecret });
|
|
2972
|
+
}
|
|
2973
|
+
|
|
2974
|
+
// ../runtime/dist/local/administration-verifier.js
|
|
2975
|
+
function createLocalAdministrationVerifier(input) {
|
|
2976
|
+
const binding = snapshotRuntimeBinding(input);
|
|
2977
|
+
const identity = localDashboardIdentity(binding);
|
|
2978
|
+
return Object.freeze({
|
|
2979
|
+
async verify(request, target) {
|
|
2980
|
+
assertLocalDashboardRequest(request);
|
|
2981
|
+
if (target.operation !== "status.inspect") {
|
|
2982
|
+
const appId = request.headers.get("x-gencow-local-app");
|
|
2983
|
+
const generationId = request.headers.get("x-gencow-local-generation");
|
|
2984
|
+
const browser = ["origin", "sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest"].some((name) => request.headers.has(name));
|
|
2985
|
+
if ((browser || appId !== null || generationId !== null) && (appId !== identity.appId || generationId !== identity.generationId))
|
|
2986
|
+
return void 0;
|
|
2987
|
+
}
|
|
2988
|
+
return Object.freeze({ binding, operation: target.operation, target: target.target });
|
|
2989
|
+
}
|
|
2990
|
+
});
|
|
2991
|
+
}
|
|
2992
|
+
|
|
2993
|
+
// ../runtime/dist/local/operation-security.js
|
|
2994
|
+
function logLocalOperationSecurity(operations, logger) {
|
|
2995
|
+
const publicQueries = [
|
|
2996
|
+
...[...operations.procedureQueries].filter(([, value]) => value.allowAnonymous).map(([name]) => name),
|
|
2997
|
+
...[...operations.legacy?.queries ?? []].filter(([, value]) => value.isPublic).map(([name]) => name)
|
|
2998
|
+
];
|
|
2999
|
+
const publicMutations = [
|
|
3000
|
+
...[...operations.procedureMutations].filter(([, value]) => value.allowAnonymous).map(([name]) => name),
|
|
3001
|
+
...[...operations.legacy?.mutations ?? []].filter(([, value]) => value.isPublic).map(([name]) => name)
|
|
3002
|
+
];
|
|
3003
|
+
if (publicQueries.length || publicMutations.length) {
|
|
3004
|
+
logger.warn("runtime.local.public_operations", {
|
|
3005
|
+
"runtime.public_queries": publicQueries,
|
|
3006
|
+
"runtime.public_mutations": publicMutations,
|
|
3007
|
+
"runtime.security_notice": publicOperationSecurityNotice(publicQueries.length > 0)
|
|
3008
|
+
});
|
|
3009
|
+
}
|
|
3010
|
+
logger.info("runtime.local.operation_security", {
|
|
3011
|
+
"runtime.protected_query_count": operations.procedureQueries.size + (operations.legacy?.queries.size ?? 0) - publicQueries.length,
|
|
3012
|
+
"runtime.protected_mutation_count": operations.procedureMutations.size + (operations.legacy?.mutations.size ?? 0) - publicMutations.length
|
|
3013
|
+
});
|
|
3014
|
+
}
|
|
3015
|
+
|
|
3016
|
+
// ../runtime/dist/local.js
|
|
3017
|
+
function createLocalRuntimeHostContext(logSink, observations) {
|
|
3018
|
+
const sink = logSink ?? createConsoleRuntimeLogSink({
|
|
3019
|
+
write: (line) => process.stdout.write(`${line}
|
|
3020
|
+
`),
|
|
3021
|
+
writeError: (line) => process.stderr.write(`${line}
|
|
3022
|
+
`)
|
|
3023
|
+
});
|
|
3024
|
+
return createRuntimeHostContext(observations ? observations.tee(sink) : sink, {
|
|
3025
|
+
"runtime.target": "local"
|
|
3026
|
+
});
|
|
3027
|
+
}
|
|
3028
|
+
function firstExisting(paths) {
|
|
3029
|
+
return paths.find(existsSync7);
|
|
3030
|
+
}
|
|
3031
|
+
async function resumeIncompleteCleanup(resume) {
|
|
3032
|
+
let delay = 25;
|
|
3033
|
+
for (; ; ) {
|
|
3034
|
+
try {
|
|
3035
|
+
await resume();
|
|
3036
|
+
return;
|
|
3037
|
+
} catch (error) {
|
|
3038
|
+
if (runtimeDiagnostic(error)?.code !== "RUNTIME_DRAIN_INCOMPLETE")
|
|
3039
|
+
throw error;
|
|
3040
|
+
await new Promise((resolve8) => setTimeout(resolve8, delay));
|
|
3041
|
+
delay = Math.min(500, delay * 2);
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
async function startLocalRuntime(params) {
|
|
3046
|
+
assertRuntimeHost();
|
|
3047
|
+
const applicationMigration = captureApplicationMigrationOutcome(params.applicationMigration);
|
|
3048
|
+
try {
|
|
3049
|
+
const databaseSecurityPolicy = params.localFeatures?.database?.adapter === "postgres" ? captureTrustedLocalDatabaseSecurityPolicy(params.databaseSecurityPolicy) : void 0;
|
|
3050
|
+
const captured = { ...params, applicationMigration, databaseSecurityPolicy };
|
|
3051
|
+
return await startOwnedLocalRuntime(captured);
|
|
3052
|
+
} catch (error) {
|
|
3053
|
+
const failure = runtimeDiagnostic(error) ? error : runtimeStartupError("RUNTIME_COMPONENT_INITIALIZATION_FAILED", "Inspect selected local configuration and any earlier initialization effects before restarting. Preserve applied migration history.", "unknown");
|
|
3054
|
+
try {
|
|
3055
|
+
params.databaseWarnings?.render(createLocalRuntimeHostContext(params.logSink).logger);
|
|
3056
|
+
} catch {
|
|
3057
|
+
}
|
|
3058
|
+
throw withStartupMigrationImpacts(failure, applicationMigration, "none");
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
async function startOwnedLocalRuntime(params) {
|
|
3062
|
+
if (params.createDocumentConverter !== void 0 && typeof params.createDocumentConverter !== "function")
|
|
3063
|
+
throw new RuntimeDiagnosticError({
|
|
3064
|
+
code: "RUNTIME_COMPONENT_DEPENDENCY_INVALID",
|
|
3065
|
+
stage: "startup",
|
|
3066
|
+
capability: "application",
|
|
3067
|
+
dataImpact: "none",
|
|
3068
|
+
servingStarted: false,
|
|
3069
|
+
retryable: false,
|
|
3070
|
+
correlationId: crypto.randomUUID(),
|
|
3071
|
+
retryPrecondition: "Correct the trusted local document converter supplier before restarting.",
|
|
3072
|
+
nextAction: "Inspect Runtime/CLI versions with `pnpm why @gencow/runtime gencow`, restore the trusted local document converter factory and restart local Runtime. No provider work was admitted."
|
|
3073
|
+
});
|
|
3074
|
+
const createConverter = params.createDocumentConverter?.bind(void 0);
|
|
3075
|
+
const rag = params.rag === void 0 ? void 0 : Object.freeze({ ...params.rag });
|
|
3076
|
+
const dashboard = params.localFeatures?.dashboard?.enabled === true ? await captureLocalDashboardOptions(params.dashboard) : void 0;
|
|
3077
|
+
const root = resolve7(params.projectDir, params.rootDir);
|
|
3078
|
+
const entryPath = firstExisting([resolve7(root, "index.js"), resolve7(root, "index.ts")]);
|
|
3079
|
+
if (!entryPath) {
|
|
3080
|
+
throw new RuntimeDiagnosticError({
|
|
3081
|
+
code: "RUNTIME_APP_LOAD_FAILED",
|
|
3082
|
+
stage: "load",
|
|
3083
|
+
servingStarted: false,
|
|
3084
|
+
retryable: false,
|
|
3085
|
+
retryPrecondition: "Correct the app entry before restarting this Runtime generation.",
|
|
3086
|
+
nextAction: "Correct the app entry and restart the Runtime generation.",
|
|
3087
|
+
capability: "application"
|
|
3088
|
+
});
|
|
3089
|
+
}
|
|
3090
|
+
const authPath = firstExisting([resolve7(root, "auth.ts"), resolve7(root, "auth.js")]);
|
|
3091
|
+
const schemaPath = authPath ? firstExisting([
|
|
3092
|
+
"schema-auth.ts",
|
|
3093
|
+
"schema-auth.js",
|
|
3094
|
+
"schema.ts",
|
|
3095
|
+
"schema.js",
|
|
3096
|
+
"generated/auth-schema.ts",
|
|
3097
|
+
"generated/auth-schema.js",
|
|
3098
|
+
"auth-schema.ts",
|
|
3099
|
+
"auth-schema.js"
|
|
3100
|
+
].map((name) => resolve7(root, name))) : void 0;
|
|
3101
|
+
if (authPath && !schemaPath) {
|
|
3102
|
+
throw runtimeStartupError("RUNTIME_COMPONENT_DEPENDENCY_INVALID", "Correct selected component dependencies and restart.");
|
|
3103
|
+
}
|
|
3104
|
+
const suppliedEnvironment = params.environment ?? process.env;
|
|
3105
|
+
const environment = Object.freeze({
|
|
3106
|
+
...rag ? captureRagEmbeddingEnvironment(suppliedEnvironment) : {},
|
|
3107
|
+
__GENCOW_SEARCH_CAPABILITY_CONFIG: suppliedEnvironment.__GENCOW_SEARCH_CAPABILITY_CONFIG,
|
|
3108
|
+
__GENCOW_SEARCH_TIER_CONFIG: suppliedEnvironment.__GENCOW_SEARCH_TIER_CONFIG,
|
|
3109
|
+
...captureRuntimeWorkflowEnvironment(suppliedEnvironment),
|
|
3110
|
+
BETTER_AUTH_SECRET: suppliedEnvironment.BETTER_AUTH_SECRET,
|
|
3111
|
+
BETTER_AUTH_URL: suppliedEnvironment.BETTER_AUTH_URL,
|
|
3112
|
+
GENCOW_APP_NAME: suppliedEnvironment.GENCOW_APP_NAME,
|
|
3113
|
+
GENCOW_INTERNAL_TOKEN: suppliedEnvironment.GENCOW_INTERNAL_TOKEN,
|
|
3114
|
+
GENCOW_SECRET_KEY_PATH: suppliedEnvironment.GENCOW_SECRET_KEY_PATH,
|
|
3115
|
+
GENCOW_APP_DATA_DIR: suppliedEnvironment.GENCOW_APP_DATA_DIR || resolve7(params.projectDir),
|
|
3116
|
+
DATABASE_URL: suppliedEnvironment.DATABASE_URL,
|
|
3117
|
+
GENCOW_UNSAFE_DATABASE_URL: suppliedEnvironment.GENCOW_UNSAFE_DATABASE_URL,
|
|
3118
|
+
GENCOW_SETUP_DATABASE_URL: suppliedEnvironment.GENCOW_SETUP_DATABASE_URL,
|
|
3119
|
+
AZURE_CLIENT_ID: suppliedEnvironment.AZURE_CLIENT_ID,
|
|
3120
|
+
AZURE_TENANT_ID: suppliedEnvironment.AZURE_TENANT_ID,
|
|
3121
|
+
AZURE_CLIENT_SECRET: suppliedEnvironment.AZURE_CLIENT_SECRET
|
|
3122
|
+
});
|
|
3123
|
+
const authEnvironment = authPath && params.localFeatures?.database ? await prepareLocalAuthEnvironment(environment) : environment;
|
|
3124
|
+
const realtimeBridge = createRuntimeRealtimeListenerBridge();
|
|
3125
|
+
const resolution = {
|
|
3126
|
+
databaseWarnings: params.databaseWarnings,
|
|
3127
|
+
databaseSecurityPolicy: params.databaseSecurityPolicy,
|
|
3128
|
+
realtimeBridge,
|
|
3129
|
+
environment: authEnvironment,
|
|
3130
|
+
async loadModule(specifier) {
|
|
3131
|
+
return await (specifier.startsWith("file:") ? import(specifier) : import(pathToFileURL(specifier).href));
|
|
3132
|
+
}
|
|
3133
|
+
};
|
|
3134
|
+
const jobActivation = createRuntimeJobActivation();
|
|
3135
|
+
const selection = {
|
|
3136
|
+
search: params.localFeatures?.search,
|
|
3137
|
+
...rag === void 0 ? {} : { rag },
|
|
3138
|
+
realtime: { adapter: "local" },
|
|
3139
|
+
scheduler: { adapter: "local" },
|
|
3140
|
+
database: params.localFeatures?.database?.adapter === "pglite" ? { adapter: "pglite", dataDir: resolve7(params.projectDir, params.databasePath ?? "./.gencow/data") } : params.localFeatures?.database?.adapter === "postgres" ? { adapter: "postgres" } : void 0,
|
|
3141
|
+
storage: params.localFeatures?.storage?.adapter === "filesystem" ? {
|
|
3142
|
+
...params.localFeatures.storage,
|
|
3143
|
+
adapter: "filesystem",
|
|
3144
|
+
directory: resolve7(params.projectDir, params.storagePath ?? "./.gencow/uploads")
|
|
3145
|
+
} : params.localFeatures?.storage?.adapter === "azure-blob" ? params.localFeatures.storage : void 0,
|
|
3146
|
+
auth: authPath && schemaPath ? { authModule: authPath, schemaModule: schemaPath } : void 0
|
|
3147
|
+
};
|
|
3148
|
+
const appId = await resolveRuntimeProjectIdentity({
|
|
3149
|
+
projectDir: params.projectDir,
|
|
3150
|
+
sourceRoot: root,
|
|
3151
|
+
...params.standaloneEntryDir ? { artifactRoot: resolve7(params.projectDir, params.standaloneEntryDir) } : {},
|
|
3152
|
+
...selection.storage?.adapter === "filesystem" ? { storageDirectory: selection.storage.directory } : {}
|
|
3153
|
+
});
|
|
3154
|
+
const binding = Object.freeze({ appId, generationId: params.generationId ?? crypto.randomUUID() });
|
|
3155
|
+
const audit = await runLocalStartupAudit({
|
|
3156
|
+
projectRoot: params.projectDir,
|
|
3157
|
+
rootDir: params.rootDir,
|
|
3158
|
+
...params.audit,
|
|
3159
|
+
entryPath,
|
|
3160
|
+
strict: (params.environment?.GENCOW_STRICT ?? process.env.GENCOW_STRICT) === "true"
|
|
3161
|
+
});
|
|
3162
|
+
if (audit.blocked) {
|
|
3163
|
+
throw new RuntimeDiagnosticError({
|
|
3164
|
+
code: "RUNTIME_LOCAL_STARTUP_AUDIT_FAILED",
|
|
3165
|
+
stage: "startup",
|
|
3166
|
+
capability: "application",
|
|
3167
|
+
servingStarted: false,
|
|
3168
|
+
dataImpact: "unknown",
|
|
3169
|
+
retryable: false,
|
|
3170
|
+
retryPrecondition: "Correct the reported startup audit violations before restarting.",
|
|
3171
|
+
nextAction: "Review the preceding audit report, correct the flagged application code, and restart local development. Inspect any earlier startup effects before retrying.",
|
|
3172
|
+
correlationId: crypto.randomUUID()
|
|
3173
|
+
});
|
|
3174
|
+
}
|
|
3175
|
+
const observations = dashboard ? createLocalDashboardObservations(binding, params.appEnvironmentKeys ?? []) : void 0;
|
|
3176
|
+
const runtime = createLocalRuntimeHostContext(params.logSink, observations);
|
|
3177
|
+
const configuration = {
|
|
3178
|
+
selection,
|
|
3179
|
+
browser: {
|
|
3180
|
+
origin: authEnvironment.BETTER_AUTH_URL ?? `http://localhost:${params.port}`,
|
|
3181
|
+
frontendOrigins: params.frontendOrigins,
|
|
3182
|
+
trustedOrigins: params.trustedOrigins
|
|
3183
|
+
}
|
|
3184
|
+
};
|
|
3185
|
+
const loader = createLocalRuntimeApplicationLoader({ entryPath, importModule: resolution.loadModule });
|
|
3186
|
+
let warned = false;
|
|
3187
|
+
const generation = await composeRuntime({
|
|
3188
|
+
applicationMigration: params.applicationMigration,
|
|
3189
|
+
...createConverter ? {
|
|
3190
|
+
profile: {
|
|
3191
|
+
host: "standalone",
|
|
3192
|
+
admit: ({ binding: binding2, resolution: resolution2 }) => admitStandaloneProfile(configuration, binding2, resolution2, jobActivation.gate, createConverter)
|
|
3193
|
+
}
|
|
3194
|
+
} : configuration,
|
|
3195
|
+
jobActivation: jobActivation.gate,
|
|
3196
|
+
resolution,
|
|
3197
|
+
application: {
|
|
3198
|
+
async loadApplicationOnce() {
|
|
3199
|
+
const application = await loader.loadApplicationOnce();
|
|
3200
|
+
if (!warned) {
|
|
3201
|
+
warned = true;
|
|
3202
|
+
logLocalOperationSecurity(application.operations, runtime.logger);
|
|
3203
|
+
}
|
|
3204
|
+
return application;
|
|
3205
|
+
}
|
|
3206
|
+
},
|
|
3207
|
+
binding,
|
|
3208
|
+
schedulerStatusObserver: params.schedulerStatusObserver,
|
|
3209
|
+
localAdmin: {
|
|
3210
|
+
...dashboard ? { dashboard, observations, administrationVerifier: createLocalAdministrationVerifier(binding) } : {},
|
|
3211
|
+
seedModulePath: firstExisting([resolve7(root, "seed.ts"), resolve7(root, "seed.js")]),
|
|
3212
|
+
loadModule: resolution.loadModule
|
|
3213
|
+
},
|
|
3214
|
+
logger: runtime.logger
|
|
3215
|
+
}).catch((error) => {
|
|
3216
|
+
const cleanup = getRuntimeStartupCleanup(error);
|
|
3217
|
+
if (!cleanup)
|
|
3218
|
+
observations?.dispose();
|
|
3219
|
+
else {
|
|
3220
|
+
void resumeIncompleteCleanup(() => cleanup.resumeCleanup()).then(() => observations?.dispose(), () => {
|
|
3221
|
+
});
|
|
3222
|
+
}
|
|
3223
|
+
throw error;
|
|
3224
|
+
});
|
|
3225
|
+
let admissionClosed = false;
|
|
3226
|
+
const realtimeListener = createBunRealtimeListenerOptions(generation, realtimeBridge);
|
|
3227
|
+
const started = await startRuntimeBunListener({
|
|
3228
|
+
generation,
|
|
3229
|
+
serve: () => Bun.serve({
|
|
3230
|
+
hostname: "127.0.0.1",
|
|
3231
|
+
port: params.port,
|
|
3232
|
+
...realtimeListener,
|
|
3233
|
+
fetch(request, server) {
|
|
3234
|
+
if (admissionClosed)
|
|
3235
|
+
return generation.fetch(request);
|
|
3236
|
+
if (dashboard && isLocalDashboardSurface(new URL(request.url).pathname)) {
|
|
3237
|
+
try {
|
|
3238
|
+
assertLocalDashboardRequest(request, server.port);
|
|
3239
|
+
} catch {
|
|
3240
|
+
return localDashboardDenial(request);
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
return realtimeListener.fetch(request, server);
|
|
3244
|
+
}
|
|
3245
|
+
}),
|
|
3246
|
+
realtimeBridge,
|
|
3247
|
+
closeAdmission() {
|
|
3248
|
+
admissionClosed = true;
|
|
3249
|
+
},
|
|
3250
|
+
activate() {
|
|
3251
|
+
jobActivation.activate();
|
|
3252
|
+
},
|
|
3253
|
+
onReady(port) {
|
|
3254
|
+
runtime.logger.info("runtime.listener.ready", {
|
|
3255
|
+
"runtime.port": port,
|
|
3256
|
+
"runtime.scheduler.durability": "memory",
|
|
3257
|
+
"runtime.scheduler.timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
3258
|
+
"runtime.adapters": [
|
|
3259
|
+
"realtime:local",
|
|
3260
|
+
"scheduler:local",
|
|
3261
|
+
...selection.rag ? ["rag:pgvector"] : [],
|
|
3262
|
+
...selection.search ? ["search:postgres"] : [],
|
|
3263
|
+
...selection.database ? [`database:${selection.database.adapter}`] : [],
|
|
3264
|
+
...selection.storage ? [`storage:${selection.storage.adapter}`] : [],
|
|
3265
|
+
...selection.auth ? ["auth:better-auth"] : []
|
|
3266
|
+
]
|
|
3267
|
+
});
|
|
3268
|
+
},
|
|
3269
|
+
logger: runtime.logger
|
|
3270
|
+
});
|
|
3271
|
+
return { generation, ...started };
|
|
3272
|
+
}
|
|
3273
|
+
export {
|
|
3274
|
+
startLocalRuntime
|
|
3275
|
+
};
|