@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
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
-- Apply as a NEW numbered migration. Authority and audit are durable, not sessions.
|
|
2
|
+
CREATE TABLE IF NOT EXISTS oa_policy_approvals (
|
|
3
|
+
id TEXT PRIMARY KEY, policy_id TEXT NOT NULL, version_hash TEXT NOT NULL,
|
|
4
|
+
definition TEXT NOT NULL, actions TEXT NOT NULL,
|
|
5
|
+
owner_id TEXT NOT NULL REFERENCES oa_operators(id), owner_version INTEGER NOT NULL,
|
|
6
|
+
approved_at INTEGER NOT NULL, revoked_at INTEGER,
|
|
7
|
+
session_kind TEXT NOT NULL, revoke_reason TEXT
|
|
8
|
+
);
|
|
9
|
+
CREATE UNIQUE INDEX IF NOT EXISTS oa_policy_live ON oa_policy_approvals(policy_id) WHERE revoked_at IS NULL;
|
|
10
|
+
CREATE TABLE IF NOT EXISTS oa_policy_runs (
|
|
11
|
+
id TEXT PRIMARY KEY, policy_id TEXT NOT NULL, version_hash TEXT,
|
|
12
|
+
approval_id TEXT REFERENCES oa_policy_approvals(id), approved_by TEXT,
|
|
13
|
+
started_at INTEGER NOT NULL, finished_at INTEGER,
|
|
14
|
+
status TEXT NOT NULL CHECK(status IN ('running','completed','refused','failed')), error TEXT,
|
|
15
|
+
admitted INTEGER NOT NULL DEFAULT 0, repeats INTEGER NOT NULL DEFAULT 1, last_seen_at INTEGER
|
|
16
|
+
);
|
|
17
|
+
CREATE INDEX IF NOT EXISTS oa_policy_runs_time ON oa_policy_runs(started_at DESC);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS oa_policy_action_run ON oa_auth_audit(CASE WHEN json_valid(value) THEN json_extract(value,'$.runId') END,action);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { deny } from '../errors.mjs';
|
|
2
|
+
// One persistence door for session and policy actors. The caller authorizes the
|
|
3
|
+
// action; the actor fence repeats live authority in this atomic write/audit.
|
|
4
|
+
export async function writeOperatorStatus(store, actor, target, status, now, audit) {
|
|
5
|
+
const fence = store.actorFence(actor, now);
|
|
6
|
+
try {
|
|
7
|
+
const statements = [[`UPDATE oa_operators SET status=? WHERE id=? AND version=? AND ${fence.sql} RETURNING id`, [status, target.id, target.version, ...fence.args]]];
|
|
8
|
+
if (audit) statements.push([`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at)
|
|
9
|
+
SELECT ?,?,?,?,? WHERE changes()>0`, [crypto.randomUUID(), audit.actor, audit.action, JSON.stringify(audit.value), now]]);
|
|
10
|
+
const [result] = await store.batch(statements);
|
|
11
|
+
if (!result.results.some(row => row.id === target.id)) deny('authority_changed', 409);
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (String(error).includes('last_owner')) deny('last_owner', 409);
|
|
14
|
+
if (String(error).includes('invitation_required')) deny('invitation_required', 409);
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
return store.operator(target.id);
|
|
18
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { policyActorFence } from '../scheduled/fence.mjs';
|
|
1
2
|
import { providerPinFence, recordProviderPin } from './provider-pin.mjs';
|
|
2
3
|
// D1 batches are transactions. All decisions that grant a session or mutate
|
|
3
4
|
// operator authority are repeated inside the same database transaction.
|
|
@@ -42,6 +43,8 @@ export class AuthStore {
|
|
|
42
43
|
// Snapshot authorization fence: both actor session and operator authority must
|
|
43
44
|
// still be valid when the SQL mutation executes, not merely when JS checked it.
|
|
44
45
|
actorFence(actor, now) {
|
|
46
|
+
const policy = policyActorFence(actor);
|
|
47
|
+
if (policy) return policy;
|
|
45
48
|
const pin = providerPinFence(actor.providerPin);
|
|
46
49
|
return { sql: `${pin.sql} AND EXISTS(SELECT 1 FROM oa_sessions a JOIN oa_operators ao ON ao.id=a.operator_id
|
|
47
50
|
WHERE a.token_hash=? AND a.revoked_at IS NULL AND a.expires_at>? AND ao.status='active'
|
|
@@ -32,7 +32,7 @@ function validProductName(name) {
|
|
|
32
32
|
export function configureBranding(input = {}) {
|
|
33
33
|
const invalid = () => { throw new AuthError('invalid_configuration', 503); };
|
|
34
34
|
if (!input || typeof input !== 'object' || Array.isArray(input)) invalid();
|
|
35
|
-
const { productName = 'your workspace', accentColor = '#334155', signInPath = '/signin', theme } = input;
|
|
35
|
+
const { productName = 'your workspace', accentColor = '#334155', signInPath = '/signin', theme, mark } = input;
|
|
36
36
|
if (!validProductName(productName)) invalid();
|
|
37
37
|
if (typeof accentColor !== 'string' || !/^#[0-9a-f]{6}$/i.test(accentColor)) invalid();
|
|
38
38
|
if (typeof signInPath !== 'string' || !signInPath.startsWith('/') || signInPath.startsWith('//') || /[\\\u0000-\u0020\u007f-\u009f]/u.test(signInPath)) invalid();
|
|
@@ -54,7 +54,10 @@ export function configureBranding(input = {}) {
|
|
|
54
54
|
}
|
|
55
55
|
// A seed theme is its own served rer-theme.css; Base onboarding validates its contents.
|
|
56
56
|
if (theme !== undefined && (typeof theme !== 'string' || !/^\/(?!\/)[A-Za-z0-9._~/-]{1,200}\.css$/.test(theme) || theme.includes('//') || theme.includes('/.'))) invalid();
|
|
57
|
-
|
|
57
|
+
// A served image pathname, never a remote URL or an encoded URL reference.
|
|
58
|
+
if (mark !== undefined && (typeof mark !== 'string' || mark.length < 2 || mark.length > 2048 || !mark.startsWith('/')
|
|
59
|
+
|| /[^A-Za-z0-9._~/-]/.test(mark) || mark.includes('//') || /\/\.{1,2}(?:\/|$)/.test(mark))) invalid();
|
|
60
|
+
return Object.freeze({ productName: productName.trim(), accentColor, signInPath, ...(theme ? { theme } : {}), ...(mark !== undefined ? { mark } : {}) });
|
|
58
61
|
}
|
|
59
62
|
|
|
60
63
|
/** WCAG relative luminance chooses readable text for any permitted brand color. */
|
|
@@ -24,11 +24,15 @@ hash plus only same-origin style/font permissions, and still rejects external
|
|
|
24
24
|
origins, scripts, images and unsafe inline attributes. Mail stays self-contained.
|
|
25
25
|
|
|
26
26
|
A consumer that configures `branding.productName` or a seed theme
|
|
27
|
-
(`branding.theme`, its served `rer-theme.css`)
|
|
28
|
-
`
|
|
27
|
+
(`branding.theme`, its served `rer-theme.css`) or an installation mark
|
|
28
|
+
(`branding.mark`, for example `/brand/mark.svg`) declares the same values as
|
|
29
|
+
`adapter.branding: { productName, theme, mark }`. Mail and confirmation must then
|
|
29
30
|
carry that name, and a themed confirmation must hold exactly that one theme
|
|
30
31
|
stylesheet link and the CSP `style-src 'self' 'sha256-…'; font-src 'self';
|
|
31
|
-
img-src 'self'
|
|
32
|
+
img-src 'self'`. A declared mark requires exactly that image, with product-name
|
|
33
|
+
alt text, 32×32 dimensions and asynchronous decoding beside the text name;
|
|
34
|
+
without a theme its CSP adds only `img-src 'self'`. Every other resource rule
|
|
35
|
+
above still applies, and mail stays image-free.
|
|
32
36
|
|
|
33
37
|
The Base conformance registration is executable at
|
|
34
38
|
[`../tests/conformance.test.ts`](../tests/conformance.test.ts), and its D1/Worker
|
|
@@ -29,8 +29,8 @@ export interface OperatorAuthConformanceRuntime {
|
|
|
29
29
|
export interface OperatorAuthConformanceAdapter {
|
|
30
30
|
/** Verify the consumer's same-origin font links and their bounded CSP permissions. */
|
|
31
31
|
confirmationFonts?: boolean;
|
|
32
|
-
/** The consumer's configured
|
|
33
|
-
branding?: { productName?: string; theme?: string };
|
|
32
|
+
/** The consumer's configured product name, served mark and rer-theme.css paths, when declared. */
|
|
33
|
+
branding?: { productName?: string; mark?: string; theme?: string };
|
|
34
34
|
/** Set only when the runtime also implements the provider-key-free admission seam case. */
|
|
35
35
|
oidcIssuer?: string;
|
|
36
36
|
/** Must create disposable real workerd/D1 state and mount the consumer's actual auth and private API routes. */
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { checkConfirmation, checkMail } from './presentation.mjs';
|
|
2
|
+
import { configureBranding } from '../branding.mjs';
|
|
2
3
|
const BASE_CONFIG = Object.freeze({
|
|
3
4
|
origin: 'https://auth.conformance.test',
|
|
4
5
|
OWNER_EMAIL: 'owner@example.test',
|
|
@@ -83,11 +84,12 @@ export function registerOperatorAuthConformance({ test, adapter }) {
|
|
|
83
84
|
throw new TypeError('confirmationFonts must be boolean.');
|
|
84
85
|
}
|
|
85
86
|
const { branding = {} } = adapter;
|
|
86
|
-
if (typeof branding !== 'object' || Object.keys(branding).some(key => !['productName', 'theme'].includes(key))
|
|
87
|
+
if (typeof branding !== 'object' || Object.keys(branding).some(key => !['productName', 'theme', 'mark'].includes(key))
|
|
87
88
|
|| (branding.productName !== undefined && typeof branding.productName !== 'string')
|
|
88
89
|
|| (branding.theme !== undefined && !/^\/(?!\/)[A-Za-z0-9._~/-]+\.css$/.test(branding.theme))) {
|
|
89
|
-
throw new TypeError('branding declares only the consumer\'s productName and same-origin theme stylesheet.');
|
|
90
|
+
throw new TypeError('branding declares only the consumer\'s productName, mark and same-origin theme stylesheet.');
|
|
90
91
|
}
|
|
92
|
+
if (branding.mark !== undefined) configureBranding({ mark: branding.mark });
|
|
91
93
|
|
|
92
94
|
async function scenario(name, options, run) {
|
|
93
95
|
test(name, async () => {
|
|
@@ -156,7 +158,7 @@ export function registerOperatorAuthConformance({ test, adapter }) {
|
|
|
156
158
|
const path = `${link.pathname}${link.search}`;
|
|
157
159
|
const preview = await runtime.call(path);
|
|
158
160
|
const headers = [...preview.headers];
|
|
159
|
-
await checkConfirmation(preview, { kind, productName, token, confirmationFonts: adapter.confirmationFonts === true, theme: branding.theme });
|
|
161
|
+
await checkConfirmation(preview, { kind, productName, token, confirmationFonts: adapter.confirmationFonts === true, theme: branding.theme, mark: branding.mark });
|
|
160
162
|
const head = await runtime.call(path, { method: 'HEAD' });
|
|
161
163
|
assertStatus(head, 200);
|
|
162
164
|
equal(await head.text(), '', 'HEAD has no body');
|
|
@@ -164,7 +166,7 @@ export function registerOperatorAuthConformance({ test, adapter }) {
|
|
|
164
166
|
equal(head.headers.get(name), headers.find(([key]) => key === name)?.[1], 'HEAD presentation headers');
|
|
165
167
|
}
|
|
166
168
|
assertStatus(await runtime.call('/auth/confirm', post({ token })), 303);
|
|
167
|
-
await checkConfirmation(await runtime.call(path), { productName, confirmationFonts: adapter.confirmationFonts === true, theme: branding.theme });
|
|
169
|
+
await checkConfirmation(await runtime.call(path), { productName, confirmationFonts: adapter.confirmationFonts === true, theme: branding.theme, mark: branding.mark });
|
|
168
170
|
}
|
|
169
171
|
});
|
|
170
172
|
|
|
@@ -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,38 @@
|
|
|
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 '[' + Array.from(value, 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
|
+
const json = canonical(input);
|
|
15
|
+
if (json.length > 32768) invalid();
|
|
16
|
+
input = JSON.parse(json);
|
|
17
|
+
keys(input, ['id', 'kind', 'parameters', 'actions', 'maxActionsPerRun', 'minIntervalMinutes']);
|
|
18
|
+
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();
|
|
19
|
+
if (!Number.isSafeInteger(input.maxActionsPerRun) || input.maxActionsPerRun < 1 || input.maxActionsPerRun > 100 || !Number.isSafeInteger(input.minIntervalMinutes) || input.minIntervalMinutes < 1 || input.minIntervalMinutes > 525600) invalid();
|
|
20
|
+
for (const grant of input.actions) {
|
|
21
|
+
keys(grant, ['action', 'scope']);
|
|
22
|
+
if (!actions.includes(grant.action)) invalid();
|
|
23
|
+
keys(grant.scope, ['roles', 'operatorIds', 'inactiveDays']);
|
|
24
|
+
const { roles, operatorIds, inactiveDays } = grant.scope;
|
|
25
|
+
if (!Array.isArray(roles) || !roles.length || roles.some(role => !['member', 'admin'].includes(role)) || new Set(roles).size !== roles.length) invalid();
|
|
26
|
+
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();
|
|
27
|
+
if (inactiveDays !== undefined && (!Number.isSafeInteger(inactiveDays) || inactiveDays < 1 || inactiveDays > 36500)) invalid();
|
|
28
|
+
}
|
|
29
|
+
const versionHash = [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(json)))].map(byte => byte.toString(16).padStart(2, '0')).join('');
|
|
30
|
+
return { definition: input, versionHash, json, actionsJson: canonical(input.actions) };
|
|
31
|
+
}
|
|
32
|
+
export async function readPolicy(definitions, id) {
|
|
33
|
+
const policies = definitions();
|
|
34
|
+
if (!Array.isArray(policies) || new Set(policies.map(policy => policy.id)).size !== policies.length) invalid();
|
|
35
|
+
const input = policies.find(policy => policy.id === id);
|
|
36
|
+
if (!input) throw new AuthError('policy_not_found', 404);
|
|
37
|
+
return policyVersion(input);
|
|
38
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Cloudflare's scheduled-handler wall-clock limit:
|
|
2
|
+
// https://developers.cloudflare.com/workers/platform/limits/#duration
|
|
3
|
+
export const scheduledHandlerLimitMs = 15 * 60000;
|
|
4
|
+
|
|
5
|
+
export async function expireRuns(store, policyId, now) {
|
|
6
|
+
const stale = "policy_id=? AND admitted=1 AND status='running' AND started_at<?";
|
|
7
|
+
const args = [policyId, now - scheduledHandlerLimitMs];
|
|
8
|
+
// One transaction records each abandoned run exactly once before closing it.
|
|
9
|
+
await store.batch([
|
|
10
|
+
[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at)
|
|
11
|
+
SELECT lower(hex(randomblob(16))),'policy:'||policy_id||'@'||version_hash,'policy:expired',
|
|
12
|
+
json_object('policyId',policy_id,'versionHash',version_hash,'approvalId',approval_id,
|
|
13
|
+
'approvedBy',approved_by,'runId',id,'error','policy_expired'),?
|
|
14
|
+
FROM oa_policy_runs WHERE ${stale}`, [now, ...args]],
|
|
15
|
+
[`UPDATE oa_policy_runs SET status='failed',error='policy_expired',finished_at=?,last_seen_at=? WHERE ${stale}`, [now, now, ...args]],
|
|
16
|
+
]);
|
|
17
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { scheduledHandlerLimitMs } from './expiry.mjs';
|
|
2
|
+
// Identity, not a property of a request or session, selects this fence.
|
|
3
|
+
const actors = new WeakMap();
|
|
4
|
+
export function bindPolicyActor(actor, fence) { actors.set(actor, fence); }
|
|
5
|
+
export function policyActorFence(actor) { return actors.get(actor)?.(); }
|
|
6
|
+
export function approvalFence(approval) {
|
|
7
|
+
return { sql: `EXISTS(SELECT 1 FROM oa_policy_approvals pa JOIN oa_operators po ON po.id=pa.owner_id
|
|
8
|
+
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')
|
|
9
|
+
AND po.status='active' AND po.role='owner' AND po.version=pa.owner_version)`,
|
|
10
|
+
args: [approval.id, approval.policyId, approval.versionHash, approval.actions] };
|
|
11
|
+
}
|
|
12
|
+
export function actionFence(approval, runId, action, target, now, maxActions) {
|
|
13
|
+
const approvalGuard = approvalFence(approval);
|
|
14
|
+
const scopes = JSON.parse(approval.actions).filter(grant => grant.action === action).map(({ scope }) => {
|
|
15
|
+
const args = [...scope.roles];
|
|
16
|
+
let sql = `role IN (${scope.roles.map(() => '?').join(',')})`;
|
|
17
|
+
if (scope.operatorIds) { sql += ` AND id IN (${scope.operatorIds.map(() => '?').join(',')})`; args.push(...scope.operatorIds); }
|
|
18
|
+
if (scope.inactiveDays !== undefined) {
|
|
19
|
+
sql += ' AND created_at<=? AND COALESCE(last_signin_at,created_at)<=?';
|
|
20
|
+
const cutoff = now - scope.inactiveDays * 86400000; args.push(cutoff, cutoff);
|
|
21
|
+
}
|
|
22
|
+
return { sql: '(' + sql + ')', args };
|
|
23
|
+
});
|
|
24
|
+
return { sql: `${approvalGuard.sql} AND EXISTS(SELECT 1 FROM oa_policy_runs WHERE id=? AND approval_id=? AND status='running' AND admitted=1 AND started_at>=?)
|
|
25
|
+
AND (SELECT COUNT(*) FROM oa_auth_audit WHERE CASE WHEN json_valid(value) THEN json_extract(value,'$.runId') END=?)<?
|
|
26
|
+
AND role!='owner' AND status!='invited' AND id=? AND (${scopes.map(scope => scope.sql).join(' OR ') || '0'})`,
|
|
27
|
+
args: [...approvalGuard.args, runId, approval.id, now - scheduledHandlerLimitMs, runId, maxActions, target.id, ...scopes.flatMap(scope => scope.args)] };
|
|
28
|
+
}
|
|
@@ -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=? AND status='running'", [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,68 @@
|
|
|
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
|
+
import { expireRuns } from './expiry.mjs';
|
|
7
|
+
const actionStatuses = Object.freeze({ 'operators:deactivate': 'inactive', 'operators:reactivate': 'active' });
|
|
8
|
+
|
|
9
|
+
export function policyRunner({ definitions, store, clock, currentApproval, check, rolePolicy }) {
|
|
10
|
+
return async function run(policyId, execute) {
|
|
11
|
+
const id = crypto.randomUUID(), startedAt = clock();
|
|
12
|
+
await store.run("INSERT INTO oa_policy_runs(id,policy_id,started_at,status) VALUES(?,?,?,'running')", [id, policyId, startedAt]);
|
|
13
|
+
let open = true, approval, policy;
|
|
14
|
+
async function verify(current) {
|
|
15
|
+
try { return await check(current, approval); } catch (error) {
|
|
16
|
+
if (error instanceof AuthError && error.code === 'policy_changed' && approval) {
|
|
17
|
+
await store.batch([
|
|
18
|
+
["UPDATE oa_policy_approvals SET revoked_at=?,revoke_reason='superseded_by_change' WHERE id=? AND revoked_at IS NULL", [clock(), approval.id]],
|
|
19
|
+
["UPDATE oa_policy_runs SET status='refused',error='policy_changed',finished_at=? WHERE id=? AND status='running'", [clock(), id]],
|
|
20
|
+
]);
|
|
21
|
+
}
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
policy = await readPolicy(definitions, policyId); approval = await currentApproval(policyId);
|
|
27
|
+
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]);
|
|
28
|
+
await verify(policy);
|
|
29
|
+
await expireRuns(store, policyId, startedAt);
|
|
30
|
+
const admission = await store.first(`UPDATE oa_policy_runs SET admitted=1 WHERE id=? AND NOT EXISTS(
|
|
31
|
+
SELECT 1 FROM oa_policy_runs WHERE policy_id=? AND id!=? AND admitted=1
|
|
32
|
+
AND (status='running' OR COALESCE(CASE WHEN error='policy_expired' THEN started_at ELSE finished_at END,started_at)>?)) RETURNING id`,
|
|
33
|
+
[id, policyId, id, startedAt - policy.definition.minIntervalMinutes * 60000]);
|
|
34
|
+
if (!admission) deny('policy_interval', 429);
|
|
35
|
+
let pending = null, actionError = null, committed = 0;
|
|
36
|
+
const capability = Object.freeze({ id, actor: `policy:${policyId}@${policy.versionHash}`, async execute(action, operatorId) {
|
|
37
|
+
if (!open || pending) deny('policy_run_closed', 409);
|
|
38
|
+
const operation = (async () => {
|
|
39
|
+
const current = await readPolicy(definitions, policyId), owner = await verify(current);
|
|
40
|
+
if (!Object.hasOwn(actionStatuses, action) || !current.definition.actions.some(grant => grant.action === action)) deny('policy_action_denied', 403);
|
|
41
|
+
if (committed >= current.definition.maxActionsPerRun) deny('policy_action_limit', 429);
|
|
42
|
+
const target = await store.operator(operatorId);
|
|
43
|
+
if (!target) deny('operator_not_found', 404);
|
|
44
|
+
if (!await rolePolicy({ actor: owner, action, target })) deny('policy_action_denied', 403);
|
|
45
|
+
const actor = Object.freeze({});
|
|
46
|
+
bindPolicyActor(actor, () => actionFence(approval, id, action, target, clock(), current.definition.maxActionsPerRun));
|
|
47
|
+
const result = await writeOperatorStatus(store, actor, target, actionStatuses[action], clock(), {
|
|
48
|
+
actor: capability.actor, action, value: { policyId, versionHash: policy.versionHash, approvalId: approval.id, approvedBy: approval.ownerId, runId: id, operatorId },
|
|
49
|
+
});
|
|
50
|
+
committed++; return result;
|
|
51
|
+
})();
|
|
52
|
+
pending = operation;
|
|
53
|
+
try { return await operation; } catch (error) {
|
|
54
|
+
actionError = error;
|
|
55
|
+
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()]);
|
|
56
|
+
throw error;
|
|
57
|
+
} finally { pending = null; }
|
|
58
|
+
} });
|
|
59
|
+
try { await execute(capability); } finally { open = false; if (pending) await pending; }
|
|
60
|
+
if (actionError) throw actionError;
|
|
61
|
+
await finishRun(store, id, null, clock());
|
|
62
|
+
return { id };
|
|
63
|
+
} catch (error) {
|
|
64
|
+
await finishRun(store, id, { status: error instanceof AuthError ? 'refused' : 'failed', code: error instanceof AuthError ? error.code : 'policy_failed' }, clock());
|
|
65
|
+
throw error;
|
|
66
|
+
} finally { open = false; }
|
|
67
|
+
};
|
|
68
|
+
}
|