From e05c930a9d557f749b55c0f6fc60dad0822ecbee Mon Sep 17 00:00:00 2001 From: xhgit Date: Mon, 16 Nov 2026 07:06:40 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=AF=86=E7=A0=81=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E3=80=81=E4=BC=9A=E8=AF=9D=E9=80=80=E5=87=BA=E5=92=8C?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E8=AE=B0=E5=BD=95=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/api.md | 4 + docs/database.md | 1 + server/internal/account/settings.go | 110 ++++++++++++++++++ server/internal/account/store.go | 17 ++- .../internal/database/015_login_history.sql | 11 ++ server/internal/database/database.go | 5 +- server/internal/httpapi/account_settings.go | 92 +++++++++++++++ server/internal/httpapi/api.go | 4 + tests/account-security.test.mjs | 77 ++++++++++++ 9 files changed, 319 insertions(+), 2 deletions(-) create mode 100644 server/internal/account/settings.go create mode 100644 server/internal/database/015_login_history.sql create mode 100644 server/internal/httpapi/account_settings.go create mode 100644 tests/account-security.test.mjs diff --git a/docs/api.md b/docs/api.md index 351b7ce..e6d6698 100644 --- a/docs/api.md +++ b/docs/api.md @@ -9,8 +9,12 @@ | POST | /api/v1/auth/register | 接收 username、password、deviceName、platform、publicKey、challenge、signature,返回 201 和 token、user、device | | POST | /api/v1/auth/login | 同上,返回 200 | | POST | /api/v1/auth/logout | 使当前会话失效,返回 204 | +| POST | /api/v1/auth/password | currentPassword、newPassword,校验当前密码后修改,结束全部会话,返回 204 | +| POST | /api/v1/auth/logout-others | 结束当前账号除调用令牌以外的全部会话,返回 204 | +| GET | /api/v1/auth/history | 最近 50 次成功登录记录,包含 id、deviceName、platform、createdAt、currentDevice | | GET | /api/v1/me | 返回账号和当前设备 | | GET | /api/v1/devices | 返回当前账号的设备列表,signedIn 表示有未过期会话,lastActiveAt 来自登录与 WebSocket 心跳 | +| POST | /api/v1/devices/{id} | name,修改当前账号有效设备名称,返回 204,后续登录保留手动名称 | | DELETE | /api/v1/devices/{id} | 撤销指定设备和其全部会话,返回 204 | | POST | /api/v1/realtime/ticket | 返回 30 秒单次 WebSocket 票据 | | GET | /api/v1/realtime | 通过子协议 xhchat.v1 和 ticket.票据升级,服务器选择 xhchat.v1,连接建立后发送 ready 事件 | diff --git a/docs/database.md b/docs/database.md index 39c3b74..d0bf572 100644 --- a/docs/database.md +++ b/docs/database.md @@ -7,6 +7,7 @@ | sessions | 高熵令牌的 SHA-256 摘要为主键,关联设备,包含到期时间 | | contact_relationships、contact_blocks、contact_preferences | 关系按账号对去重,拉黑有方向,备注、分组、免打扰和置顶按拥有者授权 | | device_contact_seen | 每个接收设备和发送设备之间的已查看游标,只向前更新 | +| login_history | 每个账号最近 50 次成功登录的设备名称、平台和时间 | | conversations、memberships | 会话与成员关系,记录角色和生效世代 | | devices、device_key_packages | 公开设备凭据及签名的一次性密钥包,事务领取,撤销后停止发放 | | device_envelopes | 二进制协议封包、投递游标和目标设备,按发送设备、接收设备和客户端消息 ID 幂等 | diff --git a/server/internal/account/settings.go b/server/internal/account/settings.go new file mode 100644 index 0000000..9d6fc70 --- /dev/null +++ b/server/internal/account/settings.go @@ -0,0 +1,110 @@ +package account + +import ( + "context" + "errors" + "time" + + "github.com/jackc/pgx/v5" +) + +var ErrPassword = errors.New("incorrect current password") + +func lockSession(ctx context.Context, tx pgx.Tx, user, token string) error { + if _, err := tx.Exec(ctx, "SELECT id FROM users WHERE id=$1 FOR UPDATE", user); err != nil { + return err + } + digest, err := SessionDigest(token) + if err != nil { + return err + } + var device string + err = tx.QueryRow(ctx, `SELECT d.id FROM sessions s JOIN devices d ON d.id=s.device_id + WHERE s.token_hash=$1 AND d.user_id=$2 AND d.revoked_at IS NULL AND s.expires_at>now() + FOR UPDATE OF d,s`, digest[:], user).Scan(&device) + if errors.Is(err, pgx.ErrNoRows) { + return ErrCredentials + } + return err +} + +func (s *Store) ChangePassword(ctx context.Context, user, token, current, next string) error { + var previousHash string + if err := s.db.QueryRow(ctx, "SELECT password_hash FROM users WHERE id=$1", user).Scan(&previousHash); err != nil { + return err + } + if !VerifyPassword(current, previousHash) { + return ErrPassword + } + nextHash := PasswordHash(next) + tx, err := s.db.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + if err = lockSession(ctx, tx, user, token); err != nil { + return err + } + tag, err := tx.Exec(ctx, "UPDATE users SET password_hash=$1 WHERE id=$2 AND password_hash=$3", nextHash, user, previousHash) + if err != nil { + return err + } + if tag.RowsAffected() != 1 { + return ErrPassword + } + if _, err = tx.Exec(ctx, "DELETE FROM sessions WHERE device_id IN (SELECT id FROM devices WHERE user_id=$1)", user); err != nil { + return err + } + return tx.Commit(ctx) +} + +func (s *Store) LogoutOthers(ctx context.Context, user, token string) error { + tx, err := s.db.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + if err = lockSession(ctx, tx, user, token); err != nil { + return err + } + digest, _ := SessionDigest(token) + if _, err = tx.Exec(ctx, `DELETE FROM sessions WHERE token_hash<>$2 AND device_id IN + (SELECT id FROM devices WHERE user_id=$1)`, user, digest[:]); err != nil { + return err + } + return tx.Commit(ctx) +} + +func (s *Store) RenameDevice(ctx context.Context, user, device, name string) error { + tag, err := s.db.Exec(ctx, "UPDATE devices SET name=$3,name_custom=true WHERE user_id=$1 AND id=$2 AND revoked_at IS NULL", user, device, name) + if err == nil && tag.RowsAffected() != 1 { + return pgx.ErrNoRows + } + return err +} + +type LoginRecord struct { + ID string `json:"id"` + DeviceName string `json:"deviceName"` + Platform string `json:"platform"` + CreatedAt time.Time `json:"createdAt"` + CurrentDevice bool `json:"currentDevice"` +} + +func (s *Store) LoginHistory(ctx context.Context, user, device string) ([]LoginRecord, error) { + rows, err := s.db.Query(ctx, `SELECT id::text,device_name,platform,created_at,device_id=$2 + FROM login_history WHERE user_id=$1 ORDER BY id DESC LIMIT 50`, user, device) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]LoginRecord, 0) + for rows.Next() { + var item LoginRecord + if err := rows.Scan(&item.ID, &item.DeviceName, &item.Platform, &item.CreatedAt, &item.CurrentDevice); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} diff --git a/server/internal/account/store.go b/server/internal/account/store.go index 05814f4..1600e13 100644 --- a/server/internal/account/store.go +++ b/server/internal/account/store.go @@ -87,12 +87,19 @@ func (s *Store) Open(ctx context.Context, register bool, username, password, nam return Auth{}, err } } + var currentHash string + if err = tx.QueryRow(ctx, "SELECT password_hash FROM users WHERE id=$1 FOR UPDATE", result.User.ID).Scan(¤tHash); err != nil { + return Auth{}, err + } + if currentHash != hash { + return Auth{}, ErrCredentials + } row := tx.QueryRow(ctx, ` INSERT INTO devices(user_id, public_key, name, platform) VALUES ($1,$2,$3,$4) ON CONFLICT (user_id, public_key) DO UPDATE - SET last_active_at=now(), name=EXCLUDED.name + SET last_active_at=now(), name=CASE WHEN devices.name_custom THEN devices.name ELSE EXCLUDED.name END WHERE devices.revoked_at IS NULL AND devices.platform=EXCLUDED.platform RETURNING id, name, platform, created_at, last_active_at, revoked_at `, result.User.ID, publicKey, name, platform) @@ -107,6 +114,14 @@ func (s *Store) Open(ctx context.Context, register bool, username, password, nam if _, err = tx.Exec(ctx, "INSERT INTO sessions VALUES ($1,$2,$3)", digest[:], result.Device.ID, time.Now().Add(s.ttl)); err != nil { return Auth{}, err } + if _, err = tx.Exec(ctx, `INSERT INTO login_history(user_id,device_id,device_name,platform) VALUES ($1,$2,$3,$4)`, + result.User.ID, result.Device.ID, result.Device.Name, result.Device.Platform); err != nil { + return Auth{}, err + } + if _, err = tx.Exec(ctx, `DELETE FROM login_history WHERE user_id=$1 AND id NOT IN + (SELECT id FROM login_history WHERE user_id=$1 ORDER BY id DESC LIMIT 50)`, result.User.ID); err != nil { + return Auth{}, err + } result.Device.SignedIn = true return result, tx.Commit(ctx) } diff --git a/server/internal/database/015_login_history.sql b/server/internal/database/015_login_history.sql new file mode 100644 index 0000000..475c161 --- /dev/null +++ b/server/internal/database/015_login_history.sql @@ -0,0 +1,11 @@ +ALTER TABLE devices ADD COLUMN name_custom boolean NOT NULL DEFAULT false; + +CREATE TABLE login_history ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + device_id uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE, + device_name text NOT NULL, + platform text NOT NULL CHECK (platform IN ('web','windows')), + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX login_history_user ON login_history(user_id,id DESC); diff --git a/server/internal/database/database.go b/server/internal/database/database.go index f821d6e..4ec7aa3 100644 --- a/server/internal/database/database.go +++ b/server/internal/database/database.go @@ -49,6 +49,9 @@ var contactMuteMigration string //go:embed 014_private_conversations.sql var privateConversationsMigration string +//go:embed 015_login_history.sql +var loginHistoryMigration string + func Migrate(ctx context.Context, pool *pgxpool.Pool) error { tx, err := pool.Begin(ctx) if err != nil { @@ -64,7 +67,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error { for index, migration := range []string{ identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration, attachmentsMigration, groupsMigration, groupTransportMigration, groupAttachmentsMigration, groupPreferencesMigration, - groupSeenMigration, groupInviteLinkMigration, contactMuteMigration, privateConversationsMigration, + groupSeenMigration, groupInviteLinkMigration, contactMuteMigration, privateConversationsMigration, loginHistoryMigration, } { version := index + 1 var applied bool diff --git a/server/internal/httpapi/account_settings.go b/server/internal/httpapi/account_settings.go new file mode 100644 index 0000000..5f9fc85 --- /dev/null +++ b/server/internal/httpapi/account_settings.go @@ -0,0 +1,92 @@ +package httpapi + +import ( + "errors" + "net/http" + "strings" + "unicode" + "unicode/utf8" + + "github.com/jackc/pgx/v5" + "xhchat/server/internal/account" +) + +func (a *API) changePassword(w http.ResponseWriter, r *http.Request, token string, identity account.Identity) { + var input struct { + CurrentPassword string `json:"currentPassword"` + NewPassword string `json:"newPassword"` + } + if !parse(w, r, &input) { + return + } + if len(input.CurrentPassword) > 256 || input.CurrentPassword == "" || len(input.NewPassword) > 256 || utf8.RuneCountInString(input.NewPassword) < 12 { + problem(w, 400, "invalid_password", "新密码须至少 12 个字符且最多 256 字节") + return + } + if !a.limit(w, r, "change-password:"+identity.User.ID, 6) { + return + } + select { + case a.hashSlots <- struct{}{}: + defer func() { <-a.hashSlots }() + default: + problem(w, 429, "busy", "密码服务繁忙,请稍后重试") + return + } + err := a.accounts.ChangePassword(r.Context(), identity.User.ID, token, input.CurrentPassword, input.NewPassword) + if errors.Is(err, account.ErrPassword) { + problem(w, 403, "incorrect_password", "当前密码不正确") + return + } + accountSettingResult(w, err) +} + +func accountSettingResult(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, account.ErrCredentials): + problem(w, 401, "unauthorized", "登录会话已失效") + case errors.Is(err, pgx.ErrNoRows): + problem(w, 404, "device_not_found", "找不到有效设备") + case err != nil: + unavailable(w, err) + default: + w.WriteHeader(204) + } +} + +func (a *API) logoutOthers(w http.ResponseWriter, r *http.Request, token string, identity account.Identity) { + if !a.limit(w, r, "logout-others:"+identity.User.ID, 12) { + return + } + accountSettingResult(w, a.accounts.LogoutOthers(r.Context(), identity.User.ID, token)) +} + +func (a *API) renameDevice(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) { + var input struct { + Name string `json:"name"` + } + if !parse(w, r, &input) { + return + } + input.Name = strings.TrimSpace(input.Name) + if !uuidPattern.MatchString(r.PathValue("id")) || input.Name == "" || utf8.RuneCountInString(input.Name) > 64 || strings.ContainsFunc(input.Name, unicode.IsControl) { + problem(w, 400, "invalid_device", "请检查设备名称,最多 64 个字符") + return + } + if !a.limit(w, r, "rename-device:"+identity.User.ID, 30) { + return + } + accountSettingResult(w, a.accounts.RenameDevice(r.Context(), identity.User.ID, r.PathValue("id"), input.Name)) +} + +func (a *API) loginHistory(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) { + if !a.limit(w, r, "login-history:"+identity.User.ID, 60) { + return + } + items, err := a.accounts.LoginHistory(r.Context(), identity.User.ID, identity.Device.ID) + if err != nil { + unavailable(w, err) + return + } + respond(w, 200, items) +} diff --git a/server/internal/httpapi/api.go b/server/internal/httpapi/api.go index a2f00f8..cb139a2 100644 --- a/server/internal/httpapi/api.go +++ b/server/internal/httpapi/api.go @@ -44,6 +44,10 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d mux.HandleFunc("POST /api/v1/auth/logout", a.authorized(a.logout)) mux.HandleFunc("GET /api/v1/me", a.authorized(a.me)) mux.HandleFunc("GET /api/v1/devices", a.authorized(a.devices)) + mux.HandleFunc("POST /api/v1/devices/{id}", a.authorized(a.renameDevice)) + mux.HandleFunc("POST /api/v1/auth/password", a.authorized(a.changePassword)) + mux.HandleFunc("POST /api/v1/auth/logout-others", a.authorized(a.logoutOthers)) + mux.HandleFunc("GET /api/v1/auth/history", a.authorized(a.loginHistory)) mux.HandleFunc("DELETE /api/v1/devices/{id}", a.authorized(a.revoke)) mux.HandleFunc("POST /api/v1/realtime/ticket", a.authorized(a.ticket)) mux.HandleFunc("GET /api/v1/realtime", a.realtime) diff --git a/tests/account-security.test.mjs b/tests/account-security.test.mjs new file mode 100644 index 0000000..aea47db --- /dev/null +++ b/tests/account-security.test.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict' +import { generateKeyPairSync, randomBytes, sign } from 'node:crypto' +import { once } from 'node:events' +import test from 'node:test' +import { WebSocket } from 'ws' + +const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080' +async function call(path, method = 'GET', token, body, status = 200) { + const response = await fetch(base + '/api/v1' + path, { + method, headers: { ...(token && { Authorization: 'Bearer ' + token }), ...(body && { 'Content-Type': 'application/json' }) }, + body: body && JSON.stringify(body), signal: AbortSignal.timeout(10000), + }) + assert.equal(response.status, status, await response.clone().text()) + return response.status === 204 ? undefined : response.json() +} + +test('密码修改、会话退出、设备重命名与登录记录隔离', { timeout: 30000 }, async () => { + const username = 'safe_' + randomBytes(6).toString('hex') + const password = randomBytes(24).toString('hex') + const nextPassword = randomBytes(24).toString('hex') + const pair = generateKeyPairSync('ed25519') + async function auth(mode, name = username, pass = password, keys = pair, status = 200) { + const { challenge } = await call('/auth/challenge', 'POST') + return call('/auth/' + mode, 'POST', '', { username: name, password: pass, deviceName: '安全测试设备', platform: 'web', challenge, + publicKey: keys.publicKey.export({ format: 'jwk' }).x, + signature: sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), keys.privateKey).toString('base64url'), + }, status) + } + const first = await auth('register', username, password, pair, 201) + const second = await auth('login', username, password, generateKeyPairSync('ed25519')) + const outsider = await auth('register', 'other_' + randomBytes(6).toString('hex'), password, pair, 201) + await call('/devices/' + first.device.id, 'POST', outsider.token, { name: '越权修改' }, 404) + await call('/devices/' + first.device.id, 'POST', first.token, { name: '\n' }, 400) + await call('/devices/' + first.device.id, 'POST', first.token, { name: '我的电脑' }, 204) + const renamed = await auth('login') + assert.equal(renamed.device.name, '我的电脑') + assert.equal(renamed.device.id, first.device.id) + const history = await call('/auth/history', 'GET', first.token) + assert.equal(history.length, 3) + assert.equal(history[0].deviceName, '我的电脑') + assert.deepEqual(history.map((item) => item.currentDevice), [true, false, true]) + assert.equal((await call('/auth/history', 'GET', outsider.token)).length, 1) + assert.deepEqual(Object.keys(history[0]).sort(), ['createdAt','currentDevice','deviceName','id','platform']) + const { ticket } = await call('/realtime/ticket', 'POST', second.token) + const socket = new WebSocket(base.replace(/^http/, 'ws') + '/api/v1/realtime', ['xhchat.v1', 'ticket.' + ticket], { origin: base }) + try { + await once(socket, 'message', { signal: AbortSignal.timeout(5000) }) + const closed = once(socket, 'close', { signal: AbortSignal.timeout(9000) }) + await call('/auth/logout-others', 'POST', first.token, {}, 204) + await call('/me', 'GET', first.token) + await call('/me', 'GET', second.token, undefined, 401) + await call('/me', 'GET', renamed.token, undefined, 401) + assert.equal((await closed)[0], 1008) + await call('/auth/password', 'POST', first.token, { currentPassword: password, newPassword: 'short' }, 400) + await call('/auth/password', 'POST', first.token, { currentPassword: password + 'x', newPassword: nextPassword }, 403) + await call('/me', 'GET', first.token) + const activeSecond = await auth('login', username, password, generateKeyPairSync('ed25519')) + const [changed, racingLogin] = await Promise.all([ + call('/auth/password', 'POST', first.token, { currentPassword: password, newPassword: nextPassword }, 204), + (async () => { const { challenge } = await call('/auth/challenge', 'POST'); return fetch(base + '/api/v1/auth/login', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username,password,challenge,deviceName:'并发登录',platform:'web', + publicKey: pair.publicKey.export({format:'jwk'}).x, + signature: sign(null,Buffer.from('XHChat device authentication v1\n'+challenge),pair.privateKey).toString('base64url') }), + }) })(), + ]) + assert.equal(changed, undefined) + assert.ok([200,401].includes(racingLogin.status)) + if (racingLogin.status === 200) await call('/me','GET',(await racingLogin.json()).token,undefined,401) + await call('/me', 'GET', first.token, undefined, 401) + await call('/me', 'GET', activeSecond.token, undefined, 401) + await auth('login', username, password, pair, 401) + const restored = await auth('login', username, nextPassword) + assert.equal(restored.device.id, first.device.id) + assert.equal(restored.device.name, '我的电脑') + await call('/me', 'GET', outsider.token) + } finally { socket.terminate() } +}) -- 2.54.0