@runeditrun/rer 0.2.68 → 0.2.70
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/README.md +2 -0
- package/cli/deploy-command.mjs +5 -1
- package/cli/deploy-product.mjs +30 -0
- package/cli/deploy.mjs +3 -1
- package/cli/inspect.mjs +29 -1
- package/global/CHANGELOG.md +16 -0
- package/modules/deploy-kit/README.md +2 -0
- package/modules/deploy-kit/owner.mjs +1 -1
- package/modules/operator-auth/README.md +31 -10
- package/modules/operator-auth/SCHEDULED-POLICY.md +130 -0
- package/modules/operator-auth/accounts/admin.mjs +2 -10
- package/modules/operator-auth/accounts/schema/last-signin.sql +11 -0
- package/modules/operator-auth/accounts/schema/operator-auth.sql +25 -1
- package/modules/operator-auth/accounts/schema/scheduled-policy-hardening.sql +8 -0
- package/modules/operator-auth/accounts/schema/scheduled-policy.sql +18 -0
- package/modules/operator-auth/accounts/status.mjs +18 -0
- package/modules/operator-auth/accounts/store.mjs +3 -0
- package/modules/operator-auth/branding.mjs +5 -2
- package/modules/operator-auth/conformance/README.md +7 -3
- package/modules/operator-auth/conformance/index.d.mts +2 -2
- package/modules/operator-auth/conformance/index.mjs +6 -4
- package/modules/operator-auth/conformance/presentation.mjs +8 -3
- package/modules/operator-auth/dev/index.mjs +2 -1
- package/modules/operator-auth/dev-gate.mjs +5 -3
- package/modules/operator-auth/index.d.mts +6 -2
- package/modules/operator-auth/page.mjs +5 -3
- package/modules/operator-auth/routes.mjs +6 -1
- package/modules/operator-auth/scheduled/definition.mjs +37 -0
- package/modules/operator-auth/scheduled/fence.mjs +27 -0
- package/modules/operator-auth/scheduled/history.mjs +30 -0
- package/modules/operator-auth/scheduled/index.d.mts +21 -0
- package/modules/operator-auth/scheduled/index.mjs +83 -0
- package/modules/operator-auth/scheduled/runner.mjs +65 -0
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/operator-auth/signin/index.mjs +2 -2
- package/modules/operator-auth/signin/one-click.mjs +8 -3
- package/modules/portability/README.md +75 -7
- package/modules/portability/backfills.mjs +89 -0
- package/modules/portability/bridge.mjs +18 -12
- package/modules/portability/export.mjs +5 -1
- package/modules/portability/http.mjs +2 -1
- package/modules/portability/import-lease.mjs +99 -0
- package/modules/portability/import.mjs +45 -16
- package/modules/portability/index.d.mts +4 -4
- package/modules/portability/index.mjs +4 -2
- package/modules/portability/migration-statements.mjs +96 -9
- package/modules/portability/policy-data.mjs +10 -0
- package/onboarding/adapter.mjs +5 -2
- package/onboarding/process-diagnostics.mjs +7 -2
- package/package.json +1 -1
package/cli/README.md
CHANGED
|
@@ -371,6 +371,8 @@ declaration refuses completion. A kit or custom-hook deploy, except `--dry-run`,
|
|
|
371
371
|
first refuses uncommitted tracked source, naming the files, before any build or
|
|
372
372
|
upload.
|
|
373
373
|
|
|
374
|
+
The owner deployment declaration may set top-level `"productDirectory": ".rer/deploy/product"` for a product staged by the build or deploy hook. It must name a normalized checkout-relative subdirectory: no absolute path, backslash, empty, `.` or `..` segment. The directory must exist after the build or hook, with no symlink on its path. rer reads this field and passes `--product` only to the kit's packaging commands (`dry-run`, `deploy` and `health`), including its extra dry run after a custom hook. A hook that invokes the kit itself still supplies `--product` on its own invocation; the wrapper reads the declaration for its own steps. Omitting the field keeps packaging at the checkout root. State, root ownership, secret changes and removal keep their existing locations and behavior; dry run still requires credentials for target secret reads.
|
|
375
|
+
|
|
374
376
|
For a hosted owner claim, deploy reuses the name saved by `rer setup` in the
|
|
375
377
|
checkout's `.seed/installer/setup-answers.json`, under the adapter's
|
|
376
378
|
`input.names.name` field (default `displayName`). If no name is known,
|
package/cli/deploy-command.mjs
CHANGED
|
@@ -23,6 +23,7 @@ import { settingKinds } from './deploy-settings.mjs';
|
|
|
23
23
|
import { deployGuide, neededForRealDeploy, reportNeeded } from './deploy-needs.mjs';
|
|
24
24
|
import { keepHookSecrets } from './deploy-secrets.mjs';
|
|
25
25
|
import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
|
|
26
|
+
import { deployProductDirectory, deployProductArguments, DeployProductError } from './deploy-product.mjs';
|
|
26
27
|
|
|
27
28
|
export function validateDeployOptions(options) {
|
|
28
29
|
const changes = [options.remove && '--remove', options.setSecret && '--set-secret', options.unsetSecret && '--unset-secret', options.rotateSecret && '--rotate-secret'].filter(Boolean);
|
|
@@ -93,6 +94,7 @@ export async function deployCommand(context) {
|
|
|
93
94
|
// A hook that deployed through the kit keeps what its Worker holds: rotate there as a secret change.
|
|
94
95
|
if (options.rotateSecret && !adapter.deploy.managesHostedOwner && await hookState(root, options.environment ?? 'production')) return ownerDeploy(path, adapter)(context);
|
|
95
96
|
if (adapter.deploy.managesHostedOwner) { const result = await adapter.deploy(context); return options.dryRun ? dryRun(result) : result; }
|
|
97
|
+
const productDirectory = deployProductDirectory(declaration);
|
|
96
98
|
const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
|
|
97
99
|
await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options });
|
|
98
100
|
const sourceSha = options.dryRun ? undefined : committedSource(root, options);
|
|
@@ -109,7 +111,7 @@ export async function deployCommand(context) {
|
|
|
109
111
|
// A hook keeping the kit's record in its own state file named it; every kit
|
|
110
112
|
// step after the hook (inspect, secret, record-owner) reads that record.
|
|
111
113
|
let hookRecord = await hookState(root, environment);
|
|
112
|
-
const command = (verb, extra = [], values = env, more = {}) => owner([verb, '--declaration', path, '--environment', environment, ...(hookRecord ? ['--state', hookRecord] : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
|
|
114
|
+
const command = async (verb, extra = [], values = env, more = {}) => owner([verb, '--declaration', path, '--environment', environment, ...(hookRecord ? ['--state', hookRecord] : []), ...(['dry-run', 'deploy', 'health'].includes(verb) ? await deployProductArguments(root, productDirectory) : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
|
|
113
115
|
// A hook that deployed through the kit's standard record lets rer issue and
|
|
114
116
|
// retire the setup token; a hook keeping an unnamed record of its own keeps its token.
|
|
115
117
|
let recorded, hookReturned = false;
|
|
@@ -134,6 +136,7 @@ export async function deployCommand(context) {
|
|
|
134
136
|
Object.assign(process.env, saved);
|
|
135
137
|
}
|
|
136
138
|
hookReturned = true;
|
|
139
|
+
await deployProductArguments(root, productDirectory);
|
|
137
140
|
await refuseLocalEnvOutput(root, adapter.devIdentity?.output, { uploaded: !options.dryRun });
|
|
138
141
|
if (options.dryRun) {
|
|
139
142
|
await command('dry-run');
|
|
@@ -165,6 +168,7 @@ export async function deployCommand(context) {
|
|
|
165
168
|
return { ...result, ...(claimed ? { owner: claimed } : {}), dependenciesLinked: true };
|
|
166
169
|
});
|
|
167
170
|
} catch (error) {
|
|
171
|
+
if (error instanceof DeployProductError) throw error;
|
|
168
172
|
const again = deployAgain(options);
|
|
169
173
|
const { commandFailure } = await shared('failures.mjs');
|
|
170
174
|
const secrets = secretFailureMessage(error);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { stat } from 'node:fs/promises';
|
|
2
|
+
import { win32 } from 'node:path';
|
|
3
|
+
import { contained } from './project.mjs';
|
|
4
|
+
import { RerError } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
export class DeployProductError extends RerError {
|
|
7
|
+
constructor(message) { super('safety_refusal', message, 4); }
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// Omission preserves the owner's existing root product and command arguments.
|
|
11
|
+
export function deployProductDirectory(declaration) {
|
|
12
|
+
const directory = declaration.productDirectory;
|
|
13
|
+
if (directory === undefined) return;
|
|
14
|
+
if (typeof directory !== 'string' || !directory || win32.isAbsolute(directory) || /^[A-Za-z]:/.test(directory) || /[\\\x00-\x1f\x7f]/.test(directory) || directory.split('/').some(part => !part || part === '.' || part === '..')) {
|
|
15
|
+
throw new DeployProductError('Deploy productDirectory must be a normalized checkout-relative directory, without absolute paths, backslashes or traversal.');
|
|
16
|
+
}
|
|
17
|
+
return directory;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Check after the build/hook: staging need not exist before it runs. contained
|
|
21
|
+
// checks every ancestor, so a symlink cannot redirect the packager outside.
|
|
22
|
+
export async function deployProductArguments(root, directory) {
|
|
23
|
+
if (directory === undefined) return [];
|
|
24
|
+
try {
|
|
25
|
+
if (!(await stat(await contained(root, directory))).isDirectory()) throw new Error('not-directory');
|
|
26
|
+
} catch {
|
|
27
|
+
throw new DeployProductError('Deploy productDirectory must exist as a directory inside the checkout after the build or deploy hook; symlinks are refused.');
|
|
28
|
+
}
|
|
29
|
+
return ['--product', directory];
|
|
30
|
+
}
|
package/cli/deploy.mjs
CHANGED
|
@@ -19,6 +19,7 @@ import { deploymentRecord } from './deployment-record.mjs';
|
|
|
19
19
|
import { cloudflareCredentials, missingCredentialsMessage } from './deploy-needs.mjs';
|
|
20
20
|
import { keptSecrets, keepSecrets, forgetSecrets } from './deploy-secrets.mjs';
|
|
21
21
|
import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
|
|
22
|
+
import { deployProductDirectory, deployProductArguments } from './deploy-product.mjs';
|
|
22
23
|
|
|
23
24
|
export function ownerDeploy(declarationPath, lifecycle) {
|
|
24
25
|
// rer verify serves the build with this declaration's vars and secrets.
|
|
@@ -35,6 +36,7 @@ export function ownerDeploy(declarationPath, lifecycle) {
|
|
|
35
36
|
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;
|
|
36
37
|
if (change.length > 1 || change.length && options.dryRun) throw invalid(`Use ${change.join(', ')}${options.dryRun ? ' and --dry-run' : ''} on separate runs.`);
|
|
37
38
|
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.`);
|
|
39
|
+
const productDirectory = change.length ? undefined : deployProductDirectory(declaration);
|
|
38
40
|
const recordedState = change.length ? await deploymentRecord(root, options) : undefined;
|
|
39
41
|
// A dry run reads the settings file too, so a refused key fails here and not only on the real deploy.
|
|
40
42
|
if (options.dryRun && options.envFile) await deployEnvironment({ root, options, declaration, localOnlyKeys });
|
|
@@ -58,7 +60,7 @@ export function ownerDeploy(declarationPath, lifecycle) {
|
|
|
58
60
|
redaction.addSecrets([...(await settingKinds({ declaration, setupManifest })).privateValues(env), env.CLOUDFLARE_ACCOUNT_ID, ...(declaration.secrets ?? []).map(item => env[item.environment]).filter(Boolean)]);
|
|
59
61
|
const claim = setupManifest?.steps?.find(item => item.type === 'owner-claim');
|
|
60
62
|
const declared = binding => (Array.isArray(declaration.secrets) ? declaration.secrets : []).find(item => item?.binding === binding);
|
|
61
|
-
const owner = (command, extra = [], values = env, more = {}) => main([command, '--declaration', declarationPath, '--environment', environment, ...extra], values, { cwd: root, localOnlyKeys, ...more });
|
|
63
|
+
const owner = async (command, extra = [], values = env, more = {}) => main([command, '--declaration', declarationPath, '--environment', environment, ...(['dry-run', 'deploy', 'health'].includes(command) ? await deployProductArguments(root, productDirectory) : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
|
|
62
64
|
// Keep confirmed creation events across deploy and the independent health call.
|
|
63
65
|
const created = [];
|
|
64
66
|
let step = 'deploy', deployed;
|
package/cli/inspect.mjs
CHANGED
|
@@ -141,8 +141,12 @@ export async function check(project, explicitProfile) {
|
|
|
141
141
|
// command still calling one.
|
|
142
142
|
async function packageClauses(root, pkg) {
|
|
143
143
|
const declared = declaredPackage(pkg), locked = await lockedPackage(root), clauses = [];
|
|
144
|
+
const patchHash = /\(patch_hash=([^)]*)\)/.exec(locked?.version ?? '')?.[1];
|
|
145
|
+
const patchPath = patchHash ? await rerPatchPath(root, pkg, locked.version, patchHash) : undefined;
|
|
144
146
|
clauses.push(['SC-13.package.pin', pkg.devDependencies?.[packageName] === declared && exactVersion.test(declared), `Pin ${packageName} in devDependencies to an exact version (for example "0.2.0"), not ${JSON.stringify(declared)} or a runtime dependency.`]);
|
|
145
|
-
clauses.push(['SC-13.package.lockfile', locked?.locked && locked.specifier === declared && locked.version === declared,
|
|
147
|
+
clauses.push(['SC-13.package.lockfile', locked?.locked && locked.specifier === declared && locked.version === declared, patchHash
|
|
148
|
+
? `${packageName} is patched locally${patchPath ? ` by ${patchPath}` : ' (see pnpm patchedDependencies metadata)'}. This change belongs upstream in Base; adopt a published rer version containing it and remove the local patch before checking the first-party contract again.`
|
|
149
|
+
: `Run pnpm install so pnpm-lock.yaml locks ${packageName} ${declared}${locked?.version ? ` (it locks ${locked.version})` : ''}.`]);
|
|
146
150
|
for (const path of vendoredPaths) {
|
|
147
151
|
let present = true; try { await lstat(resolve(root, path)); } catch { present = false; }
|
|
148
152
|
clauses.push(['SC-13.package.vendored.' + path, !present, `Remove ${path}: a checkout that pins ${packageName} runs the package, not a vendored copy (node scripts/export-cli.mjs --to-package converts one).`]);
|
|
@@ -153,6 +157,30 @@ async function packageClauses(root, pkg) {
|
|
|
153
157
|
return clauses;
|
|
154
158
|
}
|
|
155
159
|
|
|
160
|
+
// pnpm's lockfile records the selected patch hash and path, including when
|
|
161
|
+
// patchedDependencies lives in pnpm-workspace.yaml rather than package.json.
|
|
162
|
+
async function rerPatchPath(root, pkg, version, hash) {
|
|
163
|
+
const selector = `${packageName}@${version.split('(')[0]}`;
|
|
164
|
+
let text;
|
|
165
|
+
try { text = await readFile(resolve(root, 'pnpm-lock.yaml'), 'utf8'); } catch {}
|
|
166
|
+
const scalar = value => value.trim().replace(/^(['"])(.*)\1$/, (_, quote, content) => quote === "'" ? content.replace(/''/g, "'") : content);
|
|
167
|
+
const patches = [];
|
|
168
|
+
let reading = false, entry;
|
|
169
|
+
for (const line of (text ?? '').split('\n')) {
|
|
170
|
+
if (line === 'patchedDependencies:') { reading = true; continue; }
|
|
171
|
+
if (!reading || !line.trim()) continue;
|
|
172
|
+
if (/^\S/.test(line)) break;
|
|
173
|
+
const key = /^ (\S.*):\s*$/.exec(line);
|
|
174
|
+
if (key) { entry = { selector: scalar(key[1]) }; patches.push(entry); continue; }
|
|
175
|
+
const field = /^ (hash|path):\s*(.+)$/.exec(line);
|
|
176
|
+
if (entry && field) entry[field[1]] = scalar(field[2]);
|
|
177
|
+
}
|
|
178
|
+
const selected = patches.find(patch => (patch.selector === packageName || patch.selector.startsWith(packageName + '@')) && patch.hash === hash);
|
|
179
|
+
if (selected?.path) return selected.path;
|
|
180
|
+
const declared = pkg.pnpm?.patchedDependencies;
|
|
181
|
+
return declared?.[selector] ?? declared?.[packageName];
|
|
182
|
+
}
|
|
183
|
+
|
|
156
184
|
// Without the pinned pnpm on PATH, rer provides it for this command only
|
|
157
185
|
// (cli/pnpm-runtime.mjs); it never changes global tools.
|
|
158
186
|
export async function tools(root, store, signal) {
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.70
|
|
4
|
+
|
|
5
|
+
- **Archive restores judge later data statements by the table they write (#340).** A bounded INSERT/REPLACE/UPDATE/DELETE whose target is outside the restorable catalogue, and reaches none of it by trigger or FK action, is admitted whatever it reads; an INSERT…SELECT/VALUES into a catalogue table the archive lacks is replayed at finalize in migration order, in the same D1 batch, and recorded in bridged.replayed. Nook's retained archive restores past 0061.
|
|
6
|
+
- **Owner-approved scheduled policy jobs (#323).** Owners approve hash-pinned, scoped scheduled operator-auth status actions with fresh proof; every cron attempt re-checks owner, version, revocation, role policy, action and target inside the write transaction and is audited, with approve/revoke/history at /app/policies and an additive migration.
|
|
7
|
+
- **Staged product directory for deploy (#334).** An owner deploy declaration can set top-level "productDirectory" (for example .rer/deploy/product); rer validates its checkout-relative placement and symlink containment and forwards it to the kit's dry run, deploy and health checks.
|
|
8
|
+
- **Sign-in mark (#338).** Optional config.branding.mark (a same-origin root-relative image path) shows on sign-in, one-click, confirmation, settings and dev key-exchange pages; pages without a mark are unchanged.
|
|
9
|
+
- **/contract overlap regression checks (#336).** The run-site browser door now measures /contract split cards at 860, 1000 and 1160 px for overlap and sideways overflow.
|
|
10
|
+
- **Owned runtime stops promptly (#341).** The post-health port-ownership check now stops when its launch is cancelled, so a stop during startup no longer leaves rer polling for 15 seconds.
|
|
11
|
+
|
|
12
|
+
## 0.2.69
|
|
13
|
+
|
|
14
|
+
- **Renewable hosted import leases (#328).** A hosted import holds a five-minute renewable lease (30-second heartbeat while active) with fenced request claims; the next restore safely aborts stale staging and owned blobs through the existing recovery, and owner active/status/abort routes stay authenticated.
|
|
15
|
+
- **One-click sign-in offers providers (#324).** One-click owner entry also offers the visible provider forms, carrying returnTo, with provider origins in the CSP; SC-13 names a local rer patch and points it upstream to Base.
|
|
16
|
+
- **Run site dates and command (#326).** /contract shows US short UTC dates, and the /run command's `npx` start stays whole, breaking only before the repository.
|
|
17
|
+
- **CLI setup tests (#325).** Five CLI setup tests no longer pre-probe a --port, and shared fixture cleanup tolerates a late .DS_Store.
|
|
18
|
+
|
|
3
19
|
## 0.2.68
|
|
4
20
|
|
|
5
21
|
- **Retained-archive restores (#316, #318).** Placing an older archive treats a CREATE TRIGGER or DROP TRIGGER statement bounded as exactly one trigger as schema-only, and restore drops and recreates the destination's triggers around insertion; a later write that reaches an archived table through a trigger is still refused. Base reads RER Platform's rer_migrations ledger, places an archive without a migration record by the ledger it carries (every archived name and hash must match an applied migration), and admits a later UPDATE or DELETE of a table the archive holds no rows of.
|
|
@@ -72,6 +72,8 @@ node <kit>/owner-cli.mjs deploy --declaration deploy.json --environment producti
|
|
|
72
72
|
node <kit>/owner-cli.mjs health --declaration deploy.json --environment production
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
+
The owner deployment declaration may set top-level `"productDirectory": ".rer/deploy/product"` for a product staged by the build or deploy hook. It must name a normalized checkout-relative subdirectory: no absolute path, backslash, empty, `.` or `..` segment. The directory must exist after the build or hook, with no symlink on its path. rer reads this field and passes `--product` only to the kit's packaging commands (`dry-run`, `deploy` and `health`), including its extra dry run after a custom hook. A hook that invokes the kit itself still supplies `--product` on its own invocation; the wrapper reads the declaration for its own steps. Omitting the field keeps packaging at the checkout root. State, root ownership, secret changes and removal keep their existing locations and behavior; dry run still requires credentials for target secret reads.
|
|
76
|
+
|
|
75
77
|
The seed declares bindings, never names:
|
|
76
78
|
|
|
77
79
|
```json
|
|
@@ -23,7 +23,7 @@ import { publicOrigin } from './public-origin.mjs';
|
|
|
23
23
|
const segment = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
24
24
|
const STATE_KIND = 'rer-deploy-owner-state';
|
|
25
25
|
export const KINDS = ['d1','r2','kv','queues'];
|
|
26
|
-
const DECLARATION_KEYS = ['version','project','compatibilityDate','compatibilityFlags','d1','r2','kv','queues','durableObjects','secrets','crons','vars','originVar','publicOriginSetting','publicSettings','services','workersDev','platforms','container','deployGuide'];
|
|
26
|
+
const DECLARATION_KEYS = ['version','project','compatibilityDate','compatibilityFlags','d1','r2','kv','queues','durableObjects','secrets','crons','vars','originVar','publicOriginSetting','publicSettings','services','workersDev','platforms','container','deployGuide','productDirectory'];
|
|
27
27
|
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']};
|
|
28
28
|
|
|
29
29
|
export function refuse(code, kind, name) { const error = new Error(code); error.resource = `${kind}:${name}`; return error; }
|
|
@@ -20,7 +20,7 @@ const auth = createOperatorAuth({
|
|
|
20
20
|
SESSION_SECRET, SETUP_TOKEN,
|
|
21
21
|
MAIL_FROM: env.MAIL_FROM,
|
|
22
22
|
// Optional; omit for neutral workspace wording and /signin recovery.
|
|
23
|
-
branding: { productName: 'Example', accentColor: '#334155', signInPath: '/signin' },
|
|
23
|
+
branding: { productName: 'Example', accentColor: '#334155', signInPath: '/signin', mark: '/brand/mark.svg' },
|
|
24
24
|
// Optional explicit address list further restricts active operators.
|
|
25
25
|
// allowList: ['owner@example.com', 'staff@example.com'],
|
|
26
26
|
},
|
|
@@ -171,6 +171,16 @@ Optional `config.branding` fields are independently defaulted and validated:
|
|
|
171
171
|
| `productName` | `your workspace` | At most 80 UTF-16 code units before trimming, with at least one visible letter, number, punctuation or symbol; rejects C0/C1 controls, U+2028/U+2029 and default-ignorable code points, except contextual script joiners and emoji presentation described below |
|
|
172
172
|
| `accentColor` | `#334155` | Exactly six hexadecimal digits after `#` |
|
|
173
173
|
| `signInPath` | `/signin` | Same-origin absolute path, at most 2048 characters; no scheme, network-path reference, backslash or control characters, including encoded variants |
|
|
174
|
+
| `mark` | Omitted | Same-origin root-relative image pathname, 2–2048 characters from ASCII letters, digits, `/`, `.`, `_`, `~` and `-`; no doubled slashes or `.`/`..` path segments, schemes, encodings, query strings, fragments, whitespace, quotes or angle brackets |
|
|
175
|
+
| `theme` | Omitted | Same-origin CSS pathname ending in `.css`; `/` followed by 1–200 ASCII letters, digits, `.`, `_`, `~`, `/` or `-` before the extension; no doubled slashes or `/.` |
|
|
176
|
+
|
|
177
|
+
Serve `mark` from the installation, for example `public/brand/mark.svg` at
|
|
178
|
+
`/brand/mark.svg` (SVG or PNG). The shared sign-in, one-click owner entry and
|
|
179
|
+
confirmation header shows it as a 32×32 image beside the product name, which
|
|
180
|
+
stays as text. The local dev key exchange header uses 40×40. Both set
|
|
181
|
+
`alt` to the product name and `decoding="async"`, and permit only same-origin
|
|
182
|
+
images through CSP. An explicit mark takes precedence over a theme's
|
|
183
|
+
`--rer-logo`; omitting `mark` preserves the existing HTML and theme behaviour.
|
|
174
184
|
|
|
175
185
|
Product names preserve letters and combining marks in every script. ZWNJ
|
|
176
186
|
(U+200C) is allowed after a letter (including its combining marks) when a letter
|
|
@@ -192,16 +202,17 @@ allowed; malformed encodings in the configured value are rejected. Encoded
|
|
|
192
202
|
percent data is preserved, and nested encoded separators and controls are still
|
|
193
203
|
rejected. Invalid branding throws
|
|
194
204
|
`AuthError('invalid_configuration', 503)`. Branding is copied and frozen at
|
|
195
|
-
construction. `auth.presentation` exposes
|
|
196
|
-
|
|
205
|
+
construction. `auth.presentation` exposes the normalized branding fields,
|
|
206
|
+
including `mark` and `theme` only when supplied; it never exposes configuration secrets. `previewLink` returns only
|
|
197
207
|
`{kind, expiresInMinutes}` for an authorized link, otherwise null. Names are
|
|
198
208
|
HTML-escaped in documents and mail. The accent chooses black or white button
|
|
199
209
|
text for contrast, with a visible keyboard focus ring in light and dark schemes.
|
|
200
210
|
|
|
201
211
|
The module's confirmation HTML responses contain exactly one inline stylesheet. Their
|
|
202
|
-
CSP adds
|
|
203
|
-
policy
|
|
204
|
-
|
|
212
|
+
CSP adds its exact UTF-8 SHA-256 `style-src` hash to the existing restrictive
|
|
213
|
+
policy, plus same-origin image, stylesheet and font permissions when needed by
|
|
214
|
+
the declared mark, icons or theme. No scripts, remote resources, style attributes
|
|
215
|
+
or CSS imports are included in the document. JSON errors, redirects and other responses retain
|
|
205
216
|
the original CSP. Do not add a broad inline-style allowance to an adopting seed.
|
|
206
217
|
|
|
207
218
|
An application can compose its same-origin brand font head onto this document,
|
|
@@ -496,9 +507,10 @@ key, so a reset key refuses old cookies) or the key in `x-rer-dev-key` (the rer
|
|
|
496
507
|
CLI and test harnesses). `exchange(request, branding)` serves `GET /__dev/key` and trades
|
|
497
508
|
the key from the URL fragment, through a same-origin POST, for a host-only
|
|
498
509
|
`HttpOnly; SameSite=Strict; Path=/` cookie. Given the seed's `branding`
|
|
499
|
-
(`productName`, `theme`), the page between `rer dev` and the
|
|
500
|
-
mark, the `--rer-logo` its theme declares, as an
|
|
501
|
-
|
|
510
|
+
(`productName`, optional `mark` and `theme`), the page between `rer dev` and the
|
|
511
|
+
app shows the explicit mark, or the `--rer-logo` its theme declares, as an
|
|
512
|
+
`<img>` with the product name as its alt text. With neither mark declaration,
|
|
513
|
+
it shows the product name as text alone.
|
|
502
514
|
|
|
503
515
|
`dev/` is the dev layer: **server-only and local-only**. Import it only from a
|
|
504
516
|
local-only Worker entry (a Vite-serve or local `wrangler dev` entry), never
|
|
@@ -603,7 +615,9 @@ address; anything else is ignored; never submitted for the visitor), so a link
|
|
|
603
615
|
from the platform's Open app or a seed's own page can pass the claimed owner.
|
|
604
616
|
|
|
605
617
|
Wire `config.branding` with the seed's `productName`, `accentColor` and
|
|
606
|
-
`signInPath`; the defaults are `your workspace`, `#334155` and `/signin`.
|
|
618
|
+
`signInPath`; the defaults are `your workspace`, `#334155` and `/signin`. Pass
|
|
619
|
+
the seed's served mark path as optional `mark: '/brand/mark.svg'`, and its
|
|
620
|
+
served token stylesheet as optional `theme: '/rer-theme.css'`. Keep
|
|
607
621
|
`MAIL_FROM` in auth config and provide a real `mailSender` that implements
|
|
608
622
|
`send(message)`. The Base example builds it with `createMailSender` from
|
|
609
623
|
[the mail module](../mail/README.md), using mail config fields `provider`, `mode`, `apiKey` and
|
|
@@ -680,3 +694,10 @@ route configuration, CI and release; Base checks do not establish integrated
|
|
|
680
694
|
adoption or deployment.
|
|
681
695
|
|
|
682
696
|
The application-side dependency, owner-setting and logout protocol is documented in [dependencies](../dependencies/README.md). Existing stores default to provider sign-in off, and provider admission requires the app-owned setting.
|
|
697
|
+
|
|
698
|
+
## Owner-approved schedules
|
|
699
|
+
|
|
700
|
+
OA accounts offer a bounded, hash-pinned scheduled policy door, separate from
|
|
701
|
+
human sessions. Read [SCHEDULED-POLICY.md](SCHEDULED-POLICY.md) for the design,
|
|
702
|
+
additive migration, declaration, owner approval/revocation flow and audit contract.
|
|
703
|
+
The reference `/app/policies` screen and Worker scheduled handler show adoption.
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Owner-approved scheduled policies
|
|
2
|
+
|
|
3
|
+
Design · 19 October 2026
|
|
4
|
+
|
|
5
|
+
A seed declares trusted server-side definitions through OA `createOperatorAuth`'s
|
|
6
|
+
`scheduledPolicies: () => definitions` option. Only trusted Worker code calls
|
|
7
|
+
`run`; there is no HTTP run endpoint or caller-supplied actor granting scheduled
|
|
8
|
+
authority. Native-account adapters need an equivalent transaction fence before
|
|
9
|
+
adopting this door.
|
|
10
|
+
|
|
11
|
+
## Definition and approval
|
|
12
|
+
|
|
13
|
+
A definition contains an id, job kind, JSON parameters, allowed actions/scopes,
|
|
14
|
+
and two required integer bounds: `maxActionsPerRun` (1–100) and
|
|
15
|
+
`minIntervalMinutes` (1–525600). Supported actions are `operators:deactivate`
|
|
16
|
+
and `operators:reactivate`. Scopes require non-owner roles and may restrict exact
|
|
17
|
+
operator ids or require inactivity for `inactiveDays`. Owners and invitations
|
|
18
|
+
cannot be targets.
|
|
19
|
+
|
|
20
|
+
Inactivity uses `oa_operators.last_signin_at`, retained when sessions are deleted.
|
|
21
|
+
An insert trigger advances it when an OA session is created. For new accounts
|
|
22
|
+
that have never signed in, account creation is used; both the account creation
|
|
23
|
+
and sign-in cutoffs must pass. This measures sign-in, not activity in the seed's
|
|
24
|
+
domain. Legacy accounts receive a conservative timestamp at migration time,
|
|
25
|
+
retaining any later known sign-in, so missing historical sessions never establish
|
|
26
|
+
immediate inactivity.
|
|
27
|
+
|
|
28
|
+
Canonical JSON sorts object keys, preserves array order and rejects non-JSON
|
|
29
|
+
values. SHA-256 covers the complete definition, including both bounds. The owner
|
|
30
|
+
reviews that exact hash; approval rereads the definition and rejects stale hashes.
|
|
31
|
+
Approval stores the definition, actions, hash, owner id/authority version, session
|
|
32
|
+
kind, approval time and revocation details. Reapproval atomically revokes its
|
|
33
|
+
predecessor. When the runner first observes a changed definition, it revokes the
|
|
34
|
+
old approval with `superseded_by_change`; reverting the source cannot revive it.
|
|
35
|
+
|
|
36
|
+
Standing approval requires a native, OIDC or password owner session and the
|
|
37
|
+
existing `requireFreshProof` check, as well as origin/session transaction fences.
|
|
38
|
+
Development and review sessions are refused outright: cron cannot repeat their
|
|
39
|
+
request gate. The seed's `rolePolicy` must allow every declared action at approval.
|
|
40
|
+
Approval survives sign-out and session expiry; it is an explicit delegation.
|
|
41
|
+
Owner authority-version changes invalidate it, including demotion then promotion.
|
|
42
|
+
|
|
43
|
+
## Scheduled authority and bounds
|
|
44
|
+
|
|
45
|
+
A scheduled handler calls `auth.scheduledPolicies.run(policyId, async run => {
|
|
46
|
+
await run.execute('operators:deactivate', operatorId) })`. The callback receives a
|
|
47
|
+
bounded capability, never a simulated owner session. The door rereads the current
|
|
48
|
+
definition and live approval at admission and before each action. Before acting,
|
|
49
|
+
it evaluates the seed's current `rolePolicy` with the approving owner and target.
|
|
50
|
+
|
|
51
|
+
An internal policy actor selects an unforgeable store fence. The status mutation
|
|
52
|
+
and committed-action audit share a D1 transaction that rechecks approval
|
|
53
|
+
id/hash/actions, revocation, accepted approval session kind, active owner role and
|
|
54
|
+
authority version, admitted live run, action count and target scope. Sequential
|
|
55
|
+
capability use and the transaction count enforce `maxActionsPerRun`; the reference
|
|
56
|
+
selector also limits its candidates to that bound. Stale or overbroad selection
|
|
57
|
+
does not widen the approved scope. Closed run capabilities cannot act again.
|
|
58
|
+
Revocation stops subsequent writes at the transaction boundary; committed actions
|
|
59
|
+
remain committed. Existing final-owner and invitation/version triggers still apply.
|
|
60
|
+
|
|
61
|
+
Admission is serialized per policy: another admitted run cannot overlap, and the
|
|
62
|
+
minimum interval starts at the last admitted run's finish, including failed or
|
|
63
|
+
refused admitted runs. Early ticks are refused with `policy_interval`. Consecutive
|
|
64
|
+
identical unadmitted refusals for the same policy/version/approval/outcome coalesce
|
|
65
|
+
into one history row with `repeats` occurrences and `lastSeenAt`. Admitted runs
|
|
66
|
+
retain separate rows and action history.
|
|
67
|
+
|
|
68
|
+
Runs record outcome, timestamps and refusal/error codes. Action audits bind
|
|
69
|
+
`policy:<id>@<sha256>`, approving owner, approval id, unique run id, action and
|
|
70
|
+
target. Refused target attempts also record the attempted action and error code.
|
|
71
|
+
Other auth audit values may be opaque identifiers; policy queries and the run index only extract run ids from valid JSON. Partial failures retain earlier committed-action audits. The reference handler
|
|
72
|
+
attempts every policy despite prior failures, and attempts recording, policies
|
|
73
|
+
and pending erasures independently. Durable policy `AuthError` refusals remain
|
|
74
|
+
recorded; unexpected failures aggregate only after the jobs have been attempted.
|
|
75
|
+
Storage failures can prevent durable history and are surfaced as failures.
|
|
76
|
+
|
|
77
|
+
Worker code and the raw DB binding remain trusted. These fences bound authority
|
|
78
|
+
through operator-auth; they do not restrict arbitrary SQL in a compromised seed.
|
|
79
|
+
Version a job kind when changing its semantics and put all security-relevant
|
|
80
|
+
bounds in the hashed definition and enforcing implementation.
|
|
81
|
+
|
|
82
|
+
## Adoption, history and portability
|
|
83
|
+
|
|
84
|
+
For a deployment that applied the original scheduled-policy schema, apply
|
|
85
|
+
`scheduled-policy-hardening.sql` and `last-signin.sql` as new numbered migrations.
|
|
86
|
+
When first adding policies to an older OA store, apply the current
|
|
87
|
+
`accounts/schema/scheduled-policy.sql` instead of the hardening migration, plus
|
|
88
|
+
`last-signin.sql` if the sign-in column is absent. Preserve applied migration
|
|
89
|
+
history. Base upgrades its original `0029` with `0030` and `0031`. The hardening migration revokes existing approvals with
|
|
90
|
+
`fresh_approval_required`; owners must approve again with fresh proof. Apply the
|
|
91
|
+
last-sign-in migration after any `oa_sessions` rebuild so its trigger survives.
|
|
92
|
+
Fresh OA schemas include the current tables and trigger.
|
|
93
|
+
|
|
94
|
+
Declare definitions in trusted source, wire cron to `run`, select real candidates
|
|
95
|
+
and call `run.execute` for each. The default reference starts unapproved at
|
|
96
|
+
`/app/policies`. Its owner screen shows complete parameters/scopes, bounds, current
|
|
97
|
+
hash, approving owner/session kind, approval history and revocation reasons. Run
|
|
98
|
+
history exposes outcomes, tick occurrences, committed actions and refused targets,
|
|
99
|
+
including target ids, actor, approving owner, approval id, run id and timestamps.
|
|
100
|
+
Owners can navigate to older pages rather than losing history after a fixed cap.
|
|
101
|
+
|
|
102
|
+
Owner APIs are `GET /auth/policies`, `GET /auth/policy-runs`,
|
|
103
|
+
`POST /auth/policy/approve` with `{policyId, versionHash}`, and
|
|
104
|
+
`POST /auth/policy/revoke` with `{approvalId}`. `list` returns approval history and
|
|
105
|
+
each current definition's state. `runs` returns `{runs, nextCursor}` with up to 25
|
|
106
|
+
runs, newest first, including their action audits; pass `?before=<nextCursor>` for
|
|
107
|
+
the next page. Occurrences include the first tick. Retain `oa_policy_runs` and
|
|
108
|
+
`oa_auth_audit` for durable history.
|
|
109
|
+
|
|
110
|
+
Portable exports preserve approval provenance but revoke approvals in the export
|
|
111
|
+
snapshot, leaving the source installation unchanged. Import refuses an archive
|
|
112
|
+
containing any live policy approval. Restoring records does not transfer standing
|
|
113
|
+
authority; the destination owner must review and approve its current definitions.
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
const definitions = () => [{
|
|
117
|
+
id: 'inactive-members', kind: 'deactivate-members-without-recent-signin.v1',
|
|
118
|
+
parameters: { inactiveDays: 90 },
|
|
119
|
+
maxActionsPerRun: 25, minIntervalMinutes: 10,
|
|
120
|
+
actions: [{ action: 'operators:deactivate',
|
|
121
|
+
scope: { roles: ['member'], inactiveDays: 90 } }],
|
|
122
|
+
}];
|
|
123
|
+
const auth = createOperatorAuth({ ...authOptions, scheduledPolicies: definitions });
|
|
124
|
+
// Inside Worker.scheduled; select real candidates within the declared run limit.
|
|
125
|
+
await auth.scheduledPolicies.run('inactive-members', async run => {
|
|
126
|
+
for (const candidate of candidates) {
|
|
127
|
+
await run.execute('operators:deactivate', candidate.id);
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
```
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { writeOperatorStatus } from './status.mjs';
|
|
1
2
|
import { AuthError, deny } from '../errors.mjs';
|
|
2
3
|
import { normalizeEmail, safeReturnTo } from '../policy.mjs';
|
|
3
4
|
import { requirePost } from '../http.mjs';
|
|
@@ -72,16 +73,7 @@ export function administration(context) {
|
|
|
72
73
|
const target = await targetFor(operatorId);
|
|
73
74
|
const actor = await actorFor(request, status === 'active' ? 'operators:reactivate' : 'operators:deactivate', target);
|
|
74
75
|
if (target.status === 'invited') deny('invitation_required', 409);
|
|
75
|
-
|
|
76
|
-
try {
|
|
77
|
-
const result = await store.run(`UPDATE oa_operators SET status=? WHERE id=? AND version=? AND ${fence.sql}`, [status, target.id, target.version, ...fence.args]);
|
|
78
|
-
if (result.meta.changes < 1) deny('authority_changed', 409);
|
|
79
|
-
} catch (e) {
|
|
80
|
-
if (String(e).includes('last_owner')) deny('last_owner', 409);
|
|
81
|
-
if (String(e).includes('invitation_required')) deny('invitation_required', 409);
|
|
82
|
-
throw e;
|
|
83
|
-
}
|
|
84
|
-
return store.operator(target.id);
|
|
76
|
+
return writeOperatorStatus(store, actor, target, status, clock());
|
|
85
77
|
},
|
|
86
78
|
async setRole(request, operatorId, role) {
|
|
87
79
|
if (!DEFAULT_ROLES.includes(role)) throw new AuthError('invalid_role');
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
-- Apply as a NEW numbered migration after any oa_sessions rebuild.
|
|
2
|
+
-- Never infer inactivity from missing credentials: older sessions may have been
|
|
3
|
+
-- pruned. Existing operators receive a full inactivity window from this upgrade.
|
|
4
|
+
ALTER TABLE oa_operators ADD COLUMN last_signin_at INTEGER;
|
|
5
|
+
UPDATE oa_operators SET last_signin_at=MAX(
|
|
6
|
+
created_at, CAST(strftime('%s','now') AS INTEGER)*1000+999,
|
|
7
|
+
COALESCE((SELECT MAX(created_at) FROM oa_sessions WHERE operator_id=oa_operators.id),0)
|
|
8
|
+
);
|
|
9
|
+
CREATE TRIGGER oa_record_last_signin AFTER INSERT ON oa_sessions
|
|
10
|
+
BEGIN UPDATE oa_operators SET last_signin_at=NEW.created_at
|
|
11
|
+
WHERE id=NEW.operator_id AND (last_signin_at IS NULL OR last_signin_at<NEW.created_at); END;
|
|
@@ -4,7 +4,7 @@ CREATE TABLE oa_operators (
|
|
|
4
4
|
id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL,
|
|
5
5
|
role TEXT NOT NULL CHECK(role IN ('owner','admin','member')),
|
|
6
6
|
status TEXT NOT NULL CHECK(status IN ('invited','active','inactive')),
|
|
7
|
-
version INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL
|
|
7
|
+
version INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, last_signin_at INTEGER
|
|
8
8
|
);
|
|
9
9
|
CREATE TABLE oa_bootstrap (singleton INTEGER PRIMARY KEY CHECK(singleton=1), claim_id TEXT NOT NULL UNIQUE, claimed_at INTEGER NOT NULL);
|
|
10
10
|
CREATE TABLE oa_tokens (
|
|
@@ -25,6 +25,11 @@ CREATE TABLE oa_sessions (
|
|
|
25
25
|
created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, revoked_at INTEGER
|
|
26
26
|
);
|
|
27
27
|
CREATE INDEX oa_sessions_operator ON oa_sessions(operator_id);
|
|
28
|
+
-- Admission history survives credential expiry, revocation and portability scrubbing.
|
|
29
|
+
-- Existing stores apply schema/last-signin.sql after session rebuild migrations.
|
|
30
|
+
CREATE TRIGGER oa_record_last_signin AFTER INSERT ON oa_sessions
|
|
31
|
+
BEGIN UPDATE oa_operators SET last_signin_at=NEW.created_at
|
|
32
|
+
WHERE id=NEW.operator_id AND (last_signin_at IS NULL OR last_signin_at<NEW.created_at); END;
|
|
28
33
|
CREATE TABLE oa_external_identities (
|
|
29
34
|
issuer TEXT NOT NULL, subject TEXT NOT NULL, operator_id TEXT NOT NULL REFERENCES oa_operators(id),
|
|
30
35
|
PRIMARY KEY(issuer, subject)
|
|
@@ -140,3 +145,22 @@ BEGIN
|
|
|
140
145
|
UPDATE oa_setup_links SET owner_id=NEW.operator_id,owner_version=NEW.operator_version,session_id=NEW.id
|
|
141
146
|
WHERE owner_id IS NULL AND completed=0 AND expires_at>NEW.created_at;
|
|
142
147
|
END;
|
|
148
|
+
|
|
149
|
+
-- Apply as a NEW numbered migration. Authority and audit are durable, not sessions.
|
|
150
|
+
CREATE TABLE IF NOT EXISTS oa_policy_approvals (
|
|
151
|
+
id TEXT PRIMARY KEY, policy_id TEXT NOT NULL, version_hash TEXT NOT NULL,
|
|
152
|
+
definition TEXT NOT NULL, actions TEXT NOT NULL,
|
|
153
|
+
owner_id TEXT NOT NULL REFERENCES oa_operators(id), owner_version INTEGER NOT NULL,
|
|
154
|
+
approved_at INTEGER NOT NULL, revoked_at INTEGER,
|
|
155
|
+
session_kind TEXT NOT NULL, revoke_reason TEXT
|
|
156
|
+
);
|
|
157
|
+
CREATE UNIQUE INDEX IF NOT EXISTS oa_policy_live ON oa_policy_approvals(policy_id) WHERE revoked_at IS NULL;
|
|
158
|
+
CREATE TABLE IF NOT EXISTS oa_policy_runs (
|
|
159
|
+
id TEXT PRIMARY KEY, policy_id TEXT NOT NULL, version_hash TEXT,
|
|
160
|
+
approval_id TEXT REFERENCES oa_policy_approvals(id), approved_by TEXT,
|
|
161
|
+
started_at INTEGER NOT NULL, finished_at INTEGER,
|
|
162
|
+
status TEXT NOT NULL CHECK(status IN ('running','completed','refused','failed')), error TEXT,
|
|
163
|
+
admitted INTEGER NOT NULL DEFAULT 0, repeats INTEGER NOT NULL DEFAULT 1, last_seen_at INTEGER
|
|
164
|
+
);
|
|
165
|
+
CREATE INDEX IF NOT EXISTS oa_policy_runs_time ON oa_policy_runs(started_at DESC);
|
|
166
|
+
CREATE INDEX IF NOT EXISTS oa_policy_action_run ON oa_auth_audit(CASE WHEN json_valid(value) THEN json_extract(value,'$.runId') END,action);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
-- Existing approvals lack fresh proof and session provenance: require approval again.
|
|
2
|
+
ALTER TABLE oa_policy_approvals ADD COLUMN session_kind TEXT NOT NULL DEFAULT 'legacy';
|
|
3
|
+
ALTER TABLE oa_policy_approvals ADD COLUMN revoke_reason TEXT;
|
|
4
|
+
UPDATE oa_policy_approvals SET revoked_at=COALESCE(revoked_at,CAST(strftime('%s','now') AS INTEGER)*1000),revoke_reason='fresh_approval_required' WHERE revoked_at IS NULL;
|
|
5
|
+
ALTER TABLE oa_policy_runs ADD COLUMN admitted INTEGER NOT NULL DEFAULT 0;
|
|
6
|
+
ALTER TABLE oa_policy_runs ADD COLUMN repeats INTEGER NOT NULL DEFAULT 1;
|
|
7
|
+
ALTER TABLE oa_policy_runs ADD COLUMN last_seen_at INTEGER;
|
|
8
|
+
CREATE INDEX IF NOT EXISTS oa_policy_action_run ON oa_auth_audit(CASE WHEN json_valid(value) THEN json_extract(value,'$.runId') END,action);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
-- Apply as a NEW numbered migration. Authority and audit are durable, not sessions.
|
|
2
|
+
CREATE TABLE IF NOT EXISTS oa_policy_approvals (
|
|
3
|
+
id TEXT PRIMARY KEY, policy_id TEXT NOT NULL, version_hash TEXT NOT NULL,
|
|
4
|
+
definition TEXT NOT NULL, actions TEXT NOT NULL,
|
|
5
|
+
owner_id TEXT NOT NULL REFERENCES oa_operators(id), owner_version INTEGER NOT NULL,
|
|
6
|
+
approved_at INTEGER NOT NULL, revoked_at INTEGER,
|
|
7
|
+
session_kind TEXT NOT NULL, revoke_reason TEXT
|
|
8
|
+
);
|
|
9
|
+
CREATE UNIQUE INDEX IF NOT EXISTS oa_policy_live ON oa_policy_approvals(policy_id) WHERE revoked_at IS NULL;
|
|
10
|
+
CREATE TABLE IF NOT EXISTS oa_policy_runs (
|
|
11
|
+
id TEXT PRIMARY KEY, policy_id TEXT NOT NULL, version_hash TEXT,
|
|
12
|
+
approval_id TEXT REFERENCES oa_policy_approvals(id), approved_by TEXT,
|
|
13
|
+
started_at INTEGER NOT NULL, finished_at INTEGER,
|
|
14
|
+
status TEXT NOT NULL CHECK(status IN ('running','completed','refused','failed')), error TEXT,
|
|
15
|
+
admitted INTEGER NOT NULL DEFAULT 0, repeats INTEGER NOT NULL DEFAULT 1, last_seen_at INTEGER
|
|
16
|
+
);
|
|
17
|
+
CREATE INDEX IF NOT EXISTS oa_policy_runs_time ON oa_policy_runs(started_at DESC);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS oa_policy_action_run ON oa_auth_audit(CASE WHEN json_valid(value) THEN json_extract(value,'$.runId') END,action);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { deny } from '../errors.mjs';
|
|
2
|
+
// One persistence door for session and policy actors. The caller authorizes the
|
|
3
|
+
// action; the actor fence repeats live authority in this atomic write/audit.
|
|
4
|
+
export async function writeOperatorStatus(store, actor, target, status, now, audit) {
|
|
5
|
+
const fence = store.actorFence(actor, now);
|
|
6
|
+
try {
|
|
7
|
+
const statements = [[`UPDATE oa_operators SET status=? WHERE id=? AND version=? AND ${fence.sql} RETURNING id`, [status, target.id, target.version, ...fence.args]]];
|
|
8
|
+
if (audit) statements.push([`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at)
|
|
9
|
+
SELECT ?,?,?,?,? WHERE changes()>0`, [crypto.randomUUID(), audit.actor, audit.action, JSON.stringify(audit.value), now]]);
|
|
10
|
+
const [result] = await store.batch(statements);
|
|
11
|
+
if (!result.results.some(row => row.id === target.id)) deny('authority_changed', 409);
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (String(error).includes('last_owner')) deny('last_owner', 409);
|
|
14
|
+
if (String(error).includes('invitation_required')) deny('invitation_required', 409);
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
return store.operator(target.id);
|
|
18
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { policyActorFence } from '../scheduled/fence.mjs';
|
|
1
2
|
import { providerPinFence, recordProviderPin } from './provider-pin.mjs';
|
|
2
3
|
// D1 batches are transactions. All decisions that grant a session or mutate
|
|
3
4
|
// operator authority are repeated inside the same database transaction.
|
|
@@ -42,6 +43,8 @@ export class AuthStore {
|
|
|
42
43
|
// Snapshot authorization fence: both actor session and operator authority must
|
|
43
44
|
// still be valid when the SQL mutation executes, not merely when JS checked it.
|
|
44
45
|
actorFence(actor, now) {
|
|
46
|
+
const policy = policyActorFence(actor);
|
|
47
|
+
if (policy) return policy;
|
|
45
48
|
const pin = providerPinFence(actor.providerPin);
|
|
46
49
|
return { sql: `${pin.sql} AND EXISTS(SELECT 1 FROM oa_sessions a JOIN oa_operators ao ON ao.id=a.operator_id
|
|
47
50
|
WHERE a.token_hash=? AND a.revoked_at IS NULL AND a.expires_at>? AND ao.status='active'
|
|
@@ -32,7 +32,7 @@ function validProductName(name) {
|
|
|
32
32
|
export function configureBranding(input = {}) {
|
|
33
33
|
const invalid = () => { throw new AuthError('invalid_configuration', 503); };
|
|
34
34
|
if (!input || typeof input !== 'object' || Array.isArray(input)) invalid();
|
|
35
|
-
const { productName = 'your workspace', accentColor = '#334155', signInPath = '/signin', theme } = input;
|
|
35
|
+
const { productName = 'your workspace', accentColor = '#334155', signInPath = '/signin', theme, mark } = input;
|
|
36
36
|
if (!validProductName(productName)) invalid();
|
|
37
37
|
if (typeof accentColor !== 'string' || !/^#[0-9a-f]{6}$/i.test(accentColor)) invalid();
|
|
38
38
|
if (typeof signInPath !== 'string' || !signInPath.startsWith('/') || signInPath.startsWith('//') || /[\\\u0000-\u0020\u007f-\u009f]/u.test(signInPath)) invalid();
|
|
@@ -54,7 +54,10 @@ export function configureBranding(input = {}) {
|
|
|
54
54
|
}
|
|
55
55
|
// A seed theme is its own served rer-theme.css; Base onboarding validates its contents.
|
|
56
56
|
if (theme !== undefined && (typeof theme !== 'string' || !/^\/(?!\/)[A-Za-z0-9._~/-]{1,200}\.css$/.test(theme) || theme.includes('//') || theme.includes('/.'))) invalid();
|
|
57
|
-
|
|
57
|
+
// A served image pathname, never a remote URL or an encoded URL reference.
|
|
58
|
+
if (mark !== undefined && (typeof mark !== 'string' || mark.length < 2 || mark.length > 2048 || !mark.startsWith('/')
|
|
59
|
+
|| /[^A-Za-z0-9._~/-]/.test(mark) || mark.includes('//') || /\/\.{1,2}(?:\/|$)/.test(mark))) invalid();
|
|
60
|
+
return Object.freeze({ productName: productName.trim(), accentColor, signInPath, ...(theme ? { theme } : {}), ...(mark !== undefined ? { mark } : {}) });
|
|
58
61
|
}
|
|
59
62
|
|
|
60
63
|
/** WCAG relative luminance chooses readable text for any permitted brand color. */
|
|
@@ -24,11 +24,15 @@ hash plus only same-origin style/font permissions, and still rejects external
|
|
|
24
24
|
origins, scripts, images and unsafe inline attributes. Mail stays self-contained.
|
|
25
25
|
|
|
26
26
|
A consumer that configures `branding.productName` or a seed theme
|
|
27
|
-
(`branding.theme`, its served `rer-theme.css`)
|
|
28
|
-
`
|
|
27
|
+
(`branding.theme`, its served `rer-theme.css`) or an installation mark
|
|
28
|
+
(`branding.mark`, for example `/brand/mark.svg`) declares the same values as
|
|
29
|
+
`adapter.branding: { productName, theme, mark }`. Mail and confirmation must then
|
|
29
30
|
carry that name, and a themed confirmation must hold exactly that one theme
|
|
30
31
|
stylesheet link and the CSP `style-src 'self' 'sha256-…'; font-src 'self';
|
|
31
|
-
img-src 'self'
|
|
32
|
+
img-src 'self'`. A declared mark requires exactly that image, with product-name
|
|
33
|
+
alt text, 32×32 dimensions and asynchronous decoding beside the text name;
|
|
34
|
+
without a theme its CSP adds only `img-src 'self'`. Every other resource rule
|
|
35
|
+
above still applies, and mail stays image-free.
|
|
32
36
|
|
|
33
37
|
The Base conformance registration is executable at
|
|
34
38
|
[`../tests/conformance.test.ts`](../tests/conformance.test.ts), and its D1/Worker
|
|
@@ -29,8 +29,8 @@ export interface OperatorAuthConformanceRuntime {
|
|
|
29
29
|
export interface OperatorAuthConformanceAdapter {
|
|
30
30
|
/** Verify the consumer's same-origin font links and their bounded CSP permissions. */
|
|
31
31
|
confirmationFonts?: boolean;
|
|
32
|
-
/** The consumer's configured
|
|
33
|
-
branding?: { productName?: string; theme?: string };
|
|
32
|
+
/** The consumer's configured product name, served mark and rer-theme.css paths, when declared. */
|
|
33
|
+
branding?: { productName?: string; mark?: string; theme?: string };
|
|
34
34
|
/** Set only when the runtime also implements the provider-key-free admission seam case. */
|
|
35
35
|
oidcIssuer?: string;
|
|
36
36
|
/** Must create disposable real workerd/D1 state and mount the consumer's actual auth and private API routes. */
|