@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.
- package/README.md +55 -2
- package/dist/cli.js +322 -0
- package/dist/template/.env.example +22 -0
- package/dist/template/.github/workflows/ci.yml +96 -0
- package/dist/template/.oxfmtrc.json +18 -0
- package/dist/template/.oxlintrc.json +69 -0
- package/dist/template/CLAUDE.md +42 -0
- package/dist/template/_gitignore +14 -0
- package/dist/template/app/app.vue +3 -0
- package/dist/template/app/components/qr-code.vue +36 -0
- package/dist/template/app/components/totp-setup.vue +151 -0
- package/dist/template/app/composables/use-features.ts +1 -0
- package/dist/template/app/composables/use-me.ts +10 -0
- package/dist/template/app/middleware/admin.global.ts +12 -0
- package/dist/template/app/middleware/auth.ts +6 -0
- package/dist/template/app/middleware/guest.ts +4 -0
- package/dist/template/app/pages/account.vue +22 -0
- package/dist/template/app/pages/admin/index.vue +16 -0
- package/dist/template/app/pages/admin/login.vue +39 -0
- package/dist/template/app/pages/index.vue +18 -0
- package/dist/template/app/pages/login.vue +110 -0
- package/dist/template/app/pages/register.vue +51 -0
- package/dist/template/app/utils/api-error.ts +50 -0
- package/dist/template/nuxt.config.ts +115 -0
- package/dist/template/package.json +59 -0
- package/dist/template/scripts/admin-password.ts +123 -0
- package/dist/template/server/api/account/email/index.delete.ts +5 -0
- package/dist/template/server/api/account/email/index.post.ts +8 -0
- package/dist/template/server/api/account/index.delete.ts +18 -0
- package/dist/template/server/api/account/index.patch.ts +16 -0
- package/dist/template/server/api/account/sessions.get.ts +11 -0
- package/dist/template/server/api/account/totp/cancel.post.ts +5 -0
- package/dist/template/server/api/account/totp/confirm.post.ts +10 -0
- package/dist/template/server/api/account/totp/disable.post.ts +8 -0
- package/dist/template/server/api/account/totp/index.get.ts +6 -0
- package/dist/template/server/api/account/totp/start.post.ts +8 -0
- package/dist/template/server/api/admin/me.get.ts +7 -0
- package/dist/template/server/api/admin/session/index.delete.ts +12 -0
- package/dist/template/server/api/admin/session/index.post.ts +18 -0
- package/dist/template/server/api/auth/email/index.post.ts +13 -0
- package/dist/template/server/api/auth/login/totp.post.ts +15 -0
- package/dist/template/server/api/auth/login.post.ts +17 -0
- package/dist/template/server/api/auth/logout-everywhere.post.ts +17 -0
- package/dist/template/server/api/auth/logout.post.ts +14 -0
- package/dist/template/server/api/auth/register.post.ts +18 -0
- package/dist/template/server/api/auth/reset/check.post.ts +5 -0
- package/dist/template/server/api/auth/reset/index.post.ts +5 -0
- package/dist/template/server/api/auth/reset/request.post.ts +5 -0
- package/dist/template/server/api/auth/verify/index.post.ts +17 -0
- package/dist/template/server/api/auth/verify/send.post.ts +7 -0
- package/dist/template/server/api/me.get.ts +8 -0
- package/dist/template/server/app/admin/auth.test.ts +41 -0
- package/dist/template/server/app/admin/auth.ts +133 -0
- package/dist/template/server/app/features.ts +18 -0
- package/dist/template/server/app/identity/email-change.ts +147 -0
- package/dist/template/server/app/identity/identity.test.ts +119 -0
- package/dist/template/server/app/identity/lockout.ts +93 -0
- package/dist/template/server/app/identity/password-reset.ts +119 -0
- package/dist/template/server/app/identity/service.ts +379 -0
- package/dist/template/server/app/identity/sessions.ts +141 -0
- package/dist/template/server/app/identity/state.ts +41 -0
- package/dist/template/server/app/identity/totp-crypto.ts +89 -0
- package/dist/template/server/app/identity/totp.test.ts +103 -0
- package/dist/template/server/app/identity/totp.ts +361 -0
- package/dist/template/server/app/identity/verification.ts +120 -0
- package/dist/template/server/app/notifications/email.ts +12 -0
- package/dist/template/server/app/notifications/render.test.ts +26 -0
- package/dist/template/server/app/notifications/render.ts +82 -0
- package/dist/template/server/app/notifications/samples.ts +11 -0
- package/dist/template/server/app/notifications/templates.ts +37 -0
- package/dist/template/server/assets/email/blocks/button.html +1 -0
- package/dist/template/server/assets/email/blocks/lead.html +1 -0
- package/dist/template/server/assets/email/blocks/note.html +1 -0
- package/dist/template/server/assets/email/blocks/text.html +1 -0
- package/dist/template/server/assets/email/layout.html +22 -0
- package/dist/template/server/cloudflare/exports/rate-limit.do.ts +38 -0
- package/dist/template/server/core/app-layer.ts +33 -0
- package/dist/template/server/core/db/atomic-d1.ts +21 -0
- package/dist/template/server/core/db/atomic.ts +86 -0
- package/dist/template/server/core/db/chunked.ts +13 -0
- package/dist/template/server/core/db/migrations.ts +149 -0
- package/dist/template/server/core/db/migrator.ts +39 -0
- package/dist/template/server/core/http/body-limit.ts +35 -0
- package/dist/template/server/core/http/csrf.ts +16 -0
- package/dist/template/server/core/http/device-label.ts +27 -0
- package/dist/template/server/core/http/handle.ts +271 -0
- package/dist/template/server/core/http/limit-key.ts +17 -0
- package/dist/template/server/core/http/page-csp.ts +16 -0
- package/dist/template/server/core/http/public-failure.ts +9 -0
- package/dist/template/server/core/http/request-user.ts +13 -0
- package/dist/template/server/core/http/runtime.ts +30 -0
- package/dist/template/server/core/http/session-cookie.ts +29 -0
- package/dist/template/server/core/platform/app-config.ts +55 -0
- package/dist/template/server/core/platform/clock.ts +4 -0
- package/dist/template/server/core/platform/database.ts +78 -0
- package/dist/template/server/core/platform/email-assets.ts +32 -0
- package/dist/template/server/core/platform/id-generator.ts +29 -0
- package/dist/template/server/core/platform/kv.ts +54 -0
- package/dist/template/server/core/platform/mailer-cloudflare.ts +51 -0
- package/dist/template/server/core/platform/mailer.ts +21 -0
- package/dist/template/server/core/platform/password-hasher.ts +27 -0
- package/dist/template/server/core/platform/pii.ts +80 -0
- package/dist/template/server/core/platform/provider-http.ts +21 -0
- package/dist/template/server/core/platform/rate-limiter-strict.ts +42 -0
- package/dist/template/server/core/platform/rate-limiter.ts +35 -0
- package/dist/template/server/core/platform/runtime-config-schema.ts +15 -0
- package/dist/template/server/core/platform/seal.ts +68 -0
- package/dist/template/server/core/platform/sliding-window.ts +39 -0
- package/dist/template/server/core/platform/tokens.ts +36 -0
- package/dist/template/server/core/platform/turnstile.ts +61 -0
- package/dist/template/server/middleware/00-body-limit.ts +10 -0
- package/dist/template/server/middleware/00-security-headers.ts +19 -0
- package/dist/template/server/middleware/01-user-session.ts +25 -0
- package/dist/template/server/plugins/page-csp.ts +15 -0
- package/dist/template/server/plugins/sessions.ts +21 -0
- package/dist/template/server/routes/(dev)/emails.get.dev.ts +37 -0
- package/dist/template/server/routes/auth/github.get.ts +96 -0
- package/dist/template/server/routes/auth/google.get.ts +61 -0
- package/dist/template/server/test/email-assets.ts +8 -0
- package/dist/template/server/test/invariants.test.ts +83 -0
- package/dist/template/server/test/kit.ts +83 -0
- package/dist/template/server/utils/define-validated-handler.ts +78 -0
- package/dist/template/server/utils/errors.ts +16 -0
- package/dist/template/server/utils/read-body.ts +34 -0
- package/dist/template/server/utils/user-actor.ts +10 -0
- package/dist/template/server.ts +5 -0
- package/dist/template/shared/domain/errors.ts +33 -0
- package/dist/template/shared/types/auth.d.ts +13 -0
- package/dist/template/shared/utils/admin.ts +13 -0
- package/dist/template/shared/utils/auth.ts +132 -0
- package/dist/template/shared/utils/ids.ts +21 -0
- package/dist/template/shared/utils/local-path.ts +2 -0
- package/dist/template/shared/utils/schema-validation.ts +59 -0
- package/dist/template/shared/utils/unknown.ts +9 -0
- package/dist/template/tsconfig.json +17 -0
- package/dist/template/vitest.config.ts +10 -0
- package/dist/template/wrangler.json +46 -0
- package/package.json +28 -4
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { Effect, Layer } from 'effect'
|
|
2
|
+
import { Mac, SecureRandom } from 'effect/crypto'
|
|
3
|
+
import { describe, expect, it } from 'vitest'
|
|
4
|
+
|
|
5
|
+
import { Identity } from '#server/app/identity/service'
|
|
6
|
+
import { Totp } from '#server/app/identity/totp'
|
|
7
|
+
import { base32Decode, base32Encode, hotp, otpauthUri, stepOf, verifyTotp } from '#server/app/identity/totp-crypto'
|
|
8
|
+
import { makeTestLayer } from '#server/test/kit'
|
|
9
|
+
|
|
10
|
+
const MacLive = Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto))
|
|
11
|
+
const runCrypto = <A, E>(effect: Effect.Effect<A, E, Mac.Mac>) => Effect.runPromise(effect.pipe(Effect.provide(MacLive)))
|
|
12
|
+
|
|
13
|
+
const RFC_SECRET = new TextEncoder().encode('12345678901234567890')
|
|
14
|
+
|
|
15
|
+
describe('totp crypto', () => {
|
|
16
|
+
it('matches RFC 4226 and RFC 6238 test vectors', async () => {
|
|
17
|
+
const expected = ['755224', '287082', '359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']
|
|
18
|
+
for (const [counter, code] of expected.entries()) expect(await runCrypto(hotp(RFC_SECRET, counter))).toBe(code)
|
|
19
|
+
expect(await runCrypto(hotp(RFC_SECRET, Math.floor(59 / 30), 8))).toBe('94287082')
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('round-trips base32 and builds otpauth URI', () => {
|
|
23
|
+
const bytes = new Uint8Array([0, 1, 2, 250, 251, 252, 253, 254, 255, 7])
|
|
24
|
+
expect([...Effect.runSync(base32Decode(base32Encode(bytes)))]).toEqual([...bytes])
|
|
25
|
+
expect(Effect.runSync(Effect.result(base32Decode('AB1!')))._tag).toBe('Failure')
|
|
26
|
+
expect(otpauthUri('a@b.test', 'ABCDEFGH', 'My App')).toBe(
|
|
27
|
+
'otpauth://totp/My%20App:a%40b.test?secret=ABCDEFGH&issuer=My%20App&algorithm=SHA1&digits=6&period=30',
|
|
28
|
+
)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('prevents replay of used or older steps', async () => {
|
|
32
|
+
const verify = (code: string, lastStep: number) => runCrypto(verifyTotp(RFC_SECRET, code, lastStep))
|
|
33
|
+
const step = stepOf(Date.now())
|
|
34
|
+
const code = await runCrypto(hotp(RFC_SECRET, step))
|
|
35
|
+
expect(await verify(code, 0)).toBeGreaterThanOrEqual(step - 1)
|
|
36
|
+
expect(await verify(code, step + 1)).toBeUndefined()
|
|
37
|
+
expect(await verify(await runCrypto(hotp(RFC_SECRET, step - 5)), 0)).toBeUndefined()
|
|
38
|
+
})
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
describe('totp explicit state machine', () => {
|
|
42
|
+
it('transitions Off -> Pending -> Enabled -> Off with recovery codes and login challenge', async () => {
|
|
43
|
+
const { run } = await makeTestLayer()
|
|
44
|
+
|
|
45
|
+
const user = await run(Identity.use((id) => id.register({ username: 'alice', email: 'alice@example.com', password: 'correct-password' })))
|
|
46
|
+
|
|
47
|
+
// Off -> cannot confirm before starting
|
|
48
|
+
const confirmEarly = await run(Totp.use((t) => t.confirmSetup(user.id, '123456')).pipe(Effect.result))
|
|
49
|
+
expect(confirmEarly._tag).toBe('Failure')
|
|
50
|
+
|
|
51
|
+
// Off -> Pending
|
|
52
|
+
const setup = await run(Totp.use((t) => t.startSetup(user.id, 'correct-password')))
|
|
53
|
+
expect(setup.uri).toContain('otpauth://totp/Starter%20Test:alice%40example.com')
|
|
54
|
+
|
|
55
|
+
const pending = await run(Totp.use((t) => t.security(user.id)))
|
|
56
|
+
expect(pending.status).toBe('pending')
|
|
57
|
+
|
|
58
|
+
// Pending -> Off (cancel)
|
|
59
|
+
await run(Totp.use((t) => t.cancelSetup(user.id)))
|
|
60
|
+
expect((await run(Totp.use((t) => t.security(user.id)))).status).toBe('off')
|
|
61
|
+
|
|
62
|
+
// Off -> Pending -> Enabled
|
|
63
|
+
const setup2 = await run(Totp.use((t) => t.startSetup(user.id, 'correct-password')))
|
|
64
|
+
const secretBytes = Effect.runSync(base32Decode(setup2.secret))
|
|
65
|
+
const firstCode = await runCrypto(hotp(secretBytes, stepOf(Date.now())))
|
|
66
|
+
const recoveryCodes = await run(Totp.use((t) => t.confirmSetup(user.id, firstCode)))
|
|
67
|
+
expect(recoveryCodes).toHaveLength(8)
|
|
68
|
+
|
|
69
|
+
const enabled = await run(Totp.use((t) => t.security(user.id)))
|
|
70
|
+
expect(enabled).toEqual({ status: 'enabled', recoveryCodesLeft: 8 })
|
|
71
|
+
|
|
72
|
+
// Login now requires explicit 2FA challenge
|
|
73
|
+
const outcome = await run(Identity.use((id) => id.login({ identity: 'alice', password: 'correct-password' })))
|
|
74
|
+
expect(outcome.status).toBe('totp_required')
|
|
75
|
+
if (outcome.status !== 'totp_required') throw new Error('expected totp_required')
|
|
76
|
+
|
|
77
|
+
// Replaying the same step used during confirmSetup fails
|
|
78
|
+
const replay = await run(Totp.use((t) => t.verifyChallenge(outcome.challenge, firstCode)).pipe(Effect.result))
|
|
79
|
+
expect(replay._tag).toBe('Failure')
|
|
80
|
+
|
|
81
|
+
// Using a recovery code succeeds once and consumes it
|
|
82
|
+
const authed = await run(Totp.use((t) => t.verifyChallenge(outcome.challenge, recoveryCodes[0]!)))
|
|
83
|
+
expect(authed.id).toBe(user.id)
|
|
84
|
+
expect((await run(Totp.use((t) => t.security(user.id)))).recoveryCodesLeft).toBe(7)
|
|
85
|
+
|
|
86
|
+
// Reusing the consumed recovery code fails
|
|
87
|
+
const reuse = await run(Totp.use((t) => t.verifyChallenge(outcome.challenge, recoveryCodes[0]!)).pipe(Effect.result))
|
|
88
|
+
expect(reuse._tag).toBe('Failure')
|
|
89
|
+
|
|
90
|
+
// Enabled -> Off using another recovery code
|
|
91
|
+
await run(Totp.use((t) => t.disable(user.id, 'correct-password', recoveryCodes[1]!)))
|
|
92
|
+
expect(await run(Totp.use((t) => t.security(user.id)))).toEqual({ status: 'off', recoveryCodesLeft: 0 })
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it('refuses TOTP endpoints explicitly and skips 2FA challenge when features.totp is false', async () => {
|
|
96
|
+
const { run } = await makeTestLayer({ config: { features: { totp: false } } })
|
|
97
|
+
|
|
98
|
+
const user = await run(Identity.use((id) => id.register({ username: 'bob', email: 'bob@example.com', password: 'correct-password' })))
|
|
99
|
+
const res = await run(Totp.use((t) => t.startSetup(user.id, 'correct-password')).pipe(Effect.result))
|
|
100
|
+
expect(res._tag).toBe('Failure')
|
|
101
|
+
if (res._tag === 'Failure') expect(res.failure._tag).toBe('Forbidden')
|
|
102
|
+
})
|
|
103
|
+
})
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import { Context, Effect, Layer, Redacted, Schema } from 'effect'
|
|
2
|
+
import { Mac, SecureRandom } from 'effect/crypto'
|
|
3
|
+
import { Base64Url } from 'effect/encoding'
|
|
4
|
+
|
|
5
|
+
import type { RateLimited } from '#shared/domain/errors'
|
|
6
|
+
import type { TotpStatus } from '#shared/utils/auth'
|
|
7
|
+
|
|
8
|
+
import { AtomicBatch, assertPreviousChanged } from '#server/core/db/atomic'
|
|
9
|
+
import { AppConfig } from '#server/core/platform/app-config'
|
|
10
|
+
import { nowIso, nowMillis } from '#server/core/platform/clock'
|
|
11
|
+
import { Database } from '#server/core/platform/database'
|
|
12
|
+
import { PasswordHasher } from '#server/core/platform/password-hasher'
|
|
13
|
+
import { Pii } from '#server/core/platform/pii'
|
|
14
|
+
import { Seal } from '#server/core/platform/seal'
|
|
15
|
+
import { Tokens } from '#server/core/platform/tokens'
|
|
16
|
+
import { Conflict, Forbidden, Unauthorized, Unprocessable } from '#shared/domain/errors'
|
|
17
|
+
|
|
18
|
+
import type { AuthUser } from './state'
|
|
19
|
+
|
|
20
|
+
import { LoginLockout } from './lockout'
|
|
21
|
+
import { decodeTotpState } from './state'
|
|
22
|
+
import { base32Decode, newSecret, otpauthUri, verifyTotp } from './totp-crypto'
|
|
23
|
+
|
|
24
|
+
const RECOVERY_CODES_COUNT = 8
|
|
25
|
+
const CHALLENGE_TTL_MS = 5 * 60_000
|
|
26
|
+
const CHALLENGE_CONTEXT = 'identity:totp-challenge'
|
|
27
|
+
const WRONG_CODE = 'That verification code is not valid. Use a fresh code from your authenticator app or a recovery code.'
|
|
28
|
+
|
|
29
|
+
const encoder = new TextEncoder()
|
|
30
|
+
const decoder = new TextDecoder()
|
|
31
|
+
|
|
32
|
+
const UserTotpRow = Schema.Struct({
|
|
33
|
+
id: Schema.String,
|
|
34
|
+
username: Schema.String,
|
|
35
|
+
email: Schema.String,
|
|
36
|
+
email_status: Schema.Literals(['unverified', 'verified']),
|
|
37
|
+
password_hash: Schema.NullOr(Schema.String),
|
|
38
|
+
totp_status: Schema.Literals(['off', 'pending', 'enabled']),
|
|
39
|
+
totp_secret: Schema.NullOr(Schema.String),
|
|
40
|
+
totp_enabled_at: Schema.NullOr(Schema.String),
|
|
41
|
+
totp_last_step: Schema.Finite,
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
const CountRow = Schema.Struct({ n: Schema.Finite })
|
|
45
|
+
|
|
46
|
+
const ChallengePayload = Schema.fromJsonString(
|
|
47
|
+
Schema.Struct({
|
|
48
|
+
userId: Schema.String,
|
|
49
|
+
exp: Schema.Finite,
|
|
50
|
+
}),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
const USER_COLUMNS = `id, username, email, email_status, password_hash, totp_status, totp_secret, totp_enabled_at, totp_last_step`
|
|
54
|
+
|
|
55
|
+
export interface TotpSetup {
|
|
56
|
+
readonly secret: string
|
|
57
|
+
readonly uri: string
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface TotpSecurity {
|
|
61
|
+
readonly status: TotpStatus
|
|
62
|
+
readonly recoveryCodesLeft: number
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Explicit TOTP two-factor authentication state machine:
|
|
67
|
+
* Off --(startSetup)--> Pending --(confirmSetup)--> Enabled --(disable)--> Off
|
|
68
|
+
* Pending --(cancelSetup)---> Off
|
|
69
|
+
* Controlled globally by `runtimeConfig.public.features.totp` in `nuxt.config.ts`.
|
|
70
|
+
*/
|
|
71
|
+
export class Totp extends Context.Service<
|
|
72
|
+
Totp,
|
|
73
|
+
{
|
|
74
|
+
readonly isEnabled: Effect.Effect<boolean>
|
|
75
|
+
readonly security: (userId: string) => Effect.Effect<TotpSecurity, Forbidden>
|
|
76
|
+
readonly startSetup: (userId: string, password: string) => Effect.Effect<TotpSetup, Forbidden | Conflict | Unauthorized | Unprocessable | RateLimited>
|
|
77
|
+
readonly cancelSetup: (userId: string) => Effect.Effect<void, Forbidden | Conflict>
|
|
78
|
+
readonly confirmSetup: (userId: string, code: string) => Effect.Effect<ReadonlyArray<string>, Forbidden | Conflict | Unauthorized | RateLimited>
|
|
79
|
+
readonly disable: (userId: string, password: string, code: string) => Effect.Effect<void, Forbidden | Unauthorized | RateLimited>
|
|
80
|
+
readonly issueChallenge: (userId: string) => Effect.Effect<string, Forbidden>
|
|
81
|
+
readonly verifyChallenge: (challenge: string, code: string) => Effect.Effect<AuthUser, Forbidden | Unauthorized | RateLimited>
|
|
82
|
+
readonly verifySecondFactor: (userId: string, code: string) => Effect.Effect<boolean, Forbidden | RateLimited>
|
|
83
|
+
}
|
|
84
|
+
>()('app/identity/Totp') {
|
|
85
|
+
static readonly layer = Layer.effect(
|
|
86
|
+
Totp,
|
|
87
|
+
Effect.gen(function* () {
|
|
88
|
+
const config = yield* AppConfig
|
|
89
|
+
const db = yield* Database
|
|
90
|
+
const atomic = yield* AtomicBatch
|
|
91
|
+
const hasher = yield* PasswordHasher
|
|
92
|
+
const pii = yield* Pii
|
|
93
|
+
const seal = yield* Seal
|
|
94
|
+
const tokens = yield* Tokens
|
|
95
|
+
const lockout = yield* LoginLockout
|
|
96
|
+
const random = yield* SecureRandom.SecureRandom
|
|
97
|
+
const mac = yield* Mac.Mac
|
|
98
|
+
|
|
99
|
+
const challengeKey = yield* Effect.cached(seal.sha256(encoder.encode(`totp-challenge:${Redacted.value(config.appSecret)}`)))
|
|
100
|
+
|
|
101
|
+
const assertFeatureOn = () => (config.features.totp ? Effect.void : Effect.fail(new Forbidden({ message: 'Two-factor authentication is disabled.' })))
|
|
102
|
+
|
|
103
|
+
const lockKey = (userId: string) => `totp:${userId}`
|
|
104
|
+
|
|
105
|
+
const hashRecoveryCode = (code: string) => tokens.hash(`recovery:${code.trim().toLowerCase().replace(/[\s-]/g, '')}`)
|
|
106
|
+
|
|
107
|
+
const loadUser = (userId: string) => db.first(UserTotpRow, `SELECT ${USER_COLUMNS} FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
|
|
108
|
+
|
|
109
|
+
const verifyCodeAgainstState = (userId: string, sealedSecret: string, lastStep: number, code: string) =>
|
|
110
|
+
Effect.gen(function* () {
|
|
111
|
+
const secret = yield* base32Decode(yield* pii.open(sealedSecret, 'users.totp_secret')).pipe(Effect.orDie)
|
|
112
|
+
const matchedStep = yield* verifyTotp(secret, code.trim(), lastStep).pipe(Effect.provideService(Mac.Mac, mac), Effect.orDie)
|
|
113
|
+
if (matchedStep !== undefined) {
|
|
114
|
+
const [claimed] = yield* atomic
|
|
115
|
+
.run([
|
|
116
|
+
{
|
|
117
|
+
sql: `UPDATE users SET totp_last_step = ? WHERE id = ? AND totp_status = 'enabled' AND totp_last_step < ?`,
|
|
118
|
+
params: [matchedStep, userId, matchedStep],
|
|
119
|
+
},
|
|
120
|
+
])
|
|
121
|
+
.pipe(Effect.orDie)
|
|
122
|
+
return Boolean(claimed && claimed.changes > 0)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const usedAt = yield* nowIso
|
|
126
|
+
const [used] = yield* atomic
|
|
127
|
+
.run([
|
|
128
|
+
{
|
|
129
|
+
sql: `UPDATE totp_recovery_codes SET status = 'used', used_at = ? WHERE user_id = ? AND code_hash = ? AND status = 'unused'`,
|
|
130
|
+
params: [usedAt, userId, yield* hashRecoveryCode(code)],
|
|
131
|
+
},
|
|
132
|
+
])
|
|
133
|
+
.pipe(Effect.orDie)
|
|
134
|
+
return Boolean(used && used.changes > 0)
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
const security = Effect.fn('Totp.security')(function* (userId: string) {
|
|
138
|
+
yield* assertFeatureOn()
|
|
139
|
+
const user = yield* loadUser(userId)
|
|
140
|
+
const left = yield* db
|
|
141
|
+
.first(CountRow, `SELECT COUNT(*) AS n FROM totp_recovery_codes WHERE user_id = ? AND status = 'unused'`, [userId])
|
|
142
|
+
.pipe(Effect.orDie)
|
|
143
|
+
return {
|
|
144
|
+
status: user?.totp_status ?? 'off',
|
|
145
|
+
recoveryCodesLeft: left?.n ?? 0,
|
|
146
|
+
} satisfies TotpSecurity
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
const startSetup = Effect.fn('Totp.startSetup')(function* (userId: string, password: string) {
|
|
150
|
+
yield* assertFeatureOn()
|
|
151
|
+
yield* lockout.assertUnlocked(lockKey(userId))
|
|
152
|
+
|
|
153
|
+
const user = yield* loadUser(userId)
|
|
154
|
+
if (!user) return yield* new Unauthorized({ message: 'Please sign in again.' })
|
|
155
|
+
if (!user.password_hash) return yield* new Unprocessable({ message: 'Set a password before enabling two-factor authentication.' })
|
|
156
|
+
|
|
157
|
+
if (!(yield* hasher.verify(user.password_hash, password))) {
|
|
158
|
+
yield* lockout.recordFailure(lockKey(userId))
|
|
159
|
+
return yield* new Unauthorized({ message: 'The password is not right.' })
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const state = decodeTotpState(user)
|
|
163
|
+
if (state._tag === 'Enabled') {
|
|
164
|
+
return yield* new Conflict({ message: 'Two-factor authentication is already enabled. Disable it first to set it up again.' })
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const secret = yield* newSecret(random.randomBytes)
|
|
168
|
+
const sealed = yield* pii.seal(secret, 'users.totp_secret')
|
|
169
|
+
const [updated] = yield* atomic
|
|
170
|
+
.run([
|
|
171
|
+
{
|
|
172
|
+
sql: `UPDATE users SET totp_status = 'pending', totp_secret = ?, totp_enabled_at = NULL, totp_last_step = 0 WHERE id = ? AND totp_status IN ('off', 'pending')`,
|
|
173
|
+
params: [sealed, userId],
|
|
174
|
+
},
|
|
175
|
+
])
|
|
176
|
+
.pipe(Effect.orDie)
|
|
177
|
+
|
|
178
|
+
if (!updated || updated.changes === 0) {
|
|
179
|
+
return yield* new Conflict({ message: 'Two-factor authentication is already enabled.' })
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
yield* lockout.clear(lockKey(userId))
|
|
183
|
+
return { secret, uri: otpauthUri(user.email, secret, config.appName) } satisfies TotpSetup
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
const cancelSetup = Effect.fn('Totp.cancelSetup')(function* (userId: string) {
|
|
187
|
+
yield* assertFeatureOn()
|
|
188
|
+
const user = yield* loadUser(userId)
|
|
189
|
+
if (!user) return
|
|
190
|
+
const state = decodeTotpState(user)
|
|
191
|
+
if (state._tag === 'Enabled') return yield* new Conflict({ message: 'Two-factor authentication is already enabled.' })
|
|
192
|
+
if (state._tag === 'Off') return
|
|
193
|
+
|
|
194
|
+
yield* db
|
|
195
|
+
.run(
|
|
196
|
+
`UPDATE users SET totp_status = 'off', totp_secret = NULL, totp_enabled_at = NULL, totp_last_step = 0 WHERE id = ? AND totp_status = 'pending'`,
|
|
197
|
+
[userId],
|
|
198
|
+
)
|
|
199
|
+
.pipe(Effect.orDie)
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
const confirmSetup = Effect.fn('Totp.confirmSetup')(function* (userId: string, code: string) {
|
|
203
|
+
yield* assertFeatureOn()
|
|
204
|
+
yield* lockout.assertUnlocked(lockKey(userId))
|
|
205
|
+
|
|
206
|
+
const user = yield* loadUser(userId)
|
|
207
|
+
if (!user) return yield* new Unauthorized({ message: 'Please sign in again.' })
|
|
208
|
+
|
|
209
|
+
const state = decodeTotpState(user)
|
|
210
|
+
if (state._tag === 'Off') return yield* new Conflict({ message: 'Start two-factor setup first.' })
|
|
211
|
+
if (state._tag === 'Enabled') return yield* new Conflict({ message: 'Two-factor authentication is already enabled.' })
|
|
212
|
+
|
|
213
|
+
const secret = yield* base32Decode(yield* pii.open(state.sealedSecret, 'users.totp_secret')).pipe(Effect.orDie)
|
|
214
|
+
const matchedStep = yield* verifyTotp(secret, code.trim(), 0).pipe(Effect.provideService(Mac.Mac, mac), Effect.orDie)
|
|
215
|
+
if (matchedStep === undefined) {
|
|
216
|
+
yield* lockout.recordFailure(lockKey(userId))
|
|
217
|
+
return yield* new Unauthorized({ message: WRONG_CODE })
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const recoveryCodes = yield* Effect.forEach(Array.from({ length: RECOVERY_CODES_COUNT }), () =>
|
|
221
|
+
random.randomBytes(5).pipe(
|
|
222
|
+
Effect.map((bytes) => {
|
|
223
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
|
|
224
|
+
return `${hex.slice(0, 5)}-${hex.slice(5)}`
|
|
225
|
+
}),
|
|
226
|
+
),
|
|
227
|
+
)
|
|
228
|
+
const hashes = yield* Effect.forEach(recoveryCodes, hashRecoveryCode)
|
|
229
|
+
const enabledAt = yield* nowIso
|
|
230
|
+
|
|
231
|
+
yield* atomic
|
|
232
|
+
.runGuarded('totp_not_pending', [
|
|
233
|
+
{
|
|
234
|
+
sql: `UPDATE users SET totp_status = 'enabled', totp_enabled_at = ?, totp_last_step = ? WHERE id = ? AND totp_status = 'pending' AND totp_secret = ?`,
|
|
235
|
+
params: [enabledAt, matchedStep, userId, state.sealedSecret],
|
|
236
|
+
},
|
|
237
|
+
assertPreviousChanged,
|
|
238
|
+
{ sql: `DELETE FROM totp_recovery_codes WHERE user_id = ?`, params: [userId] },
|
|
239
|
+
...hashes.map((hash) => ({
|
|
240
|
+
sql: `INSERT INTO totp_recovery_codes (user_id, code_hash, status) VALUES (?, ?, 'unused')`,
|
|
241
|
+
params: [userId, hash],
|
|
242
|
+
})),
|
|
243
|
+
{ sql: `DELETE FROM login_failures WHERE subject = ?`, params: [lockKey(userId)] },
|
|
244
|
+
])
|
|
245
|
+
.pipe(
|
|
246
|
+
Effect.catchTags({
|
|
247
|
+
GuardFailed: () => Effect.fail(new Conflict({ message: 'Two-factor setup is no longer pending.' })),
|
|
248
|
+
DatabaseError: Effect.die,
|
|
249
|
+
}),
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
return recoveryCodes
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
const disable = Effect.fn('Totp.disable')(function* (userId: string, password: string, code: string) {
|
|
256
|
+
yield* assertFeatureOn()
|
|
257
|
+
yield* lockout.assertUnlocked(lockKey(userId))
|
|
258
|
+
|
|
259
|
+
const wrong = new Unauthorized({ message: 'The password or verification code is not right.' })
|
|
260
|
+
const user = yield* loadUser(userId)
|
|
261
|
+
if (!user || !user.password_hash) {
|
|
262
|
+
yield* lockout.recordFailure(lockKey(userId))
|
|
263
|
+
return yield* wrong
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const passwordOk = yield* hasher.verify(user.password_hash, password)
|
|
267
|
+
const state = decodeTotpState(user)
|
|
268
|
+
if (!passwordOk || state._tag !== 'Enabled') {
|
|
269
|
+
yield* lockout.recordFailure(lockKey(userId))
|
|
270
|
+
return yield* wrong
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const codeOk = yield* verifyCodeAgainstState(userId, state.sealedSecret, state.lastStep, code)
|
|
274
|
+
if (!codeOk) {
|
|
275
|
+
yield* lockout.recordFailure(lockKey(userId))
|
|
276
|
+
return yield* wrong
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
yield* atomic
|
|
280
|
+
.run([
|
|
281
|
+
{
|
|
282
|
+
sql: `UPDATE users SET totp_status = 'off', totp_secret = NULL, totp_enabled_at = NULL, totp_last_step = 0 WHERE id = ?`,
|
|
283
|
+
params: [userId],
|
|
284
|
+
},
|
|
285
|
+
{ sql: `DELETE FROM totp_recovery_codes WHERE user_id = ?`, params: [userId] },
|
|
286
|
+
{ sql: `DELETE FROM login_failures WHERE subject = ?`, params: [lockKey(userId)] },
|
|
287
|
+
])
|
|
288
|
+
.pipe(Effect.orDie)
|
|
289
|
+
})
|
|
290
|
+
|
|
291
|
+
const issueChallenge = Effect.fn('Totp.issueChallenge')(function* (userId: string) {
|
|
292
|
+
yield* assertFeatureOn()
|
|
293
|
+
const key = yield* challengeKey
|
|
294
|
+
const exp = (yield* nowMillis) + CHALLENGE_TTL_MS
|
|
295
|
+
const bytes = yield* seal.seal(encoder.encode(JSON.stringify({ userId, exp })), key, CHALLENGE_CONTEXT).pipe(Effect.orDie)
|
|
296
|
+
return Base64Url.encode(bytes)
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
const verifySecondFactor = Effect.fn('Totp.verifySecondFactor')(function* (userId: string, code: string) {
|
|
300
|
+
yield* assertFeatureOn()
|
|
301
|
+
yield* lockout.assertUnlocked(lockKey(userId))
|
|
302
|
+
|
|
303
|
+
const user = yield* loadUser(userId)
|
|
304
|
+
if (!user) return false
|
|
305
|
+
const state = decodeTotpState(user)
|
|
306
|
+
if (state._tag !== 'Enabled') return false
|
|
307
|
+
|
|
308
|
+
const ok = yield* verifyCodeAgainstState(userId, state.sealedSecret, state.lastStep, code)
|
|
309
|
+
if (!ok) {
|
|
310
|
+
yield* lockout.recordFailure(lockKey(userId))
|
|
311
|
+
return false
|
|
312
|
+
}
|
|
313
|
+
yield* lockout.clear(lockKey(userId))
|
|
314
|
+
return true
|
|
315
|
+
})
|
|
316
|
+
|
|
317
|
+
const verifyChallenge = Effect.fn('Totp.verifyChallenge')(function* (challenge: string, code: string) {
|
|
318
|
+
yield* assertFeatureOn()
|
|
319
|
+
const invalid = new Unauthorized({ message: 'Your sign-in challenge expired. Sign in again.' })
|
|
320
|
+
const raw = Base64Url.decode(challenge)
|
|
321
|
+
if (raw._tag === 'Failure') return yield* invalid
|
|
322
|
+
|
|
323
|
+
const key = yield* challengeKey
|
|
324
|
+
const opened = yield* seal.open(raw.success, key, CHALLENGE_CONTEXT).pipe(Effect.option)
|
|
325
|
+
if (opened._tag === 'None') return yield* invalid
|
|
326
|
+
|
|
327
|
+
const parsed = yield* Schema.decodeEffect(ChallengePayload)(decoder.decode(opened.value)).pipe(Effect.option)
|
|
328
|
+
if (parsed._tag === 'None') return yield* invalid
|
|
329
|
+
|
|
330
|
+
const now = yield* nowMillis
|
|
331
|
+
if (parsed.value.exp <= now) return yield* invalid
|
|
332
|
+
|
|
333
|
+
const { userId } = parsed.value
|
|
334
|
+
const ok = yield* verifySecondFactor(userId, code)
|
|
335
|
+
if (!ok) return yield* new Unauthorized({ message: WRONG_CODE })
|
|
336
|
+
|
|
337
|
+
const user = yield* loadUser(userId)
|
|
338
|
+
if (!user) return yield* invalid
|
|
339
|
+
return {
|
|
340
|
+
id: user.id,
|
|
341
|
+
username: user.username,
|
|
342
|
+
email: user.email,
|
|
343
|
+
emailStatus: user.email_status,
|
|
344
|
+
totpStatus: user.totp_status,
|
|
345
|
+
} satisfies AuthUser
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
return Totp.of({
|
|
349
|
+
isEnabled: Effect.succeed(config.features.totp),
|
|
350
|
+
security,
|
|
351
|
+
startSetup,
|
|
352
|
+
cancelSetup,
|
|
353
|
+
confirmSetup,
|
|
354
|
+
disable,
|
|
355
|
+
issueChallenge,
|
|
356
|
+
verifyChallenge,
|
|
357
|
+
verifySecondFactor,
|
|
358
|
+
})
|
|
359
|
+
}),
|
|
360
|
+
).pipe(Layer.provide(Layer.mergeAll(SecureRandom.layerWebCrypto, Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)))))
|
|
361
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { Context, DateTime, Effect, Layer, Schema } from 'effect'
|
|
2
|
+
|
|
3
|
+
import type { RateLimited } from '#shared/domain/errors'
|
|
4
|
+
|
|
5
|
+
import { EmailRenderer } from '#server/app/notifications/render'
|
|
6
|
+
import { verificationEmail } from '#server/app/notifications/templates'
|
|
7
|
+
import { AtomicBatch, assertPreviousChanged } from '#server/core/db/atomic'
|
|
8
|
+
import { AppConfig } from '#server/core/platform/app-config'
|
|
9
|
+
import { nowIso } from '#server/core/platform/clock'
|
|
10
|
+
import { Database } from '#server/core/platform/database'
|
|
11
|
+
import { Mailer } from '#server/core/platform/mailer'
|
|
12
|
+
import { Pii } from '#server/core/platform/pii'
|
|
13
|
+
import { RateLimiter } from '#server/core/platform/rate-limiter'
|
|
14
|
+
import { Tokens } from '#server/core/platform/tokens'
|
|
15
|
+
import { Unauthorized } from '#shared/domain/errors'
|
|
16
|
+
|
|
17
|
+
import { Sessions } from './sessions'
|
|
18
|
+
|
|
19
|
+
const LINK_HOURS = 24
|
|
20
|
+
|
|
21
|
+
const UserRow = Schema.Struct({
|
|
22
|
+
id: Schema.String,
|
|
23
|
+
email: Schema.String,
|
|
24
|
+
email_status: Schema.Literals(['unverified', 'verified']),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
const TokenRow = Schema.Struct({
|
|
28
|
+
user_id: Schema.String,
|
|
29
|
+
email: Schema.String,
|
|
30
|
+
status: Schema.Literals(['active', 'used', 'revoked']),
|
|
31
|
+
expires_at: Schema.String,
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
export class EmailVerification extends Context.Service<
|
|
35
|
+
EmailVerification,
|
|
36
|
+
{
|
|
37
|
+
readonly send: (userId: string) => Effect.Effect<void, RateLimited>
|
|
38
|
+
readonly confirm: (token: string) => Effect.Effect<{ readonly userId: string }, Unauthorized>
|
|
39
|
+
}
|
|
40
|
+
>()('app/identity/EmailVerification') {
|
|
41
|
+
static readonly layer = Layer.effect(
|
|
42
|
+
EmailVerification,
|
|
43
|
+
Effect.gen(function* () {
|
|
44
|
+
const config = yield* AppConfig
|
|
45
|
+
const db = yield* Database
|
|
46
|
+
const atomic = yield* AtomicBatch
|
|
47
|
+
const tokens = yield* Tokens
|
|
48
|
+
const mailer = yield* Mailer
|
|
49
|
+
const renderer = yield* EmailRenderer
|
|
50
|
+
const pii = yield* Pii
|
|
51
|
+
const limiter = yield* RateLimiter
|
|
52
|
+
const sessions = yield* Sessions
|
|
53
|
+
|
|
54
|
+
const send = Effect.fn('EmailVerification.send')(function* (userId: string) {
|
|
55
|
+
const user = yield* db.first(UserRow, `SELECT id, email, email_status FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
|
|
56
|
+
if (!user || user.email_status === 'verified') return
|
|
57
|
+
|
|
58
|
+
yield* limiter.check('verify', yield* pii.index(user.email))
|
|
59
|
+
|
|
60
|
+
const { token, hash } = yield* tokens.generate
|
|
61
|
+
const now = yield* DateTime.now
|
|
62
|
+
const nowStr = DateTime.formatIso(now)
|
|
63
|
+
const expiresAt = DateTime.formatIso(DateTime.add(now, { hours: LINK_HOURS }))
|
|
64
|
+
|
|
65
|
+
yield* atomic
|
|
66
|
+
.run([
|
|
67
|
+
{
|
|
68
|
+
sql: `UPDATE email_verification_tokens SET status = 'revoked', revoked_at = ? WHERE user_id = ? AND status = 'active'`,
|
|
69
|
+
params: [nowStr, userId],
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
sql: `INSERT INTO email_verification_tokens (token_hash, user_id, email, status, created_at, expires_at) VALUES (?, ?, ?, 'active', ?, ?)`,
|
|
73
|
+
params: [hash, userId, user.email, nowStr, expiresAt],
|
|
74
|
+
},
|
|
75
|
+
])
|
|
76
|
+
.pipe(Effect.orDie)
|
|
77
|
+
|
|
78
|
+
const rendered = yield* renderer.render(verificationEmail(`${config.appUrl}/verify/${token}`, config.appName))
|
|
79
|
+
yield* mailer.send({ to: user.email, ...rendered }).pipe(Effect.ignore)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
const confirm = Effect.fn('EmailVerification.confirm')(function* (token: string) {
|
|
83
|
+
const invalid = new Unauthorized({ message: 'This verification link is invalid or has expired.' })
|
|
84
|
+
const hash = yield* tokens.hash(token)
|
|
85
|
+
const now = yield* nowIso
|
|
86
|
+
|
|
87
|
+
const row = yield* db
|
|
88
|
+
.first(TokenRow, `SELECT user_id, email, status, expires_at FROM email_verification_tokens WHERE token_hash = ?`, [hash])
|
|
89
|
+
.pipe(Effect.orDie)
|
|
90
|
+
|
|
91
|
+
if (!row || row.status !== 'active' || row.expires_at <= now) return yield* invalid
|
|
92
|
+
|
|
93
|
+
yield* atomic
|
|
94
|
+
.runGuarded('verification_token_not_active', [
|
|
95
|
+
{
|
|
96
|
+
sql: `UPDATE email_verification_tokens SET status = 'used', used_at = ? WHERE token_hash = ? AND status = 'active' AND expires_at > ?`,
|
|
97
|
+
params: [now, hash, now],
|
|
98
|
+
},
|
|
99
|
+
assertPreviousChanged,
|
|
100
|
+
{
|
|
101
|
+
sql: `UPDATE users SET email_status = 'verified', email_verified_at = COALESCE(email_verified_at, ?) WHERE id = ? AND email = ?`,
|
|
102
|
+
params: [now, row.user_id, row.email],
|
|
103
|
+
},
|
|
104
|
+
assertPreviousChanged,
|
|
105
|
+
])
|
|
106
|
+
.pipe(
|
|
107
|
+
Effect.catchTags({
|
|
108
|
+
GuardFailed: () => Effect.fail(invalid),
|
|
109
|
+
DatabaseError: Effect.die,
|
|
110
|
+
}),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
yield* sessions.forget(row.user_id)
|
|
114
|
+
return { userId: row.user_id }
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
return EmailVerification.of({ send, confirm })
|
|
118
|
+
}),
|
|
119
|
+
)
|
|
120
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type Block =
|
|
2
|
+
| { readonly kind: 'text'; readonly text: string }
|
|
3
|
+
| { readonly kind: 'button'; readonly label: string; readonly url: string }
|
|
4
|
+
| { readonly kind: 'note'; readonly text: string }
|
|
5
|
+
|
|
6
|
+
export interface Email {
|
|
7
|
+
readonly subject: string
|
|
8
|
+
readonly preheader: string
|
|
9
|
+
readonly headline: string
|
|
10
|
+
readonly blocks: ReadonlyArray<Block>
|
|
11
|
+
readonly footer: string
|
|
12
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
|
|
3
|
+
import { makeTestLayer } from '#server/test/kit'
|
|
4
|
+
|
|
5
|
+
import { EmailRenderer, fill } from './render'
|
|
6
|
+
import { sampleEmails } from './samples'
|
|
7
|
+
|
|
8
|
+
describe('email rendering', () => {
|
|
9
|
+
it('escapes {{vars}}, preserves {{{raw}}}, and throws on missing keys', () => {
|
|
10
|
+
expect(fill('<p>{{text}}</p>{{{body}}}', { text: '<b>hi</b>', body: '<span>ok</span>' })).toBe('<p><b>hi</b></p><span>ok</span>')
|
|
11
|
+
expect(() => fill('<p>{{missing}}</p>', {})).toThrow(/missing/)
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('renders every sample email into HTML and plain text with no leftover placeholders', async () => {
|
|
15
|
+
const { run } = await makeTestLayer()
|
|
16
|
+
const samples = sampleEmails('https://starter.test', 'Starter Test')
|
|
17
|
+
|
|
18
|
+
for (const email of Object.values(samples)) {
|
|
19
|
+
const rendered = await run(EmailRenderer.use((renderer) => renderer.render(email)))
|
|
20
|
+
expect(rendered.subject).toBe(email.subject)
|
|
21
|
+
expect(rendered.html).toContain('<!DOCTYPE html>')
|
|
22
|
+
expect(rendered.html).not.toMatch(/\{\{|\}\}/)
|
|
23
|
+
expect(rendered.text).toContain(email.headline)
|
|
24
|
+
}
|
|
25
|
+
})
|
|
26
|
+
})
|