交付双端基础、实时联系人和隔离浏览器

This commit is contained in:
xhgit committed 2026-11-13 18:03:32 +08:00
1 parent 43687d5e7e
commit 67fef3ff87
59 files changed
+5094 -1

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
package account
import (
"crypto/ed25519"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const deviceProof = "XHChat device authentication v1\n"
var Encoding = base64.RawURLEncoding
func Secret() string {
var bytes [32]byte
rand.Read(bytes[:])
return Encoding.EncodeToString(bytes[:])
}
func Proof(publicKey, challenge, signature string) ([]byte, bool) {
key, keyErr := Encoding.DecodeString(publicKey)
sig, sigErr := Encoding.DecodeString(signature)
nonce, nonceErr := Encoding.DecodeString(challenge)
if keyErr != nil || sigErr != nil || nonceErr != nil || len(key) != ed25519.PublicKeySize || len(nonce) != 32 {
return nil, false
}
return key, ed25519.Verify(key, []byte(deviceProof+challenge), sig)
}
func PasswordHash(password string) string {
var salt [16]byte
rand.Read(salt[:])
key := derive(password, salt[:])
return fmt.Sprintf("$argon2id$v=19$m=65536,t=3,p=2$%s$%s",
base64.RawStdEncoding.EncodeToString(salt[:]), base64.RawStdEncoding.EncodeToString(key))
}
func VerifyPassword(password, hash string) bool {
fields := strings.Split(hash, "$")
if len(fields) != 6 || strings.Join(fields[:4], "$") != "$argon2id$v=19$m=65536,t=3,p=2" {
return false
}
salt, saltErr := base64.RawStdEncoding.DecodeString(fields[4])
key, keyErr := base64.RawStdEncoding.DecodeString(fields[5])
if saltErr != nil || keyErr != nil || len(salt) != 16 || len(key) != 32 {
return false
}
return subtle.ConstantTimeCompare(derive(password, salt), key) == 1
}
func derive(password string, salt []byte) []byte {
return argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32)
}
+37
View File
@@ -0,0 +1,37 @@
package account
import (
"crypto/ed25519"
"crypto/rand"
"testing"
)
func TestDeviceProof(t *testing.T) {
public, private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
challenge := Secret()
signature := Encoding.EncodeToString(ed25519.Sign(private, []byte(deviceProof+challenge)))
key := Encoding.EncodeToString(public)
if _, ok := Proof(key, challenge, signature); !ok {
t.Fatal("valid signature rejected")
}
if _, ok := Proof(key, Secret(), signature); ok {
t.Fatal("signature accepted for a different challenge")
}
if _, ok := Proof("invalid", challenge, signature); ok {
t.Fatal("invalid public key accepted")
}
}
func TestPasswordHash(t *testing.T) {
const password = "test password with sufficient length"
hash := PasswordHash(password)
if hash == PasswordHash(password) {
t.Fatal("salt was reused")
}
if !VerifyPassword(password, hash) || VerifyPassword("wrong", hash) || VerifyPassword(password, "malformed") {
t.Fatal("unexpected password verification result")
}
}
+210
View File
@@ -0,0 +1,210 @@
package account
import (
"context"
"crypto/sha256"
"errors"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
ErrCredentials = errors.New("invalid credentials")
ErrDuplicate = errors.New("username already in use")
ErrRevoked = errors.New("device revoked")
)
type User struct {
ID string `json:"id"`
Username string `json:"username"`
}
type Device struct {
ID string `json:"id"`
Name string `json:"name"`
Platform string `json:"platform"`
CreatedAt time.Time `json:"createdAt"`
LastActiveAt time.Time `json:"lastActiveAt"`
RevokedAt *time.Time `json:"revokedAt,omitempty"`
SignedIn bool `json:"signedIn"`
}
type Identity struct {
User User `json:"user"`
Device Device `json:"device"`
}
type Auth struct {
Identity
Token string `json:"token"`
}
type Store struct {
db *pgxpool.Pool
ttl time.Duration
dummyHash string
}
func New(db *pgxpool.Pool, ttl time.Duration) *Store {
return &Store{db: db, ttl: ttl, dummyHash: PasswordHash(Secret())}
}
func (s *Store) Open(ctx context.Context, register bool, username, password, name, platform string, publicKey []byte) (Auth, error) {
var result Auth
result.User.Username = username
var hash string
if register {
hash = PasswordHash(password)
} else {
err := s.db.QueryRow(ctx, "SELECT id, password_hash FROM users WHERE username=$1", username).Scan(&result.User.ID, &hash)
if errors.Is(err, pgx.ErrNoRows) {
VerifyPassword(password, s.dummyHash)
return Auth{}, ErrCredentials
}
if err != nil {
return Auth{}, err
}
if !VerifyPassword(password, hash) {
return Auth{}, ErrCredentials
}
}
tx, err := s.db.Begin(ctx)
if err != nil {
return Auth{}, err
}
defer tx.Rollback(ctx)
if register {
err = tx.QueryRow(ctx, "INSERT INTO users(username,password_hash) VALUES ($1,$2) RETURNING id", username, hash).Scan(&result.User.ID)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return Auth{}, ErrDuplicate
}
if err != nil {
return Auth{}, err
}
}
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
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)
if err = scanDevice(row, &result.Device); errors.Is(err, pgx.ErrNoRows) {
return Auth{}, ErrRevoked
}
if err != nil {
return Auth{}, err
}
result.Token = Secret()
digest := sha256.Sum256([]byte(result.Token))
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
}
result.Device.SignedIn = true
return result, tx.Commit(ctx)
}
func (s *Store) Session(ctx context.Context, token string) (Identity, error) {
digest, err := SessionDigest(token)
if err != nil {
return Identity{}, err
}
return s.SessionByDigest(ctx, digest[:])
}
func SessionDigest(token string) ([32]byte, error) {
raw, err := Encoding.Strict().DecodeString(token)
if err != nil || len(raw) != 32 {
return [32]byte{}, ErrCredentials
}
return sha256.Sum256([]byte(token)), nil
}
func (s *Store) SessionByDigest(ctx context.Context, digest []byte) (Identity, error) {
var identity Identity
d := &identity.Device
err := s.db.QueryRow(ctx, `
SELECT u.id, u.username, d.id, d.name, d.platform, d.created_at, d.last_active_at, d.revoked_at
FROM sessions s JOIN devices d ON d.id=s.device_id JOIN users u ON u.id=d.user_id
WHERE token_hash=$1 AND expires_at > now() AND d.revoked_at IS NULL
`, digest).Scan(&identity.User.ID, &identity.User.Username, &d.ID, &d.Name, &d.Platform, &d.CreatedAt, &d.LastActiveAt, &d.RevokedAt)
if errors.Is(err, pgx.ErrNoRows) {
return Identity{}, ErrCredentials
}
d.SignedIn = err == nil
return identity, err
}
func (s *Store) Logout(ctx context.Context, token string) error {
digest := sha256.Sum256([]byte(token))
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest[:])
return err
}
func (s *Store) Devices(ctx context.Context, user string) ([]Device, error) {
rows, err := s.db.Query(ctx, `
SELECT id, name, platform, created_at, last_active_at, revoked_at,
revoked_at IS NULL AND EXISTS (
SELECT 1 FROM sessions WHERE device_id=devices.id AND expires_at > now()
)
FROM devices
WHERE user_id=$1 ORDER BY created_at DESC
`, user)
if err != nil {
return nil, err
}
defer rows.Close()
devices := make([]Device, 0)
for rows.Next() {
var device Device
if err := rows.Scan(&device.ID, &device.Name, &device.Platform, &device.CreatedAt,
&device.LastActiveAt, &device.RevokedAt, &device.SignedIn); err != nil {
return nil, err
}
devices = append(devices, device)
}
return devices, rows.Err()
}
func (s *Store) TouchDevice(ctx context.Context, device string) error {
_, err := s.db.Exec(ctx, `
UPDATE devices SET last_active_at=now()
WHERE id=$1 AND revoked_at IS NULL AND last_active_at < now() - interval '1 minute'
`, device)
return err
}
func (s *Store) Revoke(ctx context.Context, user, device string) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
result, err := tx.Exec(ctx, "UPDATE devices SET revoked_at=COALESCE(revoked_at,now()) WHERE user_id=$1 AND id=$2", user, device)
if err != nil {
return err
}
if result.RowsAffected() == 0 {
return pgx.ErrNoRows
}
if _, err := tx.Exec(ctx, "DELETE FROM sessions WHERE device_id=$1", device); err != nil {
return err
}
return tx.Commit(ctx)
}
func (s *Store) Cleanup(ctx context.Context) error {
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE expires_at <= now()")
return err
}
func scanDevice(row pgx.Row, d *Device) error {
return row.Scan(&d.ID, &d.Name, &d.Platform, &d.CreatedAt, &d.LastActiveAt, &d.RevokedAt)
}