@runeditrun/rer 0.2.18 → 0.2.20
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 +7 -7
- package/cli/README.md +22 -21
- package/cli/adapter.mjs +5 -0
- package/cli/container.mjs +7 -2
- package/cli/contract.mjs +6 -4
- package/cli/delivery-declarations.mjs +36 -0
- package/cli/demo-host.mjs +2 -2
- package/cli/demo.mjs +16 -5
- package/cli/deploy-command.mjs +4 -1
- package/cli/deploy.mjs +4 -1
- package/cli/detached-server.mjs +2 -2
- package/cli/dev-identity.mjs +1 -1
- package/cli/export.mjs +1 -1
- package/cli/inspect.mjs +17 -15
- package/cli/lifecycle.mjs +16 -49
- package/cli/listen.mjs +31 -0
- package/cli/local.mjs +12 -18
- package/cli/main.mjs +7 -0
- package/cli/managed-server.mjs +26 -44
- package/cli/output.mjs +1 -1
- package/cli/parse.mjs +8 -7
- package/cli/port.mjs +20 -20
- package/cli/production-auth.mjs +38 -0
- package/cli/server-proxy.mjs +2 -6
- package/cli/server-registry.mjs +7 -2
- package/cli/setup-input.mjs +3 -0
- package/cli/signin.mjs +41 -0
- package/global/CHANGELOG.md +18 -0
- package/global/README.md +7 -7
- package/global/cli/install.mjs +4 -28
- package/global/cli/path-link.mjs +25 -21
- package/global/launch/dev.mjs +1 -1
- package/global/launch/facts.mjs +11 -14
- package/global/launch/failure.mjs +20 -0
- package/global/launch/render.mjs +2 -6
- package/global/launch/worker.mjs +3 -3
- package/global/main.mjs +3 -3
- package/modules/container/build.mjs +2 -2
- package/modules/container/demo-egress.mjs +35 -0
- package/modules/container/worker-engine.mjs +3 -3
- package/modules/d1-transport/index.d.mts +9 -0
- package/modules/d1-transport/index.mjs +124 -0
- package/modules/delivery-producer/bindings.mjs +140 -0
- package/modules/delivery-producer/declarations.mjs +49 -0
- package/modules/demo/README.md +34 -0
- package/modules/demo/effects.mjs +73 -0
- package/modules/demo/index.d.mts +15 -0
- package/modules/demo/index.mjs +63 -0
- package/modules/demo/label.d.mts +2 -0
- package/modules/demo/label.mjs +24 -0
- package/modules/demo/responses.mjs +26 -0
- package/modules/demo/sockets.mjs +13 -0
- package/modules/demo/vite.d.mts +2 -0
- package/modules/demo/vite.mjs +19 -0
- package/modules/demo-host/README.md +5 -1
- package/modules/demo-host/container.mjs +4 -4
- package/modules/demo-host/pages.mjs +1 -1
- package/modules/demo-host/worker.mjs +1 -1
- package/modules/deploy-kit/README.md +2 -0
- package/modules/deploy-kit/owner-cli.mjs +5 -2
- package/modules/deploy-kit/owner-signin.mjs +34 -0
- package/modules/deploy-kit/owner.mjs +2 -2
- package/modules/deploy-kit/r2-objects.mjs +8 -5
- package/modules/job-queue/storage.mjs +4 -1
- package/modules/mail/README.md +62 -87
- package/modules/mail/src/adapters/rer/contract.mjs +22 -0
- package/modules/mail/src/adapters/rer/index.mjs +30 -0
- package/modules/mail/src/core/transport.mjs +1 -1
- package/modules/mail/src/core/validation.mjs +6 -3
- package/modules/mail/src/development/index.d.mts +1 -6
- package/modules/mail/src/development/index.mjs +3 -16
- package/modules/mail/src/sender.mjs +2 -1
- package/modules/operator-auth/README.md +53 -9
- package/modules/operator-auth/accounts/email-change.mjs +34 -0
- package/modules/operator-auth/accounts/owner-signin.mjs +50 -0
- package/modules/operator-auth/accounts/schema/owner-signin.sql +10 -0
- package/modules/operator-auth/csp.mjs +1 -2
- package/modules/operator-auth/dev/cli-session.mjs +32 -0
- package/modules/operator-auth/dev/index.mjs +18 -11
- package/modules/operator-auth/identity/email-link/confirmation.mjs +3 -3
- package/modules/operator-auth/identity/email-link/index.mjs +4 -1
- package/modules/operator-auth/index.d.mts +8 -2
- package/modules/operator-auth/owner-signin-grant.mjs +10 -0
- package/modules/operator-auth/page.mjs +1 -1
- package/modules/operator-auth/routes.mjs +11 -1
- package/modules/operator-auth/service.mjs +4 -0
- package/modules/operator-auth/signin/index.d.mts +1 -1
- package/modules/portability/README.md +6 -0
- package/modules/portability/catalogue.mjs +1 -1
- package/modules/portability/copies.mjs +17 -2
- package/modules/portability/index.mjs +2 -0
- package/modules/portability/provider-data.mjs +1 -1
- package/modules/portability/storage.mjs +5 -1
- package/onboarding/README.md +8 -11
- package/onboarding/adapter-auth.mjs +6 -38
- package/onboarding/adapter-labels.mjs +1 -1
- package/onboarding/adapter.mjs +8 -11
- package/onboarding/app-fetch.mjs +1 -1
- package/onboarding/dependency-approval.mjs +5 -15
- package/onboarding/dev-identity.mjs +1 -1
- package/onboarding/operator-install.mjs +6 -7
- package/onboarding/operator-installer.mjs +5 -5
- package/onboarding/operator-prerequisites.mjs +4 -5
- package/onboarding/port-probe.mjs +38 -0
- package/onboarding/process-diagnostics.mjs +36 -20
- package/onboarding/server.mjs +1 -1
- package/onboarding/ui/app.js +1 -1
- package/operations/README.md +3 -0
- package/package.json +4 -2
- package/scripts/publish-check/public_hygiene.py +31 -10
- package/modules/mail/src/development/viewer-html.mjs +0 -42
- package/modules/mail/src/development/viewer.mjs +0 -72
- package/modules/operator-auth/dev/badge.mjs +0 -44
|
@@ -63,7 +63,7 @@ Base's operator auth is the only staff sign-in, in three layers:
|
|
|
63
63
|
| --- | --- | --- |
|
|
64
64
|
| `identity/` | Proving who a person is: the email link (`identity/email-link/`), identity providers over OpenID Connect (`identity/oidc/`, see [its README](identity/oidc/README.md)), and the admission that turns a verified principal into a session (`identity/admission.mjs`). | Outputs a **verified principal** `{issuer, subject, provider?, email?, emailVerified?, emailVerifiedAt?, amr?}`; `identity/index.mjs`. |
|
|
65
65
|
| `accounts/` | Who a person is in this app and what they may do: operators, roles, invitations, sessions, domain rules and step-up proofs in the `oa_` store (`accounts/store.mjs`, `accounts/schema/`). | The **accounts adapter interface** (`accounts/adapter.mjs`); Base's implementation over `oa_` is `accounts/oa.mjs`. |
|
|
66
|
-
| `dev/` | Local-only dev sessions, personas and
|
|
66
|
+
| `dev/` | Local-only dev sessions, personas and mode labels, loaded only from a local-only Worker entry. | `dev/index.mjs`; see "Local dev identity" below. |
|
|
67
67
|
|
|
68
68
|
The files at the root are shared by all three: HTTP and input checks, crypto,
|
|
69
69
|
configuration and branding, the shared page frame (`page.mjs`), the key gate
|
|
@@ -130,6 +130,9 @@ version), domain rules in `oa_domain_rules`. `auth.accounts` exposes it and
|
|
|
130
130
|
| `/auth/providers` | GET | the pinned provider links; owner only |
|
|
131
131
|
| `/auth/providers/unlink`, `/auth/providers/relink` | POST | provider; owner only, step-up |
|
|
132
132
|
| `/auth/oidc/<id>/start`, `/auth/oidc/<id>/callback` | POST / GET | each provider's own routes (see [identity/oidc](identity/oidc/README.md)) |
|
|
133
|
+
| `/auth/owner-signin?token=…` | GET/HEAD | 200 owner sign-in confirmation for a live `rer signin` link, or 400 invalid/used/expired; **no writes** |
|
|
134
|
+
| `/auth/owner-signin` | POST | token; consume once for the active owner it names, 303 with cookie; see "Owner sign-in without mail" |
|
|
135
|
+
| `/auth/email` | POST | email; the signed-in operator's own sign-in email; fresh step-up proof; 409 `email_in_use` |
|
|
133
136
|
|
|
134
137
|
Unknown `/auth/*` paths return 404. Unsupported methods return 405. Except for invalid/expired confirmation GET/HEAD documents, known public
|
|
135
138
|
errors are JSON `{error:code}`: invalid input 400, unauthenticated 401, policy/host/
|
|
@@ -377,7 +380,7 @@ for other requests). It is server-rendered plain HTML with no script, so it work
|
|
|
377
380
|
before hydration and without JavaScript, in the same hashed-style frame as the
|
|
378
381
|
confirmation page (light and dark, the seed's `rer-theme.css` when declared).
|
|
379
382
|
It shows "Continue with…" for each linked, reachable provider, then the email
|
|
380
|
-
link, then optional seed links
|
|
383
|
+
link, then optional seed links and, while the first owner is
|
|
381
384
|
unclaimed, the setup form. A provider that has failed discovery or JWKS for 5
|
|
382
385
|
minutes, or answered 404 or a DNS failure, is hidden, and a browser that still
|
|
383
386
|
posts to it comes back to this page with a notice and the email link instead of
|
|
@@ -426,6 +429,40 @@ Creating a server-declared owner dev persona also requires the signed-in owner's
|
|
|
426
429
|
fresh local proof in addition to the checkout key. Its creation repeats the actor
|
|
427
430
|
session/version fence in the database write.
|
|
428
431
|
|
|
432
|
+
## Owner sign-in without mail (`rer signin`)
|
|
433
|
+
|
|
434
|
+
An owner whose mail does not work yet, or whose `OWNER_EMAIL` was mistyped, gets
|
|
435
|
+
in with `rer signin [--environment NAME]`. rer uses only the Cloudflare
|
|
436
|
+
credentials that deployed that environment: it checks that the live Worker is
|
|
437
|
+
the one its deploy record names, writes one row into `oa_owner_signins` in the
|
|
438
|
+
deployment's own D1 through the D1 API, and prints the link
|
|
439
|
+
`/auth/owner-signin?token=…` once to the terminal. The row holds the SHA-256 of
|
|
440
|
+
the 256-bit token (`owner-signin-grant.mjs`), the claimed owner's id and
|
|
441
|
+
version, and an expiry 15 minutes ahead; the token itself is never stored, and
|
|
442
|
+
rer writes it to no log, receipt or deploy record.
|
|
443
|
+
|
|
444
|
+
GET only shows a confirmation page (link scanners cannot use it). POST consumes
|
|
445
|
+
the grant in one transaction with the session it opens, and only while the
|
|
446
|
+
grant is unused, unexpired, at most 15 minutes from the Worker's own clock
|
|
447
|
+
(whatever clock minted it), and names the operator that is still the active
|
|
448
|
+
owner at the same version (a role or status change voids it). The same
|
|
449
|
+
transaction records `owner:signin-link` in `oa_auth_audit` for that owner and
|
|
450
|
+
counts as a fresh step-up proof. The route uses the confirmation rate limit,
|
|
451
|
+
the exact Origin and the secure cookie of every other sign-in.
|
|
452
|
+
|
|
453
|
+
Why it is safe: writing that table needs the same Cloudflare token that can
|
|
454
|
+
already replace the Worker or read and write its database, so the link adds no
|
|
455
|
+
authority beyond the deploy credentials. It works once, only for the recorded
|
|
456
|
+
owner, within 15 minutes, and its use is logged. Production email-link sign-in
|
|
457
|
+
is unchanged. Native accounts (`createNativeAuth`) do not mount this route.
|
|
458
|
+
|
|
459
|
+
A wrong sign-in email is corrected in the app: `POST /auth/email {email}`
|
|
460
|
+
changes the signed-in operator's own address after a fresh proof (a step-up
|
|
461
|
+
link to the current address, a recent email-link sign-in, or a `rer signin`
|
|
462
|
+
link). It revokes unused links sent to the old address and keeps sessions and
|
|
463
|
+
provider bindings. An address another operator holds is refused with
|
|
464
|
+
`email_in_use`. `STEP_UP_ACTIONS` gains `email:change`.
|
|
465
|
+
|
|
429
466
|
## Local dev identity and the key gate
|
|
430
467
|
|
|
431
468
|
`dev-gate.mjs` (exported as `devGate`, production-safe) is the per-checkout key
|
|
@@ -440,8 +477,7 @@ local mode. `admits(request)` accepts the `rer_dev_gate_<port>` cookie (an HMAC
|
|
|
440
477
|
key, so a reset key refuses old cookies) or the key in `x-rer-dev-key` (the rer
|
|
441
478
|
CLI and test harnesses). `exchange(request)` serves `GET /__dev/key` and trades
|
|
442
479
|
the key from the URL fragment, through a same-origin POST, for a host-only
|
|
443
|
-
`HttpOnly; SameSite=Strict; Path=/` cookie.
|
|
444
|
-
with it.
|
|
480
|
+
`HttpOnly; SameSite=Strict; Path=/` cookie.
|
|
445
481
|
|
|
446
482
|
`dev/` is the dev layer: **server-only and local-only**. Import it only from a
|
|
447
483
|
local-only Worker entry (a Vite-serve or local `wrangler dev` entry), never
|
|
@@ -452,19 +488,21 @@ the seed's Worker and serves, behind the gate only:
|
|
|
452
488
|
| Path | Result |
|
|
453
489
|
| --- | --- |
|
|
454
490
|
| `/auth/dev/enter?as=owner\|signed-out\|PERSONA&returnTo=` | Creates or reuses a real `oa_sessions` row of kind `dev` for the configured owner or persona and 303s to `returnTo` (default `/app`); `signed-out` revokes the current session. |
|
|
491
|
+
| `POST /auth/local/cli-session` | Owner-side tooling proves possession of the session secret with `x-rer-local-cli`; exact loopback and origin checks precede issuing a native owner session and fresh local proof. This route exists only in the dev entry. |
|
|
455
492
|
| `/__dev/personas` | `[{as,email,role?}]`, used by `rer dev` for `RER_SIGNED_IN`. |
|
|
456
493
|
|
|
457
494
|
`personas()` returns the seed's `devPersonas()`: `[{as, role, displayName?}]`,
|
|
458
495
|
real operators at `<as>@dev.localhost` created only by dev sign-in. Dev
|
|
459
496
|
sessions pass the same version fences, revocation, deactivation and allow-list
|
|
460
|
-
as every other session.
|
|
497
|
+
as every other session. An admitted local dev session also confirms sensitive
|
|
498
|
+
actions directly, so dev never waits for an email step-up link. The core admits a `dev` session, and any credential
|
|
461
499
|
minted while using one (`oa_dev_credentials`, today an invitation link, whose
|
|
462
500
|
confirmation then yields a `dev` session), only when the dev layer's
|
|
463
501
|
registered check passes for that request; a production Worker never registers
|
|
464
|
-
one. HTML documents gain
|
|
465
|
-
document
|
|
466
|
-
document
|
|
467
|
-
dev sign-in and personas
|
|
502
|
+
one. HTML documents gain the Dev suffix on product labels marked with
|
|
503
|
+
`data-rer-name` and document titles; a demo receives Demo instead. The dedicated
|
|
504
|
+
`/__dev/key` document exchanges the RER_OPEN fragment without placing the key in
|
|
505
|
+
request URLs. `RER_DEV_IDENTITY=off` disables dev sign-in and personas. The
|
|
468
506
|
layer answers 503 to every request when `RER_INSTALLATION_ID` is set beside a
|
|
469
507
|
non-loopback `RER_MANAGEMENT_ORIGIN`.
|
|
470
508
|
|
|
@@ -593,6 +631,12 @@ requesting email links. The reference applies them as
|
|
|
593
631
|
(`createOidcClient`) is replaced by `config.providers`; its existing bindings keep
|
|
594
632
|
signing in once the same issuer is configured as a provider.
|
|
595
633
|
|
|
634
|
+
**Owner sign-in links.** `rer signin` needs `oa_owner_signins`: apply
|
|
635
|
+
`accounts/schema/owner-signin.sql` as a new numbered migration (additive, safe
|
|
636
|
+
after the fresh schema; the reference applies it as
|
|
637
|
+
`migrations/core/0024_owner_signin.sql`). Only the owner-signin route reads it;
|
|
638
|
+
until it exists, `rer signin` refuses before writing anything.
|
|
639
|
+
|
|
596
640
|
Seeds copy this module at different revisions, and an older copy lacks the
|
|
597
641
|
cancellation migration and the optional OIDC and conformance files. Check each
|
|
598
642
|
seed's present source and applied migrations before adopting. A seed owns its
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// A signed-in operator changes their own sign-in email. It needs a fresh proof
|
|
2
|
+
// (a step-up, the email-link sign-in that opened this session, or a `rer signin`
|
|
3
|
+
// owner link) and fences the change to this session and operator version. Links
|
|
4
|
+
// already sent to the old address stop working; sessions and bindings stay.
|
|
5
|
+
import { deny } from '../errors.mjs';
|
|
6
|
+
import { requirePost } from '../http.mjs';
|
|
7
|
+
import { normalizeEmail } from '../policy.mjs';
|
|
8
|
+
import { emailAllowed } from './roles.mjs';
|
|
9
|
+
|
|
10
|
+
export function emailChange({ config, store, clock, authenticate, requireFreshProof }) {
|
|
11
|
+
return {
|
|
12
|
+
async changeEmail(request, input) {
|
|
13
|
+
requirePost(request, config);
|
|
14
|
+
const actor = await authenticate(request);
|
|
15
|
+
if (!actor) deny('unauthenticated', 401);
|
|
16
|
+
const email = normalizeEmail(input?.email);
|
|
17
|
+
if (!emailAllowed(email, config.allowList)) deny('email_not_allowed');
|
|
18
|
+
await requireFreshProof(actor);
|
|
19
|
+
if (email !== actor.operator.email) {
|
|
20
|
+
const now = clock(), fence = store.actorFence(actor, now);
|
|
21
|
+
let changed;
|
|
22
|
+
try {
|
|
23
|
+
[changed] = await store.batch([
|
|
24
|
+
[`UPDATE oa_operators SET email=? WHERE id=? AND version=? AND ${fence.sql}`, [email, actor.operator.id, actor.operator.version, ...fence.args]],
|
|
25
|
+
['UPDATE oa_tokens SET revoked_at=? WHERE operator_id=? AND consumed_at IS NULL AND revoked_at IS NULL AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND email=?)',
|
|
26
|
+
[now, actor.operator.id, actor.operator.id, email]],
|
|
27
|
+
]);
|
|
28
|
+
} catch (error) { if (/UNIQUE/.test(String(error))) deny('email_in_use', 409); throw error; }
|
|
29
|
+
if (changed.meta.changes !== 1) deny('authority_changed', 409);
|
|
30
|
+
}
|
|
31
|
+
return store.operator(actor.operator.id);
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// The owner's way in without mail: a one-time link `rer signin` minted with the
|
|
2
|
+
// deployment's own Cloudflare credentials (see ../owner-signin-grant.mjs). The
|
|
3
|
+
// grant names the owner and its version; it admits only that operator while it
|
|
4
|
+
// is still the active owner, once, before it expires, and never longer than
|
|
5
|
+
// OWNER_SIGNIN_SECONDS from now whatever the minting clock said. The session it
|
|
6
|
+
// opens counts as a fresh step-up proof, so the owner can correct a wrong email.
|
|
7
|
+
import { deny } from '../errors.mjs';
|
|
8
|
+
import { validToken } from '../crypto.mjs';
|
|
9
|
+
import { requireOrigin, requirePost } from '../http.mjs';
|
|
10
|
+
import { safeReturnTo } from '../policy.mjs';
|
|
11
|
+
import { OWNER_SIGNIN_SECONDS, ownerSigninDigest } from '../owner-signin-grant.mjs';
|
|
12
|
+
|
|
13
|
+
export function ownerSignIn({ config, store, clock, sessions, limit }) {
|
|
14
|
+
const live = `g.token_hash=? AND g.consumed_at IS NULL AND g.expires_at>? AND g.expires_at<=? AND g.operator_version=o.version
|
|
15
|
+
AND o.role='owner' AND o.status='active'`;
|
|
16
|
+
const allowed = () => config.allowList === undefined ? { sql: '1', args: [] } : { sql: `o.email IN (${config.allowList.map(() => '?').join(',') || 'NULL'})`, args: config.allowList };
|
|
17
|
+
return {
|
|
18
|
+
async previewOwnerSignIn(request, token) {
|
|
19
|
+
requireOrigin(request, config);
|
|
20
|
+
if (!validToken(token)) return null;
|
|
21
|
+
const now = clock(), allow = allowed();
|
|
22
|
+
const grant = await store.first(`SELECT g.expires_at AS expiresAt FROM oa_owner_signins g JOIN oa_operators o ON o.id=g.operator_id WHERE ${live} AND ${allow.sql}`,
|
|
23
|
+
[await ownerSigninDigest(token), now, now + OWNER_SIGNIN_SECONDS * 1000, ...allow.args]);
|
|
24
|
+
return grant ? { kind: 'owner', expiresInMinutes: Math.max(1, Math.ceil((grant.expiresAt - now) / 60000)) } : null;
|
|
25
|
+
},
|
|
26
|
+
async confirmOwnerSignIn(request, { token }) {
|
|
27
|
+
requirePost(request, config);
|
|
28
|
+
// Keyed per token like /auth/confirm: bad guesses cannot spend the owner's own attempts.
|
|
29
|
+
await limit(request, typeof token === 'string' ? `owner-signin:${token.slice(0, 128)}` : '', 'confirmation');
|
|
30
|
+
if (!validToken(token)) deny('invalid_or_expired', 400);
|
|
31
|
+
const digest = await ownerSigninDigest(token), now = clock(), allow = allowed();
|
|
32
|
+
const session = await sessions.newSession();
|
|
33
|
+
// One transaction: the session, the grant's consumption, the owner's audit
|
|
34
|
+
// record and the step-up proof stand or fall together.
|
|
35
|
+
await store.batch([
|
|
36
|
+
[`INSERT INTO oa_sessions(id,token_hash,operator_id,operator_version,kind,created_at,expires_at)
|
|
37
|
+
SELECT ?,?,o.id,o.version,'native',?,? FROM oa_owner_signins g JOIN oa_operators o ON o.id=g.operator_id WHERE ${live} AND ${allow.sql}`,
|
|
38
|
+
[session.id, session.hash, now, session.expiresAt, digest, now, now + OWNER_SIGNIN_SECONDS * 1000, ...allow.args]],
|
|
39
|
+
['UPDATE oa_owner_signins SET consumed_at=? WHERE token_hash=? AND consumed_at IS NULL AND EXISTS(SELECT 1 FROM oa_sessions WHERE id=?)', [now, digest, session.id]],
|
|
40
|
+
[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,s.operator_id,'owner:signin-link',g.id,? FROM oa_sessions s
|
|
41
|
+
JOIN oa_owner_signins g ON g.token_hash=? AND g.consumed_at=? WHERE s.id=?`, [crypto.randomUUID(), now, digest, now, session.id]],
|
|
42
|
+
[`INSERT INTO oa_step_up_challenges(id,token_hash,session_id,operator_id,operator_version,action,return_to,created_at,expires_at,consumed_at)
|
|
43
|
+
SELECT ?,?,id,operator_id,operator_version,'owner:signin-link','/',?,?,? FROM oa_sessions WHERE id=?`, [crypto.randomUUID(), `owner-signin:${session.id}`, now, now, now, session.id]],
|
|
44
|
+
]);
|
|
45
|
+
const record = await store.session(session.hash, now);
|
|
46
|
+
if (!record) deny('invalid_or_expired', 400);
|
|
47
|
+
return sessions.completed(session, record, safeReturnTo(undefined));
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
-- One-time owner sign-in links minted by `rer signin` with the deployment's own
|
|
2
|
+
-- Cloudflare credentials, written straight into this table through the D1 API.
|
|
3
|
+
-- Apply as a NEW numbered migration under the seed's next unused number; never
|
|
4
|
+
-- rewrite an applied migration. Additive only. token_hash is the SHA-256 of the
|
|
5
|
+
-- link token (owner-signin-grant.mjs); the token itself is never stored.
|
|
6
|
+
CREATE TABLE IF NOT EXISTS oa_owner_signins (
|
|
7
|
+
id TEXT PRIMARY KEY, token_hash TEXT NOT NULL UNIQUE,
|
|
8
|
+
operator_id TEXT NOT NULL REFERENCES oa_operators(id), operator_version INTEGER NOT NULL,
|
|
9
|
+
created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, consumed_at INTEGER
|
|
10
|
+
);
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
// Inline
|
|
2
|
-
// the demo bar each add one hashed style without loosening anything else.
|
|
1
|
+
// Inline product labels add exact CSP hashes without broadening other sources.
|
|
3
2
|
|
|
4
3
|
/** The CSP source token for an exact inline text. */
|
|
5
4
|
export async function sha256(text) {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { isLocalCli } from '../local-cli.mjs';
|
|
2
|
+
import { requireLoopback, requirePost, sessionCookie } from '../http.mjs';
|
|
3
|
+
import { opaqueToken } from '../crypto.mjs';
|
|
4
|
+
import { safeReturnTo } from '../policy.mjs';
|
|
5
|
+
import { isActiveOperator } from '../accounts/roles.mjs';
|
|
6
|
+
import { AuthError } from '../errors.mjs';
|
|
7
|
+
import { devNotFound } from '../dev-gate.mjs';
|
|
8
|
+
import { readInput } from '../input.mjs';
|
|
9
|
+
|
|
10
|
+
// Owner-side local tooling proves possession of this installation's session
|
|
11
|
+
// secret. This endpoint exists only in the local dev entry, never production.
|
|
12
|
+
export async function cliSession(request, { config, store, hash, everyone }, headers) {
|
|
13
|
+
requireLoopback(request);
|
|
14
|
+
requirePost(request, config);
|
|
15
|
+
if (!await isLocalCli(request, config)) return devNotFound();
|
|
16
|
+
const input = await readInput(request);
|
|
17
|
+
const ownerEmail = (await everyone()).find(persona => persona.as === 'owner')?.email;
|
|
18
|
+
const operator = ownerEmail ? await store.byEmail(ownerEmail) : null;
|
|
19
|
+
if (operator?.role !== 'owner' || !isActiveOperator(operator, config.allowList)) throw new AuthError('owner_required', 403);
|
|
20
|
+
const now = Date.now(), token = opaqueToken();
|
|
21
|
+
const session = { id: crypto.randomUUID(), hash: await hash(token), expiresAt: now + config.sessionSeconds * 1000 };
|
|
22
|
+
const record = await store.issue({ operatorId: operator.id, expectedVersion: operator.version, session, now, kind: 'native' });
|
|
23
|
+
if (!record || record.operator.role !== 'owner') throw new AuthError('authority_changed', 409);
|
|
24
|
+
// A local owner proof uses the existing durable, version-fenced proof ledger.
|
|
25
|
+
// It can authorize setup linking without manufacturing an email credential.
|
|
26
|
+
const inserted = await store.run(`INSERT INTO oa_step_up_challenges(id,token_hash,session_id,operator_id,operator_version,action,return_to,created_at,expires_at,consumed_at)
|
|
27
|
+
SELECT ?,?,?,?,?,?,?,?,?,? WHERE EXISTS(SELECT 1 FROM oa_sessions s JOIN oa_operators o ON o.id=s.operator_id
|
|
28
|
+
WHERE s.id=? AND s.revoked_at IS NULL AND o.role='owner' AND o.status='active' AND o.version=?)`,
|
|
29
|
+
[crypto.randomUUID(), await hash(opaqueToken()), record.id, operator.id, operator.version, 'local-cli', '/', now, session.expiresAt, now, record.id, operator.version]);
|
|
30
|
+
if (inserted.meta.changes !== 1) throw new AuthError('authority_changed', 409);
|
|
31
|
+
return new Response(null, { status: 303, headers: { ...headers, location: safeReturnTo(input.returnTo), 'set-cookie': sessionCookie(token, config) } });
|
|
32
|
+
}
|
|
@@ -7,13 +7,15 @@ import { AuthStore } from '../accounts/store.mjs';
|
|
|
7
7
|
import { createOperatorAuth } from '../service.mjs';
|
|
8
8
|
import { AuthError } from '../errors.mjs';
|
|
9
9
|
import { hashToken, opaqueToken } from '../crypto.mjs';
|
|
10
|
-
import { readCookie, sessionCookie, isLoopbackHost } from '../http.mjs';
|
|
10
|
+
import { readCookie, sessionCookie, isLoopbackHost, escapeHtml } from '../http.mjs';
|
|
11
11
|
import { safeReturnTo } from '../policy.mjs';
|
|
12
12
|
import { isActiveOperator, defaultRolePolicy } from '../accounts/roles.mjs';
|
|
13
13
|
import { devGate, devNotFound } from '../dev-gate.mjs';
|
|
14
14
|
import { registerDevAdmission } from '../dev-admission.mjs';
|
|
15
15
|
import { definePersonas } from './personas.mjs';
|
|
16
|
-
import {
|
|
16
|
+
import { cliSession } from './cli-session.mjs';
|
|
17
|
+
import { decorateLabel } from '../../demo/label.mjs';
|
|
18
|
+
import { pageResponse } from '../page.mjs';
|
|
17
19
|
|
|
18
20
|
export const DEV_LAYER_MARKER = 'rer-dev-layer:local-only-never-deploy';
|
|
19
21
|
const headers = { 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff', 'x-robots-tag': 'noindex, nofollow', 'x-rer-dev-layer': DEV_LAYER_MARKER };
|
|
@@ -28,7 +30,7 @@ export function managedInstallation(env) {
|
|
|
28
30
|
|
|
29
31
|
/**
|
|
30
32
|
* Wraps a seed's Worker with dev sign-in (`/auth/dev/enter?as=…`), the persona
|
|
31
|
-
* list (`/__dev/personas`)
|
|
33
|
+
* list (`/__dev/personas`). Every identity surface needs the key
|
|
32
34
|
* gate and answers 404 without it. `config(env)` is the seed's own AuthConfig
|
|
33
35
|
* and `personas()` its devPersonas() declaration.
|
|
34
36
|
*/
|
|
@@ -42,16 +44,24 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
|
|
|
42
44
|
// Never admit a dev credential here; with dev identity on, serve nothing.
|
|
43
45
|
registerDevAdmission(null);
|
|
44
46
|
if (env.RER_DEV_IDENTITY !== 'off') return rejectedResponse(request, text(503, 'Dev identity refuses to run beside RER_INSTALLATION_ID with a non-loopback RER_MANAGEMENT_ORIGIN. Remove those bindings from local settings or use rer dev --login.'));
|
|
45
|
-
return new URL(request.url).pathname === '/auth/dev/enter' || new URL(request.url).pathname === '/__dev/personas' ? rejectedResponse(request, devNotFound()) : worker.fetch(request, original, execution);
|
|
47
|
+
return new URL(request.url).pathname === '/auth/dev/enter' || new URL(request.url).pathname === '/__dev/personas' || new URL(request.url).pathname === '/auth/local/cli-session' ? rejectedResponse(request, devNotFound()) : worker.fetch(request, original, execution);
|
|
46
48
|
}
|
|
47
49
|
const gate = devGate({ key: env.RER_DEV_KEY, origin: env.AUTH_ORIGIN, local: env.AUTH_LOCAL === 'true' });
|
|
48
50
|
registerDevAdmission(gate ? r => gate.admits(r) : null);
|
|
49
51
|
const path = new URL(request.url).pathname;
|
|
50
|
-
if (path === '/
|
|
51
|
-
|
|
52
|
+
if (path === '/__dev/key') return gate ? gate.exchange(request) : devNotFound();
|
|
53
|
+
if (path === '/signin' && gate && env.RER_DEV_IDENTITY !== 'off' && request.method === 'GET') {
|
|
54
|
+
if (!await gate.admits(request)) return new Response(null, { status: 303, headers: { ...headers, location: '/__dev/key' } });
|
|
55
|
+
const { config } = identity(env, authConfig, declared);
|
|
56
|
+
const returnTo = safeReturnTo(new URL(request.url).searchParams.get('returnTo'));
|
|
57
|
+
const href = `/auth/dev/enter?as=owner&returnTo=${encodeURIComponent(returnTo)}`;
|
|
58
|
+
return decorateLabel(await pageResponse({ branding: config.branding, heading: 'Open your local app', content: `<a class="action" href="${escapeHtml(href)}">Continue as owner</a>` }), env.RER_DEMO === '1' ? 'Demo' : 'Dev');
|
|
59
|
+
}
|
|
60
|
+
if (path === '/auth/dev/enter' || path === '/__dev/personas' || path === '/auth/local/cli-session') {
|
|
61
|
+
if (!gate || env.RER_DEV_IDENTITY === 'off' || (path !== '/auth/local/cli-session' && !await gate.admits(request))) return rejectedResponse(request, devNotFound());
|
|
52
62
|
const context = identity(env, authConfig, declared);
|
|
53
63
|
try {
|
|
54
|
-
const response = path === '/__dev/personas' ? Response.json(await context.list(), { headers }) : await enter(request, gate, context);
|
|
64
|
+
const response = path === '/auth/local/cli-session' ? await cliSession(request, context, headers) : path === '/__dev/personas' ? Response.json(await context.list(), { headers }) : await enter(request, gate, context);
|
|
55
65
|
return rejectedResponse(request, response);
|
|
56
66
|
} catch (error) {
|
|
57
67
|
if (error instanceof AuthError) return rejectedResponse(request, Response.json({ error: error.code }, { status: error.status, headers }));
|
|
@@ -60,9 +70,7 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
|
|
|
60
70
|
}
|
|
61
71
|
const response = await worker.fetch(request, original, execution);
|
|
62
72
|
if (!gate || request.method !== 'GET' || path.startsWith('/__dev/')) return response;
|
|
63
|
-
|
|
64
|
-
const badge = admitted && env.RER_DEV_IDENTITY !== 'off' ? await identity(env, authConfig, declared).badge(request) : null;
|
|
65
|
-
return decorate(response, { exchange: path === '/', badge });
|
|
73
|
+
return decorateLabel(response, env.RER_DEMO === '1' ? 'Demo' : 'Dev');
|
|
66
74
|
},
|
|
67
75
|
};
|
|
68
76
|
}
|
|
@@ -97,7 +105,6 @@ function identity(env, authConfig, declared) {
|
|
|
97
105
|
return { ...actor, hash: await hash(readCookie(request, config)) };
|
|
98
106
|
},
|
|
99
107
|
list: async () => [...(await everyone()).map(({ as, email, role }) => ({ as, email, ...(role ? { role } : {}) })), { as: 'signed-out' }],
|
|
100
|
-
async badge(request) { return { session: await current(request), choices: (await everyone()).filter(persona => persona.email) }; },
|
|
101
108
|
};
|
|
102
109
|
}
|
|
103
110
|
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { escapeHtml } from '../../http.mjs';
|
|
2
2
|
import { pageResponse } from '../../page.mjs';
|
|
3
3
|
|
|
4
|
-
const HEADINGS = { invite: 'Accept your invitation to', magic: 'Confirm sign-in to', step_up: "Confirm it's you in" };
|
|
4
|
+
const HEADINGS = { invite: 'Accept your invitation to', magic: 'Confirm sign-in to', step_up: "Confirm it's you in", owner: 'Sign in as the owner of' };
|
|
5
5
|
|
|
6
|
-
export async function confirmationResponse({ branding, preview, token, method }) {
|
|
6
|
+
export async function confirmationResponse({ branding, preview, token, method, action = '/auth/confirm' }) {
|
|
7
7
|
const product = escapeHtml(branding.productName);
|
|
8
8
|
const heading = preview ? `${HEADINGS[preview.kind]} ${product}` : 'This link is invalid or expired';
|
|
9
9
|
const content = preview
|
|
10
|
-
? `<p>This link works once and expires in ${preview.expiresInMinutes} ${preview.expiresInMinutes === 1 ? 'minute' : 'minutes'}.</p><form method="post" action="
|
|
10
|
+
? `<p>This link works once and expires in ${preview.expiresInMinutes} ${preview.expiresInMinutes === 1 ? 'minute' : 'minutes'}.</p><form method="post" action="${escapeHtml(action)}"><input type="hidden" name="token" value="${escapeHtml(token)}"><button type="submit">Confirm</button></form>`
|
|
11
11
|
: `<p>This link may have expired or already been used. Request a new link to continue.</p><a class="action" href="${escapeHtml(branding.signInPath)}">Request a new link</a>`;
|
|
12
12
|
// Native form POSTs need their Origin; never disclose the token path/query.
|
|
13
13
|
return pageResponse({ branding, heading, content, status: preview ? 200 : 400, method, referrer: preview ? 'strict-origin' : undefined });
|
|
@@ -7,7 +7,7 @@ import { isActiveOperator } from '../../accounts/roles.mjs';
|
|
|
7
7
|
import { isLocalCli } from '../../local-cli.mjs';
|
|
8
8
|
import { linkMessage } from './message.mjs';
|
|
9
9
|
import { completionHook } from '../after-confirm.mjs';
|
|
10
|
-
export const STEP_UP_ACTIONS = Object.freeze(['providers:unlink', 'providers:relink', 'domains:change', 'owner:transfer', 'export', 'delete', 'credentials:mint']);
|
|
10
|
+
export const STEP_UP_ACTIONS = Object.freeze(['providers:unlink', 'providers:relink', 'domains:change', 'owner:transfer', 'export', 'delete', 'credentials:mint', 'email:change']);
|
|
11
11
|
export const STEP_UP_SECONDS = 600;
|
|
12
12
|
|
|
13
13
|
// Persistence owns the atomic authority check, proof consumption and session
|
|
@@ -55,6 +55,9 @@ export function createEmailLinkLifecycle({ config: input, clock = Date.now, mail
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
async function requireFreshProof(actor) {
|
|
58
|
+
// Authentication already required the local key gate for this session.
|
|
59
|
+
// Dev confirms actions directly rather than sending an unusable mail link.
|
|
60
|
+
if (config.local && actor.kind === 'dev') return;
|
|
58
61
|
if (!await store.steppedUp(actor, clock() - STEP_UP_SECONDS * 1000, clock())) deny('step_up_required', 403);
|
|
59
62
|
}
|
|
60
63
|
const authenticate = request => store.authenticate(request);
|
|
@@ -7,10 +7,10 @@ export interface MailMessage { deliveryId: string; from: string; to: string[]; s
|
|
|
7
7
|
export interface MailSender { send(message: MailMessage): Promise<{ status: 'accepted' | 'rejected' | 'rate_limited' | 'uncertain' | 'development'; provider: string; providerMessageId: string | null; code?: string }> }
|
|
8
8
|
export interface AuthBranding { productName?: string; accentColor?: string; signInPath?: string; /** Same-origin path of the seed's served rer-theme.css. */ theme?: string }
|
|
9
9
|
export interface AuthPresentation { readonly productName: string; readonly accentColor: string; readonly signInPath: string; readonly theme?: string }
|
|
10
|
-
export interface LinkPreview { kind: 'magic' | 'invite' | 'step_up'; expiresInMinutes: number }
|
|
10
|
+
export interface LinkPreview { kind: 'magic' | 'invite' | 'step_up' | 'owner'; expiresInMinutes: number }
|
|
11
11
|
/** A step-up confirmation proves the session's operator again; it issues no new session. */
|
|
12
12
|
export interface StepUpConfirmed { stepUp: StepUpAction; returnTo: string; cookie?: undefined }
|
|
13
|
-
export type StepUpAction = 'providers:unlink' | 'providers:relink' | 'domains:change' | 'owner:transfer' | 'export' | 'delete' | 'credentials:mint';
|
|
13
|
+
export type StepUpAction = 'providers:unlink' | 'providers:relink' | 'domains:change' | 'owner:transfer' | 'export' | 'delete' | 'credentials:mint' | 'email:change';
|
|
14
14
|
export const STEP_UP_ACTIONS: readonly StepUpAction[];
|
|
15
15
|
export type ProviderPreset = 'auth' | 'google' | 'microsoft' | 'okta' | 'legacy-rs256';
|
|
16
16
|
/** One identity provider. Secrets and the private key are server bindings, never source text. */
|
|
@@ -183,6 +183,12 @@ export interface OperatorAuth<R extends string = Role> {
|
|
|
183
183
|
requestStepUp(request: Request, input: { action: StepUpAction; returnTo?: string }): Promise<{ status: 'accepted' }>;
|
|
184
184
|
/** Refuse unless this session holds a fresh (10-minute) app-local email-link proof. Provider sessions never do by themselves. */
|
|
185
185
|
requireStepUp(request: Request, action: StepUpAction): Promise<Session<R>>;
|
|
186
|
+
/** The `rer signin` owner link (GET /auth/owner-signin): its preview, or null when invalid, used, expired or not the active owner's. Absent with native accounts. */
|
|
187
|
+
previewOwnerSignIn?(request: Request, token: string | null): Promise<LinkPreview | null>;
|
|
188
|
+
/** Consume the owner link once; records 'owner:signin-link' in oa_auth_audit and counts as a fresh step-up. */
|
|
189
|
+
confirmOwnerSignIn?(request: Request, input: { token: string }): Promise<CompletedSession<R>>;
|
|
190
|
+
/** The signed-in operator's own sign-in email; needs a fresh step-up proof. */
|
|
191
|
+
changeEmail?(request: Request, input: { email: string }): Promise<Operator<R>>;
|
|
186
192
|
listDomainRules(request: Request): Promise<DomainRule[]>;
|
|
187
193
|
/** provider null lifts the rule. Needs a fresh step-up proof. */
|
|
188
194
|
setDomainRule(request: Request, input: { domain: string; provider: string | null }): Promise<DomainRule[]>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The one-time owner sign-in link that `rer signin` mints with the deployment's
|
|
2
|
+
// own Cloudflare credentials. rer writes the grant straight into the auth D1
|
|
3
|
+
// (accounts/schema/owner-signin.sql) and prints the link once; the Worker
|
|
4
|
+
// consumes it (accounts/owner-signin.mjs). Only this digest is stored.
|
|
5
|
+
export const OWNER_SIGNIN_SECONDS = 900;
|
|
6
|
+
export const OWNER_SIGNIN_PATH = '/auth/owner-signin';
|
|
7
|
+
export async function ownerSigninDigest(token) {
|
|
8
|
+
const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`owner-signin\0${token}`));
|
|
9
|
+
return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
10
|
+
}
|
|
@@ -23,7 +23,7 @@ export async function pageResponse({ branding, title, heading, content, status =
|
|
|
23
23
|
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(css)));
|
|
24
24
|
const hash = btoa(String.fromCharCode(...digest));
|
|
25
25
|
const product = escapeHtml(branding.productName);
|
|
26
|
-
const html = `<!doctype html><html lang="en"${branding.theme ? ' class="rer-themed"' : ''}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title ?? heading}</title>${branding.theme ? `<link rel="stylesheet" href="${escapeHtml(branding.theme)}">` : ''}<style>${css}</style></head><body><main><p class="brand"><span class="mark" aria-hidden="true"></span>${product}</p><h1>${heading}</h1>${content}</main></body></html>`;
|
|
26
|
+
const html = `<!doctype html><html lang="en"${branding.theme ? ' class="rer-themed"' : ''}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title ?? heading}</title>${branding.theme ? `<link rel="stylesheet" href="${escapeHtml(branding.theme)}">` : ''}<style>${css}</style></head><body><main><p class="brand"><span class="mark" aria-hidden="true"></span><span data-rer-name>${product}</span></p><h1>${heading}</h1>${content}</main></body></html>`;
|
|
27
27
|
const headers = { ...securityHeaders(), 'Content-Type': 'text/html; charset=utf-8' };
|
|
28
28
|
// A form may post to this origin only, plus any origin its own redirect must reach (a provider's authorization endpoint).
|
|
29
29
|
if (formTargets.length) headers['Content-Security-Policy'] = headers['Content-Security-Policy'].replace("form-action 'self'", `form-action 'self' ${formTargets.join(' ')}`);
|
|
@@ -6,6 +6,7 @@ import { AuthError } from './errors.mjs';
|
|
|
6
6
|
import { securityHeaders, requireLoopback } from './http.mjs';
|
|
7
7
|
import { safeReturnTo } from './policy.mjs';
|
|
8
8
|
import { readInput, readParameters } from './input.mjs';
|
|
9
|
+
import { OWNER_SIGNIN_PATH } from './owner-signin-grant.mjs';
|
|
9
10
|
function json(value, status = 200) { return Response.json(value, { status, headers: securityHeaders() }); }
|
|
10
11
|
function seeOther(location, cookie) { return new Response(null, { status: 303, headers: { ...securityHeaders(), ...(cookie ? { 'Set-Cookie': cookie } : {}), Location: location } }); }
|
|
11
12
|
// A native HTML form (the sign-in page before any script) gets a page back; an
|
|
@@ -36,6 +37,13 @@ export function createAuthHandler(auth) {
|
|
|
36
37
|
const preview = await auth.previewLink(request, token);
|
|
37
38
|
return await confirmationResponse({ branding: auth.presentation, preview, token, method: request.method });
|
|
38
39
|
}
|
|
40
|
+
// Composition without the owner link or email change (native accounts) does not own these paths.
|
|
41
|
+
if ((path === OWNER_SIGNIN_PATH && !auth.confirmOwnerSignIn) || (path === '/auth/email' && !auth.changeEmail)) return json({ error: 'not_found' }, 404);
|
|
42
|
+
if (path === OWNER_SIGNIN_PATH && ['GET', 'HEAD'].includes(request.method)) {
|
|
43
|
+
const token = readParameters(url.searchParams).token ?? null;
|
|
44
|
+
const preview = await auth.previewOwnerSignIn(request, token);
|
|
45
|
+
return await confirmationResponse({ branding: auth.presentation, preview, token, method: request.method, action: OWNER_SIGNIN_PATH });
|
|
46
|
+
}
|
|
39
47
|
if (path === '/auth/session' && request.method === 'GET') {
|
|
40
48
|
const session = await auth.getSession(request);
|
|
41
49
|
return session ? json(session) : json({ error: 'unauthenticated' }, 401);
|
|
@@ -46,7 +54,7 @@ export function createAuthHandler(auth) {
|
|
|
46
54
|
if (path === '/auth/settings/identity' && request.method === 'GET') {const value=await auth.identitySettings(request);return /text\/html/.test(request.headers.get('accept')??'')?await identitySettingsPage(value,auth.presentation):json(value);}
|
|
47
55
|
if (path === '/auth/providers' && request.method === 'GET') return json(await auth.listProviders(request));
|
|
48
56
|
const posts = new Set(['/auth/bootstrap', '/auth/magic-link', '/auth/confirm', '/auth/signout', '/auth/invite', '/auth/invite/cancel', '/auth/review-session',
|
|
49
|
-
'/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete']);
|
|
57
|
+
'/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email']);
|
|
50
58
|
if (!posts.has(path)) return json({ error: 'not_found' }, 404);
|
|
51
59
|
if (request.method !== 'POST') return json({ error: 'method_not_allowed' }, 405);
|
|
52
60
|
const query = readParameters(url.searchParams);
|
|
@@ -64,6 +72,8 @@ export function createAuthHandler(auth) {
|
|
|
64
72
|
return form ? seeOther(notice(auth, 'sent', { returnTo: safeReturnTo(input.returnTo) === '/app' ? undefined : safeReturnTo(input.returnTo), provider: result.requiredProvider })) : json(result, 202);
|
|
65
73
|
}
|
|
66
74
|
case '/auth/confirm': { const value = await auth.confirmLink(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
75
|
+
case OWNER_SIGNIN_PATH: { const value = await auth.confirmOwnerSignIn(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
76
|
+
case '/auth/email': return json(await auth.changeEmail(request, input));
|
|
67
77
|
case '/auth/review-session': { const value = await auth.issueReviewSession(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
68
78
|
case '/auth/step-up': {
|
|
69
79
|
const result = await auth.requestStepUp(request, input);
|
|
@@ -16,6 +16,8 @@ import { emailAllowed, isActiveOperator, defaultRolePolicy } from './accounts/ro
|
|
|
16
16
|
import { oaSessions, createOaAccounts } from './accounts/oa.mjs';
|
|
17
17
|
import { createAdmission, legacyAdmission } from './identity/admission.mjs';
|
|
18
18
|
import { createOidcProviders } from './identity/oidc/index.mjs';
|
|
19
|
+
import { ownerSignIn } from './accounts/owner-signin.mjs';
|
|
20
|
+
import { emailChange } from './accounts/email-change.mjs';
|
|
19
21
|
import { isLocalCli } from './local-cli.mjs';
|
|
20
22
|
import { devAdmitted } from './dev-admission.mjs';
|
|
21
23
|
|
|
@@ -74,6 +76,8 @@ export function createOperatorAuth(options) {
|
|
|
74
76
|
...admin,
|
|
75
77
|
...providerControl({ store, accounts, authenticate, config, clock }),
|
|
76
78
|
...fencedCredentials({store,authenticate,requireFreshProof,config,clock,hash}),
|
|
79
|
+
...ownerSignIn({ config, store, clock, sessions, limit }),
|
|
80
|
+
...emailChange({ config, store, clock, authenticate, requireFreshProof }),
|
|
77
81
|
presentation: config.branding,
|
|
78
82
|
emailSignInAvailable: Boolean(mailSender),
|
|
79
83
|
/** Identity providers (null when none is configured): routes, the sign-in page's list and owner actions. */
|
|
@@ -3,7 +3,7 @@ import type { OperatorAuth } from '../index.mjs';
|
|
|
3
3
|
export interface SignInPageOptions {
|
|
4
4
|
/** While the first owner is unclaimed: the setup form and its instructions. */
|
|
5
5
|
setup?: (request: Request) => null | false | undefined | { instructions?: string } | Promise<null | false | undefined | { instructions?: string }>;
|
|
6
|
-
/** Extra same-origin links under the form
|
|
6
|
+
/** Extra same-origin links under the form. */
|
|
7
7
|
links?: (request: Request) => Array<{ href: string; label: string }> | Promise<Array<{ href: string; label: string }>>;
|
|
8
8
|
defaultReturnTo?: string;
|
|
9
9
|
}
|
|
@@ -292,6 +292,10 @@ by table name. Product-only staging keeps restore queries small even with long
|
|
|
292
292
|
column names.
|
|
293
293
|
Advance normalizes the durable snapshot, sorts archived keys and checks attachment
|
|
294
294
|
references again before completing the archive.
|
|
295
|
+
The shared D1 transport preserves mixed-script text through SQLite decoding and
|
|
296
|
+
accounts for workerd's whole-call string width. Snapshot and archive-segment
|
|
297
|
+
reads are bounded before crossing the provider boundary; staging and restore
|
|
298
|
+
transactions remain atomic.
|
|
295
299
|
`exports.advance(id,{expectedPart,maxParts})` commits durable bounded parts;
|
|
296
300
|
`expectedPart` makes a lost-acknowledgement retry a no-op. Status reports progress;
|
|
297
301
|
download streams completed jobs. Abort removes snapshots and stored parts.
|
|
@@ -417,6 +421,8 @@ executes the copied Worker and CLI. Tests and development fixtures are not copie
|
|
|
417
421
|
|
|
418
422
|
```text
|
|
419
423
|
modules/portability/index.mjs
|
|
424
|
+
modules/d1-transport/index.mjs
|
|
425
|
+
modules/d1-transport/index.d.mts
|
|
420
426
|
modules/portability/index.d.mts
|
|
421
427
|
modules/portability/lines.mjs
|
|
422
428
|
modules/portability/hash.mjs
|
|
@@ -52,7 +52,7 @@ export async function catalogue(db,config) {
|
|
|
52
52
|
columns.forEach(c=>{if(c.hidden)c.generated=c.hidden===2?'virtual':'stored';delete c.hidden;});
|
|
53
53
|
// Both archived base cells and visible staging reads must fit D1's SQL
|
|
54
54
|
// limit, with room for copy names and joins.
|
|
55
|
-
insist([false,true].every(encoded=>utf8(projectedColumns({columns},encoded)).length+1024<=100000),'transfer_sql_limit:'+entry.name);
|
|
55
|
+
insist([false,true].every(encoded=>utf8(projectedColumns({columns},encoded)).length+1024+columns.length*64<=100000),'transfer_sql_limit:'+entry.name);
|
|
56
56
|
const dependencies=[...new Set((await all(db,`PRAGMA foreign_key_list(${quote(entry.name)})`)).map(ref=>objects.find(x=>x.type==='table' && identifier(x.name)===identifier(ref.table))?.name??ref.table))].sort();
|
|
57
57
|
for(const parent of dependencies) insist(!excluded.some(x=>x.name===parent),'excluded_foreign_key:'+entry.name+':'+parent);
|
|
58
58
|
const rowidAlias=columns.some(c=>c.pk)?null:['rowid','_rowid_','oid'].find(alias=>!columns.some(c=>c.name.toLowerCase()===alias));
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { all,statement,quote,insist } from './storage.mjs';
|
|
2
2
|
import { projectedColumns,encodedRow,mapRow,bindCell,writableColumns } from './catalogue.mjs';
|
|
3
|
-
import { canonicalJson } from './hash.mjs';
|
|
3
|
+
import { canonicalJson, utf8 } from './hash.mjs';
|
|
4
4
|
import { generatedCopySQL } from './generated.mjs';
|
|
5
5
|
|
|
6
6
|
export const sidecar=copy=>copy+'_meta';
|
|
@@ -10,6 +10,7 @@ export function copyRowid(table) {
|
|
|
10
10
|
}
|
|
11
11
|
const keys=table=>table.columns.filter(c=>c.pk).sort((a,b)=>a.pk-b.pk);
|
|
12
12
|
const order=table=>keys(table).length?keys(table).map(c=>quote(c.name)).join(','):quote(table.rowidAlias);
|
|
13
|
+
const sum=terms=>terms.length<2?(terms[0]??'0'):`(${sum(terms.slice(0,terms.length>>1))}+${sum(terms.slice(terms.length>>1))})`;
|
|
13
14
|
export function createCopy(db,table,copy,snapshot=false) {
|
|
14
15
|
const ordering=order(table),meta=quote(sidecar(copy));
|
|
15
16
|
const columns=writableColumns(table).map(c=>quote(c.name)).join(',');
|
|
@@ -22,7 +23,21 @@ export function createCopy(db,table,copy,snapshot=false) {
|
|
|
22
23
|
}
|
|
23
24
|
export async function readCopy(db,table,copy,offset,limit,encoded=false) {
|
|
24
25
|
const columns=projectedColumns(table,encoded);
|
|
25
|
-
const
|
|
26
|
+
const selected=encoded?writableColumns(table):table.columns;
|
|
27
|
+
const from=`FROM ${quote(copy)} s JOIN ${quote(sidecar(copy))} m ON s.${copyRowid(table)}=m.rer_portability_copy_rowid ORDER BY m.rer_portability_row_order LIMIT ? OFFSET ?`;
|
|
28
|
+
// Read sizes first, never discover a large row by overflowing the RPC result.
|
|
29
|
+
// 12x covers JSON control escapes (6x), binary arrays (4x), and whole-string
|
|
30
|
+
// two-byte workerd serialization. Names and scalar framing count separately.
|
|
31
|
+
const overhead=selected.reduce((n,c)=>n+utf8(c.name).length*12+128,256);
|
|
32
|
+
const weight=sum(selected.map(c=>`COALESCE(length(CAST(s.${quote(c.name)} AS BLOB)),0)`));
|
|
33
|
+
const sizes=await all(db,`SELECT (${weight})*12+${overhead} AS bytes ${from}`,limit,offset);
|
|
34
|
+
const raw=[];
|
|
35
|
+
for(let start=0;start<sizes.length;) {
|
|
36
|
+
let end=start,bytes=0;
|
|
37
|
+
while(end<sizes.length && bytes+sizes[end].bytes<30*1024*1024){bytes+=sizes[end].bytes;end++;}
|
|
38
|
+
insist(end>start,'row_part_too_large:'+table.name);
|
|
39
|
+
raw.push(...await all(db,`SELECT ${columns} ${from}`,end-start,offset+start));start=end;
|
|
40
|
+
}
|
|
26
41
|
const meta=await all(db,`SELECT * FROM ${quote(sidecar(copy))} ORDER BY rer_portability_row_order LIMIT ? OFFSET ?`,limit,offset);
|
|
27
42
|
insist(raw.length===meta.length,'copy_inventory:'+table.name);
|
|
28
43
|
return raw.map((row,i)=>({row,meta:meta[i]}));
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { policy, catalogue } from './catalogue.mjs';
|
|
2
|
+
import { wireDatabase } from '../d1-transport/index.mjs';
|
|
2
3
|
import { insist, job } from './storage.mjs';
|
|
3
4
|
import { createExport, advanceExport, exportStatus, downloadExport, abortExport } from './export.mjs';
|
|
4
5
|
import { createImport, uploadPart, finalizeImport, importStatus, abortImport } from './import.mjs';
|
|
@@ -10,6 +11,7 @@ export { canonicalJson, sha256 } from './hash.mjs';
|
|
|
10
11
|
export { PortabilityError } from './storage.mjs';
|
|
11
12
|
export { createPortabilityHandler } from './http.mjs';
|
|
12
13
|
export async function createPortability({db,buckets={},policy:input,migrations}) {
|
|
14
|
+
db=wireDatabase(db);
|
|
13
15
|
const config=policy(input);await catalogue(db,config);
|
|
14
16
|
for(const name of Object.keys(config.buckets))insist(buckets[name] && typeof buckets[name].get==='function','missing_bucket:'+name);
|
|
15
17
|
const context={db,buckets,config,migrations};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { all, quote, insist } from './storage.mjs';
|
|
2
2
|
import { sidecar, copyRowid } from './copies.mjs';
|
|
3
|
-
const TRANSIENT=['oa_setup_links','rer_dependency_keys','rer_dependency_pending','rer_dependency_codes','oa_provider_sessions','oa_provider_session_pins','oa_oidc_transactions','oa_step_up_challenges','oa_identity_provider_health'];
|
|
3
|
+
const TRANSIENT=['oa_setup_links','rer_dependency_keys','rer_dependency_pending','rer_dependency_codes','oa_provider_sessions','oa_provider_session_pins','oa_oidc_transactions','oa_step_up_challenges','oa_identity_provider_health','oa_owner_signins'];
|
|
4
4
|
// Mandatory secret/session filtering even when a product explicitly includes a table.
|
|
5
5
|
export async function dropProviderData(db,tables,copies) {
|
|
6
6
|
const commands=[];
|
|
@@ -36,7 +36,11 @@ export function partStatements(db,id,part) {
|
|
|
36
36
|
return result;
|
|
37
37
|
}
|
|
38
38
|
export async function readPart(db,id,index) {
|
|
39
|
-
const rows=
|
|
39
|
+
const rows=[];
|
|
40
|
+
for(let offset=0;;offset+=64) {
|
|
41
|
+
const page=await all(db,'SELECT data FROM rer_portability_segments WHERE job=? AND part=? ORDER BY segment LIMIT 64 OFFSET ?',id,index,offset);
|
|
42
|
+
rows.push(...page);if(page.length<64)break;
|
|
43
|
+
}
|
|
40
44
|
insist(rows.length,'part_missing');
|
|
41
45
|
return JSON.parse(rows.map(x=>x.data).join(''));
|
|
42
46
|
}
|