@humanonlyweb/create-nuxtflare 0.1.0 → 0.1.2

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 (52) hide show
  1. package/dist/cli.js +20 -2
  2. package/dist/template/app/pages/login.vue +1 -1
  3. package/dist/template/server/api/account/email/index.delete.ts +1 -1
  4. package/dist/template/server/api/account/email/index.post.ts +1 -1
  5. package/dist/template/server/api/account/index.delete.ts +1 -2
  6. package/dist/template/server/api/account/index.patch.ts +1 -2
  7. package/dist/template/server/api/account/sessions.get.ts +1 -2
  8. package/dist/template/server/api/account/totp/cancel.post.ts +1 -1
  9. package/dist/template/server/api/account/totp/confirm.post.ts +1 -1
  10. package/dist/template/server/api/account/totp/disable.post.ts +1 -1
  11. package/dist/template/server/api/account/totp/index.get.ts +1 -1
  12. package/dist/template/server/api/account/totp/start.post.ts +1 -1
  13. package/dist/template/server/api/auth/email/index.post.ts +1 -1
  14. package/dist/template/server/api/auth/login/totp.post.ts +1 -1
  15. package/dist/template/server/api/auth/login.post.ts +1 -1
  16. package/dist/template/server/api/auth/logout-everywhere.post.ts +1 -2
  17. package/dist/template/server/api/auth/logout.post.ts +1 -2
  18. package/dist/template/server/api/auth/register.post.ts +1 -1
  19. package/dist/template/server/api/auth/verify/index.post.ts +1 -2
  20. package/dist/template/server/api/auth/verify/send.post.ts +1 -1
  21. package/dist/template/server/api/me.get.ts +1 -1
  22. package/dist/template/server/app/notifications/render.test.ts +1 -1
  23. package/dist/template/server/app/notifications/render.ts +12 -1
  24. package/dist/template/server/app/notifications/templates.ts +9 -1
  25. package/dist/template/server/core/http/body.ts +67 -0
  26. package/dist/template/server/core/http/handle.ts +2 -5
  27. package/dist/template/server/core/http/security.ts +58 -0
  28. package/dist/template/server/core/http/session.ts +73 -0
  29. package/dist/template/server/core/platform/database.ts +12 -0
  30. package/dist/template/server/middleware/00-body-limit.ts +1 -1
  31. package/dist/template/server/middleware/01-user-session.ts +1 -1
  32. package/dist/template/server/plugins/page-csp.ts +1 -1
  33. package/dist/template/server/routes/(dev)/emails.get.dev.ts +1 -1
  34. package/dist/template/server/routes/auth/github.get.ts +2 -2
  35. package/dist/template/server/routes/auth/google.get.ts +2 -2
  36. package/dist/template/server/utils/define-validated-handler.ts +1 -1
  37. package/dist/template/shared/utils/auth.ts +3 -0
  38. package/package.json +20 -2
  39. package/dist/template/server/app/notifications/email.ts +0 -12
  40. package/dist/template/server/app/notifications/samples.ts +0 -11
  41. package/dist/template/server/core/db/chunked.ts +0 -13
  42. package/dist/template/server/core/http/body-limit.ts +0 -35
  43. package/dist/template/server/core/http/csrf.ts +0 -16
  44. package/dist/template/server/core/http/device-label.ts +0 -27
  45. package/dist/template/server/core/http/limit-key.ts +0 -17
  46. package/dist/template/server/core/http/page-csp.ts +0 -16
  47. package/dist/template/server/core/http/public-failure.ts +0 -9
  48. package/dist/template/server/core/http/request-user.ts +0 -13
  49. package/dist/template/server/core/http/session-cookie.ts +0 -29
  50. package/dist/template/server/utils/read-body.ts +0 -34
  51. package/dist/template/server/utils/user-actor.ts +0 -10
  52. package/dist/template/shared/utils/local-path.ts +0 -2
package/dist/cli.js CHANGED
@@ -6,9 +6,27 @@ import { basename as basename2, resolve as resolve2 } from "node:path";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@humanonlyweb/create-nuxtflare",
9
- version: "0.1.0",
9
+ version: "0.1.2",
10
10
  description: "Scaffold a Nuxt 5 + Cloudflare Workers + D1 + Effect v4 app with explicit auth, TOTP 2FA, and admin.",
11
11
  license: "MIT",
12
+ repository: {
13
+ type: "git",
14
+ url: "git+https://github.com/humanonlyweb/nuxtflare.git"
15
+ },
16
+ homepage: "https://github.com/humanonlyweb/nuxtflare#readme",
17
+ bugs: {
18
+ url: "https://github.com/humanonlyweb/nuxtflare/issues"
19
+ },
20
+ keywords: [
21
+ "nuxt",
22
+ "nuxt5",
23
+ "cloudflare",
24
+ "cloudflare-workers",
25
+ "d1",
26
+ "effect",
27
+ "starter",
28
+ "create"
29
+ ],
12
30
  type: "module",
13
31
  publishConfig: {
14
32
  access: "public"
@@ -30,7 +48,7 @@ var package_default = {
30
48
  },
31
49
  engines: {
32
50
  bun: ">=1.4.0",
33
- node: ">=22.0.0"
51
+ node: ">=24.0.0"
34
52
  },
35
53
  packageManager: "bun@1.4.5"
36
54
  };
@@ -1,5 +1,5 @@
1
1
  <script setup lang="ts">
2
- import { isLocalPath } from '#shared/utils/local-path'
2
+ import { isLocalPath } from '#shared/utils/auth'
3
3
  import { problemOf } from '~/utils/api-error'
4
4
 
5
5
  definePageMeta({ middleware: 'guest' })
@@ -1,5 +1,5 @@
1
1
  import { EmailChange } from '#server/app/identity/email-change'
2
2
  import { handleAuthed } from '#server/core/http/handle'
3
- import { UserActor } from '#server/utils/user-actor'
3
+ import { UserActor } from '#server/core/http/session'
4
4
 
5
5
  export default handleAuthed({}, () => UserActor.use((actor) => EmailChange.use((change) => change.cancel(actor.id))))
@@ -1,6 +1,6 @@
1
1
  import { EmailChange } from '#server/app/identity/email-change'
2
2
  import { handleAuthed } from '#server/core/http/handle'
3
- import { UserActor } from '#server/utils/user-actor'
3
+ import { UserActor } from '#server/core/http/session'
4
4
  import { EmailChangeRequestBody } from '#shared/utils/auth'
5
5
 
6
6
  export default handleAuthed({ body: EmailChangeRequestBody, limit: 'email-change' }, ({ body }) =>
@@ -2,8 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { Identity } from '#server/app/identity/service'
4
4
  import { handleAuthed } from '#server/core/http/handle'
5
- import { endUserSession } from '#server/core/http/session-cookie'
6
- import { UserActor } from '#server/utils/user-actor'
5
+ import { UserActor, endUserSession } from '#server/core/http/session'
7
6
  import { DeleteAccountBody } from '#shared/utils/auth'
8
7
 
9
8
  export default handleAuthed(
@@ -2,8 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { Identity } from '#server/app/identity/service'
4
4
  import { handleAuthed } from '#server/core/http/handle'
5
- import { updateUserSessionMetadata } from '#server/core/http/session-cookie'
6
- import { UserActor } from '#server/utils/user-actor'
5
+ import { UserActor, updateUserSessionMetadata } from '#server/core/http/session'
7
6
  import { AuthUserView, UpdateProfileBody } from '#shared/utils/auth'
8
7
 
9
8
  export default handleAuthed({ body: UpdateProfileBody, response: AuthUserView }, ({ body }, event) =>
@@ -2,8 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { Sessions } from '#server/app/identity/sessions'
4
4
  import { handleAuthed } from '#server/core/http/handle'
5
- import { requestSessionId } from '#server/core/http/request-user'
6
- import { UserActor } from '#server/utils/user-actor'
5
+ import { UserActor, requestSessionId } from '#server/core/http/session'
7
6
  import { SessionsResponse } from '#shared/utils/auth'
8
7
 
9
8
  export default handleAuthed({ response: SessionsResponse }, (_input, event) =>
@@ -1,5 +1,5 @@
1
1
  import { Totp } from '#server/app/identity/totp'
2
2
  import { handleAuthed } from '#server/core/http/handle'
3
- import { UserActor } from '#server/utils/user-actor'
3
+ import { UserActor } from '#server/core/http/session'
4
4
 
5
5
  export default handleAuthed({}, () => UserActor.use((actor) => Totp.use((totp) => totp.cancelSetup(actor.id))))
@@ -2,7 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { Totp } from '#server/app/identity/totp'
4
4
  import { handleAuthed } from '#server/core/http/handle'
5
- import { UserActor } from '#server/utils/user-actor'
5
+ import { UserActor } from '#server/core/http/session'
6
6
  import { TotpConfirmBody, TotpConfirmResponse } from '#shared/utils/auth'
7
7
 
8
8
  export default handleAuthed({ body: TotpConfirmBody, response: TotpConfirmResponse, limit: 'totp' }, ({ body }) =>
@@ -1,6 +1,6 @@
1
1
  import { Totp } from '#server/app/identity/totp'
2
2
  import { handleAuthed } from '#server/core/http/handle'
3
- import { UserActor } from '#server/utils/user-actor'
3
+ import { UserActor } from '#server/core/http/session'
4
4
  import { TotpDisableBody } from '#shared/utils/auth'
5
5
 
6
6
  export default handleAuthed({ body: TotpDisableBody, limit: 'totp' }, ({ body }) =>
@@ -1,6 +1,6 @@
1
1
  import { Totp } from '#server/app/identity/totp'
2
2
  import { handleAuthed } from '#server/core/http/handle'
3
- import { UserActor } from '#server/utils/user-actor'
3
+ import { UserActor } from '#server/core/http/session'
4
4
  import { TotpSecurityView } from '#shared/utils/auth'
5
5
 
6
6
  export default handleAuthed({ response: TotpSecurityView }, () => UserActor.use((actor) => Totp.use((totp) => totp.security(actor.id))))
@@ -1,6 +1,6 @@
1
1
  import { Totp } from '#server/app/identity/totp'
2
2
  import { handleAuthed } from '#server/core/http/handle'
3
- import { UserActor } from '#server/utils/user-actor'
3
+ import { UserActor } from '#server/core/http/session'
4
4
  import { TotpStartBody, TotpStartResponse } from '#shared/utils/auth'
5
5
 
6
6
  export default handleAuthed({ body: TotpStartBody, response: TotpStartResponse, limit: 'totp' }, ({ body }) =>
@@ -2,7 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { EmailChange } from '#server/app/identity/email-change'
4
4
  import { handlePublic } from '#server/core/http/handle'
5
- import { endUserSession } from '#server/core/http/session-cookie'
5
+ import { endUserSession } from '#server/core/http/session'
6
6
  import { TokenBody } from '#shared/utils/auth'
7
7
 
8
8
  export default handlePublic({ body: TokenBody }, ({ body }, event) =>
@@ -2,7 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { Totp } from '#server/app/identity/totp'
4
4
  import { handlePublic } from '#server/core/http/handle'
5
- import { establishUserSession } from '#server/core/http/session-cookie'
5
+ import { establishUserSession } from '#server/core/http/session'
6
6
  import { AuthUserView, LoginTotpBody } from '#shared/utils/auth'
7
7
 
8
8
  export default handlePublic({ body: LoginTotpBody, response: AuthUserView, limit: 'totp' }, ({ body }, event) =>
@@ -2,7 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { Identity } from '#server/app/identity/service'
4
4
  import { handlePublic } from '#server/core/http/handle'
5
- import { establishUserSession } from '#server/core/http/session-cookie'
5
+ import { establishUserSession } from '#server/core/http/session'
6
6
  import { LoginBody, LoginResponse } from '#shared/utils/auth'
7
7
 
8
8
  export default handlePublic({ body: LoginBody, response: LoginResponse, limit: 'sign-in' }, ({ body }, event) =>
@@ -2,8 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { Sessions } from '#server/app/identity/sessions'
4
4
  import { handleAuthed } from '#server/core/http/handle'
5
- import { endUserSession } from '#server/core/http/session-cookie'
6
- import { UserActor } from '#server/utils/user-actor'
5
+ import { UserActor, endUserSession } from '#server/core/http/session'
7
6
 
8
7
  export default handleAuthed(
9
8
  {},
@@ -2,8 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { Sessions } from '#server/app/identity/sessions'
4
4
  import { handlePublic } from '#server/core/http/handle'
5
- import { requestSessionId } from '#server/core/http/request-user'
6
- import { endUserSession } from '#server/core/http/session-cookie'
5
+ import { endUserSession, requestSessionId } from '#server/core/http/session'
7
6
 
8
7
  export default handlePublic({}, (_input, event) =>
9
8
  Effect.gen(function* () {
@@ -3,7 +3,7 @@ import { Effect } from 'effect'
3
3
  import { Identity } from '#server/app/identity/service'
4
4
  import { EmailVerification } from '#server/app/identity/verification'
5
5
  import { handlePublic } from '#server/core/http/handle'
6
- import { establishUserSession } from '#server/core/http/session-cookie'
6
+ import { establishUserSession } from '#server/core/http/session'
7
7
  import { AuthUserView, RegisterBody } from '#shared/utils/auth'
8
8
 
9
9
  export default handlePublic({ body: RegisterBody, response: AuthUserView, limit: 'register', captcha: true }, ({ body }, event) =>
@@ -2,8 +2,7 @@ import { Effect } from 'effect'
2
2
 
3
3
  import { EmailVerification } from '#server/app/identity/verification'
4
4
  import { handlePublic } from '#server/core/http/handle'
5
- import { requestUser } from '#server/core/http/request-user'
6
- import { updateUserSessionMetadata } from '#server/core/http/session-cookie'
5
+ import { requestUser, updateUserSessionMetadata } from '#server/core/http/session'
7
6
  import { TokenBody } from '#shared/utils/auth'
8
7
 
9
8
  export default handlePublic({ body: TokenBody }, ({ body }, event) =>
@@ -1,6 +1,6 @@
1
1
  import { EmailVerification } from '#server/app/identity/verification'
2
2
  import { handleAuthed } from '#server/core/http/handle'
3
- import { UserActor } from '#server/utils/user-actor'
3
+ import { UserActor } from '#server/core/http/session'
4
4
 
5
5
  export default handleAuthed({}, () => UserActor.use((actor) => EmailVerification.use((verification) => verification.send(actor.id))), {
6
6
  verification: 'allow-unverified',
@@ -1,6 +1,6 @@
1
1
  import { Identity } from '#server/app/identity/service'
2
2
  import { handleAuthed } from '#server/core/http/handle'
3
- import { UserActor } from '#server/utils/user-actor'
3
+ import { UserActor } from '#server/core/http/session'
4
4
  import { MeView } from '#shared/utils/auth'
5
5
 
6
6
  export default handleAuthed({ response: MeView }, () => UserActor.use((actor) => Identity.use((identity) => identity.me(actor.id))), {
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
3
3
  import { makeTestLayer } from '#server/test/kit'
4
4
 
5
5
  import { EmailRenderer, fill } from './render'
6
- import { sampleEmails } from './samples'
6
+ import { sampleEmails } from './templates'
7
7
 
8
8
  describe('email rendering', () => {
9
9
  it('escapes {{vars}}, preserves {{{raw}}}, and throws on missing keys', () => {
@@ -6,7 +6,18 @@ import { AppConfig } from '#server/core/platform/app-config'
6
6
  import { EmailAssets } from '#server/core/platform/email-assets'
7
7
  import { readKey } from '#shared/utils/unknown'
8
8
 
9
- import type { Block, Email } from './email'
9
+ export type Block =
10
+ | { readonly kind: 'text'; readonly text: string }
11
+ | { readonly kind: 'button'; readonly label: string; readonly url: string }
12
+ | { readonly kind: 'note'; readonly text: string }
13
+
14
+ export interface Email {
15
+ readonly subject: string
16
+ readonly preheader: string
17
+ readonly headline: string
18
+ readonly blocks: ReadonlyArray<Block>
19
+ readonly footer: string
20
+ }
10
21
 
11
22
  export type Rendered = Pick<Mail, 'subject' | 'text' | 'html'>
12
23
 
@@ -1,4 +1,4 @@
1
- import type { Email } from './email'
1
+ import type { Email } from './render'
2
2
 
3
3
  export const verificationEmail = (url: string, appName: string): Email => ({
4
4
  subject: `Confirm your email for ${appName}`,
@@ -35,3 +35,11 @@ export const emailChangeEmail = (url: string, appName: string): Email => ({
35
35
  ],
36
36
  footer: `Sent by ${appName}.`,
37
37
  })
38
+
39
+ const SAMPLE_TOKEN = '0'.repeat(64)
40
+
41
+ export const sampleEmails = (appUrl: string, appName: string): Readonly<Record<string, Email>> => ({
42
+ verification: verificationEmail(`${appUrl}/verify/${SAMPLE_TOKEN}`, appName),
43
+ passwordReset: passwordResetEmail(`${appUrl}/reset/${SAMPLE_TOKEN}`, appName),
44
+ emailChange: emailChangeEmail(`${appUrl}/email/${SAMPLE_TOKEN}`, appName),
45
+ })
@@ -0,0 +1,67 @@
1
+ import type { RequestEvent } from 'nuxt/server'
2
+
3
+ import { Effect, Predicate } from 'effect'
4
+ import { createError, getRequestURL } from 'nuxt/server'
5
+
6
+ import { TooLarge } from '#shared/domain/errors'
7
+
8
+ const JSON_LIMIT = 1024 * 1024
9
+
10
+ /** Maximum body size in bytes for API writes, or undefined when the route reads no body. */
11
+ export const bodyLimitFor = (method: string, path: string): number | undefined => {
12
+ if (!['POST', 'PUT', 'PATCH'].includes(method) || !path.startsWith('/api/')) return undefined
13
+ return JSON_LIMIT
14
+ }
15
+
16
+ /** Reads bytes up to `limit`, returning undefined if the stream exceeds `limit` (handles chunked bodies without Content-Length). */
17
+ export const readCapped = async (body: ReadableStream<Uint8Array> | null, limit: number): Promise<Uint8Array | undefined> => {
18
+ if (!body) return new Uint8Array()
19
+ const reader = body.getReader()
20
+ const chunks: Uint8Array[] = []
21
+ let size = 0
22
+ for (;;) {
23
+ // Stream chunks are consumed sequentially.
24
+ // oxlint-disable-next-line eslint/no-await-in-loop
25
+ const { done, value } = await reader.read()
26
+ if (done) break
27
+ size += value.byteLength
28
+ if (size > limit) {
29
+ // oxlint-disable-next-line eslint/no-await-in-loop
30
+ await reader.cancel()
31
+ return undefined
32
+ }
33
+ chunks.push(value)
34
+ }
35
+ const bytes = new Uint8Array(size)
36
+ let offset = 0
37
+ for (const chunk of chunks) {
38
+ bytes.set(chunk, offset)
39
+ offset += chunk.byteLength
40
+ }
41
+ return bytes
42
+ }
43
+
44
+ const limitOf = (event: RequestEvent) => bodyLimitFor(event.req.method, getRequestURL(event).pathname) ?? JSON_LIMIT
45
+
46
+ export const readBodyBytes = (event: RequestEvent): Effect.Effect<Uint8Array, TooLarge> =>
47
+ Effect.promise(() => readCapped(event.req.body, limitOf(event))).pipe(
48
+ Effect.filterOrFail(Predicate.isNotNullish, () => new TooLarge({ message: 'The request is too large.' })),
49
+ )
50
+
51
+ export const readLimitedBody = async (event: RequestEvent): Promise<Uint8Array> => {
52
+ const bytes = await readCapped(event.req.body, limitOf(event))
53
+ if (!bytes) throw createError({ status: 413, message: 'The request is too large.' })
54
+ return bytes
55
+ }
56
+
57
+ export const readLimitedText = async (event: RequestEvent): Promise<string> => new TextDecoder().decode(await readLimitedBody(event))
58
+
59
+ export const readLimitedJson = async (event: RequestEvent): Promise<unknown> => {
60
+ const text = await readLimitedText(event)
61
+ if (!text) return undefined
62
+ try {
63
+ return JSON.parse(text)
64
+ } catch {
65
+ throw createError({ status: 400, statusText: 'Bad Request', message: 'Invalid JSON body' })
66
+ }
67
+ }
@@ -14,16 +14,13 @@ import { AppConfig } from '#server/core/platform/app-config'
14
14
  import { RateLimiter } from '#server/core/platform/rate-limiter'
15
15
  import { Turnstile } from '#server/core/platform/turnstile'
16
16
  import { defineValidatedHandler } from '#server/utils/define-validated-handler'
17
- import { UserActor } from '#server/utils/user-actor'
18
17
  import { Forbidden, Unauthorized } from '#shared/domain/errors'
19
18
  import { ADMIN_COOKIE, ADMIN_SESSION_HOURS } from '#shared/utils/admin'
20
19
  import { readKey } from '#shared/utils/unknown'
21
20
 
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
21
  import { runtime } from './runtime'
22
+ import { UNSAFE_METHODS, isSameOriginRequest, isWithheld, limitKeyOf, publicFailure } from './security'
23
+ import { UserActor, requestUser } from './session'
27
24
 
28
25
  export type ApiFailure = NotFound | Conflict | Unprocessable | TooLarge | Unauthorized | Forbidden | RateLimited | ServiceNotConfigured | UpstreamFailure
29
26
 
@@ -0,0 +1,58 @@
1
+ /** Cookie-backed writes are forgeable cross-site; browsers send Sec-Fetch-Site or Origin, while non-browser clients pass. */
2
+ export const isSameOriginRequest = (headers: { get: (name: string) => string | null }, expectedHost: string): boolean => {
3
+ const site = headers.get('sec-fetch-site')
4
+ if (site) return site === 'same-origin' || site === 'none'
5
+ const origin = headers.get('origin')
6
+ if (origin) {
7
+ try {
8
+ return new URL(origin).host === expectedHost
9
+ } catch {
10
+ return false
11
+ }
12
+ }
13
+ return true
14
+ }
15
+
16
+ export const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
17
+
18
+ /** Normalizes IPv6 callers to their `/64` prefix so rotating addresses within one allocation cannot multiply rate-limit budgets. */
19
+ export const limitKeyOf = (ip: string): string => {
20
+ if (!ip.includes(':')) return ip
21
+ const [head = '', tail] = ip.toLowerCase().split('%')[0]!.split('::')
22
+ const left = head ? head.split(':') : []
23
+ const right = tail ? tail.split(':') : []
24
+ const last = [...left, ...right].at(-1) ?? ''
25
+ if (last.includes('.')) return last
26
+ const groups = tail === undefined ? left : [...left, ...Array<string>(Math.max(0, 8 - left.length - right.length)).fill('0'), ...right]
27
+ return `${groups
28
+ .slice(0, 4)
29
+ .map((group) => (Number.parseInt(group, 16) || 0).toString(16))
30
+ .join(':')}::/64`
31
+ }
32
+
33
+ const WITHHELD: Readonly<Record<string, string>> = {
34
+ ServiceNotConfigured: 'This feature is not available right now. Please try again later.',
35
+ UpstreamFailure: 'A service we rely on did not respond. Please try again.',
36
+ }
37
+
38
+ export const isWithheld = (tag: string): boolean => tag in WITHHELD
39
+
40
+ export const publicFailure = <F extends { readonly _tag: string }>(failure: F): F | { readonly _tag: string; readonly message: string } =>
41
+ isWithheld(failure._tag) ? { _tag: failure._tag, message: WITHHELD[failure._tag]! } : failure
42
+
43
+ export const pageCsp = (nonce: string): string =>
44
+ [
45
+ "default-src 'self'",
46
+ `script-src 'self' 'nonce-${nonce}' https://challenges.cloudflare.com`,
47
+ "style-src 'self' 'unsafe-inline'",
48
+ "img-src 'self' data: blob:",
49
+ "font-src 'self' data:",
50
+ "connect-src 'self' https://challenges.cloudflare.com",
51
+ 'frame-src https://challenges.cloudflare.com',
52
+ "frame-ancestors 'none'",
53
+ "base-uri 'self'",
54
+ "form-action 'self'",
55
+ "object-src 'none'",
56
+ ].join('; ')
57
+
58
+ export const withNonce = (html: string, nonce: string): string => html.replace(/<script(?=[\s>])/g, `<script nonce="${nonce}"`)
@@ -0,0 +1,73 @@
1
+ import type { RequestEvent } from 'nuxt/server'
2
+
3
+ import { Context, Effect } from 'effect'
4
+
5
+ import { Sessions } from '#server/app/identity/sessions'
6
+
7
+ export interface UserActorShape {
8
+ readonly id: string
9
+ readonly username: string
10
+ readonly emailStatus: 'unverified' | 'verified'
11
+ }
12
+
13
+ /** The authenticated user resolved from a verified D1 session on the current request. */
14
+ export class UserActor extends Context.Service<UserActor, UserActorShape>()('app/http/UserActor') {}
15
+
16
+ const attached = new WeakMap<RequestEvent, { readonly user: UserActorShape; readonly sessionId: string }>()
17
+
18
+ export const setRequestUser = (event: RequestEvent, user: UserActorShape, sessionId: string) => {
19
+ attached.set(event, { user, sessionId })
20
+ }
21
+
22
+ export const requestUser = (event: RequestEvent): UserActorShape | undefined => attached.get(event)?.user
23
+ export const requestSessionId = (event: RequestEvent): string | undefined => attached.get(event)?.sessionId
24
+
25
+ const BROWSERS: ReadonlyArray<[RegExp, string]> = [
26
+ [/Edg(e|A|iOS)?\//, 'Edge'],
27
+ [/OPR\/|Opera/, 'Opera'],
28
+ [/SamsungBrowser/, 'Samsung Internet'],
29
+ [/Firefox\/|FxiOS/, 'Firefox'],
30
+ [/CriOS|Chrome\//, 'Chrome'],
31
+ [/Safari\//, 'Safari'],
32
+ ]
33
+
34
+ const SYSTEMS: ReadonlyArray<[RegExp, string]> = [
35
+ [/iPhone/, 'iPhone'],
36
+ [/iPad/, 'iPad'],
37
+ [/Android/, 'Android'],
38
+ [/CrOS/, 'ChromeOS'],
39
+ [/Mac OS X|Macintosh/, 'macOS'],
40
+ [/Windows/, 'Windows'],
41
+ [/Linux/, 'Linux'],
42
+ ]
43
+
44
+ /** Coarse device description ("Chrome on macOS") stored on sessions instead of raw User-Agent strings or IPs. */
45
+ export const deviceLabel = (userAgent: string | null | undefined) => {
46
+ const ua = userAgent ?? ''
47
+ const browser = BROWSERS.find(([pattern]) => pattern.test(ua))?.[1]
48
+ const system = SYSTEMS.find(([pattern]) => pattern.test(ua))?.[1]
49
+ if (browser && system) return `${browser} on ${system}`
50
+ return browser ?? system ?? 'Unknown device'
51
+ }
52
+
53
+ export const establishUserSession = (
54
+ event: RequestEvent,
55
+ user: { readonly id: string; readonly username: string; readonly emailStatus: 'unverified' | 'verified' },
56
+ ) =>
57
+ Effect.gen(function* () {
58
+ const sessions = yield* Sessions
59
+ const before = (yield* Effect.promise(() => getUserSession(event))).secure?.sessionId
60
+ if (before) yield* sessions.end(before)
61
+ const sessionId = yield* sessions.start(user.id, deviceLabel(event.req.headers.get('user-agent')))
62
+ yield* Effect.promise(() =>
63
+ replaceUserSession(event, {
64
+ user: { username: user.username, verified: user.emailStatus === 'verified' },
65
+ secure: { sessionId },
66
+ }),
67
+ )
68
+ })
69
+
70
+ export const updateUserSessionMetadata = (event: RequestEvent, user: { readonly username: string; readonly emailStatus: 'unverified' | 'verified' }) =>
71
+ Effect.promise(() => setUserSession(event, { user: { username: user.username, verified: user.emailStatus === 'verified' } }))
72
+
73
+ export const endUserSession = (event: RequestEvent) => Effect.promise(() => clearUserSession(event))
@@ -76,3 +76,15 @@ export class Database extends Context.Service<
76
76
  return Database.of({ all, first, run })
77
77
  }
78
78
  }
79
+
80
+ /** D1 allows 100 bound parameters per statement, so variable-length `IN (...)` queries run in slices. */
81
+ export const MAX_IDS_PER_QUERY = 90
82
+
83
+ export const chunked = <A, E, R>(ids: ReadonlyArray<string>, run: (slice: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<A>, E, R>) =>
84
+ Effect.gen(function* () {
85
+ const found: A[] = []
86
+ for (let start = 0; start < ids.length; start += MAX_IDS_PER_QUERY) found.push(...(yield* run(ids.slice(start, start + MAX_IDS_PER_QUERY))))
87
+ return found
88
+ })
89
+
90
+ export const placeholders = (slice: ReadonlyArray<unknown>) => slice.map(() => '?').join(', ')
@@ -1,6 +1,6 @@
1
1
  import { createError, defineHandler, getRequestURL } from 'nuxt/server'
2
2
 
3
- import { bodyLimitFor } from '#server/core/http/body-limit'
3
+ import { bodyLimitFor } from '#server/core/http/body'
4
4
 
5
5
  export default defineHandler((event) => {
6
6
  const limit = bodyLimitFor(event.req.method, getRequestURL(event).pathname)
@@ -1,8 +1,8 @@
1
1
  import { defineHandler, getRequestURL, useRuntimeConfig } from 'nuxt/server'
2
2
 
3
3
  import { Sessions } from '#server/app/identity/sessions'
4
- import { setRequestUser } from '#server/core/http/request-user'
5
4
  import { runtime } from '#server/core/http/runtime'
5
+ import { setRequestUser } from '#server/core/http/session'
6
6
 
7
7
  export default defineHandler(async (event) => {
8
8
  const path = getRequestURL(event).pathname
@@ -1,7 +1,7 @@
1
1
  import { definePlugin } from 'nitro'
2
2
  import { useServerHooks } from 'nuxt/server'
3
3
 
4
- import { pageCsp, withNonce } from '#server/core/http/page-csp'
4
+ import { pageCsp, withNonce } from '#server/core/http/security'
5
5
 
6
6
  /** Per-response CSP nonce for rendered documents. Skipped in dev so Vite HMR works. */
7
7
  export default definePlugin(() => {
@@ -2,7 +2,7 @@ import { Effect } from 'effect'
2
2
  import { defineHandler, getQuery } from 'nuxt/server'
3
3
 
4
4
  import { EmailRenderer } from '#server/app/notifications/render'
5
- import { sampleEmails } from '#server/app/notifications/samples'
5
+ import { sampleEmails } from '#server/app/notifications/templates'
6
6
  import { runtime } from '#server/core/http/runtime'
7
7
  import { AppConfig } from '#server/core/platform/app-config'
8
8
 
@@ -4,10 +4,10 @@ import { deleteCookie, getCookie, sendRedirect } from 'nuxt/server'
4
4
 
5
5
  import { Identity } from '#server/app/identity/service'
6
6
  import { runtime } from '#server/core/http/runtime'
7
- import { establishUserSession } from '#server/core/http/session-cookie'
7
+ import { establishUserSession } from '#server/core/http/session'
8
8
  import { providerHttp } from '#server/core/platform/provider-http'
9
9
  import { UpstreamFailure } from '#server/utils/errors'
10
- import { isLocalPath } from '#shared/utils/local-path'
10
+ import { isLocalPath } from '#shared/utils/auth'
11
11
 
12
12
  const GitHubEmailList = Schema.Array(
13
13
  Schema.Struct({
@@ -3,8 +3,8 @@ import { deleteCookie, getCookie, sendRedirect } from 'nuxt/server'
3
3
 
4
4
  import { Identity } from '#server/app/identity/service'
5
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'
6
+ import { establishUserSession } from '#server/core/http/session'
7
+ import { isLocalPath } from '#shared/utils/auth'
8
8
 
9
9
  interface GoogleUser {
10
10
  readonly sub?: string
@@ -2,7 +2,7 @@ import type { NuxtErrorDetails, RequestEvent } from 'nuxt/server'
2
2
 
3
3
  import { createError, defineHandler, getQuery, getRouterParams } from 'nuxt/server'
4
4
 
5
- import { readLimitedJson } from './read-body'
5
+ import { readLimitedJson } from '#server/core/http/body'
6
6
 
7
7
  interface StandardSchema<Output = unknown> {
8
8
  readonly '~standard': {
@@ -4,6 +4,9 @@ import { EmailField, NonEmptyPasswordField, PasswordField, SecondFactorCodeField
4
4
 
5
5
  export const EMAIL_CHANGE_DAYS = 14
6
6
 
7
+ /** A relative path on this site: starts with one `/`, never `//`, never contains backslashes or control characters. */
8
+ export const isLocalPath = (path: string): boolean => /^\/(?!\/)[^\r\n\\]*$/.test(path)
9
+
7
10
  export const EmailStatus = Schema.Literals(['unverified', 'verified'])
8
11
  export type EmailStatus = typeof EmailStatus.Type
9
12
 
package/package.json CHANGED
@@ -1,8 +1,26 @@
1
1
  {
2
2
  "name": "@humanonlyweb/create-nuxtflare",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Scaffold a Nuxt 5 + Cloudflare Workers + D1 + Effect v4 app with explicit auth, TOTP 2FA, and admin.",
5
5
  "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/humanonlyweb/nuxtflare.git"
9
+ },
10
+ "homepage": "https://github.com/humanonlyweb/nuxtflare#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/humanonlyweb/nuxtflare/issues"
13
+ },
14
+ "keywords": [
15
+ "nuxt",
16
+ "nuxt5",
17
+ "cloudflare",
18
+ "cloudflare-workers",
19
+ "d1",
20
+ "effect",
21
+ "starter",
22
+ "create"
23
+ ],
6
24
  "type": "module",
7
25
  "publishConfig": {
8
26
  "access": "public"
@@ -24,7 +42,7 @@
24
42
  },
25
43
  "engines": {
26
44
  "bun": ">=1.4.0",
27
- "node": ">=22.0.0"
45
+ "node": ">=24.0.0"
28
46
  },
29
47
  "packageManager": "bun@1.4.5"
30
48
  }
@@ -1,12 +0,0 @@
1
- export type Block =
2
- | { readonly kind: 'text'; readonly text: string }
3
- | { readonly kind: 'button'; readonly label: string; readonly url: string }
4
- | { readonly kind: 'note'; readonly text: string }
5
-
6
- export interface Email {
7
- readonly subject: string
8
- readonly preheader: string
9
- readonly headline: string
10
- readonly blocks: ReadonlyArray<Block>
11
- readonly footer: string
12
- }
@@ -1,11 +0,0 @@
1
- import type { Email } from './email'
2
-
3
- import { emailChangeEmail, passwordResetEmail, verificationEmail } from './templates'
4
-
5
- const SAMPLE_TOKEN = '0'.repeat(64)
6
-
7
- export const sampleEmails = (appUrl: string, appName: string): Readonly<Record<string, Email>> => ({
8
- verification: verificationEmail(`${appUrl}/verify/${SAMPLE_TOKEN}`, appName),
9
- passwordReset: passwordResetEmail(`${appUrl}/reset/${SAMPLE_TOKEN}`, appName),
10
- emailChange: emailChangeEmail(`${appUrl}/email/${SAMPLE_TOKEN}`, appName),
11
- })
@@ -1,13 +0,0 @@
1
- import { Effect } from 'effect'
2
-
3
- /** D1 allows 100 bound parameters per statement, so variable-length `IN (...)` queries run in slices. */
4
- export const MAX_IDS_PER_QUERY = 90
5
-
6
- export const chunked = <A, E, R>(ids: ReadonlyArray<string>, run: (slice: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<A>, E, R>) =>
7
- Effect.gen(function* () {
8
- const found: A[] = []
9
- for (let start = 0; start < ids.length; start += MAX_IDS_PER_QUERY) found.push(...(yield* run(ids.slice(start, start + MAX_IDS_PER_QUERY))))
10
- return found
11
- })
12
-
13
- export const placeholders = (slice: ReadonlyArray<unknown>) => slice.map(() => '?').join(', ')
@@ -1,35 +0,0 @@
1
- const JSON_LIMIT = 1024 * 1024
2
-
3
- /** Maximum body size in bytes for API writes, or undefined when the route reads no body. */
4
- export const bodyLimitFor = (method: string, path: string): number | undefined => {
5
- if (!['POST', 'PUT', 'PATCH'].includes(method) || !path.startsWith('/api/')) return undefined
6
- return JSON_LIMIT
7
- }
8
-
9
- /** Reads bytes up to `limit`, returning undefined if the stream exceeds `limit` (handles chunked bodies without Content-Length). */
10
- export const readCapped = async (body: ReadableStream<Uint8Array> | null, limit: number): Promise<Uint8Array | undefined> => {
11
- if (!body) return new Uint8Array()
12
- const reader = body.getReader()
13
- const chunks: Uint8Array[] = []
14
- let size = 0
15
- for (;;) {
16
- // Stream chunks are consumed sequentially.
17
- // oxlint-disable-next-line eslint/no-await-in-loop
18
- const { done, value } = await reader.read()
19
- if (done) break
20
- size += value.byteLength
21
- if (size > limit) {
22
- // oxlint-disable-next-line eslint/no-await-in-loop
23
- await reader.cancel()
24
- return undefined
25
- }
26
- chunks.push(value)
27
- }
28
- const bytes = new Uint8Array(size)
29
- let offset = 0
30
- for (const chunk of chunks) {
31
- bytes.set(chunk, offset)
32
- offset += chunk.byteLength
33
- }
34
- return bytes
35
- }
@@ -1,16 +0,0 @@
1
- /** Cookie-backed writes are forgeable cross-site; browsers send Sec-Fetch-Site or Origin, while non-browser clients (curl) pass. */
2
- export const isSameOriginRequest = (headers: { get: (name: string) => string | null }, expectedHost: string): boolean => {
3
- const site = headers.get('sec-fetch-site')
4
- if (site) return site === 'same-origin' || site === 'none'
5
- const origin = headers.get('origin')
6
- if (origin) {
7
- try {
8
- return new URL(origin).host === expectedHost
9
- } catch {
10
- return false
11
- }
12
- }
13
- return true
14
- }
15
-
16
- export const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
@@ -1,27 +0,0 @@
1
- const BROWSERS: ReadonlyArray<[RegExp, string]> = [
2
- [/Edg(e|A|iOS)?\//, 'Edge'],
3
- [/OPR\/|Opera/, 'Opera'],
4
- [/SamsungBrowser/, 'Samsung Internet'],
5
- [/Firefox\/|FxiOS/, 'Firefox'],
6
- [/CriOS|Chrome\//, 'Chrome'],
7
- [/Safari\//, 'Safari'],
8
- ]
9
-
10
- const SYSTEMS: ReadonlyArray<[RegExp, string]> = [
11
- [/iPhone/, 'iPhone'],
12
- [/iPad/, 'iPad'],
13
- [/Android/, 'Android'],
14
- [/CrOS/, 'ChromeOS'],
15
- [/Mac OS X|Macintosh/, 'macOS'],
16
- [/Windows/, 'Windows'],
17
- [/Linux/, 'Linux'],
18
- ]
19
-
20
- /** Coarse device description ("Chrome on macOS") stored on sessions instead of raw User-Agent strings or IP addresses. */
21
- export const deviceLabel = (userAgent: string | null | undefined) => {
22
- const ua = userAgent ?? ''
23
- const browser = BROWSERS.find(([pattern]) => pattern.test(ua))?.[1]
24
- const system = SYSTEMS.find(([pattern]) => pattern.test(ua))?.[1]
25
- if (browser && system) return `${browser} on ${system}`
26
- return browser ?? system ?? 'Unknown device'
27
- }
@@ -1,17 +0,0 @@
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
- }
@@ -1,16 +0,0 @@
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}"`)
@@ -1,9 +0,0 @@
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
@@ -1,13 +0,0 @@
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
@@ -1,29 +0,0 @@
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))
@@ -1,34 +0,0 @@
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
- }
@@ -1,10 +0,0 @@
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') {}
@@ -1,2 +0,0 @@
1
- /** A relative path on this site: starts with one `/`, never `//`, never contains backslashes or control characters. */
2
- export const isLocalPath = (path: string): boolean => /^\/(?!\/)[^\r\n\\]*$/.test(path)