@akanjs/devkit 3.3.0-rc.2 → 3.3.0-rc.21

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 (111) hide show
  1. package/CHANGELOG.md +284 -20
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/README.ko.md +3 -2
  4. package/README.md +3 -3
  5. package/akanApp/akanApp.host.test.ts +1 -1
  6. package/akanConfig/akanConfig.test.ts +57 -8
  7. package/akanConfig/akanConfig.ts +16 -69
  8. package/akanConfig/dockerImage.ts +17 -0
  9. package/akanConfig/nativeKeys.ts +52 -0
  10. package/app/applicationBuildRunner.test.ts +321 -1
  11. package/app/applicationBuildRunner.ts +90 -3
  12. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  13. package/codeAgent/agent/CodeAgent.ts +36 -16
  14. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  15. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  16. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  17. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  18. package/codeAgent/agent/codeAgent.test.ts +62 -0
  19. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  20. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  21. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  22. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  23. package/codeAgent/skills/akan-err/SKILL.md +11 -2
  24. package/codeAgent/skills/akan-page/SKILL.md +21 -26
  25. package/codeAgent/skills/akan-runtime/SKILL.md +41 -16
  26. package/codeAgent/skills/akan-service/SKILL.md +2 -2
  27. package/docs/apiReference.test.ts +14 -0
  28. package/docs/apiReference.ts +21 -3
  29. package/docs/declarationReader.ts +28 -1
  30. package/executors/appExecutor.ts +16 -7
  31. package/executors/workspaceExecutor.ts +7 -4
  32. package/frontendBuild/buildRouteClient.test.ts +2 -7
  33. package/frontendBuild/clientEntryDiscovery.test.ts +35 -0
  34. package/frontendBuild/clientEntryDiscovery.ts +16 -3
  35. package/frontendBuild/cssCompiler.test.ts +112 -0
  36. package/frontendBuild/cssCompiler.ts +41 -21
  37. package/frontendBuild/devBarrelImports.test.ts +30 -0
  38. package/frontendBuild/devBarrelImports.ts +2 -2
  39. package/frontendBuild/pagesBundleBuilder.ts +3 -1
  40. package/frontendBuild/plainStylesheet.test.ts +155 -0
  41. package/frontendBuild/plainStylesheet.ts +197 -0
  42. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  43. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  44. package/guideline/agentAssets.test.ts +10 -0
  45. package/guideline/agentAssets.ts +52 -11
  46. package/incrementalBuilder/buildBatch.proc.ts +9 -9
  47. package/incrementalBuilder/buildBatchProtocol.ts +1 -1
  48. package/incrementalBuilder/builderBoot.ts +5 -5
  49. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  50. package/incrementalBuilder/builderLanes.ts +2 -2
  51. package/incrementalBuilder/builderWatch.ts +8 -8
  52. package/incrementalBuilder/csrRegistry.ts +4 -4
  53. package/incrementalBuilder/incrementalBuilder.proc.ts +8 -8
  54. package/incrementalBuilder/ssrRegistry.ts +6 -6
  55. package/index.ts +1 -1
  56. package/integration/renderAdmissionSoak.test.ts +99 -0
  57. package/integration/renderAdmissionSoak.ts +609 -0
  58. package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
  59. package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
  60. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
  61. package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
  62. package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
  63. package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
  64. package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
  65. package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
  66. package/lint/biomeCheck.test.ts +145 -0
  67. package/lint/biomeCheck.ts +131 -0
  68. package/lint/no-arbitrary-color.grit +5 -0
  69. package/lint/no-conditional-st-hook.grit +5 -1
  70. package/lint/no-daisyui-legacy-class.grit +8 -0
  71. package/lint/no-document-cookie.grit +3 -0
  72. package/lint/no-inline-color.grit +10 -2
  73. package/lint/no-oversized-list-limit.grit +2 -0
  74. package/lint/no-raw-palette-class.grit +7 -0
  75. package/lint/no-unpublished-form-setter.grit +2 -0
  76. package/lint/no-web-only-api-outside-webkit.grit +5 -0
  77. package/lint/no-web-storage.grit +3 -0
  78. package/lint/withheldEnvFile.ts +17 -0
  79. package/mobile/nativeApp.test.ts +7 -5
  80. package/mobile/nativeApp.ts +2 -2
  81. package/mobile/nativeConfig.test.ts +117 -1
  82. package/mobile/nativeConfig.ts +66 -22
  83. package/mobile/serverBundleSecrets.ts +43 -0
  84. package/package.json +14 -169
  85. package/packageExports.test.ts +38 -24
  86. package/test/secretEnvFixture.ts +134 -0
  87. package/transforms/barrelAnalyzer.ts +2 -2
  88. package/transforms/secretEnvDeclaration.test.ts +208 -0
  89. package/transforms/secretEnvDeclaration.ts +213 -0
  90. package/transforms/secretEnvFile.test.ts +117 -0
  91. package/transforms/secretEnvFile.ts +113 -0
  92. package/transforms/secretEnvName.test.ts +54 -0
  93. package/transforms/secretEnvName.ts +29 -0
  94. package/transforms/secretEnvSource.test.ts +148 -0
  95. package/transforms/secretEnvSource.ts +166 -0
  96. package/transforms/serverEnvEvaluationError.ts +11 -0
  97. package/transforms/serverEnvPlugin.test.ts +2 -1
  98. package/transforms/serverEnvPlugin.ts +13 -0
  99. package/transforms/serverEnvProfile.test.ts +115 -2
  100. package/transforms/serverEnvProfile.ts +117 -40
  101. package/transforms/serverEnvSecrets.test.ts +292 -0
  102. package/transforms/transforms.test.ts +3 -3
  103. package/tunnel/createTunnel.test.ts +29 -8
  104. package/tunnel/createTunnel.ts +18 -11
  105. package/typecheck/projectTypecheck.test.ts +29 -0
  106. package/typecheck/typeChecker.test.ts +49 -0
  107. package/typecheck/typeChecker.ts +9 -7
  108. package/typecheck/withheldDiagnostics.ts +41 -0
  109. package/util/fileEditor.ts +1 -0
  110. package/util/selectModel.ts +1 -0
  111. package/workspace/getRelatedCnsts.ts +7 -0
@@ -14,12 +14,19 @@ const barrelFacets = async (): Promise<string[]> => {
14
14
  return [...barrel.matchAll(/^export (?:type )?\* from "\.\/([^"]+)";$/gm)].map((match) => `./${match[1]}`);
15
15
  };
16
16
 
17
+ //? The CLI's dist inlines devkit: once installed, only devkit's own sources, the CLI's templates and the README
18
+ //? examples a tool author copies import a subpath.
17
19
  const importedSubpaths = async (): Promise<string[]> => {
18
20
  const repoRoot = path.resolve(packageDir, "../../..");
19
- const glob = new Bun.Glob("pkgs/@akanjs/{cli,devkit}/**/*.{ts,tsx}");
20
21
  const found = new Set<string>();
21
- for await (const relative of glob.scan({ cwd: repoRoot })) {
22
- if (relative.includes("node_modules/") || relative.includes("/dist/")) continue;
22
+ const sources = [
23
+ ...new Bun.Glob("pkgs/@akanjs/devkit/**/*.{ts,tsx}").scanSync({ cwd: repoRoot }),
24
+ ...new Bun.Glob("pkgs/@akanjs/devkit/README*.md").scanSync({ cwd: repoRoot }),
25
+ ...new Bun.Glob("pkgs/@akanjs/cli/templates/**/*").scanSync({ cwd: repoRoot }),
26
+ ];
27
+ for (const relative of sources) {
28
+ if (relative.includes("node_modules/") || relative.includes("/dist/") || /\.(test|spec)\.tsx?$/.test(relative))
29
+ continue;
23
30
  const source = await Bun.file(path.join(repoRoot, relative)).text();
24
31
  for (const match of source.matchAll(/"@akanjs\/devkit\/([a-zA-Z0-9_./-]+)"/g)) found.add(`./${match[1]}`);
25
32
  }
@@ -27,29 +34,45 @@ const importedSubpaths = async (): Promise<string[]> => {
27
34
  };
28
35
 
29
36
  describe("published exports map", () => {
30
- test("resolves every facet the root barrel re-exports", async () => {
31
- const facets = await barrelFacets();
32
- expect(facets.length).toBeGreaterThan(30);
33
- expect(exportsMap.findUnreachable(facets)).toEqual([]);
37
+ test("names every public subpath, with no wildcard to reach a file it does not", async () => {
38
+ const manifest = (await Bun.file(path.join(packageDir, "package.json")).json()) as {
39
+ exports: Record<string, unknown>;
40
+ };
41
+ const subpaths = Object.keys(manifest.exports);
42
+ expect(subpaths.filter((subpath) => subpath.includes("*"))).toEqual([]);
43
+ expect(subpaths.length).toBeGreaterThan(20);
44
+ expect(exportsMap.findUnreachable(subpaths)).toEqual([]);
34
45
  });
35
46
 
36
- test("resolves every subpath the monorepo actually imports", async () => {
47
+ test("resolves every subpath a published install imports", async () => {
37
48
  const subpaths = await importedSubpaths();
38
- expect(subpaths.length).toBeGreaterThan(20);
49
+ expect(subpaths).toContain("./executors");
39
50
  expect(exportsMap.findUnreachable(subpaths)).toEqual([]);
40
51
  });
41
52
 
42
- test("covers both facet shapes and keeps explicit extensions intact", () => {
43
- // One wildcard cannot serve bare files, directory facets and already-suffixed specifiers (no `.ts.ts`) at once.
53
+ test("points a directory facet at its index and a nested entry at its file", () => {
44
54
  expect(exportsMap.resolve("./executors")).toBe("./executors/index.ts");
45
- expect(exportsMap.resolve("./fileSys")).toBe("./util/fileSys.ts");
46
- expect(exportsMap.resolve("./workspaceLayout.ts")).toBe("./workspace/workspaceLayout.ts");
47
55
  expect(exportsMap.resolve("./frontendBuild")).toBe("./frontendBuild/index.ts");
48
- expect(exportsMap.resolve("./cloud/cloudApi.ts")).toBe("./cloud/cloudApi.ts");
56
+ expect(exportsMap.resolve("./cloud/cloudApi")).toBe("./cloud/cloudApi.ts");
49
57
  expect(exportsMap.resolve("./package.json")).toBe("./package.json");
50
58
  });
51
59
 
52
- test("every directory facet has a literal entry, since the wildcard cannot probe index.ts", async () => {
60
+ test("keeps an entry for each nested file a consumer workspace imports", () => {
61
+ const nested = [
62
+ "cloud/cloudApi",
63
+ "cloud/cloudUpdates",
64
+ "commandDecorators/exitCodeError",
65
+ "mobile/desktopRelease",
66
+ "mobile/serverBundleSecrets",
67
+ "transforms/serverEnvProfile",
68
+ "util/fileEditor",
69
+ "util/selectModel",
70
+ "workspace/getRelatedCnsts",
71
+ ];
72
+ expect(nested.filter((file) => exportsMap.resolve(`./${file}`) !== `./${file}.ts`)).toEqual([]);
73
+ });
74
+
75
+ test("every directory facet the root barrel re-exports has a literal entry", async () => {
53
76
  const facets = await barrelFacets();
54
77
  const missing = facets.filter(
55
78
  (subpath) =>
@@ -58,15 +81,6 @@ describe("published exports map", () => {
58
81
  expect(missing).toEqual([]);
59
82
  });
60
83
 
61
- test("points every literal entry at a file, so a subpath the root once held still loads from its folder", async () => {
62
- const manifest = (await Bun.file(path.join(packageDir, "package.json")).json()) as {
63
- exports: Record<string, unknown>;
64
- };
65
- const literals = Object.keys(manifest.exports).filter((subpath) => !subpath.includes("*"));
66
- expect(literals.length).toBeGreaterThan(100);
67
- expect(exportsMap.findUnreachable(literals)).toEqual([]);
68
- });
69
-
70
84
  test("keeps every source out of the package root but its type barrel", () => {
71
85
  const loose = [...new Bun.Glob("*.{ts,tsx}").scanSync({ cwd: packageDir })].filter(
72
86
  (file) => file !== "index.ts" && !file.endsWith(".test.ts"),
@@ -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
+ };
@@ -18,7 +18,7 @@ export interface PackageEntry {
18
18
  entryFile: string;
19
19
  /** Absolute base directory for subpath computation, typically `dirname(entryFile)`. */
20
20
  pkgDir: string;
21
- /** Emit concrete file paths, for package exports that do not support extensionless deep imports. */
21
+ /** Emit absolute file paths: an installed package's exports name its barrels, never the files behind them. */
22
22
  preserveFilePath?: boolean;
23
23
  }
24
24
 
@@ -211,7 +211,7 @@ export class BarrelAnalyzer {
211
211
  #subpathFor(pkg: PackageEntry, absFile: string): string | null {
212
212
  const rel = path.relative(pkg.pkgDir, absFile);
213
213
  if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null;
214
- if (pkg.preserveFilePath) return `${pkg.pkgName}/${rel.split(path.sep).join("/")}`;
214
+ if (pkg.preserveFilePath) return absFile.split(path.sep).join("/");
215
215
  const ext = CANDIDATE_EXTS.find((candidate) => rel.endsWith(candidate));
216
216
  const parts = (ext ? rel.slice(0, -ext.length) : rel).split(path.sep);
217
217
  // `xxx/index` collapses to `xxx`: callers import `@pkg/xxx`, never `@pkg/xxx/index`.
@@ -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
+ });
@@ -0,0 +1,213 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { Logger } from "akanjs/common";
4
+ import type { SecretEnvEntry, SecretEnvKind } from "akanjs/server/lifecycle/secretEnv";
5
+ import { SecretEnvName } from "./secretEnvName";
6
+ import { type SecretEnvMode, SecretEnvSource } from "./secretEnvSource";
7
+ import { ServerEnvEvaluationError } from "./serverEnvEvaluationError";
8
+ import { type EnvEvaluated, ServerEnvProfile, type ServerEnvSource } from "./serverEnvProfile";
9
+
10
+ export interface SecretEnvVariable extends SecretEnvEntry {
11
+ path: string;
12
+ value: string;
13
+ }
14
+
15
+ interface Variables {
16
+ readonly [name: string]: string;
17
+ }
18
+
19
+ interface Loaded extends EnvEvaluated {
20
+ variables: Variables;
21
+ }
22
+
23
+ interface Computed {
24
+ at: string;
25
+ segments: string[];
26
+ value: string;
27
+ }
28
+
29
+ interface MarkedVariable extends SecretEnvVariable {
30
+ literal: unknown;
31
+ underSecret: boolean;
32
+ }
33
+
34
+ interface Found {
35
+ variables: MarkedVariable[];
36
+ computed: Computed[];
37
+ plain: { at: string; value: string }[];
38
+ }
39
+
40
+ export interface SecretEnvMoved {
41
+ path: string;
42
+ name: string;
43
+ /** One secret string the variable holds: the value, an item of its array, or the password of a URL in it. */
44
+ value: string;
45
+ /** Keys of the env that hold the same string and stay in the build as written. */
46
+ twins: string[];
47
+ }
48
+
49
+ export interface SecretEnvDeclared {
50
+ variables: SecretEnvVariable[];
51
+ /** Keys whose secret value the env computes or imports, and does not read from the process env itself. */
52
+ unmoved: string[];
53
+ moved: SecretEnvMoved[];
54
+ }
55
+
56
+ //* Evaluated with each secret literal marked as a build replaces it, so the list is the reads the built server holds.
57
+ export class SecretEnvDeclaration {
58
+ //? Lowercase letters and digits, which `encodeURIComponent` and a URL's parts keep as they are.
59
+ static readonly #unset = "akanownenvunset7q3x9";
60
+ static readonly #set = "akanownenvset5k8w2";
61
+
62
+ static async of(envDir: string, environment: string): Promise<SecretEnvDeclared> {
63
+ const file = path.join(envDir, "env.server.ts");
64
+ if (!existsSync(file))
65
+ throw new Error(`${file} is missing: \`akan sync\` writes the app's env files where it has none.`);
66
+ const loaded = await SecretEnvDeclaration.#loaded(file, envDir, environment);
67
+ const found: Found = { variables: [], computed: [], plain: [] };
68
+ SecretEnvDeclaration.#collect(loaded.value, "", [], false, found);
69
+ const variables = new Map<string, MarkedVariable>();
70
+ for (const variable of found.variables) {
71
+ const taken = variables.get(variable.name);
72
+ if (taken && taken.path !== variable.path)
73
+ throw new Error(
74
+ `${file} holds \`${taken.path}\` and \`${variable.path}\`, secrets a build would both read from the environment variable ${variable.name}. Rename one of the keys.`,
75
+ );
76
+ variables.set(variable.name, variable);
77
+ }
78
+ const computed = await SecretEnvDeclaration.#notRead(found.computed, file, envDir, environment, loaded);
79
+ return {
80
+ variables: [...variables.values()].map(({ name, kind, path: at, value }) => ({ name, kind, path: at, value })),
81
+ unmoved: [...new Set(computed.map(({ at }) => at))],
82
+ moved: [...variables.values()].flatMap(({ name, path: at, literal, underSecret }) =>
83
+ ServerEnvProfile.movedTexts(literal, underSecret).map((value) => ({
84
+ path: at,
85
+ name,
86
+ value,
87
+ twins: [
88
+ ...new Set(
89
+ found.plain
90
+ .filter((plain) => plain.value === value || (value.length >= 8 && plain.value.includes(value)))
91
+ .map((plain) => plain.at),
92
+ ),
93
+ ],
94
+ })),
95
+ ),
96
+ };
97
+ }
98
+
99
+ static async #evaluate(file: string, envDir: string, environment: string, variables: Variables) {
100
+ return await ServerEnvProfile.evaluateReads(
101
+ file,
102
+ path.dirname(envDir),
103
+ (envFile) => SecretEnvDeclaration.source(envFile, "mark"),
104
+ { environment, loads: ServerEnvProfile.envModulePattern, variables },
105
+ );
106
+ }
107
+
108
+ //* With no variable of the shell first, so the list is the same from any shell and a value is what the bundle
109
+ //* carries with none set. An env file that cannot load so (`process.env.HOSTS!.split(",")`) loads with the shell's.
110
+ static async #loaded(file: string, envDir: string, environment: string): Promise<Loaded> {
111
+ try {
112
+ return { ...(await SecretEnvDeclaration.#evaluate(file, envDir, environment, {})), variables: {} };
113
+ } catch (error) {
114
+ if (!(error instanceof ServerEnvEvaluationError) || error.reason === "timedOut") throw error;
115
+ }
116
+ const variables = Object.fromEntries(
117
+ Object.entries(process.env).flatMap(([name, value]) => (value === undefined ? [] : [[name, value]])),
118
+ );
119
+ return { ...(await SecretEnvDeclaration.#evaluate(file, envDir, environment, variables)), variables };
120
+ }
121
+
122
+ //* Leaves out what the env file reads from the process env itself, which the bundle holds as a read: a value a
123
+ //* variable of the shell gave, and one that changes with a variable the file asked for.
124
+ static async #notRead(computed: Computed[], file: string, envDir: string, environment: string, loaded: Loaded) {
125
+ const given = Object.values(loaded.variables).filter((value) => value !== "");
126
+ const kept = computed.filter(
127
+ ({ value }) => !given.some((own) => own === value || (own.length >= 8 && value.includes(own))),
128
+ );
129
+ if (!kept.length) return kept;
130
+ const names = loaded.reads.filter((name) => SecretEnvName.refusal(name) === null);
131
+ const probe = async (probed: string[]) =>
132
+ await SecretEnvDeclaration.#evaluate(file, envDir, environment, {
133
+ ...loaded.variables,
134
+ ...Object.fromEntries(
135
+ probed.map((name) => [
136
+ name,
137
+ Object.hasOwn(loaded.variables, name)
138
+ ? `${loaded.variables[name]}${SecretEnvDeclaration.#set}`
139
+ : SecretEnvDeclaration.#unset,
140
+ ]),
141
+ ),
142
+ }).then(
143
+ ({ value }) => [value],
144
+ (error: unknown) => {
145
+ if (error instanceof ServerEnvEvaluationError) return [];
146
+ throw error;
147
+ },
148
+ );
149
+ //? All names at once, and one at a time when that cannot load: `new URL(process.env.BASE ?? "…")` throws on a probe.
150
+ const all = names.length ? await probe(names) : [];
151
+ const probes = all.length ? all : (await Promise.all(names.slice(0, 32).map((name) => probe([name])))).flat();
152
+ return kept.filter(
153
+ ({ segments, value }) =>
154
+ !probes.some((probed) =>
155
+ SecretEnvDeclaration.#followsRead(
156
+ value,
157
+ segments.reduce<unknown>(
158
+ (node, key) => (node as { [key: string]: unknown } | null | undefined)?.[key],
159
+ probed,
160
+ ),
161
+ ),
162
+ ),
163
+ );
164
+ }
165
+
166
+ //* `"Bearer " + process.env.TOKEN` reads "Bearer undefined" with the variable unset and holds the probe with it set.
167
+ static #followsRead(value: string, probed: unknown) {
168
+ if (typeof probed !== "string") return false;
169
+ const lower = probed.toLowerCase();
170
+ if (!lower.includes(SecretEnvDeclaration.#set) && !lower.includes(SecretEnvDeclaration.#unset)) return false;
171
+ const given = probed.replace(new RegExp(SecretEnvDeclaration.#set, "gi"), "");
172
+ const unset = new RegExp(SecretEnvDeclaration.#unset, "gi");
173
+ return ["undefined", "", "null"].some((gone) => given.replace(unset, gone) === value);
174
+ }
175
+
176
+ static async source(file: string, mode: SecretEnvMode): Promise<ServerEnvSource> {
177
+ const contents = await Bun.file(file).text();
178
+ const name = path.basename(file, ".ts").slice("env.server.".length);
179
+ if (name === "type" || name === "example") return { loader: "ts", contents };
180
+ return { loader: "ts", contents: SecretEnvSource.rewrite(file, contents, mode) };
181
+ }
182
+
183
+ static #collect(value: unknown, at: string, segments: string[], underSecret: boolean, found: Found): void {
184
+ if (typeof value === "string") {
185
+ found.plain.push({ at, value });
186
+ if (ServerEnvProfile.isSecret(value, underSecret)) found.computed.push({ at, segments, value });
187
+ return;
188
+ }
189
+ if (!value || typeof value !== "object") return;
190
+ if (Array.isArray(value)) {
191
+ for (const [index, item] of value.entries())
192
+ SecretEnvDeclaration.#collect(item, at, [...segments, String(index)], underSecret, found);
193
+ return;
194
+ }
195
+ const mark = (value as { [key: string]: unknown })[SecretEnvSource.markKey];
196
+ if (Array.isArray(mark)) {
197
+ const [name, kind, literal] = mark as [string, SecretEnvKind, unknown];
198
+ //? A string a build moved is a secret wherever it sits: a credential URL is one under a plain key too.
199
+ const held = underSecret || typeof literal === "string";
200
+ const value = typeof literal === "string" ? literal : JSON.stringify(literal);
201
+ found.variables.push({ name, kind, path: at, value, literal, underSecret: held });
202
+ return;
203
+ }
204
+ for (const [key, child] of Object.entries(value))
205
+ SecretEnvDeclaration.#collect(
206
+ child,
207
+ at ? `${at}.${key}` : key,
208
+ [...segments, key],
209
+ underSecret || Logger.isSecretKey(key),
210
+ found,
211
+ );
212
+ }
213
+ }