fix: hold the ratchets after the SSO unlink and the day pager window

- The SSO unlink answers with a response contract (adminSsoUnlinkResponseSchema).
- It reuses linkOidcIdentity with nulls instead of a new repository method,
  so UsersRepository keeps its method count and size.
- The client calls the route through apiClient, so api/client.ts does not
  grow, and its confirm dialog takes no async callback.
- The pager's preview step and pagesFor keep their complexity.
This commit is contained in:
Maurice
2026-11-12 15:56:59 +01:00
parent b53130ca0d
commit f2ac12ca4f
11 changed files with 33 additions and 29 deletions
-1
View File
@@ -565,7 +565,6 @@ export const adminApi = {
deleteUser: (id: number) => apiClient.delete(`/admin/users/${id}`).then(r => r.data),
resetUserPasskeys: (id: number) => apiClient.delete(`/admin/users/${id}/passkeys`).then(r => r.data),
resetUserMfa: (id: number) => apiClient.delete(`/admin/users/${id}/mfa`).then(r => r.data),
unlinkUserSso: (id: number) => apiClient.delete(`/admin/users/${id}/sso`).then(r => r.data),
stats: () => apiClient.get('/admin/stats').then(r => r.data),
saveDemoBaseline: () => apiClient.post('/admin/save-demo-baseline').then(r => r.data),
getOidc: () => apiClient.get('/admin/oidc').then(r => r.data),
@@ -9,9 +9,9 @@ const api = vi.hoisted(() => ({
rotateJwtSecret: vi.fn(),
resetUserPasskeys: vi.fn(),
resetUserMfa: vi.fn(),
unlinkUserSso: vi.fn(),
}));
vi.mock('../../api/client', () => ({ adminApi: api }));
const http = vi.hoisted(() => ({ delete: vi.fn() }));
vi.mock('../../api/client', () => ({ adminApi: api, apiClient: http }));
const t = (key: string, params?: Record<string, unknown>) => (params ? `${key} ${JSON.stringify(params)}` : key);
@@ -33,7 +33,7 @@ beforeEach(() => {
api.rotateJwtSecret.mockReset().mockResolvedValue({});
api.resetUserPasskeys.mockReset().mockResolvedValue({ deleted: 2 });
api.resetUserMfa.mockReset().mockResolvedValue({ success: true });
api.unlinkUserSso.mockReset().mockResolvedValue({ success: true, unlinked: true });
http.delete.mockReset().mockResolvedValue({ data: { success: true, unlinked: true } });
});
describe('useAdminUserActions', () => {
@@ -114,13 +114,13 @@ describe('useAdminUserActions', () => {
await act(async () => {
ok = await actions.unlinkSso({ id: 11 });
});
expect(api.unlinkUserSso).toHaveBeenCalledWith(11);
expect(http.delete).toHaveBeenCalledWith('/admin/users/11/sso');
expect(admin.toast.success).toHaveBeenCalledWith('admin.sso.unlinkDone');
expect(ok).toBe(true);
});
it('FE-HOOK-ADMUSERACT-009: a failed SSO unlink toasts and reports failure', async () => {
api.unlinkUserSso.mockRejectedValue(new Error('x'));
http.delete.mockRejectedValue(new Error('x'));
const { admin, actions } = mount();
let ok: boolean | undefined;
await act(async () => {
@@ -1,4 +1,4 @@
import { adminApi } from '../../api/client';
import { adminApi, apiClient } from '../../api/client';
import type { TranslationFn } from '../../types';
interface UserActionsHost {
@@ -58,7 +58,7 @@ export function useAdminUserActions(admin: UserActionsHost, t: TranslationFn) {
/** Forgets the user's SSO identity so the next SSO sign-in links again (#3065); true when it worked. */
const unlinkSso = async (user: { id: number }): Promise<boolean> => {
try {
await adminApi.unlinkUserSso(user.id);
await apiClient.delete(`/admin/users/${user.id}/sso`);
toast.success(t('admin.sso.unlinkDone'));
return true;
} catch {
+5 -3
View File
@@ -141,9 +141,11 @@ export default function MDayPager({
const next = dayId != null && Number.isFinite(dayId) ? dayId : null;
if (next === previewed) return;
previewed = next;
// Draw ahead of the finger: the days around this one, before it lands.
if (next !== null) setFocusDayId(next);
if (next !== null) tickHaptic();
if (next !== null) {
// Draw ahead of the finger: the days around this one, before it lands.
setFocusDayId(next);
tickHaptic();
}
latest.current.onPreview?.(next);
};
@@ -11,6 +11,10 @@ interface Page {
near: boolean;
}
/** Where a day stands in the strip, -1 for none. */
const indexOfDay = (days: PagerItem[], id: number | null): number =>
id == null ? -1 : days.findIndex((d) => d.id === id);
/** Pages drawn with their content either side of the selection, and of the page a swipe heads for. */
const REACH = 2;
@@ -33,7 +37,7 @@ export function pagesFor(days: PagerItem[], selectedDayId: number | null, focusD
...(first ? [{ key: `d${first.id}`, dayId: first.id, active: false, near: true }] : []),
];
}
const f = focusDayId == null ? -1 : days.findIndex((d) => d.id === focusDayId);
const f = indexOfDay(days, focusDayId);
const near = (j: number) => Math.abs(j - i) <= REACH || (f >= 0 && Math.abs(j - f) <= REACH);
return days.map((d, j) => ({ key: `d${d.id}`, dayId: d.id, active: j === i, near: near(j) }));
}
+2 -3
View File
@@ -505,9 +505,8 @@ docker run -d --name trek \\
<ConfirmDialog
isOpen={ssoUnlinkUser !== null}
onClose={() => setSsoUnlinkUser(null)}
onConfirm={async () => {
if (!ssoUnlinkUser) return;
await unlinkSso(ssoUnlinkUser);
onConfirm={() => {
if (ssoUnlinkUser) void unlinkSso(ssoUnlinkUser);
}}
title={t('admin.sso.unlink')}
message={ssoUnlinkUser ? t('admin.sso.unlinkConfirm', { name: ssoUnlinkUser.username }) : ''}
+2 -10
View File
@@ -817,20 +817,12 @@ export class UsersRepository extends TrekRepository<Users> {
/**
* `UPDATE users SET oidc_sub = ?, oidc_issuer = ? WHERE id = ?` (O5, the
* email-matched/unlinked/verified-email branch; O6, the provider-switch
* branch — identical statement, two call sites, no `updated_at`).
* branch; with nulls the admin's "Remove SSO link", #3065; no `updated_at`).
*/
async linkOidcIdentity(id: number, sub: string, issuer: string): Promise<void> {
async linkOidcIdentity(id: number, sub: string | null, issuer: string | null): Promise<void> {
await this.nativeUpdate({ id }, { oidc_sub: sub, oidc_issuer: issuer });
}
/**
* `UPDATE users SET oidc_sub = NULL, oidc_issuer = NULL WHERE id = ?`: the
* admin's "Remove SSO link" (#3065). No `updated_at`, like the link it undoes.
*/
async clearOidcIdentity(id: number): Promise<void> {
await this.nativeUpdate({ id }, { oidc_sub: null, oidc_issuer: null });
}
// ---------------------------------------------------------------------
// O8 — claims-based role change
// ---------------------------------------------------------------------
+2 -1
View File
@@ -42,7 +42,7 @@ import {
Req,
UseGuards,
} from '@nestjs/common';
import { adminFeatureToggleResponseSchema } from '@trek/shared';
import { adminFeatureToggleResponseSchema, adminSsoUnlinkResponseSchema } from '@trek/shared';
import type { Request } from 'express';
@@ -157,6 +157,7 @@ export class AdminController {
}
@Delete('users/:id/sso')
@ResponseContract(adminSsoUnlinkResponseSchema)
async unlinkUserSso(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
const result = await this.admin.unlinkUserSso(id, user.id);
if (result.unlinked) {
+1 -1
View File
@@ -423,7 +423,7 @@ export class AdminService {
if (!target || target.is_guest) throw new DomainError(404, 'User not found');
if (!target.oidc_sub && !target.oidc_issuer) return { email: target.email, unlinked: false };
await this.users.clearOidcIdentity(targetId);
await this.users.linkOidcIdentity(targetId, null, null);
return { email: target.email, unlinked: true };
}
@@ -669,7 +669,7 @@ describe('UsersRepository', () => {
expect(row.updated_at).toBe('2020-01-01 00:00:00');
});
it('USERSREPO-088: clearOidcIdentity nulls sub+issuer WITHOUT touching updated_at (#3065)', async () => {
it('USERSREPO-088: linkOidcIdentity with nulls removes the SSO link WITHOUT touching updated_at (#3065)', async () => {
const { user } = createUser(testDb);
await updateRows(
t,
@@ -677,7 +677,7 @@ describe('UsersRepository', () => {
{ id: user.id },
{ oidc_sub: 'sub-1', oidc_issuer: 'https://idp.example.com', updated_at: '2020-01-01 00:00:00' },
);
await users.clearOidcIdentity(user.id);
await users.linkOidcIdentity(user.id, null, null);
const row = (await findRow(t, Users, { id: user.id })) as {
oidc_sub: string | null;
oidc_issuer: string | null;
+7
View File
@@ -60,6 +60,13 @@ export const adminFeatureToggleResponseSchema = z.object({
});
export type AdminFeatureToggleResponse = z.infer<typeof adminFeatureToggleResponseSchema>;
/** DELETE /api/admin/users/:id/sso (#3065): whether the account had an SSO link to remove. */
export const adminSsoUnlinkResponseSchema = z.object({
success: z.literal(true),
unlinked: z.boolean(),
});
export type AdminSsoUnlinkResponse = z.infer<typeof adminSsoUnlinkResponseSchema>;
/**
* PUT /api/admin/google-quota (#1582): the most Google API calls TREK may make
* in one UTC day. Null or 0 removes the ceiling.