@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,271 @@
1
+ import type { EventHandler, RequestEvent } from 'nuxt/server'
2
+
3
+ import { getAccessIdentity } from '@humanonlyweb/cf-access'
4
+ import { Cause, Effect, Exit, Schema } from 'effect'
5
+ import { createError, defineHandler, deleteCookie, getCookie, setCookie, setResponseStatus } from 'nuxt/server'
6
+
7
+ import type { AppServices } from '#server/core/app-layer'
8
+ import type { LimitName } from '#server/core/platform/rate-limiter'
9
+ import type { ServiceNotConfigured, UpstreamFailure } from '#server/utils/errors'
10
+ import type { Conflict, NotFound, RateLimited, TooLarge, Unprocessable } from '#shared/domain/errors'
11
+
12
+ import { AdminActor, AdminAuth, isLocalHost } from '#server/app/admin/auth'
13
+ import { AppConfig } from '#server/core/platform/app-config'
14
+ import { RateLimiter } from '#server/core/platform/rate-limiter'
15
+ import { Turnstile } from '#server/core/platform/turnstile'
16
+ import { defineValidatedHandler } from '#server/utils/define-validated-handler'
17
+ import { UserActor } from '#server/utils/user-actor'
18
+ import { Forbidden, Unauthorized } from '#shared/domain/errors'
19
+ import { ADMIN_COOKIE, ADMIN_SESSION_HOURS } from '#shared/utils/admin'
20
+ import { readKey } from '#shared/utils/unknown'
21
+
22
+ import { UNSAFE_METHODS, isSameOriginRequest } from './csrf'
23
+ import { limitKeyOf } from './limit-key'
24
+ import { isWithheld, publicFailure } from './public-failure'
25
+ import { requestUser } from './request-user'
26
+ import { runtime } from './runtime'
27
+
28
+ export type ApiFailure = NotFound | Conflict | Unprocessable | TooLarge | Unauthorized | Forbidden | RateLimited | ServiceNotConfigured | UpstreamFailure
29
+
30
+ const statuses: Record<ApiFailure['_tag'], number> = {
31
+ NotFound: 404,
32
+ Conflict: 409,
33
+ Unprocessable: 422,
34
+ TooLarge: 413,
35
+ Unauthorized: 401,
36
+ Forbidden: 403,
37
+ RateLimited: 429,
38
+ ServiceNotConfigured: 424,
39
+ UpstreamFailure: 502,
40
+ }
41
+
42
+ /** Audience controls whether provider/configuration error details are exposed or redacted. */
43
+ export type Audience = 'public' | 'authed'
44
+
45
+ const isApiFailure = (value: unknown): value is ApiFailure => {
46
+ const tag = readKey(value, '_tag')
47
+ return typeof tag === 'string' && tag in statuses
48
+ }
49
+
50
+ export const toHttpError = (failure: ApiFailure, audience: Audience = 'public') => {
51
+ const shown = audience === 'public' ? publicFailure(failure) : failure
52
+ return createError({
53
+ status: statuses[failure._tag],
54
+ message: failure._tag === 'NotFound' ? `${failure.resource} not found` : (shown as { message: string }).message,
55
+ data: Object.fromEntries(Object.entries(shown)),
56
+ })
57
+ }
58
+
59
+ type AnySchema = Schema.ConstraintCodec<unknown, unknown>
60
+
61
+ export interface RouteSchemas {
62
+ readonly params?: AnySchema
63
+ readonly query?: AnySchema
64
+ readonly body?: AnySchema
65
+ readonly headers?: AnySchema
66
+ readonly response?: AnySchema
67
+ readonly limit?: LimitName
68
+ readonly captcha?: boolean
69
+ }
70
+
71
+ type Part<K extends string, S> = S extends AnySchema ? { readonly [P in K]: S['Type'] } : unknown
72
+
73
+ export type InputOf<D extends RouteSchemas> = Part<'params', D['params']> & Part<'query', D['query']> & Part<'body', D['body']> & Part<'headers', D['headers']>
74
+
75
+ export type OutputOf<D extends RouteSchemas> = D['response'] extends AnySchema ? D['response']['Encoded'] : void
76
+
77
+ /** Params, query, and headers arrive as strings and decode through the string-tree codec; body is JSON. */
78
+ const wire = (schema: AnySchema) => Schema.toStandardSchemaV1(Schema.toCodecStringTree(schema))
79
+
80
+ export const compile = (schemas: RouteSchemas) => ({
81
+ validate: {
82
+ params: schemas.params && wire(schemas.params),
83
+ query: schemas.query && wire(schemas.query),
84
+ body: schemas.body && Schema.toStandardSchemaV1(schemas.body),
85
+ headers: schemas.headers && wire(schemas.headers),
86
+ },
87
+ encode: schemas.response && Schema.encodeUnknownEffect(schemas.response),
88
+ })
89
+
90
+ /** Redacts 64-hex single-use tokens from request paths before logging. */
91
+ export const logPath = (url: string) => new URL(url).pathname.replace(/^(\/(?:verify|reset|email)\/)[0-9a-f]{64}/, '$1[token]')
92
+
93
+ const crossSite = (event: RequestEvent) => UNSAFE_METHODS.has(event.req.method) && !isSameOriginRequest(event.req.headers, new URL(event.req.url).host)
94
+
95
+ const crossSiteError = () => new Forbidden({ message: 'Cross-site requests are not allowed.' })
96
+
97
+ export const callerIp = (event: RequestEvent) => event.req.headers.get('cf-connecting-ip') ?? 'unknown'
98
+
99
+ export const guards = (schemas: RouteSchemas, event: RequestEvent) =>
100
+ Effect.gen(function* () {
101
+ const ip = callerIp(event)
102
+ if (schemas.limit) yield* RateLimiter.use((limiter) => limiter.check(schemas.limit!, limitKeyOf(ip)))
103
+ if (schemas.captcha) yield* Turnstile.use((turnstile) => turnstile.verify(event.req.headers.get('x-turnstile-token') ?? undefined, ip))
104
+ })
105
+
106
+ const runEffect = async <A>(event: RequestEvent, program: Effect.Effect<A, ApiFailure | Schema.SchemaError, AppServices>, audience: Audience): Promise<A> => {
107
+ const exit = await runtime.runPromiseExit(program.pipe(Effect.annotateLogs({ method: event.req.method, path: logPath(event.req.url) })))
108
+
109
+ if (Exit.isSuccess(exit)) return exit.value
110
+
111
+ const failure = Cause.findError(exit.cause)
112
+ if (failure._tag === 'Success' && isApiFailure(failure.success)) {
113
+ if (audience === 'public' && isWithheld(failure.success._tag)) {
114
+ await runtime.runPromise(Effect.logWarning(`${logPath(event.req.url)}: ${failure.success._tag}: ${failure.success.message}`))
115
+ }
116
+ throw toHttpError(failure.success, audience)
117
+ }
118
+
119
+ await runtime.runPromise(Effect.logError(Cause.pretty(exit.cause)))
120
+ throw createError({ status: 500, message: 'Unexpected server error.' })
121
+ }
122
+
123
+ export const respond = async <D extends RouteSchemas>(
124
+ event: RequestEvent,
125
+ program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices>,
126
+ audience: Audience,
127
+ ): Promise<OutputOf<D>> => {
128
+ const value = await runEffect(event, program, audience)
129
+ // Encoded by the route's response schema.
130
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
131
+ return value as OutputOf<D>
132
+ }
133
+
134
+ /** Public route: same-origin check on unsafe methods, rate limit + Turnstile before body parsing, then schema validation and Effect program. */
135
+ export const handlePublic = <const D extends RouteSchemas>(
136
+ schemas: D,
137
+ run: (input: InputOf<D>, event: RequestEvent) => Effect.Effect<OutputOf<D>, ApiFailure, AppServices>,
138
+ ): EventHandler<Promise<OutputOf<D>>> => {
139
+ const { validate, encode } = compile(schemas)
140
+ const validated = defineValidatedHandler({
141
+ validate,
142
+ handler: async (event, input) => {
143
+ // `validate` was compiled from the same schemas.
144
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
145
+ const ran = crossSite(event) ? Effect.fail(crossSiteError()) : run(input as InputOf<D>, event)
146
+ const program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices> = encode ? Effect.flatMap(ran, encode) : ran
147
+ const value = await respond<D>(event, program, 'public')
148
+ if (!schemas.response) setResponseStatus(event, 204)
149
+ return value
150
+ },
151
+ })
152
+ return defineHandler<Promise<OutputOf<D>>>(async (event) => {
153
+ if (crossSite(event)) return respond<D>(event, Effect.fail(crossSiteError()), 'public')
154
+ if (schemas.limit || schemas.captcha) await respond<D>(event, guards(schemas, event), 'public')
155
+ return validated(event)
156
+ })
157
+ }
158
+
159
+ const UNCONFIRMED = 'Confirm your email address first.'
160
+
161
+ export type VerificationPolicy = 'required' | 'allow-unverified'
162
+
163
+ /**
164
+ * Authenticated user route.
165
+ * Explicitly enforces `verification` policy (`'required'` by default when `features.emailVerificationRequired` is enabled).
166
+ */
167
+ export const handleAuthed = <const D extends RouteSchemas>(
168
+ schemas: D,
169
+ run: (input: InputOf<D>, event: RequestEvent) => Effect.Effect<OutputOf<D>, ApiFailure, AppServices | UserActor>,
170
+ options: { readonly verification?: VerificationPolicy } = {},
171
+ ): EventHandler<Promise<OutputOf<D>>> => {
172
+ const verificationPolicy: VerificationPolicy = options.verification ?? 'required'
173
+ const { validate, encode } = compile(schemas)
174
+
175
+ const checkAccess = (event: RequestEvent) =>
176
+ Effect.gen(function* () {
177
+ const user = requestUser(event)
178
+ if (!user) return yield* new Unauthorized({ message: 'Please sign in again.' })
179
+ const config = yield* AppConfig
180
+ if (verificationPolicy === 'required' && config.features.emailVerificationRequired && user.emailStatus !== 'verified') {
181
+ return yield* new Forbidden({ message: UNCONFIRMED })
182
+ }
183
+ return user
184
+ })
185
+
186
+ const validated = defineValidatedHandler({
187
+ validate,
188
+ handler: async (event, input) => {
189
+ const program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices> = Effect.gen(function* () {
190
+ const user = yield* checkAccess(event)
191
+ // `validate` was compiled from the same schemas.
192
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
193
+ const value = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(UserActor, user))
194
+ return encode ? yield* encode(value) : value
195
+ })
196
+ const value = await respond<D>(event, program, 'authed')
197
+ if (!schemas.response) setResponseStatus(event, 204)
198
+ return value
199
+ },
200
+ })
201
+
202
+ return defineHandler<Promise<OutputOf<D>>>(async (event) => {
203
+ if (crossSite(event)) return respond<D>(event, Effect.fail(crossSiteError()), 'public')
204
+ const user = requestUser(event)
205
+ if (!user) return respond<D>(event, Effect.fail(new Unauthorized({ message: 'Please sign in again.' })), 'public')
206
+ await runEffect(event, checkAccess(event), 'authed')
207
+ if (schemas.limit || schemas.captcha) await respond<D>(event, guards(schemas, event), 'authed')
208
+ return validated(event)
209
+ })
210
+ }
211
+
212
+ export type AdminGate = 'access-only' | 'access-and-session'
213
+
214
+ /**
215
+ * Admin route behind Cloudflare Access + admin password session.
216
+ * Use `{ gate: 'access-only' }` strictly for admin sign-in.
217
+ */
218
+ export const handleAdmin = <const D extends RouteSchemas>(
219
+ schemas: D,
220
+ run: (input: InputOf<D>, event: RequestEvent) => Effect.Effect<OutputOf<D>, ApiFailure, AppServices | AdminActor>,
221
+ options: { readonly gate?: AdminGate } = {},
222
+ ): EventHandler<Promise<OutputOf<D>>> => {
223
+ const gate: AdminGate = options.gate ?? 'access-and-session'
224
+ const { validate, encode } = compile(schemas)
225
+ const actors = new WeakMap<RequestEvent, { readonly email: string }>()
226
+
227
+ const validated = defineValidatedHandler({
228
+ validate,
229
+ handler: async (event, input) => {
230
+ const program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices> = Effect.gen(function* () {
231
+ const actor = actors.get(event)
232
+ if (!actor) return yield* new Unauthorized({ message: 'Sign in to the admin.' })
233
+ // `validate` was compiled from the same schemas.
234
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
235
+ const value = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(AdminActor, actor))
236
+ return encode ? yield* encode(value) : value
237
+ })
238
+ const value = await respond<D>(event, program, 'authed')
239
+ if (!schemas.response) setResponseStatus(event, 204)
240
+ return value
241
+ },
242
+ })
243
+
244
+ return defineHandler<Promise<OutputOf<D>>>(async (event) => {
245
+ if (crossSite(event)) return respond<D>(event, Effect.fail(crossSiteError()), 'public')
246
+ const actor = await runEffect(
247
+ event,
248
+ Effect.gen(function* () {
249
+ const auth = yield* AdminAuth
250
+ const accessEmail = yield* auth.gate(getAccessIdentity(event))
251
+ return gate === 'access-only' ? { email: accessEmail } : yield* auth.session(accessEmail, getCookie(event, ADMIN_COOKIE))
252
+ }),
253
+ 'authed',
254
+ )
255
+ actors.set(event, actor)
256
+ if (schemas.limit || schemas.captcha) await respond<D>(event, guards(schemas, event), 'authed')
257
+ return validated(event)
258
+ })
259
+ }
260
+
261
+ export const setAdminCookie = (event: RequestEvent, token: string) =>
262
+ setCookie(event, ADMIN_COOKIE, token, {
263
+ httpOnly: true,
264
+ secure: !isLocalHost(event.req.url),
265
+ sameSite: 'strict',
266
+ path: '/api/admin',
267
+ maxAge: ADMIN_SESSION_HOURS * 3600,
268
+ })
269
+
270
+ export const clearAdminCookie = (event: RequestEvent) => deleteCookie(event, ADMIN_COOKIE, { path: '/api/admin' })
271
+ export const adminCookieOf = (event: RequestEvent) => getCookie(event, ADMIN_COOKIE)
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Rate-limit key for a caller IP.
3
+ * IPv4 addresses key directly; IPv6 callers normalize to their `/64` prefix so rotating addresses within one allocation cannot multiply budgets.
4
+ */
5
+ export const limitKeyOf = (ip: string): string => {
6
+ if (!ip.includes(':')) return ip
7
+ const [head = '', tail] = ip.toLowerCase().split('%')[0]!.split('::')
8
+ const left = head ? head.split(':') : []
9
+ const right = tail ? tail.split(':') : []
10
+ const last = [...left, ...right].at(-1) ?? ''
11
+ if (last.includes('.')) return last
12
+ const groups = tail === undefined ? left : [...left, ...Array<string>(Math.max(0, 8 - left.length - right.length)).fill('0'), ...right]
13
+ return `${groups
14
+ .slice(0, 4)
15
+ .map((group) => (Number.parseInt(group, 16) || 0).toString(16))
16
+ .join(':')}::/64`
17
+ }
@@ -0,0 +1,16 @@
1
+ export const pageCsp = (nonce: string): string =>
2
+ [
3
+ "default-src 'self'",
4
+ `script-src 'self' 'nonce-${nonce}' https://challenges.cloudflare.com`,
5
+ "style-src 'self' 'unsafe-inline'",
6
+ "img-src 'self' data: blob:",
7
+ "font-src 'self' data:",
8
+ "connect-src 'self' https://challenges.cloudflare.com",
9
+ 'frame-src https://challenges.cloudflare.com',
10
+ "frame-ancestors 'none'",
11
+ "base-uri 'self'",
12
+ "form-action 'self'",
13
+ "object-src 'none'",
14
+ ].join('; ')
15
+
16
+ export const withNonce = (html: string, nonce: string): string => html.replace(/<script(?=[\s>])/g, `<script nonce="${nonce}"`)
@@ -0,0 +1,9 @@
1
+ const WITHHELD: Readonly<Record<string, string>> = {
2
+ ServiceNotConfigured: 'This feature is not available right now. Please try again later.',
3
+ UpstreamFailure: 'A service we rely on did not respond. Please try again.',
4
+ }
5
+
6
+ export const isWithheld = (tag: string): boolean => tag in WITHHELD
7
+
8
+ export const publicFailure = <F extends { readonly _tag: string }>(failure: F): F | { readonly _tag: string; readonly message: string } =>
9
+ isWithheld(failure._tag) ? { _tag: failure._tag, message: WITHHELD[failure._tag]! } : failure
@@ -0,0 +1,13 @@
1
+ import type { RequestEvent } from 'nuxt/server'
2
+
3
+ import type { UserActorShape } from '#server/utils/user-actor'
4
+
5
+ const attached = new WeakMap<RequestEvent, { readonly user: UserActorShape; readonly sessionId: string }>()
6
+
7
+ export const setRequestUser = (event: RequestEvent, user: UserActorShape, sessionId: string) => {
8
+ attached.set(event, { user, sessionId })
9
+ }
10
+
11
+ export const requestUser = (event: RequestEvent): UserActorShape | undefined => attached.get(event)?.user
12
+
13
+ export const requestSessionId = (event: RequestEvent): string | undefined => attached.get(event)?.sessionId
@@ -0,0 +1,30 @@
1
+ import type { Effect, Layer } from 'effect'
2
+
3
+ import { ManagedRuntime } from 'effect'
4
+
5
+ import { AppLayer, type AppServices } from '#server/core/app-layer'
6
+
7
+ type Runtime = ManagedRuntime.ManagedRuntime<AppServices, Layer.Error<typeof AppLayer>>
8
+
9
+ let ready: Promise<Runtime> | undefined
10
+
11
+ const build = async (): Promise<Runtime> => {
12
+ const managed = ManagedRuntime.make(AppLayer)
13
+ await managed.context()
14
+ return managed
15
+ }
16
+
17
+ /**
18
+ * Built lazily on the first request (Cloudflare bindings are only available inside a request).
19
+ * Failed builds are cleared so the next request retries instead of caching a cold-start error for the isolate's lifetime.
20
+ */
21
+ const current = () =>
22
+ (ready ??= build().catch((error: unknown) => {
23
+ ready = undefined
24
+ throw error
25
+ }))
26
+
27
+ export const runtime = {
28
+ runPromise: async <A, E>(program: Effect.Effect<A, E, AppServices>) => (await current()).runPromise(program),
29
+ runPromiseExit: async <A, E>(program: Effect.Effect<A, E, AppServices>) => (await current()).runPromiseExit(program),
30
+ }
@@ -0,0 +1,29 @@
1
+ import type { RequestEvent } from 'nuxt/server'
2
+
3
+ import { Effect } from 'effect'
4
+
5
+ import { Sessions } from '#server/app/identity/sessions'
6
+
7
+ import { deviceLabel } from './device-label'
8
+
9
+ export const establishUserSession = (
10
+ event: RequestEvent,
11
+ user: { readonly id: string; readonly username: string; readonly emailStatus: 'unverified' | 'verified' },
12
+ ) =>
13
+ Effect.gen(function* () {
14
+ const sessions = yield* Sessions
15
+ const before = (yield* Effect.promise(() => getUserSession(event))).secure?.sessionId
16
+ if (before) yield* sessions.end(before)
17
+ const sessionId = yield* sessions.start(user.id, deviceLabel(event.req.headers.get('user-agent')))
18
+ yield* Effect.promise(() =>
19
+ replaceUserSession(event, {
20
+ user: { username: user.username, verified: user.emailStatus === 'verified' },
21
+ secure: { sessionId },
22
+ }),
23
+ )
24
+ })
25
+
26
+ export const updateUserSessionMetadata = (event: RequestEvent, user: { readonly username: string; readonly emailStatus: 'unverified' | 'verified' }) =>
27
+ Effect.promise(() => setUserSession(event, { user: { username: user.username, verified: user.emailStatus === 'verified' } }))
28
+
29
+ export const endUserSession = (event: RequestEvent) => Effect.promise(() => clearUserSession(event))
@@ -0,0 +1,55 @@
1
+ import { Context, Layer, Redacted } from 'effect'
2
+ import { useRuntimeConfig } from 'nuxt/server'
3
+
4
+ export interface FeatureFlags {
5
+ readonly totp: boolean
6
+ readonly googleOAuth: boolean
7
+ readonly githubOAuth: boolean
8
+ readonly emailVerificationRequired: boolean
9
+ readonly admin: boolean
10
+ }
11
+
12
+ export interface Settings {
13
+ readonly appName: string
14
+ readonly appUrl: string
15
+ readonly mailFrom: string
16
+ readonly appSecret: Redacted.Redacted
17
+ readonly piiKey: Redacted.Redacted
18
+ readonly piiKeyPrevious: Redacted.Redacted
19
+ readonly piiIndexKey: Redacted.Redacted
20
+ readonly turnstileSecret: Redacted.Redacted
21
+ readonly turnstileRequired: boolean
22
+ readonly rateLimitScale: number
23
+ readonly adminEmails: string
24
+ readonly features: FeatureFlags
25
+ }
26
+
27
+ /**
28
+ * Application settings as an Effect service so code depends on a port and tests inject `testConfig`.
29
+ * All secrets are wrapped in `Redacted` so they cannot leak into logs or serialized errors.
30
+ */
31
+ export class AppConfig extends Context.Service<AppConfig, Settings>()('app/platform/AppConfig') {
32
+ static readonly layer = Layer.sync(AppConfig, () => {
33
+ const config = useRuntimeConfig()
34
+ return AppConfig.of({
35
+ appName: config.appName,
36
+ appUrl: config.appUrl,
37
+ mailFrom: config.mailFrom,
38
+ appSecret: Redacted.make(config.appSecret),
39
+ piiKey: Redacted.make(config.piiKey),
40
+ piiKeyPrevious: Redacted.make(config.piiKeyPrevious),
41
+ piiIndexKey: Redacted.make(config.piiIndexKey),
42
+ turnstileSecret: Redacted.make(config.turnstileSecret),
43
+ turnstileRequired: config.turnstileRequired,
44
+ rateLimitScale: config.rateLimitScale,
45
+ adminEmails: config.adminEmails,
46
+ features: {
47
+ totp: config.public.features.totp,
48
+ googleOAuth: config.public.features.googleOAuth,
49
+ githubOAuth: config.public.features.githubOAuth,
50
+ emailVerificationRequired: config.public.features.emailVerificationRequired,
51
+ admin: config.public.features.admin,
52
+ },
53
+ })
54
+ })
55
+ }
@@ -0,0 +1,4 @@
1
+ import { DateTime, Effect } from 'effect'
2
+
3
+ export const nowIso = DateTime.now.pipe(Effect.map(DateTime.formatIso))
4
+ export const nowMillis = DateTime.now.pipe(Effect.map(DateTime.toEpochMillis))
@@ -0,0 +1,78 @@
1
+ import type { Database as Db0 } from 'db0'
2
+
3
+ import { Context, Effect, Layer, Schedule, Schema } from 'effect'
4
+ import { useDatabase } from 'nitro/database'
5
+
6
+ export class DatabaseError extends Schema.TaggedError<DatabaseError, { readonly brand: unique symbol }>()('DatabaseError', {
7
+ message: Schema.String,
8
+ sql: Schema.String,
9
+ }) {}
10
+
11
+ type Param = string | number | boolean | null | undefined
12
+
13
+ /**
14
+ * D1 transient failures: dropped connection or isolate/DO reset during deploy.
15
+ * Only pure read queries retry — never writes, which could have committed before the error returned.
16
+ */
17
+ const TRANSIENT = /network connection lost|object to be reset|reset because its code was updated|transient issue/i
18
+ export const isTransient = (error: DatabaseError) => TRANSIENT.test(error.message)
19
+
20
+ /** `all` and `first` can run `INSERT/UPDATE/DELETE ... RETURNING`; only pure reads may retry. */
21
+ export const isReadQuery = (sql: string) => /^\s*SELECT\b/i.test(sql) || (/^\s*WITH\b/i.test(sql) && !/\b(INSERT|UPDATE|DELETE|REPLACE)\b/i.test(sql))
22
+
23
+ const READ_RETRY = Schedule.exponential('50 millis').pipe(Schedule.jittered)
24
+
25
+ export class Database extends Context.Service<
26
+ Database,
27
+ {
28
+ readonly all: <A, I>(schema: Schema.Codec<A, I>, sql: string, params?: ReadonlyArray<Param>) => Effect.Effect<ReadonlyArray<A>, DatabaseError>
29
+ readonly first: <A, I>(schema: Schema.Codec<A, I>, sql: string, params?: ReadonlyArray<Param>) => Effect.Effect<A | undefined, DatabaseError>
30
+ readonly run: (sql: string, params?: ReadonlyArray<Param>) => Effect.Effect<void, DatabaseError>
31
+ }
32
+ >()('app/platform/Database') {
33
+ static readonly layer = Layer.sync(Database, () => Database.over(useDatabase()))
34
+
35
+ static readonly layerFor = (db: Db0) => Layer.succeed(Database, Database.over(db))
36
+
37
+ private static over(db: Db0) {
38
+ const failure = (sql: string) => (cause: unknown) => new DatabaseError({ sql, message: cause instanceof Error ? cause.message : String(cause) })
39
+
40
+ const rows = (sql: string, params: ReadonlyArray<Param>) => {
41
+ const query = Effect.tryPromise({
42
+ try: () =>
43
+ db
44
+ .prepare(sql)
45
+ .bind(...params)
46
+ .all(),
47
+ catch: failure(sql),
48
+ })
49
+ return isReadQuery(sql) ? query.pipe(Effect.retry({ schedule: READ_RETRY, times: 2, while: isTransient })) : query
50
+ }
51
+
52
+ const decode =
53
+ <A, I>(schema: Schema.Codec<A, I>, sql: string) =>
54
+ (input: unknown) =>
55
+ Schema.decodeUnknownEffect(schema)(input).pipe(Effect.mapError(failure(sql)))
56
+
57
+ const all = <A, I>(schema: Schema.Codec<A, I>, sql: string, params: ReadonlyArray<Param> = []) =>
58
+ rows(sql, params).pipe(
59
+ Effect.flatMap((found) => Effect.forEach(found, decode(schema, sql))),
60
+ Effect.withSpan('Database.all'),
61
+ )
62
+
63
+ const first = <A, I>(schema: Schema.Codec<A, I>, sql: string, params: ReadonlyArray<Param> = []) =>
64
+ all(schema, sql, params).pipe(Effect.map((found) => found[0]))
65
+
66
+ const run = (sql: string, params: ReadonlyArray<Param> = []) =>
67
+ Effect.tryPromise({
68
+ try: () =>
69
+ db
70
+ .prepare(sql)
71
+ .bind(...params)
72
+ .run(),
73
+ catch: failure(sql),
74
+ }).pipe(Effect.asVoid, Effect.withSpan('Database.run'))
75
+
76
+ return Database.of({ all, first, run })
77
+ }
78
+ }
@@ -0,0 +1,32 @@
1
+ import { Context, Effect, Layer } from 'effect'
2
+ import { useKV } from 'nitro/kv'
3
+
4
+ // In `nuxt dev` (workerd), Nitro's dev server-asset mount sees no Node filesystem files; Vite serves them via glob instead.
5
+ // Production builds drop this branch and read the bundled Nitro server assets from `assets:server`.
6
+ const devFiles = import.meta.dev ? import.meta.glob<string>('../../assets/email/**/*.html', { query: '?raw', import: 'default' }) : undefined
7
+
8
+ export class EmailAssets extends Context.Service<EmailAssets, { readonly read: (name: string) => Effect.Effect<string> }>()('app/platform/EmailAssets') {
9
+ static readonly layer = Layer.sync(EmailAssets, () =>
10
+ EmailAssets.from(async (name) => {
11
+ if (devFiles) return devFiles[`../../assets/email/${name}`]?.()
12
+ const value = await useKV('assets:server').getItem(`email:${name.replaceAll('/', ':')}`)
13
+ return typeof value === 'string' ? value : value instanceof Uint8Array ? new TextDecoder().decode(value) : undefined
14
+ }),
15
+ )
16
+
17
+ static from(load: (name: string) => Promise<string | undefined>) {
18
+ const kept = new Map<string, string>()
19
+ return EmailAssets.of({
20
+ read: (name) =>
21
+ Effect.gen(function* () {
22
+ const known = kept.get(name)
23
+ if (known !== undefined) return known
24
+ const text = yield* Effect.promise(() => load(name))
25
+ // A missing template is a build defect, never a recoverable runtime error.
26
+ if (text === undefined) return yield* Effect.die(new Error(`Email template ${name} is missing from server assets.`))
27
+ kept.set(name, text)
28
+ return text
29
+ }),
30
+ })
31
+ }
32
+ }
@@ -0,0 +1,29 @@
1
+ import { Context, Effect, Layer } from 'effect'
2
+ import { SecureRandom } from 'effect/crypto'
3
+
4
+ import { kinds, type Id, type IdKind } from '#shared/utils/ids'
5
+
6
+ export class IdGenerator extends Context.Service<IdGenerator, { readonly next: <K extends IdKind>(kind: K) => Effect.Effect<Id<K>> }>()(
7
+ 'app/platform/IdGenerator',
8
+ ) {
9
+ static readonly layer = Layer.effect(
10
+ IdGenerator,
11
+ Effect.gen(function* () {
12
+ const random = yield* SecureRandom.SecureRandom
13
+ return IdGenerator.of({
14
+ next: <K extends IdKind>(kind: K) => Effect.map(random.uuidV7(), (uuid): Id<K> => kinds[kind].schema.make(`${kinds[kind].prefix}_${uuid}`)),
15
+ })
16
+ }),
17
+ ).pipe(Layer.provide(SecureRandom.layerWebCrypto))
18
+
19
+ static readonly sequential = (start = 1) => {
20
+ let counter = start
21
+ return Layer.succeed(
22
+ IdGenerator,
23
+ IdGenerator.of({
24
+ next: <K extends IdKind>(kind: K) =>
25
+ Effect.sync((): Id<K> => kinds[kind].schema.make(`${kinds[kind].prefix}_00000000-0000-7000-8000-${String(counter++).padStart(12, '0')}`)),
26
+ }),
27
+ )
28
+ }
29
+ }
@@ -0,0 +1,54 @@
1
+ import type { Storage, StorageValue } from 'unstorage'
2
+
3
+ import { Context, Effect, Layer } from 'effect'
4
+ import { useKV } from 'nitro/kv'
5
+ import { createStorage } from 'unstorage'
6
+
7
+ /**
8
+ * Key-value cache through Nitro's `useKV()` (Cloudflare KV in production, in-memory in tests).
9
+ * Treats KV strictly as a cache: failures are logged and treated as cache misses.
10
+ */
11
+ export class Kv extends Context.Service<
12
+ Kv,
13
+ {
14
+ readonly get: (key: string) => Effect.Effect<unknown>
15
+ readonly set: (key: string, value: StorageValue, ttlSeconds: number) => Effect.Effect<void>
16
+ readonly getBytes: (key: string) => Effect.Effect<Uint8Array<ArrayBuffer> | undefined>
17
+ readonly setBytes: (key: string, value: Uint8Array, ttlSeconds: number) => Effect.Effect<void>
18
+ readonly remove: (key: string) => Effect.Effect<void>
19
+ }
20
+ >()('app/platform/Kv') {
21
+ static readonly layer = Layer.sync(Kv, () => Kv.over(() => useKV('cache')))
22
+
23
+ static readonly memory = () =>
24
+ Layer.succeed(
25
+ Kv,
26
+ Kv.over(
27
+ (
28
+ (storage) => () =>
29
+ storage
30
+ )(createStorage()),
31
+ ),
32
+ )
33
+
34
+ private static over(storage: () => Storage) {
35
+ const quietly = <A>(what: string, work: () => Promise<A>, otherwise: A) =>
36
+ Effect.tryPromise({ try: work, catch: String }).pipe(Effect.catch((cause) => Effect.logWarning(`KV ${what} failed: ${cause}`).pipe(Effect.as(otherwise))))
37
+
38
+ return Kv.of({
39
+ get: (key) => quietly('read', async (): Promise<unknown> => (await storage().getItem(key)) ?? undefined, undefined),
40
+ set: (key, value, ttlSeconds) => quietly('write', () => storage().setItem(key, value, { ttl: ttlSeconds }), undefined),
41
+ getBytes: (key) =>
42
+ quietly(
43
+ 'read',
44
+ async () => {
45
+ const raw: unknown = await storage().getItemRaw(key)
46
+ return raw instanceof ArrayBuffer || raw instanceof Uint8Array ? new Uint8Array(raw) : undefined
47
+ },
48
+ undefined,
49
+ ),
50
+ setBytes: (key, value, ttlSeconds) => quietly('write', () => storage().setItemRaw(key, value, { ttl: ttlSeconds }), undefined),
51
+ remove: (key) => quietly('delete', () => storage().removeItem(key), undefined),
52
+ })
53
+ }
54
+ }