@humanonlyweb/create-nuxtflare 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +4 -2
  2. package/dist/cli.js +9 -1
  3. package/dist/template/.github/workflows/ci.yml +3 -1
  4. package/dist/template/CLAUDE.md +4 -2
  5. package/dist/template/app/components/turnstile-widget.vue +81 -0
  6. package/dist/template/app/composables/use-auth.ts +418 -0
  7. package/dist/template/app/pages/account.vue +125 -11
  8. package/dist/template/app/pages/email/[token].vue +18 -0
  9. package/dist/template/app/pages/forgot-password.vue +28 -0
  10. package/dist/template/app/pages/login.vue +9 -73
  11. package/dist/template/app/pages/register.vue +4 -26
  12. package/dist/template/app/pages/reset/[token].vue +31 -0
  13. package/dist/template/app/pages/verify/[token].vue +18 -0
  14. package/dist/template/nuxt.config.ts +4 -0
  15. package/dist/template/package.json +2 -0
  16. package/dist/template/scripts/admin-password.ts +13 -6
  17. package/dist/template/scripts/migrate.ts +67 -0
  18. package/dist/template/server/api/account/email/index.post.ts +1 -1
  19. package/dist/template/server/api/account/index.delete.ts +2 -2
  20. package/dist/template/server/api/account/password.post.ts +8 -0
  21. package/dist/template/server/api/auth/email/index.post.ts +1 -1
  22. package/dist/template/server/api/auth/login/totp.post.ts +6 -2
  23. package/dist/template/server/api/auth/login.post.ts +4 -2
  24. package/dist/template/server/api/auth/register.post.ts +1 -1
  25. package/dist/template/server/api/auth/verify/index.post.ts +1 -1
  26. package/dist/template/server/app/admin/auth.ts +2 -1
  27. package/dist/template/server/app/features.ts +4 -3
  28. package/dist/template/server/app/identity/email-change.ts +44 -7
  29. package/dist/template/server/app/identity/identity.test.ts +70 -0
  30. package/dist/template/server/app/identity/lockout.ts +8 -3
  31. package/dist/template/server/app/identity/password-reset.ts +3 -1
  32. package/dist/template/server/app/identity/service.ts +145 -30
  33. package/dist/template/server/app/identity/sessions.ts +38 -6
  34. package/dist/template/server/app/identity/totp-crypto.ts +12 -5
  35. package/dist/template/server/app/identity/totp.ts +13 -12
  36. package/dist/template/server/app/identity/verification.ts +3 -1
  37. package/dist/template/server/app/maintenance/cleanup.test.ts +56 -0
  38. package/dist/template/server/app/maintenance/cleanup.ts +63 -0
  39. package/dist/template/server/core/db/migrations.ts +7 -0
  40. package/dist/template/server/core/db/migrator.ts +5 -1
  41. package/dist/template/server/core/http/body.ts +1 -1
  42. package/dist/template/server/core/http/handle.ts +93 -80
  43. package/dist/template/server/core/http/security.test.ts +38 -0
  44. package/dist/template/server/core/http/security.ts +17 -5
  45. package/dist/template/server/core/http/session.ts +15 -0
  46. package/dist/template/server/core/platform/crypto-and-window.test.ts +75 -0
  47. package/dist/template/server/core/platform/database.ts +16 -1
  48. package/dist/template/server/core/platform/pii.ts +5 -8
  49. package/dist/template/server/core/platform/rate-limiter-strict.ts +35 -5
  50. package/dist/template/server/core/platform/rate-limiter.ts +2 -2
  51. package/dist/template/server/core/platform/seal.ts +13 -11
  52. package/dist/template/server/core/platform/sliding-window.ts +11 -2
  53. package/dist/template/server/core/platform/tokens.ts +3 -1
  54. package/dist/template/server/middleware/00-security-headers.ts +8 -4
  55. package/dist/template/server/middleware/01-user-session.ts +17 -5
  56. package/dist/template/server/plugins/page-csp.ts +24 -4
  57. package/dist/template/server/plugins/sessions.ts +4 -2
  58. package/dist/template/server/routes/auth/github.get.ts +4 -3
  59. package/dist/template/server/routes/auth/google.get.ts +4 -2
  60. package/dist/template/server/tasks/cleanup.ts +15 -0
  61. package/dist/template/server/test/invariants.test.ts +4 -2
  62. package/dist/template/server/utils/define-validated-handler.ts +14 -12
  63. package/dist/template/shared/domain/errors.ts +1 -0
  64. package/dist/template/shared/types/auth.d.ts +1 -1
  65. package/dist/template/shared/utils/auth.ts +10 -4
  66. package/dist/template/shared/utils/paths.ts +2 -0
  67. package/dist/template/shared/utils/schema-validation.ts +1 -1
  68. package/dist/template/wrangler.json +17 -0
  69. package/package.json +1 -1
@@ -1,16 +1,19 @@
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 => {
1
+ /**
2
+ * Cookie-backed writes are forgeable cross-site: browsers always send `Sec-Fetch-Site` or `Origin` on unsafe methods.
3
+ * Non-browser clients without cookies pass; cookie-bearing requests without either header are refused.
4
+ */
5
+ export const isSameOriginRequest = (headers: { get: (name: string) => string | null }, expectedOrigin: string): boolean => {
3
6
  const site = headers.get('sec-fetch-site')
4
7
  if (site) return site === 'same-origin' || site === 'none'
5
8
  const origin = headers.get('origin')
6
9
  if (origin) {
7
10
  try {
8
- return new URL(origin).host === expectedHost
11
+ return new URL(origin).origin === expectedOrigin
9
12
  } catch {
10
13
  return false
11
14
  }
12
15
  }
13
- return true
16
+ return !headers.get('cookie')
14
17
  }
15
18
 
16
19
  export const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
@@ -55,4 +58,13 @@ export const pageCsp = (nonce: string): string =>
55
58
  "object-src 'none'",
56
59
  ].join('; ')
57
60
 
58
- export const withNonce = (html: string, nonce: string): string => html.replace(/<script(?=[\s>])/g, `<script nonce="${nonce}"`)
61
+ /**
62
+ * Stamps `nonce` onto top-level executable `<script>` elements inside framework-owned fragments (`head` / `bodyAppend`).
63
+ * Skips script body text (so `<script` inside serialized JSON payloads is untouched) and skips JSON data blocks.
64
+ */
65
+ export const stampScriptNonces = (fragment: string, nonce: string): string =>
66
+ fragment.replace(/<script(?=[\s>])([^>]*)>([\s\S]*?)<\/script>/gi, (full, attrs: string, body: string) => {
67
+ if (/\bnonce\s*=/i.test(attrs)) return full
68
+ if (/\btype\s*=\s*["']?application\/(?:json|ld\+json)["']?/i.test(attrs)) return full
69
+ return `<script nonce="${nonce}"${attrs}>${body}</script>`
70
+ })
@@ -3,6 +3,21 @@ import type { RequestEvent } from 'nuxt/server'
3
3
  import { Context, Effect } from 'effect'
4
4
 
5
5
  import { Sessions } from '#server/app/identity/sessions'
6
+ import { readKey } from '#shared/utils/unknown'
7
+
8
+ interface WaitUntilHost {
9
+ readonly waitUntil: (promise: Promise<unknown>) => void
10
+ }
11
+
12
+ const hasWaitUntil = (value: unknown): value is WaitUntilHost => typeof readKey(value, 'waitUntil') === 'function'
13
+
14
+ /** Extracts Nitro/Cloudflare's `waitUntil` from a portable `RequestEvent` when running inside a request runtime. */
15
+ export const waitUntilOf = (event: RequestEvent): ((promise: Promise<unknown>) => void) | undefined => {
16
+ if (hasWaitUntil(event)) return (promise) => event.waitUntil(promise)
17
+ const req: unknown = event.req
18
+ if (hasWaitUntil(req)) return (promise) => req.waitUntil(promise)
19
+ return undefined
20
+ }
6
21
 
7
22
  export interface UserActorShape {
8
23
  readonly id: string
@@ -0,0 +1,75 @@
1
+ import { Effect, Redacted } from 'effect'
2
+ import { DatabaseSync } from 'node:sqlite'
3
+ import { describe, expect, it } from 'vitest'
4
+
5
+ import { makeTestLayer } from '#server/test/kit'
6
+
7
+ import { Pii } from './pii'
8
+ import { Seal } from './seal'
9
+ import { makeSlidingWindow, type WindowSql } from './sliding-window'
10
+
11
+ const KEY_A = '1'.repeat(64)
12
+ const KEY_B = '2'.repeat(64)
13
+ const encoder = new TextEncoder()
14
+ const decoder = new TextDecoder()
15
+
16
+ const nodeSqliteWindowSql = (): WindowSql => {
17
+ const db = new DatabaseSync(':memory:')
18
+ return {
19
+ exec: (query, ...bindings) => {
20
+ const stmt = db.prepare(query)
21
+ const params = bindings as Array<string | number | null>
22
+ if (/^\s*SELECT\b/i.test(query)) {
23
+ const rows = stmt.all(...params) as Array<Record<string, unknown>>
24
+ return { toArray: () => rows }
25
+ }
26
+ stmt.run(...params)
27
+ return { toArray: () => [] }
28
+ },
29
+ }
30
+ }
31
+
32
+ describe('Seal and Pii', () => {
33
+ it('seals and opens without compression, rejecting wrong context and truncated payloads', async () => {
34
+ const { run } = await makeTestLayer()
35
+ const payload = encoder.encode('secret-totp-value')
36
+ const sealed = await run(Seal.use((s) => s.seal(payload, KEY_A, 'users.totp_secret')))
37
+ const opened = await run(Seal.use((s) => s.open(sealed, KEY_A, 'users.totp_secret')))
38
+ expect(decoder.decode(opened)).toBe('secret-totp-value')
39
+
40
+ const wrongContext = await run(Seal.use((s) => s.open(sealed, KEY_A, 'other.column')).pipe(Effect.result))
41
+ expect(wrongContext._tag).toBe('Failure')
42
+
43
+ const truncated = await run(Seal.use((s) => s.open(sealed.slice(0, 10), KEY_A, 'users.totp_secret')).pipe(Effect.result))
44
+ expect(truncated._tag).toBe('Failure')
45
+ })
46
+
47
+ it('rejects unencrypted plaintext in Pii.open and rotates keys cleanly', async () => {
48
+ const first = await makeTestLayer({ config: { piiKey: Redacted.make(KEY_A) } })
49
+ const sealed = await first.run(Pii.use((p) => p.seal('hello@example.com', 'users.email')))
50
+ expect(sealed.startsWith('pii2:')).toBe(true)
51
+
52
+ await expect(first.run(Pii.use((p) => p.open('unencrypted-plaintext', 'users.email')))).rejects.toThrow(/not sealed/i)
53
+
54
+ const rotated = await makeTestLayer({ config: { piiKey: Redacted.make(KEY_B), piiKeyPrevious: Redacted.make(KEY_A) } })
55
+ expect(await rotated.run(Pii.use((p) => p.open(sealed, 'users.email')))).toBe('hello@example.com')
56
+ })
57
+
58
+ it('fails fast at layer construction on invalid piiIndexKey or short appSecret', async () => {
59
+ await expect(makeTestLayer({ config: { piiIndexKey: Redacted.make('not-64-hex') } }).then((t) => t.run(Effect.void))).rejects.toThrow(/NUXT_PII_INDEX_KEY/)
60
+
61
+ await expect(makeTestLayer({ config: { appSecret: Redacted.make('short') } }).then((t) => t.run(Effect.void))).rejects.toThrow(/NUXT_APP_SECRET/)
62
+ })
63
+ })
64
+
65
+ describe('makeSlidingWindow', () => {
66
+ it('enforces rolling window limits, computes retryAfterMs, and detects idle windows', () => {
67
+ const win = makeSlidingWindow(nodeSqliteWindowSql())
68
+ expect(win.hit(2, 10_000, 1000)).toEqual({ allowed: true, retryAfterMs: 0 })
69
+ expect(win.hit(2, 10_000, 2000)).toEqual({ allowed: true, retryAfterMs: 0 })
70
+ expect(win.hit(2, 10_000, 3000)).toEqual({ allowed: false, retryAfterMs: 8000 })
71
+ expect(win.windowMs(60_000)).toBe(10_000)
72
+ expect(win.idle(10_000, 5000)).toBe(false)
73
+ expect(win.idle(10_000, 12_000)).toBe(true)
74
+ })
75
+ })
@@ -49,6 +49,18 @@ export class Database extends Context.Service<
49
49
  return isReadQuery(sql) ? query.pipe(Effect.retry({ schedule: READ_RETRY, times: 2, while: isTransient })) : query
50
50
  }
51
51
 
52
+ const row = (sql: string, params: ReadonlyArray<Param>) => {
53
+ const query = Effect.tryPromise({
54
+ try: () =>
55
+ db
56
+ .prepare(sql)
57
+ .bind(...params)
58
+ .get(),
59
+ catch: failure(sql),
60
+ })
61
+ return isReadQuery(sql) ? query.pipe(Effect.retry({ schedule: READ_RETRY, times: 2, while: isTransient })) : query
62
+ }
63
+
52
64
  const decode =
53
65
  <A, I>(schema: Schema.Codec<A, I>, sql: string) =>
54
66
  (input: unknown) =>
@@ -61,7 +73,10 @@ export class Database extends Context.Service<
61
73
  )
62
74
 
63
75
  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]))
76
+ row(sql, params).pipe(
77
+ Effect.flatMap((found) => (found === undefined || found === null ? Effect.undefined : decode(schema, sql)(found))),
78
+ Effect.withSpan('Database.first'),
79
+ )
65
80
 
66
81
  const run = (sql: string, params: ReadonlyArray<Param> = []) =>
67
82
  Effect.tryPromise({
@@ -41,13 +41,14 @@ export class Pii extends Context.Service<
41
41
  if (!/^[0-9a-f]{64}$/i.test(current)) {
42
42
  return yield* Effect.die(new Error('NUXT_PII_KEY must be 64 hex characters (generate with `openssl rand -hex 32`).'))
43
43
  }
44
- if (indexKey.length < 32) {
45
- return yield* Effect.die(new Error('NUXT_PII_INDEX_KEY is missing or too short (generate with `openssl rand -hex 32`).'))
44
+ if (!/^[0-9a-f]{64}$/i.test(indexKey)) {
45
+ return yield* Effect.die(new Error('NUXT_PII_INDEX_KEY must be 64 hex characters (generate with `openssl rand -hex 32`).'))
46
46
  }
47
47
  const idOf = (key: string) => seal.sha256(encoder.encode(`pii-key:${key}`)).pipe(Effect.map((hash) => hash.slice(0, 8)))
48
48
  const keys = new Map<string, string>()
49
49
  for (const key of keyList(current, Redacted.value(config.piiKeyPrevious))) keys.set(yield* idOf(key), key)
50
50
  const kid = yield* idOf(current)
51
+ const indexMacKey = yield* Mac.key(Mac.hmacSha256, encoder.encode(`pii-index:${indexKey}`)).pipe(Effect.orDie)
51
52
 
52
53
  const sealValue = (value: string, field: string) =>
53
54
  seal.seal(encoder.encode(value), current, field).pipe(
@@ -56,7 +57,7 @@ export class Pii extends Context.Service<
56
57
  )
57
58
 
58
59
  const openValue = (stored: string, field: string) => {
59
- if (!stored.startsWith(PREFIX)) return Effect.succeed(stored)
60
+ if (!stored.startsWith(PREFIX)) return Effect.die(new Error(`Stored ${field} is not sealed.`))
60
61
  const [id = '', body = ''] = stored.slice(PREFIX.length).split(':')
61
62
  const key = keys.get(id)
62
63
  const bytes = Base64Url.decode(body)
@@ -68,11 +69,7 @@ export class Pii extends Context.Service<
68
69
  )
69
70
  }
70
71
 
71
- const index = (value: string) =>
72
- Effect.gen(function* () {
73
- const key = yield* Mac.key(Mac.hmacSha256, encoder.encode(`pii-index:${indexKey}`))
74
- return Hex.encode(yield* mac.sign(key, encoder.encode(value.trim().toLowerCase())))
75
- }).pipe(Effect.orDie)
72
+ const index = (value: string) => mac.sign(indexMacKey, encoder.encode(value.trim().toLowerCase())).pipe(Effect.map(Hex.encode), Effect.orDie)
76
73
 
77
74
  return Pii.of({ kid, seal: sealValue, open: openValue, index })
78
75
  }),
@@ -4,12 +4,12 @@ import { Effect, Layer } from 'effect'
4
4
  import { UpstreamFailure } from '#server/utils/errors'
5
5
  import { RateLimited } from '#shared/domain/errors'
6
6
 
7
- import type { LimitName } from './rate-limiter'
7
+ import type { LimitBinding, LimitName } from './rate-limiter'
8
8
 
9
9
  import { AppConfig } from './app-config'
10
- import { RateLimiter } from './rate-limiter'
10
+ import { RateLimiter, allowed } from './rate-limiter'
11
11
 
12
- /** Global per-caller budgets backed by the `RateLimitCounter` Durable Object. */
12
+ /** Global per-caller budgets backed by Cloudflare edge rate limits (coarse IP) and `RateLimitCounter` DO (strict per-account/long windows). */
13
13
  export const LIMITS: Record<LimitName, { readonly limit: number; readonly windowMs: number }> = {
14
14
  'sign-in': { limit: 30, windowMs: 60_000 },
15
15
  'sign-in-account': { limit: 20, windowMs: 10 * 60_000 },
@@ -21,21 +21,51 @@ export const LIMITS: Record<LimitName, { readonly limit: number; readonly window
21
21
  totp: { limit: 15, windowMs: 10 * 60_000 },
22
22
  }
23
23
 
24
+ const edgeBindingFor = (limit: LimitName): LimitBinding | undefined => {
25
+ switch (limit) {
26
+ case 'sign-in':
27
+ return env.RL_SIGN_IN
28
+ case 'register':
29
+ return env.RL_REGISTER
30
+ case 'reset':
31
+ return env.RL_RESET
32
+ default:
33
+ return undefined
34
+ }
35
+ }
36
+
24
37
  export const RateLimiterStrict = Layer.effect(
25
38
  RateLimiter,
26
39
  Effect.gen(function* () {
27
40
  const config = yield* AppConfig
41
+ if (config.rateLimitScale < 1) {
42
+ return yield* Effect.die(new Error('NUXT_RATE_LIMIT_SCALE must be at least 1.'))
43
+ }
44
+ if (!import.meta.dev && config.rateLimitScale !== 1) {
45
+ yield* Effect.logWarning(`NUXT_RATE_LIMIT_SCALE is set to ${config.rateLimitScale} in production; rate limits are scaled accordingly.`)
46
+ }
28
47
  // Resolved per call, never cached across requests: a DO stub is tied to the request I/O context that created it.
29
48
  const counter = (name: string) => env.RATE_LIMITER.getByName(name)
30
49
  return RateLimiter.of({
31
50
  check: (limit, key) =>
32
51
  Effect.gen(function* () {
52
+ // Coarse 60s IP limits use Cloudflare's zero-RTT edge Rate Limiting binding in prod so IP floods never spin up DOs.
53
+ if (config.rateLimitScale === 1) {
54
+ const edge = edgeBindingFor(limit)
55
+ if (edge) return yield* allowed(edge, `${limit}:${key}`)
56
+ }
57
+
33
58
  const rule = LIMITS[limit]
34
59
  const verdict = yield* Effect.tryPromise({
35
60
  try: () => counter(`${limit}:${key}`).hit(rule.limit * config.rateLimitScale, rule.windowMs),
36
61
  catch: (cause) => new UpstreamFailure({ service: 'rate-limiter', message: String(cause) }),
37
- }).pipe(Effect.option)
38
- if (verdict._tag === 'Some' && !verdict.value.allowed) return yield* new RateLimited({ message: 'Too many requests. Please try again in a minute.' })
62
+ }).pipe(Effect.catch((error) => Effect.logWarning(`Rate limiter (${limit}) failed open: ${error.message}`).pipe(Effect.as(undefined))))
63
+ if (verdict && !verdict.allowed) {
64
+ return yield* new RateLimited({
65
+ message: 'Too many requests. Please try again in a minute.',
66
+ retryAfterSeconds: Math.max(1, Math.ceil(verdict.retryAfterMs / 1000)),
67
+ })
68
+ }
39
69
  }),
40
70
  })
41
71
  }),
@@ -15,9 +15,9 @@ export const allowed = (binding: LimitBinding | undefined, key: string): Effect.
15
15
  const outcome = yield* Effect.tryPromise({
16
16
  try: () => binding.limit({ key }),
17
17
  catch: (cause) => new UpstreamFailure({ service: 'rate-limiter', message: String(cause) }),
18
- }).pipe(Effect.option)
18
+ }).pipe(Effect.catch((error) => Effect.logWarning(`Rate limiter failed open: ${error.message}`).pipe(Effect.as(undefined))))
19
19
 
20
- if (outcome._tag === 'Some' && !outcome.value.success) return yield* new RateLimited({ message: 'Too many requests. Please try again in a minute.' })
20
+ if (outcome && !outcome.success) return yield* new RateLimited({ message: 'Too many requests. Please try again in a minute.' })
21
21
  })
22
22
 
23
23
  export class RateLimiter extends Context.Service<RateLimiter, { readonly check: (limit: LimitName, key: string) => Effect.Effect<void, RateLimited> }>()(
@@ -4,15 +4,13 @@ import { Hex } from 'effect/encoding'
4
4
 
5
5
  export class SealError extends Schema.TaggedError<SealError, { readonly brand: unique symbol }>()('SealError', { message: Schema.String }) {}
6
6
 
7
- /** Binary format: version(1) | nonce(12) | AES-256-GCM(gzip(plain), aad = context). */
8
- const VERSION = 2
7
+ /** Binary format: version(1) | nonce(12) | AES-256-GCM(plain, aad = context). No compression to avoid length-oracle side channels. */
8
+ const VERSION = 3
9
9
  const NONCE_BYTES = 12
10
+ const TAG_BYTES = 16
11
+ const MIN_SEALED_BYTES = 1 + NONCE_BYTES + TAG_BYTES
10
12
  const encoder = new TextEncoder()
11
13
 
12
- const collect = async (stream: ReadableStream<Uint8Array>) => new Uint8Array(await new Response(stream).arrayBuffer())
13
- const gzip = (bytes: Uint8Array) => collect(new Blob([new Uint8Array(bytes)]).stream().pipeThrough(new CompressionStream('gzip')))
14
- const gunzip = (bytes: Uint8Array) => collect(new Blob([new Uint8Array(bytes)]).stream().pipeThrough(new DecompressionStream('gzip')))
15
-
16
14
  export class Seal extends Context.Service<
17
15
  Seal,
18
16
  {
@@ -27,13 +25,18 @@ export class Seal extends Context.Service<
27
25
  const aead = yield* Aead.Aead
28
26
  const random = yield* SecureRandom.SecureRandom
29
27
  const digest = yield* Digest.Digest
28
+ const importedKeys = new Map<string, Aead.Key<typeof Aead.aes256Gcm>>()
30
29
 
31
30
  const keyOf = (keyHex: string) =>
32
31
  Effect.gen(function* () {
32
+ const cached = importedKeys.get(keyHex)
33
+ if (cached) return cached
33
34
  const decoded = Hex.decode(keyHex)
34
35
  if (decoded._tag === 'Failure' || decoded.success.length !== Aead.aes256Gcm.keyLength)
35
36
  return yield* new SealError({ message: 'Encryption key must be 64 hex characters (32 bytes).' })
36
- return yield* Aead.key(Aead.aes256Gcm, decoded.success).pipe(Effect.mapError(() => new SealError({ message: 'Encryption key was refused.' })))
37
+ const key = yield* Aead.key(Aead.aes256Gcm, decoded.success).pipe(Effect.mapError(() => new SealError({ message: 'Encryption key was refused.' })))
38
+ importedKeys.set(keyHex, key)
39
+ return key
37
40
  })
38
41
 
39
42
  const seal = (plain: Uint8Array, keyHex: string, context: string) =>
@@ -41,7 +44,7 @@ export class Seal extends Context.Service<
41
44
  const key = yield* keyOf(keyHex)
42
45
  const nonce = yield* random.randomBytes(NONCE_BYTES)
43
46
  const body = yield* aead
44
- .encrypt(key, yield* Effect.promise(() => gzip(plain)), { nonce, aad: encoder.encode(context) })
47
+ .encrypt(key, plain, { nonce, aad: encoder.encode(context) })
45
48
  .pipe(Effect.mapError(() => new SealError({ message: 'Sealing failed.' })))
46
49
  const out = new Uint8Array(1 + NONCE_BYTES + body.length)
47
50
  out[0] = VERSION
@@ -52,12 +55,11 @@ export class Seal extends Context.Service<
52
55
 
53
56
  const open = (sealed: Uint8Array, keyHex: string, context: string) =>
54
57
  Effect.gen(function* () {
55
- if (sealed[0] !== VERSION) return yield* new SealError({ message: 'Unknown sealed format.' })
58
+ if (sealed.length < MIN_SEALED_BYTES || sealed[0] !== VERSION) return yield* new SealError({ message: 'Unknown sealed format.' })
56
59
  const key = yield* keyOf(keyHex)
57
- const plain = yield* aead
60
+ return yield* aead
58
61
  .decrypt(key, sealed.slice(1 + NONCE_BYTES), { nonce: sealed.slice(1, 1 + NONCE_BYTES), aad: encoder.encode(context) })
59
62
  .pipe(Effect.mapError(() => new SealError({ message: 'Cannot be opened: wrong key, wrong context, or damaged.' })))
60
- return yield* Effect.tryPromise({ try: () => gunzip(plain), catch: () => new SealError({ message: 'The data inside is damaged.' }) })
61
63
  })
62
64
 
63
65
  return Seal.of({ seal, open, sha256: (bytes) => digest.digestHex(Digest.sha256, bytes) })
@@ -10,14 +10,21 @@ export interface WindowVerdict {
10
10
 
11
11
  /** Caller must serialize access (a Durable Object does automatically). */
12
12
  export const makeSlidingWindow = (sql: WindowSql) => {
13
+ let cachedWindowMs: number | undefined
14
+
13
15
  const init = () => {
16
+ cachedWindowMs = undefined
14
17
  sql.exec(`CREATE TABLE IF NOT EXISTS hits (at INTEGER NOT NULL)`)
18
+ sql.exec(`CREATE INDEX IF NOT EXISTS idx_hits_at ON hits (at)`)
15
19
  sql.exec(`CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value INTEGER NOT NULL)`)
16
20
  }
17
21
  init()
18
22
 
19
23
  const hit = (limit: number, windowMs: number, now: number): WindowVerdict => {
20
- sql.exec(`INSERT INTO meta (key, value) VALUES ('window_ms', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`, windowMs)
24
+ if (cachedWindowMs !== windowMs) {
25
+ sql.exec(`INSERT INTO meta (key, value) VALUES ('window_ms', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`, windowMs)
26
+ cachedWindowMs = windowMs
27
+ }
21
28
  sql.exec(`DELETE FROM hits WHERE at <= ?`, now - windowMs)
22
29
  const [row] = sql.exec(`SELECT COUNT(*) AS n, MIN(at) AS oldest FROM hits`).toArray()
23
30
  if (Number(row!.n) >= limit) return { allowed: false, retryAfterMs: Math.max(0, Number(row!.oldest) + windowMs - now) }
@@ -26,8 +33,10 @@ export const makeSlidingWindow = (sql: WindowSql) => {
26
33
  }
27
34
 
28
35
  const windowMs = (fallback: number): number => {
36
+ if (cachedWindowMs !== undefined) return cachedWindowMs
29
37
  const row = sql.exec(`SELECT value FROM meta WHERE key = 'window_ms'`).toArray()[0]
30
- return row ? Number(row.value) : fallback
38
+ cachedWindowMs = row ? Number(row.value) : fallback
39
+ return cachedWindowMs
31
40
  }
32
41
 
33
42
  const idle = (ms: number, now: number): boolean => {
@@ -2,6 +2,8 @@ import { Context, Effect, Layer } from 'effect'
2
2
  import { Digest, Mac, SecureRandom } from 'effect/crypto'
3
3
  import { Hex } from 'effect/encoding'
4
4
 
5
+ const encoder = new TextEncoder()
6
+
5
7
  /** One-time tokens for emailed links and HMAC signing: only the SHA-256 hash is persisted in D1. */
6
8
  export class Tokens extends Context.Service<
7
9
  Tokens,
@@ -18,7 +20,7 @@ export class Tokens extends Context.Service<
18
20
  const random = yield* SecureRandom.SecureRandom
19
21
  const digest = yield* Digest.Digest
20
22
  const mac = yield* Mac.Mac
21
- const bytesOf = (value: string) => new TextEncoder().encode(value)
23
+ const bytesOf = (value: string) => encoder.encode(value)
22
24
  const hash = (token: string) => digest.digestHex(Digest.sha256, bytesOf(token))
23
25
  const generate = Effect.gen(function* () {
24
26
  const token = Hex.encode(yield* random.randomBytes(32))
@@ -1,5 +1,6 @@
1
1
  import { defineHandler } from 'nuxt/server'
2
2
 
3
+ import { isLocalHost } from '#server/app/admin/auth'
3
4
  import { readKey } from '#shared/utils/unknown'
4
5
 
5
6
  export const SECURITY_HEADERS: Readonly<Record<string, string>> = {
@@ -7,13 +8,16 @@ export const SECURITY_HEADERS: Readonly<Record<string, string>> = {
7
8
  'x-frame-options': 'DENY',
8
9
  'referrer-policy': 'strict-origin-when-cross-origin',
9
10
  'permissions-policy': 'camera=(), microphone=(), geolocation=()',
10
- 'strict-transport-security': 'max-age=31536000; includeSubDomains',
11
11
  }
12
12
 
13
+ const HSTS = 'max-age=31536000; includeSubDomains'
14
+
13
15
  export default defineHandler((event) => {
14
16
  const errHeaders = readKey(event.res, 'errHeaders')
15
- for (const [name, value] of Object.entries(SECURITY_HEADERS)) {
16
- event.res.headers.set(name, value)
17
- if (errHeaders instanceof Headers) errHeaders.set(name, value)
17
+ const setIfMissing = (name: string, value: string) => {
18
+ if (!event.res.headers.has(name)) event.res.headers.set(name, value)
19
+ if (errHeaders instanceof Headers && !errHeaders.has(name)) errHeaders.set(name, value)
18
20
  }
21
+ for (const [name, value] of Object.entries(SECURITY_HEADERS)) setIfMissing(name, value)
22
+ if (!isLocalHost(event.req.url)) setIfMissing('strict-transport-security', HSTS)
19
23
  })
@@ -1,12 +1,22 @@
1
- import { defineHandler, getRequestURL, useRuntimeConfig } from 'nuxt/server'
1
+ import { defineHandler, deleteCookie, getRequestURL, useRuntimeConfig } from 'nuxt/server'
2
2
 
3
3
  import { Sessions } from '#server/app/identity/sessions'
4
4
  import { runtime } from '#server/core/http/runtime'
5
- import { setRequestUser } from '#server/core/http/session'
5
+ import { setRequestUser, waitUntilOf } from '#server/core/http/session'
6
+
7
+ const PUBLIC_ONLY_PATHS = new Set([
8
+ '/api/auth/login',
9
+ '/api/auth/login/totp',
10
+ '/api/auth/register',
11
+ '/api/auth/reset',
12
+ '/api/auth/reset/request',
13
+ '/api/auth/reset/check',
14
+ '/api/auth/email',
15
+ ])
6
16
 
7
17
  export default defineHandler(async (event) => {
8
18
  const path = getRequestURL(event).pathname
9
- if (!path.startsWith('/api/')) return
19
+ if (!path.startsWith('/api/') || path.startsWith('/api/admin/') || PUBLIC_ONLY_PATHS.has(path)) return
10
20
 
11
21
  // Reading a session creates an empty cookie when absent; skip unless the browser sent one.
12
22
  const cookieName = (useRuntimeConfig().session as { name?: string } | undefined)?.name
@@ -14,12 +24,14 @@ export default defineHandler(async (event) => {
14
24
 
15
25
  const session = await getUserSession(event)
16
26
  const sessionId = session.secure?.sessionId
17
- const user = sessionId ? await runtime.runPromise(Sessions.use((sessions) => sessions.verify(sessionId))) : undefined
27
+ const waitUntil = waitUntilOf(event)
28
+ const user = sessionId ? await runtime.runPromise(Sessions.use((sessions) => sessions.verify(sessionId, waitUntil ? { waitUntil } : undefined))) : undefined
18
29
 
19
30
  if (user && sessionId) {
20
31
  setRequestUser(event, user, sessionId)
21
32
  return
22
33
  }
23
34
 
24
- if (Object.keys(session).length > 1) await clearUserSession(event)
35
+ // Session is already missing or expired in D1; drop the stale browser cookie without triggering a redundant D1 DELETE.
36
+ if (Object.keys(session).length > 1) deleteCookie(event, cookieName, { path: '/' })
25
37
  })
@@ -1,15 +1,35 @@
1
+ import type { RequestEvent } from 'nuxt/server'
2
+
1
3
  import { definePlugin } from 'nitro'
2
4
  import { useServerHooks } from 'nuxt/server'
3
5
 
4
- import { pageCsp, withNonce } from '#server/core/http/security'
6
+ import { pageCsp, stampScriptNonces } from '#server/core/http/security'
7
+
8
+ const stampSlots = (slots: string[], nonce: string) => {
9
+ for (let i = 0; i < slots.length; i++) slots[i] = stampScriptNonces(slots[i]!, nonce)
10
+ }
5
11
 
6
- /** Per-response CSP nonce for rendered documents. Skipped in dev so Vite HMR works. */
12
+ /**
13
+ * Per-response CSP nonce stamped only onto Nuxt's framework-controlled `head` and `bodyAppend` slots —
14
+ * never `html.body`, so SSR-injected `<script>` tags never receive a valid nonce.
15
+ * Skipped in dev so Vite HMR works.
16
+ */
7
17
  export default definePlugin(() => {
8
18
  if (import.meta.dev) return
9
19
 
10
- useServerHooks().hook('render:document', (document, { event }) => {
20
+ const nonces = new WeakMap<RequestEvent, string>()
21
+ const hooks = useServerHooks()
22
+
23
+ hooks.hook('render:html', (html, { event }) => {
11
24
  const nonce = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(16))))
12
- document.html = withNonce(document.html, nonce)
25
+ nonces.set(event, nonce)
26
+ stampSlots(html.head, nonce)
27
+ stampSlots(html.bodyAppend, nonce)
13
28
  event.res.headers.set('content-security-policy', pageCsp(nonce))
14
29
  })
30
+
31
+ hooks.hook('render:html:close', (close, { event }) => {
32
+ const nonce = nonces.get(event)
33
+ if (nonce) stampSlots(close.bodyAppend, nonce)
34
+ })
15
35
  })
@@ -3,13 +3,15 @@ import { createError } from 'nuxt/server'
3
3
 
4
4
  import { Sessions } from '#server/app/identity/sessions'
5
5
  import { runtime } from '#server/core/http/runtime'
6
+ import { waitUntilOf } from '#server/core/http/session'
6
7
 
7
8
  export default definePlugin(() => {
8
- sessionHooks.hook('fetch', async (session) => {
9
+ sessionHooks.hook('fetch', async (session, event) => {
9
10
  const sessionId = session.secure?.sessionId
10
11
  if (!sessionId) return
11
12
 
12
- const user = await runtime.runPromise(Sessions.use((sessions) => sessions.verify(sessionId)))
13
+ const waitUntil = waitUntilOf(event)
14
+ const user = await runtime.runPromise(Sessions.use((sessions) => sessions.verify(sessionId, waitUntil ? { waitUntil } : undefined)))
13
15
  if (!user) throw createError({ status: 401, message: 'Please sign in again.' })
14
16
  session.user = { username: user.username, verified: user.emailStatus === 'verified' }
15
17
  })
@@ -3,11 +3,12 @@ import { HttpClientRequest, HttpClientResponse } from 'effect/http'
3
3
  import { deleteCookie, getCookie, sendRedirect } from 'nuxt/server'
4
4
 
5
5
  import { Identity } from '#server/app/identity/service'
6
+ import { setTotpChallengeCookie } from '#server/core/http/handle'
6
7
  import { runtime } from '#server/core/http/runtime'
7
8
  import { establishUserSession } from '#server/core/http/session'
8
9
  import { providerHttp } from '#server/core/platform/provider-http'
9
10
  import { UpstreamFailure } from '#server/utils/errors'
10
- import { isLocalPath } from '#shared/utils/auth'
11
+ import { isLocalPath } from '#shared/utils/paths'
11
12
 
12
13
  const GitHubEmailList = Schema.Array(
13
14
  Schema.Struct({
@@ -27,7 +28,6 @@ const nextPath = (cookie: string | undefined) => {
27
28
  }
28
29
 
29
30
  /**
30
- * Resolves the user's primary verified email explicitly via Effect's `HttpClient`:
31
31
  * `nuxt-auth-utils` only queries `/user/emails` when the public profile email is empty,
32
32
  * so when `email_verified` is absent we verify it directly.
33
33
  */
@@ -83,7 +83,8 @@ export default defineOAuthGitHubEventHandler({
83
83
  }
84
84
 
85
85
  if (result.success.status === 'totp_required') {
86
- return sendRedirect(event, `/login#totp=${encodeURIComponent(result.success.challenge)}`)
86
+ setTotpChallengeCookie(event, result.success.challenge)
87
+ return sendRedirect(event, '/login?totp=1')
87
88
  }
88
89
 
89
90
  const next = nextPath(getCookie(event, 'app_next'))
@@ -2,9 +2,10 @@ import { Effect } from 'effect'
2
2
  import { deleteCookie, getCookie, sendRedirect } from 'nuxt/server'
3
3
 
4
4
  import { Identity } from '#server/app/identity/service'
5
+ import { setTotpChallengeCookie } from '#server/core/http/handle'
5
6
  import { runtime } from '#server/core/http/runtime'
6
7
  import { establishUserSession } from '#server/core/http/session'
7
- import { isLocalPath } from '#shared/utils/auth'
8
+ import { isLocalPath } from '#shared/utils/paths'
8
9
 
9
10
  interface GoogleUser {
10
11
  readonly sub?: string
@@ -48,7 +49,8 @@ export default defineOAuthGoogleEventHandler({
48
49
  }
49
50
 
50
51
  if (result.success.status === 'totp_required') {
51
- return sendRedirect(event, `/login#totp=${encodeURIComponent(result.success.challenge)}`)
52
+ setTotpChallengeCookie(event, result.success.challenge)
53
+ return sendRedirect(event, '/login?totp=1')
52
54
  }
53
55
 
54
56
  const next = nextPath(getCookie(event, 'app_next'))
@@ -0,0 +1,15 @@
1
+ import { defineTask } from 'nitro/task'
2
+
3
+ import { Maintenance } from '#server/app/maintenance/cleanup'
4
+ import { runtime } from '#server/core/http/runtime'
5
+
6
+ export default defineTask({
7
+ meta: {
8
+ name: 'cleanup',
9
+ description: 'Purges expired sessions, one-time tokens, stale login failure rows, and abandoned unverified accounts.',
10
+ },
11
+ async run() {
12
+ const result = await runtime.runPromise(Maintenance.use((maintenance) => maintenance.purgeExpired))
13
+ return { result }
14
+ },
15
+ })
@@ -62,11 +62,13 @@ describe('database invariants', () => {
62
62
 
63
63
  // counting with 0 failures is rejected
64
64
  await expect(async () =>
65
- db.exec(`INSERT INTO login_failures (subject, status, failures, locked_until) VALUES ('u1', 'counting', 0, NULL)`),
65
+ db.exec(`INSERT INTO login_failures (subject, status, failures, locked_until, updated_at) VALUES ('u1', 'counting', 0, NULL, '${now}')`),
66
66
  ).rejects.toThrow()
67
67
 
68
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()
69
+ await expect(async () =>
70
+ db.exec(`INSERT INTO login_failures (subject, status, failures, locked_until, updated_at) VALUES ('u2', 'locked', 0, NULL, '${now}')`),
71
+ ).rejects.toThrow()
70
72
 
71
73
  // active token with used_at set is rejected
72
74
  await db.exec(