@akanjs/devkit 3.3.0-rc.12 → 3.3.0-rc.13

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/akanConfig/akanConfig.ts +4 -4
  4. package/app/applicationBuildRunner.test.ts +272 -0
  5. package/app/applicationBuildRunner.ts +87 -2
  6. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  7. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  8. package/executors/workspaceExecutor.ts +7 -4
  9. package/frontendBuild/clientEntryDiscovery.test.ts +35 -0
  10. package/frontendBuild/clientEntryDiscovery.ts +14 -1
  11. package/lint/biomeCheck.test.ts +145 -0
  12. package/lint/biomeCheck.ts +131 -0
  13. package/lint/withheldEnvFile.ts +17 -0
  14. package/mobile/serverBundleSecrets.ts +43 -0
  15. package/package.json +3 -3
  16. package/test/secretEnvFixture.ts +134 -0
  17. package/transforms/secretEnvDeclaration.test.ts +208 -0
  18. package/transforms/secretEnvDeclaration.ts +213 -0
  19. package/transforms/secretEnvFile.test.ts +117 -0
  20. package/transforms/secretEnvFile.ts +113 -0
  21. package/transforms/secretEnvName.test.ts +54 -0
  22. package/transforms/secretEnvName.ts +29 -0
  23. package/transforms/secretEnvSource.test.ts +148 -0
  24. package/transforms/secretEnvSource.ts +166 -0
  25. package/transforms/serverEnvEvaluationError.ts +11 -0
  26. package/transforms/serverEnvPlugin.test.ts +2 -1
  27. package/transforms/serverEnvPlugin.ts +13 -0
  28. package/transforms/serverEnvProfile.test.ts +115 -2
  29. package/transforms/serverEnvProfile.ts +117 -40
  30. package/transforms/serverEnvSecrets.test.ts +292 -0
  31. package/typecheck/projectTypecheck.test.ts +29 -0
  32. package/typecheck/typeChecker.test.ts +49 -0
  33. package/typecheck/typeChecker.ts +9 -7
  34. package/typecheck/withheldDiagnostics.ts +41 -0
@@ -8,12 +8,15 @@ import type { BaseDevEnv, TsConfigJson } from "../workspace/types";
8
8
  import { Executor, execEmoji } from "./executor";
9
9
  import { SysExecutor } from "./sysExecutor";
10
10
 
11
- //? As Bun's own .env loader reads it (1.4.4), which fills process.env too: `#` ends an unquoted value even mid-word.
11
+ //? As Bun's .env loader reads it (1.4.4), which fills process.env too: `#` ends an unquoted value mid-word, `\$` is `$`.
12
12
  const parseEnvValue = (value: string) => {
13
13
  const [, quote, inner] = value.match(/^(["'`])((?:\\.|(?!\1)[^\\])*)\1/) ?? [];
14
- if (!quote) return value.replace(/#.*/, "").trim();
15
- if (quote !== '"') return inner;
16
- return inner.replace(/\\(.)/g, (pair, char: string) => (char === "n" ? "\n" : char === "r" ? "\r" : pair));
14
+ const text = !quote
15
+ ? value.replace(/#.*/, "").trim()
16
+ : quote !== '"'
17
+ ? inner
18
+ : inner.replace(/\\(.)/g, (pair, char: string) => (char === "n" ? "\n" : char === "r" ? "\r" : pair));
19
+ return text.replaceAll("\\$", "$");
17
20
  };
18
21
 
19
22
  export const parseEnvFile = (envPath: string): Record<string, string> => {
@@ -189,4 +189,39 @@ describe("GraphClientEntryDiscovery", () => {
189
189
  fresh.invalidate([file("Server.tsx")]);
190
190
  expect(await fresh.discover([file("Page.tsx")], { importsAs })).toEqual([]);
191
191
  });
192
+
193
+ test("a client file exporting only hooks is no entry of a server graph that imports it, one with a component still is", async () => {
194
+ const file = await tempDir();
195
+ await Bun.write(file("Layout.tsx"), 'import "./store";\nimport "./Panel";\n');
196
+ await Bun.write(
197
+ file("store.ts"),
198
+ 'import { useForm } from "./useForm";\nimport { useEffect } from "./reactHooks";\nimport "./useMixed";\nexport const st = { useForm, useEffect };\n',
199
+ );
200
+ await Bun.write(
201
+ file("useForm.ts"),
202
+ '"use client";\nimport "./Inner";\nexport interface FormShape {}\nexport const useForm = () => null;\nexport function useOther() {}\n',
203
+ );
204
+ await Bun.write(file("reactHooks.ts"), '"use client";\nexport { useContext, useEffect } from "react";\n');
205
+ await Bun.write(
206
+ file("useMixed.ts"),
207
+ '"use client";\nexport const useMixed = () => null;\nexport const Mixed = () => null;\n',
208
+ );
209
+ await Bun.write(file("Inner.tsx"), '"use client";\nexport const Inner = () => null;\n');
210
+ await Bun.write(
211
+ file("Panel.tsx"),
212
+ '"use client";\nimport { useForm } from "./useForm";\nexport const Panel = () => useForm();\n',
213
+ );
214
+ const discovery = new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never);
215
+ expect(await discovery.discover([file("Layout.tsx")])).toEqual([file("Panel.tsx"), file("useMixed.ts")]);
216
+ });
217
+
218
+ test("a client file with a default export or a star re-export stays an entry", async () => {
219
+ const file = await tempDir();
220
+ await Bun.write(file("S.tsx"), 'import "./A";\nimport "./B";\nimport "./C";\n');
221
+ await Bun.write(file("A.ts"), '"use client";\nexport default function useA() {}\n');
222
+ await Bun.write(file("B.ts"), '"use client";\nexport * from "./C";\nexport const useB = () => null;\n');
223
+ await Bun.write(file("C.ts"), '"use client";\nexport const C = () => null;\n');
224
+ const discovery = new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never);
225
+ expect(await discovery.discover([file("S.tsx")])).toEqual([file("A.ts"), file("B.ts"), file("C.ts")]);
226
+ });
192
227
  });
@@ -7,6 +7,8 @@ import { createTsconfigPackageResolver, rewriteBarrelImports } from "../transfor
7
7
  import type { AkanConfig, ClientEntryDiscovery, DiscoverOptions, ScannedImport } from "./clientBuildTypes";
8
8
 
9
9
  const USE_CLIENT_RE = /^\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*|\/\/[^\n]*\n\s*)*["']use client["']/;
10
+ const EXPORT_STAR_RE = /^\s*export\s*\*/m;
11
+ const HOOK_NAME_RE = /^use[A-Z0-9]/;
10
12
  const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
11
13
  const AKANJS_NODE_MODULE_RE = /[\\/]node_modules[\\/]akanjs[\\/]/;
12
14
  // Bun's scanImports also surfaces CSS and asset imports, none of which can be a client component.
@@ -172,7 +174,7 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
172
174
  .catch(() => null);
173
175
  if (content === null) return null;
174
176
  this.#readFiles.add(absPath);
175
- if (USE_CLIENT_RE.test(content)) return { isClientEntry: true, imports: [] };
177
+ if (USE_CLIENT_RE.test(content)) return { isClientEntry: !this.#exportsOnlyHooks(content), imports: [] };
176
178
  return { isClientEntry: false, imports: this.#scanImports(await this.#rewrite(content, absPath)) };
177
179
  })();
178
180
  this.#factsCache.set(absPath, cached);
@@ -191,6 +193,17 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
191
193
  }
192
194
  }
193
195
 
196
+ //? A hook is never rendered, so no flight row names its file; `export *` hides names from the scan, so it stays an entry.
197
+ #exportsOnlyHooks(content: string): boolean {
198
+ if (EXPORT_STAR_RE.test(content)) return false;
199
+ try {
200
+ const { exports } = this.#tsTranspiler.scan(content);
201
+ return exports.length > 0 && exports.every((name) => HOOK_NAME_RE.test(name));
202
+ } catch {
203
+ return false;
204
+ }
205
+ }
206
+
194
207
  #scanImports(source: string): ScannedImport[] {
195
208
  try {
196
209
  return this.#tsTranspiler.scanImports(source);
@@ -0,0 +1,145 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdir, symlink } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { hasBiome, tempDirs, writeText } from "../test/testHelpers";
5
+ import { BiomeCheck } from "./biomeCheck";
6
+
7
+ const makeTempRoot = tempDirs("akan-devkit-biome-check-");
8
+ const repoRoot = path.resolve(import.meta.dir, "../../../..");
9
+ const sentinel = "SENTINEL_DB_PASSWORD_4f9c2a71e0b3";
10
+
11
+ const workspace = async () => {
12
+ const root = await makeTempRoot();
13
+ await mkdir(path.join(root, "node_modules"), { recursive: true });
14
+ await symlink(path.join(repoRoot, "node_modules/@biomejs"), path.join(root, "node_modules/@biomejs"));
15
+ await writeText(
16
+ path.join(root, "biome.json"),
17
+ JSON.stringify({
18
+ vcs: { enabled: false },
19
+ linter: { rules: { suspicious: { noTemplateCurlyInString: "error", noExplicitAny: "error" } } },
20
+ }),
21
+ );
22
+ await writeText(
23
+ path.join(root, "apps/demo/env/env.server.main.ts"),
24
+ `export const env = { apiKey: "${sentinel}", password: "${sentinel}\${x}" };\n`,
25
+ );
26
+ await writeText(path.join(root, "apps/demo/ui/card.ts"), "export const card: any = 1;\n");
27
+ return root;
28
+ };
29
+
30
+ const run = async (root: string, options: { write: boolean; maxDiagnostics: number }) => {
31
+ const printed: string[] = [];
32
+ const error = await BiomeCheck.run({
33
+ root,
34
+ target: path.join(root, "apps/demo"),
35
+ configPath: path.join(root, "biome.json"),
36
+ print: (text) => printed.push(text),
37
+ ...options,
38
+ }).then(
39
+ () => null,
40
+ (e: unknown) => e as Error,
41
+ );
42
+ return { output: printed.join("\n"), error };
43
+ };
44
+
45
+ describe.skipIf(!hasBiome)("BiomeCheck", () => {
46
+ test.each([true, false])(
47
+ "names an env file's diagnostics by position and rule only, with write %p",
48
+ async (write) => {
49
+ const root = await workspace();
50
+ const { output, error } = await run(root, { write, maxDiagnostics: 200 });
51
+
52
+ expect(output).not.toContain(sentinel);
53
+ expect(output).not.toContain("apiKey");
54
+ expect(output).toMatch(
55
+ /apps\/demo\/env\/env\.server\.main\.ts:\d+:\d+ error lint\/suspicious\/noTemplateCurlyInString/,
56
+ );
57
+ expect(output).toContain("withheld");
58
+ expect(output).toContain("export const card: any = 1;");
59
+ expect(error?.message).toBe(write ? "Lint found 2 errors." : "Lint found 3 errors.");
60
+ if (!write) expect(output).toMatch(/env\.server\.main\.ts:0:0 error format/);
61
+ },
62
+ 60_000,
63
+ );
64
+
65
+ test("counts an env file's diagnostics when nothing else fails, and keeps to the cap", async () => {
66
+ const root = await workspace();
67
+ await writeText(path.join(root, "apps/demo/ui/card.ts"), "export const card = 1;\n");
68
+ const all = await run(root, { write: true, maxDiagnostics: 0 });
69
+ expect(all.error?.message).toBe("Lint found 1 error.");
70
+ expect(all.output).not.toContain(sentinel);
71
+
72
+ const capped = await run(await workspace(), { write: false, maxDiagnostics: 1 });
73
+ expect(capped.output.match(/env\.server\.main\.ts:/g)).toHaveLength(1);
74
+ expect(capped.output).toContain("not shown");
75
+ expect(capped.output).not.toContain("export const card: any");
76
+ expect(capped.error).not.toBeNull();
77
+ }, 60_000);
78
+
79
+ test("explains a biome.json Biome cannot read, in Biome's own words", async () => {
80
+ const root = await workspace();
81
+ await writeText(path.join(root, "biome.json"), '{ // a comment\n "vcs": { "enabled": false } }');
82
+ const { error, output } = await run(root, { write: false, maxDiagnostics: 200 });
83
+ expect(output).toBe("");
84
+ expect(error?.message).toContain("biome.json");
85
+ expect(error?.message).not.toContain("gave no report");
86
+ }, 60_000);
87
+
88
+ test("reports every file of a large app in groups, and stops at the cap with the count left", async () => {
89
+ const root = await workspace();
90
+ await writeText(path.join(root, "apps/demo/env/env.server.main.ts"), "export const env = {};\n");
91
+ await writeText(path.join(root, "apps/demo/ui/card.ts"), "export const card = 1;\n");
92
+ for (let idx = 0; idx < 250; idx += 1)
93
+ await writeText(path.join(root, `apps/demo/ui/many/file${idx}.ts`), `export const value${idx}: any = ${idx};\n`);
94
+ const reported = (output: string) => output.match(/noExplicitAny ━/g)?.length ?? 0;
95
+
96
+ const all = await run(root, { write: false, maxDiagnostics: 0 });
97
+ expect(reported(all.output)).toBe(250);
98
+ expect(all.output).not.toContain("not shown");
99
+ expect(all.output.match(/^Found 250 errors\.$/gm)).toHaveLength(1);
100
+ expect(all.output).not.toContain("Checked ");
101
+ expect(all.error?.message).toBe("Lint found 250 errors.");
102
+
103
+ const capped = await run(root, { write: false, maxDiagnostics: 150 });
104
+ expect(reported(capped.output)).toBe(150);
105
+ expect(capped.output).toContain("50 more diagnostics are not shown; --max-diagnostics 0 shows them all.");
106
+ }, 120_000);
107
+
108
+ test("lists after a write only what is still wrong", async () => {
109
+ const root = await workspace();
110
+ await writeText(path.join(root, "apps/demo/env/env.server.main.ts"), "export const env = {};\n");
111
+ await writeText(path.join(root, "apps/demo/ui/card.ts"), "export const card = 1;\nexport const other = 2\n");
112
+ const { output, error } = await run(root, { write: true, maxDiagnostics: 200 });
113
+ expect(output).toBe("");
114
+ expect(error).toBeNull();
115
+ expect(await Bun.file(path.join(root, "apps/demo/ui/card.ts")).text()).toContain("export const other = 2;");
116
+ }, 60_000);
117
+
118
+ test("withholds a grit plugin diagnostic on an env file", async () => {
119
+ const root = await workspace();
120
+ await writeText(
121
+ path.join(root, "no-marker.grit"),
122
+ 'engine biome(1.0)\nlanguage js(typescript)\n`MARKER` as $m where { register_diagnostic(span = $m, message = "marker found", severity = "error") }\n',
123
+ );
124
+ await writeText(
125
+ path.join(root, "biome.json"),
126
+ JSON.stringify({ vcs: { enabled: false }, plugins: ["./no-marker.grit"] }),
127
+ );
128
+ await writeText(
129
+ path.join(root, "apps/demo/env/env.server.main.ts"),
130
+ `export const env = { password: MARKER, other: "${sentinel}" };\n`,
131
+ );
132
+ const { output, error } = await run(root, { write: false, maxDiagnostics: 200 });
133
+ expect(output).not.toContain(sentinel);
134
+ expect(output).toMatch(/env\.server\.main\.ts:\d+:\d+ error plugin - the text is withheld/);
135
+ expect(error).not.toBeNull();
136
+ }, 60_000);
137
+
138
+ test("drops a group's own summary lines, coloured or not", () => {
139
+ const coloured = "\u001b[1mChecked 100 files in 1s.\u001b[0m\n\u001b[31mFound 3 errors.\u001b[39m\na.ts:1:1 lint/x";
140
+ expect(BiomeCheck.withoutSummary(coloured)).toBe("a.ts:1:1 lint/x");
141
+ expect(BiomeCheck.withoutSummary("Checked 1 file in 2ms.\nFound 1 warning.\nb.ts:2:1 lint/y")).toBe(
142
+ "b.ts:2:1 lint/y",
143
+ );
144
+ });
145
+ });
@@ -0,0 +1,131 @@
1
+ import { CliError } from "../commandDecorators/cliError";
2
+ import { type BiomeDiagnostic, Linter, parseBiomeReport } from "./linter";
3
+ import { WithheldEnvFile } from "./withheldEnvFile";
4
+
5
+ export interface BiomeCheckOptions {
6
+ root: string;
7
+ target: string;
8
+ configPath: string | null;
9
+ write: boolean;
10
+ //? 0 shows every diagnostic.
11
+ maxDiagnostics: number;
12
+ print: (text: string) => void;
13
+ }
14
+
15
+ //* Biome's own report quotes source lines, so a first run writes the fixes and reads the JSON report. An env file's
16
+ //* diagnostics are printed from it by position and rule alone; Biome prints the rest again, from the files that have any.
17
+ export class BiomeCheck {
18
+ static readonly #groupSize = 100;
19
+ static readonly #summary = /^(?:Checked \d+ files? in |Found \d+ (?:errors?|warnings?|info))/;
20
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: an ANSI colour sequence starts with the escape character
21
+ static readonly #colour = /\u001b\[[0-9;]*m/g;
22
+
23
+ static async run({ root, target, configPath, write, maxDiagnostics, print }: BiomeCheckOptions) {
24
+ const [biome, ...biomeArgs] = Linter.biomeCommand(root);
25
+ //? Pinned: without it a malformed biome.json makes Biome fall back to discovery and name the wrong file.
26
+ const config = configPath ? ["--config-path", configPath] : [];
27
+ const first = Bun.spawn(
28
+ [
29
+ biome,
30
+ ...biomeArgs,
31
+ "check",
32
+ ...(write ? ["--write"] : []),
33
+ "--reporter=json",
34
+ "--max-diagnostics=none",
35
+ "--no-errors-on-unmatched",
36
+ ...config,
37
+ target,
38
+ ],
39
+ { cwd: root, stdout: "pipe", stderr: "pipe" },
40
+ );
41
+ const [stdout, stderr, exitCode] = await Promise.all([
42
+ new Response(first.stdout).text(),
43
+ new Response(first.stderr).text(),
44
+ first.exited,
45
+ ]);
46
+ let diagnostics: BiomeDiagnostic[];
47
+ try {
48
+ diagnostics = parseBiomeReport(stdout).diagnostics ?? [];
49
+ } catch {
50
+ const cause = (stderr || stdout).trim();
51
+ throw new CliError(
52
+ "failed",
53
+ cause && !WithheldEnvFile.namesEnvFile(cause)
54
+ ? cause
55
+ : `Biome exited with ${exitCode} and gave no report that could be read.`,
56
+ );
57
+ }
58
+ const shown = diagnostics.filter(({ severity }) => severity !== "hint");
59
+ const inEnv = (diagnostic: BiomeDiagnostic) =>
60
+ WithheldEnvFile.isEnvFile(diagnostic.location?.path?.replaceAll("\\", "/"));
61
+ const fromEnv = shown.filter(inEnv);
62
+ const rest = shown.filter((diagnostic) => !inEnv(diagnostic));
63
+ let remaining = maxDiagnostics > 0 ? maxDiagnostics : Number.POSITIVE_INFINITY;
64
+ for (const diagnostic of fromEnv.slice(0, remaining)) print(BiomeCheck.#line(diagnostic));
65
+ let hidden = Math.max(0, fromEnv.length - remaining);
66
+ remaining -= Math.min(fromEnv.length, remaining);
67
+ for (const group of BiomeCheck.#groups(rest)) {
68
+ if (remaining <= 0) {
69
+ hidden += group.count;
70
+ continue;
71
+ }
72
+ const second = Bun.spawn(
73
+ [
74
+ biome,
75
+ ...biomeArgs,
76
+ "check",
77
+ //? Biome shows 20 diagnostics unless told otherwise.
78
+ `--max-diagnostics=${Number.isFinite(remaining) ? remaining : "none"}`,
79
+ ...(process.stdout.isTTY && !process.env.NO_COLOR ? ["--colors=force"] : []),
80
+ ...config,
81
+ ...group.files,
82
+ ],
83
+ { cwd: root, stdout: "pipe", stderr: "pipe" },
84
+ );
85
+ const [out, err] = await Promise.all([
86
+ new Response(second.stdout).text(),
87
+ new Response(second.stderr).text(),
88
+ second.exited,
89
+ ]);
90
+ print(BiomeCheck.withoutSummary(`${out}${err}`));
91
+ remaining -= Math.min(group.count, remaining);
92
+ }
93
+ for (const diagnostic of rest.filter(({ location }) => !location?.path)) print(diagnostic.message);
94
+ if (hidden) print(`${hidden} more diagnostics are not shown; --max-diagnostics 0 shows them all.`);
95
+ const count = (severity: string) => shown.filter((diagnostic) => diagnostic.severity === severity).length;
96
+ for (const [severity, noun] of [
97
+ ["error", "error"],
98
+ ["warning", "warning"],
99
+ ["information", "info"],
100
+ ] as const)
101
+ if (count(severity))
102
+ print(`Found ${count(severity)} ${noun}${count(severity) === 1 || noun === "info" ? "" : "s"}.`);
103
+ const errors = count("error");
104
+ if (errors) throw new CliError("checkFailed", `Lint found ${errors} error${errors === 1 ? "" : "s"}.`);
105
+ }
106
+
107
+ //? Each group's summary counts only its own files; the one printed at the end counts the whole run.
108
+ static withoutSummary(text: string) {
109
+ return text
110
+ .split("\n")
111
+ .filter((line) => !BiomeCheck.#summary.test(line.replace(BiomeCheck.#colour, "")))
112
+ .join("\n")
113
+ .trim();
114
+ }
115
+
116
+ static #groups(diagnostics: BiomeDiagnostic[]) {
117
+ const counts = new Map<string, number>();
118
+ for (const { location } of diagnostics)
119
+ if (location?.path) counts.set(location.path, (counts.get(location.path) ?? 0) + 1);
120
+ const entries = [...counts];
121
+ return Array.from({ length: Math.ceil(entries.length / BiomeCheck.#groupSize) }, (_, index) => {
122
+ const slice = entries.slice(index * BiomeCheck.#groupSize, (index + 1) * BiomeCheck.#groupSize);
123
+ return { files: slice.map(([file]) => file), count: slice.reduce((sum, [, count]) => sum + count, 0) };
124
+ });
125
+ }
126
+
127
+ static #line({ severity, category, location }: BiomeDiagnostic) {
128
+ const at = `${location?.path}:${location?.start?.line ?? 0}:${location?.start?.column ?? 0}`;
129
+ return `${at} ${severity} ${category ?? "biome"} - ${WithheldEnvFile.note}`;
130
+ }
131
+ }
@@ -0,0 +1,17 @@
1
+ //* An env file holds deployment secrets, and a source line, a formatter diff or a rule message quotes them.
2
+ export class WithheldEnvFile {
3
+ static readonly #name = "env[\\\\/]env\\.(?:server|client)(?:\\.[A-Za-z0-9-]+)*\\.ts";
4
+ static readonly #envFile = new RegExp(`[\\\\/]${WithheldEnvFile.#name}$`);
5
+ static readonly #named = new RegExp(WithheldEnvFile.#name);
6
+ static readonly note = "the text is withheld because this file holds secrets";
7
+
8
+ static isEnvFile(fileName: string | undefined) {
9
+ return (
10
+ fileName !== undefined && WithheldEnvFile.#envFile.test(fileName.startsWith("env/") ? `/${fileName}` : fileName)
11
+ );
12
+ }
13
+
14
+ static namesEnvFile(text: string) {
15
+ return WithheldEnvFile.#named.test(text);
16
+ }
17
+ }
@@ -1,5 +1,6 @@
1
1
  import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import type { SecretEnvMoved } from "../transforms/secretEnvDeclaration";
3
4
  import { ServerEnvProfile } from "../transforms/serverEnvProfile";
4
5
 
5
6
  interface SecretValue {
@@ -66,6 +67,48 @@ export class ServerBundleSecrets {
66
67
  return unread;
67
68
  }
68
69
 
70
+ //* An image's own check: the build left each secret string out at its key, and the same string may sit in what it
71
+ //* wrote for another reason. A long mixed one stops the build; a short or plain one, which code holds by chance
72
+ //* (a password equal to a database's name), comes back as a warning. Neither names a value.
73
+ async assertImageClean(bundleDir: string, moved: readonly SecretEnvMoved[]): Promise<string | null> {
74
+ //? A string under eight characters is in any bundle by chance, so it is not looked for: the env alone says
75
+ //? whether a key the build leaves as written holds it too.
76
+ const searched = (value: string) => value.length >= 8;
77
+ const sought = moved
78
+ .filter(({ value }) => searched(value))
79
+ .map((secret) => ({ secret, needles: ServerBundleSecrets.#needles(secret.value) }));
80
+ const holders = new Map<SecretEnvMoved, string[]>();
81
+ if (sought.length)
82
+ for (const bundled of await ServerBundleSecrets.#files(bundleDir)) {
83
+ const text = await readFile(bundled, "latin1");
84
+ for (const { secret, needles } of sought)
85
+ if (needles.some((needle) => text.includes(needle)))
86
+ holders.set(secret, [...(holders.get(secret) ?? []), ServerBundleSecrets.#relative(bundleDir, bundled)]);
87
+ }
88
+ const stops: string[] = [];
89
+ const notes: string[] = [];
90
+ for (const secret of moved) {
91
+ const files = holders.get(secret) ?? [];
92
+ const key = `${secret.path} (${secret.name})`;
93
+ const twins = secret.twins.length ? `the env's ${secret.twins.join(", ")}` : "";
94
+ if (files.length && ServerEnvProfile.distinctive(secret.value))
95
+ stops.push(
96
+ ...files.map((file) => `${file} holds the value of ${key}${twins ? `, which ${twins} holds as well` : ""}`),
97
+ );
98
+ else if (files.length || (twins && !searched(secret.value)))
99
+ notes.push(
100
+ `${key}: ${[files.join(", "), twins ? `${twins} holds the same string` : ""].filter(Boolean).join("; ")}`,
101
+ );
102
+ }
103
+ if (stops.length)
104
+ throw new Error(
105
+ `The build holds secret values the server reads from its process env, so it stops here:\n ${[...new Set(stops)].join("\n ")}\nThe build left each out at its secret-named key of the env file, and the same string is in what it wrote for another reason: another key of the env holds it too, or the app's code, or a file the build copies. Take it out there, or read it there from the same variable. \`akan build --inline-secrets\` builds with the env files as written until akanjs 3.5.0 removes it.`,
106
+ );
107
+ if (!notes.length) return null;
108
+ const lines = [...new Set(notes)];
109
+ return `${lines.length} secret value${lines.length === 1 ? "" : "s"} the server reads from its process env ${lines.length === 1 ? "is" : "are"} also in what this build wrote, short or plain enough to be there for another reason, so the build goes on:\n ${lines.join("\n ")}\nWhere another key of the env or the app's code holds a secret's own string, the image holds it too: change one of the two.`;
110
+ }
111
+
69
112
  //? A short or plain value the app's or a lib's own code holds as well (a default password) is that code's, which
70
113
  //? the bundle carries with or without the env file; a long mixed one is a secret copied into the code.
71
114
  async #coded(values: string[]): Promise<Set<string>> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.12",
3
+ "version": "3.3.0-rc.13",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -50,7 +50,7 @@
50
50
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
51
51
  },
52
52
  "dependencies": {
53
- "@akanjs/language": "3.3.0-rc.12",
53
+ "@akanjs/language": "3.3.0-rc.13",
54
54
  "@earendil-works/pi-agent-core": "1.5.2",
55
55
  "@earendil-works/pi-ai": "1.5.2",
56
56
  "@earendil-works/pi-codemode": "1.5.2",
@@ -59,7 +59,7 @@
59
59
  "@earendil-works/pi-tui": "1.5.2",
60
60
  "@inquirer/prompts": "^8.7.3",
61
61
  "@tailwindcss/node": "^4.3.3",
62
- "akanjs": "3.3.0-rc.12",
62
+ "akanjs": "3.3.0-rc.13",
63
63
  "chalk": "^6.0.1",
64
64
  "commander": "^15.0.0",
65
65
  "dayjs": "^1.11.23",
@@ -0,0 +1,134 @@
1
+ import path from "node:path";
2
+ import { writeText } from "./testHelpers";
3
+
4
+ const environments = ["local", "main"] as const;
5
+
6
+ export const secretEnvSentinels = {
7
+ jwt: "sentinel-jwt-2f0c",
8
+ google: "sentinel-google-91ab",
9
+ bots: ["sentinel-bot-a-44d1", "sentinel-bot-b-55e2"],
10
+ webhook: "https://hooks.example.test/services/sentinel-hook-66f3",
11
+ pem: "-----BEGIN PRIVATE KEY-----\nsentinel-pem-line-one-aa17\nsentinel-pem-line-two-bb28\n-----END PRIVATE KEY-----\n",
12
+ postgres: "postgres://app:sentinel-db-pass-77a4@db.example.test:5432/app",
13
+ storage: "https://minio:sentinel-url-pass-cc39@storage.example.test",
14
+ dollar: ["sentinel-$HOME-", '"quoted"-$', "{USER}-dd40"].join(""),
15
+ apostrophe: "sentinel-it's-$1-ee51",
16
+ libPass: "sentinel-lib-pass-88b5",
17
+ libJwt: "sentinel-lib-jwt-99c6",
18
+ local: "sentinel-local-llm-ff62",
19
+ };
20
+
21
+ export const secretEnvPlain = { hostname: "app.example.test", clientID: "plain-client-id", region: "ap-northeast-2" };
22
+
23
+ const s = secretEnvSentinels;
24
+
25
+ const mainEnv = (extra = "", head = "") => `${head}import { libEnv } from "./env.server.type";
26
+
27
+ export const env = {
28
+ ...libEnv,
29
+ hostname: ${JSON.stringify(secretEnvPlain.hostname)},
30
+ security: {
31
+ jwtSecret: ${JSON.stringify(s.jwt)},
32
+ verifies: [["password"], ["email"]],
33
+ accessTokenSeconds: 900,
34
+ sso: { google: { clientID: ${JSON.stringify(secretEnvPlain.clientID)}, clientSecret: ${JSON.stringify(s.google)} } },
35
+ },
36
+ objectStorage: { region: ${JSON.stringify(secretEnvPlain.region)}, endpoint: ${JSON.stringify(s.storage)} },
37
+ discord: { tokens: ${JSON.stringify(s.bots)}, webhook: ${JSON.stringify(s.webhook)} },
38
+ pushNoti: { firebase: { type: "service_account", private_key: ${JSON.stringify(s.pem)} } },
39
+ message: { apiSecret: ${JSON.stringify(s.dollar)}, senderPassword: ${JSON.stringify(s.apostrophe)} },
40
+ database: { postgres: { url: process.env.DATABASE_URL ?? ${JSON.stringify(s.postgres)} } },${extra}
41
+ } as const;
42
+ `;
43
+
44
+ export interface SecretEnvFixture {
45
+ appDir: string;
46
+ envDir: string;
47
+ libEnvFile: string;
48
+ }
49
+
50
+ export const writeSecretEnvFixture = async (
51
+ root: string,
52
+ { app = "demo", mainExtra = "", mainHead = "" } = {},
53
+ ): Promise<SecretEnvFixture> => {
54
+ const appDir = path.join(root, "apps", app);
55
+ const envDir = path.join(appDir, "env");
56
+ const libEnvFile = path.join(root, "libs/util/env/env.server.testing.ts");
57
+ await writeText(
58
+ path.join(envDir, "env.server.ts"),
59
+ [
60
+ ...environments.map((name) => `import { env as ${name} } from "./env.server.${name}";`),
61
+ `const envConfigs = { ${environments.join(", ")} };`,
62
+ 'const currentEnv = process.env.AKAN_PUBLIC_ENV ?? "local";',
63
+ "export const env = envConfigs[currentEnv as keyof typeof envConfigs];",
64
+ "",
65
+ ].join("\n"),
66
+ );
67
+ await writeText(
68
+ path.join(envDir, "env.server.type.ts"),
69
+ `import { env as utilOption } from ${JSON.stringify(libEnvFile)};\n\nexport const libEnv = { ...utilOption };\n`,
70
+ );
71
+ await writeText(
72
+ libEnvFile,
73
+ `export const env = {\n hostname: null,\n security: { jwtSecret: ${JSON.stringify(s.libJwt)}, verifies: [["password"]] },\n mailer: { address: "noreply@example.test", auth: { user: "mailer", pass: ${JSON.stringify(s.libPass)} } },\n};\n`,
74
+ );
75
+ await writeText(path.join(envDir, "env.server.main.ts"), mainEnv(mainExtra, mainHead));
76
+ await writeText(
77
+ path.join(envDir, "env.server.local.ts"),
78
+ `export const env = { hostname: "localhost", llm: { apiKey: ${JSON.stringify(s.local)} } };\n`,
79
+ );
80
+ return { appDir, envDir, libEnvFile };
81
+ };
82
+
83
+ export const secretEnvFixtureNames = [
84
+ "JWT_SECRET",
85
+ "SECURITY__SSO__GOOGLE__CLIENT_SECRET",
86
+ "MAILER__AUTH__PASS",
87
+ "OBJECT_STORAGE__ENDPOINT",
88
+ "DISCORD__TOKENS",
89
+ "DISCORD__WEBHOOK",
90
+ "PUSH_NOTI__FIREBASE__PRIVATE_KEY",
91
+ "MESSAGE__API_SECRET",
92
+ "MESSAGE__SENDER_PASSWORD",
93
+ "POSTGRES_URL",
94
+ ];
95
+
96
+ export const holdsSentinel = (text: string) => text.includes("sentinel-");
97
+
98
+ //* What no search of a build's files tells from code: a short password, a passphrase of plain words, a value under
99
+ //* eight characters, and a plain-named key under a secret-named one.
100
+ export const computedSecrets = {
101
+ password: "sentinel-12c",
102
+ passphrase: "sentinel-correct-horse-battery-xyzz",
103
+ short: "s9-k2",
104
+ user: "sentinel-user",
105
+ };
106
+
107
+ //* One string under a secret-named key and a plain one: a long mixed one, a short one, and one under eight characters.
108
+ export const twinSecrets = { long: "sentinel-Twin-7d21-Xq", plain: "sentinel-db", short: "s-pin" };
109
+
110
+ export const twinSecretEnv = [
111
+ "",
112
+ ` audit: { password: ${JSON.stringify(twinSecrets.long)}, label: ${JSON.stringify(twinSecrets.long)} },`,
113
+ ` cache: { password: ${JSON.stringify(twinSecrets.plain)}, name: ${JSON.stringify(twinSecrets.plain)} },`,
114
+ ` door: { secret: ${JSON.stringify(twinSecrets.short)}, hint: ${JSON.stringify(twinSecrets.short)} },`,
115
+ ].join("\n");
116
+
117
+ export const computedSecretKeys = ["store.password", "store.passphrase", "otp.secret", "credentials.user"];
118
+
119
+ export const writeComputedSecretFixture = async (root: string, app = "demo"): Promise<SecretEnvFixture> => {
120
+ await writeText(
121
+ path.join(root, "apps", app, "srvkit/keys.ts"),
122
+ `export const keys = ${JSON.stringify({ password: computedSecrets.password, passphrase: computedSecrets.passphrase, user: computedSecrets.user })};\n`,
123
+ );
124
+ return await writeSecretEnvFixture(root, {
125
+ app,
126
+ mainHead: 'import { keys } from "../srvkit/keys";\n',
127
+ mainExtra: [
128
+ "",
129
+ " store: { password: keys.password, passphrase: keys.passphrase },",
130
+ ` otp: { secret: ${JSON.stringify(computedSecrets.short.split("-"))}.join("-") },`,
131
+ " credentials: { user: keys.user },",
132
+ ].join("\n"),
133
+ });
134
+ };