@davidvornholt/standards 0.11.1 → 0.12.0

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/README.md CHANGED
@@ -10,6 +10,7 @@ standards doctor
10
10
  standards structure
11
11
  standards dependabot --check
12
12
  standards dependabot --write
13
+ standards dev-env
13
14
  standards github --check
14
15
  standards github --apply
15
16
  standards poller --config <path>
@@ -18,9 +19,11 @@ standards poller --print-units --config <path>
18
19
 
19
20
  `dependabot --write` regenerates the composed `.github/dependabot.yml` from the canonical `.github/dependabot.base.yml` and the optional repo-owned `.github/dependabot.local.yml`; `init` and `sync` do the same automatically. `dependabot --check` verifies the generated file still matches its sources, and `doctor`/`check` include the same verification. The overlay is deliberately lean and additive only: new update blocks for repo-specific ecosystems, top-level private registry definitions, and `ignore` or `registries` entries appended by repeating a canonical block's normalized target. Matching blocks cannot add labels, groups, cooldowns, pull-request limits, or other policy.
20
21
 
22
+ `dev-env` decrypts the SOPS-encrypted `secrets/dev.yaml` — keyed by workspace group and a one-segment kebab-case workspace name (`apps.<name>`, `packages.<name>`), each mapping portable environment variable names to string values — and transactionally writes every declared workspace's `.env.local` with owner-only permissions and a do-not-edit header. Its Bun-specific dotenv codec exactly round-trips every value it accepts without adding helper environment variables; a value the codec cannot encode exactly is gathered as a validation problem instead of being changed silently. Validation gathers all document, containment, destination-type, workspace, and gitignore problems before writing anything. Generation then stages every output in its destination directory and rolls the whole set back if staging or commit fails, preserving prior contents, modes, and absent files; symlink destinations, duplicate resolved destinations, changed parent-directory identities, and symlinked workspace paths are rejected without following the link. Cleanup trouble after a completed commit is reported loudly as a warning rather than falsely reporting generation failure. Parent identities are checked immediately before each path operation; an unavoidable swap in the syscall-sized interval after a check remains outside the non-hostile maintainer threat model. The canonical `justfile` exposes the command as `just dev-env-generate`, and `just dev-refresh` chains a `just secrets edit dev` session into regeneration.
23
+
21
24
  `check` also rejects the raw token formed by `biome-` + `ignore` anywhere in lock-listed canonical files. The intentionally blunt policy keeps synced sources compatible with consumer Biome configurations without invoking Biome or maintaining language-aware comment parsing.
22
25
 
23
- `github --check` compares the live GitHub repository (merge settings, rulesets, and declared labels) against the merged declaration in `.github/settings.json` + `.github/settings.local.json`; `github --apply` converges that declared state. Undeclared live labels remain untouched, while undeclared repository-owned rulesets are removed. `check` runs the same comparison whenever `.github/settings.json` is present, and fails closed: declared state the token cannot see fails the gate with a message naming the token fix instead of passing unverified. The canonical workflow sets `STANDARDS_SKIP_GITHUB_CHECK=true` only in its unprivileged quality step because its isolated `github-settings` job runs the live comparison with the settings-read token; this is a workflow-internal integration seam, not a general way to disable the local gate. The CLI prints an explicit diagnostic whenever that exact value skips either `check`'s live phase or `github --check`; `github --apply` is never skipped. `--apply` re-diffs the PATCH response, so a setting GitHub accepts with HTTP 200 but silently ignores (plan-unavailable features) is a reported failure, not a false success. A repository whose GitHub plan cannot enforce rulesets can declare that in the seam (see `rulesetEnforcement` below); both commands then skip rulesets and plan-gated repository settings, converge the rest, and print an unprotected-branch notice on every run.
26
+ `github --check` compares the live GitHub repository (including the canonical squash-only repository settings, rulesets, and declared labels) against the merged declaration in `.github/settings.json` + `.github/settings.local.json`; `github --apply` converges that declared state. The canonical declaration enables squash while disabling merge commits and rebases, and its default-branch ruleset independently allows only squash. Undeclared live labels remain untouched, while undeclared repository-owned rulesets are removed. `check` runs the same comparison whenever `.github/settings.json` is present, and fails closed: declared state the token cannot see fails the gate with a message naming the token fix instead of passing unverified. The canonical workflow sets `STANDARDS_SKIP_GITHUB_CHECK=true` only in its unprivileged quality step because its isolated `github-settings` job runs the live comparison with the settings-read token; this is a workflow-internal integration seam, not a general way to disable the local gate. The CLI prints an explicit diagnostic whenever that exact value skips either `check`'s live phase or `github --check`; `github --apply` is never skipped. `--apply` re-diffs the PATCH response, so a setting GitHub accepts with HTTP 200 but silently ignores (plan-unavailable features) is a reported failure, not a false success. A repository whose GitHub plan cannot enforce rulesets can declare that in the seam (see `rulesetEnforcement` below); both commands then skip rulesets and plan-gated repository settings, converge the rest, and print an unprotected-branch notice on every run.
24
27
 
25
28
  `structure` enforces the canonical monorepo structure contract: workspace scripts (`check-types`, `lint`, `lint:fix`, `test`), root gate scripts, filtered Turbo convenience aliases, internal `0.0.0`/`workspace:*` versioning, package `exports`, shared tsconfig inheritance, and browser a11y wiring. Only a workspace containing an explicit `*.a11y.ts` suite must provide a `test:a11y` script and direct `@axe-core/playwright` and `@playwright/test` dependencies. `check` includes `structure`, so these rules gate every consumer PR.
26
29
 
@@ -31,7 +34,7 @@ standards poller --print-units --config <path>
31
34
  ## Configuration
32
35
 
33
36
  - **`.github/dependabot.local.yml`** (optional) — repo-owned Dependabot extension composed with the canonical `.github/dependabot.base.yml` into the generated `.github/dependabot.yml`. May define `updates` and top-level `registries`; a block matching a canonical normalized target may only add `ignore` and/or `registries` entries. Other matching-block policy is rejected deliberately. A missing or comments-only file means no additions. CLI 0.10.1 requires the selected content ref to contain the canonical base and rejects older refs before mutation.
34
- - **`sync-standards.local.json`** (optional) — consumer-owned sync policy at the repo root, validated by `doctor`/`check` and every `init`/`sync` even when an explicit ref or local source makes its `"ref"` irrelevant. All fields optional; a missing file means the defaults. `"ref"` is a non-empty single-line string that pins a tag, branch, or full commit sha to sync from instead of `main` (an explicit `--ref` overrides it; a local-path `--from` source is used as-is and ignores only the validated pin). `"autoSync": false` is read by the standards-sync workflow, not the CLI, and skips the weekly scheduled run. Version 0.7.0 removes the legacy `STANDARDS_AUTO_SYNC` and `STANDARDS_SYNC_REF` variable behavior; consumers must upgrade the package and lockfile before adopting a policy file.
37
+ - **`sync-standards.local.json`** (optional) — consumer-owned sync policy at the repo root, validated by `doctor`/`check` and every `init`/`sync` even when an explicit ref or local source makes its `"ref"` irrelevant. All fields optional; a missing file means the defaults. `"ref"` is a non-empty single-line string that pins a tag, branch, or full commit sha to sync from instead of `main` (an explicit `--ref` overrides it; a local-path `--from` source is used as-is and ignores only the validated pin). `"autoSync": false` is read by the standards-sync workflow, not the CLI, and skips the weekly scheduled run; deliberate syncs then run locally because the secret-bearing workflow is schedule-only. Version 0.7.0 removes the legacy `STANDARDS_AUTO_SYNC` and `STANDARDS_SYNC_REF` variable behavior; consumers must upgrade the package and lockfile before adopting a policy file.
35
38
  - **`.github/settings.local.json` `"rulesetEnforcement": "unavailable-on-plan"`** (optional) — declares that the repository's GitHub plan cannot enforce rulesets (private repositories on GitHub Free, both personal accounts and organizations). `github --check` and `--apply` then skip rulesets instead of comparing them, because a comparison cannot be trusted there: personal accounts answer ruleset reads with HTTP 403, and free-plan organizations report declared rulesets as active while silently not enforcing them. Plan-gated repository settings that only function alongside branch protection (`allow_auto_merge`) are skipped for the same reason — GitHub accepts a PATCH for them with HTTP 200 and silently keeps the old value. The remaining repository merge settings are still checked and converged, and both commands print an unprotected-branch notice on every run. The only accepted value is `"unavailable-on-plan"` (enforcement is the default; omit the key on paid plans), and combining the opt-out with additional local rulesets is rejected. After upgrading the plan, remove the declaration and run `bun standards github --apply` to restore enforcement.
36
39
  - **Poller config file** (required for `poller`, passed via `--config`) — host-level JSON, deliberately not repository state. Required: `"repos"` (unique `owner/repo` strings — one poller watches any number of repositories), `"model"` and `"reasoningEffort"` (passed to `codex exec`; the model choice is deliberate and has no default). Optional: `"maxJobsPerTick"` (default 1 — the concurrency and rate-limit guard; subscription-authenticated Codex runs share the interactive rate window), `"staleClaimHours"` (default 6; must exceed `runTimeoutMinutes` so a sweep can never release the claim of a job that is still running), `"runTimeoutMinutes"` (default 240 — the timeout catches wedged agents, not honest multi-hour review runs), `"cacheDir"` (default `~/.cache/standards-poller`; holds bare mirrors and job worktrees; relative paths resolve against the config file), `"extraCodexArgs"` (extra `codex exec` arguments, e.g. enabling the collaboration feature for subagent fan-out). Unknown keys are rejected. The poller needs `git`, `codex` (authenticated — its rotating auth state must live in a writable location), and a GitHub token per the bullet below; the token needs issues, pull-requests, and contents write on the watched repos, and nothing else.
37
40
  - **`GH_TOKEN` / `GITHUB_TOKEN`** (optional) — GitHub API token for the `github` command and the GitHub portion of `check`. When neither is set, the token from the local `gh` CLI is used; with no token at all, reads still work on public repositories. `--apply` needs an admin token. GitHub's REST API reveals repo merge settings only to write-capable viewers — `check` retries REST-hidden keys over GraphQL, which serves them to read-only tokens — ruleset `bypass_actors` requires repository Administration read, and private-repository labels require Issues read (or Pull requests read); a token that still cannot see declared state fails the check rather than passing unverified. In CI, the canonical workflow decrypts `ci.github_settings_read_token` from the SOPS-encrypted `secrets/ci.yaml`: a repository-scoped fine-grained PAT with read-only "Administration" and "Issues" access.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@davidvornholt/standards",
3
- "version": "0.11.1",
3
+ "version": "0.12.0",
4
4
  "description": "Bootstrap, synchronize, and validate davidvornholt/standards consumers",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -24,6 +24,14 @@
24
24
  "src/dependabot-compose.ts",
25
25
  "src/dependabot-inspect.ts",
26
26
  "src/dependabot-update.ts",
27
+ "src/dev-env-document.ts",
28
+ "src/dev-env-destination-duplicates.ts",
29
+ "src/dev-env-destination.ts",
30
+ "src/dev-env-dotenv-value.ts",
31
+ "src/dev-env-dotenv.ts",
32
+ "src/dev-env-transaction-recovery.ts",
33
+ "src/dev-env-transaction.ts",
34
+ "src/dev-env.ts",
27
35
  "src/github-api.ts",
28
36
  "src/github-apply.ts",
29
37
  "src/github-command-shared.ts",
package/src/cli.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  DEPENDABOT_LOCAL_FILE,
25
25
  } from './dependabot-compose';
26
26
  import { inspectDependabot } from './dependabot-inspect';
27
+ import { runDevEnv } from './dev-env';
27
28
  import { CANONICAL_SETTINGS_FILE, LOCAL_SETTINGS_FILE } from './github-api';
28
29
  import { runGithubApply, runGithubCheck } from './github-commands';
29
30
  import { loadGithubSettings } from './github-settings';
@@ -66,6 +67,7 @@ type Source = {
66
67
  type Command =
67
68
  | 'check'
68
69
  | 'dependabot'
70
+ | 'dev-env'
69
71
  | 'doctor'
70
72
  | 'github'
71
73
  | 'help'
@@ -736,6 +738,7 @@ Commands:
736
738
  doctor Validate extension seams only
737
739
  structure Validate monorepo structure rules only
738
740
  dependabot Verify (--check) or regenerate (--write) the composed .github/dependabot.yml
741
+ dev-env Write each workspace's generated .env.local from the SOPS-encrypted secrets/dev.yaml
739
742
  github Compare (--check) or converge (--apply) live GitHub settings
740
743
  poller Run one fix-poller tick over the configured repositories (host automation)
741
744
  help Show this help
@@ -756,6 +759,7 @@ const commandFromArg = (arg: string): Command => {
756
759
  if (
757
760
  arg === 'check' ||
758
761
  arg === 'dependabot' ||
762
+ arg === 'dev-env' ||
759
763
  arg === 'doctor' ||
760
764
  arg === 'github' ||
761
765
  arg === 'help' ||
@@ -984,8 +988,8 @@ const runGithubCheckGate = (consumer: string): Promise<boolean> => {
984
988
  // standards-sync workflow it configures — versioned and reviewable, unlike
985
989
  // repository Actions variables. All fields are optional; a missing file means
986
990
  // the defaults (track main, weekly auto-sync on).
987
- // autoSync false skips the scheduled workflow run; manual dispatch and
988
- // local CLI runs are deliberate acts and always proceed.
991
+ // autoSync false skips the scheduled workflow run; local CLI runs remain
992
+ // the deliberate sync path.
989
993
  // ref tag, branch, or full commit sha to sync from instead of main.
990
994
  const POLICY_FILE = 'sync-standards.local.json';
991
995
  const LINE_BREAK = /[\r\n]/u;
@@ -1108,7 +1112,13 @@ const runSyncCommand = async (
1108
1112
 
1109
1113
  // Commands whose success is reported through the exit code.
1110
1114
  const runGateCommand = (
1111
- command: 'check' | 'dependabot' | 'doctor' | 'github' | 'structure',
1115
+ command:
1116
+ | 'check'
1117
+ | 'dependabot'
1118
+ | 'dev-env'
1119
+ | 'doctor'
1120
+ | 'github'
1121
+ | 'structure',
1112
1122
  consumer: string,
1113
1123
  apply: boolean,
1114
1124
  profile: StructureProfile,
@@ -1119,6 +1129,9 @@ const runGateCommand = (
1119
1129
  if (command === 'dependabot') {
1120
1130
  return runDependabotCheck(consumer);
1121
1131
  }
1132
+ if (command === 'dev-env') {
1133
+ return runDevEnv(consumer);
1134
+ }
1122
1135
  if (command === 'doctor') {
1123
1136
  return runDoctor(consumer);
1124
1137
  }
@@ -0,0 +1,32 @@
1
+ import { resolve } from 'node:path';
2
+ import type { DevEnvWrite } from './dev-env-destination';
3
+
4
+ export const duplicateDestinationProblems = (
5
+ root: string,
6
+ writes: ReadonlyArray<DevEnvWrite>,
7
+ ): ReadonlyArray<string> => {
8
+ const rawDuplicates = writes.flatMap((write, index) => {
9
+ const firstIndex = writes.findIndex(({ rel }) => rel === write.rel);
10
+ return firstIndex < index
11
+ ? [`${write.rel} is declared more than once`]
12
+ : [];
13
+ });
14
+ const resolved = writes.map((write) => ({
15
+ write,
16
+ dest: resolve(root, write.rel),
17
+ }));
18
+ const normalizedDuplicates = resolved.flatMap((destination, index) => {
19
+ const firstIndex = resolved.findIndex(
20
+ ({ dest }) => dest === destination.dest,
21
+ );
22
+ const first = resolved[firstIndex];
23
+ return firstIndex < index &&
24
+ first !== undefined &&
25
+ first.write.rel !== destination.write.rel
26
+ ? [
27
+ `${destination.write.rel} resolves to the same destination as ${first.write.rel}`,
28
+ ]
29
+ : [];
30
+ });
31
+ return [...rawDuplicates, ...normalizedDuplicates];
32
+ };
@@ -0,0 +1,175 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { Stats } from 'node:fs';
3
+ import { lstat, realpath } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { duplicateDestinationProblems } from './dev-env-destination-duplicates';
6
+
7
+ export type DevEnvWrite = {
8
+ readonly rel: string;
9
+ readonly content: string;
10
+ };
11
+
12
+ type DevEnvPathIdentity = {
13
+ readonly path: string;
14
+ readonly device: number;
15
+ readonly inode: number;
16
+ };
17
+
18
+ export type DevEnvDestination = {
19
+ readonly write: DevEnvWrite;
20
+ readonly dest: string;
21
+ readonly previous: Stats | null;
22
+ readonly temp: string;
23
+ readonly backup: string;
24
+ readonly parents: ReadonlyArray<DevEnvPathIdentity>;
25
+ readonly realParent: string;
26
+ readonly realRoot: string;
27
+ backupCreated: boolean;
28
+ committed: boolean;
29
+ };
30
+
31
+ type PreflightResult =
32
+ | {
33
+ readonly ok: true;
34
+ readonly destinations: ReadonlyArray<DevEnvDestination>;
35
+ }
36
+ | { readonly ok: false; readonly problems: ReadonlyArray<string> };
37
+
38
+ const containedBy = (root: string, candidate: string): boolean => {
39
+ const rel = relative(root, candidate);
40
+ return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
41
+ };
42
+
43
+ export const devEnvStatOrNull = async (path: string): Promise<Stats | null> => {
44
+ try {
45
+ return await lstat(path);
46
+ } catch (error) {
47
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
48
+ return null;
49
+ }
50
+ throw error;
51
+ }
52
+ };
53
+
54
+ const inspectDestination = async (
55
+ root: string,
56
+ realRoot: string,
57
+ write: DevEnvWrite,
58
+ ): Promise<string | DevEnvDestination> => {
59
+ const dest = resolve(root, write.rel);
60
+ if (!containedBy(root, dest)) {
61
+ return `${write.rel} escapes the consumer repository`;
62
+ }
63
+ const paths = dirname(write.rel)
64
+ .split(sep)
65
+ .map((_segment, index, segments) =>
66
+ join(root, ...segments.slice(0, index + 1)),
67
+ );
68
+ const parentPaths = [root, ...paths];
69
+ const parents = await Promise.all(parentPaths.map(devEnvStatOrNull));
70
+ if (
71
+ parents.some(
72
+ (entry) =>
73
+ entry === null || !entry.isDirectory() || entry.isSymbolicLink(),
74
+ )
75
+ ) {
76
+ return `${write.rel} has an unsafe destination directory`;
77
+ }
78
+ const realParent = await realpath(dirname(dest));
79
+ if (!containedBy(realRoot, realParent)) {
80
+ return `${write.rel} resolves outside the consumer repository`;
81
+ }
82
+ const previous = await devEnvStatOrNull(dest);
83
+ if (previous !== null && (!previous.isFile() || previous.isSymbolicLink())) {
84
+ return `${write.rel} must be absent or a regular file, not a symlink or other file type`;
85
+ }
86
+ const suffix = randomUUID();
87
+ return {
88
+ write,
89
+ dest,
90
+ previous,
91
+ temp: join(dirname(dest), `.env.local.standards-${suffix}.tmp`),
92
+ backup: join(dirname(dest), `.env.local.standards-${suffix}.bak`),
93
+ parents: parents.map((entry, index) => ({
94
+ path: parentPaths[index] ?? root,
95
+ device: entry?.dev ?? 0,
96
+ inode: entry?.ino ?? 0,
97
+ })),
98
+ realParent,
99
+ realRoot,
100
+ backupCreated: false,
101
+ committed: false,
102
+ };
103
+ };
104
+
105
+ export const preflightDevEnvDestinations = async (
106
+ consumer: string,
107
+ writes: ReadonlyArray<DevEnvWrite>,
108
+ ): Promise<PreflightResult> => {
109
+ const root = resolve(consumer);
110
+ const realRoot = await realpath(root);
111
+ const duplicates = duplicateDestinationProblems(root, writes);
112
+ const checked = await Promise.all(
113
+ writes.map(async (write) => {
114
+ try {
115
+ return await inspectDestination(root, realRoot, write);
116
+ } catch (error) {
117
+ const detail = error instanceof Error ? error.message : String(error);
118
+ return `${write.rel} could not be preflighted: ${detail}`;
119
+ }
120
+ }),
121
+ );
122
+ const destinations = checked.filter(
123
+ (item): item is DevEnvDestination => typeof item !== 'string',
124
+ );
125
+ const problems = [
126
+ ...duplicates,
127
+ ...checked.filter((item): item is string => typeof item === 'string'),
128
+ ];
129
+ return problems.length > 0
130
+ ? { ok: false, problems }
131
+ : {
132
+ ok: true,
133
+ destinations,
134
+ };
135
+ };
136
+
137
+ export const devEnvParentProblem = async (
138
+ destination: DevEnvDestination,
139
+ ): Promise<string | null> => {
140
+ try {
141
+ const current = await Promise.all(
142
+ destination.parents.map(async (parent) => ({
143
+ expected: parent,
144
+ actual: await devEnvStatOrNull(parent.path),
145
+ })),
146
+ );
147
+ const changed = current.some(
148
+ ({ expected, actual }) =>
149
+ actual === null ||
150
+ !actual.isDirectory() ||
151
+ actual.isSymbolicLink() ||
152
+ actual.dev !== expected.device ||
153
+ actual.ino !== expected.inode,
154
+ );
155
+ const realParent = await realpath(dirname(destination.dest));
156
+ if (
157
+ changed ||
158
+ realParent !== destination.realParent ||
159
+ !containedBy(destination.realRoot, realParent)
160
+ ) {
161
+ return `${destination.write.rel} destination directory changed after preflight`;
162
+ }
163
+ return null;
164
+ } catch {
165
+ return `${destination.write.rel} destination directory changed after preflight`;
166
+ }
167
+ };
168
+
169
+ export const devEnvDestinationProblems = async (
170
+ consumer: string,
171
+ writes: ReadonlyArray<DevEnvWrite>,
172
+ ): Promise<ReadonlyArray<string>> => {
173
+ const checked = await preflightDevEnvDestinations(consumer, writes);
174
+ return checked.ok ? [] : checked.problems;
175
+ };
@@ -0,0 +1,117 @@
1
+ // Workspace-group keyed dev secrets document: `apps.<name>` and
2
+ // `packages.<name>` map env keys to string values — the shape mirrored in
3
+ // secrets/dev.example.yaml. Parsing gathers every problem instead of failing
4
+ // on the first one so a malformed document is repaired in one pass.
5
+
6
+ import { encodeBunDotenvValue } from './dev-env-dotenv-value';
7
+ import { isRecord } from './github-settings-parse';
8
+
9
+ export type EnvValues = Readonly<Record<string, string>>;
10
+
11
+ export type DevEnvTarget = {
12
+ readonly group: string;
13
+ readonly workspace: string;
14
+ readonly env: EnvValues;
15
+ };
16
+
17
+ export type DevEnvDocument = {
18
+ readonly targets: ReadonlyArray<DevEnvTarget>;
19
+ readonly problems: ReadonlyArray<string>;
20
+ };
21
+
22
+ const WORKSPACE_GROUPS: ReadonlyArray<string> = ['apps', 'packages'];
23
+ const PORTABLE_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;
24
+ const WORKSPACE_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
25
+
26
+ type ParsedWorkspaces = {
27
+ readonly targets: ReadonlyArray<DevEnvTarget>;
28
+ readonly problems: ReadonlyArray<string>;
29
+ };
30
+
31
+ const parseWorkspaceEnv = (
32
+ label: string,
33
+ raw: Record<string, unknown>,
34
+ ): { readonly env: EnvValues; readonly problems: ReadonlyArray<string> } => {
35
+ const problems: Array<string> = [];
36
+ const entries: Array<readonly [string, string]> = [];
37
+ for (const [key, value] of Object.entries(raw)) {
38
+ const portableName = PORTABLE_ENV_NAME.test(key);
39
+ if (!portableName) {
40
+ problems.push(
41
+ `${label} env key ${JSON.stringify(key)} must be a portable environment variable name`,
42
+ );
43
+ }
44
+ if (typeof value !== 'string') {
45
+ problems.push(`${label}.${key} must be a string value`);
46
+ } else if (encodeBunDotenvValue(value) === null) {
47
+ problems.push(
48
+ `${label}.${key} cannot be represented losslessly in Bun dotenv syntax`,
49
+ );
50
+ } else if (portableName) {
51
+ entries.push([key, value]);
52
+ }
53
+ }
54
+ return { env: Object.fromEntries(entries), problems };
55
+ };
56
+
57
+ const parseWorkspaces = (
58
+ source: string,
59
+ group: string,
60
+ workspaces: Record<string, unknown>,
61
+ ): ParsedWorkspaces => {
62
+ const problems: Array<string> = [];
63
+ const targets: Array<DevEnvTarget> = [];
64
+ for (const [workspace, env] of Object.entries(workspaces)) {
65
+ const validWorkspace = WORKSPACE_NAME.test(workspace);
66
+ if (!validWorkspace) {
67
+ problems.push(
68
+ `${source} ${JSON.stringify(`${group}.${workspace}`)} workspace name must be one kebab-case path segment`,
69
+ );
70
+ }
71
+ if (isRecord(env)) {
72
+ const parsed = parseWorkspaceEnv(
73
+ `${source} "${group}.${workspace}"`,
74
+ env,
75
+ );
76
+ problems.push(...parsed.problems);
77
+ if (validWorkspace) {
78
+ targets.push({ group, workspace, env: parsed.env });
79
+ }
80
+ } else {
81
+ problems.push(
82
+ `${source} "${group}.${workspace}" must map env keys to string values`,
83
+ );
84
+ }
85
+ }
86
+ return { targets, problems };
87
+ };
88
+
89
+ export const parseDevEnvDocument = (
90
+ raw: unknown,
91
+ source: string,
92
+ ): DevEnvDocument => {
93
+ if (!isRecord(raw)) {
94
+ return {
95
+ targets: [],
96
+ problems: [`${source} must decrypt to a YAML object`],
97
+ };
98
+ }
99
+ const problems: Array<string> = [];
100
+ const targets: Array<DevEnvTarget> = [];
101
+ for (const [group, workspaces] of Object.entries(raw)) {
102
+ if (!WORKSPACE_GROUPS.includes(group)) {
103
+ problems.push(
104
+ `${source} top-level key "${group}" must be "apps" or "packages"`,
105
+ );
106
+ } else if (isRecord(workspaces)) {
107
+ const parsed = parseWorkspaces(source, group, workspaces);
108
+ problems.push(...parsed.problems);
109
+ targets.push(...parsed.targets);
110
+ } else {
111
+ problems.push(
112
+ `${source} "${group}" must map workspace names to env objects`,
113
+ );
114
+ }
115
+ }
116
+ return { targets, problems };
117
+ };
@@ -0,0 +1,51 @@
1
+ const EMPTY_EXPANSION = ['$', '{:-}'].join('');
2
+ const QUOTED_BACKSLASH_HAZARD = /\\(?:[nr]|\r|\n)/u;
3
+ const EDGE_BACKSLASH = /\\$/u;
4
+ const UNQUOTED_BODY_HAZARD = /[#\r\n]/u;
5
+ const EDGE_DOLLAR = /\$$/u;
6
+ const EDGE_WHITESPACE = /\s$/u;
7
+
8
+ const escapeDollars = (value: string): string => value.replaceAll('$', '\\$');
9
+
10
+ const terminalDollarExpansion = (value: string): string =>
11
+ EDGE_DOLLAR.test(value) ? EMPTY_EXPANSION : '';
12
+
13
+ const encodeUnquoted = (value: string): string | null => {
14
+ if (UNQUOTED_BODY_HAZARD.test(value)) {
15
+ return null;
16
+ }
17
+ const terminator =
18
+ EDGE_WHITESPACE.test(value) || EDGE_DOLLAR.test(value)
19
+ ? EMPTY_EXPANSION
20
+ : '#';
21
+ return `${EMPTY_EXPANSION}${escapeDollars(value)}${terminator}`;
22
+ };
23
+
24
+ const encodeDoubleQuoted = (value: string): string | null => {
25
+ if (
26
+ value.includes('"') ||
27
+ EDGE_BACKSLASH.test(value) ||
28
+ QUOTED_BACKSLASH_HAZARD.test(value)
29
+ ) {
30
+ return null;
31
+ }
32
+ return `"${escapeDollars(value)
33
+ .replaceAll('\r', '\\r')
34
+ .replaceAll('\n', '\\n')}${terminalDollarExpansion(value)}"`;
35
+ };
36
+
37
+ const encodeLiteralQuoted = (
38
+ value: string,
39
+ delimiter: "'" | '`',
40
+ ): string | null =>
41
+ value.includes(delimiter) ||
42
+ value.includes('\r') ||
43
+ EDGE_BACKSLASH.test(value)
44
+ ? null
45
+ : `${delimiter}${escapeDollars(value)}${terminalDollarExpansion(value)}${delimiter}`;
46
+
47
+ export const encodeBunDotenvValue = (value: string): string | null =>
48
+ encodeUnquoted(value) ??
49
+ encodeDoubleQuoted(value) ??
50
+ encodeLiteralQuoted(value, "'") ??
51
+ encodeLiteralQuoted(value, '`');
@@ -0,0 +1,22 @@
1
+ import type { EnvValues } from './dev-env-document';
2
+ import { encodeBunDotenvValue } from './dev-env-dotenv-value';
3
+
4
+ const renderValue = (key: string, value: string): string => {
5
+ const encoded = encodeBunDotenvValue(value);
6
+ if (encoded === null) {
7
+ throw new Error(`${key} was not validated for Bun dotenv rendering`);
8
+ }
9
+ return `${key}=${encoded}`;
10
+ };
11
+
12
+ export const renderDotenv = (
13
+ sourcePath: string,
14
+ secretsFile: string,
15
+ env: EnvValues,
16
+ ): string =>
17
+ [
18
+ '# Generated by `bun standards dev-env` (just dev-env-generate). Do not edit.',
19
+ `# Source: ${secretsFile} (${sourcePath})`,
20
+ ...Object.entries(env).map(([key, value]) => renderValue(key, value)),
21
+ '',
22
+ ].join('\n');
@@ -0,0 +1,80 @@
1
+ import { rename, rm } from 'node:fs/promises';
2
+ import {
3
+ type DevEnvDestination,
4
+ devEnvParentProblem,
5
+ } from './dev-env-destination';
6
+
7
+ const message = (error: unknown): string =>
8
+ error instanceof Error ? error.message : String(error);
9
+
10
+ const requireParent = async (
11
+ destination: DevEnvDestination,
12
+ ): Promise<string | null> => devEnvParentProblem(destination);
13
+
14
+ const rollbackOne = async (
15
+ destination: DevEnvDestination,
16
+ ): Promise<ReadonlyArray<string>> => {
17
+ const problems: Array<string> = [];
18
+ if (destination.committed) {
19
+ const parentProblem = await requireParent(destination);
20
+ if (parentProblem !== null) {
21
+ return [parentProblem];
22
+ }
23
+ try {
24
+ await rm(destination.dest, { force: true });
25
+ destination.committed = false;
26
+ } catch (error) {
27
+ problems.push(`${destination.write.rel}: ${message(error)}`);
28
+ }
29
+ }
30
+ if (destination.backupCreated && problems.length === 0) {
31
+ const parentProblem = await requireParent(destination);
32
+ if (parentProblem !== null) {
33
+ return [parentProblem];
34
+ }
35
+ try {
36
+ await rename(destination.backup, destination.dest);
37
+ destination.backupCreated = false;
38
+ } catch (error) {
39
+ problems.push(`${destination.write.rel}: ${message(error)}`);
40
+ }
41
+ }
42
+ return problems;
43
+ };
44
+
45
+ export const rollbackDevEnvFiles = async (
46
+ destinations: ReadonlyArray<DevEnvDestination>,
47
+ ): Promise<ReadonlyArray<string>> => {
48
+ const outcomes = await Promise.all(destinations.map(rollbackOne));
49
+ return outcomes.flat();
50
+ };
51
+
52
+ const cleanupOne = async (
53
+ destination: DevEnvDestination,
54
+ preserveBackups: boolean,
55
+ ): Promise<ReadonlyArray<string>> => {
56
+ const parentProblem = await requireParent(destination);
57
+ if (parentProblem !== null) {
58
+ return [parentProblem];
59
+ }
60
+ const paths = [destination.temp];
61
+ if (!preserveBackups) {
62
+ paths.push(destination.backup);
63
+ }
64
+ const outcomes = await Promise.allSettled(
65
+ paths.map((path) => rm(path, { force: true })),
66
+ );
67
+ return outcomes.flatMap((outcome) =>
68
+ outcome.status === 'rejected' ? [message(outcome.reason)] : [],
69
+ );
70
+ };
71
+
72
+ export const cleanupDevEnvArtifacts = async (
73
+ destinations: ReadonlyArray<DevEnvDestination>,
74
+ preserveBackups: boolean,
75
+ ): Promise<ReadonlyArray<string>> => {
76
+ const outcomes = await Promise.all(
77
+ destinations.map((destination) => cleanupOne(destination, preserveBackups)),
78
+ );
79
+ return outcomes.flat();
80
+ };
@@ -0,0 +1,152 @@
1
+ import { link, open, rename } from 'node:fs/promises';
2
+ import {
3
+ type DevEnvDestination,
4
+ type DevEnvWrite,
5
+ devEnvParentProblem,
6
+ devEnvStatOrNull,
7
+ preflightDevEnvDestinations,
8
+ } from './dev-env-destination';
9
+ import {
10
+ cleanupDevEnvArtifacts,
11
+ rollbackDevEnvFiles,
12
+ } from './dev-env-transaction-recovery';
13
+
14
+ const OWNER_ONLY_FILE_MODE = 0o600;
15
+
16
+ export type DevEnvTransactionHooks = {
17
+ readonly beforeStage?: (index: number) => void | Promise<void>;
18
+ readonly beforeCommit?: (index: number) => void | Promise<void>;
19
+ readonly beforeCleanup?: () => void | Promise<void>;
20
+ };
21
+
22
+ export type DevEnvTransactionResult =
23
+ | { readonly ok: true; readonly warnings: ReadonlyArray<string> }
24
+ | { readonly ok: false; readonly problems: ReadonlyArray<string> };
25
+
26
+ const requireParent = async (destination: DevEnvDestination): Promise<void> => {
27
+ const problem = await devEnvParentProblem(destination);
28
+ if (problem !== null) {
29
+ throw new Error(problem);
30
+ }
31
+ };
32
+
33
+ const stage = async (destination: DevEnvDestination): Promise<void> => {
34
+ await requireParent(destination);
35
+ const file = await open(destination.temp, 'wx', OWNER_ONLY_FILE_MODE);
36
+ try {
37
+ await file.chmod(OWNER_ONLY_FILE_MODE);
38
+ await file.writeFile(destination.write.content, 'utf8');
39
+ await file.sync();
40
+ } finally {
41
+ await file.close();
42
+ }
43
+ };
44
+
45
+ const unchanged = async (destination: DevEnvDestination): Promise<boolean> => {
46
+ const current = await devEnvStatOrNull(destination.dest);
47
+ if (current === null || destination.previous === null) {
48
+ return current === destination.previous;
49
+ }
50
+ return (
51
+ current.isFile() &&
52
+ !current.isSymbolicLink() &&
53
+ current.dev === destination.previous.dev &&
54
+ current.ino === destination.previous.ino &&
55
+ current.mode === destination.previous.mode
56
+ );
57
+ };
58
+
59
+ const stageAll = async (
60
+ destinations: ReadonlyArray<DevEnvDestination>,
61
+ hooks: DevEnvTransactionHooks,
62
+ ): Promise<void> => {
63
+ await destinations.reduce<Promise<void>>(
64
+ async (previous, destination, index) => {
65
+ await previous;
66
+ await hooks.beforeStage?.(index);
67
+ await stage(destination);
68
+ },
69
+ Promise.resolve(),
70
+ );
71
+ };
72
+
73
+ const commitOne = async (destination: DevEnvDestination): Promise<void> => {
74
+ await requireParent(destination);
75
+ if (!(await unchanged(destination))) {
76
+ throw new Error(`${destination.write.rel} changed after preflight`);
77
+ }
78
+ if (destination.previous !== null) {
79
+ await requireParent(destination);
80
+ await link(destination.dest, destination.backup);
81
+ destination.backupCreated = true;
82
+ }
83
+ await requireParent(destination);
84
+ await rename(destination.temp, destination.dest);
85
+ destination.committed = true;
86
+ };
87
+
88
+ const commitAll = async (
89
+ destinations: ReadonlyArray<DevEnvDestination>,
90
+ hooks: DevEnvTransactionHooks,
91
+ ): Promise<void> => {
92
+ await destinations.reduce<Promise<void>>(
93
+ async (previous, destination, index) => {
94
+ await previous;
95
+ await hooks.beforeCommit?.(index);
96
+ await commitOne(destination);
97
+ },
98
+ Promise.resolve(),
99
+ );
100
+ };
101
+
102
+ const problemMessage = (error: unknown): string =>
103
+ error instanceof Error ? error.message : String(error);
104
+
105
+ const recoverFailure = async (
106
+ destinations: ReadonlyArray<DevEnvDestination>,
107
+ error: unknown,
108
+ ): Promise<DevEnvTransactionResult> => {
109
+ const rollbackProblems = await rollbackDevEnvFiles(destinations);
110
+ const cleanupProblems = await cleanupDevEnvArtifacts(
111
+ destinations,
112
+ rollbackProblems.length > 0,
113
+ );
114
+ return {
115
+ ok: false,
116
+ problems: [
117
+ problemMessage(error),
118
+ ...rollbackProblems.map((problem) => `rollback failed: ${problem}`),
119
+ ...cleanupProblems.map((problem) => `cleanup failed: ${problem}`),
120
+ ],
121
+ };
122
+ };
123
+
124
+ export const writeDevEnvFiles = async (
125
+ consumer: string,
126
+ writes: ReadonlyArray<DevEnvWrite>,
127
+ hooks: DevEnvTransactionHooks = {},
128
+ ): Promise<DevEnvTransactionResult> => {
129
+ const checked = await preflightDevEnvDestinations(consumer, writes);
130
+ if (!checked.ok) {
131
+ return checked;
132
+ }
133
+ try {
134
+ await stageAll(checked.destinations, hooks);
135
+ await commitAll(checked.destinations, hooks);
136
+ } catch (error) {
137
+ return recoverFailure(checked.destinations, error);
138
+ }
139
+ let cleanupProblems: ReadonlyArray<string>;
140
+ try {
141
+ await hooks.beforeCleanup?.();
142
+ cleanupProblems = await cleanupDevEnvArtifacts(checked.destinations, false);
143
+ } catch (error) {
144
+ cleanupProblems = [problemMessage(error)];
145
+ }
146
+ return {
147
+ ok: true,
148
+ warnings: cleanupProblems.map(
149
+ (problem) => `generation committed but cleanup failed: ${problem}`,
150
+ ),
151
+ };
152
+ };
package/src/dev-env.ts ADDED
@@ -0,0 +1,165 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import {
5
+ type DevEnvWrite,
6
+ devEnvDestinationProblems,
7
+ } from './dev-env-destination';
8
+ import { parseDevEnvDocument } from './dev-env-document';
9
+ import { renderDotenv } from './dev-env-dotenv';
10
+ import { writeDevEnvFiles } from './dev-env-transaction';
11
+
12
+ export const DEV_SECRETS_FILE = 'secrets/dev.yaml';
13
+
14
+ const SOPS_ARGS = ['--decrypt', '--output-type', 'json', DEV_SECRETS_FILE];
15
+
16
+ type DecryptResult =
17
+ | { readonly ok: true; readonly value: unknown }
18
+ | { readonly ok: false; readonly problem: string };
19
+
20
+ // sops emits JSON here so the CLI never parses the encrypted YAML itself; the
21
+ // nix fallback mirrors the canonical secrets.just tool resolution.
22
+ const decryptDevSecrets = (consumer: string): DecryptResult => {
23
+ const localSops = spawnSync('sops', SOPS_ARGS, {
24
+ cwd: consumer,
25
+ encoding: 'utf8',
26
+ });
27
+ const result =
28
+ localSops.error === undefined && localSops.status !== null
29
+ ? localSops
30
+ : spawnSync(
31
+ 'nix',
32
+ [
33
+ '--extra-experimental-features',
34
+ 'nix-command flakes',
35
+ 'run',
36
+ 'nixpkgs#sops',
37
+ '--',
38
+ ...SOPS_ARGS,
39
+ ],
40
+ { cwd: consumer, encoding: 'utf8' },
41
+ );
42
+ if (result.status !== 0) {
43
+ const detail = result.error?.message ?? result.stderr?.trim();
44
+ return {
45
+ ok: false,
46
+ problem: detail
47
+ ? `could not decrypt ${DEV_SECRETS_FILE}: ${detail}`
48
+ : `could not decrypt ${DEV_SECRETS_FILE}`,
49
+ };
50
+ }
51
+ try {
52
+ return { ok: true, value: JSON.parse(result.stdout) as unknown };
53
+ } catch (error) {
54
+ return {
55
+ ok: false,
56
+ problem: `could not parse decrypted ${DEV_SECRETS_FILE} as JSON: ${
57
+ error instanceof Error ? error.message : String(error)
58
+ }`,
59
+ };
60
+ }
61
+ };
62
+
63
+ // Writing decrypted values into the tree is only safe when git will never
64
+ // track them. `git check-ignore` is authoritative; anything but a clear
65
+ // "ignored" answer fails closed, including running outside a git checkout.
66
+ const gitIgnoreProblem = (consumer: string, rel: string): string | null => {
67
+ const result = spawnSync('git', ['check-ignore', '-q', '--', rel], {
68
+ cwd: consumer,
69
+ });
70
+ if (result.error !== undefined || result.status === null) {
71
+ return `cannot run git to verify ${rel} is gitignored`;
72
+ }
73
+ if (result.status === 0) {
74
+ return null;
75
+ }
76
+ if (result.status === 1) {
77
+ return `${rel} is not gitignored; ignore it before generating dev env files`;
78
+ }
79
+ return `cannot verify ${rel} is gitignored (git check-ignore exited ${result.status})`;
80
+ };
81
+
82
+ export type DevEnvPlan = {
83
+ readonly writes: ReadonlyArray<DevEnvWrite>;
84
+ readonly problems: ReadonlyArray<string>;
85
+ };
86
+
87
+ export const planDevEnvWrites = (
88
+ consumer: string,
89
+ raw: unknown,
90
+ ): DevEnvPlan => {
91
+ const document = parseDevEnvDocument(raw, DEV_SECRETS_FILE);
92
+ const problems: Array<string> = [...document.problems];
93
+ const writes: Array<DevEnvWrite> = [];
94
+ for (const target of document.targets) {
95
+ const workspaceDir = `${target.group}/${target.workspace}`;
96
+ const rel = `${workspaceDir}/.env.local`;
97
+ if (existsSync(join(consumer, workspaceDir, 'package.json'))) {
98
+ const ignoreProblem = gitIgnoreProblem(consumer, rel);
99
+ if (ignoreProblem === null) {
100
+ writes.push({
101
+ rel,
102
+ content: renderDotenv(
103
+ `${target.group}.${target.workspace}`,
104
+ DEV_SECRETS_FILE,
105
+ target.env,
106
+ ),
107
+ });
108
+ } else {
109
+ problems.push(ignoreProblem);
110
+ }
111
+ } else {
112
+ problems.push(
113
+ `${DEV_SECRETS_FILE} defines ${target.group}.${target.workspace}, but ${workspaceDir}/package.json does not exist`,
114
+ );
115
+ }
116
+ }
117
+ return { writes, problems };
118
+ };
119
+
120
+ export const runDevEnv = async (consumer: string): Promise<boolean> => {
121
+ if (!existsSync(join(consumer, DEV_SECRETS_FILE))) {
122
+ console.error(
123
+ `standards dev-env: ${DEV_SECRETS_FILE} not found; create it with \`just secrets edit dev\``,
124
+ );
125
+ return false;
126
+ }
127
+ const decrypted = decryptDevSecrets(consumer);
128
+ if (!decrypted.ok) {
129
+ console.error(`standards dev-env: ${decrypted.problem}`);
130
+ return false;
131
+ }
132
+ const plan = planDevEnvWrites(consumer, decrypted.value);
133
+ const problems = [
134
+ ...plan.problems,
135
+ ...(await devEnvDestinationProblems(consumer, plan.writes)),
136
+ ];
137
+ if (problems.length > 0) {
138
+ console.error(`standards dev-env: ${problems.length} problem(s):`);
139
+ console.error(problems.map((problem) => ` - ${problem}`).join('\n'));
140
+ return false;
141
+ }
142
+ const generated = await writeDevEnvFiles(consumer, plan.writes);
143
+ if (!generated.ok) {
144
+ console.error('standards dev-env: generation failed:');
145
+ console.error(
146
+ generated.problems.map((problem) => ` - ${problem}`).join('\n'),
147
+ );
148
+ return false;
149
+ }
150
+ if (generated.warnings.length > 0) {
151
+ console.error(
152
+ `standards dev-env: generated files with ${generated.warnings.length} cleanup warning(s):`,
153
+ );
154
+ console.error(
155
+ generated.warnings.map((warning) => ` - ${warning}`).join('\n'),
156
+ );
157
+ }
158
+ for (const write of plan.writes) {
159
+ console.log(` wrote ${write.rel}`);
160
+ }
161
+ console.log(
162
+ `standards dev-env: generated ${plan.writes.length} env file(s) from ${DEV_SECRETS_FILE}`,
163
+ );
164
+ return true;
165
+ };