@runeditrun/rer 0.2.37 → 0.2.39
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/cli/contract-status.mjs +26 -0
- package/cli/contract.mjs +1 -1
- package/cli/deploy-command.mjs +16 -5
- package/cli/deploy-inputs.mjs +32 -10
- package/cli/deploy-secrets.mjs +99 -0
- package/cli/deploy-settings.mjs +45 -0
- package/cli/deploy.mjs +27 -8
- package/cli/export.mjs +1 -1
- package/cli/inspect.mjs +2 -0
- package/cli/lifecycle.mjs +9 -3
- package/cli/local-env.mjs +33 -0
- package/cli/parse.mjs +3 -2
- package/cli/signin.mjs +3 -2
- package/cli/site-render.mjs +12 -2
- package/foundation/runtime/seed-contract.mjs +280 -0
- package/global/CHANGELOG.md +14 -0
- package/modules/container/build.mjs +4 -0
- package/modules/deploy-kit/README.md +2 -2
- package/modules/deploy-kit/local-only.mjs +20 -2
- package/modules/deploy-kit/owner.mjs +2 -1
- package/modules/deploy-kit/prepare.mjs +2 -1
- package/modules/release/catalogue.mjs +2 -1
- package/onboarding/README.md +6 -2
- package/onboarding/local-variables-output.d.mts +2 -0
- package/onboarding/local-variables-output.mjs +21 -0
- package/onboarding/redaction.mjs +1 -1
- package/onboarding/theme.mjs +5 -0
- package/package.json +5 -1
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// `rer check` on a seed's CONTRACT.md: the Status table parses, and every
|
|
2
|
+
// evidence path it cites is in the checkout. A seed without CONTRACT.md has
|
|
3
|
+
// nothing to check here.
|
|
4
|
+
import { lstat, readFile } from 'node:fs/promises';
|
|
5
|
+
import { isAbsolute, join, normalize, sep } from 'node:path';
|
|
6
|
+
import { ContractError, parseContract } from '../foundation/runtime/seed-contract.mjs';
|
|
7
|
+
|
|
8
|
+
const file = 'CONTRACT.md';
|
|
9
|
+
|
|
10
|
+
export async function contractStatusClauses(root) {
|
|
11
|
+
let text;
|
|
12
|
+
try { text = await readFile(join(root, file), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
13
|
+
let contract;
|
|
14
|
+
try { contract = parseContract(text, { file }); } catch (error) {
|
|
15
|
+
if (!(error instanceof ContractError)) throw error;
|
|
16
|
+
return error.problems.map(problem => ({ id: 'CONTRACT.status', ok: false, message: `${file}:${problem.line}: ${problem.message}` }));
|
|
17
|
+
}
|
|
18
|
+
const clauses = [{ id: 'CONTRACT.status', ok: true }];
|
|
19
|
+
for (const clause of contract.clauses) for (const path of clause.evidence) {
|
|
20
|
+
const inside = !isAbsolute(path) && !normalize(path).split(sep).includes('..');
|
|
21
|
+
let exists = false;
|
|
22
|
+
if (inside) try { await lstat(join(root, path)); exists = true; } catch {}
|
|
23
|
+
clauses.push({ id: `CONTRACT.evidence.${clause.id}`, ok: exists, ...(!exists ? { message: `${file}:${clause.row}: ${clause.id} is ${clause.status} with evidence ${path}, which ${inside ? 'is not in this checkout' : 'is outside this repository'}.` } : {}) });
|
|
24
|
+
}
|
|
25
|
+
return clauses;
|
|
26
|
+
}
|
package/cli/contract.mjs
CHANGED
|
@@ -11,7 +11,7 @@ const definitions = {
|
|
|
11
11
|
build: [['--site'], 'Production build with private local settings excluded and restored. --site instead writes the static run site (homepage, /run, docs) to its declared folder and prints that folder.'],
|
|
12
12
|
verify: [[], 'Run the complete internal verification target.'],
|
|
13
13
|
reset: [['--yes'], 'Confirmed removal of the declared local inventory only.'],
|
|
14
|
-
deploy: [['--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret'], 'Owner-account deployment and health; dry run performs local validation/build only. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. After a healthy deploy rer claims the setup owner on the hosted app with the one-time setup token, then removes the token. --set-secret NAME (value from the environment or --env-file) and --unset-secret NAME change one secret of the deployed Worker without a build and record its new version. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
|
|
14
|
+
deploy: [['--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret'], 'Owner-account deployment and health; dry run performs local validation/build only. Builds and deploy hooks run with the checkout\'s local settings files moved aside, and a build output holding one (.dev.vars, .env) is refused. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. rer keeps the secrets it generates in .rer/deploy/ENVIRONMENT.secrets.env (0600) and reuses them on every redeploy; it refuses to generate a replacement for one a live Worker holds, and --rotate-secret NAME[,NAME] replaces them on purpose. After a healthy deploy rer claims the setup owner on the hosted app with the one-time setup token, then removes the token. --set-secret NAME (value from the environment or --env-file) and --unset-secret NAME change one secret of the deployed Worker without a build and record its new version. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
|
|
15
15
|
export: [['--target', '--output', '--origin', '--session-file'], 'Complete supported installation archive with integrity and exclusions.'],
|
|
16
16
|
import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--output'], 'Confirmed atomic restore into an empty destination; --journal LATER_ARCHIVE also fences rows that installation erased since. Backup-only local v1 recovery requires --legacy-v1 --acknowledge-unverified-metadata and a new --output v2 archive; --journal requires normal v2 import.'],
|
|
17
17
|
doctor: [[], 'Read-only installed tool, configuration and state diagnostics.'],
|
package/cli/deploy-command.mjs
CHANGED
|
@@ -17,10 +17,13 @@ import { localOnlyBinding, ownerWorkerName } from '../modules/deploy-kit/owner.m
|
|
|
17
17
|
import { refuseLocalModels } from '../modules/deploy-kit/local-only.mjs';
|
|
18
18
|
import { migrationFailure, providerFailure, assetFailure } from '../modules/deploy-kit/diagnostics.mjs';
|
|
19
19
|
import { shared } from './shared.mjs';
|
|
20
|
+
import { settingKinds } from './deploy-settings.mjs';
|
|
20
21
|
import { deployGuide, neededForRealDeploy, reportNeeded } from './deploy-needs.mjs';
|
|
22
|
+
import { keepHookSecrets } from './deploy-secrets.mjs';
|
|
23
|
+
import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
|
|
21
24
|
|
|
22
25
|
export function validateDeployOptions(options) {
|
|
23
|
-
const changes = [options.remove && '--remove', options.setSecret && '--set-secret', options.unsetSecret && '--unset-secret'].filter(Boolean);
|
|
26
|
+
const changes = [options.remove && '--remove', options.setSecret && '--set-secret', options.unsetSecret && '--unset-secret', options.rotateSecret && '--rotate-secret'].filter(Boolean);
|
|
24
27
|
if (changes.length > 1 || changes.length && options.dryRun) throw invalid(`Use ${changes.join(', ')}${options.dryRun ? ' and --dry-run' : ''} on separate runs.`);
|
|
25
28
|
if (options.remove && !options.yes) throw invalid(`${deployAgain(options)} --remove deletes this environment's Worker and every D1, R2, KV and queue rer created for it, with their data. Add --yes to confirm.`);
|
|
26
29
|
}
|
|
@@ -73,16 +76,21 @@ export async function deployCommand(context) {
|
|
|
73
76
|
// Custom hooks historically ignored these flags. Only the ownership controller
|
|
74
77
|
// may perform them; neither a build nor a custom upload runs here.
|
|
75
78
|
if (options.remove || options.setSecret || options.unsetSecret) return ownerDeploy(path, adapter)(context);
|
|
79
|
+
// A hook that deployed through the kit keeps what its Worker holds: rotate there as a secret change.
|
|
80
|
+
if (options.rotateSecret && !adapter.deploy.managesHostedOwner && await hookState(root, options.environment ?? 'production')) return ownerDeploy(path, adapter)(context);
|
|
76
81
|
if (adapter.deploy.managesHostedOwner) { const result = await adapter.deploy(context); return options.dryRun ? dryRun(result) : result; }
|
|
77
82
|
const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
|
|
78
83
|
await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options });
|
|
79
84
|
const sourceSha = options.dryRun ? undefined : committedSource(root, options);
|
|
80
|
-
const { env, supplied } = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
|
|
81
|
-
const { createRedaction
|
|
85
|
+
const { env, supplied, generated, reused, rotated } = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
|
|
86
|
+
const { createRedaction } = await shared('redaction.mjs');
|
|
82
87
|
const redaction = createRedaction();
|
|
88
|
+
const kinds = await settingKinds({ declaration, setupManifest });
|
|
83
89
|
const addSecret = value => { redaction.addSecrets([value]); store.addSecrets?.([value]); };
|
|
84
|
-
for (const value of [...
|
|
90
|
+
for (const value of [...kinds.privateValues(env), env.CLOUDFLARE_ACCOUNT_ID, ...(declaration.secrets ?? []).map(item => env[item.environment])].filter(Boolean)) addSecret(value);
|
|
85
91
|
const environment = options.environment ?? 'production';
|
|
92
|
+
// The hook uploads every value it is given: a generated secret it gets is the one the Worker keeps.
|
|
93
|
+
if (!options.dryRun) await keepHookSecrets({ root, environment, declaration, setupManifest, env, generated, reused, rotated, again: deployAgain(options), report: line => store.report(line) });
|
|
86
94
|
// A hook keeping the kit's record in its own state file named it; every kit
|
|
87
95
|
// step after the hook (inspect, secret, record-owner) reads that record.
|
|
88
96
|
let hookRecord = await hookState(root, environment);
|
|
@@ -103,12 +111,15 @@ export async function deployCommand(context) {
|
|
|
103
111
|
const saved = { ...process.env };
|
|
104
112
|
try {
|
|
105
113
|
Object.assign(process.env, env);
|
|
106
|
-
|
|
114
|
+
// The hook builds and uploads by itself: it never sees the checkout's local settings.
|
|
115
|
+
deployed = await withoutLocalSettings(root, { settings: [...(Array.isArray(adapter.settings) ? adapter.settings : []), adapter.hooks?.secrets?.file], operationToken: context.operationToken },
|
|
116
|
+
() => adapter.deploy({ ...context, linkDependencies: async (origin, token) => link(token, origin) }));
|
|
107
117
|
} finally {
|
|
108
118
|
for (const key of Object.keys(process.env)) if (!Object.hasOwn(saved, key)) delete process.env[key];
|
|
109
119
|
Object.assign(process.env, saved);
|
|
110
120
|
}
|
|
111
121
|
hookReturned = true;
|
|
122
|
+
await refuseLocalEnvOutput(root, adapter.devIdentity?.output, { uploaded: !options.dryRun });
|
|
112
123
|
if (options.dryRun) return dryRun(deployed);
|
|
113
124
|
await rememberHookState(root, environment, deployed?.state);
|
|
114
125
|
hookRecord = await hookState(root, environment);
|
package/cli/deploy-inputs.mjs
CHANGED
|
@@ -4,12 +4,14 @@ import { shared } from './shared.mjs';
|
|
|
4
4
|
import { invalid } from './errors.mjs';
|
|
5
5
|
import { readDeployEnvFile } from '../modules/deploy-kit/env-file.mjs';
|
|
6
6
|
import { publicOrigin } from '../modules/deploy-kit/public-origin.mjs';
|
|
7
|
+
import { keptSecrets, rotations, savedSecrets } from './deploy-secrets.mjs';
|
|
7
8
|
|
|
8
9
|
// The values a Workers deploy reads for its declared secrets: this process's
|
|
9
10
|
// environment, then the --env-file (which wins), then what rer supplies itself:
|
|
10
|
-
// the local setup owner's email, and
|
|
11
|
-
//
|
|
12
|
-
//
|
|
11
|
+
// the local setup owner's email, and for each secret the setup manifest generates
|
|
12
|
+
// the value kept for this environment (deploy-secrets.mjs), else a fresh one
|
|
13
|
+
// (`generated`; always fresh for the one-time setup token and --rotate-secret).
|
|
14
|
+
// The owner kit sends a value only to a Worker that lacks that secret.
|
|
13
15
|
export async function deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys = [] }) {
|
|
14
16
|
const env = { ...process.env }, supplied = [];
|
|
15
17
|
if (options.envFile) {
|
|
@@ -35,24 +37,44 @@ export async function deployEnvironment({ root, options, declaration, setupManif
|
|
|
35
37
|
const owner = (await readSettings(root, settings)).values[emailField];
|
|
36
38
|
if (typeof owner === 'string' && owner.includes('@')) { env[email.environment] = owner; supplied.push(email.binding); }
|
|
37
39
|
}
|
|
40
|
+
// withDeployEnvironment reads only the --env-file, with no declaration to rotate in.
|
|
41
|
+
const kept = keptSecrets(declaration, setupManifest), rotate = setupManifest || declaration.project ? rotations(options, kept, env) : [];
|
|
42
|
+
const saved = kept.some(absent) ? await savedSecrets(root, options.environment ?? 'production') : {};
|
|
43
|
+
const generated = [], reused = [];
|
|
38
44
|
for (const field of setupManifest?.fields ?? []) {
|
|
39
45
|
const item = field.kind === 'secret' && field.generate ? secrets.find(entry => entry?.binding === field.name) : undefined;
|
|
40
|
-
if (absent(item))
|
|
46
|
+
if (!absent(item)) continue;
|
|
47
|
+
const keep = kept.includes(item), value = keep && !rotate.includes(item.binding) ? saved[item.binding] : undefined;
|
|
48
|
+
env[item.environment] = value ?? randomBytes(32).toString(field.generate);
|
|
49
|
+
supplied.push(item.binding);
|
|
50
|
+
if (value) reused.push(item.binding); else if (keep) generated.push(item.binding);
|
|
41
51
|
}
|
|
42
|
-
return { env, supplied };
|
|
52
|
+
return { env, supplied, generated, reused, rotated: rotate };
|
|
43
53
|
}
|
|
44
54
|
|
|
45
55
|
// Hooks and their child builds read process.env. Install the private file for
|
|
46
|
-
// this command only, and restore even keys changed by a failing hook.
|
|
47
|
-
|
|
56
|
+
// this command only, and restore even keys changed by a failing hook. Output
|
|
57
|
+
// redaction follows what the deploy declaration says each value is: declared
|
|
58
|
+
// secrets and credentials stay redacted, declared non-secret settings print in
|
|
59
|
+
// full, and an undeclared --env-file value stays redacted with a note on how to
|
|
60
|
+
// declare it.
|
|
61
|
+
export async function withDeployEnvironment(project, options, out, run) {
|
|
48
62
|
const saved = { ...process.env };
|
|
49
|
-
const { env } = await deployEnvironment({ root, options, declaration: {} });
|
|
50
|
-
const { createRedaction
|
|
63
|
+
const { env } = await deployEnvironment({ root: project.root, options, declaration: {} });
|
|
64
|
+
const { createRedaction } = await shared('redaction.mjs');
|
|
65
|
+
const { declaredSettings, settingKinds, undeclaredNotice } = await import('./deploy-settings.mjs');
|
|
66
|
+
const declared = await declaredSettings(project), kinds = await settingKinds(declared);
|
|
51
67
|
const redaction = createRedaction();
|
|
52
68
|
// Provider names are public enum values. Masking "resend" would also hide
|
|
53
69
|
// RESEND_API_KEY in the preflight's instruction for the missing credential.
|
|
54
70
|
const publicProvider = (key, value) => key === 'MAIL_PROVIDER' && /^(resend|sendgrid|cloudflare|rer|later)$/.test(value);
|
|
55
|
-
|
|
71
|
+
const supplied = Object.entries(env).filter(([key, value]) => saved[key] !== value);
|
|
72
|
+
redaction.addSecrets([...kinds.privateValues(env), ...supplied.filter(([key, value]) => !kinds.shown(key, value) && !publicProvider(key, value)).map(([, value]) => value)]);
|
|
73
|
+
const undeclared = declared.declaration ? kinds.undeclared(supplied.map(([key]) => key)) : [];
|
|
74
|
+
if (undeclared.length) {
|
|
75
|
+
const message = undeclaredNotice(undeclared, declared.path);
|
|
76
|
+
if (options.json) out.event('warning', { code: 'undeclared_env_setting', names: undeclared, message }); else out.progress(`${message}\n`);
|
|
77
|
+
}
|
|
56
78
|
Object.assign(process.env, env);
|
|
57
79
|
try { return await run(redaction); }
|
|
58
80
|
catch (error) { if (typeof error?.message === 'string') error.message = redaction.redact(error.message); throw error; }
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { readFile, rm } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { invalid, missing, refuse } from './errors.mjs';
|
|
4
|
+
import { cloudflareCredentials, missingCredentialsMessage } from './deploy-needs.mjs';
|
|
5
|
+
import { shared } from './shared.mjs';
|
|
6
|
+
import { readDeployEnvFile } from '../modules/deploy-kit/env-file.mjs';
|
|
7
|
+
import { cloudflare } from '../modules/deploy-kit/provider.mjs';
|
|
8
|
+
import { ownerWorkerName } from '../modules/deploy-kit/owner.mjs';
|
|
9
|
+
|
|
10
|
+
// Secrets rer generates for a deployment (the setup manifest's `generate` secret
|
|
11
|
+
// fields, such as a session or subscriber-link secret) outlive the run that made
|
|
12
|
+
// them: rer keeps them with the environment's deployment record, in the private
|
|
13
|
+
// (0600) file .rer/deploy/<environment>.secrets.env, and a redeploy reuses them.
|
|
14
|
+
// Cloudflare never reads a secret's value back, only its name, so a checkout
|
|
15
|
+
// without that file cannot know what a live Worker holds: rer then refuses to
|
|
16
|
+
// generate a replacement unless `--rotate-secret NAME` asks for one. The one-time
|
|
17
|
+
// owner setup token is not kept: rer issues it fresh and retires it after the claim.
|
|
18
|
+
export const savedSecretsFile = environment => join('.rer', 'deploy', `${environment}.secrets.env`);
|
|
19
|
+
|
|
20
|
+
const ignore = '# rer: generated deployment secrets never enter Git.\n*.secrets.env\n.gitignore\n';
|
|
21
|
+
|
|
22
|
+
/** The declared secrets rer generates and keeps: `generate` secret fields, except the owner setup token. */
|
|
23
|
+
export function keptSecrets(declaration, setupManifest) {
|
|
24
|
+
const token = setupManifest?.steps?.find(step => step.type === 'owner-claim')?.tokenField ?? 'SETUP_TOKEN';
|
|
25
|
+
const declared = Array.isArray(declaration?.secrets) ? declaration.secrets : [];
|
|
26
|
+
return (setupManifest?.fields ?? []).flatMap(field => {
|
|
27
|
+
const item = field.kind === 'secret' && field.generate && field.name !== token ? declared.find(entry => entry?.binding === field.name) : undefined;
|
|
28
|
+
return item ? [item] : [];
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** `--rotate-secret A,B`: each must be a secret rer generates and keeps, and not supplied by the person. */
|
|
33
|
+
export function rotations(options, kept, env) {
|
|
34
|
+
const names = options.rotateSecret === undefined ? [] : options.rotateSecret.split(',');
|
|
35
|
+
const generated = kept.map(item => item.binding);
|
|
36
|
+
for (const name of names) {
|
|
37
|
+
if (!generated.includes(name)) throw invalid(`--rotate-secret names a secret rer generates for this deployment${generated.length ? ` (${generated.join(', ')})` : ', and this seed declares none'}; ${name} is not one. Set another secret with --set-secret.`);
|
|
38
|
+
const item = kept.find(entry => entry.binding === name);
|
|
39
|
+
if (env[item.environment]?.trim()) throw invalid(`--rotate-secret ${name} generates a fresh value, but ${item.environment} is also set in the environment or --env-file. Leave it unset to rotate, or deploy with the value you supplied.`);
|
|
40
|
+
}
|
|
41
|
+
return names;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The values kept for this environment, by binding; {} when none are. */
|
|
45
|
+
export async function savedSecrets(root, environment) {
|
|
46
|
+
try { return await readDeployEnvFile(root, savedSecretsFile(environment)); }
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error.code === 'ENOENT') return {};
|
|
49
|
+
throw invalid(`${savedSecretsFile(environment)} could not be read: ${error.message}. Restore it as an owned 0600 file of NAME=VALUE lines.`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Keep these values (merged over what is kept) before they can reach a Worker. */
|
|
54
|
+
export async function saveSecrets(root, environment, values) {
|
|
55
|
+
if (!Object.keys(values).length) return;
|
|
56
|
+
const { privateDirectory, writePrivateFile } = await shared('private-files.mjs');
|
|
57
|
+
await privateDirectory(root, ['.rer', 'deploy']);
|
|
58
|
+
const gitignore = join(root, '.rer', 'deploy', '.gitignore');
|
|
59
|
+
const current = await readFile(gitignore, 'utf8').catch(error => { if (error.code === 'ENOENT') return ''; throw error; });
|
|
60
|
+
if (!current.split('\n').includes('*.secrets.env')) await writePrivateFile(gitignore, current + (current && !current.endsWith('\n') ? '\n' : '') + ignore);
|
|
61
|
+
const merged = { ...await savedSecrets(root, environment), ...values };
|
|
62
|
+
await writePrivateFile(join(root, savedSecretsFile(environment)), Object.entries(merged).map(([name, value]) => `${name}=${value}\n`).join(''));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const forgetSecrets = (root, environment) => rm(join(root, savedSecretsFile(environment)), { force: true });
|
|
66
|
+
|
|
67
|
+
/** The secret names the environment's live Worker holds; [] when it has no Worker yet. */
|
|
68
|
+
export async function liveSecretNames(env, declaration, environment) {
|
|
69
|
+
const api = cloudflare({ accountId: env.CLOUDFLARE_ACCOUNT_ID, token: env.CLOUDFLARE_API_TOKEN });
|
|
70
|
+
try { return (await api.request(`/workers/scripts/${ownerWorkerName(declaration.project, environment)}/secrets`)).map(row => row.name); }
|
|
71
|
+
catch (error) { if (error.status === 404) return []; throw error; }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Refuse to replace generated secrets a live Worker holds when rer kept no value for them. */
|
|
75
|
+
export function refuseRotation({ worker, held, environment, again }) {
|
|
76
|
+
const names = held.map(item => item.binding), many = held.length > 1, them = many ? 'them' : 'it';
|
|
77
|
+
return refuse(`The live ${worker} Worker holds ${names.join(', ')}, which rer generates for this deployment, but this checkout keeps no value for ${them} in ${savedSecretsFile(environment)}. A new value would replace the live one and break everything made with it, such as signed-in sessions and links already emailed. Nothing was uploaded.\nTo keep ${them}: copy ${savedSecretsFile(environment)} from the checkout that deployed this environment, or set ${held.map(item => item.environment).join(', ')} in --env-file, then run ${again} again.\nTo replace ${them} on purpose: ${again} --rotate-secret ${names.join(',')}`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Before a seed's own deploy hook uploads them: refuse to replace generated secrets a
|
|
81
|
+
* live Worker holds without a kept value, then keep what this run generated. */
|
|
82
|
+
export async function keepHookSecrets({ root, environment, declaration, setupManifest, env, generated, reused, rotated, again, report }) {
|
|
83
|
+
const kept = keptSecrets(declaration, setupManifest), fresh = generated.filter(binding => !rotated.includes(binding));
|
|
84
|
+
if (fresh.length) {
|
|
85
|
+
if (cloudflareCredentials.some(name => !env[name]?.trim())) throw missing(missingCredentialsMessage(declaration, env));
|
|
86
|
+
const live = await liveSecretNames(env, declaration, environment);
|
|
87
|
+
const held = kept.filter(item => fresh.includes(item.binding) && live.includes(item.binding));
|
|
88
|
+
if (held.length) throw refuseRotation({ worker: ownerWorkerName(declaration.project, environment), held, environment, again });
|
|
89
|
+
}
|
|
90
|
+
await keepSecrets({ root, environment, kept, env, generated, reused, report });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Keep the generated values that reach the Worker, and say which were generated or reused. */
|
|
94
|
+
export async function keepSecrets({ root, environment, kept, env, generated, reused, report }) {
|
|
95
|
+
await saveSecrets(root, environment, Object.fromEntries(kept.filter(item => generated.includes(item.binding)).map(item => [item.binding, env[item.environment]])));
|
|
96
|
+
const file = savedSecretsFile(environment), them = names => names.length > 1 ? 'them' : 'it';
|
|
97
|
+
if (generated.length) report(`rer generated ${generated.join(', ')} for this deployment and keeps ${them(generated)} in ${file} (private; Git ignores it), so a redeploy reuses ${them(generated)}. To deploy this environment from another checkout, copy that file there.`);
|
|
98
|
+
if (reused.length) report(`rer reused ${reused.join(', ')} kept in ${file}.`);
|
|
99
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { shared } from './shared.mjs';
|
|
2
|
+
|
|
3
|
+
// What a deployment's declaration says each value is. A value prints in full only
|
|
4
|
+
// when the declaration names it a non-secret setting: a declared var, the origin
|
|
5
|
+
// variable and its setting, a setup field that is not a secret, or a name in
|
|
6
|
+
// "publicSettings". Anything the declaration calls a secret, any credential-named
|
|
7
|
+
// key and any other --env-file value stays redacted.
|
|
8
|
+
const PRIVATE_KEYS = ['CLOUDFLARE_ACCOUNT_ID'];
|
|
9
|
+
|
|
10
|
+
export async function settingKinds({ declaration = {}, setupManifest } = {}) {
|
|
11
|
+
const { credentialName, credentialUrl, credentialValues } = await shared('redaction.mjs');
|
|
12
|
+
const secrets = Array.isArray(declaration.secrets) ? declaration.secrets : [];
|
|
13
|
+
const names = list => (Array.isArray(list) ? list : []).filter(name => typeof name === 'string');
|
|
14
|
+
const fields = Array.isArray(setupManifest?.fields) ? setupManifest.fields : [];
|
|
15
|
+
const secret = new Set([...PRIVATE_KEYS, ...secrets.flatMap(item => [item?.binding, item?.environment]), ...fields.filter(field => field?.kind === 'secret').map(field => field.name)].filter(Boolean));
|
|
16
|
+
const open = new Set([...Object.keys(declaration.vars ?? {}), declaration.originVar, declaration.publicOriginSetting, ...names(declaration.publicSettings), ...fields.filter(field => field?.kind !== 'secret').map(field => field?.name)].filter(name => name && !secret.has(name)));
|
|
17
|
+
// A declared setting is exempt from the key-name heuristic (AUTH_ORIGIN is a
|
|
18
|
+
// name, not a credential), never when its value carries credentials itself.
|
|
19
|
+
const shown = (key, value) => open.has(key) && typeof value === 'string' && !credentialUrl(value);
|
|
20
|
+
return {
|
|
21
|
+
shown,
|
|
22
|
+
// The values to keep out of output, from every key that is not shown.
|
|
23
|
+
privateValues: env => Object.entries(env).flatMap(([key, value]) => typeof value !== 'string' || shown(key, value) ? [] : secret.has(key) ? (value ? [value] : []) : credentialValues({ [key]: value })),
|
|
24
|
+
// Keys the deploy hides by default and the person may declare.
|
|
25
|
+
undeclared: keys => keys.filter(key => !open.has(key) && !secret.has(key) && !credentialName(key)),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// The declaration and setup manifest the deploy will read, loaded early so the
|
|
30
|
+
// redaction knows each value's kind. A project that cannot yield them yet
|
|
31
|
+
// declares nothing, so every --env-file value stays redacted and the deploy
|
|
32
|
+
// itself reports the real error.
|
|
33
|
+
export async function declaredSettings(project) {
|
|
34
|
+
let declaration, path, setupManifest = project.setupManifest;
|
|
35
|
+
if (!project.adapter) return {};
|
|
36
|
+
try { ({ path, value: declaration } = await (await import('./deploy-command.mjs')).declarationFor(project.root, project.adapter)); } catch { return {}; }
|
|
37
|
+
if (!setupManifest && project.adapter.setup) {
|
|
38
|
+
try { setupManifest = (await (await shared('setup-manifest.mjs')).loadInstallerSeed(project.root, project.adapter)).manifest; } catch { /* the lifecycle reports an invalid manifest */ }
|
|
39
|
+
}
|
|
40
|
+
return { declaration, path, setupManifest };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function undeclaredNotice(names, path) {
|
|
44
|
+
return `Undeclared --env-file settings stay out of rer's output: ${names.join(', ')}. To print one, declare it as a non-secret setting: add its name to "publicSettings" in ${path}.`;
|
|
45
|
+
}
|
package/cli/deploy.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { requireProductionAuth } from './production-auth.mjs';
|
|
|
2
2
|
import { readFile } from 'node:fs/promises';
|
|
3
3
|
import { deployDiagnostic, migrationFailure, providerFailure, assetFailure } from '../modules/deploy-kit/diagnostics.mjs';
|
|
4
4
|
import { shared } from './shared.mjs';
|
|
5
|
+
import { settingKinds } from './deploy-settings.mjs';
|
|
5
6
|
import { contained } from './project.mjs';
|
|
6
7
|
import { missing, invalid, refuse, RerError } from './errors.mjs';
|
|
7
8
|
import { ownerPlan, ownerWorkerName, localOnlyBinding } from '../modules/deploy-kit/owner.mjs';
|
|
@@ -15,6 +16,8 @@ import { committedSource } from './deploy-source.mjs';
|
|
|
15
16
|
import { hookState, forgetHookState } from './deploy-hook-record.mjs';
|
|
16
17
|
import { deploymentRecord } from './deployment-record.mjs';
|
|
17
18
|
import { cloudflareCredentials, missingCredentialsMessage } from './deploy-needs.mjs';
|
|
19
|
+
import { keptSecrets, keepSecrets, forgetSecrets } from './deploy-secrets.mjs';
|
|
20
|
+
import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
|
|
18
21
|
|
|
19
22
|
export function ownerDeploy(declarationPath, lifecycle) {
|
|
20
23
|
// rer verify serves the build with this declaration's vars and secrets.
|
|
@@ -26,9 +29,9 @@ export function ownerDeploy(declarationPath, lifecycle) {
|
|
|
26
29
|
if (local) throw refuse(`${declarationPath} names the local-only key ${local} as a deploy binding or secret. Remove it; local dev keys never reach a deployment.`);
|
|
27
30
|
const environment = options.environment ?? 'production';
|
|
28
31
|
const again = deployAgain(options);
|
|
29
|
-
const change = [options.remove && '--remove', options.setSecret && '--set-secret', options.unsetSecret && '--unset-secret'].filter(Boolean);
|
|
32
|
+
const change = [options.remove && '--remove', options.setSecret && '--set-secret', options.unsetSecret && '--unset-secret', options.rotateSecret && '--rotate-secret'].filter(Boolean);
|
|
30
33
|
// The command that finishes what this run started: the same verb, never a plain deploy in its place.
|
|
31
|
-
const retry = options.remove ? `${again} --remove --yes` : options.setSecret ? `${again} --set-secret ${options.setSecret}` : options.unsetSecret ? `${again} --unset-secret ${options.unsetSecret}` : again;
|
|
34
|
+
const retry = options.remove ? `${again} --remove --yes` : options.setSecret ? `${again} --set-secret ${options.setSecret}` : options.unsetSecret ? `${again} --unset-secret ${options.unsetSecret}` : options.rotateSecret ? `${again} --rotate-secret ${options.rotateSecret}` : again;
|
|
32
35
|
if (change.length > 1 || change.length && options.dryRun) throw invalid(`Use ${change.join(', ')}${options.dryRun ? ' and --dry-run' : ''} on separate runs.`);
|
|
33
36
|
if (options.remove && !options.yes) throw invalid(`${again} --remove deletes this environment's Worker and every D1, R2, KV and queue rer created for it, with their data. Add --yes to confirm.`);
|
|
34
37
|
const recordedState = change.length ? await deploymentRecord(root, options) : undefined;
|
|
@@ -39,8 +42,9 @@ export function ownerDeploy(declarationPath, lifecycle) {
|
|
|
39
42
|
production = await deployEnvironment({ root, options, declaration, setupManifest, settings: lifecycle.settings, localOnlyKeys });
|
|
40
43
|
await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed, adapter: lifecycle, declarationPath, options });
|
|
41
44
|
if (!options.dryRun) committedSource(root, options);
|
|
42
|
-
await lifecycle.run(root, {}, store, () => {}, signal, { verb: 'build', operationToken });
|
|
45
|
+
await withoutLocalSettings(root, { settings: lifecycle.settings, operationToken }, () => lifecycle.run(root, {}, store, () => {}, signal, { verb: 'build', operationToken }));
|
|
43
46
|
await checkBuild();
|
|
47
|
+
await refuseLocalEnvOutput(root);
|
|
44
48
|
}
|
|
45
49
|
if (options.dryRun) {
|
|
46
50
|
// Locally validate the real declaration/artifact without ownerTarget's
|
|
@@ -53,12 +57,13 @@ export function ownerDeploy(declarationPath, lifecycle) {
|
|
|
53
57
|
store.report('deploy: dry run complete; no deployment occurred and no provider request was made.');
|
|
54
58
|
return { dryRun: true, deployed: false };
|
|
55
59
|
}
|
|
56
|
-
const { env, supplied } = await deployEnvironment({ root, options, declaration, setupManifest, settings: lifecycle.settings, localOnlyKeys });
|
|
60
|
+
const { env, supplied, generated, reused, rotated } = await deployEnvironment({ root, options, declaration, setupManifest, settings: lifecycle.settings, localOnlyKeys });
|
|
61
|
+
const kept = keptSecrets(declaration, setupManifest);
|
|
57
62
|
if (cloudflareCredentials.some(name => !env[name]?.trim())) throw missing(missingCredentialsMessage(declaration, env));
|
|
58
63
|
const { main } = await import('../modules/deploy-kit/owner-cli.mjs');
|
|
59
|
-
const { createRedaction
|
|
64
|
+
const { createRedaction } = await shared('redaction.mjs');
|
|
60
65
|
const redaction = createRedaction();
|
|
61
|
-
redaction.addSecrets([...
|
|
66
|
+
redaction.addSecrets([...(await settingKinds({ declaration, setupManifest })).privateValues(env), env.CLOUDFLARE_ACCOUNT_ID, ...(declaration.secrets ?? []).map(item => env[item.environment]).filter(Boolean)]);
|
|
62
67
|
const claim = setupManifest?.steps?.find(item => item.type === 'owner-claim');
|
|
63
68
|
const declared = binding => (Array.isArray(declaration.secrets) ? declaration.secrets : []).find(item => item?.binding === binding);
|
|
64
69
|
const owner = (command, extra = [], values = env, more = {}) => main([command, '--declaration', declarationPath, '--environment', environment, ...extra], values, { cwd: root, localOnlyKeys, ...more });
|
|
@@ -72,9 +77,20 @@ export function ownerDeploy(declarationPath, lifecycle) {
|
|
|
72
77
|
step = 'remove';
|
|
73
78
|
const result = await owner('remove', state ? ['--state', state] : []);
|
|
74
79
|
await forgetHookState(root, environment);
|
|
80
|
+
await forgetSecrets(root, environment);
|
|
75
81
|
store.report(`Removed ${result.removed.join(', ') || 'nothing (already gone)'}; read back: none of them remains.`);
|
|
76
82
|
return { removed: result.removed, deployed: false };
|
|
77
83
|
}
|
|
84
|
+
if (options.rotateSecret) {
|
|
85
|
+
// The kit never replaces a secret its Worker holds: rotation is this explicit change, kept once it is live.
|
|
86
|
+
step = 'secrets';
|
|
87
|
+
for (const binding of rotated) {
|
|
88
|
+
await owner('secret', ['--set', binding, ...(state ? ['--state', state] : [])]);
|
|
89
|
+
await keepSecrets({ root, environment, kept, env, generated: [binding], reused: [], report: () => {} });
|
|
90
|
+
store.report(`Rotated ${binding} on this environment's Worker to a fresh value kept in .rer/deploy/${environment}.secrets.env, recorded its new version and verified hosted readiness.`);
|
|
91
|
+
}
|
|
92
|
+
return { rotated, deployed: false };
|
|
93
|
+
}
|
|
78
94
|
if (change.length) {
|
|
79
95
|
step = 'secrets';
|
|
80
96
|
const binding = options.setSecret ?? options.unsetSecret;
|
|
@@ -84,8 +100,11 @@ export function ownerDeploy(declarationPath, lifecycle) {
|
|
|
84
100
|
}
|
|
85
101
|
store.report(`Deploying the ${environment} environment to your Cloudflare account.`);
|
|
86
102
|
deployed = await owner('deploy', [], env, { notice: line => store.report(line), onCreated: resource => created.push(redaction.redact(resource)) });
|
|
87
|
-
|
|
88
|
-
|
|
103
|
+
// A generated value the kit did not send stays unknown: the Worker kept its own.
|
|
104
|
+
const sent = supplied.filter(name => deployed.sentSecrets.includes(name)), keptSent = [...generated, ...reused].filter(name => sent.includes(name));
|
|
105
|
+
await keepSecrets({ root, environment, kept, env, generated: generated.filter(name => sent.includes(name)), reused: reused.filter(name => sent.includes(name)), report: line => store.report(line) });
|
|
106
|
+
const other = sent.filter(name => !keptSent.includes(name));
|
|
107
|
+
if (other.length) store.report(`rer supplied ${other.join(', ')} from the local setup owner and fresh generated values.`);
|
|
89
108
|
if (deployed.optionalUnset) store.report(`Optional secrets not set: ${deployed.optionalUnset.join(', ')}. The application runs without them; set one later with ${again} --set-secret NAME.`);
|
|
90
109
|
step = 'health';
|
|
91
110
|
await owner('health', [], env, {propagation:deployed.propagation});
|
package/cli/export.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { cliVersion } from './version.mjs';
|
|
|
6
6
|
|
|
7
7
|
// Copy whole maintained source/tooling directories. Python publication scans
|
|
8
8
|
// load sibling modules and data dynamically; they belong in the inventory too.
|
|
9
|
-
export const sourceRoots = ['bin/rer.mjs', 'cli', 'modules/delivery-producer/declarations.mjs', 'modules/delivery-producer/bindings.mjs', 'modules/delivery-producer/migrations.mjs', 'modules/delivery-producer/mail.mjs', 'modules/job-queue', 'modules/release', 'modules/deploy-kit', 'modules/container', 'modules/demo-host', 'modules/demo', 'modules/integrations/core', 'modules/mail', 'modules/ai', 'modules/portability', 'modules/d1-transport', 'modules/erasure', 'modules/dependencies', 'modules/operator-auth', 'modules/owner-claim', 'operations', 'scripts/publish-check', 'scripts/publish-check.mjs', 'composition/git-source.mjs', 'edition-authoring/manifest.mjs', 'edition-authoring/files.mjs'];
|
|
9
|
+
export const sourceRoots = ['bin/rer.mjs', 'cli', 'modules/delivery-producer/declarations.mjs', 'modules/delivery-producer/bindings.mjs', 'modules/delivery-producer/migrations.mjs', 'modules/delivery-producer/mail.mjs', 'modules/job-queue', 'modules/release', 'modules/deploy-kit', 'modules/container', 'modules/demo-host', 'modules/demo', 'modules/integrations/core', 'modules/mail', 'modules/ai', 'modules/portability', 'modules/d1-transport', 'modules/erasure', 'modules/dependencies', 'modules/operator-auth', 'modules/owner-claim', 'operations', 'scripts/publish-check', 'scripts/publish-check.mjs', 'composition/git-source.mjs', 'edition-authoring/manifest.mjs', 'edition-authoring/files.mjs', 'foundation/runtime/seed-contract.mjs'];
|
|
10
10
|
export async function inventory(base, roots = sourceRoots) {
|
|
11
11
|
const files = [];
|
|
12
12
|
async function walk(path) {
|
package/cli/inspect.mjs
CHANGED
|
@@ -22,6 +22,7 @@ import { savedOrigin } from './door-mode.mjs';
|
|
|
22
22
|
import { probePnpm } from './pnpm-probe.mjs';
|
|
23
23
|
import { deliveryDeclarationClauses } from './delivery-declarations.mjs';
|
|
24
24
|
import { checkoutPlaceholderMarks } from './placeholder-mark.mjs';
|
|
25
|
+
import { contractStatusClauses } from './contract-status.mjs';
|
|
25
26
|
|
|
26
27
|
// cliVersion: the rer version of the code answering (absent for a vendored copy
|
|
27
28
|
// too old to record one). defaults: what a server start applies when the person
|
|
@@ -129,6 +130,7 @@ export async function check(project, explicitProfile) {
|
|
|
129
130
|
add('SC-08.portability', typeof adapter?.portability?.export === 'function' && typeof adapter?.portability?.import === 'function', 'Adopt the reviewed mainline complete local portability API; archive support remains unavailable until then.');
|
|
130
131
|
if (adapter?.devIdentity) for (const [id, ok, message] of await devIdentityClauses(project.root, adapter)) add(id, ok, message);
|
|
131
132
|
for (const [id, ok, message] of await authCopyClauses(project.root)) add(id, ok, message);
|
|
133
|
+
clauses.push(...await contractStatusClauses(project.root));
|
|
132
134
|
placeholderMarks = await checkoutPlaceholderMarks(project.root, project.descriptor.project);
|
|
133
135
|
}
|
|
134
136
|
for(const issue of await localAiDiagnostics(project,process.env))add('AI.'+issue.feature,false,issue.code+': '+issue.message);
|
package/cli/lifecycle.mjs
CHANGED
|
@@ -15,6 +15,7 @@ import { runtimeFrontDoor } from './runtime-front-door.mjs';
|
|
|
15
15
|
import { localCliSessionProof, localSettingKeys } from './settings.mjs';
|
|
16
16
|
import { rememberSetupAnswers } from './setup-answers.mjs';
|
|
17
17
|
import { ensureDevKey, refuseDevLayerOutput } from './dev-identity.mjs';
|
|
18
|
+
import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
|
|
18
19
|
import { announceDoorRoute } from './door-mode.mjs';
|
|
19
20
|
|
|
20
21
|
export async function runCommand(project, options, out) {
|
|
@@ -22,7 +23,7 @@ export async function runCommand(project, options, out) {
|
|
|
22
23
|
const { validateDeployOptions } = await import('./deploy-command.mjs');
|
|
23
24
|
validateDeployOptions(options);
|
|
24
25
|
const { withDeployEnvironment } = await import('./deploy-inputs.mjs');
|
|
25
|
-
return withDeployEnvironment(project
|
|
26
|
+
return withDeployEnvironment(project, options, out, redaction => runLifecycle(project, options, out, redaction));
|
|
26
27
|
}
|
|
27
28
|
return runLifecycle(project, options, out);
|
|
28
29
|
}
|
|
@@ -120,10 +121,15 @@ async function runLifecycle(project, options, out, deployRedaction) {
|
|
|
120
121
|
if (options.verb === 'setup') { proxy = await runtimeFrontDoor({ ...selected, devKey: devKey ?? undefined, origin: selected.url }); if (selected.door) await announceDoorRoute(selected, proxy); }
|
|
121
122
|
const { appFetch } = await shared('app-fetch.mjs');
|
|
122
123
|
const emailKey = localSettingKeys(project).email;
|
|
123
|
-
|
|
124
|
+
const privateSettings = [...adapter.settings, '.rer/local/models.json', ...(project.privateInputs??[])];
|
|
125
|
+
const run = () => adapter.run(project.root, input ?? { [emailKey]: options.ownerEmail ?? selected?.vars[emailKey] }, store,
|
|
124
126
|
child => { app = child; }, signal,
|
|
125
|
-
{ verb: options.verb, ownerKey: emailKey, selectedOrigin: selected?.url, runtimePort: proxy?.runtimePort, operationToken: operation?.token, dev: adapter.dev, privateSettings
|
|
127
|
+
{ verb: options.verb, ownerKey: emailKey, selectedOrigin: selected?.url, runtimePort: proxy?.runtimePort, operationToken: operation?.token, dev: adapter.dev, privateSettings, devKey: devKey ?? undefined });
|
|
128
|
+
// A production build never sees the checkout's local settings, whatever the seed's build runs.
|
|
129
|
+
if (options.verb === 'build') await withoutLocalSettings(project.root, { settings: privateSettings, operationToken: operation?.token }, run);
|
|
130
|
+
else await run();
|
|
126
131
|
if (['setup', 'build'].includes(options.verb)) await refuseDevLayerOutput(project.root, adapter.devIdentity);
|
|
132
|
+
if (options.verb === 'build') await refuseLocalEnvOutput(project.root, adapter.devIdentity?.output);
|
|
127
133
|
const url = selected?.url;
|
|
128
134
|
if (options.verb === 'setup') {
|
|
129
135
|
// Only a connected provider leaves first setup open; a native claim with
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { refuse } from './errors.mjs';
|
|
2
|
+
import { shared } from './shared.mjs';
|
|
3
|
+
import { refuseLocalEnvFiles } from '../modules/deploy-kit/local-only.mjs';
|
|
4
|
+
|
|
5
|
+
// Wrangler (and the Cloudflare Vite plugin through it) reads .dev.vars, then .env
|
|
6
|
+
// and process.env, and writes what it read into dist/<worker>/.dev.vars. During a
|
|
7
|
+
// deploy process.env holds the deployment's secrets.
|
|
8
|
+
const switches = { CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV: 'false', CLOUDFLARE_INCLUDE_PROCESS_ENV: 'false' };
|
|
9
|
+
|
|
10
|
+
// Every build rer runs for a deployment, and a seed's own deploy hook, runs with
|
|
11
|
+
// the checkout's local settings files moved aside (restored afterwards, or by the
|
|
12
|
+
// next operation after a hard kill) and those Wrangler sources switched off, so
|
|
13
|
+
// no bundler can copy local credentials into what is uploaded.
|
|
14
|
+
export async function withoutLocalSettings(root, { settings = [], operationToken } = {}, action) {
|
|
15
|
+
const { withoutLocalVariables } = await shared('local/build.mjs');
|
|
16
|
+
const saved = Object.fromEntries(Object.keys(switches).map(key => [key, process.env[key]]));
|
|
17
|
+
return withoutLocalVariables(root, async () => {
|
|
18
|
+
Object.assign(process.env, switches);
|
|
19
|
+
try { return await action(); }
|
|
20
|
+
finally { for (const [key, value] of Object.entries(saved)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } }
|
|
21
|
+
}, { nested: operationToken, settings: ['.dev.vars', '.dev.vars.previous', ...(Array.isArray(settings) ? settings : []).filter(path => typeof path === 'string')] });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// rer build and rer deploy refuse build output that holds a local settings file,
|
|
25
|
+
// naming it. `uploaded` says a deploy hook has already sent its build.
|
|
26
|
+
export async function refuseLocalEnvOutput(root, outputs, { uploaded = false } = {}) {
|
|
27
|
+
try { await refuseLocalEnvFiles(root, outputs ?? ['dist']); }
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (!error.resource) throw error;
|
|
30
|
+
if (uploaded) throw refuse(`The deploy hook's build output holds the local settings file ${error.resource}, and the hook has already uploaded its build, so it may be on the live Worker. Remove what copies it into the build output, rotate every credential in that file, then run rer deploy again.`);
|
|
31
|
+
throw refuse(`The build output holds the local settings file ${error.resource}; a deployment never carries one. Remove what puts it there (a file in public/, or a build step that copies it), then run the command again. Nothing was uploaded.`);
|
|
32
|
+
}
|
|
33
|
+
}
|
package/cli/parse.mjs
CHANGED
|
@@ -84,9 +84,10 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
|
|
|
84
84
|
if (options.profile !== undefined && options.profile !== 'first-party') throw invalid('The supported explicit profile is first-party.');
|
|
85
85
|
if (options.environment !== undefined && !/^[a-z][a-z0-9-]{0,39}$/.test(options.environment)) throw invalid('Provide a valid deployment environment name.');
|
|
86
86
|
for (const key of ['setSecret', 'unsetSecret']) if (options[key] !== undefined && !/^[A-Z][A-Z0-9_]{0,63}$/.test(options[key])) throw invalid('Name a declared secret binding, such as SESSION_SECRET.');
|
|
87
|
-
if(
|
|
87
|
+
if (options.rotateSecret !== undefined && !/^[A-Z][A-Z0-9_]{0,63}(?:,[A-Z][A-Z0-9_]{0,63}){0,15}$/.test(options.rotateSecret)) throw invalid('--rotate-secret names generated secret bindings, separated by commas, such as SESSION_SECRET.');
|
|
88
|
+
if(verb==='deploy'&&options.demo&&(options.site||['platform','image','bindAddress','httpPort','httpsPort','envFile','host','setSecret','unsetSecret','rotateSecret'].some(key=>options[key]!==undefined)))throw invalid('--demo takes only --environment, --dry-run and --remove --yes: the hosted demo is its own Worker on demo.<domain>.');
|
|
88
89
|
if(verb==='deploy'&&options.demo&&options.remove&&(options.dryRun||!options.yes))throw invalid(options.dryRun?'Use --remove and --dry-run on separate runs.':'deploy --demo --remove deletes the hosted demo\'s Worker, its demo.<domain> Custom Domain. Add --yes to confirm.');
|
|
89
|
-
if ((options.remove || options.setSecret || options.unsetSecret) && options.site) throw invalid('--remove, --set-secret and --
|
|
90
|
+
if ((options.remove || options.setSecret || options.unsetSecret || options.rotateSecret) && options.site) throw invalid('--remove, --set-secret, --unset-secret and --rotate-secret act on the application Worker, not the run site.');
|
|
90
91
|
if (options.origin !== undefined) {
|
|
91
92
|
let url; try { url = new URL(options.origin); } catch { throw invalid('Provide a valid credential-free origin.'); }
|
|
92
93
|
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== '/') throw invalid('Provide a credential-free HTTP origin without a path.');
|
package/cli/signin.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
|
|
|
3
3
|
import { deploymentRecord } from './deployment-record.mjs';
|
|
4
4
|
import { invalid, missing, refuse, RerError } from './errors.mjs';
|
|
5
5
|
import { shared } from './shared.mjs';
|
|
6
|
+
import { settingKinds } from './deploy-settings.mjs';
|
|
6
7
|
import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
|
|
7
8
|
import { deployDiagnostic, providerRefusal } from '../modules/deploy-kit/diagnostics.mjs';
|
|
8
9
|
|
|
@@ -18,9 +19,9 @@ export async function signinCommand(project, options, out, { fetch } = {}) {
|
|
|
18
19
|
const state = await deploymentRecord(root, { ...options, verb: 'signin' });
|
|
19
20
|
const { env } = await deployEnvironment({ root, options, declaration, localOnlyKeys: project.adapter.localOnlyKeys ?? [] });
|
|
20
21
|
if (['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN'].some(name => !env[name]?.trim())) throw missing('rer signin uses the Cloudflare credentials that deployed this environment: set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN in the environment or an --env-file, then run it again.');
|
|
21
|
-
const { createRedaction
|
|
22
|
+
const { createRedaction } = await shared('redaction.mjs');
|
|
22
23
|
const redaction = createRedaction();
|
|
23
|
-
redaction.addSecrets([...
|
|
24
|
+
redaction.addSecrets([...(await settingKinds({ declaration, setupManifest: project.setupManifest })).privateValues(env), env.CLOUDFLARE_ACCOUNT_ID]);
|
|
24
25
|
let result;
|
|
25
26
|
try { result = await owner(['signin', '--declaration', path, '--environment', environment, ...(state ? ['--state', state] : [])], env, { cwd: root, localOnlyKeys: project.adapter.localOnlyKeys ?? [], ...(fetch ? { fetch } : {}) }); }
|
|
26
27
|
catch (error) { throw failure(error, { environment, again, adapter: project.adapter, redact: redaction.redact }); }
|
package/cli/site-render.mjs
CHANGED
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
// entry's CSS imports compile to. The optional site config is a Vite config
|
|
8
8
|
// naming the plugins the site pages need (a docs virtual module, a CSS
|
|
9
9
|
// toolchain); the app's own Vite config is never loaded, because its Worker
|
|
10
|
-
// plugins do not run in Node. It reads no installation data.
|
|
10
|
+
// plugins do not run in Node. It reads no installation data. A seed with a
|
|
11
|
+
// CONTRACT.md gets it parsed as sitePages({ contract }), for its /contract
|
|
12
|
+
// page; one that does not parse stops the build, naming its lines.
|
|
11
13
|
// Usage: node site-render.mjs ROOT ENTRY OUTPUT [CONFIG]
|
|
12
14
|
import { cp, lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
13
15
|
import { createRequire } from 'node:module';
|
|
@@ -15,6 +17,7 @@ import { dirname, join, resolve, sep } from 'node:path';
|
|
|
15
17
|
import { pathToFileURL } from 'node:url';
|
|
16
18
|
import { buildClients, writeSiteAsset } from './site-client.mjs';
|
|
17
19
|
import { redactSiteOutput, siteBuildDiagnostic } from './site-diagnostics.mjs';
|
|
20
|
+
import { ContractError, parseContract } from '../foundation/runtime/seed-contract.mjs';
|
|
18
21
|
|
|
19
22
|
redactSiteOutput();
|
|
20
23
|
|
|
@@ -30,6 +33,13 @@ try { vite = await import(pathToFileURL(createRequire(join(root, 'package.json')
|
|
|
30
33
|
catch { fail('The run site renders with the checkout\'s own Vite. Run rer install first.'); }
|
|
31
34
|
process.env.NODE_ENV ??= 'production';
|
|
32
35
|
|
|
36
|
+
let contract;
|
|
37
|
+
try { contract = parseContract(await readFile(join(root, 'CONTRACT.md'), 'utf8')); }
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error instanceof ContractError) fail(`The run site's /contract page is built from CONTRACT.md, which does not parse:\n${error.message}`);
|
|
40
|
+
if (error.code !== 'ENOENT') throw error;
|
|
41
|
+
}
|
|
42
|
+
|
|
33
43
|
// The Node bundle sits beside the output, inside the checkout, so its external
|
|
34
44
|
// imports resolve from the checkout's node_modules. It never enters the site.
|
|
35
45
|
const server = `${output}.render`;
|
|
@@ -52,7 +62,7 @@ try {
|
|
|
52
62
|
if (typeof module.sitePages !== 'function') fail(`${entry} must export sitePages(), returning { pages: [{ path, html }], assets: [public paths] }.`);
|
|
53
63
|
const clientBuild = await buildClients(vite, root, output, clientJSON ? JSON.parse(clientJSON) : {}), clients = clientBuild.clients;
|
|
54
64
|
styles = [...new Set([...styles,...clientBuild.styles])];
|
|
55
|
-
const build = await module.sitePages({ styles, clients });
|
|
65
|
+
const build = await module.sitePages({ styles, clients, ...(contract ? { contract } : {}) });
|
|
56
66
|
if (!Array.isArray(build?.pages) || !Array.isArray(build.assets)) fail('sitePages() returns { pages, assets }.');
|
|
57
67
|
|
|
58
68
|
const written = new Set();
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// A seed's CONTRACT.md as data: the product target, the clauses it defines,
|
|
2
|
+
// and its Status table. `rer check` validates it and the run site's /contract
|
|
3
|
+
// page is built from it, so both read the contract through this one parser.
|
|
4
|
+
// The shape it accepts is documented in SEED-COMMAND-CONTRACT.md ("Contract
|
|
5
|
+
// status"). It throws a ContractError listing every problem, each with the
|
|
6
|
+
// CONTRACT.md line it is on; it never guesses a missing value.
|
|
7
|
+
// Plain JavaScript (types in seed-contract.d.mts) so the rer CLI runs it under
|
|
8
|
+
// Node and the seed's Vite site build imports it from src/base.
|
|
9
|
+
|
|
10
|
+
export const kinds = Object.freeze(['published', 'target', 'push-further'])
|
|
11
|
+
export const statuses = Object.freeze(['done', 'partial', 'missing'])
|
|
12
|
+
export const statusHeader = Object.freeze(['Clause', 'Title', 'Kind', 'Status', 'Evidence', 'Gap'])
|
|
13
|
+
const summaryHeader = ['Clauses', 'Done', 'Partial', 'Missing', 'Total']
|
|
14
|
+
|
|
15
|
+
// The one clause-ID rule, shared with the release catalogue: uppercase words
|
|
16
|
+
// and a two- or three-digit number joined by hyphens (HOME-001, PAN-01), or the
|
|
17
|
+
// legacy hyphenless form of up to four capitals and a number (E1, A7).
|
|
18
|
+
export const clauseIdSource = '(?:[A-Z][A-Z0-9]*(?:-[A-Z][A-Z0-9]*)*-[0-9]{2,3}|[A-Z]{1,4}[0-9]{1,3})'
|
|
19
|
+
const id = clauseIdSource
|
|
20
|
+
const clauseId = new RegExp(`^${id}$`)
|
|
21
|
+
const dash = '\\s+[—–-]\\s+'
|
|
22
|
+
// The three ways a contract defines a clause: a bold bullet, a bold paragraph
|
|
23
|
+
// or a heading, each "ID — Title." at the start of its line.
|
|
24
|
+
const definitions = [
|
|
25
|
+
new RegExp(`^-\\s+\\*\\*(${id})${dash}(.+?)\\*\\*`),
|
|
26
|
+
new RegExp(`^\\*\\*(${id})${dash}(.+?)\\*\\*`),
|
|
27
|
+
new RegExp(`^#{2,6}\\s+(${id})${dash}(.+?)\\s*#*\\s*$`),
|
|
28
|
+
]
|
|
29
|
+
const heading = /^(#{1,6})\s+(.+?)\s*#*\s*$/
|
|
30
|
+
const judged = /^Judged from the code and tests at commit `([0-9a-f]{7,40})` \(([^)]+)\)[.;:]/
|
|
31
|
+
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
|
|
32
|
+
|
|
33
|
+
export class ContractError extends Error {
|
|
34
|
+
constructor(file, problems) {
|
|
35
|
+
super(problems.map(problem => `${file}:${problem.line}: ${problem.message}`).join('\n'))
|
|
36
|
+
this.name = 'ContractError'
|
|
37
|
+
this.file = file
|
|
38
|
+
this.problems = problems
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Markdown inline text as plain text: links keep their label; emphasis and code marks go. */
|
|
43
|
+
export function plainText(value) {
|
|
44
|
+
return value.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\*\*|__|`/g, '').replace(/(^|\W)[*_](\S[^*_]*?)[*_](?=\W|$)/g, '$1$2').trim()
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const cleanTitle = value => plainText(value).replace(/[.:]$/, '').trim()
|
|
48
|
+
|
|
49
|
+
function cells(line) {
|
|
50
|
+
const body = line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '')
|
|
51
|
+
return body.split(/(?<!\\)\|/).map(cell => cell.trim().replace(/\\\|/g, '|'))
|
|
52
|
+
}
|
|
53
|
+
const isTableLine = line => line.trimStart().startsWith('|')
|
|
54
|
+
const isDivider = line => /^\|?(\s*:?-{3,}:?\s*\|)+\s*:?-{0,}:?\s*$/.test(line.trim())
|
|
55
|
+
|
|
56
|
+
function isoDate(text) {
|
|
57
|
+
let year, month, day
|
|
58
|
+
const written = /^(\d{1,2}) ([A-Z][a-z]+) (\d{4})$/.exec(text), iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text)
|
|
59
|
+
if (written && months.includes(written[2])) [day, month, year] = [Number(written[1]), months.indexOf(written[2]) + 1, Number(written[3])]
|
|
60
|
+
else if (iso) [year, month, day] = iso.slice(1).map(Number)
|
|
61
|
+
else return undefined
|
|
62
|
+
const date = new Date(Date.UTC(year, month - 1, day))
|
|
63
|
+
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return undefined
|
|
64
|
+
return date.toISOString().slice(0, 10)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Every heading outside fenced code, with the 1-based line it is on.
|
|
68
|
+
function outline(lines) {
|
|
69
|
+
const headings = []
|
|
70
|
+
let fence
|
|
71
|
+
lines.forEach((line, index) => {
|
|
72
|
+
const marker = /^\s*(```|~~~)/.exec(line)?.[1]
|
|
73
|
+
if (marker) { fence = fence === marker ? undefined : fence ?? marker; return }
|
|
74
|
+
if (fence) return
|
|
75
|
+
const match = heading.exec(line)
|
|
76
|
+
if (match) headings.push({ level: match[1].length, text: plainText(match[2]), line: index + 1 })
|
|
77
|
+
})
|
|
78
|
+
return headings
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The section a heading opens: its line through the line before the next
|
|
82
|
+
// heading at its level or above.
|
|
83
|
+
function sectionEnd(headings, start, lineCount) {
|
|
84
|
+
const next = headings.find(other => other.line > start.line && other.level <= start.level)
|
|
85
|
+
return next ? next.line - 1 : lineCount
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function readTarget(lines, headings, problems) {
|
|
89
|
+
const section = headings.find(entry => entry.level === 2 && /^Product target\b/i.test(entry.text))
|
|
90
|
+
if (!section) { problems.push({ line: 1, message: 'CONTRACT.md has no "## Product target" section with its Category, Incumbents and First buyer table.' }); return undefined }
|
|
91
|
+
const end = sectionEnd(headings, section, lines.length), found = {}
|
|
92
|
+
for (let line = section.line + 1; line <= end; line++) {
|
|
93
|
+
const text = lines[line - 1]
|
|
94
|
+
if (!isTableLine(text) || isDivider(text)) continue
|
|
95
|
+
const [label = '', value = ''] = cells(text), name = plainText(label).toLowerCase()
|
|
96
|
+
const key = name === 'category' ? 'category' : name.startsWith('incumbents') ? 'incumbents' : name === 'first buyer' ? 'firstBuyer' : /\balso beat\b/.test(name) ? 'alsoBeats' : undefined
|
|
97
|
+
if (key && !found[key]) found[key] = { value: plainText(value), line }
|
|
98
|
+
}
|
|
99
|
+
for (const [key, label] of [['category', 'Category'], ['incumbents', 'Incumbents a buyer switches from'], ['firstBuyer', 'First buyer']])
|
|
100
|
+
if (!found[key]?.value) problems.push({ line: found[key]?.line ?? section.line, message: `The Product target table needs a non-empty "${label}" row.` })
|
|
101
|
+
if (!found.category?.value || !found.incumbents?.value || !found.firstBuyer?.value) return undefined
|
|
102
|
+
const incumbents = found.incumbents.value.split(/\s*,\s*|\s+(?:and|or)\s+/).map(name => name.trim()).filter(Boolean)
|
|
103
|
+
return { category: found.category.value, incumbents, replaces: found.incumbents.value, alsoBeats: found.alsoBeats?.value || null, firstBuyer: found.firstBuyer.value }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** An area's anchor: "Archive, trash and deletion" -> "archive-trash-and-deletion". */
|
|
107
|
+
export function areaSlug(name) {
|
|
108
|
+
return name.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
|
109
|
+
}
|
|
110
|
+
// Target and push-further areas sit under (or are) a heading starting
|
|
111
|
+
// "Target clauses" or "Push further"; every other area is published.
|
|
112
|
+
const targetSection = /^(?:Target clauses|Push further)\b/i
|
|
113
|
+
function areaGroup(headings, area) {
|
|
114
|
+
let level = area.level + 1
|
|
115
|
+
for (const entry of headings.filter(other => other.line <= area.line).reverse()) {
|
|
116
|
+
if (entry.level >= level) continue
|
|
117
|
+
if (targetSection.test(entry.text)) return 'target'
|
|
118
|
+
level = entry.level
|
|
119
|
+
}
|
|
120
|
+
return 'published'
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Clause definitions everywhere except the Status section and retired-ID
|
|
124
|
+
// sections. The area is the nearest heading above that is not a clause.
|
|
125
|
+
// A clause's own "*Status:* partial." line, kept beside its text, is recorded
|
|
126
|
+
// so a row that disagrees with it is refused.
|
|
127
|
+
function readDefinitions(lines, headings, skipped, problems) {
|
|
128
|
+
const defined = new Map(), areas = new Map(), slugs = new Map()
|
|
129
|
+
let fence, current
|
|
130
|
+
lines.forEach((text, index) => {
|
|
131
|
+
const line = index + 1
|
|
132
|
+
const marker = /^\s*(```|~~~)/.exec(text)?.[1]
|
|
133
|
+
if (marker) { fence = fence === marker ? undefined : fence ?? marker; return }
|
|
134
|
+
if (fence || skipped.some(([start, end]) => line >= start && line <= end)) { current = undefined; return }
|
|
135
|
+
const match = definitions.map(pattern => pattern.exec(text)).find(Boolean)
|
|
136
|
+
if (!match) {
|
|
137
|
+
if (heading.test(text)) current = undefined
|
|
138
|
+
const stated = /^\*{1,2}Status:\*{1,2}\s*(done|partial|missing)\b/.exec(text)
|
|
139
|
+
if (stated && current && !current.stated) current.stated = { status: stated[1], line }
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
const area = headings.filter(entry => entry.line < line && !definitions[2].test(lines[entry.line - 1])).at(-1)
|
|
143
|
+
const [, clause, title] = match
|
|
144
|
+
if (defined.has(clause)) { problems.push({ line, message: `${clause} is defined twice (first at line ${defined.get(clause).line}).` }); return }
|
|
145
|
+
if (!area) { problems.push({ line, message: `${clause} is defined above every section heading, so it has no area.` }); return }
|
|
146
|
+
current = { id: clause, title: cleanTitle(title), area: area.text, line }
|
|
147
|
+
defined.set(clause, current)
|
|
148
|
+
const group = areaGroup(headings, area), known = areas.get(area.text)
|
|
149
|
+
if (known && known.group !== group) problems.push({ line: area.line, message: `Area "${area.text}" is a ${group} area here but a ${known.group} area at line ${known.line}; give one of them its own name.` })
|
|
150
|
+
if (known) return
|
|
151
|
+
const slug = areaSlug(area.text)
|
|
152
|
+
if (!slug) problems.push({ line: area.line, message: `Area "${area.text}" has no letters or digits to make its #area- link from.` })
|
|
153
|
+
else if (slugs.has(slug)) problems.push({ line: area.line, message: `Area "${area.text}" has the same link (#area-${slug}) as "${slugs.get(slug).text}" at line ${slugs.get(slug).line}; rename one.` })
|
|
154
|
+
else slugs.set(slug, area)
|
|
155
|
+
areas.set(area.text, { name: area.text, slug, group, line: area.line })
|
|
156
|
+
})
|
|
157
|
+
return { defined, areas }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function readSummary(lines, start, problems) {
|
|
161
|
+
const rows = []
|
|
162
|
+
for (let line = start + 2; line <= lines.length && isTableLine(lines[line - 1]); line++) {
|
|
163
|
+
const [label, ...numbers] = cells(lines[line - 1])
|
|
164
|
+
const values = numbers.map(value => /^\d+$/.test(value) ? Number(value) : NaN)
|
|
165
|
+
if (values.length !== 4 || values.some(Number.isNaN)) { problems.push({ line, message: 'A summary row is a label and four whole numbers: Done, Partial, Missing, Total.' }); continue }
|
|
166
|
+
rows.push({ line, label: plainText(label), done: values[0], partial: values[1], missing: values[2], total: values[3] })
|
|
167
|
+
}
|
|
168
|
+
return rows
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Which kinds a summary row counts: "All", or kinds joined by "and".
|
|
172
|
+
function summaryKinds(label) {
|
|
173
|
+
const name = label.toLowerCase()
|
|
174
|
+
if (name === 'all' || name === 'total') return kinds
|
|
175
|
+
const parts = name.split(/\s*,\s*|\s+and\s+/).map(part => part === 'push further' ? 'push-further' : part)
|
|
176
|
+
return parts.every(part => kinds.includes(part)) ? parts : undefined
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function checkSummaries(summaries, sentences, clauses, problems) {
|
|
180
|
+
const count = selected => {
|
|
181
|
+
const rows = clauses.filter(clause => selected.includes(clause.kind))
|
|
182
|
+
return { done: rows.filter(row => row.status === 'done').length, partial: rows.filter(row => row.status === 'partial').length, missing: rows.filter(row => row.status === 'missing').length, total: rows.length }
|
|
183
|
+
}
|
|
184
|
+
for (const row of summaries) {
|
|
185
|
+
const selected = summaryKinds(row.label)
|
|
186
|
+
if (!selected) { problems.push({ line: row.line, message: `Summary row "${row.label}" names no kind: use All, Published, Target, Push further, or kinds joined by "and".` }); continue }
|
|
187
|
+
const actual = count(selected)
|
|
188
|
+
const wrong = ['done', 'partial', 'missing', 'total'].filter(key => row[key] !== actual[key])
|
|
189
|
+
if (wrong.length) problems.push({ line: row.line, message: `Summary row "${row.label}" says ${wrong.map(key => `${row[key]} ${key}`).join(', ')}; the Status table has ${wrong.map(key => `${actual[key]} ${key}`).join(', ')}.` })
|
|
190
|
+
}
|
|
191
|
+
const all = count(kinds)
|
|
192
|
+
for (const sentence of sentences) {
|
|
193
|
+
const wrong = ['total', 'done', 'partial', 'missing'].filter(key => sentence[key] !== undefined && sentence[key] !== all[key])
|
|
194
|
+
if (wrong.length) problems.push({ line: sentence.line, message: `The summary says ${wrong.map(key => `${sentence[key]} ${key === 'total' ? 'clauses' : key}`).join(', ')}; the Status table has ${wrong.map(key => `${all[key]} ${key === 'total' ? 'clauses' : key}`).join(', ')}.` })
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Parse CONTRACT.md text. `file` names it in error messages.
|
|
200
|
+
* @returns {import('./seed-contract.d.mts').SeedContract}
|
|
201
|
+
*/
|
|
202
|
+
export function parseContract(text, { file = 'CONTRACT.md' } = {}) {
|
|
203
|
+
if (typeof text !== 'string') throw new TypeError('parseContract takes the CONTRACT.md text.')
|
|
204
|
+
const lines = text.replace(/\r\n?/g, '\n').split('\n'), headings = outline(lines), problems = []
|
|
205
|
+
const statusHeading = headings.filter(entry => entry.level === 2 && entry.text === 'Status')
|
|
206
|
+
if (statusHeading.length !== 1) throw new ContractError(file, [statusHeading.length ? { line: statusHeading[1].line, message: 'CONTRACT.md has more than one "## Status" section.' } : { line: lines.length, message: 'CONTRACT.md has no "## Status" section.' }])
|
|
207
|
+
const status = statusHeading[0], statusEnd = sectionEnd(headings, status, lines.length)
|
|
208
|
+
const skipped = [[status.line, statusEnd], ...headings.filter(entry => /^Retired\b/i.test(entry.text)).map(entry => [entry.line, sectionEnd(headings, entry, lines.length)])]
|
|
209
|
+
const target = readTarget(lines, headings, problems)
|
|
210
|
+
const { defined, areas: areaHeadings } = readDefinitions(lines, headings, skipped, problems)
|
|
211
|
+
|
|
212
|
+
// The judged-at line opens the section.
|
|
213
|
+
let commit, date
|
|
214
|
+
const first = lines.slice(status.line, statusEnd).findIndex(line => line.trim()) + status.line + 1
|
|
215
|
+
const opening = first > status.line ? judged.exec(lines[first - 1].trim()) : null
|
|
216
|
+
if (!opening) problems.push({ line: first > status.line ? first : status.line, message: 'The Status section opens with "Judged from the code and tests at commit `<sha>` (<date>)."' })
|
|
217
|
+
else {
|
|
218
|
+
commit = opening[1]
|
|
219
|
+
date = isoDate(opening[2])
|
|
220
|
+
if (!date) problems.push({ line: first, message: `"${opening[2]}" is not a date: write it as 16 October 2026 or 2026-10-16.` })
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// The section's tables: optional summaries, then exactly one clause table.
|
|
224
|
+
const summaries = [], sentences = [], clauses = [], rows = new Map()
|
|
225
|
+
let tableLine, wrongHeader
|
|
226
|
+
for (let line = status.line + 1; line <= statusEnd; line++) {
|
|
227
|
+
const textLine = lines[line - 1]
|
|
228
|
+
const sentence = /\b(\d+) clauses?:\s*(\d+) done,\s*(\d+) partial(?:,| and)\s*(\d+) missing\b/i.exec(textLine)
|
|
229
|
+
if (sentence) sentences.push({ line, total: Number(sentence[1]), done: Number(sentence[2]), partial: Number(sentence[3]), missing: Number(sentence[4]) })
|
|
230
|
+
if (!isTableLine(textLine)) continue
|
|
231
|
+
const header = cells(textLine)
|
|
232
|
+
let end = line
|
|
233
|
+
while (end + 1 <= statusEnd && isTableLine(lines[end])) end++
|
|
234
|
+
if (!isDivider(lines[line] ?? '')) problems.push({ line: line + 1, message: 'A table header is followed by its |---| divider line.' })
|
|
235
|
+
if (header.join('|') === summaryHeader.join('|')) summaries.push(...readSummary(lines, line, problems))
|
|
236
|
+
else if (tableLine) problems.push({ line, message: `The Status section has one clause table (at line ${tableLine}); this is a second table.` })
|
|
237
|
+
else if (header.join('|') !== statusHeader.join('|')) { wrongHeader = true; problems.push({ line, message: `The Status table header is | ${statusHeader.join(' | ')} |, not | ${header.join(' | ')} |.` }) }
|
|
238
|
+
else {
|
|
239
|
+
tableLine = line
|
|
240
|
+
if (end < line + 2) problems.push({ line, message: 'The Status table has no rows: it holds one row per clause the contract defines.' })
|
|
241
|
+
for (let rowLine = line + 2; rowLine <= end; rowLine++) {
|
|
242
|
+
const row = cells(lines[rowLine - 1])
|
|
243
|
+
if (row.length !== statusHeader.length) { problems.push({ line: rowLine, message: `A Status row has ${statusHeader.length} cells (${statusHeader.join(', ')}); this one has ${row.length}.` }); continue }
|
|
244
|
+
const [clauseCell, titleCell, kind, state, evidenceCell, gapCell] = row, clause = plainText(clauseCell), title = cleanTitle(titleCell)
|
|
245
|
+
if (!clauseId.test(clause)) { problems.push({ line: rowLine, message: `"${clauseCell}" is not a clause ID such as HOME-001.` }); continue }
|
|
246
|
+
if (rows.has(clause)) { problems.push({ line: rowLine, message: `${clause} has a second Status row (the first is at line ${rows.get(clause)}).` }); continue }
|
|
247
|
+
rows.set(clause, rowLine)
|
|
248
|
+
const definition = defined.get(clause)
|
|
249
|
+
if (!definition) problems.push({ line: rowLine, message: `${clause} has a Status row but CONTRACT.md defines no such clause.` })
|
|
250
|
+
else if (title && title !== definition.title) problems.push({ line: rowLine, message: `${clause} is titled "${title}" here but "${definition.title}" where it is defined (line ${definition.line}).` })
|
|
251
|
+
if (definition?.stated && statuses.includes(state) && definition.stated.status !== state) problems.push({ line: rowLine, message: `${clause} is ${state} here but its own Status line says ${definition.stated.status} (line ${definition.stated.line}).` })
|
|
252
|
+
if (!kinds.includes(kind)) problems.push({ line: rowLine, message: `${clause} kind "${kind}" is not one of ${kinds.join(', ')}.` })
|
|
253
|
+
if (!statuses.includes(state)) problems.push({ line: rowLine, message: `${clause} status "${state}" is not one of ${statuses.join(', ')}.` })
|
|
254
|
+
if (!title) problems.push({ line: rowLine, message: `${clause} has no title.` })
|
|
255
|
+
const evidence = [...evidenceCell.matchAll(/`([^`]+)`/g)].map(match => match[1].trim()).filter(Boolean), gap = plainText(gapCell)
|
|
256
|
+
if (state === 'done' && !evidence.length) problems.push({ line: rowLine, message: `${clause} is done, so its Evidence names the repository path that proves it, in backticks.` })
|
|
257
|
+
if (state === 'partial' && !evidence.length) problems.push({ line: rowLine, message: `${clause} is partial, so its Evidence names the repository path that backs it, in backticks.` })
|
|
258
|
+
if ((state === 'partial' || state === 'missing') && !gap) problems.push({ line: rowLine, message: `${clause} is ${state}, so its Gap says what is missing.` })
|
|
259
|
+
if (definition && kinds.includes(kind) && statuses.includes(state)) clauses.push({ id: clause, title, kind, status: state, evidence, gap, area: definition.area, line: definition.line, row: rowLine })
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
line = end
|
|
263
|
+
}
|
|
264
|
+
if (!tableLine) { if (!wrongHeader) problems.push({ line: status.line, message: `The Status section has no | ${statusHeader.join(' | ')} | table.` }) }
|
|
265
|
+
else for (const definition of defined.values()) if (!rows.has(definition.id)) problems.push({ line: definition.line, message: `${definition.id} is defined here but has no Status row.` })
|
|
266
|
+
if (!problems.length) checkSummaries(summaries, sentences, clauses, problems)
|
|
267
|
+
if (problems.length) throw new ContractError(file, problems.sort((a, b) => a.line - b.line))
|
|
268
|
+
|
|
269
|
+
const tally = rows => {
|
|
270
|
+
const counts = { done: 0, partial: 0, missing: 0, total: rows.length }
|
|
271
|
+
for (const row of rows) counts[row.status]++
|
|
272
|
+
return counts
|
|
273
|
+
}
|
|
274
|
+
const areas = [...areaHeadings.values()].map(({ name, slug, group }) => {
|
|
275
|
+
const own = clauses.filter(clause => clause.area === name).sort((a, b) => a.line - b.line)
|
|
276
|
+
return { name, slug, group, clauses: own.map(clause => clause.id), ...tally(own) }
|
|
277
|
+
}).filter(area => area.total)
|
|
278
|
+
const counts = tally(clauses)
|
|
279
|
+
return { commit, date, target, areas, clauses, counts }
|
|
280
|
+
}
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.39
|
|
4
|
+
|
|
5
|
+
- **A seed's CONTRACT.md is parsed and checked.** `rer check` and `rer build --site` now parse a seed's CONTRACT.md with one parser: its clauses, the `## Status` table (judged-at line, header, one row per defined clause, kind, status, evidence and gap), the summary counts and the Product target. Clause IDs follow one rule, shared with the release catalogue: `AREA-NN(N)`, or the legacy `A1` form. `rer check` reports each problem as a failing `CONTRACT.status` clause naming the line, and reports each cited evidence path missing from the checkout as `CONTRACT.evidence.<ID>`.
|
|
6
|
+
- **The run site has a /contract page.** `rer build --site` renders the parsed contract at `/contract`: progress by status, a split by kind, the Product target, progress by area, and every clause with status filters and search. The Run, home and 404 headers link Contract only when the page exists. Base's template and default seed render it. An existing seed's site entry needs three lines to do the same (gr-base-199's report shows them): import `contractPageHtml`, take `{ contract }` in `sitePages`, and add the `/contract` page.
|
|
7
|
+
- **Release note: a non-canonical or malformed CONTRACT.md now fails `rer check` and `rer build --site`.** Each problem's line is named, and a failed site build leaves the previous site as it was. Seeds without a CONTRACT.md are unaffected. A seed whose site entry has not been updated still has its CONTRACT.md parsed, but gets no `/contract` page.
|
|
8
|
+
- **`rer deploy` redacts by what a value is.** Declared non-secret settings now print in full, so the final line can name the address: "Sign in by email at https://<host>". These are `vars`, `originVar`, `publicOriginSetting`, setup fields that are not secrets, and names in the new optional deploy-declaration key `publicSettings`. Declared secrets, generated secrets, `CLOUDFLARE_ACCOUNT_ID`, credential-named keys and values that carry credentials stay redacted everywhere: stdout, stderr, `--json` and logs. A secret also listed in `publicSettings` stays redacted. Undeclared `--env-file` values stay redacted too, and the output names them and says to add them to `publicSettings`.
|
|
9
|
+
- **Release note: `publicSettings` is a new optional deploy-declaration key.** It takes a list of upper-case setting names that a hook reads but that are not bindings, such as hosts, origins, names or regions. An invalid list is refused.
|
|
10
|
+
|
|
11
|
+
## 0.2.38
|
|
12
|
+
|
|
13
|
+
- **Local settings never reach a deployment.** `rer build`, the build `rer deploy` runs, and every custom deploy hook now run with the checkout's local settings files (`.dev.vars`, `.env`) moved aside, and Wrangler's `.env` and `process.env` loading is switched off. A hard kill puts the files back on the next run. If build output still holds a `.dev.vars*`, `.env*` or `*.env` file, it is refused, naming the file, before anything is uploaded. This applies to `rer build`, `rer deploy`, the deploy kit, the container image build and the delivery package. Before, a seed whose build copied `.dev.vars` into `dist/client` uploaded it as a public Worker asset, and the demo container image copied `dist/server/.dev.vars`. No live deployment was affected. The Vite plugin that drops these files from every build now lives in onboarding (`@runeditrun/rer/local-variables-output` in package mode), and the seed template uses it too.
|
|
14
|
+
- **Generated deployment secrets are kept and reused.** Secrets rer generates for a deployment, such as the session and subscriber-link keys, are saved in `.rer/deploy/<env>.secrets.env`. The file is owner-only and Git-ignored, and every redeploy reuses it and says so. An existing unsubscribe link stays valid and the operator session stays alive across a redeploy. `--rotate-secret NAME[,NAME]` replaces the named secrets on purpose.
|
|
15
|
+
- **Release note: a custom-hook redeploy without that file now stops instead of rotating.** Custom-hook installs deployed before this release have no `.rer/deploy/<env>.secrets.env`. If the live Worker already holds the secrets, the next redeploy refuses before any upload and names them. Restore the file, or pass `--rotate-secret NAME` to rotate on purpose. Before, the redeploy rotated those secrets silently, which broke existing links and sessions.
|
|
16
|
+
|
|
3
17
|
## 0.2.37
|
|
4
18
|
|
|
5
19
|
- **A native demo's D1 answers `withSession`, `dump()` and `meta.size_after`, as production D1 does.** In a native hosted demo, `env.DB.withSession(...)` now returns a session whose `prepare`, `batch` and `getBookmark` work against the visitor's own database. Each visitor's database is a single primary, so every constraint or bookmark is already met and the bookmark stays the same. Before, a seed that read through a session hung: Slate's feature routes never answered. `dump()` now exists and rejects with `D1_DUMP_ERROR`, as production D1 does. Before, Uptime's owner-session revoke bound `db.dump` and answered 503 `auth_unavailable`; it now answers 404 `session_not_found`, once Uptime takes this release. Query `meta` adds `size_after`, which Orbit's archive budget reads.
|
|
@@ -9,6 +9,7 @@ import { localDurableObjects } from './durable-objects.mjs';
|
|
|
9
9
|
import { readMigrationRewrites, withRewrites } from '../deploy-kit/migrations.mjs';
|
|
10
10
|
import { containerMigrationInventory } from './migration-inventory.mjs';
|
|
11
11
|
import { checkImageVariables } from './image-variables.mjs';
|
|
12
|
+
import { refuseLocalEnvFiles } from '../deploy-kit/local-only.mjs';
|
|
12
13
|
export async function buildContainer(root, options={}) {
|
|
13
14
|
const previous=process.cwd();process.chdir(root);
|
|
14
15
|
try{return await buildImage(root,options);}finally{process.chdir(previous);}
|
|
@@ -57,6 +58,9 @@ async function buildImage(root, { output = join(root,'.rer/container/image'), en
|
|
|
57
58
|
const builder = await vite.createBuilder({ ...config,root,configFile:false }); await builder.buildApp();
|
|
58
59
|
// Apply the same local-only bundle guard before packaging any container image.
|
|
59
60
|
await (await import('../../cli/dev-identity.mjs')).refuseDevLayerOutput(root);
|
|
61
|
+
// The image copies dist/ whole: a local settings file there would ship in it.
|
|
62
|
+
try { await refuseLocalEnvFiles(root,['dist']); }
|
|
63
|
+
catch (error) { if (!error.resource) throw error; throw new Error(`The build output holds the local settings file ${error.resource}; a container image never carries one. Remove what copies it into dist/, then build again.`); }
|
|
60
64
|
let workerConfig;
|
|
61
65
|
if (engine === 'workerd') {
|
|
62
66
|
workerConfig = JSON.parse(await readFile(join(root,'dist/server/wrangler.json'),'utf8'));
|
|
@@ -115,9 +115,9 @@ A transport failure carries `providerTransport`: the operation, sanitized endpoi
|
|
|
115
115
|
|
|
116
116
|
`rer deploy` runs these steps for a seed whose adapter uses `ownerDeploy` from `cli/deploy.mjs`.
|
|
117
117
|
|
|
118
|
-
- **Inputs.** Declared secrets come from the environment, then `--env-file FILE` (an owned 0600 file of `KEY=VALUE` lines), which wins. For a secret the Worker does not hold yet, rer supplies the setup manifest's owner email (`emailField`) from the local setup's private settings, and
|
|
118
|
+
- **Inputs.** Declared secrets come from the environment, then `--env-file FILE` (an owned 0600 file of `KEY=VALUE` lines), which wins. For a secret the Worker does not hold yet, rer supplies the setup manifest's owner email (`emailField`) from the local setup's private settings, and for each secret field the manifest generates (`generate`) the value rer keeps for this environment in `.rer/deploy/<environment>.secrets.env` (0600, ignored by Git), else a fresh random value, which rer keeps once the Worker holds it (the one-time setup token is always fresh and never kept); a value the Worker already holds is kept. The build runs with the checkout's local settings files moved aside, and a `dist/` holding a `.dev.vars*`, `.env*` or `*.env` file is refused by name before any provider request. A still-missing secret stops the run before any write with a message that names it, unless its declaration says `"optional": true`: then the deploy binds nothing for it and reports it as not set, and `--set-secret` adds it later.
|
|
119
119
|
- **Hosted owner.** After deploy and health pass, rer claims the setup owner on the hosted app: it POSTs the setup token to the seed's standard owner step (`hooks.owner`, by default `/auth/bootstrap`). 303 means claimed; `409 already_initialized` means an owner was already claimed and is kept. Then rer deletes the token secret from the Worker, records the new Worker version in the state file, and lists the token in `retiredSecrets`, so later plans no longer declare it. The build fingerprint still names it, and the recorded claim stays as recorded, so an untouched repeat deploy writes nothing. A Worker that still holds a token rer did not upload in this run (an older deploy) first gets a fresh token through the same recorded secret change. Dependency approvals that need the token run before the claim. A seed with an owner step function, an identity-provider claim, or no declared token secret claims its owner its own way.
|
|
120
|
-
- **Secret changes.** `rer deploy --set-secret NAME` (value from the environment or `--env-file`, under the declaration's environment name) and `--
|
|
120
|
+
- **Secret changes.** `rer deploy --set-secret NAME` (value from the environment or `--env-file`, under the declaration's environment name), `--unset-secret NAME` and `--rotate-secret NAME[,NAME]` (a fresh value for a secret rer generates, kept in `.rer/deploy/<environment>.secrets.env` once set) change declared secrets of the recorded Worker without a build. Before writing, rer records the starting version and the exact live names of all other secrets, never their values. Accepted or ambiguous writes retain that intent until readback confirms the change; explicit refusals clear it. An ambiguous failure, or a later command's preflight, can clear an unapplied intent only when the live deployment still matches the receipt and the newest listed version matches it too. A surviving intent blocks further mutations until consistency returns; retry the same command then. Recovery requires the recorded immediate successor (or the recorded confirming rotation's successor), the receipt's script etag and fingerprint, the intended binding's presence, and an unchanged set of other secret names. Ambiguous rotations require a confirming PUT before reporting success. Older intents without names may recover only from the exact starting version's historical bindings, with its id, etag and fingerprint verified; unavailable or malformed historical bindings refuse adoption. Each historical binding must have an exact provider type supported by this kit; unrecognized types cannot prove that a name was not a secret. Added, removed or renamed other secrets refuse deploy and removal before writes. Values remain opaque: these checks cannot distinguish an otherwise identical outside change to the pending binding.
|
|
121
121
|
- **Removal.** `rer deploy --remove --yes` deletes what the state file says rer created for this environment: the Worker (schedules first; its Durable Objects go with it) and each D1, R2, KV and queue that is still the one rer created, after checking all of them before the first delete. A replaced or uncertain resource refuses the whole removal, except a D1 or KV whose create answer was lost: under this environment's derived name it is deleted once confirmed empty (a D1 with no tables, a KV namespace with no keys); one holding data is refused as `uncertain-resource-not-empty`, and an uncertain queue, whose backlog rer cannot read, as `uncertain-resource-unverifiable` (delete it by hand if it is the empty one from the interrupted run).
|
|
122
122
|
|
|
123
123
|
R2 removal requires a saved `created` identity (the bucket's creation date). Pending buckets or buckets missing that identity are refused as `uncertain-resource-create`, and same-named replacements as `owned-resource-replaced`, even if empty. For a confirmed bucket, removal automatically lists and deletes its objects before deleting the bucket, checking its identity again before every object delete and the bucket delete. Serialize outside bucket deletion and recreation with removal: the provider cannot make a delete conditional on that identity.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { lstat } from 'node:fs/promises';
|
|
2
|
-
import { join } from 'node:path';
|
|
1
|
+
import { lstat, readdir } from 'node:fs/promises';
|
|
2
|
+
import { join, relative } from 'node:path';
|
|
3
3
|
|
|
4
4
|
export const LOCAL_MODELS_FILE = '.rer/local/models.json';
|
|
5
5
|
/** Refuse presence, including symlinks: never read this key to build a plan. */
|
|
@@ -8,3 +8,21 @@ export async function refuseLocalModels(root) {
|
|
|
8
8
|
catch (error) { if (error.code === 'ENOENT') return; throw error; }
|
|
9
9
|
throw new Error('local-only-models-file');
|
|
10
10
|
}
|
|
11
|
+
|
|
12
|
+
/** A local settings file: .dev.vars or .env with any suffix (.dev.vars.production,
|
|
13
|
+
* .env.local), or a NAME.env file such as rer's own dev-key.env. */
|
|
14
|
+
export const localEnvFile = path => /(?:^|\/)(?:\.dev\.vars(?:\.[^/]*)?|\.env(?:\.[^/]*)?|[^/]+\.env)$/.test(path);
|
|
15
|
+
|
|
16
|
+
/** Refuse build output that holds a local settings file, by presence alone: the
|
|
17
|
+
* Cloudflare Vite plugin copies .dev.vars into dist/<worker>/ for preview, and a
|
|
18
|
+
* deployment never carries one. The error names the first file, relative to root;
|
|
19
|
+
* its contents are never read. */
|
|
20
|
+
export async function refuseLocalEnvFiles(root, directories) {
|
|
21
|
+
for (const directory of directories) {
|
|
22
|
+
let entries;
|
|
23
|
+
try { entries = await readdir(join(root, directory), { withFileTypes: true, recursive: true }); }
|
|
24
|
+
catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
25
|
+
const found = entries.map(entry => relative(root, join(entry.parentPath, entry.name)).split('\\').join('/')).filter(localEnvFile).sort()[0];
|
|
26
|
+
if (found) throw Object.assign(new Error('local-env-file-in-build-output'), { resource: found });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -22,7 +22,7 @@ import { publicOrigin } from './public-origin.mjs';
|
|
|
22
22
|
const segment = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
23
23
|
const STATE_KIND = 'rer-deploy-owner-state';
|
|
24
24
|
export const KINDS = ['d1','r2','kv','queues'];
|
|
25
|
-
const DECLARATION_KEYS = ['version','project','compatibilityDate','compatibilityFlags','d1','r2','kv','queues','durableObjects','secrets','crons','vars','originVar','publicOriginSetting','services','workersDev','platforms','container','deployGuide'];
|
|
25
|
+
const DECLARATION_KEYS = ['version','project','compatibilityDate','compatibilityFlags','d1','r2','kv','queues','durableObjects','secrets','crons','vars','originVar','publicOriginSetting','publicSettings','services','workersDev','platforms','container','deployGuide'];
|
|
26
26
|
const ENTRY_KEYS = {d1:['binding'],r2:['binding','locationHint'],kv:['binding'],queues:['binding','consumer','deadLetterQueue'],durableObjects:['binding','className','storage'],secrets:['binding','environment','verifyStandIn','optional'],services:['binding','project','entrypoint','allowedHosts','grant']};
|
|
27
27
|
|
|
28
28
|
export function refuse(code, kind, name) { const error = new Error(code); error.resource = `${kind}:${name}`; return error; }
|
|
@@ -114,6 +114,7 @@ export function localOnlyBinding(declaration, localOnlyKeys = []) {
|
|
|
114
114
|
/** A seed declares bindings, never names. Migrations come from the packaged artifact. */
|
|
115
115
|
export function ownerPlan(target, declaration, artifact, { localOnlyKeys = [], env = {} } = {}) {
|
|
116
116
|
assert(declaration?.version === 1 && typeof declaration === 'object' && Object.keys(declaration).every(key => DECLARATION_KEYS.includes(key)), 'invalid-owner-declaration');
|
|
117
|
+
assert(declaration.publicSettings === undefined || Array.isArray(declaration.publicSettings) && new Set(declaration.publicSettings).size === declaration.publicSettings.length && declaration.publicSettings.every(name => typeof name === 'string' && /^[A-Z][A-Z0-9_]*$/.test(name)), 'invalid-public-settings');
|
|
117
118
|
if (declaration.platforms !== undefined) assert(Array.isArray(declaration.platforms) && declaration.platforms.length > 0 && new Set(declaration.platforms).size === declaration.platforms.length && declaration.platforms.every(item => ['workers','container'].includes(item)), 'invalid-platforms');
|
|
118
119
|
if (declaration.container !== undefined) {
|
|
119
120
|
const config=declaration.container;
|
|
@@ -5,7 +5,7 @@ import { pathToFileURL } from 'node:url';
|
|
|
5
5
|
import { assert, hash, localPath } from './validation.mjs';
|
|
6
6
|
import { assetsIgnore, collectFiles, regularBytes, validateArtifact, MAX_ARTIFACT } from './artifact.mjs';
|
|
7
7
|
import { collectBuildModules } from './build-modules.mjs';
|
|
8
|
-
import { refuseLocalModels } from './local-only.mjs';
|
|
8
|
+
import { refuseLocalEnvFiles, refuseLocalModels } from './local-only.mjs';
|
|
9
9
|
import { readMigrationRewrites, withRewrites } from './migrations.mjs';
|
|
10
10
|
|
|
11
11
|
export function assertCredentialFree(env) {
|
|
@@ -21,6 +21,7 @@ export async function packageBuild({root,source,runIdentity,productDirectory = '
|
|
|
21
21
|
const product = join(root,productDirectory);
|
|
22
22
|
await refuseLocalModels(root);
|
|
23
23
|
if (product !== root) await refuseLocalModels(product);
|
|
24
|
+
await refuseLocalEnvFiles(root, [join(productDirectory,'dist/server'), join(productDirectory,'dist/client')]);
|
|
24
25
|
const build = join(product,'dist/server');
|
|
25
26
|
const config = JSON.parse(await regularBytes(join(build,'wrangler.json'),1024*1024));
|
|
26
27
|
const main = localPath(relative(build,resolve(build,config.main)));
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { resolve, dirname } from 'node:path';
|
|
4
|
+
import { clauseIdSource } from '../../foundation/runtime/seed-contract.mjs';
|
|
4
5
|
|
|
5
6
|
export const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
6
7
|
export const json = value => JSON.stringify(value, null, 2) + '\n';
|
|
@@ -14,7 +15,7 @@ function clauses(text) {
|
|
|
14
15
|
if (body) result.push({ id: current.id, title: current.title, text: body });
|
|
15
16
|
current = null;
|
|
16
17
|
};
|
|
17
|
-
const clauseLine =
|
|
18
|
+
const clauseLine = new RegExp(`^- \\*\\*(${clauseIdSource})\\s+[—–-]\\s+(.+?)\\.?\\*\\*[ \\t]*(.*)$`);
|
|
18
19
|
for (const line of text.split(/\r\n|\n|\r/)) {
|
|
19
20
|
const match = clauseLine.exec(line);
|
|
20
21
|
if (match) {
|
package/onboarding/README.md
CHANGED
|
@@ -79,11 +79,15 @@ font files the app already serves; anything else is refused.
|
|
|
79
79
|
| `--rer-font-body`, `--rer-font-heading` | font stack (optional) | text; headings and product name |
|
|
80
80
|
| `--rer-radius` | `px` or `rem` length (optional) | cards, inputs, buttons |
|
|
81
81
|
| `--rer-logo` | `url("/path")` to an svg, png or webp the app serves (optional) | mark beside the product name |
|
|
82
|
+
| `--rer-done`, `--rer-partial`, `--rer-missing` | colour (optional; Base has defaults) | status fills on the run site's `/contract` |
|
|
83
|
+
| `--rer-done-ink`, `--rer-partial-ink`, `--rer-missing-ink` | colour (optional) | status words and counts on `/contract` |
|
|
84
|
+
| `--rer-on-done`, `--rer-on-partial`, `--rer-on-missing` | colour (optional) | labels printed on each status fill |
|
|
82
85
|
|
|
83
86
|
Contrast is checked against the declared colours before the installer starts:
|
|
84
87
|
text on page and surface, muted text on page and surface, links on surface and
|
|
85
|
-
accent text on accent need 4.5:1
|
|
86
|
-
surface
|
|
88
|
+
accent text on accent need 4.5:1, as do each declared status ink on page and
|
|
89
|
+
surface and each `--rer-on-*` label on its declared fill; focus on page and
|
|
90
|
+
surface and borders on surface need 3:1. A failing pair is named with its ratio. Every `url()` must
|
|
87
91
|
name a same-origin file under the served directory.
|
|
88
92
|
|
|
89
93
|
The app must serve the file at `/rer-theme.css` with its fonts and logo; a
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The Cloudflare Vite plugin serialises .dev.vars (or .env, or process
|
|
2
|
+
// variables) into dist/<worker>/.dev.vars for `vite preview`. Every build,
|
|
3
|
+
// including a direct `vite build`, drops local settings files before they are
|
|
4
|
+
// written: local credentials never reach dist/, and so never a deployment.
|
|
5
|
+
// rer build and rer deploy also run builds with these files moved aside and
|
|
6
|
+
// refuse output that still holds one, naming it.
|
|
7
|
+
const localVariables = fileName => /(?:^|\/)(?:\.dev\.vars|\.env)(?:\.[^/]*)?$/.test(fileName);
|
|
8
|
+
|
|
9
|
+
export function excludeLocalVariables() {
|
|
10
|
+
return {
|
|
11
|
+
name: 'rer:exclude-local-variables',
|
|
12
|
+
apply: 'build',
|
|
13
|
+
enforce: 'post',
|
|
14
|
+
generateBundle: {
|
|
15
|
+
order: 'post',
|
|
16
|
+
handler(_options, bundle) {
|
|
17
|
+
for (const fileName of Object.keys(bundle)) if (localVariables(fileName)) delete bundle[fileName];
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
package/onboarding/redaction.mjs
CHANGED
|
@@ -37,7 +37,7 @@ const PRIVATE_VALUE = `(?:${DOUBLE_QUOTED}(?:"|(?=[\\r\\n]|$))|${SINGLE_QUOTED}(
|
|
|
37
37
|
const FIELD_VALUE = '["\']?\\s*[=:]\\s*' + NOT_FLAG + PRIVATE_VALUE;
|
|
38
38
|
// These deploy flags take a binding name, never the secret value. Explicitly
|
|
39
39
|
// registered private bytes remain redacted by the exact-value pass.
|
|
40
|
-
const CLI_PREFIX = '(?<![A-Za-z0-9_-])--(?!(?:set|unset)-secret(?:\\s|$))(?:[A-Za-z0-9]+[_-])*';
|
|
40
|
+
const CLI_PREFIX = '(?<![A-Za-z0-9_-])--(?!(?:set|unset|rotate)-secret(?:\\s|$))(?:[A-Za-z0-9]+[_-])*';
|
|
41
41
|
const CLI_ARGUMENT = CLI_PREFIX + '(' + FIELD_NAME + ')\\s+' + NOT_FLAG + '(' + PRIVATE_VALUE + ')';
|
|
42
42
|
// A bare Bearer/Basic value must look like a credential, not the next word of
|
|
43
43
|
// prose such as "Basic checks passed"; after Authorization any value is private.
|
package/onboarding/theme.mjs
CHANGED
|
@@ -12,6 +12,10 @@ export const themeTokens = Object.freeze({
|
|
|
12
12
|
'--rer-page': 'colour', '--rer-surface': 'colour', '--rer-text': 'colour', '--rer-muted': 'colour',
|
|
13
13
|
'--rer-border': 'colour', '--rer-focus': 'colour', '--rer-accent': 'colour', '--rer-accent-text': 'colour',
|
|
14
14
|
'--rer-link': 'colour', '--rer-font-body': 'stack', '--rer-font-heading': 'stack', '--rer-radius': 'radius', '--rer-logo': 'logo',
|
|
15
|
+
// The run site's /contract statuses: fills, text inks and the labels printed on fills. Base has defaults for each.
|
|
16
|
+
'--rer-done': 'colour', '--rer-partial': 'colour', '--rer-missing': 'colour',
|
|
17
|
+
'--rer-done-ink': 'colour', '--rer-partial-ink': 'colour', '--rer-missing-ink': 'colour',
|
|
18
|
+
'--rer-on-done': 'colour', '--rer-on-partial': 'colour', '--rer-on-missing': 'colour',
|
|
15
19
|
});
|
|
16
20
|
const required = ['--rer-page', '--rer-surface', '--rer-text', '--rer-muted', '--rer-border', '--rer-focus'];
|
|
17
21
|
|
|
@@ -20,6 +24,7 @@ const pairs = [
|
|
|
20
24
|
['--rer-text', '--rer-page', 4.5], ['--rer-text', '--rer-surface', 4.5], ['--rer-muted', '--rer-surface', 4.5], ['--rer-muted', '--rer-page', 4.5],
|
|
21
25
|
['--rer-link', '--rer-surface', 4.5], ['--rer-accent-text', '--rer-accent', 4.5],
|
|
22
26
|
['--rer-focus', '--rer-page', 3], ['--rer-focus', '--rer-surface', 3], ['--rer-border', '--rer-surface', 3],
|
|
27
|
+
...['done', 'partial', 'missing'].flatMap(status => [[`--rer-${status}-ink`, '--rer-page', 4.5], [`--rer-${status}-ink`, '--rer-surface', 4.5], [`--rer-on-${status}`, `--rer-${status}`, 4.5]]),
|
|
23
28
|
];
|
|
24
29
|
|
|
25
30
|
const faceDescriptors = {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@runeditrun/rer",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.39",
|
|
4
4
|
"description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -46,6 +46,10 @@
|
|
|
46
46
|
"types": "./onboarding/archive-output.d.mts",
|
|
47
47
|
"default": "./onboarding/archive-output.mjs"
|
|
48
48
|
},
|
|
49
|
+
"./local-variables-output": {
|
|
50
|
+
"types": "./onboarding/local-variables-output.d.mts",
|
|
51
|
+
"default": "./onboarding/local-variables-output.mjs"
|
|
52
|
+
},
|
|
49
53
|
"./launcher": "./onboarding/launcher.mjs",
|
|
50
54
|
"./installer-server": "./onboarding/server.mjs",
|
|
51
55
|
"./server-resources": "./cli/server-resources.mjs",
|