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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/DEV_RUNTIME_KNOBS.md +1 -1
  3. package/akanConfig/akanConfig.ts +4 -4
  4. package/app/applicationBuildRunner.test.ts +272 -0
  5. package/app/applicationBuildRunner.ts +87 -2
  6. package/artifact/implicitRootLayoutRender.test.tsx +4 -1
  7. package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
  8. package/executors/workspaceExecutor.ts +7 -4
  9. package/frontendBuild/clientEntryDiscovery.test.ts +35 -0
  10. package/frontendBuild/clientEntryDiscovery.ts +14 -1
  11. package/lint/biomeCheck.test.ts +145 -0
  12. package/lint/biomeCheck.ts +131 -0
  13. package/lint/withheldEnvFile.ts +17 -0
  14. package/mobile/serverBundleSecrets.ts +43 -0
  15. package/package.json +3 -3
  16. package/test/secretEnvFixture.ts +134 -0
  17. package/transforms/secretEnvDeclaration.test.ts +208 -0
  18. package/transforms/secretEnvDeclaration.ts +213 -0
  19. package/transforms/secretEnvFile.test.ts +117 -0
  20. package/transforms/secretEnvFile.ts +113 -0
  21. package/transforms/secretEnvName.test.ts +54 -0
  22. package/transforms/secretEnvName.ts +29 -0
  23. package/transforms/secretEnvSource.test.ts +148 -0
  24. package/transforms/secretEnvSource.ts +166 -0
  25. package/transforms/serverEnvEvaluationError.ts +11 -0
  26. package/transforms/serverEnvPlugin.test.ts +2 -1
  27. package/transforms/serverEnvPlugin.ts +13 -0
  28. package/transforms/serverEnvProfile.test.ts +115 -2
  29. package/transforms/serverEnvProfile.ts +117 -40
  30. package/transforms/serverEnvSecrets.test.ts +292 -0
  31. package/typecheck/projectTypecheck.test.ts +29 -0
  32. package/typecheck/typeChecker.test.ts +49 -0
  33. package/typecheck/typeChecker.ts +9 -7
  34. package/typecheck/withheldDiagnostics.ts +41 -0
@@ -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
+ }
@@ -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
+ }