@lago-morph/prototype-framework 0.1.0 → 0.2.0-rc02
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 +4 -2
- package/dist/admin-app/app.d.ts +63 -0
- package/dist/admin-app/app.js +175 -0
- package/dist/admin-app/bundle.d.ts +17 -0
- package/dist/admin-app/bundle.js +51 -0
- package/dist/admin-app/cleanup-page.d.ts +4 -0
- package/dist/admin-app/cleanup-page.js +93 -0
- package/dist/admin-app/config.d.ts +2 -0
- package/dist/admin-app/config.js +51 -0
- package/dist/admin-app/everyday-page.d.ts +2 -0
- package/dist/admin-app/everyday-page.js +71 -0
- package/dist/admin-app/grant.d.ts +63 -0
- package/dist/admin-app/grant.js +138 -0
- package/dist/admin-app/html.d.ts +17 -0
- package/dist/admin-app/html.js +27 -0
- package/dist/admin-app/pages.d.ts +9 -0
- package/dist/admin-app/pages.js +13 -0
- package/dist/admin-app/params.d.ts +11 -0
- package/dist/admin-app/params.js +11 -0
- package/dist/admin-app/scopes.d.ts +11 -0
- package/dist/admin-app/scopes.js +33 -0
- package/dist/admin-app/seal.d.ts +5 -0
- package/dist/admin-app/seal.js +55 -0
- package/dist/admin-app/setup-page.d.ts +8 -0
- package/dist/admin-app/setup-page.js +31 -0
- package/dist/admin-app/status-page.d.ts +12 -0
- package/dist/admin-app/status-page.js +97 -0
- package/dist/admin-app/worker.d.ts +4 -0
- package/dist/admin-app/worker.js +27 -0
- package/dist/auth/auth-app-binding.d.ts +72 -0
- package/dist/auth/auth-app-binding.js +82 -0
- package/dist/auth/auth-app-provider.d.ts +15 -0
- package/dist/auth/auth-app-provider.js +75 -0
- package/dist/auth/login-provider.d.ts +10 -69
- package/dist/auth/login-provider.js +3 -4
- package/dist/auth/return-to.js +8 -4
- package/dist/auth/role-refresh.d.ts +30 -0
- package/dist/auth/role-refresh.js +30 -0
- package/dist/auth/runtime.d.ts +9 -46
- package/dist/auth/runtime.js +62 -74
- package/dist/auth/session.d.ts +14 -2
- package/dist/auth/session.js +24 -9
- package/dist/auth/stub-provider.js +2 -1
- package/dist/auth-app/app.d.ts +11 -0
- package/dist/auth-app/app.js +122 -0
- package/dist/auth-app/config.d.ts +2 -0
- package/dist/auth-app/config.js +50 -0
- package/dist/auth-app/errors.d.ts +8 -0
- package/dist/auth-app/errors.js +12 -0
- package/dist/auth-app/id-token.d.ts +14 -0
- package/dist/auth-app/id-token.js +79 -0
- package/dist/auth-app/params.d.ts +20 -0
- package/dist/auth-app/params.js +20 -0
- package/dist/auth-app/pkce.d.ts +10 -0
- package/dist/auth-app/pkce.js +20 -0
- package/dist/auth-app/roles.d.ts +15 -0
- package/dist/auth-app/roles.js +21 -0
- package/dist/auth-app/schema-gate.d.ts +5 -0
- package/dist/auth-app/schema-gate.js +18 -0
- package/dist/auth-app/service.d.ts +15 -0
- package/dist/auth-app/service.js +26 -0
- package/dist/auth-app/sign-in.d.ts +33 -0
- package/dist/auth-app/sign-in.js +41 -0
- package/dist/auth-app/store.d.ts +67 -0
- package/dist/auth-app/store.js +115 -0
- package/dist/auth-app/upstream.d.ts +49 -0
- package/dist/auth-app/upstream.js +133 -0
- package/dist/auth-app/worker.d.ts +29 -0
- package/dist/auth-app/worker.js +67 -0
- package/dist/build/build.js +1 -1
- package/dist/cli/cloudflare-settings.d.ts +16 -0
- package/dist/cli/cloudflare-settings.js +45 -0
- package/dist/cli/commands/check-login.d.ts +31 -89
- package/dist/cli/commands/check-login.js +94 -324
- package/dist/cli/commands/cloudflare-setup.d.ts +11 -0
- package/dist/cli/commands/cloudflare-setup.js +34 -0
- package/dist/cli/commands/operations.js +4 -1
- package/dist/cli/commands/setup-account.d.ts +2 -3
- package/dist/cli/commands/setup-account.js +2 -5
- package/dist/cli/commands/upgrade.d.ts +42 -0
- package/dist/cli/commands/upgrade.js +176 -0
- package/dist/cli/commands/verify.d.ts +6 -0
- package/dist/cli/commands/verify.js +14 -0
- package/dist/cli/commands/version-check.d.ts +31 -0
- package/dist/cli/commands/version-check.js +127 -0
- package/dist/cli/commands/versions.d.ts +30 -0
- package/dist/cli/commands/versions.js +117 -0
- package/dist/cli/dev/runtime.js +3 -5
- package/dist/cli/main.js +14 -17
- package/dist/cli/wiring.d.ts +12 -2
- package/dist/cli/wiring.js +16 -8
- package/dist/files/base64url.d.ts +6 -2
- package/dist/files/base64url.js +9 -4
- package/dist/kv/cursor.js +3 -1
- package/dist/mig/framework.d.ts +1 -534
- package/dist/mig/framework.js +7 -32
- package/dist/provision/cloudflare/account-settings.d.ts +4 -5
- package/dist/provision/cloudflare/account-settings.js +6 -13
- package/dist/provision/cloudflare/account-setup-run.d.ts +19 -0
- package/dist/provision/cloudflare/account-setup-run.js +114 -0
- package/dist/provision/cloudflare/account.d.ts +20 -2
- package/dist/provision/cloudflare/account.js +65 -31
- package/dist/provision/cloudflare/admin-app-deploy.d.ts +22 -0
- package/dist/provision/cloudflare/admin-app-deploy.js +52 -0
- package/dist/provision/cloudflare/api.d.ts +19 -0
- package/dist/provision/cloudflare/api.js +60 -0
- package/dist/provision/cloudflare/auth-app-deploy.d.ts +44 -0
- package/dist/provision/cloudflare/auth-app-deploy.js +72 -0
- package/dist/provision/cloudflare/backup.d.ts +3 -3
- package/dist/provision/cloudflare/backup.js +5 -10
- package/dist/provision/cloudflare/cloudflare-setup.d.ts +79 -0
- package/dist/provision/cloudflare/cloudflare-setup.js +423 -0
- package/dist/provision/cloudflare/d1/fake-d1-api.d.ts +11 -1
- package/dist/provision/cloudflare/d1/fake-d1-api.js +27 -2
- package/dist/provision/cloudflare/environment.d.ts +5 -1
- package/dist/provision/cloudflare/environment.js +2 -2
- package/dist/provision/cloudflare/everyday-token.d.ts +48 -0
- package/dist/provision/cloudflare/everyday-token.js +139 -0
- package/dist/provision/cloudflare/git-safety.d.ts +31 -0
- package/dist/provision/cloudflare/git-safety.js +113 -0
- package/dist/provision/cloudflare/names.d.ts +6 -0
- package/dist/provision/cloudflare/names.js +6 -0
- package/dist/provision/cloudflare/oauth-clients.d.ts +37 -0
- package/dist/provision/cloudflare/oauth-clients.js +134 -0
- package/dist/provision/cloudflare/permissions.d.ts +165 -0
- package/dist/provision/cloudflare/permissions.js +184 -0
- package/dist/provision/cloudflare/plan.d.ts +5 -2
- package/dist/provision/cloudflare/plan.js +19 -2
- package/dist/provision/cloudflare/r2-token.d.ts +32 -4
- package/dist/provision/cloudflare/r2-token.js +113 -18
- package/dist/provision/cloudflare/secrets-store.d.ts +34 -0
- package/dist/provision/cloudflare/secrets-store.js +60 -0
- package/dist/provision/cloudflare/setup-record.d.ts +40 -0
- package/dist/provision/cloudflare/setup-record.js +101 -0
- package/dist/provision/cloudflare/setup-steps.d.ts +54 -0
- package/dist/provision/cloudflare/setup-steps.js +96 -0
- package/dist/provision/cloudflare/sst.d.ts +23 -2
- package/dist/provision/cloudflare/sst.js +44 -20
- package/dist/provision/cloudflare/target.d.ts +7 -3
- package/dist/provision/cloudflare/target.js +106 -43
- package/dist/provision/cloudflare/{email-permissions.d.ts → token-policies.d.ts} +5 -12
- package/dist/provision/cloudflare/{email-permissions.js → token-policies.js} +6 -21
- package/dist/provision/cloudflare/token-sources.d.ts +60 -0
- package/dist/provision/cloudflare/token-sources.js +184 -0
- package/dist/provision/cloudflare/worker.d.ts +21 -0
- package/dist/provision/cloudflare/worker.js +98 -1
- package/dist/provision/core/account-settings.d.ts +4 -8
- package/dist/provision/core/account-settings.js +4 -8
- package/dist/provision/core/deploy.js +11 -28
- package/dist/provision/core/fake-target.d.ts +10 -18
- package/dist/provision/core/fake-target.js +15 -33
- package/dist/provision/core/local-setup.d.ts +32 -0
- package/dist/provision/core/local-setup.js +134 -0
- package/dist/provision/core/operations.d.ts +20 -30
- package/dist/provision/core/remove.js +10 -1
- package/dist/provision/core/setup-account.d.ts +14 -10
- package/dist/provision/core/setup-account.js +11 -50
- package/dist/provision/public.d.ts +6 -1
- package/dist/provision/public.js +6 -1
- package/dist/secrets/service.d.ts +6 -1
- package/dist/secrets/service.js +10 -1
- package/dist/targets/cloudflare/auth-app.d.ts +15 -0
- package/dist/targets/cloudflare/auth-app.js +33 -0
- package/dist/targets/cloudflare/bindings.d.ts +4 -4
- package/dist/targets/cloudflare/bindings.js +4 -4
- package/dist/targets/cloudflare/public.d.ts +0 -4
- package/dist/targets/cloudflare/public.js +6 -13
- package/dist/targets/cloudflare/settings.d.ts +0 -9
- package/dist/targets/cloudflare/settings.js +7 -22
- package/dist/targets/local/public.js +2 -8
- package/dist/targets/stage.d.ts +9 -13
- package/dist/targets/stage.js +1 -10
- package/dist/testing/auth-app-adapter.d.ts +17 -0
- package/dist/testing/auth-app-adapter.js +17 -0
- package/dist/testing/connect.d.ts +1 -1
- package/dist/testing/connect.js +16 -33
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/public.d.ts +1 -1
- package/dist/testing/test-app.d.ts +50 -12
- package/dist/testing/test-app.js +80 -47
- package/migrations/checksums.json +3 -1
- package/migrations/postgres/0004_drop_auth_mail_tables.sql +11 -0
- package/migrations/postgres/meta/0004_drop_auth_mail_tables.json +81 -0
- package/migrations/sqlite/0004_drop_auth_mail_tables.sql +11 -0
- package/migrations/sqlite/meta/0004_drop_auth_mail_tables.json +79 -0
- package/package.json +8 -5
- package/skill/SKILL.md +67 -0
- package/skill/VERSION +1 -0
- package/skill/examples/admin-and-current-user.md +105 -0
- package/skill/examples/configuration.md +100 -0
- package/skill/examples/endpoint-and-page.md +194 -0
- package/skill/examples/files-tickets.md +152 -0
- package/skill/examples/notes-sql.md +218 -0
- package/skill/examples/secrets.md +209 -0
- package/skill/examples/status-kv.md +74 -0
- package/skill/examples/tests.md +396 -0
- package/skill/reference/configuration.md +62 -0
- package/skill/reference/current-user.md +65 -0
- package/skill/reference/deploying.md +122 -0
- package/skill/reference/files.md +65 -0
- package/skill/reference/http-and-validation.md +91 -0
- package/skill/reference/kv.md +41 -0
- package/skill/reference/local-development.md +73 -0
- package/skill/reference/log.md +54 -0
- package/skill/reference/owner-tasks.md +137 -0
- package/skill/reference/secrets.md +42 -0
- package/skill/reference/sql-and-migrations.md +104 -0
- package/skill/reference/testing/e2e.md +44 -0
- package/skill/reference/testing/failures.md +44 -0
- package/skill/reference/testing/fuzzing.md +28 -0
- package/skill/reference/testing/test-changes.md +42 -0
- package/skill/reference/testing.md +66 -0
- package/skill/reference/troubleshooting.md +134 -0
- package/skill/templates/FRAMEWORK-ISSUE.md +14 -0
- package/skill/templates/README.md +10 -0
- package/skill/templates/production-stage.json +4 -0
- package/dist/auth/password/account.d.ts +0 -12
- package/dist/auth/password/account.js +0 -55
- package/dist/auth/password/bridge.d.ts +0 -37
- package/dist/auth/password/bridge.js +0 -48
- package/dist/auth/password/mail.d.ts +0 -24
- package/dist/auth/password/mail.js +0 -50
- package/dist/auth/password/options.d.ts +0 -80
- package/dist/auth/password/options.js +0 -122
- package/dist/auth/password/pages.d.ts +0 -33
- package/dist/auth/password/pages.js +0 -137
- package/dist/auth/password/provider.d.ts +0 -15
- package/dist/auth/password/provider.js +0 -152
- package/dist/auth/password/routes.d.ts +0 -23
- package/dist/auth/password/routes.js +0 -205
- package/dist/auth/password/tables.d.ts +0 -1488
- package/dist/auth/password/tables.js +0 -175
- package/dist/cli/commands/admins.d.ts +0 -85
- package/dist/cli/commands/admins.js +0 -195
- package/dist/cli/commands/mail.d.ts +0 -14
- package/dist/cli/commands/mail.js +0 -64
- package/dist/mail/capture.d.ts +0 -31
- package/dist/mail/capture.js +0 -80
- package/dist/mail/cloudflare.d.ts +0 -48
- package/dist/mail/cloudflare.js +0 -45
- package/dist/mail/config.d.ts +0 -7
- package/dist/mail/config.js +0 -6
- package/dist/mail/local-files.d.ts +0 -11
- package/dist/mail/local-files.js +0 -37
- package/dist/mail/local.d.ts +0 -36
- package/dist/mail/local.js +0 -30
- package/dist/mail/mime.d.ts +0 -25
- package/dist/mail/mime.js +0 -145
- package/dist/mail/outbox.d.ts +0 -27
- package/dist/mail/outbox.js +0 -34
- package/dist/mail/request.d.ts +0 -18
- package/dist/mail/request.js +0 -21
- package/dist/mail/sender.d.ts +0 -68
- package/dist/mail/sender.js +0 -73
- package/dist/mail/sink-worker.d.ts +0 -22
- package/dist/mail/sink-worker.js +0 -32
- package/dist/mail/test-stage.d.ts +0 -19
- package/dist/mail/test-stage.js +0 -70
- package/dist/provision/cloudflare/email-delivery.d.ts +0 -24
- package/dist/provision/cloudflare/email-delivery.js +0 -60
- package/dist/provision/cloudflare/email.d.ts +0 -80
- package/dist/provision/cloudflare/email.js +0 -395
- package/dist/provision/cloudflare/mail-sink.d.ts +0 -10
- package/dist/provision/cloudflare/mail-sink.js +0 -68
- package/dist/targets/cloudflare/password.d.ts +0 -3
- package/dist/targets/cloudflare/password.js +0 -26
package/README.md
CHANGED
|
@@ -26,9 +26,11 @@ The other subpaths (`/targets/*`, `/provision`, `/check`) are used by the comman
|
|
|
26
26
|
|
|
27
27
|
## Commands
|
|
28
28
|
|
|
29
|
-
Run them in an app's folder as `
|
|
29
|
+
Run them in an app's folder as `npm run <command>` or `npm exec --no -- prototype-framework <command>` (not plain `npx`, which, before `npm install`, would fetch an unrelated package of that name):
|
|
30
30
|
|
|
31
|
-
`dev`, `verify`, `build`, `generate-migration`, `deploy`, `smoke`, `remove`, `secrets`, `setup-account`, `check-login`, `mail`, `admins`, `reset-local`.
|
|
31
|
+
`dev`, `verify`, `build`, `generate-migration`, `deploy`, `smoke`, `remove`, `stop`, `start`, `secrets`, `cloudflare-setup`, `setup-account`, `check-login`, `mail`, `admins`, `reset-local`, `version-check`, `upgrade`.
|
|
32
|
+
|
|
33
|
+
`cloudflare-setup` sets up Cloudflare from two pre-filled token links; see the [quickstart](https://github.com/lago-morph/cloud-app/blob/main/QUICKSTART.md).
|
|
32
34
|
|
|
33
35
|
`verify` runs the type check, the portability lint, the app's tests and the migration checks. Run it before calling a change done.
|
|
34
36
|
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The admin app's routes (v0.2.0 plan §3, §5.2; D8, D10; DEC-0710). Admin-only: anyone not signed
|
|
3
|
+
* in sees only the sign-in button, and only an administrator of the account gets a session.
|
|
4
|
+
*
|
|
5
|
+
* - `GET /`: signed out, the sign-in button; signed in, the pages.
|
|
6
|
+
* - `POST /signin`: starts the sign-in grant (identity and membership only).
|
|
7
|
+
* - `GET /<page>`: the page and its button (signed in only; otherwise back to `/`).
|
|
8
|
+
* - `POST /<page>`: starts that page's grant, asking for its own optional scopes (scopes.ts).
|
|
9
|
+
* - `GET /callback`: the one redirect URI of the admin client. It finishes the grant named by the
|
|
10
|
+
* grant cookie: sign-in sets the session; a page's grant runs the page's action with the person's
|
|
11
|
+
* token, which is revoked at once (grant.ts). A page's grant must be by the session's person, who
|
|
12
|
+
* must still be an administrator, and every scope the page asked for must have been granted;
|
|
13
|
+
* otherwise the page says which scopes are missing and runs nothing.
|
|
14
|
+
* - `POST /signout`: ends the session.
|
|
15
|
+
*
|
|
16
|
+
* POSTs must come from the admin app's own pages (`Origin` equal to its origin), and the session
|
|
17
|
+
* cookie is `SameSite=Lax`, so another site can start nothing. The session is short (PAR-445) and
|
|
18
|
+
* never renewed. Log lines name a fixed reason only, never a code, state or token.
|
|
19
|
+
*/
|
|
20
|
+
import type { CloudflareApi } from "../provision/cloudflare/api.js";
|
|
21
|
+
import { type AdminConfig } from "./grant.js";
|
|
22
|
+
import { type AdminPageId } from "./scopes.js";
|
|
23
|
+
export interface Admin {
|
|
24
|
+
readonly sub: string;
|
|
25
|
+
readonly email: string;
|
|
26
|
+
}
|
|
27
|
+
/** What a page's action gets: the person's grant, for this request only. */
|
|
28
|
+
export interface GrantContext {
|
|
29
|
+
readonly admin: Admin;
|
|
30
|
+
readonly accountId: string;
|
|
31
|
+
/** The Cloudflare API with the person's token. */
|
|
32
|
+
readonly api: CloudflareApi;
|
|
33
|
+
readonly granted: readonly string[];
|
|
34
|
+
readonly log: (line: string) => void;
|
|
35
|
+
readonly now: () => number;
|
|
36
|
+
/** The page form's sub-action (`isAction`), if it posted one. */
|
|
37
|
+
readonly action?: string;
|
|
38
|
+
}
|
|
39
|
+
/** A page's result: trusted HTML, optionally with one inline script (run under the CSP nonce). */
|
|
40
|
+
export type PageResult = string | {
|
|
41
|
+
readonly html: string;
|
|
42
|
+
readonly script: string;
|
|
43
|
+
};
|
|
44
|
+
export interface AdminPage {
|
|
45
|
+
readonly id: Exclude<AdminPageId, "signin">;
|
|
46
|
+
readonly title: string;
|
|
47
|
+
/** The sub-action verbs its form may post (`<verb>:<ids>`); none when absent. */
|
|
48
|
+
readonly actions?: readonly string[];
|
|
49
|
+
/** The page before its action: what it will do (trusted HTML). */
|
|
50
|
+
view(admin: Admin): string | Promise<string>;
|
|
51
|
+
/** The action, with the person's grant; its result as trusted HTML. */
|
|
52
|
+
run(ctx: GrantContext): Promise<PageResult>;
|
|
53
|
+
}
|
|
54
|
+
export interface AdminDeps {
|
|
55
|
+
readonly fetch: typeof fetch;
|
|
56
|
+
readonly now: () => number;
|
|
57
|
+
readonly log: (line: string) => void;
|
|
58
|
+
readonly config: AdminConfig;
|
|
59
|
+
readonly pages: readonly AdminPage[];
|
|
60
|
+
}
|
|
61
|
+
/** A Cloudflare API client carrying the person's token. */
|
|
62
|
+
export declare function grantApi(f: typeof fetch, apiBase: string, token: string): CloudflareApi;
|
|
63
|
+
export declare function handleAdminRequest(request: Request, deps: AdminDeps): Promise<Response>;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { readCookie } from "../auth/cookies.js";
|
|
2
|
+
import { actionVerb, GrantError, isAction, logLine, openGrant, startGrant, useGrant } from "./grant.js";
|
|
3
|
+
import { button, esc, page, SECURITY_HEADERS } from "./html.js";
|
|
4
|
+
import { ADMIN_GRANT_MS, ADMIN_SESSION_MS, GRANT_COOKIE, SESSION_COOKIE } from "./params.js";
|
|
5
|
+
import { open, seal } from "./seal.js";
|
|
6
|
+
import {} from "./scopes.js";
|
|
7
|
+
const cookie = (name, value, maxAgeMs) => `${name}=${value}; Path=/; Max-Age=${String(Math.floor(maxAgeMs / 1000))}; HttpOnly; Secure; SameSite=Lax`;
|
|
8
|
+
const clear = (name) => `${name}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax`;
|
|
9
|
+
const redirect = (location, status, cookies = []) => {
|
|
10
|
+
const headers = new Headers({ ...SECURITY_HEADERS, location });
|
|
11
|
+
for (const c of cookies)
|
|
12
|
+
headers.append("set-cookie", c);
|
|
13
|
+
return new Response(null, { status, headers });
|
|
14
|
+
};
|
|
15
|
+
const withCookies = (res, cookies) => {
|
|
16
|
+
for (const c of cookies)
|
|
17
|
+
res.headers.append("set-cookie", c);
|
|
18
|
+
return res;
|
|
19
|
+
};
|
|
20
|
+
/** A Cloudflare API client carrying the person's token. */
|
|
21
|
+
export function grantApi(f, apiBase, token) {
|
|
22
|
+
return async (method, path, body) => {
|
|
23
|
+
const headers = { authorization: `Bearer ${token}` };
|
|
24
|
+
const multipart = body instanceof FormData;
|
|
25
|
+
if (body !== undefined && !multipart)
|
|
26
|
+
headers["content-type"] = "application/json";
|
|
27
|
+
const res = await f(`${apiBase}${path}`, { method, headers, redirect: "manual", ...(body === undefined ? {} : { body: multipart ? body : JSON.stringify(body) }) });
|
|
28
|
+
const text = await res.text();
|
|
29
|
+
let parsed = text;
|
|
30
|
+
try {
|
|
31
|
+
parsed = text === "" ? null : JSON.parse(text);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// not JSON: keep the text
|
|
35
|
+
}
|
|
36
|
+
return { status: res.status, body: parsed };
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
async function sessionOf(request, deps) {
|
|
40
|
+
const value = readCookie(request.headers.get("cookie"), SESSION_COOKIE);
|
|
41
|
+
if (value === undefined)
|
|
42
|
+
return null;
|
|
43
|
+
const s = (await open(deps.config.clientSecret, "session", value, deps.now()));
|
|
44
|
+
return s !== null && typeof s.sub === "string" && typeof s.email === "string" ? { sub: s.sub, email: s.email } : null;
|
|
45
|
+
}
|
|
46
|
+
const sameOrigin = (request, deps) => request.headers.get("origin") === deps.config.origin;
|
|
47
|
+
const signInPage = (status = 200, note = "") => page("Prototype admin", `${note}<p>Sign in with your Cloudflare account. Only an administrator of this account can use the admin app.</p>${button("/signin", "Sign in with Cloudflare")}`, { status });
|
|
48
|
+
function homePage(admin, deps) {
|
|
49
|
+
const links = deps.pages.map((p) => `<li><a href="/${p.id}">${esc(p.title)}</a></li>`).join("");
|
|
50
|
+
return page("Prototype admin", `<p>Signed in as ${esc(admin.email)}.</p><ul>${links}</ul><nav>${button("/signout", "Sign out")}</nav>`);
|
|
51
|
+
}
|
|
52
|
+
/** A refusal page; `text` is trusted HTML. */
|
|
53
|
+
const refusedPage = (status, text, cookies = []) => withCookies(page("Prototype admin", `<p>${text}</p><p><a href="/">Back to the admin app</a></p>`, { status }), cookies);
|
|
54
|
+
const NOT_ADMIN = "Only an administrator of this Cloudflare account can use the admin app. Ask the account's owner if you need it.";
|
|
55
|
+
async function callback(request, url, deps) {
|
|
56
|
+
const warn = (reason) => deps.log(logLine("warn", `grant refused: ${reason}`));
|
|
57
|
+
const g = await openGrant(deps, readCookie(request.headers.get("cookie"), GRANT_COOKIE), url.searchParams.get("state") ?? "");
|
|
58
|
+
// A mismatched callback leaves the grant cookie alone: any site can send a browser here.
|
|
59
|
+
if (g === null) {
|
|
60
|
+
warn("state mismatch or expired grant");
|
|
61
|
+
return refusedPage(400, "This sign-in has expired or did not start here. Go back to the admin app and start again.");
|
|
62
|
+
}
|
|
63
|
+
const done = [clear(GRANT_COOKIE)];
|
|
64
|
+
if (url.searchParams.get("error") !== null) {
|
|
65
|
+
warn("declined at Cloudflare");
|
|
66
|
+
return refusedPage(400, "The request was not approved at Cloudflare, so nothing was done.", done);
|
|
67
|
+
}
|
|
68
|
+
const code = url.searchParams.get("code") ?? "";
|
|
69
|
+
if (code === "") {
|
|
70
|
+
warn("no code");
|
|
71
|
+
return refusedPage(400, "Cloudflare sent no authorization. Start again.", done);
|
|
72
|
+
}
|
|
73
|
+
const session = g.page === "signin" ? null : await sessionOf(request, deps);
|
|
74
|
+
const target = g.page === "signin" ? undefined : deps.pages.find((p) => p.id === g.page);
|
|
75
|
+
// A page's grant needs a live session: refused before the code is exchanged, so no token is issued for nothing.
|
|
76
|
+
if (g.page !== "signin" && (session === null || target === undefined)) {
|
|
77
|
+
warn("no session");
|
|
78
|
+
return refusedPage(401, "Your admin session ended. Sign in again, then repeat the step.", done);
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
return await useGrant(deps, g, code, async (grant) => {
|
|
82
|
+
if (g.page === "signin") {
|
|
83
|
+
const value = await seal(deps.config.clientSecret, "session", grant.admin, deps.now() + ADMIN_SESSION_MS);
|
|
84
|
+
deps.log(logLine("info", "admin signed in"));
|
|
85
|
+
return redirect("/", 303, [...done, cookie(SESSION_COOKIE, value, ADMIN_SESSION_MS)]);
|
|
86
|
+
}
|
|
87
|
+
// Checked before the exchange; repeated for the type checker.
|
|
88
|
+
if (session === null || target === undefined)
|
|
89
|
+
return refusedPage(401, "Your admin session ended. Sign in again, then repeat the step.", done);
|
|
90
|
+
if (grant.admin.sub !== session.sub) {
|
|
91
|
+
warn("grant by another person than the session's");
|
|
92
|
+
return refusedPage(403, "You approved this at Cloudflare as a different person than the one signed in here. Sign in again.", [...done, clear(SESSION_COOKIE)]);
|
|
93
|
+
}
|
|
94
|
+
if (grant.missing.length > 0) {
|
|
95
|
+
warn(`optional scopes not granted (${grant.missing.join(", ")})`);
|
|
96
|
+
const list = grant.missing.map((s) => `<li><code>${esc(s)}</code></li>`).join("");
|
|
97
|
+
return withCookies(page(target.title, `<p class="warn">Nothing was done: at Cloudflare these permissions were not granted, and this step needs them:</p><ul>${list}</ul><p>Start again and keep every permission on the Cloudflare page ticked.</p>${button(`/${target.id}`, "Start again")}`, { status: 403 }), done);
|
|
98
|
+
}
|
|
99
|
+
const api = grantApi(deps.fetch, deps.config.apiBase, grant.accessToken);
|
|
100
|
+
let result;
|
|
101
|
+
try {
|
|
102
|
+
result = await target.run({ admin: grant.admin, accountId: deps.config.accountId, api, granted: grant.granted, log: deps.log, now: deps.now, ...(g.action === undefined ? {} : { action: g.action }) });
|
|
103
|
+
}
|
|
104
|
+
catch (e) {
|
|
105
|
+
// Step errors name the step and Cloudflare's answer, never a token or a value (each step's own rule).
|
|
106
|
+
const message = e instanceof Error ? e.message : "unknown error";
|
|
107
|
+
deps.log(logLine("warn", `${target.id} step failed`));
|
|
108
|
+
const advice = /code 9109\b/.test(message) ? "<p>Cloudflare refused a permission: start again and keep every permission on the Cloudflare page ticked.</p>" : "";
|
|
109
|
+
return withCookies(page(target.title, `<p class="warn">That step failed: ${esc(message)}</p>${advice}${button(`/${target.id}`, "Start again")}<p><a href="/">Back to the admin app</a></p>`, { status: 502 }), done);
|
|
110
|
+
}
|
|
111
|
+
const { html, script } = typeof result === "string" ? { html: result, script: undefined } : result;
|
|
112
|
+
return withCookies(page(target.title, `${html}<p><a href="/">Back to the admin app</a></p>`, script === undefined ? {} : { script }), done);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
catch (e) {
|
|
116
|
+
if (e instanceof GrantError) {
|
|
117
|
+
warn(e.reason);
|
|
118
|
+
if (e.kind === "not-admin")
|
|
119
|
+
return refusedPage(403, NOT_ADMIN, [...done, clear(SESSION_COOKIE)]);
|
|
120
|
+
return refusedPage(400, "Signing in with Cloudflare failed. Start again.", done);
|
|
121
|
+
}
|
|
122
|
+
deps.log(logLine("error", "grant failed: internal error"));
|
|
123
|
+
return refusedPage(503, "Something went wrong talking to Cloudflare. Nothing secret was shown; try again shortly.", done);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
export async function handleAdminRequest(request, deps) {
|
|
127
|
+
const url = new URL(request.url);
|
|
128
|
+
const path = url.pathname;
|
|
129
|
+
const pageFor = deps.pages.find((p) => `/${p.id}` === path);
|
|
130
|
+
const known = path === "/" || path === "/signin" || path === "/signout" || path === "/callback" || pageFor !== undefined;
|
|
131
|
+
if (!known)
|
|
132
|
+
return page("Not found", "<p>Not found.</p>", { status: 404 });
|
|
133
|
+
const methods = path === "/" || path === "/callback" ? ["GET"] : path === "/signin" || path === "/signout" ? ["POST"] : ["GET", "POST"];
|
|
134
|
+
if (!methods.includes(request.method))
|
|
135
|
+
return page("Method not allowed", "<p>Method not allowed.</p>", { status: 405, headers: { allow: methods.join(", ") } });
|
|
136
|
+
try {
|
|
137
|
+
if (path === "/callback")
|
|
138
|
+
return await callback(request, url, deps);
|
|
139
|
+
if (request.method === "POST" && !sameOrigin(request, deps)) {
|
|
140
|
+
deps.log(logLine("warn", "cross-site request refused"));
|
|
141
|
+
return page("Prototype admin", "<p>This request did not come from the admin app's own page.</p>", { status: 403 });
|
|
142
|
+
}
|
|
143
|
+
const admin = await sessionOf(request, deps);
|
|
144
|
+
if (path === "/signout")
|
|
145
|
+
return redirect("/", 303, [clear(SESSION_COOKIE)]);
|
|
146
|
+
if (path === "/signin") {
|
|
147
|
+
const g = await startGrant(deps, "signin");
|
|
148
|
+
return redirect(g.location, 302, [cookie(GRANT_COOKIE, g.cookie, ADMIN_GRANT_MS)]);
|
|
149
|
+
}
|
|
150
|
+
if (path === "/")
|
|
151
|
+
return admin === null ? signInPage() : homePage(admin, deps);
|
|
152
|
+
// A page: signed-in administrators only.
|
|
153
|
+
const target = pageFor;
|
|
154
|
+
if (admin === null)
|
|
155
|
+
return request.method === "GET" ? redirect("/", 303) : signInPage(401, "<p class=\"warn\">Your admin session ended. Sign in again.</p>");
|
|
156
|
+
if (request.method === "GET")
|
|
157
|
+
return page(target.title, `${await target.view(admin)}${button(`/${target.id}`, `Continue at Cloudflare`)}<p><a href="/">Back</a></p>`);
|
|
158
|
+
let action;
|
|
159
|
+
if ((request.headers.get("content-type") ?? "").startsWith("application/x-www-form-urlencoded")) {
|
|
160
|
+
const posted = new URLSearchParams(await request.text()).get("action");
|
|
161
|
+
if (posted !== null) {
|
|
162
|
+
// Only a well-formed action whose verb the page declares; anything else starts nothing.
|
|
163
|
+
if (!isAction(posted) || !(target.actions ?? []).includes(actionVerb(posted)))
|
|
164
|
+
return page(target.title, "<p>That request was not understood.</p>", { status: 400 });
|
|
165
|
+
action = posted;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const g = await startGrant(deps, target.id, action);
|
|
169
|
+
return redirect(g.location, 302, [cookie(GRANT_COOKIE, g.cookie, ADMIN_GRANT_MS)]);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
deps.log(logLine("error", "request failed: internal error"));
|
|
173
|
+
return page("Prototype admin", "<p>The admin app could not reach Cloudflare. Try again shortly.</p>", { status: 503 });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** The one Node built-in the admin app's bundle may import. */
|
|
2
|
+
export declare const ADMIN_APP_NODE_IMPORTS: readonly string[];
|
|
3
|
+
/** This package's version, as the setup record records it. */
|
|
4
|
+
export declare function frameworkVersion(): string;
|
|
5
|
+
/** The esbuild options both Workers are built with. */
|
|
6
|
+
export declare const BUNDLE_OPTIONS: Readonly<{
|
|
7
|
+
readonly bundle: true;
|
|
8
|
+
readonly format: "esm";
|
|
9
|
+
readonly platform: "neutral";
|
|
10
|
+
readonly target: "es2022";
|
|
11
|
+
readonly write: false;
|
|
12
|
+
readonly logLevel: "silent";
|
|
13
|
+
readonly legalComments: "none";
|
|
14
|
+
}>;
|
|
15
|
+
/** The auth app's Worker module, exactly as account setup uploads it (`cloudflare:workers` external). */
|
|
16
|
+
export declare function bundleAuthApp(): Promise<string>;
|
|
17
|
+
export declare function bundleAdminApp(): Promise<string>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The admin app as the one ES module the bootstrap uploads (DEC-0712, DEC-0720): `worker.ts` (or,
|
|
3
|
+
* in the published package, `dist/admin-app/worker.js`) bundled by esbuild, a dependency of the
|
|
4
|
+
* framework already used by `build`. Built when the bootstrap runs, so the upload is always this
|
|
5
|
+
* framework version's admin app. Two values are compiled in:
|
|
6
|
+
* - `__PF_AUTH_APP_SOURCE__`: the auth app's Worker (`auth-app/worker.ts`, its own bundle with
|
|
7
|
+
* `cloudflare:workers` external), which account setup (page 1) uploads;
|
|
8
|
+
* - `__PF_FRAMEWORK_VERSION__`: this package's version, which page 1 records in the setup record.
|
|
9
|
+
* `node:crypto` stays an import: page 1 reuses the framework's account-setup code (C's buckets, F's
|
|
10
|
+
* signing credential), which uses it, so the Worker runs with `nodejs_compat` (admin-app-deploy.ts).
|
|
11
|
+
* Node only; the Worker never imports this file.
|
|
12
|
+
*/
|
|
13
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
14
|
+
import { dirname, join } from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
17
|
+
/** The one Node built-in the admin app's bundle may import. */
|
|
18
|
+
export const ADMIN_APP_NODE_IMPORTS = Object.freeze(["node:crypto"]);
|
|
19
|
+
const entry = (dir, name) => (existsSync(join(dir, `${name}.ts`)) ? join(dir, `${name}.ts`) : join(dir, `${name}.js`));
|
|
20
|
+
/** This package's version, as the setup record records it. */
|
|
21
|
+
export function frameworkVersion() {
|
|
22
|
+
const version = JSON.parse(readFileSync(join(HERE, "..", "..", "package.json"), "utf8")).version;
|
|
23
|
+
if (typeof version !== "string")
|
|
24
|
+
throw new Error("the framework's package.json has no version");
|
|
25
|
+
return version;
|
|
26
|
+
}
|
|
27
|
+
/** The esbuild options both Workers are built with. */
|
|
28
|
+
export const BUNDLE_OPTIONS = Object.freeze({ bundle: true, format: "esm", platform: "neutral", target: "es2022", write: false, logLevel: "silent", legalComments: "none" });
|
|
29
|
+
/** The auth app's Worker module, exactly as account setup uploads it (`cloudflare:workers` external). */
|
|
30
|
+
export async function bundleAuthApp() {
|
|
31
|
+
const { build } = await import("esbuild");
|
|
32
|
+
const out = await build({ ...BUNDLE_OPTIONS, entryPoints: [entry(join(HERE, "..", "auth-app"), "worker")], external: ["cloudflare:workers"] });
|
|
33
|
+
return out.outputFiles[0].text;
|
|
34
|
+
}
|
|
35
|
+
let cached;
|
|
36
|
+
export function bundleAdminApp() {
|
|
37
|
+
cached ??= (async () => {
|
|
38
|
+
const { build } = await import("esbuild");
|
|
39
|
+
const out = await build({
|
|
40
|
+
...BUNDLE_OPTIONS,
|
|
41
|
+
entryPoints: [entry(HERE, "worker")],
|
|
42
|
+
external: [...ADMIN_APP_NODE_IMPORTS],
|
|
43
|
+
define: { __PF_AUTH_APP_SOURCE__: JSON.stringify(await bundleAuthApp()), __PF_FRAMEWORK_VERSION__: JSON.stringify(frameworkVersion()) },
|
|
44
|
+
});
|
|
45
|
+
return out.outputFiles[0].text;
|
|
46
|
+
})();
|
|
47
|
+
cached.catch(() => {
|
|
48
|
+
cached = undefined;
|
|
49
|
+
});
|
|
50
|
+
return cached;
|
|
51
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The optional cleanup of v0.1.x's email resources (v0.2.0 plan §8: "The admin app offers cleanup
|
|
3
|
+
* … It's optional, and never automatic"; DEC-0718). The page says what v0.1.x left. Nothing is
|
|
4
|
+
* deleted until the person presses the button and approves at Cloudflare.
|
|
5
|
+
*
|
|
6
|
+
* With the person's grant (PAR-447 `cleanup`: `workers-scripts.write`, `workers-r2.write`) it
|
|
7
|
+
* deletes the mail-sink Worker `prototype-mailsink`, then empties and deletes its R2 bucket of the
|
|
8
|
+
* same name. What is already gone counts as done, so a second run is harmless.
|
|
9
|
+
*
|
|
10
|
+
* The email parts sit on the domain's zone: the routing rule `sink@t.<domain>`, Email Routing on
|
|
11
|
+
* `t.<domain>`, and the Email Sending entry. The admin client has no email or zone scope (C's
|
|
12
|
+
* `ADMIN_OPTIONAL_SCOPES`), so the page gives the dashboard steps for these, naming the domain from
|
|
13
|
+
* the account settings record when it is there.
|
|
14
|
+
*/
|
|
15
|
+
import { ACCOUNT_SETTINGS_KEY } from "../provision/cloudflare/account-settings.js";
|
|
16
|
+
import { describeFailure, succeeded } from "../provision/cloudflare/api.js";
|
|
17
|
+
import { MAIL_SINK_NAME, STATE_BUCKET } from "../provision/cloudflare/names.js";
|
|
18
|
+
import { esc } from "./html.js";
|
|
19
|
+
/** PAR-449: at most this many 1000-key pages of the mail sink's bucket are emptied in one run. */
|
|
20
|
+
export const CLEANUP_MAX_PAGES = 10;
|
|
21
|
+
const gone = (status) => status === 404;
|
|
22
|
+
async function deleteWorker(api, a) {
|
|
23
|
+
const r = await api("DELETE", `/accounts/${a}/workers/scripts/${MAIL_SINK_NAME}`);
|
|
24
|
+
if (gone(r.status))
|
|
25
|
+
return `The Worker <code>${MAIL_SINK_NAME}</code> was already gone.`;
|
|
26
|
+
if (!succeeded(r))
|
|
27
|
+
throw new Error(`deleting the Worker ${MAIL_SINK_NAME} failed: ${describeFailure(r)}`);
|
|
28
|
+
return `Deleted the Worker <code>${MAIL_SINK_NAME}</code>.`;
|
|
29
|
+
}
|
|
30
|
+
async function deleteBucket(api, a) {
|
|
31
|
+
const base = `/accounts/${a}/r2/buckets/${MAIL_SINK_NAME}`;
|
|
32
|
+
let removed = 0;
|
|
33
|
+
// Each pass lists from the start (deleted keys are gone); one more listing than PAR-449 pages
|
|
34
|
+
// tells "empty" from "more remain".
|
|
35
|
+
for (let page = 0;; page++) {
|
|
36
|
+
const r = await api("GET", `${base}/objects?per_page=1000`);
|
|
37
|
+
if (gone(r.status))
|
|
38
|
+
return removed === 0 ? `The R2 bucket <code>${MAIL_SINK_NAME}</code> was already gone.` : `Deleted ${String(removed)} stored test messages; the R2 bucket <code>${MAIL_SINK_NAME}</code> itself was already gone.`;
|
|
39
|
+
const list = r.body?.result;
|
|
40
|
+
if (!succeeded(r) || !Array.isArray(list))
|
|
41
|
+
throw new Error(`listing the R2 bucket ${MAIL_SINK_NAME} failed: ${describeFailure(r)}`);
|
|
42
|
+
if (list.length === 0)
|
|
43
|
+
break;
|
|
44
|
+
if (page === CLEANUP_MAX_PAGES)
|
|
45
|
+
return `Deleted ${String(removed)} stored test messages; more remain in <code>${MAIL_SINK_NAME}</code>. Run the cleanup again to finish.`;
|
|
46
|
+
for (const o of list) {
|
|
47
|
+
if (typeof o.key !== "string")
|
|
48
|
+
throw new Error(`listing the R2 bucket ${MAIL_SINK_NAME}: an entry has no key; nothing more was deleted`);
|
|
49
|
+
const d = await api("DELETE", `${base}/objects/${encodeURIComponent(o.key)}`);
|
|
50
|
+
if (!succeeded(d) && !gone(d.status))
|
|
51
|
+
throw new Error(`emptying the R2 bucket ${MAIL_SINK_NAME} failed: ${describeFailure(d)}`);
|
|
52
|
+
removed++;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const d = await api("DELETE", base);
|
|
56
|
+
if (gone(d.status))
|
|
57
|
+
return `The R2 bucket <code>${MAIL_SINK_NAME}</code> was already gone.`;
|
|
58
|
+
if (!succeeded(d))
|
|
59
|
+
throw new Error(`deleting the R2 bucket ${MAIL_SINK_NAME} failed: ${describeFailure(d)}`);
|
|
60
|
+
return `Deleted the R2 bucket <code>${MAIL_SINK_NAME}</code> and its ${String(removed)} stored test messages.`;
|
|
61
|
+
}
|
|
62
|
+
/** The v0.1.x email domain from the account settings record, if any. */
|
|
63
|
+
async function emailDomain(api, a) {
|
|
64
|
+
const r = await api("GET", `/accounts/${a}/r2/buckets/${STATE_BUCKET}/objects/${encodeURIComponent(ACCOUNT_SETTINGS_KEY)}`);
|
|
65
|
+
const d = r.status >= 200 && r.status < 300 ? r.body?.emailDomain : undefined;
|
|
66
|
+
return typeof d === "string" && /^[a-z0-9.-]{1,253}$/i.test(d) ? d : undefined;
|
|
67
|
+
}
|
|
68
|
+
function dashboardSteps(domain) {
|
|
69
|
+
const zone = domain === undefined ? "your email domain" : `<code>${esc(domain)}</code>`;
|
|
70
|
+
const sub = domain === undefined ? "the <code>t.</code> subdomain" : `<code>t.${esc(domain)}</code>`;
|
|
71
|
+
return [
|
|
72
|
+
"<p>These are on the domain's zone. The admin app has no permission there, so do them in the Cloudflare dashboard if you want them gone:</p>",
|
|
73
|
+
"<ul>",
|
|
74
|
+
`<li>Email → Email Routing on ${zone}: delete the routing rule <code>sink@</code>${sub}, then turn off routing on ${sub} (this removes its MX and SPF records).</li>`,
|
|
75
|
+
`<li>Email → Email Sending: delete the entry for ${zone}.</li>`,
|
|
76
|
+
"</ul>",
|
|
77
|
+
].join("\n");
|
|
78
|
+
}
|
|
79
|
+
async function run(ctx) {
|
|
80
|
+
const domain = await emailDomain(ctx.api, ctx.accountId);
|
|
81
|
+
const worker = await deleteWorker(ctx.api, ctx.accountId);
|
|
82
|
+
const bucket = await deleteBucket(ctx.api, ctx.accountId);
|
|
83
|
+
return `<p>${worker}</p><p>${bucket}</p>${dashboardSteps(domain)}`;
|
|
84
|
+
}
|
|
85
|
+
export const cleanupPage = {
|
|
86
|
+
id: "cleanup",
|
|
87
|
+
title: "Clean up v0.1.x email",
|
|
88
|
+
view: () => [
|
|
89
|
+
"<p>v0.2.0 signs people in through Cloudflare and sends no email. If this account was set up by v0.1.x, it still has the email pieces that version made. Removing them is optional; nothing is removed unless you continue.</p>",
|
|
90
|
+
`<p>Continuing deletes the mail-sink Worker <code>${MAIL_SINK_NAME}</code> and its R2 bucket <code>${MAIL_SINK_NAME}</code> with the test messages in it. Nothing else is touched. The page then lists the email settings on your domain to remove in the dashboard.</p>`,
|
|
91
|
+
].join("\n"),
|
|
92
|
+
run,
|
|
93
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The admin app's settings from its Worker env (DEC-0711):
|
|
3
|
+
* - `ADMIN_CLIENT_ID`, `ADMIN_CLIENT_SECRET` (PAR-439): the admin client, as Secrets Store bindings
|
|
4
|
+
* (`{ get() }`) or, as the Secrets Store fallback (plan §10), plain Worker secrets;
|
|
5
|
+
* - `ADMIN_ACCOUNT_ID`, `ADMIN_APP_ORIGIN`: plain-text bindings the bootstrap sets
|
|
6
|
+
* (admin-app-deploy.ts). The callback URL is built from the origin, never from the Host header;
|
|
7
|
+
* - `ADMIN_DISCOVERY_URL`, `ADMIN_API_BASE`: only tests set them (default: Cloudflare's, PAR-418).
|
|
8
|
+
* Errors name the setting, never its value.
|
|
9
|
+
*/
|
|
10
|
+
import { CLOUDFLARE_API_BASE, CLOUDFLARE_DISCOVERY_URL } from "../auth-app/params.js";
|
|
11
|
+
const fail = (message) => {
|
|
12
|
+
throw new Error(`admin app misconfigured: ${message}`);
|
|
13
|
+
};
|
|
14
|
+
async function setting(env, name) {
|
|
15
|
+
let value = env[name];
|
|
16
|
+
if (typeof value === "object" && value !== null && typeof value.get === "function") {
|
|
17
|
+
try {
|
|
18
|
+
value = await value.get();
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return fail(`${name} could not be read`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (typeof value !== "string" || value === "")
|
|
25
|
+
return fail(`${name} is not set`);
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
const optional = (env, name, fallback) => {
|
|
29
|
+
const v = env[name];
|
|
30
|
+
return typeof v === "string" && v !== "" ? v : fallback;
|
|
31
|
+
};
|
|
32
|
+
export async function readAdminConfig(env) {
|
|
33
|
+
const clientId = await setting(env, "ADMIN_CLIENT_ID");
|
|
34
|
+
const clientSecret = await setting(env, "ADMIN_CLIENT_SECRET");
|
|
35
|
+
const accountId = await setting(env, "ADMIN_ACCOUNT_ID");
|
|
36
|
+
const origin = await setting(env, "ADMIN_APP_ORIGIN");
|
|
37
|
+
if (!URL.canParse(origin))
|
|
38
|
+
fail("ADMIN_APP_ORIGIN is not an origin");
|
|
39
|
+
const parsed = new URL(origin);
|
|
40
|
+
const local = parsed.protocol === "http:" && (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1");
|
|
41
|
+
if (parsed.origin !== origin || !(parsed.protocol === "https:" || local))
|
|
42
|
+
fail("ADMIN_APP_ORIGIN is not an origin");
|
|
43
|
+
return {
|
|
44
|
+
clientId,
|
|
45
|
+
clientSecret,
|
|
46
|
+
accountId,
|
|
47
|
+
origin,
|
|
48
|
+
discoveryUrl: optional(env, "ADMIN_DISCOVERY_URL", CLOUDFLARE_DISCOVERY_URL),
|
|
49
|
+
apiBase: optional(env, "ADMIN_API_BASE", CLOUDFLARE_API_BASE),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admin page 2, the everyday token (v0.2.0 plan §5.2 page 2; DEC-0715). The action runs with the
|
|
3
|
+
* person's grant (PAR-447 `everyday`): it creates the everyday token, or updates an existing one
|
|
4
|
+
* (from 0.1.x too) in place to exactly the four groups (everyday-token.ts).
|
|
5
|
+
*
|
|
6
|
+
* A new token's value is **shown once, to the person, on this page**, with a copy button and where
|
|
7
|
+
* to put it. It is never logged, stored or sent anywhere else; the agent never sees it. When the
|
|
8
|
+
* grant could not update the old token, the page shows the new value and offers to delete the old
|
|
9
|
+
* token once the person confirms they saved the new one (a second grant, action `delete:<ids>`).
|
|
10
|
+
*/
|
|
11
|
+
import { deleteOldEverydayTokens, ensureEverydayToken } from "../provision/cloudflare/everyday-token.js";
|
|
12
|
+
import { EVERYDAY_V2 } from "../provision/cloudflare/permissions.js";
|
|
13
|
+
import { esc } from "./html.js";
|
|
14
|
+
const SETTING = "CLOUDFLARE_API_TOKEN";
|
|
15
|
+
const groupList = () => `<ul>${EVERYDAY_V2.map((g) => `<li>${esc(g.name)}</li>`).join("")}</ul>`;
|
|
16
|
+
const COPY_SCRIPT = `document.getElementById("copy").addEventListener("click",function(){navigator.clipboard.writeText(document.getElementById("everyday-token").textContent).then(function(){document.getElementById("copied").textContent="Copied."})});`;
|
|
17
|
+
function showValue(value, lead) {
|
|
18
|
+
// `lead` is a paragraph's text; the group list follows it, outside the paragraph.
|
|
19
|
+
return {
|
|
20
|
+
html: [
|
|
21
|
+
`<p>${lead}</p>`,
|
|
22
|
+
groupList(),
|
|
23
|
+
`<p><strong>This is the only time the value is shown.</strong> Copy it now:</p>`,
|
|
24
|
+
`<pre id="everyday-token">${esc(value)}</pre>`,
|
|
25
|
+
`<p><button type="button" id="copy">Copy</button> <span id="copied"></span></p>`,
|
|
26
|
+
"<p>Where it goes (keep it out of chats, commits and logs: the agent never needs to see it):</p>",
|
|
27
|
+
"<ul>",
|
|
28
|
+
`<li>In a Claude Code cloud session: open the environment menu, choose Edit, and add <code>${SETTING}=<the value></code> under Environment variables; save, then start a new session.</li>`,
|
|
29
|
+
`<li>On your own computer: put the line <code>${SETTING}=<the value></code> in <code>~/.secrets/cloudflare</code> in your home directory (keep it private: <code>chmod 600</code>).</li>`,
|
|
30
|
+
"</ul>",
|
|
31
|
+
'<p>Then tell the agent: "continue prototype setup".</p>',
|
|
32
|
+
].join("\n"),
|
|
33
|
+
script: COPY_SCRIPT,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const deleteForm = (ids) => `<form method="post" action="/everyday"><input type="hidden" name="action" value="delete:${esc(ids.join(","))}"><button type="submit">I have saved the new token: delete the old one</button></form>`;
|
|
37
|
+
async function run(ctx) {
|
|
38
|
+
if (ctx.action?.startsWith("delete:") === true) {
|
|
39
|
+
const ids = ctx.action.slice("delete:".length).split(",").filter((s) => s !== "");
|
|
40
|
+
const out = await deleteOldEverydayTokens(ctx.api, ctx.accountId, ids);
|
|
41
|
+
return `<p>Deleted ${String(out.deleted.length)} old everyday token(s).${out.skipped.length > 0 ? ` ${String(out.skipped.length)} ID(s) were left alone: not an everyday token, or the last one.` : ""}</p>`;
|
|
42
|
+
}
|
|
43
|
+
const out = await ensureEverydayToken(ctx.api, ctx.accountId);
|
|
44
|
+
switch (out.kind) {
|
|
45
|
+
case "created":
|
|
46
|
+
return showValue(out.value, "The everyday token <code>prototype-framework</code> was created with exactly these permissions:");
|
|
47
|
+
case "replaced": {
|
|
48
|
+
const r = showValue(out.value, "Cloudflare did not let this sign-in change the existing everyday token, so a new one was created with exactly these permissions:");
|
|
49
|
+
return typeof r === "string" ? r : { ...r, html: `${r.html}\n<p>Once the new value is saved where it goes, delete the old token:</p>${deleteForm(out.oldIds)}` };
|
|
50
|
+
}
|
|
51
|
+
case "updated":
|
|
52
|
+
return [
|
|
53
|
+
`<p>The existing everyday token was updated in place to exactly these permissions; its value did not change, so nothing needs re-saving:</p>${groupList()}`,
|
|
54
|
+
out.added.length > 0 ? `<p>Added: ${out.added.map(esc).join(", ")}.</p>` : "",
|
|
55
|
+
out.removed.length > 0 ? `<p>Removed (only v0.1.x email code used them): ${out.removed.map(esc).join(", ")}.</p>` : "",
|
|
56
|
+
].join("\n");
|
|
57
|
+
case "current":
|
|
58
|
+
return `<p>The everyday token already holds exactly these permissions; nothing was changed:</p>${groupList()}`;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export const everydayPage = {
|
|
62
|
+
id: "everyday",
|
|
63
|
+
title: "Everyday token",
|
|
64
|
+
actions: ["delete"],
|
|
65
|
+
view: () => [
|
|
66
|
+
"<p>The everyday token is what the agent uses for deploys and checks. This step creates it, or updates an existing one (from 0.1.x too) in place to exactly these permissions on this account:</p>",
|
|
67
|
+
groupList(),
|
|
68
|
+
"<p>Cloudflare will ask you to approve the permissions this step needs. Keep them all ticked. A new token's value is shown once, here, to you.</p>",
|
|
69
|
+
].join("\n"),
|
|
70
|
+
run,
|
|
71
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { type AdminPageId } from "./scopes.js";
|
|
2
|
+
export interface AdminConfig {
|
|
3
|
+
/** The admin OAuth client (the bootstrap creates it, plan §5.1). */
|
|
4
|
+
readonly clientId: string;
|
|
5
|
+
readonly clientSecret: string;
|
|
6
|
+
/** The Cloudflare account this admin app belongs to. */
|
|
7
|
+
readonly accountId: string;
|
|
8
|
+
/** The admin app's public origin; the callback is `<origin>/callback`. */
|
|
9
|
+
readonly origin: string;
|
|
10
|
+
readonly discoveryUrl: string;
|
|
11
|
+
readonly apiBase: string;
|
|
12
|
+
}
|
|
13
|
+
export interface GrantDeps {
|
|
14
|
+
readonly fetch: typeof fetch;
|
|
15
|
+
readonly config: AdminConfig;
|
|
16
|
+
readonly now: () => number;
|
|
17
|
+
readonly log: (line: string) => void;
|
|
18
|
+
}
|
|
19
|
+
export declare class GrantError extends Error {
|
|
20
|
+
readonly reason: string;
|
|
21
|
+
/** "declined": the person said no at Cloudflare; "refused": anything else. */
|
|
22
|
+
readonly kind: "declined" | "refused" | "not-admin";
|
|
23
|
+
constructor(reason: string, kind?: GrantError["kind"]);
|
|
24
|
+
}
|
|
25
|
+
export declare const logLine: (level: "warn" | "error" | "info", message: string) => string;
|
|
26
|
+
interface GrantState {
|
|
27
|
+
readonly state: string;
|
|
28
|
+
readonly verifier: string;
|
|
29
|
+
readonly nonce: string;
|
|
30
|
+
readonly page: AdminPageId;
|
|
31
|
+
/** The page's sub-action (its form's `action`, checked by `isAction`), if any. */
|
|
32
|
+
readonly action?: string;
|
|
33
|
+
}
|
|
34
|
+
/** A page's sub-action: a lower-case verb, `:`, and 1–20 comma-separated 32-hex IDs. */
|
|
35
|
+
export declare const isAction: (v: unknown) => v is string;
|
|
36
|
+
/** The verb of a well-formed action. */
|
|
37
|
+
export declare const actionVerb: (action: string) => string;
|
|
38
|
+
/** The authorization URL for `page` and the sealed grant cookie value. */
|
|
39
|
+
export declare function startGrant(deps: GrantDeps, page: AdminPageId, action?: string): Promise<{
|
|
40
|
+
location: string;
|
|
41
|
+
cookie: string;
|
|
42
|
+
}>;
|
|
43
|
+
/** The page a sealed grant cookie is for, once its `state` matches; null when it does not. */
|
|
44
|
+
export declare function openGrant(deps: GrantDeps, cookie: string | undefined, state: string): Promise<GrantState | null>;
|
|
45
|
+
export interface Grant {
|
|
46
|
+
readonly page: AdminPageId;
|
|
47
|
+
readonly admin: {
|
|
48
|
+
readonly sub: string;
|
|
49
|
+
readonly email: string;
|
|
50
|
+
};
|
|
51
|
+
/** The person's access token, valid only while `use` runs. Never logged, shown or stored. */
|
|
52
|
+
readonly accessToken: string;
|
|
53
|
+
/** Every scope Cloudflare granted. */
|
|
54
|
+
readonly granted: readonly string[];
|
|
55
|
+
/** The page's optional scopes the person unticked. */
|
|
56
|
+
readonly missing: readonly string[];
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Completes the grant `g` with the callback's `code`, checks the person is an administrator of the
|
|
60
|
+
* account, and runs `use`; the tokens are revoked when it ends.
|
|
61
|
+
*/
|
|
62
|
+
export declare function useGrant<T>(deps: GrantDeps, g: GrantState, code: string, use: (grant: Grant) => Promise<T>): Promise<T>;
|
|
63
|
+
export {};
|