@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
package/README.md CHANGED
@@ -14,7 +14,14 @@ npm run dev
14
14
  2. names the app after the folder: `package.json` `name`, and the app name in `src/app.ts` and `index.html` (1 to 20 lowercase letters and digits; pass `--name` to choose another);
15
15
  3. pins `@lago-morph/prototype-framework` at the release that matches this package's version;
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
- 5. runs `npm install`.
17
+ 5. runs `npm install`;
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` (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
+ 8. makes the first commit.
21
+
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.
23
+
24
+ Later, `npm run upgrade` moves the app to a newer framework release and refreshes its skill copy, and `npm run version-check` says whether that is worth doing.
18
25
 
19
26
  Node.js 22.22.0 is what the framework requires.
20
27
 
@@ -26,7 +33,7 @@ Pass options after `--` with `npm create`, for example `npm create @lago-morph/p
26
33
  | --- | --- |
27
34
  | `--name <app>` | App name instead of one made from the folder name |
28
35
  | `--framework <spec>` | Another dependency spec for the framework, such as a `file:` tarball path |
29
- | `--no-install` | Skip `npm install` |
36
+ | `--no-install` | Skip `npm install`, and the local secrets that need it |
30
37
  | `--no-skill` | Do not copy the skill (install the plugin instead, below) |
31
38
  | `--force` | Overwrite files in a folder that is not empty |
32
39
 
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  // `npm create @lago-morph/prototype-app <dir>` runs this (npm maps @scope/name to
3
- // @scope/create-name). See README.md for the options.
3
+ // @scope/create-name). See README.md for the options. Asks for no account (plan-setup-wizard §3.1).
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { existsSync, readFileSync } from "node:fs";
6
6
  import { dirname, join, relative } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
- import { create } from "../lib/create.mjs";
8
+ import { create, firstCommit, initRepo, localSetupLines, nextStep } from "../lib/create.mjs";
9
9
 
10
10
  const USAGE = `usage: create-prototype-app <dir> [--name <app>] [--framework <spec>] [--no-install] [--no-skill] [--force]
11
11
 
@@ -13,7 +13,7 @@ const USAGE = `usage: create-prototype-app <dir> [--name <app>] [--framework <sp
13
13
  --name <app> app name: 1-20 lowercase letters and digits (default: from <dir>)
14
14
  --framework <spec> dependency spec for @lago-morph/prototype-framework
15
15
  (default: this package's version, the matching framework release)
16
- --no-install do not run npm install
16
+ --no-install do not run npm install (nor the local setup, which needs it)
17
17
  --no-skill do not copy the Claude Code skill into .claude/skills/
18
18
  --force overwrite files in a non-empty <dir>`;
19
19
 
@@ -89,13 +89,29 @@ if (opts.install) {
89
89
  }
90
90
  }
91
91
 
92
- console.log(`
93
- Next steps:
94
- cd ${rel}${opts.install ? "" : "\n npm install"}
95
- npm run dev # serve the app locally
96
- npm run verify # check everything before calling a change done
92
+ // Git problems warn and never fail (owner, 2026-10-26).
93
+ const repo = initRepo(result.target);
94
+ if (repo.message !== undefined) (repo.status === "warned" ? console.error : console.log)(repo.message);
97
95
 
98
- The owner's guide (local and Cloudflare) is README.md in the new folder.
99
- Claude Code: ${result.skill ? "the skill is in .claude/skills/prototype-framework/. Or i" : "i"}nstall it as a plugin:
96
+ // The framework's local setup: local secrets and .env.cloudflare in .gitignore (dependencies are installed above).
97
+ // Never fails the starter: a failure is a warning, and the first commit and the next step follow (exit 0).
98
+ if (opts.install) {
99
+ const { notes, warnings } = await localSetupLines(result.target);
100
+ for (const n of notes) console.log(n);
101
+ for (const w of warnings) console.error(w);
102
+ } else {
103
+ console.log("Skipped npm install and the local setup (--no-install): no local secret values were set.");
104
+ }
105
+
106
+ if (repo.status === "initialized") {
107
+ const commit = firstCommit(result.target, `Start ${result.appName} from @lago-morph/create-prototype-app ${self.version}`);
108
+ if (commit.ok) console.log("Made the first git commit.");
109
+ else console.error(commit.message);
110
+ }
111
+
112
+ if (!result.skill) {
113
+ console.log(`Claude Code: install the skill as a plugin:
100
114
  /plugin marketplace add lago-morph/cloud-app
101
115
  /plugin install prototype-framework@lago-morph`);
116
+ }
117
+ console.log(`\n${nextStep(rel, { installed: opts.install })}`);
package/lib/create.mjs CHANGED
@@ -1,8 +1,12 @@
1
1
  // Core of `npm create @lago-morph/prototype-app`: copy the template app into a new folder, give it
2
- // its own name, pin the framework at the published version, and add the Claude Code skill.
2
+ // its own name, pin the framework at the published version, and add the Claude Code skill; then
3
+ // the git repository and its first commit, around the framework's local setup (plan-setup-wizard §3.1).
3
4
  // Node built-ins only: the package has no runtime dependencies.
5
+ import { spawnSync } from "node:child_process";
4
6
  import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { createRequire } from "node:module";
5
8
  import { basename, join, relative, resolve, sep } from "node:path";
9
+ import { pathToFileURL } from "node:url";
6
10
 
7
11
  export const FRAMEWORK_PACKAGE = "@lago-morph/prototype-framework";
8
12
 
@@ -40,6 +44,26 @@ export function copyTree(from, to, skip) {
40
44
  });
41
45
  }
42
46
 
47
+ /** The skill's version marker: one line, the version the skill was released at (DEC-0592). */
48
+ export const SKILL_VERSION_FILE = "VERSION";
49
+
50
+ /**
51
+ * Copy the skill in `from` to `to` (SKILL_SKIP left out) and give the copy its version marker:
52
+ * from the plugin manifest of the repository's skill/, or the marker an earlier copy carries.
53
+ * Returns the version, or undefined when `from` has neither.
54
+ */
55
+ export function copySkill(from, to) {
56
+ copyTree(from, to, SKILL_SKIP);
57
+ const manifest = join(from, ".claude-plugin", "plugin.json");
58
+ if (existsSync(manifest)) {
59
+ const { version } = JSON.parse(readFileSync(manifest, "utf8"));
60
+ writeFileSync(join(to, SKILL_VERSION_FILE), `${version}\n`);
61
+ return version;
62
+ }
63
+ const marker = join(to, SKILL_VERSION_FILE);
64
+ return existsSync(marker) ? readFileSync(marker, "utf8").trim() : undefined;
65
+ }
66
+
43
67
  /** The app name derived from a folder name: lowercase letters and digits only, cut to 20. */
44
68
  export function appNameFrom(dir) {
45
69
  return basename(resolve(dir)).toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 20);
@@ -110,7 +134,96 @@ export function create({ target, templateDir, skillDir = null, frameworkSpec, ap
110
134
  replaceOnce(join(dir, "index.html"), "<title>template</title>", `<title>${name}</title>`);
111
135
 
112
136
  const skill = skillDir !== null && existsSync(join(skillDir, "SKILL.md"));
113
- if (skill) copyTree(skillDir, join(dir, SKILL_TARGET), SKILL_SKIP);
137
+ if (skill) copySkill(skillDir, join(dir, SKILL_TARGET));
114
138
 
115
139
  return { target: dir, appName: name, packageName, skill };
116
140
  }
141
+
142
+ /** Runs git in `dir`; `{ error }` when git is missing or cannot start. */
143
+ function runGit(git, dir, args) {
144
+ const r = spawnSync(git, args, { cwd: dir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
145
+ if (r.error !== undefined) return { error: r.error };
146
+ return { status: r.status, stderr: (r.stderr ?? "").trim().split("\n")[0] ?? "" };
147
+ }
148
+
149
+ /**
150
+ * `git init` in `dir` (DEC-0596). Never throws: git missing or failing is a warning. A folder that
151
+ * is already inside a git work tree (a repository checkout) is left to that repository.
152
+ *
153
+ * @returns {{ status: "initialized" | "inside-repo" | "warned", message?: string }}
154
+ */
155
+ export function initRepo(dir, { git = "git" } = {}) {
156
+ const inside = runGit(git, dir, ["rev-parse", "--is-inside-work-tree"]);
157
+ if (inside.error !== undefined) {
158
+ return { status: "warned", message: "WARNING: git was not found, so this folder is not a git repository. Install git, then run `git init` here." };
159
+ }
160
+ if (inside.status === 0) return { status: "inside-repo", message: "This folder is inside an existing git repository: no new repository, and nothing committed." };
161
+ const r = runGit(git, dir, ["init", "-q"]);
162
+ if (r.error !== undefined || r.status !== 0) {
163
+ return { status: "warned", message: `WARNING: git init failed${r.stderr ? ` (${r.stderr})` : ""}, so this folder is not a git repository. Run \`git init\` here.` };
164
+ }
165
+ return { status: "initialized" };
166
+ }
167
+
168
+ /**
169
+ * The first commit of everything not ignored (DEC-0596). Never throws: a failure (for example
170
+ * no `user.name` / `user.email`) is a warning naming the commands to run.
171
+ *
172
+ * @returns {{ ok: boolean, message?: string }}
173
+ */
174
+ export function firstCommit(dir, message, { git = "git" } = {}) {
175
+ const add = runGit(git, dir, ["add", "-A"]);
176
+ const commit = add.error === undefined && add.status === 0 ? runGit(git, dir, ["commit", "-q", "-m", message]) : add;
177
+ if (commit.error !== undefined || commit.status !== 0) {
178
+ const why = commit.error === undefined && commit.stderr ? ` (${commit.stderr})` : "";
179
+ return { ok: false, message: `WARNING: the first commit failed${why}. Commit yourself: git add -A && git commit -m "First commit"` };
180
+ }
181
+ return { ok: true };
182
+ }
183
+
184
+ /**
185
+ * The framework's local setup (`runLocalSetup`, DEC-0591), loaded from the app's installed
186
+ * framework, so the starter and `cloudflare-setup` run the same steps. Undefined when the
187
+ * installed framework does not have it.
188
+ */
189
+ export async function loadLocalSetup(appDir) {
190
+ try {
191
+ const entry = createRequire(join(appDir, "package.json")).resolve(`${FRAMEWORK_PACKAGE}/provision`);
192
+ const mod = await import(pathToFileURL(entry).href);
193
+ return typeof mod.runLocalSetup === "function" ? { runLocalSetup: mod.runLocalSetup, describeLocalSetup: mod.describeLocalSetup } : undefined;
194
+ } catch {
195
+ return undefined;
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Runs the local setup in `appDir` and returns what to print. Never throws: a framework without
201
+ * it, or a run that throws, is a warning naming how to set the secrets by hand. The app stays
202
+ * usable either way (`dev` generates the framework's own keys), so the starter carries on to the
203
+ * first commit and exits 0 (DEC-0596).
204
+ *
205
+ * @returns {Promise<{ notes: string[], warnings: string[] }>}
206
+ */
207
+ export async function localSetupLines(appDir, { load = loadLocalSetup } = {}) {
208
+ const byHand = "set the app's secrets with `npm run secrets -- set <name> --target local --stage local`.";
209
+ let setup;
210
+ try {
211
+ setup = await load(appDir);
212
+ } catch {
213
+ setup = undefined;
214
+ }
215
+ if (setup === undefined) return { notes: [], warnings: [`WARNING: the installed framework has no local setup; ${byHand}`] };
216
+ try {
217
+ const outcomes = await setup.runLocalSetup(appDir);
218
+ const said = outcomes.filter((o) => o.message !== undefined);
219
+ return { notes: said.filter((o) => o.result !== "warned").map((o) => o.message), warnings: said.filter((o) => o.result === "warned").map((o) => o.message) };
220
+ } catch (error) {
221
+ return { notes: [], warnings: [`WARNING: the local setup failed (${error instanceof Error ? error.message : String(error)}). Run \`npm run dev\` once, then ${byHand}`] };
222
+ }
223
+ }
224
+
225
+ /** The closing line (plan §3.1): what to do next, with the folder as the owner would type it. */
226
+ export function nextStep(rel, { installed = true } = {}) {
227
+ const run = installed ? "`npm run dev`" : "`npm install` and `npm run dev`";
228
+ return rel === "." ? `Run ${run}, or open this folder in Claude Code and say what to build.` : `cd ${rel}, then ${run}, or open this folder in Claude Code and say what to build.`;
229
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lago-morph/create-prototype-app",
3
- "version": "0.1.0",
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
@@ -1,11 +1,13 @@
1
1
  ---
2
2
  name: prototype-framework
3
- description: Build, test and deploy small web apps on the portable prototype framework (@lago-morph/prototype-framework). Use when creating or changing an app built from apps/template, or when its verify, smoke or deploy fails.
3
+ description: Build, test and deploy small web apps on the portable prototype framework (@lago-morph/prototype-framework), and set up Cloudflare for them. Use when creating or changing an app built from apps/template; when its verify, smoke or deploy fails; when the user says "set up Cloudflare", "continue prototype setup" or "continue setup"; or on /prototype-framework … (for example /prototype-framework setup cloudflare, /prototype-framework continue setup).
4
4
  ---
5
5
 
6
6
  # Building apps on the prototype framework
7
7
 
8
- Apps are small (one or a few users, little data) and are designed to run unchanged locally, on Cloudflare and on AWS. In this phase only local runs are verified: running on Cloudflare is not yet verified, and AWS is a future release (this release targets local and Cloudflare). The framework gives each request handler SQL, KV, files, configuration, secrets, a log and the current user; app code never sees which cloud it runs on. Package: `@lago-morph/prototype-framework` (server code), `/client` (browser code), `/testing` (tests). Commands: `npx prototype-framework <command>`, also `npm run <command>`.
8
+ Apps are small (one or a few users, little data) and run unchanged locally and on Cloudflare. The framework gives each request handler SQL, KV, files, configuration, secrets, a log and the current user; app code never sees which cloud it runs on. Package: `@lago-morph/prototype-framework` (server code), `/client` (browser code), `/testing` (tests). Commands: `npm run <command>` (flags after `--`), or `npm exec --no -- prototype-framework <command>`; never plain `npx`, which fetches a stranger's package of that name when the app is not installed.
9
+
10
+ **First step of every session:** run `npm run version-check`. It changes nothing; relay its suggestions as it prints them, and its "newer npm release" one only once per session. If the app is not installed yet (no `node_modules`), skip the check until `npm install` has run. Then run the git checks of [Cloudflare setup](#cloudflare-setup).
9
11
 
10
12
  Read this page, then only the references your task needs (task map below).
11
13
 
@@ -13,9 +15,9 @@ Read this page, then only the references your task needs (task map below).
13
15
 
14
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.
15
17
  2. **Never insert user text as HTML.** Build elements and set `textContent`; no `innerHTML` or other raw-HTML sinks.
16
- 3. **Pass `npx prototype-framework 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).
17
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.
18
- 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`.
19
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:
20
22
  - the task attempted;
21
23
  - the contract or reference consulted (file and section);
@@ -25,7 +27,14 @@ Read this page, then only the references your task needs (task map below).
25
27
 
26
28
  Use [templates/FRAMEWORK-ISSUE.md](templates/FRAMEWORK-ISSUE.md).
27
29
  7. **After recording an entry**, stop work on the blocked requirement; continue only work that does not depend on it; report the issue and the list of unfinished requirements to the user; and do not declare the app done.
28
- 8. **A target this phase cannot reach is not a framework issue.** AWS is a future release, so there is no AWS target to deploy to, and Cloudflare runs may be paused (for example while a cloud quota is used up). Do not add a `FRAMEWORK-ISSUE.md` entry for that. In your build record, leave AWS out (it is not part of this release), and list each check that needs a paused Cloudflare run as `blocked` with the stated reason.
30
+ 8. **A cloud run that cannot go ahead is not a framework issue** (Cloudflare not set up yet, a run paused, a quota used up). Do not add a `FRAMEWORK-ISSUE.md` entry for it; in your build record, list each check that needs it as `blocked` with the reason.
31
+
32
+ ## Cloudflare setup
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. 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
+
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
+ - **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.
29
38
 
30
39
  ## Task map
31
40
 
@@ -40,35 +49,19 @@ Read this page, then only the references your task needs (task map below).
40
49
  | Add a per-stage setting | [configuration.md](reference/configuration.md) |
41
50
  | Use an API key; sign or verify data | [secrets.md](reference/secrets.md) |
42
51
  | Record what happened | [log.md](reference/log.md) |
43
- | 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 |
44
53
  | Deploy, run the smoke test on a cloud, remove a stage | [deploying.md](reference/deploying.md) |
45
54
  | Diagnose a failing request or deploy; a `verify` diagnostic | [troubleshooting.md](reference/troubleshooting.md), and the reference the diagnostic names |
46
- | Steps the owner performs (account setup 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) |
47
56
 
48
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.
49
58
 
50
- ## References
51
-
52
- - [http-and-validation.md](reference/http-and-validation.md): routes, guards, validation, error codes, browser calls, HTML safety.
53
- - [sql-and-migrations.md](reference/sql-and-migrations.md): tables, the portable query subset, `atomic`, migrations.
54
- - [kv.md](reference/kv.md): key-value storage.
55
- - [files.md](reference/files.md): tickets, the safe upload pattern, downloads.
56
- - [secrets.md](reference/secrets.md): declaring, reading and setting secrets; HMAC signing.
57
- - [configuration.md](reference/configuration.md): config keys and per-stage values files.
58
- - [current-user.md](reference/current-user.md): levels, the admin role, login, login tests.
59
- - [log.md](reference/log.md): writing entries and where they go.
60
- - [local-development.md](reference/local-development.md): scaffolding, `dev`, local state.
61
- - [testing.md](reference/testing.md): `createTestApp`, fake timers, the smoke test.
62
- - [deploying.md](reference/deploying.md): stages, deploy, smoke, remove.
63
- - [troubleshooting.md](reference/troubleshooting.md): finding log entries, error codes, login failures.
64
- - [owner-tasks.md](reference/owner-tasks.md): the owner's copy-and-paste steps.
65
-
66
59
  ## Examples and templates
67
60
 
68
- 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.
69
62
 
70
- 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.
71
64
 
72
65
  ## Done means
73
66
 
74
- `npx prototype-framework 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. Runs on a target this phase cannot reach 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 ADDED
@@ -0,0 +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
 
@@ -59,4 +59,4 @@ App code reads configuration only through `c.var.config`. Never read `process.en
59
59
 
60
60
  ## Stopping condition
61
61
 
62
- Stop reading when each setting is declared with a type, read through `c.var.config.get`, given values in each stage's committed file (or a default), and `npx prototype-framework verify` passes.
62
+ Stop reading when each setting is declared with a type, read through `c.var.config.get`, given values in each stage's committed file (or a default), and `npm run verify` passes.
@@ -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 `npx prototype-framework 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.