@runeditrun/rer 0.2.80 → 0.2.82
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 +12 -0
- package/cli/deploy-needs.mjs +4 -2
- package/cli/export.mjs +1 -1
- package/cli/ledger-refusal.mjs +18 -0
- package/cli/portability-migrations.mjs +30 -11
- package/cli/portability-worker.mjs +3 -1
- package/cli/portability.mjs +2 -0
- package/cli/release.mjs +4 -4
- package/cli/site-hosting.mjs +90 -0
- package/cli/site-render.mjs +3 -2
- package/cli/site.mjs +5 -2
- package/edition-authoring/base-copies.mjs +12 -1
- package/edition-authoring/copy-checkout.mjs +152 -1
- package/edition-authoring/files.mjs +1 -1
- package/edition-authoring/runtime-dependencies.mjs +108 -0
- package/global/CHANGELOG.md +25 -0
- package/global/README.md +12 -0
- package/modules/demo/README.md +8 -0
- package/modules/demo/navigation.mjs +131 -15
- package/modules/dependencies/auth.mjs +2 -2
- package/modules/deploy-kit/owner.mjs +8 -1
- package/modules/import-kit/src/d1/apply-effects.ts +33 -0
- package/modules/import-kit/src/d1/apply.ts +38 -10
- package/modules/import-kit/src/door/ADOPTING.md +452 -0
- package/modules/import-kit/src/door/README.md +553 -0
- package/modules/import-kit/src/door/admission.ts +45 -0
- package/modules/import-kit/src/door/archive.ts +129 -0
- package/modules/import-kit/src/door/authority.ts +107 -0
- package/modules/import-kit/src/door/failures.ts +70 -0
- package/modules/import-kit/src/door/grants.ts +162 -0
- package/modules/import-kit/src/door/handler.ts +90 -0
- package/modules/import-kit/src/door/index.ts +20 -0
- package/modules/import-kit/src/door/intake/csv.ts +74 -0
- package/modules/import-kit/src/door/intake/json.ts +182 -0
- package/modules/import-kit/src/door/intake/projection.ts +61 -0
- package/modules/import-kit/src/door/intake/types.ts +28 -0
- package/modules/import-kit/src/door/intake-policy.ts +38 -0
- package/modules/import-kit/src/door/intake-upload.ts +91 -0
- package/modules/import-kit/src/door/inventory.ts +68 -0
- package/modules/import-kit/src/door/jobs.ts +134 -0
- package/modules/import-kit/src/door/limits.ts +16 -0
- package/modules/import-kit/src/door/operator.ts +41 -0
- package/modules/import-kit/src/door/planning.ts +227 -0
- package/modules/import-kit/src/door/protocol.ts +38 -0
- package/modules/import-kit/src/door/refusals.ts +51 -0
- package/modules/import-kit/src/door/schema.ts +101 -0
- package/modules/import-kit/src/door/store.ts +152 -0
- package/modules/import-kit/src/door/types.ts +100 -0
- package/modules/import-kit/src/door/uploads.ts +98 -0
- package/modules/import-kit/src/provenance/numeric-credentials.ts +40 -0
- package/modules/import-kit/src/readers/README.md +139 -0
- package/modules/import-kit/src/readers/api-policy.ts +67 -0
- package/modules/import-kit/src/readers/api.ts +86 -0
- package/modules/import-kit/src/readers/bytes.ts +73 -0
- package/modules/import-kit/src/readers/errors.ts +33 -0
- package/modules/import-kit/src/readers/file.ts +74 -0
- package/modules/import-kit/src/readers/index.ts +3 -0
- package/modules/import-kit/src/readers/json.ts +29 -0
- package/modules/import-kit/src/readers/numeric-lexemes.ts +104 -0
- package/modules/import-kit/src/readers/original.ts +31 -0
- package/modules/import-kit/src/readers/records.ts +105 -0
- package/modules/import-kit/src/types.ts +3 -1
- 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 +3 -1
- package/modules/operator-auth/accounts/settings-page.mjs +15 -2
- 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/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 +40 -1
- package/modules/operator-auth/routes.mjs +11 -6
- package/modules/operator-auth/service.mjs +8 -3
- package/modules/operator-auth/signin/index.mjs +1 -1
- package/modules/portability/README.md +82 -1
- package/modules/portability/export.mjs +6 -4
- package/modules/portability/format.mjs +5 -0
- package/modules/portability/index.d.mts +10 -2
- package/modules/portability/index.mjs +3 -2
- package/modules/portability/ledgers.mjs +27 -4
- package/modules/release/README.md +74 -2
- 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/onboarding/schema/SETUP.schema.json +43 -1
- package/onboarding/schema/business-field-inputs.mjs +0 -1
- package/onboarding/schema/setup-validation.mjs +3 -0
- package/package.json +3 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Operator auth (IF-055-CORE-v1)
|
|
2
2
|
|
|
3
3
|
Portable server-only ESM: import `createOperatorAuth`, `createAuthHandler` and
|
|
4
|
-
`createSignInHandler` from
|
|
4
|
+
`createSignInHandler` from `./modules/operator-auth/index.mjs`. TypeScript
|
|
5
5
|
declarations are `index.d.mts`. No framework or mail transport is bundled. Apply
|
|
6
6
|
`accounts/schema/operator-auth.sql` once for a fresh auth database (and
|
|
7
7
|
`identity/oidc/schema/oidc.sql` when the app offers identity providers). Preserve applied migration history in an existing
|
|
@@ -418,6 +418,63 @@ Two hooks on `createOperatorAuth({hooks})` keep a seed's own sign-in work in pla
|
|
|
418
418
|
(Pencil's audit mail), or throw an `AuthError` to refuse: the session it was
|
|
419
419
|
about to get is revoked first (Cradle's forgery check).
|
|
420
420
|
|
|
421
|
+
## Administrative audit hook
|
|
422
|
+
|
|
423
|
+
`createOperatorAuth({hooks: {audit}})` optionally accepts
|
|
424
|
+
`audit({action, actorId, subjectId, detail, now})`, returning `[sql, args][]` or a
|
|
425
|
+
Promise of those pairs. The callback must be pure: return SQL for the module to
|
|
426
|
+
append to the administrative mutation's own D1 batch, with no external writes. A raced
|
|
427
|
+
request may generate statements and then be refused by its transaction fence.
|
|
428
|
+
Authorization, actor/version fences, the mutation and audit statements retain
|
|
429
|
+
their transaction guards. A refused or rolled-back mutation leaves no audit row;
|
|
430
|
+
a thrown hook or failed audit SQL fails the action closed. With no hook,
|
|
431
|
+
administrative behavior is unchanged. This hook covers the OA-backed
|
|
432
|
+
administrative methods below; it does not cover native accounts adapters or
|
|
433
|
+
other write paths.
|
|
434
|
+
|
|
435
|
+
An already-unlinked provider remains a successful no-op (HTTP 200, as without
|
|
436
|
+
the hook) and produces no audit row. An audited unlink advances the pin's
|
|
437
|
+
generation in the same statement; the batch checks the old snapshot and that
|
|
438
|
+
new generation before inserting audit rows. A suppressed or stale mutation
|
|
439
|
+
returns 409 and rolls back the batch.
|
|
440
|
+
|
|
441
|
+
`actorId` is the authenticated actor's opaque `oa_operators.id`. `subjectId` is
|
|
442
|
+
the target operator's opaque id, including the operator owning a revoked
|
|
443
|
+
session; domain and provider actions use `null`. `now` is the action's clock
|
|
444
|
+
time in milliseconds since the Unix epoch. The event has only these fields:
|
|
445
|
+
|
|
446
|
+
| `action` | `subjectId` | `detail` |
|
|
447
|
+
| --- | --- | --- |
|
|
448
|
+
| `operators.invite` | Invited operator id | New role |
|
|
449
|
+
| `operators.cancel-invite` | Cancelled operator id | `inactive` |
|
|
450
|
+
| `operators.deactivate` | Target operator id | `inactive` |
|
|
451
|
+
| `operators.reactivate` | Target operator id | `active` |
|
|
452
|
+
| `operators.role` | Target operator id | New role |
|
|
453
|
+
| `sessions.revoke` | Session owner's operator id | `null` |
|
|
454
|
+
| `domains.rule.set` | `null` | Normalized domain |
|
|
455
|
+
| `domains.rule.lift` | `null` | Normalized domain |
|
|
456
|
+
| `providers.unlink` | `null` | Provider id |
|
|
457
|
+
| `providers.relink` | `null` | Provider id |
|
|
458
|
+
|
|
459
|
+
`detail` is a string or `null`. Never add names, email addresses, IdP issuers or
|
|
460
|
+
subjects, tokens, record data or file paths. The seed owns audit storage,
|
|
461
|
+
migrations, retention and erasure; Base creates no audit table. For example,
|
|
462
|
+
Cradle can return an insert into its `company_identity_audit` table after its
|
|
463
|
+
seed migration adds nullable `detail` and supports nullable `operator_id` for
|
|
464
|
+
domain/provider events:
|
|
465
|
+
|
|
466
|
+
```js
|
|
467
|
+
hooks: {
|
|
468
|
+
audit: ({action, actorId, subjectId, detail, now}) => [[
|
|
469
|
+
'INSERT INTO company_identity_audit(actor_id,operator_id,action,detail,created_at) VALUES(?,?,?,?,?)',
|
|
470
|
+
[actorId, subjectId, action, detail, now],
|
|
471
|
+
]],
|
|
472
|
+
}
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
Use the seed's actor and subject erasure rules for this table. `oa_auth_audit`
|
|
476
|
+
is not a substitute for seed-owned administrative audit storage.
|
|
477
|
+
|
|
421
478
|
## Domain rules and step-up
|
|
422
479
|
|
|
423
480
|
An owner can require a provider for an email domain (`POST /auth/domain-rules`
|
|
@@ -594,7 +651,7 @@ an independently captured pre-update source snapshot containing the complete
|
|
|
594
651
|
root. With the frozen workspace dependencies installed, run:
|
|
595
652
|
|
|
596
653
|
```sh
|
|
597
|
-
OA_BASELINE_SOURCE=/path/to/snapshot node --test modules/operator-auth/tests/reinvitation-upgrade.mjs
|
|
654
|
+
OA_BASELINE_SOURCE=/path/to/snapshot node --test ./modules/operator-auth/tests/reinvitation-upgrade.mjs
|
|
598
655
|
```
|
|
599
656
|
|
|
600
657
|
Runtime tests use the locked Wrangler Miniflare/esbuild dependencies and run the
|
|
@@ -608,7 +665,7 @@ deployment remain separate.
|
|
|
608
665
|
|
|
609
666
|
## Adopting this version
|
|
610
667
|
|
|
611
|
-
Copy the **complete**
|
|
668
|
+
Copy the **complete** `./modules/operator-auth/` directory from one reviewed Base
|
|
612
669
|
revision into the seed's operator-auth source location. Keep its layers
|
|
613
670
|
(`identity/`, `accounts/`, `dev/`), runtime files, declarations, schema,
|
|
614
671
|
conformance files and tests from that same revision; `rer check` names any copied
|
|
@@ -707,3 +764,35 @@ OA accounts offer a bounded, hash-pinned scheduled policy door, separate from
|
|
|
707
764
|
human sessions. Read [SCHEDULED-POLICY.md](SCHEDULED-POLICY.md) for the design,
|
|
708
765
|
additive migration, declaration, owner approval/revocation flow and audit contract.
|
|
709
766
|
The reference `/app/policies` screen and Worker scheduled handler show adoption.
|
|
767
|
+
|
|
768
|
+
### Business settings and the default team adapter
|
|
769
|
+
|
|
770
|
+
An edition that adopts `./modules/business-settings` passes its runtime instance as
|
|
771
|
+
`createOperatorAuth({ ..., businessSettings })`. It supplies `publicBrand()`,
|
|
772
|
+
`read()` provenance and `stop(actorId, guard?)`. The optional guard is the OA
|
|
773
|
+
session's live SQL authority fence: include it in the stop transaction. The
|
|
774
|
+
owner-only sign-in settings page shows the source Business, revision and applied
|
|
775
|
+
time, with a `business:stop` step-up control. Public sign-in uses the runtime
|
|
776
|
+
name and versioned same-origin logo; no Business colour is applied there. For
|
|
777
|
+
Base's setup frame, pass the instance as `theme.businessSettings`.
|
|
778
|
+
|
|
779
|
+
OA compositions expose the server-only `auth.businessTeam` adapter. The Business
|
|
780
|
+
runtime calls `ownerEmail()` to bind trust to the current claimed owner, then
|
|
781
|
+
`prepare({ members, managed, ownerEmail, roles, guard })`. Here `members` is the
|
|
782
|
+
verified roster; `managed` contains only durable Business-owned rows
|
|
783
|
+
`{email,operatorId,invite,state}`; `roles` maps `admin` and `member` to the app's
|
|
784
|
+
non-owner OA roles; and `guard:{sql,args}` proves this document's accepted
|
|
785
|
+
revision and fresh nonce. Batch the returned `statements` with settings, logo
|
|
786
|
+
and managed-row writes on the same D1 binding, then call `afterCommit()` to send
|
|
787
|
+
invitations. Never call it before a successful batch.
|
|
788
|
+
|
|
789
|
+
The adapter preserves the configured role policy and repeats claimed-owner and
|
|
790
|
+
target versions in SQL. New and reissued invitations use the existing
|
|
791
|
+
administration invitation preparation, issuer authority, cancellation ledger
|
|
792
|
+
and app mail sender. Removal cancels pending invitations or deactivates an
|
|
793
|
+
accepted account, invalidating its sessions. Re-adding an unaccepted account
|
|
794
|
+
requires its invitation; accepted accounts reactivate. Existing unowned
|
|
795
|
+
operators return `conflict`, and owner operators are never changed or granted.
|
|
796
|
+
Audit rows retain the claimed owner as actor and record `via: "via Business by <owner email>"`. Native account compositions
|
|
797
|
+
supply their own team adapter and can use the same optional branding/settings
|
|
798
|
+
integration.
|
|
@@ -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';
|
|
@@ -24,7 +25,7 @@ function validate(value, required, optional = []) {
|
|
|
24
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);
|
|
25
26
|
}
|
|
26
27
|
|
|
27
|
-
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 }) {
|
|
28
29
|
accountsAdapter(accounts);
|
|
29
30
|
validate(accounts, ACCOUNT_METHODS, OPTIONAL);
|
|
30
31
|
validate(proofs, PROOF_METHODS);
|
|
@@ -108,6 +109,7 @@ export function createNativeAuth({ accounts, proofs, db, config, clock, hooks, m
|
|
|
108
109
|
return session;
|
|
109
110
|
}
|
|
110
111
|
return Object.freeze({
|
|
112
|
+
...businessSettingsControls({ businessSettings, config, accounts, authenticate, requireFreshProof: email.requireFreshProof, clock }),
|
|
111
113
|
// Account administration belongs to the seed; unsupported operations are
|
|
112
114
|
// explicit refusals, never apparently successful writes to an unused store.
|
|
113
115
|
...Object.fromEntries(['invite', 'listOperators', 'cancelInvitation', 'setOperatorStatus', 'setRole', 'listSessions', 'revokeSession',
|
|
@@ -2,9 +2,9 @@ import { pageResponse } from '../page.mjs';
|
|
|
2
2
|
import { escapeHtml } from '../http.mjs';
|
|
3
3
|
|
|
4
4
|
// The owner's sign-in settings, in the same frame (and seed theme) as sign-in.
|
|
5
|
-
export function identitySettingsPage({ idpSignIn, providerSetup }, branding, { saved = false, error, status = 200, method = 'GET' } = {}) {
|
|
5
|
+
export function identitySettingsPage({ idpSignIn, providerSetup, business }, branding, { saved = false, error, status = 200, method = 'GET' } = {}) {
|
|
6
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 ? '<p class="notice" role="alert">Provider sign-in could not be enabled. Link or relink your identity provider, then try again.</p>'
|
|
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
8
|
: saved ? `<p class="notice" role="status">Settings saved. Provider sign-in is ${idpSignIn ? 'on' : 'off'}.</p>` : '';
|
|
9
9
|
const setup = providerSetup.providers.length
|
|
10
10
|
? providerSetup.providers.map(provider => `<p>${escapeHtml(provider.label)}: ${states[provider.state]}</p>`).join('')
|
|
@@ -13,6 +13,19 @@ export function identitySettingsPage({ idpSignIn, providerSetup }, branding, { s
|
|
|
13
13
|
+ '<h2>Provider setup</h2>' + setup
|
|
14
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
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)
|
|
16
17
|
+ '<p class="secondary-link"><a href="/app">Back to app</a></p>';
|
|
17
18
|
return pageResponse({ branding, title: 'Sign-in settings', heading: 'Sign-in settings', content, status, method, referrer: 'strict-origin' });
|
|
18
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>';
|
|
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
|
+
}
|