@humanonlyweb/create-nuxtflare 0.0.0-stage → 0.1.0

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 (138) hide show
  1. package/README.md +55 -2
  2. package/dist/cli.js +322 -0
  3. package/dist/template/.env.example +22 -0
  4. package/dist/template/.github/workflows/ci.yml +96 -0
  5. package/dist/template/.oxfmtrc.json +18 -0
  6. package/dist/template/.oxlintrc.json +69 -0
  7. package/dist/template/CLAUDE.md +42 -0
  8. package/dist/template/_gitignore +14 -0
  9. package/dist/template/app/app.vue +3 -0
  10. package/dist/template/app/components/qr-code.vue +36 -0
  11. package/dist/template/app/components/totp-setup.vue +151 -0
  12. package/dist/template/app/composables/use-features.ts +1 -0
  13. package/dist/template/app/composables/use-me.ts +10 -0
  14. package/dist/template/app/middleware/admin.global.ts +12 -0
  15. package/dist/template/app/middleware/auth.ts +6 -0
  16. package/dist/template/app/middleware/guest.ts +4 -0
  17. package/dist/template/app/pages/account.vue +22 -0
  18. package/dist/template/app/pages/admin/index.vue +16 -0
  19. package/dist/template/app/pages/admin/login.vue +39 -0
  20. package/dist/template/app/pages/index.vue +18 -0
  21. package/dist/template/app/pages/login.vue +110 -0
  22. package/dist/template/app/pages/register.vue +51 -0
  23. package/dist/template/app/utils/api-error.ts +50 -0
  24. package/dist/template/nuxt.config.ts +115 -0
  25. package/dist/template/package.json +59 -0
  26. package/dist/template/scripts/admin-password.ts +123 -0
  27. package/dist/template/server/api/account/email/index.delete.ts +5 -0
  28. package/dist/template/server/api/account/email/index.post.ts +8 -0
  29. package/dist/template/server/api/account/index.delete.ts +18 -0
  30. package/dist/template/server/api/account/index.patch.ts +16 -0
  31. package/dist/template/server/api/account/sessions.get.ts +11 -0
  32. package/dist/template/server/api/account/totp/cancel.post.ts +5 -0
  33. package/dist/template/server/api/account/totp/confirm.post.ts +10 -0
  34. package/dist/template/server/api/account/totp/disable.post.ts +8 -0
  35. package/dist/template/server/api/account/totp/index.get.ts +6 -0
  36. package/dist/template/server/api/account/totp/start.post.ts +8 -0
  37. package/dist/template/server/api/admin/me.get.ts +7 -0
  38. package/dist/template/server/api/admin/session/index.delete.ts +12 -0
  39. package/dist/template/server/api/admin/session/index.post.ts +18 -0
  40. package/dist/template/server/api/auth/email/index.post.ts +13 -0
  41. package/dist/template/server/api/auth/login/totp.post.ts +15 -0
  42. package/dist/template/server/api/auth/login.post.ts +17 -0
  43. package/dist/template/server/api/auth/logout-everywhere.post.ts +17 -0
  44. package/dist/template/server/api/auth/logout.post.ts +14 -0
  45. package/dist/template/server/api/auth/register.post.ts +18 -0
  46. package/dist/template/server/api/auth/reset/check.post.ts +5 -0
  47. package/dist/template/server/api/auth/reset/index.post.ts +5 -0
  48. package/dist/template/server/api/auth/reset/request.post.ts +5 -0
  49. package/dist/template/server/api/auth/verify/index.post.ts +17 -0
  50. package/dist/template/server/api/auth/verify/send.post.ts +7 -0
  51. package/dist/template/server/api/me.get.ts +8 -0
  52. package/dist/template/server/app/admin/auth.test.ts +41 -0
  53. package/dist/template/server/app/admin/auth.ts +133 -0
  54. package/dist/template/server/app/features.ts +18 -0
  55. package/dist/template/server/app/identity/email-change.ts +147 -0
  56. package/dist/template/server/app/identity/identity.test.ts +119 -0
  57. package/dist/template/server/app/identity/lockout.ts +93 -0
  58. package/dist/template/server/app/identity/password-reset.ts +119 -0
  59. package/dist/template/server/app/identity/service.ts +379 -0
  60. package/dist/template/server/app/identity/sessions.ts +141 -0
  61. package/dist/template/server/app/identity/state.ts +41 -0
  62. package/dist/template/server/app/identity/totp-crypto.ts +89 -0
  63. package/dist/template/server/app/identity/totp.test.ts +103 -0
  64. package/dist/template/server/app/identity/totp.ts +361 -0
  65. package/dist/template/server/app/identity/verification.ts +120 -0
  66. package/dist/template/server/app/notifications/email.ts +12 -0
  67. package/dist/template/server/app/notifications/render.test.ts +26 -0
  68. package/dist/template/server/app/notifications/render.ts +82 -0
  69. package/dist/template/server/app/notifications/samples.ts +11 -0
  70. package/dist/template/server/app/notifications/templates.ts +37 -0
  71. package/dist/template/server/assets/email/blocks/button.html +1 -0
  72. package/dist/template/server/assets/email/blocks/lead.html +1 -0
  73. package/dist/template/server/assets/email/blocks/note.html +1 -0
  74. package/dist/template/server/assets/email/blocks/text.html +1 -0
  75. package/dist/template/server/assets/email/layout.html +22 -0
  76. package/dist/template/server/cloudflare/exports/rate-limit.do.ts +38 -0
  77. package/dist/template/server/core/app-layer.ts +33 -0
  78. package/dist/template/server/core/db/atomic-d1.ts +21 -0
  79. package/dist/template/server/core/db/atomic.ts +86 -0
  80. package/dist/template/server/core/db/chunked.ts +13 -0
  81. package/dist/template/server/core/db/migrations.ts +149 -0
  82. package/dist/template/server/core/db/migrator.ts +39 -0
  83. package/dist/template/server/core/http/body-limit.ts +35 -0
  84. package/dist/template/server/core/http/csrf.ts +16 -0
  85. package/dist/template/server/core/http/device-label.ts +27 -0
  86. package/dist/template/server/core/http/handle.ts +271 -0
  87. package/dist/template/server/core/http/limit-key.ts +17 -0
  88. package/dist/template/server/core/http/page-csp.ts +16 -0
  89. package/dist/template/server/core/http/public-failure.ts +9 -0
  90. package/dist/template/server/core/http/request-user.ts +13 -0
  91. package/dist/template/server/core/http/runtime.ts +30 -0
  92. package/dist/template/server/core/http/session-cookie.ts +29 -0
  93. package/dist/template/server/core/platform/app-config.ts +55 -0
  94. package/dist/template/server/core/platform/clock.ts +4 -0
  95. package/dist/template/server/core/platform/database.ts +78 -0
  96. package/dist/template/server/core/platform/email-assets.ts +32 -0
  97. package/dist/template/server/core/platform/id-generator.ts +29 -0
  98. package/dist/template/server/core/platform/kv.ts +54 -0
  99. package/dist/template/server/core/platform/mailer-cloudflare.ts +51 -0
  100. package/dist/template/server/core/platform/mailer.ts +21 -0
  101. package/dist/template/server/core/platform/password-hasher.ts +27 -0
  102. package/dist/template/server/core/platform/pii.ts +80 -0
  103. package/dist/template/server/core/platform/provider-http.ts +21 -0
  104. package/dist/template/server/core/platform/rate-limiter-strict.ts +42 -0
  105. package/dist/template/server/core/platform/rate-limiter.ts +35 -0
  106. package/dist/template/server/core/platform/runtime-config-schema.ts +15 -0
  107. package/dist/template/server/core/platform/seal.ts +68 -0
  108. package/dist/template/server/core/platform/sliding-window.ts +39 -0
  109. package/dist/template/server/core/platform/tokens.ts +36 -0
  110. package/dist/template/server/core/platform/turnstile.ts +61 -0
  111. package/dist/template/server/middleware/00-body-limit.ts +10 -0
  112. package/dist/template/server/middleware/00-security-headers.ts +19 -0
  113. package/dist/template/server/middleware/01-user-session.ts +25 -0
  114. package/dist/template/server/plugins/page-csp.ts +15 -0
  115. package/dist/template/server/plugins/sessions.ts +21 -0
  116. package/dist/template/server/routes/(dev)/emails.get.dev.ts +37 -0
  117. package/dist/template/server/routes/auth/github.get.ts +96 -0
  118. package/dist/template/server/routes/auth/google.get.ts +61 -0
  119. package/dist/template/server/test/email-assets.ts +8 -0
  120. package/dist/template/server/test/invariants.test.ts +83 -0
  121. package/dist/template/server/test/kit.ts +83 -0
  122. package/dist/template/server/utils/define-validated-handler.ts +78 -0
  123. package/dist/template/server/utils/errors.ts +16 -0
  124. package/dist/template/server/utils/read-body.ts +34 -0
  125. package/dist/template/server/utils/user-actor.ts +10 -0
  126. package/dist/template/server.ts +5 -0
  127. package/dist/template/shared/domain/errors.ts +33 -0
  128. package/dist/template/shared/types/auth.d.ts +13 -0
  129. package/dist/template/shared/utils/admin.ts +13 -0
  130. package/dist/template/shared/utils/auth.ts +132 -0
  131. package/dist/template/shared/utils/ids.ts +21 -0
  132. package/dist/template/shared/utils/local-path.ts +2 -0
  133. package/dist/template/shared/utils/schema-validation.ts +59 -0
  134. package/dist/template/shared/utils/unknown.ts +9 -0
  135. package/dist/template/tsconfig.json +17 -0
  136. package/dist/template/vitest.config.ts +10 -0
  137. package/dist/template/wrangler.json +46 -0
  138. package/package.json +28 -4
package/README.md CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # `@humanonlyweb/create-nuxtflare`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ CLI scaffolder and starter template for **Nuxt 5 + Nitro + Cloudflare Workers + D1 + Effect v4**.
4
+
5
+ ## Usage
6
+
7
+ ### From npm
8
+
9
+ ```bash
10
+ bun create @humanonlyweb/nuxtflare@latest my-project
11
+ ```
12
+
13
+ Non-interactive with flags:
14
+
15
+ ```bash
16
+ bun create @humanonlyweb/nuxtflare@latest my-project -y \
17
+ --name "My Project" \
18
+ --domain myproject.com \
19
+ --totp \
20
+ --google \
21
+ --github
22
+ ```
23
+
24
+ ### Local (before publishing)
25
+
26
+ ```bash
27
+ bun bin/cli.ts my-project
28
+ ```
29
+
30
+ ## Publishing to npm
31
+
32
+ First release (creates the package on npm so Trusted Publishing can be linked):
33
+
34
+ ```bash
35
+ npm login
36
+ bun publish --access public
37
+ ```
38
+
39
+ Then configure **Trusted Publisher** on npmjs.com pointing at `humanonlyweb / nuxtflare / release.yml`. Future releases publish automatically with provenance when you push a matching `v*` tag:
40
+
41
+ ```bash
42
+ npm version patch # or minor / major
43
+ git push --follow-tags
44
+ ```
45
+
46
+ ## What's included
47
+
48
+ - **Cloudflare Workers + D1 + KV + Durable Objects + Email** behind Effect v4 `Context.Service` ports (`Database` with read-only transient retry, `AtomicBatch` with `runGuarded` + `assertPreviousChanged`, race-safe `MigratorLive`, `RateLimitCounter` sliding-window DO, `Pii` AES-256-GCM field encryption with key rotation + blind index, `Seal`, `Tokens`, `Turnstile`, `Mailer`, `EmailAssets`).
49
+ - **Explicit auth & TOTP 2FA**:
50
+ - Email + password + optional Google and GitHub OAuth, D1 revocable sessions with 3s in-isolate cache, email verification, password reset, email change, and per-subject lockout.
51
+ - Nitro server-asset email templates (`server/assets/email/layout.html` + `blocks/*.html`) rendered via `EmailRenderer` into HTML + plain text, with dev preview at `/emails`.
52
+ - Built-in WebCrypto RFC 4226/6238 **TOTP 2FA** (`Off -> Pending -> Enabled -> Off`), SVG QR code component, 8 single-use recovery codes, and AEAD-sealed login challenge tokens.
53
+ - **Two-lock Admin** (`@humanonlyweb/cf-access` + D1 admin password + 12h cookie + audit log) with `scripts/admin-password.ts`.
54
+ - **Single source of truth for feature toggles** in `nuxt.config.ts` (`features.totp`, `features.googleOAuth`, `features.githubOAuth`, `features.emailVerificationRequired`, `features.admin`): exposed via `runtimeConfig.public.features` so server services and client UI stay in sync.
55
+ - **No implicit state machines or invariants**: SQL `CHECK` constraints enforce `totp_status`, `email_status`, `login_failures.status`, credential presence, normalized email/username casing, and token lifecycles (`active | used | revoked`).
56
+ - **Fast test kit**: `server/test/kit.ts` boots real in-memory SQLite (`node:sqlite` via `db0`) with all migrations applied and fakes for Cloudflare bindings.
package/dist/cli.js ADDED
@@ -0,0 +1,322 @@
1
+ #!/usr/bin/env node
2
+
3
+ // bin/cli.ts
4
+ import { spawnSync } from "node:child_process";
5
+ import { basename as basename2, resolve as resolve2 } from "node:path";
6
+ // package.json
7
+ var package_default = {
8
+ name: "@humanonlyweb/create-nuxtflare",
9
+ version: "0.1.0",
10
+ description: "Scaffold a Nuxt 5 + Cloudflare Workers + D1 + Effect v4 app with explicit auth, TOTP 2FA, and admin.",
11
+ license: "MIT",
12
+ type: "module",
13
+ publishConfig: {
14
+ access: "public"
15
+ },
16
+ bin: {
17
+ "create-nuxtflare": "./dist/cli.js",
18
+ nuxtflare: "./dist/cli.js"
19
+ },
20
+ files: [
21
+ "dist"
22
+ ],
23
+ scripts: {
24
+ build: "bun scripts/build.ts",
25
+ test: "bun test src/scaffold.test.ts",
26
+ "test:template": "bun run --cwd template check",
27
+ "build:template": "bun run --cwd template build",
28
+ check: "bun run build && bun run test && bun run test:template && bun run build:template",
29
+ prepublishOnly: "bun run check"
30
+ },
31
+ engines: {
32
+ bun: ">=1.4.0",
33
+ node: ">=22.0.0"
34
+ },
35
+ packageManager: "bun@1.4.5"
36
+ };
37
+
38
+ // src/prompt.ts
39
+ import { createInterface } from "node:readline/promises";
40
+ var createPrompter = () => {
41
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
42
+ const text = async (question, fallback) => {
43
+ const answer = (await rl.question(`${question} (${fallback}): `)).trim();
44
+ return answer || fallback;
45
+ };
46
+ const confirm = async (question, fallback) => {
47
+ const hint = fallback ? "Y/n" : "y/N";
48
+ const answer = (await rl.question(`${question} (${hint}): `)).trim().toLowerCase();
49
+ if (!answer)
50
+ return fallback;
51
+ return answer === "y" || answer === "yes";
52
+ };
53
+ const close = () => rl.close();
54
+ return { text, confirm, close };
55
+ };
56
+
57
+ // src/scaffold.ts
58
+ import { randomBytes } from "node:crypto";
59
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
60
+ import { basename, join, resolve } from "node:path";
61
+ var SKIP_DIRS_AND_FILES = new Set([
62
+ "node_modules",
63
+ ".nuxt",
64
+ ".nitro",
65
+ ".cache",
66
+ ".output",
67
+ ".wrangler",
68
+ ".env",
69
+ "bun.lock",
70
+ "worker-configuration.d.ts",
71
+ ".DS_Store"
72
+ ]);
73
+ var bundledTemplate = resolve(import.meta.dirname, "template");
74
+ var TEMPLATE_DIR = existsSync(bundledTemplate) ? bundledTemplate : resolve(import.meta.dirname, "..", "template");
75
+ var toSlug = (raw) => {
76
+ const cleaned = raw.trim().toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
77
+ return cleaned || "nuxtflare-app";
78
+ };
79
+ var toTitle = (slug) => slug.split("-").filter(Boolean).map((part) => part[0].toUpperCase() + part.slice(1)).join(" ") || "Nuxtflare App";
80
+ var toCookiePrefix = (slug) => {
81
+ const cleaned = slug.replace(/[^a-z0-9]+/g, "").slice(0, 12);
82
+ return cleaned || "app";
83
+ };
84
+ var assertSafeDir = (targetDir) => {
85
+ if (!existsSync(targetDir))
86
+ return;
87
+ const entries = readdirSync(targetDir).filter((entry) => entry !== ".git");
88
+ if (entries.length > 0) {
89
+ throw new Error(`Target directory is not empty: ${targetDir}`);
90
+ }
91
+ };
92
+ var replaceInFile = (filePath, transform) => {
93
+ const current = readFileSync(filePath, "utf8");
94
+ const next = transform(current);
95
+ writeFileSync(filePath, next, "utf8");
96
+ };
97
+ var hexSecret = () => randomBytes(32).toString("hex");
98
+ var scaffold = (options) => {
99
+ const targetDir = resolve(options.targetDir);
100
+ assertSafeDir(targetDir);
101
+ mkdirSync(targetDir, { recursive: true });
102
+ cpSync(TEMPLATE_DIR, targetDir, {
103
+ recursive: true,
104
+ filter: (source) => !SKIP_DIRS_AND_FILES.has(basename(source))
105
+ });
106
+ const templateGitignore = join(targetDir, "_gitignore");
107
+ if (existsSync(templateGitignore)) {
108
+ renameSync(templateGitignore, join(targetDir, ".gitignore"));
109
+ }
110
+ replaceInFile(join(targetDir, "package.json"), (content) => {
111
+ const pkg = JSON.parse(content);
112
+ pkg.name = options.slug;
113
+ return `${JSON.stringify(pkg, null, 2)}
114
+ `;
115
+ });
116
+ replaceInFile(join(targetDir, "wrangler.json"), (content) => {
117
+ let next = content.replace(`"name": "nuxtflare-app"`, `"name": ${JSON.stringify(options.slug)}`).replace(`"database_name": "nuxtflare-app"`, `"database_name": ${JSON.stringify(options.slug)}`).replace(`"allowed_sender_addresses": ["no-reply@example.com"]`, `"allowed_sender_addresses": [${JSON.stringify(`no-reply@${options.domain}`)}]`);
118
+ if (options.domain && options.domain !== "example.com") {
119
+ const routeBlock = ` "routes": [
120
+ {
121
+ "pattern": ${JSON.stringify(options.domain)},
122
+ "custom_domain": true
123
+ }
124
+ ],
125
+ `;
126
+ next = next.replace(` "observability": {`, `${routeBlock} "observability": {`);
127
+ }
128
+ JSON.parse(next);
129
+ return next;
130
+ });
131
+ replaceInFile(join(targetDir, "nuxt.config.ts"), (content) => content.replace(/const features = \{[\s\S]*?\} as const/, `const features = {
132
+ totp: ${options.features.totp},
133
+ googleOAuth: ${options.features.googleOAuth},
134
+ githubOAuth: ${options.features.githubOAuth},
135
+ emailVerificationRequired: ${options.features.emailVerificationRequired},
136
+ admin: ${options.features.admin},
137
+ } as const`).replace(`title: 'Nuxtflare App'`, `title: '${options.appName.replaceAll("'", "\\'")}'`).replace(`appUrl: 'https://example.com'`, `appUrl: 'https://${options.domain}'`).replace(`adminEmails: 'admin@example.test'`, `adminEmails: 'admin@${options.slug}.test'`).replace(`appName: text('Nuxtflare App'`, `appName: text('${options.appName.replaceAll("'", "\\'")}'`).replace(`mailFrom: text('Nuxtflare App <no-reply@example.com>'`, `mailFrom: text('${options.appName.replaceAll("'", "\\'")} <no-reply@${options.domain}>'`).replace(`name: 'app-session'`, `name: '${options.cookiePrefix}-session'`));
138
+ replaceInFile(join(targetDir, "shared/utils/admin.ts"), (content) => content.replace(`ADMIN_COOKIE = 'app_admin'`, `ADMIN_COOKIE = '${options.cookiePrefix}_admin'`));
139
+ replaceInFile(join(targetDir, "server/routes/auth/google.get.ts"), (content) => content.replaceAll(`'app_next'`, `'${options.cookiePrefix}_next'`));
140
+ replaceInFile(join(targetDir, "server/routes/auth/github.get.ts"), (content) => content.replaceAll(`'app_next'`, `'${options.cookiePrefix}_next'`).replace(`'nuxtflare-oauth'`, `'${options.slug}-oauth'`));
141
+ replaceInFile(join(targetDir, ".github/workflows/ci.yml"), (content) => content.replace(`url: https://example.com`, `url: https://${options.domain}`));
142
+ replaceInFile(join(targetDir, "CLAUDE.md"), (content) => content.replace(`# Nuxtflare App`, `# ${options.appName}`));
143
+ replaceInFile(join(targetDir, "app/pages/index.vue"), (content) => content.replace(`<h1>Nuxtflare</h1>`, `<h1>${options.appName}</h1>`));
144
+ if (options.writeLocalEnv) {
145
+ const envLines = [
146
+ `NUXT_APP_SECRET=${hexSecret()}`,
147
+ `NUXT_PII_KEY=${hexSecret()}`,
148
+ `NUXT_PII_INDEX_KEY=${hexSecret()}`,
149
+ `NUXT_TURNSTILE_REQUIRED=false`,
150
+ `NUXT_RATE_LIMIT_SCALE=100`,
151
+ `NUXT_OAUTH_GOOGLE_CLIENT_ID=`,
152
+ `NUXT_OAUTH_GOOGLE_CLIENT_SECRET=`,
153
+ `NUXT_OAUTH_GITHUB_CLIENT_ID=`,
154
+ `NUXT_OAUTH_GITHUB_CLIENT_SECRET=`,
155
+ ``
156
+ ].join(`
157
+ `);
158
+ writeFileSync(join(targetDir, ".env"), envLines, "utf8");
159
+ }
160
+ return { targetDir };
161
+ };
162
+
163
+ // bin/cli.ts
164
+ var args = process.argv.slice(2);
165
+ var VALUE_FLAGS = new Set(["--name", "--domain", "--cookie-prefix"]);
166
+ var BOOLEAN_FLAGS = new Set([
167
+ "-y",
168
+ "--yes",
169
+ "-h",
170
+ "--help",
171
+ "-v",
172
+ "--version",
173
+ "--totp",
174
+ "--no-totp",
175
+ "--google",
176
+ "--no-google",
177
+ "--github",
178
+ "--no-github",
179
+ "--verify-email",
180
+ "--no-verify-email",
181
+ "--admin",
182
+ "--no-admin",
183
+ "--no-env",
184
+ "--no-git",
185
+ "--no-install"
186
+ ]);
187
+ var usage = `Usage: create-nuxtflare [directory] [options]
188
+
189
+ Options:
190
+ -y, --yes Skip interactive prompts and use defaults / flags
191
+ --name <name> Display name (default: Title Case of directory)
192
+ --domain <domain> Production domain (default: <slug>.com)
193
+ --cookie-prefix <prefix> Cookie prefix (default: alphanumeric slug)
194
+ --totp / --no-totp Enable/disable TOTP 2FA in nuxt.config.ts (default: on)
195
+ --google / --no-google Enable/disable Google OAuth in nuxt.config.ts (default: off)
196
+ --github / --no-github Enable/disable GitHub OAuth in nuxt.config.ts (default: off)
197
+ --verify-email / --no-verify-email
198
+ Require email verification on authed routes (default: on)
199
+ --admin / --no-admin Enable/disable two-lock Admin (CF Access + password) (default: on)
200
+ --no-env Skip generating local .env with random secrets
201
+ --no-git Skip git init
202
+ --no-install Skip bun install
203
+ -v, --version Show version
204
+ -h, --help Show this help message
205
+ `;
206
+ if (args.includes("-h") || args.includes("--help")) {
207
+ console.log(usage);
208
+ process.exit(0);
209
+ }
210
+ if (args.includes("-v") || args.includes("--version")) {
211
+ console.log(package_default.version);
212
+ process.exit(0);
213
+ }
214
+ var values = new Map;
215
+ var positionals = [];
216
+ for (let i = 0;i < args.length; i++) {
217
+ const arg = args[i];
218
+ if (VALUE_FLAGS.has(arg)) {
219
+ const next = args[i + 1];
220
+ if (!next || next.startsWith("-")) {
221
+ console.error(`Missing value for ${arg}
222
+
223
+ ${usage}`);
224
+ process.exit(1);
225
+ }
226
+ values.set(arg, next);
227
+ i++;
228
+ continue;
229
+ }
230
+ if (BOOLEAN_FLAGS.has(arg))
231
+ continue;
232
+ if (arg.startsWith("-")) {
233
+ console.error(`Unknown option: ${arg}
234
+
235
+ ${usage}`);
236
+ process.exit(1);
237
+ }
238
+ positionals.push(arg);
239
+ }
240
+ if (positionals.length > 1) {
241
+ console.error(`Expected at most one directory argument, received: ${positionals.join(", ")}
242
+
243
+ ${usage}`);
244
+ process.exit(1);
245
+ }
246
+ var boolFlag = (onFlag, offFlag) => {
247
+ if (args.includes(onFlag))
248
+ return true;
249
+ if (args.includes(offFlag))
250
+ return false;
251
+ return;
252
+ };
253
+ var nonInteractive = args.includes("-y") || args.includes("--yes") || !process.stdin.isTTY;
254
+ var targetInput = positionals[0] ?? "my-app";
255
+ var slug = toSlug(basename2(resolve2(targetInput)));
256
+ var appName = values.get("--name") ?? toTitle(slug);
257
+ var domain = values.get("--domain") ?? `${slug}.com`;
258
+ var cookiePrefix = values.get("--cookie-prefix") ?? toCookiePrefix(slug);
259
+ var totp = boolFlag("--totp", "--no-totp") ?? true;
260
+ var googleOAuth = boolFlag("--google", "--no-google") ?? false;
261
+ var githubOAuth = boolFlag("--github", "--no-github") ?? false;
262
+ var emailVerificationRequired = boolFlag("--verify-email", "--no-verify-email") ?? true;
263
+ var admin = boolFlag("--admin", "--no-admin") ?? true;
264
+ var writeLocalEnv = !args.includes("--no-env");
265
+ var runGit = !args.includes("--no-git");
266
+ var runInstall = !args.includes("--no-install");
267
+ if (!nonInteractive) {
268
+ const prompt = createPrompter();
269
+ try {
270
+ console.log(`
271
+ Nuxtflare v${package_default.version} — Nuxt 5 + Cloudflare Workers + Effect v4
272
+ `);
273
+ targetInput = await prompt.text("Project directory", targetInput);
274
+ slug = toSlug(basename2(resolve2(targetInput)));
275
+ appName = await prompt.text("App display name", values.get("--name") ?? toTitle(slug));
276
+ domain = await prompt.text("Production domain", values.get("--domain") ?? `${slug}.com`);
277
+ cookiePrefix = await prompt.text("Cookie prefix", values.get("--cookie-prefix") ?? toCookiePrefix(slug));
278
+ totp = await prompt.confirm("Enable TOTP 2FA (QR code + recovery codes)?", totp);
279
+ googleOAuth = await prompt.confirm("Enable Google OAuth?", googleOAuth);
280
+ githubOAuth = await prompt.confirm("Enable GitHub OAuth?", githubOAuth);
281
+ emailVerificationRequired = await prompt.confirm("Require verified email on authenticated routes?", emailVerificationRequired);
282
+ admin = await prompt.confirm("Enable two-lock Admin (Cloudflare Access + password)?", admin);
283
+ writeLocalEnv = await prompt.confirm("Generate local .env with random 32-byte secrets?", writeLocalEnv);
284
+ runInstall = await prompt.confirm("Run bun install now?", runInstall);
285
+ runGit = await prompt.confirm("Initialize git repository?", runGit);
286
+ } finally {
287
+ prompt.close();
288
+ }
289
+ }
290
+ var { targetDir } = scaffold({
291
+ targetDir: targetInput,
292
+ slug,
293
+ appName,
294
+ domain,
295
+ cookiePrefix,
296
+ features: { totp, googleOAuth, githubOAuth, emailVerificationRequired, admin },
297
+ writeLocalEnv
298
+ });
299
+ console.log(`
300
+ Scaffolded ${appName} in ${targetDir}`);
301
+ if (runGit) {
302
+ spawnSync("git", ["init"], { cwd: targetDir, stdio: "inherit" });
303
+ }
304
+ if (runInstall) {
305
+ const installed = spawnSync("bun", ["install"], { cwd: targetDir, stdio: "inherit" });
306
+ if (installed.status !== 0) {
307
+ console.error("\n`bun install` failed. Fix the error above and rerun `bun install`.");
308
+ process.exit(installed.status ?? 1);
309
+ }
310
+ }
311
+ var steps = [
312
+ targetInput === "." ? null : `cd ${targetInput}`,
313
+ runInstall ? null : "bun install",
314
+ "bun run dev",
315
+ "bun run check",
316
+ admin ? `bun scripts/admin-password.ts --email admin@${slug}.test` : null
317
+ ].filter((step) => step !== null);
318
+ console.log(`
319
+ Next steps:
320
+ ${steps.map((step) => ` ${step}`).join(`
321
+ `)}
322
+ `);
@@ -0,0 +1,22 @@
1
+ # Generate secrets with: openssl rand -hex 32
2
+ NUXT_APP_SECRET=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
3
+ NUXT_PII_KEY=1111111111111111111111111111111111111111111111111111111111111111
4
+ NUXT_PII_INDEX_KEY=2222222222222222222222222222222222222222222222222222222222222222
5
+
6
+ NUXT_TURNSTILE_REQUIRED=false
7
+ NUXT_PUBLIC_TURNSTILE_SITE_KEY=1x00000000000000000000BB
8
+
9
+ NUXT_RATE_LIMIT_SCALE=100
10
+
11
+ # Google sign-in (enable features.googleOAuth in nuxt.config.ts). Redirect URI: <app url>/auth/google
12
+ NUXT_OAUTH_GOOGLE_CLIENT_ID=
13
+ NUXT_OAUTH_GOOGLE_CLIENT_SECRET=
14
+
15
+ # GitHub sign-in (enable features.githubOAuth in nuxt.config.ts). Redirect URI: <app url>/auth/github
16
+ NUXT_OAUTH_GITHUB_CLIENT_ID=
17
+ NUXT_OAUTH_GITHUB_CLIENT_SECRET=
18
+
19
+ # Admin (enable features.admin in nuxt.config.ts). Local dev defaults to admin@example.test
20
+ # NUXT_CF_ACCESS_TEAM_DOMAIN=
21
+ # NUXT_CF_ACCESS_AUD=
22
+ # NUXT_ADMIN_EMAILS=
@@ -0,0 +1,96 @@
1
+ name: CI
2
+
3
+ on:
4
+ pull_request:
5
+ paths-ignore:
6
+ - 'docs/**'
7
+ push:
8
+ branches:
9
+ - main
10
+ paths-ignore:
11
+ - 'docs/**'
12
+ workflow_dispatch:
13
+
14
+ permissions:
15
+ contents: read
16
+
17
+ concurrency:
18
+ group: ${{ github.workflow }}-${{ github.ref }}
19
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
20
+
21
+ jobs:
22
+ verify:
23
+ name: Verify
24
+ runs-on: ubuntu-latest
25
+ timeout-minutes: 20
26
+
27
+ steps:
28
+ - name: Check out repository
29
+ uses: actions/checkout@v7.0.1
30
+
31
+ - name: Set up Bun
32
+ uses: oven-sh/setup-bun@v2.2.0
33
+ with:
34
+ bun-version-file: package.json
35
+
36
+ - name: Cache Bun packages
37
+ uses: actions/cache@v6.1.0
38
+ with:
39
+ path: ~/.bun/install/cache
40
+ key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('bun.lock') }}
41
+ restore-keys: |
42
+ ${{ runner.os }}-${{ runner.arch }}-bun-
43
+
44
+ - name: Install dependencies
45
+ run: bun install --frozen-lockfile
46
+
47
+ - name: Type-check
48
+ run: bun run typecheck
49
+
50
+ - name: Lint
51
+ run: bun run lint
52
+
53
+ - name: Format
54
+ run: bun run fmt:check
55
+
56
+ - name: Test
57
+ run: bun run test
58
+
59
+ - name: Build
60
+ run: bun run build
61
+
62
+ deploy:
63
+ name: Deploy production
64
+ if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
65
+ needs: verify
66
+ runs-on: ubuntu-latest
67
+ timeout-minutes: 20
68
+ environment:
69
+ name: production
70
+ url: https://example.com
71
+ env:
72
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
73
+
74
+ steps:
75
+ - name: Check out repository
76
+ uses: actions/checkout@v7.0.1
77
+
78
+ - name: Set up Bun
79
+ uses: oven-sh/setup-bun@v2.2.0
80
+ with:
81
+ bun-version-file: package.json
82
+
83
+ - name: Cache Bun packages
84
+ uses: actions/cache@v6.1.0
85
+ with:
86
+ path: ~/.bun/install/cache
87
+ key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('bun.lock') }}
88
+ restore-keys: |
89
+ ${{ runner.os }}-${{ runner.arch }}-bun-
90
+
91
+ - name: Install dependencies
92
+ run: bun install --frozen-lockfile
93
+
94
+ # Migrations run automatically on the Worker's first request.
95
+ - name: Build and deploy the Worker
96
+ run: bun run deploy
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "./node_modules/oxfmt/configuration_schema.json",
3
+ "printWidth": 160,
4
+ "semi": false,
5
+ "singleQuote": true,
6
+ "ignorePatterns": ["bun.lock", "worker-configuration.d.ts", "public/**", "server/assets/email/**"],
7
+ "sortImports": {
8
+ "groups": [
9
+ "type-import",
10
+ ["value-builtin", "value-external"],
11
+ "type-internal",
12
+ "value-internal",
13
+ ["type-parent", "type-sibling", "type-index"],
14
+ ["value-parent", "value-sibling", "value-index"],
15
+ "unknown"
16
+ ]
17
+ }
18
+ }
@@ -0,0 +1,69 @@
1
+ {
2
+ "$schema": "./node_modules/@effect/tsgo/oxlint-schema.json",
3
+ "extends": ["./node_modules/@effect/tsgo/oxlint-presets/recommended.json"],
4
+ "plugins": ["typescript", "unicorn", "oxc", "vue", "vitest"],
5
+ "env": {
6
+ "browser": true,
7
+ "node": true,
8
+ "builtin": true
9
+ },
10
+ "options": {
11
+ "typeAware": true
12
+ },
13
+ "categories": {
14
+ "correctness": "error",
15
+ "suspicious": "warn",
16
+ "perf": "warn"
17
+ },
18
+ "rules": {
19
+ "typescript/no-floating-promises": "error",
20
+ "typescript/consistent-type-imports": "error",
21
+ "eslint/no-underscore-dangle": "off",
22
+ "effecttsgo/unstable-api-usage": "off",
23
+ "unicorn/consistent-function-scoping": "off",
24
+ "typescript/no-misused-spread": "off",
25
+ "vitest/valid-expect": [
26
+ "error",
27
+ {
28
+ "maxArgs": 2
29
+ }
30
+ ],
31
+ "vitest/require-to-throw-message": "off",
32
+ "vitest/no-conditional-expect": "off",
33
+ "eslint/no-restricted-imports": [
34
+ "error",
35
+ {
36
+ "paths": [
37
+ {
38
+ "name": "h3",
39
+ "message": "Use nuxt/server instead of h3: its helpers and portable RequestEvent work cleanly with Nitro v3 and tests."
40
+ }
41
+ ]
42
+ }
43
+ ]
44
+ },
45
+ "ignorePatterns": ["worker-configuration.d.ts", "public/**"],
46
+ "overrides": [
47
+ {
48
+ "files": ["**/*.test.ts", "server/test/**"],
49
+ "rules": {
50
+ "effecttsgo/any-unknown-in-error-context": "off",
51
+ "typescript/no-unsafe-type-assertion": "off",
52
+ "effecttsgo/strict-effect-provide": "off",
53
+ "eslint/no-await-in-loop": "off"
54
+ }
55
+ },
56
+ {
57
+ "files": ["shared/types/auth.d.ts"],
58
+ "rules": {
59
+ "unicorn/require-module-specifiers": "off"
60
+ }
61
+ },
62
+ {
63
+ "files": ["server/**"],
64
+ "rules": {
65
+ "typescript/consistent-return": "off"
66
+ }
67
+ }
68
+ ]
69
+ }
@@ -0,0 +1,42 @@
1
+ # Nuxtflare App
2
+
3
+ Nuxt 5 / Nitro on one Cloudflare Worker, D1 via `useDatabase()` (no ORM), Effect v4 services, thin routes.
4
+
5
+ ## Architecture
6
+
7
+ - `server/core/`: Platform ports (`Database`, `AtomicBatch`, `Kv`, `Pii`, `Seal`, `Tokens`, `PasswordHasher`, `IdGenerator`, `RateLimiter`, `Turnstile`, `Mailer`, `EmailAssets`), HTTP handlers (`handlePublic`, `handleAuthed`, `handleAdmin`), migrations, and `app-layer.ts`.
8
+ - `server/app/`: Domain features (`identity/`, `notifications/`, `admin/`, plus your own features) composed once in `server/app/features.ts`.
9
+ - `server/assets/email/`: Nitro server-asset HTML layout and blocks rendered by `EmailRenderer` (both HTML and plain text). Preview all templates in dev at `/emails`.
10
+ - `server/api/`: Thin routes. Routes validate schemas, delegate to Effect services, and encode responses — no business logic.
11
+ - `server/cloudflare/exports/`: Durable Objects (`RateLimitCounter`). Exported from root `server.ts`.
12
+ - `shared/`: Schemas, branded IDs, and tagged domain errors shared by server and client.
13
+
14
+ ## Core Design Principles (Apply Everywhere)
15
+
16
+ ### No implicit state machines
17
+
18
+ Every multi-state lifecycle anywhere in the app — database tables, Effect services, API responses, platform adapters, and Vue UI flows — must be modeled explicitly rather than inferred from combinations of booleans or nullable fields:
19
+
20
+ - **Database**: Store an explicit `status` column with `CHECK (status IN (...))` paired with a `CHECK` constraint coupling every state-dependent column (for example, `totp_status`, `email_status`, `login_failures.status`, and token `status`). Never infer state from whether multiple nullable timestamps/columns happen to be `NULL`.
21
+ - **Services & domain code**: Decode rows and config into discriminated unions (`_tag` or `status`) and exhaustively `switch` on them. Model transitions as explicit functions/SQL `WHERE status = ...` guards.
22
+ - **API & shared schemas**: Never emit parallel nullable fields that only make sense together (use a single nullable struct or a `Schema.Union` of tagged variants such as `LoginResponse` or `pendingEmailChange`).
23
+ - **Frontend UI**: Model multi-step flows (sign-in, enrolment, editors, async wizards) as a single discriminated union ref (e.g. `step: { kind: 'idle' } | { kind: 'enrolling'; ... }`) instead of independent boolean flags that can contradict each other.
24
+
25
+ ### No implicit invariants
26
+
27
+ Never rely on callers "remembering" a rule, ordering assumption, or hidden convention — enforce every invariant at the lowest boundary where it can be violated:
28
+
29
+ - **Database constraints first**: Enforce uniqueness, normalization (`lower(trim(...))`), foreign keys (`ON DELETE CASCADE`), non-negativity, timestamp ordering (`expires_at > created_at`), and required credential rules directly with SQL `CHECK` constraints, and cover them in `server/test/invariants.test.ts`.
30
+ - **Fail fast at layer construction**: Validate secrets, key lengths, and incompatible configuration when building Effect layers (e.g. `Pii.layer`, `Turnstile.layer`), not lazily on the first request that happens to touch them.
31
+ - **Typed conditional writes**: Multi-statement conditional D1 writes go through `AtomicBatch.runGuarded` + `assertPreviousChanged` so failed preconditions surface as a typed `GuardFailed` error instead of raw SQL tricks or error-string regexes.
32
+ - **Single source of truth for feature toggles**: Feature flags live in `nuxt.config.ts` (`runtimeConfig.public.features`) and are read by both server (`AppConfig`) and client (`useFeatures()`). Disabled features fail explicitly with `Forbidden` / `ServiceNotConfigured`.
33
+ - **No silent fallbacks or unverified trust**: External HTTP calls go through Effect's `HttpClient` (`providerHttp`) with explicit timeouts, retries, and `Schema` decoding. Never trust unverified OAuth emails, unvalidated inputs, or unchecked JSON parses.
34
+
35
+ ## Conventions
36
+
37
+ - **Comments**: No useless or restating comments — only add a comment when it explains a non-obvious reason, constraint, or trade-off that genuinely improves understanding.
38
+ - **Vue components**: Component filenames use `kebab-case` (e.g. `app/components/qr-code.vue`, `app/components/totp-setup.vue`).
39
+ - **Typed errors only**: Services fail with tagged errors from `shared/domain/errors.ts` or `server/utils/errors.ts`. Unexpected defects become a bare 500.
40
+ - **D1 safety**: Bound parameters are capped at 100 per statement — use `chunked` for variable-length `IN (...)` lists. Pure `SELECT` queries retry transient D1 resets; writes never retry automatically.
41
+ - **Secrets**: Come from Nuxt runtime config (`NUXT_*`), wrapped in `Redacted` inside `AppConfig`. Never read secrets off Cloudflare `env`.
42
+ - **Testing**: `server/test/kit.ts` boots real SQLite (`node:sqlite` via `db0`) with all migrations applied and fast in-memory fakes for Cloudflare bindings. Keep `bun run check` green.
@@ -0,0 +1,14 @@
1
+ node_modules
2
+ .nuxt
3
+ .nitro
4
+ .cache
5
+ .output
6
+ .wrangler
7
+ dist
8
+ .env
9
+ .env.*
10
+ !.env.example
11
+ .DS_Store
12
+ *.log
13
+ .wrangler/
14
+ worker-configuration.d.ts
@@ -0,0 +1,3 @@
1
+ <template>
2
+ <NuxtPage />
3
+ </template>