@lago-morph/create-prototype-app 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.
Files changed (42) hide show
  1. package/README.md +9 -2
  2. package/bin/create-prototype-app.js +26 -10
  3. package/lib/create.mjs +115 -2
  4. package/package.json +1 -1
  5. package/skill/SKILL.md +19 -26
  6. package/skill/VERSION +1 -0
  7. package/skill/examples/notes-sql.md +1 -1
  8. package/skill/examples/secrets.md +20 -1
  9. package/skill/examples/tests.md +109 -0
  10. package/skill/reference/configuration.md +4 -4
  11. package/skill/reference/current-user.md +10 -10
  12. package/skill/reference/deploying.md +6 -8
  13. package/skill/reference/files.md +1 -1
  14. package/skill/reference/http-and-validation.md +1 -1
  15. package/skill/reference/kv.md +1 -1
  16. package/skill/reference/local-development.md +2 -2
  17. package/skill/reference/log.md +1 -1
  18. package/skill/reference/owner-tasks.md +53 -67
  19. package/skill/reference/secrets.md +3 -3
  20. package/skill/reference/sql-and-migrations.md +3 -3
  21. package/skill/reference/testing/e2e.md +44 -0
  22. package/skill/reference/testing/failures.md +44 -0
  23. package/skill/reference/testing/fuzzing.md +28 -0
  24. package/skill/reference/testing/test-changes.md +42 -0
  25. package/skill/reference/testing.md +33 -22
  26. package/skill/reference/troubleshooting.md +12 -15
  27. package/skill/templates/FRAMEWORK-ISSUE.md +1 -1
  28. package/skill/templates/README.md +1 -1
  29. package/skill/templates/production-stage.json +1 -3
  30. package/template/.claude/settings.json +36 -0
  31. package/template/README.md +27 -66
  32. package/template/gitignore +3 -0
  33. package/template/package.json +10 -4
  34. package/template/playwright.config.ts +31 -0
  35. package/template/src/server/routes/notes.ts +1 -1
  36. package/template/src/server/signing.ts +4 -1
  37. package/template/tests/e2e/api/notes.spec.ts +74 -0
  38. package/template/tests/e2e/ui/account.spec.ts +22 -0
  39. package/template/tests/fuzz.test.ts +22 -0
  40. package/template/tests/signing.test.ts +16 -0
  41. package/template/tests/support/fuzz.test.ts +72 -0
  42. package/template/tests/support/fuzz.ts +88 -0
@@ -35,7 +35,7 @@ The date and time are UTC. `smoke` prints today's prefix.
35
35
 
36
36
  **Dashboard (no setup; these menu names are not yet verified).** Open Storage & databases → R2 → `prototype-logs`. Then open the folders `<app>` / `<stage>` / year / month / day. The file name ends in the request ID. Open the file and choose Download to read it.
37
37
 
38
- **Command line, with the API token from [owner-tasks.md](owner-tasks.md) §2.** `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` must be set in the shell. These two `curl` commands are **verified on Cloudflare**: on a real test stage, the list command found a failed request's key and the read command returned its `CORE.INTERNAL` entry (E2E-011, Cloudflare pass 2–5; the framework repository's `validation/cloudflare/pass-2to5/SUMMARY.md` and `logs/5-trouble.log`). List one day's keys:
38
+ **Command line, only where both values are in the environment.** These commands need `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` in the shell's environment, for example in a cloud session whose environment settings hold them. When the token is only in `~/.secrets/cloudflare` (the usual case on a computer, [owner-tasks.md](owner-tasks.md) §2), the variables are empty and the requests fail: use the dashboard route above instead. Never `source`, `cat` or otherwise read `~/.secrets/cloudflare` (or an old `.env.cloudflare`) to fill them in. These two `curl` commands are **verified on Cloudflare**: on a real test stage, the list command found a failed request's key and the read command returned its `CORE.INTERNAL` entry (E2E-011, Cloudflare pass 2–5; the framework repository's `validation/cloudflare/pass-2to5/SUMMARY.md` and `logs/5-trouble.log`). List one day's keys:
39
39
 
40
40
  ```sh
41
41
  STAGE='<stage>'; DAY=$(date -u +%Y/%m/%d)
@@ -70,7 +70,7 @@ Not yet verified on Cloudflare in this phase.
70
70
  ```sh
71
71
  npx wrangler tail "$APP-$STAGE" --format pretty
72
72
  ```
73
- It needs `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` set. Not yet verified on Cloudflare in this phase.
73
+ It needs `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` in the shell's environment, as the `curl` commands above do; with the token only in `~/.secrets/cloudflare`, use the dashboard instead (Workers & Pages → `<app>-<stage>` → Logs, menu names not yet verified). Not yet verified on Cloudflare in this phase.
74
74
  - If entries are printed as lines starting `[prototype-framework:log]` in `wrangler tail`, the Worker has no `LOGS` binding. Run `deploy` again.
75
75
  - Locally, entries reach `.logs/` only while `npm run dev` runs. In-process tests write no files.
76
76
 
@@ -93,27 +93,24 @@ Each code's meaning, HTTP status and whether it is retryable are in the framewor
93
93
 
94
94
  ## 3. Login failures
95
95
 
96
- Every stage signs people in with email and password. A failed attempt writes one `warn` entry from `AUTH`, `login failed: <reason>`, never the address (§1):
96
+ Production stages sign people in with Cloudflare, through the account's auth app. A failed sign-in returns to `/?authError=login_failed&requestId=<id>` and writes one `warn` entry from `AUTH`, `login failed: <reason>`, never an address or code (§1):
97
97
 
98
- - `wrong credentials`: unknown address or wrong password (both get the same answer). Use "Forgot your password?" on the sign-in page.
99
- - `not verified`: the address is not confirmed yet. Open the link in the "Confirm your email address" mail, or use "Send a new confirmation link".
100
- - `rate limited`: too many attempts from one network address; wait a minute (sign-in) or five minutes (sign-up, forgot, resend).
101
- - `invalid token`: the mailed link was used already or expired (confirmation 24 hours, reset 1 hour). Ask for a new one.
102
- - `provider unavailable (<code>)`: the database was not reachable; retry.
98
+ - `transaction missing or expired`: the sign-in took too long, or cookies are blocked. Sign in again.
99
+ - `state mismatch`: two sign-ins ran at once in one browser. Sign in again.
100
+ - `provider refused`: Cloudflare or the auth app refused. Most often the person is not a member of the owner's Cloudflare account: invite them (Manage Account → Members, [owner-tasks.md](owner-tasks.md) §6).
101
+ - `code refused`: the one-time code was used, expired, or issued to another app or stage. Sign in again; if it repeats, deploy the stage again so the auth app knows its address.
102
+ - `auth app unavailable`: the auth app or its database was not reachable; retry. If it repeats, check on the admin app's Status page that the auth app is set up.
103
103
 
104
- No mail arrives:
105
- - Locally nothing is sent: read `.mail/` with `npm run mail -- last --to '<address>'`. On a test stage the mail is captured, not sent.
106
- - On a production stage, look for a `MAIL` entry `mail send failed: <code>` (§1). The sender is `no-reply@<domain>`; if `deploy` or `setup-account` said the domain is not verified for sending, run `npm run setup-account -- --target cloudflare` again.
107
- - A test address `sink+<tag>@t.<domain>`: read it with `npm run mail -- last --to '<address>' --target cloudflare`. Only `sink+…` addresses reach the test mailbox. Right after `setup-account` created the mailbox rule, a send may be rejected for a minute.
104
+ Signed out after a while, with a `warn` entry `role refresh failed (<code>)`: the app could not confirm the person's role with the auth app, so it ended the session. Sign in again once the auth app answers.
108
105
 
109
- Signed in, but not admin: the `admin` role is granted per stage with `admins grant` ([owner-tasks.md](owner-tasks.md) §7); check with `admins list`.
106
+ Signed in, but not admin (or still admin): the level comes from the person's role in the Cloudflare account ([owner-tasks.md](owner-tasks.md) §7), recorded when they last signed in. Log out and sign in again after the role changes.
110
107
 
111
108
  ## 4. Deploy, remove and setup failures
112
109
 
113
110
  `deploy` prints the failed step, the stage's state and the next action. Follow the next action. Common messages:
114
111
 
115
- - `run setup-account … first`: the account's shared resources are missing. See [owner-tasks.md](owner-tasks.md) §3.
116
- - A missing `CLOUDFLARE_API_TOKEN` or `CLOUDFLARE_ACCOUNT_ID`, or a missing permission: see [owner-tasks.md](owner-tasks.md) §2. "Account API Tokens Write" is the setup token's, needed only by `setup-account`; "R2 signing credential … missing" means `setup-account` must run with the setup token.
112
+ - `run npm run cloudflare-setup first` (older releases: `run setup-account … first`), or the account's auth app is missing: run `npm run cloudflare-setup` ([owner-tasks.md](owner-tasks.md) §2). It names what is missing and sets the account up.
113
+ - A missing `CLOUDFLARE_API_TOKEN` or `CLOUDFLARE_ACCOUNT_ID`, a missing permission, or "R2 signing credential … missing": run `npm run cloudflare-setup`, which says what to fix ([owner-tasks.md](owner-tasks.md) §2). Setup names each permission the token lacks; add it to the token in the dashboard, or make a new token from setup's link.
117
114
  - `NODE_USE_ENV_PROXY`: you are behind an HTTPS proxy. Put `NODE_USE_ENV_PROXY=1 ` in front of the command.
118
115
  - `required secrets are not set: …`: this happens on the first deploy of a stage. Set each named secret with `--target cloudflare`, then run `deploy` again.
119
116
  - An error about the number of D1 databases: an account holds at most 10, and a schema-changing deploy briefly holds two per stage. Remove unused test stages ([deploying.md](deploying.md)).
@@ -7,7 +7,7 @@ Suspected framework defects found while building this app. Each entry is reprodu
7
7
  - **Status:** open
8
8
  - **Task attempted:** <the requirement or step you were implementing>
9
9
  - **Contract or reference consulted:** <file and section, for example `skill/reference/files.md`, "The safe upload pattern">
10
- - **Minimal reproduction:** <the smallest code, and the exact command that shows the problem, for example `npx prototype-framework verify`>
10
+ - **Minimal reproduction:** <the smallest code, and the exact command that shows the problem, for example `npm run verify`>
11
11
  - **Observed code or diagnostic:** <copied exactly: error code and status, the `verify` line, the request ID>
12
12
  - **Expected:** <what the contract or reference says should happen>
13
13
  - **Workaround not taken:** <what you could have done instead, and did not>
@@ -5,6 +5,6 @@ Files you copy and fill in. The app itself comes from the scaffolder: `skill/scr
5
5
  | File | Copy to | Fill in |
6
6
  | --- | --- | --- |
7
7
  | [FRAMEWORK-ISSUE.md](FRAMEWORK-ISSUE.md) | `FRAMEWORK-ISSUE.md` at the app's root, when you first suspect a framework defect | One numbered entry per defect, every field (router, hard rules 6 and 7) |
8
- | [production-stage.json](production-stage.json) | `config/<target>/<stage>.json` for each production stage, for example `config/cloudflare/prod.json` | `values` for keys without defaults; the email sender's display name (`framework.email.senderName`, or remove `email` to use the app name). No admins: they get the `admin` role with `admins grant` ([configuration.md](../reference/configuration.md), [owner-tasks.md](../reference/owner-tasks.md)) |
8
+ | [production-stage.json](production-stage.json) | `config/<target>/<stage>.json` for each production stage, for example `config/cloudflare/prod.json` | `values` for keys without defaults. No admins: they are the Cloudflare account's administrators ([configuration.md](../reference/configuration.md), [owner-tasks.md](../reference/owner-tasks.md)) |
9
9
 
10
10
  Test stages need no new file: every `test-*` stage uses the template's `config/<target>/test.json`.
@@ -1,6 +1,4 @@
1
1
  {
2
2
  "values": {},
3
- "framework": {
4
- "email": { "senderName": "REPLACE-WITH-THE-SENDER-NAME" }
5
- }
3
+ "framework": {}
6
4
  }
@@ -0,0 +1,36 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/claude-code-settings.json",
3
+ "permissions": {
4
+ "deny": [
5
+ "Read(.env.cloudflare)",
6
+ "Edit(.env.cloudflare)",
7
+ "Bash(grep *.env.cloudflare*)",
8
+ "Bash(rg *.env.cloudflare*)",
9
+ "Bash(awk *.env.cloudflare*)",
10
+ "Bash(less *.env.cloudflare*)",
11
+ "Bash(more *.env.cloudflare*)",
12
+ "Bash(source *.env.cloudflare*)",
13
+ "Bash(. *.env.cloudflare*)",
14
+ "Read(~/.secrets/**)",
15
+ "Edit(~/.secrets/**)",
16
+ "Bash(grep *.secrets/cloudflare*)",
17
+ "Bash(rg *.secrets/cloudflare*)",
18
+ "Bash(awk *.secrets/cloudflare*)",
19
+ "Bash(less *.secrets/cloudflare*)",
20
+ "Bash(more *.secrets/cloudflare*)",
21
+ "Bash(source *.secrets/cloudflare*)",
22
+ "Bash(. *.secrets/cloudflare*)",
23
+ "Bash(echo *CLOUDFLARE_API_TOKEN*)",
24
+ "Bash(echo *CLOUDFLARE_BOOTSTRAP_TOKEN*)",
25
+ "Bash(env)",
26
+ "Bash(env -0)",
27
+ "Bash(printenv *)",
28
+ "Bash(set)",
29
+ "Bash(export)",
30
+ "Bash(export -p)",
31
+ "Bash(declare -p*)",
32
+ "Bash(declare -x*)",
33
+ "Bash(* /proc/*environ*)"
34
+ ]
35
+ }
36
+ }
@@ -4,9 +4,9 @@ This is the smallest app built on the prototype framework. It uses each capabili
4
4
 
5
5
  This page lists everything the owner does by hand, as copy-and-paste steps. Run the commands in a terminal, in this app's folder, on macOS or Linux with Node 22.22.0. Replace the `<…>` parts. Never paste a secret value into a command line, a committed file or a chat.
6
6
 
7
- **What is verified in this phase.** Local development (§1) is verified. The Cloudflare steps (§2–§11) have run against a simulated Cloudflare, and the email setup (§3) once against the real account; treat the rest as **not yet verified on Cloudflare**. AWS is a future release: this release targets local and Cloudflare only.
7
+ This release runs apps locally (§1) and on Cloudflare (§2 on). The short version of everything here is the framework's [QUICKSTART.md](https://github.com/lago-morph/cloud-app/blob/main/QUICKSTART.md).
8
8
 
9
- People sign in with an email address and a password. **Anyone who signs up and verifies their address is a user.** Admins are users holding the `admin` role, granted with the `admins` command (§8); nothing about people is kept in configuration. `<domain>` below is the account's email domain.
9
+ People sign in with Cloudflare. **Only members of the owner's Cloudflare account can sign in**, and every member is a user. Members with the account role "Super Administrator - All Privileges" or "Administrator" are admins (§8). Nothing about people is kept in configuration.
10
10
 
11
11
  ## 1. Run it on your computer
12
12
 
@@ -22,7 +22,7 @@ People sign in with an email address and a password. **Anyone who signs up and v
22
22
  ```sh
23
23
  APP=$(npm run --silent build -- --target local --stage local | sed -n 's/^built \([^ ]*\) for .*/\1/p'); echo "$APP"
24
24
  ```
25
- 3. Set the local value of the app's secret, which the admin page checks. `npm run dev` creates only the framework's own development keys, not the app's secrets. Run the command, paste any value, press Enter, then press Ctrl-D:
25
+ 3. The app's secret `apiKey`, which the admin page checks, needs a local value. An app made with `npm create @lago-morph/prototype-app` already has a random one, set when it was made (and `npm run cloudflare-setup` sets any that is missing). `npm run dev` generates only the framework's own development keys. To set or change the value yourself (in the framework's repository, do this once), run the command, paste any value, press Enter, then press Ctrl-D:
26
26
  ```sh
27
27
  npm run secrets -- set apiKey --target local --stage local
28
28
  ```
@@ -31,11 +31,7 @@ People sign in with an email address and a password. **Anyone who signs up and v
31
31
  ```sh
32
32
  npm run dev
33
33
  ```
34
- Press Ctrl-C to stop. The login button opens the sign-in page: create an account with any address. Locally no mail is sent; it is written to `.mail/`. Read the latest message to the address, open its link, and press the button:
35
- ```sh
36
- npm run mail -- last --to '<address>'
37
- ```
38
- To make yourself an admin locally, run `npm run admins -- grant '<address>' --target local` (`revoke` takes it away). Your next request is admin.
34
+ Press Ctrl-C to stop. Locally there is no real sign-in: the login button signs you in as a test user. Tests choose any level with the authentication mock.
39
35
  5. Check everything before you call a change done:
40
36
  ```sh
41
37
  npm run verify
@@ -47,40 +43,29 @@ People sign in with an email address and a password. **Anyone who signs up and v
47
43
  ```
48
44
  7. To start again from empty local data (the database, files and logs), run `npm run reset-local`. Your code, configuration and `.dev.vars` stay.
49
45
 
50
- ## 2. Cloudflare account and API tokens (once)
46
+ ## 2. Cloudflare setup (once per account)
51
47
 
52
- 1. Sign up or log in at https://dash.cloudflare.com.
53
- 2. Copy your **Account ID**. Open Account home, choose your account, and copy the Account ID from its overview page. The Cloudflare dashboard menu names on this page are **not yet verified**.
54
- 3. Create two **account API tokens**: go to Manage Account → Account API Tokens → Create Token → Create Custom Token (not yet verified). The email domain must be a zone on this account with Cloudflare DNS active. For each token, under Account Resources include only your account, and under Zone Resources the email domain's zone. Create the token, then copy it. Cloudflare shows it only once.
55
- - The **everyday token**, named `prototype-framework`, for every command except `setup-account`. **Account** permissions: Workers Scripts: Edit, Workers R2 Storage: Edit, D1: Edit, Email Sending: Read. **Zone** permissions: Zone: Read, Analytics: Read. It cannot create API tokens.
56
- - The **setup token**, named `prototype-framework-setup`, for `setup-account` only (§3), which you run rarely. **Account** permissions: Workers Scripts: Edit, Workers R2 Storage: Edit, Account API Tokens: Edit (it creates the file-signing credential all stages share), Email Sending: Edit, Email Routing Addresses: Edit. **Zone** permissions: Email Routing Rules: Edit, DNS: Edit, Zone Settings: Edit, Zone: Read. Keep it apart from the everyday token.
48
+ Any Cloudflare account works, on the free Workers plan too; no domain is needed. Run, in this app's folder (in Claude Code, say "set up Cloudflare"):
57
49
 
58
- These lists are checked against the Cloudflare API: a token with exactly the everyday permissions passed every read `deploy` makes before it changes anything. A command that lacks a permission names it.
59
- 4. In every new terminal where you deploy, set both values. `read` keeps the token out of your shell history. Paste the everyday token when it waits, then press Enter:
60
- ```sh
61
- export CLOUDFLARE_ACCOUNT_ID='<your Account ID>'
62
- read -rs CLOUDFLARE_API_TOKEN && export CLOUDFLARE_API_TOKEN
63
- ```
64
- 5. Check the token. The output must contain `"success":true`:
65
- ```sh
66
- curl -sS -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/tokens/verify"
67
- ```
50
+ ```sh
51
+ npm run cloudflare-setup
52
+ ```
68
53
 
69
- If a command says it needs `NODE_USE_ENV_PROXY=1`, you are behind an HTTPS proxy. Put `NODE_USE_ENV_PROXY=1 ` in front of that command.
54
+ 1. With no token yet, it prints a two-line template (`CLOUDFLARE_API_TOKEN=` and `CLOUDFLARE_ACCOUNT_ID=`), one pre-filled dashboard link for the token, and where the lines go: the file `~/.secrets/cloudflare` in your home directory (shared by every app on the machine), or a cloud session's environment variables. Make the token (any end date, or none; a token you have with more permissions works too), fill in the lines, put them there, and run the command again. Never paste the token into a chat.
55
+ 2. It checks the token and sets the account up in one run: the sign-in clients, the **auth app** that signs people in to every app, the shared buckets and the optional admin app. It never deletes or changes your token.
56
+ 3. It ends with the next step, a deploy of a `test-` stage. Run it again whenever it stops (in Claude Code, "continue prototype setup") until it says everything is set up.
70
57
 
71
- ## 3. One-time account setup
58
+ Coming from framework 0.1.x or 0.2.0-rc01: `npm run upgrade` says setup needs re-running; move the token and account ID from `.env.cloudflare` to `~/.secrets/cloudflare` (with the permissions setup names), delete `.env.cloudflare`, and do steps 1–3 once per account. Everyone signs in again, with Cloudflare (QUICKSTART, "Coming from 0.1.x?").
72
59
 
73
- Set the **setup token** first, the same way as in §2 step 4 (`read -rs CLOUDFLARE_API_TOKEN && export CLOUDFLARE_API_TOKEN`, paste the setup token). Run:
60
+ It never prints a token value, and every later command reads the token itself. The steps, and what to do when it stops: [QUICKSTART.md](https://github.com/lago-morph/cloud-app/blob/main/QUICKSTART.md) and the skill's `reference/owner-tasks.md` §2 (in this app, `.claude/skills/prototype-framework/reference/owner-tasks.md`).
74
61
 
75
- ```sh
76
- npm run setup-account -- --target cloudflare --email-domain <domain>
77
- ```
62
+ ## 3. What the account setup creates
78
63
 
79
- Then set the everyday token again the same way. This creates the account's shared resources once, 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 account's `workers.dev` address, sending from `no-reply@<domain>`, and a test mailbox for agents: mail to `sink+<tag>@t.<domain>` is kept for a day. When it creates the mailbox rule, it waits about a minute before it finishes. Running it again changes nothing; to change the domain, run it again with the new `--email-domain`. `deploy` never creates these resources; if any is missing (for example on an account set up before the backup bucket or the file-signing credential existed), it names them and tells you to run this command again, with the setup token.
64
+ `npm run cloudflare-setup` creates the account's shared resources once (the admin app's optional Account setup page does the same): the **auth app**, which signs people in to every 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. `deploy` never creates these resources; if any is missing, it says so and names `npm run cloudflare-setup`.
80
65
 
81
66
  ## 4. Deploy a test stage, test it, remove it
82
67
 
83
- A stage whose name starts with `test-` is a test stage. It uses `config/cloudflare/test.json`, has the mock login for tests, never sends mail, and holds no real data. Stage names are at most 20 lowercase letters, digits and hyphens.
68
+ A stage whose name starts with `test-` is a test stage. It uses `config/cloudflare/test.json`, has only the mock login for tests, and holds no real data. Stage names are at most 20 lowercase letters, digits and hyphens.
84
69
 
85
70
  Set the stage name once, in the first line, and deploy. In a new terminal, set `STAGE` again:
86
71
 
@@ -109,14 +94,12 @@ npm run remove -- --target cloudflare --stage "$STAGE"
109
94
 
110
95
  ## 5. The production stage's values file
111
96
 
112
- Every stage that does not start with `test-` is a production stage, for example `prod`. It needs its own committed values file. Copy the skill's template (in the framework's repository: `skill/templates/production-stage.json`) and set the display name of the sign-up and reset mail in it:
97
+ Every stage that does not start with `test-` is a production stage, for example `prod`. It needs its own committed values file. Copy the skill's template (in the framework's repository: `skill/templates/production-stage.json`):
113
98
 
114
99
  ```sh
115
100
  STAGE=prod
116
101
  mkdir -p config/cloudflare
117
102
  cp ../../skill/templates/production-stage.json "config/cloudflare/$STAGE.json"
118
- SENDER='<the sender name, for example the app name>'
119
- node -e 'const fs=require("fs"),f=process.argv[1],c=JSON.parse(fs.readFileSync(f,"utf8"));c.framework.email.senderName=process.argv[2];fs.writeFileSync(f,JSON.stringify(c,null,2)+"\n")' "config/cloudflare/$STAGE.json" "$SENDER"
120
103
  npm run build -- --target cloudflare --stage "$STAGE"
121
104
  git add "config/cloudflare/$STAGE.json"
122
105
  git commit -m "Add the values file of stage $STAGE"
@@ -133,7 +116,7 @@ npm run secrets -- set apiKey --target cloudflare --stage "$STAGE"
133
116
  npm run deploy -- --target cloudflare --stage "$STAGE"
134
117
  ```
135
118
 
136
- The first `deploy` stops and names the unset secrets. Set them as above, pasting each value and then pressing Ctrl-D, and deploy again. The framework generates its own keys. The second deploy prints the stage's address, its sign-in page and the sender address `no-reply@<domain>`.
119
+ The first `deploy` stops and names the unset secrets. Set them as above, pasting each value and then pressing Ctrl-D, and deploy again. The framework generates its own keys. The second deploy registers the stage with the auth app and prints its address. Without the account's auth app it stops before creating anything: do the admin app's Account setup (§2) first.
137
120
 
138
121
  To change the stage later (code or configuration), commit the change and run the same `deploy` again:
139
122
 
@@ -143,39 +126,17 @@ git commit -m "<what you changed>"
143
126
  npm run deploy -- --target cloudflare --stage "$STAGE"
144
127
  ```
145
128
 
146
- ## 7. Sign up and sign in
147
-
148
- 1. Open the sign-in page `https://template-prod.<subdomain>.workers.dev/api/auth/sign-in` and choose "Create an account". Enter an email address, a password of 12 to 128 characters, and a display name.
149
- 2. Open the link in the "Confirm your email address" mail and press the button.
150
- 3. Sign in. `https://template-prod.<subdomain>.workers.dev/api/auth/me` now shows `"level":"user"`.
151
-
152
- "Forgot your password?" on the sign-in page mails a reset link (valid for one hour); "Send a new confirmation link" mails a new confirmation link.
153
-
154
- **An agent with no mailbox** signs up with a test address, `sink+<tag>@t.<domain>` (`<tag>`: lowercase letters, digits and hyphens), and reads the mail with:
155
-
156
- ```sh
157
- npm run mail -- last --to 'sink+<tag>@t.<domain>' --target cloudflare
158
- ```
159
-
160
- Without a browser, it posts the link's token (the value after `token=`) instead of pressing the button:
129
+ ## 7. Sign in
161
130
 
162
- ```sh
163
- curl -sS -X POST 'https://template-prod.<subdomain>.workers.dev/api/auth/password/verify' -H 'Origin: https://template-prod.<subdomain>.workers.dev' -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"token":"<token>"}'
164
- ```
131
+ 1. Open `https://template-prod.<subdomain>.workers.dev/` and press the login button.
132
+ 2. Sign in on Cloudflare's page with a member of the account, and allow what it asks.
133
+ 3. Back on the app, `https://template-prod.<subdomain>.workers.dev/api/auth/me` shows `"level":"user"` or `"level":"admin"`.
165
134
 
166
- `npm run check-login -- --target cloudflare --stage "$STAGE"` runs this whole flow automatically on a production stage (with a password reset and the sign-in rate limit) and writes an evidence record under `validation/`.
135
+ To let someone sign in, invite them to the Cloudflare account (Manage Account → Members); a read-only role, for example "HTTP Applications Read", is enough. `npm run check-login -- --target cloudflare --stage "$STAGE"` checks, with no sign-in, that the stage sends people to the auth app with its own address.
167
136
 
168
137
  ## 8. Admins
169
138
 
170
- The `admin` role is stored with the person's account in the stage's 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 (§7). On a production stage, repeat the stage's name with `--confirm-production`:
171
-
172
- ```sh
173
- STAGE=prod
174
- npm run admins -- grant '<their address>' --target cloudflare --stage "$STAGE" --confirm-production "$STAGE"
175
- npm run admins -- list --target cloudflare --stage "$STAGE" --confirm-production "$STAGE"
176
- ```
177
-
178
- `grant` prints the person's user ID (as `/api/auth/me` shows it) and roles. To take the role away, run the same command with `revoke`; the person is a user again. On a test stage, leave out `--confirm-production`. An address with no verified account is refused, and nothing changes.
139
+ A member whose Cloudflare account role is "Super Administrator - All Privileges" or "Administrator" is admin; every other member is a user. Change a person's role in the dashboard (Manage Account → Members). No file edit, no commit and no deploy: the change shows when they next sign in (ask them to log out and in again). Removing someone from the account does not end a session they already have; it lasts until it expires (12 hours) or they log out.
179
140
 
180
141
  ## 9. Stop, start and remove
181
142
 
@@ -191,7 +152,7 @@ npm run admins -- list --target cloudflare --stage "$STAGE" --confirm-production
191
152
  Every error response has a `requestId`. A failed login returns to `/?authError=login_failed&requestId=<id>`. Each log entry is a file in the R2 bucket `prototype-logs`, under `template/<stage>/<yyyy>/<mm>/<dd>/`. The date is UTC, and the file name ends in `-<requestId>.json`.
192
153
 
193
154
  - **Dashboard** (menu names not yet verified)**:** open Storage & databases → R2 → `prototype-logs`, then the folders `template` / `<stage>` / year / month / day. Open the file whose name ends in the request ID.
194
- - **Command line:** list today's entries of a stage, and keep only the line with the request ID. `APP` must be set (§1 step 2):
155
+ - **Command line, only where both values are in the environment:** these commands need `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` in the shell's environment, for example in a cloud session whose environment settings hold them. With the token only in `~/.secrets/cloudflare` (§2), the variables are empty and the requests fail: use the dashboard route above. Never `source` or `cat` `~/.secrets/cloudflare` to fill them in. List today's entries of a stage, and keep only the line with the request ID. `APP` must be set (§1 step 2):
195
156
  ```sh
196
157
  STAGE='<stage>'; DAY=$(date -u +%Y/%m/%d)
197
158
  curl -sS -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
@@ -205,7 +166,7 @@ Every error response has a `requestId`. A failed login returns to `/?authError=l
205
166
  curl -sS -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
206
167
  "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/r2/buckets/prototype-logs/objects/$(node -p 'encodeURIComponent(process.argv[1])' "$KEY")"
207
168
  ```
208
- - **No entry?** Watch the Worker's output while you repeat the request: `npx wrangler tail "$APP-$STAGE" --format pretty`. More help is in the skill's troubleshooting reference, `skill/reference/troubleshooting.md` in the framework repository.
169
+ - **No entry?** Watch the Worker's output while you repeat the request: `npx wrangler tail "$APP-$STAGE" --format pretty` (it too needs both values in the environment; otherwise open the Worker's logs in the dashboard, Workers & Pages → `template-<stage>` → Logs, menu names not yet verified). More help is in the skill's troubleshooting reference, `skill/reference/troubleshooting.md` in the framework repository.
209
170
 
210
171
  ## 11. Cost: what stays billable while idle
211
172
 
@@ -11,6 +11,9 @@ dist/
11
11
  .mail/
12
12
  .dev.vars
13
13
 
14
+ # Cloudflare tokens (cloudflare-setup); never commit
15
+ .env.cloudflare
16
+
14
17
  # Playwright output
15
18
  test-results/
16
19
  playwright-report/
@@ -5,7 +5,9 @@
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "dev": "prototype-framework dev",
8
- "verify": "prototype-framework verify",
8
+ "verify": "prototype-framework verify && playwright test --project e2e-api",
9
+ "test:e2e:api": "playwright test --project e2e-api",
10
+ "test:e2e:ui": "playwright test --project e2e-ui",
9
11
  "generate-migration": "prototype-framework generate-migration",
10
12
  "build": "prototype-framework build",
11
13
  "deploy": "prototype-framework deploy",
@@ -15,17 +17,21 @@
15
17
  "start": "prototype-framework start",
16
18
  "secrets": "prototype-framework secrets",
17
19
  "setup-account": "prototype-framework setup-account",
20
+ "cloudflare-setup": "prototype-framework cloudflare-setup",
18
21
  "check-login": "prototype-framework check-login",
19
22
  "reset-local": "prototype-framework reset-local",
20
- "mail": "prototype-framework mail",
21
- "admins": "prototype-framework admins"
23
+ "version-check": "prototype-framework version-check",
24
+ "upgrade": "prototype-framework upgrade"
22
25
  },
23
26
  "dependencies": {
24
- "@lago-morph/prototype-framework": "0.1.0",
27
+ "@lago-morph/prototype-framework": "0.2.0-rc02",
25
28
  "hono": "4.13.13",
26
29
  "zod": "4.6.7"
27
30
  },
28
31
  "devDependencies": {
32
+ "@playwright/test": "1.64.1",
33
+ "@vitest/browser-playwright": "5.0.5",
34
+ "fast-check": "4.10.2",
29
35
  "typescript": "6.0.3",
30
36
  "vite": "8.3.4",
31
37
  "vitest": "5.0.5"
@@ -0,0 +1,31 @@
1
+ import { defineConfig } from "@playwright/test";
2
+
3
+ // The app's e2e layer (the skill's reference/testing/e2e.md): two projects against a local `dev`
4
+ // server that Playwright starts and stops.
5
+ // - "e2e-api": most e2e tests, through the HTTP API with the `request` fixture; no browser.
6
+ // `npm run verify` runs it after the unit tests.
7
+ // - "e2e-ui": the few tests of what only a browser shows; the only project that needs Chromium.
8
+ // `dev` binds a free port and prints "… is running at http://localhost:<port>/". `webServer.wait`
9
+ // reads the port into APP_E2E_PORT for the test workers, which load this file again.
10
+ const port = process.env["APP_E2E_PORT"];
11
+ const origin = port === undefined ? "http://localhost" : `http://localhost:${port}`;
12
+
13
+ export default defineConfig({
14
+ testDir: "tests/e2e",
15
+ outputDir: "test-results",
16
+ // One local server and one local database: tests use fresh mock users, not a fresh database.
17
+ workers: 1,
18
+ projects: [
19
+ // State-changing API requests must carry the app's origin (the framework's forgery check).
20
+ { name: "e2e-api", testMatch: "api/**/*.spec.ts", use: { baseURL: origin, extraHTTPHeaders: { Origin: origin } } },
21
+ { name: "e2e-ui", testMatch: "ui/**/*.spec.ts", use: { baseURL: origin, browserName: "chromium" } },
22
+ ],
23
+ webServer: {
24
+ command: "npm run dev",
25
+ wait: { stdout: /is running at http:\/\/localhost:(?<app_e2e_port>\d+)\// },
26
+ // dev's own server log is not test output; its "is running at" line is still read for the port.
27
+ stderr: "ignore",
28
+ timeout: 120_000,
29
+ gracefulShutdown: { signal: "SIGTERM", timeout: 10_000 },
30
+ },
31
+ });
@@ -4,7 +4,7 @@ import type { NoteList } from "../../shared/types";
4
4
  import type { Env } from "../env";
5
5
  import { notes } from "../schema";
6
6
 
7
- const newNote = z.object({ text: z.string().trim().min(1).max(500) });
7
+ export const newNote = z.object({ text: z.string().trim().min(1).max(500) });
8
8
 
9
9
  /** SQL and log: a logged-in user writes notes and lists their own. */
10
10
  export function noteRoutes(api: Hono<Env>): void {
@@ -20,11 +20,14 @@ function toBase64url(bytes: Uint8Array): string {
20
20
  function fromBase64url(text: string): Uint8Array<ArrayBuffer> | null {
21
21
  if (!/^[A-Za-z0-9_-]+$/.test(text)) return null;
22
22
  const base64 = text.replaceAll("-", "+").replaceAll("_", "/").padEnd(Math.ceil(text.length / 4) * 4, "=");
23
+ let bytes: Uint8Array<ArrayBuffer>;
23
24
  try {
24
- return Uint8Array.from(atob(base64), (ch) => ch.charCodeAt(0));
25
+ bytes = Uint8Array.from(atob(base64), (ch) => ch.charCodeAt(0));
25
26
  } catch {
26
27
  return null;
27
28
  }
29
+ // atob ignores the unused low bits of the last character, so accept only the canonical spelling.
30
+ return toBase64url(bytes) === text ? bytes : null;
28
31
  }
29
32
 
30
33
  /** A token for `subject` that verifies until `expiresAt` (milliseconds since the epoch). */
@@ -0,0 +1,74 @@
1
+ import { expect, test, type APIRequestContext, type APIResponse } from "@playwright/test";
2
+ import type { NoteList } from "../../../src/shared/types";
3
+
4
+ /**
5
+ * The notes flow end to end, through the HTTP API of a local `dev` server: a person signs in,
6
+ * writes notes and lists their own. Most of a flow's e2e cases are API tests like these.
7
+ *
8
+ * Edge cases, listed before the tests (the skill's reference/testing/e2e.md):
9
+ * - Boundaries: empty text and text of only spaces are refused; 500 characters are accepted; 501 are refused.
10
+ * - Text: Unicode text comes back unchanged; surrounding spaces are trimmed. Case, `..`, `/`,
11
+ * percent-encoding and prefix names do not apply: a note is free text, never a name or a path.
12
+ * - Order and time: not asserted here. Two notes made in the same millisecond tie on their time and
13
+ * fall back to their random IDs; there is no expiry.
14
+ * - Access: anonymous is refused (401); another user does not see the notes. Admin does not apply:
15
+ * the notes routes treat an admin as any user, and there is no admin view of notes.
16
+ * - Repetition: the same text twice makes two notes. Concurrent writes do not apply: each request
17
+ * inserts one row with a new ID, and the notes contract promises nothing about concurrency.
18
+ * - Failures: an unavailable database is simulated in-process only (`setUnavailable`, tests/app.test.ts).
19
+ */
20
+
21
+ /** Signs `request` in as a fresh mock user (local data is kept between runs) and returns its ID. */
22
+ async function signIn(request: APIRequestContext): Promise<string> {
23
+ const id = `e2e-${crypto.randomUUID()}`;
24
+ const res = await request.post("/api/auth/mock-login", { data: { level: "user", id } });
25
+ expect(res.status()).toBe(204);
26
+ return id;
27
+ }
28
+
29
+ async function errorCode(res: APIResponse): Promise<string | undefined> {
30
+ const body: { error?: { code?: string } } = await res.json();
31
+ return body.error?.code;
32
+ }
33
+
34
+ test("a signed-in user writes notes and lists only their own", async ({ request }) => {
35
+ await signIn(request);
36
+ const text = `Ünïcödé ✓ ${crypto.randomUUID()}`;
37
+ const created = await request.post("/api/notes", { data: { text: ` ${text} ` } });
38
+ expect(created.status()).toBe(201);
39
+ const again = await request.post("/api/notes", { data: { text } });
40
+ expect(again.status()).toBe(201);
41
+
42
+ const mineRes = await request.get("/api/notes");
43
+ expect(mineRes.status()).toBe(200);
44
+ const mine: NoteList = await mineRes.json();
45
+ expect(mine.notes.filter((n) => n.text === text)).toHaveLength(2);
46
+
47
+ // A new mock login replaces the session: now another user.
48
+ await signIn(request);
49
+ const theirsRes = await request.get("/api/notes");
50
+ expect(theirsRes.status()).toBe(200);
51
+ const theirs: NoteList = await theirsRes.json();
52
+ expect(theirs.notes.filter((n) => n.text === text)).toEqual([]);
53
+ });
54
+
55
+ test("anonymous requests are refused", async ({ request }) => {
56
+ const list = await request.get("/api/notes");
57
+ expect(list.status()).toBe(401);
58
+ expect(await errorCode(list)).toBe("AUTH.UNAUTHENTICATED");
59
+ const write = await request.post("/api/notes", { data: { text: "hello" } });
60
+ expect(write.status()).toBe(401);
61
+ });
62
+
63
+ test("note text must be 1 to 500 characters after trimming", async ({ request }) => {
64
+ await signIn(request);
65
+ for (const text of ["", " ", "x".repeat(501)]) {
66
+ const res = await request.post("/api/notes", { data: { text } });
67
+ expect(res.status(), JSON.stringify(text.slice(0, 20))).toBe(400);
68
+ expect(await errorCode(res)).toBe("HTTP.INVALID_INPUT");
69
+ }
70
+ expect((await request.post("/api/notes", { data: { text: "x".repeat(500) } })).status()).toBe(201);
71
+ const missing = await request.post("/api/notes", { data: {} });
72
+ expect(missing.status()).toBe(400);
73
+ expect(await errorCode(missing)).toBe("HTTP.INVALID_INPUT");
74
+ });
@@ -0,0 +1,22 @@
1
+ import { expect, test } from "@playwright/test";
2
+
3
+ /**
4
+ * What only a browser shows: the home page renders the greeting, and the login button signs in
5
+ * (locally, the authentication mock's default user). Every other case is an API test (../api/).
6
+ *
7
+ * Edge cases, listed before the test (the skill's reference/testing/e2e.md): access is the one that
8
+ * applies here (anonymous sees "Log in", a signed-in user sees "Log out"); boundaries, text, order,
9
+ * repetition and failures are covered by the API and in-process tests.
10
+ */
11
+ test("the login button signs in, and the page shows who is logged in", async ({ page }) => {
12
+ await page.goto("/");
13
+ await expect(page.getByRole("heading", { level: 1 })).toHaveText("Hello");
14
+ await expect(page.getByText("You are not logged in.")).toBeVisible();
15
+
16
+ await page.getByRole("button", { name: "Log in" }).click();
17
+ await expect(page.getByText(/^Logged in as .+ \(user\)\.$/)).toBeVisible();
18
+ await expect(page.getByRole("button", { name: "Log out" })).toBeVisible();
19
+
20
+ await page.getByRole("button", { name: "Log out" }).click();
21
+ await expect(page.getByText("You are not logged in.")).toBeVisible();
22
+ });
@@ -0,0 +1,22 @@
1
+ import { createTestApp, mockUsers, type TestApp } from "@lago-morph/prototype-framework/testing";
2
+ import { afterEach, describe, it } from "vitest";
3
+ import app from "../src/app";
4
+ import { newNote } from "../src/server/routes/notes";
5
+ import { fuzzJsonRoute } from "./support/fuzz";
6
+
7
+ let opened: TestApp | undefined;
8
+ afterEach(async () => {
9
+ await opened?.dispose();
10
+ opened = undefined;
11
+ });
12
+
13
+ describe("fuzz: POST /api/notes", () => {
14
+ // Why this route: its body is user text at a trust boundary, trimmed and length-limited, where
15
+ // whitespace-only, Unicode and boundary lengths are easy to miss in example tests.
16
+ // Why 150 runs and seed 20261031: enough to reach the trimmed and length boundaries the helper
17
+ // generates, in about a second per dialect; the fixed seed makes every run the same.
18
+ it("never answers a server error, and refuses exactly the bodies its schema refuses", async () => {
19
+ opened = await createTestApp(app, { user: mockUsers.user("fuzz") });
20
+ await fuzzJsonRoute(opened, { path: "/api/notes", schema: newNote, examples: [{ text: "a note" }], numRuns: 150, seed: 20261031 });
21
+ });
22
+ });
@@ -27,6 +27,22 @@ describe("signed tokens (HMAC, base64url)", () => {
27
27
  }
28
28
  });
29
29
 
30
+ // root cause 2026-10-31-G-template-signing-noncanonical: a 32-byte signature is 43 base64url
31
+ // characters, so its last character carries 2 unused bits; only the issued spelling may verify.
32
+ it("accepts only the issued spelling of a signature, not one re-spelled in its last character", async () => {
33
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
34
+ const token = await signToken(key, "note-1", Date.now() + 60_000);
35
+ const [subject = "", expiresAt = "", signature = ""] = token.split(".");
36
+ expect(signature).toHaveLength(43);
37
+ const last = alphabet.indexOf(signature.slice(-1));
38
+ expect(last % 4, "the issued spelling leaves the unused low bits at zero").toBe(0);
39
+ for (const flip of [1, 2, 3]) {
40
+ const respelled = signature.slice(0, -1) + (alphabet[last ^ flip] ?? "");
41
+ expect(await verifyToken(key, `${subject}.${expiresAt}.${respelled}`), respelled.slice(-3)).toBeNull();
42
+ }
43
+ expect(await verifyToken(key, token)).toBe("note-1");
44
+ });
45
+
30
46
  it("refuses a token once it has expired", async () => {
31
47
  vi.useFakeTimers();
32
48
  vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));