fix(passkey): 删除 passkey 先确认并显示名称与注册时间,邮箱未验证时后端拒删最后一把,错误内联显示
This commit is contained in:
16 files changed
+336
-40
No files matched your search
+8
-1
@@ -4142,7 +4142,9 @@ paths:
|
|||||||
description: >
|
description: >
|
||||||
Removes a passkey scoped to the authenticated principal, so a caller can only
|
Removes a passkey scoped to the authenticated principal, so a caller can only
|
||||||
unbind their OWN credential. An unknown or cross-user id is a 404; it never
|
unbind their OWN credential. An unknown or cross-user id is a 404; it never
|
||||||
silently no-ops as success.
|
silently no-ops as success. The account's only passkey cannot be removed while
|
||||||
|
its email is unverified (409 last_passkey): it is then the account's only
|
||||||
|
durable way in.
|
||||||
x-felis-face: [external]
|
x-felis-face: [external]
|
||||||
x-felis-tier: app
|
x-felis-tier: app
|
||||||
security: [{ accessJWT: [] }]
|
security: [{ accessJWT: [] }]
|
||||||
@@ -4162,6 +4164,11 @@ paths:
|
|||||||
content:
|
content:
|
||||||
application/json:
|
application/json:
|
||||||
schema: { $ref: '#/components/schemas/Error' }
|
schema: { $ref: '#/components/schemas/Error' }
|
||||||
|
'409':
|
||||||
|
description: last_passkey — this is the only passkey and the email is unverified.
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: { $ref: '#/components/schemas/Error' }
|
||||||
|
|
||||||
/api/v1/account/migrate:
|
/api/v1/account/migrate:
|
||||||
get:
|
get:
|
||||||
|
|||||||
@@ -539,14 +539,31 @@ func (f *fakeRepo) PasskeyCredentialsForUser(_ context.Context, userID string) (
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeletePasskeyCredential mirrors PGRepo: scoped to userID so a caller can only unbind
|
// DeletePasskeyCredential mirrors PGRepo: scoped to userID so a caller can only unbind
|
||||||
// their OWN credential; no matching (user, id) row → ErrNotFound.
|
// their OWN credential; no matching (user, id) row → ErrNotFound; the last passkey of
|
||||||
|
// a user whose email is unverified (or who has no user row here) → ErrLastPasskey.
|
||||||
func (f *fakeRepo) DeletePasskeyCredential(_ context.Context, userID, id string) error {
|
func (f *fakeRepo) DeletePasskeyCredential(_ context.Context, userID, id string) error {
|
||||||
if c, ok := f.passkeyCreds[id]; ok && c.UserID == userID {
|
c, ok := f.passkeyCreds[id]
|
||||||
|
if !ok || c.UserID != userID {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
total := 0
|
||||||
|
for _, other := range f.passkeyCreds {
|
||||||
|
if other.UserID == userID {
|
||||||
|
total++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
verified := false
|
||||||
|
for _, u := range f.staff {
|
||||||
|
if u.ID == userID {
|
||||||
|
verified = u.EmailVerified
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if total == 1 && !verified {
|
||||||
|
return ErrLastPasskey
|
||||||
|
}
|
||||||
delete(f.passkeyCreds, id)
|
delete(f.passkeyCreds, id)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return ErrNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteAllPasskeyCredentialsForUser mirrors PGRepo: unbind every passkey the user holds,
|
// DeleteAllPasskeyCredentialsForUser mirrors PGRepo: unbind every passkey the user holds,
|
||||||
// and removing zero is a successful no-op (never ErrNotFound).
|
// and removing zero is a successful no-op (never ErrNotFound).
|
||||||
|
|||||||
@@ -57,6 +57,12 @@ var (
|
|||||||
// finish endpoint exists; the ceremony state is gone (never begun, already
|
// finish endpoint exists; the ceremony state is gone (never begun, already
|
||||||
// consumed, or expired) — so handlers map it to 400, not 404.
|
// consumed, or expired) — so handlers map it to 400, not 404.
|
||||||
ErrPasskeyChallengeInvalid = errors.New("passkey challenge invalid or expired")
|
ErrPasskeyChallengeInvalid = errors.New("passkey challenge invalid or expired")
|
||||||
|
// ErrLastPasskey means a passkey delete would remove the account's only one while
|
||||||
|
// its email is unverified. That passkey is then the account's only durable way
|
||||||
|
// in (setupRequired: no verified email and no passkey puts it back behind the
|
||||||
|
// setup gate, and a staff account has no other self-service door at all), so the
|
||||||
|
// delete is refused; handlers map it to 409 last_passkey.
|
||||||
|
ErrLastPasskey = errors.New("cannot remove the only passkey of an account without a verified email")
|
||||||
// ErrPlayerBindForbidden means a public Bind-Code redemption resolved to a STAFF
|
// ErrPlayerBindForbidden means a public Bind-Code redemption resolved to a STAFF
|
||||||
// account (admin or owner), which the player-console bootstrap refuses
|
// account (admin or owner), which the player-console bootstrap refuses
|
||||||
// (console-tier access model). Staff authenticate at op.console behind Zero Trust,
|
// (console-tier access model). Staff authenticate at op.console behind Zero Trust,
|
||||||
|
|||||||
@@ -400,6 +400,8 @@ func (a *API) handlePasskeyList(w http.ResponseWriter, r *http.Request) {
|
|||||||
// handlePasskeyDelete unbinds one of the caller's passkeys (spec §14, external app
|
// handlePasskeyDelete unbinds one of the caller's passkeys (spec §14, external app
|
||||||
// face). The delete is scoped to the principal, so a caller can only remove their OWN
|
// face). The delete is scoped to the principal, so a caller can only remove their OWN
|
||||||
// credential; an unknown or cross-user id → 404 (it never silently no-ops as success).
|
// credential; an unknown or cross-user id → 404 (it never silently no-ops as success).
|
||||||
|
// The last passkey of an account without a verified email → 409 last_passkey: it is
|
||||||
|
// that account's only durable way in (ErrLastPasskey).
|
||||||
func (a *API) handlePasskeyDelete(w http.ResponseWriter, r *http.Request) {
|
func (a *API) handlePasskeyDelete(w http.ResponseWriter, r *http.Request) {
|
||||||
p := principalFromContext(r.Context())
|
p := principalFromContext(r.Context())
|
||||||
id := r.PathValue("id")
|
id := r.PathValue("id")
|
||||||
@@ -412,6 +414,11 @@ func (a *API) handlePasskeyDelete(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, r, newError(http.StatusNotFound, "not_found", "no such passkey"))
|
writeError(w, r, newError(http.StatusNotFound, "not_found", "no such passkey"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if errors.Is(err, ErrLastPasskey) {
|
||||||
|
writeError(w, r, newError(http.StatusConflict, "last_passkey",
|
||||||
|
"this is your only passkey and your email is not verified; add another passkey or verify an email first"))
|
||||||
|
return
|
||||||
|
}
|
||||||
writeError(w, r, err)
|
writeError(w, r, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,8 @@ func plantPasskeyChallenge(repo *fakeRepo, id string, expiresAt time.Time, sessi
|
|||||||
func TestPasskeyRegisterVertical(t *testing.T) {
|
func TestPasskeyRegisterVertical(t *testing.T) {
|
||||||
user := &Principal{UserID: "u1", Email: "[email protected]", Role: "user"}
|
user := &Principal{UserID: "u1", Email: "[email protected]", Role: "user"}
|
||||||
repo := newFakeRepo()
|
repo := newFakeRepo()
|
||||||
|
// A verified email keeps a door open, so step 5 may remove the only passkey.
|
||||||
|
repo.staff["u1"] = &StaffUser{ID: "u1", Username: "u1", Email: "[email protected]", Role: "user", EmailVerified: true}
|
||||||
v := &fakePasskeyVerifier{
|
v := &fakePasskeyVerifier{
|
||||||
options: json.RawMessage(`{"publicKey":{"challenge":"Y2hhbGxlbmdl"}}`),
|
options: json.RawMessage(`{"publicKey":{"challenge":"Y2hhbGxlbmdl"}}`),
|
||||||
credential: VerifiedCredential{
|
credential: VerifiedCredential{
|
||||||
@@ -294,6 +296,65 @@ func TestPasskeyDeleteScoping(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestPasskeyDeleteLastGuard pins the last-passkey guard: without a verified email
|
||||||
|
// the only passkey is the account's way in, so its delete is a 409 that leaves it
|
||||||
|
// bound; a second passkey or a verified email lets the delete through.
|
||||||
|
func TestPasskeyDeleteLastGuard(t *testing.T) {
|
||||||
|
cred := func(id string) PasskeyCredential {
|
||||||
|
return PasskeyCredential{ID: id, UserID: "u1", CredentialID: "c-" + id, CreatedAt: frozenNow}
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
verified bool
|
||||||
|
creds []string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"only passkey, email unverified", false, []string{"a"}, http.StatusConflict},
|
||||||
|
{"only passkey, email verified", true, []string{"a"}, http.StatusNoContent},
|
||||||
|
{"two passkeys, email unverified", false, []string{"a", "b"}, http.StatusNoContent},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
for _, role := range []string{"user", "admin"} {
|
||||||
|
user := &Principal{UserID: "u1", Email: "[email protected]", Role: role}
|
||||||
|
repo := newFakeRepo()
|
||||||
|
repo.staff["u1"] = &StaffUser{ID: "u1", Username: "u1", Email: "[email protected]", Role: role, EmailVerified: tc.verified}
|
||||||
|
for _, id := range tc.creds {
|
||||||
|
repo.passkeyCreds[id] = cred(id)
|
||||||
|
}
|
||||||
|
eh := newPasskeyAPI(repo, &fakePasskeyVerifier{}, user)
|
||||||
|
w := do(eh, "DELETE", "/api/v1/account/passkey/credentials/a", "", nil)
|
||||||
|
if w.Code != tc.want {
|
||||||
|
t.Fatalf("%s: code = %d body %s, want %d", role, w.Code, w.Body.String(), tc.want)
|
||||||
|
}
|
||||||
|
_, kept := repo.passkeyCreds["a"]
|
||||||
|
if tc.want == http.StatusConflict {
|
||||||
|
if got := decodeErr(t, w); got != "last_passkey" {
|
||||||
|
t.Errorf("%s: error code = %q, want last_passkey", role, got)
|
||||||
|
}
|
||||||
|
if !kept {
|
||||||
|
t.Errorf("%s: a refused delete must leave the passkey bound", role)
|
||||||
|
}
|
||||||
|
} else if kept {
|
||||||
|
t.Errorf("%s: an allowed delete must remove the passkey", role)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removing one of two leaves the other as the last one, which is then guarded.
|
||||||
|
user := &Principal{UserID: "u1", Email: "[email protected]", Role: "user"}
|
||||||
|
repo := newFakeRepo()
|
||||||
|
repo.staff["u1"] = &StaffUser{ID: "u1", Username: "u1", Email: "[email protected]", Role: "user"}
|
||||||
|
repo.passkeyCreds["a"], repo.passkeyCreds["b"] = cred("a"), cred("b")
|
||||||
|
eh := newPasskeyAPI(repo, &fakePasskeyVerifier{}, user)
|
||||||
|
if w := do(eh, "DELETE", "/api/v1/account/passkey/credentials/a", "", nil); w.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("first delete: code = %d, want 204", w.Code)
|
||||||
|
}
|
||||||
|
if w := do(eh, "DELETE", "/api/v1/account/passkey/credentials/b", "", nil); w.Code != http.StatusConflict {
|
||||||
|
t.Fatalf("second delete: code = %d, want 409 (it is now the last one)", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestPasskeyDeleteUnknown pins the unknown-id path: deleting an id that does not exist
|
// TestPasskeyDeleteUnknown pins the unknown-id path: deleting an id that does not exist
|
||||||
// is a 404, never a silent 204.
|
// is a 404, never a silent 204.
|
||||||
func TestPasskeyDeleteUnknown(t *testing.T) {
|
func TestPasskeyDeleteUnknown(t *testing.T) {
|
||||||
|
|||||||
+25
-6
@@ -1412,19 +1412,38 @@ func (p *PGRepo) AdvanceCredentialSignCount(ctx context.Context, credentialID st
|
|||||||
// only unbind their OWN credential. No matching (user, id) row → ErrNotFound via a zero
|
// only unbind their OWN credential. No matching (user, id) row → ErrNotFound via a zero
|
||||||
// RowsAffected, so a stale or cross-user id cannot silently no-op as success.
|
// RowsAffected, so a stale or cross-user id cannot silently no-op as success.
|
||||||
func (p *PGRepo) DeletePasskeyCredential(ctx context.Context, userID, id string) error {
|
func (p *PGRepo) DeletePasskeyCredential(ctx context.Context, userID, id string) error {
|
||||||
res, err := p.db.ExecContext(ctx,
|
tx, err := p.db.BeginTx(ctx, nil)
|
||||||
`DELETE FROM webauthn_credentials WHERE id = $1 AND user_id = $2`, id, userID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
n, err := res.RowsAffected()
|
defer func() { _ = tx.Rollback() }()
|
||||||
if err != nil {
|
// Lock the user row first: every delete for this user queues here, so the count
|
||||||
|
// below cannot go stale between the check and the DELETE.
|
||||||
|
var verified bool
|
||||||
|
switch err := tx.QueryRowContext(ctx,
|
||||||
|
`SELECT email_verified FROM users WHERE id = $1 FOR UPDATE`, userID).Scan(&verified); {
|
||||||
|
case errors.Is(err, sql.ErrNoRows):
|
||||||
|
return ErrNotFound
|
||||||
|
case err != nil:
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if n == 0 {
|
var mine, total int
|
||||||
|
if err := tx.QueryRowContext(ctx,
|
||||||
|
`SELECT count(*) FILTER (WHERE id = $2), count(*) FROM webauthn_credentials WHERE user_id = $1`,
|
||||||
|
userID, id).Scan(&mine, &total); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if mine == 0 {
|
||||||
return ErrNotFound
|
return ErrNotFound
|
||||||
}
|
}
|
||||||
return nil
|
if total == 1 && !verified {
|
||||||
|
return ErrLastPasskey
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx,
|
||||||
|
`DELETE FROM webauthn_credentials WHERE id = $1 AND user_id = $2`, id, userID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAllPasskeyCredentialsForUser unbinds every passkey a user holds. Unlike the
|
// DeleteAllPasskeyCredentialsForUser unbinds every passkey a user holds. Unlike the
|
||||||
|
|||||||
@@ -459,7 +459,10 @@ type Repo interface {
|
|||||||
PasskeyCredentialsForUser(ctx context.Context, userID string) ([]PasskeyCredential, error)
|
PasskeyCredentialsForUser(ctx context.Context, userID string) ([]PasskeyCredential, error)
|
||||||
// DeletePasskeyCredential removes the passkey row id, scoped to userID so a caller
|
// DeletePasskeyCredential removes the passkey row id, scoped to userID so a caller
|
||||||
// can only unbind their OWN credential. No matching (user, id) row → ErrNotFound,
|
// can only unbind their OWN credential. No matching (user, id) row → ErrNotFound,
|
||||||
// so a stale or cross-user id cannot silently no-op as success.
|
// so a stale or cross-user id cannot silently no-op as success. When the row is
|
||||||
|
// the user's last passkey and their email is unverified it returns ErrLastPasskey
|
||||||
|
// and deletes nothing; the check and the delete hold the user row locked, so two
|
||||||
|
// concurrent deletes of a user's last two passkeys cannot both pass.
|
||||||
DeletePasskeyCredential(ctx context.Context, userID, id string) error
|
DeletePasskeyCredential(ctx context.Context, userID, id string) error
|
||||||
// DeleteAllPasskeyCredentialsForUser unbinds every passkey a user holds — the
|
// DeleteAllPasskeyCredentialsForUser unbinds every passkey a user holds — the
|
||||||
// remediation that stops a passkey planted via a transiently-hijacked session from
|
// remediation that stops a passkey planted via a transiently-hijacked session from
|
||||||
|
|||||||
@@ -722,6 +722,90 @@ func TestDeadAccountsAreLockedOutInPG(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeletePasskeyCredential keeps the last passkey of an account whose email is
|
||||||
|
// unverified: removing it would leave no durable way in. The guard reads the count
|
||||||
|
// under the user-row lock, so two concurrent deletes of an account's last two
|
||||||
|
// passkeys resolve to exactly one delete and one ErrLastPasskey, never zero left.
|
||||||
|
func TestLastPasskeyGuardInPG(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
seed := func(t *testing.T, userID string) string {
|
||||||
|
t.Helper()
|
||||||
|
id := "cred-" + suffix(t)
|
||||||
|
if _, err := db.ExecContext(ctx,
|
||||||
|
`INSERT INTO webauthn_credentials (id, user_id, credential_id, public_key) VALUES ($1,$2,$3,'pk')`,
|
||||||
|
id, userID, "cid-"+suffix(t)); err != nil {
|
||||||
|
t.Fatalf("seed passkey: %v", err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
count := func(t *testing.T, userID string) int {
|
||||||
|
t.Helper()
|
||||||
|
var n int
|
||||||
|
if err := db.QueryRowContext(ctx,
|
||||||
|
`SELECT count(*) FROM webauthn_credentials WHERE user_id = $1`, userID).Scan(&n); err != nil {
|
||||||
|
t.Fatalf("count: %v", err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
u := newUser(t, "user", "lastpk")
|
||||||
|
a, b := seed(t, u.ID), seed(t, u.ID)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errs := make([]error, 2)
|
||||||
|
for j, id := range []string{a, b} {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(j int, id string) {
|
||||||
|
defer wg.Done()
|
||||||
|
errs[j] = repo.DeletePasskeyCredential(ctx, u.ID, id)
|
||||||
|
}(j, id)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
ok, refused := 0, 0
|
||||||
|
for _, err := range errs {
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
ok++
|
||||||
|
case errors.Is(err, api.ErrLastPasskey):
|
||||||
|
refused++
|
||||||
|
default:
|
||||||
|
t.Fatalf("concurrent delete: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ok != 1 || refused != 1 || count(t, u.ID) != 1 {
|
||||||
|
t.Fatalf("round %d: %d deleted, %d refused, %d left; want 1, 1, 1", i, ok, refused, count(t, u.ID))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
u := newUser(t, "admin", "lastpk")
|
||||||
|
last := seed(t, u.ID)
|
||||||
|
if err := repo.DeletePasskeyCredential(ctx, u.ID, last); !errors.Is(err, api.ErrLastPasskey) {
|
||||||
|
t.Fatalf("last passkey, unverified: %v, want ErrLastPasskey", err)
|
||||||
|
}
|
||||||
|
if err := repo.DeletePasskeyCredential(ctx, u.ID, "cred-none-"+suffix(t)); !errors.Is(err, api.ErrNotFound) {
|
||||||
|
t.Fatalf("unknown id: %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
other := newUser(t, "user", "lastpk")
|
||||||
|
if err := repo.DeletePasskeyCredential(ctx, other.ID, last); !errors.Is(err, api.ErrNotFound) {
|
||||||
|
t.Fatalf("another user's passkey: %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A verified email is another door, so the last passkey may go.
|
||||||
|
now := mustNow()
|
||||||
|
if err := repo.CreateEmailOTP(ctx, "lp-"+suffix(t), u.ID, "lastpk-"+suffix(t)+"@example.net", "h", "onboard_email", now.Add(5*time.Minute)); err != nil {
|
||||||
|
t.Fatalf("CreateEmailOTP: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.VerifyEmailOTP(ctx, u.ID, "onboard_email", "h", now); err != nil {
|
||||||
|
t.Fatalf("VerifyEmailOTP: %v", err)
|
||||||
|
}
|
||||||
|
if err := repo.DeletePasskeyCredential(ctx, u.ID, last); err != nil {
|
||||||
|
t.Fatalf("last passkey, verified: %v", err)
|
||||||
|
}
|
||||||
|
if n := count(t, u.ID); n != 0 {
|
||||||
|
t.Fatalf("%d passkeys left after the allowed delete, want 0", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// VerifyLinkCode's takeover rule: a fresh in-game code (proof the caller holds the
|
// VerifyLinkCode's takeover rule: a fresh in-game code (proof the caller holds the
|
||||||
// UUID) lets a live account take over a link whose account was SOFT-DELETED — the
|
// UUID) lets a live account take over a link whose account was SOFT-DELETED — the
|
||||||
// migrated-source case, whose retire keeps the link but kills the account — while a
|
// migrated-source case, whose retire keeps the link but kills the account — while a
|
||||||
|
|||||||
+11
-4
@@ -899,12 +899,19 @@ async function handleSession(ctx: SessionContext): Promise<boolean> {
|
|||||||
default:
|
default:
|
||||||
if (ctx.method === "DELETE" && ctx.parts[2] === "account" && ctx.parts[3] === "passkey" && ctx.parts[4] === "credentials" && ctx.parts[5]) {
|
if (ctx.method === "DELETE" && ctx.parts[2] === "account" && ctx.parts[3] === "passkey" && ctx.parts[4] === "credentials" && ctx.parts[5]) {
|
||||||
const id = ctx.parts[5];
|
const id = ctx.parts[5];
|
||||||
if (ctx.state.passkeys[ctx.account.id]) {
|
const list = ctx.state.passkeys[ctx.account.id] ?? [];
|
||||||
const idx = ctx.state.passkeys[ctx.account.id].findIndex((k) => k.id === id);
|
const idx = list.findIndex((k) => k.id === id);
|
||||||
if (idx >= 0) {
|
if (idx < 0) {
|
||||||
ctx.state.passkeys[ctx.account.id].splice(idx, 1);
|
sendError(ctx.res, 404, "not_found", "passkey not found");
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
// Same rule as the real API: the only passkey of an account without a
|
||||||
|
// verified email stays, or the account would have no way to sign in.
|
||||||
|
if (list.length === 1 && !ctx.account.emailVerified) {
|
||||||
|
sendError(ctx.res, 409, "last_passkey", "this is your only passkey and your email is not verified");
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
list.splice(idx, 1);
|
||||||
ctx.res.statusCode = 204;
|
ctx.res.statusCode = 204;
|
||||||
ctx.res.end();
|
ctx.res.end();
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -44,6 +44,11 @@
|
|||||||
"created_at": "Registered at: ",
|
"created_at": "Registered at: ",
|
||||||
"last_used": "Last used: ",
|
"last_used": "Last used: ",
|
||||||
"never": "Never",
|
"never": "Never",
|
||||||
|
"passkey_delete_aria": "Delete passkey “{{name}}”",
|
||||||
|
"passkey_delete_title": "Delete this passkey?",
|
||||||
|
"passkey_delete_desc": "“{{name}}” (registered {{created}}) will no longer sign you in. You can register it again later.",
|
||||||
|
"passkey_delete_confirm": "Delete",
|
||||||
|
"passkey_last_hint": "This is your only passkey and your email is not verified, so deleting it would lock you out. Verify an email or add another passkey first.",
|
||||||
"migration": "Account migration",
|
"migration": "Account migration",
|
||||||
"migration_desc": "Move everything a retired account owns onto this one. Migration starts in-game and finishes here.",
|
"migration_desc": "Move everything a retired account owns onto this one. Migration starts in-game and finishes here.",
|
||||||
"account_id": "Account ID",
|
"account_id": "Account ID",
|
||||||
|
|||||||
@@ -37,6 +37,7 @@
|
|||||||
"invalid_attestation": "Could not verify this Passkey, please try again.",
|
"invalid_attestation": "Could not verify this Passkey, please try again.",
|
||||||
"passkey_already_bound": "This Passkey is already bound to another account.",
|
"passkey_already_bound": "This Passkey is already bound to another account.",
|
||||||
"passkey_unavailable": "Passkey subsystem is not available right now.",
|
"passkey_unavailable": "Passkey subsystem is not available right now.",
|
||||||
|
"last_passkey": "This is your only passkey and your email is not verified, so it can't be removed. Verify an email or add another passkey first.",
|
||||||
"passkey_not_allowed": "The operation was cancelled by the user or browser.",
|
"passkey_not_allowed": "The operation was cancelled by the user or browser.",
|
||||||
"passkey_aborted": "Passkey registration was aborted.",
|
"passkey_aborted": "Passkey registration was aborted.",
|
||||||
"bad_name": "That server name is invalid — use 3–32 lowercase letters, digits or dashes, and avoid reserved names.",
|
"bad_name": "That server name is invalid — use 3–32 lowercase letters, digits or dashes, and avoid reserved names.",
|
||||||
|
|||||||
@@ -44,6 +44,11 @@
|
|||||||
"created_at": "注册时间:",
|
"created_at": "注册时间:",
|
||||||
"last_used": "上次使用:",
|
"last_used": "上次使用:",
|
||||||
"never": "从未",
|
"never": "从未",
|
||||||
|
"passkey_delete_aria": "删除 Passkey「{{name}}」",
|
||||||
|
"passkey_delete_title": "删除这个 Passkey?",
|
||||||
|
"passkey_delete_desc": "「{{name}}」(注册于 {{created}})删除后无法再用它登录,需要时可以重新注册。",
|
||||||
|
"passkey_delete_confirm": "删除",
|
||||||
|
"passkey_last_hint": "这是你唯一的 Passkey,邮箱也还没验证,删掉就没法登录了。先验证邮箱或再注册一个 Passkey,才能删除它。",
|
||||||
"migration": "账户迁移",
|
"migration": "账户迁移",
|
||||||
"migration_desc": "将被弃用账户名下的所有服务器转移到本账户。迁移在游戏内发起,在此完成。",
|
"migration_desc": "将被弃用账户名下的所有服务器转移到本账户。迁移在游戏内发起,在此完成。",
|
||||||
"account_id": "账户 ID",
|
"account_id": "账户 ID",
|
||||||
|
|||||||
@@ -37,6 +37,7 @@
|
|||||||
"invalid_attestation": "无法验证此 Passkey,请重试。",
|
"invalid_attestation": "无法验证此 Passkey,请重试。",
|
||||||
"passkey_already_bound": "此 Passkey 已被其他账户绑定。",
|
"passkey_already_bound": "此 Passkey 已被其他账户绑定。",
|
||||||
"passkey_unavailable": "Passkey 功能当前不可用。",
|
"passkey_unavailable": "Passkey 功能当前不可用。",
|
||||||
|
"last_passkey": "这是你唯一的 Passkey,邮箱也还没验证,不能删除。先验证邮箱或再注册一个 Passkey。",
|
||||||
"passkey_not_allowed": "操作已被用户或浏览器取消。",
|
"passkey_not_allowed": "操作已被用户或浏览器取消。",
|
||||||
"passkey_aborted": "Passkey 注册已被取消。",
|
"passkey_aborted": "Passkey 注册已被取消。",
|
||||||
"bad_name": "服务器名称不合法:需为 3–32 位小写字母、数字或连字符,且不能使用保留名。",
|
"bad_name": "服务器名称不合法:需为 3–32 位小写字母、数字或连字符,且不能使用保留名。",
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import type {
|
|||||||
LinkResult,
|
LinkResult,
|
||||||
LinkStatus,
|
LinkStatus,
|
||||||
BindResult,
|
BindResult,
|
||||||
|
PasskeyCredential,
|
||||||
PatchUserRequest,
|
PatchUserRequest,
|
||||||
PlayersResult,
|
PlayersResult,
|
||||||
QuotaInput,
|
QuotaInput,
|
||||||
@@ -560,7 +561,7 @@ export const api = rejectingSync({
|
|||||||
request<any>("POST", "/account/passkey/register/finish", { name, attestation }),
|
request<any>("POST", "/account/passkey/register/finish", { name, attestation }),
|
||||||
|
|
||||||
passkeyList: () =>
|
passkeyList: () =>
|
||||||
request<{ credentials: any[] }>("GET", "/account/passkey/credentials"),
|
request<{ credentials: PasskeyCredential[] }>("GET", "/account/passkey/credentials"),
|
||||||
|
|
||||||
passkeyDelete: (id: string) =>
|
passkeyDelete: (id: string) =>
|
||||||
request<void>("DELETE", urlPath`/account/passkey/credentials/${id}`),
|
request<void>("DELETE", urlPath`/account/passkey/credentials/${id}`),
|
||||||
@@ -800,6 +801,8 @@ export function humanizeError(e: unknown): string {
|
|||||||
return t("passkey_already_bound");
|
return t("passkey_already_bound");
|
||||||
case "passkey_unavailable":
|
case "passkey_unavailable":
|
||||||
return t("passkey_unavailable");
|
return t("passkey_unavailable");
|
||||||
|
case "last_passkey":
|
||||||
|
return t("last_passkey");
|
||||||
case "quota_exceeded":
|
case "quota_exceeded":
|
||||||
return t("quota_exceeded");
|
return t("quota_exceeded");
|
||||||
case "already_claimed":
|
case "already_claimed":
|
||||||
|
|||||||
@@ -392,6 +392,15 @@ export interface QuotaInput {
|
|||||||
max_storage_gb?: number | null;
|
max_storage_gb?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// One registered passkey as GET /account/passkey/credentials lists it.
|
||||||
|
export interface PasskeyCredential {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
aaguid?: string;
|
||||||
|
created_at: string;
|
||||||
|
last_used_at?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface SessionView {
|
export interface SessionView {
|
||||||
token_hash: string;
|
token_hash: string;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
|
|||||||
+84
-23
@@ -6,8 +6,12 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Loading, ErrorState } from "@/components/States";
|
import { Loading, ErrorState } from "@/components/States";
|
||||||
|
import { ConfirmFooter } from "@/components/ConfirmFooter";
|
||||||
|
import { MessageLine } from "@/components/MessageLine";
|
||||||
import { PageHeader } from "@/components/PageHeader";
|
import { PageHeader } from "@/components/PageHeader";
|
||||||
import { api, humanizeError } from "@/lib/api";
|
import { api, humanizeError } from "@/lib/api";
|
||||||
|
import { formatAbsolute } from "@/lib/format";
|
||||||
|
import type { PasskeyCredential } from "@/lib/types";
|
||||||
import { useAsync } from "@/lib/hooks";
|
import { useAsync } from "@/lib/hooks";
|
||||||
import { useTier } from "@/lib/tier";
|
import { useTier } from "@/lib/tier";
|
||||||
import { base64urlToBytes, bytesToBase64url } from "@/lib/utils";
|
import { base64urlToBytes, bytesToBase64url } from "@/lib/utils";
|
||||||
@@ -30,7 +34,7 @@ import {
|
|||||||
export function Account() {
|
export function Account() {
|
||||||
const status = useAsync(() => api.linkStatus(), []);
|
const status = useAsync(() => api.linkStatus(), []);
|
||||||
const { identity, refresh } = useTier();
|
const { identity, refresh } = useTier();
|
||||||
const { t } = useTranslation("account");
|
const { t, i18n } = useTranslation("account");
|
||||||
|
|
||||||
// Email verification state
|
// Email verification state
|
||||||
const [emailInput, setEmailInput] = useState("");
|
const [emailInput, setEmailInput] = useState("");
|
||||||
@@ -93,7 +97,15 @@ export function Account() {
|
|||||||
const [registeringPasskey, setRegisteringPasskey] = useState(false);
|
const [registeringPasskey, setRegisteringPasskey] = useState(false);
|
||||||
const [passkeyError, setPasskeyError] = useState<string | null>(null);
|
const [passkeyError, setPasskeyError] = useState<string | null>(null);
|
||||||
const [registerDialogOpen, setRegisterDialogOpen] = useState(false);
|
const [registerDialogOpen, setRegisterDialogOpen] = useState(false);
|
||||||
const [deletingMap, setDeletingMap] = useState<Record<string, boolean>>({});
|
// Deleting a passkey goes through a confirm dialog that names it. The API
|
||||||
|
// refuses to remove the only passkey of an account whose email is unverified
|
||||||
|
// (it would be left with no way back in); the button mirrors that rule so the
|
||||||
|
// refusal is explained up front instead of after a round trip.
|
||||||
|
const [pendingDelete, setPendingDelete] = useState<PasskeyCredential | null>(null);
|
||||||
|
const [deletingPasskey, setDeletingPasskey] = useState(false);
|
||||||
|
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||||
|
const credentials = passkeys.data?.credentials ?? [];
|
||||||
|
const keepLastPasskey = credentials.length === 1 && !identity?.email_verified;
|
||||||
|
|
||||||
const abortControllerRef = useRef<AbortController | null>(null);
|
const abortControllerRef = useRef<AbortController | null>(null);
|
||||||
|
|
||||||
@@ -165,16 +177,30 @@ export function Account() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleDeletePasskey(id: string) {
|
function askDeletePasskey(cred: PasskeyCredential) {
|
||||||
if (deletingMap[id]) return;
|
setDeleteError(null);
|
||||||
setDeletingMap((prev) => ({ ...prev, [id]: true }));
|
setPendingDelete(cred);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmDeletePasskey() {
|
||||||
|
if (!pendingDelete || deletingPasskey) return;
|
||||||
|
setDeletingPasskey(true);
|
||||||
|
setDeleteError(null);
|
||||||
try {
|
try {
|
||||||
await api.passkeyDelete(id);
|
await api.passkeyDelete(pendingDelete.id);
|
||||||
|
setPendingDelete(null);
|
||||||
await passkeys.reload();
|
await passkeys.reload();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert(humanizeError(err));
|
// Another device may have changed the list meanwhile: refresh it. A 404
|
||||||
|
// means the passkey is already gone, which is what was asked for.
|
||||||
|
void passkeys.reload();
|
||||||
|
if ((err as { code?: string }).code === "not_found") {
|
||||||
|
setPendingDelete(null);
|
||||||
|
} else {
|
||||||
|
setDeleteError(humanizeError(err));
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setDeletingMap((prev) => ({ ...prev, [id]: false }));
|
setDeletingPasskey(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -404,47 +430,82 @@ export function Account() {
|
|||||||
<Loading label={t("loading_passkeys")} />
|
<Loading label={t("loading_passkeys")} />
|
||||||
) : passkeys.error ? (
|
) : passkeys.error ? (
|
||||||
<ErrorState error={passkeys.error} onRetry={passkeys.reload} />
|
<ErrorState error={passkeys.error} onRetry={passkeys.reload} />
|
||||||
) : !passkeys.data?.credentials || passkeys.data.credentials.length === 0 ? (
|
) : credentials.length === 0 ? (
|
||||||
<p className="text-xs text-muted-foreground py-2 italic">{t("no_passkeys")}</p>
|
<p className="text-xs text-muted-foreground py-2 italic">{t("no_passkeys")}</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="border rounded-md divide-y bg-background/50">
|
<>
|
||||||
{passkeys.data.credentials.map((cred: any) => (
|
<ul className="border rounded-md divide-y bg-background/50">
|
||||||
<div key={cred.id} className="flex items-center justify-between p-3">
|
{credentials.map((cred) => (
|
||||||
<div className="space-y-1">
|
<li key={cred.id} className="flex items-center justify-between gap-3 p-3">
|
||||||
|
<div className="min-w-0 space-y-1">
|
||||||
<p className="font-medium text-foreground flex items-center gap-1.5">
|
<p className="font-medium text-foreground flex items-center gap-1.5">
|
||||||
<KeyRound className="h-3.5 w-3.5 text-muted-foreground" />
|
<KeyRound className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||||
{cred.name}
|
<span className="truncate">{cred.name}</span>
|
||||||
</p>
|
</p>
|
||||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||||
<span>
|
<span>
|
||||||
{t("created_at")}
|
{t("created_at")}
|
||||||
{new Date(cred.created_at).toLocaleString()}
|
{formatAbsolute(cred.created_at, i18n.language)}
|
||||||
</span>
|
</span>
|
||||||
<span>
|
<span>
|
||||||
{t("last_used")}
|
{t("last_used")}
|
||||||
{cred.last_used_at ? new Date(cred.last_used_at).toLocaleString() : t("never")}
|
{cred.last_used_at ? formatAbsolute(cred.last_used_at, i18n.language) : t("never")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
size="icon"
|
size="icon"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
onClick={() => handleDeletePasskey(cred.id)}
|
onClick={() => askDeletePasskey(cred)}
|
||||||
disabled={deletingMap[cred.id]}
|
disabled={keepLastPasskey}
|
||||||
className="text-muted-foreground hover:text-destructive"
|
aria-label={t("passkey_delete_aria", { name: cred.name })}
|
||||||
|
title={keepLastPasskey ? t("passkey_last_hint") : t("passkey_delete_aria", { name: cred.name })}
|
||||||
|
className="shrink-0 text-muted-foreground hover:text-destructive"
|
||||||
>
|
>
|
||||||
<Trash2 className="h-4 w-4" />
|
<Trash2 className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</li>
|
||||||
))}
|
))}
|
||||||
</div>
|
</ul>
|
||||||
|
{keepLastPasskey && (
|
||||||
|
<p className="text-xs text-muted-foreground">{t("passkey_last_hint")}</p>
|
||||||
)}
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Dialog
|
||||||
|
open={pendingDelete !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open && !deletingPasskey) setPendingDelete(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent hideClose={deletingPasskey}>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{t("passkey_delete_title")}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{pendingDelete &&
|
||||||
|
t("passkey_delete_desc", {
|
||||||
|
name: pendingDelete.name,
|
||||||
|
created: formatAbsolute(pendingDelete.created_at, i18n.language),
|
||||||
|
})}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
{deleteError && <MessageLine kind="error" message={deleteError} />}
|
||||||
|
<ConfirmFooter
|
||||||
|
onCancel={() => setPendingDelete(null)}
|
||||||
|
onConfirm={() => void confirmDeletePasskey()}
|
||||||
|
loading={deletingPasskey}
|
||||||
|
disabled={deletingPasskey || keepLastPasskey}
|
||||||
|
cancelLabel={t("common:cancel")}
|
||||||
|
confirmLabel={t("passkey_delete_confirm")}
|
||||||
|
/>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<MigrationCard
|
<MigrationCard
|
||||||
userId={identity?.user_id}
|
userId={identity?.user_id}
|
||||||
hasPasskey={(passkeys.data?.credentials?.length ?? 0) > 0}
|
hasPasskey={credentials.length > 0}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
|
|||||||
Reference in new issue
Block a user