@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
@@ -0,0 +1,117 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { parseEnvFile } from "../executors";
5
+ import { secretEnvSentinels, writeSecretEnvFixture } from "../test/secretEnvFixture";
6
+ import { tempDirs } from "../test/testHelpers";
7
+ import { SecretEnvDeclaration } from "./secretEnvDeclaration";
8
+ import { SecretEnvFile } from "./secretEnvFile";
9
+
10
+ const makeTempRoot = tempDirs("akan-devkit-secret-env-file-");
11
+
12
+ const declare = async () => {
13
+ const root = await makeTempRoot();
14
+ const { envDir } = await writeSecretEnvFixture(root);
15
+ const { variables } = await SecretEnvDeclaration.of(envDir, "main");
16
+ return { root, variables, values: Object.fromEntries(variables.map(({ name, value }) => [name, value])) };
17
+ };
18
+
19
+ describe("SecretEnvFile", () => {
20
+ test("a Kubernetes Secret decodes to the values the env file evaluates to, byte for byte", async () => {
21
+ const { variables, values } = await declare();
22
+ const manifest = Bun.YAML.parse(SecretEnvFile.render("k8s", variables, "app-env")) as {
23
+ apiVersion: string;
24
+ kind: string;
25
+ metadata: { name: string };
26
+ type: string;
27
+ data: { [name: string]: string };
28
+ };
29
+ expect({ ...manifest, data: undefined }).toEqual({
30
+ apiVersion: "v1",
31
+ kind: "Secret",
32
+ metadata: { name: "app-env" },
33
+ type: "Opaque",
34
+ data: undefined,
35
+ });
36
+ const decoded = Object.fromEntries(
37
+ Object.entries(manifest.data).map(([name, value]) => [name, Buffer.from(value, "base64").toString("utf8")]),
38
+ );
39
+ expect(decoded).toEqual(values);
40
+ expect(decoded.PUSH_NOTI__FIREBASE__PRIVATE_KEY).toBe(secretEnvSentinels.pem);
41
+ expect(JSON.parse(decoded.DISCORD__TOKENS ?? "")).toEqual(secretEnvSentinels.bots);
42
+ });
43
+
44
+ test("a Secret of no variable is still one a deployment can reference, and a name Kubernetes refuses is refused", () => {
45
+ expect(Bun.YAML.parse(SecretEnvFile.render("k8s", [], "app-env"))).toMatchObject({ kind: "Secret", data: {} });
46
+ expect(() => SecretEnvFile.render("k8s", [], "App_Env")).toThrow(
47
+ "--name App_Env is not a name a Kubernetes Secret can take",
48
+ );
49
+ });
50
+
51
+ test("a dotenv file reads back to the same strings, through this package's reader and through Bun's own loader", async () => {
52
+ const { root, variables, values } = await declare();
53
+ const file = path.join(root, "secrets.env");
54
+ await writeFile(file, SecretEnvFile.render("dotenv", variables, "unused"));
55
+ expect(parseEnvFile(file)).toEqual(values);
56
+ const loaded = Bun.spawnSync(
57
+ [
58
+ process.execPath,
59
+ `--env-file=${file}`,
60
+ "-e",
61
+ `console.log(JSON.stringify(Object.fromEntries(${JSON.stringify(Object.keys(values))}.map((name) => [name, process.env[name]]))))`,
62
+ ],
63
+ { cwd: root, env: { PATH: process.env.PATH ?? "", HOME: "/home/fixture", USER: "fixture" } },
64
+ );
65
+ expect(JSON.parse(loaded.stdout.toString())).toEqual(values);
66
+ });
67
+
68
+ test("refuses a value no dotenv line carries unchanged, naming the variable alone", () => {
69
+ const value = 'sentinel-line-one\n"quoted" \\n';
70
+ const failure = (() => {
71
+ try {
72
+ SecretEnvFile.render("dotenv", [{ name: "FIXTURE__KEY", kind: "multiline", path: "fixture.key", value }], "");
73
+ return "";
74
+ } catch (error) {
75
+ return (error as Error).message;
76
+ }
77
+ })();
78
+ expect(failure).toBe(
79
+ "FIXTURE__KEY holds a mix of line breaks, quotes and backslashes no dotenv line carries unchanged. Write it with --format k8s, which keeps every byte.",
80
+ );
81
+ });
82
+
83
+ test("writes a file its user alone can read, and replaces an existing one only when told to", async () => {
84
+ const root = await makeTempRoot();
85
+ const file = path.join(root, "out/secrets.yaml");
86
+ await SecretEnvFile.write(file, "first\n", { workspaceRoot: root });
87
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
88
+ await expect(SecretEnvFile.write(file, "second\n", { workspaceRoot: root })).rejects.toThrow(
89
+ `--out ${file} exists. Pass --force to replace it.`,
90
+ );
91
+ expect(await readFile(file, "utf8")).toBe("first\n");
92
+ await writeFile(file, "loose\n", { mode: 0o644 });
93
+ await SecretEnvFile.write(file, "second\n", { workspaceRoot: root, force: true });
94
+ expect(await readFile(file, "utf8")).toBe("second\n");
95
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
96
+ });
97
+
98
+ test("refuses a path under dist/, which an image copies, and one git would track", async () => {
99
+ const root = await makeTempRoot();
100
+ await mkdir(path.join(root, "dist/apps/demo"), { recursive: true });
101
+ const built = path.join(root, "dist/apps/demo/.env");
102
+ await expect(SecretEnvFile.write(built, "x\n", { workspaceRoot: root })).rejects.toThrow(
103
+ `--out ${built} is under dist/, and an image copies the whole of dist/apps/<app>, so the secrets would ship in it. Write the file outside dist/.`,
104
+ );
105
+ expect(await Bun.file(built).exists()).toBe(false);
106
+
107
+ expect(Bun.spawnSync(["git", "init", "-q", root]).exitCode).toBe(0);
108
+ await writeFile(path.join(root, ".gitignore"), "local/\n");
109
+ const tracked = path.join(root, "secrets.env");
110
+ await expect(SecretEnvFile.write(tracked, "x\n", { workspaceRoot: root })).rejects.toThrow(
111
+ `--out ${tracked} is inside a git repository that does not ignore it, so the secrets could be committed.`,
112
+ );
113
+ expect(await Bun.file(tracked).exists()).toBe(false);
114
+ await SecretEnvFile.write(path.join(root, "local/secrets.env"), "x\n", { workspaceRoot: root });
115
+ expect(await readFile(path.join(root, "local/secrets.env"), "utf8")).toBe("x\n");
116
+ });
117
+ });
@@ -0,0 +1,113 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
5
+ import type { SecretEnvDeclared, SecretEnvVariable } from "./secretEnvDeclaration";
6
+
7
+ export type SecretEnvFormat = "k8s" | "dotenv";
8
+
9
+ export interface SecretEnvWrite {
10
+ workspaceRoot: string;
11
+ force?: boolean;
12
+ }
13
+
14
+ export class SecretEnvFile {
15
+ static readonly formats = ["k8s", "dotenv"] as const;
16
+
17
+ static listing({ variables, unmoved }: SecretEnvDeclared): string {
18
+ if (!variables.length && !unmoved.length) return "The server env holds no secret value, so a build reads none.";
19
+ const rows = [
20
+ ["VARIABLE", "KIND", "SHELL", "ENV FILE KEY"],
21
+ ...variables.map(({ name, kind, path: at }) => [name, kind, SecretEnv.read(name) ? "set" : "unset", at]),
22
+ ];
23
+ const widths = [0, 1, 2].map((column) => Math.max(...rows.map((row) => row[column]?.length ?? 0)));
24
+ const table = variables.length
25
+ ? rows.map((row) =>
26
+ row
27
+ .map((cell, column) => cell.padEnd(widths[column] ?? 0))
28
+ .join(" ")
29
+ .trimEnd(),
30
+ )
31
+ : [];
32
+ return [...table, ...(unmoved.length ? [SecretEnvFile.unmovedNote(unmoved)] : [])].join("\n");
33
+ }
34
+
35
+ static unmovedNote(unmoved: readonly string[]): string {
36
+ if (!unmoved.length) return "";
37
+ return `\`akan build\` stops at ${unmoved.join(", ")}: ${unmoved.length === 1 ? "a secret value" : "secret values"} the env file computes or imports. Write the string at the key, or read it there yourself as \`process.env.<NAME>\`.`;
38
+ }
39
+
40
+ static unmovedStop(app: string, environment: string, envFile: string, unmoved: readonly string[]): string {
41
+ const one = unmoved.length === 1;
42
+ return `The server env of ${app} (${environment}) holds ${one ? "a secret value" : `${unmoved.length} secret values`} this build cannot leave out, so it stops here: ${unmoved.join(", ")} (${envFile} and what it imports).\nA build turns a secret written as a string at its key into a read from the server's process env, and ${one ? "this one is" : "these are"} computed or imported. Write the string at the key, or read it there yourself as \`process.env.<NAME>\` and set that variable where the server is deployed. \`akan build --inline-secrets\` builds with the env files as written until akanjs 3.5.0 removes it.`;
43
+ }
44
+
45
+ static render(format: SecretEnvFormat, variables: readonly SecretEnvVariable[], name: string): string {
46
+ return format === "k8s" ? SecretEnvFile.#k8s(variables, name) : SecretEnvFile.#dotenv(variables);
47
+ }
48
+
49
+ static #k8s(variables: readonly SecretEnvVariable[], name: string) {
50
+ if (name.length > 253 || !/^[a-z0-9](?:[-a-z0-9.]*[a-z0-9])?$/.test(name))
51
+ throw new Error(
52
+ `--name ${name} is not a name a Kubernetes Secret can take: lowercase letters, digits, "-" and ".", starting and ending with a letter or digit.`,
53
+ );
54
+ const data = variables.map(({ name: key, value }) => ` ${key}: ${Buffer.from(value, "utf8").toString("base64")}`);
55
+ return [
56
+ "apiVersion: v1",
57
+ "kind: Secret",
58
+ "metadata:",
59
+ ` name: ${name}`,
60
+ "type: Opaque",
61
+ ...(data.length ? ["data:", ...data] : ["data: {}"]),
62
+ "",
63
+ ].join("\n");
64
+ }
65
+
66
+ static #dotenv(variables: readonly SecretEnvVariable[]) {
67
+ return variables.map(({ name, value }) => `${name}=${SecretEnvFile.#dotenvValue(name, value)}\n`).join("");
68
+ }
69
+
70
+ //? As Bun's .env loader reads a value back (1.4.4): it expands `$NAME` inside every kind of quote and takes `\$` for
71
+ //? a dollar; only double quotes turn `\n` into a line break, and they keep `\"` and `\\` as two characters each.
72
+ static #dotenvValue(name: string, value: string) {
73
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(value)) return value;
74
+ const dollars = value.replaceAll("$", "\\$");
75
+ if (!/[\r\n]/.test(value) && !value.endsWith("\\"))
76
+ for (const quote of ["'", "`"]) if (!value.includes(quote)) return `${quote}${dollars}${quote}`;
77
+ if (!value.includes('"') && !value.includes("\\"))
78
+ return `"${dollars.replaceAll("\r", "\\r").replaceAll("\n", "\\n")}"`;
79
+ throw new Error(
80
+ `${name} holds a mix of line breaks, quotes and backslashes no dotenv line carries unchanged. Write it with --format k8s, which keeps every byte.`,
81
+ );
82
+ }
83
+
84
+ static async write(file: string, contents: string, { workspaceRoot, force = false }: SecretEnvWrite) {
85
+ const target = path.resolve(file);
86
+ const inWorkspace = path.relative(path.resolve(workspaceRoot), target);
87
+ if (inWorkspace.split(path.sep)[0] === "dist")
88
+ throw new Error(
89
+ `--out ${file} is under dist/, and an image copies the whole of dist/apps/<app>, so the secrets would ship in it. Write the file outside dist/.`,
90
+ );
91
+ if (SecretEnvFile.#gitWouldTrack(target))
92
+ throw new Error(
93
+ `--out ${file} is inside a git repository that does not ignore it, so the secrets could be committed. Write it to a git-ignored path or outside the repository.`,
94
+ );
95
+ if (existsSync(target)) {
96
+ if (!force) throw new Error(`--out ${file} exists. Pass --force to replace it.`);
97
+ await rm(target);
98
+ }
99
+ await mkdir(path.dirname(target), { recursive: true });
100
+ await writeFile(target, contents, { mode: 0o600, flag: "wx" });
101
+ }
102
+
103
+ static #gitWouldTrack(target: string) {
104
+ let dir = path.dirname(target);
105
+ while (!existsSync(dir) && dir !== path.dirname(dir)) dir = path.dirname(dir);
106
+ try {
107
+ //? Exit 0 is ignored, 1 is not ignored, and 128 is no repository at all.
108
+ return Bun.spawnSync(["git", "check-ignore", "-q", "--", target], { cwd: dir }).exitCode === 1;
109
+ } catch {
110
+ return false;
111
+ }
112
+ }
113
+ }
@@ -0,0 +1,54 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { SecretEnvName } from "./secretEnvName";
3
+
4
+ describe("SecretEnvName", () => {
5
+ test("names a secret after its key path, one upper snake case segment per key", () => {
6
+ const names = Object.fromEntries(
7
+ [
8
+ "security.sso.google.clientSecret",
9
+ "security.sso.kakao.clientID",
10
+ "objectStorage.secretAccessKey",
11
+ "mailer.auth.pass",
12
+ "iapVerify.google.private_key",
13
+ "rootAdminInfo.password",
14
+ "llm.apiKey",
15
+ "storage.s3Key",
16
+ "push-noti.apns.keyId",
17
+ ].map((at) => [at, SecretEnvName.of(at.split("."))]),
18
+ );
19
+ expect(names).toEqual({
20
+ "security.sso.google.clientSecret": "SECURITY__SSO__GOOGLE__CLIENT_SECRET",
21
+ "security.sso.kakao.clientID": "SECURITY__SSO__KAKAO__CLIENT_ID",
22
+ "objectStorage.secretAccessKey": "OBJECT_STORAGE__SECRET_ACCESS_KEY",
23
+ "mailer.auth.pass": "MAILER__AUTH__PASS",
24
+ "iapVerify.google.private_key": "IAP_VERIFY__GOOGLE__PRIVATE_KEY",
25
+ "rootAdminInfo.password": "ROOT_ADMIN_INFO__PASSWORD",
26
+ "llm.apiKey": "LLM__API_KEY",
27
+ "storage.s3Key": "STORAGE__S3_KEY",
28
+ "push-noti.apns.keyId": "PUSH_NOTI__APNS__KEY_ID",
29
+ });
30
+ });
31
+
32
+ test("keeps the names the framework already reads from the process env", () => {
33
+ expect(SecretEnvName.of(["security", "jwtSecret"])).toBe("JWT_SECRET");
34
+ expect(SecretEnvName.of(["database", "postgres", "url"])).toBe("POSTGRES_URL");
35
+ expect(SecretEnvName.of(["database", "postgres", "password"])).toBe("POSTGRES_PASSWORD");
36
+ expect(SecretEnvName.of(["database", "postgres", "insightUrl"])).toBe("POSTGRES_INSIGHT_URL");
37
+ });
38
+
39
+ test("refuses a name the platform sets, one akan or Bun keeps, and one no environment variable can take", () => {
40
+ for (const name of ["PATH", "HOME", "HOSTNAME", "PORT", "USER", "PWD", "TZ", "NODE_ENV"])
41
+ expect(SecretEnvName.refusal(name)).toBe("a variable the platform sets");
42
+ expect(SecretEnvName.refusal(SecretEnvName.of(["akan", "token"]))).toBe(
43
+ "a name akan and Bun keep for their own settings",
44
+ );
45
+ expect(SecretEnvName.refusal(SecretEnvName.of(["bun", "apiKey"]))).toBe(
46
+ "a name akan and Bun keep for their own settings",
47
+ );
48
+ expect(SecretEnvName.refusal(SecretEnvName.of(["2fa", "secret"]))).toBe(
49
+ "which is not a name an environment variable can take",
50
+ );
51
+ expect(SecretEnvName.refusal("JWT_SECRET")).toBeNull();
52
+ expect(SecretEnvName.refusal("SECURITY__SSO__GOOGLE__CLIENT_SECRET")).toBeNull();
53
+ });
54
+ });
@@ -0,0 +1,29 @@
1
+ export class SecretEnvName {
2
+ //? What the database adaptor and the util lib's JWT secret already read from the process env, ahead of the env file.
3
+ static readonly #existing: { readonly [path: string]: string } = {
4
+ "security.jwtSecret": "JWT_SECRET",
5
+ "database.postgres.url": "POSTGRES_URL",
6
+ "database.postgres.password": "POSTGRES_PASSWORD",
7
+ "database.postgres.insightUrl": "POSTGRES_INSIGHT_URL",
8
+ };
9
+ //? Kubernetes sets HOSTNAME to the pod's name, and a shell, Docker or Bun the rest: a secret read there takes theirs.
10
+ static readonly #platform = new Set(["PATH", "HOME", "HOSTNAME", "PORT", "USER", "PWD", "TZ", "NODE_ENV"]);
11
+
12
+ static of(keys: readonly string[]): string {
13
+ return SecretEnvName.#existing[keys.join(".")] ?? keys.map((key) => SecretEnvName.#segment(key)).join("__");
14
+ }
15
+
16
+ static #segment(key: string) {
17
+ return key
18
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
19
+ .replace(/[^A-Za-z0-9]/g, "_")
20
+ .toUpperCase();
21
+ }
22
+
23
+ static refusal(name: string): string | null {
24
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) return "which is not a name an environment variable can take";
25
+ if (SecretEnvName.#platform.has(name)) return "a variable the platform sets";
26
+ if (/^(?:AKAN|BUN)_/.test(name)) return "a name akan and Bun keep for their own settings";
27
+ return null;
28
+ }
29
+ }
@@ -0,0 +1,148 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { SecretEnvSource } from "./secretEnvSource";
3
+
4
+ const file = "/workspace/apps/demo/env/env.server.main.ts";
5
+ const read = (contents: string) => SecretEnvSource.rewrite(file, contents, "read");
6
+ const body = (rewritten: string) => rewritten.replace(/^import \{ SecretEnv as __akanSecretEnv \} from "[^"]+"; /, "");
7
+
8
+ describe("SecretEnvSource", () => {
9
+ test("leaves a read of the process env where a secret string was, and every plain value as written", () => {
10
+ const source = [
11
+ 'import type { ModulesOptions } from "../lib/option";',
12
+ "export const env: ModulesOptions = {",
13
+ ' hostname: "app.example.test",',
14
+ " security: {",
15
+ ' jwtSecret: "sentinel-jwt",',
16
+ ' verifies: [["password"], ["email"]],',
17
+ " accessTokenSeconds: 900,",
18
+ ' sso: { google: { clientID: "plain-id", "clientSecret": \'sentinel-google\' } },',
19
+ " },",
20
+ " mailer: { auth: { user: `mailer`, pass: `sentinel-pass` } },",
21
+ ' objectStorage: { endpoint: "https://minio:sentinel-url-pass@storage.example.test", region: "ap-northeast-2" },',
22
+ ' cookieDomain: "",',
23
+ "};",
24
+ "",
25
+ ].join("\n");
26
+ const rewritten = read(source);
27
+ expect(rewritten).toStartWith('import { SecretEnv as __akanSecretEnv } from "');
28
+ expect(rewritten.split("\n").length).toBe(source.split("\n").length);
29
+ expect(body(rewritten)).toBe(
30
+ [
31
+ 'import type { ModulesOptions } from "../lib/option";',
32
+ "export const env: ModulesOptions = {",
33
+ ' hostname: "app.example.test",',
34
+ " security: {",
35
+ ' jwtSecret: __akanSecretEnv.read("JWT_SECRET"),',
36
+ ' verifies: [["password"], ["email"]],',
37
+ " accessTokenSeconds: 900,",
38
+ ' sso: { google: { clientID: "plain-id", "clientSecret": __akanSecretEnv.read("SECURITY__SSO__GOOGLE__CLIENT_SECRET") } },',
39
+ " },",
40
+ ' mailer: { auth: { user: `mailer`, pass: __akanSecretEnv.read("MAILER__AUTH__PASS") } },',
41
+ ' objectStorage: { endpoint: __akanSecretEnv.read("OBJECT_STORAGE__ENDPOINT"), region: "ap-northeast-2" },',
42
+ ' cookieDomain: "",',
43
+ "};",
44
+ "",
45
+ ].join("\n"),
46
+ );
47
+ });
48
+
49
+ test("moves an array holding a secret whole, as one JSON variable, and leaves one it cannot read as a literal", () => {
50
+ const rewritten = body(
51
+ read(
52
+ [
53
+ "const more = [];",
54
+ "export const env = {",
55
+ ' discord: { tokens: ["sentinel-a", "sentinel-b"], rooms: ["general"] },',
56
+ ' accounts: [{ name: "ops", password: "sentinel-ops", retries: -1, active: true, note: null }],',
57
+ ' apiKeys: ["sentinel-c", ...more],',
58
+ "};",
59
+ ].join("\n"),
60
+ ),
61
+ );
62
+ expect(rewritten).toContain('discord: { tokens: __akanSecretEnv.json("DISCORD__TOKENS"), rooms: ["general"] },');
63
+ expect(rewritten).toContain('accounts: __akanSecretEnv.json("ACCOUNTS"),');
64
+ expect(rewritten).toContain('apiKeys: ["sentinel-c", ...more],');
65
+ });
66
+
67
+ test("replaces only the literal beside the developer's own variable, through `as` and `satisfies`", () => {
68
+ const rewritten = body(
69
+ read(
70
+ [
71
+ "export const env = {",
72
+ ' database: { postgres: { url: process.env.DATABASE_URL ?? "postgres://app:sentinel@db.example.test/app" } },',
73
+ ' llm: { apiKey: (process.env.LLM_KEY || "sentinel-llm") as string },',
74
+ "} as const satisfies object;",
75
+ ].join("\n"),
76
+ ),
77
+ );
78
+ expect(rewritten).toContain('url: process.env.DATABASE_URL ?? __akanSecretEnv.read("POSTGRES_URL")');
79
+ expect(rewritten).toContain('apiKey: (process.env.LLM_KEY || __akanSecretEnv.read("LLM__API_KEY")) as string');
80
+ });
81
+
82
+ test("a listing marks the literal with the developer's own variable beside it whole, so a shell that sets that variable lists it too", () => {
83
+ const marked = SecretEnvSource.rewrite(
84
+ file,
85
+ [
86
+ "export const env = {",
87
+ ' database: { postgres: { url: process.env.DATABASE_URL ?? "postgres://app:sentinel@db.example.test/app" } },',
88
+ ' llm: { apiKey: (process.env.LLM_KEY || process.env.OTHER_KEY || "sentinel-llm") as string },',
89
+ "};",
90
+ ].join("\n"),
91
+ "mark",
92
+ );
93
+ expect(marked).toContain(
94
+ 'url: ({ __akanSecretEnv: ["POSTGRES_URL", "string", "postgres://app:sentinel@db.example.test/app"] }) }',
95
+ );
96
+ expect(marked).toContain('apiKey: ({ __akanSecretEnv: ["LLM__API_KEY", "string", "sentinel-llm"] }) }');
97
+ });
98
+
99
+ test("leaves a file alone that holds no secret literal, or whose env is not an object it can read", () => {
100
+ const plain = 'export const env = { hostname: "app.example.test", port: 8080, tokenTtl: 3600 };\n';
101
+ expect(read(plain)).toBe(plain);
102
+ const computed = [
103
+ 'import { secret } from "./elsewhere";',
104
+ "const token = [secret].join();",
105
+ ["export const env = { llm: { apiKey: token, model: `m-$", "{secret}` }, ...secret };"].join(""),
106
+ 'export const other = { password: "sentinel-other" };',
107
+ "",
108
+ ].join("\n");
109
+ expect(read(computed)).toBe(computed);
110
+ const switched = "export const env = envConfigs[currentEnv as keyof typeof envConfigs];\n";
111
+ expect(read(switched)).toBe(switched);
112
+ });
113
+
114
+ test("an --inline-secrets build keeps the literal behind the read, and a listing marks it with its variable", () => {
115
+ const source = 'export const env = { llm: { apiKey: "sentinel-llm" }, discord: { tokens: ["sentinel-a"] } };\n';
116
+ expect(body(SecretEnvSource.rewrite(file, source, "inline"))).toBe(
117
+ 'export const env = { llm: { apiKey: __akanSecretEnv.read("LLM__API_KEY", "sentinel-llm") }, discord: { tokens: __akanSecretEnv.json("DISCORD__TOKENS", ["sentinel-a"]) } };\n',
118
+ );
119
+ expect(SecretEnvSource.rewrite(file, source, "mark")).toBe(
120
+ 'export const env = { llm: { apiKey: ({ __akanSecretEnv: ["LLM__API_KEY", "string", "sentinel-llm"] }) }, discord: { tokens: ({ __akanSecretEnv: ["DISCORD__TOKENS", "json", ["sentinel-a"]] }) } };\n',
121
+ );
122
+ });
123
+
124
+ test("marks a string holding a line break as multi-line", () => {
125
+ const source = 'export const env = { push: { privateKey: "-----BEGIN-----\\nsentinel\\n-----END-----\\n" } };\n';
126
+ expect(SecretEnvSource.rewrite(file, source, "mark")).toContain('["PUSH__PRIVATE_KEY", "multiline", ');
127
+ });
128
+
129
+ test("refuses two keys that would share one variable, and a key whose variable the platform owns, without a value", () => {
130
+ const failure = (contents: string) => {
131
+ try {
132
+ read(contents);
133
+ return "";
134
+ } catch (error) {
135
+ return (error as Error).message;
136
+ }
137
+ };
138
+ expect(failure('export const env = { a: { apiKey: "sentinel-one", api_key: "sentinel-two" } };')).toBe(
139
+ `${file} \`a.apiKey\` and \`a.api_key\` are secrets a build would both read from the environment variable A__API_KEY. Rename one of the keys.`,
140
+ );
141
+ expect(failure('export const env = { pwd: "sentinel-three" };')).toBe(
142
+ `${file} \`pwd\` is a secret a build would read from the environment variable PWD, a variable the platform sets. Rename the key, or write \`process.env.<NAME>\` there yourself, which a build leaves as it is.`,
143
+ );
144
+ expect(failure('export const env = { akan: { token: "sentinel-four" } };')).toContain(
145
+ "AKAN__TOKEN, a name akan and Bun keep for their own settings.",
146
+ );
147
+ });
148
+ });
@@ -0,0 +1,166 @@
1
+ import path from "node:path";
2
+ import { Logger } from "akanjs/common";
3
+ import type { SecretEnvKind } from "akanjs/server/lifecycle/secretEnv";
4
+ import ts from "typescript";
5
+ import { SecretEnvName } from "./secretEnvName";
6
+ import { ServerEnvProfile } from "./serverEnvProfile";
7
+
8
+ //* `inline` keeps the literal as the read's fallback; `mark` wraps it with its variable's name, for a listing.
9
+ export type SecretEnvMode = "read" | "inline" | "mark";
10
+
11
+ interface Edit {
12
+ start: number;
13
+ end: number;
14
+ text: string;
15
+ }
16
+
17
+ //* Reads source text alone, so a secret that is computed, imported or spread stays as written.
18
+ export class SecretEnvSource {
19
+ static readonly markKey = "__akanSecretEnv";
20
+ static readonly #runtime = "akanjs/server/lifecycle/secretEnv";
21
+ static readonly #binding = "__akanSecretEnv";
22
+ static readonly #dynamic = Symbol("dynamic");
23
+
24
+ readonly #file: string;
25
+ readonly #source: ts.SourceFile;
26
+ readonly #mode: SecretEnvMode;
27
+ readonly #edits: Edit[] = [];
28
+ readonly #pathOfName = new Map<string, string>();
29
+
30
+ private constructor(file: string, contents: string, mode: SecretEnvMode) {
31
+ this.#file = file;
32
+ this.#source = ts.createSourceFile(file, contents, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
33
+ this.#mode = mode;
34
+ }
35
+
36
+ static rewrite(file: string, contents: string, mode: SecretEnvMode): string {
37
+ return new SecretEnvSource(file, contents, mode).#rewritten(contents);
38
+ }
39
+
40
+ #rewritten(contents: string) {
41
+ for (const statement of this.#source.statements) {
42
+ if (!ts.isVariableStatement(statement)) continue;
43
+ if (!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue;
44
+ for (const declaration of statement.declarationList.declarations)
45
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === "env" && declaration.initializer)
46
+ this.#visit(declaration.initializer, [], false);
47
+ }
48
+ if (!this.#edits.length) return contents;
49
+ const rewritten = this.#edits
50
+ .toSorted((a, b) => b.start - a.start)
51
+ .reduce((text, edit) => `${text.slice(0, edit.start)}${edit.text}${text.slice(edit.end)}`, contents);
52
+ if (this.#mode === "mark") return rewritten;
53
+ //? On the first line, so every line of the file keeps its number in an error the bundler reports.
54
+ return `import { SecretEnv as ${SecretEnvSource.#binding} } from ${JSON.stringify(this.#runtimePath())}; ${rewritten}`;
55
+ }
56
+
57
+ //? As the env file itself would import it, then as this package does: a lib's env file may have no akanjs beside it.
58
+ #runtimePath() {
59
+ for (const from of [path.dirname(this.#file), import.meta.dir]) {
60
+ try {
61
+ return Bun.resolveSync(SecretEnvSource.#runtime, from);
62
+ } catch {}
63
+ }
64
+ throw new Error(
65
+ `${this.#file} holds secret values, which the build reads from the process env through ${SecretEnvSource.#runtime}, and the installed akanjs has no such module. Install the akanjs of this akan version.`,
66
+ );
67
+ }
68
+
69
+ static #unwrap(node: ts.Expression): ts.Expression {
70
+ return ts.isParenthesizedExpression(node) ||
71
+ ts.isAsExpression(node) ||
72
+ ts.isSatisfiesExpression(node) ||
73
+ ts.isNonNullExpression(node) ||
74
+ ts.isTypeAssertionExpression(node)
75
+ ? SecretEnvSource.#unwrap(node.expression)
76
+ : node;
77
+ }
78
+
79
+ static #keyOf(name: ts.PropertyName): string | null {
80
+ return ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : null;
81
+ }
82
+
83
+ #visit(expression: ts.Expression, keys: string[], underSecret: boolean, beside?: ts.Expression): void {
84
+ const node = SecretEnvSource.#unwrap(expression);
85
+ if (ts.isObjectLiteralExpression(node)) {
86
+ for (const property of node.properties) {
87
+ const key = ts.isPropertyAssignment(property) ? SecretEnvSource.#keyOf(property.name) : null;
88
+ if (key !== null && ts.isPropertyAssignment(property))
89
+ this.#visit(property.initializer, [...keys, key], underSecret || Logger.isSecretKey(key));
90
+ }
91
+ return;
92
+ }
93
+ if (!keys.length) return;
94
+ //? `process.env.X ?? "literal"`: the developer's own variable keeps its place ahead of the one read here.
95
+ if (ts.isBinaryExpression(node)) {
96
+ const { kind } = node.operatorToken;
97
+ if (kind === ts.SyntaxKind.QuestionQuestionToken || kind === ts.SyntaxKind.BarBarToken)
98
+ this.#visit(node.right, keys, underSecret, beside ?? expression);
99
+ return;
100
+ }
101
+ if (ts.isStringLiteralLike(node)) {
102
+ if (ServerEnvProfile.isSecret(node.text, underSecret))
103
+ this.#replace(node, keys, node.text.includes("\n") ? "multiline" : "string", beside);
104
+ return;
105
+ }
106
+ if (!ts.isArrayLiteralExpression(node)) return;
107
+ const value = SecretEnvSource.#literal(node);
108
+ if (value !== SecretEnvSource.#dynamic && ServerEnvProfile.secretPaths(value, underSecret).length)
109
+ this.#replace(node, keys, "json", beside);
110
+ }
111
+
112
+ static #literal(expression: ts.Expression): unknown {
113
+ const node = SecretEnvSource.#unwrap(expression);
114
+ if (ts.isStringLiteralLike(node)) return node.text;
115
+ if (ts.isNumericLiteral(node)) return Number(node.text);
116
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
117
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
118
+ if (node.kind === ts.SyntaxKind.NullKeyword) return null;
119
+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken) {
120
+ const operand = SecretEnvSource.#literal(node.operand);
121
+ return typeof operand === "number" ? -operand : SecretEnvSource.#dynamic;
122
+ }
123
+ if (ts.isArrayLiteralExpression(node)) {
124
+ const items = node.elements.map((element) => SecretEnvSource.#literal(element));
125
+ return items.includes(SecretEnvSource.#dynamic) ? SecretEnvSource.#dynamic : items;
126
+ }
127
+ if (!ts.isObjectLiteralExpression(node)) return SecretEnvSource.#dynamic;
128
+ const entries: [string, unknown][] = [];
129
+ for (const property of node.properties) {
130
+ const key = ts.isPropertyAssignment(property) ? SecretEnvSource.#keyOf(property.name) : null;
131
+ if (key === null || !ts.isPropertyAssignment(property)) return SecretEnvSource.#dynamic;
132
+ const value = SecretEnvSource.#literal(property.initializer);
133
+ if (value === SecretEnvSource.#dynamic) return SecretEnvSource.#dynamic;
134
+ entries.push([key, value]);
135
+ }
136
+ return Object.fromEntries(entries);
137
+ }
138
+
139
+ //? A listing marks the whole `process.env.X ?? "literal"`, so it names the variable whether or not a shell sets X.
140
+ #replace(node: ts.Expression, keys: string[], kind: SecretEnvKind, beside?: ts.Expression) {
141
+ const at = keys.join(".");
142
+ const name = SecretEnvName.of(keys);
143
+ const refusal = SecretEnvName.refusal(name);
144
+ if (refusal)
145
+ throw new Error(
146
+ `${this.#file} \`${at}\` is a secret a build would read from the environment variable ${name}, ${refusal}. Rename the key, or write \`process.env.<NAME>\` there yourself, which a build leaves as it is.`,
147
+ );
148
+ const taken = this.#pathOfName.get(name);
149
+ if (taken !== undefined && taken !== at)
150
+ throw new Error(
151
+ `${this.#file} \`${taken}\` and \`${at}\` are secrets a build would both read from the environment variable ${name}. Rename one of the keys.`,
152
+ );
153
+ this.#pathOfName.set(name, at);
154
+ const start = node.getStart(this.#source);
155
+ const written = this.#source.text.slice(start, node.end);
156
+ const read = `${SecretEnvSource.#binding}.${kind === "json" ? "json" : "read"}`;
157
+ const text =
158
+ this.#mode === "mark"
159
+ ? `({ ${SecretEnvSource.markKey}: [${JSON.stringify(name)}, ${JSON.stringify(kind)}, ${written}] })`
160
+ : this.#mode === "inline"
161
+ ? `${read}(${JSON.stringify(name)}, ${written})`
162
+ : `${read}(${JSON.stringify(name)})`;
163
+ const marked = this.#mode === "mark" && beside ? beside : node;
164
+ this.#edits.push({ start: marked.getStart(this.#source), end: marked.end, text });
165
+ }
166
+ }
@@ -0,0 +1,11 @@
1
+ export type ServerEnvEvaluationFailure = "threw" | "exited" | "timedOut";
2
+
3
+ export class ServerEnvEvaluationError extends Error {
4
+ constructor(
5
+ readonly reason: ServerEnvEvaluationFailure,
6
+ message: string,
7
+ ) {
8
+ super(message);
9
+ this.name = "ServerEnvEvaluationError";
10
+ }
11
+ }
@@ -250,7 +250,8 @@ describe("createServerEnvPlugin", () => {
250
250
  });
251
251
  expect(result.success).toBe(false);
252
252
  const printed = result.logs.map((log) => `${log.message}\n${log.position?.lineText ?? ""}`).join("\n");
253
- expect(printed).toContain("ReferenceError: undefinedVar is not defined");
253
+ expect(printed).toMatch(/: ReferenceError at .*libs\/util\/env\/env\.server\.testing\.ts:3\n/);
254
+ expect(printed).not.toContain("undefinedVar");
254
255
  expect(printed).not.toContain("lib-jwt-dummy-0123");
255
256
  });
256
257