@rehearsal-db/core 0.1.0-beta.13 → 0.1.0-beta.15
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/CHANGELOG.md +93 -0
- package/README.md +4 -1
- package/dist/package.json +100 -0
- package/dist/scripts/install/create_root_config.d.mts +3 -0
- package/dist/scripts/install/create_root_config.mjs +13 -0
- package/dist/scripts/runtime/manage_database.d.mts +6 -0
- package/{scripts → dist/scripts}/runtime/manage_database.mjs +6 -8
- package/dist/src/application/session.d.mts +96 -0
- package/dist/src/application/session.mjs +380 -0
- package/dist/src/baseline/artifact.d.mts +119 -0
- package/dist/src/baseline/artifact.mjs +522 -0
- package/dist/src/baseline/builder.d.mts +19 -0
- package/dist/src/baseline/builder.mjs +142 -0
- package/dist/src/baseline/input_discovery.d.mts +13 -0
- package/dist/src/baseline/input_discovery.mjs +149 -0
- package/dist/src/baseline/policy_review.d.mts +56 -0
- package/dist/src/baseline/policy_review.mjs +73 -0
- package/dist/src/baseline/preparation.d.mts +63 -0
- package/dist/src/baseline/preparation.mjs +295 -0
- package/dist/src/baseline/privacy_engine.d.mts +162 -0
- package/dist/src/baseline/privacy_engine.mjs +1162 -0
- package/dist/src/baseline/privacy_structured_json.d.mts +66 -0
- package/dist/src/baseline/privacy_structured_json.mjs +464 -0
- package/dist/src/baseline/sanitization_policy.d.mts +69 -0
- package/dist/src/baseline/sanitization_policy.mjs +227 -0
- package/dist/src/baseline/schema_snapshot.d.mts +19 -0
- package/dist/src/baseline/schema_snapshot.mjs +79 -0
- package/dist/src/cli/arguments.d.mts +43 -0
- package/dist/src/cli/arguments.mjs +135 -0
- package/dist/src/cli/guided.d.mts +51 -0
- package/dist/src/cli/guided.mjs +713 -0
- package/dist/src/cli/init_command.d.mts +21 -0
- package/dist/src/cli/init_command.mjs +90 -0
- package/dist/src/cli/project_commands.d.mts +157 -0
- package/dist/src/cli/project_commands.mjs +183 -0
- package/dist/src/cli/rehearsal.d.mts +7 -0
- package/dist/src/cli/rehearsal.mjs +706 -0
- package/dist/src/cli/renderers.d.mts +299 -0
- package/dist/src/cli/renderers.mjs +554 -0
- package/dist/src/cli/runtime_commands.d.mts +265 -0
- package/dist/src/cli/runtime_commands.mjs +599 -0
- package/dist/src/cli/source_commands.d.mts +432 -0
- package/dist/src/cli/source_commands.mjs +299 -0
- package/dist/src/cli/terminal.d.mts +59 -0
- package/dist/src/cli/terminal.mjs +230 -0
- package/dist/src/identity/claim.d.mts +144 -0
- package/dist/src/identity/claim.mjs +947 -0
- package/dist/src/identity/provider_configuration.d.mts +37 -0
- package/dist/src/identity/provider_configuration.mjs +132 -0
- package/dist/src/identity/storage.d.mts +21 -0
- package/dist/src/identity/storage.mjs +122 -0
- package/dist/src/index.d.mts +4 -0
- package/dist/src/index.mjs +3 -0
- package/dist/src/project/configuration.d.mts +181 -0
- package/dist/src/project/configuration.mjs +958 -0
- package/dist/src/project/install_scaffold.d.mts +42 -0
- package/dist/src/project/install_scaffold.mjs +263 -0
- package/dist/src/project/setup.d.mts +87 -0
- package/dist/src/project/setup.mjs +414 -0
- package/dist/src/project/support_report.d.mts +88 -0
- package/dist/src/project/support_report.mjs +83 -0
- package/dist/src/runtime/cleanup.d.mts +85 -0
- package/dist/src/runtime/cleanup.mjs +311 -0
- package/dist/src/runtime/migration_history.d.mts +51 -0
- package/dist/src/runtime/migration_history.mjs +170 -0
- package/dist/src/runtime/plan.d.mts +134 -0
- package/dist/src/runtime/plan.mjs +636 -0
- package/dist/src/runtime/policy.d.mts +66 -0
- package/dist/src/runtime/policy.mjs +369 -0
- package/dist/src/runtime/restore.d.mts +22 -0
- package/dist/src/runtime/restore.mjs +276 -0
- package/dist/src/runtime/service_environment.d.mts +11 -0
- package/dist/src/runtime/service_environment.mjs +58 -0
- package/dist/src/runtime/topology.d.mts +51 -0
- package/dist/src/runtime/topology.mjs +128 -0
- package/dist/src/shared/diagnostics.d.mts +97 -0
- package/dist/src/shared/diagnostics.mjs +170 -0
- package/dist/src/shared/human_output.d.mts +2 -0
- package/{src → dist/src}/shared/human_output.mjs +1 -3
- package/dist/src/shared/node_runtime.d.mts +14 -0
- package/dist/src/shared/node_runtime.mjs +25 -0
- package/dist/src/shared/operation_guard.d.mts +22 -0
- package/dist/src/shared/operation_guard.mjs +150 -0
- package/dist/src/shared/process_environment.d.mts +15 -0
- package/dist/src/shared/process_environment.mjs +50 -0
- package/dist/src/source/access.d.mts +165 -0
- package/dist/src/source/access.mjs +602 -0
- package/dist/src/source/asset_transfer.d.mts +27 -0
- package/dist/src/source/asset_transfer.mjs +202 -0
- package/dist/src/source/baseline.d.mts +66 -0
- package/dist/src/source/baseline.mjs +372 -0
- package/dist/src/source/external_reader.d.mts +42 -0
- package/dist/src/source/external_reader.mjs +278 -0
- package/dist/src/source/postgresql_access.d.mts +86 -0
- package/dist/src/source/postgresql_access.mjs +454 -0
- package/dist/src/source/privacy_paths.d.mts +10 -0
- package/dist/src/source/privacy_paths.mjs +27 -0
- package/dist/src/targets/driver.d.mts +2 -0
- package/dist/src/targets/driver.mjs +13 -0
- package/dist/src/targets/postgresql.d.mts +5 -0
- package/dist/src/targets/postgresql.mjs +641 -0
- package/dist/src/targets/supabase.d.mts +8 -0
- package/dist/src/targets/supabase.mjs +659 -0
- package/dist/src/targets/supabase_environment.d.mts +49 -0
- package/dist/src/targets/supabase_environment.mjs +162 -0
- package/dist/src/targets/target.d.mts +33 -0
- package/dist/src/targets/target.mjs +39 -0
- package/docs/README.md +1 -0
- package/docs/architecture.md +17 -9
- package/docs/configuration.md +49 -8
- package/docs/getting-started.md +28 -0
- package/docs/index.md +1 -0
- package/docs/production-source.md +43 -7
- package/docs/releasing.md +5 -3
- package/docs/roadmap.md +3 -2
- package/docs/sanitization.md +415 -14
- package/docs/standalone-workflow.md +12 -6
- package/docs/troubleshooting.md +5 -1
- package/docs/tutorial.md +5 -0
- package/docs/typescript.md +87 -0
- package/package.json +35 -29
- package/scripts/install/create_root_config.mjs +0 -36
- package/src/README.md +0 -17
- package/src/application/session.mjs +0 -435
- package/src/baseline/artifact.mjs +0 -684
- package/src/baseline/builder.mjs +0 -164
- package/src/baseline/input_discovery.mjs +0 -155
- package/src/baseline/policy_review.mjs +0 -92
- package/src/baseline/preparation.mjs +0 -323
- package/src/baseline/privacy_engine.mjs +0 -952
- package/src/baseline/sanitization_policy.mjs +0 -299
- package/src/baseline/schema_snapshot.mjs +0 -113
- package/src/cli/arguments.mjs +0 -126
- package/src/cli/guided.mjs +0 -814
- package/src/cli/init_command.mjs +0 -94
- package/src/cli/rehearsal.mjs +0 -970
- package/src/cli/renderers.mjs +0 -626
- package/src/cli/runtime_commands.mjs +0 -707
- package/src/cli/source_commands.mjs +0 -347
- package/src/cli/terminal.mjs +0 -275
- package/src/identity/claim.mjs +0 -1163
- package/src/identity/provider_configuration.mjs +0 -177
- package/src/identity/storage.mjs +0 -165
- package/src/project/configuration.mjs +0 -1337
- package/src/project/install_scaffold.mjs +0 -291
- package/src/project/setup.mjs +0 -466
- package/src/project/support_report.mjs +0 -105
- package/src/runtime/cleanup.mjs +0 -381
- package/src/runtime/migration_history.mjs +0 -220
- package/src/runtime/plan.mjs +0 -722
- package/src/runtime/policy.mjs +0 -438
- package/src/runtime/restore.mjs +0 -337
- package/src/runtime/service_environment.mjs +0 -82
- package/src/runtime/topology.mjs +0 -177
- package/src/shared/diagnostics.mjs +0 -207
- package/src/shared/node_runtime.mjs +0 -31
- package/src/shared/operation_guard.mjs +0 -162
- package/src/shared/process_environment.mjs +0 -68
- package/src/source/access.mjs +0 -753
- package/src/source/asset_transfer.mjs +0 -207
- package/src/source/baseline.mjs +0 -482
- package/src/source/external_reader.mjs +0 -255
- package/src/source/postgresql_access.mjs +0 -581
- package/src/source/privacy_paths.mjs +0 -38
- package/src/targets/postgresql.mjs +0 -808
- package/src/targets/supabase.mjs +0 -840
- package/src/targets/supabase_environment.mjs +0 -229
- package/src/targets/target.mjs +0 -66
- /package/{src/project → types}/configuration.d.mts +0 -0
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
/** Launch ordinary application commands against verified local runtime files. */
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { readFile, stat } from "node:fs/promises";
|
|
4
|
+
import { parseEnv } from "node:util";
|
|
5
|
+
import { createCleanProcessEnvironment, isLoopbackUrl, } from "../shared/process_environment.mjs";
|
|
6
|
+
const ENV_KEY = /^[A-Z][A-Z0-9_]*$/u;
|
|
7
|
+
const MAX_DIAGNOSTIC_BYTES = 64 * 1024;
|
|
8
|
+
const SESSION_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP", "SIGTSTP"];
|
|
9
|
+
const parseCommand = (source) => {
|
|
10
|
+
if (typeof source !== "string" || !source.trim())
|
|
11
|
+
throw new Error("Application command is empty.");
|
|
12
|
+
const values = [];
|
|
13
|
+
let value = "";
|
|
14
|
+
let quote = null;
|
|
15
|
+
for (const character of source) {
|
|
16
|
+
if (quote) {
|
|
17
|
+
if (character === quote)
|
|
18
|
+
quote = null;
|
|
19
|
+
else
|
|
20
|
+
value += character;
|
|
21
|
+
}
|
|
22
|
+
else if (character === '"' || character === "'")
|
|
23
|
+
quote = character;
|
|
24
|
+
else if (/\s/u.test(character)) {
|
|
25
|
+
if (value)
|
|
26
|
+
values.push(value);
|
|
27
|
+
value = "";
|
|
28
|
+
}
|
|
29
|
+
else
|
|
30
|
+
value += character;
|
|
31
|
+
}
|
|
32
|
+
if (quote)
|
|
33
|
+
throw new Error("Application command contains an unmatched quote.");
|
|
34
|
+
if (value)
|
|
35
|
+
values.push(value);
|
|
36
|
+
const [program, ...args] = values;
|
|
37
|
+
if (!program)
|
|
38
|
+
throw new Error("Application command is empty.");
|
|
39
|
+
return [program, ...args];
|
|
40
|
+
};
|
|
41
|
+
const readOwnedEnvironment = async (path) => {
|
|
42
|
+
const details = await stat(path);
|
|
43
|
+
if (!details.isFile() || (details.mode & 0o077) !== 0) {
|
|
44
|
+
throw new Error("Runtime environment file must be an owner-only regular file.");
|
|
45
|
+
}
|
|
46
|
+
const parsed = parseEnv(await readFile(path, "utf8"));
|
|
47
|
+
return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "string"));
|
|
48
|
+
};
|
|
49
|
+
const assertLocalValue = (key, value) => {
|
|
50
|
+
if (/(_URL|_URI|_ENDPOINT)$/u.test(key)) {
|
|
51
|
+
let parsed;
|
|
52
|
+
try {
|
|
53
|
+
parsed = new URL(value);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
throw new Error(`Mapped runtime variable ${key} is not a URL.`);
|
|
57
|
+
}
|
|
58
|
+
if (!isLoopbackUrl(value) &&
|
|
59
|
+
!["postgres:", "postgresql:"].includes(parsed.protocol)) {
|
|
60
|
+
throw new Error(`Mapped runtime variable ${key} is not local.`);
|
|
61
|
+
}
|
|
62
|
+
if (["postgres:", "postgresql:"].includes(parsed.protocol) &&
|
|
63
|
+
!["127.0.0.1", "::1", "localhost"].includes(parsed.hostname)) {
|
|
64
|
+
throw new Error(`Mapped runtime variable ${key} is not local.`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
export const buildApplicationEnvironment = async ({ files, mappings, }) => {
|
|
69
|
+
if (!files?.primary)
|
|
70
|
+
throw new Error("Primary runtime environment file is required.");
|
|
71
|
+
const environments = {};
|
|
72
|
+
for (const [name, path] of Object.entries(files)) {
|
|
73
|
+
environments[name] = await readOwnedEnvironment(path);
|
|
74
|
+
}
|
|
75
|
+
if (!mappings || typeof mappings !== "object" || Array.isArray(mappings)) {
|
|
76
|
+
throw new Error("Application environment mappings must be an object.");
|
|
77
|
+
}
|
|
78
|
+
const result = {};
|
|
79
|
+
for (const [destination, reference] of Object.entries(mappings)) {
|
|
80
|
+
if (!ENV_KEY.test(destination) || typeof reference !== "string") {
|
|
81
|
+
throw new Error("Application environment mapping is invalid.");
|
|
82
|
+
}
|
|
83
|
+
const separator = reference.indexOf(":");
|
|
84
|
+
if (separator < 1)
|
|
85
|
+
throw new Error(`Application mapping ${destination} has an invalid reference.`);
|
|
86
|
+
const target = reference.slice(0, separator);
|
|
87
|
+
const source = reference.slice(separator + 1);
|
|
88
|
+
const sourceValue = environments[target]?.[source];
|
|
89
|
+
if (!ENV_KEY.test(source) || !sourceValue) {
|
|
90
|
+
throw new Error(`Application mapping ${destination} references a missing runtime value.`);
|
|
91
|
+
}
|
|
92
|
+
assertLocalValue(source, sourceValue);
|
|
93
|
+
result[destination] = sourceValue;
|
|
94
|
+
}
|
|
95
|
+
return result;
|
|
96
|
+
};
|
|
97
|
+
const boundedAppend = (current, chunk) => `${current}${chunk}`.slice(-MAX_DIAGNOSTIC_BYTES);
|
|
98
|
+
const childHasExited = (child) => child.exitCode !== null || child.signalCode !== null;
|
|
99
|
+
const waitForChildExit = (child) => {
|
|
100
|
+
if (childHasExited(child)) {
|
|
101
|
+
return Promise.resolve({
|
|
102
|
+
status: child.exitCode,
|
|
103
|
+
signal: child.signalCode,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return new Promise((resolve) => {
|
|
107
|
+
child.once("exit", (status, signal) => resolve({ status, signal }));
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
export const summarizeProjectCommandFailure = ({ error, status, signal, stdout = "", stderr = "", stdoutByteCount, stderrByteCount, }) => {
|
|
111
|
+
const stdoutBytes = stdoutByteCount ?? Buffer.byteLength(String(stdout));
|
|
112
|
+
const stderrBytes = stderrByteCount ?? Buffer.byteLength(String(stderr));
|
|
113
|
+
if (error) {
|
|
114
|
+
const code = /^[A-Z0-9_]+$/u.test(error.code ?? "")
|
|
115
|
+
? ` (${error.code})`
|
|
116
|
+
: "";
|
|
117
|
+
return `command could not start${code}; output withheld`;
|
|
118
|
+
}
|
|
119
|
+
const outcome = signal
|
|
120
|
+
? `signal ${signal}`
|
|
121
|
+
: `exit ${Number.isInteger(status) ? status : "unknown"}`;
|
|
122
|
+
return `${outcome}; stdout ${stdoutBytes} bytes; stderr ${stderrBytes} bytes; output withheld`;
|
|
123
|
+
};
|
|
124
|
+
const waitForReadiness = async ({ readiness, fetchImplementation, child, }) => {
|
|
125
|
+
if (!readiness || !isLoopbackUrl(readiness.url)) {
|
|
126
|
+
throw new Error("Application readiness must use a loopback URL.");
|
|
127
|
+
}
|
|
128
|
+
const expected = readiness.expectedStatus ?? 200;
|
|
129
|
+
const deadline = Date.now() + (readiness.timeoutSeconds ?? 30) * 1_000;
|
|
130
|
+
let lastStatus = null;
|
|
131
|
+
while (Date.now() < deadline) {
|
|
132
|
+
if (childHasExited(child))
|
|
133
|
+
throw new Error("Application exited before becoming ready.");
|
|
134
|
+
try {
|
|
135
|
+
const response = await fetchImplementation(readiness.url, {
|
|
136
|
+
redirect: "manual",
|
|
137
|
+
signal: AbortSignal.timeout(2_000),
|
|
138
|
+
});
|
|
139
|
+
lastStatus = response.status;
|
|
140
|
+
if (response.status === expected)
|
|
141
|
+
return { url: readiness.url, status: response.status };
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// A bounded retry is expected while the local process starts.
|
|
145
|
+
}
|
|
146
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
147
|
+
}
|
|
148
|
+
throw new Error(`Application readiness timed out${lastStatus === null ? "" : ` after HTTP ${lastStatus}`}.`);
|
|
149
|
+
};
|
|
150
|
+
const stopOwnedChild = async (child) => {
|
|
151
|
+
if (childHasExited(child))
|
|
152
|
+
return;
|
|
153
|
+
const exit = waitForChildExit(child);
|
|
154
|
+
const kill = (signal) => {
|
|
155
|
+
try {
|
|
156
|
+
if (process.platform === "win32")
|
|
157
|
+
child.kill(signal);
|
|
158
|
+
else {
|
|
159
|
+
if (child.pid === undefined) {
|
|
160
|
+
throw new Error("Application child process has no process identifier.");
|
|
161
|
+
}
|
|
162
|
+
process.kill(-child.pid, signal);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
if (typeof error !== "object" ||
|
|
167
|
+
error === null ||
|
|
168
|
+
!("code" in error) ||
|
|
169
|
+
error.code !== "ESRCH")
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
kill("SIGTERM");
|
|
174
|
+
await Promise.race([
|
|
175
|
+
exit,
|
|
176
|
+
new Promise((resolve) => setTimeout(resolve, 5_000)),
|
|
177
|
+
]);
|
|
178
|
+
if (!childHasExited(child)) {
|
|
179
|
+
kill("SIGKILL");
|
|
180
|
+
await exit;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
export const startApplicationSession = async ({ command, cwd, files, mappings, readiness, inheritedEnvironment = process.env, spawnImplementation = spawn, fetchImplementation = fetch, signalTarget = process, }) => {
|
|
184
|
+
const mapped = await buildApplicationEnvironment({ files, mappings });
|
|
185
|
+
const [program, ...args] = parseCommand(command);
|
|
186
|
+
const child = spawnImplementation(program, args, {
|
|
187
|
+
cwd,
|
|
188
|
+
env: createCleanProcessEnvironment({
|
|
189
|
+
inheritedEnvironment,
|
|
190
|
+
overrides: mapped,
|
|
191
|
+
}),
|
|
192
|
+
detached: process.platform !== "win32",
|
|
193
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
194
|
+
});
|
|
195
|
+
let stdout = "";
|
|
196
|
+
let stderr = "";
|
|
197
|
+
child.stdout?.on("data", (chunk) => {
|
|
198
|
+
stdout = boundedAppend(stdout, chunk.toString("utf8"));
|
|
199
|
+
});
|
|
200
|
+
child.stderr?.on("data", (chunk) => {
|
|
201
|
+
stderr = boundedAppend(stderr, chunk.toString("utf8"));
|
|
202
|
+
});
|
|
203
|
+
await new Promise((resolve, reject) => {
|
|
204
|
+
child.once("spawn", resolve);
|
|
205
|
+
child.once("error", reject);
|
|
206
|
+
});
|
|
207
|
+
let interruptStartup = () => undefined;
|
|
208
|
+
const interruption = new Promise((_, reject) => {
|
|
209
|
+
interruptStartup = (signal) => reject(new Error(`Application startup was interrupted by ${signal}.`));
|
|
210
|
+
});
|
|
211
|
+
const startupHandlers = new Map(SESSION_SIGNALS.map((signal) => [signal, () => interruptStartup(signal)]));
|
|
212
|
+
for (const [signal, handler] of startupHandlers) {
|
|
213
|
+
signalTarget.prependListener(signal, handler);
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
const ready = await Promise.race([
|
|
217
|
+
waitForReadiness({
|
|
218
|
+
readiness,
|
|
219
|
+
fetchImplementation,
|
|
220
|
+
child,
|
|
221
|
+
}),
|
|
222
|
+
interruption,
|
|
223
|
+
]);
|
|
224
|
+
return Object.freeze({
|
|
225
|
+
pid: child.pid,
|
|
226
|
+
ready,
|
|
227
|
+
stop: () => stopOwnedChild(child),
|
|
228
|
+
wait: () => waitForChildExit(child),
|
|
229
|
+
diagnostics: () => ({
|
|
230
|
+
stdoutBytes: Buffer.byteLength(stdout),
|
|
231
|
+
stderrBytes: Buffer.byteLength(stderr),
|
|
232
|
+
}),
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
await stopOwnedChild(child);
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
for (const [signal, handler] of startupHandlers) {
|
|
241
|
+
signalTarget.removeListener(signal, handler);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
/**
|
|
246
|
+
* Keep a ready application session attached until the user interrupts it.
|
|
247
|
+
* The child process group is always stopped before this function returns.
|
|
248
|
+
*/
|
|
249
|
+
export const holdApplicationSession = async ({ session, signalTarget = process, input = process.stdin, onReady = () => undefined, }) => {
|
|
250
|
+
if (!session ||
|
|
251
|
+
typeof session.wait !== "function" ||
|
|
252
|
+
typeof session.stop !== "function") {
|
|
253
|
+
throw new Error("A started application session is required.");
|
|
254
|
+
}
|
|
255
|
+
let finishInterruption = () => undefined;
|
|
256
|
+
const interruption = new Promise((resolve) => {
|
|
257
|
+
finishInterruption = resolve;
|
|
258
|
+
});
|
|
259
|
+
const handlers = new Map(SESSION_SIGNALS.map((signal) => [
|
|
260
|
+
signal,
|
|
261
|
+
() => finishInterruption({ kind: "interrupted", signal }),
|
|
262
|
+
]));
|
|
263
|
+
for (const [signal, handler] of handlers) {
|
|
264
|
+
signalTarget.prependListener(signal, handler);
|
|
265
|
+
}
|
|
266
|
+
const onInput = (chunk) => {
|
|
267
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
268
|
+
if (bytes.includes(0x03)) {
|
|
269
|
+
finishInterruption({ kind: "interrupted", signal: "SIGINT" });
|
|
270
|
+
}
|
|
271
|
+
else if (bytes.includes(0x1a)) {
|
|
272
|
+
finishInterruption({ kind: "interrupted", signal: "SIGTSTP" });
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
if (input?.isTTY)
|
|
276
|
+
input.prependListener("data", onInput);
|
|
277
|
+
try {
|
|
278
|
+
onReady(session.ready);
|
|
279
|
+
const outcome = await Promise.race([
|
|
280
|
+
interruption,
|
|
281
|
+
session.wait().then((exit) => ({ kind: "exited", ...exit })),
|
|
282
|
+
]);
|
|
283
|
+
if (outcome.kind === "exited") {
|
|
284
|
+
const diagnostics = session.diagnostics?.() ?? {};
|
|
285
|
+
throw new Error(`Application exited before the sandbox was closed (${summarizeProjectCommandFailure({
|
|
286
|
+
status: outcome.status,
|
|
287
|
+
signal: outcome.signal,
|
|
288
|
+
stdoutByteCount: diagnostics.stdoutBytes ?? 0,
|
|
289
|
+
stderrByteCount: diagnostics.stderrBytes ?? 0,
|
|
290
|
+
})}).`);
|
|
291
|
+
}
|
|
292
|
+
return Object.freeze({
|
|
293
|
+
signal: outcome.signal,
|
|
294
|
+
diagnostics: session.diagnostics?.() ?? {
|
|
295
|
+
stdoutBytes: 0,
|
|
296
|
+
stderrBytes: 0,
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
finally {
|
|
301
|
+
try {
|
|
302
|
+
// npm can forward the terminal's SIGINT after the CLI receives it.
|
|
303
|
+
// Keep our handlers installed until the owned process group is fully
|
|
304
|
+
// stopped so a duplicate signal cannot terminate Rehearsal mid-cleanup.
|
|
305
|
+
await session.stop();
|
|
306
|
+
}
|
|
307
|
+
finally {
|
|
308
|
+
for (const [signal, handler] of handlers) {
|
|
309
|
+
signalTarget.removeListener(signal, handler);
|
|
310
|
+
}
|
|
311
|
+
if (input?.isTTY)
|
|
312
|
+
input.removeListener("data", onInput);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
const valueAtPath = (value, path) => {
|
|
317
|
+
let current = value;
|
|
318
|
+
for (const segment of path) {
|
|
319
|
+
if (current === null ||
|
|
320
|
+
typeof current !== "object" ||
|
|
321
|
+
!Object.hasOwn(current, segment)) {
|
|
322
|
+
return undefined;
|
|
323
|
+
}
|
|
324
|
+
current = current[segment];
|
|
325
|
+
}
|
|
326
|
+
return current;
|
|
327
|
+
};
|
|
328
|
+
export const runHttpProofs = async ({ checks, fetchImplementation = fetch, }) => {
|
|
329
|
+
if (!Array.isArray(checks) || checks.length < 2) {
|
|
330
|
+
throw new Error("HTTP proof requires explicit positive and negative checks.");
|
|
331
|
+
}
|
|
332
|
+
if (!checks.some((check) => check.kind === "positive") ||
|
|
333
|
+
!checks.some((check) => check.kind === "negative")) {
|
|
334
|
+
throw new Error("HTTP proof requires at least one positive and one negative check.");
|
|
335
|
+
}
|
|
336
|
+
const results = [];
|
|
337
|
+
for (const check of checks) {
|
|
338
|
+
if (!isLoopbackUrl(check.url))
|
|
339
|
+
throw new Error(`HTTP proof ${check.name} is not local.`);
|
|
340
|
+
const response = await fetchImplementation(check.url, {
|
|
341
|
+
method: check.method ?? "GET",
|
|
342
|
+
redirect: "manual",
|
|
343
|
+
signal: AbortSignal.timeout(check.timeoutMs ?? 5_000),
|
|
344
|
+
});
|
|
345
|
+
if (response.status !== check.expectedStatus) {
|
|
346
|
+
throw new Error(`HTTP proof ${check.name} expected status ${check.expectedStatus} but received ${response.status}.`);
|
|
347
|
+
}
|
|
348
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
349
|
+
if (bytes.length > 1024 * 1024)
|
|
350
|
+
throw new Error(`HTTP proof ${check.name} returned too much data.`);
|
|
351
|
+
if (check.json) {
|
|
352
|
+
let parsed;
|
|
353
|
+
try {
|
|
354
|
+
parsed = JSON.parse(bytes.toString("utf8"));
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
throw new Error(`HTTP proof ${check.name} did not return JSON.`);
|
|
358
|
+
}
|
|
359
|
+
const actual = valueAtPath(parsed, check.json.path);
|
|
360
|
+
if (Object.hasOwn(check.json, "equals") &&
|
|
361
|
+
!Object.is(actual, check.json.equals)) {
|
|
362
|
+
throw new Error(`HTTP proof ${check.name} did not return its required value.`);
|
|
363
|
+
}
|
|
364
|
+
if (Object.hasOwn(check.json, "notEquals") &&
|
|
365
|
+
Object.is(actual, check.json.notEquals)) {
|
|
366
|
+
throw new Error(`HTTP proof ${check.name} returned a forbidden value.`);
|
|
367
|
+
}
|
|
368
|
+
if (check.json.minimumItems !== undefined &&
|
|
369
|
+
(!Array.isArray(actual) || actual.length < check.json.minimumItems)) {
|
|
370
|
+
throw new Error(`HTTP proof ${check.name} returned too few matching items.`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
results.push({
|
|
374
|
+
name: check.name,
|
|
375
|
+
kind: check.kind,
|
|
376
|
+
status: response.status,
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
return Object.freeze(results);
|
|
380
|
+
};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Purpose: Write, verify, and atomically activate immutable sanitized Rehearsal
|
|
3
|
+
* baseline generations. Do not run directly; this module is reusable script
|
|
4
|
+
* infrastructure.
|
|
5
|
+
*/
|
|
6
|
+
import { type MigrationLedgerEntry } from "../runtime/migration_history.mjs";
|
|
7
|
+
type ByteChunk = string | Uint8Array;
|
|
8
|
+
type ByteStream = Iterable<ByteChunk> | AsyncIterable<ByteChunk>;
|
|
9
|
+
export interface BaselineRecord {
|
|
10
|
+
readonly schema?: string;
|
|
11
|
+
readonly table: string;
|
|
12
|
+
readonly row: Readonly<Record<string, unknown>>;
|
|
13
|
+
}
|
|
14
|
+
export interface BaselineMigrationFile {
|
|
15
|
+
readonly filename: string;
|
|
16
|
+
readonly content: string;
|
|
17
|
+
readonly fileSha256?: string;
|
|
18
|
+
readonly version?: string;
|
|
19
|
+
readonly name?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface BaselineStorageAsset {
|
|
22
|
+
readonly bucket: string;
|
|
23
|
+
readonly objectPath: string;
|
|
24
|
+
readonly contentType?: string;
|
|
25
|
+
readonly content: Buffer | ByteStream;
|
|
26
|
+
}
|
|
27
|
+
export interface BaselineMetadata extends Record<string, unknown> {
|
|
28
|
+
readonly migrationCutoff: string;
|
|
29
|
+
readonly migrationHistorySha256: string;
|
|
30
|
+
readonly sanitizationPolicySha256: string;
|
|
31
|
+
readonly sourceMigrationHistory?: readonly MigrationLedgerEntry[];
|
|
32
|
+
}
|
|
33
|
+
interface ContentReceipt {
|
|
34
|
+
readonly sha256: string;
|
|
35
|
+
readonly bytes: number;
|
|
36
|
+
}
|
|
37
|
+
interface StorageAssetReceipt extends ContentReceipt {
|
|
38
|
+
readonly bucket: string;
|
|
39
|
+
readonly objectPath: string;
|
|
40
|
+
readonly contentType: string;
|
|
41
|
+
}
|
|
42
|
+
export interface BaselineManifest extends BaselineMetadata {
|
|
43
|
+
readonly formatVersion: 1 | 2;
|
|
44
|
+
readonly generationId: string;
|
|
45
|
+
readonly rowCount: number;
|
|
46
|
+
readonly tableCounts: Readonly<Record<string, number>>;
|
|
47
|
+
readonly files: Readonly<Record<string, Readonly<{
|
|
48
|
+
sha256: string;
|
|
49
|
+
rows?: number;
|
|
50
|
+
bytes?: number;
|
|
51
|
+
}>>>;
|
|
52
|
+
readonly storageAssets: Readonly<Record<string, StorageAssetReceipt>>;
|
|
53
|
+
readonly migrations: Readonly<Record<string, Readonly<{
|
|
54
|
+
sha256: string;
|
|
55
|
+
}>>>;
|
|
56
|
+
}
|
|
57
|
+
export interface ActiveBaselinePaths {
|
|
58
|
+
readonly artifactRoot: string;
|
|
59
|
+
readonly generationDirectory: string;
|
|
60
|
+
readonly dataPath: string;
|
|
61
|
+
readonly manifestPath: string;
|
|
62
|
+
readonly migrationsDirectory: string;
|
|
63
|
+
readonly schemaPath: string;
|
|
64
|
+
}
|
|
65
|
+
export interface BaselinePrunePlan {
|
|
66
|
+
readonly retained: string[];
|
|
67
|
+
readonly removed: string[];
|
|
68
|
+
}
|
|
69
|
+
export declare const createBaselineGenerationId: ({ now, }?: {
|
|
70
|
+
now?: Date;
|
|
71
|
+
}) => string;
|
|
72
|
+
export declare const createAndActivateBaseline: ({ artifactRoot, generationId, records, metadata, expectedTables, migrationFiles, assets, schemaSql, activate, }: {
|
|
73
|
+
artifactRoot: string;
|
|
74
|
+
generationId?: string;
|
|
75
|
+
records: Iterable<unknown> | AsyncIterable<unknown>;
|
|
76
|
+
metadata: BaselineMetadata;
|
|
77
|
+
expectedTables?: readonly string[];
|
|
78
|
+
migrationFiles?: readonly BaselineMigrationFile[] | Promise<readonly BaselineMigrationFile[]> | (() => readonly BaselineMigrationFile[] | Promise<readonly BaselineMigrationFile[]>);
|
|
79
|
+
assets?: Iterable<BaselineStorageAsset> | AsyncIterable<BaselineStorageAsset>;
|
|
80
|
+
schemaSql?: string | null;
|
|
81
|
+
activate?: boolean;
|
|
82
|
+
}) => Promise<BaselineManifest>;
|
|
83
|
+
export declare const activateBaselineGeneration: ({ artifactRoot, generationId, }: {
|
|
84
|
+
artifactRoot: string;
|
|
85
|
+
generationId: string;
|
|
86
|
+
}) => Promise<BaselineManifest>;
|
|
87
|
+
export declare const removeStagedBaselineGeneration: ({ artifactRoot, generationId, }: {
|
|
88
|
+
artifactRoot: string;
|
|
89
|
+
generationId: string;
|
|
90
|
+
}) => Promise<void>;
|
|
91
|
+
export declare const resolveActiveBaselinePaths: ({ artifactRoot, }: {
|
|
92
|
+
artifactRoot: string;
|
|
93
|
+
}) => Promise<ActiveBaselinePaths>;
|
|
94
|
+
export declare const verifyActiveBaseline: ({ artifactRoot, }: {
|
|
95
|
+
artifactRoot: string;
|
|
96
|
+
}) => Promise<BaselineManifest>;
|
|
97
|
+
export declare const listIncompleteBaselineBuilds: ({ artifactRoot, }: {
|
|
98
|
+
artifactRoot: string;
|
|
99
|
+
}) => Promise<string[]>;
|
|
100
|
+
export declare const planBaselineGenerationPrune: ({ artifactRoot, retain, }: {
|
|
101
|
+
artifactRoot: string;
|
|
102
|
+
retain?: number;
|
|
103
|
+
}) => Promise<BaselinePrunePlan>;
|
|
104
|
+
export declare const planBaselineReplacementPrune: ({ artifactRoot, retain, }: {
|
|
105
|
+
artifactRoot: string;
|
|
106
|
+
retain?: number;
|
|
107
|
+
}) => Promise<{
|
|
108
|
+
retainedAfterReplacement: string[];
|
|
109
|
+
removedAfterReplacement: string[];
|
|
110
|
+
}>;
|
|
111
|
+
export declare const pruneBaselineGenerations: ({ artifactRoot, retain, expectedRemoved, }: {
|
|
112
|
+
artifactRoot: string;
|
|
113
|
+
retain?: number;
|
|
114
|
+
expectedRemoved?: readonly string[];
|
|
115
|
+
}) => Promise<BaselinePrunePlan>;
|
|
116
|
+
export declare const removeBaselineArtifactRoot: ({ artifactRoot, }: {
|
|
117
|
+
artifactRoot: string;
|
|
118
|
+
}) => Promise<void>;
|
|
119
|
+
export {};
|