@humanonlyweb/create-nuxtflare 0.2.3 → 0.2.5

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 (43) hide show
  1. package/README.md +0 -22
  2. package/dist/cli.js +2 -1
  3. package/dist/template/.github/workflows/ci.yml +19 -14
  4. package/dist/template/CLAUDE.md +3 -3
  5. package/dist/template/app/components/totp-setup.vue +18 -13
  6. package/dist/template/app/composables/use-account.ts +7 -5
  7. package/dist/template/app/composables/use-auth.ts +11 -7
  8. package/dist/template/app/pages/account.vue +2 -1
  9. package/dist/template/nuxt.config.ts +5 -2
  10. package/dist/template/package.json +3 -2
  11. package/dist/template/public/_headers +6 -0
  12. package/dist/template/scripts/migrate.ts +19 -8
  13. package/dist/template/server/api/account/index.delete.ts +1 -1
  14. package/dist/template/server/api/auth/logout-everywhere.post.ts +1 -1
  15. package/dist/template/server/api/auth/logout.post.ts +3 -11
  16. package/dist/template/server/api/auth/register.post.ts +11 -3
  17. package/dist/template/server/api/auth/verify/send.post.ts +11 -4
  18. package/dist/template/server/app/identity/lockout.ts +10 -5
  19. package/dist/template/server/app/identity/service.ts +50 -16
  20. package/dist/template/server/app/identity/sessions.ts +2 -1
  21. package/dist/template/server/app/identity/totp.test.ts +1 -0
  22. package/dist/template/server/app/identity/totp.ts +16 -6
  23. package/dist/template/server/app/identity/verification.ts +29 -7
  24. package/dist/template/server/core/app-layer.ts +3 -2
  25. package/dist/template/server/core/db/atomic-d1.ts +12 -6
  26. package/dist/template/server/core/db/atomic.ts +36 -25
  27. package/dist/template/server/core/db/migrations.ts +11 -0
  28. package/dist/template/server/core/db/migrator.ts +0 -10
  29. package/dist/template/server/core/db/session-d1.ts +56 -0
  30. package/dist/template/server/core/db/session.test.ts +97 -0
  31. package/dist/template/server/core/db/session.ts +171 -0
  32. package/dist/template/server/core/http/handle.ts +13 -3
  33. package/dist/template/server/core/http/session.ts +49 -1
  34. package/dist/template/server/core/platform/app-config.ts +2 -0
  35. package/dist/template/server/core/platform/database.ts +39 -22
  36. package/dist/template/server/middleware/01-user-session.ts +11 -2
  37. package/dist/template/server/plugins/page-csp.ts +1 -1
  38. package/dist/template/server/plugins/sessions.ts +16 -4
  39. package/dist/template/server/test/kit.ts +4 -0
  40. package/dist/template/shared/utils/auth.ts +1 -0
  41. package/dist/template/wrangler.json +3 -0
  42. package/package.json +1 -1
  43. /package/dist/template/app/components/{qr-code.vue → qr-code.client.vue} +0 -0
@@ -0,0 +1,171 @@
1
+ import type { Database as Db0 } from 'db0'
2
+
3
+ import { Context, Effect, Layer } from 'effect'
4
+
5
+ import { readKey } from '#shared/utils/unknown'
6
+
7
+ import type { Applied, Statement } from './atomic'
8
+
9
+ export type DbParam = string | number | boolean | null | undefined
10
+
11
+ /** Initial D1 routing constraint when no client bookmark is supplied. */
12
+ export type SessionConstraint = 'first-primary' | 'first-unconstrained'
13
+
14
+ /** Explicit D1 session anchor: either a prior bookmark or a fresh consistency constraint. */
15
+ export type SessionAnchor = { readonly _tag: 'Bookmark'; readonly bookmark: string } | { readonly _tag: 'Constraint'; readonly constraint: SessionConstraint }
16
+
17
+ export const resolveAnchor = (bookmark: string | undefined, constraint: SessionConstraint = 'first-unconstrained'): SessionAnchor =>
18
+ constraint === 'first-primary'
19
+ ? { _tag: 'Constraint', constraint: 'first-primary' }
20
+ : bookmark
21
+ ? { _tag: 'Bookmark', bookmark }
22
+ : { _tag: 'Constraint', constraint }
23
+
24
+ export interface DbSessionHandle {
25
+ readonly all: (sql: string, params: ReadonlyArray<DbParam>) => Promise<ReadonlyArray<unknown>>
26
+ readonly first: (sql: string, params: ReadonlyArray<DbParam>) => Promise<unknown>
27
+ readonly run: (sql: string, params: ReadonlyArray<DbParam>) => Promise<void>
28
+ readonly batch: (statements: ReadonlyArray<Statement>) => Promise<ReadonlyArray<Applied>>
29
+ readonly getBookmark: () => string | null
30
+ }
31
+
32
+ /**
33
+ * Fiber-local active D1 session. Automatically used by `Database` and `AtomicBatch` when set.
34
+ * Detached background work (`waitUntil`) should clear this reference so it never races with the request bookmark.
35
+ */
36
+ export const CurrentDbSession = Context.Reference<DbSessionHandle | undefined>('app/db/CurrentDbSession', {
37
+ defaultValue: () => undefined,
38
+ })
39
+
40
+ export interface WithSessionOptions {
41
+ /** Bookmark from a prior request (cookie or `x-d1-bookmark` header) for read-your-writes consistency. */
42
+ readonly bookmark?: string | undefined
43
+ /** Initial routing constraint when no bookmark is supplied, or `'first-primary'` to force primary routing. Defaults to `'first-unconstrained'`. */
44
+ readonly constraint?: SessionConstraint | undefined
45
+ /** Invoked after the effect settles whenever the session produced a bookmark. */
46
+ readonly onBookmark?: ((bookmark: string) => void) | undefined
47
+ }
48
+
49
+ /**
50
+ * Optional Cloudflare D1 Sessions API (`env.DB.withSession`) port for global read replication.
51
+ * Disabled by default (`d1Sessions: false`); when enabled, all `Database` and `AtomicBatch` calls inside
52
+ * `withDbSession` share one sequentially consistent session and emit an updated bookmark.
53
+ */
54
+ export class DbSession extends Context.Service<
55
+ DbSession,
56
+ {
57
+ readonly enabled: boolean
58
+ readonly withSession: <A, E, R>(effect: Effect.Effect<A, E, R>, options?: WithSessionOptions) => Effect.Effect<A, E, R>
59
+ }
60
+ >()('app/platform/DbSession') {
61
+ static readonly disabled = Layer.succeed(
62
+ DbSession,
63
+ DbSession.of({
64
+ enabled: false,
65
+ withSession: (effect) => effect,
66
+ }),
67
+ )
68
+
69
+ static readonly make = (open: (anchor: SessionAnchor) => DbSessionHandle) =>
70
+ DbSession.of({
71
+ enabled: true,
72
+ withSession: (effect, options) =>
73
+ Effect.suspend(() => {
74
+ const handle = open(resolveAnchor(options?.bookmark, options?.constraint))
75
+ return effect.pipe(
76
+ Effect.provideService(CurrentDbSession, handle),
77
+ Effect.ensuring(
78
+ Effect.sync(() => {
79
+ const next = handle.getBookmark()
80
+ if (next && options?.onBookmark) options.onBookmark(next)
81
+ }),
82
+ ),
83
+ )
84
+ }),
85
+ })
86
+
87
+ /** Test/SQLite adapter over `db0`: runs queries against local SQLite and emits synthetic monotonic bookmarks. */
88
+ static readonly layerFor = (
89
+ db: Db0,
90
+ options: {
91
+ readonly enabled?: boolean
92
+ readonly onOpen?: (anchor: SessionAnchor) => void
93
+ } = {},
94
+ ) => {
95
+ if (options.enabled === false) return DbSession.disabled
96
+ let txQueue: Promise<unknown> = Promise.resolve()
97
+ const serializeTx = <A>(work: () => Promise<A>): Promise<A> => {
98
+ const next = txQueue.then(work, work)
99
+ txQueue = next.then(
100
+ () => undefined,
101
+ () => undefined,
102
+ )
103
+ return next
104
+ }
105
+ let version = 0
106
+ return Layer.succeed(
107
+ DbSession,
108
+ DbSession.make((anchor) => {
109
+ options.onOpen?.(anchor)
110
+ let bookmark: string | null = anchor._tag === 'Bookmark' ? anchor.bookmark : null
111
+ const touch = () => {
112
+ version += 1
113
+ bookmark = `sqlite-bm-${version}`
114
+ }
115
+ return {
116
+ all: async (sql, params) => {
117
+ const rows = await db
118
+ .prepare(sql)
119
+ .bind(...params)
120
+ .all()
121
+ touch()
122
+ return rows
123
+ },
124
+ first: async (sql, params) => {
125
+ const row = await db
126
+ .prepare(sql)
127
+ .bind(...params)
128
+ .get()
129
+ touch()
130
+ return row
131
+ },
132
+ run: async (sql, params) => {
133
+ await db
134
+ .prepare(sql)
135
+ .bind(...params)
136
+ .run()
137
+ touch()
138
+ },
139
+ batch: (statements) =>
140
+ serializeTx(async () => {
141
+ await db.exec('BEGIN')
142
+ try {
143
+ const applied: Applied[] = []
144
+ for (const { sql, params = [] } of statements) {
145
+ // Transaction statements execute sequentially on one SQLite connection.
146
+ // oxlint-disable-next-line eslint/no-await-in-loop
147
+ const result = await db
148
+ .prepare(sql)
149
+ .bind(...params)
150
+ .run()
151
+ const changes = readKey(result, 'changes')
152
+ applied.push({ changes: typeof changes === 'number' || typeof changes === 'bigint' ? Number(changes) : 0 })
153
+ }
154
+ await db.exec('COMMIT')
155
+ touch()
156
+ return applied
157
+ } catch (error) {
158
+ await db.exec('ROLLBACK')
159
+ throw error
160
+ }
161
+ }),
162
+ getBookmark: () => bookmark,
163
+ }
164
+ }),
165
+ )
166
+ }
167
+ }
168
+
169
+ /** Runs `effect` inside a D1 read-replication session when `d1Sessions` is enabled; no-op passthrough otherwise. */
170
+ export const withDbSession = <A, E, R>(effect: Effect.Effect<A, E, R>, options?: WithSessionOptions): Effect.Effect<A, E, R | DbSession> =>
171
+ DbSession.use((sessions) => sessions.withSession(effect, options))
@@ -5,6 +5,7 @@ import { Cause, Data, Effect, Exit, Schema } from 'effect'
5
5
  import { createError, defineHandler, deleteCookie, getCookie, setCookie, setResponseStatus } from 'nuxt/server'
6
6
 
7
7
  import type { AppServices } from '#server/core/app-layer'
8
+ import type { SessionConstraint } from '#server/core/db/session'
8
9
  import type { LimitName } from '#server/core/platform/rate-limiter'
9
10
  import type { ServiceNotConfigured, UpstreamFailure } from '#server/utils/errors'
10
11
  import type { Conflict, NotFound, RateLimited, TooLarge, Unprocessable } from '#shared/domain/errors'
@@ -20,7 +21,7 @@ import { readKey } from '#shared/utils/unknown'
20
21
 
21
22
  import { runtime } from './runtime'
22
23
  import { UNSAFE_METHODS, isSameOriginRequest, isWithheld, limitKeyOf, publicFailure } from './security'
23
- import { UserActor, requestUser } from './session'
24
+ import { UserActor, requestUser, withRequestDbSession } from './session'
24
25
 
25
26
  export type ApiFailure = NotFound | Conflict | Unprocessable | TooLarge | Unauthorized | Forbidden | RateLimited | ServiceNotConfigured | UpstreamFailure
26
27
 
@@ -63,6 +64,8 @@ export interface RouteSchemas {
63
64
  readonly response?: AnySchema
64
65
  readonly limit?: LimitName
65
66
  readonly captcha?: boolean
67
+ /** D1 read-replication session constraint when `d1Sessions` is enabled (`false` to bypass). */
68
+ readonly dbSession?: SessionConstraint | false
66
69
  }
67
70
 
68
71
  type Part<K extends string, S> = S extends AnySchema ? { readonly [P in K]: S['Type'] } : unknown
@@ -112,8 +115,11 @@ const runEffect = async <A>(
112
115
  event: RequestEvent,
113
116
  program: Effect.Effect<A, ApiFailure | Schema.SchemaError | RequestValidationError, AppServices>,
114
117
  audience: Audience,
118
+ dbSession?: SessionConstraint | false,
115
119
  ): Promise<A> => {
116
- const exit = await runtime.runPromiseExit(program.pipe(Effect.annotateLogs({ method: event.req.method, path: logPath(event.req.url) })))
120
+ const exit = await runtime.runPromiseExit(
121
+ withRequestDbSession(event, program, dbSession).pipe(Effect.annotateLogs({ method: event.req.method, path: logPath(event.req.url) })),
122
+ )
117
123
 
118
124
  if (Exit.isSuccess(exit)) return exit.value
119
125
 
@@ -139,8 +145,9 @@ export const respond = async <D extends RouteSchemas>(
139
145
  event: RequestEvent,
140
146
  program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError | RequestValidationError, AppServices>,
141
147
  audience: Audience,
148
+ dbSession?: SessionConstraint | false,
142
149
  ): Promise<OutputOf<D>> => {
143
- const value = await runEffect(event, program, audience)
150
+ const value = await runEffect(event, program, audience, dbSession)
144
151
  // Encoded by the route's response schema.
145
152
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion
146
153
  return value as OutputOf<D>
@@ -165,6 +172,7 @@ export const handlePublic = <const D extends RouteSchemas>(
165
172
  return encode ? yield* encode(out) : out
166
173
  }),
167
174
  'public',
175
+ schemas.dbSession,
168
176
  )
169
177
  if (!schemas.response) setResponseStatus(event, 204)
170
178
  return value
@@ -206,6 +214,7 @@ export const handleAuthed = <const D extends RouteSchemas>(
206
214
  return encode ? yield* encode(out) : out
207
215
  }),
208
216
  'authed',
217
+ schemas.dbSession,
209
218
  )
210
219
  if (!schemas.response) setResponseStatus(event, 204)
211
220
  return value
@@ -242,6 +251,7 @@ export const handleAdmin = <const D extends RouteSchemas>(
242
251
  return encode ? yield* encode(out) : out
243
252
  }),
244
253
  'authed',
254
+ schemas.dbSession,
245
255
  )
246
256
  if (!schemas.response) setResponseStatus(event, 204)
247
257
  return value
@@ -1,10 +1,54 @@
1
1
  import type { RequestEvent } from 'nuxt/server'
2
2
 
3
3
  import { Context, Effect } from 'effect'
4
+ import { getCookie, setCookie } from 'nuxt/server'
4
5
 
6
+ import type { SessionConstraint } from '#server/core/db/session'
7
+
8
+ import { isLocalHost } from '#server/app/admin/auth'
5
9
  import { Sessions } from '#server/app/identity/sessions'
10
+ import { DbSession } from '#server/core/db/session'
6
11
  import { readKey } from '#shared/utils/unknown'
7
12
 
13
+ export const D1_BOOKMARK_COOKIE = 'app_d1_bm'
14
+ export const D1_BOOKMARK_HEADER = 'x-d1-bookmark'
15
+ const D1_BOOKMARK_MAX_AGE_SECONDS = 60
16
+
17
+ const requestBookmarks = new WeakMap<RequestEvent, string>()
18
+ const revokedEvents = new WeakSet<RequestEvent>()
19
+
20
+ export const isSessionRevokedOnEvent = (event: RequestEvent): boolean => revokedEvents.has(event)
21
+
22
+ /** Wraps an Effect in a request-scoped D1 read-replication session when `d1Sessions` is enabled; zero-cost passthrough otherwise. */
23
+ export const withRequestDbSession = <A, E, R>(
24
+ event: RequestEvent,
25
+ program: Effect.Effect<A, E, R>,
26
+ policy?: SessionConstraint | false,
27
+ ): Effect.Effect<A, E, R | DbSession> => {
28
+ if (policy === false) return program
29
+ return DbSession.use((sessions) => {
30
+ if (!sessions.enabled) return program
31
+ const incoming = requestBookmarks.get(event) ?? event.req.headers.get(D1_BOOKMARK_HEADER) ?? getCookie(event, D1_BOOKMARK_COOKIE) ?? undefined
32
+ return sessions.withSession(program, {
33
+ bookmark: incoming,
34
+ constraint: policy,
35
+ onBookmark: (next) => {
36
+ requestBookmarks.set(event, next)
37
+ event.res.headers.set(D1_BOOKMARK_HEADER, next)
38
+ if (next !== incoming) {
39
+ setCookie(event, D1_BOOKMARK_COOKIE, next, {
40
+ httpOnly: true,
41
+ secure: !isLocalHost(event.req.url),
42
+ sameSite: 'lax',
43
+ path: '/',
44
+ maxAge: D1_BOOKMARK_MAX_AGE_SECONDS,
45
+ })
46
+ }
47
+ },
48
+ })
49
+ })
50
+ }
51
+
8
52
  interface WaitUntilHost {
9
53
  readonly waitUntil: (promise: Promise<unknown>) => void
10
54
  }
@@ -85,4 +129,8 @@ export const establishUserSession = (
85
129
  export const updateUserSessionMetadata = (event: RequestEvent, user: { readonly username: string; readonly emailStatus: 'unverified' | 'verified' }) =>
86
130
  Effect.promise(() => setUserSession(event, { user: { username: user.username, verified: user.emailStatus === 'verified' } }))
87
131
 
88
- export const endUserSession = (event: RequestEvent) => Effect.promise(() => clearUserSession(event))
132
+ export const endUserSession = (event: RequestEvent, options?: { readonly alreadyRevoked?: boolean }) =>
133
+ Effect.promise(() => {
134
+ if (options?.alreadyRevoked) revokedEvents.add(event)
135
+ return clearUserSession(event)
136
+ })
@@ -20,6 +20,7 @@ export interface Settings {
20
20
  readonly turnstileSecret: Redacted.Redacted
21
21
  readonly turnstileRequired: boolean
22
22
  readonly rateLimitScale: number
23
+ readonly d1Sessions: boolean
23
24
  readonly adminEmails: string
24
25
  readonly features: FeatureFlags
25
26
  }
@@ -42,6 +43,7 @@ export class AppConfig extends Context.Service<AppConfig, Settings>()('app/platf
42
43
  turnstileSecret: Redacted.make(config.turnstileSecret),
43
44
  turnstileRequired: config.turnstileRequired,
44
45
  rateLimitScale: config.rateLimitScale,
46
+ d1Sessions: config.d1Sessions,
45
47
  adminEmails: config.adminEmails,
46
48
  features: {
47
49
  totp: config.public.features.totp,
@@ -3,6 +3,8 @@ import type { Database as Db0 } from 'db0'
3
3
  import { Context, Effect, Layer, Schedule, Schema } from 'effect'
4
4
  import { useDatabase } from 'nitro/database'
5
5
 
6
+ import { CurrentDbSession } from '#server/core/db/session'
7
+
6
8
  export class DatabaseError extends Schema.TaggedError<DatabaseError, { readonly brand: unique symbol }>()('DatabaseError', {
7
9
  message: Schema.String,
8
10
  sql: Schema.String,
@@ -38,25 +40,35 @@ export class Database extends Context.Service<
38
40
  const failure = (sql: string) => (cause: unknown) => new DatabaseError({ sql, message: cause instanceof Error ? cause.message : String(cause) })
39
41
 
40
42
  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),
43
+ const query = Effect.gen(function* () {
44
+ const session = yield* CurrentDbSession
45
+ return yield* Effect.tryPromise({
46
+ try: () =>
47
+ session
48
+ ? session.all(sql, params)
49
+ : db
50
+ .prepare(sql)
51
+ .bind(...params)
52
+ .all(),
53
+ catch: failure(sql),
54
+ })
48
55
  })
49
56
  return isReadQuery(sql) ? query.pipe(Effect.retry({ schedule: READ_RETRY, times: 2, while: isTransient })) : query
50
57
  }
51
58
 
52
59
  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
+ const query = Effect.gen(function* () {
61
+ const session = yield* CurrentDbSession
62
+ return yield* Effect.tryPromise({
63
+ try: () =>
64
+ session
65
+ ? session.first(sql, params)
66
+ : db
67
+ .prepare(sql)
68
+ .bind(...params)
69
+ .get(),
70
+ catch: failure(sql),
71
+ })
60
72
  })
61
73
  return isReadQuery(sql) ? query.pipe(Effect.retry({ schedule: READ_RETRY, times: 2, while: isTransient })) : query
62
74
  }
@@ -78,15 +90,20 @@ export class Database extends Context.Service<
78
90
  Effect.withSpan('Database.first'),
79
91
  )
80
92
 
81
- const run = (sql: string, params: ReadonlyArray<Param> = []) =>
82
- Effect.tryPromise({
83
- try: () =>
84
- db
85
- .prepare(sql)
86
- .bind(...params)
87
- .run(),
93
+ const run = Effect.fn('Database.run')(function* (sql: string, params: ReadonlyArray<Param> = []) {
94
+ const session = yield* CurrentDbSession
95
+ yield* Effect.tryPromise({
96
+ try: async () => {
97
+ if (session) await session.run(sql, params)
98
+ else
99
+ await db
100
+ .prepare(sql)
101
+ .bind(...params)
102
+ .run()
103
+ },
88
104
  catch: failure(sql),
89
- }).pipe(Effect.asVoid, Effect.withSpan('Database.run'))
105
+ })
106
+ })
90
107
 
91
108
  return Database.of({ all, first, run })
92
109
  }
@@ -2,11 +2,13 @@ import { defineHandler, deleteCookie, getRequestURL, useRuntimeConfig } from 'nu
2
2
 
3
3
  import { Sessions } from '#server/app/identity/sessions'
4
4
  import { runtime } from '#server/core/http/runtime'
5
- import { setRequestUser, waitUntilOf } from '#server/core/http/session'
5
+ import { setRequestUser, waitUntilOf, withRequestDbSession } from '#server/core/http/session'
6
6
 
7
7
  const PUBLIC_ONLY_PATHS = new Set([
8
+ '/api/_auth/session',
8
9
  '/api/auth/login',
9
10
  '/api/auth/login/totp',
11
+ '/api/auth/logout',
10
12
  '/api/auth/register',
11
13
  '/api/auth/reset',
12
14
  '/api/auth/reset/request',
@@ -25,7 +27,14 @@ export default defineHandler(async (event) => {
25
27
  const session = await getUserSession(event)
26
28
  const sessionId = session.secure?.sessionId
27
29
  const waitUntil = waitUntilOf(event)
28
- const user = sessionId ? await runtime.runPromise(Sessions.use((sessions) => sessions.verify(sessionId, waitUntil ? { waitUntil } : undefined))) : undefined
30
+ const user = sessionId
31
+ ? await runtime.runPromise(
32
+ withRequestDbSession(
33
+ event,
34
+ Sessions.use((sessions) => sessions.verify(sessionId, waitUntil ? { waitUntil } : undefined)),
35
+ ),
36
+ )
37
+ : undefined
29
38
 
30
39
  if (user && sessionId) {
31
40
  setRequestUser(event, user, sessionId)
@@ -15,7 +15,7 @@ const stampSlots = (slots: string[], nonce: string) => {
15
15
  * Skipped in dev so Vite HMR works.
16
16
  */
17
17
  export default definePlugin(() => {
18
- if (import.meta.dev) return
18
+ if (import.meta.dev || import.meta.prerender) return
19
19
 
20
20
  const nonces = new WeakMap<RequestEvent, string>()
21
21
  const hooks = useServerHooks()
@@ -3,7 +3,7 @@ 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
+ import { isSessionRevokedOnEvent, waitUntilOf, withRequestDbSession } from '#server/core/http/session'
7
7
 
8
8
  export default definePlugin(() => {
9
9
  sessionHooks.hook('fetch', async (session, event) => {
@@ -11,13 +11,25 @@ export default definePlugin(() => {
11
11
  if (!sessionId) return
12
12
 
13
13
  const waitUntil = waitUntilOf(event)
14
- const user = await runtime.runPromise(Sessions.use((sessions) => sessions.verify(sessionId, waitUntil ? { waitUntil } : undefined)))
14
+ const user = await runtime.runPromise(
15
+ withRequestDbSession(
16
+ event,
17
+ Sessions.use((sessions) => sessions.verify(sessionId, waitUntil ? { waitUntil } : undefined)),
18
+ ),
19
+ )
15
20
  if (!user) throw createError({ status: 401, message: 'Please sign in again.' })
16
21
  session.user = { username: user.username, verified: user.emailStatus === 'verified' }
17
22
  })
18
23
 
19
- sessionHooks.hook('clear', async (session) => {
24
+ sessionHooks.hook('clear', async (session, event) => {
25
+ if (isSessionRevokedOnEvent(event)) return
20
26
  const sessionId = session.secure?.sessionId
21
- if (sessionId) await runtime.runPromise(Sessions.use((sessions) => sessions.end(sessionId)))
27
+ if (sessionId)
28
+ await runtime.runPromise(
29
+ withRequestDbSession(
30
+ event,
31
+ Sessions.use((sessions) => sessions.end(sessionId)),
32
+ ),
33
+ )
22
34
  })
23
35
  })
@@ -9,6 +9,7 @@ import type { Mail } from '#server/core/platform/mailer'
9
9
  import { Features } from '#server/app/features'
10
10
  import { AtomicBatch } from '#server/core/db/atomic'
11
11
  import { migrations } from '#server/core/db/migrations'
12
+ import { DbSession } from '#server/core/db/session'
12
13
  import { AppConfig } from '#server/core/platform/app-config'
13
14
  import { Database } from '#server/core/platform/database'
14
15
  import { IdGenerator } from '#server/core/platform/id-generator'
@@ -34,6 +35,7 @@ export const testConfig = (overrides: Partial<Omit<Settings, 'features'>> & { re
34
35
  turnstileSecret: Redacted.make(''),
35
36
  turnstileRequired: false,
36
37
  rateLimitScale: 1,
38
+ d1Sessions: false,
37
39
  adminEmails: 'admin@starter.test',
38
40
  ...overrides,
39
41
  features: {
@@ -53,6 +55,7 @@ export const makeTestLayer = async (
53
55
  readonly turnstile?: Layer.Layer<Turnstile>
54
56
  readonly mailer?: Layer.Layer<Mailer>
55
57
  readonly limiter?: Layer.Layer<RateLimiter>
58
+ readonly dbSession?: Layer.Layer<DbSession>
56
59
  } = {},
57
60
  ) => {
58
61
  const db = createDatabase(nodeSqlite({ name: ':memory:' }))
@@ -64,6 +67,7 @@ export const makeTestLayer = async (
64
67
  const platform = Layer.mergeAll(
65
68
  Database.layerFor(db),
66
69
  AtomicBatch.layerFor(db),
70
+ options.dbSession ?? DbSession.disabled,
67
71
  IdGenerator.sequential(),
68
72
  Tokens.layer,
69
73
  Kv.memory(),
@@ -60,6 +60,7 @@ export const MeView = Schema.Struct({
60
60
  emailStatus: EmailStatus,
61
61
  hasPassword: Schema.Boolean,
62
62
  totpStatus: TotpStatus,
63
+ totpRecoveryCodesLeft: Schema.Int,
63
64
  pendingEmailChange: Schema.NullOr(PendingEmailChangeView),
64
65
  emailChangedAt: Schema.NullOr(Schema.String),
65
66
  })
@@ -4,6 +4,9 @@
4
4
  "main": "./server.ts",
5
5
  "compatibility_date": "2026-11-11",
6
6
  "compatibility_flags": ["nodejs_compat", "temporal", "global_fetch_strictly_public"],
7
+ "placement": {
8
+ "mode": "smart"
9
+ },
7
10
  "observability": {
8
11
  "enabled": true,
9
12
  "logs": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@humanonlyweb/create-nuxtflare",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "Scaffold a Nuxt 5 + Cloudflare Workers + D1 + Effect v4 app with explicit auth, TOTP 2FA, and admin.",
5
5
  "keywords": [
6
6
  "cloudflare",