@runeditrun/rer 0.2.69 → 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/global/CHANGELOG.md +9 -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-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/portability/README.md +46 -4
- package/modules/portability/backfills.mjs +89 -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 +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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Shared black-box presentation checks run against each consumer's actual Worker.
|
|
2
|
-
export async function checkConfirmation(response, { kind, productName, minutes = 15, token, signInPath = '/signin', confirmationFonts = false, theme }) {
|
|
2
|
+
export async function checkConfirmation(response, { kind, productName, minutes = 15, token, signInPath = '/signin', confirmationFonts = false, theme, mark }) {
|
|
3
3
|
const valid = !!kind;
|
|
4
4
|
expect(response.status === (valid ? 200 : 400), 'confirmation status');
|
|
5
5
|
expect(response.headers.get('set-cookie') === null, 'preview must be cookie-free');
|
|
@@ -11,7 +11,7 @@ export async function checkConfirmation(response, { kind, productName, minutes =
|
|
|
11
11
|
const hash = btoa(String.fromCharCode(...new Uint8Array(digest)));
|
|
12
12
|
const fontsPolicy = confirmationFonts ? " 'self'; font-src 'self'" : '';
|
|
13
13
|
// A declared seed theme is one same-origin stylesheet whose fonts and logo the app serves.
|
|
14
|
-
const sources = theme ? `style-src 'self' 'sha256-${hash}'; font-src 'self'; img-src 'self'` : `style-src 'sha256-${hash}'${fontsPolicy}`;
|
|
14
|
+
const sources = theme ? `style-src 'self' 'sha256-${hash}'; font-src 'self'; img-src 'self'` : `style-src 'sha256-${hash}'${fontsPolicy}${mark ? "; img-src 'self'" : ''}`;
|
|
15
15
|
expect(response.headers.get('content-security-policy') === `default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'; ${sources}`, 'only approved stylesheet and font CSP sources');
|
|
16
16
|
const themeLink = theme && `<link rel="stylesheet" href="${escape(theme)}">`;
|
|
17
17
|
const allLinks = [...html.matchAll(/<link\b[^>]*>/gi)].map(match => match[0]);
|
|
@@ -31,7 +31,12 @@ export async function checkConfirmation(response, { kind, productName, minutes =
|
|
|
31
31
|
expect(resources.filter(attrs => attrs.rel === 'stylesheet' && /\.css$/i.test(attrs.href) && Object.keys(attrs).length === 2).length === 1, 'one same-origin font stylesheet');
|
|
32
32
|
expect(resources.filter(attrs => attrs.rel === 'preload' && attrs.as === 'font' && /^font\//.test(attrs.type ?? '') && attrs.crossorigin === 'anonymous' && /\.(woff2?|ttf|otf)$/i.test(attrs.href)).length === 1, 'one reusable primary font preload');
|
|
33
33
|
} else expect(links.length === 0, 'standalone confirmation remains self-contained');
|
|
34
|
-
|
|
34
|
+
const image = mark ? `<img src="${escape(mark)}" alt="${escape(productName)}" width="32" height="32" decoding="async">` : '';
|
|
35
|
+
if (mark) {
|
|
36
|
+
expect(html.includes(image), 'the declared mark with product alt text and header dimensions');
|
|
37
|
+
expect(html.includes(`<span data-rer-name>${escape(productName)}</span>`), 'product name remains text beside the mark');
|
|
38
|
+
}
|
|
39
|
+
expect(!/<script|<img|\bon[a-z]+\s*=|style=|url\s*\(|@import|https?:\/\//i.test(html.replace(/<link\b[^>]*>/gi, '').replace(image, '')), 'no other resources or inline attributes');
|
|
35
40
|
expect(html.includes(escape(productName)), 'escaped product name');
|
|
36
41
|
if (valid) {
|
|
37
42
|
expect(html.includes(`<h1>${kind === 'invite' ? 'Accept your invitation to' : 'Confirm sign-in to'} ${escape(productName)}</h1>`), 'plain confirmation heading');
|
|
@@ -81,7 +81,7 @@ export function devGate({ key, origin, local }) {
|
|
|
81
81
|
return value !== null && constantEqual(value, await cookie());
|
|
82
82
|
},
|
|
83
83
|
setCookie,
|
|
84
|
-
// GET serves the exchange page
|
|
84
|
+
// GET serves the exchange page with the seed's productName, mark and theme; POST trades the key for the cookie.
|
|
85
85
|
async exchange(request, branding) {
|
|
86
86
|
if (new URL(request.url).pathname !== DEV_KEY_PATH) return null;
|
|
87
87
|
if (request.method === 'GET' || request.method === 'HEAD') {
|
|
@@ -89,9 +89,11 @@ export function devGate({ key, origin, local }) {
|
|
|
89
89
|
// The seed's declared branding (its product name and theme) brands the page; without it the page is unnamed.
|
|
90
90
|
const brand = branding === undefined ? undefined : configureBranding(branding);
|
|
91
91
|
const theme = brand?.theme;
|
|
92
|
-
const
|
|
92
|
+
const mark = brand?.mark ? `<img src="${escapeHtml(brand.mark)}" alt="${escapeHtml(brand.productName)}" width="40" height="40" decoding="async">` : '';
|
|
93
|
+
const themeLogo = theme && !brand.mark;
|
|
94
|
+
const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex, nofollow"><title>Opening the local app</title>${iconHead}${theme ? `<link rel="stylesheet" href="${escapeHtml(theme)}">` : ''}<style>${PAGE_STYLE}</style></head><body><main>${brand ? `<p class="brand">${mark}<span>${escapeHtml(brand.productName)}</span></p>` : ''}<h1>Opening the local app</h1><p>Open the RER_OPEN link that rer prints on this computer.</p></main>${themeLogo ? `<script>${LOGO_SCRIPT}</script>` : ''}<script>${EXCHANGE_SCRIPT}</script></body></html>`;
|
|
93
95
|
return new Response(request.method === 'HEAD' ? null : body, { headers: { ...privateHeaders, 'content-type': 'text/html; charset=utf-8',
|
|
94
|
-
'content-security-policy': `default-src 'none'; img-src 'self'; script-src ${script}${
|
|
96
|
+
'content-security-policy': `default-src 'none'; img-src 'self'; script-src ${script}${themeLogo ? ` ${logo}` : ''}; style-src ${theme ? "'self' " : ''}${style}${theme ? "; font-src 'self'" : ''}; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'` } });
|
|
95
97
|
}
|
|
96
98
|
if (request.method !== 'POST' || request.headers.get('sec-fetch-site') === 'cross-site' || !request.headers.get('content-type')?.startsWith('application/json')) return rejectedResponse(request, devNotFound());
|
|
97
99
|
const text = await request.text();
|
|
@@ -5,8 +5,8 @@ export interface Session<R extends string = Role> { issuer?: string; subject?: s
|
|
|
5
5
|
export interface CompletedSession<R extends string = Role> { session: Pick<Session<R>, 'id' | 'kind' | 'createdAt' | 'expiresAt'>; operator: Operator<R>; cookie: string; returnTo: string }
|
|
6
6
|
export interface MailMessage { deliveryId: string; from: string; to: string[]; subject: string; text: string; html: string; headers: Record<string, string> }
|
|
7
7
|
export interface MailSender { send(message: MailMessage): Promise<{ status: 'accepted' | 'rejected' | 'rate_limited' | 'uncertain' | 'development'; provider: string; providerMessageId: string | null; code?: string }> }
|
|
8
|
-
export interface AuthBranding { productName?: string; accentColor?: string; signInPath?: string; /** Same-origin path of the seed's served rer-theme.css. */ theme?: string }
|
|
9
|
-
export interface AuthPresentation { readonly productName: string; readonly accentColor: string; readonly signInPath: string; readonly theme?: string }
|
|
8
|
+
export interface AuthBranding { productName?: string; accentColor?: string; signInPath?: string; /** Same-origin root-relative image pathname served by the installation. */ mark?: string; /** Same-origin path of the seed's served rer-theme.css. */ theme?: string }
|
|
9
|
+
export interface AuthPresentation { readonly productName: string; readonly accentColor: string; readonly signInPath: string; readonly mark?: string; readonly theme?: string }
|
|
10
10
|
export interface LinkPreview { kind: 'magic' | 'invite' | 'step_up' | 'owner'; expiresInMinutes: number }
|
|
11
11
|
/** A step-up confirmation proves the session's operator again; it issues no new session. */
|
|
12
12
|
export interface StepUpConfirmed { stepUp: StepUpAction; returnTo: string; cookie?: undefined }
|
|
@@ -90,7 +90,10 @@ export interface AuthHooks<R extends string = Role> {
|
|
|
90
90
|
/** After an email-link or provider sign-in completes. Return a returnTo to redirect; throw to refuse (the new session is revoked). */
|
|
91
91
|
afterConfirm?(input: { request: Request; operator: Operator<R>; session: CompletedSession<R>['session']; method: 'email' | 'oidc'; returnTo: string }): void | { returnTo?: string } | Promise<void | { returnTo?: string }>;
|
|
92
92
|
}
|
|
93
|
+
export type { ScheduledPolicy, ScheduledPolicyDoor, PolicyApproval, PolicyRun } from './scheduled/index.mjs';
|
|
93
94
|
export interface AuthOptions<R extends string = Role> {
|
|
95
|
+
/** OA store only: trusted source, re-read at approval/run/action time. */
|
|
96
|
+
scheduledPolicies?: () => import('./scheduled/index.mjs').ScheduledPolicy[];
|
|
94
97
|
db: Database; config: AuthConfig; mailSender?: MailSender; clientIp: (request: Request) => string | Promise<string>; rolePolicy?: RolePolicy; clock?: () => number;
|
|
95
98
|
hooks?: AuthHooks<R>;
|
|
96
99
|
/** The runtime's fetch for provider discovery, JWKS and token calls (it must honour redirect: 'manual' and AbortSignal). */
|
|
@@ -142,6 +145,7 @@ export interface IdentityProviders {
|
|
|
142
145
|
}
|
|
143
146
|
export interface DomainRule { domain: string; providerId: string; createdAt: number }
|
|
144
147
|
export interface OperatorAuth<R extends string = Role> {
|
|
148
|
+
readonly scheduledPolicies?: import('./scheduled/index.mjs').ScheduledPolicyDoor;
|
|
145
149
|
/** Key-gated local development or an isolated hosted demo; unavailable in production. */
|
|
146
150
|
readonly oneClick?: {
|
|
147
151
|
people(request: Request): Promise<Array<{ email: string; displayName: string; role: R; href: string }> | null>;
|
|
@@ -20,16 +20,18 @@ function stylesheet(accentColor) {
|
|
|
20
20
|
const FORMS = `label{display:block;font-weight:600;margin:0 0 8px}input{display:block;width:100%;margin:0 0 16px;padding:12px 14px;border:1px solid #64748b;border-radius:10px;font:inherit;line-height:1.5;color:inherit;background:transparent}input:focus-visible{outline:3px solid #172033;outline-offset:2px}.stack{display:grid;gap:12px;margin:0 0 24px}.check{display:flex;align-items:center;gap:12px;margin:0 0 24px}.check input{width:20px;height:20px;margin:0;padding:0;flex:none}button.secondary{background:transparent;color:inherit}.divider{display:flex;align-items:center;gap:12px;margin:0 0 24px;color:#475569;font-size:14px}.divider::before,.divider::after{content:"";flex:1;border-top:1px solid #dce2ea}.notice{border-left:4px solid #64748b;padding:8px 12px;margin:0 0 24px}h2{font-size:20px;line-height:1.4;margin:32px 0 16px}.secondary-link{margin:16px 0 0;text-align:center;font-size:15px}.secondary-link a{display:inline-block;min-width:24px;min-height:24px;color:#334155;font-weight:600;text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:3px}.secondary-link a:hover{text-decoration-thickness:2px}.secondary-link a:focus-visible{outline:3px solid #172033;outline-offset:2px;border-radius:2px}@media(prefers-color-scheme:dark){input:focus-visible,.secondary-link a:focus-visible{outline-color:#f8fafc}.divider{color:#cbd5e1}.divider::before,.divider::after{border-color:#475569}.secondary-link a{color:#cbd5e1}}`;
|
|
21
21
|
|
|
22
22
|
export async function pageResponse({ branding, title, heading, content, status = 200, method = 'GET', referrer, formTargets = [] }) {
|
|
23
|
-
const css = stylesheet(branding.accentColor) + FORMS + (branding.theme ? themed(branding.accentColor) : '')
|
|
23
|
+
const css = stylesheet(branding.accentColor) + FORMS + (branding.theme ? themed(branding.accentColor) : '')
|
|
24
|
+
+ (branding.mark ? '.brand{display:flex;align-items:center;gap:12px}.brand img{display:block;flex:none;width:32px;height:32px;object-fit:contain}.rer-themed .brand::before,.brand::before{display:none}' : '');
|
|
24
25
|
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(css)));
|
|
25
26
|
const hash = btoa(String.fromCharCode(...digest));
|
|
26
27
|
const product = escapeHtml(branding.productName);
|
|
27
|
-
const
|
|
28
|
+
const mark = branding.mark ? `<img src="${escapeHtml(branding.mark)}" alt="${product}" width="32" height="32" decoding="async">` : '<span class="mark" aria-hidden="true"></span>';
|
|
29
|
+
const html = `<!doctype html><html lang="en"${branding.theme ? ' class="rer-themed"' : ''}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title ?? heading}</title>${iconHead}${branding.theme ? `<link rel="stylesheet" href="${escapeHtml(branding.theme)}">` : ''}<style>${css}</style></head><body><main><p class="brand">${mark}<span data-rer-name>${product}</span></p><h1>${heading}</h1>${content}</main></body></html>`;
|
|
28
30
|
const headers = { ...securityHeaders(), 'Content-Type': 'text/html; charset=utf-8' };
|
|
29
31
|
// A form may post to this origin only, plus any origin its own redirect must reach (a provider's authorization endpoint).
|
|
30
32
|
if (formTargets.length) headers['Content-Security-Policy'] = headers['Content-Security-Policy'].replace("form-action 'self'", `form-action 'self' ${formTargets.join(' ')}`);
|
|
31
33
|
headers['Content-Security-Policy'] += branding.theme ? `; style-src 'self' 'sha256-${hash}'; font-src 'self'; img-src 'self'` : `; style-src 'sha256-${hash}'`;
|
|
32
|
-
if (iconHead && !branding.theme) headers['Content-Security-Policy'] += "; img-src 'self'";
|
|
34
|
+
if ((iconHead || branding.mark) && !branding.theme) headers['Content-Security-Policy'] += "; img-src 'self'";
|
|
33
35
|
// Native form POSTs need their Origin; never disclose the path or query.
|
|
34
36
|
if (referrer) headers['Referrer-Policy'] = referrer;
|
|
35
37
|
return new Response(method === 'HEAD' ? null : html, { status, headers });
|
|
@@ -60,12 +60,14 @@ export function createAuthHandler(auth) {
|
|
|
60
60
|
return person ? { ...operator, signInUrl: person.href } : operator;
|
|
61
61
|
}));
|
|
62
62
|
}
|
|
63
|
+
if (auth.scheduledPolicies && path === '/auth/policies' && request.method === 'GET') return json(await auth.scheduledPolicies.list(request));
|
|
64
|
+
if (auth.scheduledPolicies && path === '/auth/policy-runs' && request.method === 'GET') return json(await auth.scheduledPolicies.runs(request));
|
|
63
65
|
if (path === '/auth/sessions' && request.method === 'GET') return json(await auth.listSessions(request, readParameters(url.searchParams).operatorId));
|
|
64
66
|
if (path === '/auth/domain-rules' && request.method === 'GET') return json(await auth.listDomainRules(request));
|
|
65
67
|
if (path === '/auth/settings/identity' && request.method === 'GET') {const value=await auth.identitySettings(request);return /text\/html/.test(request.headers.get('accept')??'')?await identitySettingsPage(value,auth.presentation):json(value);}
|
|
66
68
|
if (path === '/auth/providers' && request.method === 'GET') return json(await auth.listProviders(request));
|
|
67
69
|
const posts = new Set(['/auth/bootstrap', '/auth/magic-link', '/auth/confirm', '/auth/signout', '/auth/invite', '/auth/invite/cancel', '/auth/review-session',
|
|
68
|
-
'/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email', '/auth/display-name']);
|
|
70
|
+
'/auth/policy/approve', '/auth/policy/revoke', '/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email', '/auth/display-name']);
|
|
69
71
|
if (!posts.has(path)) return json({ error: 'not_found' }, 404);
|
|
70
72
|
if (request.method !== 'POST') return json({ error: 'method_not_allowed' }, 405);
|
|
71
73
|
const query = readParameters(url.searchParams);
|
|
@@ -74,7 +76,10 @@ export function createAuthHandler(auth) {
|
|
|
74
76
|
if (Object.hasOwn(query, 'token')) throw new AuthError('invalid_input');
|
|
75
77
|
form = formPost(request) && ['/auth/magic-link', '/auth/step-up'].includes(path);
|
|
76
78
|
const input = await readInput(request);
|
|
79
|
+
if (path.startsWith('/auth/policy/') && !auth.scheduledPolicies) return json({ error: 'not_found' }, 404);
|
|
77
80
|
switch (path) {
|
|
81
|
+
case '/auth/policy/approve': return json(await auth.scheduledPolicies.approve(request, input));
|
|
82
|
+
case '/auth/policy/revoke': await auth.scheduledPolicies.revoke(request, input); return json({ revoked: true });
|
|
78
83
|
case '/auth/settings/identity': {const value=await auth.setIdentitySettings(request,formPost(request)?{idpSignIn:input.idpSignIn==='true'}:input);return formPost(request)?seeOther('/auth/settings/identity'):json(value);}
|
|
79
84
|
case '/auth/setup-complete': return json(await auth.completeLocalSetup(request));
|
|
80
85
|
case '/auth/bootstrap': { const value = await auth.bootstrap(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { AuthError } from '../errors.mjs';
|
|
2
|
+
const actions = ['operators:deactivate', 'operators:reactivate'];
|
|
3
|
+
const plain = value => value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
|
|
4
|
+
function invalid() { throw new AuthError('invalid_policy', 503); }
|
|
5
|
+
function keys(value, allowed) { if (!plain(value) || Object.keys(value).some(key => !allowed.includes(key))) invalid(); }
|
|
6
|
+
function canonical(value) {
|
|
7
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
|
|
8
|
+
if (typeof value === 'number' && Number.isFinite(value)) return JSON.stringify(value);
|
|
9
|
+
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
|
|
10
|
+
if (plain(value)) return '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonical(value[key])).join(',') + '}';
|
|
11
|
+
return invalid();
|
|
12
|
+
}
|
|
13
|
+
export async function policyVersion(input) {
|
|
14
|
+
keys(input, ['id', 'kind', 'parameters', 'actions', 'maxActionsPerRun', 'minIntervalMinutes']);
|
|
15
|
+
if (!/^[a-z][a-z0-9-]{0,79}$/.test(input.id) || typeof input.id !== 'string' || typeof input.kind !== 'string' || !/^[a-z][a-z0-9:._-]{0,119}$/.test(input.kind) || !plain(input.parameters) || !Array.isArray(input.actions) || !input.actions.length || input.actions.length > 20) invalid();
|
|
16
|
+
if (!Number.isSafeInteger(input.maxActionsPerRun) || input.maxActionsPerRun < 1 || input.maxActionsPerRun > 100 || !Number.isSafeInteger(input.minIntervalMinutes) || input.minIntervalMinutes < 1 || input.minIntervalMinutes > 525600) invalid();
|
|
17
|
+
for (const grant of input.actions) {
|
|
18
|
+
keys(grant, ['action', 'scope']);
|
|
19
|
+
if (!actions.includes(grant.action)) invalid();
|
|
20
|
+
keys(grant.scope, ['roles', 'operatorIds', 'inactiveDays']);
|
|
21
|
+
const { roles, operatorIds, inactiveDays } = grant.scope;
|
|
22
|
+
if (!Array.isArray(roles) || !roles.length || roles.some(role => !['member', 'admin'].includes(role)) || new Set(roles).size !== roles.length) invalid();
|
|
23
|
+
if (operatorIds !== undefined && (!Array.isArray(operatorIds) || !operatorIds.length || operatorIds.length > 500 || operatorIds.some(id => typeof id !== 'string' || !id || id.length > 200) || new Set(operatorIds).size !== operatorIds.length)) invalid();
|
|
24
|
+
if (inactiveDays !== undefined && (!Number.isSafeInteger(inactiveDays) || inactiveDays < 1 || inactiveDays > 36500)) invalid();
|
|
25
|
+
}
|
|
26
|
+
const json = canonical(input);
|
|
27
|
+
if (json.length > 32768) invalid();
|
|
28
|
+
const versionHash = [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(json)))].map(byte => byte.toString(16).padStart(2, '0')).join('');
|
|
29
|
+
return { definition: JSON.parse(json), versionHash, json, actionsJson: canonical(input.actions) };
|
|
30
|
+
}
|
|
31
|
+
export async function readPolicy(definitions, id) {
|
|
32
|
+
const policies = definitions();
|
|
33
|
+
if (!Array.isArray(policies) || new Set(policies.map(policy => policy.id)).size !== policies.length) invalid();
|
|
34
|
+
const input = policies.find(policy => policy.id === id);
|
|
35
|
+
if (!input) throw new AuthError('policy_not_found', 404);
|
|
36
|
+
return policyVersion(input);
|
|
37
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Identity, not a property of a request or session, selects this fence.
|
|
2
|
+
const actors = new WeakMap();
|
|
3
|
+
export function bindPolicyActor(actor, fence) { actors.set(actor, fence); }
|
|
4
|
+
export function policyActorFence(actor) { return actors.get(actor)?.(); }
|
|
5
|
+
export function approvalFence(approval) {
|
|
6
|
+
return { sql: `EXISTS(SELECT 1 FROM oa_policy_approvals pa JOIN oa_operators po ON po.id=pa.owner_id
|
|
7
|
+
WHERE pa.id=? AND pa.policy_id=? AND pa.version_hash=? AND pa.actions=? AND pa.revoked_at IS NULL AND pa.session_kind IN ('native','oidc','password')
|
|
8
|
+
AND po.status='active' AND po.role='owner' AND po.version=pa.owner_version)`,
|
|
9
|
+
args: [approval.id, approval.policyId, approval.versionHash, approval.actions] };
|
|
10
|
+
}
|
|
11
|
+
export function actionFence(approval, runId, action, target, now, maxActions) {
|
|
12
|
+
const approvalGuard = approvalFence(approval);
|
|
13
|
+
const scopes = JSON.parse(approval.actions).filter(grant => grant.action === action).map(({ scope }) => {
|
|
14
|
+
const args = [...scope.roles];
|
|
15
|
+
let sql = `role IN (${scope.roles.map(() => '?').join(',')})`;
|
|
16
|
+
if (scope.operatorIds) { sql += ` AND id IN (${scope.operatorIds.map(() => '?').join(',')})`; args.push(...scope.operatorIds); }
|
|
17
|
+
if (scope.inactiveDays !== undefined) {
|
|
18
|
+
sql += ' AND created_at<=? AND COALESCE(last_signin_at,created_at)<=?';
|
|
19
|
+
const cutoff = now - scope.inactiveDays * 86400000; args.push(cutoff, cutoff);
|
|
20
|
+
}
|
|
21
|
+
return { sql: '(' + sql + ')', args };
|
|
22
|
+
});
|
|
23
|
+
return { sql: `${approvalGuard.sql} AND EXISTS(SELECT 1 FROM oa_policy_runs WHERE id=? AND approval_id=? AND status='running' AND admitted=1)
|
|
24
|
+
AND (SELECT COUNT(*) FROM oa_auth_audit WHERE CASE WHEN json_valid(value) THEN json_extract(value,'$.runId') END=? AND action IN ('operators:deactivate','operators:reactivate'))<?
|
|
25
|
+
AND role!='owner' AND status!='invited' AND id=? AND (${scopes.map(scope => scope.sql).join(' OR ') || '0'})`,
|
|
26
|
+
args: [...approvalGuard.args, runId, approval.id, runId, maxActions, target.id, ...scopes.flatMap(scope => scope.args)] };
|
|
27
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { deny } from '../errors.mjs';
|
|
2
|
+
export const runColumns = 'id,policy_id AS policyId,version_hash AS versionHash,approval_id AS approvalId,approved_by AS approvedBy,started_at AS startedAt,finished_at AS finishedAt,status,error,repeats,COALESCE(last_seen_at,started_at) AS lastSeenAt';
|
|
3
|
+
export async function runHistory(store, request, fence) {
|
|
4
|
+
const cursor = new URL(request.url).searchParams.get('before');
|
|
5
|
+
if (cursor !== null && !/^[1-9][0-9]{0,15}$/.test(cursor)) deny('invalid_cursor', 400);
|
|
6
|
+
const rows = (await store.statement(`SELECT rowid AS cursor,${runColumns} FROM oa_policy_runs WHERE ${fence.sql}
|
|
7
|
+
${cursor ? 'AND rowid<?' : ''} ORDER BY rowid DESC LIMIT 26`, [...fence.args, ...(cursor ? [Number(cursor)] : [])]).all()).results;
|
|
8
|
+
const more = rows.length > 25;
|
|
9
|
+
const runs = await Promise.all(rows.slice(0, 25).map(async ({ cursor: _, ...run }) => {
|
|
10
|
+
const actions = (await store.statement(`SELECT id,actor_id AS actor,action,value,created_at AS createdAt FROM oa_auth_audit
|
|
11
|
+
WHERE CASE WHEN json_valid(value) THEN json_extract(value,'$.runId') END=? AND ${fence.sql} ORDER BY rowid`, [run.id, ...fence.args]).all()).results
|
|
12
|
+
.map(action => ({ ...action, value: JSON.parse(action.value) }));
|
|
13
|
+
return { ...run, actions };
|
|
14
|
+
}));
|
|
15
|
+
return { runs, nextCursor: more ? String(rows[24].cursor) : null };
|
|
16
|
+
}
|
|
17
|
+
// Only identical, unadmitted ticks coalesce. Admitted runs retain their own actions.
|
|
18
|
+
export async function finishRun(store, id, error, now) {
|
|
19
|
+
const status = error?.status ?? 'completed', code = error?.code ?? null;
|
|
20
|
+
await store.batch([
|
|
21
|
+
["UPDATE oa_policy_runs SET status=?,error=?,finished_at=?,last_seen_at=? WHERE id=?", [status, code, now, now, id]],
|
|
22
|
+
[`UPDATE oa_policy_runs SET repeats=repeats+1,last_seen_at=? WHERE rowid=(
|
|
23
|
+
SELECT prior.rowid FROM oa_policy_runs prior JOIN oa_policy_runs tick ON tick.id=?
|
|
24
|
+
WHERE tick.admitted=0 AND tick.status='refused' AND prior.rowid=(SELECT MAX(rowid) FROM oa_policy_runs WHERE rowid<tick.rowid AND policy_id=tick.policy_id)
|
|
25
|
+
AND prior.admitted=0 AND prior.policy_id=tick.policy_id AND prior.version_hash IS tick.version_hash
|
|
26
|
+
AND prior.approval_id IS tick.approval_id AND prior.status=tick.status AND prior.error IS tick.error)
|
|
27
|
+
`, [now, id]],
|
|
28
|
+
['DELETE FROM oa_policy_runs WHERE id=? AND changes()>0', [id]],
|
|
29
|
+
]);
|
|
30
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Operator } from '../index.mjs';
|
|
2
|
+
export interface ScheduledPolicy {
|
|
3
|
+
id: string;
|
|
4
|
+
/** Bump when the job's semantics change. All bounds also belong in actions. */
|
|
5
|
+
kind: string;
|
|
6
|
+
parameters: Record<string, unknown>;
|
|
7
|
+
maxActionsPerRun: number;
|
|
8
|
+
minIntervalMinutes: number;
|
|
9
|
+
actions: Array<{ action: 'operators:deactivate' | 'operators:reactivate'; scope: { roles: Array<'admin' | 'member'>; operatorIds?: string[]; inactiveDays?: number } }>;
|
|
10
|
+
}
|
|
11
|
+
export interface PolicyApproval { id: string; policyId: string; versionHash: string; ownerId: string; ownerVersion: number; approvedAt: number; revokedAt: number | null; sessionKind: string; revokeReason: string | null }
|
|
12
|
+
export interface PolicyAction { id: string; actor: string; action: string; createdAt: number; value: { policyId: string; versionHash: string; approvalId: string; approvedBy: string; runId: string; operatorId: string; attemptedAction?: string; error?: string } }
|
|
13
|
+
export interface PolicyRun { id: string; policyId: string; versionHash: string | null; approvalId: string | null; approvedBy: string | null; startedAt: number; finishedAt: number | null; status: 'running' | 'completed' | 'refused' | 'failed'; error: string | null; repeats: number; lastSeenAt: number; actions: PolicyAction[] }
|
|
14
|
+
export interface ScheduledPolicyDoor {
|
|
15
|
+
list(request: Request): Promise<{ policies: Array<{ definition: ScheduledPolicy; versionHash: string; approval: PolicyApproval | null; state: string }>; approvals: PolicyApproval[] }>;
|
|
16
|
+
runs(request: Request): Promise<{ runs: PolicyRun[]; nextCursor: string | null }>;
|
|
17
|
+
approve(request: Request, input: { policyId: string; versionHash: string }): Promise<PolicyApproval>;
|
|
18
|
+
revoke(request: Request, input: { approvalId: string }): Promise<void>;
|
|
19
|
+
/** Trusted server-only scheduled handler. There is deliberately no HTTP adapter. */
|
|
20
|
+
run(policyId: string, execute: (run: { id: string; actor: string; execute(action: ScheduledPolicy['actions'][number]['action'], operatorId: string): Promise<Operator | null> }) => Promise<void>): Promise<{ id: string }>;
|
|
21
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { AuthError, deny } from '../errors.mjs';
|
|
2
|
+
import { requirePost } from '../http.mjs';
|
|
3
|
+
import { emailAllowed } from '../accounts/roles.mjs';
|
|
4
|
+
import { readPolicy, policyVersion } from './definition.mjs';
|
|
5
|
+
import { approvalFence } from './fence.mjs';
|
|
6
|
+
import { policyRunner } from './runner.mjs';
|
|
7
|
+
import { runHistory } from './history.mjs';
|
|
8
|
+
const approvalColumns = 'id,policy_id AS policyId,version_hash AS versionHash,owner_id AS ownerId,owner_version AS ownerVersion,approved_at AS approvedAt,revoked_at AS revokedAt,session_kind AS sessionKind,revoke_reason AS revokeReason';
|
|
9
|
+
export function scheduledPolicies({ definitions, store, config, clock, authenticate, requireFreshProof, rolePolicy }) {
|
|
10
|
+
if (typeof definitions !== 'function') throw new AuthError('invalid_policy', 503);
|
|
11
|
+
async function owner(request, mutation = false) {
|
|
12
|
+
if (mutation) requirePost(request, config);
|
|
13
|
+
const actor = await authenticate(request);
|
|
14
|
+
if (!actor) deny('unauthenticated', 401);
|
|
15
|
+
if (actor.operator.role !== 'owner') deny();
|
|
16
|
+
return actor;
|
|
17
|
+
}
|
|
18
|
+
function ownerFence(actor, now) {
|
|
19
|
+
const session = store.actorFence(actor, now);
|
|
20
|
+
return { sql: `${session.sql} AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND role='owner')`, args: [...session.args, actor.operator.id] };
|
|
21
|
+
}
|
|
22
|
+
async function currentApproval(id) {
|
|
23
|
+
return store.first(`SELECT ${approvalColumns},actions FROM oa_policy_approvals WHERE policy_id=? ORDER BY approved_at DESC,rowid DESC LIMIT 1`, [id]);
|
|
24
|
+
}
|
|
25
|
+
async function check(policy, approval) {
|
|
26
|
+
if (!approval) deny('policy_approval_required', 403);
|
|
27
|
+
const live = await store.first('SELECT revoked_at AS revokedAt FROM oa_policy_approvals WHERE id=?', [approval.id]);
|
|
28
|
+
if (!live) deny('policy_approval_required', 403);
|
|
29
|
+
if (live.revokedAt !== null) deny('policy_revoked', 403);
|
|
30
|
+
if (!['native', 'oidc', 'password'].includes(approval.sessionKind)) deny('policy_session_denied', 403);
|
|
31
|
+
if (approval.versionHash !== policy.versionHash || approval.actions !== policy.actionsJson) deny('policy_changed', 409);
|
|
32
|
+
const fence = approvalFence(approval);
|
|
33
|
+
if (!await store.first(`SELECT 1 AS valid WHERE ${fence.sql}`, fence.args)) deny('policy_owner_changed', 403);
|
|
34
|
+
const approvingOwner = await store.operator(approval.ownerId);
|
|
35
|
+
if (!emailAllowed(approvingOwner?.email, config.allowList)) deny('policy_owner_changed', 403);
|
|
36
|
+
return approvingOwner;
|
|
37
|
+
}
|
|
38
|
+
return Object.freeze({
|
|
39
|
+
async list(request) {
|
|
40
|
+
const actor = await owner(request);
|
|
41
|
+
const fence = ownerFence(actor, clock());
|
|
42
|
+
const records = (await store.statement(`SELECT ${approvalColumns},actions FROM oa_policy_approvals WHERE ${fence.sql} ORDER BY approved_at DESC,rowid DESC`, fence.args).all()).results;
|
|
43
|
+
const approvals = records.map(({ actions, ...approval }) => approval);
|
|
44
|
+
const policies = await Promise.all(definitions().map(async input => {
|
|
45
|
+
const policy = await policyVersion(input), approval = approvals.find(row => row.policyId === input.id) ?? null;
|
|
46
|
+
let state = 'approval required';
|
|
47
|
+
try { await check(policy, records.find(row => row.policyId === input.id)); state = 'approved'; } catch (error) { if (!(error instanceof AuthError)) throw error; state = error.code; }
|
|
48
|
+
return { definition: policy.definition, versionHash: policy.versionHash, approval, state };
|
|
49
|
+
}));
|
|
50
|
+
return { policies, approvals };
|
|
51
|
+
},
|
|
52
|
+
async runs(request) {
|
|
53
|
+
const actor = await owner(request), fence = ownerFence(actor, clock());
|
|
54
|
+
return runHistory(store, request, fence);
|
|
55
|
+
},
|
|
56
|
+
async approve(request, { policyId, versionHash }) {
|
|
57
|
+
const actor = await owner(request, true), policy = await readPolicy(definitions, policyId);
|
|
58
|
+
if (!['native', 'oidc', 'password'].includes(actor.kind)) deny('policy_session_denied', 403);
|
|
59
|
+
await requireFreshProof(actor);
|
|
60
|
+
for (const grant of policy.definition.actions) if (!await rolePolicy({ actor: actor.operator, action: grant.action })) deny('policy_action_denied', 403);
|
|
61
|
+
if (versionHash !== policy.versionHash) deny('policy_changed', 409);
|
|
62
|
+
const id = crypto.randomUUID(), now = clock(), fence = ownerFence(actor, now);
|
|
63
|
+
await store.batch([
|
|
64
|
+
[`UPDATE oa_policy_approvals SET revoked_at=?,revoke_reason='superseded_by_approval' WHERE policy_id=? AND revoked_at IS NULL AND ${fence.sql}`, [now, policyId, ...fence.args]],
|
|
65
|
+
[`INSERT INTO oa_policy_approvals(id,policy_id,version_hash,definition,actions,owner_id,owner_version,approved_at,session_kind)
|
|
66
|
+
SELECT ?,?,?,?,?,?,?,?,? WHERE ${fence.sql}`, [id, policyId, policy.versionHash, policy.json, policy.actionsJson, actor.operator.id, actor.operator.version, now, actor.kind, ...fence.args]],
|
|
67
|
+
[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,?,'policy:approve',?,? WHERE EXISTS(SELECT 1 FROM oa_policy_approvals WHERE id=?)`, [crypto.randomUUID(), actor.operator.id, JSON.stringify({ approvalId: id, policyId, versionHash }), now, id]],
|
|
68
|
+
]);
|
|
69
|
+
const approval = await store.first(`SELECT ${approvalColumns} FROM oa_policy_approvals WHERE id=?`, [id]);
|
|
70
|
+
if (!approval) deny('authority_changed', 409);
|
|
71
|
+
return approval;
|
|
72
|
+
},
|
|
73
|
+
async revoke(request, { approvalId }) {
|
|
74
|
+
const actor = await owner(request, true), now = clock(), fence = ownerFence(actor, now);
|
|
75
|
+
const [result] = await store.batch([
|
|
76
|
+
[`UPDATE oa_policy_approvals SET revoked_at=COALESCE(revoked_at,?),revoke_reason=COALESCE(revoke_reason,'owner_revoked') WHERE id=? AND ${fence.sql} RETURNING id`, [now, approvalId, ...fence.args]],
|
|
77
|
+
[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,?,'policy:revoke',?,? WHERE changes()>0`, [crypto.randomUUID(), actor.operator.id, JSON.stringify({ approvalId }), now]],
|
|
78
|
+
]);
|
|
79
|
+
if (!result.results.length) deny('authority_changed', 409);
|
|
80
|
+
},
|
|
81
|
+
run: policyRunner({ definitions, store, clock, currentApproval, check, rolePolicy }),
|
|
82
|
+
});
|
|
83
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { AuthError, deny } from '../errors.mjs';
|
|
2
|
+
import { writeOperatorStatus } from '../accounts/status.mjs';
|
|
3
|
+
import { readPolicy } from './definition.mjs';
|
|
4
|
+
import { actionFence, bindPolicyActor } from './fence.mjs';
|
|
5
|
+
import { finishRun } from './history.mjs';
|
|
6
|
+
|
|
7
|
+
export function policyRunner({ definitions, store, clock, currentApproval, check, rolePolicy }) {
|
|
8
|
+
return async function run(policyId, execute) {
|
|
9
|
+
const id = crypto.randomUUID(), startedAt = clock();
|
|
10
|
+
await store.run("INSERT INTO oa_policy_runs(id,policy_id,started_at,status) VALUES(?,?,?,'running')", [id, policyId, startedAt]);
|
|
11
|
+
let open = true, approval, policy;
|
|
12
|
+
async function verify(current) {
|
|
13
|
+
try { return await check(current, approval); } catch (error) {
|
|
14
|
+
if (error instanceof AuthError && error.code === 'policy_changed' && approval) {
|
|
15
|
+
await store.batch([
|
|
16
|
+
["UPDATE oa_policy_approvals SET revoked_at=?,revoke_reason='superseded_by_change' WHERE id=? AND revoked_at IS NULL", [clock(), approval.id]],
|
|
17
|
+
["UPDATE oa_policy_runs SET status='refused',error='policy_changed',finished_at=? WHERE id=?", [clock(), id]],
|
|
18
|
+
]);
|
|
19
|
+
}
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
policy = await readPolicy(definitions, policyId); approval = await currentApproval(policyId);
|
|
25
|
+
await store.run('UPDATE oa_policy_runs SET version_hash=?,approval_id=?,approved_by=? WHERE id=?', [policy.versionHash, approval?.id ?? null, approval?.ownerId ?? null, id]);
|
|
26
|
+
await verify(policy);
|
|
27
|
+
const admission = await store.first(`UPDATE oa_policy_runs SET admitted=1 WHERE id=? AND NOT EXISTS(
|
|
28
|
+
SELECT 1 FROM oa_policy_runs WHERE policy_id=? AND id!=? AND admitted=1
|
|
29
|
+
AND (status='running' OR COALESCE(finished_at,started_at)>?)) RETURNING id`,
|
|
30
|
+
[id, policyId, id, startedAt - policy.definition.minIntervalMinutes * 60000]);
|
|
31
|
+
if (!admission) deny('policy_interval', 429);
|
|
32
|
+
let pending = null, actionError = null, committed = 0;
|
|
33
|
+
const capability = Object.freeze({ id, actor: `policy:${policyId}@${policy.versionHash}`, async execute(action, operatorId) {
|
|
34
|
+
if (!open || pending) deny('policy_run_closed', 409);
|
|
35
|
+
const operation = (async () => {
|
|
36
|
+
const current = await readPolicy(definitions, policyId), owner = await verify(current);
|
|
37
|
+
if (!current.definition.actions.some(grant => grant.action === action)) deny('policy_action_denied', 403);
|
|
38
|
+
if (committed >= current.definition.maxActionsPerRun) deny('policy_action_limit', 429);
|
|
39
|
+
const target = await store.operator(operatorId);
|
|
40
|
+
if (!target) deny('operator_not_found', 404);
|
|
41
|
+
if (!await rolePolicy({ actor: owner, action, target })) deny('policy_action_denied', 403);
|
|
42
|
+
const actor = Object.freeze({});
|
|
43
|
+
bindPolicyActor(actor, () => actionFence(approval, id, action, target, clock(), current.definition.maxActionsPerRun));
|
|
44
|
+
const result = await writeOperatorStatus(store, actor, target, action === 'operators:deactivate' ? 'inactive' : 'active', clock(), {
|
|
45
|
+
actor: capability.actor, action, value: { policyId, versionHash: policy.versionHash, approvalId: approval.id, approvedBy: approval.ownerId, runId: id, operatorId },
|
|
46
|
+
});
|
|
47
|
+
committed++; return result;
|
|
48
|
+
})();
|
|
49
|
+
pending = operation;
|
|
50
|
+
try { return await operation; } catch (error) {
|
|
51
|
+
actionError = error;
|
|
52
|
+
await store.run('INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) VALUES(?,?,?,?,?)', [crypto.randomUUID(), capability.actor, 'policy:refused', JSON.stringify({ policyId, versionHash: policy.versionHash, approvalId: approval.id, approvedBy: approval.ownerId, runId: id, operatorId, attemptedAction: action, error: error instanceof AuthError ? error.code : 'policy_failed' }), clock()]);
|
|
53
|
+
throw error;
|
|
54
|
+
} finally { pending = null; }
|
|
55
|
+
} });
|
|
56
|
+
try { await execute(capability); } finally { open = false; if (pending) await pending; }
|
|
57
|
+
if (actionError) throw actionError;
|
|
58
|
+
await finishRun(store, id, null, clock());
|
|
59
|
+
return { id };
|
|
60
|
+
} catch (error) {
|
|
61
|
+
await finishRun(store, id, { status: error instanceof AuthError ? 'refused' : 'failed', code: error instanceof AuthError ? error.code : 'policy_failed' }, clock());
|
|
62
|
+
throw error;
|
|
63
|
+
} finally { open = false; }
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Composed identity over Base's OA accounts, or an explicitly paired native
|
|
2
2
|
// accounts/proof adapter. Native composition never constructs the OA store.
|
|
3
|
+
import { scheduledPolicies } from './scheduled/index.mjs';
|
|
3
4
|
import { fencedCredentials } from './accounts/credentials.mjs';
|
|
4
5
|
import { providerControl } from './accounts/provider-control.mjs';
|
|
5
6
|
import { linkedProviders } from '../dependencies/auth.mjs';
|
|
@@ -76,6 +77,7 @@ export function createOperatorAuth(options) {
|
|
|
76
77
|
const external = legacyAdmission({ admission, config });
|
|
77
78
|
return Object.freeze({
|
|
78
79
|
...admin,
|
|
80
|
+
...(options.scheduledPolicies ? { scheduledPolicies: scheduledPolicies({ definitions: options.scheduledPolicies, store, config, clock, authenticate, requireFreshProof, rolePolicy }) } : {}),
|
|
79
81
|
...providerControl({ store, accounts, authenticate, config, clock }),
|
|
80
82
|
...fencedCredentials({store,authenticate,requireFreshProof,config,clock,hash}),
|
|
81
83
|
...ownerSignIn({ config, store, clock, sessions, limit }),
|
|
@@ -132,6 +132,12 @@ that generation and the content hash, while retained domain and identity rows
|
|
|
132
132
|
remain equal. Re-linking keeps the installation sector and person bindings;
|
|
133
133
|
restored provider sign-in remains off until the owner explicitly enables it.
|
|
134
134
|
|
|
135
|
+
Included standing policy approvals retain their provenance and run references,
|
|
136
|
+
but export revokes them in the snapshot. The source approval stays unchanged.
|
|
137
|
+
Restore refuses an archive containing a live approval, even with valid archive
|
|
138
|
+
checksums. The destination owner must approve its policies again. Included
|
|
139
|
+
operators retain their durable `last_signin_at` when sessions are scrubbed.
|
|
140
|
+
|
|
135
141
|
SQLite VIRTUAL and STORED generated columns retain their visible schema metadata
|
|
136
142
|
and original table SQL. Only writable base cells appear in archived rows or
|
|
137
143
|
restore inserts; the destination's migrated schema computes generated values and
|
|
@@ -286,7 +292,15 @@ contain only `CREATE TABLE` (not `AS SELECT`), `CREATE INDEX` and
|
|
|
286
292
|
restorable tables. A later migration with any other statement that names a
|
|
287
293
|
restorable table, such as an `INSERT`, `UPDATE` or `DELETE` that purges or
|
|
288
294
|
backfills rows or a trigger, is refused with `schema_mismatch`; statements that
|
|
289
|
-
touch only excluded tables are allowed.
|
|
295
|
+
touch only excluded tables are allowed. A data statement (`INSERT`, `REPLACE`,
|
|
296
|
+
`UPDATE` or `DELETE`, including `INSERT ... SELECT` and a leading `WITH`) is
|
|
297
|
+
judged by the table it writes: when that table is outside the restorable
|
|
298
|
+
catalogue (excluded, derived or platform) and no trigger or foreign key action
|
|
299
|
+
(`ON DELETE`/`ON UPDATE CASCADE` or `SET`) carries its writes into a catalogue
|
|
300
|
+
table, it changes no restored row and is allowed whatever it reads. Such a table
|
|
301
|
+
then holds live rows the restore lacks, so a later statement that copies it into
|
|
302
|
+
a catalogue table is refused. A statement this parser cannot bound to one table
|
|
303
|
+
keeps the rule above. An archived table the archive holds no
|
|
290
304
|
rows of restores empty, so an `UPDATE` or `DELETE` of it changes nothing and is
|
|
291
305
|
allowed unless it also names a table the archive holds rows of (which it could
|
|
292
306
|
read into its writes); an `INSERT` into it, or any other statement naming it,
|
|
@@ -294,6 +308,28 @@ is still refused. For archives without a migration record,
|
|
|
294
308
|
every migration after the earliest prefix that gives the archive's schema is
|
|
295
309
|
checked, since the archive may predate any of them.
|
|
296
310
|
|
|
311
|
+
A backfill of a catalogue table the archive does not carry (one a later
|
|
312
|
+
migration adds, restored empty) is **replayed** instead of refused: an
|
|
313
|
+
`INSERT ... SELECT` (or `INSERT ... VALUES`) into that table. Finalize empties
|
|
314
|
+
the table (resetting its `AUTOINCREMENT` counter, as the live upgrade created
|
|
315
|
+
it) and runs each of its later writes in migration order, exactly as written,
|
|
316
|
+
after every archived row is inserted and while the destination's triggers are
|
|
317
|
+
still dropped, in the same atomic D1 transaction as the rest of the restore. The
|
|
318
|
+
table then holds what the live upgrade gave it. Time functions such as
|
|
319
|
+
`strftime(..., 'now')` take the restore's time, as they took the upgrade's; an
|
|
320
|
+
`INSERT ... SELECT` without `ORDER BY` assigns new keys in the order SQLite
|
|
321
|
+
scans the restored rows. Rows the restore normalizes (import safety) are read
|
|
322
|
+
as restored. The restore is refused with
|
|
323
|
+
`schema_mismatch:migration_data:<migration>` instead when the archive carries
|
|
324
|
+
the table (even with no rows), when a write to it is not a plain `INSERT` or
|
|
325
|
+
`REPLACE`, reads any table other than archived ones and itself, selects `*` or
|
|
326
|
+
a secret column, when a trigger on it or a foreign key action from it reaches a
|
|
327
|
+
catalogue table, when any other later statement writes it (directly or through
|
|
328
|
+
a trigger) or changes its columns other than by `ADD COLUMN` (allowed only when
|
|
329
|
+
every replay names its columns), or when the statement cannot be bounded.
|
|
330
|
+
A failed or interrupted apply leaves no replayed row; finalizing again replays
|
|
331
|
+
from the start.
|
|
332
|
+
|
|
297
333
|
The same check runs when the archive's schema identity equals the destination's:
|
|
298
334
|
a later migration that only purges or backfills rows leaves the schema unchanged,
|
|
299
335
|
yet the archive's rows never passed through it. Such an archive is refused with
|
|
@@ -313,9 +349,13 @@ before any staging or audit write. Without a replayer (the HTTP handler, direct
|
|
|
313
349
|
bindings), only identical schemas and `acceptedSchemas` restore.
|
|
314
350
|
|
|
315
351
|
The import status and CLI receipt carry `bridged`: `migrations` (the later
|
|
316
|
-
migrations bridged), `tables` (later tables left empty),
|
|
317
|
-
per table that took defaults), `fromSchema` and
|
|
318
|
-
and
|
|
352
|
+
migrations bridged), `tables` (later tables, left empty unless replayed),
|
|
353
|
+
`columns` (later columns per table that took defaults), `fromSchema` and
|
|
354
|
+
`toSchema`, and with any replay `replayed`: one `{migration, statement, table,
|
|
355
|
+
rows}` per replayed statement in the order run (`statement` is its index, from
|
|
356
|
+
0, in the migration's split statements, `rows` the rows it wrote, recorded in the same
|
|
357
|
+
transaction). The import job keeps it as the restore's journal of replays and
|
|
358
|
+
v1 recovery adds it to its audit record. `archiveHash`, `contentHash`,
|
|
319
359
|
the erasure fence and v1's own checks are unchanged.
|
|
320
360
|
|
|
321
361
|
## Backup-only v1 recovery
|
|
@@ -581,11 +621,13 @@ modules/portability/storage.mjs
|
|
|
581
621
|
modules/portability/copies.mjs
|
|
582
622
|
modules/portability/dev-data.mjs
|
|
583
623
|
modules/portability/provider-data.mjs
|
|
624
|
+
modules/portability/policy-data.mjs
|
|
584
625
|
modules/portability/generated.mjs
|
|
585
626
|
modules/portability/restore-safety.mjs
|
|
586
627
|
modules/portability/bridge.mjs
|
|
587
628
|
modules/portability/ledgers.mjs
|
|
588
629
|
modules/portability/migration-statements.mjs
|
|
630
|
+
modules/portability/backfills.mjs
|
|
589
631
|
modules/portability/legacy-safety.mjs
|
|
590
632
|
modules/portability/export.mjs
|
|
591
633
|
modules/portability/import.mjs
|