@lago-morph/create-prototype-app 0.1.1 → 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 CHANGED
@@ -16,7 +16,7 @@ npm run dev
16
16
  4. copies the Claude Code skill for the framework into `.claude/skills/prototype-framework/`, so Claude Code finds it in the app's folder;
17
17
  5. runs `npm install`;
18
18
  6. runs `git init` (unless the folder is already inside a git repository);
19
- 7. sets a random local value for each of the app's secrets in `.dev.vars`, and makes sure `.gitignore` lists `.env.cloudflare`;
19
+ 7. sets a random local value for each of the app's secrets in `.dev.vars` (the Cloudflare token is not kept in the app: `npm run cloudflare-setup` later prints the two-line template `CLOUDFLARE_API_TOKEN=` / `CLOUDFLARE_ACCOUNT_ID=` for `~/.secrets/cloudflare` or the environment);
20
20
  8. makes the first commit.
21
21
 
22
22
  It asks for no account. If git is missing or a git step fails, it warns and carries on. It ends with what to do next: `cd my-app`, then `npm run dev`, or open the folder in Claude Code and say what to build.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lago-morph/create-prototype-app",
3
- "version": "0.1.1",
3
+ "version": "0.2.0-rc02",
4
4
  "description": "Start a new app on @lago-morph/prototype-framework: npm create @lago-morph/prototype-app my-app",
5
5
  "keywords": [
6
6
  "create",
package/skill/SKILL.md CHANGED
@@ -15,9 +15,9 @@ Read this page, then only the references your task needs (task map below).
15
15
 
16
16
  1. **Use only the framework's public exports**: `@lago-morph/prototype-framework` in server code, `/client` in browser code, `/testing` in tests, plus `hono` and `zod`. No platform SDKs, database drivers, Node built-ins or other framework subpaths.
17
17
  2. **Never insert user text as HTML.** Build elements and set `textContent`; no `innerHTML` or other raw-HTML sinks.
18
- 3. **Pass `npm run verify` before declaring any work done.** Never disable, suppress or weaken a check (`eslint-disable`, `@ts-ignore`, `any`, `as` casts, editing lint configuration).
18
+ 3. **Pass `npm run verify` before declaring any work done**, including its e2e-api tests, and `npm run test:e2e:ui` when a page changed. Never skip or weaken a test, and never disable, suppress or weaken a check (`eslint-disable`, `@ts-ignore`, `any`, `as` casts, editing lint configuration).
19
19
  4. **Claim an app works on a cloud only after its smoke test has passed on a deployed stage there** (`smoke --target <t> --stage test-…`). Local success says nothing about a cloud.
20
- 5. **Never change framework version pins**: the exact versions of `@lago-morph/prototype-framework`, `hono`, `zod`, `typescript`, `vite` and `vitest` in the app's `package.json`.
20
+ 5. **Never change framework version pins**: the exact versions of `@lago-morph/prototype-framework`, `hono`, `zod`, `typescript`, `vite`, `vitest`, `@vitest/browser-playwright`, `@playwright/test` and `fast-check` in the app's `package.json`.
21
21
  6. **Never work around the framework.** If you suspect a framework defect (a contract or reference that does not hold, a check that rejects code the references allow, a capability that is missing for the task), add an entry to `FRAMEWORK-ISSUE.md` at the app's root instead of patching, copying or bypassing framework code. Each entry states:
22
22
  - the task attempted;
23
23
  - the contract or reference consulted (file and section);
@@ -31,9 +31,9 @@ Read this page, then only the references your task needs (task map below).
31
31
 
32
32
  ## Cloudflare setup
33
33
 
34
- On "set up Cloudflare", "continue prototype setup" or "continue setup", run `npm run cloudflare-setup` and relay its output as is: links, template and next prompt unchanged. It does only what is missing, so run it again whenever asked. Exit status 1 with a message is a stop for the user, not a failure to work around. What to do when it stops: [owner-tasks.md](reference/owner-tasks.md) §2.
34
+ On "set up Cloudflare", "continue prototype setup" or "continue setup", run `npm run cloudflare-setup` and relay its output as is: links, template and next prompt unchanged. It does only what is missing, so run it again whenever asked. Exit status 1 with a message is a stop for the user, not a failure to work around. The flow: with no credential, setup prints a template and a token link; the owner puts the token and account ID in `~/.secrets/cloudflare` or the session's environment and says "continue prototype setup"; setup then sets the account up, never changing the owner's token. Steps and stops: [owner-tasks.md](reference/owner-tasks.md) §2.
35
35
 
36
- - **Never open, print or search `.env.cloudflare`**, and never echo `CLOUDFLARE_API_TOKEN` or `CLOUDFLARE_BOOTSTRAP_TOKEN`. The CLI reads them itself. Never ask for a token in the chat.
36
+ - **Never open, print or search `.env.cloudflare` or `~/.secrets/cloudflare`** (or the file `CLOUDFLARE_SECRETS_FILE` names), and never echo `CLOUDFLARE_API_TOKEN` or `CLOUDFLARE_BOOTSTRAP_TOKEN`. The CLI reads them itself. Never ask for a token in the chat.
37
37
  - **Git checks**, when a session starts work on the app and before every commit or push: `git check-ignore -q .env.cloudflare` and `git ls-files --error-unmatch .env.cloudflare`. Each time the file is not ignored (the first exits non-zero) or is tracked (the second exits 0), remind the user and point to [owner-tasks.md](reference/owner-tasks.md) §2. Never refuse to commit because of it.
38
38
 
39
39
  ## Task map
@@ -49,19 +49,19 @@ On "set up Cloudflare", "continue prototype setup" or "continue setup", run `npm
49
49
  | Add a per-stage setting | [configuration.md](reference/configuration.md) |
50
50
  | Use an API key; sign or verify data | [secrets.md](reference/secrets.md) |
51
51
  | Record what happened | [log.md](reference/log.md) |
52
- | Test (in-process, time-dependent, smoke) | [testing.md](reference/testing.md) |
52
+ | Test (TDD, in-process, e2e, smoke, fuzz); a test or check fails; a test must change | [testing.md](reference/testing.md) and the file it names |
53
53
  | Deploy, run the smoke test on a cloud, remove a stage | [deploying.md](reference/deploying.md) |
54
54
  | Diagnose a failing request or deploy; a `verify` diagnostic | [troubleshooting.md](reference/troubleshooting.md), and the reference the diagnostic names |
55
- | Set up Cloudflare; steps the owner performs (tokens and email domain, secrets, sign-up and sign-in, admins, deploy and remove, logs) | [owner-tasks.md](reference/owner-tasks.md) |
55
+ | Set up Cloudflare; steps the owner performs (the one token, secrets, sign-in, admins, deploy and remove, logs) | [owner-tasks.md](reference/owner-tasks.md) |
56
56
 
57
57
  Every `verify` diagnostic ends with `(read skill/reference/<file>.md)`; that file has a "Check rules that send you here" section for the rule.
58
58
 
59
59
  ## Examples and templates
60
60
 
61
- Examples are whole files copied unchanged from the framework's template and compliance reference app, which CI type-checks and tests: [endpoint-and-page](examples/endpoint-and-page.md), [notes-sql](examples/notes-sql.md), [status-kv](examples/status-kv.md), [files-tickets](examples/files-tickets.md), [admin-and-current-user](examples/admin-and-current-user.md), [secrets](examples/secrets.md), [configuration](examples/configuration.md), [tests](examples/tests.md). Start from the template, not from any other app.
61
+ Examples are whole files copied unchanged from the template and the reference app, type-checked and tested in CI: [endpoint-and-page](examples/endpoint-and-page.md), [notes-sql](examples/notes-sql.md), [status-kv](examples/status-kv.md), [files-tickets](examples/files-tickets.md), [admin-and-current-user](examples/admin-and-current-user.md), [secrets](examples/secrets.md), [configuration](examples/configuration.md), [tests](examples/tests.md). Start from the template, not from any other app.
62
62
 
63
- A new app starts from the template: `npm create @lago-morph/prototype-app@latest <dir>`, or `skill/scripts/scaffold <dir>` in a checkout of the framework repository ([local-development.md](reference/local-development.md)); [templates/](templates/README.md) holds the other files you fill in.
63
+ A new app starts from the template: `npm create @lago-morph/prototype-app@latest <dir>`, or `skill/scripts/scaffold <dir>` in the framework repository ([local-development.md](reference/local-development.md)); [templates/](templates/README.md) holds the files you fill in.
64
64
 
65
65
  ## Done means
66
66
 
67
- `npm run verify` passes; every requirement is implemented and tested; for each cloud you claim, the smoke test passed on a deployed test stage there; and `FRAMEWORK-ISSUE.md` has no open entry blocking a requirement. Cloud runs that could not go ahead are listed as unfinished (`not-run` or `blocked`, hard rule 8), not raised as issues.
67
+ `npm run verify` passes; every requirement is implemented and tested, each flow end to end ([testing.md](reference/testing.md)); for each cloud you claim, the smoke test passed on a deployed test stage there; and `FRAMEWORK-ISSUE.md` has no open entry blocking a requirement. Cloud runs that could not go ahead are listed as unfinished (`not-run` or `blocked`, hard rule 8), not raised as issues.
package/skill/VERSION CHANGED
@@ -1 +1 @@
1
- 0.1.1
1
+ 0.2.0-rc02
@@ -53,7 +53,7 @@ import type { NoteList } from "../../shared/types";
53
53
  import type { Env } from "../env";
54
54
  import { notes } from "../schema";
55
55
 
56
- const newNote = z.object({ text: z.string().trim().min(1).max(500) });
56
+ export const newNote = z.object({ text: z.string().trim().min(1).max(500) });
57
57
 
58
58
  /** SQL and log: a logged-in user writes notes and lists their own. */
59
59
  export function noteRoutes(api: Hono<Env>): void {
@@ -118,11 +118,14 @@ function toBase64url(bytes: Uint8Array): string {
118
118
  function fromBase64url(text: string): Uint8Array<ArrayBuffer> | null {
119
119
  if (!/^[A-Za-z0-9_-]+$/.test(text)) return null;
120
120
  const base64 = text.replaceAll("-", "+").replaceAll("_", "/").padEnd(Math.ceil(text.length / 4) * 4, "=");
121
+ let bytes: Uint8Array<ArrayBuffer>;
121
122
  try {
122
- return Uint8Array.from(atob(base64), (ch) => ch.charCodeAt(0));
123
+ bytes = Uint8Array.from(atob(base64), (ch) => ch.charCodeAt(0));
123
124
  } catch {
124
125
  return null;
125
126
  }
127
+ // atob ignores the unused low bits of the last character, so accept only the canonical spelling.
128
+ return toBase64url(bytes) === text ? bytes : null;
126
129
  }
127
130
 
128
131
  /** A token for `subject` that verifies until `expiresAt` (milliseconds since the epoch). */
@@ -177,6 +180,22 @@ describe("signed tokens (HMAC, base64url)", () => {
177
180
  }
178
181
  });
179
182
 
183
+ // root cause 2026-10-31-G-template-signing-noncanonical: a 32-byte signature is 43 base64url
184
+ // characters, so its last character carries 2 unused bits; only the issued spelling may verify.
185
+ it("accepts only the issued spelling of a signature, not one re-spelled in its last character", async () => {
186
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
187
+ const token = await signToken(key, "note-1", Date.now() + 60_000);
188
+ const [subject = "", expiresAt = "", signature = ""] = token.split(".");
189
+ expect(signature).toHaveLength(43);
190
+ const last = alphabet.indexOf(signature.slice(-1));
191
+ expect(last % 4, "the issued spelling leaves the unused low bits at zero").toBe(0);
192
+ for (const flip of [1, 2, 3]) {
193
+ const respelled = signature.slice(0, -1) + (alphabet[last ^ flip] ?? "");
194
+ expect(await verifyToken(key, `${subject}.${expiresAt}.${respelled}`), respelled.slice(-3)).toBeNull();
195
+ }
196
+ expect(await verifyToken(key, token)).toBe("note-1");
197
+ });
198
+
180
199
  it("refuses a token once it has expired", async () => {
181
200
  vi.useFakeTimers();
182
201
  vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
@@ -7,6 +7,7 @@ What it shows:
7
7
  - `tests/app.test.ts`: `createTestApp` per test with `dispose()` afterwards; `mockUsers` with `as()` and the `user` option; `config` and `secrets` options; asserting status codes, error codes and `logs()`; an in-process upload sent with the ticket's wire form, to test the finalize route (the form is the same on every target; only `url` differs: here a path on the app, sent with `t.request`; on a cloud an absolute storage URL, which tests send with plain `fetch`, never a test helper, see "The smoke test" in [testing.md](../reference/testing.md)) (the HMAC tests are in [secrets.md](secrets.md)).
8
8
  - `tests/smoke/smoke.test.ts`: one file that runs in-process under `verify` and against a deployed test stage under `smoke` (`connectTestStage()`).
9
9
  - From the reference app, `tests/support.ts`: a shared `open()` helper that disposes test apps after each test.
10
+ - `tests/e2e/`: the e2e layer, against a local `dev` server that the template's `playwright.config.ts` has Playwright start and stop. `api/notes.spec.ts` drives one flow through the HTTP API (project `e2e-api`, no browser, run by `verify`) with its edge cases listed first; `ui/account.spec.ts` is the one browser test, of what only a page shows (project `e2e-ui`) ([e2e.md](../reference/testing/e2e.md)).
10
11
 
11
12
  ## `apps/template/tests/app.test.ts`
12
13
 
@@ -285,3 +286,111 @@ export interface ErrorBody {
285
286
  readonly error: { readonly code: string; readonly message: string; readonly requestId: string };
286
287
  }
287
288
  ```
289
+
290
+ ## `apps/template/tests/e2e/api/notes.spec.ts`
291
+
292
+ <!-- example-source: apps/template/tests/e2e/api/notes.spec.ts -->
293
+ ```ts
294
+ import { expect, test, type APIRequestContext, type APIResponse } from "@playwright/test";
295
+ import type { NoteList } from "../../../src/shared/types";
296
+
297
+ /**
298
+ * The notes flow end to end, through the HTTP API of a local `dev` server: a person signs in,
299
+ * writes notes and lists their own. Most of a flow's e2e cases are API tests like these.
300
+ *
301
+ * Edge cases, listed before the tests (the skill's reference/testing/e2e.md):
302
+ * - Boundaries: empty text and text of only spaces are refused; 500 characters are accepted; 501 are refused.
303
+ * - Text: Unicode text comes back unchanged; surrounding spaces are trimmed. Case, `..`, `/`,
304
+ * percent-encoding and prefix names do not apply: a note is free text, never a name or a path.
305
+ * - Order and time: not asserted here. Two notes made in the same millisecond tie on their time and
306
+ * fall back to their random IDs; there is no expiry.
307
+ * - Access: anonymous is refused (401); another user does not see the notes. Admin does not apply:
308
+ * the notes routes treat an admin as any user, and there is no admin view of notes.
309
+ * - Repetition: the same text twice makes two notes. Concurrent writes do not apply: each request
310
+ * inserts one row with a new ID, and the notes contract promises nothing about concurrency.
311
+ * - Failures: an unavailable database is simulated in-process only (`setUnavailable`, tests/app.test.ts).
312
+ */
313
+
314
+ /** Signs `request` in as a fresh mock user (local data is kept between runs) and returns its ID. */
315
+ async function signIn(request: APIRequestContext): Promise<string> {
316
+ const id = `e2e-${crypto.randomUUID()}`;
317
+ const res = await request.post("/api/auth/mock-login", { data: { level: "user", id } });
318
+ expect(res.status()).toBe(204);
319
+ return id;
320
+ }
321
+
322
+ async function errorCode(res: APIResponse): Promise<string | undefined> {
323
+ const body: { error?: { code?: string } } = await res.json();
324
+ return body.error?.code;
325
+ }
326
+
327
+ test("a signed-in user writes notes and lists only their own", async ({ request }) => {
328
+ await signIn(request);
329
+ const text = `Ünïcödé ✓ ${crypto.randomUUID()}`;
330
+ const created = await request.post("/api/notes", { data: { text: ` ${text} ` } });
331
+ expect(created.status()).toBe(201);
332
+ const again = await request.post("/api/notes", { data: { text } });
333
+ expect(again.status()).toBe(201);
334
+
335
+ const mineRes = await request.get("/api/notes");
336
+ expect(mineRes.status()).toBe(200);
337
+ const mine: NoteList = await mineRes.json();
338
+ expect(mine.notes.filter((n) => n.text === text)).toHaveLength(2);
339
+
340
+ // A new mock login replaces the session: now another user.
341
+ await signIn(request);
342
+ const theirsRes = await request.get("/api/notes");
343
+ expect(theirsRes.status()).toBe(200);
344
+ const theirs: NoteList = await theirsRes.json();
345
+ expect(theirs.notes.filter((n) => n.text === text)).toEqual([]);
346
+ });
347
+
348
+ test("anonymous requests are refused", async ({ request }) => {
349
+ const list = await request.get("/api/notes");
350
+ expect(list.status()).toBe(401);
351
+ expect(await errorCode(list)).toBe("AUTH.UNAUTHENTICATED");
352
+ const write = await request.post("/api/notes", { data: { text: "hello" } });
353
+ expect(write.status()).toBe(401);
354
+ });
355
+
356
+ test("note text must be 1 to 500 characters after trimming", async ({ request }) => {
357
+ await signIn(request);
358
+ for (const text of ["", " ", "x".repeat(501)]) {
359
+ const res = await request.post("/api/notes", { data: { text } });
360
+ expect(res.status(), JSON.stringify(text.slice(0, 20))).toBe(400);
361
+ expect(await errorCode(res)).toBe("HTTP.INVALID_INPUT");
362
+ }
363
+ expect((await request.post("/api/notes", { data: { text: "x".repeat(500) } })).status()).toBe(201);
364
+ const missing = await request.post("/api/notes", { data: {} });
365
+ expect(missing.status()).toBe(400);
366
+ expect(await errorCode(missing)).toBe("HTTP.INVALID_INPUT");
367
+ });
368
+ ```
369
+
370
+ ## `apps/template/tests/e2e/ui/account.spec.ts`
371
+
372
+ <!-- example-source: apps/template/tests/e2e/ui/account.spec.ts -->
373
+ ```ts
374
+ import { expect, test } from "@playwright/test";
375
+
376
+ /**
377
+ * What only a browser shows: the home page renders the greeting, and the login button signs in
378
+ * (locally, the authentication mock's default user). Every other case is an API test (../api/).
379
+ *
380
+ * Edge cases, listed before the test (the skill's reference/testing/e2e.md): access is the one that
381
+ * applies here (anonymous sees "Log in", a signed-in user sees "Log out"); boundaries, text, order,
382
+ * repetition and failures are covered by the API and in-process tests.
383
+ */
384
+ test("the login button signs in, and the page shows who is logged in", async ({ page }) => {
385
+ await page.goto("/");
386
+ await expect(page.getByRole("heading", { level: 1 })).toHaveText("Hello");
387
+ await expect(page.getByText("You are not logged in.")).toBeVisible();
388
+
389
+ await page.getByRole("button", { name: "Log in" }).click();
390
+ await expect(page.getByText(/^Logged in as .+ \(user\)\.$/)).toBeVisible();
391
+ await expect(page.getByRole("button", { name: "Log out" })).toBeVisible();
392
+
393
+ await page.getByRole("button", { name: "Log out" }).click();
394
+ await expect(page.getByText("You are not logged in.")).toBeVisible();
395
+ });
396
+ ```
@@ -32,12 +32,12 @@ Each file has exactly two members:
32
32
  ```json
33
33
  {
34
34
  "values": { "greeting": "Hello from production" },
35
- "framework": { "email": { "senderName": "Notes" } }
35
+ "framework": {}
36
36
  }
37
37
  ```
38
38
 
39
39
  - `values` holds values for your declared keys; keys with a default may be left out. A key you did not declare, a missing value for a key without a default, or a wrong type fails the build with `CORE.MISCONFIGURED`, naming the file and every bad field.
40
- - `framework` holds only `email` (only `senderName`, the display name of the framework's sign-up and reset mail; optional, default the app name). It holds no address or domain: the sender address comes from the account's email domain, which the owner sets up once ([owner-tasks.md](owner-tasks.md)).
40
+ - `framework` is empty (`{}`): the framework sends no email, and who may sign in comes from the owner's Cloudflare account ([current-user.md](current-user.md)). `framework.admins` and `framework.users` fail the build.
41
41
  - A production stage reads only its own file and never falls back to `test.json`, so create `config/<target>/<stage>.json` before its first deploy.
42
42
  - Never put a secret in these files: there is no place for one.
43
43
 
@@ -47,7 +47,7 @@ App code reads configuration only through `c.var.config`. Never read `process.en
47
47
 
48
48
  ## In tests
49
49
 
50
- `createTestApp(app, { config: { greeting: "Hi there" } })` overrides declared values; an undeclared key makes it throw. The reserved key `framework` takes only `email`; `admins` or `users` make it throw, as the build does. Test roles with `grantRole` ([current-user.md](current-user.md)).
50
+ `createTestApp(app, { config: { greeting: "Hi there" } })` overrides declared values; an undeclared key makes it throw. The reserved key `framework` takes no `admins` or `users`: they make it throw, as the build does. Test role changes with the fake auth app ([current-user.md](current-user.md)).
51
51
 
52
52
  ## Check rules that send you here
53
53
 
@@ -13,12 +13,12 @@ Store `c.var.user.id` in your rows to record ownership (an `ownerId: text()` col
13
13
 
14
14
  ## Levels
15
15
 
16
- - **Anyone who signs up and verifies their email address is a user.** Level `user` means *any verified account*, not a person this app trusts; there is no list of allowed people. An unverified account cannot sign in.
17
- - **Admins** are users holding the `admin` role, stored with the account in the stage's own database. There is no "user" role: a new account has no roles.
18
- - The level is read from the account on every request with a session, so a grant or revoke applies from the person's next request, with no deploy and no new login.
16
+ - **Only members of the owner's Cloudflare account can sign in.** Level `user` means *any member of that account*, not a person this app trusts; an app that needs finer trust keeps its own records (for example a table of allowed user IDs).
17
+ - **Admins** are members whose account role is one of PAR-413's administrator roles ("Super Administrator - All Privileges", "Administrator"). There is no "user" role, and no list of allowed people.
18
+ - The auth app records the person's role at each sign-in, and the app re-reads that record every 5 minutes (PAR-425). So a role change in the dashboard shows after the person next signs in (to any app on the account), with no deploy; removing a member does not end a session they already have. If the role cannot be confirmed, the person is signed out: a protected route then answers 401.
19
19
  - Configuration holds no admins or users: `framework.admins` and `framework.users` are rejected by the build.
20
20
 
21
- How someone becomes an admin (copy-and-paste steps): [owner-tasks.md](owner-tasks.md) §7. In short: they sign up and verify on the stage, then the owner (or an agent) runs `npm run admins -- grant <address> --target <t> --stage <s>`, adding `--confirm-production <s>` on a production stage; `admins revoke` takes it away and `admins list` shows the admins.
21
+ How someone becomes an admin: [owner-tasks.md](owner-tasks.md) §7. In short: the owner gives them one of those roles in the Cloudflare dashboard (Manage Account → Members), and they sign in again; another role takes it away the same way. `/api/auth/me` shows a person's level and user ID.
22
22
 
23
23
  ## Protecting routes
24
24
 
@@ -37,22 +37,22 @@ From `@lago-morph/prototype-framework/client`: `getCurrentUser()` (the user as t
37
37
 
38
38
  A failed login returns to `/?authError=login_failed&requestId=<id>`. Show a message with the request ID; the reason is in the log ([troubleshooting.md](troubleshooting.md)).
39
39
 
40
- Sessions last 7 days (PAR-250). There is no server-side session list: logging out clears this browser's cookie only.
40
+ Sessions last 12 hours (PAR-250). There is no server-side session list: logging out clears this browser's cookie only.
41
41
 
42
42
  ## Which login runs where
43
43
 
44
44
  | Where | Login |
45
45
  | --- | --- |
46
- | Local `dev` | Email and password: the login button opens the sign-in page; mail is written to `.mail/` (`npm run mail -- last --to <address>`). Tests may also use the authentication mock. |
47
- | Test stages (`test-*`) | Email and password, plus the authentication mock for tests (`mockUsers`, `connectTestStage`) |
48
- | Production stages | Email and password only, with real mail ([owner-tasks.md](owner-tasks.md) §6) |
46
+ | Local `dev` | The authentication mock: the login button signs in a test user. |
47
+ | Test stages (`test-*`) | The authentication mock only, for tests (`mockUsers`, `connectTestStage`) |
48
+ | Production stages | Sign-in with Cloudflare through the account's auth app ([owner-tasks.md](owner-tasks.md) §6) |
49
49
 
50
50
  The mock chooses the level directly: it reads no roles.
51
51
 
52
52
  ## Testing
53
53
 
54
54
  - Choose the identity per test app: `createTestApp(app, { user: mockUsers.user("alice") })`, or `t.as(mockUsers.admin())` for further requests with another identity (sharing the same storage). `mockUsers.user(id?)` and `mockUsers.admin(id?)` use the ID as given.
55
- - To test the **real login and roles**, use `createTestApp(app, { passwordLoginProvider: true })`: sign up, read the mail with `t.mail.lastTo(address)`, verify and sign in through the app's requests. `t.grantRole(userId, "admin")` and `t.revokeRole(userId, "admin")` change that account's roles as `admins` does (the ID as `/api/auth/me` shows it); the next request sees the new level. `as()` is not available on such a test app.
55
+ - To test the **real sign-in and role changes**, use `createTestApp(app, { authAppLoginProvider: true })`: `await t.loginWithAuthApp({ sub: "cf-1", email: "a@example.com", role: "user" })` signs in through a fake auth app. `t.authApp.setRole("cf-1", "admin")` changes the role the next refresh reads; move `t.clock.advance(…)` past PAR-425 to see it, with no new login. `t.authApp.setUnavailable(true)` makes the refresh fail, which signs the person out. `as()` is not available on such a test app.
56
56
  - Assert 401 `AUTH.UNAUTHENTICATED` for anonymous and 403 `AUTH.FORBIDDEN` for a user on admin routes. See [testing.md](testing.md).
57
57
 
58
58
  ## Examples
@@ -62,4 +62,4 @@ The mock chooses the level directly: it reads no roles.
62
62
 
63
63
  ## Stopping condition
64
64
 
65
- Stop reading when every private route has a guard and filters by `c.var.user.id`, admin routes use `requireAdmin()`, the stage's values file has the lists the owner wants, your tests cover anonymous, user and admin callers, and `npm run verify` passes.
65
+ Stop reading when every private route has a guard and filters by `c.var.user.id`, admin routes use `requireAdmin()`, your tests cover anonymous, user and admin callers, and `npm run verify` passes.
@@ -1,13 +1,13 @@
1
1
  # Deploying
2
2
 
3
- Read this when you deploy, smoke-test, stop, start or remove a stage on a cloud. Cloudflare setup (the tokens and the email domain), secrets, sign-up and admins are in [owner-tasks.md](owner-tasks.md).
3
+ Read this when you deploy, smoke-test, stop, start or remove a stage on a cloud. Cloudflare setup (the one token), secrets, sign-in and admins are in [owner-tasks.md](owner-tasks.md).
4
4
 
5
- Commands run in the app's directory, after `npm run cloudflare-setup` has said everything is set up ([owner-tasks.md](owner-tasks.md) §2); each reads the tokens itself, from the environment or `.env.cloudflare`. Each `npm run <command> -- …` is the same as `npm exec --no -- prototype-framework <command> …`. Behind an HTTPS proxy, put `NODE_USE_ENV_PROXY=1 ` in front of every cloud command; the command says so if it is needed.
5
+ Commands run in the app's directory, after `npm run cloudflare-setup` has said everything is set up ([owner-tasks.md](owner-tasks.md) §2); each reads the token itself, from the environment or `~/.secrets/cloudflare`. Each `npm run <command> -- …` is the same as `npm exec --no -- prototype-framework <command> …`. Behind an HTTPS proxy, put `NODE_USE_ENV_PROXY=1 ` in front of every cloud command; the command says so if it is needed.
6
6
 
7
7
  ## 1. Test stages and production stages
8
8
 
9
- - A stage whose name starts with `test-` is a **test stage**. It uses `config/cloudflare/test.json`, has the mock login for tests beside email-and-password sign-in, keeps its mail in a test capture (never sent), holds no real data, and is removed after use.
10
- - Every other stage is a **production stage**, for example `prod`. It needs its own committed `config/cloudflare/<stage>.json` ([owner-tasks.md](owner-tasks.md) §5) and the account's email domain (§3 there). It has no mock: people sign up with email and password, and real mail is sent from `no-reply@<domain>`.
9
+ - A stage whose name starts with `test-` is a **test stage**. It uses `config/cloudflare/test.json`, has only the mock login for tests (no real sign-in), holds no real data, and is removed after use.
10
+ - Every other stage is a **production stage**, for example `prod`. It needs its own committed `config/cloudflare/<stage>.json` ([owner-tasks.md](owner-tasks.md) §5) and the account's auth app (§2 there). It has no mock: members of the owner's Cloudflare account sign in with Cloudflare.
11
11
  - A stage name is at most 20 lowercase letters, digits and hyphens. The stage's address is `https://<app>-<stage>.<subdomain>.workers.dev`.
12
12
 
13
13
  ## 2. Deploy and smoke-test a test stage
@@ -42,8 +42,8 @@ npm run smoke -- --target cloudflare --stage "$STAGE"
42
42
  npm run secrets -- set apiKey --target cloudflare --stage "$STAGE"
43
43
  npm run deploy -- --target cloudflare --stage "$STAGE"
44
44
  ```
45
- It prints the stage's address, its sign-in page and the sender address.
46
- 3. Sign up on the stage, then make yourself an admin with `admins grant` ([owner-tasks.md](owner-tasks.md) §6, §7). Admins change without a deploy.
45
+ It registers the stage with the auth app and prints the stage's address.
46
+ 3. Sign in on the stage ([owner-tasks.md](owner-tasks.md) §6). Admins are the account's administrators (§7 there); they change without a deploy.
47
47
 
48
48
  To change a production stage later (code or configuration), commit the change and run `deploy` again:
49
49
 
@@ -1,8 +1,8 @@
1
1
  # Owner tasks
2
2
 
3
- Read this when the app's owner (or an agent acting for them) must do something outside the code: set up Cloudflare (its two tokens and the email domain), set secrets, create a production stage, sign up and sign in, make someone an admin, or keep costs down. Give the owner these steps as written. The owner does not read code.
3
+ Read this when the app's owner (or an agent acting for them) must do something outside the code: set up Cloudflare (one token, one command), set secrets, create a production stage, sign in, make someone an admin, or keep costs down. Give the owner these steps as written. The owner does not read code.
4
4
 
5
- Commands run in a terminal, in the app's directory, on macOS or Linux with Node 22.22.0. Replace `<…>` parts; `<domain>` is the account's email domain. Never paste a secret value into a command line, a file in the repository, or a chat.
5
+ Commands run in a terminal, in the app's directory, on macOS or Linux with Node 22.22.0. Replace `<…>` parts. Never paste a secret value or a token into a command line, a file in the repository, or a chat.
6
6
 
7
7
  ## 1. Before anything else (once per checkout)
8
8
 
@@ -22,46 +22,47 @@ Set the stage's name in `STAGE` once in each new terminal (`<stage>` is for exam
22
22
  STAGE='<stage>'
23
23
  ```
24
24
 
25
- ## 2. Cloudflare: two links and one command
25
+ ## 2. Cloudflare: one token, one command
26
26
 
27
- You need a Cloudflare account on the **Workers Paid** plan (sign-in sends email, which needs it), and a **domain on that account with Cloudflare DNS active** (Websites → Add a site). Its mail can stay where it is.
27
+ Any Cloudflare account works, on the free Workers plan too. No domain is needed. You need one Cloudflare API token and your account ID. The steps, in order:
28
28
 
29
- 1. Run the setup. It prints no token value and does only what is missing:
29
+ 1. **Run the setup.** It prints no token value and does only what is missing:
30
30
  ```sh
31
31
  npm run cloudflare-setup
32
32
  ```
33
- With no tokens yet, it prints two links, a template, where the values go, and the next prompt.
34
- 2. Open each link while logged in to the dashboard. The permissions and name are filled in. Pick your account if asked and keep the email domain's zone included; for the bootstrap token, under TTL set an end date 7 days away or sooner (PAR-380). Then Continue to summary, Create Token, and copy it: Cloudflare shows it only once.
35
- - **Everyday token** `prototype-framework` (7 permissions), kept for every command. It cannot create tokens and has no zone write permission.
36
- - **Bootstrap token** `prototype-framework-bootstrap` (12 permissions), used once: setup deletes it when done.
33
+ With no token yet, it prints this two-line template, where the lines go, the token's pre-filled link and the next prompt:
34
+ ```
35
+ CLOUDFLARE_API_TOKEN=
36
+ CLOUDFLARE_ACCOUNT_ID=
37
+ ```
38
+ 2. **Make the token** `prototype-framework-cli` from that link, logged in to the dashboard. Its permissions and name are filled in; keep them (more is fine). Pick your account if asked and choose any end date, or none. Then Continue to summary, Create Token, and copy it: Cloudflare shows it only once. A token you already have with more permissions (an account admin token, say) works too. Your **account ID** is on the account's home page in the dashboard.
39
+ 3. **Fill in the two lines and put them in one place** (the environment wins when both are set):
40
+ - **On your computer:** the file `~/.secrets/cloudflare` in your home directory, then `chmod 600 ~/.secrets/cloudflare`. Every app, worktree and Claude Code session on the machine shares it. `CLOUDFLARE_SECRETS_FILE` names another path if you want one.
41
+ - **In a Claude Code cloud session:** the environment's settings (environment menu → Edit → Environment variables), the same two lines; then start a new session.
42
+ Never paste the token into the chat or into a file in the repository.
43
+ 4. **Run `npm run cloudflare-setup` again** (in Claude Code, say **"continue prototype setup"**). It says where each value came from (the variable or the file, never the value), checks the token's permissions, and sets the account up in one run: the admin app's client and the sign-in client with their secrets in Cloudflare's Secrets Store, the **admin app**, the account's **auth app** (it signs people in to every app) and the shared resources (§3). It ends with "Cloudflare setup is complete" and the next step, a `deploy` of a `test-` stage. Run again, it says everything is already set up.
37
44
 
38
- Both permission lists are in the framework repository's [QUICKSTART.md](https://github.com/lago-morph/cloud-app/blob/main/QUICKSTART.md). Setup names any permission a token lacks.
39
- 3. Put the values where setup reads them, in the four lines of the template (`CLOUDFLARE_BOOTSTRAP_TOKEN`, `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_EMAIL_DOMAIN`, and `CLOUDFLARE_ACCOUNT_ID` only if your tokens see more than one account):
40
- - **In a Claude Code cloud session:** the environment's settings (environment menu → Edit → Environment variables), then start a new session.
41
- - **On your computer:** the file `.env.cloudflare` in the app's folder (setup writes the template there; git ignores it), in your editor; or the environment. The environment wins when both are set.
42
- 4. Run `npm run cloudflare-setup` again (in Claude Code, say **"continue prototype setup"**), until it says everything is set up. On success it deletes the bootstrap token, comments out its line, and fills in an empty account and email domain: copy `.env.cloudflare` into another app's folder to start that one. In a cloud session you may then remove the bootstrap variable.
45
+ **The framework never deletes, rolls or changes your token.** It makes and replaces only the tokens it needs for itself (the file-signing token `prototype-r2-signing`). The admin app (its address is printed once) is optional: it has status and cleanup pages.
43
46
 
44
47
  **When setup stops** (exit status 1), it says what is missing with the link or command to use. Do that, then run it again; it exits 0 only when all is set up:
45
48
 
46
49
  | It says | Do this |
47
50
  | --- | --- |
48
- | two tokens are needed (no everyday token) | steps 2–4 |
49
- | a setting's token is not accepted, not active, the same in both settings, of another account, or lacks a permission | make it again from the link it prints; replace its line |
50
- | the bootstrap token cannot read API tokens ("was the everyday token pasted there?"), or is a user token | make it from the bootstrap link (an account token) |
51
- | several accounts, by name | copy the chosen account's ID from the dashboard into `CLOUDFLARE_ACCOUNT_ID` |
52
- | which domain should the emails come from | set `CLOUDFLARE_EMAIL_DOMAIN`, or run `npm run cloudflare-setup -- --email-domain <domain>`; with no domain, add one |
53
- | the plan is Workers Free | upgrade it (Workers & Pages → Plans) |
54
- | this needs the bootstrap token once (with the reasons) | make it from the link and set `CLOUDFLARE_BOOTSTRAP_TOKEN`; the everyday token keeps its value |
55
- | the everyday token must be made again (wrong zone or account, a denied permission) | make it from the everyday link; setup kept the bootstrap token to check it |
56
- | the tokens belong to another account than this project's | remove the old account's stages first if you want, with its everyday token, then `npm run cloudflare-setup -- --switch-account` |
51
+ | no Cloudflare credential, or one of the two settings is not set | steps 2–3 |
52
+ | the token is not accepted or not active | make a token from the link (step 2) and replace `CLOUDFLARE_API_TOKEN` |
53
+ | the token lacks these permissions (named) | add them to the token in the dashboard (Manage account → Account API tokens → the token → Edit), or make a new one from the link |
54
+ | the token cannot read its own permissions | it lacks Account API Tokens Edit: add it, or make a new token from the link |
55
+ | the token cannot see the account `CLOUDFLARE_ACCOUNT_ID` names (accounts listed by name) | set `CLOUDFLARE_ACCOUNT_ID` to the right account's ID, or make the token on that account |
56
+ | the secrets file can be read by other users | `chmod 600 ~/.secrets/cloudflare` (a warning only) |
57
+ | `.env.cloudflare` or `CLOUDFLARE_BOOTSTRAP_TOKEN` is no longer used | move the token and account ID to `~/.secrets/cloudflare` (or the environment), then delete the old file or variable |
57
58
  | a host is blocked | allow `api.cloudflare.com`, `*.r2.cloudflarestorage.com` and `*.workers.dev` in the environment's network access settings |
58
- | `.env.cloudflare` is not ignored, or is tracked | setup adds the `.gitignore` line unless it holds `# keep-env-cloudflare-tracked`. Tracked: delete both tokens, `git rm --cached .env.cloudflare`, commit, make new ones |
59
+ | an old `.env.cloudflare` is not ignored, or is tracked | setup adds the `.gitignore` line unless it holds `# keep-env-cloudflare-tracked`. Tracked: delete the tokens it held, `git rm --cached .env.cloudflare`, commit |
59
60
 
60
- The git warnings never stop a command. Setup never updates or deletes a token whose ID is in `PROTOTYPE_FRAMEWORK_PROTECTED_TOKEN_IDS` (comma-separated). `npm run setup-account -- --target cloudflare --email-domain <domain>` is the account-setup step alone, for scripts.
61
+ The git warnings never stop a command. Setup also never touches a token whose ID is in `PROTOTYPE_FRAMEWORK_PROTECTED_TOKEN_IDS` (comma-separated).
61
62
 
62
63
  ## 3. What the account setup creates
63
64
 
64
- Setup creates the shared resources once per account, including the file-signing credential every stage uses: the log bucket `prototype-logs`, the deploy-state bucket `sst-state`, the backup bucket `prototype-backups` (a removed production stage's data, kept 30 days), the `workers.dev` address, sending from `no-reply@<domain>`, and the test mailbox: mail to `sink+<tag>@t.<domain>` is stored for a day, so an agent can read it. It records what it did in `framework/account.json` in `sst-state`. When it creates the mailbox rule it waits about a minute. To change the domain, set the new `CLOUDFLARE_EMAIL_DOMAIN` and run it again (it needs the bootstrap token). `deploy` never creates these resources; if they are missing, it says to run the setup. When a run replaces the file-signing credential, it says so: then redeploy every deployed stage (`npm run deploy -- --target cloudflare --stage <stage>`), because each one keeps the old key, and its file uploads and downloads fail, until its next deploy.
65
+ `cloudflare-setup` creates, once per account: the admin app and the sign-in clients, the **auth app** with its database, the log bucket `prototype-logs`, the deploy-state bucket `sst-state`, the backup bucket `prototype-backups` (a removed production stage's data, kept 30 days), and the file-signing credential every stage uses, kept in Secrets Store. It records what it did in `framework/account.json` in `sst-state`. `deploy` never creates these resources; if they are missing, it says so. When setup replaces the file-signing credential, redeploy every deployed stage (`npm run deploy -- --target cloudflare --stage <stage>`): until then its file uploads and downloads fail. The admin app's Account setup page does the same and is optional.
65
66
 
66
67
  ## 4. Secrets
67
68
 
@@ -87,7 +88,7 @@ mkdir -p config/cloudflare
87
88
  cp ../../skill/templates/production-stage.json "config/cloudflare/$STAGE.json"
88
89
  ```
89
90
 
90
- Replace `REPLACE-WITH-THE-SENDER-NAME` with the display name of the sign-up and reset mail (or delete the `email` entry to use the app's name). `"values"` may set the app's configuration keys; ask the developer which. Then check, commit and deploy, setting the secrets the first deploy names ([deploying.md](deploying.md)):
91
+ `"values"` may set the app's configuration keys; ask the developer which. Then check, commit and deploy, setting the secrets the first deploy names ([deploying.md](deploying.md)):
91
92
 
92
93
  ```sh
93
94
  npm run build -- --target cloudflare --stage "$STAGE"
@@ -95,63 +96,41 @@ git add "config/cloudflare/$STAGE.json" && git commit -m "Add the values file of
95
96
  npm run deploy -- --target cloudflare --stage "$STAGE"
96
97
  ```
97
98
 
98
- The deploy prints the stage's address, its sign-in page and the sender address.
99
-
100
- ## 6. Signing up and signing in
99
+ The deploy registers the stage with the auth app and prints its address. Without the account's auth app it names it and stops before creating anything: run `npm run cloudflare-setup` (§2) first.
101
100
 
102
- **Anyone who signs up and verifies their address is a user.** No list decides who may log in.
101
+ ## 6. Signing in
103
102
 
104
- 1. Open the stage's sign-in page (`<stage address>/api/auth/sign-in`; locally the app's login button). Choose "Create an account", and enter an email address, a password of 12 to 128 characters, and a display name.
105
- 2. Open the link in the "Confirm your email address" mail, and press the button.
106
- 3. Sign in. `<stage address>/api/auth/me` now shows `"level":"user"`.
103
+ **Only members of your Cloudflare account can sign in**, with their Cloudflare login. Anyone else is refused. No list in the app decides who may log in.
107
104
 
108
- Reading the mail without a mailbox (an agent, or local development):
105
+ 1. Open the stage's address and press the login button (or open `<stage address>/api/auth/login`).
106
+ 2. Sign in on Cloudflare's page, and allow the app to see your user details and memberships.
107
+ 3. You are back on the app. `<stage address>/api/auth/me` shows `"level":"user"` or `"level":"admin"`.
109
108
 
110
- - **Locally** the mail is not sent; it is written to `.mail/`. Read the latest message to an address:
111
- ```sh
112
- npm run mail -- last --to '<address>'
113
- ```
114
- - **On Cloudflare**, sign up with a test address `sink+<tag>@t.<domain>` (`<tag>`: lowercase letters, digits, hyphens), then read it:
115
- ```sh
116
- npm run mail -- last --to 'sink+<tag>@t.<domain>' --target cloudflare
117
- ```
118
- - Without a browser, post the link's token (the value after `token=`) instead of pressing the button:
119
- ```sh
120
- curl -sS -X POST '<stage address>/api/auth/password/verify' -H 'Origin: <stage address>' -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"token":"<token>"}'
121
- ```
122
-
123
- A forgotten password: "Forgot your password?" on the sign-in page mails a reset link, valid for one hour. "Send a new confirmation link" there mails a new verification link.
109
+ To let someone sign in, invite them to the account (Manage Account → Members). A read-only role works, for example "HTTP Applications Read" (plan-v0.2.0 §2.1a). Locally and on `test-` stages there is no real sign-in: the login button signs in a test user.
124
110
 
125
111
  ## 7. Admins
126
112
 
127
- Admins hold the `admin` role in the stage's own database. Granting or revoking it needs no file edit, no commit and no deploy: it applies from the person's next request. The person must have signed up and verified their address on that stage first (§6).
128
-
129
- - **Grant** (on a production stage, repeat its name with `--confirm-production`):
130
- ```sh
131
- npm run admins -- grant '<address>' --target cloudflare --stage "$STAGE" --confirm-production "$STAGE"
132
- ```
133
- - **Revoke:** the same with `revoke`. The person is a user again.
134
- - **List** the stage's admins:
135
- ```sh
136
- npm run admins -- list --target cloudflare --stage "$STAGE" --confirm-production "$STAGE"
137
- ```
138
- - On a test stage, leave out `--confirm-production`. Locally, use `--target local` (no `--stage`); it works whether or not `npm run dev` runs.
113
+ **A member whose account role is "Super Administrator - All Privileges" or "Administrator" (PAR-413) is the app's admin**; every other member is a user. To make someone an admin, give them one of those roles in the dashboard (Manage Account → Members); to make them a user again, give them another role. No file edit, no commit and no deploy.
139
114
 
140
- It prints the account's user ID (as `/api/auth/me` shows it) and its roles, never a password or token. An address with no verified account is refused and nothing changes.
115
+ The apps learn a role change when the person **next signs in**, to any app on the account; their other open sessions pick it up within 5 minutes (PAR-425). Until then they keep their old level: ask them to log out and in again. Removing someone from the account stops new sign-ins, but a session they already have lasts until it expires (12 hours, PAR-250) or they log out.
141
116
 
142
- ## 8. Checking the real login (optional)
117
+ ## 8. Checking the real sign-in (optional)
143
118
 
144
- `npm run check-login -- --target cloudflare --stage "$STAGE"` checks sign-up with real mail, sign-in, the admin grant, a password reset and the rate limit on a production stage. It needs no input, prints no address or password, writes an evidence record under `validation/`, and leaves one test account (no role).
119
+ `npm run check-login -- --target cloudflare --stage "$STAGE"` checks, on a production stage and with no sign-in, that the stage sends people to the auth app with its own address. It needs no input. The real sign-in itself needs a person: sign in once (§6).
145
120
 
146
121
  ## 9. Cost
147
122
 
148
- - Stopped or idle stages cost nothing for compute, but storage remains: the stage's D1 database and R2 file bucket, the shared `prototype-logs` bucket, and the `sst-state` bucket. Log entries are never deleted automatically. Test mail in the sink is deleted after a day.
149
- - Keep test stages small: a few rows of data, one test stage at a time, and `remove` it right after use. An account holds at most **10 D1 databases**, and a deploy that changes the schema briefly uses two per stage.
123
+ - Stopped or idle stages cost nothing for compute, but storage remains: the stage's D1 database and R2 file bucket, the shared `prototype-logs` bucket, the `sst-state` bucket, and the auth app's database. Log entries are never deleted automatically.
124
+ - Keep test stages small: a few rows of data, one test stage at a time, and `remove` it right after use. An account holds at most **10 D1 databases** (the auth app uses one), and a deploy that changes the schema briefly uses two per stage.
150
125
  - See [deploying.md](deploying.md) for deploy, stop/start and remove.
151
126
 
127
+ ## 10. Coming from 0.1.x
128
+
129
+ `npm run upgrade` to 0.2.0 says Cloudflare setup needs re-running. Once per account, do §2: put one token with the listed permissions (your old everyday token lacks some) and the account ID in `~/.secrets/cloudflare` or the environment, delete `.env.cloudflare`, and run `npm run cloudflare-setup`. Password accounts and sessions are gone, so everyone signs in again with Cloudflare; the old sign-in and test-mail tables are dropped on the next `dev` or `deploy`, and the app's own data stays. Remove `framework.email` from values files if you like: it is no longer used. The admin app's **Clean up v0.1.x email** page optionally removes the old email resources (sending domain, routing rules, test mailbox); nothing is removed automatically.
130
+
152
131
  ## Examples
153
132
 
154
- - [examples/configuration.md](../examples/configuration.md): the template's committed values files (`config/<target>/<stage>.json`), which hold the app's values and `framework.email`, and no admins.
133
+ - [examples/configuration.md](../examples/configuration.md): the template's committed values files (`config/<target>/<stage>.json`), which hold the app's values and no admins.
155
134
 
156
135
  ## Stopping condition
157
136