@alicesystems/cli 0.0.0-stage → 0.1.0-alpha.1

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -2
  3. package/dist/apps/cli/package.json +17 -0
  4. package/dist/apps/cli/src/commands/init/index.mjs +45 -0
  5. package/dist/apps/cli/src/commands/init/prompts.mjs +38 -0
  6. package/dist/apps/cli/src/helpers/validation.mjs +53 -0
  7. package/dist/apps/cli/src/index.mjs +37 -0
  8. package/dist/index.mjs +2 -0
  9. package/dist/packages/template-generator/src/foundation.mjs +130 -0
  10. package/dist/packages/template-generator/templates/README.md +7 -0
  11. package/dist/packages/template-generator/templates/base/.editorconfig +12 -0
  12. package/dist/packages/template-generator/templates/base/.env.example +2 -0
  13. package/dist/packages/template-generator/templates/base/.gitattributes +3 -0
  14. package/dist/packages/template-generator/templates/base/.github/workflows/ci.yml +31 -0
  15. package/dist/packages/template-generator/templates/base/.gitleaks.toml +7 -0
  16. package/dist/packages/template-generator/templates/base/.husky/pre-commit +2 -0
  17. package/dist/packages/template-generator/templates/base/.husky/pre-push +2 -0
  18. package/dist/packages/template-generator/templates/base/.node-version +1 -0
  19. package/dist/packages/template-generator/templates/base/AGENTS.md +11 -0
  20. package/dist/packages/template-generator/templates/base/README.md +26 -0
  21. package/dist/packages/template-generator/templates/base/alice.json +38 -0
  22. package/dist/packages/template-generator/templates/base/biome.json +27 -0
  23. package/dist/packages/template-generator/templates/base/documentation/architecture.md +13 -0
  24. package/dist/packages/template-generator/templates/base/documentation/environment.md +24 -0
  25. package/dist/packages/template-generator/templates/base/documentation/infisical.md +39 -0
  26. package/dist/packages/template-generator/templates/base/documentation/validation-results.md +25 -0
  27. package/dist/packages/template-generator/templates/base/documentation/validation.md +21 -0
  28. package/dist/packages/template-generator/templates/base/gitignore.template +12 -0
  29. package/dist/packages/template-generator/templates/base/lint-staged.config.mjs +3 -0
  30. package/dist/packages/template-generator/templates/base/npmrc.template +2 -0
  31. package/dist/packages/template-generator/templates/base/package.json +42 -0
  32. package/dist/packages/template-generator/templates/base/packages/env/README.md +9 -0
  33. package/dist/packages/template-generator/templates/base/packages/env/package.json +32 -0
  34. package/dist/packages/template-generator/templates/base/packages/env/src/client.ts +5 -0
  35. package/dist/packages/template-generator/templates/base/packages/env/src/policy.ts +9 -0
  36. package/dist/packages/template-generator/templates/base/packages/env/src/server.ts +15 -0
  37. package/dist/packages/template-generator/templates/base/packages/env/tests/env.test.ts +66 -0
  38. package/dist/packages/template-generator/templates/base/packages/env/tsconfig.json +10 -0
  39. package/dist/packages/template-generator/templates/base/packages/env/tsconfig.tooling.json +9 -0
  40. package/dist/packages/template-generator/templates/base/packages/env/tsdown.config.ts +11 -0
  41. package/dist/packages/template-generator/templates/base/packages/env/vitest.config.ts +16 -0
  42. package/dist/packages/template-generator/templates/base/packages/typescript/README.md +7 -0
  43. package/dist/packages/template-generator/templates/base/packages/typescript/base.json +15 -0
  44. package/dist/packages/template-generator/templates/base/packages/typescript/bundler.json +9 -0
  45. package/dist/packages/template-generator/templates/base/packages/typescript/nextjs.json +12 -0
  46. package/dist/packages/template-generator/templates/base/packages/typescript/node.json +6 -0
  47. package/dist/packages/template-generator/templates/base/packages/typescript/package.json +12 -0
  48. package/dist/packages/template-generator/templates/base/packages/typescript/react.json +8 -0
  49. package/dist/packages/template-generator/templates/base/pnpm-lock.yaml +1664 -0
  50. package/dist/packages/template-generator/templates/base/pnpm-workspace.yaml +10 -0
  51. package/dist/packages/template-generator/templates/base/scripts/check-presets.mjs +14 -0
  52. package/dist/packages/template-generator/templates/base/scripts/e2e.mjs +8 -0
  53. package/dist/packages/template-generator/templates/base/scripts/infisical-connect.mjs +119 -0
  54. package/dist/packages/template-generator/templates/base/scripts/infisical-local.mjs +509 -0
  55. package/dist/packages/template-generator/templates/base/scripts/prepare.mjs +15 -0
  56. package/dist/packages/template-generator/templates/base/scripts/secrets.mjs +68 -0
  57. package/dist/packages/template-generator/templates/base/scripts/security-tools.mjs +58 -0
  58. package/dist/packages/template-generator/templates/base/scripts/setup-infisical-local.mjs +115 -0
  59. package/dist/packages/template-generator/templates/base/scripts/setup-local.mjs +8 -0
  60. package/dist/packages/template-generator/templates/base/tests/fixtures/browser/boundary.ts +13 -0
  61. package/dist/packages/template-generator/templates/base/tests/fixtures/browser/tsconfig.json +8 -0
  62. package/dist/packages/template-generator/templates/base/tests/fixtures/node/boundary.ts +4 -0
  63. package/dist/packages/template-generator/templates/base/tests/fixtures/node/tsconfig.json +4 -0
  64. package/dist/packages/template-generator/templates/base/tests/foundation.test.mjs +39 -0
  65. package/dist/packages/template-generator/templates/base/tooling/ultracite/LICENSE +7 -0
  66. package/dist/packages/template-generator/templates/base/tooling/ultracite/README.md +10 -0
  67. package/dist/packages/template-generator/templates/base/tooling/ultracite/core/biome.jsonc +706 -0
  68. package/dist/packages/template-generator/templates/base/tsconfig.json +1 -0
  69. package/dist/packages/template-generator/templates/base/turbo.json +28 -0
  70. package/package.json +15 -4
@@ -0,0 +1,10 @@
1
+ packages:
2
+ - "packages/*"
3
+ - "apps/*"
4
+
5
+ minimumReleaseAgeExclude:
6
+ - "@playwright/test@1.64.0"
7
+ - playwright-core@1.64.0
8
+ - playwright@1.64.0
9
+
10
+ strictPeerDependencies: true
@@ -0,0 +1,14 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createRequire } from "node:module";
3
+
4
+ const require = createRequire(import.meta.url);
5
+ for (const runtime of ["browser", "node"]) {
6
+ const result = spawnSync(
7
+ process.execPath,
8
+ [require.resolve("typescript/bin/tsc"), "-p", `tests/fixtures/${runtime}/tsconfig.json`],
9
+ { stdio: "inherit" },
10
+ );
11
+ if (result.status !== 0) {
12
+ process.exit(result.status ?? 1);
13
+ }
14
+ }
@@ -0,0 +1,8 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+
3
+ if (existsSync("apps") && readdirSync("apps").length > 0) {
4
+ throw new Error("Register the selected app's Playwright suite before claiming E2E validation.");
5
+ }
6
+ console.log(
7
+ "Browser E2E: not applicable — this foundation contains no apps. Playwright is installed for future app adapters.",
8
+ );
@@ -0,0 +1,119 @@
1
+ import { spawn } from "node:child_process";
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ export async function findInfisical() {
6
+ const executable = process.platform === "win32" ? "infisical.exe" : "infisical";
7
+ const candidates = (process.env.PATH ?? "")
8
+ .split(path.delimiter)
9
+ .filter(Boolean)
10
+ .map((directory) => path.join(directory, executable));
11
+ if (process.platform === "win32" && process.env.LOCALAPPDATA) {
12
+ const packages = path.join(process.env.LOCALAPPDATA, "Microsoft", "WinGet", "Packages");
13
+ try {
14
+ const entries = await fs.readdir(packages);
15
+ candidates.push(
16
+ ...entries
17
+ .filter((name) => name.startsWith("infisical.infisical_"))
18
+ .map((name) => path.join(packages, name, executable)),
19
+ );
20
+ } catch (error) {
21
+ if (error.code !== "ENOENT") {
22
+ throw error;
23
+ }
24
+ }
25
+ }
26
+ const present = await Promise.all(
27
+ candidates.map(async (candidate) => {
28
+ try {
29
+ return (await fs.stat(candidate)).isFile() ? candidate : null;
30
+ } catch (error) {
31
+ if (error.code !== "ENOENT") {
32
+ throw error;
33
+ }
34
+ return null;
35
+ }
36
+ }),
37
+ );
38
+ const found = present.find(Boolean);
39
+ if (!found) {
40
+ throw new Error(
41
+ "Infisical CLI was not found. Install it using the official CLI guide; Alice does not install it automatically.",
42
+ );
43
+ }
44
+ return found;
45
+ }
46
+
47
+ function runClient(executable, args, { cwd, env, capture = false }) {
48
+ return new Promise((resolve, reject) => {
49
+ const child = spawn(executable, args, {
50
+ cwd,
51
+ env,
52
+ shell: false,
53
+ stdio: capture ? ["ignore", "pipe", "pipe"] : "inherit",
54
+ windowsHide: true,
55
+ });
56
+ let output = "";
57
+ if (capture) {
58
+ child.stdout.on("data", (data) => {
59
+ output += data;
60
+ });
61
+ child.stderr.on("data", () => {
62
+ /* Discard diagnostics from the version-only probe. */
63
+ });
64
+ }
65
+ child.once("error", (error) =>
66
+ reject(new Error("Infisical CLI could not start.", { cause: error })),
67
+ );
68
+ child.once("close", (code) =>
69
+ code === 0
70
+ ? resolve(output.trim())
71
+ : reject(
72
+ new Error(
73
+ "Infisical login/linking did not complete. The local instance and data were retained.",
74
+ ),
75
+ ),
76
+ );
77
+ });
78
+ }
79
+
80
+ export async function linkLocalProject(plan, { executable, run = runClient } = {}) {
81
+ const config = path.join(plan.root, ".infisical.json");
82
+ try {
83
+ await fs.lstat(config);
84
+ throw new Error(
85
+ "An existing .infisical.json was found. It was not overwritten; review that connection separately.",
86
+ );
87
+ } catch (error) {
88
+ if (error.code !== "ENOENT") {
89
+ throw error;
90
+ }
91
+ }
92
+ const cli = executable ?? (await findInfisical());
93
+ const env = Object.fromEntries(
94
+ Object.entries(process.env).filter(
95
+ ([key]) => !(key.startsWith("ALICE_INFISICAL_") || key.startsWith("INFISICAL_")),
96
+ ),
97
+ );
98
+ const version = await run(cli, ["--version"], { capture: true, cwd: plan.root, env });
99
+ if (version !== "infisical version 0.43.140") {
100
+ throw new Error(
101
+ "This connection helper is verified against Infisical CLI 0.43.140. Other versions require compatibility verification.",
102
+ );
103
+ }
104
+ const profile = plan.project;
105
+ const domain = `${plan.url}/api`;
106
+ await run(cli, ["login", "--domain", domain, "--save-as", profile, "--telemetry=false"], {
107
+ cwd: plan.root,
108
+ env,
109
+ });
110
+ await run(cli, ["init", "--domain", domain, "--profile", profile, "--telemetry=false"], {
111
+ cwd: plan.root,
112
+ env,
113
+ });
114
+ const link = JSON.parse(await fs.readFile(config, "utf8"));
115
+ if (typeof link.workspaceId !== "string" || !link.workspaceId.trim()) {
116
+ throw new Error("CLI linking returned no project identity. Secret sync has not run.");
117
+ }
118
+ return { profile, projectId: link.workspaceId, sync: "not-run" };
119
+ }
@@ -0,0 +1,509 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { existsSync, promises as fs } from "node:fs";
4
+ import net from "node:net";
5
+ import path from "node:path";
6
+ import { parseEnv } from "node:util";
7
+
8
+ export const images = Object.freeze({
9
+ backend:
10
+ "infisical/infisical:v0.166.2@sha256:3f014f284cb9af5b12087681cbbddc55244fe8e58a8d080987cd3e0f262bf837",
11
+ db: "postgres:14.24-alpine@sha256:4ea9e5ed06591da7ea23eb65465e8d3187fe79f4d5ec3ae976d29a33b013e77a",
12
+ redis:
13
+ "redis:7.4.11-alpine@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499",
14
+ });
15
+ export const bootstrapKeys = Object.freeze([
16
+ "ALICE_INFISICAL_ENCRYPTION_KEY",
17
+ "ALICE_INFISICAL_AUTH_SECRET",
18
+ "ALICE_INFISICAL_POSTGRES_PASSWORD",
19
+ "ALICE_INFISICAL_REDIS_PASSWORD",
20
+ ]);
21
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
22
+ const newline = /\r?\n/;
23
+ const bootstrapFormats = {
24
+ ALICE_INFISICAL_AUTH_SECRET: { bytes: 32, encoding: "base64", pattern: /^[A-Za-z0-9+/]{43}=$/ },
25
+ ALICE_INFISICAL_ENCRYPTION_KEY: { bytes: 16, encoding: "hex", pattern: /^[a-f0-9]{32}$/ },
26
+ ALICE_INFISICAL_POSTGRES_PASSWORD: { bytes: 32, encoding: "hex", pattern: /^[a-f0-9]{64}$/ },
27
+ ALICE_INFISICAL_REDIS_PASSWORD: { bytes: 32, encoding: "hex", pattern: /^[a-f0-9]{64}$/ },
28
+ };
29
+
30
+ export function projectValues(values) {
31
+ return Object.fromEntries(
32
+ Object.entries(values).filter(([key]) => !key.startsWith("ALICE_INFISICAL_")),
33
+ );
34
+ }
35
+
36
+ export function bootstrapValues(source, random = randomBytes) {
37
+ const values = parseEnv(source);
38
+ const additions = {};
39
+ for (const key of bootstrapKeys) {
40
+ const occurrences = source
41
+ .split(newline)
42
+ .filter((line) => new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`).test(line));
43
+ if (occurrences.length > 1) {
44
+ throw new Error(
45
+ `Duplicate bootstrap key: ${key}. Resolve it without rotating existing values.`,
46
+ );
47
+ }
48
+ if (Object.hasOwn(values, key)) {
49
+ const valid = bootstrapFormats[key].pattern.test(values[key]);
50
+ if (!valid) {
51
+ throw new Error(`Invalid bootstrap key format: ${key}. Existing values were not replaced.`);
52
+ }
53
+ } else {
54
+ additions[key] = random(bootstrapFormats[key].bytes).toString(bootstrapFormats[key].encoding);
55
+ }
56
+ }
57
+ return { additions, values: { ...values, ...additions } };
58
+ }
59
+
60
+ export function composeDefinition(project, port) {
61
+ if (!Number.isInteger(port) || port < 1024 || port > 65_535) {
62
+ throw new Error("Choose a local port from 1024 to 65535.");
63
+ }
64
+ const variable = (key) => `\${${key}:?Run the Alice local Infisical setup command}`;
65
+ const pg = variable(bootstrapKeys[2]);
66
+ const redis = variable(bootstrapKeys[3]);
67
+ return {
68
+ name: project,
69
+ services: {
70
+ backend: {
71
+ depends_on: {
72
+ db: { condition: "service_healthy" },
73
+ redis: { condition: "service_healthy" },
74
+ },
75
+ environment: {
76
+ AUTH_SECRET: variable(bootstrapKeys[1]),
77
+ DB_CONNECTION_URI: `postgresql://infisical:${pg}@db:5432/infisical`,
78
+ ENCRYPTION_KEY: variable(bootstrapKeys[0]),
79
+ HOST: "0.0.0.0",
80
+ NODE_ENV: "production",
81
+ PORT: "8080",
82
+ REDIS_URL: `redis://:${redis}@redis:6379`,
83
+ SITE_URL: `http://127.0.0.1:${port}`,
84
+ TELEMETRY_ENABLED: "false",
85
+ },
86
+ image: images.backend,
87
+ ports: [`127.0.0.1:${port}:8080`],
88
+ restart: "unless-stopped",
89
+ },
90
+ db: {
91
+ environment: {
92
+ POSTGRES_DB: "infisical",
93
+ POSTGRES_PASSWORD: pg,
94
+ POSTGRES_USER: "infisical",
95
+ },
96
+ healthcheck: {
97
+ interval: "5s",
98
+ retries: 30,
99
+ test: ["CMD", "pg_isready", "-U", "infisical", "-d", "infisical"],
100
+ timeout: "5s",
101
+ },
102
+ image: images.db,
103
+ restart: "unless-stopped",
104
+ volumes: ["postgres-data:/var/lib/postgresql/data"],
105
+ },
106
+ redis: {
107
+ command: ["sh", "-c", 'exec redis-server --appendonly yes --requirepass "$$REDISCLI_AUTH"'],
108
+ environment: { REDISCLI_AUTH: redis },
109
+ healthcheck: {
110
+ interval: "5s",
111
+ retries: 30,
112
+ test: ["CMD", "redis-cli", "ping"],
113
+ timeout: "5s",
114
+ },
115
+ image: images.redis,
116
+ restart: "unless-stopped",
117
+ volumes: ["redis-data:/data"],
118
+ },
119
+ },
120
+ volumes: { "postgres-data": {}, "redis-data": {} },
121
+ };
122
+ }
123
+
124
+ export function dockerRun(executable, args, { cwd, env = process.env, timeout = 600_000 } = {}) {
125
+ return new Promise((resolve, reject) => {
126
+ const child = spawn(executable, args, {
127
+ cwd,
128
+ env,
129
+ shell: false,
130
+ stdio: ["ignore", "pipe", "pipe"],
131
+ windowsHide: true,
132
+ });
133
+ let output = "";
134
+ let exceeded = false;
135
+ child.stdout.on("data", (data) => {
136
+ output += data;
137
+ if (output.length > 2_000_000) {
138
+ exceeded = true;
139
+ child.kill();
140
+ }
141
+ });
142
+ // Never print Docker's interpolated configuration or secret-bearing diagnostics.
143
+ child.stderr.on("data", () => {
144
+ /* Deliberately discard potentially secret-bearing diagnostics. */
145
+ });
146
+ const timer = setTimeout(() => child.kill(), timeout);
147
+ child.once("error", () => {
148
+ clearTimeout(timer);
149
+ reject(new Error("Docker could not start. Install/start Docker Desktop and retry."));
150
+ });
151
+ child.once("close", (code) => {
152
+ clearTimeout(timer);
153
+ if (code === 0 && !exceeded) {
154
+ resolve(output.trim());
155
+ } else {
156
+ reject(
157
+ new Error(
158
+ "Docker operation failed or timed out. Configuration and persistent data were retained; no secrets were printed.",
159
+ ),
160
+ );
161
+ }
162
+ });
163
+ });
164
+ }
165
+
166
+ export async function findDocker() {
167
+ const names = process.platform === "win32" ? ["docker.exe"] : ["docker"];
168
+ const directories = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
169
+ if (process.platform === "win32") {
170
+ directories.push(
171
+ path.join(
172
+ process.env.ProgramFiles ?? "C:\\Program Files",
173
+ "Docker",
174
+ "Docker",
175
+ "resources",
176
+ "bin",
177
+ ),
178
+ );
179
+ }
180
+ const candidates = directories.flatMap((directory) =>
181
+ names.map((name) => path.resolve(directory, name)),
182
+ );
183
+ const results = await Promise.all(
184
+ candidates.map(async (candidate) => {
185
+ try {
186
+ return (await fs.stat(candidate)).isFile() ? candidate : null;
187
+ } catch (error) {
188
+ if (error.code !== "ENOENT") {
189
+ throw error;
190
+ }
191
+ return null;
192
+ }
193
+ }),
194
+ );
195
+ const found = results.find(Boolean);
196
+ if (found) {
197
+ return found;
198
+ }
199
+ throw new Error(
200
+ "Docker was not found. Install Docker Desktop; Alice does not install it automatically.",
201
+ );
202
+ }
203
+
204
+ function verifyGitExclusion(root) {
205
+ let directory = root;
206
+ while (!existsSync(path.join(directory, ".git"))) {
207
+ const parent = path.dirname(directory);
208
+ if (parent === directory) {
209
+ return;
210
+ }
211
+ directory = parent;
212
+ }
213
+ const ignore = spawnSync("git", ["check-ignore", "--quiet", ".env"], { cwd: root });
214
+ const tracked = spawnSync("git", ["ls-files", "--", ".env"], { cwd: root, encoding: "utf8" });
215
+ if (ignore.status !== 0 || tracked.status !== 0 || tracked.stdout.trim()) {
216
+ throw new Error(
217
+ "Bootstrap storage requires an ignored, untracked root .env. Fix its Git status before setup.",
218
+ );
219
+ }
220
+ }
221
+
222
+ export async function localPlan(target, port = 8088) {
223
+ const root = path.resolve(target);
224
+ if ((await fs.realpath(root)) !== root) {
225
+ throw new Error("Use the project directory's real path, without symlink aliases.");
226
+ }
227
+ await Promise.all(
228
+ ["alice.json", ".env", ".env.example", ".gitignore"].map(async (relative) => {
229
+ const stat = await fs.lstat(path.join(root, relative));
230
+ if (!stat.isFile() || stat.isSymbolicLink()) {
231
+ throw new Error("Expected regular Alice root files; symlinks are unsupported.");
232
+ }
233
+ }),
234
+ );
235
+ if (!(await fs.readFile(path.join(root, ".gitignore"), "utf8")).split(newline).includes(".env")) {
236
+ throw new Error("Root .env must be explicitly ignored before bootstrap secrets are written.");
237
+ }
238
+ verifyGitExclusion(root);
239
+ const manifest = JSON.parse(await fs.readFile(path.join(root, "alice.json"), "utf8"));
240
+ if (
241
+ manifest.schemaVersion !== 1 ||
242
+ !manifest.project?.scope ||
243
+ manifest.packages?.env?.provider !== "infisical"
244
+ ) {
245
+ throw new Error("This helper requires the Alice reference foundation with Infisical selected.");
246
+ }
247
+ const project = `alice-infisical-${hash(process.platform === "win32" ? root.toLowerCase() : root).slice(0, 12)}`;
248
+ const compose = `${JSON.stringify(composeDefinition(project, port), null, 2)}\n`;
249
+ return {
250
+ compose,
251
+ composePath: path.join(root, "infrastructure", "infisical", "compose.yaml"),
252
+ port,
253
+ project,
254
+ root,
255
+ url: `http://127.0.0.1:${port}`,
256
+ };
257
+ }
258
+
259
+ async function availablePort(port) {
260
+ await new Promise((resolve, reject) => {
261
+ const server = net.createServer();
262
+ server.once("error", () =>
263
+ reject(
264
+ new Error(
265
+ "The selected local port is already in use. Choose another port before initial setup.",
266
+ ),
267
+ ),
268
+ );
269
+ server.listen({ exclusive: true, host: "127.0.0.1", port }, () => server.close(resolve));
270
+ });
271
+ }
272
+
273
+ export async function waitForService(
274
+ url,
275
+ {
276
+ fetcher = fetch,
277
+ timeout = 120_000,
278
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
279
+ } = {},
280
+ ) {
281
+ const deadline = Date.now() + timeout;
282
+ do {
283
+ try {
284
+ // biome-ignore lint/performance/noAwaitInLoops: Readiness probes must wait and retry sequentially.
285
+ const response = await fetcher(`${url}/api/status`, {
286
+ redirect: "error",
287
+ signal: AbortSignal.timeout(5000),
288
+ });
289
+ if (response.ok) {
290
+ return;
291
+ }
292
+ } catch {
293
+ /* Startup is allowed to retry, without displaying response bodies. */
294
+ }
295
+ if (Date.now() >= deadline) {
296
+ break;
297
+ }
298
+ await sleep(2000);
299
+ } while (Date.now() < deadline);
300
+ throw new Error(
301
+ "Infisical did not become ready. Containers, volumes and bootstrap keys were retained for retry; project connection is still pending.",
302
+ );
303
+ }
304
+
305
+ async function readConfiguration(plan) {
306
+ const local = path.join(plan.root, ".alice");
307
+ const statePath = path.join(local, "infisical-local.json");
308
+ let state;
309
+ try {
310
+ state = JSON.parse(await fs.readFile(statePath, "utf8"));
311
+ } catch (error) {
312
+ if (error.code !== "ENOENT") {
313
+ throw error;
314
+ }
315
+ }
316
+ if (state && (state.project !== plan.project || state.port !== plan.port)) {
317
+ throw new Error(
318
+ "Existing local configuration uses another project/port. Automatic migration is not supported.",
319
+ );
320
+ }
321
+ const envPath = path.join(plan.root, ".env");
322
+ const source = await fs.readFile(envPath, "utf8");
323
+ const bootstrap = bootstrapValues(source);
324
+ if (state && Object.keys(bootstrap.additions).length) {
325
+ throw new Error(
326
+ "Existing instance is missing bootstrap keys. Restore its original root .env; Alice will not regenerate recovery keys.",
327
+ );
328
+ }
329
+ try {
330
+ if ((await fs.readFile(plan.composePath, "utf8")) !== plan.compose) {
331
+ throw new Error("Existing Compose configuration differs. It was not overwritten.");
332
+ }
333
+ } catch (error) {
334
+ if (error.code !== "ENOENT") {
335
+ throw error;
336
+ }
337
+ }
338
+ return { bootstrap, envPath, source, statePath };
339
+ }
340
+
341
+ function dockerEnvironment(bootstrap, docker) {
342
+ const env = { ...process.env };
343
+ for (const key of Object.keys(env)) {
344
+ if (
345
+ key.startsWith("COMPOSE_") ||
346
+ key.startsWith("ALICE_INFISICAL_") ||
347
+ key.toUpperCase() === "PATH"
348
+ ) {
349
+ delete env[key];
350
+ }
351
+ }
352
+ for (const key of bootstrapKeys) {
353
+ env[key] = bootstrap.values[key];
354
+ }
355
+ env.PATH = `${path.dirname(docker)}${path.delimiter}${process.env.PATH ?? ""}`;
356
+ return env;
357
+ }
358
+
359
+ async function writeConfiguration(plan, envPath, source, bootstrap) {
360
+ // Keys are durable before containers initialize persistent storage. Never rotate on retry.
361
+ if ((await fs.readFile(envPath, "utf8")) !== source) {
362
+ throw new Error("Root .env changed during setup; retry without overwriting it.");
363
+ }
364
+ if (Object.keys(bootstrap.additions).length) {
365
+ const appended = `${source.endsWith("\n") ? "" : "\n"}\n# Local Infisical bootstrap only; never sync or inject into product apps.\n${Object.entries(
366
+ bootstrap.additions,
367
+ )
368
+ .map(([key, value]) => `${key}=${value}`)
369
+ .join("\n")}\n`;
370
+ const handle = await fs.open(envPath, "a");
371
+ try {
372
+ await handle.writeFile(appended);
373
+ await handle.sync();
374
+ } finally {
375
+ await handle.close();
376
+ }
377
+ }
378
+ const ignore = path.join(plan.root, ".gitignore");
379
+ const ignoreSource = await fs.readFile(ignore, "utf8");
380
+ if (!ignoreSource.split(newline).includes(".alice/")) {
381
+ await fs.appendFile(ignore, `${ignoreSource.endsWith("\n") ? "" : "\n"}.alice/\n`);
382
+ }
383
+ const example = path.join(plan.root, ".env.example");
384
+ const exampleSource = await fs.readFile(example, "utf8");
385
+ const documented = parseEnv(exampleSource);
386
+ const missing = bootstrapKeys.filter((key) => !Object.hasOwn(documented, key));
387
+ if (missing.length) {
388
+ await fs.appendFile(
389
+ example,
390
+ `${exampleSource.endsWith("\n") ? "" : "\n"}\n# Generated locally for Infisical bootstrap; excluded from project sync.\n${missing.map((key) => `${key}=`).join("\n")}\n`,
391
+ );
392
+ }
393
+ await ensureLocalDirectory(plan.root, path.join("infrastructure", "infisical"));
394
+ try {
395
+ await fs.writeFile(plan.composePath, plan.compose, { flag: "wx" });
396
+ } catch (error) {
397
+ if (error.code !== "EEXIST") {
398
+ throw error;
399
+ }
400
+ }
401
+ }
402
+
403
+ async function ensureLocalDirectory(root, relative) {
404
+ const directory = path.join(root, relative);
405
+ const parent = path.dirname(relative);
406
+ if (parent !== ".") {
407
+ await ensureLocalDirectory(root, parent);
408
+ }
409
+ try {
410
+ await fs.mkdir(directory);
411
+ } catch (error) {
412
+ if (error.code !== "EEXIST") {
413
+ throw error;
414
+ }
415
+ }
416
+ const stat = await fs.lstat(directory);
417
+ if (
418
+ !stat.isDirectory() ||
419
+ stat.isSymbolicLink() ||
420
+ (await fs.realpath(directory)) !== directory
421
+ ) {
422
+ throw new Error("Setup directories cannot contain symlink aliases.");
423
+ }
424
+ }
425
+
426
+ export async function setupLocal(
427
+ target,
428
+ {
429
+ port = 8088,
430
+ start = false,
431
+ run = dockerRun,
432
+ executable,
433
+ checkPort = availablePort,
434
+ readiness = waitForService,
435
+ say = console.log,
436
+ } = {},
437
+ ) {
438
+ const plan = await localPlan(target, port);
439
+ const docker = executable ?? (await findDocker());
440
+ await run(docker, ["version", "--format", "{{.Server.Version}}"], {
441
+ cwd: plan.root,
442
+ timeout: 15_000,
443
+ });
444
+ await run(docker, ["compose", "version"], { cwd: plan.root, timeout: 15_000 });
445
+ const local = path.join(plan.root, ".alice");
446
+ await ensureLocalDirectory(plan.root, ".alice");
447
+ const lockPath = path.join(local, "infisical-setup.lock");
448
+ let lock;
449
+ try {
450
+ lock = await fs.open(lockPath, "wx", 0o600);
451
+ } catch (error) {
452
+ throw new Error(
453
+ "Another local setup or a stale setup lock exists. Inspect .alice/infisical-setup.lock before retrying.",
454
+ { cause: error },
455
+ );
456
+ }
457
+ try {
458
+ await lock.writeFile(JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }));
459
+ const { statePath, envPath, source, bootstrap } = await readConfiguration(plan);
460
+ const args = [
461
+ "compose",
462
+ "--project-name",
463
+ plan.project,
464
+ "--project-directory",
465
+ plan.root,
466
+ "--env-file",
467
+ envPath,
468
+ "-f",
469
+ plan.composePath,
470
+ ];
471
+ const env = dockerEnvironment(bootstrap, docker);
472
+ if (start) {
473
+ const existing = await run(
474
+ docker,
475
+ ["ps", "-aq", "--filter", `label=com.docker.compose.project=${plan.project}`],
476
+ { cwd: plan.root, env, timeout: 15_000 },
477
+ );
478
+ if (!existing) {
479
+ await checkPort(port);
480
+ }
481
+ }
482
+ await writeConfiguration(plan, envPath, source, bootstrap);
483
+ await run(docker, [...args, "config", "--quiet"], { cwd: plan.root, env, timeout: 30_000 });
484
+ const saveState = async (status) =>
485
+ fs.writeFile(
486
+ statePath,
487
+ `${JSON.stringify({ images, port, project: plan.project, projectConnection: "pending", status, sync: "not-run", url: plan.url }, null, 2)}\n`,
488
+ );
489
+ await saveState("configured-not-verified");
490
+ if (start) {
491
+ say(
492
+ "Starting the isolated Infisical stack. The first image download can take several minutes.",
493
+ );
494
+ await run(docker, [...args, "up", "-d", "--wait", "--wait-timeout", "180"], {
495
+ cwd: plan.root,
496
+ env,
497
+ });
498
+ await readiness(plan.url);
499
+ await saveState("instance-ready-account-setup-pending");
500
+ say(
501
+ `Local Infisical is responding at ${plan.url}. Create your instance administrator account in the browser.`,
502
+ );
503
+ }
504
+ return plan;
505
+ } finally {
506
+ await lock.close();
507
+ await fs.unlink(lockPath);
508
+ }
509
+ }
@@ -0,0 +1,15 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ if (process.env.HUSKY !== "0" && existsSync(".git")) {
6
+ const husky = fileURLToPath(new URL("./bin.js", import.meta.resolve("husky")));
7
+ const result = spawnSync(process.execPath, [husky], {
8
+ stdio: "inherit",
9
+ });
10
+ process.exitCode = result.status ?? 1;
11
+ } else {
12
+ console.log(
13
+ "Hooks install when this workspace has its own Git repository; CI runs checks directly.",
14
+ );
15
+ }