proper productionize project
This commit is contained in:
@@ -0,0 +1,358 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import type { FormEvent, ReactNode } from 'react'
|
||||
import {
|
||||
api,
|
||||
copyToClipboard,
|
||||
errorMessage,
|
||||
json,
|
||||
normalizeEnrollment,
|
||||
normalizeRecoveryCodes,
|
||||
} from './api'
|
||||
import { PwaControls, authRoute, usePwaUpdateBlocker } from './pwa'
|
||||
import type { TotpEnrollment } from './types'
|
||||
|
||||
function AuthShell({ eyebrow, title, children, footer }: {
|
||||
eyebrow: string
|
||||
title: string
|
||||
children: ReactNode
|
||||
footer?: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<main className="auth-page">
|
||||
<section className="auth-card jade-panel">
|
||||
<PwaControls />
|
||||
<div className="auth-mark" aria-hidden="true">星</div>
|
||||
<p className="eyebrow">{eyebrow}</p>
|
||||
<h1>{title}</h1>
|
||||
{children}
|
||||
{footer && <footer>{footer}</footer>}
|
||||
</section>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
function TotpQr({ enrollment }: { enrollment: TotpEnrollment }) {
|
||||
const source = useMemo(() => {
|
||||
if (enrollment.qrDataUrl) return enrollment.qrDataUrl
|
||||
if (enrollment.qrSvg) return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(enrollment.qrSvg)}`
|
||||
return undefined
|
||||
}, [enrollment.qrDataUrl, enrollment.qrSvg])
|
||||
|
||||
return (
|
||||
<div className="totp-enrollment">
|
||||
<div className="totp-qr">
|
||||
{source
|
||||
? <img src={source} alt="TOTP 验证器绑定二维码" />
|
||||
: <span>二维码暂不可用,请使用右侧密钥手工添加。</span>}
|
||||
</div>
|
||||
<div className="totp-copy">
|
||||
<h2>绑定动态验证器</h2>
|
||||
<ol>
|
||||
<li>使用 1Password、Aegis、Microsoft Authenticator 等应用扫描二维码。</li>
|
||||
<li>若无法扫码,选择“输入设置密钥”。</li>
|
||||
<li>输入应用中出现的 6 位动态码完成绑定。</li>
|
||||
</ol>
|
||||
<label>
|
||||
手工设置密钥
|
||||
<div className="secret-row">
|
||||
<code>{enrollment.manualKey || '未提供'}</code>
|
||||
{enrollment.manualKey && (
|
||||
<button type="button" className="text-button" onClick={() => void copyToClipboard(enrollment.manualKey)}>
|
||||
复制
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RecoveryCodes({ codes, onContinue }: { codes: string[]; onContinue: () => void }) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const text = codes.join('\n')
|
||||
const download = () => {
|
||||
const blob = new Blob([
|
||||
'洛星瓷直播组件恢复码\n',
|
||||
'每个恢复码只能使用一次,请离线妥善保存。\n\n',
|
||||
text,
|
||||
'\n',
|
||||
], { type: 'text/plain;charset=utf-8' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = 'luoxingci-recovery-codes.txt'
|
||||
anchor.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthShell eyebrow="安全设置完成" title="保存账户恢复码">
|
||||
<p className="auth-lead">手机丢失或验证器不可用时,可用恢复码登录。服务端不会再次显示这些明文恢复码。</p>
|
||||
{codes.length > 0
|
||||
? <div className="recovery-grid">{codes.map(code => <code key={code}>{code}</code>)}</div>
|
||||
: <div className="notice warning">服务端没有返回恢复码,请先联系管理员确认恢复策略。</div>}
|
||||
<div className="form-actions">
|
||||
{codes.length > 0 && (
|
||||
<>
|
||||
<button type="button" className="secondary" onClick={() => void copyToClipboard(text).then(setCopied)}>
|
||||
{copied ? '已复制' : '复制全部'}
|
||||
</button>
|
||||
<button type="button" className="secondary" onClick={download}>下载文本</button>
|
||||
</>
|
||||
)}
|
||||
<button type="button" onClick={onContinue}>我已妥善保存</button>
|
||||
</div>
|
||||
</AuthShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function LoginPage({ onAuthenticated, setupRequired }: {
|
||||
onAuthenticated: () => Promise<void>
|
||||
setupRequired: boolean
|
||||
}) {
|
||||
const [username, setUsername] = useState('')
|
||||
const [totpCode, setTotpCode] = useState('')
|
||||
const [useRecoveryCode, setUseRecoveryCode] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
usePwaUpdateBlocker(
|
||||
'login-form',
|
||||
'完成或清空正在填写的登录表单',
|
||||
busy || Boolean(username || totpCode),
|
||||
)
|
||||
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
await api('/api/v1/auth/login', json('POST', { username: username.trim(), code: totpCode }))
|
||||
setTotpCode('')
|
||||
await onAuthenticated()
|
||||
location.assign('/control/')
|
||||
} catch (reason) {
|
||||
setError(errorMessage(reason, '用户名或动态验证码不正确'))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthShell
|
||||
eyebrow="洛星瓷直播组件"
|
||||
title="回到你的云台"
|
||||
footer={(
|
||||
<p>
|
||||
{setupRequired
|
||||
? <>首次部署?<a href={authRoute('setup')}>创建系统管理员</a></>
|
||||
: <>持有邀请码?<a href={authRoute('register')}>注册新账户</a></>}
|
||||
</p>
|
||||
)}
|
||||
>
|
||||
<p className="auth-lead">这是无密码账户。输入用户名与验证器中的动态验证码即可登录。</p>
|
||||
<form className="stack-form" onSubmit={submit}>
|
||||
<label>
|
||||
用户名
|
||||
<input
|
||||
autoFocus
|
||||
required
|
||||
autoComplete="username"
|
||||
value={username}
|
||||
onChange={event => setUsername(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{useRecoveryCode ? '账户恢复码' : '6 位动态验证码'}
|
||||
<input
|
||||
required
|
||||
className={useRecoveryCode ? 'recovery-input' : 'otp-input'}
|
||||
inputMode={useRecoveryCode ? 'text' : 'numeric'}
|
||||
autoComplete={useRecoveryCode ? 'off' : 'one-time-code'}
|
||||
pattern={useRecoveryCode ? undefined : '[0-9]{6}'}
|
||||
maxLength={useRecoveryCode ? 64 : 6}
|
||||
placeholder={useRecoveryCode ? '输入一个尚未使用的恢复码' : '000000'}
|
||||
value={totpCode}
|
||||
onChange={event => setTotpCode(useRecoveryCode
|
||||
? event.target.value.trimStart().slice(0, 64)
|
||||
: event.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-link"
|
||||
onClick={() => {
|
||||
setUseRecoveryCode(current => !current)
|
||||
setTotpCode('')
|
||||
}}
|
||||
>
|
||||
{useRecoveryCode ? '改用动态验证码' : '验证器不可用?改用恢复码'}
|
||||
</button>
|
||||
{error && <div className="notice error" role="alert">{error}</div>}
|
||||
<button disabled={busy}>{busy ? '正在验证…' : '安全登录'}</button>
|
||||
</form>
|
||||
</AuthShell>
|
||||
)
|
||||
}
|
||||
|
||||
export function EnrollmentPage({ mode, onAuthenticated }: {
|
||||
mode: 'setup' | 'register'
|
||||
onAuthenticated: () => Promise<void>
|
||||
}) {
|
||||
const inviteFromFragment = new URLSearchParams(location.hash.slice(1)).get('invite') ?? ''
|
||||
const [inviteCode, setInviteCode] = useState(inviteFromFragment)
|
||||
const [username, setUsername] = useState('')
|
||||
const [bootstrapPassword, setBootstrapPassword] = useState('')
|
||||
const [enrollment, setEnrollment] = useState<TotpEnrollment>()
|
||||
const [totpCode, setTotpCode] = useState('')
|
||||
const [recoveryCodes, setRecoveryCodes] = useState<string[]>()
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const isSetup = mode === 'setup'
|
||||
usePwaUpdateBlocker(
|
||||
'totp-enrollment',
|
||||
enrollment || recoveryCodes
|
||||
? '完成 TOTP 绑定并保存一次性恢复码'
|
||||
: '完成或清空正在填写的注册表单',
|
||||
busy || Boolean(inviteCode || username || bootstrapPassword || totpCode || enrollment || recoveryCodes),
|
||||
)
|
||||
|
||||
const start = async (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const payload = await api<unknown>(
|
||||
`/api/v1/auth/${isSetup ? 'setup' : 'register'}/start`,
|
||||
json('POST', {
|
||||
...(isSetup ? {} : { inviteCode: inviteCode.trim() }),
|
||||
username: username.trim(),
|
||||
...(isSetup ? { bootstrapPassword } : {}),
|
||||
}),
|
||||
)
|
||||
const next = normalizeEnrollment(payload)
|
||||
if (!next.enrollmentToken) throw new Error('服务端未返回注册流程标识')
|
||||
setEnrollment(next)
|
||||
setBootstrapPassword('')
|
||||
if (!isSetup) {
|
||||
setInviteCode('')
|
||||
history.replaceState(null, '', authRoute('register'))
|
||||
}
|
||||
} catch (reason) {
|
||||
setError(errorMessage(reason, '无法开始安全注册流程'))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const confirm = async (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
if (!enrollment) return
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const payload = await api<unknown>(
|
||||
`/api/v1/auth/${isSetup ? 'setup' : 'register'}/confirm`,
|
||||
json('POST', { enrollmentToken: enrollment.enrollmentToken, code: totpCode }),
|
||||
)
|
||||
setTotpCode('')
|
||||
// Drop QR/manual-key material from React state as soon as enrollment is
|
||||
// committed; only the one-time recovery codes remain on screen.
|
||||
setEnrollment(undefined)
|
||||
setRecoveryCodes(normalizeRecoveryCodes(payload))
|
||||
} catch (reason) {
|
||||
setError(errorMessage(reason, '动态验证码无效或注册流程已过期'))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const finish = async () => {
|
||||
await onAuthenticated()
|
||||
location.assign('/control/')
|
||||
}
|
||||
|
||||
if (recoveryCodes) return <RecoveryCodes codes={recoveryCodes} onContinue={() => void finish()} />
|
||||
|
||||
if (enrollment) {
|
||||
return (
|
||||
<AuthShell eyebrow={isSetup ? '系统初始化 · 第二步' : '邀请码注册 · 第二步'} title="强制绑定 TOTP">
|
||||
<TotpQr enrollment={enrollment} />
|
||||
<form className="stack-form compact-form" onSubmit={confirm}>
|
||||
<label>
|
||||
验证器中的 6 位动态码
|
||||
<input
|
||||
required
|
||||
autoFocus
|
||||
className="otp-input"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9]{6}"
|
||||
maxLength={6}
|
||||
placeholder="000000"
|
||||
value={totpCode}
|
||||
onChange={event => setTotpCode(event.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
/>
|
||||
</label>
|
||||
{error && <div className="notice error" role="alert">{error}</div>}
|
||||
<button disabled={busy || totpCode.length !== 6}>{busy ? '正在确认…' : '确认绑定并创建账户'}</button>
|
||||
</form>
|
||||
</AuthShell>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthShell
|
||||
eyebrow={isSetup ? '仅首次部署可用' : '仅限受邀用户'}
|
||||
title={isSetup ? '创建系统管理员' : '创建你的账户'}
|
||||
footer={<p>已有账户?<a href={authRoute('login')}>返回登录</a></p>}
|
||||
>
|
||||
<p className="auth-lead">
|
||||
{isSetup
|
||||
? '首位账户将拥有邀请码管理权限。旧管理员口令只授权这一次初始化,不会成为账户密码。'
|
||||
: '邀请码只用于注册;这是无密码账户,创建后每次登录都必须验证 TOTP。'}
|
||||
</p>
|
||||
<form className="stack-form" onSubmit={start}>
|
||||
{!isSetup && (
|
||||
<label>
|
||||
邀请码
|
||||
<input
|
||||
required
|
||||
autoFocus={!inviteFromFragment}
|
||||
autoComplete="off"
|
||||
value={inviteCode}
|
||||
onChange={event => setInviteCode(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
用户名
|
||||
<input
|
||||
required
|
||||
autoFocus={isSetup || Boolean(inviteFromFragment)}
|
||||
autoComplete="username"
|
||||
minLength={3}
|
||||
maxLength={32}
|
||||
value={username}
|
||||
onChange={event => setUsername(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{isSetup && (
|
||||
<label>
|
||||
一次性初始化口令
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={bootstrapPassword}
|
||||
onChange={event => setBootstrapPassword(event.target.value)}
|
||||
/>
|
||||
<small>填写部署配置中的旧管理员口令;它仅验证初始化权限,不会保存为用户密码。</small>
|
||||
</label>
|
||||
)}
|
||||
{error && <div className="notice error" role="alert">{error}</div>}
|
||||
<button disabled={busy}>{busy ? '正在准备 TOTP…' : '下一步:绑定验证器'}</button>
|
||||
</form>
|
||||
</AuthShell>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user