@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
@@ -15,7 +15,7 @@ import { matchesConfirm } from '#shared/utils/schema-validation'
15
15
 
16
16
  import type { AuthUser, LoginOutcome } from './state'
17
17
 
18
- import { LoginLockout } from './lockout'
18
+ import { LoginLockout, assertFailureRowUnlocked } from './lockout'
19
19
  import { Sessions } from './sessions'
20
20
  import { decodeTotpState } from './state'
21
21
  import { Totp } from './totp'
@@ -24,6 +24,21 @@ const UNCONFIRMED_HOLD_HOURS = 1
24
24
  const WRONG_LOGIN = 'Email, username, or password is not right.'
25
25
  const WRONG_CODE = 'That verification code is not valid. Use a fresh code from your authenticator app or a recovery code.'
26
26
 
27
+ const LoginLookupRow = Schema.Struct({
28
+ id: Schema.String,
29
+ username: Schema.String,
30
+ email: Schema.String,
31
+ password_hash: Schema.NullOr(Schema.String),
32
+ email_status: Schema.Literals(['unverified', 'verified']),
33
+ totp_status: Schema.Literals(['off', 'pending', 'enabled']),
34
+ totp_secret: Schema.NullOr(Schema.String),
35
+ totp_enabled_at: Schema.NullOr(Schema.String),
36
+ totp_last_step: Schema.Finite,
37
+ lock_status: Schema.NullOr(Schema.Literals(['counting', 'locked'])),
38
+ lock_failures: Schema.NullOr(Schema.Finite),
39
+ lock_until: Schema.NullOr(Schema.String),
40
+ })
41
+
27
42
  const LoginUserRow = Schema.Struct({
28
43
  id: Schema.String,
29
44
  username: Schema.String,
@@ -56,6 +71,7 @@ const MeRow = Schema.Struct({
56
71
  email_status: Schema.Literals(['unverified', 'verified']),
57
72
  has_password: Schema.Finite,
58
73
  totp_status: Schema.Literals(['off', 'pending', 'enabled']),
74
+ totp_recovery_codes_left: Schema.Finite,
59
75
  email_changed_at: Schema.NullOr(Schema.String),
60
76
  pending_email: Schema.NullOr(Schema.String),
61
77
  pending_until: Schema.NullOr(Schema.String),
@@ -204,22 +220,37 @@ export class Identity extends Context.Service<
204
220
  readonly code?: string | undefined
205
221
  }) {
206
222
  const key = input.identity.trim().toLowerCase()
207
- yield* limiter.check('sign-in-account', `login:${key}`)
208
-
209
223
  const lookupColumn = key.includes('@') ? 'email' : 'username'
210
- const user = yield* db
211
- .first(
212
- LoginUserRow,
213
- `SELECT id, username, email, password_hash, email_status, totp_status, totp_secret, totp_enabled_at, totp_last_step
214
- FROM users
215
- WHERE ${lookupColumn} = ?
216
- LIMIT 1`,
217
- [key],
218
- )
219
- .pipe(Effect.orDie)
224
+
225
+ const [, user] = yield* Effect.all(
226
+ [
227
+ limiter.check('sign-in-account', `login:${key}`),
228
+ db
229
+ .first(
230
+ LoginLookupRow,
231
+ `SELECT
232
+ u.id, u.username, u.email, u.password_hash, u.email_status,
233
+ u.totp_status, u.totp_secret, u.totp_enabled_at, u.totp_last_step,
234
+ lf.status AS lock_status, lf.failures AS lock_failures, lf.locked_until AS lock_until
235
+ FROM users u
236
+ LEFT JOIN login_failures lf ON lf.subject = 'user:' || u.id
237
+ WHERE u.${lookupColumn} = ?
238
+ LIMIT 1`,
239
+ [key],
240
+ )
241
+ .pipe(Effect.orDie),
242
+ ],
243
+ { concurrency: 'unbounded' },
244
+ )
220
245
 
221
246
  const subject = user ? `user:${user.id}` : `identity:${key}`
222
- yield* lockout.assertUnlocked(subject)
247
+ if (user) {
248
+ if (user.lock_status !== null && user.lock_failures !== null) {
249
+ yield* assertFailureRowUnlocked({ status: user.lock_status, failures: user.lock_failures, locked_until: user.lock_until })
250
+ }
251
+ } else {
252
+ yield* lockout.assertUnlocked(subject)
253
+ }
223
254
 
224
255
  const hashToVerify = user?.password_hash ?? (yield* decoy)
225
256
  const passwordOk = yield* hasher.verify(hashToVerify, input.password)
@@ -228,10 +259,11 @@ export class Identity extends Context.Service<
228
259
  return yield* new Unauthorized({ message: WRONG_LOGIN })
229
260
  }
230
261
 
262
+ const hasFailureRow = user.lock_status !== null
231
263
  const totpState = decodeTotpState(user)
232
264
  if (config.features.totp && totpState._tag === 'Enabled') {
233
265
  if (!input.code) {
234
- yield* lockout.clear(subject)
266
+ if (hasFailureRow) yield* lockout.clear(subject)
235
267
  const challenge = yield* totp.issueChallenge(user.id)
236
268
  return { status: 'totp_required', challenge } satisfies LoginOutcome
237
269
  }
@@ -239,7 +271,7 @@ export class Identity extends Context.Service<
239
271
  if (!ok) return yield* new Unauthorized({ message: WRONG_CODE })
240
272
  }
241
273
 
242
- yield* lockout.clear(subject)
274
+ if (hasFailureRow) yield* lockout.clear(subject)
243
275
  return { status: 'authenticated', user: toAuthUser(user) } satisfies LoginOutcome
244
276
  })
245
277
 
@@ -332,6 +364,7 @@ export class Identity extends Context.Service<
332
364
  u.email_status,
333
365
  u.password_hash IS NOT NULL AS has_password,
334
366
  u.totp_status,
367
+ (SELECT COUNT(*) FROM totp_recovery_codes rc WHERE rc.user_id = u.id AND rc.status = 'unused') AS totp_recovery_codes_left,
335
368
  u.email_changed_at,
336
369
  c.new_email AS pending_email,
337
370
  c.expires_at AS pending_until
@@ -355,6 +388,7 @@ export class Identity extends Context.Service<
355
388
  emailStatus: row.email_status,
356
389
  hasPassword: row.has_password > 0,
357
390
  totpStatus: row.totp_status,
391
+ totpRecoveryCodesLeft: row.totp_recovery_codes_left,
358
392
  pendingEmailChange: row.pending_email && row.pending_until ? { email: row.pending_email, expiresAt: row.pending_until } : null,
359
393
  emailChangedAt: row.email_changed_at,
360
394
  } satisfies MeView
@@ -3,6 +3,7 @@ import { Cache, Context, DateTime, Effect, Layer, Schema } from 'effect'
3
3
  import type { EmailStatus } from '#shared/utils/auth'
4
4
 
5
5
  import { AtomicBatch, type Statement } from '#server/core/db/atomic'
6
+ import { CurrentDbSession } from '#server/core/db/session'
6
7
  import { Database } from '#server/core/platform/database'
7
8
  import { IdGenerator } from '#server/core/platform/id-generator'
8
9
 
@@ -123,7 +124,7 @@ export class Sessions extends Context.Service<
123
124
  if (updates.length > 0) {
124
125
  const persist = atomic.run(updates).pipe(Effect.catch((error) => Effect.logWarning(`Session activity update failed: ${error.message}`)))
125
126
  if (options?.waitUntil) {
126
- const fiber = yield* Effect.forkDetach(persist)
127
+ const fiber = yield* Effect.forkDetach(persist.pipe(Effect.provideService(CurrentDbSession, undefined)))
127
128
  options.waitUntil(
128
129
  new Promise<void>((resolve) => {
129
130
  fiber.addObserver(() => resolve())
@@ -68,6 +68,7 @@ describe('totp explicit state machine', () => {
68
68
 
69
69
  const enabled = await run(Totp.use((t) => t.security(user.id)))
70
70
  expect(enabled).toEqual({ status: 'enabled', recoveryCodesLeft: 8 })
71
+ expect((await run(Identity.use((id) => id.me(user.id)))).totpRecoveryCodesLeft).toBe(8)
71
72
 
72
73
  // Login now requires explicit 2FA challenge
73
74
  const outcome = await run(Identity.use((id) => id.login({ identity: 'alice', password: 'correct-password' })))
@@ -40,7 +40,10 @@ const UserTotpRow = Schema.Struct({
40
40
  totp_last_step: Schema.Finite,
41
41
  })
42
42
 
43
- const CountRow = Schema.Struct({ n: Schema.Finite })
43
+ const SecurityRow = Schema.Struct({
44
+ totp_status: Schema.Literals(['off', 'pending', 'enabled']),
45
+ recovery_codes_left: Schema.Finite,
46
+ })
44
47
 
45
48
  const ChallengePayload = Schema.fromJsonString(
46
49
  Schema.Struct({
@@ -147,13 +150,20 @@ export class Totp extends Context.Service<
147
150
 
148
151
  const security = Effect.fn('Totp.security')(function* (userId: string) {
149
152
  yield* assertFeatureOn()
150
- const user = yield* loadUser(userId)
151
- const left = yield* db
152
- .first(CountRow, `SELECT COUNT(*) AS n FROM totp_recovery_codes WHERE user_id = ? AND status = 'unused'`, [userId])
153
+ const row = yield* db
154
+ .first(
155
+ SecurityRow,
156
+ `SELECT
157
+ u.totp_status,
158
+ (SELECT COUNT(*) FROM totp_recovery_codes rc WHERE rc.user_id = u.id AND rc.status = 'unused') AS recovery_codes_left
159
+ FROM users u
160
+ WHERE u.id = ?`,
161
+ [userId],
162
+ )
153
163
  .pipe(Effect.orDie)
154
164
  return {
155
- status: user?.totp_status ?? 'off',
156
- recoveryCodesLeft: left?.n ?? 0,
165
+ status: row?.totp_status ?? 'off',
166
+ recoveryCodesLeft: row?.recovery_codes_left ?? 0,
157
167
  } satisfies TotpSecurity
158
168
  })
159
169
 
@@ -1,10 +1,12 @@
1
1
  import { Context, DateTime, Effect, Layer, Schema } from 'effect'
2
2
 
3
3
  import type { RateLimited } from '#shared/domain/errors'
4
+ import type { EmailStatus } from '#shared/utils/auth'
4
5
 
5
6
  import { EmailRenderer } from '#server/app/notifications/render'
6
7
  import { verificationEmail } from '#server/app/notifications/templates'
7
8
  import { AtomicBatch, assertPreviousChanged } from '#server/core/db/atomic'
9
+ import { CurrentDbSession } from '#server/core/db/session'
8
10
  import { AppConfig } from '#server/core/platform/app-config'
9
11
  import { nowIso } from '#server/core/platform/clock'
10
12
  import { Database } from '#server/core/platform/database'
@@ -31,10 +33,17 @@ const TokenRow = Schema.Struct({
31
33
  expires_at: Schema.String,
32
34
  })
33
35
 
36
+ export interface SendVerificationOptions {
37
+ /** Skips the `SELECT users` lookup when the caller already has the freshly created/loaded user. */
38
+ readonly user?: { readonly id: string; readonly email: string; readonly emailStatus: EmailStatus }
39
+ /** Defers email rendering and delivery off the HTTP response critical path. */
40
+ readonly waitUntil?: (promise: Promise<unknown>) => void
41
+ }
42
+
34
43
  export class EmailVerification extends Context.Service<
35
44
  EmailVerification,
36
45
  {
37
- readonly send: (userId: string) => Effect.Effect<void, RateLimited>
46
+ readonly send: (userId: string, options?: SendVerificationOptions) => Effect.Effect<void, RateLimited>
38
47
  readonly confirm: (token: string) => Effect.Effect<{ readonly userId: string }, Unauthorized>
39
48
  }
40
49
  >()('app/identity/EmailVerification') {
@@ -51,8 +60,10 @@ export class EmailVerification extends Context.Service<
51
60
  const limiter = yield* RateLimiter
52
61
  const sessions = yield* Sessions
53
62
 
54
- const send = Effect.fn('EmailVerification.send')(function* (userId: string) {
55
- const user = yield* db.first(UserRow, `SELECT id, email, email_status FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
63
+ const send = Effect.fn('EmailVerification.send')(function* (userId: string, options?: SendVerificationOptions) {
64
+ const user = options?.user
65
+ ? { id: options.user.id, email: options.user.email, email_status: options.user.emailStatus }
66
+ : yield* db.first(UserRow, `SELECT id, email, email_status FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
56
67
  if (!user || user.email_status === 'verified') return
57
68
 
58
69
  yield* limiter.check('verify', yield* pii.index(user.email))
@@ -75,10 +86,21 @@ export class EmailVerification extends Context.Service<
75
86
  ])
76
87
  .pipe(Effect.orDie)
77
88
 
78
- const rendered = yield* renderer.render(verificationEmail(`${config.appUrl}/verify/${token}`, config.appName))
79
- yield* mailer
80
- .send({ to: user.email, ...rendered })
81
- .pipe(Effect.catch((error) => Effect.logWarning(`Verification email failed (${error._tag}): ${error.message}`)))
89
+ const deliver = renderer.render(verificationEmail(`${config.appUrl}/verify/${token}`, config.appName)).pipe(
90
+ Effect.flatMap((rendered) => mailer.send({ to: user.email, ...rendered })),
91
+ Effect.catch((error) => Effect.logWarning(`Verification email failed (${error._tag}): ${error.message}`)),
92
+ )
93
+
94
+ if (options?.waitUntil) {
95
+ const fiber = yield* Effect.forkDetach(deliver.pipe(Effect.provideService(CurrentDbSession, undefined)))
96
+ options.waitUntil(
97
+ new Promise<void>((resolve) => {
98
+ fiber.addObserver(() => resolve())
99
+ }),
100
+ )
101
+ } else {
102
+ yield* deliver
103
+ }
82
104
  })
83
105
 
84
106
  const confirm = Effect.fn('EmailVerification.confirm')(function* (token: string) {
@@ -5,6 +5,7 @@ import { Features } from '#server/app/features'
5
5
 
6
6
  import { AtomicBatchD1 } from './db/atomic-d1'
7
7
  import { MigratorLive } from './db/migrator'
8
+ import { DbSessionD1 } from './db/session-d1'
8
9
  import { AppConfig } from './platform/app-config'
9
10
  import { Database } from './platform/database'
10
11
  import { EmailAssets } from './platform/email-assets'
@@ -25,8 +26,8 @@ const Platform = Layer.mergeAll(Pii.layer, MailerCloudflare).pipe(
25
26
  Layer.provideMerge(Layer.mergeAll(PasswordHasher.layer, AppConfig.layer, IdGenerator.layer, Tokens.layer, Seal.layer, FetchHttpClient.layer, Bindings)),
26
27
  )
27
28
 
28
- /** Migrations run automatically on first build; feature layers sit above Foundation. */
29
- const Foundation = MigratorLive.pipe(Layer.provideMerge(Layer.mergeAll(Turnstile.layer, RateLimiterStrict).pipe(Layer.provideMerge(Platform))))
29
+ const Base = Layer.mergeAll(Turnstile.layer, RateLimiterStrict, DbSessionD1).pipe(Layer.provideMerge(Platform))
30
+ const Foundation = import.meta.dev ? MigratorLive.pipe(Layer.provideMerge(Base)) : Base
30
31
 
31
32
  export const AppLayer = Features.pipe(Layer.provideMerge(Foundation))
32
33
 
@@ -6,16 +6,22 @@ import { DatabaseError } from '#server/core/platform/database'
6
6
  import type { Applied } from './atomic'
7
7
 
8
8
  import { AtomicBatch } from './atomic'
9
+ import { CurrentDbSession } from './session'
9
10
 
10
11
  /** D1's `batch()` executes its statements in one implicit transaction: if any statement fails, none are kept. */
11
12
  export const AtomicBatchD1 = Layer.sync(AtomicBatch, () =>
12
13
  AtomicBatch.make((statements) =>
13
- Effect.tryPromise({
14
- try: async (): Promise<ReadonlyArray<Applied>> => {
15
- const results = await env.DB.batch(statements.map(({ sql, params = [] }) => env.DB.prepare(sql).bind(...params)))
16
- return results.map((result) => ({ changes: result.meta.changes }))
17
- },
18
- catch: (cause) => new DatabaseError({ sql: 'batch', message: cause instanceof Error ? cause.message : String(cause) }),
14
+ Effect.gen(function* () {
15
+ const session = yield* CurrentDbSession
16
+
17
+ return yield* Effect.tryPromise({
18
+ try: async (): Promise<ReadonlyArray<Applied>> => {
19
+ if (session) return session.batch(statements)
20
+ const results = await env.DB.batch(statements.map(({ sql, params = [] }) => env.DB.prepare(sql).bind(...params)))
21
+ return results.map((result) => ({ changes: result.meta.changes }))
22
+ },
23
+ catch: (cause) => new DatabaseError({ sql: 'batch', message: cause instanceof Error ? cause.message : String(cause) }),
24
+ })
19
25
  }),
20
26
  ),
21
27
  )
@@ -5,6 +5,8 @@ import { Context, Effect, Layer, Schema, Semaphore } from 'effect'
5
5
  import { DatabaseError } from '#server/core/platform/database'
6
6
  import { readKey } from '#shared/utils/unknown'
7
7
 
8
+ import { CurrentDbSession } from './session'
9
+
8
10
  type Param = string | number | boolean | null | undefined
9
11
 
10
12
  export interface Statement {
@@ -52,32 +54,41 @@ export class AtomicBatch extends Context.Service<
52
54
  static readonly layerFor = (db: Db0) => {
53
55
  const lock = Semaphore.makeUnsafe(1)
54
56
  const run = (statements: ReadonlyArray<Statement>) =>
55
- lock.withPermit(
56
- Effect.tryPromise({
57
- try: async () => {
58
- await db.exec('BEGIN')
59
- try {
60
- const applied: Applied[] = []
61
- for (const { sql, params = [] } of statements) {
62
- // Transaction statements execute sequentially on one SQLite connection.
63
- // oxlint-disable-next-line eslint/no-await-in-loop
64
- const result = await db
65
- .prepare(sql)
66
- .bind(...params)
67
- .run()
68
- const changes = readKey(result, 'changes')
69
- applied.push({ changes: typeof changes === 'number' || typeof changes === 'bigint' ? Number(changes) : 0 })
57
+ Effect.gen(function* () {
58
+ const session = yield* CurrentDbSession
59
+ if (session) {
60
+ return yield* Effect.tryPromise({
61
+ try: () => session.batch(statements),
62
+ catch: failure,
63
+ })
64
+ }
65
+ return yield* lock.withPermit(
66
+ Effect.tryPromise({
67
+ try: async () => {
68
+ await db.exec('BEGIN')
69
+ try {
70
+ const applied: Applied[] = []
71
+ for (const { sql, params = [] } of statements) {
72
+ // Transaction statements execute sequentially on one SQLite connection.
73
+ // oxlint-disable-next-line eslint/no-await-in-loop
74
+ const result = await db
75
+ .prepare(sql)
76
+ .bind(...params)
77
+ .run()
78
+ const changes = readKey(result, 'changes')
79
+ applied.push({ changes: typeof changes === 'number' || typeof changes === 'bigint' ? Number(changes) : 0 })
80
+ }
81
+ await db.exec('COMMIT')
82
+ return applied
83
+ } catch (error) {
84
+ await db.exec('ROLLBACK')
85
+ throw error
70
86
  }
71
- await db.exec('COMMIT')
72
- return applied
73
- } catch (error) {
74
- await db.exec('ROLLBACK')
75
- throw error
76
- }
77
- },
78
- catch: failure,
79
- }),
80
- )
87
+ },
88
+ catch: failure,
89
+ }),
90
+ )
91
+ })
81
92
 
82
93
  return Layer.succeed(AtomicBatch, AtomicBatch.make(run))
83
94
  }
@@ -153,4 +153,15 @@ export const migrations: ReadonlyArray<Migration> = [
153
153
  `CREATE INDEX idx_admin_audit_created ON admin_audit (created_at DESC)`,
154
154
  ],
155
155
  },
156
+ {
157
+ id: '0002_performance_indexes',
158
+ statements: [
159
+ `CREATE INDEX idx_users_unverified_cleanup ON users (created_at)
160
+ WHERE email_status = 'unverified' AND google_sub IS NULL AND github_id IS NULL`,
161
+ `CREATE INDEX idx_login_failures_locked_until ON login_failures (locked_until)
162
+ WHERE status = 'locked'`,
163
+ `CREATE INDEX idx_login_failures_counting_updated ON login_failures (updated_at)
164
+ WHERE status = 'counting'`,
165
+ ],
166
+ },
156
167
  ]
@@ -7,20 +7,10 @@ import { AtomicBatch } from './atomic'
7
7
  import { migrations } from './migrations'
8
8
 
9
9
  const Applied = Schema.Struct({ id: Schema.String })
10
-
11
- /**
12
- * After a deploy, several Worker isolates can start at once and race to apply a new migration.
13
- * Losers retry briefly and observe the winner's `_migrations` record; genuinely broken migrations fail fast.
14
- */
15
10
  const RACE_RETRY = Schedule.exponential('100 millis').pipe(Schedule.jittered)
16
11
 
17
- /**
18
- * Applies pending migrations automatically in local `nuxt dev` so local work stays zero-config.
19
- * Production Workers skip cold-start DDL writes — apply migrations at deploy time via `bun run db:migrate:remote`.
20
- */
21
12
  export const MigratorLive = Layer.effectDiscard(
22
13
  Effect.gen(function* () {
23
- if (!import.meta.dev) return
24
14
  const db = yield* Database
25
15
  const atomic = yield* AtomicBatch
26
16
  yield* db.run(`CREATE TABLE IF NOT EXISTS _migrations (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`)
@@ -0,0 +1,56 @@
1
+ import { env } from 'cloudflare:workers'
2
+ import { Effect, Layer } from 'effect'
3
+
4
+ import { AppConfig } from '#server/core/platform/app-config'
5
+
6
+ import type { Applied } from './atomic'
7
+
8
+ import { DbSession } from './session'
9
+
10
+ /**
11
+ * Cloudflare D1 Sessions API adapter (`env.DB.withSession`).
12
+ * Activated only when `runtimeConfig.d1Sessions` (`NUXT_D1_SESSIONS=true`) is enabled.
13
+ */
14
+ export const DbSessionD1 = Layer.effect(
15
+ DbSession,
16
+ Effect.gen(function* () {
17
+ const config = yield* AppConfig
18
+ if (!config.d1Sessions) {
19
+ return DbSession.of({
20
+ enabled: false,
21
+ withSession: (effect) => effect,
22
+ })
23
+ }
24
+
25
+ return DbSession.make((anchor) => {
26
+ const session = env.DB.withSession(anchor._tag === 'Bookmark' ? anchor.bookmark : anchor.constraint)
27
+ return {
28
+ all: async (sql, params) => {
29
+ const result = await session
30
+ .prepare(sql)
31
+ .bind(...params)
32
+ .all()
33
+ return result.results
34
+ },
35
+ first: async (sql, params) => {
36
+ const row = await session
37
+ .prepare(sql)
38
+ .bind(...params)
39
+ .first()
40
+ return row ?? undefined
41
+ },
42
+ run: async (sql, params) => {
43
+ await session
44
+ .prepare(sql)
45
+ .bind(...params)
46
+ .run()
47
+ },
48
+ batch: async (statements): Promise<ReadonlyArray<Applied>> => {
49
+ const results = await session.batch(statements.map(({ sql, params = [] }) => session.prepare(sql).bind(...params)))
50
+ return results.map((result) => ({ changes: result.meta.changes }))
51
+ },
52
+ getBookmark: () => session.getBookmark(),
53
+ }
54
+ })
55
+ }),
56
+ )
@@ -0,0 +1,97 @@
1
+ import { createDatabase } from 'db0'
2
+ import nodeSqlite from 'db0/connectors/node-sqlite'
3
+ import { Effect, Layer, Schema } from 'effect'
4
+ import { describe, expect, it } from 'vitest'
5
+
6
+ import { AtomicBatch, assertPreviousChanged } from '#server/core/db/atomic'
7
+ import { DbSession, type SessionAnchor, resolveAnchor, withDbSession } from '#server/core/db/session'
8
+ import { Database } from '#server/core/platform/database'
9
+ import { Conflict } from '#shared/domain/errors'
10
+
11
+ const ItemRow = Schema.Struct({
12
+ id: Schema.String,
13
+ label: Schema.String,
14
+ })
15
+
16
+ const makeHarness = async (enabled: boolean) => {
17
+ const db = createDatabase(nodeSqlite({ name: ':memory:' }))
18
+ await db.exec(`CREATE TABLE items (id TEXT PRIMARY KEY, label TEXT NOT NULL)`)
19
+ const anchors: SessionAnchor[] = []
20
+ const layer = Layer.mergeAll(
21
+ Database.layerFor(db),
22
+ AtomicBatch.layerFor(db),
23
+ DbSession.layerFor(db, {
24
+ enabled,
25
+ onOpen: (anchor) => anchors.push(anchor),
26
+ }),
27
+ )
28
+ const run = <A, E>(program: Effect.Effect<A, E, Layer.Success<typeof layer>>) => Effect.runPromise(program.pipe(Effect.provide(layer)))
29
+ return { run, anchors }
30
+ }
31
+
32
+ describe('DbSession / withDbSession', () => {
33
+ it('resolves explicit anchors with first-primary taking precedence over bookmarks', () => {
34
+ expect(resolveAnchor(undefined)).toEqual({ _tag: 'Constraint', constraint: 'first-unconstrained' })
35
+ expect(resolveAnchor('bm-42')).toEqual({ _tag: 'Bookmark', bookmark: 'bm-42' })
36
+ expect(resolveAnchor('bm-42', 'first-unconstrained')).toEqual({ _tag: 'Bookmark', bookmark: 'bm-42' })
37
+ expect(resolveAnchor('bm-42', 'first-primary')).toEqual({ _tag: 'Constraint', constraint: 'first-primary' })
38
+ })
39
+
40
+ it('acts as a zero-overhead passthrough when disabled', async () => {
41
+ const { run, anchors } = await makeHarness(false)
42
+ const bookmarks: string[] = []
43
+
44
+ const rows = await run(
45
+ withDbSession(
46
+ Effect.gen(function* () {
47
+ const db = yield* Database
48
+ yield* db.run(`INSERT INTO items (id, label) VALUES (?, ?)`, ['1', 'alpha'])
49
+ return yield* db.all(ItemRow, `SELECT id, label FROM items`)
50
+ }),
51
+ { bookmark: 'bm-1', onBookmark: (next) => bookmarks.push(next) },
52
+ ),
53
+ )
54
+
55
+ expect(rows).toEqual([{ id: '1', label: 'alpha' }])
56
+ expect(anchors).toEqual([])
57
+ expect(bookmarks).toEqual([])
58
+ })
59
+
60
+ it('routes Database and AtomicBatch queries through the active session and emits bookmarks even on typed failures', async () => {
61
+ const { run, anchors } = await makeHarness(true)
62
+ const bookmarks: string[] = []
63
+
64
+ const created = await run(
65
+ withDbSession(
66
+ Effect.gen(function* () {
67
+ const atomic = yield* AtomicBatch
68
+ const db = yield* Database
69
+ yield* atomic.runGuarded('insert_failed', [{ sql: `INSERT INTO items (id, label) VALUES (?, ?)`, params: ['1', 'one'] }, assertPreviousChanged])
70
+ return yield* db.first(ItemRow, `SELECT id, label FROM items WHERE id = ?`, ['1'])
71
+ }),
72
+ { onBookmark: (next) => bookmarks.push(next) },
73
+ ),
74
+ )
75
+
76
+ expect(created).toEqual({ id: '1', label: 'one' })
77
+ expect(anchors).toEqual([{ _tag: 'Constraint', constraint: 'first-unconstrained' }])
78
+ expect(bookmarks).toHaveLength(1)
79
+
80
+ // Subsequent request anchored on the returned bookmark still emits an updated bookmark even on typed failure.
81
+ const failed = await run(
82
+ withDbSession(
83
+ Effect.gen(function* () {
84
+ const db = yield* Database
85
+ yield* db.first(ItemRow, `SELECT id, label FROM items WHERE id = ?`, ['1'])
86
+ return yield* new Conflict({ message: 'already exists' })
87
+ }),
88
+ { bookmark: bookmarks[0], onBookmark: (next) => bookmarks.push(next) },
89
+ ).pipe(Effect.result),
90
+ )
91
+
92
+ expect(failed._tag).toBe('Failure')
93
+ expect(anchors[1]).toEqual({ _tag: 'Bookmark', bookmark: bookmarks[0]! })
94
+ expect(bookmarks).toHaveLength(2)
95
+ expect(bookmarks[1]).not.toBe(bookmarks[0])
96
+ })
97
+ })