@humanonlyweb/create-nuxtflare 0.0.0-stage → 0.1.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 (138) hide show
  1. package/README.md +55 -2
  2. package/dist/cli.js +322 -0
  3. package/dist/template/.env.example +22 -0
  4. package/dist/template/.github/workflows/ci.yml +96 -0
  5. package/dist/template/.oxfmtrc.json +18 -0
  6. package/dist/template/.oxlintrc.json +69 -0
  7. package/dist/template/CLAUDE.md +42 -0
  8. package/dist/template/_gitignore +14 -0
  9. package/dist/template/app/app.vue +3 -0
  10. package/dist/template/app/components/qr-code.vue +36 -0
  11. package/dist/template/app/components/totp-setup.vue +151 -0
  12. package/dist/template/app/composables/use-features.ts +1 -0
  13. package/dist/template/app/composables/use-me.ts +10 -0
  14. package/dist/template/app/middleware/admin.global.ts +12 -0
  15. package/dist/template/app/middleware/auth.ts +6 -0
  16. package/dist/template/app/middleware/guest.ts +4 -0
  17. package/dist/template/app/pages/account.vue +22 -0
  18. package/dist/template/app/pages/admin/index.vue +16 -0
  19. package/dist/template/app/pages/admin/login.vue +39 -0
  20. package/dist/template/app/pages/index.vue +18 -0
  21. package/dist/template/app/pages/login.vue +110 -0
  22. package/dist/template/app/pages/register.vue +51 -0
  23. package/dist/template/app/utils/api-error.ts +50 -0
  24. package/dist/template/nuxt.config.ts +115 -0
  25. package/dist/template/package.json +59 -0
  26. package/dist/template/scripts/admin-password.ts +123 -0
  27. package/dist/template/server/api/account/email/index.delete.ts +5 -0
  28. package/dist/template/server/api/account/email/index.post.ts +8 -0
  29. package/dist/template/server/api/account/index.delete.ts +18 -0
  30. package/dist/template/server/api/account/index.patch.ts +16 -0
  31. package/dist/template/server/api/account/sessions.get.ts +11 -0
  32. package/dist/template/server/api/account/totp/cancel.post.ts +5 -0
  33. package/dist/template/server/api/account/totp/confirm.post.ts +10 -0
  34. package/dist/template/server/api/account/totp/disable.post.ts +8 -0
  35. package/dist/template/server/api/account/totp/index.get.ts +6 -0
  36. package/dist/template/server/api/account/totp/start.post.ts +8 -0
  37. package/dist/template/server/api/admin/me.get.ts +7 -0
  38. package/dist/template/server/api/admin/session/index.delete.ts +12 -0
  39. package/dist/template/server/api/admin/session/index.post.ts +18 -0
  40. package/dist/template/server/api/auth/email/index.post.ts +13 -0
  41. package/dist/template/server/api/auth/login/totp.post.ts +15 -0
  42. package/dist/template/server/api/auth/login.post.ts +17 -0
  43. package/dist/template/server/api/auth/logout-everywhere.post.ts +17 -0
  44. package/dist/template/server/api/auth/logout.post.ts +14 -0
  45. package/dist/template/server/api/auth/register.post.ts +18 -0
  46. package/dist/template/server/api/auth/reset/check.post.ts +5 -0
  47. package/dist/template/server/api/auth/reset/index.post.ts +5 -0
  48. package/dist/template/server/api/auth/reset/request.post.ts +5 -0
  49. package/dist/template/server/api/auth/verify/index.post.ts +17 -0
  50. package/dist/template/server/api/auth/verify/send.post.ts +7 -0
  51. package/dist/template/server/api/me.get.ts +8 -0
  52. package/dist/template/server/app/admin/auth.test.ts +41 -0
  53. package/dist/template/server/app/admin/auth.ts +133 -0
  54. package/dist/template/server/app/features.ts +18 -0
  55. package/dist/template/server/app/identity/email-change.ts +147 -0
  56. package/dist/template/server/app/identity/identity.test.ts +119 -0
  57. package/dist/template/server/app/identity/lockout.ts +93 -0
  58. package/dist/template/server/app/identity/password-reset.ts +119 -0
  59. package/dist/template/server/app/identity/service.ts +379 -0
  60. package/dist/template/server/app/identity/sessions.ts +141 -0
  61. package/dist/template/server/app/identity/state.ts +41 -0
  62. package/dist/template/server/app/identity/totp-crypto.ts +89 -0
  63. package/dist/template/server/app/identity/totp.test.ts +103 -0
  64. package/dist/template/server/app/identity/totp.ts +361 -0
  65. package/dist/template/server/app/identity/verification.ts +120 -0
  66. package/dist/template/server/app/notifications/email.ts +12 -0
  67. package/dist/template/server/app/notifications/render.test.ts +26 -0
  68. package/dist/template/server/app/notifications/render.ts +82 -0
  69. package/dist/template/server/app/notifications/samples.ts +11 -0
  70. package/dist/template/server/app/notifications/templates.ts +37 -0
  71. package/dist/template/server/assets/email/blocks/button.html +1 -0
  72. package/dist/template/server/assets/email/blocks/lead.html +1 -0
  73. package/dist/template/server/assets/email/blocks/note.html +1 -0
  74. package/dist/template/server/assets/email/blocks/text.html +1 -0
  75. package/dist/template/server/assets/email/layout.html +22 -0
  76. package/dist/template/server/cloudflare/exports/rate-limit.do.ts +38 -0
  77. package/dist/template/server/core/app-layer.ts +33 -0
  78. package/dist/template/server/core/db/atomic-d1.ts +21 -0
  79. package/dist/template/server/core/db/atomic.ts +86 -0
  80. package/dist/template/server/core/db/chunked.ts +13 -0
  81. package/dist/template/server/core/db/migrations.ts +149 -0
  82. package/dist/template/server/core/db/migrator.ts +39 -0
  83. package/dist/template/server/core/http/body-limit.ts +35 -0
  84. package/dist/template/server/core/http/csrf.ts +16 -0
  85. package/dist/template/server/core/http/device-label.ts +27 -0
  86. package/dist/template/server/core/http/handle.ts +271 -0
  87. package/dist/template/server/core/http/limit-key.ts +17 -0
  88. package/dist/template/server/core/http/page-csp.ts +16 -0
  89. package/dist/template/server/core/http/public-failure.ts +9 -0
  90. package/dist/template/server/core/http/request-user.ts +13 -0
  91. package/dist/template/server/core/http/runtime.ts +30 -0
  92. package/dist/template/server/core/http/session-cookie.ts +29 -0
  93. package/dist/template/server/core/platform/app-config.ts +55 -0
  94. package/dist/template/server/core/platform/clock.ts +4 -0
  95. package/dist/template/server/core/platform/database.ts +78 -0
  96. package/dist/template/server/core/platform/email-assets.ts +32 -0
  97. package/dist/template/server/core/platform/id-generator.ts +29 -0
  98. package/dist/template/server/core/platform/kv.ts +54 -0
  99. package/dist/template/server/core/platform/mailer-cloudflare.ts +51 -0
  100. package/dist/template/server/core/platform/mailer.ts +21 -0
  101. package/dist/template/server/core/platform/password-hasher.ts +27 -0
  102. package/dist/template/server/core/platform/pii.ts +80 -0
  103. package/dist/template/server/core/platform/provider-http.ts +21 -0
  104. package/dist/template/server/core/platform/rate-limiter-strict.ts +42 -0
  105. package/dist/template/server/core/platform/rate-limiter.ts +35 -0
  106. package/dist/template/server/core/platform/runtime-config-schema.ts +15 -0
  107. package/dist/template/server/core/platform/seal.ts +68 -0
  108. package/dist/template/server/core/platform/sliding-window.ts +39 -0
  109. package/dist/template/server/core/platform/tokens.ts +36 -0
  110. package/dist/template/server/core/platform/turnstile.ts +61 -0
  111. package/dist/template/server/middleware/00-body-limit.ts +10 -0
  112. package/dist/template/server/middleware/00-security-headers.ts +19 -0
  113. package/dist/template/server/middleware/01-user-session.ts +25 -0
  114. package/dist/template/server/plugins/page-csp.ts +15 -0
  115. package/dist/template/server/plugins/sessions.ts +21 -0
  116. package/dist/template/server/routes/(dev)/emails.get.dev.ts +37 -0
  117. package/dist/template/server/routes/auth/github.get.ts +96 -0
  118. package/dist/template/server/routes/auth/google.get.ts +61 -0
  119. package/dist/template/server/test/email-assets.ts +8 -0
  120. package/dist/template/server/test/invariants.test.ts +83 -0
  121. package/dist/template/server/test/kit.ts +83 -0
  122. package/dist/template/server/utils/define-validated-handler.ts +78 -0
  123. package/dist/template/server/utils/errors.ts +16 -0
  124. package/dist/template/server/utils/read-body.ts +34 -0
  125. package/dist/template/server/utils/user-actor.ts +10 -0
  126. package/dist/template/server.ts +5 -0
  127. package/dist/template/shared/domain/errors.ts +33 -0
  128. package/dist/template/shared/types/auth.d.ts +13 -0
  129. package/dist/template/shared/utils/admin.ts +13 -0
  130. package/dist/template/shared/utils/auth.ts +132 -0
  131. package/dist/template/shared/utils/ids.ts +21 -0
  132. package/dist/template/shared/utils/local-path.ts +2 -0
  133. package/dist/template/shared/utils/schema-validation.ts +59 -0
  134. package/dist/template/shared/utils/unknown.ts +9 -0
  135. package/dist/template/tsconfig.json +17 -0
  136. package/dist/template/vitest.config.ts +10 -0
  137. package/dist/template/wrangler.json +46 -0
  138. package/package.json +28 -4
@@ -0,0 +1,82 @@
1
+ import { Context, Effect, Layer } from 'effect'
2
+
3
+ import type { Mail } from '#server/core/platform/mailer'
4
+
5
+ import { AppConfig } from '#server/core/platform/app-config'
6
+ import { EmailAssets } from '#server/core/platform/email-assets'
7
+ import { readKey } from '#shared/utils/unknown'
8
+
9
+ import type { Block, Email } from './email'
10
+
11
+ export type Rendered = Pick<Mail, 'subject' | 'text' | 'html'>
12
+
13
+ const escapeHtml = (value: string) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;')
14
+
15
+ type Vars = Readonly<Record<string, unknown>>
16
+ const lookup = (vars: Vars, path: string) => path.split('.').reduce<unknown>((node, key) => readKey(node, key), vars)
17
+
18
+ /**
19
+ * Fills a template: `{{name}}` is HTML-escaped, `{{{name}}}` is inserted raw (only for rendered blocks).
20
+ * Throws immediately if a referenced variable is missing so broken templates never send silently.
21
+ */
22
+ export const fill = (template: string, vars: Vars) =>
23
+ template.replace(/\{\{\{\s*([\w.]+)\s*\}\}\}|\{\{\s*([\w.]+)\s*\}\}/g, (_, raw: string | undefined, escaped: string | undefined) => {
24
+ const value = lookup(vars, (raw ?? escaped)!)
25
+ const text = typeof value === 'string' ? value : typeof value === 'number' || typeof value === 'boolean' ? String(value) : undefined
26
+ if (text === undefined) throw new Error(`Email template value "${raw ?? escaped}" is missing.`)
27
+ return raw ? text : escapeHtml(text)
28
+ })
29
+
30
+ const textOf = (email: Email, home: string) => {
31
+ const lines = (block: Block): ReadonlyArray<string> => {
32
+ switch (block.kind) {
33
+ case 'button':
34
+ return [`${block.label}: ${block.url}`]
35
+ case 'text':
36
+ case 'note':
37
+ return [block.text]
38
+ }
39
+ }
40
+ return [email.headline, '', ...email.blocks.flatMap((block) => [...lines(block), '']), '—', email.footer, home]
41
+ .join('\n')
42
+ .replace(/\n{3,}/g, '\n\n')
43
+ .trim()
44
+ }
45
+
46
+ /** Renders an `Email` through `server/assets/email/layout.html` and `blocks/*.html`, producing both HTML and plain text. */
47
+ export class EmailRenderer extends Context.Service<EmailRenderer, { readonly render: (email: Email) => Effect.Effect<Rendered> }>()(
48
+ 'app/notifications/EmailRenderer',
49
+ ) {
50
+ static readonly layer = Layer.effect(
51
+ EmailRenderer,
52
+ Effect.gen(function* () {
53
+ const assets = yield* EmailAssets
54
+ const config = yield* AppConfig
55
+ const base = { appName: config.appName, home: config.appUrl }
56
+
57
+ const block = (name: string, vars: Vars = {}) => assets.read(`blocks/${name}.html`).pipe(Effect.map((template) => fill(template, { ...base, ...vars })))
58
+
59
+ const blockHtml = (b: Block): Effect.Effect<string> => {
60
+ switch (b.kind) {
61
+ case 'text':
62
+ return block('text', { text: b.text })
63
+ case 'button':
64
+ return block('button', { label: b.label, url: b.url })
65
+ case 'note':
66
+ return block('note', { text: b.text })
67
+ }
68
+ }
69
+
70
+ return EmailRenderer.of({
71
+ render: (email) =>
72
+ Effect.gen(function* () {
73
+ const lead = yield* block('lead', { headline: email.headline })
74
+ const content = [lead, ...(yield* Effect.forEach(email.blocks, blockHtml))].join('\n')
75
+ const layout = yield* assets.read('layout.html')
76
+ const html = fill(layout, { ...base, subject: email.subject, preheader: email.preheader, footer: email.footer, content })
77
+ return { subject: email.subject, html, text: textOf(email, base.home) }
78
+ }),
79
+ })
80
+ }),
81
+ )
82
+ }
@@ -0,0 +1,11 @@
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
+ })
@@ -0,0 +1,37 @@
1
+ import type { Email } from './email'
2
+
3
+ export const verificationEmail = (url: string, appName: string): Email => ({
4
+ subject: `Confirm your email for ${appName}`,
5
+ preheader: `Confirm your email address to finish setting up ${appName}.`,
6
+ headline: 'Confirm your email',
7
+ blocks: [
8
+ { kind: 'text', text: `Use the link below to confirm your email address for ${appName}.` },
9
+ { kind: 'button', label: 'Confirm email', url },
10
+ { kind: 'note', text: `If you did not create an account on ${appName}, you can safely ignore this email.` },
11
+ ],
12
+ footer: `Sent by ${appName}.`,
13
+ })
14
+
15
+ export const passwordResetEmail = (url: string, appName: string): Email => ({
16
+ subject: `Reset your ${appName} password`,
17
+ preheader: `Use this one-time link to choose a new password.`,
18
+ headline: 'Reset your password',
19
+ blocks: [
20
+ { kind: 'text', text: `Someone requested a password reset for your ${appName} account.` },
21
+ { kind: 'button', label: 'Reset password', url },
22
+ { kind: 'note', text: 'This link expires in 1 hour. If you did not request a reset, nothing has changed.' },
23
+ ],
24
+ footer: `Sent by ${appName}.`,
25
+ })
26
+
27
+ export const emailChangeEmail = (url: string, appName: string): Email => ({
28
+ subject: `Confirm your new email for ${appName}`,
29
+ preheader: `Confirm this email address to finish switching your ${appName} sign-in.`,
30
+ headline: 'Confirm your new email',
31
+ blocks: [
32
+ { kind: 'text', text: `Use the link below to switch your ${appName} account to this email address.` },
33
+ { kind: 'button', label: 'Confirm new email', url },
34
+ { kind: 'note', text: 'Confirming this link signs out existing sessions so you can sign in with your new email.' },
35
+ ],
36
+ footer: `Sent by ${appName}.`,
37
+ })
@@ -0,0 +1 @@
1
+ <p><a href="{{url}}">{{label}}</a></p>
@@ -0,0 +1 @@
1
+ <h1>{{headline}}</h1>
@@ -0,0 +1 @@
1
+ <p><small>{{text}}</small></p>
@@ -0,0 +1 @@
1
+ <p>{{text}}</p>
@@ -0,0 +1,22 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en" dir="ltr">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>{{subject}}</title>
7
+ </head>
8
+ <body>
9
+ <div style="display:none;max-height:0;max-width:0;overflow:hidden;opacity:0;">{{preheader}}</div>
10
+ <header>
11
+ <p><strong>{{appName}}</strong></p>
12
+ </header>
13
+ <main>
14
+ {{{content}}}
15
+ </main>
16
+ <footer>
17
+ <hr>
18
+ <p>{{footer}}</p>
19
+ <p><a href="{{home}}">{{home}}</a></p>
20
+ </footer>
21
+ </body>
22
+ </html>
@@ -0,0 +1,38 @@
1
+ import { DurableObject } from 'cloudflare:workers'
2
+
3
+ import type { WindowVerdict } from '#server/core/platform/sliding-window'
4
+
5
+ import { makeSlidingWindow } from '#server/core/platform/sliding-window'
6
+
7
+ /** Durable Object shell: sliding-window logic lives in `sliding-window.ts` */
8
+ export class RateLimitCounter extends DurableObject<Env> {
9
+ private readonly window
10
+ private ready = true
11
+
12
+ constructor(ctx: DurableObjectState, env: Env) {
13
+ super(ctx, env)
14
+ this.window = makeSlidingWindow(ctx.storage.sql)
15
+ }
16
+
17
+ private ensure() {
18
+ if (this.ready) return
19
+ this.window.init()
20
+ this.ready = true
21
+ }
22
+
23
+ async hit(limit: number, windowMs: number): Promise<WindowVerdict> {
24
+ this.ensure()
25
+ const verdict = this.window.hit(limit, windowMs, Date.now())
26
+ if (verdict.allowed && (await this.ctx.storage.getAlarm()) === null) await this.ctx.storage.setAlarm(Date.now() + windowMs + 1000)
27
+ return verdict
28
+ }
29
+
30
+ override async alarm() {
31
+ this.ensure()
32
+ const windowMs = this.window.windowMs(60_000)
33
+ if (this.window.idle(windowMs, Date.now())) {
34
+ await this.ctx.storage.deleteAll()
35
+ this.ready = false
36
+ } else await this.ctx.storage.setAlarm(Date.now() + windowMs)
37
+ }
38
+ }
@@ -0,0 +1,33 @@
1
+ import { Layer } from 'effect'
2
+ import { FetchHttpClient } from 'effect/http'
3
+
4
+ import { Features } from '#server/app/features'
5
+
6
+ import { AtomicBatchD1 } from './db/atomic-d1'
7
+ import { MigratorLive } from './db/migrator'
8
+ import { AppConfig } from './platform/app-config'
9
+ import { Database } from './platform/database'
10
+ import { EmailAssets } from './platform/email-assets'
11
+ import { IdGenerator } from './platform/id-generator'
12
+ import { Kv } from './platform/kv'
13
+ import { MailerCloudflare } from './platform/mailer-cloudflare'
14
+ import { PasswordHasher } from './platform/password-hasher'
15
+ import { Pii } from './platform/pii'
16
+ import { RateLimiterStrict } from './platform/rate-limiter-strict'
17
+ import { Seal } from './platform/seal'
18
+ import { Tokens } from './platform/tokens'
19
+ import { Turnstile } from './platform/turnstile'
20
+
21
+ /** Cloudflare bindings behind Effect ports. */
22
+ const Bindings = Layer.mergeAll(Database.layer, AtomicBatchD1, Kv.layer, EmailAssets.layer)
23
+
24
+ const Platform = Layer.mergeAll(Pii.layer, MailerCloudflare).pipe(
25
+ Layer.provideMerge(Layer.mergeAll(PasswordHasher.layer, AppConfig.layer, IdGenerator.layer, Tokens.layer, Seal.layer, FetchHttpClient.layer, Bindings)),
26
+ )
27
+
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))))
30
+
31
+ export const AppLayer = Features.pipe(Layer.provideMerge(Foundation))
32
+
33
+ export type AppServices = Layer.Success<typeof AppLayer>
@@ -0,0 +1,21 @@
1
+ import { env } from 'cloudflare:workers'
2
+ import { Effect, Layer } from 'effect'
3
+
4
+ import { DatabaseError } from '#server/core/platform/database'
5
+
6
+ import type { Applied } from './atomic'
7
+
8
+ import { AtomicBatch } from './atomic'
9
+
10
+ /** D1's `batch()` executes its statements in one implicit transaction: if any statement fails, none are kept. */
11
+ export const AtomicBatchD1 = Layer.sync(AtomicBatch, () =>
12
+ 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) }),
19
+ }),
20
+ ),
21
+ )
@@ -0,0 +1,86 @@
1
+ import type { Database as Db0 } from 'db0'
2
+
3
+ import { Context, Effect, Layer, Schema } from 'effect'
4
+
5
+ import { DatabaseError } from '#server/core/platform/database'
6
+ import { readKey } from '#shared/utils/unknown'
7
+
8
+ type Param = string | number | boolean | null | undefined
9
+
10
+ export interface Statement {
11
+ readonly sql: string
12
+ readonly params?: ReadonlyArray<Param>
13
+ }
14
+
15
+ export interface Applied {
16
+ readonly changes: number
17
+ }
18
+
19
+ /** Explicit failure raised when an atomic batch guard (such as `assertPreviousChanged`) aborts a conditional transition. */
20
+ export class GuardFailed extends Schema.TaggedError<GuardFailed, { readonly brand: unique symbol }>()('GuardFailed', {
21
+ reason: Schema.String,
22
+ }) {}
23
+
24
+ /**
25
+ * Aborts an atomic SQLite/D1 batch if the immediately preceding write affected 0 rows, rolling back the whole batch.
26
+ * Used with `AtomicBatch.runGuarded` so conditional state-machine transitions stay explicit and typed without raw SQL tricks in services.
27
+ */
28
+ export const assertPreviousChanged: Statement = {
29
+ sql: `SELECT json(CASE WHEN changes() > 0 THEN '{}' ELSE 'guard-abort' END)`,
30
+ }
31
+
32
+ export const isGuardAbort = (error: DatabaseError) => /malformed JSON/i.test(error.message)
33
+
34
+ const failure = (cause: unknown) => new DatabaseError({ sql: 'batch', message: cause instanceof Error ? cause.message : String(cause) })
35
+
36
+ const makeRunGuarded =
37
+ (run: (statements: ReadonlyArray<Statement>) => Effect.Effect<ReadonlyArray<Applied>, DatabaseError>) =>
38
+ (reason: string, statements: ReadonlyArray<Statement>): Effect.Effect<ReadonlyArray<Applied>, GuardFailed | DatabaseError> =>
39
+ run(statements).pipe(Effect.mapError((error): GuardFailed | DatabaseError => (isGuardAbort(error) ? new GuardFailed({ reason }) : error)))
40
+
41
+ /** The only D1 transaction primitive (`db0` has none). Never perform external I/O between statements. */
42
+ export class AtomicBatch extends Context.Service<
43
+ AtomicBatch,
44
+ {
45
+ readonly run: (statements: ReadonlyArray<Statement>) => Effect.Effect<ReadonlyArray<Applied>, DatabaseError>
46
+ readonly runGuarded: (reason: string, statements: ReadonlyArray<Statement>) => Effect.Effect<ReadonlyArray<Applied>, GuardFailed | DatabaseError>
47
+ }
48
+ >()('app/platform/AtomicBatch') {
49
+ static readonly make = (run: (statements: ReadonlyArray<Statement>) => Effect.Effect<ReadonlyArray<Applied>, DatabaseError>) =>
50
+ AtomicBatch.of({ run, runGuarded: makeRunGuarded(run) })
51
+
52
+ static readonly layerFor = (db: Db0) => {
53
+ let queue: Promise<unknown> = Promise.resolve()
54
+ const run = (statements: ReadonlyArray<Statement>) =>
55
+ Effect.tryPromise({
56
+ try: () => {
57
+ const job = queue.then(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 })
70
+ }
71
+ await db.exec('COMMIT')
72
+ return applied
73
+ } catch (error) {
74
+ await db.exec('ROLLBACK')
75
+ throw error
76
+ }
77
+ })
78
+ queue = job.catch(() => undefined)
79
+ return job
80
+ },
81
+ catch: failure,
82
+ })
83
+
84
+ return Layer.succeed(AtomicBatch, AtomicBatch.make(run))
85
+ }
86
+ }
@@ -0,0 +1,13 @@
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(', ')
@@ -0,0 +1,149 @@
1
+ export interface Migration {
2
+ readonly id: string
3
+ readonly statements: ReadonlyArray<string>
4
+ }
5
+
6
+ /**
7
+ * Append-only migrations. Never edit an applied migration — add a new entry.
8
+ * Every state machine and data invariant is enforced directly by SQL CHECK constraints
9
+ * so impossible states cannot be stored even by direct queries or concurrent writes.
10
+ */
11
+ export const migrations: ReadonlyArray<Migration> = [
12
+ {
13
+ id: '0001_identity_and_admin',
14
+ statements: [
15
+ `CREATE TABLE users (
16
+ id TEXT PRIMARY KEY,
17
+ username TEXT NOT NULL UNIQUE CHECK (username = lower(trim(username)) AND length(username) BETWEEN 3 AND 24),
18
+ email TEXT NOT NULL UNIQUE CHECK (email = lower(trim(email)) AND length(email) > 0),
19
+ password_hash TEXT,
20
+ google_sub TEXT UNIQUE,
21
+ github_id TEXT UNIQUE,
22
+ email_status TEXT NOT NULL DEFAULT 'unverified' CHECK (email_status IN ('unverified', 'verified')),
23
+ email_verified_at TEXT,
24
+ email_changed_at TEXT,
25
+ totp_status TEXT NOT NULL DEFAULT 'off' CHECK (totp_status IN ('off', 'pending', 'enabled')),
26
+ totp_secret TEXT,
27
+ totp_enabled_at TEXT,
28
+ totp_last_step INTEGER NOT NULL DEFAULT 0 CHECK (totp_last_step >= 0),
29
+ created_at TEXT NOT NULL,
30
+ last_active_at TEXT NOT NULL,
31
+ CHECK (password_hash IS NOT NULL OR google_sub IS NOT NULL OR github_id IS NOT NULL),
32
+ CHECK (
33
+ (email_status = 'unverified' AND email_verified_at IS NULL) OR
34
+ (email_status = 'verified' AND email_verified_at IS NOT NULL)
35
+ ),
36
+ CHECK (
37
+ (totp_status = 'off' AND totp_secret IS NULL AND totp_enabled_at IS NULL AND totp_last_step = 0) OR
38
+ (totp_status = 'pending' AND totp_secret IS NOT NULL AND totp_enabled_at IS NULL AND totp_last_step = 0) OR
39
+ (totp_status = 'enabled' AND totp_secret IS NOT NULL AND totp_enabled_at IS NOT NULL)
40
+ )
41
+ )`,
42
+ `CREATE TABLE totp_recovery_codes (
43
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
44
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
45
+ code_hash TEXT NOT NULL,
46
+ status TEXT NOT NULL DEFAULT 'unused' CHECK (status IN ('unused', 'used')),
47
+ used_at TEXT,
48
+ UNIQUE (user_id, code_hash),
49
+ CHECK (
50
+ (status = 'unused' AND used_at IS NULL) OR
51
+ (status = 'used' AND used_at IS NOT NULL)
52
+ )
53
+ )`,
54
+ `CREATE INDEX idx_totp_recovery_codes_user ON totp_recovery_codes (user_id, status)`,
55
+ `CREATE TABLE sessions (
56
+ id TEXT PRIMARY KEY,
57
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
58
+ device TEXT NOT NULL DEFAULT '',
59
+ created_at TEXT NOT NULL,
60
+ last_seen_at TEXT NOT NULL,
61
+ expires_at TEXT NOT NULL,
62
+ CHECK (expires_at > created_at)
63
+ )`,
64
+ `CREATE INDEX idx_sessions_user ON sessions (user_id, last_seen_at DESC)`,
65
+ `CREATE INDEX idx_sessions_expires ON sessions (expires_at)`,
66
+ `CREATE TABLE login_failures (
67
+ subject TEXT PRIMARY KEY,
68
+ status TEXT NOT NULL CHECK (status IN ('counting', 'locked')),
69
+ failures INTEGER NOT NULL CHECK (failures >= 0),
70
+ locked_until TEXT,
71
+ CHECK (
72
+ (status = 'counting' AND failures > 0 AND locked_until IS NULL) OR
73
+ (status = 'locked' AND failures = 0 AND locked_until IS NOT NULL)
74
+ )
75
+ )`,
76
+ `CREATE TABLE email_verification_tokens (
77
+ token_hash TEXT PRIMARY KEY,
78
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
79
+ email TEXT NOT NULL CHECK (email = lower(trim(email))),
80
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'used', 'revoked')),
81
+ created_at TEXT NOT NULL,
82
+ expires_at TEXT NOT NULL,
83
+ used_at TEXT,
84
+ revoked_at TEXT,
85
+ CHECK (expires_at > created_at),
86
+ CHECK (
87
+ (status = 'active' AND used_at IS NULL AND revoked_at IS NULL) OR
88
+ (status = 'used' AND used_at IS NOT NULL AND revoked_at IS NULL) OR
89
+ (status = 'revoked' AND used_at IS NULL AND revoked_at IS NOT NULL)
90
+ )
91
+ )`,
92
+ `CREATE INDEX idx_email_verification_user ON email_verification_tokens (user_id, status)`,
93
+ `CREATE TABLE password_reset_tokens (
94
+ token_hash TEXT PRIMARY KEY,
95
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
96
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'used', 'revoked')),
97
+ created_at TEXT NOT NULL,
98
+ expires_at TEXT NOT NULL,
99
+ used_at TEXT,
100
+ revoked_at TEXT,
101
+ CHECK (expires_at > created_at),
102
+ CHECK (
103
+ (status = 'active' AND used_at IS NULL AND revoked_at IS NULL) OR
104
+ (status = 'used' AND used_at IS NOT NULL AND revoked_at IS NULL) OR
105
+ (status = 'revoked' AND used_at IS NULL AND revoked_at IS NOT NULL)
106
+ )
107
+ )`,
108
+ `CREATE INDEX idx_password_reset_user ON password_reset_tokens (user_id, status)`,
109
+ `CREATE TABLE email_change_tokens (
110
+ token_hash TEXT PRIMARY KEY,
111
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
112
+ new_email TEXT NOT NULL CHECK (new_email = lower(trim(new_email))),
113
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'used', 'revoked')),
114
+ created_at TEXT NOT NULL,
115
+ expires_at TEXT NOT NULL,
116
+ used_at TEXT,
117
+ revoked_at TEXT,
118
+ CHECK (expires_at > created_at),
119
+ CHECK (
120
+ (status = 'active' AND used_at IS NULL AND revoked_at IS NULL) OR
121
+ (status = 'used' AND used_at IS NOT NULL AND revoked_at IS NULL) OR
122
+ (status = 'revoked' AND used_at IS NULL AND revoked_at IS NOT NULL)
123
+ )
124
+ )`,
125
+ `CREATE INDEX idx_email_change_user ON email_change_tokens (user_id, status)`,
126
+ `CREATE TABLE admins (
127
+ email TEXT PRIMARY KEY CHECK (email = lower(trim(email))),
128
+ password_hash TEXT NOT NULL,
129
+ created_at TEXT NOT NULL
130
+ )`,
131
+ `CREATE TABLE admin_sessions (
132
+ token_hash TEXT PRIMARY KEY,
133
+ email TEXT NOT NULL REFERENCES admins(email) ON DELETE CASCADE,
134
+ created_at TEXT NOT NULL,
135
+ expires_at TEXT NOT NULL,
136
+ CHECK (expires_at > created_at)
137
+ )`,
138
+ `CREATE INDEX idx_admin_sessions_email ON admin_sessions (email)`,
139
+ `CREATE TABLE admin_audit (
140
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
141
+ actor_email TEXT NOT NULL,
142
+ action TEXT NOT NULL,
143
+ target TEXT NOT NULL,
144
+ detail TEXT,
145
+ created_at TEXT NOT NULL
146
+ )`,
147
+ ],
148
+ },
149
+ ]
@@ -0,0 +1,39 @@
1
+ import { Effect, Layer, Schedule, Schema } from 'effect'
2
+
3
+ import { nowIso } from '#server/core/platform/clock'
4
+ import { Database } from '#server/core/platform/database'
5
+
6
+ import { AtomicBatch } from './atomic'
7
+ import { migrations } from './migrations'
8
+
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
+ const RACE_RETRY = Schedule.exponential('100 millis').pipe(Schedule.jittered)
16
+
17
+ /** Applies pending migrations in order when the app layer is first built. Each migration and its record commit atomically. */
18
+ export const MigratorLive = Layer.effectDiscard(
19
+ Effect.gen(function* () {
20
+ const db = yield* Database
21
+ const atomic = yield* AtomicBatch
22
+ yield* db.run(`CREATE TABLE IF NOT EXISTS _migrations (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`)
23
+ const appliedIds = db.all(Applied, `SELECT id FROM _migrations`).pipe(Effect.map((rows) => new Set(rows.map((row) => row.id))))
24
+ const applied = yield* appliedIds
25
+
26
+ for (const migration of migrations) {
27
+ if (applied.has(migration.id)) continue
28
+ const attempt = Effect.gen(function* () {
29
+ if ((yield* appliedIds).has(migration.id)) return false
30
+ const record = { sql: `INSERT INTO _migrations (id, applied_at) VALUES (?, ?)`, params: [migration.id, yield* nowIso] }
31
+ yield* atomic
32
+ .run([...migration.statements.map((sql) => ({ sql })), record])
33
+ .pipe(Effect.catch((error) => Effect.flatMap(appliedIds, (now) => (now.has(migration.id) ? Effect.void : Effect.fail(error)))))
34
+ return true
35
+ })
36
+ if (yield* attempt.pipe(Effect.retry({ schedule: RACE_RETRY, times: 3 }))) yield* Effect.logInfo(`Applied migration ${migration.id}`)
37
+ }
38
+ }).pipe(Effect.withSpan('Migrator.run')),
39
+ )
@@ -0,0 +1,35 @@
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
+ }
@@ -0,0 +1,16 @@
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'])
@@ -0,0 +1,27 @@
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
+ }