@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,51 @@
1
+ import { env } from 'cloudflare:workers'
2
+ import { Effect, Layer } from 'effect'
3
+
4
+ import { ServiceNotConfigured, UpstreamFailure } from '#server/utils/errors'
5
+
6
+ import type { MailFailure } from './mailer'
7
+
8
+ import { AppConfig } from './app-config'
9
+ import { Mailer } from './mailer'
10
+
11
+ const failureOf = (cause: unknown): MailFailure => {
12
+ const code = typeof cause === 'object' && cause !== null ? (cause as { code?: string }).code : undefined
13
+ if (code === 'E_SENDER_NOT_VERIFIED' || code === 'E_SENDER_DOMAIN_NOT_AVAILABLE') {
14
+ return new ServiceNotConfigured({ service: 'mail', message: 'The sender address is not verified for email sending.' })
15
+ }
16
+ return new UpstreamFailure({ service: 'mail', message: `Email could not be sent${code ? ` (${code})` : ''}.` })
17
+ }
18
+
19
+ const addressOf = (value: string) => {
20
+ const match = /^\s*(.*?)\s*<([^>]+)>\s*$/.exec(value)
21
+ const email = (match ? match[2]! : value).trim()
22
+ return { email, name: match?.[1] || email }
23
+ }
24
+
25
+ interface EmailBinding {
26
+ readonly send: (message: { from: { email: string; name: string }; to: string; subject: string; text: string; html: string }) => Promise<unknown>
27
+ }
28
+
29
+ export const MailerCloudflare = Layer.unwrap(
30
+ Effect.gen(function* () {
31
+ const config = yield* AppConfig
32
+ const binding = (env as { EMAIL?: EmailBinding }).EMAIL
33
+ if (!binding) {
34
+ if (import.meta.dev) return Mailer.logging
35
+ return Layer.succeed(
36
+ Mailer,
37
+ Mailer.of({ send: () => Effect.fail(new ServiceNotConfigured({ service: 'mail', message: 'The EMAIL binding is missing.' })) }),
38
+ )
39
+ }
40
+ return Layer.succeed(
41
+ Mailer,
42
+ Mailer.of({
43
+ send: (mail) =>
44
+ Effect.tryPromise({
45
+ try: () => binding.send({ from: addressOf(config.mailFrom), to: mail.to, subject: mail.subject, text: mail.text, html: mail.html }),
46
+ catch: failureOf,
47
+ }).pipe(Effect.asVoid, Effect.withSpan('Mailer.send')),
48
+ }),
49
+ )
50
+ }),
51
+ )
@@ -0,0 +1,21 @@
1
+ import { Context, Effect, Layer } from 'effect'
2
+
3
+ import type { ServiceNotConfigured, UpstreamFailure } from '#server/utils/errors'
4
+
5
+ export interface Mail {
6
+ readonly to: string
7
+ readonly subject: string
8
+ readonly text: string
9
+ readonly html: string
10
+ }
11
+
12
+ export type MailFailure = ServiceNotConfigured | UpstreamFailure
13
+
14
+ export class Mailer extends Context.Service<Mailer, { readonly send: (mail: Mail) => Effect.Effect<void, MailFailure> }>()('app/platform/Mailer') {
15
+ static readonly recording = (sent: Mail[]) => Layer.succeed(Mailer, Mailer.of({ send: (mail) => Effect.sync(() => void sent.push(mail)) }))
16
+
17
+ static readonly logging = Layer.succeed(
18
+ Mailer,
19
+ Mailer.of({ send: (mail) => Effect.logInfo(`Email (dev log) to ${mail.to}\nSubject: ${mail.subject}\n\n${mail.text}`) }),
20
+ )
21
+ }
@@ -0,0 +1,27 @@
1
+ import { Context, Effect, Layer } from 'effect'
2
+
3
+ /** scrypt via `nuxt-auth-utils`, behind a port so service tests need no Nuxt runtime. */
4
+ export class PasswordHasher extends Context.Service<
5
+ PasswordHasher,
6
+ {
7
+ readonly hash: (plain: string) => Effect.Effect<string>
8
+ readonly verify: (hash: string, plain: string) => Effect.Effect<boolean>
9
+ }
10
+ >()('app/platform/PasswordHasher') {
11
+ static readonly layer = Layer.succeed(
12
+ PasswordHasher,
13
+ PasswordHasher.of({
14
+ hash: (plain) => Effect.promise(() => hashPassword(plain)),
15
+ verify: (hash, plain) => Effect.promise(() => verifyPassword(hash, plain)),
16
+ }),
17
+ )
18
+
19
+ /** Fast non-cryptographic fake strictly for unit tests. */
20
+ static readonly fake = Layer.succeed(
21
+ PasswordHasher,
22
+ PasswordHasher.of({
23
+ hash: (plain) => Effect.succeed(`fake:${plain}`),
24
+ verify: (hash, plain) => Effect.succeed(hash === `fake:${plain}`),
25
+ }),
26
+ )
27
+ }
@@ -0,0 +1,80 @@
1
+ import { Context, Effect, Layer, Redacted } from 'effect'
2
+ import { Mac, SecureRandom } from 'effect/crypto'
3
+ import { Base64Url, Hex } from 'effect/encoding'
4
+
5
+ import { AppConfig } from './app-config'
6
+ import { Seal } from './seal'
7
+
8
+ const PREFIX = 'pii2:'
9
+ const encoder = new TextEncoder()
10
+ const decoder = new TextDecoder()
11
+
12
+ export const keyList = (current: string, previous: string) => [
13
+ current,
14
+ ...previous
15
+ .split(',')
16
+ .map((key) => key.trim())
17
+ .filter(Boolean),
18
+ ]
19
+
20
+ /**
21
+ * Field-level AES-256-GCM encryption with key rotation and AAD bound to the column/field name.
22
+ * Stored format: `pii2:<key-id>:<base64url(sealed)>`.
23
+ */
24
+ export class Pii extends Context.Service<
25
+ Pii,
26
+ {
27
+ readonly kid: string
28
+ readonly seal: (value: string, field: string) => Effect.Effect<string>
29
+ readonly open: (stored: string, field: string) => Effect.Effect<string>
30
+ readonly index: (value: string) => Effect.Effect<string>
31
+ }
32
+ >()('app/platform/Pii') {
33
+ static readonly layer = Layer.effect(
34
+ Pii,
35
+ Effect.gen(function* () {
36
+ const config = yield* AppConfig
37
+ const seal = yield* Seal
38
+ const mac = yield* Mac.Mac
39
+ const current = Redacted.value(config.piiKey)
40
+ const indexKey = Redacted.value(config.piiIndexKey)
41
+ if (!/^[0-9a-f]{64}$/i.test(current)) {
42
+ return yield* Effect.die(new Error('NUXT_PII_KEY must be 64 hex characters (generate with `openssl rand -hex 32`).'))
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`).'))
46
+ }
47
+ const idOf = (key: string) => seal.sha256(encoder.encode(`pii-key:${key}`)).pipe(Effect.map((hash) => hash.slice(0, 8)))
48
+ const keys = new Map<string, string>()
49
+ for (const key of keyList(current, Redacted.value(config.piiKeyPrevious))) keys.set(yield* idOf(key), key)
50
+ const kid = yield* idOf(current)
51
+
52
+ const sealValue = (value: string, field: string) =>
53
+ seal.seal(encoder.encode(value), current, field).pipe(
54
+ Effect.map((bytes) => `${PREFIX}${kid}:${Base64Url.encode(bytes)}`),
55
+ Effect.orDie,
56
+ )
57
+
58
+ const openValue = (stored: string, field: string) => {
59
+ if (!stored.startsWith(PREFIX)) return Effect.succeed(stored)
60
+ const [id = '', body = ''] = stored.slice(PREFIX.length).split(':')
61
+ const key = keys.get(id)
62
+ const bytes = Base64Url.decode(body)
63
+ if (!key) return Effect.die(new Error(`Stored ${field} was sealed with an unknown key (${id}); add it to NUXT_PII_KEY_PREVIOUS.`))
64
+ if (bytes._tag === 'Failure') return Effect.die(new Error(`Stored ${field} is damaged.`))
65
+ return seal.open(bytes.success, key, field).pipe(
66
+ Effect.map((plain) => decoder.decode(plain)),
67
+ Effect.orDie,
68
+ )
69
+ }
70
+
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)
76
+
77
+ return Pii.of({ kid, seal: sealValue, open: openValue, index })
78
+ }),
79
+ ).pipe(Layer.provide(Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto))))
80
+ }
@@ -0,0 +1,21 @@
1
+ import { Effect, flow, Schedule } from 'effect'
2
+ import { HttpClient, HttpClientRequest } from 'effect/http'
3
+
4
+ interface ProviderHttpOptions {
5
+ readonly provider: string
6
+ readonly baseUrl: string
7
+ readonly headers?: Readonly<Record<string, string>>
8
+ readonly retries?: number
9
+ }
10
+
11
+ export const providerHttp = (options: ProviderHttpOptions) =>
12
+ HttpClient.HttpClient.use((client) =>
13
+ Effect.succeed(
14
+ client.pipe(
15
+ HttpClient.mapRequest(
16
+ flow(HttpClientRequest.prependUrl(options.baseUrl), HttpClientRequest.acceptJson, HttpClientRequest.setHeaders(options.headers ?? {})),
17
+ ),
18
+ HttpClient.retryTransient({ schedule: Schedule.exponential(200).pipe(Schedule.jittered), times: options.retries ?? 2 }),
19
+ ),
20
+ ),
21
+ )
@@ -0,0 +1,42 @@
1
+ import { env } from 'cloudflare:workers'
2
+ import { Effect, Layer } from 'effect'
3
+
4
+ import { UpstreamFailure } from '#server/utils/errors'
5
+ import { RateLimited } from '#shared/domain/errors'
6
+
7
+ import type { LimitName } from './rate-limiter'
8
+
9
+ import { AppConfig } from './app-config'
10
+ import { RateLimiter } from './rate-limiter'
11
+
12
+ /** Global per-caller budgets backed by the `RateLimitCounter` Durable Object. */
13
+ export const LIMITS: Record<LimitName, { readonly limit: number; readonly windowMs: number }> = {
14
+ 'sign-in': { limit: 30, windowMs: 60_000 },
15
+ 'sign-in-account': { limit: 20, windowMs: 10 * 60_000 },
16
+ register: { limit: 20, windowMs: 60_000 },
17
+ reset: { limit: 5, windowMs: 60_000 },
18
+ 'reset-email': { limit: 3, windowMs: 60 * 60_000 },
19
+ verify: { limit: 5, windowMs: 60 * 60_000 },
20
+ 'email-change': { limit: 5, windowMs: 60 * 60_000 },
21
+ totp: { limit: 15, windowMs: 10 * 60_000 },
22
+ }
23
+
24
+ export const RateLimiterStrict = Layer.effect(
25
+ RateLimiter,
26
+ Effect.gen(function* () {
27
+ const config = yield* AppConfig
28
+ // Resolved per call, never cached across requests: a DO stub is tied to the request I/O context that created it.
29
+ const counter = (name: string) => env.RATE_LIMITER.getByName(name)
30
+ return RateLimiter.of({
31
+ check: (limit, key) =>
32
+ Effect.gen(function* () {
33
+ const rule = LIMITS[limit]
34
+ const verdict = yield* Effect.tryPromise({
35
+ try: () => counter(`${limit}:${key}`).hit(rule.limit * config.rateLimitScale, rule.windowMs),
36
+ 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.' })
39
+ }),
40
+ })
41
+ }),
42
+ )
@@ -0,0 +1,35 @@
1
+ import { Context, Effect, Layer } from 'effect'
2
+
3
+ import { UpstreamFailure } from '#server/utils/errors'
4
+ import { RateLimited } from '#shared/domain/errors'
5
+
6
+ export type LimitName = 'sign-in' | 'sign-in-account' | 'register' | 'reset' | 'reset-email' | 'verify' | 'email-change' | 'totp'
7
+
8
+ export interface LimitBinding {
9
+ readonly limit: (options: { key: string }) => Promise<{ success: boolean }>
10
+ }
11
+
12
+ export const allowed = (binding: LimitBinding | undefined, key: string): Effect.Effect<void, RateLimited> =>
13
+ Effect.gen(function* () {
14
+ if (!binding) return
15
+ const outcome = yield* Effect.tryPromise({
16
+ try: () => binding.limit({ key }),
17
+ catch: (cause) => new UpstreamFailure({ service: 'rate-limiter', message: String(cause) }),
18
+ }).pipe(Effect.option)
19
+
20
+ if (outcome._tag === 'Some' && !outcome.value.success) return yield* new RateLimited({ message: 'Too many requests. Please try again in a minute.' })
21
+ })
22
+
23
+ export class RateLimiter extends Context.Service<RateLimiter, { readonly check: (limit: LimitName, key: string) => Effect.Effect<void, RateLimited> }>()(
24
+ 'app/platform/RateLimiter',
25
+ ) {
26
+ static readonly over = (bindingOf: (limit: LimitName) => LimitBinding | undefined) =>
27
+ Layer.succeed(
28
+ RateLimiter,
29
+ RateLimiter.of({
30
+ check: (limit, key) => allowed(bindingOf(limit), key),
31
+ }),
32
+ )
33
+
34
+ static readonly unlimited = RateLimiter.over(() => undefined)
35
+ }
@@ -0,0 +1,15 @@
1
+ import { Schema } from 'effect'
2
+
3
+ const standard = <S extends Schema.Codec<unknown, unknown>>(schema: S) => Schema.toStandardJSONSchemaV1(Schema.toStandardSchemaV1(schema))
4
+
5
+ export const text = (fallback: string, description: string) => standard(Schema.String.annotate({ default: fallback, description }))
6
+
7
+ /** A secret the app cannot run without: no default, supplied by a Cloudflare secret or `.env`. */
8
+ export const required = (description: string) => standard(Schema.String.annotate({ description }))
9
+
10
+ /** An optional secret: empty by default, set only by a Cloudflare secret, never hardcoded in `nuxt.config.ts`. */
11
+ export const secret = (description: string) => standard(Schema.String.annotate({ default: '', description }))
12
+
13
+ export const flag = (fallback: boolean, description: string) => standard(Schema.Boolean.annotate({ default: fallback, description }))
14
+
15
+ export const int = (fallback: number, description: string) => standard(Schema.Int.annotate({ default: fallback, description }))
@@ -0,0 +1,68 @@
1
+ import { Context, Effect, Layer, Schema } from 'effect'
2
+ import { Aead, Digest, SecureRandom } from 'effect/crypto'
3
+ import { Hex } from 'effect/encoding'
4
+
5
+ export class SealError extends Schema.TaggedError<SealError, { readonly brand: unique symbol }>()('SealError', { message: Schema.String }) {}
6
+
7
+ /** Binary format: version(1) | nonce(12) | AES-256-GCM(gzip(plain), aad = context). */
8
+ const VERSION = 2
9
+ const NONCE_BYTES = 12
10
+ const encoder = new TextEncoder()
11
+
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
+ export class Seal extends Context.Service<
17
+ Seal,
18
+ {
19
+ readonly seal: (plain: Uint8Array, keyHex: string, context: string) => Effect.Effect<Uint8Array, SealError>
20
+ readonly open: (sealed: Uint8Array, keyHex: string, context: string) => Effect.Effect<Uint8Array, SealError>
21
+ readonly sha256: (bytes: Uint8Array) => Effect.Effect<string>
22
+ }
23
+ >()('app/platform/Seal') {
24
+ static readonly layer = Layer.effect(
25
+ Seal,
26
+ Effect.gen(function* () {
27
+ const aead = yield* Aead.Aead
28
+ const random = yield* SecureRandom.SecureRandom
29
+ const digest = yield* Digest.Digest
30
+
31
+ const keyOf = (keyHex: string) =>
32
+ Effect.gen(function* () {
33
+ const decoded = Hex.decode(keyHex)
34
+ if (decoded._tag === 'Failure' || decoded.success.length !== Aead.aes256Gcm.keyLength)
35
+ 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
+ })
38
+
39
+ const seal = (plain: Uint8Array, keyHex: string, context: string) =>
40
+ Effect.gen(function* () {
41
+ const key = yield* keyOf(keyHex)
42
+ const nonce = yield* random.randomBytes(NONCE_BYTES)
43
+ const body = yield* aead
44
+ .encrypt(key, yield* Effect.promise(() => gzip(plain)), { nonce, aad: encoder.encode(context) })
45
+ .pipe(Effect.mapError(() => new SealError({ message: 'Sealing failed.' })))
46
+ const out = new Uint8Array(1 + NONCE_BYTES + body.length)
47
+ out[0] = VERSION
48
+ out.set(nonce, 1)
49
+ out.set(body, 1 + NONCE_BYTES)
50
+ return out
51
+ })
52
+
53
+ const open = (sealed: Uint8Array, keyHex: string, context: string) =>
54
+ Effect.gen(function* () {
55
+ if (sealed[0] !== VERSION) return yield* new SealError({ message: 'Unknown sealed format.' })
56
+ const key = yield* keyOf(keyHex)
57
+ const plain = yield* aead
58
+ .decrypt(key, sealed.slice(1 + NONCE_BYTES), { nonce: sealed.slice(1, 1 + NONCE_BYTES), aad: encoder.encode(context) })
59
+ .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
+ })
62
+
63
+ return Seal.of({ seal, open, sha256: (bytes) => digest.digestHex(Digest.sha256, bytes) })
64
+ }),
65
+ ).pipe(
66
+ Layer.provide(Layer.mergeAll(Aead.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)), SecureRandom.layerWebCrypto, Digest.layerWebCrypto)),
67
+ )
68
+ }
@@ -0,0 +1,39 @@
1
+ /** Minimal SQLite interface shared by Durable Object SQLite storage and `node:sqlite` in tests. */
2
+ export interface WindowSql {
3
+ exec(query: string, ...bindings: unknown[]): { toArray(): Array<Record<string, unknown>> }
4
+ }
5
+
6
+ export interface WindowVerdict {
7
+ readonly allowed: boolean
8
+ readonly retryAfterMs: number
9
+ }
10
+
11
+ /** Caller must serialize access (a Durable Object does automatically). */
12
+ export const makeSlidingWindow = (sql: WindowSql) => {
13
+ const init = () => {
14
+ sql.exec(`CREATE TABLE IF NOT EXISTS hits (at INTEGER NOT NULL)`)
15
+ sql.exec(`CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value INTEGER NOT NULL)`)
16
+ }
17
+ init()
18
+
19
+ 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)
21
+ sql.exec(`DELETE FROM hits WHERE at <= ?`, now - windowMs)
22
+ const [row] = sql.exec(`SELECT COUNT(*) AS n, MIN(at) AS oldest FROM hits`).toArray()
23
+ if (Number(row!.n) >= limit) return { allowed: false, retryAfterMs: Math.max(0, Number(row!.oldest) + windowMs - now) }
24
+ sql.exec(`INSERT INTO hits (at) VALUES (?)`, now)
25
+ return { allowed: true, retryAfterMs: 0 }
26
+ }
27
+
28
+ const windowMs = (fallback: number): number => {
29
+ const row = sql.exec(`SELECT value FROM meta WHERE key = 'window_ms'`).toArray()[0]
30
+ return row ? Number(row.value) : fallback
31
+ }
32
+
33
+ const idle = (ms: number, now: number): boolean => {
34
+ sql.exec(`DELETE FROM hits WHERE at <= ?`, now - ms)
35
+ return Number(sql.exec(`SELECT COUNT(*) AS n FROM hits`).toArray()[0]!.n) === 0
36
+ }
37
+
38
+ return { init, hit, windowMs, idle }
39
+ }
@@ -0,0 +1,36 @@
1
+ import { Context, Effect, Layer } from 'effect'
2
+ import { Digest, Mac, SecureRandom } from 'effect/crypto'
3
+ import { Hex } from 'effect/encoding'
4
+
5
+ /** One-time tokens for emailed links and HMAC signing: only the SHA-256 hash is persisted in D1. */
6
+ export class Tokens extends Context.Service<
7
+ Tokens,
8
+ {
9
+ readonly generate: Effect.Effect<{ readonly token: string; readonly hash: string }>
10
+ readonly hash: (token: string) => Effect.Effect<string>
11
+ readonly sign: (message: string, secret: string) => Effect.Effect<string>
12
+ readonly equals: (a: string, b: string) => boolean
13
+ }
14
+ >()('app/platform/Tokens') {
15
+ static readonly layer = Layer.effect(
16
+ Tokens,
17
+ Effect.gen(function* () {
18
+ const random = yield* SecureRandom.SecureRandom
19
+ const digest = yield* Digest.Digest
20
+ const mac = yield* Mac.Mac
21
+ const bytesOf = (value: string) => new TextEncoder().encode(value)
22
+ const hash = (token: string) => digest.digestHex(Digest.sha256, bytesOf(token))
23
+ const generate = Effect.gen(function* () {
24
+ const token = Hex.encode(yield* random.randomBytes(32))
25
+ return { token, hash: yield* hash(token) }
26
+ })
27
+ const sign = (message: string, secret: string) =>
28
+ Effect.gen(function* () {
29
+ const key = yield* Mac.key(Mac.hmacSha256, bytesOf(secret))
30
+ return Hex.encode(yield* mac.sign(key, bytesOf(message)))
31
+ }).pipe(Effect.orDie)
32
+ const equals = (a: string, b: string) => Mac.timingSafeEqual(bytesOf(a), bytesOf(b))
33
+ return Tokens.of({ generate, hash, sign, equals })
34
+ }),
35
+ ).pipe(Layer.provide(Layer.mergeAll(SecureRandom.layerWebCrypto, Digest.layerWebCrypto, Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)))))
36
+ }
@@ -0,0 +1,61 @@
1
+ import { Context, Effect, Layer, Redacted, Schema } from 'effect'
2
+ import { HttpClientRequest, HttpClientResponse } from 'effect/http'
3
+
4
+ import { ServiceNotConfigured, UpstreamFailure } from '#server/utils/errors'
5
+ import { Unprocessable } from '#shared/domain/errors'
6
+
7
+ import { AppConfig } from './app-config'
8
+ import { providerHttp } from './provider-http'
9
+
10
+ const Verdict = Schema.Struct({ success: Schema.Boolean })
11
+
12
+ type TurnstileMode = { readonly _tag: 'Disabled' } | { readonly _tag: 'MissingRequiredSecret' } | { readonly _tag: 'Active'; readonly secret: string }
13
+
14
+ const resolveMode = (secret: string, required: boolean): TurnstileMode => {
15
+ if (secret) return { _tag: 'Active', secret }
16
+ return required ? { _tag: 'MissingRequiredSecret' } : { _tag: 'Disabled' }
17
+ }
18
+
19
+ /** Explicit three-mode Turnstile verifier resolved once from `AppConfig`: Disabled, MissingRequiredSecret, or Active. */
20
+ export class Turnstile extends Context.Service<
21
+ Turnstile,
22
+ { readonly verify: (token: string | undefined, ip: string | undefined) => Effect.Effect<void, Unprocessable | ServiceNotConfigured | UpstreamFailure> }
23
+ >()('app/platform/Turnstile') {
24
+ static readonly layer = Layer.effect(
25
+ Turnstile,
26
+ Effect.gen(function* () {
27
+ const config = yield* AppConfig
28
+ const mode = resolveMode(Redacted.value(config.turnstileSecret), config.turnstileRequired)
29
+ const http = yield* providerHttp({ provider: 'turnstile', baseUrl: 'https://challenges.cloudflare.com', retries: 1 })
30
+
31
+ const verify = Effect.fn('Turnstile.verify')(function* (token: string | undefined, ip: string | undefined) {
32
+ switch (mode._tag) {
33
+ case 'Disabled':
34
+ return
35
+ case 'MissingRequiredSecret':
36
+ return yield* new ServiceNotConfigured({ service: 'turnstile', message: 'Bot protection is required but not configured.' })
37
+ case 'Active': {
38
+ if (!token) return yield* new Unprocessable({ message: 'Please complete the verification and try again.' })
39
+ const params = new URLSearchParams({
40
+ secret: mode.secret,
41
+ response: token,
42
+ idempotency_key: crypto.randomUUID(),
43
+ ...(ip && ip !== 'unknown' ? { remoteip: ip } : {}),
44
+ })
45
+ const verdict = yield* http.execute(HttpClientRequest.post('/turnstile/v0/siteverify').pipe(HttpClientRequest.bodyUrlParams(params))).pipe(
46
+ Effect.timeout('10 seconds'),
47
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(Verdict)),
48
+ Effect.mapError(() => new UpstreamFailure({ service: 'turnstile', message: 'The verification service could not be reached.' })),
49
+ )
50
+ if (!verdict.success) return yield* new Unprocessable({ message: 'The verification failed. Please try again.' })
51
+ }
52
+ }
53
+ })
54
+
55
+ return Turnstile.of({ verify })
56
+ }),
57
+ )
58
+
59
+ /** For tests and local runs: every request passes. */
60
+ static readonly off = Layer.succeed(Turnstile, Turnstile.of({ verify: () => Effect.void }))
61
+ }
@@ -0,0 +1,10 @@
1
+ import { createError, defineHandler, getRequestURL } from 'nuxt/server'
2
+
3
+ import { bodyLimitFor } from '#server/core/http/body-limit'
4
+
5
+ export default defineHandler((event) => {
6
+ const limit = bodyLimitFor(event.req.method, getRequestURL(event).pathname)
7
+ if (limit === undefined) return
8
+ const declared = Number(event.req.headers.get('content-length') ?? 0)
9
+ if (declared > limit) throw createError({ status: 413, message: 'The request is too large.' })
10
+ })
@@ -0,0 +1,19 @@
1
+ import { defineHandler } from 'nuxt/server'
2
+
3
+ import { readKey } from '#shared/utils/unknown'
4
+
5
+ export const SECURITY_HEADERS: Readonly<Record<string, string>> = {
6
+ 'x-content-type-options': 'nosniff',
7
+ 'x-frame-options': 'DENY',
8
+ 'referrer-policy': 'strict-origin-when-cross-origin',
9
+ 'permissions-policy': 'camera=(), microphone=(), geolocation=()',
10
+ 'strict-transport-security': 'max-age=31536000; includeSubDomains',
11
+ }
12
+
13
+ export default defineHandler((event) => {
14
+ 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)
18
+ }
19
+ })
@@ -0,0 +1,25 @@
1
+ import { defineHandler, getRequestURL, useRuntimeConfig } from 'nuxt/server'
2
+
3
+ import { Sessions } from '#server/app/identity/sessions'
4
+ import { setRequestUser } from '#server/core/http/request-user'
5
+ import { runtime } from '#server/core/http/runtime'
6
+
7
+ export default defineHandler(async (event) => {
8
+ const path = getRequestURL(event).pathname
9
+ if (!path.startsWith('/api/')) return
10
+
11
+ // Reading a session creates an empty cookie when absent; skip unless the browser sent one.
12
+ const cookieName = (useRuntimeConfig().session as { name?: string } | undefined)?.name
13
+ if (!cookieName || !(event.req.headers.get('cookie') ?? '').includes(`${cookieName}=`)) return
14
+
15
+ const session = await getUserSession(event)
16
+ const sessionId = session.secure?.sessionId
17
+ const user = sessionId ? await runtime.runPromise(Sessions.use((sessions) => sessions.verify(sessionId))) : undefined
18
+
19
+ if (user && sessionId) {
20
+ setRequestUser(event, user, sessionId)
21
+ return
22
+ }
23
+
24
+ if (Object.keys(session).length > 1) await clearUserSession(event)
25
+ })
@@ -0,0 +1,15 @@
1
+ import { definePlugin } from 'nitro'
2
+ import { useServerHooks } from 'nuxt/server'
3
+
4
+ import { pageCsp, withNonce } from '#server/core/http/page-csp'
5
+
6
+ /** Per-response CSP nonce for rendered documents. Skipped in dev so Vite HMR works. */
7
+ export default definePlugin(() => {
8
+ if (import.meta.dev) return
9
+
10
+ useServerHooks().hook('render:document', (document, { event }) => {
11
+ const nonce = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(16))))
12
+ document.html = withNonce(document.html, nonce)
13
+ event.res.headers.set('content-security-policy', pageCsp(nonce))
14
+ })
15
+ })
@@ -0,0 +1,21 @@
1
+ import { definePlugin } from 'nitro'
2
+ import { createError } from 'nuxt/server'
3
+
4
+ import { Sessions } from '#server/app/identity/sessions'
5
+ import { runtime } from '#server/core/http/runtime'
6
+
7
+ export default definePlugin(() => {
8
+ sessionHooks.hook('fetch', async (session) => {
9
+ const sessionId = session.secure?.sessionId
10
+ if (!sessionId) return
11
+
12
+ const user = await runtime.runPromise(Sessions.use((sessions) => sessions.verify(sessionId)))
13
+ if (!user) throw createError({ status: 401, message: 'Please sign in again.' })
14
+ session.user = { username: user.username, verified: user.emailStatus === 'verified' }
15
+ })
16
+
17
+ sessionHooks.hook('clear', async (session) => {
18
+ const sessionId = session.secure?.sessionId
19
+ if (sessionId) await runtime.runPromise(Sessions.use((sessions) => sessions.end(sessionId)))
20
+ })
21
+ })
@@ -0,0 +1,37 @@
1
+ import { Effect } from 'effect'
2
+ import { defineHandler, getQuery } from 'nuxt/server'
3
+
4
+ import { EmailRenderer } from '#server/app/notifications/render'
5
+ import { sampleEmails } from '#server/app/notifications/samples'
6
+ import { runtime } from '#server/core/http/runtime'
7
+ import { AppConfig } from '#server/core/platform/app-config'
8
+
9
+ /** Dev-only email preview: `/emails` lists every template, `?name=verification` renders HTML, `&text` renders plain text. */
10
+ export default defineHandler(async (event) => {
11
+ const query = getQuery(event)
12
+ return runtime.runPromise(
13
+ Effect.gen(function* () {
14
+ const config = yield* AppConfig
15
+ const emails = sampleEmails(config.appUrl, config.appName)
16
+ const name = typeof query.name === 'string' ? query.name : undefined
17
+ const email = name ? emails[name] : undefined
18
+
19
+ event.res.headers.set('content-type', 'text/html; charset=utf-8')
20
+ event.res.headers.set('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'; img-src * data:")
21
+
22
+ if (!email) {
23
+ const links = Object.entries(emails).map(
24
+ ([key, item]) => `<li><a href="?name=${key}">${key}</a> · ${item.subject} · <a href="?name=${key}&text">text</a></li>`,
25
+ )
26
+ return `<!doctype html><meta charset="utf-8"><title>Emails</title><body><h1>Emails</h1><ul>${links.join('')}</ul></body>`
27
+ }
28
+
29
+ const mail = yield* EmailRenderer.use((renderer) => renderer.render(email))
30
+ if ('text' in query) {
31
+ event.res.headers.set('content-type', 'text/plain; charset=utf-8')
32
+ return `Subject: ${mail.subject}\n\n${mail.text}`
33
+ }
34
+ return mail.html
35
+ }),
36
+ )
37
+ })