@humanonlyweb/create-nuxtflare 0.0.0-stage → 0.1.1

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 +340 -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 +46 -4
@@ -0,0 +1,96 @@
1
+ import { Effect, Schema } from 'effect'
2
+ import { HttpClientRequest, HttpClientResponse } from 'effect/http'
3
+ import { deleteCookie, getCookie, sendRedirect } from 'nuxt/server'
4
+
5
+ import { Identity } from '#server/app/identity/service'
6
+ import { runtime } from '#server/core/http/runtime'
7
+ import { establishUserSession } from '#server/core/http/session-cookie'
8
+ import { providerHttp } from '#server/core/platform/provider-http'
9
+ import { UpstreamFailure } from '#server/utils/errors'
10
+ import { isLocalPath } from '#shared/utils/local-path'
11
+
12
+ const GitHubEmailList = Schema.Array(
13
+ Schema.Struct({
14
+ email: Schema.String,
15
+ primary: Schema.Boolean,
16
+ verified: Schema.Boolean,
17
+ }),
18
+ )
19
+
20
+ const nextPath = (cookie: string | undefined) => {
21
+ try {
22
+ const next = decodeURIComponent(cookie ?? '')
23
+ return isLocalPath(next) ? next : undefined
24
+ } catch {
25
+ return undefined
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Resolves the user's primary verified email explicitly via Effect's `HttpClient`:
31
+ * `nuxt-auth-utils` only queries `/user/emails` when the public profile email is empty,
32
+ * so when `email_verified` is absent we verify it directly.
33
+ */
34
+ const resolveVerifiedEmail = (accessToken: string, email: string | null, emailVerified: boolean | undefined) =>
35
+ Effect.gen(function* () {
36
+ if (email && emailVerified !== undefined) return { email, verified: emailVerified }
37
+ const http = yield* providerHttp({
38
+ provider: 'github',
39
+ baseUrl: 'https://api.github.com',
40
+ headers: {
41
+ Accept: 'application/vnd.github+json',
42
+ Authorization: `Bearer ${accessToken}`,
43
+ 'User-Agent': 'nuxtflare-oauth',
44
+ },
45
+ retries: 1,
46
+ })
47
+ const emails = yield* http.execute(HttpClientRequest.get('/user/emails')).pipe(
48
+ Effect.timeout('10 seconds'),
49
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(GitHubEmailList)),
50
+ Effect.mapError(() => new UpstreamFailure({ service: 'github', message: 'Could not read verified email from GitHub.' })),
51
+ )
52
+ const primary = emails.find((entry) => entry.primary)
53
+ if (!primary) return yield* new UpstreamFailure({ service: 'github', message: 'No primary email found on GitHub account.' })
54
+ return { email: primary.email, verified: primary.verified }
55
+ })
56
+
57
+ export default defineOAuthGitHubEventHandler({
58
+ config: { scope: ['user:email'], emailRequired: true },
59
+ async onSuccess(event, { user, tokens }) {
60
+ if (!user.id) return sendRedirect(event, '/login?error=github')
61
+
62
+ const result = await runtime.runPromise(
63
+ Effect.gen(function* () {
64
+ const resolved = yield* resolveVerifiedEmail(tokens.access_token, user.email, user.email_verified)
65
+ const identity = yield* Identity
66
+ const outcome = yield* identity.oauth({
67
+ provider: 'github',
68
+ providerId: String(user.id),
69
+ email: resolved.email,
70
+ emailVerified: resolved.verified,
71
+ preferredUsername: user.login,
72
+ })
73
+ if (outcome.status === 'authenticated') {
74
+ yield* establishUserSession(event, outcome.user)
75
+ }
76
+ return outcome
77
+ }).pipe(Effect.result),
78
+ )
79
+
80
+ if (result._tag === 'Failure') {
81
+ const code = result.failure._tag === 'Conflict' ? 'github-email' : result.failure._tag === 'Forbidden' ? 'github-disabled' : 'github'
82
+ return sendRedirect(event, `/login?error=${code}`)
83
+ }
84
+
85
+ if (result.success.status === 'totp_required') {
86
+ return sendRedirect(event, `/login#totp=${encodeURIComponent(result.success.challenge)}`)
87
+ }
88
+
89
+ const next = nextPath(getCookie(event, 'app_next'))
90
+ deleteCookie(event, 'app_next', { path: '/auth' })
91
+ return sendRedirect(event, next ?? '/account')
92
+ },
93
+ onError(event) {
94
+ return sendRedirect(event, '/login?error=github')
95
+ },
96
+ })
@@ -0,0 +1,61 @@
1
+ import { Effect } from 'effect'
2
+ import { deleteCookie, getCookie, sendRedirect } from 'nuxt/server'
3
+
4
+ import { Identity } from '#server/app/identity/service'
5
+ import { runtime } from '#server/core/http/runtime'
6
+ import { establishUserSession } from '#server/core/http/session-cookie'
7
+ import { isLocalPath } from '#shared/utils/local-path'
8
+
9
+ interface GoogleUser {
10
+ readonly sub?: string
11
+ readonly email?: string
12
+ readonly email_verified?: boolean | string
13
+ }
14
+
15
+ const nextPath = (cookie: string | undefined) => {
16
+ try {
17
+ const next = decodeURIComponent(cookie ?? '')
18
+ return isLocalPath(next) ? next : undefined
19
+ } catch {
20
+ return undefined
21
+ }
22
+ }
23
+
24
+ export default defineOAuthGoogleEventHandler({
25
+ config: { scope: ['openid', 'email'] },
26
+ async onSuccess(event, { user }: { user: GoogleUser }) {
27
+ if (!user.sub || !user.email) return sendRedirect(event, '/login?error=google')
28
+
29
+ const result = await runtime.runPromise(
30
+ Effect.gen(function* () {
31
+ const identity = yield* Identity
32
+ const outcome = yield* identity.oauth({
33
+ provider: 'google',
34
+ providerId: user.sub!,
35
+ email: user.email!,
36
+ emailVerified: user.email_verified === true || user.email_verified === 'true',
37
+ })
38
+ if (outcome.status === 'authenticated') {
39
+ yield* establishUserSession(event, outcome.user)
40
+ }
41
+ return outcome
42
+ }).pipe(Effect.result),
43
+ )
44
+
45
+ if (result._tag === 'Failure') {
46
+ const code = result.failure._tag === 'Conflict' ? 'google-email' : result.failure._tag === 'Forbidden' ? 'google-disabled' : 'google'
47
+ return sendRedirect(event, `/login?error=${code}`)
48
+ }
49
+
50
+ if (result.success.status === 'totp_required') {
51
+ return sendRedirect(event, `/login#totp=${encodeURIComponent(result.success.challenge)}`)
52
+ }
53
+
54
+ const next = nextPath(getCookie(event, 'app_next'))
55
+ deleteCookie(event, 'app_next', { path: '/auth' })
56
+ return sendRedirect(event, next ?? '/account')
57
+ },
58
+ onError(event) {
59
+ return sendRedirect(event, '/login?error=google')
60
+ },
61
+ })
@@ -0,0 +1,8 @@
1
+ import { Layer } from 'effect'
2
+
3
+ import { EmailAssets } from '#server/core/platform/email-assets'
4
+
5
+ // Vitest runs outside Nitro without `assets:server`; bundle the same HTML files via Vite instead.
6
+ const files = import.meta.glob<string>('../assets/email/**/*.html', { query: '?raw', import: 'default', eager: true })
7
+
8
+ export const EmailAssetsBundled = Layer.sync(EmailAssets, () => EmailAssets.from(async (name) => files[`../assets/email/${name}`]))
@@ -0,0 +1,83 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { makeTestLayer } from './kit'
4
+
5
+ describe('database invariants', () => {
6
+ it('rejects impossible TOTP state combinations via SQL CHECK constraints', async () => {
7
+ const { db } = await makeTestLayer()
8
+ const now = new Date().toISOString()
9
+
10
+ // totp_status = 'off' with a secret is rejected
11
+ await expect(async () =>
12
+ db.exec(
13
+ `INSERT INTO users (id, username, email, password_hash, email_status, totp_status, totp_secret, created_at, last_active_at)
14
+ VALUES ('usr_1', 'alice', 'alice@example.com', 'hash', 'unverified', 'off', 'secret', '${now}', '${now}')`,
15
+ ),
16
+ ).rejects.toThrow()
17
+
18
+ // totp_status = 'enabled' without totp_enabled_at is rejected
19
+ await expect(async () =>
20
+ db.exec(
21
+ `INSERT INTO users (id, username, email, password_hash, email_status, totp_status, totp_secret, created_at, last_active_at)
22
+ VALUES ('usr_2', 'bob', 'bob@example.com', 'hash', 'unverified', 'enabled', 'secret', '${now}', '${now}')`,
23
+ ),
24
+ ).rejects.toThrow()
25
+ })
26
+
27
+ it('rejects users without any authentication credential (no password, Google sub, or GitHub id)', async () => {
28
+ const { db } = await makeTestLayer()
29
+ const now = new Date().toISOString()
30
+
31
+ await expect(async () =>
32
+ db.exec(
33
+ `INSERT INTO users (id, username, email, email_status, totp_status, created_at, last_active_at)
34
+ VALUES ('usr_3', 'ghost', 'ghost@example.com', 'unverified', 'off', '${now}', '${now}')`,
35
+ ),
36
+ ).rejects.toThrow()
37
+ })
38
+
39
+ it('rejects unnormalized email or username casing and inconsistent email verification state', async () => {
40
+ const { db } = await makeTestLayer()
41
+ const now = new Date().toISOString()
42
+
43
+ await expect(async () =>
44
+ db.exec(
45
+ `INSERT INTO users (id, username, email, password_hash, email_status, totp_status, created_at, last_active_at)
46
+ VALUES ('usr_4', 'Alice', 'alice@example.com', 'hash', 'unverified', 'off', '${now}', '${now}')`,
47
+ ),
48
+ ).rejects.toThrow()
49
+
50
+ await expect(async () =>
51
+ db.exec(
52
+ `INSERT INTO users (id, username, email, password_hash, email_status, email_verified_at, totp_status, created_at, last_active_at)
53
+ VALUES ('usr_5', 'carol', 'carol@example.com', 'hash', 'verified', NULL, 'off', '${now}', '${now}')`,
54
+ ),
55
+ ).rejects.toThrow()
56
+ })
57
+
58
+ it('rejects inconsistent login_failures states and token lifecycle states', async () => {
59
+ const { db } = await makeTestLayer()
60
+ const now = new Date().toISOString()
61
+ const later = new Date(Date.now() + 3_600_000).toISOString()
62
+
63
+ // counting with 0 failures is rejected
64
+ await expect(async () =>
65
+ db.exec(`INSERT INTO login_failures (subject, status, failures, locked_until) VALUES ('u1', 'counting', 0, NULL)`),
66
+ ).rejects.toThrow()
67
+
68
+ // locked without locked_until is rejected
69
+ await expect(async () => db.exec(`INSERT INTO login_failures (subject, status, failures, locked_until) VALUES ('u2', 'locked', 0, NULL)`)).rejects.toThrow()
70
+
71
+ // active token with used_at set is rejected
72
+ await db.exec(
73
+ `INSERT INTO users (id, username, email, password_hash, email_status, totp_status, created_at, last_active_at)
74
+ VALUES ('usr_6', 'dave', 'dave@example.com', 'hash', 'unverified', 'off', '${now}', '${now}')`,
75
+ )
76
+ await expect(async () =>
77
+ db.exec(
78
+ `INSERT INTO email_verification_tokens (token_hash, user_id, email, status, created_at, expires_at, used_at)
79
+ VALUES ('hash1', 'usr_6', 'dave@example.com', 'active', '${now}', '${later}', '${now}')`,
80
+ ),
81
+ ).rejects.toThrow()
82
+ })
83
+ })
@@ -0,0 +1,83 @@
1
+ import { createDatabase } from 'db0'
2
+ import nodeSqlite from 'db0/connectors/node-sqlite'
3
+ import { Effect, Layer, Redacted } from 'effect'
4
+ import { FetchHttpClient } from 'effect/http'
5
+
6
+ import type { FeatureFlags, Settings } from '#server/core/platform/app-config'
7
+ import type { Mail } from '#server/core/platform/mailer'
8
+
9
+ import { Features } from '#server/app/features'
10
+ import { AtomicBatch } from '#server/core/db/atomic'
11
+ import { migrations } from '#server/core/db/migrations'
12
+ import { AppConfig } from '#server/core/platform/app-config'
13
+ import { Database } from '#server/core/platform/database'
14
+ import { IdGenerator } from '#server/core/platform/id-generator'
15
+ import { Kv } from '#server/core/platform/kv'
16
+ import { Mailer } from '#server/core/platform/mailer'
17
+ import { PasswordHasher } from '#server/core/platform/password-hasher'
18
+ import { Pii } from '#server/core/platform/pii'
19
+ import { RateLimiter } from '#server/core/platform/rate-limiter'
20
+ import { Seal } from '#server/core/platform/seal'
21
+ import { Tokens } from '#server/core/platform/tokens'
22
+ import { Turnstile } from '#server/core/platform/turnstile'
23
+
24
+ import { EmailAssetsBundled } from './email-assets'
25
+
26
+ export const testConfig = (overrides: Partial<Omit<Settings, 'features'>> & { readonly features?: Partial<FeatureFlags> } = {}): Settings => ({
27
+ appName: 'Starter Test',
28
+ appUrl: 'https://starter.test',
29
+ mailFrom: 'Starter Test <no-reply@starter.test>',
30
+ appSecret: Redacted.make('a'.repeat(64)),
31
+ piiKey: Redacted.make('b'.repeat(64)),
32
+ piiKeyPrevious: Redacted.make(''),
33
+ piiIndexKey: Redacted.make('c'.repeat(64)),
34
+ turnstileSecret: Redacted.make(''),
35
+ turnstileRequired: false,
36
+ rateLimitScale: 1,
37
+ adminEmails: 'admin@starter.test',
38
+ ...overrides,
39
+ features: {
40
+ totp: true,
41
+ googleOAuth: true,
42
+ githubOAuth: true,
43
+ emailVerificationRequired: true,
44
+ admin: true,
45
+ ...overrides.features,
46
+ },
47
+ })
48
+
49
+ /** Boots an in-memory SQLite database with all migrations applied and fast fakes for Cloudflare bindings. */
50
+ export const makeTestLayer = async (
51
+ options: {
52
+ readonly config?: Partial<Omit<Settings, 'features'>> & { readonly features?: Partial<FeatureFlags> }
53
+ readonly turnstile?: Layer.Layer<Turnstile>
54
+ readonly mailer?: Layer.Layer<Mailer>
55
+ readonly limiter?: Layer.Layer<RateLimiter>
56
+ } = {},
57
+ ) => {
58
+ const db = createDatabase(nodeSqlite({ name: ':memory:' }))
59
+
60
+ await db.exec('PRAGMA foreign_keys = ON')
61
+ for (const statement of migrations.flatMap((migration) => migration.statements)) await db.exec(statement)
62
+
63
+ const sent: Mail[] = []
64
+ const platform = Layer.mergeAll(
65
+ Database.layerFor(db),
66
+ AtomicBatch.layerFor(db),
67
+ IdGenerator.sequential(),
68
+ Tokens.layer,
69
+ Kv.memory(),
70
+ EmailAssetsBundled,
71
+ options.mailer ?? Mailer.recording(sent),
72
+ PasswordHasher.fake,
73
+ options.limiter ?? RateLimiter.unlimited,
74
+ options.turnstile ?? Turnstile.off,
75
+ FetchHttpClient.layer,
76
+ Pii.layer.pipe(Layer.provideMerge(Layer.mergeAll(Seal.layer, Layer.succeed(AppConfig, testConfig(options.config))))),
77
+ )
78
+
79
+ const layer = Features.pipe(Layer.provideMerge(platform))
80
+ type TestServices = Layer.Success<typeof layer>
81
+ const run = <A, E>(program: Effect.Effect<A, E, TestServices>) => Effect.runPromise(program.pipe(Effect.provide(layer)))
82
+ return { layer, run, db, sent }
83
+ }
@@ -0,0 +1,78 @@
1
+ import type { NuxtErrorDetails, RequestEvent } from 'nuxt/server'
2
+
3
+ import { createError, defineHandler, getQuery, getRouterParams } from 'nuxt/server'
4
+
5
+ import { readLimitedJson } from './read-body'
6
+
7
+ interface StandardSchema<Output = unknown> {
8
+ readonly '~standard': {
9
+ readonly version: 1
10
+ readonly vendor: string
11
+ readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>
12
+ readonly types?: { readonly input: unknown; readonly output: Output } | undefined
13
+ }
14
+ }
15
+
16
+ interface Issue {
17
+ readonly message: string
18
+ readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined
19
+ }
20
+
21
+ type StandardResult<Output> = { readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<Issue> }
22
+
23
+ type SchemaOutput<S extends StandardSchema> = NonNullable<S['~standard']['types']>['output']
24
+
25
+ type OnValidateError = (result: { issues: ReadonlyArray<Issue> }) => NuxtErrorDetails
26
+
27
+ /** Every validation failure carries `data._tag = 'ValidationFailed'` so clients switch on `_tag` uniformly. */
28
+ const validationFailed: OnValidateError = ({ issues }) => ({
29
+ status: 400,
30
+ statusText: 'Bad Request',
31
+ message: 'Validation failed',
32
+ data: { _tag: 'ValidationFailed', issues },
33
+ })
34
+
35
+ async function validateInput<S extends StandardSchema>(schema: S, data: unknown, onError: OnValidateError = validationFailed): Promise<SchemaOutput<S>> {
36
+ const result = await schema['~standard'].validate(data)
37
+ if (result.issues) throw createError(onError({ issues: result.issues }))
38
+ return result.value
39
+ }
40
+
41
+ export async function getValidatedRouterParams<S extends StandardSchema>(
42
+ event: Pick<RequestEvent, 'context'>,
43
+ schema: S,
44
+ options: { onError?: OnValidateError } = {},
45
+ ): Promise<SchemaOutput<S>> {
46
+ return validateInput(schema, getRouterParams(event, { decode: true }), options.onError)
47
+ }
48
+
49
+ interface Validate {
50
+ readonly params?: StandardSchema
51
+ readonly query?: StandardSchema
52
+ readonly body?: StandardSchema
53
+ readonly headers?: StandardSchema
54
+ readonly onError?: OnValidateError
55
+ }
56
+
57
+ type Validated<V extends Validate> = {
58
+ readonly [K in 'params' | 'query' | 'body' | 'headers' as V[K] extends StandardSchema ? K : never]: V[K] extends StandardSchema ? SchemaOutput<V[K]> : never
59
+ }
60
+
61
+ export function defineValidatedHandler<const V extends Validate, Result>(def: {
62
+ readonly validate: V
63
+ readonly handler: (event: RequestEvent, input: Validated<V>) => Result | Promise<Result>
64
+ }) {
65
+ const { validate, handler } = def
66
+ const onError = validate.onError ?? validationFailed
67
+ return defineHandler(async (event) => {
68
+ const input: Record<string, unknown> = {}
69
+ if (validate.headers) input.headers = await validateInput(validate.headers, Object.fromEntries(event.req.headers), onError)
70
+ if (validate.params) input.params = await getValidatedRouterParams(event, validate.params, { onError })
71
+ if (validate.query) input.query = await validateInput(validate.query, getQuery(event), onError)
72
+ if (validate.body) input.body = await validateInput(validate.body, await readLimitedJson(event), onError)
73
+
74
+ // Each part was validated by its own schema above; TypeScript cannot narrow into the mapped type.
75
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
76
+ return handler(event, input as Validated<V>)
77
+ })
78
+ }
@@ -0,0 +1,16 @@
1
+ import { Schema } from 'effect'
2
+
3
+ export class ServiceNotConfigured extends Schema.TaggedError<ServiceNotConfigured, { readonly brand: unique symbol }>()('ServiceNotConfigured', {
4
+ service: Schema.String,
5
+ message: Schema.String,
6
+ }) {}
7
+
8
+ export class UpstreamFailure extends Schema.TaggedError<UpstreamFailure, { readonly brand: unique symbol }>()('UpstreamFailure', {
9
+ service: Schema.String,
10
+ message: Schema.String,
11
+ }) {}
12
+
13
+ /** TOTP crypto failed: a stored secret is corrupt or WebCrypto errored. Always a server defect. */
14
+ export class TotpCryptoError extends Schema.TaggedError<TotpCryptoError, { readonly brand: unique symbol }>()('TotpCryptoError', {
15
+ message: Schema.String,
16
+ }) {}
@@ -0,0 +1,34 @@
1
+ import type { RequestEvent } from 'nuxt/server'
2
+
3
+ import { Effect, Predicate } from 'effect'
4
+ import { createError, getRequestURL } from 'nuxt/server'
5
+
6
+ import { bodyLimitFor, readCapped } from '#server/core/http/body-limit'
7
+ import { TooLarge } from '#shared/domain/errors'
8
+
9
+ const FALLBACK_LIMIT = 1024 * 1024
10
+ const limitOf = (event: RequestEvent) => bodyLimitFor(event.req.method, getRequestURL(event).pathname) ?? FALLBACK_LIMIT
11
+
12
+ /** The raw body inside a route's program: exceeding the route's limit is a 413 TooLarge failure, not a defect. */
13
+ export const readBodyBytes = (event: RequestEvent): Effect.Effect<Uint8Array, TooLarge> =>
14
+ Effect.promise(() => readCapped(event.req.body, limitOf(event))).pipe(
15
+ Effect.filterOrFail(Predicate.isNotNullish, () => new TooLarge({ message: 'The request is too large.' })),
16
+ )
17
+
18
+ export const readLimitedBody = async (event: RequestEvent): Promise<Uint8Array> => {
19
+ const bytes = await readCapped(event.req.body, limitOf(event))
20
+ if (!bytes) throw createError({ status: 413, message: 'The request is too large.' })
21
+ return bytes
22
+ }
23
+
24
+ export const readLimitedText = async (event: RequestEvent): Promise<string> => new TextDecoder().decode(await readLimitedBody(event))
25
+
26
+ export const readLimitedJson = async (event: RequestEvent): Promise<unknown> => {
27
+ const text = await readLimitedText(event)
28
+ if (!text) return undefined
29
+ try {
30
+ return JSON.parse(text)
31
+ } catch {
32
+ throw createError({ status: 400, statusText: 'Bad Request', message: 'Invalid JSON body' })
33
+ }
34
+ }
@@ -0,0 +1,10 @@
1
+ import { Context } from 'effect'
2
+
3
+ export interface UserActorShape {
4
+ readonly id: string
5
+ readonly username: string
6
+ readonly emailStatus: 'unverified' | 'verified'
7
+ }
8
+
9
+ /** The authenticated user resolved from a verified D1 session on the current request. */
10
+ export class UserActor extends Context.Service<UserActor, UserActorShape>()('app/http/UserActor') {}
@@ -0,0 +1,5 @@
1
+ export { RateLimitCounter } from './server/cloudflare/exports/rate-limit.do'
2
+
3
+ export default {
4
+ fetch() {},
5
+ }
@@ -0,0 +1,33 @@
1
+ import { Schema } from 'effect'
2
+
3
+ export class NotFound extends Schema.TaggedError<NotFound, { readonly brand: unique symbol }>()('NotFound', {
4
+ resource: Schema.String,
5
+ id: Schema.String,
6
+ }) {}
7
+
8
+ /** `field` names the form field the conflict is about (for example a taken email or username). */
9
+ export class Conflict extends Schema.TaggedError<Conflict, { readonly brand: unique symbol }>()('Conflict', {
10
+ message: Schema.String,
11
+ field: Schema.optionalKey(Schema.String),
12
+ }) {}
13
+
14
+ export class Unprocessable extends Schema.TaggedError<Unprocessable, { readonly brand: unique symbol }>()('Unprocessable', {
15
+ message: Schema.String,
16
+ }) {}
17
+
18
+ export class Unauthorized extends Schema.TaggedError<Unauthorized, { readonly brand: unique symbol }>()('Unauthorized', {
19
+ message: Schema.String,
20
+ }) {}
21
+
22
+ export class Forbidden extends Schema.TaggedError<Forbidden, { readonly brand: unique symbol }>()('Forbidden', {
23
+ message: Schema.String,
24
+ }) {}
25
+
26
+ /** A request body past what its route reads. */
27
+ export class TooLarge extends Schema.TaggedError<TooLarge, { readonly brand: unique symbol }>()('TooLarge', {
28
+ message: Schema.String,
29
+ }) {}
30
+
31
+ export class RateLimited extends Schema.TaggedError<RateLimited, { readonly brand: unique symbol }>()('RateLimited', {
32
+ message: Schema.String,
33
+ }) {}
@@ -0,0 +1,13 @@
1
+ declare module '#auth-utils' {
2
+ interface User {
3
+ username: string
4
+ verified: boolean
5
+ }
6
+
7
+ interface SecureSessionData {
8
+ /** The row in `sessions` this cookie stands for. Verified on every request so revocation takes effect immediately. */
9
+ sessionId: string
10
+ }
11
+ }
12
+
13
+ export {}
@@ -0,0 +1,13 @@
1
+ import { Schema } from 'effect'
2
+
3
+ export const ADMIN_SESSION_HOURS = 12
4
+ export const ADMIN_COOKIE = 'app_admin'
5
+
6
+ export const AdminLoginBody = Schema.Struct({
7
+ email: Schema.Trim.check(Schema.isNonEmpty({ message: 'Enter your email.' })),
8
+ password: Schema.String.check(Schema.isNonEmpty({ message: 'Enter your password.' })),
9
+ })
10
+
11
+ export const AdminMeView = Schema.Struct({
12
+ email: Schema.String,
13
+ })
@@ -0,0 +1,132 @@
1
+ import { Schema } from 'effect'
2
+
3
+ import { EmailField, NonEmptyPasswordField, PasswordField, SecondFactorCodeField, TokenField, TotpSixDigitField, UsernameField } from './schema-validation'
4
+
5
+ export const EMAIL_CHANGE_DAYS = 14
6
+
7
+ export const EmailStatus = Schema.Literals(['unverified', 'verified'])
8
+ export type EmailStatus = typeof EmailStatus.Type
9
+
10
+ export const TotpStatus = Schema.Literals(['off', 'pending', 'enabled'])
11
+ export type TotpStatus = typeof TotpStatus.Type
12
+
13
+ export const RegisterBody = Schema.Struct({
14
+ username: UsernameField,
15
+ email: EmailField,
16
+ password: PasswordField,
17
+ })
18
+
19
+ export const LoginBody = Schema.Struct({
20
+ identity: Schema.Trim.check(Schema.isNonEmpty({ message: 'Enter your email or username.' }), Schema.isMaxLength(254)),
21
+ password: NonEmptyPasswordField,
22
+ code: Schema.optionalKey(SecondFactorCodeField),
23
+ })
24
+
25
+ export const LoginTotpBody = Schema.Struct({
26
+ challenge: Schema.String.check(Schema.isNonEmpty({ message: 'Missing sign-in challenge.' }), Schema.isMaxLength(2048)),
27
+ code: SecondFactorCodeField,
28
+ })
29
+
30
+ export const AuthUserView = Schema.Struct({
31
+ id: Schema.String,
32
+ username: Schema.String,
33
+ email: Schema.String,
34
+ emailStatus: EmailStatus,
35
+ totpStatus: TotpStatus,
36
+ })
37
+ export type AuthUserView = typeof AuthUserView.Type
38
+
39
+ export const LoginResponse = Schema.Union([
40
+ Schema.Struct({
41
+ status: Schema.Literal('authenticated'),
42
+ user: AuthUserView,
43
+ }),
44
+ Schema.Struct({
45
+ status: Schema.Literal('totp_required'),
46
+ challenge: Schema.String,
47
+ }),
48
+ ])
49
+ export type LoginResponse = typeof LoginResponse.Type
50
+
51
+ export const PendingEmailChangeView = Schema.Struct({
52
+ email: Schema.String,
53
+ expiresAt: Schema.String,
54
+ })
55
+
56
+ export const MeView = Schema.Struct({
57
+ id: Schema.String,
58
+ username: Schema.String,
59
+ email: Schema.String,
60
+ emailStatus: EmailStatus,
61
+ hasPassword: Schema.Boolean,
62
+ totpStatus: TotpStatus,
63
+ pendingEmailChange: Schema.NullOr(PendingEmailChangeView),
64
+ emailChangedAt: Schema.NullOr(Schema.String),
65
+ })
66
+ export type MeView = typeof MeView.Type
67
+
68
+ export const UpdateProfileBody = Schema.Struct({
69
+ username: UsernameField,
70
+ })
71
+
72
+ export const DeleteAccountBody = Schema.Struct({
73
+ confirm: Schema.Trim.check(Schema.isNonEmpty({ message: 'Type your username to confirm.' }), Schema.isMaxLength(64)),
74
+ })
75
+
76
+ export const TokenBody = Schema.Struct({
77
+ token: TokenField,
78
+ })
79
+
80
+ export const ResetRequestBody = Schema.Struct({
81
+ email: EmailField,
82
+ })
83
+
84
+ export const ResetConfirmBody = Schema.Struct({
85
+ token: TokenField,
86
+ password: PasswordField,
87
+ })
88
+
89
+ export const EmailChangeRequestBody = Schema.Struct({
90
+ email: EmailField,
91
+ password: NonEmptyPasswordField,
92
+ })
93
+
94
+ export const SessionSummaryView = Schema.Struct({
95
+ device: Schema.String,
96
+ lastSeenAt: Schema.String,
97
+ current: Schema.Boolean,
98
+ })
99
+
100
+ export const SessionsResponse = Schema.Struct({
101
+ sessions: Schema.Array(SessionSummaryView),
102
+ })
103
+
104
+ export const TotpSecurityView = Schema.Struct({
105
+ status: TotpStatus,
106
+ recoveryCodesLeft: Schema.Int,
107
+ })
108
+ export type TotpSecurityView = typeof TotpSecurityView.Type
109
+
110
+ export const TotpStartBody = Schema.Struct({
111
+ password: NonEmptyPasswordField,
112
+ })
113
+
114
+ export const TotpStartResponse = Schema.Struct({
115
+ secret: Schema.String,
116
+ uri: Schema.String,
117
+ })
118
+ export type TotpStartResponse = typeof TotpStartResponse.Type
119
+
120
+ export const TotpConfirmBody = Schema.Struct({
121
+ code: TotpSixDigitField,
122
+ })
123
+
124
+ export const TotpConfirmResponse = Schema.Struct({
125
+ recoveryCodes: Schema.Array(Schema.String),
126
+ })
127
+ export type TotpConfirmResponse = typeof TotpConfirmResponse.Type
128
+
129
+ export const TotpDisableBody = Schema.Struct({
130
+ password: NonEmptyPasswordField,
131
+ code: SecondFactorCodeField,
132
+ })