@ultimat3/cli 31.26.0 → 31.28.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/CLAUDE.md +47 -37
- package/README.md +19 -8
- package/package.json +29 -29
- package/src/app-manifest.ts +6 -1
- package/src/app-mcp.ts +17 -3
- package/src/cmd-cache-spec.ts +5 -2
- package/src/cmd-db-spec.ts +2 -3
- package/src/cmd-db.ts +0 -2
- package/src/cmd-deploy-verify-sample.ts +93 -0
- package/src/cmd-deploy-verify.ts +2 -41
- package/src/cmd-dev-spec.ts +15 -1
- package/src/cmd-dev.ts +31 -4
- package/src/cmd-doctor.ts +15 -4
- package/src/cmd-exercise-spec.ts +7 -1
- package/src/cmd-exercise.ts +22 -10
- package/src/cmd-generate.ts +2 -0
- package/src/cmd-jobs-spec.ts +3 -6
- package/src/cmd-jobs.ts +1 -7
- package/src/cmd-logs-spec.ts +2 -1
- package/src/cmd-logs.ts +9 -28
- package/src/cmd-planned.ts +11 -45
- package/src/cmd-profile-frames.ts +99 -0
- package/src/cmd-profile-spec.ts +24 -0
- package/src/cmd-profile.ts +164 -0
- package/src/cmd-repro-spec.ts +13 -1
- package/src/cmd-repro.ts +37 -5
- package/src/cmd-status-sample.ts +57 -0
- package/src/cmd-status-spec.ts +30 -0
- package/src/cmd-status.ts +108 -0
- package/src/cmd-token-spec.ts +5 -2
- package/src/cmd-token.ts +7 -3
- package/src/cmd-upgrade-codemods.ts +71 -0
- package/src/cmd-upgrade-spec.ts +19 -5
- package/src/cmd-upgrade.ts +91 -34
- package/src/codemods/agents-dev-mcp.ts +50 -0
- package/src/codemods/authenticator-session-refusal.ts +214 -0
- package/src/codemods/biome-no-default-export.ts +58 -0
- package/src/codemods/bunfig-island-coverage.ts +33 -0
- package/src/codemods/chart-dashboard.ts +73 -0
- package/src/codemods/ci-e2e-browser-stock.ts +75 -0
- package/src/codemods/ci-e2e-browser.ts +63 -0
- package/src/codemods/codemod.ts +58 -0
- package/src/codemods/define-error-leaf.ts +73 -0
- package/src/codemods/docs-ci-parts.ts +65 -0
- package/src/codemods/docs-gate-prose.ts +53 -0
- package/src/codemods/docs-island-rows.ts +31 -0
- package/src/codemods/docs-shipped-guards.ts +100 -0
- package/src/codemods/docs-test-services.ts +62 -0
- package/src/codemods/engine-diff.ts +104 -0
- package/src/codemods/engine-edits.ts +111 -0
- package/src/codemods/engine-fs.ts +95 -0
- package/src/codemods/engine.ts +191 -0
- package/src/codemods/format-edited-hook-3122.ts +28 -0
- package/src/codemods/format-edited-hook.ts +152 -0
- package/src/codemods/helm-alerts-objective.ts +105 -0
- package/src/codemods/helm-alerts-stock.ts +108 -0
- package/src/codemods/index.ts +56 -0
- package/src/codemods/metrics-probe-healthz.ts +47 -0
- package/src/codemods/pending.ts +36 -0
- package/src/codemods/repro-gitignore.ts +40 -0
- package/src/codemods/runtime-pin-lines.ts +109 -0
- package/src/codemods/runtime-pin.ts +116 -0
- package/src/codemods/solid-floor.ts +63 -0
- package/src/codemods/test-ports.ts +86 -0
- package/src/codemods/test-suites.ts +37 -0
- package/src/codemods/theme-toggle-mount-over.ts +70 -0
- package/src/codemods/vendored-guards.ts +186 -0
- package/src/codemods/verify-floor-skips.ts +88 -0
- package/src/codemods/verify-floor-steps.ts +90 -0
- package/src/coverage-island.ts +121 -0
- package/src/coverage-lcov.ts +49 -5
- package/src/coverage-remap.ts +146 -0
- package/src/db-replay-engine-prepared.ts +66 -0
- package/src/db-replay-engine-template.ts +156 -0
- package/src/db-replay-engine.ts +4 -0
- package/src/db-replay-scratch-reap.ts +54 -0
- package/src/deploy-verify-flags.ts +9 -2
- package/src/deploy-verify-grade.ts +10 -3
- package/src/dev-boot.ts +14 -1
- package/src/dev-dashboard-guard.ts +57 -10
- package/src/dev-host.ts +46 -0
- package/src/dev-tls-cache.ts +103 -0
- package/src/dev-tls-der.ts +69 -0
- package/src/dev-tls.ts +120 -0
- package/src/doctor-advisory-floors.ts +113 -0
- package/src/doctor-browser.ts +60 -0
- package/src/doctor-guards.ts +39 -86
- package/src/doctor-superseded.ts +67 -0
- package/src/error-codes-doctor.ts +12 -4
- package/src/error-codes-verify.ts +47 -0
- package/src/error-codes.ts +20 -23
- package/src/exercise-database.ts +47 -9
- package/src/exercise-push-device.ts +51 -0
- package/src/exercise-route-api.ts +74 -0
- package/src/exercise-routes.ts +14 -5
- package/src/exercise-services.ts +3 -1
- package/src/exercise-shard-flag.ts +47 -0
- package/src/fix-command.ts +2 -2
- package/src/generate-factories.ts +5 -11
- package/src/generate-feature-required.ts +9 -4
- package/src/generate-files.ts +26 -7
- package/src/generate-kinds.ts +5 -1
- package/src/guards-built-in-codes.ts +36 -0
- package/src/guards-built-in-refusal.ts +25 -0
- package/src/guards-built-in.ts +134 -0
- package/src/guards-materialize.ts +42 -0
- package/src/guards-paths.ts +37 -0
- package/src/guards-shipped-names.ts +38 -0
- package/src/guards-vendored.ts +73 -0
- package/src/guards.ts +105 -34
- package/src/index.ts +10 -0
- package/src/island-bundle-options.ts +48 -0
- package/src/island-bundle.ts +18 -46
- package/src/island-link.ts +5 -0
- package/src/island-outputs.ts +5 -0
- package/src/lint-findings.ts +3 -3
- package/src/mcp-errors-verify.ts +35 -0
- package/src/mcp-errors.ts +21 -20
- package/src/mcp-host-logs.ts +121 -0
- package/src/mcp-host.ts +12 -73
- package/src/measure-scope.ts +23 -3
- package/src/messages-floor.ts +19 -0
- package/src/messages-repro.ts +16 -2
- package/src/messages-status.ts +10 -0
- package/src/messages-upgrade.ts +15 -0
- package/src/messages.ts +22 -1
- package/src/registry.ts +4 -0
- package/src/repro-archive-collect.ts +161 -0
- package/src/repro-archive-write.ts +96 -0
- package/src/repro-archive.ts +161 -0
- package/src/repro-bundle.ts +8 -16
- package/src/repro-errors.ts +14 -2
- package/src/repro-framework.ts +53 -0
- package/src/repro-parse.ts +87 -0
- package/src/repro-redact.ts +218 -0
- package/src/repro-scrub.ts +257 -0
- package/src/role-start-types.ts +7 -0
- package/src/role-start.ts +4 -0
- package/src/serve-boot.ts +7 -1
- package/src/serve-env-tls.ts +57 -0
- package/src/solid-loader.ts +27 -10
- package/src/superseded-match.ts +87 -0
- package/src/superseded.ts +84 -0
- package/src/templates/bun-image.ts +48 -0
- package/src/templates/generate-export-rows.ts +136 -0
- package/src/templates/generate-import-rows.ts +186 -0
- package/src/templates/generate-rows-slice.ts +95 -0
- package/src/templates/github/ci.yml.ts +5 -1
- package/src/templates/guard-released-forms.ts +112 -0
- package/src/templates/guard-runtime-pin-test.ts +54 -0
- package/src/templates/guard-runtime-pin.ts +189 -0
- package/src/templates/scaffold-claude-agents.ts +6 -6
- package/src/templates/scaffold-claude-commands.ts +1 -1
- package/src/templates/scaffold-claude-hook.ts +18 -8
- package/src/templates/scaffold-claude.ts +2 -2
- package/src/templates/scaffold-db-package.ts +3 -0
- package/src/templates/scaffold-docs.ts +34 -30
- package/src/templates/scaffold-guards.ts +73 -39
- package/src/templates/scaffold-repo.ts +4 -8
- package/src/templates/scaffold-site.ts +4 -1
- package/src/templates/scaffold-suites.ts +72 -0
- package/src/templates/scaffold-test-services.ts +35 -10
- package/src/templates/scaffold-verify-floor.ts +53 -31
- package/src/templates/shapes/api.ts +4 -0
- package/src/templates/slice-foundation.ts +3 -3
- package/src/unthrown-codes.ts +3 -1
- package/src/upgrade-bun-floor.ts +4 -0
- package/src/upgrade-clean-tree.ts +54 -0
- package/src/upgrade-gate-codemods-install.ts +40 -0
- package/src/upgrade-gate-codemods.ts +151 -0
- package/src/upgrade-gate.ts +44 -7
- package/src/upgrade-guards-baseline.ts +43 -0
- package/src/upgrade-guards.ts +37 -2
- package/src/upgrade-lock.ts +118 -0
- package/src/upgrade-plan.ts +2 -1
- package/src/upgrade-report-codemods.ts +54 -0
- package/src/upgrade-report.ts +55 -27
- package/src/upgrade-signals.ts +91 -0
- package/src/upgrade-unfinished.ts +61 -0
- package/src/verify-coverage-run.ts +42 -11
- package/src/verify-e2e.ts +115 -4
- package/src/verify-floor.ts +27 -0
- package/src/verify-guard-baseline.ts +109 -0
- package/src/verify-live.ts +72 -0
- package/src/verify-merge-skips.ts +51 -0
- package/src/verify-merge.ts +36 -2
- package/src/verify-run.ts +48 -7
- package/src/verify-services.ts +287 -0
- package/src/verify-skip-reason.ts +53 -0
- package/src/verify-strict.ts +108 -0
- package/src/verify-test-command.ts +129 -0
- package/src/verify-tests.ts +39 -126
- package/types/babel-modules.d.ts +2 -0
- package/wiki/CLI-Reference.md +200 -27
- package/wiki/Caching-And-Invalidation.md +1 -1
- package/wiki/Entities-And-Migrations.md +1 -1
- package/wiki/Interface-Rules.md +17 -8
- package/wiki/Jobs-And-Workflows.md +3 -3
- package/wiki/Known-Gaps.md +5 -1
- package/wiki/MCP-And-AI.md +1 -1
- package/wiki/Observability.md +1 -0
- package/wiki/PWA-And-Offline.md +1 -1
- package/wiki/Project-Layout.md +4 -4
- package/wiki/Troubleshooting.md +3 -3
- package/wiki/Tutorial-05-Deploy-Free.md +2 -2
- package/wiki/Upgrading.md +8 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// The Postgres half of a prepared scratch database: a template per key (`CREATE DATABASE …
|
|
2
|
+
// TEMPLATE`), built once under that key's advisory lock — polled to a deadline, never a statement
|
|
3
|
+
// the pool's timeout cancels — and a working clone per run, stamped so a killed run's is reaped.
|
|
4
|
+
|
|
5
|
+
import type { DbClient } from '@ultimat3/db';
|
|
6
|
+
import { DbError, postgresClient, raw, sql } from '@ultimat3/db';
|
|
7
|
+
import { reapScratch, stampScratch } from './db-replay-scratch-reap';
|
|
8
|
+
|
|
9
|
+
/** What a prepared scratch is: how to prepare one, and the hash of everything that decides it. */
|
|
10
|
+
export interface ScratchPreparation {
|
|
11
|
+
/** Hex digest of every input the preparation reads (schema DDL, migrations, extensions). */
|
|
12
|
+
readonly key: string;
|
|
13
|
+
readonly prepare: (client: DbClient) => Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Prepared states kept besides the newest: a branch switch back is a hit, and the disk bounded. */
|
|
17
|
+
export const PREPARED_KEEP = 2;
|
|
18
|
+
|
|
19
|
+
/** How long a run waits for another's build of the same key: a migration, never a seed. */
|
|
20
|
+
export const TEMPLATE_LOCK_WAIT_MS = 5 * 60 * 1000;
|
|
21
|
+
const TEMPLATE_LOCK_POLL_MS = 250;
|
|
22
|
+
|
|
23
|
+
/** A Postgres template's name for `key`: a prefix this module alone creates and drops. */
|
|
24
|
+
const TEMPLATE_PREFIX = 'x_scratch_tpl_';
|
|
25
|
+
/** Hex characters of the key a template's name carries. */
|
|
26
|
+
const KEY_CHARS = 24;
|
|
27
|
+
/** Exactly a template name, as a regular expression: never LIKE, whose `_` is any character. */
|
|
28
|
+
const TEMPLATE_NAME = `^${TEMPLATE_PREFIX}[0-9a-f]{${String(KEY_CHARS)}}$`;
|
|
29
|
+
export const templateNameFor = (key: string): string =>
|
|
30
|
+
`${TEMPLATE_PREFIX}${key.slice(0, KEY_CHARS)}`;
|
|
31
|
+
/** Where a template is built before it is renamed into place: a name eviction never matches. */
|
|
32
|
+
const buildPrefixFor = (key: string): string => `x_scratch_bld_${key.slice(0, KEY_CHARS)}_`;
|
|
33
|
+
|
|
34
|
+
const lockSql = (name: string) => sql`select pg_try_advisory_lock(hashtext(${name})) as held`;
|
|
35
|
+
const unlockSql = (name: string) => sql`select pg_advisory_unlock(hashtext(${name}))`;
|
|
36
|
+
|
|
37
|
+
type Admin = Pick<DbClient, 'one' | 'query' | 'execute'>;
|
|
38
|
+
|
|
39
|
+
/** The key's lock, polled: a builder may hold it for a whole migration, past any statement bound. */
|
|
40
|
+
async function acquire(session: Admin, template: string): Promise<void> {
|
|
41
|
+
const started = performance.now();
|
|
42
|
+
for (;;) {
|
|
43
|
+
const row = await session.one<{ held: boolean }>(lockSql(template));
|
|
44
|
+
if (row?.held === true) return;
|
|
45
|
+
const waited = Math.round(performance.now() - started);
|
|
46
|
+
if (waited >= TEMPLATE_LOCK_WAIT_MS) {
|
|
47
|
+
throw new DbError({
|
|
48
|
+
code: 'X_DB_LOCK_TIMEOUT',
|
|
49
|
+
cause: `another process held the build lock of scratch template ${template} for ${String(waited)} ms, so this run could not clone it`,
|
|
50
|
+
fix: `psql "$TEST_DATABASE_URL" -c "select pid, query from pg_stat_activity where datname like 'x_scratch_bld_%'" # then stop that run, or wait for it`,
|
|
51
|
+
meta: { template, waitedMs: waited },
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
await Bun.sleep(Math.min(TEMPLATE_LOCK_POLL_MS, TEMPLATE_LOCK_WAIT_MS - waited));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Every template of the exact name shape past the newest kept, each only while nobody holds it. */
|
|
59
|
+
async function evictTemplates(admin: Admin, current: string): Promise<void> {
|
|
60
|
+
const stale = await admin.query<{ datname: string }>(
|
|
61
|
+
sql`select datname from pg_database where datname ~ ${TEMPLATE_NAME} and datname <> ${current} order by oid desc`,
|
|
62
|
+
);
|
|
63
|
+
for (const { datname } of stale.slice(PREPARED_KEEP)) {
|
|
64
|
+
// A process cloning it holds its lock: skipped, never dropped under the clone.
|
|
65
|
+
if ((await admin.one<{ held: boolean }>(lockSql(datname)))?.held !== true) continue;
|
|
66
|
+
try {
|
|
67
|
+
await admin.execute(raw(`drop database if exists "${datname}" with (force)`));
|
|
68
|
+
} finally {
|
|
69
|
+
await admin.execute(unlockSql(datname));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A killed build's databases for `key`: only the key's lock holder builds it, so any is debris. */
|
|
75
|
+
async function sweepBuilds(admin: Admin, key: string): Promise<void> {
|
|
76
|
+
if (!/^[0-9a-f]+$/.test(key.slice(0, KEY_CHARS))) return;
|
|
77
|
+
const debris = await admin.query<{ datname: string }>(
|
|
78
|
+
sql`select datname from pg_database where datname ~ ${`^${buildPrefixFor(key)}[0-9]+$`}`,
|
|
79
|
+
);
|
|
80
|
+
for (const { datname } of debris) {
|
|
81
|
+
await admin.execute(raw(`drop database if exists "${datname}" with (force)`));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The template for `key`, built once: into a database of its own name, renamed into place only when
|
|
87
|
+
* prepared, and dropped if the preparation fails — so no build, killed or refused, reads as ready.
|
|
88
|
+
* Called under the key's lock.
|
|
89
|
+
*/
|
|
90
|
+
async function ensureTemplate(
|
|
91
|
+
admin: Admin,
|
|
92
|
+
adminUrl: string,
|
|
93
|
+
preparation: ScratchPreparation,
|
|
94
|
+
): Promise<string> {
|
|
95
|
+
const template = templateNameFor(preparation.key);
|
|
96
|
+
const found = await admin.one(sql`select 1 as hit from pg_database where datname = ${template}`);
|
|
97
|
+
if (found !== null) return template;
|
|
98
|
+
await sweepBuilds(admin, preparation.key);
|
|
99
|
+
const building = `${buildPrefixFor(preparation.key)}${String(process.pid)}`;
|
|
100
|
+
await admin.execute(raw(`create database "${building}" template template0`));
|
|
101
|
+
try {
|
|
102
|
+
const target = new URL(adminUrl);
|
|
103
|
+
target.pathname = `/${building}`;
|
|
104
|
+
// `migrate`: no statement timeout — a migration is as long as it is.
|
|
105
|
+
const client = postgresClient({ url: target.toString(), role: 'migrate' });
|
|
106
|
+
try {
|
|
107
|
+
await preparation.prepare(client);
|
|
108
|
+
} finally {
|
|
109
|
+
await client.close();
|
|
110
|
+
}
|
|
111
|
+
await admin.execute(raw(`alter database "${building}" rename to "${template}"`));
|
|
112
|
+
} catch (error) {
|
|
113
|
+
await admin.execute(raw(`drop database if exists "${building}" with (force)`));
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
await evictTemplates(admin, template);
|
|
117
|
+
return template;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** `work` on a fresh clone of `preparation`'s template, built first when the key is new. */
|
|
121
|
+
export async function withPreparedPostgres<T>(
|
|
122
|
+
adminUrl: string,
|
|
123
|
+
preparation: ScratchPreparation,
|
|
124
|
+
work: (client: DbClient) => Promise<T>,
|
|
125
|
+
): Promise<T> {
|
|
126
|
+
const database = `x_scratch_${String(process.pid)}_${crypto.randomUUID().slice(0, 8)}`;
|
|
127
|
+
// `migrate`: no statement timeout on the clone of a large template, nor on the build.
|
|
128
|
+
const admin = postgresClient({ url: adminUrl, role: 'migrate' });
|
|
129
|
+
try {
|
|
130
|
+
await reapScratch(admin);
|
|
131
|
+
const template = templateNameFor(preparation.key);
|
|
132
|
+
{
|
|
133
|
+
// One session holds the lock: a pool's next statement may land on another.
|
|
134
|
+
using session = await admin.reserve();
|
|
135
|
+
await acquire(session, template);
|
|
136
|
+
try {
|
|
137
|
+
await ensureTemplate(session, adminUrl, preparation);
|
|
138
|
+
await session.execute(raw(`create database "${database}" template "${template}"`));
|
|
139
|
+
await stampScratch(session, database);
|
|
140
|
+
} finally {
|
|
141
|
+
await session.execute(unlockSql(template));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const target = new URL(adminUrl);
|
|
145
|
+
target.pathname = `/${database}`;
|
|
146
|
+
const client = postgresClient({ url: target.toString() });
|
|
147
|
+
try {
|
|
148
|
+
return await work(client);
|
|
149
|
+
} finally {
|
|
150
|
+
await client.close();
|
|
151
|
+
await admin.execute(raw(`drop database if exists "${database}" with (force)`));
|
|
152
|
+
}
|
|
153
|
+
} finally {
|
|
154
|
+
await admin.close();
|
|
155
|
+
}
|
|
156
|
+
}
|
package/src/db-replay-engine.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
import type { DbClient, LinkedExtensions, Migration } from '@ultimat3/db';
|
|
9
9
|
import { DbError, linkPgliteExtensions, pgliteClient, postgresClient, raw } from '@ultimat3/db';
|
|
10
|
+
import { reapScratch, stampScratch } from './db-replay-scratch-reap';
|
|
10
11
|
import { migrationExtensions } from './migration-extensions';
|
|
11
12
|
|
|
12
13
|
type Env = Readonly<Record<string, string | undefined>>;
|
|
@@ -69,9 +70,12 @@ async function withPostgresScratch<T>(
|
|
|
69
70
|
const database = scratchName();
|
|
70
71
|
const admin = postgresClient({ url: adminUrl });
|
|
71
72
|
try {
|
|
73
|
+
// A killed run's working database, stamped and old, goes first (`db-replay-scratch-reap.ts`).
|
|
74
|
+
await reapScratch(admin);
|
|
72
75
|
// `template0`: the server's `template1` may carry objects an operator put there, and they
|
|
73
76
|
// would be dumped as the app's.
|
|
74
77
|
await admin.execute(raw(`create database ${database} template template0`));
|
|
78
|
+
await stampScratch(admin, database);
|
|
75
79
|
const target = new URL(adminUrl);
|
|
76
80
|
target.pathname = `/${database}`;
|
|
77
81
|
const client = postgresClient({ url: target.toString() });
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// The working databases a scratch run creates on a shared Postgres — the schema dump's and the
|
|
2
|
+
// exercise pass's clones — stamped with the SERVER's clock when created, and a killed run's reaped
|
|
3
|
+
// by the next run once older than `SCRATCH_MAX_AGE_MS`: `reapBranches`' shape (`@ultimat3/db`'s
|
|
4
|
+
// `branch.ts`). Only a stamped database of this module's exact name shape is ever dropped.
|
|
5
|
+
|
|
6
|
+
import type { DbClient } from '@ultimat3/db';
|
|
7
|
+
import { identifier, literal, raw, sql } from '@ultimat3/db';
|
|
8
|
+
|
|
9
|
+
/** The comment a working database carries: this marker, then its creation as UTC ISO seconds. */
|
|
10
|
+
export const SCRATCH_MARKER = 'ultimate:scratch:';
|
|
11
|
+
|
|
12
|
+
/** A working database older than this is a killed run's: no pass holds one for six hours. */
|
|
13
|
+
export const SCRATCH_MAX_AGE_MS = 6 * 60 * 60 * 1000;
|
|
14
|
+
|
|
15
|
+
/** Exactly a working database's name — `x_scratch_<pid>_<8 hex>`, `x_schema_dump_<pid>_<8 hex>`. */
|
|
16
|
+
const WORKING_NAME = '^x_(scratch|schema_dump)_[0-9]+_[0-9a-f]{8}$';
|
|
17
|
+
|
|
18
|
+
/** Exactly a stamp: anything else in the comment is somebody else's, and never read as an age. */
|
|
19
|
+
const STAMP = /^ultimate:scratch:(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)$/;
|
|
20
|
+
|
|
21
|
+
type Admin = Pick<DbClient, 'one' | 'query' | 'execute'>;
|
|
22
|
+
|
|
23
|
+
/** Stamp `database` with the server's now: the age a later run reads is the server's, too. */
|
|
24
|
+
export async function stampScratch(admin: Admin, database: string): Promise<void> {
|
|
25
|
+
const row = await admin.one<{ at: string }>(
|
|
26
|
+
sql`select to_char(now() at time zone 'utc', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') as at`,
|
|
27
|
+
);
|
|
28
|
+
if (row === null) return;
|
|
29
|
+
await admin.execute(
|
|
30
|
+
sql`comment on database ${identifier(database)} is ${literal(`${SCRATCH_MARKER}${row.at}`)}`,
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Drop every stamped working database older than `maxAgeMs` by the server's clock; their names. */
|
|
35
|
+
export async function reapScratch(
|
|
36
|
+
admin: Admin,
|
|
37
|
+
maxAgeMs: number = SCRATCH_MAX_AGE_MS,
|
|
38
|
+
): Promise<readonly string[]> {
|
|
39
|
+
const rows = await admin.query<{ name: string; comment: string | null; now_ms: string | number }>(
|
|
40
|
+
sql`select d.datname as name, shobj_description(d.oid, 'pg_database') as comment,
|
|
41
|
+
(extract(epoch from now()) * 1000)::bigint as now_ms
|
|
42
|
+
from pg_database d where d.datname ~ ${WORKING_NAME}`,
|
|
43
|
+
);
|
|
44
|
+
const reaped: string[] = [];
|
|
45
|
+
for (const row of rows) {
|
|
46
|
+
const stamp = STAMP.exec(row.comment ?? '')?.[1];
|
|
47
|
+
if (stamp === undefined) continue;
|
|
48
|
+
const created = Date.parse(stamp);
|
|
49
|
+
if (!Number.isFinite(created) || Number(row.now_ms) - created < maxAgeMs) continue;
|
|
50
|
+
await admin.execute(raw(`drop database if exists "${row.name}" with (force)`));
|
|
51
|
+
reaped.push(row.name);
|
|
52
|
+
}
|
|
53
|
+
return reaped;
|
|
54
|
+
}
|
|
@@ -48,9 +48,16 @@ function parsedOrNaN(raw: string): number {
|
|
|
48
48
|
* The origin, and only that: `/readyz` lives at the root, so a path would be silently dropped, and
|
|
49
49
|
* credentials would ride into every log line that names the URL. The cause never echoes the value.
|
|
50
50
|
*/
|
|
51
|
-
function readOrigin(
|
|
51
|
+
export function readOrigin(
|
|
52
|
+
raw: string | undefined,
|
|
53
|
+
// The command the refusal names, and a runnable invocation of it: `x status` reads `--url` too.
|
|
54
|
+
asker: { readonly command: string; readonly example: string } = {
|
|
55
|
+
command: VERIFY_COMMAND,
|
|
56
|
+
example: EXAMPLE,
|
|
57
|
+
},
|
|
58
|
+
): string {
|
|
52
59
|
const refuse = (reason: string): BadFlagError =>
|
|
53
|
-
new BadFlagError({ flag: 'url', command:
|
|
60
|
+
new BadFlagError({ flag: 'url', command: asker.command, reason, fix: asker.example });
|
|
54
61
|
if (raw === undefined) throw refuse('it is required: the origin the load balancer answers on');
|
|
55
62
|
const parsed = URL.canParse(raw) ? new URL(raw) : undefined;
|
|
56
63
|
if (parsed === undefined || !['http:', 'https:'].includes(parsed.protocol)) {
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// graded per queue. No socket, no database, no clock — `cmd-deploy-verify.ts` owns the waiting.
|
|
3
3
|
|
|
4
4
|
import type { WorkerRecord } from '@ultimat3/jobs';
|
|
5
|
+
import { printableBuild } from './cmd-deploy-verify-sample';
|
|
5
6
|
|
|
6
7
|
/** One `GET /readyz`. A `null` status is a sample nothing answered: refused, reset, timed out. */
|
|
7
8
|
export interface Sample {
|
|
@@ -116,16 +117,22 @@ export function failureOf(tally: SampleTally, build: string): SampleFailure {
|
|
|
116
117
|
return namedNone && tally.unstamped > 0 ? 'X_DEPLOY_BUILD_UNSTAMPED' : 'X_DEPLOY_BUILD_MISMATCH';
|
|
117
118
|
}
|
|
118
119
|
|
|
119
|
-
/**
|
|
120
|
+
/**
|
|
121
|
+
* The tally as `--json` reports it. The window's bookkeeping stays out. A build name is the
|
|
122
|
+
* server's own bytes, so it is printed through `printableBuild`; the tally itself stays raw, which
|
|
123
|
+
* is what the grade matched on.
|
|
124
|
+
*/
|
|
120
125
|
export const tallyToJson = (tally: SampleTally) => ({
|
|
121
126
|
total: tally.total,
|
|
122
127
|
good: tally.good,
|
|
123
|
-
byBuild:
|
|
128
|
+
byBuild: Object.fromEntries(
|
|
129
|
+
Object.entries(tally.byBuild).map(([name, count]) => [printableBuild(name), count]),
|
|
130
|
+
),
|
|
124
131
|
byStatus: { ...tally.byStatus },
|
|
125
132
|
/** Each build's share of every sample, to three places: a stuck roll reads as its old share. */
|
|
126
133
|
share: Object.fromEntries(
|
|
127
134
|
Object.entries(tally.byBuild).map(([name, count]) => [
|
|
128
|
-
name,
|
|
135
|
+
printableBuild(name),
|
|
129
136
|
Math.round((count / Math.max(1, tally.total)) * 1000) / 1000,
|
|
130
137
|
]),
|
|
131
138
|
),
|
package/src/dev-boot.ts
CHANGED
|
@@ -18,6 +18,7 @@ import type { DevDashboardInput, DevStatus } from './dev-dashboard';
|
|
|
18
18
|
import { devPanels } from './dev-dashboard';
|
|
19
19
|
import { createInvalidationLog } from './dev-dashboard-invalidations';
|
|
20
20
|
import { declareDevEnvironment, needsDevEnvironmentDeclaration } from './dev-environment';
|
|
21
|
+
import { dialableUrl } from './dev-host';
|
|
21
22
|
import { createStatementLedger } from './dev-n-plus-one';
|
|
22
23
|
import type { DevState } from './dev-rebuild';
|
|
23
24
|
import { buildGeneration, devRebuilder } from './dev-rebuild';
|
|
@@ -40,6 +41,7 @@ import { replicaOverrides } from './runtime-replica';
|
|
|
40
41
|
import type { RunningServices } from './runtime-services';
|
|
41
42
|
import { releaseOrThrow, startServices } from './runtime-services';
|
|
42
43
|
import { metricsPortFor, releaseBoot } from './serve';
|
|
44
|
+
import type { ListenerTls } from './serve-env-tls';
|
|
43
45
|
import { loopFacts, loopFinding, loopNotice } from './statement-loop';
|
|
44
46
|
|
|
45
47
|
export interface DevServer {
|
|
@@ -71,6 +73,13 @@ export interface DevServer {
|
|
|
71
73
|
export interface StartDevOptions {
|
|
72
74
|
readonly root: string;
|
|
73
75
|
readonly port: number;
|
|
76
|
+
/**
|
|
77
|
+
* The interface every socket binds (`WebBinding` is one decision): `x dev --host`. Absent is
|
|
78
|
+
* loopback. `/_x` answers a loopback peer and Host whatever this says (`hostRefusal`).
|
|
79
|
+
*/
|
|
80
|
+
readonly hostname?: string;
|
|
81
|
+
/** `x dev --tls`: the generated local pair (`dev-tls.ts`); the web listener serves https. */
|
|
82
|
+
readonly tls?: ListenerTls;
|
|
74
83
|
readonly env: Readonly<Record<string, string | undefined>>;
|
|
75
84
|
readonly roles?: readonly Role[];
|
|
76
85
|
readonly onReload?: (file: string, durationMs: number) => void;
|
|
@@ -279,6 +288,9 @@ async function bootDev(
|
|
|
279
288
|
const running = await startRoles({
|
|
280
289
|
roles: options.roles ?? DEV_ROLES,
|
|
281
290
|
port: options.port,
|
|
291
|
+
// Dev-mode whatever the interface: a wider bind is still a development process.
|
|
292
|
+
...(options.hostname === undefined ? {} : { http: { dev: true, hostname: options.hostname } }),
|
|
293
|
+
...(options.tls === undefined ? {} : { tls: options.tls }),
|
|
282
294
|
// `serve.ts`'s expression, called rather than restated: `METRICS_PORT` was read in the
|
|
283
295
|
// container and ignored here, so the scrape port an operator moved was the one port `x dev`
|
|
284
296
|
// could not move — and the second `x dev` on a box died binding the hardcoded 9090.
|
|
@@ -319,7 +331,8 @@ async function bootDev(
|
|
|
319
331
|
const watcher = watchTree({ root: options.root, onChange: rebuild });
|
|
320
332
|
|
|
321
333
|
server = {
|
|
322
|
-
|
|
334
|
+
// Dialable, never Bun's `http://0.0.0.0:<port>`: the lock, `x shot` and `/_x` read this.
|
|
335
|
+
url: dialableUrl(running.url ?? `http://localhost:${options.port}`),
|
|
323
336
|
services,
|
|
324
337
|
roles: running.roles,
|
|
325
338
|
mcp: mcpPath,
|
|
@@ -1,10 +1,18 @@
|
|
|
1
|
-
// The doors in front of `/_x
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// The doors in front of `/_x`. `x dev` binds loopback by default, but a page the developer has
|
|
2
|
+
// open can still reach it: by DNS rebinding (a hostile name that resolves to 127.0.0.1, read back
|
|
3
|
+
// same-origin) and by a cross-site request to the SQL panel. Bound wider (`--host`), a LAN peer
|
|
4
|
+
// can knock too, naming a loopback Host itself — so the peer's own address is asked as well.
|
|
4
5
|
|
|
5
6
|
import { proveSameOrigin, renderFixShellArg, UltimateError } from '@ultimat3/core';
|
|
6
7
|
import type { UltimateRequest } from '@ultimat3/http';
|
|
7
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
callerLocality,
|
|
10
|
+
csrfBlocked,
|
|
11
|
+
HttpError,
|
|
12
|
+
jsonResponse,
|
|
13
|
+
RELAY_HEADERS,
|
|
14
|
+
selfOrigin,
|
|
15
|
+
} from '@ultimat3/http';
|
|
8
16
|
import { t } from '@ultimat3/schema';
|
|
9
17
|
import { isLoopbackHostname } from './loopback-host';
|
|
10
18
|
|
|
@@ -20,23 +28,62 @@ export class DevHostRefusedError extends UltimateError {
|
|
|
20
28
|
}
|
|
21
29
|
}
|
|
22
30
|
|
|
31
|
+
/**
|
|
32
|
+
* A `/_x` request from a peer that is not this machine — `x dev --host` bound a wider interface,
|
|
33
|
+
* and `/_x` (the app's SQL, outbox and spans) stays loopback-only whatever it bound. The fix dials
|
|
34
|
+
* the same server through loopback, which a wildcard bind answers on too.
|
|
35
|
+
*/
|
|
36
|
+
export class DevPeerRefusedError extends UltimateError {
|
|
37
|
+
constructor(input: { devUrl: string; relay?: string }) {
|
|
38
|
+
// The scheme and port the server speaks (`x dev --tls` is https), on the loopback name.
|
|
39
|
+
const parsed = URL.parse(input.devUrl);
|
|
40
|
+
const scheme = parsed?.protocol === 'https:' ? 'https' : 'http';
|
|
41
|
+
const port = parsed?.port ?? '';
|
|
42
|
+
const loopback = `${scheme}://localhost${port === '' ? '' : `:${port}`}/_x`;
|
|
43
|
+
super({
|
|
44
|
+
code: 'X_DEV_PEER_REFUSED',
|
|
45
|
+
cause:
|
|
46
|
+
input.relay === undefined
|
|
47
|
+
? 'a /_x request came from a peer address that is not loopback — x dev was bound past loopback with --host, and the dev dashboard answers this machine only'
|
|
48
|
+
: `a /_x request carried ${input.relay}, which a relay writes and a browser never sends — a tunnel or proxy in front of this x dev speaks for callers that are not this machine, and the dev dashboard answers this machine only`,
|
|
49
|
+
fix: `curl -sS -H 'accept: application/json' ${renderFixShellArg(loopback, 'http://localhost:3000/_x')} # on the machine x dev runs on; x dev --host 0.0.0.0 keeps loopback bound`,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The first relay header the request carries — named in the refusal, never its value. */
|
|
55
|
+
const relayOf = (request: UltimateRequest): string | undefined =>
|
|
56
|
+
RELAY_HEADERS.find((name) => request.header(name) !== null);
|
|
57
|
+
|
|
23
58
|
/** The Host as sent, else the one the URL was built from — Bun builds it from the header. */
|
|
24
59
|
const hostnameOf = (request: UltimateRequest): string | undefined => {
|
|
25
60
|
const header = request.header('host') ?? request.url.host;
|
|
26
61
|
return URL.parse(`http://${header}`)?.hostname;
|
|
27
62
|
};
|
|
28
63
|
|
|
64
|
+
const refusal = (error: UltimateError, status: number): Response =>
|
|
65
|
+
jsonResponse(
|
|
66
|
+
{ ok: false, error: { code: error.code, cause: error.cause, fix: error.fix } },
|
|
67
|
+
{ status },
|
|
68
|
+
);
|
|
69
|
+
|
|
29
70
|
/**
|
|
30
71
|
* `421 Misdirected Request` for a Host that is not this machine, on every `/_x` route. The status
|
|
31
|
-
* says "not this server", which is the truth: a rebound name was never meant to reach it.
|
|
72
|
+
* says "not this server", which is the truth: a rebound name was never meant to reach it. Then
|
|
73
|
+
* `403` for a peer that is not this machine — the Host was right, the caller is not allowed.
|
|
32
74
|
*/
|
|
33
75
|
export function hostRefusal(request: UltimateRequest, devUrl: string): Response | undefined {
|
|
34
76
|
const hostname = hostnameOf(request);
|
|
35
|
-
if (hostname
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
77
|
+
if (hostname === undefined || !isLoopbackHostname(hostname)) {
|
|
78
|
+
return refusal(new DevHostRefusedError({ devUrl }), 421);
|
|
79
|
+
}
|
|
80
|
+
// http's one rule (`callerLocality`), the same the dev overlay and the dev MCP token ask.
|
|
81
|
+
const locality = callerLocality({ ip: request.ctx.ip, headers: request.headers });
|
|
82
|
+
if (locality === 'local') return undefined;
|
|
83
|
+
const relay = locality === 'relayed' ? relayOf(request) : undefined;
|
|
84
|
+
return refusal(
|
|
85
|
+
new DevPeerRefusedError({ devUrl, ...(relay === undefined ? {} : { relay }) }),
|
|
86
|
+
403,
|
|
40
87
|
);
|
|
41
88
|
}
|
|
42
89
|
|
package/src/dev-host.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Which interface `x dev` binds: `--host`, else loopback. Validated at the boundary, because a
|
|
2
|
+
// typo handed to `Bun.serve` fails as an uncoded bind error and a hostname binds wherever DNS
|
|
3
|
+
// points today. A wider bind is something the caller types; loopback stays the default.
|
|
4
|
+
|
|
5
|
+
import { classifyAddress } from '@ultimat3/core';
|
|
6
|
+
import { BadFlagError } from './errors';
|
|
7
|
+
import { isLoopbackHostname } from './loopback-host';
|
|
8
|
+
import type { ParsedArgs } from './parse';
|
|
9
|
+
import { flagString } from './parse';
|
|
10
|
+
import { DEV_BINDING } from './web-binding';
|
|
11
|
+
|
|
12
|
+
const unbracketed = (raw: string): string =>
|
|
13
|
+
raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1) : raw;
|
|
14
|
+
|
|
15
|
+
/** `localhost` or an address LITERAL — `0.0.0.0` and `::` included — never a name to resolve. */
|
|
16
|
+
export function devHostFor(args: ParsedArgs): string {
|
|
17
|
+
const raw = flagString(args, 'host');
|
|
18
|
+
if (raw === undefined) return DEV_BINDING.hostname;
|
|
19
|
+
const host = unbracketed(raw.trim());
|
|
20
|
+
if (host.toLowerCase() === 'localhost') return 'localhost';
|
|
21
|
+
if (classifyAddress(host) !== undefined) return host;
|
|
22
|
+
throw new BadFlagError({
|
|
23
|
+
flag: 'host',
|
|
24
|
+
command: 'dev',
|
|
25
|
+
reason: `expects localhost or an IP address literal (IPv4, IPv6, 0.0.0.0, ::), got "${raw}"`,
|
|
26
|
+
fix: 'x dev --host 0.0.0.0',
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The url a client on THIS machine dials. A wildcard bind answers on loopback too, and Bun reports
|
|
32
|
+
* it as `http://0.0.0.0:<port>` — an address a browser may refuse and `/_x` (a loopback Host
|
|
33
|
+
* only) always does — so it is reported as `localhost`. A specific address is reported as itself.
|
|
34
|
+
*/
|
|
35
|
+
export function dialableUrl(url: string): string {
|
|
36
|
+
const parsed = URL.parse(url);
|
|
37
|
+
if (parsed === null || classifyAddress(parsed.hostname) !== 'unspecified') return url;
|
|
38
|
+
parsed.hostname = 'localhost';
|
|
39
|
+
return parsed.origin;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `/_x` on this server, or null when its bind leaves no loopback address to reach it on. */
|
|
43
|
+
export function dashboardUrl(url: string): string | null {
|
|
44
|
+
const parsed = URL.parse(url);
|
|
45
|
+
return parsed !== null && isLoopbackHostname(parsed.hostname) ? `${parsed.origin}/_x` : null;
|
|
46
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// `x dev --tls`'s certificate on disk: `.x/tls/` (0700; gitignored, never committed), the key
|
|
2
|
+
// created 0600, and `meta.json` written last as the one thing that vouches for the pair. Reused
|
|
3
|
+
// while the names match, its end is not near and the cert and key belong together; else regenerated.
|
|
4
|
+
|
|
5
|
+
// why: WebCrypto parses no X.509, and the cached cert must be proven to match the cached key.
|
|
6
|
+
import { createPrivateKey, X509Certificate } from 'node:crypto';
|
|
7
|
+
// why: Bun.write takes no file mode — the key is CREATED 0600 in a 0700 directory, never chmod'ed after.
|
|
8
|
+
import { chmod, mkdir, rm, stat, writeFile } from 'node:fs/promises';
|
|
9
|
+
// why: Bun exposes no path-join primitive; Bun.file takes one already joined.
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import type { CertificatePair } from './dev-tls';
|
|
12
|
+
import { DAY_MS, DEV_CERT_DAYS, selfSignedCertificate } from './dev-tls';
|
|
13
|
+
|
|
14
|
+
/** Inside this window of its end, a cached certificate is replaced rather than served. */
|
|
15
|
+
const RENEW_WITHIN_MS = 7 * DAY_MS;
|
|
16
|
+
|
|
17
|
+
export interface DevCertificate extends CertificatePair {
|
|
18
|
+
/** Where the certificate sits, for `curl --cacert` or a browser's trust store. */
|
|
19
|
+
readonly certPath: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface CachedMeta {
|
|
23
|
+
readonly names: readonly string[];
|
|
24
|
+
readonly notAfter: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function readMeta(path: string): Promise<CachedMeta | undefined> {
|
|
28
|
+
const file = Bun.file(path);
|
|
29
|
+
if (!(await file.exists())) return undefined;
|
|
30
|
+
const parsed: unknown = await file.json().catch(() => undefined);
|
|
31
|
+
if (typeof parsed !== 'object' || parsed === null) return undefined;
|
|
32
|
+
const { names, notAfter } = parsed as Record<string, unknown>;
|
|
33
|
+
if (!Array.isArray(names) || typeof notAfter !== 'number') return undefined;
|
|
34
|
+
return { names: names.filter((name): name is string => typeof name === 'string'), notAfter };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The cached key exists and no one but its owner can read it. A wider mode — a copy, an editor's
|
|
39
|
+
* save under umask 0002 — is not served: the pair is regenerated. Windows has no POSIX mode bits
|
|
40
|
+
* to read, so there the file's existence is the whole check.
|
|
41
|
+
*/
|
|
42
|
+
async function keyIsPrivate(path: string): Promise<boolean> {
|
|
43
|
+
const found = await stat(path).catch(() => undefined);
|
|
44
|
+
if (found === undefined || !found.isFile()) return false;
|
|
45
|
+
return process.platform === 'win32' || (found.mode & 0o077) === 0;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The cached cert and key when they BELONG together — a key written by a regeneration that never
|
|
50
|
+
* reached its cert would otherwise be served beside the old cert, and every handshake fails.
|
|
51
|
+
*/
|
|
52
|
+
async function cachedPair(certPath: string, keyPath: string): Promise<CertificatePair | undefined> {
|
|
53
|
+
const cert = await Bun.file(certPath)
|
|
54
|
+
.text()
|
|
55
|
+
.catch(() => undefined);
|
|
56
|
+
const key = await Bun.file(keyPath)
|
|
57
|
+
.text()
|
|
58
|
+
.catch(() => undefined);
|
|
59
|
+
if (cert === undefined || key === undefined) return undefined;
|
|
60
|
+
try {
|
|
61
|
+
return new X509Certificate(cert).checkPrivateKey(createPrivateKey(key))
|
|
62
|
+
? { cert, key }
|
|
63
|
+
: undefined;
|
|
64
|
+
} catch {
|
|
65
|
+
return undefined; // unparseable is as stale as mismatched: regenerated, never served
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The cached pair when it carries exactly `names` and is not near its end; else a new one, written. */
|
|
70
|
+
export async function devCertificate(input: {
|
|
71
|
+
readonly stateDir: string;
|
|
72
|
+
readonly names: readonly string[];
|
|
73
|
+
readonly now: Date;
|
|
74
|
+
}): Promise<DevCertificate> {
|
|
75
|
+
const dir = join(input.stateDir, 'tls');
|
|
76
|
+
const certPath = join(dir, 'cert.pem');
|
|
77
|
+
const keyPath = join(dir, 'key.pem');
|
|
78
|
+
const metaPath = join(dir, 'meta.json');
|
|
79
|
+
const names = [...new Set(input.names)].sort();
|
|
80
|
+
const meta = await readMeta(metaPath);
|
|
81
|
+
const fresh =
|
|
82
|
+
meta !== undefined &&
|
|
83
|
+
meta.names.join(',') === names.join(',') &&
|
|
84
|
+
meta.notAfter - input.now.getTime() > RENEW_WITHIN_MS;
|
|
85
|
+
if (fresh && (await keyIsPrivate(keyPath))) {
|
|
86
|
+
const cached = await cachedPair(certPath, keyPath);
|
|
87
|
+
if (cached !== undefined) return { ...cached, certPath };
|
|
88
|
+
}
|
|
89
|
+
const pair = await selfSignedCertificate({ names, now: input.now });
|
|
90
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
91
|
+
await chmod(dir, 0o700); // an existing `.x/tls` keeps whatever mode it was made with otherwise
|
|
92
|
+
// meta.json FIRST: it is what vouches for the pair, so a run killed (or failing) between the
|
|
93
|
+
// key and the cert leaves nothing vouching for the torn pair, and the next boot regenerates.
|
|
94
|
+
await rm(metaPath, { force: true });
|
|
95
|
+
// Removed, then created exclusively at 0600: a write over an existing 0644 file keeps 0644, and
|
|
96
|
+
// a chmod after the write leaves a window in which the key is readable by everyone.
|
|
97
|
+
await rm(keyPath, { force: true });
|
|
98
|
+
await writeFile(keyPath, pair.key, { mode: 0o600, flag: 'wx' });
|
|
99
|
+
await Bun.write(certPath, pair.cert);
|
|
100
|
+
const notAfter = input.now.getTime() + DEV_CERT_DAYS * DAY_MS;
|
|
101
|
+
await Bun.write(metaPath, JSON.stringify({ names, notAfter }));
|
|
102
|
+
return { ...pair, certPath };
|
|
103
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// The DER this package writes, and no more: the handful of ASN.1 types a self-signed X.509 needs
|
|
2
|
+
// (`dev-tls.ts`). Hand-written because the alternative is a certificate dependency or shelling out
|
|
3
|
+
// to openssl, and neither earns its place for one local certificate (docs/idea/18-build-vs-wrap.md).
|
|
4
|
+
|
|
5
|
+
const lengthOf = (length: number): number[] => {
|
|
6
|
+
if (length < 0x80) return [length];
|
|
7
|
+
const bytes: number[] = [];
|
|
8
|
+
for (let rest = length; rest > 0; rest = Math.floor(rest / 256)) bytes.unshift(rest % 256);
|
|
9
|
+
return [0x80 | bytes.length, ...bytes];
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
/** One tag-length-value; the contents already encoded. */
|
|
13
|
+
export const tlv = (tag: number, ...contents: readonly Uint8Array[]): Uint8Array => {
|
|
14
|
+
const body = Buffer.concat(contents);
|
|
15
|
+
return Uint8Array.from([tag, ...lengthOf(body.length), ...body]);
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export const sequence = (...items: readonly Uint8Array[]): Uint8Array => tlv(0x30, ...items);
|
|
19
|
+
export const set = (...items: readonly Uint8Array[]): Uint8Array => tlv(0x31, ...items);
|
|
20
|
+
export const octets = (bytes: Uint8Array): Uint8Array => tlv(0x04, bytes);
|
|
21
|
+
export const utf8 = (text: string): Uint8Array => tlv(0x0c, new TextEncoder().encode(text));
|
|
22
|
+
/** `[n] EXPLICIT`: a constructed context tag around the encoded value. */
|
|
23
|
+
export const explicit = (n: number, value: Uint8Array): Uint8Array => tlv(0xa0 | n, value);
|
|
24
|
+
export const bitString = (bytes: Uint8Array): Uint8Array => tlv(0x03, Uint8Array.of(0), bytes);
|
|
25
|
+
export const bool = (value: boolean): Uint8Array => Uint8Array.of(0x01, 0x01, value ? 0xff : 0);
|
|
26
|
+
|
|
27
|
+
/** An unsigned big-endian magnitude as INTEGER: no redundant zeros, a 0x00 before a high bit. */
|
|
28
|
+
export const integer = (magnitude: Uint8Array): Uint8Array => {
|
|
29
|
+
let start = 0;
|
|
30
|
+
while (start < magnitude.length - 1 && magnitude[start] === 0) start += 1;
|
|
31
|
+
const trimmed = magnitude.subarray(start);
|
|
32
|
+
const pad = (trimmed[0] ?? 0) & 0x80 ? Uint8Array.of(0) : new Uint8Array(0);
|
|
33
|
+
return tlv(0x02, pad, trimmed);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** Dotted OID, base-128 per arc after the first two. */
|
|
37
|
+
export const oid = (dotted: string): Uint8Array => {
|
|
38
|
+
const arcs = dotted.split('.').map(Number);
|
|
39
|
+
const bytes: number[] = [(arcs[0] ?? 0) * 40 + (arcs[1] ?? 0)];
|
|
40
|
+
for (const arc of arcs.slice(2)) {
|
|
41
|
+
const group: number[] = [arc % 128];
|
|
42
|
+
for (let rest = Math.floor(arc / 128); rest > 0; rest = Math.floor(rest / 128)) {
|
|
43
|
+
group.unshift(0x80 | (rest % 128));
|
|
44
|
+
}
|
|
45
|
+
bytes.push(...group);
|
|
46
|
+
}
|
|
47
|
+
return tlv(0x06, Uint8Array.from(bytes));
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** UTCTime until 2049, GeneralizedTime after — RFC 5280 §4.1.2.5, always UTC, always seconds. */
|
|
51
|
+
export const time = (at: Date): Uint8Array => {
|
|
52
|
+
const iso = at.toISOString(); // UTC by definition: `YYYY-MM-DDTHH:MM:SS.sssZ`
|
|
53
|
+
const digits = `${iso.slice(0, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}${iso.slice(11, 13)}${iso.slice(14, 16)}${iso.slice(17, 19)}Z`;
|
|
54
|
+
const utc = at.getUTCFullYear() < 2050;
|
|
55
|
+
return tlv(utc ? 0x17 : 0x18, new TextEncoder().encode(utc ? digits.slice(2) : digits));
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** WebCrypto's ECDSA signature is `r || s`; X.509 carries `SEQUENCE { INTEGER r, INTEGER s }`. */
|
|
59
|
+
export const ecdsaSignature = (raw: Uint8Array): Uint8Array => {
|
|
60
|
+
const half = raw.length / 2;
|
|
61
|
+
return sequence(integer(raw.subarray(0, half)), integer(raw.subarray(half)));
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** PEM armour, 64 columns, the label as RFC 7468 spells it. */
|
|
65
|
+
export const pem = (label: string, der: Uint8Array): string => {
|
|
66
|
+
const base64 = Buffer.from(der).toString('base64');
|
|
67
|
+
const lines = base64.match(/.{1,64}/g) ?? [];
|
|
68
|
+
return `-----BEGIN ${label}-----\n${lines.join('\n')}\n-----END ${label}-----\n`;
|
|
69
|
+
};
|