@runeditrun/rer 0.2.79 → 0.2.81
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/README.md +17 -3
- package/cli/README.md +25 -13
- package/cli/authoring.mjs +14 -0
- package/cli/contract.mjs +25 -5
- package/cli/demo-host.mjs +4 -2
- package/cli/deploy-needs.mjs +4 -2
- package/cli/dev-identity.mjs +2 -2
- package/cli/export.mjs +1 -1
- package/cli/inspect.mjs +38 -2
- package/cli/ledger-refusal.mjs +18 -0
- package/cli/main.mjs +8 -2
- package/cli/managed-server.mjs +1 -1
- package/cli/parse.mjs +7 -6
- package/cli/portability-migrations.mjs +30 -11
- package/cli/portability-worker.mjs +4 -1
- package/cli/portability.mjs +8 -2
- package/cli/production-auth.mjs +2 -1
- package/cli/production-mail.mjs +36 -9
- package/cli/project.mjs +5 -14
- package/cli/release.mjs +6 -5
- package/cli/site-hosting.mjs +90 -0
- package/cli/site-preview.mjs +4 -1
- package/cli/site-render.mjs +3 -2
- package/cli/site.mjs +8 -4
- package/edition-authoring/adopt.mjs +39 -0
- package/edition-authoring/base-acknowledgements.mjs +24 -0
- package/edition-authoring/base-copies.mjs +427 -0
- package/edition-authoring/cli.mjs +85 -0
- package/edition-authoring/copy-checkout.mjs +69 -0
- package/edition-authoring/files.mjs +15 -2
- package/edition-authoring/lock.mjs +48 -0
- package/edition-authoring/offline-git.mjs +28 -0
- package/edition-authoring/parent-comparison.mjs +77 -0
- package/edition-authoring/projection-lock.mjs +38 -0
- package/edition-authoring/release.mjs +48 -0
- package/edition-authoring/runtime-dependencies.mjs +108 -0
- package/edition-authoring/sources.mjs +114 -0
- package/edition-authoring/updates.mjs +105 -0
- package/global/CHANGELOG.md +24 -0
- package/global/README.md +17 -3
- package/global/cli/install.mjs +3 -1
- package/global/main.mjs +9 -12
- package/modules/container/build.mjs +1 -1
- package/modules/d1-transport/index.mjs +68 -21
- package/modules/demo/README.md +16 -2
- package/modules/demo/declaration.mjs +21 -0
- package/modules/demo/input-path.mjs +18 -0
- package/modules/demo/label.d.mts +1 -1
- package/modules/demo/label.mjs +10 -5
- package/modules/demo/navigation.mjs +148 -0
- package/modules/demo/run-url.mjs +9 -0
- package/modules/demo/vite.d.mts +7 -2
- package/modules/demo/vite.mjs +17 -2
- package/modules/demo-host/README.md +5 -3
- package/modules/demo-host/page-style.mjs +2 -2
- package/modules/demo-host/pages.mjs +3 -3
- package/modules/demo-host/plan.mjs +6 -4
- package/modules/demo-host/theme.mjs +5 -2
- package/modules/dependencies/auth.mjs +2 -2
- package/modules/deploy-kit/README.md +19 -15
- package/modules/deploy-kit/owner-cli.mjs +1 -1
- package/modules/deploy-kit/owner.mjs +8 -1
- package/modules/deploy-kit/readiness-window.mjs +3 -3
- package/modules/erasure/README.md +10 -5
- package/modules/import-kit/src/d1/README.md +15 -9
- package/modules/import-kit/src/d1/apply-effects.ts +33 -0
- package/modules/import-kit/src/d1/apply.ts +46 -14
- package/modules/import-kit/src/d1/atomic-prefix.ts +64 -0
- package/modules/import-kit/src/d1/budget.ts +48 -26
- package/modules/import-kit/src/d1/compressed-plan.ts +9 -2
- package/modules/import-kit/src/d1/database.ts +2 -1
- package/modules/import-kit/src/d1/jobs.ts +2 -1
- package/modules/import-kit/src/d1/plans.ts +4 -2
- package/modules/import-kit/src/d1/verified-plan.ts +63 -0
- package/modules/import-kit/src/types.ts +3 -1
- package/modules/integrations/core/README.md +2 -2
- package/modules/mail/README.md +4 -3
- package/modules/mail/pnpm-lock.yaml +16 -0
- package/modules/operator-auth/README.md +92 -3
- package/modules/operator-auth/accounts/admin.mjs +52 -20
- package/modules/operator-auth/accounts/audit.mjs +24 -0
- package/modules/operator-auth/accounts/business-team.mjs +91 -0
- package/modules/operator-auth/accounts/domain-audit.mjs +24 -0
- package/modules/operator-auth/accounts/native.mjs +6 -2
- package/modules/operator-auth/accounts/provider-control.mjs +7 -4
- package/modules/operator-auth/accounts/provider-setup.mjs +34 -0
- package/modules/operator-auth/accounts/settings-page.mjs +26 -4
- package/modules/operator-auth/accounts/status.mjs +7 -2
- package/modules/operator-auth/accounts/store.mjs +32 -6
- package/modules/operator-auth/business-settings.mjs +40 -0
- package/modules/operator-auth/conformance/README.md +1 -1
- package/modules/operator-auth/dev/index.mjs +22 -4
- package/modules/operator-auth/dev/refusal.mjs +19 -0
- package/modules/operator-auth/docs/README.md +6 -5
- package/modules/operator-auth/docs/tanstack-start.md +1 -1
- package/modules/operator-auth/docs/vite-spa.md +5 -6
- package/modules/operator-auth/identity/email-link/index.mjs +1 -1
- package/modules/operator-auth/identity/oidc/admin-audit.mjs +31 -0
- package/modules/operator-auth/identity/oidc/index.mjs +12 -5
- package/modules/operator-auth/identity/oidc/store.mjs +2 -0
- package/modules/operator-auth/index.d.mts +41 -2
- package/modules/operator-auth/page.mjs +14 -0
- package/modules/operator-auth/representation.mjs +83 -0
- package/modules/operator-auth/routes.mjs +31 -3
- package/modules/operator-auth/service.mjs +8 -3
- package/modules/operator-auth/signin/index.mjs +1 -1
- package/modules/portability/README.md +173 -15
- package/modules/portability/bookkeeping.mjs +3 -3
- package/modules/portability/bridge.mjs +5 -4
- package/modules/portability/catalogue.mjs +12 -8
- package/modules/portability/cli.mjs +5 -1
- package/modules/portability/export.mjs +10 -14
- package/modules/portability/format.mjs +12 -1
- package/modules/portability/http-errors.mjs +51 -0
- package/modules/portability/http.mjs +4 -1
- package/modules/portability/import-lease.mjs +13 -2
- package/modules/portability/import.mjs +10 -0
- package/modules/portability/index.d.mts +13 -2
- package/modules/portability/index.mjs +3 -2
- package/modules/portability/ledgers.mjs +27 -4
- package/modules/portability/references.mjs +20 -0
- package/modules/portability/schema-identity.mjs +13 -0
- package/modules/portability/schema-legacy.mjs +21 -0
- package/modules/portability/sqlite-tokens.mjs +121 -0
- package/modules/release/README.md +94 -11
- package/modules/release/github-verify.mjs +30 -9
- package/modules/release/sign.mjs +4 -2
- package/modules/release/signature.mjs +14 -7
- package/modules/release/signing-cli.mjs +2 -1
- package/modules/release/statement.mjs +2 -2
- package/modules/release/vectors/generate.mjs +1 -0
- package/modules/release/vectors/publisher-projects.mjs +133 -0
- package/modules/release/vectors/release-signature-vectors.json +5195 -0
- package/modules/release/verify.mjs +5 -1
- package/modules/site/docs-search/search.css +1 -1
- package/onboarding/README.md +16 -4
- package/onboarding/adapter.mjs +5 -1
- package/onboarding/schema/SETUP.schema.json +68 -1
- package/onboarding/schema/business-field-inputs.mjs +36 -0
- package/onboarding/schema/json-schema.mjs +6 -2
- package/onboarding/schema/setup-validation.mjs +23 -3
- package/onboarding/server.mjs +1 -1
- package/onboarding/setup-manifest.mjs +2 -0
- package/onboarding/start-origin-diagnostic.mjs +24 -0
- package/onboarding/ui/style.css +9 -9
- package/package.json +1 -1
- package/scripts/publish-check/README.md +1 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { auditMutation, operatorWitness } from './audit.mjs';
|
|
1
2
|
import { writeOperatorStatus } from './status.mjs';
|
|
2
3
|
import { AuthError, deny } from '../errors.mjs';
|
|
3
4
|
import { normalizeEmail, safeReturnTo } from '../policy.mjs';
|
|
@@ -6,7 +7,7 @@ import { operatorColumns } from './store.mjs';
|
|
|
6
7
|
import { DEFAULT_ROLES, emailAllowed } from './roles.mjs';
|
|
7
8
|
const DOMAIN = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/;
|
|
8
9
|
export function administration(context) {
|
|
9
|
-
const { config, store, clock, authorize, authenticate, newToken, sendLink, limit, requireFreshProof, providers } = context;
|
|
10
|
+
const { config, store, clock, authorize, authenticate, newToken, sendLink, limit, requireFreshProof, providers, audit } = context;
|
|
10
11
|
async function actorFor(request, action, target, role, mutation = true) {
|
|
11
12
|
if (mutation) requirePost(request, config);
|
|
12
13
|
const actor = await authenticate(request);
|
|
@@ -22,27 +23,43 @@ export function administration(context) {
|
|
|
22
23
|
&& (role === 'owner' || target?.role === 'owner')) await requireFreshProof(actor);
|
|
23
24
|
return actor;
|
|
24
25
|
}
|
|
26
|
+
function providerAudit(actor) {
|
|
27
|
+
if (!audit) return undefined;
|
|
28
|
+
const now = clock();
|
|
29
|
+
return { audit, actorId: actor.operator.id, fence: store.actorFence(actor, now), now };
|
|
30
|
+
}
|
|
25
31
|
async function targetFor(id) {
|
|
26
32
|
const target = typeof id === 'string' ? await store.operator(id) : null;
|
|
27
33
|
if (!target) deny('operator_not_found', 404);
|
|
28
34
|
return target;
|
|
29
35
|
}
|
|
30
|
-
|
|
31
|
-
async invite(request, input) {
|
|
36
|
+
async function prepareInvitation(request, input, snapshot) {
|
|
32
37
|
const role = input.role ?? 'member';
|
|
33
38
|
if (!DEFAULT_ROLES.includes(role)) throw new AuthError('invalid_role');
|
|
34
39
|
const actor = await actorFor(request, 'operators:invite', undefined, role);
|
|
35
40
|
const email = normalizeEmail(input.email);
|
|
36
|
-
|
|
41
|
+
// A trusted server batch supplies its read snapshot; browser requests
|
|
42
|
+
// retain the per-IP and mailbox invitation limits.
|
|
43
|
+
if (!snapshot) await limit(request, email, 'invite');
|
|
37
44
|
if (!emailAllowed(email, config.allowList)) deny('email_not_allowed');
|
|
38
|
-
const existing = await store.byEmail(email);
|
|
45
|
+
const existing = snapshot ? snapshot.operator : await store.byEmail(email);
|
|
39
46
|
const reinviting = existing?.status === 'inactive' && !!await store.cancellation(existing.id);
|
|
40
47
|
if (existing && (existing.role !== role || (!reinviting && existing.status !== 'invited'))) deny('invitation_conflict', 409);
|
|
41
48
|
const now = clock();
|
|
42
49
|
const token = await newToken('invite', safeReturnTo(input.returnTo));
|
|
43
|
-
const
|
|
50
|
+
const mutation = { operatorId: existing?.id ?? crypto.randomUUID(), expectedVersion: existing?.version ?? 1, reinviting, email, displayName: displayName(input.displayName), role, token, now };
|
|
51
|
+
return { mutation, actor, ...await store.prepareInvitation(mutation, actor, audit), async afterCommit() {
|
|
52
|
+
const issued = await store.first('SELECT id FROM oa_tokens WHERE id=? AND revoked_at IS NULL AND consumed_at IS NULL', [token.id]);
|
|
53
|
+
if (issued) await sendLink(email, token);
|
|
54
|
+
} };
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
prepareInvitation,
|
|
58
|
+
async invite(request, input) {
|
|
59
|
+
const plan = await prepareInvitation(request, input);
|
|
60
|
+
const created = await store.invite(plan.mutation, plan.actor, plan);
|
|
44
61
|
if (!created) deny('invitation_conflict', 409);
|
|
45
|
-
await
|
|
62
|
+
await plan.afterCommit();
|
|
46
63
|
return { status: 'accepted' };
|
|
47
64
|
},
|
|
48
65
|
async listOperators(request) {
|
|
@@ -55,16 +72,20 @@ export function administration(context) {
|
|
|
55
72
|
const target = await targetFor(operatorId);
|
|
56
73
|
const actor = await actorFor(request, 'operators:deactivate', target);
|
|
57
74
|
if (target.status !== 'invited') deny('invitation_conflict', 409);
|
|
58
|
-
const
|
|
75
|
+
const now = clock();
|
|
76
|
+
const fence = store.actorFence(actor, now);
|
|
59
77
|
// The guarded write and version trigger are one transaction: cancellation
|
|
60
78
|
// invalidates every outstanding link and cannot deactivate a raced join.
|
|
61
79
|
// Read the ledger to fail closed if its migration is missing. A previous
|
|
62
80
|
// cancellation remains guarded throughout reinvitation; cancelling again
|
|
63
81
|
// refreshes that marker through the existing database trigger.
|
|
64
82
|
await store.cancellation(target.id);
|
|
65
|
-
const result = await store
|
|
66
|
-
|
|
67
|
-
[target.id, target.version,
|
|
83
|
+
const [result] = await auditMutation(store, { audit,
|
|
84
|
+
event: { action: 'operators.cancel-invite', actorId: actor.operator.id, subjectId: target.id, detail: 'inactive', now },
|
|
85
|
+
before: { sql: `${fence.sql} AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND status='invited' AND version=?)`, args: [...fence.args, target.id, target.version] },
|
|
86
|
+
after: operatorWitness(target, 'status', 'inactive'),
|
|
87
|
+
statements: [[`UPDATE oa_operators SET status='inactive' WHERE id=? AND status='invited' AND version=? AND ${fence.sql}`, [target.id, target.version, ...fence.args]]],
|
|
88
|
+
});
|
|
68
89
|
if (result.meta.changes < 1) deny('authority_changed', 409);
|
|
69
90
|
return store.operator(target.id);
|
|
70
91
|
},
|
|
@@ -73,15 +94,21 @@ export function administration(context) {
|
|
|
73
94
|
const target = await targetFor(operatorId);
|
|
74
95
|
const actor = await actorFor(request, status === 'active' ? 'operators:reactivate' : 'operators:deactivate', target);
|
|
75
96
|
if (target.status === 'invited') deny('invitation_required', 409);
|
|
76
|
-
return writeOperatorStatus(store, actor, target, status, clock());
|
|
97
|
+
return writeOperatorStatus(store, actor, target, status, clock(), undefined, audit);
|
|
77
98
|
},
|
|
78
99
|
async setRole(request, operatorId, role) {
|
|
79
100
|
if (!DEFAULT_ROLES.includes(role)) throw new AuthError('invalid_role');
|
|
80
101
|
const target = await targetFor(operatorId);
|
|
81
102
|
const actor = await actorFor(request, 'operators:role', target, role);
|
|
82
|
-
const
|
|
103
|
+
const now = clock();
|
|
104
|
+
const fence = store.actorFence(actor, now);
|
|
83
105
|
try {
|
|
84
|
-
const result = await store
|
|
106
|
+
const [result] = await auditMutation(store, { audit: target.role === role ? undefined : audit,
|
|
107
|
+
event: { action: 'operators.role', actorId: actor.operator.id, subjectId: target.id, detail: role, now },
|
|
108
|
+
before: { sql: `${fence.sql} AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=?)`, args: [...fence.args, target.id, target.version] },
|
|
109
|
+
after: operatorWitness(target, 'role', role),
|
|
110
|
+
statements: [[`UPDATE oa_operators SET role=? WHERE id=? AND version=? AND ${fence.sql}`, [role, target.id, target.version, ...fence.args]]],
|
|
111
|
+
});
|
|
85
112
|
if (result.meta.changes < 1) deny('authority_changed', 409);
|
|
86
113
|
} catch (e) { if (String(e).includes('last_owner')) deny('last_owner', 409); throw e; }
|
|
87
114
|
return store.operator(target.id);
|
|
@@ -99,13 +126,18 @@ export function administration(context) {
|
|
|
99
126
|
return rows.results.map((r) => ({ ...r, active: !!r.active }));
|
|
100
127
|
},
|
|
101
128
|
async revokeSession(request, sessionId) {
|
|
102
|
-
const row = await store.first('SELECT operator_id AS operatorId FROM oa_sessions WHERE id=?', [sessionId]);
|
|
129
|
+
const row = await store.first('SELECT operator_id AS operatorId,revoked_at AS revokedAt FROM oa_sessions WHERE id=?', [sessionId]);
|
|
103
130
|
if (!row) deny('session_not_found', 404);
|
|
104
131
|
const target = await targetFor(row.operatorId);
|
|
105
132
|
const actor = await actorFor(request, 'sessions:revoke', target);
|
|
106
133
|
const now = clock();
|
|
107
134
|
const fence = store.actorFence(actor, now);
|
|
108
|
-
const result = await store
|
|
135
|
+
const [result] = await auditMutation(store, { audit: row.revokedAt === null ? audit : undefined,
|
|
136
|
+
event: { action: 'sessions.revoke', actorId: actor.operator.id, subjectId: target.id, detail: null, now },
|
|
137
|
+
before: { sql: `${fence.sql} AND EXISTS(SELECT 1 FROM oa_sessions s JOIN oa_operators o ON o.id=s.operator_id WHERE s.id=? AND s.revoked_at IS NULL AND o.id=? AND o.version=?)`, args: [...fence.args, sessionId, target.id, target.version] },
|
|
138
|
+
after: { sql: 'EXISTS(SELECT 1 FROM oa_sessions WHERE id=? AND revoked_at=?)', args: [sessionId, now] },
|
|
139
|
+
statements: [[`UPDATE oa_sessions SET revoked_at=COALESCE(revoked_at,?) WHERE id=? AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=?) AND ${fence.sql}${audit && row.revokedAt === null ? ' RETURNING id' : ''}`, [now, sessionId, target.id, target.version, ...fence.args]]],
|
|
140
|
+
});
|
|
109
141
|
if (result.meta.changes < 1) deny('authority_changed', 409);
|
|
110
142
|
},
|
|
111
143
|
async listDomainRules(request) {
|
|
@@ -120,7 +152,7 @@ export function administration(context) {
|
|
|
120
152
|
const providerId = input.provider ?? null;
|
|
121
153
|
if (providerId !== null && !providers?.ids.includes(providerId)) throw new AuthError('unknown_provider');
|
|
122
154
|
await requireFreshProof(actor);
|
|
123
|
-
await store.setDomainRule({ domain, providerId, now: clock() }, actor);
|
|
155
|
+
await store.setDomainRule({ domain, providerId, now: clock() }, actor, audit);
|
|
124
156
|
return store.domainRules();
|
|
125
157
|
},
|
|
126
158
|
async listProviders(request) {
|
|
@@ -131,16 +163,16 @@ export function administration(context) {
|
|
|
131
163
|
const actor = await actorFor(request, 'providers:manage');
|
|
132
164
|
if (!providers?.ids.includes(input?.provider)) throw new AuthError('unknown_provider');
|
|
133
165
|
await requireFreshProof(actor);
|
|
134
|
-
await providers.unlink(input.provider);
|
|
166
|
+
await providers.unlink(input.provider, providerAudit(actor));
|
|
135
167
|
// A rule naming a provider that is gone would lock its domain out.
|
|
136
|
-
await store.liftDomainRules(input.provider);
|
|
168
|
+
if (!audit) await store.liftDomainRules(input.provider);
|
|
137
169
|
return providers.links();
|
|
138
170
|
},
|
|
139
171
|
async relinkProvider(request, input) {
|
|
140
172
|
const actor = await actorFor(request, 'providers:manage');
|
|
141
173
|
if (!providers?.ids.includes(input?.provider)) throw new AuthError('unknown_provider');
|
|
142
174
|
await requireFreshProof(actor);
|
|
143
|
-
await providers.relink(input.provider);
|
|
175
|
+
await providers.relink(input.provider, providerAudit(actor));
|
|
144
176
|
return providers.links();
|
|
145
177
|
},
|
|
146
178
|
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { deny } from '../errors.mjs';
|
|
2
|
+
|
|
3
|
+
// D1 has no interactive transaction. A failed SQL assertion rolls the whole
|
|
4
|
+
// batch back, including arbitrary seed-owned hook statements. Check the old
|
|
5
|
+
// snapshot before the write as well as its result: old+1 alone could witness a
|
|
6
|
+
// different request that won the race. No table, trigger or changes() counter.
|
|
7
|
+
const assertion = ({ sql, args = [] }) => [
|
|
8
|
+
`SELECT CASE WHEN (${sql}) THEN 1 ELSE json_extract('[]', '$[oa_audit_refused') END`, args,
|
|
9
|
+
];
|
|
10
|
+
export async function auditMutation(store, { audit, event, before, after, statements }) {
|
|
11
|
+
if (!audit) return store.batch(statements);
|
|
12
|
+
const extra = await audit(event);
|
|
13
|
+
try {
|
|
14
|
+
const results = await store.batch([assertion(before), ...statements, assertion(after), ...extra]);
|
|
15
|
+
return results.slice(1, statements.length + 1);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (String(error).includes('oa_audit_refused')) deny('authority_changed', 409);
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export function operatorWitness(target, field, value) {
|
|
22
|
+
return { sql: `EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=? AND ${field}=?)`,
|
|
23
|
+
args: [target.id, target.version + (target[field] === value ? 0 : 1), value] };
|
|
24
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Trusted server integration only. The caller verifies the Business document;
|
|
2
|
+
// its nonce guard and every account mutation share one D1 batch.
|
|
3
|
+
import { administration, displayName } from './admin.mjs';
|
|
4
|
+
import { bindPolicyActor } from '../scheduled/fence.mjs';
|
|
5
|
+
import { normalizeEmail } from '../policy.mjs';
|
|
6
|
+
import { emailAllowed } from './roles.mjs';
|
|
7
|
+
import { deny } from '../errors.mjs';
|
|
8
|
+
|
|
9
|
+
export function businessTeam(context) {
|
|
10
|
+
const { store, accounts, config, clock, authorize } = context;
|
|
11
|
+
return Object.freeze({
|
|
12
|
+
async ownerEmail() { return (await accounts.owner())?.email ?? null; },
|
|
13
|
+
async prepare({ members, managed, ownerEmail, roles, guard }) {
|
|
14
|
+
const owner = await accounts.owner();
|
|
15
|
+
if (!owner || owner.email !== normalizeEmail(ownerEmail)) deny('owner_required', 403);
|
|
16
|
+
const operator = await store.operator(owner.id);
|
|
17
|
+
if (!operator || operator.email !== owner.email || operator.role !== 'owner' || operator.status !== 'active' || !emailAllowed(operator.email, config.allowList)) deny('owner_required', 403);
|
|
18
|
+
if (!guard || typeof guard.sql !== 'string' || !Array.isArray(guard.args)) deny('invalid_business_guard', 503);
|
|
19
|
+
if (![roles?.admin, roles?.member].every(role => role === 'admin' || role === 'member')) deny('invalid_role', 400);
|
|
20
|
+
const actor = Object.freeze({ operator });
|
|
21
|
+
bindPolicyActor(actor, () => ({ sql: `(${guard.sql}) AND EXISTS(SELECT 1 FROM oa_operators bo
|
|
22
|
+
WHERE bo.id=? AND bo.email=? AND bo.version=? AND bo.status='active' AND bo.role='owner'
|
|
23
|
+
AND bo.id=(SELECT o.id FROM oa_operators o LEFT JOIN oa_bootstrap b ON b.claim_id=o.id
|
|
24
|
+
WHERE o.role='owner' AND o.status='active' ORDER BY b.claim_id IS NULL,o.created_at,o.id LIMIT 1))`,
|
|
25
|
+
args: [...guard.args, operator.id, operator.email, operator.version] }));
|
|
26
|
+
const fence = store.actorFence(actor, clock());
|
|
27
|
+
const pending = [], rows = [];
|
|
28
|
+
// Abort the whole caller transaction if ownership changed, even when this
|
|
29
|
+
// document contains only conflicts or unchanged members.
|
|
30
|
+
const statements = [[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at)
|
|
31
|
+
SELECT ?,NULL,'business:authority_changed','{}',? WHERE NOT (${fence.sql})`,
|
|
32
|
+
[crypto.randomUUID(), clock(), ...fence.args]]];
|
|
33
|
+
const audit = (action, id, condition = 'changes()>0', args = []) => statements.push([
|
|
34
|
+
`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,CASE WHEN (${condition}) THEN ? ELSE NULL END,?,?,?`,
|
|
35
|
+
[crypto.randomUUID(), ...args, operator.id, action, JSON.stringify({ operatorId: id, via: `via Business by ${operator.email}` }), clock()],
|
|
36
|
+
]);
|
|
37
|
+
const allow = async (action, target, role) => {
|
|
38
|
+
if (target?.role === 'owner' || !await authorize({ actor: operator, action, target, role })) deny('business_team_denied', 403);
|
|
39
|
+
};
|
|
40
|
+
const request = new Request(new URL('/auth/invite', config.origin), { method: 'POST', headers: { origin: config.origin, host: new URL(config.origin).host } });
|
|
41
|
+
const desired = new Map(members.map(member => [normalizeEmail(member.email), member]));
|
|
42
|
+
const previous = new Map(managed.filter(row => row.operatorId).map(row => [normalizeEmail(row.email), row]));
|
|
43
|
+
const update = async (target, changes, action) => {
|
|
44
|
+
await allow(action, target, changes.role);
|
|
45
|
+
const changed = changes.role !== target.role || changes.status !== target.status;
|
|
46
|
+
statements.push([`UPDATE oa_operators SET role=?,status=?,display_name=? WHERE id=? AND email=? AND version=? AND role!='owner' AND ${fence.sql}`,
|
|
47
|
+
[changes.role, changes.status, changes.displayName, target.id, target.email, target.version, ...fence.args]]);
|
|
48
|
+
audit(action, target.id);
|
|
49
|
+
return { ...target, ...changes, version: target.version + (changed ? 1 : 0) };
|
|
50
|
+
};
|
|
51
|
+
for (const email of new Set([...desired.keys(), ...previous.keys()])) {
|
|
52
|
+
const member = desired.get(email), prior = previous.get(email);
|
|
53
|
+
// The roster address is a durable Business key, not the operator's
|
|
54
|
+
// current sign-in address. Self-service email changes keep this ID.
|
|
55
|
+
let target = prior ? await store.operator(prior.operatorId) : await store.byEmail(email);
|
|
56
|
+
const oldRole = target?.role;
|
|
57
|
+
if (target?.role === 'owner' || !prior && (email === owner.email || target) || prior && !target) {
|
|
58
|
+
// Never adopt an unrelated account, or discard a recorded identity
|
|
59
|
+
// because its old address now belongs to another account.
|
|
60
|
+
if (member || prior) rows.push({ email, operatorId: prior?.operatorId ?? null, invite: member?.invite ?? prior.invite, state: 'conflict' });
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (!member) {
|
|
64
|
+
if (target.status !== 'inactive') target = await update(target, { ...target, status: 'inactive' }, 'operators:deactivate');
|
|
65
|
+
rows.push({ email, operatorId: target.id, invite: prior.invite, state: 'inactive' });
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const role = roles[member.role];
|
|
69
|
+
if (role !== 'admin' && role !== 'member') deny('invalid_role', 400);
|
|
70
|
+
const name = displayName(member.name);
|
|
71
|
+
if (target && target.role !== role) target = await update(target, { ...target, role }, 'operators:role');
|
|
72
|
+
const cancelled = target?.status === 'inactive' && !!await store.cancellation(target.id);
|
|
73
|
+
if (target?.status === 'inactive' && !cancelled) target = await update(target, { ...target, status: 'active' }, 'operators:reactivate');
|
|
74
|
+
if (!target || cancelled || target.status === 'invited' && member.invite > (prior?.invite ?? -1) || target.status === 'invited' && target.role !== oldRole) {
|
|
75
|
+
// Preparation is shared with the public administration.invite path.
|
|
76
|
+
// A preceding role write is represented in the read snapshot only;
|
|
77
|
+
// the exact expected version is repeated in its invitation SQL.
|
|
78
|
+
const plan = await administration({ ...context, authenticate: async () => actor })
|
|
79
|
+
.prepareInvitation(request, { email: target?.email ?? email, displayName: name, role }, { operator: target });
|
|
80
|
+
statements.push(...plan.statements);
|
|
81
|
+
audit('operators:invite', plan.mutation.operatorId, 'EXISTS(SELECT 1 FROM oa_tokens WHERE id=?)', [plan.mutation.token.id]);
|
|
82
|
+
pending.push(plan.afterCommit);
|
|
83
|
+
target = { id: plan.mutation.operatorId, status: 'invited' };
|
|
84
|
+
} else if (target.displayName !== name) target = await update(target, { ...target, displayName: name }, 'operators:role');
|
|
85
|
+
rows.push({ email, operatorId: target.id, invite: member.invite, state: target.status });
|
|
86
|
+
}
|
|
87
|
+
return { statements: statements.map(([sql, args]) => store.statement(sql, args)), rows,
|
|
88
|
+
async afterCommit() { for (const send of pending) await send(); } };
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { auditMutation } from './audit.mjs';
|
|
2
|
+
|
|
3
|
+
export async function auditDomainRule(store, { domain, providerId, now }, actor, audit) {
|
|
4
|
+
const previous = await store.first('SELECT provider_id,created_by,created_at FROM oa_domain_rules WHERE domain=?', [domain]);
|
|
5
|
+
if (providerId === null && !previous) return 0;
|
|
6
|
+
const fence = store.actorFence(actor, now);
|
|
7
|
+
const snapshot = previous
|
|
8
|
+
? { sql: 'EXISTS(SELECT 1 FROM oa_domain_rules WHERE domain=? AND provider_id=? AND created_by=? AND created_at=?)', args: [domain, previous.provider_id, previous.created_by, previous.created_at] }
|
|
9
|
+
: { sql: 'NOT EXISTS(SELECT 1 FROM oa_domain_rules WHERE domain=?)', args: [domain] };
|
|
10
|
+
// The existing timestamp doubles as the domain rule's monotonic revision.
|
|
11
|
+
const revision = previous ? Math.max(previous.created_at + 1, now) : now;
|
|
12
|
+
const [result] = await auditMutation(store, { audit,
|
|
13
|
+
event: { action: providerId === null ? 'domains.rule.lift' : 'domains.rule.set', actorId: actor.operator.id, subjectId: null, detail: domain, now },
|
|
14
|
+
before: { sql: `${fence.sql} AND ${snapshot.sql}`, args: [...fence.args, ...snapshot.args] },
|
|
15
|
+
after: providerId === null
|
|
16
|
+
? { sql: 'NOT EXISTS(SELECT 1 FROM oa_domain_rules WHERE domain=?)', args: [domain] }
|
|
17
|
+
: { sql: 'EXISTS(SELECT 1 FROM oa_domain_rules WHERE domain=? AND provider_id=? AND created_by=? AND created_at=?)', args: [domain, providerId, actor.operator.id, revision] },
|
|
18
|
+
statements: [providerId === null
|
|
19
|
+
? ['DELETE FROM oa_domain_rules WHERE domain=? RETURNING domain', [domain]]
|
|
20
|
+
: [`INSERT INTO oa_domain_rules(domain,provider_id,created_by,created_at) VALUES(?,?,?,?)
|
|
21
|
+
ON CONFLICT(domain) DO UPDATE SET provider_id=excluded.provider_id,created_by=excluded.created_by,created_at=excluded.created_at RETURNING domain`, [domain, providerId, actor.operator.id, revision]]],
|
|
22
|
+
});
|
|
23
|
+
return result.results.length;
|
|
24
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { businessSettingsControls } from '../business-settings.mjs';
|
|
1
2
|
// Native composition never constructs an OA account/session store. The seed
|
|
2
3
|
// selects its tenant in these adapters, before any request is handled.
|
|
3
4
|
import { AuthError, deny } from '../errors.mjs';
|
|
@@ -14,6 +15,7 @@ import { createOidcProviders } from '../identity/oidc/index.mjs';
|
|
|
14
15
|
import { isLocalCli } from '../local-cli.mjs';
|
|
15
16
|
import { nativeDependencyAuthority } from '../../dependencies/native.mjs';
|
|
16
17
|
import { linkedProviders } from '../../dependencies/auth.mjs';
|
|
18
|
+
import { providerSetup } from './provider-setup.mjs';
|
|
17
19
|
|
|
18
20
|
const ACCOUNT_METHODS = ['findById', 'getSession', 'signOut', 'policyVersion', 'identityEnabled', 'requiredProvider', 'bindAndIssueSession'];
|
|
19
21
|
const PROOF_METHODS = ['limits', 'token', 'preview', 'consumeLink', 'revokeLink', 'stepUpPreview', 'stepUpChallenge', 'consumeStepUp', 'revokeStepUp', 'steppedUp'];
|
|
@@ -23,7 +25,7 @@ function validate(value, required, optional = []) {
|
|
|
23
25
|
if (!value || typeof value !== 'object' || required.some(k => typeof value[k] !== 'function') || optional.some(k => value[k] !== undefined && typeof value[k] !== 'function')) throw new AuthError('invalid_native_adapter', 503);
|
|
24
26
|
}
|
|
25
27
|
|
|
26
|
-
export function createNativeAuth({ accounts, proofs, db, config, clock, hooks, mailSender, clientIp, fetch, waitUntil }) {
|
|
28
|
+
export function createNativeAuth({ businessSettings, accounts, proofs, db, config, clock, hooks, mailSender, clientIp, fetch, waitUntil }) {
|
|
27
29
|
accountsAdapter(accounts);
|
|
28
30
|
validate(accounts, ACCOUNT_METHODS, OPTIONAL);
|
|
29
31
|
validate(proofs, PROOF_METHODS);
|
|
@@ -107,6 +109,7 @@ export function createNativeAuth({ accounts, proofs, db, config, clock, hooks, m
|
|
|
107
109
|
return session;
|
|
108
110
|
}
|
|
109
111
|
return Object.freeze({
|
|
112
|
+
...businessSettingsControls({ businessSettings, config, accounts, authenticate, requireFreshProof: email.requireFreshProof, clock }),
|
|
110
113
|
// Account administration belongs to the seed; unsupported operations are
|
|
111
114
|
// explicit refusals, never apparently successful writes to an unused store.
|
|
112
115
|
...Object.fromEntries(['invite', 'listOperators', 'cancelInvitation', 'setOperatorStatus', 'setRole', 'listSessions', 'revokeSession',
|
|
@@ -146,11 +149,12 @@ export function createNativeAuth({ accounts, proofs, db, config, clock, hooks, m
|
|
|
146
149
|
async admitVerifiedPassword(request, id, { returnTo } = {}) {
|
|
147
150
|
requirePost(request, config); return localSession(request, id, 'password', returnTo);
|
|
148
151
|
},
|
|
149
|
-
async identitySettings(request) { await owner(request); return { idpSignIn: await enabled() }; },
|
|
152
|
+
async identitySettings(request) { await owner(request); return { idpSignIn: await enabled(), providerSetup: await providerSetup(db, config) }; },
|
|
150
153
|
async setIdentitySettings(request, { idpSignIn }) {
|
|
151
154
|
const actor = await owner(request, true);
|
|
152
155
|
if (typeof idpSignIn !== 'boolean') deny('invalid_input', 400);
|
|
153
156
|
if (!accounts.setIdentitySettings) unavailable();
|
|
157
|
+
if (idpSignIn && !(await providerSetup(db, config)).canEnable) deny('provider_unlinked', 409);
|
|
154
158
|
if (!await accounts.setIdentitySettings({ actor, idpSignIn, now: clock() })) deny('authority_changed', 409);
|
|
155
159
|
return { idpSignIn };
|
|
156
160
|
},
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { devAdmitted } from '../dev-admission.mjs';
|
|
2
2
|
import { deny } from '../errors.mjs';
|
|
3
3
|
import { requirePost } from '../http.mjs';
|
|
4
|
+
import { providerEnableFence, providerSetup } from './provider-setup.mjs';
|
|
4
5
|
|
|
5
6
|
export function providerControl({ store, accounts, authenticate, config, clock }) {
|
|
6
7
|
async function owner(request, post = false) {
|
|
@@ -11,17 +12,19 @@ export function providerControl({ store, accounts, authenticate, config, clock }
|
|
|
11
12
|
return actor;
|
|
12
13
|
}
|
|
13
14
|
return {
|
|
14
|
-
async identitySettings(request) { await owner(request); return { idpSignIn: await accounts.identityEnabled() }; },
|
|
15
|
+
async identitySettings(request) { await owner(request); return { idpSignIn: await accounts.identityEnabled(), providerSetup: await providerSetup(store.db, config) }; },
|
|
15
16
|
async setIdentitySettings(request, { idpSignIn }) {
|
|
16
17
|
const actor = await owner(request, true);
|
|
17
18
|
if (typeof idpSignIn !== 'boolean') deny('invalid_input', 400);
|
|
19
|
+
const readiness = idpSignIn ? providerEnableFence(config) : { sql: '1', args: [] };
|
|
20
|
+
if (idpSignIn && !(await providerSetup(store.db, config)).canEnable) deny('provider_unlinked', 409);
|
|
18
21
|
const fence = store.actorFence(actor, clock());
|
|
19
22
|
const currentOwner = `?=(SELECT o.id FROM oa_operators o LEFT JOIN oa_bootstrap b ON b.claim_id=o.id WHERE o.role='owner' AND o.status='active' ORDER BY b.claim_id IS NULL,o.created_at,o.id LIMIT 1)`;
|
|
20
23
|
const auditId=crypto.randomUUID();
|
|
21
24
|
const results = await store.batch([
|
|
22
|
-
[`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation,first_setup) SELECT 1,0,0,0 WHERE ${fence.sql} AND ${currentOwner} ON CONFLICT(singleton) DO UPDATE SET first_setup=0 RETURNING singleton`, [...fence.args, actor.operator.id]],
|
|
23
|
-
[`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation) SELECT 1,?,1 WHERE ${fence.sql} AND ${currentOwner} AND NOT EXISTS(SELECT 1 FROM oa_auth_settings WHERE singleton=1 AND idp_sign_in=?)
|
|
24
|
-
ON CONFLICT(singleton) DO UPDATE SET idp_sign_in=excluded.idp_sign_in,generation=oa_auth_settings.generation+1,first_setup=0 RETURNING singleton`, [idpSignIn ? 1 : 0, ...fence.args, actor.operator.id, idpSignIn ? 1 : 0]],
|
|
25
|
+
[`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation,first_setup) SELECT 1,0,0,0 WHERE ${fence.sql} AND ${currentOwner} AND (${readiness.sql}) ON CONFLICT(singleton) DO UPDATE SET first_setup=0 RETURNING singleton`, [...fence.args, actor.operator.id, ...readiness.args]],
|
|
26
|
+
[`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation) SELECT 1,?,1 WHERE ${fence.sql} AND ${currentOwner} AND (${readiness.sql}) AND NOT EXISTS(SELECT 1 FROM oa_auth_settings WHERE singleton=1 AND idp_sign_in=?)
|
|
27
|
+
ON CONFLICT(singleton) DO UPDATE SET idp_sign_in=excluded.idp_sign_in,generation=oa_auth_settings.generation+1,first_setup=0 RETURNING singleton`, [idpSignIn ? 1 : 0, ...fence.args, actor.operator.id, ...readiness.args, idpSignIn ? 1 : 0]],
|
|
25
28
|
[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,?,'idpSignIn',?,? WHERE changes()=1`, [auditId, actor.operator.id, String(idpSignIn), clock()]],
|
|
26
29
|
[`UPDATE oa_sessions SET revoked_at=COALESCE(revoked_at,?) WHERE kind='oidc' AND EXISTS(SELECT 1 FROM oa_auth_audit WHERE id=? AND value='false')`, [clock(), auditId]],
|
|
27
30
|
]);
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Registration state, independent of the sign-in switch and network health.
|
|
2
|
+
// Static providers pin on first use; an explicit unlink still requires relinking.
|
|
3
|
+
export function providerEnableFence(config) {
|
|
4
|
+
if (config.externalIssuers.length) return { sql: '1', args: [] };
|
|
5
|
+
const clauses = [], args = [];
|
|
6
|
+
for (const provider of config.providers) {
|
|
7
|
+
clauses.push("NOT EXISTS(SELECT 1 FROM oa_identity_providers WHERE provider_id=? AND status='unlinked')");
|
|
8
|
+
args.push(provider.id);
|
|
9
|
+
}
|
|
10
|
+
if (config.dependencies) clauses.push(`EXISTS(SELECT 1 FROM rer_dependency_link l JOIN rer_dependency_keys k ON k.interface=l.interface
|
|
11
|
+
WHERE l.interface='oidc-provider@1' AND l.needs_relink=0)
|
|
12
|
+
AND NOT EXISTS(SELECT 1 FROM oa_identity_providers WHERE provider_id='auth' AND status='unlinked')`);
|
|
13
|
+
return { sql: clauses.length ? clauses.map(sql => `(${sql})`).join(' OR ') : '0', args };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function providerSetup(db, config) {
|
|
17
|
+
const providers = [];
|
|
18
|
+
if (config.externalIssuers.length) providers.push({ id: 'external', label: 'Verified identity provider', state: 'configured' });
|
|
19
|
+
if (config.providers.length || config.dependencies) {
|
|
20
|
+
let pins = config.providers.length ? (await db.prepare('SELECT provider_id,status FROM oa_identity_providers').all()).results : [];
|
|
21
|
+
for (const provider of config.providers) {
|
|
22
|
+
const pin = pins.find(pin => pin.provider_id === provider.id);
|
|
23
|
+
providers.push({ id: provider.id, label: provider.label ?? provider.id, state: pin?.status ?? 'configured' });
|
|
24
|
+
}
|
|
25
|
+
if (config.dependencies) {
|
|
26
|
+
const link = await db.prepare(`SELECT l.needs_relink,EXISTS(SELECT 1 FROM rer_dependency_keys k WHERE k.interface=l.interface) AS has_key
|
|
27
|
+
FROM rer_dependency_link l WHERE l.interface='oidc-provider@1'`).first();
|
|
28
|
+
if (link && !config.providers.length) pins = (await db.prepare('SELECT provider_id,status FROM oa_identity_providers').all()).results;
|
|
29
|
+
const unlinked = pins.some(pin => pin.provider_id === 'auth' && pin.status === 'unlinked');
|
|
30
|
+
providers.push({ id: 'auth', label: 'Auth', state: !link || unlinked ? 'unlinked' : link.needs_relink || !link.has_key ? 'needs-relink' : 'linked' });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return { canEnable: providers.some(provider => ['linked', 'configured'].includes(provider.state)), providers };
|
|
34
|
+
}
|
|
@@ -1,9 +1,31 @@
|
|
|
1
1
|
import { pageResponse } from '../page.mjs';
|
|
2
|
+
import { escapeHtml } from '../http.mjs';
|
|
2
3
|
|
|
3
4
|
// The owner's sign-in settings, in the same frame (and seed theme) as sign-in.
|
|
4
|
-
export function identitySettingsPage({ idpSignIn }, branding) {
|
|
5
|
-
const
|
|
6
|
-
|
|
5
|
+
export function identitySettingsPage({ idpSignIn, providerSetup, business }, branding, { saved = false, error, status = 200, method = 'GET' } = {}) {
|
|
6
|
+
const states = { linked: 'Linked', configured: 'Configured · connects on first sign-in', unlinked: 'Not linked', 'needs-relink': 'Link needs setup again' };
|
|
7
|
+
const notice = error === 'step_up_required' ? '<p class="notice" role="alert">Confirm your identity below, then stop Business settings.</p>' : error ? '<p class="notice" role="alert">Provider sign-in could not be enabled. Link or relink your identity provider, then try again.</p>'
|
|
8
|
+
: saved ? `<p class="notice" role="status">Settings saved. Provider sign-in is ${idpSignIn ? 'on' : 'off'}.</p>` : '';
|
|
9
|
+
const setup = providerSetup.providers.length
|
|
10
|
+
? providerSetup.providers.map(provider => `<p>${escapeHtml(provider.label)}: ${states[provider.state]}</p>`).join('')
|
|
11
|
+
: '<p>No identity provider is configured.</p>';
|
|
12
|
+
const content = notice + '<p>Allow invited people to sign in through your linked identity provider. Email links remain available to the owner.</p>'
|
|
13
|
+
+ '<h2>Provider setup</h2>' + setup
|
|
14
|
+
+ (!providerSetup.canEnable ? '<p>Have the installation administrator link or relink a provider through the project’s identity setup, then return here to enable sign-in.</p>' : '')
|
|
15
|
+
+ `<form action="/auth/settings/identity" method="post"><input type="hidden" name="setting" value="identity"><label class="check"><input type="checkbox" name="idpSignIn" value="true"${idpSignIn ? ' checked' : ''}${!providerSetup.canEnable && !idpSignIn ? ' disabled' : ''}>Allow provider sign-in</label><button>Save settings</button></form>`
|
|
16
|
+
+ businessSection(business)
|
|
7
17
|
+ '<p class="secondary-link"><a href="/app">Back to app</a></p>';
|
|
8
|
-
return pageResponse({ branding, title: 'Sign-in settings', heading: 'Sign-in settings', content, referrer: 'strict-origin' });
|
|
18
|
+
return pageResponse({ branding, title: 'Sign-in settings', heading: 'Sign-in settings', content, status, method, referrer: 'strict-origin' });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function businessSection(value) {
|
|
22
|
+
if (!value) return '';
|
|
23
|
+
const details = value.business
|
|
24
|
+
? `<p>Source: Business ${escapeHtml(value.business)}<br>Revision: ${escapeHtml(String(value.rev))}<br>Applied: ${escapeHtml(value.appliedAt ?? 'Not yet applied')}</p>`
|
|
25
|
+
: '<p>No Business settings have been applied.</p>';
|
|
26
|
+
if (value.stopped) return '<h2>Business</h2>' + details + '<p>Business settings are stopped. The last applied settings and team are kept.</p>';
|
|
27
|
+
return '<h2>Business</h2>' + details
|
|
28
|
+
+ '<p>The owner can stop receiving settings and team updates from Business. Confirm your identity first.</p>'
|
|
29
|
+
+ '<div class="stack"><form method="post" action="/auth/step-up"><input type="hidden" name="action" value="business:stop"><input type="hidden" name="returnTo" value="/auth/settings/identity"><button class="secondary">Confirm identity</button></form>'
|
|
30
|
+
+ '<form method="post" action="/auth/settings/business"><button class="secondary">Stop taking settings from Business</button></form></div>';
|
|
9
31
|
}
|
|
@@ -1,13 +1,18 @@
|
|
|
1
|
+
import { auditMutation, operatorWitness } from './audit.mjs';
|
|
1
2
|
import { deny } from '../errors.mjs';
|
|
2
3
|
// One persistence door for session and policy actors. The caller authorizes the
|
|
3
4
|
// action; the actor fence repeats live authority in this atomic write/audit.
|
|
4
|
-
export async function writeOperatorStatus(store, actor, target, status, now, audit) {
|
|
5
|
+
export async function writeOperatorStatus(store, actor, target, status, now, audit, adminAudit) {
|
|
5
6
|
const fence = store.actorFence(actor, now);
|
|
6
7
|
try {
|
|
7
8
|
const statements = [[`UPDATE oa_operators SET status=? WHERE id=? AND version=? AND ${fence.sql} RETURNING id`, [status, target.id, target.version, ...fence.args]]];
|
|
8
9
|
if (audit) statements.push([`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at)
|
|
9
10
|
SELECT ?,?,?,?,? WHERE changes()>0`, [crypto.randomUUID(), audit.actor, audit.action, JSON.stringify(audit.value), now]]);
|
|
10
|
-
const [result] = await
|
|
11
|
+
const [result] = await (adminAudit && target.status !== status ? auditMutation(store, { audit: adminAudit,
|
|
12
|
+
event: { action: status === 'active' ? 'operators.reactivate' : 'operators.deactivate', actorId: actor.operator.id, subjectId: target.id, detail: status, now },
|
|
13
|
+
before: { sql: `${fence.sql} AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=?)`, args: [...fence.args, target.id, target.version] },
|
|
14
|
+
after: operatorWitness(target, 'status', status), statements,
|
|
15
|
+
}) : store.batch(statements));
|
|
11
16
|
if (!result.results.some(row => row.id === target.id)) deny('authority_changed', 409);
|
|
12
17
|
} catch (error) {
|
|
13
18
|
if (String(error).includes('last_owner')) deny('last_owner', 409);
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { deny } from '../errors.mjs';
|
|
2
|
+
import { auditDomainRule } from './domain-audit.mjs';
|
|
1
3
|
import { policyActorFence } from '../scheduled/fence.mjs';
|
|
2
4
|
import { providerPinFence, recordProviderPin } from './provider-pin.mjs';
|
|
3
5
|
// D1 batches are transactions. All decisions that grant a session or mutate
|
|
@@ -59,7 +61,7 @@ export class AuthStore {
|
|
|
59
61
|
[input.id, input.hash, input.kind, input.returnTo, input.now, input.expiresAt, input.operatorId, ...fence.args]);
|
|
60
62
|
return result?.id === input.id;
|
|
61
63
|
}
|
|
62
|
-
|
|
64
|
+
invitationStatements({ operatorId, expectedVersion, reinviting = false, email, displayName, role, token, now }, actor, audit) {
|
|
63
65
|
const fence = this.actorFence(actor, now);
|
|
64
66
|
// Only a witnessed cancellation may reopen an inactive identity. Keep its
|
|
65
67
|
// durable admission guard until confirmation, including through pruning.
|
|
@@ -69,11 +71,11 @@ export class AuthStore {
|
|
|
69
71
|
[displayName, operatorId, email, role, expectedVersion, operatorId, ...fence.args]]
|
|
70
72
|
: [`INSERT INTO oa_operators(id,email,display_name,role,status,created_at)
|
|
71
73
|
SELECT ?,?,?,?,'invited',? WHERE ${fence.sql} ON CONFLICT(email) DO NOTHING`, [operatorId, email, displayName, role, now, ...fence.args]];
|
|
72
|
-
|
|
74
|
+
return [
|
|
73
75
|
prepare,
|
|
74
76
|
[`INSERT INTO oa_tokens(id,token_hash,kind,operator_id,operator_version,issuer_id,issuer_version,return_to,created_at,expires_at)
|
|
75
77
|
SELECT ?,?,'invite',id,version,?,?,?,?,? FROM oa_operators WHERE id=? AND status='invited' AND role=? AND version=?
|
|
76
|
-
${reinviting ? 'AND changes()=1' : ''} AND ${fence.sql} RETURNING id`,
|
|
78
|
+
${reinviting && !audit ? 'AND changes()=1' : ''} AND ${fence.sql} RETURNING id`,
|
|
77
79
|
[token.id, token.hash, actor.operator.id, actor.operator.version, token.returnTo, now, token.expiresAt, operatorId, role, expectedVersion + (reinviting ? 1 : 0), ...fence.args]],
|
|
78
80
|
// Bind revocation to this transaction's successful issuance, so a stale
|
|
79
81
|
// reissue cannot invalidate the winner's link or send another credential.
|
|
@@ -82,8 +84,31 @@ export class AuthStore {
|
|
|
82
84
|
// A link minted while using a dev session stays a dev credential.
|
|
83
85
|
...(actor.kind === 'dev' ? [[`INSERT INTO oa_dev_credentials(credential,id,created_at)
|
|
84
86
|
SELECT 'oa_tokens',id,? FROM oa_tokens WHERE id=?`, [now, token.id]]] : []),
|
|
85
|
-
]
|
|
86
|
-
|
|
87
|
+
];
|
|
88
|
+
}
|
|
89
|
+
async prepareInvitation(input, actor, audit) {
|
|
90
|
+
const statements = this.invitationStatements(input, actor, audit);
|
|
91
|
+
if (!audit) return { statements, mutationOffset: 0, mutationCount: statements.length };
|
|
92
|
+
const { operatorId, expectedVersion, reinviting = false, role, token, now } = input;
|
|
93
|
+
const fence = this.actorFence(actor, now);
|
|
94
|
+
const previousToken = await this.first('SELECT id FROM oa_tokens WHERE operator_id=? ORDER BY rowid DESC LIMIT 1', [operatorId]);
|
|
95
|
+
const extra = await audit({ action: 'operators.invite', actorId: actor.operator.id, subjectId: operatorId, detail: role, now });
|
|
96
|
+
const assertion = ({ sql, args }) => [
|
|
97
|
+
`SELECT CASE WHEN (${sql}) THEN 1 ELSE json_extract('[]', '$[oa_audit_refused') END`, args,
|
|
98
|
+
];
|
|
99
|
+
const before = { sql: `${fence.sql} AND (NOT EXISTS(SELECT 1 FROM oa_operators WHERE id=?) OR EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=?)) AND COALESCE((SELECT id FROM oa_tokens WHERE operator_id=? ORDER BY rowid DESC LIMIT 1),'')=?`, args: [...fence.args, operatorId, operatorId, expectedVersion, operatorId, previousToken?.id ?? ''] };
|
|
100
|
+
const after = { sql: 'EXISTS(SELECT 1 FROM oa_tokens WHERE id=? AND operator_id=? AND operator_version=?)', args: [token.id, operatorId, expectedVersion + (reinviting ? 1 : 0)] };
|
|
101
|
+
return { statements: [assertion(before), ...statements, assertion(after), ...extra], mutationOffset: 1, mutationCount: statements.length };
|
|
102
|
+
}
|
|
103
|
+
async invite(input, actor, prepared) {
|
|
104
|
+
const plan = prepared ?? await this.prepareInvitation(input, actor);
|
|
105
|
+
try {
|
|
106
|
+
const results = (await this.batch(plan.statements)).slice(plan.mutationOffset, plan.mutationOffset + plan.mutationCount);
|
|
107
|
+
return results[1].results.some(row => row.id === input.token.id);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (String(error).includes('oa_audit_refused')) deny('authority_changed', 409);
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
87
112
|
}
|
|
88
113
|
async preview(hash, now) {
|
|
89
114
|
return this.first(`SELECT t.kind,t.expires_at AS expiresAt,t.return_to AS returnTo,o.email,o.role,t.issuer_id AS issuerId,t.issuer_version AS issuerVersion,
|
|
@@ -211,7 +236,8 @@ export class AuthStore {
|
|
|
211
236
|
}
|
|
212
237
|
domainRule(domain) { return this.first('SELECT domain,provider_id AS providerId FROM oa_domain_rules WHERE domain=?', [domain]); }
|
|
213
238
|
async domainRules() { return (await this.statement('SELECT domain,provider_id AS providerId,created_at AS createdAt FROM oa_domain_rules ORDER BY domain').all()).results; }
|
|
214
|
-
async setDomainRule({ domain, providerId, now }, actor) {
|
|
239
|
+
async setDomainRule({ domain, providerId, now }, actor, audit) {
|
|
240
|
+
if (audit) return auditDomainRule(this, { domain, providerId, now }, actor, audit);
|
|
215
241
|
const fence = this.actorFence(actor, now);
|
|
216
242
|
const result = providerId === null
|
|
217
243
|
? await this.run(`DELETE FROM oa_domain_rules WHERE domain=? AND ${fence.sql}`, [domain, ...fence.args])
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { deny } from './errors.mjs';
|
|
2
|
+
import { requirePost } from './http.mjs';
|
|
3
|
+
|
|
4
|
+
// The integration contains only public branding and owner-visible provenance.
|
|
5
|
+
// It never returns the signed document (which includes private team data).
|
|
6
|
+
export function businessSettingsControls({ businessSettings, config, accounts, authenticate, requireFreshProof, store, clock }) {
|
|
7
|
+
if (!businessSettings) return {};
|
|
8
|
+
async function owner(request, post = false) {
|
|
9
|
+
if (post) requirePost(request, config);
|
|
10
|
+
const actor = await authenticate(request), current = await accounts.owner();
|
|
11
|
+
if (!actor) deny('unauthenticated', 401);
|
|
12
|
+
if (!current || current.id !== actor.operator.id) deny('owner_required', 403);
|
|
13
|
+
return actor;
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
businessSettings,
|
|
17
|
+
async publicPresentation() {
|
|
18
|
+
const brand = await businessSettings.publicBrand();
|
|
19
|
+
const logo = typeof brand.logo === 'string' && /^\/rer-business-logo\?v=[a-f0-9]{12,64}$/.test(brand.logo) ? brand.logo : undefined;
|
|
20
|
+
return { ...config.branding, ...(brand.displayName ? { productName: brand.displayName } : {}), ...(logo ? { mark: logo } : {}) };
|
|
21
|
+
},
|
|
22
|
+
async businessSettingsInfo(request) {
|
|
23
|
+
await owner(request);
|
|
24
|
+
const value = await businessSettings.read();
|
|
25
|
+
return { business: value.document?.business ?? null, rev: value.rev, appliedAt: value.appliedAt, stopped: value.stopped };
|
|
26
|
+
},
|
|
27
|
+
async stopBusinessSettings(request) {
|
|
28
|
+
const actor = await owner(request, true);
|
|
29
|
+
await requireFreshProof(actor);
|
|
30
|
+
const current = await owner(request);
|
|
31
|
+
if (current.operator.version !== actor.operator.version) deny('authority_changed', 409);
|
|
32
|
+
const sessionFence = store?.actorFence(actor, clock());
|
|
33
|
+
const guard = sessionFence ? { sql: `(${sessionFence.sql}) AND ?=(SELECT o.id FROM oa_operators o
|
|
34
|
+
LEFT JOIN oa_bootstrap b ON b.claim_id=o.id WHERE o.role='owner' AND o.status='active'
|
|
35
|
+
ORDER BY b.claim_id IS NULL,o.created_at,o.id LIMIT 1)`, args: [...sessionFence.args, actor.operator.id] } : undefined;
|
|
36
|
+
await businessSettings.stop(actor.operator.id, guard);
|
|
37
|
+
return { stopped: true };
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -35,7 +35,7 @@ without a theme its CSP adds only `img-src 'self'`. Every other resource rule
|
|
|
35
35
|
above still applies, and mail stays image-free.
|
|
36
36
|
|
|
37
37
|
The Base conformance registration is executable at
|
|
38
|
-
[`../tests/conformance.test.ts`](
|
|
38
|
+
[`../tests/conformance.test.ts`](https://github.com/runeditrun/base/blob/main/modules/operator-auth/tests/conformance.test.ts), and its D1/Worker
|
|
39
39
|
adapter lives in this directory's `tests/worker.mjs` and `tests/runtime.mjs`.
|
|
40
40
|
An adopting seed should map these methods to its actual Hono/Worker dispatcher
|
|
41
41
|
and native private API, then import and call the exported registration from its
|