@akanjs/devkit 3.3.0-rc.2 → 3.3.0-rc.20
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 +284 -20
- package/DEV_RUNTIME_KNOBS.md +1 -1
- package/README.ko.md +3 -2
- package/README.md +3 -3
- package/akanApp/akanApp.host.test.ts +1 -1
- package/akanConfig/akanConfig.test.ts +57 -8
- package/akanConfig/akanConfig.ts +16 -69
- package/akanConfig/dockerImage.ts +17 -0
- package/akanConfig/nativeKeys.ts +52 -0
- package/app/applicationBuildRunner.test.ts +321 -1
- package/app/applicationBuildRunner.ts +90 -3
- package/artifact/implicitRootLayoutRender.test.tsx +4 -1
- package/codeAgent/agent/CodeAgent.ts +36 -16
- package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
- package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
- package/codeAgent/agent/CodeAgentGate.ts +23 -4
- package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
- package/codeAgent/agent/codeAgent.test.ts +62 -0
- package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
- package/codeAgent/agent/codeAgentContract.test.ts +117 -5
- package/codeAgent/skills/akan-agent/SKILL.md +8 -1
- package/codeAgent/skills/akan-code/SKILL.md +38 -3
- package/codeAgent/skills/akan-err/SKILL.md +11 -2
- package/codeAgent/skills/akan-page/SKILL.md +21 -26
- package/codeAgent/skills/akan-runtime/SKILL.md +41 -16
- package/codeAgent/skills/akan-service/SKILL.md +2 -2
- package/docs/apiReference.test.ts +14 -0
- package/docs/apiReference.ts +21 -3
- package/docs/declarationReader.ts +28 -1
- package/executors/appExecutor.ts +16 -7
- package/executors/workspaceExecutor.ts +7 -4
- package/frontendBuild/buildRouteClient.test.ts +2 -7
- package/frontendBuild/clientEntryDiscovery.test.ts +35 -0
- package/frontendBuild/clientEntryDiscovery.ts +16 -3
- package/frontendBuild/cssCompiler.test.ts +112 -0
- package/frontendBuild/cssCompiler.ts +41 -21
- package/frontendBuild/devBarrelImports.test.ts +30 -0
- package/frontendBuild/devBarrelImports.ts +2 -2
- package/frontendBuild/pagesBundleBuilder.ts +3 -1
- package/frontendBuild/plainStylesheet.test.ts +155 -0
- package/frontendBuild/plainStylesheet.ts +197 -0
- package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
- package/frontendBuild/rscServerRendererGuard.ts +68 -0
- package/guideline/agentAssets.test.ts +10 -0
- package/guideline/agentAssets.ts +52 -11
- package/incrementalBuilder/buildBatch.proc.ts +9 -9
- package/incrementalBuilder/buildBatchProtocol.ts +1 -1
- package/incrementalBuilder/builderBoot.ts +5 -5
- package/incrementalBuilder/builderGraphPayloads.ts +4 -4
- package/incrementalBuilder/builderLanes.ts +2 -2
- package/incrementalBuilder/builderWatch.ts +8 -8
- package/incrementalBuilder/csrRegistry.ts +4 -4
- package/incrementalBuilder/incrementalBuilder.proc.ts +8 -8
- package/incrementalBuilder/ssrRegistry.ts +6 -6
- package/index.ts +1 -1
- package/integration/renderAdmissionSoak.test.ts +99 -0
- package/integration/renderAdmissionSoak.ts +609 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
- package/lint/biomeCheck.test.ts +145 -0
- package/lint/biomeCheck.ts +131 -0
- package/lint/no-arbitrary-color.grit +5 -0
- package/lint/no-conditional-st-hook.grit +5 -1
- package/lint/no-daisyui-legacy-class.grit +8 -0
- package/lint/no-document-cookie.grit +3 -0
- package/lint/no-inline-color.grit +10 -2
- package/lint/no-oversized-list-limit.grit +2 -0
- package/lint/no-raw-palette-class.grit +7 -0
- package/lint/no-unpublished-form-setter.grit +2 -0
- package/lint/no-web-only-api-outside-webkit.grit +5 -0
- package/lint/no-web-storage.grit +3 -0
- package/lint/withheldEnvFile.ts +17 -0
- package/mobile/nativeApp.test.ts +7 -5
- package/mobile/nativeApp.ts +2 -2
- package/mobile/nativeConfig.test.ts +117 -1
- package/mobile/nativeConfig.ts +66 -22
- package/mobile/serverBundleSecrets.ts +43 -0
- package/package.json +14 -169
- package/packageExports.test.ts +38 -24
- package/test/secretEnvFixture.ts +134 -0
- package/transforms/barrelAnalyzer.ts +2 -2
- package/transforms/secretEnvDeclaration.test.ts +208 -0
- package/transforms/secretEnvDeclaration.ts +213 -0
- package/transforms/secretEnvFile.test.ts +117 -0
- package/transforms/secretEnvFile.ts +113 -0
- package/transforms/secretEnvName.test.ts +54 -0
- package/transforms/secretEnvName.ts +29 -0
- package/transforms/secretEnvSource.test.ts +148 -0
- package/transforms/secretEnvSource.ts +166 -0
- package/transforms/serverEnvEvaluationError.ts +11 -0
- package/transforms/serverEnvPlugin.test.ts +2 -1
- package/transforms/serverEnvPlugin.ts +13 -0
- package/transforms/serverEnvProfile.test.ts +115 -2
- package/transforms/serverEnvProfile.ts +117 -40
- package/transforms/serverEnvSecrets.test.ts +292 -0
- package/transforms/transforms.test.ts +3 -3
- package/tunnel/createTunnel.test.ts +29 -8
- package/tunnel/createTunnel.ts +18 -11
- package/typecheck/projectTypecheck.test.ts +29 -0
- package/typecheck/typeChecker.test.ts +49 -0
- package/typecheck/typeChecker.ts +9 -7
- package/typecheck/withheldDiagnostics.ts +41 -0
- package/util/fileEditor.ts +1 -0
- package/util/selectModel.ts +1 -0
- package/workspace/getRelatedCnsts.ts +7 -0
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync, realpathSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import type { BunPlugin, OnLoadResult } from "bun";
|
|
4
|
+
import { SecretEnvDeclaration } from "./secretEnvDeclaration";
|
|
4
5
|
import { ServerEnvProfile } from "./serverEnvProfile";
|
|
5
6
|
|
|
6
7
|
export interface ServerEnvPluginOptions {
|
|
@@ -12,6 +13,11 @@ export interface ServerEnvPluginOptions {
|
|
|
12
13
|
profile?: string;
|
|
13
14
|
/** Under a profile, once per lib env file: whether the lib gave one of the profile's, and what was left out if not. */
|
|
14
15
|
onLibEnv?: (file: string, report: { profileFile: boolean; stripped: string[] }) => void;
|
|
16
|
+
/**
|
|
17
|
+
* Without a profile: `read` bundles each env file, a lib's included, with its secret strings replaced by reads of the
|
|
18
|
+
* process env, and `inline` keeps each string as what its read falls back to. Unset, the files are bundled as written.
|
|
19
|
+
*/
|
|
20
|
+
secrets?: "read" | "inline";
|
|
15
21
|
}
|
|
16
22
|
|
|
17
23
|
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
@@ -24,6 +30,7 @@ export const createServerEnvPlugin = ({
|
|
|
24
30
|
environments,
|
|
25
31
|
profile,
|
|
26
32
|
onLibEnv,
|
|
33
|
+
secrets,
|
|
27
34
|
}: ServerEnvPluginOptions): BunPlugin => {
|
|
28
35
|
const others = [...new Set(environments)].filter((name) => name !== environment);
|
|
29
36
|
//? Bun hands onLoad the real path, which differs from the given one under a symlink (macOS's /var -> /private/var).
|
|
@@ -64,6 +71,12 @@ export const createServerEnvPlugin = ({
|
|
|
64
71
|
].join("\n"),
|
|
65
72
|
};
|
|
66
73
|
});
|
|
74
|
+
//? After the stubs, which take the other environments' files first; `env.server.ts` itself is the env file where
|
|
75
|
+
//? a pipeline copies one over the switch.
|
|
76
|
+
if (secrets && !profile)
|
|
77
|
+
build.onLoad({ filter: ServerEnvProfile.envModulePattern }, (args) =>
|
|
78
|
+
SecretEnvDeclaration.source(args.path, secrets),
|
|
79
|
+
);
|
|
67
80
|
//? Last: the app's own env files above are taken by the handlers before it, which match them first.
|
|
68
81
|
if (profile)
|
|
69
82
|
build.onLoad({ filter: ServerEnvProfile.envFilePattern }, async (args) => {
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import { Logger } from "akanjs/common";
|
|
4
5
|
import { tempDirs, writeText as write } from "../test/testHelpers";
|
|
6
|
+
import { ServerEnvEvaluationError } from "./serverEnvEvaluationError";
|
|
5
7
|
import { ServerEnvProfile } from "./serverEnvProfile";
|
|
6
8
|
|
|
7
9
|
const makeTempRoot = tempDirs("akan-devkit-server-env-profile-");
|
|
@@ -129,6 +131,20 @@ describe("ServerEnvProfile.strip", () => {
|
|
|
129
131
|
});
|
|
130
132
|
});
|
|
131
133
|
|
|
134
|
+
const alive = (pid: number) => {
|
|
135
|
+
try {
|
|
136
|
+
process.kill(pid, 0);
|
|
137
|
+
return true;
|
|
138
|
+
} catch {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const goneWithin = async (pid: number, ms: number) => {
|
|
144
|
+
for (const started = Date.now(); Date.now() - started < ms; await Bun.sleep(50)) if (!alive(pid)) return true;
|
|
145
|
+
return !alive(pid);
|
|
146
|
+
};
|
|
147
|
+
|
|
132
148
|
describe("ServerEnvProfile.evaluate", () => {
|
|
133
149
|
test("says why and where an env file could not be evaluated, and never a line or a value of it", async () => {
|
|
134
150
|
const root = await makeTempRoot();
|
|
@@ -155,11 +171,108 @@ describe("ServerEnvProfile.evaluate", () => {
|
|
|
155
171
|
expect(message).not.toContain(secret);
|
|
156
172
|
}
|
|
157
173
|
expect(messages.reference).toMatch(
|
|
158
|
-
/^env\.server\.reference\.ts could not be evaluated to check it for secrets: ReferenceError
|
|
174
|
+
/^env\.server\.reference\.ts could not be evaluated to check it for secrets: ReferenceError at .*env\.server\.reference\.ts:3$/,
|
|
175
|
+
);
|
|
176
|
+
expect(messages.syntax).toMatch(/: [A-Za-z]+ at .*env\.server\.syntax\.ts:2$/);
|
|
177
|
+
expect(messages.thrown).toMatch(/: Error at .*env\.server\.thrown\.ts:2$/);
|
|
178
|
+
expect(messages.thrownString).toEndWith(": Error, which gave no location");
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test("names the class and the place of an error whose message quotes a value another file holds, and not the message", async () => {
|
|
182
|
+
const root = realpathSync(await makeTempRoot());
|
|
183
|
+
const secret = "sentinel-imported-0123456789";
|
|
184
|
+
await write(
|
|
185
|
+
path.join(root, "srvkit/keys.ts"),
|
|
186
|
+
`export const key = ${JSON.stringify(secret)};\nexport const word = "sentinelpassphrase";\n`,
|
|
187
|
+
);
|
|
188
|
+
const sources = {
|
|
189
|
+
thrown:
|
|
190
|
+
'import { key } from "../srvkit/keys";\nif (key) throw new Error("expected a longer key, got " + key);\nexport const env = {};\n',
|
|
191
|
+
parsed: 'import { key } from "../srvkit/keys";\nexport const env = {\n settings: JSON.parse(key),\n};\n',
|
|
192
|
+
framed:
|
|
193
|
+
'import { key } from "../srvkit/keys";\nthrow new Error("failed\\n at " + key + ":1:1");\nexport const env = {};\n',
|
|
194
|
+
named:
|
|
195
|
+
'import { word } from "../srvkit/keys";\nconst error = new Error("failed");\nerror.name = word;\nthrow error;\nexport const env = {};\n',
|
|
196
|
+
};
|
|
197
|
+
const messages: Record<string, string> = {};
|
|
198
|
+
for (const [name, source] of Object.entries(sources)) {
|
|
199
|
+
const file = path.join(root, `env/env.server.${name}.ts`);
|
|
200
|
+
await write(file, source);
|
|
201
|
+
messages[name] = await ServerEnvProfile.evaluate(file, root).then(
|
|
202
|
+
() => "",
|
|
203
|
+
(error: Error) => error.message,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
for (const message of Object.values(messages)) expect(message).not.toContain("sentinel");
|
|
207
|
+
expect(messages.thrown).toBe(
|
|
208
|
+
`env.server.thrown.ts could not be evaluated to check it for secrets: Error at ${path.join(root, "env/env.server.thrown.ts")}:2`,
|
|
209
|
+
);
|
|
210
|
+
expect(messages.parsed).toBe(
|
|
211
|
+
`env.server.parsed.ts could not be evaluated to check it for secrets: SyntaxError at ${path.join(root, "env/env.server.parsed.ts")}:3`,
|
|
159
212
|
);
|
|
160
|
-
expect(messages.
|
|
213
|
+
expect(messages.framed).toEndWith(`: Error at ${path.join(root, "env/env.server.framed.ts")}:2`);
|
|
214
|
+
expect(messages.named).toEndWith(`: Error at ${path.join(root, "env/env.server.named.ts")}:2`);
|
|
161
215
|
});
|
|
162
216
|
|
|
217
|
+
test("answers for an env file whose import keeps a timer running, and leaves no process behind", async () => {
|
|
218
|
+
const root = await makeTempRoot();
|
|
219
|
+
const pidFile = path.join(root, "pid");
|
|
220
|
+
await write(
|
|
221
|
+
path.join(root, "lib/ticker.ts"),
|
|
222
|
+
`await Bun.write(${JSON.stringify(pidFile)}, String(process.pid));\nexport const ticker = setInterval(() => undefined, 1_000);\n`,
|
|
223
|
+
);
|
|
224
|
+
const file = path.join(root, "env/env.server.main.ts");
|
|
225
|
+
await write(file, 'import "../lib/ticker";\nexport const env = { hostname: "app.example.test" };\n');
|
|
226
|
+
const started = Date.now();
|
|
227
|
+
expect(await ServerEnvProfile.evaluate(file, root)).toEqual({ hostname: "app.example.test" });
|
|
228
|
+
expect(Date.now() - started).toBeLessThan(10_000);
|
|
229
|
+
expect(await goneWithin(Number(await Bun.file(pidFile).text()), 3_000)).toBe(true);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
test("stops an env file that never finishes loading, names it, and leaves no process behind", async () => {
|
|
233
|
+
const root = await makeTempRoot();
|
|
234
|
+
const pidFile = path.join(root, "pid");
|
|
235
|
+
const file = path.join(root, "env/env.server.main.ts");
|
|
236
|
+
await write(
|
|
237
|
+
file,
|
|
238
|
+
`await Bun.write(${JSON.stringify(pidFile)}, String(process.pid));\nsetInterval(() => undefined, 1_000);\nawait new Promise(() => undefined);\nexport const env = {};\n`,
|
|
239
|
+
);
|
|
240
|
+
const failure = await ServerEnvProfile.evaluate(file, root, undefined, { timeoutMs: 1_500 }).then(
|
|
241
|
+
() => null,
|
|
242
|
+
(error: unknown) => error,
|
|
243
|
+
);
|
|
244
|
+
expect(failure).toBeInstanceOf(ServerEnvEvaluationError);
|
|
245
|
+
expect((failure as ServerEnvEvaluationError).reason).toBe("timedOut");
|
|
246
|
+
expect((failure as Error).message).toStartWith(`${file} was not evaluated within 1.5s, so its process was stopped`);
|
|
247
|
+
expect(await goneWithin(Number(await Bun.file(pidFile).text()), 3_000)).toBe(true);
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
test("its process ends with the process that asked, even one that was killed", async () => {
|
|
251
|
+
const root = await makeTempRoot();
|
|
252
|
+
const pidFile = path.join(root, "pid");
|
|
253
|
+
const file = path.join(root, "env/env.server.main.ts");
|
|
254
|
+
await write(
|
|
255
|
+
file,
|
|
256
|
+
`await Bun.write(${JSON.stringify(pidFile)}, String(process.pid));\nsetInterval(() => undefined, 1_000);\nawait new Promise(() => undefined);\nexport const env = {};\n`,
|
|
257
|
+
);
|
|
258
|
+
const asker = path.join(root, "asker.ts");
|
|
259
|
+
await write(
|
|
260
|
+
asker,
|
|
261
|
+
`import { ServerEnvProfile } from ${JSON.stringify(path.join(import.meta.dir, "serverEnvProfile.ts"))};\nawait ServerEnvProfile.evaluate(${JSON.stringify(file)}, ${JSON.stringify(root)});\n`,
|
|
262
|
+
);
|
|
263
|
+
const parent = Bun.spawn([process.execPath, asker], { cwd: import.meta.dir, stdout: "ignore", stderr: "ignore" });
|
|
264
|
+
try {
|
|
265
|
+
for (let tries = 0; tries < 200 && !(await Bun.file(pidFile).exists()); tries++) await Bun.sleep(50);
|
|
266
|
+
const child = Number(await Bun.file(pidFile).text());
|
|
267
|
+
expect(alive(child)).toBe(true);
|
|
268
|
+
parent.kill("SIGKILL");
|
|
269
|
+
await parent.exited;
|
|
270
|
+
expect(await goneWithin(child, 5_000)).toBe(true);
|
|
271
|
+
} finally {
|
|
272
|
+
parent.kill("SIGKILL");
|
|
273
|
+
}
|
|
274
|
+
}, 30_000);
|
|
275
|
+
|
|
163
276
|
test("reads an env file that writes to stdout as it loads", async () => {
|
|
164
277
|
const envDir = await writeProfile(
|
|
165
278
|
'console.info("loading the edge env");\nprocess.stdout.write("{ not json");\nexport const env = { hostname: "edge" };\n',
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync, realpathSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { Logger, toError } from "akanjs/common";
|
|
4
|
+
import { ServerEnvEvaluationError } from "./serverEnvEvaluationError";
|
|
4
5
|
|
|
5
6
|
export interface ServerEnvProfileProps {
|
|
6
7
|
envDir: string;
|
|
@@ -20,6 +21,21 @@ export interface LibEnvSource extends ServerEnvSource {
|
|
|
20
21
|
|
|
21
22
|
type EnvLoad = (envFile: string) => Promise<ServerEnvSource>;
|
|
22
23
|
|
|
24
|
+
export interface EnvEvaluation {
|
|
25
|
+
environment?: string;
|
|
26
|
+
loads?: RegExp;
|
|
27
|
+
timeoutMs?: number;
|
|
28
|
+
//* What the child's process env holds beside PATH, HOME and the environment's selector.
|
|
29
|
+
variables?: { readonly [name: string]: string };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface EnvEvaluated {
|
|
33
|
+
value: unknown;
|
|
34
|
+
lossy: string[];
|
|
35
|
+
//* The names the env file and its imports asked the process env for, set or not.
|
|
36
|
+
reads: string[];
|
|
37
|
+
}
|
|
38
|
+
|
|
23
39
|
interface Stripped {
|
|
24
40
|
value: unknown;
|
|
25
41
|
stripped: string[];
|
|
@@ -31,13 +47,15 @@ interface EnvFold<T> {
|
|
|
31
47
|
node(value: object, children: (readonly [string, T])[]): T;
|
|
32
48
|
}
|
|
33
49
|
|
|
34
|
-
type EvaluatedMessage = { load: string } | { env: string; lossy: string[] } | { failure: string };
|
|
50
|
+
type EvaluatedMessage = { load: string } | { env: string; lossy: string[]; reads: string[] } | { failure: string };
|
|
35
51
|
|
|
36
52
|
//* A server env profile is bundled in place of the environment's own file, for a server that runs where its bundle
|
|
37
53
|
//* can be read: the computers a desktop app is installed on. So it may hold no secret.
|
|
38
54
|
export class ServerEnvProfile {
|
|
39
55
|
static readonly namePattern = /^[a-z][a-zA-Z0-9-]*$/;
|
|
40
56
|
static readonly envFilePattern = /[\\/]env[\\/]env\.server\.[A-Za-z0-9-]+\.ts$/;
|
|
57
|
+
static readonly envModulePattern = /[\\/]env[\\/]env\.server(?:\.[A-Za-z0-9-]+)?\.ts$/;
|
|
58
|
+
static readonly evaluationTimeoutMs = 60_000;
|
|
41
59
|
|
|
42
60
|
static fileName(environment: string, profile: string) {
|
|
43
61
|
return `env.server.${environment}.${profile}.ts`;
|
|
@@ -65,7 +83,7 @@ export class ServerEnvProfile {
|
|
|
65
83
|
return !!url && ServerEnvProfile.#carriesCredential(url);
|
|
66
84
|
}
|
|
67
85
|
|
|
68
|
-
static
|
|
86
|
+
static isSecret(value: string, underSecret: boolean) {
|
|
69
87
|
return (underSecret && !!value.trim()) || ServerEnvProfile.#isCredentialUrl(value);
|
|
70
88
|
}
|
|
71
89
|
|
|
@@ -92,7 +110,7 @@ export class ServerEnvProfile {
|
|
|
92
110
|
static strip(value: unknown): Stripped {
|
|
93
111
|
return ServerEnvProfile.#fold<Stripped>(value, {
|
|
94
112
|
text: (text, at, underSecret) =>
|
|
95
|
-
ServerEnvProfile
|
|
113
|
+
ServerEnvProfile.isSecret(text, underSecret)
|
|
96
114
|
? { value: undefined, stripped: [at] }
|
|
97
115
|
: { value: text, stripped: [] },
|
|
98
116
|
other: (other) => ({ value: other, stripped: [] }),
|
|
@@ -152,26 +170,60 @@ export class ServerEnvProfile {
|
|
|
152
170
|
return value.length >= 16 && !/^https?:\/\//.test(value) && !/^[a-z]+(?:[._-][a-z]+)*$/.test(value);
|
|
153
171
|
}
|
|
154
172
|
|
|
155
|
-
static secretPaths(value: unknown): string[] {
|
|
173
|
+
static secretPaths(value: unknown, underSecret = false): string[] {
|
|
156
174
|
return ServerEnvProfile.#fold(
|
|
157
175
|
value,
|
|
158
|
-
ServerEnvProfile.#collect((text, at,
|
|
176
|
+
ServerEnvProfile.#collect((text, at, held) => (ServerEnvProfile.isSecret(text, held) ? [at] : [])),
|
|
177
|
+
"",
|
|
178
|
+
underSecret,
|
|
159
179
|
);
|
|
160
180
|
}
|
|
161
181
|
|
|
182
|
+
//? A URL's password is looked for on its own too: code that holds it holds it without the URL around it.
|
|
183
|
+
static movedTexts(value: unknown, underSecret: boolean): string[] {
|
|
184
|
+
const texts = ServerEnvProfile.#fold(
|
|
185
|
+
value,
|
|
186
|
+
ServerEnvProfile.#collect((text, _at, held) =>
|
|
187
|
+
ServerEnvProfile.isSecret(text, held) ? [text, ServerEnvProfile.#url(text)?.password ?? ""] : [],
|
|
188
|
+
),
|
|
189
|
+
"",
|
|
190
|
+
underSecret,
|
|
191
|
+
);
|
|
192
|
+
return [...new Set(texts)].filter((text) => text !== "");
|
|
193
|
+
}
|
|
194
|
+
|
|
162
195
|
//* Evaluated in a child with no app env, so `process.env.X ?? "fallback"` reads as the fallback the bundle carries.
|
|
163
196
|
//* The result comes back over IPC, as an import may write to stdout; `load` answers for each env file it reaches.
|
|
164
|
-
static async evaluate(file: string, cwd: string, load?: EnvLoad): Promise<unknown> {
|
|
165
|
-
return (await ServerEnvProfile.#evaluated(file, cwd, load)).value;
|
|
197
|
+
static async evaluate(file: string, cwd: string, load?: EnvLoad, evaluation?: EnvEvaluation): Promise<unknown> {
|
|
198
|
+
return (await ServerEnvProfile.#evaluated(file, cwd, load, evaluation)).value;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
static async evaluateReads(file: string, cwd: string, load: EnvLoad, evaluation: EnvEvaluation) {
|
|
202
|
+
return await ServerEnvProfile.#evaluated(file, cwd, load, evaluation, true);
|
|
166
203
|
}
|
|
167
204
|
|
|
168
|
-
//? Bun prints a failing module's source line with its error, so stderr is never read
|
|
169
|
-
//?
|
|
170
|
-
static async #evaluated(
|
|
171
|
-
|
|
172
|
-
|
|
205
|
+
//? Bun prints a failing module's source line with its error, so stderr is never read. The child sends the error's
|
|
206
|
+
//? class and place and never its message, which can quote a value of any file the env file imports.
|
|
207
|
+
static async #evaluated(
|
|
208
|
+
file: string,
|
|
209
|
+
cwd: string,
|
|
210
|
+
load?: EnvLoad,
|
|
211
|
+
{
|
|
212
|
+
environment,
|
|
213
|
+
loads = ServerEnvProfile.envFilePattern,
|
|
214
|
+
timeoutMs = ServerEnvProfile.evaluationTimeoutMs,
|
|
215
|
+
variables,
|
|
216
|
+
}: EnvEvaluation = {},
|
|
217
|
+
notesReads = false,
|
|
218
|
+
): Promise<EnvEvaluated> {
|
|
173
219
|
const frame = /^\s*at (?:[^(]*\()?(.+):(\d+):(\d+)\)?\s*$/;
|
|
174
220
|
const script = [
|
|
221
|
+
//? An import may leave a timer, a server or a socket open, which would keep this process alive past its answer
|
|
222
|
+
//? and past a parent that died: it exits when its answer is sent, when the parent's channel closes, and at a
|
|
223
|
+
//? deadline of its own.
|
|
224
|
+
'process.on("disconnect", () => process.exit(1));',
|
|
225
|
+
"setTimeout(() => process.exit(1), Number(process.env.AKAN_PROFILE_ENV_DEADLINE)).unref();",
|
|
226
|
+
"const finish = (message, code) => process.send(message, undefined, undefined, () => process.exit(code));",
|
|
175
227
|
"const waiting = new Map();",
|
|
176
228
|
'process.on("message", ({ load, error, loader, contents }) => {',
|
|
177
229
|
" const reply = waiting.get(load);",
|
|
@@ -190,23 +242,30 @@ export class ServerEnvProfile {
|
|
|
190
242
|
" }));",
|
|
191
243
|
" },",
|
|
192
244
|
" });",
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
`
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
"
|
|
245
|
+
"const reads = new Set();",
|
|
246
|
+
'const note = (key) => typeof key === "string" && reads.add(key);',
|
|
247
|
+
"const noting = { get: (target, key, receiver) => (note(key), Reflect.get(target, key, receiver)), has: (target, key) => (note(key), Reflect.has(target, key)) };",
|
|
248
|
+
//? `Bun.env` and `import.meta.env` stay the object `process.env` was, which a proxy put in its place does not
|
|
249
|
+
//? see: a name that object lacks is noted through its prototype, and a name it holds through the proxy alone.
|
|
250
|
+
"if (process.env.AKAN_PROFILE_ENV_READS) {",
|
|
251
|
+
" Object.setPrototypeOf(process.env, new Proxy(Object.prototype, noting));",
|
|
252
|
+
" process.env = new Proxy(process.env, noting);",
|
|
253
|
+
"}",
|
|
254
|
+
`const frameOf = new RegExp(${JSON.stringify(frame.source)});`,
|
|
255
|
+
'const { existsSync } = require("node:fs");',
|
|
256
|
+
//? The stack opens with the message, whose own lines could read as a frame: only lines after it are looked at,
|
|
257
|
+
//? and only one that names a file on disk.
|
|
258
|
+
"const describe = (error) => {",
|
|
200
259
|
" const first = Array.isArray(error?.errors) && error.errors.length ? error.errors[0] : error;",
|
|
201
|
-
' const
|
|
202
|
-
|
|
203
|
-
" const
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
'
|
|
208
|
-
' const name =
|
|
209
|
-
' return name +
|
|
260
|
+
' const stack = String(first?.stack ?? "");',
|
|
261
|
+
' const message = String(first?.message ?? "");',
|
|
262
|
+
" const frames = message && stack.includes(message) ? stack.slice(stack.indexOf(message) + message.length) : stack;",
|
|
263
|
+
' const frame = frames.split("\\n").map((line) => frameOf.exec(line)).find((found) => found && existsSync(found[1]));',
|
|
264
|
+
" const at = first?.position?.file ? [first.position.file, first.position.line] : frame ? frame.slice(1, 3) : [];",
|
|
265
|
+
//? `error.name` is a property any code can set to a value, so the class is read from the constructor.
|
|
266
|
+
' const named = first === null || first === undefined ? "" : String(Object.getPrototypeOf(first)?.constructor?.name ?? "");',
|
|
267
|
+
' const name = first instanceof Error && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(named) ? named : "Error";',
|
|
268
|
+
' return name + (at.length ? " at " + at.join(":") : ", which gave no location");',
|
|
210
269
|
"};",
|
|
211
270
|
"try {",
|
|
212
271
|
" const { env } = await import(process.env.AKAN_PROFILE_ENV_FILE);",
|
|
@@ -220,13 +279,12 @@ export class ServerEnvProfile {
|
|
|
220
279
|
" };",
|
|
221
280
|
' walk(env, "");',
|
|
222
281
|
' const plain = (_, value) => (typeof value === "function" || typeof value === "symbol" ? undefined : typeof value === "bigint" ? String(value) : value);',
|
|
223
|
-
'
|
|
282
|
+
' finish({ env: JSON.stringify(env ?? null, plain) ?? "null", lossy, reads: [...reads] }, 0);',
|
|
224
283
|
"} catch (error) {",
|
|
225
|
-
"
|
|
226
|
-
" process.send({ failure: await describe(error) }, undefined, undefined, () => process.disconnect());",
|
|
284
|
+
" finish({ failure: describe(error) }, 1);",
|
|
227
285
|
"}",
|
|
228
286
|
].join("\n");
|
|
229
|
-
let sent: { env: string; lossy: string[] } | undefined;
|
|
287
|
+
let sent: { env: string; lossy: string[]; reads: string[] } | undefined;
|
|
230
288
|
let failure: string | undefined;
|
|
231
289
|
let loadError: unknown;
|
|
232
290
|
const child = Bun.spawn([process.execPath, "--eval", script], {
|
|
@@ -234,8 +292,12 @@ export class ServerEnvProfile {
|
|
|
234
292
|
env: {
|
|
235
293
|
PATH: process.env.PATH ?? "",
|
|
236
294
|
HOME: process.env.HOME ?? "",
|
|
295
|
+
...variables,
|
|
237
296
|
AKAN_PROFILE_ENV_FILE: file,
|
|
238
|
-
|
|
297
|
+
AKAN_PROFILE_ENV_DEADLINE: String(timeoutMs + 5_000),
|
|
298
|
+
...(load ? { AKAN_PROFILE_ENV_LOAD: loads.source } : {}),
|
|
299
|
+
...(notesReads ? { AKAN_PROFILE_ENV_READS: "1" } : {}),
|
|
300
|
+
...(environment ? { AKAN_PUBLIC_ENV: environment } : {}),
|
|
239
301
|
},
|
|
240
302
|
stdout: "ignore",
|
|
241
303
|
stderr: "ignore",
|
|
@@ -264,14 +326,29 @@ export class ServerEnvProfile {
|
|
|
264
326
|
.catch(() => undefined);
|
|
265
327
|
},
|
|
266
328
|
});
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
329
|
+
let timedOut = false;
|
|
330
|
+
const kill = () => child.kill("SIGKILL");
|
|
331
|
+
const timer = setTimeout(() => {
|
|
332
|
+
timedOut = true;
|
|
333
|
+
kill();
|
|
334
|
+
}, timeoutMs);
|
|
335
|
+
process.on("exit", kill);
|
|
336
|
+
const exitCode = await child.exited.finally(() => {
|
|
337
|
+
clearTimeout(timer);
|
|
338
|
+
process.off("exit", kill);
|
|
339
|
+
});
|
|
340
|
+
if (sent && !timedOut && exitCode === 0)
|
|
341
|
+
return { value: JSON.parse(sent.env) as unknown, lossy: sent.lossy, reads: sent.reads };
|
|
342
|
+
if (loadError) throw loadError;
|
|
343
|
+
if (timedOut)
|
|
344
|
+
throw new ServerEnvEvaluationError(
|
|
345
|
+
"timedOut",
|
|
346
|
+
`${file} was not evaluated within ${timeoutMs / 1000}s, so its process was stopped: the file, or one it imports, waits on something as it loads that does not end (a server it starts, a connection it opens, a loop).`,
|
|
272
347
|
);
|
|
273
|
-
|
|
274
|
-
|
|
348
|
+
throw new ServerEnvEvaluationError(
|
|
349
|
+
failure ? "threw" : "exited",
|
|
350
|
+
`${path.basename(file)} could not be evaluated to check it for secrets: ${failure ?? `its process exited with code ${exitCode} and sent nothing`}`,
|
|
351
|
+
);
|
|
275
352
|
}
|
|
276
353
|
|
|
277
354
|
//? A profile is served under the path of the file it replaces, so its import of that file would import itself.
|