@akanjs/devkit 3.3.0-rc.11 → 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 (56) hide show
  1. package/CHANGELOG.md +51 -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-err/SKILL.md +11 -2
  8. package/codeAgent/skills/akan-page/SKILL.md +4 -14
  9. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  10. package/docs/apiReference.test.ts +9 -0
  11. package/docs/apiReference.ts +14 -0
  12. package/executors/workspaceExecutor.ts +7 -4
  13. package/frontendBuild/clientEntryDiscovery.test.ts +35 -0
  14. package/frontendBuild/clientEntryDiscovery.ts +14 -1
  15. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  16. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  17. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  18. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  19. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  20. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  21. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  22. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  23. package/lint/biomeCheck.test.ts +145 -0
  24. package/lint/biomeCheck.ts +131 -0
  25. package/lint/no-arbitrary-color.grit +5 -0
  26. package/lint/no-conditional-st-hook.grit +5 -1
  27. package/lint/no-daisyui-legacy-class.grit +8 -0
  28. package/lint/no-document-cookie.grit +3 -0
  29. package/lint/no-inline-color.grit +10 -2
  30. package/lint/no-oversized-list-limit.grit +2 -0
  31. package/lint/no-raw-palette-class.grit +7 -0
  32. package/lint/no-unpublished-form-setter.grit +2 -0
  33. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  34. package/lint/no-web-storage.grit +3 -0
  35. package/lint/withheldEnvFile.ts +17 -0
  36. package/mobile/serverBundleSecrets.ts +43 -0
  37. package/package.json +3 -3
  38. package/test/secretEnvFixture.ts +134 -0
  39. package/transforms/secretEnvDeclaration.test.ts +208 -0
  40. package/transforms/secretEnvDeclaration.ts +213 -0
  41. package/transforms/secretEnvFile.test.ts +117 -0
  42. package/transforms/secretEnvFile.ts +113 -0
  43. package/transforms/secretEnvName.test.ts +54 -0
  44. package/transforms/secretEnvName.ts +29 -0
  45. package/transforms/secretEnvSource.test.ts +148 -0
  46. package/transforms/secretEnvSource.ts +166 -0
  47. package/transforms/serverEnvEvaluationError.ts +11 -0
  48. package/transforms/serverEnvPlugin.test.ts +2 -1
  49. package/transforms/serverEnvPlugin.ts +13 -0
  50. package/transforms/serverEnvProfile.test.ts +115 -2
  51. package/transforms/serverEnvProfile.ts +117 -40
  52. package/transforms/serverEnvSecrets.test.ts +292 -0
  53. package/typecheck/projectTypecheck.test.ts +29 -0
  54. package/typecheck/typeChecker.test.ts +49 -0
  55. package/typecheck/typeChecker.ts +9 -7
  56. package/typecheck/withheldDiagnostics.ts +41 -0
@@ -18,8 +18,10 @@ or {
18
18
  JsStringLiteralExpression() as $s,
19
19
  JsTemplateChunkElement() as $s
20
20
  } where {
21
+ // GritQL compiles a regex anew for every node it tries, so a substring every match must contain gates each one.
21
22
  any {
22
23
  and {
24
+ $s <: or { includes "-base-", includes "-content", includes "-error" },
23
25
  $s <: r"[\s\S]*(?:^|[\s\"'`{(\[:!])(?:bg|text|border(?:-[tblrxy])?(?:-[se])?|ring(?:-offset)?|fill|stroke|shadow|from|to|via|divide|outline|decoration|placeholder|caret|accent)-(?:base-(?:100|200|300|content)|(?:primary|secondary|accent|neutral|info|success|warning|error)-content|error)(?:[\s\"'`})\]:/!,]|$)[\s\S]*",
24
26
  register_diagnostic(
25
27
  span = $s,
@@ -28,6 +30,12 @@ or {
28
30
  )
29
31
  },
30
32
  and {
33
+ $s <: or {
34
+ includes "btn-", includes "badge-", includes "alert-", includes "input-", includes "select-",
35
+ includes "textarea-", includes "checkbox-", includes "toggle-", includes "loading-", includes "card-",
36
+ includes "modal-", includes "collapse-", includes "dropdown-", includes "stat-", includes "tab",
37
+ includes "menu-", includes "steps-", includes "join-item", includes "mockup-", includes "drawer-"
38
+ },
31
39
  $s <: r"[\s\S]*(?:^|[\s\"'`{(\[:!])(?:btn-(?:primary|secondary|accent|neutral|info|success|warning|error|ghost|link|outline|square|circle|wide|block|xs|sm|md|lg)|badge-(?:primary|secondary|accent|neutral|info|success|warning|error|ghost|outline)|alert-(?:info|success|warning|error)|input-(?:bordered|primary|secondary|accent|ghost|error)|select-(?:bordered|primary|ghost)|textarea-(?:bordered|primary|ghost)|checkbox-(?:primary|secondary|accent)|toggle-(?:primary|secondary|accent)|loading-(?:spinner|dots|ring|ball|bars|infinity)|card-(?:body|title|actions)|modal-(?:box|action|backdrop)|collapse-(?:title|content|arrow|plus)|dropdown-(?:content|end|start|hover)|stat-(?:title|value|desc)|tabs-(?:boxed|lifted|bordered)|tab-active|menu-(?:title|dropdown)|steps-(?:horizontal|vertical)|join-item|mockup-(?:code|phone|browser|window)|drawer-(?:side|content|toggle))(?:[\s\"'`})\]:/!,]|$)[\s\S]*",
32
40
  register_diagnostic(
33
41
  span = $s,
@@ -10,6 +10,8 @@ language js(typescript, jsx)
10
10
  // write is its own node (JsStaticMemberAssignment) that the expression form does not match.
11
11
  or {
12
12
  JsStaticMemberExpression() as $access where {
13
+ // GritQL copies its match state for every snippet it tries, so a substring every match must contain goes first.
14
+ $access <: includes "cookie",
13
15
  $access <: or { `document.cookie`, `window.document.cookie`, `globalThis.document.cookie`, `self.document.cookie` },
14
16
  register_diagnostic(
15
17
  span = $access,
@@ -18,6 +20,7 @@ or {
18
20
  )
19
21
  },
20
22
  JsStaticMemberAssignment(object = $object, member = $member) as $access where {
23
+ $member <: includes "cookie",
21
24
  $member <: `cookie`,
22
25
  $object <: or { `document`, `window.document`, `globalThis.document`, `self.document` },
23
26
  register_diagnostic(
@@ -11,16 +11,24 @@ language js(typescript, jsx)
11
11
  // warnings, not errors, so code written before the rule reached them is not broken.
12
12
  // The hex arm skips `url(#id)`: a paint-server id such as `#fade` is spelled in hex digits.
13
13
  // Cases: lint/__fixtures__/no-inline-color/{bad,good}.tsx
14
+
15
+ // GritQL compiles a regex anew for every node it tries, so a substring every match must contain gates it first.
16
+ pattern colour_literal_text() {
17
+ or { includes "#", includes "rgb", includes "hsl", includes "lab(", includes "lch(", includes "hwb(" }
18
+ }
19
+
14
20
  or {
15
21
  or {
16
- JsStringLiteralExpression() as $s where { $s <: within `style={$obj}` },
17
- JsTemplateChunkElement() as $s where { $s <: within `<style>$body</style>` }
22
+ JsStringLiteralExpression() as $s where { $s <: colour_literal_text(), $s <: within `style={$obj}` },
23
+ JsTemplateChunkElement() as $s where { $s <: colour_literal_text(), $s <: within `<style>$body</style>` }
18
24
  } where { $tier = "error" },
19
25
  or {
20
26
  or { JsxString(), JsStringLiteralExpression(), JsTemplateChunkElement() } as $s where {
27
+ $s <: colour_literal_text(),
21
28
  $s <: within JsxAttribute(name = r"(?:fill|stroke|stopColor|floodColor|lightingColor|color|stop-color|flood-color|lighting-color)")
22
29
  },
23
30
  or { JsStringLiteralExpression(), JsTemplateChunkElement() } as $s where {
31
+ $s <: colour_literal_text(),
24
32
  $s <: within or { `$el.style.$prop = $value`, `$el.style[$prop] = $value`, `$el.style.setProperty($prop, $value)` }
25
33
  }
26
34
  } where { $tier = "warn" }
@@ -34,6 +34,8 @@ pattern page_sort() {
34
34
  }
35
35
 
36
36
  JsCallExpression(callee = $callee, arguments = JsCallArguments(args = $args)) where {
37
+ // GritQL copies its match state for every snippet it tries, so a substring every match must contain goes first.
38
+ $callee <: or { includes "fetch", includes "do" },
37
39
  or {
38
40
  and {
39
41
  $callee <: `fetch.$endpoint`,
@@ -16,6 +16,13 @@ or {
16
16
  JsStringLiteralExpression() as $s,
17
17
  JsTemplateChunkElement() as $s
18
18
  } where {
19
+ // GritQL compiles a regex anew for every node it tries, so a substring every match must contain gates it.
20
+ $s <: or {
21
+ includes "slate-", includes "gray-", includes "zinc-", includes "neutral-", includes "stone-", includes "red-",
22
+ includes "orange-", includes "amber-", includes "yellow-", includes "lime-", includes "green-", includes "emerald-",
23
+ includes "teal-", includes "cyan-", includes "sky-", includes "blue-", includes "indigo-", includes "violet-",
24
+ includes "purple-", includes "fuchsia-", includes "pink-", includes "rose-"
25
+ },
19
26
  $s <: r"[\s\S]*(?:^|[\s\"'`{(\[:!])(?:bg|text|border(?:-[tblrxy])?(?:-[se])?|ring(?:-offset)?|fill|stroke|shadow|from|to|via|divide|outline|decoration|placeholder|caret|accent)-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d{2,3}(?:[\s\"'`})\]:/!,]|$)[\s\S]*",
20
27
  register_diagnostic(
21
28
  span = $s,
@@ -24,6 +24,8 @@ language js(typescript, jsx)
24
24
  // bind to different text, so the metavariable cannot unify them. Under-reporting, not a false positive.
25
25
  //
26
26
  JsxAttribute() as $attr where {
27
+ // GritQL copies its match state for every node a pattern tries, so a substring the reported body needs goes first.
28
+ $attr <: includes "st.do.",
27
29
  $attr <: contains JsArrowFunctionExpression() as $arrow,
28
30
  $arrow <: `($p) => $body`,
29
31
  // One bare parameter. A metavariable matches a whole parameter list leniently, so `(a, b)` binds the
@@ -10,6 +10,8 @@ language js(typescript, jsx)
10
10
  // points, because the name is also the libs/shared model (`Notification.View`, `cnst.Notification`).
11
11
  or {
12
12
  JsStaticMemberExpression() as $access where {
13
+ // GritQL copies its match state for every snippet it tries, so a substring every match must contain goes first.
14
+ $access <: includes "navigator",
13
15
  $access <: or { `navigator.share`, `navigator.canShare` },
14
16
  register_diagnostic(
15
17
  span = $access,
@@ -18,6 +20,7 @@ or {
18
20
  )
19
21
  },
20
22
  JsStaticMemberExpression() as $access where {
23
+ $access <: or { includes "navigator", includes "Notification" },
21
24
  $access <: or { `navigator.serviceWorker`, `Notification.requestPermission`, `Notification.permission` },
22
25
  register_diagnostic(
23
26
  span = $access,
@@ -26,6 +29,7 @@ or {
26
29
  )
27
30
  },
28
31
  JsStaticMemberExpression() as $access where {
32
+ $access <: includes "navigator",
29
33
  $access <: `navigator.geolocation`,
30
34
  register_diagnostic(
31
35
  span = $access,
@@ -34,6 +38,7 @@ or {
34
38
  )
35
39
  },
36
40
  JsStaticMemberExpression() as $access where {
41
+ $access <: includes "navigator",
37
42
  $access <: `navigator.vibrate`,
38
43
  register_diagnostic(
39
44
  span = $access,
@@ -11,6 +11,8 @@ language js(typescript, jsx)
11
11
  // bare snippet matches the name in any position, a field, an object key or JSX text included.
12
12
  or {
13
13
  JsIdentifierExpression() as $access where {
14
+ // GritQL copies its match state for every snippet it tries, so a substring every match must contain goes first.
15
+ $access <: includes "Storage",
14
16
  $access <: or { `localStorage`, `sessionStorage` },
15
17
  register_diagnostic(
16
18
  span = $access,
@@ -19,6 +21,7 @@ or {
19
21
  )
20
22
  },
21
23
  JsStaticMemberExpression(object = $root, member = $name) as $access where {
24
+ $name <: includes "Storage",
22
25
  $root <: or { `window`, `globalThis`, `self` },
23
26
  $name <: or { `localStorage`, `sessionStorage` },
24
27
  register_diagnostic(
@@ -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.11",
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.11",
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.11",
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
+ };
@@ -0,0 +1,208 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import path from "node:path";
3
+ import {
4
+ computedSecretKeys,
5
+ holdsSentinel,
6
+ secretEnvFixtureNames,
7
+ secretEnvSentinels,
8
+ writeComputedSecretFixture,
9
+ writeSecretEnvFixture,
10
+ } from "../test/secretEnvFixture";
11
+ import { tempDirs, writeText } from "../test/testHelpers";
12
+ import { SecretEnvDeclaration } from "./secretEnvDeclaration";
13
+ import { SecretEnvFile } from "./secretEnvFile";
14
+
15
+ const makeTempRoot = tempDirs("akan-devkit-secret-env-");
16
+
17
+ const withShell = async <T>(variables: { [name: string]: string }, run: () => Promise<T>) => {
18
+ const before = Object.fromEntries(Object.keys(variables).map((name) => [name, process.env[name]]));
19
+ Object.assign(process.env, variables);
20
+ try {
21
+ return await run();
22
+ } finally {
23
+ for (const [name, value] of Object.entries(before)) {
24
+ if (value === undefined) delete process.env[name];
25
+ else process.env[name] = value;
26
+ }
27
+ }
28
+ };
29
+
30
+ const ownReads = [
31
+ "",
32
+ " own: {",
33
+ " apiKey: process.env.ZQ_API_KEY,",
34
+ ' token: "Bearer " + process.env.ZQ_TOKEN,',
35
+ [" url: `postgres://app:$", "{process.env.ZQ_DB_PASS}@db.example.test/app`,"].join(""),
36
+ ' privateKey: process.env.ZQ_PEM?.replace(/\\\\n/g, "\\n"),',
37
+ ' password: process.env.ZQ_PASSWORD ?? "sentinel-own-fallback-3c55",',
38
+ " },",
39
+ ].join("\n");
40
+
41
+ const shellOwn = {
42
+ ZQ_API_KEY: "shell-api-key-1d20",
43
+ ZQ_TOKEN: "abc",
44
+ ZQ_DB_PASS: "shell-db-pass-2e31",
45
+ ZQ_PEM: "-----BEGIN-----\\nshell-pem-line-3f42\\n-----END-----",
46
+ ZQ_PASSWORD: "shell-password-4a53",
47
+ };
48
+
49
+ describe("SecretEnvDeclaration", () => {
50
+ test("lists each secret of the environment's server env with its variable, kind and value, a lib's default included", async () => {
51
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot());
52
+ const { variables, unmoved } = await SecretEnvDeclaration.of(envDir, "main");
53
+ expect(unmoved).toEqual([]);
54
+ expect(variables.map(({ name }) => name)).toEqual(secretEnvFixtureNames);
55
+ expect(Object.fromEntries(variables.map(({ name, kind, path: at, value }) => [name, { kind, at, value }]))).toEqual(
56
+ {
57
+ JWT_SECRET: { kind: "string", at: "security.jwtSecret", value: secretEnvSentinels.jwt },
58
+ SECURITY__SSO__GOOGLE__CLIENT_SECRET: {
59
+ kind: "string",
60
+ at: "security.sso.google.clientSecret",
61
+ value: secretEnvSentinels.google,
62
+ },
63
+ MAILER__AUTH__PASS: { kind: "string", at: "mailer.auth.pass", value: secretEnvSentinels.libPass },
64
+ OBJECT_STORAGE__ENDPOINT: { kind: "string", at: "objectStorage.endpoint", value: secretEnvSentinels.storage },
65
+ DISCORD__TOKENS: { kind: "json", at: "discord.tokens", value: JSON.stringify(secretEnvSentinels.bots) },
66
+ DISCORD__WEBHOOK: { kind: "string", at: "discord.webhook", value: secretEnvSentinels.webhook },
67
+ PUSH_NOTI__FIREBASE__PRIVATE_KEY: {
68
+ kind: "multiline",
69
+ at: "pushNoti.firebase.private_key",
70
+ value: secretEnvSentinels.pem,
71
+ },
72
+ MESSAGE__API_SECRET: { kind: "string", at: "message.apiSecret", value: secretEnvSentinels.dollar },
73
+ MESSAGE__SENDER_PASSWORD: {
74
+ kind: "string",
75
+ at: "message.senderPassword",
76
+ value: secretEnvSentinels.apostrophe,
77
+ },
78
+ POSTGRES_URL: { kind: "string", at: "database.postgres.url", value: secretEnvSentinels.postgres },
79
+ },
80
+ );
81
+ });
82
+
83
+ test("the listing names every variable and its key, says which the shell sets, and holds no value", async () => {
84
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot());
85
+ const declared = await SecretEnvDeclaration.of(envDir, "main");
86
+ const shell = process.env.MAILER__AUTH__PASS;
87
+ process.env.MAILER__AUTH__PASS = "set-in-the-shell";
88
+ try {
89
+ const listing = SecretEnvFile.listing(declared);
90
+ expect(holdsSentinel(listing)).toBe(false);
91
+ expect(listing.split("\n")).toEqual([
92
+ "VARIABLE KIND SHELL ENV FILE KEY",
93
+ "JWT_SECRET string unset security.jwtSecret",
94
+ "SECURITY__SSO__GOOGLE__CLIENT_SECRET string unset security.sso.google.clientSecret",
95
+ "MAILER__AUTH__PASS string set mailer.auth.pass",
96
+ "OBJECT_STORAGE__ENDPOINT string unset objectStorage.endpoint",
97
+ "DISCORD__TOKENS json unset discord.tokens",
98
+ "DISCORD__WEBHOOK string unset discord.webhook",
99
+ "PUSH_NOTI__FIREBASE__PRIVATE_KEY multiline unset pushNoti.firebase.private_key",
100
+ "MESSAGE__API_SECRET string unset message.apiSecret",
101
+ "MESSAGE__SENDER_PASSWORD string unset message.senderPassword",
102
+ "POSTGRES_URL string unset database.postgres.url",
103
+ ]);
104
+ } finally {
105
+ if (shell === undefined) delete process.env.MAILER__AUTH__PASS;
106
+ else process.env.MAILER__AUTH__PASS = shell;
107
+ }
108
+ });
109
+
110
+ test("lists the environment asked for, and the env file itself where it replaced the switch", async () => {
111
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot());
112
+ const local = await SecretEnvDeclaration.of(envDir, "local");
113
+ expect(local.variables.map(({ name, value }) => [name, value])).toEqual([
114
+ ["LLM__API_KEY", secretEnvSentinels.local],
115
+ ]);
116
+ await writeText(
117
+ path.join(envDir, "env.server.ts"),
118
+ `export const env = { security: { jwtSecret: ${JSON.stringify(secretEnvSentinels.jwt)} }, hostname: "app.example.test" };\n`,
119
+ );
120
+ const replaced = await SecretEnvDeclaration.of(envDir, "main");
121
+ expect(replaced.variables.map(({ name, value }) => [name, value])).toEqual([
122
+ ["JWT_SECRET", secretEnvSentinels.jwt],
123
+ ]);
124
+ });
125
+
126
+ test("names every key whose secret the env file imports or computes, a short one and a plain-named one under a secret parent included", async () => {
127
+ const { envDir } = await writeComputedSecretFixture(await makeTempRoot());
128
+ const declared = await SecretEnvDeclaration.of(envDir, "main");
129
+ expect(declared.unmoved).toEqual(computedSecretKeys);
130
+ expect(SecretEnvFile.listing(declared)).toEndWith(
131
+ `\n\`akan build\` stops at ${computedSecretKeys.join(", ")}: secret values the env file computes or imports. Write the string at the key, or read it there yourself as \`process.env.<NAME>\`.`,
132
+ );
133
+ });
134
+
135
+ test("names a secret the env file computes as one no build can move, without its value", async () => {
136
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), {
137
+ mainExtra: '\n llm: { apiKey: ["sentinel", "computed", "0a73"].join("-") },',
138
+ });
139
+ const declared = await SecretEnvDeclaration.of(envDir, "main");
140
+ expect(declared.unmoved).toEqual(["llm.apiKey"]);
141
+ expect(declared.variables.map(({ name }) => name)).toEqual(secretEnvFixtureNames);
142
+ const listing = SecretEnvFile.listing(declared);
143
+ expect(holdsSentinel(listing)).toBe(false);
144
+ expect(listing).toEndWith(
145
+ "\n`akan build` stops at llm.apiKey: a secret value the env file computes or imports. Write the string at the key, or read it there yourself as `process.env.<NAME>`.",
146
+ );
147
+ });
148
+
149
+ test("a secret key the env file reads from the process env itself is nothing the build moves or holds, with the variable unset", async () => {
150
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), { mainExtra: ownReads });
151
+ const declared = await SecretEnvDeclaration.of(envDir, "main");
152
+ expect(declared.unmoved).toEqual([]);
153
+ expect(declared.variables.map(({ name }) => name)).toEqual([...secretEnvFixtureNames, "OWN__PASSWORD"]);
154
+ });
155
+
156
+ test("its own read is told from a computed secret also when another of its variables cannot take a made-up value", async () => {
157
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), {
158
+ mainExtra: `${ownReads}\n origin: new URL(process.env.ZQ_ORIGIN ?? "https://app.example.test").host,`,
159
+ });
160
+ expect((await SecretEnvDeclaration.of(envDir, "main")).unmoved).toEqual([]);
161
+ });
162
+
163
+ test("an env file that needs a variable of the shell to load is listed with it set, its own reads left alone, and named by error class and line without it", async () => {
164
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), {
165
+ mainExtra: `${ownReads}\n hosts: process.env.ZQ_HOSTS!.split(","),\n push: { privateKey: process.env.ZQ_PEM!.replace(/\\\\n/g, "\\n") },`,
166
+ });
167
+ const failure = await SecretEnvDeclaration.of(envDir, "main").catch((error: Error) => error.message);
168
+ expect(failure).toMatch(
169
+ /^env\.server\.ts could not be evaluated to check it for secrets: TypeError at .*env\.server\.main\.ts:\d+$/,
170
+ );
171
+ const declared = await withShell({ ...shellOwn, ZQ_HOSTS: "a.example.test,b.example.test" }, () =>
172
+ SecretEnvDeclaration.of(envDir, "main"),
173
+ );
174
+ expect(declared.unmoved).toEqual([]);
175
+ expect(declared.variables.map(({ name }) => name)).toEqual([...secretEnvFixtureNames, "OWN__PASSWORD"]);
176
+ expect(JSON.stringify(declared.variables)).not.toContain("shell-");
177
+ });
178
+
179
+ test("a value the env file imports behind its own read is still one no build can move, while the variable is unset", async () => {
180
+ const root = await makeTempRoot();
181
+ await writeText(path.join(root, "apps/demo/srvkit/keys.ts"), 'export const llmKey = "sentinel-imported-0a73";\n');
182
+ const { envDir } = await writeSecretEnvFixture(root, {
183
+ mainHead: 'import { llmKey } from "../srvkit/keys";\n',
184
+ mainExtra: "\n llm: { apiKey: process.env.ZQ_LLM_KEY ?? llmKey },",
185
+ });
186
+ expect((await SecretEnvDeclaration.of(envDir, "main")).unmoved).toEqual(["llm.apiKey"]);
187
+ });
188
+
189
+ test("says so when the server env holds no secret", async () => {
190
+ const root = await makeTempRoot();
191
+ const envDir = path.join(root, "apps/demo/env");
192
+ await writeText(path.join(envDir, "env.server.ts"), 'export const env = { hostname: "app.example.test" };\n');
193
+ expect(SecretEnvFile.listing(await SecretEnvDeclaration.of(envDir, "main"))).toBe(
194
+ "The server env holds no secret value, so a build reads none.",
195
+ );
196
+ });
197
+
198
+ test("refuses a key whose variable the platform owns, naming the file and the key and not the value", async () => {
199
+ const { envDir } = await writeSecretEnvFixture(await makeTempRoot(), {
200
+ mainExtra: '\n pwd: "sentinel-pwd-1b84",',
201
+ });
202
+ const failure = await SecretEnvDeclaration.of(envDir, "main").catch((error: Error) => error.message);
203
+ expect(failure).toContain(
204
+ "env.server.main.ts `pwd` is a secret a build would read from the environment variable PWD",
205
+ );
206
+ expect(holdsSentinel(String(failure))).toBe(false);
207
+ });
208
+ });