@runeditrun/rer 0.2.69 → 0.2.71
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-claim-session.mjs +25 -0
- package/cli/deploy-command.mjs +8 -3
- package/cli/deploy-observation.mjs +7 -2
- package/cli/deploy-owner.mjs +5 -4
- package/cli/deploy-product.mjs +30 -0
- package/cli/deploy.mjs +3 -1
- package/cli/portability-worker.mjs +7 -4
- package/global/CHANGELOG.md +17 -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 +137 -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-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 +38 -0
- package/modules/operator-auth/scheduled/expiry.mjs +17 -0
- package/modules/operator-auth/scheduled/fence.mjs +28 -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 +68 -0
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/portability/README.md +57 -4
- package/modules/portability/backfills.mjs +94 -0
- package/modules/portability/bridge.mjs +18 -12
- package/modules/portability/export.mjs +5 -1
- package/modules/portability/import.mjs +11 -7
- package/modules/portability/index.d.mts +1 -1
- package/modules/portability/migration-statements.mjs +105 -11
- package/modules/portability/policy-data.mjs +10 -0
- package/modules/portability/sql-text.mjs +95 -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,
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Nested deploy/hook observers can see the same response. Retire its credential
|
|
2
|
+
// once, after the hook has finished using it, and share any retirement failure.
|
|
3
|
+
const retirements = new WeakMap();
|
|
4
|
+
export function retireOwnerClaimSession(fetch, response, origin) {
|
|
5
|
+
const cookies = response.headers.getSetCookie().map(cookie => cookie.split(';', 1)[0]);
|
|
6
|
+
if (!cookies.length) return;
|
|
7
|
+
if (!retirements.has(response)) retirements.set(response, signOut(fetch, origin, cookies.join('; ')));
|
|
8
|
+
return retirements.get(response);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async function signOut(fetch, origin, cookie) {
|
|
12
|
+
let response;
|
|
13
|
+
try {
|
|
14
|
+
response = await fetch(new URL('/auth/signout', origin), {
|
|
15
|
+
method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(30000),
|
|
16
|
+
headers: { Origin: origin, 'Content-Type': 'application/json', Cookie: cookie }, body: '{}',
|
|
17
|
+
});
|
|
18
|
+
await response.body?.cancel();
|
|
19
|
+
if (response.status === 204 && !response.redirected) return;
|
|
20
|
+
} catch {}
|
|
21
|
+
const error = new Error('owner-claim-failed');
|
|
22
|
+
error.ownerSessionRetirement = true;
|
|
23
|
+
error.cause = `POST /auth/signout ${response ? `returned HTTP ${response.status}` : 'did not answer'}; the unused owner session could not be retired`;
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
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;
|
|
@@ -121,7 +123,7 @@ export async function deployCommand(context) {
|
|
|
121
123
|
let deployed, claimed, linked = false, linkResult, step = 'custom deploy';
|
|
122
124
|
const link = async (token, origin) => { if (!linked) { const state = await inspect(origin); linkResult = await linkDependencies?.(state?.origin ?? origin, token); linked = true; } return linkResult; };
|
|
123
125
|
try {
|
|
124
|
-
|
|
126
|
+
const result = await observeOwner({ paths: ['/auth/bootstrap', adapter.hooks?.owner?.path, setupManifest?.steps?.find(item => item.type === 'owner-claim')?.path].filter(Boolean), inspect, beforeClaim: link, addSecret, deployed: () => deployed, tokenKey: setupManifest?.steps?.find(item => item.type === 'owner-claim')?.tokenField }, async claims => {
|
|
125
127
|
observedClaims = claims;
|
|
126
128
|
const saved = { ...process.env };
|
|
127
129
|
try {
|
|
@@ -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');
|
|
@@ -160,11 +163,13 @@ export async function deployCommand(context) {
|
|
|
160
163
|
if (!linked) await linkDependencies?.(origin);
|
|
161
164
|
step = 'verify hosted setup';
|
|
162
165
|
await checkHostedSetup({ origin, claimed: claimed ?? state?.ownerClaim?.outcome ?? claims.at(-1)?.outcome, signal: context.signal });
|
|
163
|
-
if (claimed) store.report(`${claimed === 'claimed' ? 'Claimed the hosted owner' : 'The hosted owner was already claimed and was kept'}${state ? '; the one-time setup token was removed' : ''}. Sign in by email at ${origin}.`);
|
|
164
166
|
const { setupToken: _, ...result } = deployed;
|
|
165
167
|
return { ...result, ...(claimed ? { owner: claimed } : {}), dependenciesLinked: true };
|
|
166
168
|
});
|
|
169
|
+
if (claimed) store.report(`${claimed === 'claimed' ? 'Claimed the hosted owner' : 'The hosted owner was already claimed and was kept'}${recorded ? '; the one-time setup token was removed' : ''}. Sign in by email at ${result.origin}.`);
|
|
170
|
+
return result;
|
|
167
171
|
} catch (error) {
|
|
172
|
+
if (error instanceof DeployProductError) throw error;
|
|
168
173
|
const again = deployAgain(options);
|
|
169
174
|
const { commandFailure } = await shared('failures.mjs');
|
|
170
175
|
const secrets = secretFailureMessage(error);
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { observeReadiness, observedReadiness } from '../modules/deploy-kit/readiness-window.mjs';
|
|
2
2
|
import { ownerClaimRequest } from './deploy-claim-request.mjs';
|
|
3
|
+
import { retireOwnerClaimSession } from './deploy-claim-session.mjs';
|
|
3
4
|
// Observe the actual bootstrap exchange of a custom hook, including hooks that
|
|
4
5
|
// call the shared owner helper themselves. Never issue a second claim after it.
|
|
5
6
|
// The kit's deployment record, when the hook keeps one there, is checked before
|
|
6
7
|
// linking with its live setup token; rer checks the origin the hook returns too.
|
|
7
8
|
export async function observeOwner({ paths, inspect, beforeClaim, addSecret, deployed: knownDeployment, tokenKey }, run) {
|
|
8
|
-
const fetch = globalThis.fetch, claims = [];
|
|
9
|
+
const fetch = globalThis.fetch, claims = [], sessions = [];
|
|
9
10
|
globalThis.fetch = async (input, init = {}) => {
|
|
10
11
|
const url = new URL(input instanceof Request ? input.url : input);
|
|
11
12
|
let body;
|
|
@@ -23,6 +24,7 @@ export async function observeOwner({ paths, inspect, beforeClaim, addSecret, dep
|
|
|
23
24
|
await beforeClaim?.(body.token, url.origin);
|
|
24
25
|
const known = knownDeployment?.() ?? observedReadiness(url.origin);
|
|
25
26
|
const response = await ownerClaimRequest(fetch, input, init, {deployed:known ?? deployed, tokenKey});
|
|
27
|
+
if (response.status === 303) sessions.push({ response, origin: url.origin });
|
|
26
28
|
let code;
|
|
27
29
|
if (response.status !== 303) {
|
|
28
30
|
try { code = (await response.clone().json()).error; } catch {}
|
|
@@ -33,7 +35,10 @@ export async function observeOwner({ paths, inspect, beforeClaim, addSecret, dep
|
|
|
33
35
|
return response;
|
|
34
36
|
};
|
|
35
37
|
try { return await observeReadiness(() => run(claims)); }
|
|
36
|
-
finally {
|
|
38
|
+
finally {
|
|
39
|
+
globalThis.fetch = fetch;
|
|
40
|
+
await Promise.all(sessions.map(({ response, origin }) => retireOwnerClaimSession(fetch, response, origin)));
|
|
41
|
+
}
|
|
37
42
|
}
|
|
38
43
|
|
|
39
44
|
async function exchange(response,url,method) {
|
package/cli/deploy-owner.mjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { ownerClaimRequest } from './deploy-claim-request.mjs';
|
|
2
|
+
import { retireOwnerClaimSession } from './deploy-claim-session.mjs';
|
|
2
3
|
import { observeOwner, ownerExchangeFailure } from './deploy-observation.mjs';
|
|
3
4
|
import { randomBytes } from 'node:crypto';
|
|
4
5
|
|
|
5
6
|
// After a healthy deploy, the hosted app's first owner is the setup owner: rer
|
|
6
7
|
// claims it with the one-time setup token through the seed's standard owner step
|
|
7
|
-
// (Base operator-auth POST /auth/bootstrap),
|
|
8
|
-
// Worker and records the new Worker version. A Worker still holding a token rer
|
|
8
|
+
// (Base operator-auth POST /auth/bootstrap), signs out its unused session, then
|
|
9
|
+
// removes that token from the Worker and records the new Worker version. A Worker still holding a token rer
|
|
9
10
|
// did not upload this run gets a fresh one first, unless the person supplied the
|
|
10
11
|
// token (environment or --env-file) and inspection has not found it absent. A
|
|
11
12
|
// seed with its own owner step function runs its own bootstrap; identity-provider
|
|
@@ -60,7 +61,7 @@ export async function claimHostedOwner({ hook, setupManifest, declaration, deplo
|
|
|
60
61
|
} catch (cause) {
|
|
61
62
|
const exchange = exchanges.lastExchange ?? exchanges.at(-1);
|
|
62
63
|
const error = cause.message === 'owner-claim-failed' ? cause : ownerFailure(cause.message);
|
|
63
|
-
if (exchange) { error.ownerExchange = exchange; error.cause = ownerExchangeFailure(exchange); }
|
|
64
|
+
if (exchange && !cause.ownerSessionRetirement) { error.ownerExchange = exchange; error.cause = ownerExchangeFailure(exchange); }
|
|
64
65
|
throw error;
|
|
65
66
|
}
|
|
66
67
|
// Function hooks can keep existing owners without returning a value. Observe
|
|
@@ -76,7 +77,7 @@ export async function claimHostedOwner({ hook, setupManifest, declaration, deplo
|
|
|
76
77
|
headers: { Origin: deployed.origin, 'Content-Type': 'application/json' }, body: JSON.stringify({ token, displayName, returnTo: hook.returnTo ?? '/' }) }, {deployed, tokenKey, signal});
|
|
77
78
|
} catch (error) { throw ownerFailure(`POST ${new URL(hook.path ?? '/auth/bootstrap',deployed.origin).pathname}: ` + (['owner-claim-origin-mismatch','owner-claim-redirected','owner-claim-readiness-timeout'].includes(error.message) ? error.message : 'the hosted application did not answer')); }
|
|
78
79
|
if (response.status !== 303) { try { const body = await response.json(); if (typeof body?.error === 'string' && /^[a-z_]{1,64}$/.test(body.error)) code = body.error; } catch {} }
|
|
79
|
-
else await response.body?.cancel();
|
|
80
|
+
else { await retireOwnerClaimSession(fetch, response, deployed.origin); await response.body?.cancel(); }
|
|
80
81
|
const outcome = response.status === 303 ? 'claimed' : response.status === 409 && code === 'already_initialized' ? 'kept' : undefined;
|
|
81
82
|
const advice = code !== 'invalid_setup_token' ? '' : !secret ? `; the Worker holds another setup token: have the deploy hook return the one it deployed as setupToken, or set it as ${item.environment} with --env-file` : given ? `; the ${item.environment} you supplied is not the deployed setup token: leave it unset and rer issues a fresh one` : '';
|
|
82
83
|
if (!outcome) throw ownerFailure(`POST ${new URL(hook.path ?? '/auth/bootstrap',deployed.origin).pathname} returned HTTP ${response.status} (${code})${advice}`);
|
|
@@ -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;
|
|
@@ -4,6 +4,7 @@ import { readLegacyArchive } from '../modules/portability/format.mjs';
|
|
|
4
4
|
import { recoverLegacyArchive } from '../modules/portability/legacy-files.mjs';
|
|
5
5
|
import { legacyTargetState, requireLegacyEmpty } from '../modules/portability/legacy-safety.mjs';
|
|
6
6
|
import { migrationReplay } from '../modules/portability/migration-history.mjs';
|
|
7
|
+
import { splitStatements } from '../modules/portability/sql-text.mjs';
|
|
7
8
|
import { appliedMigrations as appliedMigrationNames } from '../modules/portability/bridge.mjs';
|
|
8
9
|
import { join } from 'node:path';
|
|
9
10
|
import { createHash } from 'node:crypto';
|
|
@@ -16,14 +17,16 @@ import { parseJsonc } from './jsonc.mjs';
|
|
|
16
17
|
import { loadPolicy } from './portability-policy.mjs';
|
|
17
18
|
|
|
18
19
|
// The migrations this installation applied, in its ledger's order, with each
|
|
19
|
-
// file's hash, so a restore can place an older archive within them.
|
|
20
|
-
|
|
20
|
+
// file's hash, so a restore can place an older archive within them. Statements
|
|
21
|
+
// are split at SQLite's own boundaries (sql-text.mjs), not Wrangler's: its
|
|
22
|
+
// splitter can glue a trigger holding CASE ... END to the statements after it.
|
|
23
|
+
async function appliedMigrations(root, db, binding) {
|
|
21
24
|
const config = parseJsonc(await readFile(join(root, 'wrangler.jsonc'), 'utf8'));
|
|
22
25
|
const directory = join(root, config.d1_databases.find(entry => entry.binding === binding).migrations_dir ?? 'migrations');
|
|
23
26
|
const names = await appliedMigrationNames(db) ?? [];
|
|
24
27
|
return Promise.all(names.map(async name => {
|
|
25
28
|
const bytes = await readFile(join(directory, name));
|
|
26
|
-
return { name, statements:
|
|
29
|
+
return { name, statements: splitStatements(bytes.toString('utf8')), sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
27
30
|
}));
|
|
28
31
|
}
|
|
29
32
|
|
|
@@ -57,7 +60,7 @@ async function run(direction, { root, path, journal, binding, buckets, policy, p
|
|
|
57
60
|
let proxy;
|
|
58
61
|
try {
|
|
59
62
|
proxy = await getPlatformProxy({ configPath, persist: { path: join(root, '.wrangler/state/v3') }, remoteBindings: false });
|
|
60
|
-
const migrations=async()=>migrationReplay(await appliedMigrations(root,proxy.env[binding],binding
|
|
63
|
+
const migrations=async()=>migrationReplay(await appliedMigrations(root,proxy.env[binding],binding),policy);
|
|
61
64
|
const options={ db: proxy.env[binding], buckets: Object.fromEntries(Object.entries(buckets).map(([name, binding]) => [name, proxy.env[binding]])), policy, migrations };
|
|
62
65
|
if(direction==='legacy-preflight') {
|
|
63
66
|
await requireLegacyEmpty(options,await legacyTargetState(options.db,options.migrations));
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.71
|
|
4
|
+
|
|
5
|
+
- **Restores split migrations at SQLite's own statement boundaries (#344).** The portability classifier re-splits each migration chunk with sql-text.mjs splitStatements (the sqlite3_complete state machine: a trigger ends only at `; END ;`, so `CASE … END` never ends it) and counts only real table names, never keywords, function names, qualified columns, literals or comments; the secret-column check still sees every identifier. rer import's replay uses the same splitter. Slate's retained archive restores past 0038.
|
|
6
|
+
- **Import door archive and restore-check (#320).** Door grants gain archive and restore-check actions behind one additive door migration: archives survive plan and catch-up, erasure withdraws them and says so, and restore-check parses with zero native writes and returns the hash and counts. A catch-up of an unchanged vendor export plans zero changes.
|
|
7
|
+
- **Scheduled policy hardening (#339).** One canonical snapshot is validated, hashed, stored and executed; unknown actions are refused at approval and at execution; the cap counts every run-linked audit action; running rows past the 15-minute scheduled-handler limit expire atomically as failed/policy_expired with an audit row the owner sees.
|
|
8
|
+
- **/run fits 360 px (#343).** The /run header reflows at its cause, so a 360 px viewport has no sideways scroll; the one-line npx start and byte-exact Copy are unchanged.
|
|
9
|
+
- **Deploy revokes the bootstrap session (#327).** After owner hooks and before reporting success, rer deploy signs out the unused bootstrap session it created, so a fresh hosted install holds zero live sessions until the owner signs in.
|
|
10
|
+
|
|
11
|
+
## 0.2.70
|
|
12
|
+
|
|
13
|
+
- **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.
|
|
14
|
+
- **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.
|
|
15
|
+
- **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.
|
|
16
|
+
- **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.
|
|
17
|
+
- **/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.
|
|
18
|
+
- **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.
|
|
19
|
+
|
|
3
20
|
## 0.2.69
|
|
4
21
|
|
|
5
22
|
- **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.
|
|
@@ -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,137 @@
|
|
|
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. The definition is snapshotted once; validation, action grants and SHA-256
|
|
30
|
+
all use that same snapshot, including both bounds. The owner
|
|
31
|
+
reviews that exact hash; approval rereads the definition and rejects stale hashes.
|
|
32
|
+
Approval stores the definition, actions, hash, owner id/authority version, session
|
|
33
|
+
kind, approval time and revocation details. Reapproval atomically revokes its
|
|
34
|
+
predecessor. When the runner first observes a changed definition, it revokes the
|
|
35
|
+
old approval with `superseded_by_change`; reverting the source cannot revive it.
|
|
36
|
+
|
|
37
|
+
Standing approval requires a native, OIDC or password owner session and the
|
|
38
|
+
existing `requireFreshProof` check, as well as origin/session transaction fences.
|
|
39
|
+
Development and review sessions are refused outright: cron cannot repeat their
|
|
40
|
+
request gate. The seed's `rolePolicy` must allow every declared action at approval.
|
|
41
|
+
Approval survives sign-out and session expiry; it is an explicit delegation.
|
|
42
|
+
Owner authority-version changes invalidate it, including demotion then promotion.
|
|
43
|
+
|
|
44
|
+
## Scheduled authority and bounds
|
|
45
|
+
|
|
46
|
+
A scheduled handler calls `auth.scheduledPolicies.run(policyId, async run => {
|
|
47
|
+
await run.execute('operators:deactivate', operatorId) })`. The callback receives a
|
|
48
|
+
bounded capability, never a simulated owner session. The door rereads the current
|
|
49
|
+
definition and live approval at admission and before each action. Before acting,
|
|
50
|
+
it evaluates the seed's current `rolePolicy` with the approving owner and target.
|
|
51
|
+
|
|
52
|
+
An internal policy actor selects an unforgeable store fence. The status mutation
|
|
53
|
+
and committed-action audit share a D1 transaction that rechecks approval
|
|
54
|
+
id/hash/actions, revocation, accepted approval session kind, active owner role and
|
|
55
|
+
authority version, admitted live run, action count and target scope. Sequential
|
|
56
|
+
capability use and the transaction count enforce `maxActionsPerRun`; the reference
|
|
57
|
+
selector also limits its candidates to that bound. Stale or overbroad selection
|
|
58
|
+
does not widen the approved scope. Closed run capabilities cannot act again.
|
|
59
|
+
Revocation stops subsequent writes at the transaction boundary; committed actions
|
|
60
|
+
remain committed. Existing final-owner and invitation/version triggers still apply.
|
|
61
|
+
|
|
62
|
+
Admission is serialized per policy: another admitted run cannot overlap, and the
|
|
63
|
+
minimum interval starts at the last admitted run's finish, including failed or
|
|
64
|
+
refused admitted runs. An admitted run still running beyond Cloudflare's
|
|
65
|
+
[15-minute scheduled-handler limit](https://developers.cloudflare.com/workers/platform/limits/#duration)
|
|
66
|
+
is atomically marked failed with `policy_expired` and a `policy:expired` audit
|
|
67
|
+
bound to its original run id. Its minimum interval is measured from admission,
|
|
68
|
+
so recovery cannot exceed the approved tick frequency; live runs still block
|
|
69
|
+
overlap. Expired capabilities cannot write or overwrite the expiry outcome.
|
|
70
|
+
Early ticks are refused with `policy_interval`. Consecutive
|
|
71
|
+
identical unadmitted refusals for the same policy/version/approval/outcome coalesce
|
|
72
|
+
into one history row with `repeats` occurrences and `lastSeenAt`. Admitted runs
|
|
73
|
+
retain separate rows and action history.
|
|
74
|
+
|
|
75
|
+
Runs record outcome, timestamps and refusal/error codes. Action audits bind
|
|
76
|
+
`policy:<id>@<sha256>`, approving owner, approval id, unique run id, action and
|
|
77
|
+
target. Refused target attempts also record the attempted action and error code.
|
|
78
|
+
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
|
|
79
|
+
attempts every policy despite prior failures, and attempts recording, policies
|
|
80
|
+
and pending erasures independently. Durable policy `AuthError` refusals remain
|
|
81
|
+
recorded; unexpected failures aggregate only after the jobs have been attempted.
|
|
82
|
+
Storage failures can prevent durable history and are surfaced as failures.
|
|
83
|
+
|
|
84
|
+
Worker code and the raw DB binding remain trusted. These fences bound authority
|
|
85
|
+
through operator-auth; they do not restrict arbitrary SQL in a compromised seed.
|
|
86
|
+
Version a job kind when changing its semantics and put all security-relevant
|
|
87
|
+
bounds in the hashed definition and enforcing implementation.
|
|
88
|
+
|
|
89
|
+
## Adoption, history and portability
|
|
90
|
+
|
|
91
|
+
For a deployment that applied the original scheduled-policy schema, apply
|
|
92
|
+
`scheduled-policy-hardening.sql` and `last-signin.sql` as new numbered migrations.
|
|
93
|
+
When first adding policies to an older OA store, apply the current
|
|
94
|
+
`accounts/schema/scheduled-policy.sql` instead of the hardening migration, plus
|
|
95
|
+
`last-signin.sql` if the sign-in column is absent. Preserve applied migration
|
|
96
|
+
history. Base upgrades its original `0029` with `0030` and `0031`. The hardening migration revokes existing approvals with
|
|
97
|
+
`fresh_approval_required`; owners must approve again with fresh proof. Apply the
|
|
98
|
+
last-sign-in migration after any `oa_sessions` rebuild so its trigger survives.
|
|
99
|
+
Fresh OA schemas include the current tables and trigger.
|
|
100
|
+
|
|
101
|
+
Declare definitions in trusted source, wire cron to `run`, select real candidates
|
|
102
|
+
and call `run.execute` for each. The default reference starts unapproved at
|
|
103
|
+
`/app/policies`. Its owner screen shows complete parameters/scopes, bounds, current
|
|
104
|
+
hash, approving owner/session kind, approval history and revocation reasons. Run
|
|
105
|
+
history exposes outcomes, tick occurrences, committed actions and refused targets,
|
|
106
|
+
including target ids, actor, approving owner, approval id, run id and timestamps.
|
|
107
|
+
Owners can navigate to older pages rather than losing history after a fixed cap.
|
|
108
|
+
|
|
109
|
+
Owner APIs are `GET /auth/policies`, `GET /auth/policy-runs`,
|
|
110
|
+
`POST /auth/policy/approve` with `{policyId, versionHash}`, and
|
|
111
|
+
`POST /auth/policy/revoke` with `{approvalId}`. `list` returns approval history and
|
|
112
|
+
each current definition's state. `runs` returns `{runs, nextCursor}` with up to 25
|
|
113
|
+
runs, newest first, including their action audits; pass `?before=<nextCursor>` for
|
|
114
|
+
the next page. Occurrences include the first tick. Retain `oa_policy_runs` and
|
|
115
|
+
`oa_auth_audit` for durable history.
|
|
116
|
+
|
|
117
|
+
Portable exports preserve approval provenance but revoke approvals in the export
|
|
118
|
+
snapshot, leaving the source installation unchanged. Import refuses an archive
|
|
119
|
+
containing any live policy approval. Restoring records does not transfer standing
|
|
120
|
+
authority; the destination owner must review and approve its current definitions.
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
const definitions = () => [{
|
|
124
|
+
id: 'inactive-members', kind: 'deactivate-members-without-recent-signin.v1',
|
|
125
|
+
parameters: { inactiveDays: 90 },
|
|
126
|
+
maxActionsPerRun: 25, minIntervalMinutes: 10,
|
|
127
|
+
actions: [{ action: 'operators:deactivate',
|
|
128
|
+
scope: { roles: ['member'], inactiveDays: 90 } }],
|
|
129
|
+
}];
|
|
130
|
+
const auth = createOperatorAuth({ ...authOptions, scheduledPolicies: definitions });
|
|
131
|
+
// Inside Worker.scheduled; select real candidates within the declared run limit.
|
|
132
|
+
await auth.scheduledPolicies.run('inactive-members', async run => {
|
|
133
|
+
for (const candidate of candidates) {
|
|
134
|
+
await run.execute('operators:deactivate', candidate.id);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
```
|
|
@@ -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);
|