@humanonlyweb/create-nuxtflare 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/cli.js +3 -1
- package/dist/template/.github/workflows/ci.yml +3 -1
- package/dist/template/CLAUDE.md +4 -2
- package/dist/template/app/components/turnstile-widget.vue +81 -0
- package/dist/template/app/composables/use-auth.ts +418 -0
- package/dist/template/app/pages/account.vue +125 -11
- package/dist/template/app/pages/email/[token].vue +18 -0
- package/dist/template/app/pages/forgot-password.vue +28 -0
- package/dist/template/app/pages/login.vue +9 -73
- package/dist/template/app/pages/register.vue +4 -26
- package/dist/template/app/pages/reset/[token].vue +31 -0
- package/dist/template/app/pages/verify/[token].vue +18 -0
- package/dist/template/nuxt.config.ts +4 -0
- package/dist/template/package.json +2 -0
- package/dist/template/scripts/admin-password.ts +13 -6
- package/dist/template/scripts/migrate.ts +67 -0
- package/dist/template/server/api/account/email/index.post.ts +1 -1
- package/dist/template/server/api/account/index.delete.ts +2 -2
- package/dist/template/server/api/account/password.post.ts +8 -0
- package/dist/template/server/api/auth/email/index.post.ts +1 -1
- package/dist/template/server/api/auth/login/totp.post.ts +6 -2
- package/dist/template/server/api/auth/login.post.ts +4 -2
- package/dist/template/server/api/auth/register.post.ts +1 -1
- package/dist/template/server/api/auth/verify/index.post.ts +1 -1
- package/dist/template/server/app/admin/auth.ts +2 -1
- package/dist/template/server/app/features.ts +4 -3
- package/dist/template/server/app/identity/email-change.ts +44 -7
- package/dist/template/server/app/identity/identity.test.ts +70 -0
- package/dist/template/server/app/identity/lockout.ts +8 -3
- package/dist/template/server/app/identity/password-reset.ts +3 -1
- package/dist/template/server/app/identity/service.ts +145 -30
- package/dist/template/server/app/identity/sessions.ts +38 -6
- package/dist/template/server/app/identity/totp-crypto.ts +12 -5
- package/dist/template/server/app/identity/totp.ts +13 -12
- package/dist/template/server/app/identity/verification.ts +3 -1
- package/dist/template/server/app/maintenance/cleanup.test.ts +56 -0
- package/dist/template/server/app/maintenance/cleanup.ts +63 -0
- package/dist/template/server/core/db/migrations.ts +7 -0
- package/dist/template/server/core/db/migrator.ts +5 -1
- package/dist/template/server/core/http/body.ts +1 -1
- package/dist/template/server/core/http/handle.ts +93 -80
- package/dist/template/server/core/http/security.test.ts +38 -0
- package/dist/template/server/core/http/security.ts +17 -5
- package/dist/template/server/core/http/session.ts +15 -0
- package/dist/template/server/core/platform/crypto-and-window.test.ts +75 -0
- package/dist/template/server/core/platform/database.ts +16 -1
- package/dist/template/server/core/platform/pii.ts +5 -8
- package/dist/template/server/core/platform/rate-limiter-strict.ts +35 -5
- package/dist/template/server/core/platform/rate-limiter.ts +2 -2
- package/dist/template/server/core/platform/seal.ts +13 -11
- package/dist/template/server/core/platform/sliding-window.ts +11 -2
- package/dist/template/server/core/platform/tokens.ts +3 -1
- package/dist/template/server/middleware/00-security-headers.ts +8 -4
- package/dist/template/server/middleware/01-user-session.ts +17 -5
- package/dist/template/server/plugins/page-csp.ts +24 -4
- package/dist/template/server/plugins/sessions.ts +4 -2
- package/dist/template/server/routes/auth/github.get.ts +4 -3
- package/dist/template/server/routes/auth/google.get.ts +4 -2
- package/dist/template/server/tasks/cleanup.ts +15 -0
- package/dist/template/server/test/invariants.test.ts +4 -2
- package/dist/template/server/utils/define-validated-handler.ts +14 -12
- package/dist/template/shared/domain/errors.ts +1 -0
- package/dist/template/shared/types/auth.d.ts +1 -1
- package/dist/template/shared/utils/auth.ts +10 -4
- package/dist/template/shared/utils/paths.ts +2 -0
- package/dist/template/shared/utils/schema-validation.ts +1 -1
- package/dist/template/wrangler.json +17 -0
- package/package.json +1 -1
|
@@ -7,6 +7,7 @@ import { TotpCryptoError } from '#server/utils/errors'
|
|
|
7
7
|
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
|
8
8
|
const STEP_SECONDS = 30
|
|
9
9
|
const DIGITS = 6
|
|
10
|
+
const encoder = new TextEncoder()
|
|
10
11
|
|
|
11
12
|
export const base32Encode = (bytes: Uint8Array): string => {
|
|
12
13
|
let bits = 0
|
|
@@ -48,11 +49,9 @@ export const base32Decode = (text: string): Effect.Effect<Uint8Array, TotpCrypto
|
|
|
48
49
|
return Effect.succeed(new Uint8Array(out))
|
|
49
50
|
})
|
|
50
51
|
|
|
51
|
-
|
|
52
|
-
export const hotp = (secret: Uint8Array, counter: number, digits = DIGITS): Effect.Effect<string, CryptoError.CryptoError, Mac.Mac> =>
|
|
52
|
+
const hotpWithKey = (key: Mac.Key, counter: number, digits = DIGITS): Effect.Effect<string, CryptoError.CryptoError, Mac.Mac> =>
|
|
53
53
|
Effect.gen(function* () {
|
|
54
54
|
const mac = yield* Mac.Mac
|
|
55
|
-
const key = yield* Mac.key(Mac.hmacSha1, secret)
|
|
56
55
|
const message = new Uint8Array(8)
|
|
57
56
|
|
|
58
57
|
new DataView(message.buffer).setUint32(4, counter >>> 0)
|
|
@@ -65,6 +64,10 @@ export const hotp = (secret: Uint8Array, counter: number, digits = DIGITS): Effe
|
|
|
65
64
|
return String(code % 10 ** digits).padStart(digits, '0')
|
|
66
65
|
})
|
|
67
66
|
|
|
67
|
+
/** One-time password for a counter (RFC 4226) using HMAC-SHA1 as authenticator apps expect. */
|
|
68
|
+
export const hotp = (secret: Uint8Array, counter: number, digits = DIGITS): Effect.Effect<string, CryptoError.CryptoError, Mac.Mac> =>
|
|
69
|
+
Effect.flatMap(Mac.key(Mac.hmacSha1, secret), (key) => hotpWithKey(key, counter, digits))
|
|
70
|
+
|
|
68
71
|
export const stepOf = (nowMs: number) => Math.floor(nowMs / 1000 / STEP_SECONDS)
|
|
69
72
|
|
|
70
73
|
/**
|
|
@@ -77,8 +80,12 @@ export const verifyTotp = (secret: Uint8Array, code: string, lastStep: number):
|
|
|
77
80
|
|
|
78
81
|
const now = stepOf(yield* nowMillis)
|
|
79
82
|
const candidates = [now, now - 1, now + 1].filter((step) => step > lastStep)
|
|
80
|
-
|
|
81
|
-
|
|
83
|
+
if (!candidates.length) return undefined
|
|
84
|
+
|
|
85
|
+
const key = yield* Mac.key(Mac.hmacSha1, secret)
|
|
86
|
+
const codes = yield* Effect.forEach(candidates, (step) => hotpWithKey(key, step), { concurrency: 'unbounded' })
|
|
87
|
+
const provided = encoder.encode(code)
|
|
88
|
+
const matchedIndex = codes.findIndex((candidate) => Mac.timingSafeEqual(encoder.encode(candidate), provided))
|
|
82
89
|
|
|
83
90
|
return matchedIndex === -1 ? undefined : candidates[matchedIndex]
|
|
84
91
|
})
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Context, Effect, Layer, Redacted, Schema } from 'effect'
|
|
2
2
|
import { Mac, SecureRandom } from 'effect/crypto'
|
|
3
|
-
import { Base64Url } from 'effect/encoding'
|
|
3
|
+
import { Base64Url, Hex } from 'effect/encoding'
|
|
4
4
|
|
|
5
5
|
import type { RateLimited } from '#shared/domain/errors'
|
|
6
6
|
import type { TotpStatus } from '#shared/utils/auth'
|
|
@@ -12,7 +12,6 @@ import { Database } from '#server/core/platform/database'
|
|
|
12
12
|
import { PasswordHasher } from '#server/core/platform/password-hasher'
|
|
13
13
|
import { Pii } from '#server/core/platform/pii'
|
|
14
14
|
import { Seal } from '#server/core/platform/seal'
|
|
15
|
-
import { Tokens } from '#server/core/platform/tokens'
|
|
16
15
|
import { Conflict, Forbidden, Unauthorized, Unprocessable } from '#shared/domain/errors'
|
|
17
16
|
|
|
18
17
|
import type { AuthUser } from './state'
|
|
@@ -91,18 +90,22 @@ export class Totp extends Context.Service<
|
|
|
91
90
|
const hasher = yield* PasswordHasher
|
|
92
91
|
const pii = yield* Pii
|
|
93
92
|
const seal = yield* Seal
|
|
94
|
-
const tokens = yield* Tokens
|
|
95
93
|
const lockout = yield* LoginLockout
|
|
96
94
|
const random = yield* SecureRandom.SecureRandom
|
|
97
95
|
const mac = yield* Mac.Mac
|
|
98
96
|
|
|
99
|
-
const
|
|
97
|
+
const rawAppSecret = Redacted.value(config.appSecret)
|
|
98
|
+
if (rawAppSecret.length < 32) {
|
|
99
|
+
return yield* Effect.die(new Error('NUXT_APP_SECRET must be at least 32 characters (generate with `openssl rand -hex 32`).'))
|
|
100
|
+
}
|
|
101
|
+
const challengeMacKey = yield* Mac.key(Mac.hmacSha256, encoder.encode(rawAppSecret)).pipe(Effect.orDie)
|
|
102
|
+
const challengeKey = Hex.encode(yield* mac.sign(challengeMacKey, encoder.encode(CHALLENGE_CONTEXT)).pipe(Effect.orDie))
|
|
100
103
|
|
|
101
104
|
const assertFeatureOn = () => (config.features.totp ? Effect.void : Effect.fail(new Forbidden({ message: 'Two-factor authentication is disabled.' })))
|
|
102
105
|
|
|
103
106
|
const lockKey = (userId: string) => `totp:${userId}`
|
|
104
107
|
|
|
105
|
-
const hashRecoveryCode = (code: string) =>
|
|
108
|
+
const hashRecoveryCode = (code: string) => pii.index(`recovery:${code.trim().toLowerCase().replace(/[\s-]/g, '')}`)
|
|
106
109
|
|
|
107
110
|
const loadUser = (userId: string) => db.first(UserTotpRow, `SELECT ${USER_COLUMNS} FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
|
|
108
111
|
|
|
@@ -218,10 +221,10 @@ export class Totp extends Context.Service<
|
|
|
218
221
|
}
|
|
219
222
|
|
|
220
223
|
const recoveryCodes = yield* Effect.forEach(Array.from({ length: RECOVERY_CODES_COUNT }), () =>
|
|
221
|
-
random.randomBytes(
|
|
224
|
+
random.randomBytes(10).pipe(
|
|
222
225
|
Effect.map((bytes) => {
|
|
223
|
-
const hex =
|
|
224
|
-
return `${hex.slice(0, 5)}-${hex.slice(5)}`
|
|
226
|
+
const hex = Hex.encode(bytes)
|
|
227
|
+
return `${hex.slice(0, 5)}-${hex.slice(5, 10)}-${hex.slice(10, 15)}-${hex.slice(15)}`
|
|
225
228
|
}),
|
|
226
229
|
),
|
|
227
230
|
)
|
|
@@ -290,9 +293,8 @@ export class Totp extends Context.Service<
|
|
|
290
293
|
|
|
291
294
|
const issueChallenge = Effect.fn('Totp.issueChallenge')(function* (userId: string) {
|
|
292
295
|
yield* assertFeatureOn()
|
|
293
|
-
const key = yield* challengeKey
|
|
294
296
|
const exp = (yield* nowMillis) + CHALLENGE_TTL_MS
|
|
295
|
-
const bytes = yield* seal.seal(encoder.encode(JSON.stringify({ userId, exp })),
|
|
297
|
+
const bytes = yield* seal.seal(encoder.encode(JSON.stringify({ userId, exp })), challengeKey, CHALLENGE_CONTEXT).pipe(Effect.orDie)
|
|
296
298
|
return Base64Url.encode(bytes)
|
|
297
299
|
})
|
|
298
300
|
|
|
@@ -320,8 +322,7 @@ export class Totp extends Context.Service<
|
|
|
320
322
|
const raw = Base64Url.decode(challenge)
|
|
321
323
|
if (raw._tag === 'Failure') return yield* invalid
|
|
322
324
|
|
|
323
|
-
const
|
|
324
|
-
const opened = yield* seal.open(raw.success, key, CHALLENGE_CONTEXT).pipe(Effect.option)
|
|
325
|
+
const opened = yield* seal.open(raw.success, challengeKey, CHALLENGE_CONTEXT).pipe(Effect.option)
|
|
325
326
|
if (opened._tag === 'None') return yield* invalid
|
|
326
327
|
|
|
327
328
|
const parsed = yield* Schema.decodeEffect(ChallengePayload)(decoder.decode(opened.value)).pipe(Effect.option)
|
|
@@ -76,7 +76,9 @@ export class EmailVerification extends Context.Service<
|
|
|
76
76
|
.pipe(Effect.orDie)
|
|
77
77
|
|
|
78
78
|
const rendered = yield* renderer.render(verificationEmail(`${config.appUrl}/verify/${token}`, config.appName))
|
|
79
|
-
yield* mailer
|
|
79
|
+
yield* mailer
|
|
80
|
+
.send({ to: user.email, ...rendered })
|
|
81
|
+
.pipe(Effect.catch((error) => Effect.logWarning(`Verification email failed (${error._tag}): ${error.message}`)))
|
|
80
82
|
})
|
|
81
83
|
|
|
82
84
|
const confirm = Effect.fn('EmailVerification.confirm')(function* (token: string) {
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
|
|
3
|
+
import { LoginLockout } from '#server/app/identity/lockout'
|
|
4
|
+
import { makeTestLayer } from '#server/test/kit'
|
|
5
|
+
|
|
6
|
+
import { Maintenance } from './cleanup'
|
|
7
|
+
|
|
8
|
+
describe('maintenance cleanup and lockout decay', () => {
|
|
9
|
+
it('purges expired sessions, tokens, stale login failures, and abandoned unverified users while keeping active rows', async () => {
|
|
10
|
+
const { run, db } = await makeTestLayer()
|
|
11
|
+
const now = new Date().toISOString()
|
|
12
|
+
const past = new Date(Date.now() - 8 * 24 * 60 * 60_000).toISOString()
|
|
13
|
+
const staleLock = new Date(Date.now() - 20 * 60_000).toISOString()
|
|
14
|
+
const future = new Date(Date.now() + 24 * 60 * 60_000).toISOString()
|
|
15
|
+
|
|
16
|
+
await db.exec(
|
|
17
|
+
`INSERT INTO users (id, username, email, password_hash, email_status, email_verified_at, totp_status, created_at, last_active_at)
|
|
18
|
+
VALUES ('usr_old', 'olduser', 'old@example.com', 'fake:pw', 'unverified', NULL, 'off', '${past}', '${past}'),
|
|
19
|
+
('usr_live', 'liveuser', 'live@example.com', 'fake:pw', 'verified', '${past}', 'off', '${past}', '${now}')`,
|
|
20
|
+
)
|
|
21
|
+
await db.exec(
|
|
22
|
+
`INSERT INTO sessions (id, user_id, device, created_at, last_seen_at, expires_at)
|
|
23
|
+
VALUES ('ses_expired', 'usr_live', 'Chrome', '${past}', '${past}', '${staleLock}'),
|
|
24
|
+
('ses_active', 'usr_live', 'Chrome', '${now}', '${now}', '${future}')`,
|
|
25
|
+
)
|
|
26
|
+
await db.exec(
|
|
27
|
+
`INSERT INTO login_failures (subject, status, failures, locked_until, updated_at)
|
|
28
|
+
VALUES ('identity:stale', 'counting', 4, NULL, '${staleLock}'),
|
|
29
|
+
('identity:fresh', 'counting', 2, NULL, '${now}')`,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
const summary = await run(Maintenance.use((m) => m.purgeExpired))
|
|
33
|
+
expect(summary.sessions).toBe(1)
|
|
34
|
+
expect(summary.loginFailures).toBe(1)
|
|
35
|
+
expect(summary.staleUnverifiedUsers).toBe(1)
|
|
36
|
+
|
|
37
|
+
const remainingSessions = await db.prepare(`SELECT id FROM sessions`).all()
|
|
38
|
+
expect(remainingSessions).toHaveLength(1)
|
|
39
|
+
const remainingUsers = await db.prepare(`SELECT id FROM users`).all()
|
|
40
|
+
expect(remainingUsers).toHaveLength(1)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('decays stale counting login_failures rows instead of locking on the next attempt', async () => {
|
|
44
|
+
const { run, db } = await makeTestLayer()
|
|
45
|
+
const stale = new Date(Date.now() - 20 * 60_000).toISOString()
|
|
46
|
+
|
|
47
|
+
await db.exec(
|
|
48
|
+
`INSERT INTO login_failures (subject, status, failures, locked_until, updated_at)
|
|
49
|
+
VALUES ('user:decay', 'counting', 4, NULL, '${stale}')`,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
// Recording one more failure after the decay window resets count to 1 instead of locking
|
|
53
|
+
await run(LoginLockout.use((l) => l.recordFailure('user:decay')))
|
|
54
|
+
await expect(run(LoginLockout.use((l) => l.assertUnlocked('user:decay')))).resolves.toBeUndefined()
|
|
55
|
+
})
|
|
56
|
+
})
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Context, DateTime, Effect, Layer } from 'effect'
|
|
2
|
+
|
|
3
|
+
import { AtomicBatch } from '#server/core/db/atomic'
|
|
4
|
+
|
|
5
|
+
const LOCKOUT_DECAY_MINUTES = 15
|
|
6
|
+
const UNVERIFIED_USER_RETENTION_DAYS = 7
|
|
7
|
+
|
|
8
|
+
export interface CleanupSummary {
|
|
9
|
+
readonly sessions: number
|
|
10
|
+
readonly adminSessions: number
|
|
11
|
+
readonly verificationTokens: number
|
|
12
|
+
readonly resetTokens: number
|
|
13
|
+
readonly emailChangeTokens: number
|
|
14
|
+
readonly loginFailures: number
|
|
15
|
+
readonly staleUnverifiedUsers: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Purges expired sessions, tokens, stale lockout counters, and abandoned unverified accounts in one atomic D1 batch. */
|
|
19
|
+
export class Maintenance extends Context.Service<Maintenance, { readonly purgeExpired: Effect.Effect<CleanupSummary> }>()('app/maintenance/Maintenance') {
|
|
20
|
+
static readonly layer = Layer.effect(
|
|
21
|
+
Maintenance,
|
|
22
|
+
Effect.gen(function* () {
|
|
23
|
+
const atomic = yield* AtomicBatch
|
|
24
|
+
|
|
25
|
+
const purgeExpired = Effect.gen(function* () {
|
|
26
|
+
const now = yield* DateTime.now
|
|
27
|
+
const nowStr = DateTime.formatIso(now)
|
|
28
|
+
const lockoutCutoff = DateTime.formatIso(DateTime.subtract(now, { minutes: LOCKOUT_DECAY_MINUTES }))
|
|
29
|
+
const unverifiedCutoff = DateTime.formatIso(DateTime.subtract(now, { days: UNVERIFIED_USER_RETENTION_DAYS }))
|
|
30
|
+
|
|
31
|
+
const [sessions, adminSessions, verificationTokens, resetTokens, emailChangeTokens, loginFailures, staleUnverifiedUsers] = yield* atomic
|
|
32
|
+
.run([
|
|
33
|
+
{ sql: `DELETE FROM sessions WHERE expires_at <= ?`, params: [nowStr] },
|
|
34
|
+
{ sql: `DELETE FROM admin_sessions WHERE expires_at <= ?`, params: [nowStr] },
|
|
35
|
+
{ sql: `DELETE FROM email_verification_tokens WHERE expires_at <= ?`, params: [nowStr] },
|
|
36
|
+
{ sql: `DELETE FROM password_reset_tokens WHERE expires_at <= ?`, params: [nowStr] },
|
|
37
|
+
{ sql: `DELETE FROM email_change_tokens WHERE expires_at <= ?`, params: [nowStr] },
|
|
38
|
+
{
|
|
39
|
+
sql: `DELETE FROM login_failures WHERE (status = 'locked' AND locked_until <= ?) OR (status = 'counting' AND updated_at <= ?)`,
|
|
40
|
+
params: [nowStr, lockoutCutoff],
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
sql: `DELETE FROM users WHERE email_status = 'unverified' AND google_sub IS NULL AND github_id IS NULL AND created_at <= ?`,
|
|
44
|
+
params: [unverifiedCutoff],
|
|
45
|
+
},
|
|
46
|
+
])
|
|
47
|
+
.pipe(Effect.orDie)
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
sessions: sessions?.changes ?? 0,
|
|
51
|
+
adminSessions: adminSessions?.changes ?? 0,
|
|
52
|
+
verificationTokens: verificationTokens?.changes ?? 0,
|
|
53
|
+
resetTokens: resetTokens?.changes ?? 0,
|
|
54
|
+
emailChangeTokens: emailChangeTokens?.changes ?? 0,
|
|
55
|
+
loginFailures: loginFailures?.changes ?? 0,
|
|
56
|
+
staleUnverifiedUsers: staleUnverifiedUsers?.changes ?? 0,
|
|
57
|
+
} satisfies CleanupSummary
|
|
58
|
+
}).pipe(Effect.withSpan('Maintenance.purgeExpired'))
|
|
59
|
+
|
|
60
|
+
return Maintenance.of({ purgeExpired })
|
|
61
|
+
}),
|
|
62
|
+
)
|
|
63
|
+
}
|
|
@@ -68,11 +68,13 @@ export const migrations: ReadonlyArray<Migration> = [
|
|
|
68
68
|
status TEXT NOT NULL CHECK (status IN ('counting', 'locked')),
|
|
69
69
|
failures INTEGER NOT NULL CHECK (failures >= 0),
|
|
70
70
|
locked_until TEXT,
|
|
71
|
+
updated_at TEXT NOT NULL,
|
|
71
72
|
CHECK (
|
|
72
73
|
(status = 'counting' AND failures > 0 AND locked_until IS NULL) OR
|
|
73
74
|
(status = 'locked' AND failures = 0 AND locked_until IS NOT NULL)
|
|
74
75
|
)
|
|
75
76
|
)`,
|
|
77
|
+
`CREATE INDEX idx_login_failures_updated ON login_failures (updated_at)`,
|
|
76
78
|
`CREATE TABLE email_verification_tokens (
|
|
77
79
|
token_hash TEXT PRIMARY KEY,
|
|
78
80
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
@@ -90,6 +92,7 @@ export const migrations: ReadonlyArray<Migration> = [
|
|
|
90
92
|
)
|
|
91
93
|
)`,
|
|
92
94
|
`CREATE INDEX idx_email_verification_user ON email_verification_tokens (user_id, status)`,
|
|
95
|
+
`CREATE INDEX idx_email_verification_expires ON email_verification_tokens (expires_at)`,
|
|
93
96
|
`CREATE TABLE password_reset_tokens (
|
|
94
97
|
token_hash TEXT PRIMARY KEY,
|
|
95
98
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
@@ -106,6 +109,7 @@ export const migrations: ReadonlyArray<Migration> = [
|
|
|
106
109
|
)
|
|
107
110
|
)`,
|
|
108
111
|
`CREATE INDEX idx_password_reset_user ON password_reset_tokens (user_id, status)`,
|
|
112
|
+
`CREATE INDEX idx_password_reset_expires ON password_reset_tokens (expires_at)`,
|
|
109
113
|
`CREATE TABLE email_change_tokens (
|
|
110
114
|
token_hash TEXT PRIMARY KEY,
|
|
111
115
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
@@ -123,6 +127,7 @@ export const migrations: ReadonlyArray<Migration> = [
|
|
|
123
127
|
)
|
|
124
128
|
)`,
|
|
125
129
|
`CREATE INDEX idx_email_change_user ON email_change_tokens (user_id, status)`,
|
|
130
|
+
`CREATE INDEX idx_email_change_expires ON email_change_tokens (expires_at)`,
|
|
126
131
|
`CREATE TABLE admins (
|
|
127
132
|
email TEXT PRIMARY KEY CHECK (email = lower(trim(email))),
|
|
128
133
|
password_hash TEXT NOT NULL,
|
|
@@ -136,6 +141,7 @@ export const migrations: ReadonlyArray<Migration> = [
|
|
|
136
141
|
CHECK (expires_at > created_at)
|
|
137
142
|
)`,
|
|
138
143
|
`CREATE INDEX idx_admin_sessions_email ON admin_sessions (email)`,
|
|
144
|
+
`CREATE INDEX idx_admin_sessions_expires ON admin_sessions (expires_at)`,
|
|
139
145
|
`CREATE TABLE admin_audit (
|
|
140
146
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
141
147
|
actor_email TEXT NOT NULL,
|
|
@@ -144,6 +150,7 @@ export const migrations: ReadonlyArray<Migration> = [
|
|
|
144
150
|
detail TEXT,
|
|
145
151
|
created_at TEXT NOT NULL
|
|
146
152
|
)`,
|
|
153
|
+
`CREATE INDEX idx_admin_audit_created ON admin_audit (created_at DESC)`,
|
|
147
154
|
],
|
|
148
155
|
},
|
|
149
156
|
]
|
|
@@ -14,9 +14,13 @@ const Applied = Schema.Struct({ id: Schema.String })
|
|
|
14
14
|
*/
|
|
15
15
|
const RACE_RETRY = Schedule.exponential('100 millis').pipe(Schedule.jittered)
|
|
16
16
|
|
|
17
|
-
/**
|
|
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
|
+
*/
|
|
18
21
|
export const MigratorLive = Layer.effectDiscard(
|
|
19
22
|
Effect.gen(function* () {
|
|
23
|
+
if (!import.meta.dev) return
|
|
20
24
|
const db = yield* Database
|
|
21
25
|
const atomic = yield* AtomicBatch
|
|
22
26
|
yield* db.run(`CREATE TABLE IF NOT EXISTS _migrations (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`)
|
|
@@ -9,7 +9,7 @@ const JSON_LIMIT = 1024 * 1024
|
|
|
9
9
|
|
|
10
10
|
/** Maximum body size in bytes for API writes, or undefined when the route reads no body. */
|
|
11
11
|
export const bodyLimitFor = (method: string, path: string): number | undefined => {
|
|
12
|
-
if (!['POST', 'PUT', 'PATCH'].includes(method) || !path.startsWith('/api/')) return undefined
|
|
12
|
+
if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) || !path.startsWith('/api/')) return undefined
|
|
13
13
|
return JSON_LIMIT
|
|
14
14
|
}
|
|
15
15
|
|
|
@@ -13,7 +13,7 @@ import { AdminActor, AdminAuth, isLocalHost } from '#server/app/admin/auth'
|
|
|
13
13
|
import { AppConfig } from '#server/core/platform/app-config'
|
|
14
14
|
import { RateLimiter } from '#server/core/platform/rate-limiter'
|
|
15
15
|
import { Turnstile } from '#server/core/platform/turnstile'
|
|
16
|
-
import {
|
|
16
|
+
import { validateRequest } from '#server/utils/define-validated-handler'
|
|
17
17
|
import { Forbidden, Unauthorized } from '#shared/domain/errors'
|
|
18
18
|
import { ADMIN_COOKIE, ADMIN_SESSION_HOURS } from '#shared/utils/admin'
|
|
19
19
|
import { readKey } from '#shared/utils/unknown'
|
|
@@ -87,7 +87,7 @@ export const compile = (schemas: RouteSchemas) => ({
|
|
|
87
87
|
/** Redacts 64-hex single-use tokens from request paths before logging. */
|
|
88
88
|
export const logPath = (url: string) => new URL(url).pathname.replace(/^(\/(?:verify|reset|email)\/)[0-9a-f]{64}/, '$1[token]')
|
|
89
89
|
|
|
90
|
-
const crossSite = (event: RequestEvent) => UNSAFE_METHODS.has(event.req.method) && !isSameOriginRequest(event.req.headers, new URL(event.req.url).
|
|
90
|
+
const crossSite = (event: RequestEvent) => UNSAFE_METHODS.has(event.req.method) && !isSameOriginRequest(event.req.headers, new URL(event.req.url).origin)
|
|
91
91
|
|
|
92
92
|
const crossSiteError = () => new Forbidden({ message: 'Cross-site requests are not allowed.' })
|
|
93
93
|
|
|
@@ -100,17 +100,40 @@ export const guards = (schemas: RouteSchemas, event: RequestEvent) =>
|
|
|
100
100
|
if (schemas.captcha) yield* Turnstile.use((turnstile) => turnstile.verify(event.req.headers.get('x-turnstile-token') ?? undefined, ip))
|
|
101
101
|
})
|
|
102
102
|
|
|
103
|
-
|
|
103
|
+
class RequestValidationError {
|
|
104
|
+
readonly _tag = 'RequestValidationError'
|
|
105
|
+
constructor(readonly httpError: unknown) {}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const isValidationError = (value: unknown): value is RequestValidationError => value instanceof RequestValidationError
|
|
109
|
+
|
|
110
|
+
const parseInput = (event: RequestEvent, validate: ReturnType<typeof compile>['validate']) =>
|
|
111
|
+
Effect.tryPromise({
|
|
112
|
+
try: () => validateRequest(event, validate),
|
|
113
|
+
catch: (httpError) => new RequestValidationError(httpError),
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
const runEffect = async <A>(
|
|
117
|
+
event: RequestEvent,
|
|
118
|
+
program: Effect.Effect<A, ApiFailure | Schema.SchemaError | RequestValidationError, AppServices>,
|
|
119
|
+
audience: Audience,
|
|
120
|
+
): Promise<A> => {
|
|
104
121
|
const exit = await runtime.runPromiseExit(program.pipe(Effect.annotateLogs({ method: event.req.method, path: logPath(event.req.url) })))
|
|
105
122
|
|
|
106
123
|
if (Exit.isSuccess(exit)) return exit.value
|
|
107
124
|
|
|
108
125
|
const failure = Cause.findError(exit.cause)
|
|
109
|
-
if (failure._tag === 'Success'
|
|
110
|
-
if (
|
|
111
|
-
|
|
126
|
+
if (failure._tag === 'Success') {
|
|
127
|
+
if (isValidationError(failure.success)) throw failure.success.httpError
|
|
128
|
+
if (isApiFailure(failure.success)) {
|
|
129
|
+
if (failure.success._tag === 'RateLimited' && failure.success.retryAfterSeconds !== undefined) {
|
|
130
|
+
event.res.headers.set('retry-after', String(failure.success.retryAfterSeconds))
|
|
131
|
+
}
|
|
132
|
+
if (audience === 'public' && isWithheld(failure.success._tag)) {
|
|
133
|
+
await runtime.runPromise(Effect.logWarning(`${logPath(event.req.url)}: ${failure.success._tag}: ${failure.success.message}`))
|
|
134
|
+
}
|
|
135
|
+
throw toHttpError(failure.success, audience)
|
|
112
136
|
}
|
|
113
|
-
throw toHttpError(failure.success, audience)
|
|
114
137
|
}
|
|
115
138
|
|
|
116
139
|
await runtime.runPromise(Effect.logError(Cause.pretty(exit.cause)))
|
|
@@ -119,7 +142,7 @@ const runEffect = async <A>(event: RequestEvent, program: Effect.Effect<A, ApiFa
|
|
|
119
142
|
|
|
120
143
|
export const respond = async <D extends RouteSchemas>(
|
|
121
144
|
event: RequestEvent,
|
|
122
|
-
program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices>,
|
|
145
|
+
program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError | RequestValidationError, AppServices>,
|
|
123
146
|
audience: Audience,
|
|
124
147
|
): Promise<OutputOf<D>> => {
|
|
125
148
|
const value = await runEffect(event, program, audience)
|
|
@@ -128,28 +151,28 @@ export const respond = async <D extends RouteSchemas>(
|
|
|
128
151
|
return value as OutputOf<D>
|
|
129
152
|
}
|
|
130
153
|
|
|
131
|
-
/** Public route: same-origin check on unsafe methods, rate limit + Turnstile
|
|
154
|
+
/** Public route: same-origin check on unsafe methods, then single Effect pass for rate limit + Turnstile, input validation, handler, and response encoding. */
|
|
132
155
|
export const handlePublic = <const D extends RouteSchemas>(
|
|
133
156
|
schemas: D,
|
|
134
157
|
run: (input: InputOf<D>, event: RequestEvent) => Effect.Effect<OutputOf<D>, ApiFailure, AppServices>,
|
|
135
158
|
): EventHandler<Promise<OutputOf<D>>> => {
|
|
136
159
|
const { validate, encode } = compile(schemas)
|
|
137
|
-
const validated = defineValidatedHandler({
|
|
138
|
-
validate,
|
|
139
|
-
handler: async (event, input) => {
|
|
140
|
-
// `validate` was compiled from the same schemas.
|
|
141
|
-
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
142
|
-
const ran = crossSite(event) ? Effect.fail(crossSiteError()) : run(input as InputOf<D>, event)
|
|
143
|
-
const program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices> = encode ? Effect.flatMap(ran, encode) : ran
|
|
144
|
-
const value = await respond<D>(event, program, 'public')
|
|
145
|
-
if (!schemas.response) setResponseStatus(event, 204)
|
|
146
|
-
return value
|
|
147
|
-
},
|
|
148
|
-
})
|
|
149
160
|
return defineHandler<Promise<OutputOf<D>>>(async (event) => {
|
|
150
|
-
if (crossSite(event))
|
|
151
|
-
|
|
152
|
-
|
|
161
|
+
if (crossSite(event)) throw toHttpError(crossSiteError(), 'public')
|
|
162
|
+
const value = await respond<D>(
|
|
163
|
+
event,
|
|
164
|
+
Effect.gen(function* () {
|
|
165
|
+
if (schemas.limit || schemas.captcha) yield* guards(schemas, event)
|
|
166
|
+
const input = yield* parseInput(event, validate)
|
|
167
|
+
// `validate` was compiled from the same schemas.
|
|
168
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
169
|
+
const out = yield* run(input as InputOf<D>, event)
|
|
170
|
+
return encode ? yield* encode(out) : out
|
|
171
|
+
}),
|
|
172
|
+
'public',
|
|
173
|
+
)
|
|
174
|
+
if (!schemas.response) setResponseStatus(event, 204)
|
|
175
|
+
return value
|
|
153
176
|
})
|
|
154
177
|
}
|
|
155
178
|
|
|
@@ -169,40 +192,28 @@ export const handleAuthed = <const D extends RouteSchemas>(
|
|
|
169
192
|
const verificationPolicy: VerificationPolicy = options.verification ?? 'required'
|
|
170
193
|
const { validate, encode } = compile(schemas)
|
|
171
194
|
|
|
172
|
-
const checkAccess = (event: RequestEvent) =>
|
|
173
|
-
Effect.gen(function* () {
|
|
174
|
-
const user = requestUser(event)
|
|
175
|
-
if (!user) return yield* new Unauthorized({ message: 'Please sign in again.' })
|
|
176
|
-
const config = yield* AppConfig
|
|
177
|
-
if (verificationPolicy === 'required' && config.features.emailVerificationRequired && user.emailStatus !== 'verified') {
|
|
178
|
-
return yield* new Forbidden({ message: UNCONFIRMED })
|
|
179
|
-
}
|
|
180
|
-
return user
|
|
181
|
-
})
|
|
182
|
-
|
|
183
|
-
const validated = defineValidatedHandler({
|
|
184
|
-
validate,
|
|
185
|
-
handler: async (event, input) => {
|
|
186
|
-
const program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices> = Effect.gen(function* () {
|
|
187
|
-
const user = yield* checkAccess(event)
|
|
188
|
-
// `validate` was compiled from the same schemas.
|
|
189
|
-
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
190
|
-
const value = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(UserActor, user))
|
|
191
|
-
return encode ? yield* encode(value) : value
|
|
192
|
-
})
|
|
193
|
-
const value = await respond<D>(event, program, 'authed')
|
|
194
|
-
if (!schemas.response) setResponseStatus(event, 204)
|
|
195
|
-
return value
|
|
196
|
-
},
|
|
197
|
-
})
|
|
198
|
-
|
|
199
195
|
return defineHandler<Promise<OutputOf<D>>>(async (event) => {
|
|
200
|
-
if (crossSite(event))
|
|
196
|
+
if (crossSite(event)) throw toHttpError(crossSiteError(), 'public')
|
|
201
197
|
const user = requestUser(event)
|
|
202
|
-
if (!user)
|
|
203
|
-
await
|
|
204
|
-
|
|
205
|
-
|
|
198
|
+
if (!user) throw toHttpError(new Unauthorized({ message: 'Please sign in again.' }), 'public')
|
|
199
|
+
const value = await respond<D>(
|
|
200
|
+
event,
|
|
201
|
+
Effect.gen(function* () {
|
|
202
|
+
const config = yield* AppConfig
|
|
203
|
+
if (verificationPolicy === 'required' && config.features.emailVerificationRequired && user.emailStatus !== 'verified') {
|
|
204
|
+
return yield* new Forbidden({ message: UNCONFIRMED })
|
|
205
|
+
}
|
|
206
|
+
if (schemas.limit || schemas.captcha) yield* guards(schemas, event)
|
|
207
|
+
const input = yield* parseInput(event, validate)
|
|
208
|
+
// `validate` was compiled from the same schemas.
|
|
209
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
210
|
+
const out = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(UserActor, user))
|
|
211
|
+
return encode ? yield* encode(out) : out
|
|
212
|
+
}),
|
|
213
|
+
'authed',
|
|
214
|
+
)
|
|
215
|
+
if (!schemas.response) setResponseStatus(event, 204)
|
|
216
|
+
return value
|
|
206
217
|
})
|
|
207
218
|
}
|
|
208
219
|
|
|
@@ -219,39 +230,26 @@ export const handleAdmin = <const D extends RouteSchemas>(
|
|
|
219
230
|
): EventHandler<Promise<OutputOf<D>>> => {
|
|
220
231
|
const gate: AdminGate = options.gate ?? 'access-and-session'
|
|
221
232
|
const { validate, encode } = compile(schemas)
|
|
222
|
-
const actors = new WeakMap<RequestEvent, { readonly email: string }>()
|
|
223
|
-
|
|
224
|
-
const validated = defineValidatedHandler({
|
|
225
|
-
validate,
|
|
226
|
-
handler: async (event, input) => {
|
|
227
|
-
const program: Effect.Effect<unknown, ApiFailure | Schema.SchemaError, AppServices> = Effect.gen(function* () {
|
|
228
|
-
const actor = actors.get(event)
|
|
229
|
-
if (!actor) return yield* new Unauthorized({ message: 'Sign in to the admin.' })
|
|
230
|
-
// `validate` was compiled from the same schemas.
|
|
231
|
-
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
232
|
-
const value = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(AdminActor, actor))
|
|
233
|
-
return encode ? yield* encode(value) : value
|
|
234
|
-
})
|
|
235
|
-
const value = await respond<D>(event, program, 'authed')
|
|
236
|
-
if (!schemas.response) setResponseStatus(event, 204)
|
|
237
|
-
return value
|
|
238
|
-
},
|
|
239
|
-
})
|
|
240
233
|
|
|
241
234
|
return defineHandler<Promise<OutputOf<D>>>(async (event) => {
|
|
242
|
-
if (crossSite(event))
|
|
243
|
-
const
|
|
235
|
+
if (crossSite(event)) throw toHttpError(crossSiteError(), 'public')
|
|
236
|
+
const value = await respond<D>(
|
|
244
237
|
event,
|
|
245
238
|
Effect.gen(function* () {
|
|
246
239
|
const auth = yield* AdminAuth
|
|
247
240
|
const accessEmail = yield* auth.gate(getAccessIdentity(event))
|
|
248
|
-
|
|
241
|
+
const actor = gate === 'access-only' ? { email: accessEmail } : yield* auth.session(accessEmail, getCookie(event, ADMIN_COOKIE))
|
|
242
|
+
if (schemas.limit || schemas.captcha) yield* guards(schemas, event)
|
|
243
|
+
const input = yield* parseInput(event, validate)
|
|
244
|
+
// `validate` was compiled from the same schemas.
|
|
245
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
246
|
+
const out = yield* run(input as InputOf<D>, event).pipe(Effect.provideService(AdminActor, actor))
|
|
247
|
+
return encode ? yield* encode(out) : out
|
|
249
248
|
}),
|
|
250
249
|
'authed',
|
|
251
250
|
)
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
return validated(event)
|
|
251
|
+
if (!schemas.response) setResponseStatus(event, 204)
|
|
252
|
+
return value
|
|
255
253
|
})
|
|
256
254
|
}
|
|
257
255
|
|
|
@@ -266,3 +264,18 @@ export const setAdminCookie = (event: RequestEvent, token: string) =>
|
|
|
266
264
|
|
|
267
265
|
export const clearAdminCookie = (event: RequestEvent) => deleteCookie(event, ADMIN_COOKIE, { path: '/api/admin' })
|
|
268
266
|
export const adminCookieOf = (event: RequestEvent) => getCookie(event, ADMIN_COOKIE)
|
|
267
|
+
|
|
268
|
+
export const TOTP_CHALLENGE_COOKIE = 'app_totp'
|
|
269
|
+
|
|
270
|
+
/** Short-lived HttpOnly cookie carrying the AEAD-sealed 2FA login challenge so OAuth redirects never put tokens in URLs. */
|
|
271
|
+
export const setTotpChallengeCookie = (event: RequestEvent, challenge: string) =>
|
|
272
|
+
setCookie(event, TOTP_CHALLENGE_COOKIE, challenge, {
|
|
273
|
+
httpOnly: true,
|
|
274
|
+
secure: !isLocalHost(event.req.url),
|
|
275
|
+
sameSite: 'lax',
|
|
276
|
+
path: '/api/auth/login/totp',
|
|
277
|
+
maxAge: 5 * 60,
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
export const clearTotpChallengeCookie = (event: RequestEvent) => deleteCookie(event, TOTP_CHALLENGE_COOKIE, { path: '/api/auth/login/totp' })
|
|
281
|
+
export const totpChallengeCookieOf = (event: RequestEvent) => getCookie(event, TOTP_CHALLENGE_COOKIE)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
|
|
3
|
+
import { isSameOriginRequest, stampScriptNonces } from './security'
|
|
4
|
+
|
|
5
|
+
describe('isSameOriginRequest', () => {
|
|
6
|
+
const headers = (entries: Record<string, string>) => new Headers(entries)
|
|
7
|
+
|
|
8
|
+
it('requires full origin match including scheme and refuses cookie-bearing requests lacking origin headers', () => {
|
|
9
|
+
expect(isSameOriginRequest(headers({ 'sec-fetch-site': 'same-origin' }), 'https://example.com')).toBe(true)
|
|
10
|
+
expect(isSameOriginRequest(headers({ 'sec-fetch-site': 'cross-site' }), 'https://example.com')).toBe(false)
|
|
11
|
+
expect(isSameOriginRequest(headers({ origin: 'https://example.com' }), 'https://example.com')).toBe(true)
|
|
12
|
+
expect(isSameOriginRequest(headers({ origin: 'http://example.com' }), 'https://example.com')).toBe(false)
|
|
13
|
+
expect(isSameOriginRequest(headers({ cookie: 'app-session=abc' }), 'https://example.com')).toBe(false)
|
|
14
|
+
expect(isSameOriginRequest(headers({}), 'https://example.com')).toBe(true)
|
|
15
|
+
})
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
describe('stampScriptNonces', () => {
|
|
19
|
+
it('stamps executable script tags and importmaps while skipping JSON payload blocks and inner text', () => {
|
|
20
|
+
const nonce = 'test-nonce-123'
|
|
21
|
+
const fragment = [
|
|
22
|
+
`<script type="importmap">{"imports":{"#entry":"/_nuxt/entry.js"}}</script>`,
|
|
23
|
+
`<script type="module" src="/_nuxt/entry.js" crossorigin></script>`,
|
|
24
|
+
`<script type="application/json" id="__NUXT_DATA__">[{"note":"<script>alert(1)<\\/script>"}]</script>`,
|
|
25
|
+
`<script>window.__NUXT__={};window.__NUXT__.config={}</script>`,
|
|
26
|
+
`<script nonce="existing">ok()</script>`,
|
|
27
|
+
].join('')
|
|
28
|
+
|
|
29
|
+
const stamped = stampScriptNonces(fragment, nonce)
|
|
30
|
+
|
|
31
|
+
expect(stamped).toContain(`<script nonce="${nonce}" type="importmap">`)
|
|
32
|
+
expect(stamped).toContain(`<script nonce="${nonce}" type="module" src="/_nuxt/entry.js" crossorigin></script>`)
|
|
33
|
+
expect(stamped).toContain(`<script nonce="${nonce}">window.__NUXT__={};window.__NUXT__.config={}</script>`)
|
|
34
|
+
expect(stamped).toContain(`<script nonce="existing">ok()</script>`)
|
|
35
|
+
expect(stamped).toContain(`<script type="application/json" id="__NUXT_DATA__">[{"note":"<script>alert(1)<\\/script>"}]</script>`)
|
|
36
|
+
expect(stamped).not.toContain(`<script nonce="${nonce}">alert(1)`)
|
|
37
|
+
})
|
|
38
|
+
})
|