@akanjs/devkit 3.3.0-rc.70 → 3.3.0-rc.72
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.
- package/akanConfig/akanConfig.test.ts +38 -0
- package/akanConfig/dockerImage.ts +25 -4
- package/app/applicationBuildRunner.test.ts +117 -39
- package/app/applicationBuildRunner.ts +50 -40
- package/codeAgent/skills/akan-runtime/SKILL.md +2 -2
- package/integration/devResourceProbe.ts +14 -0
- package/integration/renderAdmissionSoak.ts +6 -0
- package/integration/ssrMemoryProbe.ts +5 -0
- package/mobile/nativeApp.test.ts +6 -0
- package/mobile/nativeApp.ts +8 -3
- package/mobile/serverBundleSecrets.ts +1 -1
- package/package.json +3 -3
- package/transforms/secretEnvDeclaration.test.ts +4 -1
- package/transforms/secretEnvDeclaration.ts +9 -3
- package/transforms/secretEnvFile.ts +1 -1
- package/transforms/secretEnvSource.test.ts +11 -7
- package/transforms/secretEnvSource.ts +44 -13
- package/transforms/serverEnvPlugin.test.ts +153 -0
- package/transforms/serverEnvPlugin.ts +112 -21
- package/transforms/serverEnvProfile.ts +7 -3
- package/transforms/serverEnvSecrets.test.ts +20 -44
package/mobile/nativeApp.test.ts
CHANGED
|
@@ -282,6 +282,12 @@ describe("NativeApp", () => {
|
|
|
282
282
|
);
|
|
283
283
|
});
|
|
284
284
|
|
|
285
|
+
test("an indexPath's query opens the dev build ahead of its own parameters, and its hash after them", () => {
|
|
286
|
+
expect(new NativeApp(fakeApp(), target({ indexPath: "/explore?tab=new#top" })).startPath("en", "ios")).toBe(
|
|
287
|
+
"/en/explore?tab=new&csr=true&akanMobileTarget=default&akanMobileLang=device&akanMobileIndexPath=%2Fexplore%3Ftab%3Dnew%23top#top",
|
|
288
|
+
);
|
|
289
|
+
});
|
|
290
|
+
|
|
285
291
|
test("a platform section's indexPath wins on that platform, and the others keep the target's", () => {
|
|
286
292
|
const app = new NativeApp(fakeApp(), target({ indexPath: "/mobile", desktop: { indexPath: "/", server: true } }));
|
|
287
293
|
|
package/mobile/nativeApp.ts
CHANGED
|
@@ -568,13 +568,18 @@ export class NativeApp {
|
|
|
568
568
|
startPath(lang: string, platform: NativePlatform) {
|
|
569
569
|
const basePath = this.target.config.basePath?.replace(/^\/+|\/+$/g, "");
|
|
570
570
|
const indexPath = this.indexPath(platform);
|
|
571
|
-
const
|
|
571
|
+
const [indexHref = "", hash = ""] = (indexPath ?? "").split("#");
|
|
572
|
+
const [indexPathname = "", query = ""] = indexHref.split("?");
|
|
573
|
+
const params = new URLSearchParams(query);
|
|
574
|
+
params.set("csr", "true");
|
|
575
|
+
params.set("akanMobileTarget", this.target.name);
|
|
576
|
+
params.set("akanMobileLang", "device");
|
|
572
577
|
if (basePath) params.set("akanMobileBasePath", basePath);
|
|
573
578
|
if (indexPath) params.set("akanMobileIndexPath", indexPath);
|
|
574
|
-
const home = [lang, basePath,
|
|
579
|
+
const home = [lang, basePath, indexPathname]
|
|
575
580
|
.flatMap((part) => (part ?? "").split("/"))
|
|
576
581
|
.filter((segment) => segment.length > 0);
|
|
577
|
-
return `/${home.join("/")}?${params}`;
|
|
582
|
+
return `/${home.join("/")}?${params}${hash ? `#${hash}` : ""}`;
|
|
578
583
|
}
|
|
579
584
|
|
|
580
585
|
//* `installer` is the file a person downloads: a setup program on Windows, a disk image on macOS, an AppImage on Linux.
|
|
@@ -102,7 +102,7 @@ export class ServerBundleSecrets {
|
|
|
102
102
|
}
|
|
103
103
|
if (stops.length)
|
|
104
104
|
throw new Error(
|
|
105
|
-
`The build holds secret values the server reads from its process env, so it stops here:\n ${[...new Set(stops)].join("\n ")}\nThe build left each out at its secret-named key of the env file, and the same string is in what it wrote for another reason: another key of the env holds it too, or the app's code, or a file the build copies. Take it out there, or read it there from the same variable
|
|
105
|
+
`The build holds secret values the server reads from its process env, so it stops here:\n ${[...new Set(stops)].join("\n ")}\nThe build left each out at its secret-named key of the env file, and the same string is in what it wrote for another reason: another key of the env holds it too, or the app's code, or a file the build copies. Take it out there, or read it there from the same variable.`,
|
|
106
106
|
);
|
|
107
107
|
if (!notes.length) return null;
|
|
108
108
|
const lines = [...new Set(notes)];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@akanjs/devkit",
|
|
3
|
-
"version": "3.3.0-rc.
|
|
3
|
+
"version": "3.3.0-rc.72",
|
|
4
4
|
"sourceType": "module",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -52,10 +52,10 @@
|
|
|
52
52
|
"./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
|
-
"@akanjs/language": "3.3.0-rc.
|
|
55
|
+
"@akanjs/language": "3.3.0-rc.72",
|
|
56
56
|
"@inquirer/prompts": "^8.7.3",
|
|
57
57
|
"@tailwindcss/node": "^4.3.3",
|
|
58
|
-
"akanjs": "3.3.0-rc.
|
|
58
|
+
"akanjs": "3.3.0-rc.72",
|
|
59
59
|
"chalk": "^6.0.1",
|
|
60
60
|
"commander": "^15.0.0",
|
|
61
61
|
"dayjs": "^1.11.23",
|
|
@@ -47,7 +47,7 @@ const shellOwn = {
|
|
|
47
47
|
};
|
|
48
48
|
|
|
49
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 () => {
|
|
50
|
+
test("lists each secret of the environment's server env with its variable, kind and value, a lib's default included, and the developer's own variable read ahead of one", async () => {
|
|
51
51
|
const { envDir } = await writeSecretEnvFixture(await makeTempRoot());
|
|
52
52
|
const { variables, unmoved } = await SecretEnvDeclaration.of(envDir, "main");
|
|
53
53
|
expect(unmoved).toEqual([]);
|
|
@@ -78,6 +78,9 @@ describe("SecretEnvDeclaration", () => {
|
|
|
78
78
|
POSTGRES_URL: { kind: "string", at: "database.postgres.url", value: secretEnvSentinels.postgres },
|
|
79
79
|
},
|
|
80
80
|
);
|
|
81
|
+
expect(variables.flatMap(({ name, ahead }) => (ahead ? [[name, ahead]] : []))).toEqual([
|
|
82
|
+
["POSTGRES_URL", ["DATABASE_URL"]],
|
|
83
|
+
]);
|
|
81
84
|
});
|
|
82
85
|
|
|
83
86
|
test("the listing names every variable and its key, says which the shell sets, and holds no value", async () => {
|
|
@@ -77,7 +77,13 @@ export class SecretEnvDeclaration {
|
|
|
77
77
|
}
|
|
78
78
|
const computed = await SecretEnvDeclaration.#notRead(found.computed, file, envDir, environment, loaded);
|
|
79
79
|
return {
|
|
80
|
-
variables: [...variables.values()].map(({ name, kind, path: at, value }) => ({
|
|
80
|
+
variables: [...variables.values()].map(({ name, kind, path: at, value, ahead }) => ({
|
|
81
|
+
name,
|
|
82
|
+
kind,
|
|
83
|
+
path: at,
|
|
84
|
+
value,
|
|
85
|
+
...(ahead ? { ahead } : {}),
|
|
86
|
+
})),
|
|
81
87
|
unmoved: [...new Set(computed.map(({ at }) => at))],
|
|
82
88
|
moved: [...variables.values()].flatMap(({ name, path: at, literal, underSecret }) =>
|
|
83
89
|
ServerEnvProfile.movedTexts(literal, underSecret).map((value) => ({
|
|
@@ -194,11 +200,11 @@ export class SecretEnvDeclaration {
|
|
|
194
200
|
}
|
|
195
201
|
const mark = (value as { [key: string]: unknown })[SecretEnvSource.markKey];
|
|
196
202
|
if (Array.isArray(mark)) {
|
|
197
|
-
const [name, kind, literal] = mark as [string, SecretEnvKind, unknown];
|
|
203
|
+
const [name, kind, literal, ahead] = mark as [string, SecretEnvKind, unknown, string[]?];
|
|
198
204
|
//? A string a build moved is a secret wherever it sits: a credential URL is one under a plain key too.
|
|
199
205
|
const held = underSecret || typeof literal === "string";
|
|
200
206
|
const value = typeof literal === "string" ? literal : JSON.stringify(literal);
|
|
201
|
-
found.variables.push({ name, kind, path: at, value, literal, underSecret: held });
|
|
207
|
+
found.variables.push({ name, kind, path: at, value, ...(ahead ? { ahead } : {}), literal, underSecret: held });
|
|
202
208
|
return;
|
|
203
209
|
}
|
|
204
210
|
for (const [key, child] of Object.entries(value))
|
|
@@ -39,7 +39,7 @@ export class SecretEnvFile {
|
|
|
39
39
|
|
|
40
40
|
static unmovedStop(app: string, environment: string, envFile: string, unmoved: readonly string[]): string {
|
|
41
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
|
|
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.`;
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
static render(format: SecretEnvFormat, variables: readonly SecretEnvVariable[], name: string): string {
|
|
@@ -79,21 +79,25 @@ describe("SecretEnvSource", () => {
|
|
|
79
79
|
expect(rewritten).toContain('apiKey: (process.env.LLM_KEY || __akanSecretEnv.read("LLM__API_KEY")) as string');
|
|
80
80
|
});
|
|
81
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", () => {
|
|
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, and names the plain reads ahead of it", () => {
|
|
83
83
|
const marked = SecretEnvSource.rewrite(
|
|
84
84
|
file,
|
|
85
85
|
[
|
|
86
86
|
"export const env = {",
|
|
87
87
|
' database: { postgres: { url: process.env.DATABASE_URL ?? "postgres://app:sentinel@db.example.test/app" } },',
|
|
88
|
-
' llm: { apiKey: (process.env.LLM_KEY || process.env
|
|
88
|
+
' llm: { apiKey: (process.env.LLM_KEY || process.env["OTHER_KEY"] || "sentinel-llm") as string },',
|
|
89
|
+
' mailer: { pass: process.env.MAIL_PASS?.trim() || decode(process.env.RAW) || "sentinel-pass" },',
|
|
89
90
|
"};",
|
|
90
91
|
].join("\n"),
|
|
91
92
|
"mark",
|
|
92
93
|
);
|
|
93
94
|
expect(marked).toContain(
|
|
94
|
-
'url: ({ __akanSecretEnv: ["POSTGRES_URL", "string", "postgres://app:sentinel@db.example.test/app"] }) }',
|
|
95
|
+
'url: ({ __akanSecretEnv: ["POSTGRES_URL", "string", "postgres://app:sentinel@db.example.test/app", ["DATABASE_URL"]] }) }',
|
|
95
96
|
);
|
|
96
|
-
expect(marked).toContain(
|
|
97
|
+
expect(marked).toContain(
|
|
98
|
+
'apiKey: ({ __akanSecretEnv: ["LLM__API_KEY", "string", "sentinel-llm", ["LLM_KEY","OTHER_KEY"]] }) }',
|
|
99
|
+
);
|
|
100
|
+
expect(marked).toContain('pass: ({ __akanSecretEnv: ["MAILER__PASS", "string", "sentinel-pass"] }) }');
|
|
97
101
|
});
|
|
98
102
|
|
|
99
103
|
test("leaves a file alone that holds no secret literal, or whose env is not an object it can read", () => {
|
|
@@ -111,10 +115,10 @@ describe("SecretEnvSource", () => {
|
|
|
111
115
|
expect(read(switched)).toBe(switched);
|
|
112
116
|
});
|
|
113
117
|
|
|
114
|
-
test("
|
|
118
|
+
test("a build keeps no literal behind the read, and a listing marks it with its variable", () => {
|
|
115
119
|
const source = 'export const env = { llm: { apiKey: "sentinel-llm" }, discord: { tokens: ["sentinel-a"] } };\n';
|
|
116
|
-
expect(body(
|
|
117
|
-
'export const env = { llm: { apiKey: __akanSecretEnv.read("LLM__API_KEY"
|
|
120
|
+
expect(body(read(source))).toBe(
|
|
121
|
+
'export const env = { llm: { apiKey: __akanSecretEnv.read("LLM__API_KEY") }, discord: { tokens: __akanSecretEnv.json("DISCORD__TOKENS") } };\n',
|
|
118
122
|
);
|
|
119
123
|
expect(SecretEnvSource.rewrite(file, source, "mark")).toBe(
|
|
120
124
|
'export const env = { llm: { apiKey: ({ __akanSecretEnv: ["LLM__API_KEY", "string", "sentinel-llm"] }) }, discord: { tokens: ({ __akanSecretEnv: ["DISCORD__TOKENS", "json", ["sentinel-a"]] }) } };\n',
|
|
@@ -5,8 +5,8 @@ import ts from "typescript";
|
|
|
5
5
|
import { SecretEnvName } from "./secretEnvName";
|
|
6
6
|
import { ServerEnvProfile } from "./serverEnvProfile";
|
|
7
7
|
|
|
8
|
-
//* `
|
|
9
|
-
export type SecretEnvMode = "read" | "
|
|
8
|
+
//* `mark` wraps the literal with its variable's name, for a listing.
|
|
9
|
+
export type SecretEnvMode = "read" | "mark";
|
|
10
10
|
|
|
11
11
|
interface Edit {
|
|
12
12
|
start: number;
|
|
@@ -80,7 +80,13 @@ export class SecretEnvSource {
|
|
|
80
80
|
return ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : null;
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
-
#visit(
|
|
83
|
+
#visit(
|
|
84
|
+
expression: ts.Expression,
|
|
85
|
+
keys: string[],
|
|
86
|
+
underSecret: boolean,
|
|
87
|
+
beside?: ts.Expression,
|
|
88
|
+
ahead: string[] = [],
|
|
89
|
+
): void {
|
|
84
90
|
const node = SecretEnvSource.#unwrap(expression);
|
|
85
91
|
if (ts.isObjectLiteralExpression(node)) {
|
|
86
92
|
for (const property of node.properties) {
|
|
@@ -93,20 +99,46 @@ export class SecretEnvSource {
|
|
|
93
99
|
if (!keys.length) return;
|
|
94
100
|
//? `process.env.X ?? "literal"`: the developer's own variable keeps its place ahead of the one read here.
|
|
95
101
|
if (ts.isBinaryExpression(node)) {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
102
|
+
if (SecretEnvSource.#fallsBack(node))
|
|
103
|
+
this.#visit(node.right, keys, underSecret, beside ?? expression, [
|
|
104
|
+
...ahead,
|
|
105
|
+
...SecretEnvSource.#envReads(node.left),
|
|
106
|
+
]);
|
|
99
107
|
return;
|
|
100
108
|
}
|
|
101
109
|
if (ts.isStringLiteralLike(node)) {
|
|
102
110
|
if (ServerEnvProfile.isSecret(node.text, underSecret))
|
|
103
|
-
this.#replace(node, keys, node.text.includes("\n") ? "multiline" : "string", beside);
|
|
111
|
+
this.#replace(node, keys, node.text.includes("\n") ? "multiline" : "string", beside, ahead);
|
|
104
112
|
return;
|
|
105
113
|
}
|
|
106
114
|
if (!ts.isArrayLiteralExpression(node)) return;
|
|
107
115
|
const value = SecretEnvSource.#literal(node);
|
|
108
116
|
if (value !== SecretEnvSource.#dynamic && ServerEnvProfile.secretPaths(value, underSecret).length)
|
|
109
|
-
this.#replace(node, keys, "json", beside);
|
|
117
|
+
this.#replace(node, keys, "json", beside, ahead);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
//? Plain reads alone: a variable that is set makes `process.env.X ?? …` take it, and `f(process.env.X) ?? …` may not.
|
|
121
|
+
static #envReads(expression: ts.Expression): string[] {
|
|
122
|
+
const node = SecretEnvSource.#unwrap(expression);
|
|
123
|
+
if (ts.isBinaryExpression(node))
|
|
124
|
+
return SecretEnvSource.#fallsBack(node)
|
|
125
|
+
? [...SecretEnvSource.#envReads(node.left), ...SecretEnvSource.#envReads(node.right)]
|
|
126
|
+
: [];
|
|
127
|
+
if (!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node)) return [];
|
|
128
|
+
const env = SecretEnvSource.#unwrap(node.expression);
|
|
129
|
+
const processEnv =
|
|
130
|
+
ts.isPropertyAccessExpression(env) &&
|
|
131
|
+
env.name.text === "env" &&
|
|
132
|
+
ts.isIdentifier(env.expression) &&
|
|
133
|
+
env.expression.text === "process";
|
|
134
|
+
if (!processEnv) return [];
|
|
135
|
+
if (ts.isPropertyAccessExpression(node)) return [node.name.text];
|
|
136
|
+
return ts.isStringLiteralLike(node.argumentExpression) ? [node.argumentExpression.text] : [];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
static #fallsBack(node: ts.BinaryExpression) {
|
|
140
|
+
const { kind } = node.operatorToken;
|
|
141
|
+
return kind === ts.SyntaxKind.QuestionQuestionToken || kind === ts.SyntaxKind.BarBarToken;
|
|
110
142
|
}
|
|
111
143
|
|
|
112
144
|
static #literal(expression: ts.Expression): unknown {
|
|
@@ -137,7 +169,7 @@ export class SecretEnvSource {
|
|
|
137
169
|
}
|
|
138
170
|
|
|
139
171
|
//? 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) {
|
|
172
|
+
#replace(node: ts.Expression, keys: string[], kind: SecretEnvKind, beside?: ts.Expression, ahead: string[] = []) {
|
|
141
173
|
const at = keys.join(".");
|
|
142
174
|
const name = SecretEnvName.of(keys);
|
|
143
175
|
const refusal = SecretEnvName.refusal(name);
|
|
@@ -154,12 +186,11 @@ export class SecretEnvSource {
|
|
|
154
186
|
const start = node.getStart(this.#source);
|
|
155
187
|
const written = this.#source.text.slice(start, node.end);
|
|
156
188
|
const read = `${SecretEnvSource.#binding}.${kind === "json" ? "json" : "read"}`;
|
|
189
|
+
const own = ahead.length ? `, ${JSON.stringify([...new Set(ahead)])}` : "";
|
|
157
190
|
const text =
|
|
158
191
|
this.#mode === "mark"
|
|
159
|
-
? `({ ${SecretEnvSource.markKey}: [${JSON.stringify(name)}, ${JSON.stringify(kind)}, ${written}] })`
|
|
160
|
-
:
|
|
161
|
-
? `${read}(${JSON.stringify(name)}, ${written})`
|
|
162
|
-
: `${read}(${JSON.stringify(name)})`;
|
|
192
|
+
? `({ ${SecretEnvSource.markKey}: [${JSON.stringify(name)}, ${JSON.stringify(kind)}, ${written}${own}] })`
|
|
193
|
+
: `${read}(${JSON.stringify(name)})`;
|
|
163
194
|
const marked = this.#mode === "mark" && beside ? beside : node;
|
|
164
195
|
this.#edits.push({ start: marked.getStart(this.#source), end: marked.end, text });
|
|
165
196
|
}
|
|
@@ -141,6 +141,7 @@ describe("createServerEnvPlugin", () => {
|
|
|
141
141
|
expect(reports).toEqual([
|
|
142
142
|
{
|
|
143
143
|
file: "env.server.testing.ts",
|
|
144
|
+
profile: "edge",
|
|
144
145
|
profileFile: false,
|
|
145
146
|
stripped: ["security.jwtSecret", "mailer.auth.pass", "cloudflare.authKey"],
|
|
146
147
|
},
|
|
@@ -255,6 +256,158 @@ describe("createServerEnvPlugin", () => {
|
|
|
255
256
|
expect(printed).not.toContain("lib-jwt-dummy-0123");
|
|
256
257
|
});
|
|
257
258
|
|
|
259
|
+
describe("profiles carried beside the environment's own file", () => {
|
|
260
|
+
const carry = async (secrets?: "read", profile?: string) => {
|
|
261
|
+
const root = await makeTempRoot();
|
|
262
|
+
const libEnv = path.join(root, "libs/shared/env/env.server.testing.ts");
|
|
263
|
+
await write(
|
|
264
|
+
libEnv,
|
|
265
|
+
'export const env = { hostname: "lib-host", security: { jwtSecret: "lib-jwt", accessTokenSeconds: 900 } };\n',
|
|
266
|
+
);
|
|
267
|
+
const kioskLibEnv = path.join(root, "libs/shared/env/env.server.testing.kiosk.ts");
|
|
268
|
+
await write(kioskLibEnv, 'export const env = { hostname: "lib-kiosk-host" };\n');
|
|
269
|
+
const { envDir, entry } = await writeApp(root);
|
|
270
|
+
await write(
|
|
271
|
+
path.join(envDir, "env.server.main.ts"),
|
|
272
|
+
[
|
|
273
|
+
'import { libEnv } from "./env.server.type";',
|
|
274
|
+
'if (process.env.CLOUD_REGION !== "seoul") throw new Error("the cloud env file was evaluated");',
|
|
275
|
+
'export const env = { ...libEnv, secret: "main-secret" };',
|
|
276
|
+
'export default "main-default";',
|
|
277
|
+
"",
|
|
278
|
+
].join("\n"),
|
|
279
|
+
);
|
|
280
|
+
for (const name of ["edge", "kiosk", "runtime"])
|
|
281
|
+
await write(
|
|
282
|
+
path.join(envDir, `env.server.main.${name}.ts`),
|
|
283
|
+
[
|
|
284
|
+
'import { libEnv } from "./env.server.type";',
|
|
285
|
+
`export const env = { ...libEnv, origin: "${name}-origin" };`,
|
|
286
|
+
`export default "${name}-default";`,
|
|
287
|
+
"",
|
|
288
|
+
].join("\n"),
|
|
289
|
+
);
|
|
290
|
+
await write(
|
|
291
|
+
entry,
|
|
292
|
+
[
|
|
293
|
+
'import fallback, { env as app } from "./env/env.server.main";',
|
|
294
|
+
`import { env as lib } from ${JSON.stringify(libEnv)};`,
|
|
295
|
+
"console.info(JSON.stringify({ app, lib, fallback }));",
|
|
296
|
+
"",
|
|
297
|
+
].join("\n"),
|
|
298
|
+
);
|
|
299
|
+
const reports: unknown[] = [];
|
|
300
|
+
const result = await Bun.build({
|
|
301
|
+
entrypoints: [entry],
|
|
302
|
+
outdir: path.join(root, "out"),
|
|
303
|
+
target: "bun",
|
|
304
|
+
plugins: [
|
|
305
|
+
createServerEnvPlugin({
|
|
306
|
+
envDir,
|
|
307
|
+
environment: "main",
|
|
308
|
+
environments,
|
|
309
|
+
profile,
|
|
310
|
+
profiles: [...(profile ? [profile] : []), "edge", "kiosk"],
|
|
311
|
+
secrets,
|
|
312
|
+
onLibEnv: (file, report) => reports.push({ file: path.basename(file), ...report }),
|
|
313
|
+
}),
|
|
314
|
+
],
|
|
315
|
+
});
|
|
316
|
+
expect(result.success).toBe(true);
|
|
317
|
+
const file = result.outputs.find((artifact) => artifact.kind === "entry-point")?.path ?? "";
|
|
318
|
+
const start = (env: { [name: string]: string }) =>
|
|
319
|
+
Bun.spawnSync([process.execPath, file], { env: { ...process.env, AKAN_PUBLIC_ENV: "main", ...env } });
|
|
320
|
+
return { reports, start, text: await Bun.file(file).text() };
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
test("the server starts on the environment's own file with no profile named", async () => {
|
|
324
|
+
const { start } = await carry();
|
|
325
|
+
const proc = start({ CLOUD_REGION: "seoul" });
|
|
326
|
+
expect(proc.exitCode).toBe(0);
|
|
327
|
+
expect(JSON.parse(proc.stdout.toString())).toEqual({
|
|
328
|
+
app: { shared: "shared-value", secret: "main-secret" },
|
|
329
|
+
lib: { hostname: "lib-host", security: { jwtSecret: "lib-jwt", accessTokenSeconds: 900 } },
|
|
330
|
+
fallback: "main-default",
|
|
331
|
+
});
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
test("AKAN_ENV_PROFILE starts it on that profile's file, and the environment's own is never evaluated", async () => {
|
|
335
|
+
const { start, reports } = await carry();
|
|
336
|
+
const edge = start({ AKAN_ENV_PROFILE: "edge" });
|
|
337
|
+
expect(edge.stderr.toString()).not.toContain("the cloud env file was evaluated");
|
|
338
|
+
expect(JSON.parse(edge.stdout.toString())).toEqual({
|
|
339
|
+
app: { shared: "shared-value", origin: "edge-origin" },
|
|
340
|
+
lib: { hostname: "lib-host", security: { accessTokenSeconds: 900 } },
|
|
341
|
+
fallback: "edge-default",
|
|
342
|
+
});
|
|
343
|
+
expect(JSON.parse(start({ AKAN_ENV_PROFILE: "kiosk" }).stdout.toString())).toEqual({
|
|
344
|
+
app: { shared: "shared-value", origin: "kiosk-origin" },
|
|
345
|
+
lib: { hostname: "lib-kiosk-host" },
|
|
346
|
+
fallback: "kiosk-default",
|
|
347
|
+
});
|
|
348
|
+
expect(reports).toEqual([
|
|
349
|
+
{ file: "env.server.testing.ts", profile: "edge", profileFile: false, stripped: ["security.jwtSecret"] },
|
|
350
|
+
{ file: "env.server.testing.ts", profile: "kiosk", profileFile: true, stripped: [] },
|
|
351
|
+
]);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
test("a profile the build does not carry refuses to start, naming the ones it does", async () => {
|
|
355
|
+
const { start } = await carry();
|
|
356
|
+
const proc = start({ AKAN_ENV_PROFILE: "desk", CLOUD_REGION: "seoul" });
|
|
357
|
+
expect(proc.exitCode).not.toBe(0);
|
|
358
|
+
expect(proc.stderr.toString()).toContain(
|
|
359
|
+
"AKAN_ENV_PROFILE=desk names a server env profile this build does not carry (it carries edge, kiosk).",
|
|
360
|
+
);
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
test("a profile build carries them beside its own profile, which it starts on with none named", async () => {
|
|
364
|
+
const { start, reports, text } = await carry(undefined, "runtime");
|
|
365
|
+
expect(text).not.toContain("main-secret");
|
|
366
|
+
const runtime = {
|
|
367
|
+
app: { shared: "shared-value", origin: "runtime-origin" },
|
|
368
|
+
lib: { hostname: "lib-host", security: { accessTokenSeconds: 900 } },
|
|
369
|
+
fallback: "runtime-default",
|
|
370
|
+
};
|
|
371
|
+
for (const named of [[], ["runtime"]]) {
|
|
372
|
+
const proc = start(Object.fromEntries(named.map((name) => ["AKAN_ENV_PROFILE", name])));
|
|
373
|
+
expect(proc.stderr.toString()).toBe("");
|
|
374
|
+
expect(JSON.parse(proc.stdout.toString())).toEqual(runtime);
|
|
375
|
+
}
|
|
376
|
+
expect(JSON.parse(start({ AKAN_ENV_PROFILE: "edge" }).stdout.toString())).toEqual({
|
|
377
|
+
...runtime,
|
|
378
|
+
app: { shared: "shared-value", origin: "edge-origin" },
|
|
379
|
+
fallback: "edge-default",
|
|
380
|
+
});
|
|
381
|
+
expect(JSON.parse(start({ AKAN_ENV_PROFILE: "kiosk" }).stdout.toString())).toEqual({
|
|
382
|
+
app: { shared: "shared-value", origin: "kiosk-origin" },
|
|
383
|
+
lib: { hostname: "lib-kiosk-host" },
|
|
384
|
+
fallback: "kiosk-default",
|
|
385
|
+
});
|
|
386
|
+
expect(start({ AKAN_ENV_PROFILE: "desk" }).stderr.toString()).toContain(
|
|
387
|
+
"AKAN_ENV_PROFILE=desk names a server env profile this build does not carry (it carries runtime, edge, kiosk).",
|
|
388
|
+
);
|
|
389
|
+
expect(reports).toEqual(
|
|
390
|
+
expect.arrayContaining([
|
|
391
|
+
{ file: "env.server.testing.ts", profile: "runtime", profileFile: false, stripped: ["security.jwtSecret"] },
|
|
392
|
+
{ file: "env.server.testing.ts", profile: "edge", profileFile: false, stripped: ["security.jwtSecret"] },
|
|
393
|
+
{ file: "env.server.testing.ts", profile: "kiosk", profileFile: true, stripped: [] },
|
|
394
|
+
]),
|
|
395
|
+
);
|
|
396
|
+
expect(reports).toHaveLength(3);
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
test("an image build still leaves every secret value out, the app's and a lib's", async () => {
|
|
400
|
+
const { start, text } = await carry("read");
|
|
401
|
+
for (const secret of ["main-secret", "lib-jwt"]) expect(text).not.toContain(secret);
|
|
402
|
+
const edge = start({ AKAN_ENV_PROFILE: "edge" });
|
|
403
|
+
expect(edge.exitCode).toBe(0);
|
|
404
|
+
expect(JSON.parse(edge.stdout.toString()).lib).toEqual({
|
|
405
|
+
hostname: "lib-host",
|
|
406
|
+
security: { accessTokenSeconds: 900 },
|
|
407
|
+
});
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
|
|
258
411
|
test("leaves env files outside the app's env directory alone", async () => {
|
|
259
412
|
const root = await makeTempRoot();
|
|
260
413
|
const other = path.join(root, "libs/shared/env/env.server.testing.ts");
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { existsSync, realpathSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { EnvProfile } from "akanjs/server/lifecycle/envProfile";
|
|
3
4
|
import type { BunPlugin, OnLoadResult } from "bun";
|
|
4
5
|
import { SecretEnvDeclaration } from "./secretEnvDeclaration";
|
|
5
6
|
import { ServerEnvProfile } from "./serverEnvProfile";
|
|
@@ -11,17 +12,44 @@ export interface ServerEnvPluginOptions {
|
|
|
11
12
|
environments: Iterable<string>;
|
|
12
13
|
/** Bundled in place of the environment's own file: `env.server.<environment>.<profile>.ts`, read from the same folder. */
|
|
13
14
|
profile?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Carried beside the environment's own file, or beside `profile` when one is bundled in its place, each as
|
|
17
|
+
* `env.server.<environment>.<profile>.ts`: the server runs the one `AKAN_ENV_PROFILE` names when it starts.
|
|
18
|
+
*/
|
|
19
|
+
profiles?: readonly string[];
|
|
14
20
|
/** Under a profile, once per lib env file: whether the lib gave one of the profile's, and what was left out if not. */
|
|
15
|
-
onLibEnv?: (file: string, report: { profileFile: boolean; stripped: string[] }) => void;
|
|
21
|
+
onLibEnv?: (file: string, report: { profile: string; profileFile: boolean; stripped: string[] }) => void;
|
|
16
22
|
/**
|
|
17
23
|
* Without a profile: `read` bundles each env file, a lib's included, with its secret strings replaced by reads of the
|
|
18
|
-
* process env
|
|
24
|
+
* process env. Unset, the files are bundled as written.
|
|
19
25
|
*/
|
|
20
|
-
secrets?: "read"
|
|
26
|
+
secrets?: "read";
|
|
21
27
|
}
|
|
22
28
|
|
|
23
29
|
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
24
30
|
|
|
31
|
+
const ORIGINAL_NAMESPACE = "akan-server-env";
|
|
32
|
+
const ORIGINAL_PREFIX = `${ORIGINAL_NAMESPACE}:`;
|
|
33
|
+
//? Bun keys a module by its path whatever its namespace, so the file as written needs a path of its own.
|
|
34
|
+
const ORIGINAL_SUFFIX = ".original";
|
|
35
|
+
|
|
36
|
+
//? Only the env the server starts on is evaluated: the environment's own file may not load without its variables.
|
|
37
|
+
const selectorOf = (file: string, exports: string[], carried: { [profile: string]: string }, base?: string) => {
|
|
38
|
+
const names = Object.keys(carried);
|
|
39
|
+
const all = [...(base ? [base] : []), ...names];
|
|
40
|
+
const refusal = ` names a server env profile this build does not carry (it carries ${all.join(", ")}).`;
|
|
41
|
+
const named = `process.env.${EnvProfile.key}`;
|
|
42
|
+
return [
|
|
43
|
+
`const profile = ${base ? `${named} === ${JSON.stringify(base)} ? undefined : ${named}` : named};`,
|
|
44
|
+
`const carried = { ${names.map((name) => `${JSON.stringify(name)}: () => ${carried[name]}`).join(", ")} };`,
|
|
45
|
+
`if (profile && !Object.hasOwn(carried, profile)) throw new Error("${EnvProfile.key}=" + profile + ${JSON.stringify(refusal)});`,
|
|
46
|
+
`const picked = profile ? carried[profile]() : require(${JSON.stringify(`${ORIGINAL_PREFIX}${file}`)});`,
|
|
47
|
+
...exports.map((name) =>
|
|
48
|
+
name === "default" ? "export default picked.default;" : `export const ${name} = picked[${JSON.stringify(name)}];`,
|
|
49
|
+
),
|
|
50
|
+
].join("\n");
|
|
51
|
+
};
|
|
52
|
+
|
|
25
53
|
//* `env.server.ts` imports every environment's file, so an image would hand out the secrets of each environment it
|
|
26
54
|
//* never runs. Every file but the image's own is swapped for exports that refuse to be read.
|
|
27
55
|
export const createServerEnvPlugin = ({
|
|
@@ -29,6 +57,7 @@ export const createServerEnvPlugin = ({
|
|
|
29
57
|
environment,
|
|
30
58
|
environments,
|
|
31
59
|
profile,
|
|
60
|
+
profiles = [],
|
|
32
61
|
onLibEnv,
|
|
33
62
|
secrets,
|
|
34
63
|
}: ServerEnvPluginOptions): BunPlugin => {
|
|
@@ -38,25 +67,74 @@ export const createServerEnvPlugin = ({
|
|
|
38
67
|
const folder = `^(?:${[...dirs].map(escapeRegExp).join("|")})[\\\\/]env\\.server\\.`;
|
|
39
68
|
const filter = new RegExp(`${folder}(?:${others.map(escapeRegExp).join("|")})\\.ts$`);
|
|
40
69
|
const own = new RegExp(`${folder}${escapeRegExp(environment)}\\.ts$`);
|
|
70
|
+
const carriedNames = profiles.filter((name) => name !== profile);
|
|
41
71
|
const libEnvs = new Map<string, Promise<OnLoadResult>>();
|
|
72
|
+
const libSelectors = new Map<string, Promise<OnLoadResult>>();
|
|
73
|
+
const once = (
|
|
74
|
+
cache: Map<string, Promise<OnLoadResult>>,
|
|
75
|
+
file: string,
|
|
76
|
+
load: (file: string) => Promise<OnLoadResult>,
|
|
77
|
+
) => {
|
|
78
|
+
if (!cache.has(file)) cache.set(file, load(file));
|
|
79
|
+
return cache.get(file) as Promise<OnLoadResult>;
|
|
80
|
+
};
|
|
42
81
|
const libEnv = async (file: string): Promise<OnLoadResult> => {
|
|
43
82
|
const { loader, contents, profileFile, stripped } = await ServerEnvProfile.libEnvSource(file, profile ?? "");
|
|
44
|
-
onLibEnv?.(file, { profileFile, stripped });
|
|
83
|
+
onLibEnv?.(file, { profile: profile ?? "", profileFile, stripped });
|
|
45
84
|
return { loader, contents };
|
|
46
85
|
};
|
|
86
|
+
const inPlace = async (file: string, name: string): Promise<OnLoadResult> => ({
|
|
87
|
+
loader: "ts",
|
|
88
|
+
contents: await ServerEnvProfile.sourceInPlaceOf(
|
|
89
|
+
path.join(path.dirname(file), ServerEnvProfile.fileName(environment, name)),
|
|
90
|
+
file,
|
|
91
|
+
name,
|
|
92
|
+
),
|
|
93
|
+
});
|
|
94
|
+
const exportsOf = async (file: string) =>
|
|
95
|
+
new Bun.Transpiler({ loader: "ts" }).scan(await Bun.file(file).text()).exports;
|
|
96
|
+
const original = async (file: string): Promise<OnLoadResult> =>
|
|
97
|
+
secrets && !profile
|
|
98
|
+
? await SecretEnvDeclaration.source(file, secrets)
|
|
99
|
+
: { loader: "ts", contents: await Bun.file(file).text() };
|
|
100
|
+
const base = (file: string): Promise<OnLoadResult> => {
|
|
101
|
+
if (!profile) return original(file);
|
|
102
|
+
return own.test(file) ? inPlace(file, profile) : once(libEnvs, file, libEnv);
|
|
103
|
+
};
|
|
104
|
+
const isAppEnv = (file: string) => {
|
|
105
|
+
const name = path.basename(file, ".ts").slice("env.server.".length);
|
|
106
|
+
return dirs.has(path.dirname(file)) || name === "type" || name === "example";
|
|
107
|
+
};
|
|
108
|
+
const ownSelector = async (file: string): Promise<OnLoadResult> => ({
|
|
109
|
+
loader: "js",
|
|
110
|
+
contents: selectorOf(
|
|
111
|
+
file,
|
|
112
|
+
await exportsOf(file),
|
|
113
|
+
Object.fromEntries(
|
|
114
|
+
carriedNames.map((name) => [
|
|
115
|
+
name,
|
|
116
|
+
`require(${JSON.stringify(path.join(path.dirname(file), ServerEnvProfile.fileName(environment, name)))})`,
|
|
117
|
+
]),
|
|
118
|
+
),
|
|
119
|
+
profile,
|
|
120
|
+
),
|
|
121
|
+
});
|
|
122
|
+
const libSelector = async (file: string): Promise<OnLoadResult> => {
|
|
123
|
+
const carried: { [name: string]: string } = {};
|
|
124
|
+
for (const name of carriedNames) {
|
|
125
|
+
const { profileFile, stripped, value } = await ServerEnvProfile.libEnvSource(file, name);
|
|
126
|
+
onLibEnv?.(file, { profile: name, profileFile, stripped });
|
|
127
|
+
carried[name] = profileFile
|
|
128
|
+
? `require(${JSON.stringify(ServerEnvProfile.profileFileOf(file, name))})`
|
|
129
|
+
: `({ env: ${JSON.stringify(value)} })`;
|
|
130
|
+
}
|
|
131
|
+
return { loader: "js", contents: selectorOf(file, await exportsOf(file), carried, profile) };
|
|
132
|
+
};
|
|
47
133
|
return {
|
|
48
134
|
name: "akan-server-env",
|
|
49
135
|
setup(build) {
|
|
50
136
|
//* The environment's own file never enters a profile's bundle: its contents are the profile file's.
|
|
51
|
-
if (profile)
|
|
52
|
-
build.onLoad({ filter: own }, async (args) => ({
|
|
53
|
-
loader: "ts",
|
|
54
|
-
contents: await ServerEnvProfile.sourceInPlaceOf(
|
|
55
|
-
path.join(path.dirname(args.path), ServerEnvProfile.fileName(environment, profile)),
|
|
56
|
-
args.path,
|
|
57
|
-
profile,
|
|
58
|
-
),
|
|
59
|
-
}));
|
|
137
|
+
if (profile && !carriedNames.length) build.onLoad({ filter: own }, (args) => inPlace(args.path, profile));
|
|
60
138
|
if (others.length)
|
|
61
139
|
build.onLoad({ filter }, async (args) => {
|
|
62
140
|
const name = path.basename(args.path, ".ts").slice("env.server.".length);
|
|
@@ -71,6 +149,23 @@ export const createServerEnvPlugin = ({
|
|
|
71
149
|
].join("\n"),
|
|
72
150
|
};
|
|
73
151
|
});
|
|
152
|
+
if (carriedNames.length) {
|
|
153
|
+
build.onResolve({ filter: new RegExp(`^${ORIGINAL_PREFIX}`) }, (args) => ({
|
|
154
|
+
path: `${args.path.slice(ORIGINAL_PREFIX.length)}${ORIGINAL_SUFFIX}`,
|
|
155
|
+
namespace: ORIGINAL_NAMESPACE,
|
|
156
|
+
}));
|
|
157
|
+
//? A module under a namespace has no folder of its own to resolve a relative import from.
|
|
158
|
+
build.onResolve({ filter: /^\.{1,2}[\\/]/, namespace: ORIGINAL_NAMESPACE }, (args) => ({
|
|
159
|
+
path: Bun.resolveSync(args.path, path.dirname(args.importer)),
|
|
160
|
+
}));
|
|
161
|
+
build.onLoad({ filter: /.*/, namespace: ORIGINAL_NAMESPACE }, (args) =>
|
|
162
|
+
base(args.path.slice(0, -ORIGINAL_SUFFIX.length)),
|
|
163
|
+
);
|
|
164
|
+
build.onLoad({ filter: own }, (args) => ownSelector(args.path));
|
|
165
|
+
build.onLoad({ filter: ServerEnvProfile.envFilePattern }, (args) => {
|
|
166
|
+
return isAppEnv(args.path) ? original(args.path) : once(libSelectors, args.path, libSelector);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
74
169
|
//? After the stubs, which take the other environments' files first; `env.server.ts` itself is the env file where
|
|
75
170
|
//? a pipeline copies one over the switch.
|
|
76
171
|
if (secrets && !profile)
|
|
@@ -78,14 +173,10 @@ export const createServerEnvPlugin = ({
|
|
|
78
173
|
SecretEnvDeclaration.source(args.path, secrets),
|
|
79
174
|
);
|
|
80
175
|
//? Last: the app's own env files above are taken by the handlers before it, which match them first.
|
|
81
|
-
if (profile)
|
|
82
|
-
build.onLoad({ filter: ServerEnvProfile.envFilePattern },
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
return { loader: "ts", contents: await Bun.file(args.path).text() };
|
|
86
|
-
if (!libEnvs.has(args.path)) libEnvs.set(args.path, libEnv(args.path));
|
|
87
|
-
return (await libEnvs.get(args.path)) as OnLoadResult;
|
|
88
|
-
});
|
|
176
|
+
if (profile && !carriedNames.length)
|
|
177
|
+
build.onLoad({ filter: ServerEnvProfile.envFilePattern }, (args) =>
|
|
178
|
+
isAppEnv(args.path) ? original(args.path) : once(libEnvs, args.path, libEnv),
|
|
179
|
+
);
|
|
89
180
|
},
|
|
90
181
|
};
|
|
91
182
|
};
|