@humanonlyweb/create-nuxtflare 0.0.0-stage → 0.1.1
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 +340 -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 +46 -4
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { Context, DateTime, Effect, Layer, Schema } from 'effect'
|
|
2
|
+
|
|
3
|
+
import type { RateLimited } from '#shared/domain/errors'
|
|
4
|
+
import type { MeView } from '#shared/utils/auth'
|
|
5
|
+
|
|
6
|
+
import { AtomicBatch } from '#server/core/db/atomic'
|
|
7
|
+
import { AppConfig } from '#server/core/platform/app-config'
|
|
8
|
+
import { nowIso } from '#server/core/platform/clock'
|
|
9
|
+
import { Database } from '#server/core/platform/database'
|
|
10
|
+
import { IdGenerator } from '#server/core/platform/id-generator'
|
|
11
|
+
import { PasswordHasher } from '#server/core/platform/password-hasher'
|
|
12
|
+
import { RateLimiter } from '#server/core/platform/rate-limiter'
|
|
13
|
+
import { Conflict, Forbidden, NotFound, Unauthorized, Unprocessable } from '#shared/domain/errors'
|
|
14
|
+
import { matchesConfirm } from '#shared/utils/schema-validation'
|
|
15
|
+
|
|
16
|
+
import type { AuthUser, LoginOutcome } from './state'
|
|
17
|
+
|
|
18
|
+
import { LoginLockout } from './lockout'
|
|
19
|
+
import { Sessions } from './sessions'
|
|
20
|
+
import { decodeTotpState } from './state'
|
|
21
|
+
import { Totp } from './totp'
|
|
22
|
+
|
|
23
|
+
const UNCONFIRMED_HOLD_HOURS = 1
|
|
24
|
+
const WRONG_LOGIN = 'Email, username, or password is not right.'
|
|
25
|
+
const WRONG_CODE = 'That verification code is not valid. Use a fresh code from your authenticator app or a recovery code.'
|
|
26
|
+
|
|
27
|
+
const LoginUserRow = Schema.Struct({
|
|
28
|
+
id: Schema.String,
|
|
29
|
+
username: Schema.String,
|
|
30
|
+
email: Schema.String,
|
|
31
|
+
password_hash: Schema.NullOr(Schema.String),
|
|
32
|
+
email_status: Schema.Literals(['unverified', 'verified']),
|
|
33
|
+
totp_status: Schema.Literals(['off', 'pending', 'enabled']),
|
|
34
|
+
totp_secret: Schema.NullOr(Schema.String),
|
|
35
|
+
totp_enabled_at: Schema.NullOr(Schema.String),
|
|
36
|
+
totp_last_step: Schema.Finite,
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
const OAuthUserRow = Schema.Struct({
|
|
40
|
+
id: Schema.String,
|
|
41
|
+
username: Schema.String,
|
|
42
|
+
email: Schema.String,
|
|
43
|
+
google_sub: Schema.NullOr(Schema.String),
|
|
44
|
+
github_id: Schema.NullOr(Schema.String),
|
|
45
|
+
email_status: Schema.Literals(['unverified', 'verified']),
|
|
46
|
+
totp_status: Schema.Literals(['off', 'pending', 'enabled']),
|
|
47
|
+
totp_secret: Schema.NullOr(Schema.String),
|
|
48
|
+
totp_enabled_at: Schema.NullOr(Schema.String),
|
|
49
|
+
totp_last_step: Schema.Finite,
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
const MeRow = Schema.Struct({
|
|
53
|
+
id: Schema.String,
|
|
54
|
+
username: Schema.String,
|
|
55
|
+
email: Schema.String,
|
|
56
|
+
email_status: Schema.Literals(['unverified', 'verified']),
|
|
57
|
+
has_password: Schema.Finite,
|
|
58
|
+
totp_status: Schema.Literals(['off', 'pending', 'enabled']),
|
|
59
|
+
email_changed_at: Schema.NullOr(Schema.String),
|
|
60
|
+
pending_email: Schema.NullOr(Schema.String),
|
|
61
|
+
pending_until: Schema.NullOr(Schema.String),
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
const TakenRow = Schema.Struct({ field: Schema.Literals(['username', 'email']) })
|
|
65
|
+
const UsernameRow = Schema.Struct({ username: Schema.String })
|
|
66
|
+
|
|
67
|
+
export type OAuthProvider = 'google' | 'github'
|
|
68
|
+
|
|
69
|
+
export interface OAuthProfile {
|
|
70
|
+
readonly provider: OAuthProvider
|
|
71
|
+
readonly providerId: string
|
|
72
|
+
readonly email: string
|
|
73
|
+
readonly emailVerified: boolean
|
|
74
|
+
readonly preferredUsername?: string | undefined
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const OAUTH_META: Record<OAuthProvider, { readonly column: 'google_sub' | 'github_id'; readonly label: string }> = {
|
|
78
|
+
google: { column: 'google_sub', label: 'Google' },
|
|
79
|
+
github: { column: 'github_id', label: 'GitHub' },
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const usernameBaseFrom = (raw: string) => {
|
|
83
|
+
const base = raw
|
|
84
|
+
.toLowerCase()
|
|
85
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
86
|
+
.replace(/^-+|-+$/g, '')
|
|
87
|
+
.slice(0, 18)
|
|
88
|
+
return base.length >= 3 ? base : 'user'
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const toAuthUser = (row: {
|
|
92
|
+
readonly id: string
|
|
93
|
+
readonly username: string
|
|
94
|
+
readonly email: string
|
|
95
|
+
readonly email_status: 'unverified' | 'verified'
|
|
96
|
+
readonly totp_status: 'off' | 'pending' | 'enabled'
|
|
97
|
+
}): AuthUser => ({
|
|
98
|
+
id: row.id,
|
|
99
|
+
username: row.username,
|
|
100
|
+
email: row.email,
|
|
101
|
+
emailStatus: row.email_status,
|
|
102
|
+
totpStatus: row.totp_status,
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
const UNCONFIRMED_STALE = `email = ? AND email_status = 'unverified' AND google_sub IS NULL AND github_id IS NULL AND created_at < ?`
|
|
106
|
+
|
|
107
|
+
export class Identity extends Context.Service<
|
|
108
|
+
Identity,
|
|
109
|
+
{
|
|
110
|
+
readonly register: (input: { readonly username: string; readonly email: string; readonly password: string }) => Effect.Effect<AuthUser, Conflict>
|
|
111
|
+
readonly login: (input: {
|
|
112
|
+
readonly identity: string
|
|
113
|
+
readonly password: string
|
|
114
|
+
readonly code?: string | undefined
|
|
115
|
+
}) => Effect.Effect<LoginOutcome, Unauthorized | RateLimited | Forbidden>
|
|
116
|
+
readonly oauth: (profile: OAuthProfile) => Effect.Effect<LoginOutcome, Forbidden | Conflict | Unprocessable>
|
|
117
|
+
readonly me: (userId: string) => Effect.Effect<MeView, NotFound>
|
|
118
|
+
readonly updateProfile: (userId: string, input: { readonly username: string }) => Effect.Effect<AuthUser, Conflict | NotFound>
|
|
119
|
+
readonly deleteAccount: (userId: string, confirm: string) => Effect.Effect<void, NotFound | Unprocessable>
|
|
120
|
+
}
|
|
121
|
+
>()('app/identity/Identity') {
|
|
122
|
+
static readonly layer = Layer.effect(
|
|
123
|
+
Identity,
|
|
124
|
+
Effect.gen(function* () {
|
|
125
|
+
const config = yield* AppConfig
|
|
126
|
+
const db = yield* Database
|
|
127
|
+
const atomic = yield* AtomicBatch
|
|
128
|
+
const ids = yield* IdGenerator
|
|
129
|
+
const hasher = yield* PasswordHasher
|
|
130
|
+
const limiter = yield* RateLimiter
|
|
131
|
+
const lockout = yield* LoginLockout
|
|
132
|
+
const sessions = yield* Sessions
|
|
133
|
+
const totp = yield* Totp
|
|
134
|
+
|
|
135
|
+
const decoy = yield* Effect.cached(hasher.hash('decoy-password-constant-timing'))
|
|
136
|
+
|
|
137
|
+
const register = Effect.fn('Identity.register')(function* (input: { readonly username: string; readonly email: string; readonly password: string }) {
|
|
138
|
+
const username = input.username.trim().toLowerCase()
|
|
139
|
+
const email = input.email.trim().toLowerCase()
|
|
140
|
+
const now = yield* DateTime.now
|
|
141
|
+
const nowStr = DateTime.formatIso(now)
|
|
142
|
+
const staleBefore = DateTime.formatIso(DateTime.subtract(now, { hours: UNCONFIRMED_HOLD_HOURS }))
|
|
143
|
+
|
|
144
|
+
const taken = yield* db
|
|
145
|
+
.first(
|
|
146
|
+
TakenRow,
|
|
147
|
+
`SELECT 'email' AS field FROM users WHERE email = ? AND NOT (${UNCONFIRMED_STALE})
|
|
148
|
+
UNION ALL
|
|
149
|
+
SELECT 'username' AS field FROM users WHERE username = ? AND NOT (${UNCONFIRMED_STALE})
|
|
150
|
+
LIMIT 1`,
|
|
151
|
+
[email, email, staleBefore, username, email, staleBefore],
|
|
152
|
+
)
|
|
153
|
+
.pipe(Effect.orDie)
|
|
154
|
+
|
|
155
|
+
if (taken) {
|
|
156
|
+
return yield* new Conflict({
|
|
157
|
+
field: taken.field,
|
|
158
|
+
message: taken.field === 'email' ? 'That email address is already registered.' : 'That username is already taken.',
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const id = yield* ids.next('user')
|
|
163
|
+
const passwordHash = yield* hasher.hash(input.password)
|
|
164
|
+
|
|
165
|
+
yield* atomic
|
|
166
|
+
.run([
|
|
167
|
+
{ sql: `DELETE FROM users WHERE ${UNCONFIRMED_STALE}`, params: [email, staleBefore] },
|
|
168
|
+
{
|
|
169
|
+
sql: `INSERT INTO users (id, username, email, password_hash, email_status, totp_status, created_at, last_active_at)
|
|
170
|
+
VALUES (?, ?, ?, ?, 'unverified', 'off', ?, ?)`,
|
|
171
|
+
params: [id, username, email, passwordHash, nowStr, nowStr],
|
|
172
|
+
},
|
|
173
|
+
])
|
|
174
|
+
.pipe(
|
|
175
|
+
Effect.catch((error) => {
|
|
176
|
+
if (/UNIQUE constraint failed: users\.email/i.test(error.message)) {
|
|
177
|
+
return Effect.fail(new Conflict({ field: 'email', message: 'That email address is already registered.' }))
|
|
178
|
+
}
|
|
179
|
+
if (/UNIQUE constraint failed: users\.username/i.test(error.message)) {
|
|
180
|
+
return Effect.fail(new Conflict({ field: 'username', message: 'That username is already taken.' }))
|
|
181
|
+
}
|
|
182
|
+
return Effect.die(error)
|
|
183
|
+
}),
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
return { id, username, email, emailStatus: 'unverified', totpStatus: 'off' } satisfies AuthUser
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
const login = Effect.fn('Identity.login')(function* (input: {
|
|
190
|
+
readonly identity: string
|
|
191
|
+
readonly password: string
|
|
192
|
+
readonly code?: string | undefined
|
|
193
|
+
}) {
|
|
194
|
+
const key = input.identity.trim().toLowerCase()
|
|
195
|
+
yield* limiter.check('sign-in-account', `login:${key}`)
|
|
196
|
+
|
|
197
|
+
const user = yield* db
|
|
198
|
+
.first(
|
|
199
|
+
LoginUserRow,
|
|
200
|
+
`SELECT id, username, email, password_hash, email_status, totp_status, totp_secret, totp_enabled_at, totp_last_step
|
|
201
|
+
FROM users
|
|
202
|
+
WHERE email = ? OR username = ?
|
|
203
|
+
LIMIT 1`,
|
|
204
|
+
[key, key],
|
|
205
|
+
)
|
|
206
|
+
.pipe(Effect.orDie)
|
|
207
|
+
|
|
208
|
+
const subject = user ? `user:${user.id}` : `identity:${key}`
|
|
209
|
+
yield* lockout.assertUnlocked(subject)
|
|
210
|
+
|
|
211
|
+
const decoyHash = yield* decoy
|
|
212
|
+
const passwordOk = yield* hasher.verify(user?.password_hash ?? decoyHash, input.password)
|
|
213
|
+
if (!user || !user.password_hash || !passwordOk) {
|
|
214
|
+
yield* lockout.recordFailure(subject)
|
|
215
|
+
return yield* new Unauthorized({ message: WRONG_LOGIN })
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const totpState = decodeTotpState(user)
|
|
219
|
+
if (config.features.totp && totpState._tag === 'Enabled') {
|
|
220
|
+
if (!input.code) {
|
|
221
|
+
yield* lockout.clear(subject)
|
|
222
|
+
const challenge = yield* totp.issueChallenge(user.id)
|
|
223
|
+
return { status: 'totp_required', challenge } satisfies LoginOutcome
|
|
224
|
+
}
|
|
225
|
+
const ok = yield* totp.verifySecondFactor(user.id, input.code)
|
|
226
|
+
if (!ok) return yield* new Unauthorized({ message: WRONG_CODE })
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
yield* lockout.clear(subject)
|
|
230
|
+
return { status: 'authenticated', user: toAuthUser(user) } satisfies LoginOutcome
|
|
231
|
+
})
|
|
232
|
+
|
|
233
|
+
const pickUniqueUsername = (base: string) =>
|
|
234
|
+
Effect.gen(function* () {
|
|
235
|
+
for (let attempt = 0; attempt < 12; attempt++) {
|
|
236
|
+
const candidate = attempt === 0 ? base : `${base.slice(0, 18)}-${Math.floor(1000 + Math.random() * 9000)}`
|
|
237
|
+
const exists = yield* db.first(UsernameRow, `SELECT username FROM users WHERE username = ?`, [candidate]).pipe(Effect.orDie)
|
|
238
|
+
if (!exists) return candidate
|
|
239
|
+
}
|
|
240
|
+
return `user-${crypto.randomUUID().slice(0, 8)}`
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
const oauth = Effect.fn('Identity.oauth')(function* (profile: OAuthProfile) {
|
|
244
|
+
const meta = OAUTH_META[profile.provider]
|
|
245
|
+
const enabled = profile.provider === 'google' ? config.features.googleOAuth : config.features.githubOAuth
|
|
246
|
+
if (!enabled) return yield* new Forbidden({ message: `${meta.label} sign-in is disabled.` })
|
|
247
|
+
if (!profile.emailVerified) return yield* new Unprocessable({ message: `Your ${meta.label} account email must be verified.` })
|
|
248
|
+
|
|
249
|
+
const email = profile.email.trim().toLowerCase()
|
|
250
|
+
const columns = `id, username, email, google_sub, github_id, email_status, totp_status, totp_secret, totp_enabled_at, totp_last_step`
|
|
251
|
+
|
|
252
|
+
const byProvider = yield* db.first(OAuthUserRow, `SELECT ${columns} FROM users WHERE ${meta.column} = ?`, [profile.providerId]).pipe(Effect.orDie)
|
|
253
|
+
|
|
254
|
+
if (byProvider) {
|
|
255
|
+
const totpState = decodeTotpState(byProvider)
|
|
256
|
+
if (config.features.totp && totpState._tag === 'Enabled') {
|
|
257
|
+
return { status: 'totp_required', challenge: yield* totp.issueChallenge(byProvider.id) } satisfies LoginOutcome
|
|
258
|
+
}
|
|
259
|
+
return { status: 'authenticated', user: toAuthUser(byProvider) } satisfies LoginOutcome
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const now = yield* DateTime.now
|
|
263
|
+
const nowStr = DateTime.formatIso(now)
|
|
264
|
+
const staleBefore = DateTime.formatIso(DateTime.subtract(now, { hours: UNCONFIRMED_HOLD_HOURS }))
|
|
265
|
+
|
|
266
|
+
const byEmail = yield* db
|
|
267
|
+
.first(OAuthUserRow, `SELECT ${columns} FROM users WHERE email = ? AND NOT (${UNCONFIRMED_STALE})`, [email, email, staleBefore])
|
|
268
|
+
.pipe(Effect.orDie)
|
|
269
|
+
|
|
270
|
+
if (byEmail) {
|
|
271
|
+
const existingProviderId = byEmail[meta.column]
|
|
272
|
+
if (existingProviderId && existingProviderId !== profile.providerId) {
|
|
273
|
+
return yield* new Conflict({ message: `That email address is already linked to another ${meta.label} account.` })
|
|
274
|
+
}
|
|
275
|
+
yield* db
|
|
276
|
+
.run(`UPDATE users SET ${meta.column} = ?, email_status = 'verified', email_verified_at = COALESCE(email_verified_at, ?) WHERE id = ?`, [
|
|
277
|
+
profile.providerId,
|
|
278
|
+
nowStr,
|
|
279
|
+
byEmail.id,
|
|
280
|
+
])
|
|
281
|
+
.pipe(Effect.orDie)
|
|
282
|
+
const linked: AuthUser = { ...toAuthUser(byEmail), emailStatus: 'verified' }
|
|
283
|
+
const totpState = decodeTotpState(byEmail)
|
|
284
|
+
if (config.features.totp && totpState._tag === 'Enabled') {
|
|
285
|
+
return { status: 'totp_required', challenge: yield* totp.issueChallenge(byEmail.id) } satisfies LoginOutcome
|
|
286
|
+
}
|
|
287
|
+
return { status: 'authenticated', user: linked } satisfies LoginOutcome
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const id = yield* ids.next('user')
|
|
291
|
+
const preferred = profile.preferredUsername ? usernameBaseFrom(profile.preferredUsername) : usernameBaseFrom(email.split('@')[0] ?? '')
|
|
292
|
+
const username = yield* pickUniqueUsername(preferred)
|
|
293
|
+
yield* atomic
|
|
294
|
+
.run([
|
|
295
|
+
{ sql: `DELETE FROM users WHERE ${UNCONFIRMED_STALE}`, params: [email, staleBefore] },
|
|
296
|
+
{
|
|
297
|
+
sql: `INSERT INTO users (id, username, email, ${meta.column}, email_status, email_verified_at, totp_status, created_at, last_active_at)
|
|
298
|
+
VALUES (?, ?, ?, ?, 'verified', ?, 'off', ?, ?)`,
|
|
299
|
+
params: [id, username, email, profile.providerId, nowStr, nowStr, nowStr],
|
|
300
|
+
},
|
|
301
|
+
])
|
|
302
|
+
.pipe(Effect.orDie)
|
|
303
|
+
|
|
304
|
+
return {
|
|
305
|
+
status: 'authenticated',
|
|
306
|
+
user: { id, username, email, emailStatus: 'verified', totpStatus: 'off' },
|
|
307
|
+
} satisfies LoginOutcome
|
|
308
|
+
})
|
|
309
|
+
|
|
310
|
+
const me = Effect.fn('Identity.me')(function* (userId: string) {
|
|
311
|
+
const now = yield* nowIso
|
|
312
|
+
const row = yield* db
|
|
313
|
+
.first(
|
|
314
|
+
MeRow,
|
|
315
|
+
`SELECT
|
|
316
|
+
u.id,
|
|
317
|
+
u.username,
|
|
318
|
+
u.email,
|
|
319
|
+
u.email_status,
|
|
320
|
+
u.password_hash IS NOT NULL AS has_password,
|
|
321
|
+
u.totp_status,
|
|
322
|
+
u.email_changed_at,
|
|
323
|
+
(SELECT c.new_email FROM email_change_tokens c WHERE c.user_id = u.id AND c.status = 'active' AND c.expires_at > ? ORDER BY c.created_at DESC LIMIT 1) AS pending_email,
|
|
324
|
+
(SELECT c.expires_at FROM email_change_tokens c WHERE c.user_id = u.id AND c.status = 'active' AND c.expires_at > ? ORDER BY c.created_at DESC LIMIT 1) AS pending_until
|
|
325
|
+
FROM users u
|
|
326
|
+
WHERE u.id = ?`,
|
|
327
|
+
[now, now, userId],
|
|
328
|
+
)
|
|
329
|
+
.pipe(Effect.orDie)
|
|
330
|
+
if (!row) return yield* new NotFound({ resource: 'User', id: userId })
|
|
331
|
+
return {
|
|
332
|
+
id: row.id,
|
|
333
|
+
username: row.username,
|
|
334
|
+
email: row.email,
|
|
335
|
+
emailStatus: row.email_status,
|
|
336
|
+
hasPassword: row.has_password > 0,
|
|
337
|
+
totpStatus: row.totp_status,
|
|
338
|
+
pendingEmailChange: row.pending_email && row.pending_until ? { email: row.pending_email, expiresAt: row.pending_until } : null,
|
|
339
|
+
emailChangedAt: row.email_changed_at,
|
|
340
|
+
} satisfies MeView
|
|
341
|
+
})
|
|
342
|
+
|
|
343
|
+
const updateProfile = Effect.fn('Identity.updateProfile')(function* (userId: string, input: { readonly username: string }) {
|
|
344
|
+
const username = input.username.trim().toLowerCase()
|
|
345
|
+
yield* db
|
|
346
|
+
.run(`UPDATE users SET username = ? WHERE id = ?`, [username, userId])
|
|
347
|
+
.pipe(
|
|
348
|
+
Effect.catch((error) =>
|
|
349
|
+
/UNIQUE constraint failed: users\.username/i.test(error.message)
|
|
350
|
+
? Effect.fail(new Conflict({ field: 'username', message: 'That username is already taken.' }))
|
|
351
|
+
: Effect.die(error),
|
|
352
|
+
),
|
|
353
|
+
)
|
|
354
|
+
const updated = yield* db
|
|
355
|
+
.first(
|
|
356
|
+
LoginUserRow,
|
|
357
|
+
`SELECT id, username, email, password_hash, email_status, totp_status, totp_secret, totp_enabled_at, totp_last_step FROM users WHERE id = ?`,
|
|
358
|
+
[userId],
|
|
359
|
+
)
|
|
360
|
+
.pipe(Effect.orDie)
|
|
361
|
+
if (!updated) return yield* new NotFound({ resource: 'User', id: userId })
|
|
362
|
+
yield* sessions.forget(userId)
|
|
363
|
+
return toAuthUser(updated)
|
|
364
|
+
})
|
|
365
|
+
|
|
366
|
+
const deleteAccount = Effect.fn('Identity.deleteAccount')(function* (userId: string, confirm: string) {
|
|
367
|
+
const row = yield* db.first(UsernameRow, `SELECT username FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
|
|
368
|
+
if (!row) return yield* new NotFound({ resource: 'User', id: userId })
|
|
369
|
+
if (!matchesConfirm(confirm, row.username)) {
|
|
370
|
+
return yield* new Unprocessable({ message: `Type ${row.username} to confirm deletion.` })
|
|
371
|
+
}
|
|
372
|
+
yield* sessions.forget(userId)
|
|
373
|
+
yield* db.run(`DELETE FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
|
|
374
|
+
})
|
|
375
|
+
|
|
376
|
+
return Identity.of({ register, login, oauth, me, updateProfile, deleteAccount })
|
|
377
|
+
}),
|
|
378
|
+
)
|
|
379
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { Context, DateTime, Effect, Layer, Schema } from 'effect'
|
|
2
|
+
|
|
3
|
+
import type { EmailStatus } from '#shared/utils/auth'
|
|
4
|
+
|
|
5
|
+
import { Database } from '#server/core/platform/database'
|
|
6
|
+
import { IdGenerator } from '#server/core/platform/id-generator'
|
|
7
|
+
|
|
8
|
+
export const SESSION_DAYS = 30
|
|
9
|
+
|
|
10
|
+
const ACTIVITY_STEP_HOURS = 24
|
|
11
|
+
const SEEN_STEP_MINUTES = 60
|
|
12
|
+
export const RECENT_SESSIONS = 10
|
|
13
|
+
|
|
14
|
+
const VerifyRow = Schema.Struct({
|
|
15
|
+
id: Schema.String,
|
|
16
|
+
username: Schema.String,
|
|
17
|
+
email_status: Schema.Literals(['unverified', 'verified']),
|
|
18
|
+
last_active_at: Schema.String,
|
|
19
|
+
last_seen_at: Schema.String,
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
const RecentRow = Schema.Struct({
|
|
23
|
+
id: Schema.String,
|
|
24
|
+
device: Schema.String,
|
|
25
|
+
last_seen_at: Schema.String,
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
export interface SessionSummary {
|
|
29
|
+
readonly device: string
|
|
30
|
+
readonly lastSeenAt: string
|
|
31
|
+
readonly current: boolean
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SessionUser {
|
|
35
|
+
readonly id: string
|
|
36
|
+
readonly username: string
|
|
37
|
+
readonly emailStatus: EmailStatus
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const REMEMBER_MS = 3000
|
|
41
|
+
const REMEMBER_MAX = 1000
|
|
42
|
+
|
|
43
|
+
export class Sessions extends Context.Service<
|
|
44
|
+
Sessions,
|
|
45
|
+
{
|
|
46
|
+
readonly start: (userId: string, device?: string) => Effect.Effect<string>
|
|
47
|
+
readonly verify: (sessionId: string) => Effect.Effect<SessionUser | undefined>
|
|
48
|
+
readonly end: (sessionId: string) => Effect.Effect<void>
|
|
49
|
+
readonly endAll: (userId: string) => Effect.Effect<void>
|
|
50
|
+
readonly forget: (userId: string) => Effect.Effect<void>
|
|
51
|
+
readonly recent: (userId: string, currentId?: string) => Effect.Effect<ReadonlyArray<SessionSummary>>
|
|
52
|
+
}
|
|
53
|
+
>()('app/identity/Sessions') {
|
|
54
|
+
static readonly layer = Layer.effect(
|
|
55
|
+
Sessions,
|
|
56
|
+
Effect.gen(function* () {
|
|
57
|
+
const db = yield* Database
|
|
58
|
+
const ids = yield* IdGenerator
|
|
59
|
+
const remembered = new Map<string, { readonly user: SessionUser; readonly until: number }>()
|
|
60
|
+
|
|
61
|
+
const forgetUser = (userId: string) => {
|
|
62
|
+
for (const [id, entry] of remembered) if (entry.user.id === userId) remembered.delete(id)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return Sessions.of({
|
|
66
|
+
start: (userId, device = '') =>
|
|
67
|
+
Effect.gen(function* () {
|
|
68
|
+
const id = yield* ids.next('session')
|
|
69
|
+
const now = yield* DateTime.now
|
|
70
|
+
const at = DateTime.formatIso(now)
|
|
71
|
+
yield* db
|
|
72
|
+
.run(`INSERT INTO sessions (id, user_id, device, created_at, last_seen_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)`, [
|
|
73
|
+
id,
|
|
74
|
+
userId,
|
|
75
|
+
device,
|
|
76
|
+
at,
|
|
77
|
+
at,
|
|
78
|
+
DateTime.formatIso(DateTime.add(now, { days: SESSION_DAYS })),
|
|
79
|
+
])
|
|
80
|
+
.pipe(Effect.orDie)
|
|
81
|
+
return id
|
|
82
|
+
}),
|
|
83
|
+
|
|
84
|
+
verify: (sessionId) =>
|
|
85
|
+
Effect.gen(function* () {
|
|
86
|
+
const known = remembered.get(sessionId)
|
|
87
|
+
if (known && known.until > Date.now()) return known.user
|
|
88
|
+
|
|
89
|
+
const now = yield* DateTime.now
|
|
90
|
+
const nowStr = DateTime.formatIso(now)
|
|
91
|
+
const row = yield* db
|
|
92
|
+
.first(
|
|
93
|
+
VerifyRow,
|
|
94
|
+
`SELECT u.id, u.username, u.email_status, u.last_active_at, s.last_seen_at
|
|
95
|
+
FROM sessions s
|
|
96
|
+
JOIN users u ON u.id = s.user_id
|
|
97
|
+
WHERE s.id = ? AND s.expires_at > ?`,
|
|
98
|
+
[sessionId, nowStr],
|
|
99
|
+
)
|
|
100
|
+
.pipe(Effect.orDie)
|
|
101
|
+
if (!row) return undefined
|
|
102
|
+
|
|
103
|
+
if (row.last_active_at < DateTime.formatIso(DateTime.subtract(now, { hours: ACTIVITY_STEP_HOURS }))) {
|
|
104
|
+
yield* db.run(`UPDATE users SET last_active_at = ? WHERE id = ?`, [nowStr, row.id]).pipe(Effect.orDie)
|
|
105
|
+
}
|
|
106
|
+
if (row.last_seen_at < DateTime.formatIso(DateTime.subtract(now, { minutes: SEEN_STEP_MINUTES }))) {
|
|
107
|
+
yield* db.run(`UPDATE sessions SET last_seen_at = ? WHERE id = ?`, [nowStr, sessionId]).pipe(Effect.orDie)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const user: SessionUser = { id: row.id, username: row.username, emailStatus: row.email_status }
|
|
111
|
+
if (remembered.size >= REMEMBER_MAX) remembered.clear()
|
|
112
|
+
remembered.set(sessionId, { user, until: Date.now() + REMEMBER_MS })
|
|
113
|
+
return user
|
|
114
|
+
}),
|
|
115
|
+
|
|
116
|
+
end: (sessionId) =>
|
|
117
|
+
Effect.sync(() => remembered.delete(sessionId)).pipe(
|
|
118
|
+
Effect.flatMap(() => db.run(`DELETE FROM sessions WHERE id = ?`, [sessionId]).pipe(Effect.orDie)),
|
|
119
|
+
),
|
|
120
|
+
|
|
121
|
+
endAll: (userId) =>
|
|
122
|
+
Effect.sync(() => forgetUser(userId)).pipe(Effect.flatMap(() => db.run(`DELETE FROM sessions WHERE user_id = ?`, [userId]).pipe(Effect.orDie))),
|
|
123
|
+
|
|
124
|
+
forget: (userId) => Effect.sync(() => forgetUser(userId)),
|
|
125
|
+
|
|
126
|
+
recent: (userId, currentId) =>
|
|
127
|
+
Effect.gen(function* () {
|
|
128
|
+
const nowStr = DateTime.formatIso(yield* DateTime.now)
|
|
129
|
+
const rows = yield* db
|
|
130
|
+
.all(RecentRow, `SELECT id, device, last_seen_at FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY last_seen_at DESC LIMIT ?`, [
|
|
131
|
+
userId,
|
|
132
|
+
nowStr,
|
|
133
|
+
RECENT_SESSIONS,
|
|
134
|
+
])
|
|
135
|
+
.pipe(Effect.orDie)
|
|
136
|
+
return rows.map((row): SessionSummary => ({ device: row.device || 'Unknown device', lastSeenAt: row.last_seen_at, current: row.id === currentId }))
|
|
137
|
+
}),
|
|
138
|
+
})
|
|
139
|
+
}),
|
|
140
|
+
)
|
|
141
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { EmailStatus, TotpStatus } from '#shared/utils/auth'
|
|
2
|
+
|
|
3
|
+
export interface AuthUser {
|
|
4
|
+
readonly id: string
|
|
5
|
+
readonly username: string
|
|
6
|
+
readonly email: string
|
|
7
|
+
readonly emailStatus: EmailStatus
|
|
8
|
+
readonly totpStatus: TotpStatus
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Explicit discriminated union for the 2FA lifecycle — impossible states are rejected at both DB and decode boundaries. */
|
|
12
|
+
export type TotpState =
|
|
13
|
+
| { readonly _tag: 'Off' }
|
|
14
|
+
| { readonly _tag: 'Pending'; readonly sealedSecret: string }
|
|
15
|
+
| { readonly _tag: 'Enabled'; readonly sealedSecret: string; readonly enabledAt: string; readonly lastStep: number }
|
|
16
|
+
|
|
17
|
+
export interface TotpColumns {
|
|
18
|
+
readonly totp_status: TotpStatus
|
|
19
|
+
readonly totp_secret: string | null
|
|
20
|
+
readonly totp_enabled_at: string | null
|
|
21
|
+
readonly totp_last_step: number
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Decodes SQL TOTP columns into the explicit `TotpState` union, asserting DB invariants instead of guessing from nullable fields. */
|
|
25
|
+
export const decodeTotpState = (row: TotpColumns): TotpState => {
|
|
26
|
+
switch (row.totp_status) {
|
|
27
|
+
case 'off':
|
|
28
|
+
if (row.totp_secret !== null || row.totp_enabled_at !== null) throw new Error('Invariant violation: totp_status=off has TOTP data.')
|
|
29
|
+
return { _tag: 'Off' }
|
|
30
|
+
case 'pending':
|
|
31
|
+
if (row.totp_secret === null || row.totp_enabled_at !== null) throw new Error('Invariant violation: totp_status=pending is inconsistent.')
|
|
32
|
+
return { _tag: 'Pending', sealedSecret: row.totp_secret }
|
|
33
|
+
case 'enabled':
|
|
34
|
+
if (row.totp_secret === null || row.totp_enabled_at === null) throw new Error('Invariant violation: totp_status=enabled is missing data.')
|
|
35
|
+
return { _tag: 'Enabled', sealedSecret: row.totp_secret, enabledAt: row.totp_enabled_at, lastStep: row.totp_last_step }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type LoginOutcome = { readonly status: 'authenticated'; readonly user: AuthUser } | { readonly status: 'totp_required'; readonly challenge: string }
|
|
40
|
+
|
|
41
|
+
export type TokenStatus = 'active' | 'used' | 'revoked'
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { Effect } from 'effect'
|
|
2
|
+
import { Mac, type CryptoError } from 'effect/crypto'
|
|
3
|
+
|
|
4
|
+
import { nowMillis } from '#server/core/platform/clock'
|
|
5
|
+
import { TotpCryptoError } from '#server/utils/errors'
|
|
6
|
+
|
|
7
|
+
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
|
8
|
+
const STEP_SECONDS = 30
|
|
9
|
+
const DIGITS = 6
|
|
10
|
+
|
|
11
|
+
export const base32Encode = (bytes: Uint8Array): string => {
|
|
12
|
+
let bits = 0
|
|
13
|
+
let value = 0
|
|
14
|
+
let out = ''
|
|
15
|
+
|
|
16
|
+
for (const byte of bytes) {
|
|
17
|
+
value = (value << 8) | byte
|
|
18
|
+
bits += 8
|
|
19
|
+
while (bits >= 5) {
|
|
20
|
+
out += ALPHABET[(value >>> (bits - 5)) & 31]
|
|
21
|
+
bits -= 5
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (bits > 0) out += ALPHABET[(value << (5 - bits)) & 31]
|
|
26
|
+
return out
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Strict decode of a stored secret. Any character outside the alphabet means the value is corrupt. */
|
|
30
|
+
export const base32Decode = (text: string): Effect.Effect<Uint8Array, TotpCryptoError> =>
|
|
31
|
+
Effect.suspend(() => {
|
|
32
|
+
let bits = 0
|
|
33
|
+
let value = 0
|
|
34
|
+
const out: number[] = []
|
|
35
|
+
|
|
36
|
+
for (const char of text) {
|
|
37
|
+
const index = ALPHABET.indexOf(char)
|
|
38
|
+
if (index === -1) return Effect.fail(new TotpCryptoError({ message: 'Stored TOTP secret is not valid base32.' }))
|
|
39
|
+
|
|
40
|
+
value = ((value << 5) | index) & 0xffff
|
|
41
|
+
bits += 5
|
|
42
|
+
|
|
43
|
+
if (bits >= 8) {
|
|
44
|
+
out.push((value >>> (bits - 8)) & 255)
|
|
45
|
+
bits -= 8
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return Effect.succeed(new Uint8Array(out))
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
/** One-time password for a counter (RFC 4226) using HMAC-SHA1 as authenticator apps expect. */
|
|
52
|
+
export const hotp = (secret: Uint8Array, counter: number, digits = DIGITS): Effect.Effect<string, CryptoError.CryptoError, Mac.Mac> =>
|
|
53
|
+
Effect.gen(function* () {
|
|
54
|
+
const mac = yield* Mac.Mac
|
|
55
|
+
const key = yield* Mac.key(Mac.hmacSha1, secret)
|
|
56
|
+
const message = new Uint8Array(8)
|
|
57
|
+
|
|
58
|
+
new DataView(message.buffer).setUint32(4, counter >>> 0)
|
|
59
|
+
new DataView(message.buffer).setUint32(0, Math.floor(counter / 2 ** 32))
|
|
60
|
+
|
|
61
|
+
const tag = yield* mac.sign(key, message)
|
|
62
|
+
const offset = tag[tag.length - 1]! & 15
|
|
63
|
+
const code = ((tag[offset]! & 127) << 24) | (tag[offset + 1]! << 16) | (tag[offset + 2]! << 8) | tag[offset + 3]!
|
|
64
|
+
|
|
65
|
+
return String(code % 10 ** digits).padStart(digits, '0')
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
export const stepOf = (nowMs: number) => Math.floor(nowMs / 1000 / STEP_SECONDS)
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Returns the matched time step (within ±1 step of the current clock time) if strictly greater than `lastStep`, else undefined.
|
|
72
|
+
* Refusing `step <= lastStep` prevents replay of a previously used code.
|
|
73
|
+
*/
|
|
74
|
+
export const verifyTotp = (secret: Uint8Array, code: string, lastStep: number): Effect.Effect<number | undefined, CryptoError.CryptoError, Mac.Mac> =>
|
|
75
|
+
Effect.gen(function* () {
|
|
76
|
+
if (!/^\d{6}$/.test(code)) return undefined
|
|
77
|
+
|
|
78
|
+
const now = stepOf(yield* nowMillis)
|
|
79
|
+
const candidates = [now, now - 1, now + 1].filter((step) => step > lastStep)
|
|
80
|
+
const codes = yield* Effect.forEach(candidates, (step) => hotp(secret, step), { concurrency: 'unbounded' })
|
|
81
|
+
const matchedIndex = codes.indexOf(code)
|
|
82
|
+
|
|
83
|
+
return matchedIndex === -1 ? undefined : candidates[matchedIndex]
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
export const newSecret = (randomBytes: (size: number) => Effect.Effect<Uint8Array>): Effect.Effect<string> => Effect.map(randomBytes(20), base32Encode)
|
|
87
|
+
|
|
88
|
+
export const otpauthUri = (email: string, secret: string, issuer: string): string =>
|
|
89
|
+
`otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(email)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=${DIGITS}&period=${STEP_SECONDS}`
|