@prunellejs/auth 0.1.1 → 0.7.3
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/LICENSE +21 -0
- package/llms.txt +53 -23
- package/package.json +5 -4
- package/src/account.ts +101 -0
- package/src/crypto.ts +57 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +127 -24
- package/src/index.ts +320 -237
- package/src/links.ts +178 -0
- package/src/oauth-routes.ts +119 -52
- package/src/org-routes.ts +226 -0
- package/src/orgs.ts +421 -0
- package/src/passkey-client.ts +211 -0
- package/src/passkey-routes.ts +220 -0
- package/src/passkeys.ts +422 -0
- package/src/routes.ts +178 -120
- package/src/session-cookie.ts +62 -0
- package/src/session.ts +158 -104
- package/src/sqlite-ext.ts +550 -0
- package/src/sqlite.ts +144 -71
- package/src/store-ext.ts +493 -0
- package/src/store.ts +120 -48
- package/src/totp-routes.ts +144 -0
- package/src/totp.ts +376 -0
- package/src/webauthn-crypto.ts +284 -0
package/src/store.ts
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
// Clean pluggable AuthStore contract + zero-setup in-memory store for dev & tests.
|
|
2
2
|
|
|
3
|
+
import type { AuthStoreExt, UserExportExt } from './store-ext'
|
|
4
|
+
import { createMemoryStoreExt } from './store-ext'
|
|
5
|
+
|
|
6
|
+
export type {
|
|
7
|
+
AuthStoreExt,
|
|
8
|
+
Organization,
|
|
9
|
+
OrgInvitation,
|
|
10
|
+
OrgMembership,
|
|
11
|
+
PasskeyRecord,
|
|
12
|
+
PasskeySummary,
|
|
13
|
+
RecoveryCodeRecord,
|
|
14
|
+
TotpRecord,
|
|
15
|
+
UserExportExt,
|
|
16
|
+
UserOrgSummary,
|
|
17
|
+
} from './store-ext'
|
|
18
|
+
export { toPasskeySummary } from './store-ext'
|
|
19
|
+
|
|
3
20
|
export interface AuthUser {
|
|
4
21
|
id: string
|
|
5
22
|
email: string
|
|
@@ -31,6 +48,7 @@ export interface OAuthAccount {
|
|
|
31
48
|
createdAt: number
|
|
32
49
|
}
|
|
33
50
|
|
|
51
|
+
/** Verification token purposes. `'reset-password'` is reserved for app-defined password-reset flows via `store.createToken`/`store.consumeToken`. */
|
|
34
52
|
export type TokenKind = 'magic-link' | 'verify-email' | 'reset-password'
|
|
35
53
|
|
|
36
54
|
export interface VerificationToken {
|
|
@@ -41,14 +59,18 @@ export interface VerificationToken {
|
|
|
41
59
|
expiresAt: number
|
|
42
60
|
}
|
|
43
61
|
|
|
44
|
-
export interface UserExport<TUser extends AuthUser = AuthUser> {
|
|
62
|
+
export interface UserExport<TUser extends AuthUser = AuthUser> extends UserExportExt {
|
|
45
63
|
user: PublicUser<TUser>
|
|
46
64
|
sessions: AuthSession[]
|
|
47
65
|
oauthAccounts: Array<{ provider: string, providerAccountId: string, createdAt: number }>
|
|
66
|
+
/** Unexpired sign-in, verification and reset links mailed to the user, without their token. */
|
|
67
|
+
pendingTokens?: Array<{ kind: TokenKind, expiresAt: number }> | undefined
|
|
68
|
+
/** What `onExportUser` returned for this user. */
|
|
69
|
+
app?: unknown
|
|
48
70
|
exportedAt: number
|
|
49
71
|
}
|
|
50
72
|
|
|
51
|
-
export interface AuthStore<TUser extends AuthUser = AuthUser> {
|
|
73
|
+
export interface AuthStore<TUser extends AuthUser = AuthUser> extends AuthStoreExt {
|
|
52
74
|
getUserById(id: string): TUser | undefined | Promise<TUser | undefined>
|
|
53
75
|
getUserByEmail(email: string): TUser | undefined | Promise<TUser | undefined>
|
|
54
76
|
createUser(user: TUser): TUser | Promise<TUser>
|
|
@@ -70,10 +92,15 @@ export interface AuthStore<TUser extends AuthUser = AuthUser> {
|
|
|
70
92
|
createToken(token: VerificationToken): void | Promise<void>
|
|
71
93
|
consumeToken(tokenHash: string, kind: TokenKind): VerificationToken | undefined | Promise<VerificationToken | undefined>
|
|
72
94
|
|
|
73
|
-
pruneExpired(): void | Promise<void>
|
|
95
|
+
pruneExpired(options?: PruneOptions): void | Promise<void>
|
|
74
96
|
close?(): void | Promise<void>
|
|
75
97
|
}
|
|
76
98
|
|
|
99
|
+
export interface PruneOptions {
|
|
100
|
+
/** Also delete every user whose email was never verified and who was created before this time (ms), with all their data. */
|
|
101
|
+
unverifiedCreatedBefore?: number | undefined
|
|
102
|
+
}
|
|
103
|
+
|
|
77
104
|
export function normalizeEmail(email: string): string {
|
|
78
105
|
return email.trim().toLowerCase()
|
|
79
106
|
}
|
|
@@ -92,6 +119,7 @@ interface MemoryState<TUser extends AuthUser = AuthUser> {
|
|
|
92
119
|
}
|
|
93
120
|
|
|
94
121
|
const inMemoryStores = new WeakSet<object>()
|
|
122
|
+
const syncStores = new WeakSet<object>()
|
|
95
123
|
|
|
96
124
|
/** Marks `store` as one whose data lives in the process alone when `inMemory`, for `requires` to refuse it in production. */
|
|
97
125
|
export function keptInMemory<T extends object>(inMemory: boolean, store: T): T {
|
|
@@ -105,6 +133,80 @@ export function isKeptInMemory(store: object): boolean {
|
|
|
105
133
|
return inMemoryStores.has(store)
|
|
106
134
|
}
|
|
107
135
|
|
|
136
|
+
/** Marks a built-in store whose methods are guaranteed synchronous, enabling lazy session resolution on the very first request. */
|
|
137
|
+
export function markSyncStore<T extends object>(store: T): T {
|
|
138
|
+
syncStores.add(store)
|
|
139
|
+
return store
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Whether `store` is a known built-in synchronous `AuthStore`. */
|
|
143
|
+
export function isKnownSyncStore(store: object): boolean {
|
|
144
|
+
return syncStores.has(store)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function deleteMemoryUser<TUser extends AuthUser>(
|
|
148
|
+
state: MemoryState<TUser>,
|
|
149
|
+
ext: ReturnType<typeof createMemoryStoreExt>,
|
|
150
|
+
userId: string,
|
|
151
|
+
): void {
|
|
152
|
+
const cur = state.users.get(userId)
|
|
153
|
+
state.users.delete(userId)
|
|
154
|
+
if (cur)
|
|
155
|
+
state.usersByEmail.delete(cur.email)
|
|
156
|
+
for (const [k, s] of state.sessions) {
|
|
157
|
+
if (s.userId === userId)
|
|
158
|
+
state.sessions.delete(k)
|
|
159
|
+
}
|
|
160
|
+
for (const [k, a] of state.oauth) {
|
|
161
|
+
if (a.userId === userId)
|
|
162
|
+
state.oauth.delete(k)
|
|
163
|
+
}
|
|
164
|
+
for (const [k, t] of state.tokens) {
|
|
165
|
+
if (t.userId === userId || (cur && t.email === cur.email))
|
|
166
|
+
state.tokens.delete(k)
|
|
167
|
+
}
|
|
168
|
+
ext.deleteUserExt(userId, cur?.email)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function exportMemoryUser<TUser extends AuthUser>(
|
|
172
|
+
state: MemoryState<TUser>,
|
|
173
|
+
ext: ReturnType<typeof createMemoryStoreExt>,
|
|
174
|
+
userId: string,
|
|
175
|
+
): UserExport<TUser> | null {
|
|
176
|
+
const cur = state.users.get(userId)
|
|
177
|
+
if (!cur)
|
|
178
|
+
return null
|
|
179
|
+
const now = Date.now()
|
|
180
|
+
const sessions: AuthSession[] = []
|
|
181
|
+
for (const [k, s] of state.sessions) {
|
|
182
|
+
if (s.expiresAt <= now) {
|
|
183
|
+
state.sessions.delete(k)
|
|
184
|
+
continue
|
|
185
|
+
}
|
|
186
|
+
if (s.userId === userId)
|
|
187
|
+
sessions.push({ ...s })
|
|
188
|
+
}
|
|
189
|
+
sessions.sort((a, b) => b.createdAt - a.createdAt)
|
|
190
|
+
const oauthAccounts: UserExport['oauthAccounts'] = []
|
|
191
|
+
for (const a of state.oauth.values()) {
|
|
192
|
+
if (a.userId === userId)
|
|
193
|
+
oauthAccounts.push({ provider: a.provider, providerAccountId: a.providerAccountId, createdAt: a.createdAt })
|
|
194
|
+
}
|
|
195
|
+
oauthAccounts.sort((a, b) => a.createdAt - b.createdAt)
|
|
196
|
+
const pendingTokens = [...state.tokens.values()]
|
|
197
|
+
.filter(t => t.expiresAt > now && (t.userId === userId || t.email === cur.email))
|
|
198
|
+
.sort((a, b) => a.expiresAt - b.expiresAt)
|
|
199
|
+
.map(t => ({ kind: t.kind, expiresAt: t.expiresAt }))
|
|
200
|
+
return {
|
|
201
|
+
user: toPublicUser(cur),
|
|
202
|
+
sessions,
|
|
203
|
+
oauthAccounts,
|
|
204
|
+
pendingTokens,
|
|
205
|
+
...ext.exportUserExt(userId, cur.email, now),
|
|
206
|
+
exportedAt: now,
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
108
210
|
export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<TUser> {
|
|
109
211
|
const state: MemoryState<TUser> = {
|
|
110
212
|
users: new Map(),
|
|
@@ -113,8 +215,10 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
113
215
|
oauth: new Map(),
|
|
114
216
|
tokens: new Map(),
|
|
115
217
|
}
|
|
218
|
+
const ext = createMemoryStoreExt()
|
|
116
219
|
|
|
117
|
-
return keptInMemory(true, {
|
|
220
|
+
return markSyncStore(keptInMemory(true, {
|
|
221
|
+
...ext.methods,
|
|
118
222
|
getUserById(userId) {
|
|
119
223
|
return state.users.get(userId)
|
|
120
224
|
},
|
|
@@ -142,50 +246,10 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
142
246
|
return next
|
|
143
247
|
},
|
|
144
248
|
deleteUser(userId) {
|
|
145
|
-
|
|
146
|
-
state.users.delete(userId)
|
|
147
|
-
if (cur)
|
|
148
|
-
state.usersByEmail.delete(cur.email)
|
|
149
|
-
for (const [k, s] of state.sessions) {
|
|
150
|
-
if (s.userId === userId)
|
|
151
|
-
state.sessions.delete(k)
|
|
152
|
-
}
|
|
153
|
-
for (const [k, a] of state.oauth) {
|
|
154
|
-
if (a.userId === userId)
|
|
155
|
-
state.oauth.delete(k)
|
|
156
|
-
}
|
|
157
|
-
for (const [k, t] of state.tokens) {
|
|
158
|
-
if (t.userId === userId || (cur && t.email === cur.email))
|
|
159
|
-
state.tokens.delete(k)
|
|
160
|
-
}
|
|
249
|
+
deleteMemoryUser(state, ext, userId)
|
|
161
250
|
},
|
|
162
251
|
exportUser(userId) {
|
|
163
|
-
|
|
164
|
-
if (!cur)
|
|
165
|
-
return null
|
|
166
|
-
const now = Date.now()
|
|
167
|
-
const sessions: AuthSession[] = []
|
|
168
|
-
for (const [k, s] of state.sessions) {
|
|
169
|
-
if (s.expiresAt <= now) {
|
|
170
|
-
state.sessions.delete(k)
|
|
171
|
-
continue
|
|
172
|
-
}
|
|
173
|
-
if (s.userId === userId)
|
|
174
|
-
sessions.push({ ...s })
|
|
175
|
-
}
|
|
176
|
-
sessions.sort((a, b) => b.createdAt - a.createdAt)
|
|
177
|
-
const oauthAccounts: UserExport['oauthAccounts'] = []
|
|
178
|
-
for (const a of state.oauth.values()) {
|
|
179
|
-
if (a.userId === userId)
|
|
180
|
-
oauthAccounts.push({ provider: a.provider, providerAccountId: a.providerAccountId, createdAt: a.createdAt })
|
|
181
|
-
}
|
|
182
|
-
oauthAccounts.sort((a, b) => a.createdAt - b.createdAt)
|
|
183
|
-
return {
|
|
184
|
-
user: toPublicUser(cur),
|
|
185
|
-
sessions,
|
|
186
|
-
oauthAccounts,
|
|
187
|
-
exportedAt: now,
|
|
188
|
-
}
|
|
252
|
+
return exportMemoryUser(state, ext, userId)
|
|
189
253
|
},
|
|
190
254
|
getSession(tokenHash) {
|
|
191
255
|
const s = state.sessions.get(tokenHash)
|
|
@@ -252,7 +316,7 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
252
316
|
return undefined
|
|
253
317
|
return tok
|
|
254
318
|
},
|
|
255
|
-
pruneExpired() {
|
|
319
|
+
pruneExpired(options) {
|
|
256
320
|
const now = Date.now()
|
|
257
321
|
for (const [k, s] of state.sessions) {
|
|
258
322
|
if (s.expiresAt <= now)
|
|
@@ -262,6 +326,14 @@ export function memoryAuthStore<TUser extends AuthUser = AuthUser>(): AuthStore<
|
|
|
262
326
|
if (t.expiresAt <= now)
|
|
263
327
|
state.tokens.delete(k)
|
|
264
328
|
}
|
|
329
|
+
ext.pruneExpiredExt(now)
|
|
330
|
+
const cutoff = options?.unverifiedCreatedBefore
|
|
331
|
+
if (cutoff === undefined)
|
|
332
|
+
return
|
|
333
|
+
for (const user of [...state.users.values()]) {
|
|
334
|
+
if (!user.emailVerified && user.createdAt < cutoff)
|
|
335
|
+
deleteMemoryUser(state, ext, user.id)
|
|
336
|
+
}
|
|
265
337
|
},
|
|
266
|
-
})
|
|
338
|
+
}))
|
|
267
339
|
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// HTTP routes for TOTP second factor setup, confirmation, verification (2FA), and disabling.
|
|
2
|
+
// Works both with JSON clients and with zero-JS HTML forms.
|
|
3
|
+
|
|
4
|
+
import type { RequestContext } from 'prunelle/server'
|
|
5
|
+
import type { AuthFormMessages } from './form-messages'
|
|
6
|
+
import type { AuthRouteRegistrar } from './http'
|
|
7
|
+
import type { SessionManager } from './session'
|
|
8
|
+
import type { AuthStore, AuthUser } from './store'
|
|
9
|
+
import type { TotpManager } from './totp'
|
|
10
|
+
import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
11
|
+
import { readFormMessage } from './form-messages'
|
|
12
|
+
import { escapeHtml, fail, respondAuthError } from './http'
|
|
13
|
+
import { toPublicUser } from './store'
|
|
14
|
+
|
|
15
|
+
export interface TotpRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
16
|
+
authRoute: AuthRouteRegistrar
|
|
17
|
+
store: AuthStore<TUser>
|
|
18
|
+
sessions: SessionManager<TUser>
|
|
19
|
+
totp: TotpManager
|
|
20
|
+
basePath: string
|
|
21
|
+
defaultRedirect: string
|
|
22
|
+
messages: AuthFormMessages
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function renderHtmlPage(title: string, bodyHtml: string): Response {
|
|
26
|
+
const html = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><meta name="referrer" content="same-origin"><title>${escapeHtml(title)}</title></head><body><main>${bodyHtml}</main></body></html>`
|
|
27
|
+
return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function registerTotpRoutes<TUser extends AuthUser = AuthUser>(deps: TotpRoutesDeps<TUser>): void {
|
|
31
|
+
const { authRoute, store, sessions, totp, basePath, defaultRedirect, messages } = deps
|
|
32
|
+
|
|
33
|
+
authRoute('POST', '/totp/setup', { limit: 'totp-setup', readBody: true }, async (ctx, body) => {
|
|
34
|
+
const resolved = await sessions.resolve(ctx)
|
|
35
|
+
if (!resolved)
|
|
36
|
+
return fail(ctx, 401, 'Authentication required')
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
const setup = await totp.setupTotp(resolved.user.id, body.issuer ? { issuer: body.issuer } : undefined)
|
|
40
|
+
if (wantsJson(ctx.request))
|
|
41
|
+
return ctx.json({ ok: true, secret: setup.secret, otpauthUrl: setup.otpauthUrl }, { status: 200 })
|
|
42
|
+
const redirect = safeRedirect(body.redirect ?? body.next, '')
|
|
43
|
+
const redirectInput = redirect ? `<input type="hidden" name="redirect" value="${escapeHtml(redirect)}">` : ''
|
|
44
|
+
return renderHtmlPage(
|
|
45
|
+
'Set up two-factor authentication',
|
|
46
|
+
`<h1>Set up two-factor authentication</h1><p>Secret: <code>${escapeHtml(setup.secret)}</code></p><p>URI: <code>${escapeHtml(setup.otpauthUrl)}</code></p><form method="post" action="${escapeHtml(`${basePath}/totp/confirm`)}">${redirectInput}<label>Verification code <input type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required></label><button type="submit">Enable 2FA</button></form>`,
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
const msg = err instanceof Error ? err.message : 'Unable to start TOTP setup'
|
|
51
|
+
const status = msg.includes('already enabled') ? 409 : 400
|
|
52
|
+
return fail(ctx, status, msg)
|
|
53
|
+
}
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
authRoute('POST', '/totp/confirm', { limit: 'totp-confirm', readBody: true }, async (ctx, body) => {
|
|
57
|
+
const resolved = await sessions.resolve(ctx)
|
|
58
|
+
if (!resolved)
|
|
59
|
+
return fail(ctx, 401, 'Authentication required')
|
|
60
|
+
|
|
61
|
+
const code = (body.code ?? '').trim()
|
|
62
|
+
if (!code)
|
|
63
|
+
return fail(ctx, 400, 'Verification code is required')
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
const result = await totp.confirmTotp(resolved.user.id, code)
|
|
67
|
+
if (wantsJson(ctx.request))
|
|
68
|
+
return ctx.json({ ok: true, enabled: true, recoveryCodes: result.recoveryCodes }, { status: 200 })
|
|
69
|
+
if (body.redirect || body.next)
|
|
70
|
+
return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
|
|
71
|
+
const list = result.recoveryCodes.map(c => `<li><code>${escapeHtml(c)}</code></li>`).join('')
|
|
72
|
+
return renderHtmlPage(
|
|
73
|
+
'Two-factor authentication enabled',
|
|
74
|
+
`<h1>Two-factor authentication enabled</h1><p>Save these single-use recovery codes in a safe place:</p><ul>${list}</ul>`,
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
const msg = err instanceof Error ? err.message : 'Invalid verification code'
|
|
79
|
+
const status = msg.includes('already enabled') ? 409 : 400
|
|
80
|
+
return fail(ctx, status, msg)
|
|
81
|
+
}
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
authRoute('GET', '/totp/verify', { limit: 'totp-verify' }, (ctx: RequestContext) => {
|
|
85
|
+
const pending = totp.readPendingCookie(ctx)
|
|
86
|
+
if (!pending)
|
|
87
|
+
return fail(ctx, 401, 'Two-factor session expired or invalid')
|
|
88
|
+
const redirect = safeRedirect(ctx.url.searchParams.get('next') ?? ctx.url.searchParams.get('redirect') ?? pending.redirect, defaultRedirect)
|
|
89
|
+
const message = readFormMessage(messages, ctx.url)
|
|
90
|
+
const error = message?.form === 'totp' ? message.text : undefined
|
|
91
|
+
const described = error !== undefined ? ' aria-invalid="true" aria-describedby="code-error"' : ''
|
|
92
|
+
return renderHtmlPage(
|
|
93
|
+
'Two-factor verification',
|
|
94
|
+
`<h1>Two-factor verification</h1><form method="post" action="${escapeHtml(`${basePath}/totp/verify`)}"><input type="hidden" name="redirect" value="${escapeHtml(redirect)}"><label>Authentication or recovery code <input type="text" name="code" autocomplete="one-time-code" required${described}></label>${error !== undefined ? `<p id="code-error" role="alert">${escapeHtml(error)}</p>` : ''}<button type="submit">Verify</button></form>`,
|
|
95
|
+
)
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
authRoute('POST', '/totp/verify', { limit: 'totp-verify', readBody: true }, async (ctx, body) => {
|
|
99
|
+
const pending = totp.readPendingCookie(ctx)
|
|
100
|
+
if (!pending)
|
|
101
|
+
return fail(ctx, 401, 'Two-factor session expired or invalid')
|
|
102
|
+
|
|
103
|
+
const code = (body.code ?? '').trim()
|
|
104
|
+
if (!code)
|
|
105
|
+
return respondAuthError(ctx, 400, messages['totp.code-required'])
|
|
106
|
+
|
|
107
|
+
const check = await totp.verifyTotp(pending.userId, code)
|
|
108
|
+
if (!check.valid)
|
|
109
|
+
return respondAuthError(ctx, 401, messages['totp.invalid-code'])
|
|
110
|
+
|
|
111
|
+
const userRecord = await sessions.observeAsync(store.getUserById(pending.userId))
|
|
112
|
+
if (!userRecord) {
|
|
113
|
+
totp.clearPendingCookie(ctx)
|
|
114
|
+
return fail(ctx, 401, 'Unable to resolve user account')
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
totp.clearPendingCookie(ctx)
|
|
118
|
+
const pub = toPublicUser(userRecord)
|
|
119
|
+
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
120
|
+
const redirectTarget = safeRedirect(body.redirect ?? body.next ?? pending.redirect, defaultRedirect)
|
|
121
|
+
|
|
122
|
+
if (wantsJson(ctx.request))
|
|
123
|
+
return ctx.json({ ok: true, user: pub, usedRecoveryCode: check.method === 'recovery' }, { status: 200 })
|
|
124
|
+
return ctx.redirect(redirectTarget, 303)
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
authRoute('POST', '/totp/disable', { limit: 'totp-disable', readBody: true }, async (ctx, body) => {
|
|
128
|
+
const resolved = await sessions.resolve(ctx)
|
|
129
|
+
if (!resolved)
|
|
130
|
+
return fail(ctx, 401, 'Authentication required')
|
|
131
|
+
|
|
132
|
+
const code = (body.code ?? '').trim()
|
|
133
|
+
if (!code)
|
|
134
|
+
return fail(ctx, 400, 'Verification code is required')
|
|
135
|
+
|
|
136
|
+
const disabled = await totp.disableTotp(resolved.user.id, code)
|
|
137
|
+
if (!disabled)
|
|
138
|
+
return fail(ctx, 401, 'Invalid verification code')
|
|
139
|
+
|
|
140
|
+
if (wantsJson(ctx.request))
|
|
141
|
+
return ctx.json({ ok: true, enabled: false }, { status: 200 })
|
|
142
|
+
return ctx.redirect(safeRedirect(body.redirect ?? body.next, defaultRedirect), 303)
|
|
143
|
+
})
|
|
144
|
+
}
|