diff --git a/docs/contributing/adding-capabilities.md b/docs/contributing/adding-capabilities.md index 07ccd46468..a65da51e09 100644 --- a/docs/contributing/adding-capabilities.md +++ b/docs/contributing/adding-capabilities.md @@ -216,6 +216,12 @@ export; feedback status may remain exportable. Current admin capabilities: +User-targeting admin capabilities accept `stableUserId`, email, or username +where operator ergonomics call for lookup. They never accept or return numeric +`users.id`; handlers resolve the stable identity to that internal D1 join key +only after boundary validation. Admin URLs and audit reasons follow the same +rule. + - `admin_user_list` - `admin_user_get` - `admin_user_create` diff --git a/docs/contributing/architecture/authentication.md b/docs/contributing/architecture/authentication.md index f71179fd37..c9617c057f 100644 --- a/docs/contributing/architecture/authentication.md +++ b/docs/contributing/architecture/authentication.md @@ -34,7 +34,8 @@ Session cookie behavior is implemented in The cookie payload stores: -- `id` (user id as string) +- `v: 2` +- `stableUserId` (the authoritative `users.stable_user_id`) - `email` - `issuedAt` (epoch ms when the cookie was issued or last renewed) - `rememberMe` when the login used remember-me @@ -43,6 +44,10 @@ Password reset confirmation writes `users.password_changed_at`. Session resolution rejects cookies whose `issuedAt` is missing or at/before that timestamp, so a reset invalidates every existing browser session. +`users.id` never crosses the cookie boundary. Session resolution looks up the +stable id and only then uses the numeric primary key for internal D1 joins. +Version-1 cookies fail closed and require a fresh login. + `packages/worker/src/app/handler.ts` calls `setAuthSessionSecret` on each request so cookie signing and verification are available to handlers. @@ -353,10 +358,11 @@ signed-in owner requests `/@{username}/packages/{kodyId}/...` on the app origin, the app origin mints `.`: - signed with `COOKIE_SECRET` over a purpose-labelled message - (`kody-package-app-handoff:v1`), so it is not interchangeable with any other + (`kody-package-app-handoff:v2`), so it is not interchangeable with any other signed value -- payload binds `{ userId, username, kodyId, exp, jti }`; the package-app origin - rejects a token whose `username`/`kodyId` do not match the requested path +- payload binds `{ stableUserId, username, kodyId, exp, jti }`; the package-app + origin rejects a token whose `username`/`kodyId` do not match the requested + path - 60 second lifetime - single use: `jti` is burned in `BUNDLE_ARTIFACTS_KV` for 60 seconds on first use. The burn happens **after** the path binding is checked, so a token @@ -381,16 +387,17 @@ sets `kody_pkg_session` on the package-app origin: - `httpOnly: true`, `sameSite: 'Lax'`, `path: '/'`, `secure` per request - 12 hour max age - signed with a **derived** secret, - `sha256Base64Url('kody-package-app-session:v1:' + COOKIE_SECRET)`, so a value + `sha256Base64Url('kody-package-app-session:v2:' + COOKIE_SECRET)`, so a value signed for this cookie can never verify as a `kody_session` -- payload is `{ v, pkgUserId, pkgUsername, issuedAt }` — a shape the app session - schema rejects, so the two cannot be confused even by name substitution +- payload is `{ v, stableUserId, pkgUsername, issuedAt }` — a shape the app + session schema rejects, so the two cannot be confused even by name + substitution It authorizes hosted package-app serving for one account and nothing else: the app origin has no code path that reads it, and the package-app origin has no first-party routes. Every request re-resolves the account from D1 -(`resolvePackageAppOwnerByUserId`) and fails closed for unknown, deleting, or -suspended accounts, and for sessions issued at or before +(`resolvePackageAppOwnerByStableUserId`) and fails closed for unknown, deleting, +or suspended accounts, and for sessions issued at or before `users.password_changed_at` — the same rules browser sessions follow. Deployments with `PACKAGE_APP_BASE_URL` unset never mint either credential; they serve package apps inline behind `kody_session`. diff --git a/e2e/admin-rbac.spec.ts b/e2e/admin-rbac.spec.ts index 6112238635..79f4d48af6 100644 --- a/e2e/admin-rbac.spec.ts +++ b/e2e/admin-rbac.spec.ts @@ -30,7 +30,7 @@ test('admin RBAC controls access, role assignment, and privacy boundaries', asyn await expect(page.getByRole('heading', { name: 'Admin users' })).toBeHidden() await expect(page.getByText('Forbidden')).toBeVisible() const memberUsageResponse = await page.request.get( - '/admin/users/usage.json?userId=1', + '/admin/users/usage.json?stableUserId=forbidden', ) expect(memberUsageResponse.status()).toBe(403) await page.goto('/admin/insights') @@ -146,12 +146,12 @@ test('admin RBAC controls access, role assignment, and privacy boundaries', asyn expect(memberRecord.plan).toBe('free') expect(JSON.stringify(memberRecord)).not.toContain('memberPrivateSecret') expect(JSON.stringify(memberRecord)).not.toContain('super-secret-value') - const memberId = Number(memberRecord.id) + const memberStableUserId = String(memberRecord.stableUserId) // URL-backed selection: click updates the path, reload restores it, and a // detail pane opens that account (use the non-first seeded user). await page.getByRole('button', { name: memberUser.username }).click() - await expect(page).toHaveURL(new RegExp(`/admin/users/${memberId}`)) + await expect(page).toHaveURL(new RegExp(`/admin/users/${memberStableUserId}`)) await expect(page.getByText('Account metadata only')).toBeVisible() await expect(page.getByText('Usage & quotas')).toBeVisible() await expect( @@ -161,7 +161,7 @@ test('admin RBAC controls access, role assignment, and privacy boundaries', asyn page.getByRole('heading', { name: 'Entitlements' }), ).toBeVisible() await page.reload() - await expect(page).toHaveURL(new RegExp(`/admin/users/${memberId}`)) + await expect(page).toHaveURL(new RegExp(`/admin/users/${memberStableUserId}`)) await expect( page.getByRole('heading', { name: memberUser.username, exact: true }), ).toBeVisible() @@ -169,12 +169,12 @@ test('admin RBAC controls access, role assignment, and privacy boundaries', asyn await expect(page.getByText('memberPrivateSecret')).toHaveCount(0) await expect(page.getByText('super-secret-value')).toHaveCount(0) const usageApiResponse = await page.request.get( - `/admin/users/usage.json?userId=${memberId}`, + `/admin/users/usage.json?stableUserId=${memberStableUserId}`, ) expect(usageApiResponse.ok()).toBe(true) const usagePayload = await usageApiResponse.json() expect(usagePayload.ok).toBe(true) - expect(usagePayload.userId).toBe(memberId) + expect(usagePayload.stableUserId).toBe(memberStableUserId) expect(JSON.stringify(usagePayload)).not.toContain('memberPrivateSecret') expect(JSON.stringify(usagePayload)).not.toContain('super-secret-value') expect(JSON.stringify(usagePayload)).not.toContain(memberUser.email) diff --git a/packages/worker/client/routes/admin-feature-flags.tsx b/packages/worker/client/routes/admin-feature-flags.tsx index fa14846bd8..cfe132f31b 100644 --- a/packages/worker/client/routes/admin-feature-flags.tsx +++ b/packages/worker/client/routes/admin-feature-flags.tsx @@ -419,9 +419,9 @@ export function AdminFeatureFlagsRoute(handle: Handle) { { label: 'Updated by', value: - flag.global.updatedBy == null + flag.global.updatedByStableUserId == null ? 'Unknown' - : String(flag.global.updatedBy), + : flag.global.updatedByStableUserId, }, { label: 'Note', @@ -448,7 +448,7 @@ export function AdminFeatureFlagsRoute(handle: Handle) {
{flag.overrides.map((override) => (
({ mergeDirection: 'append', - getKey: (user) => String(user.id), + getKey: (user) => user.stableUserId, onSnapshot: (snapshot) => { usersSnapshot = snapshot }, @@ -194,7 +190,7 @@ export function AdminUsersRoute(handle: Handle) { // Draft follows the selected user (see the render body) until the admin // edits it. Null stored plan values are shown/saved as `free`. let selectedPlanChoice: AdminPlanName = 'free' - let planDraftUserId: number | null = null + let planDraftStableUserId: string | null = null let loadRequestId = 0 let lastLoadedDataKey = '' let lastLoadedListKey = '' @@ -204,24 +200,26 @@ export function AdminUsersRoute(handle: Handle) { let usageData: AdminUserUsageLoaderData | null = null let usageMessage: string | null = null let usageRequestId = 0 - let usageLoadedForUserId: number | null = null - let usageLoadingForUserId: number | null = null - let usageFailedForUserId: number | null = null + let usageLoadedForStableUserId: string | null = null + let usageLoadingForStableUserId: string | null = null + let usageFailedForStableUserId: string | null = null function getCurrentHref() { return readCurrentRouterHref(handle) } - function getSelectedUserIdFromHref(href: string) { - return parseSelectedUserId(getSelection(href).selectedId) + function getSelectedStableUserIdFromHref(href: string) { + return parseSelectedStableUserId(getSelection(href).selectedId) } function resolveSelectedUser(href: string) { - const selectedUserId = getSelectedUserIdFromHref(href) - if (selectedUserId == null) return null + const selectedStableUserId = getSelectedStableUserIdFromHref(href) + if (selectedStableUserId == null) return null return ( - usersSnapshot.items.find((user) => user.id === selectedUserId) ?? - (selectedUserFallback?.id === selectedUserId + usersSnapshot.items.find( + (user) => user.stableUserId === selectedStableUserId, + ) ?? + (selectedUserFallback?.stableUserId === selectedStableUserId ? selectedUserFallback : null) ) @@ -250,7 +248,7 @@ export function AdminUsersRoute(handle: Handle) { selectedUserFallback = payload.selectedUser resetPlanDraft() message = - getSelectedUserIdFromHref(href) != null && !payload.selectedUser + getSelectedStableUserIdFromHref(href) != null && !payload.selectedUser ? 'User not found.' : null status = 'ready' @@ -272,18 +270,18 @@ export function AdminUsersRoute(handle: Handle) { return `${url.pathname}${url.search}` } - function buildUserDetailHref(userId: number) { + function buildUserDetailHref(stableUserId: string) { const url = new URL(getCurrentHref(), 'http://localhost') url.searchParams.delete('page') - return buildDetailHref(String(userId), url.search) + return buildDetailHref(stableUserId, url.search) } - async function loadUserUsage(userId: number) { - usageLoadingForUserId = userId + async function loadUserUsage(stableUserId: string) { + usageLoadingForStableUserId = stableUserId const requestId = ++usageRequestId try { const response = await fetch( - `${adminUserUsageApiPath}?userId=${userId}`, + `${adminUserUsageApiPath}?stableUserId=${stableUserId}`, { headers: { Accept: 'application/json' }, credentials: 'include' }, ) if (requestId !== usageRequestId) return @@ -298,8 +296,8 @@ export function AdminUsersRoute(handle: Handle) { usageData = payload usageStatus = 'ready' usageMessage = null - usageLoadedForUserId = userId - usageFailedForUserId = null + usageLoadedForStableUserId = stableUserId + usageFailedForStableUserId = null handle.update() } catch (error) { if (requestId !== usageRequestId) return @@ -308,10 +306,10 @@ export function AdminUsersRoute(handle: Handle) { error instanceof Error ? error.message : 'Unable to load usage for this account.' - usageFailedForUserId = userId + usageFailedForStableUserId = stableUserId handle.update() } finally { - if (requestId === usageRequestId) usageLoadingForUserId = null + if (requestId === usageRequestId) usageLoadingForStableUserId = null } } @@ -320,15 +318,15 @@ export function AdminUsersRoute(handle: Handle) { // keeps stale limits from rendering while the refetch is in flight. function invalidateUsage() { usageData = null - usageLoadedForUserId = null - usageFailedForUserId = null + usageLoadedForStableUserId = null + usageFailedForStableUserId = null } // Any refresh of `users` may carry a newer stored plan, so drop the // unsaved draft and let the render pass reseed the select from the // refreshed record. function resetPlanDraft() { - planDraftUserId = null + planDraftStableUserId = null } async function loadAdminUsers() { @@ -442,9 +440,11 @@ export function AdminUsersRoute(handle: Handle) { const nextItems = updatedUser ? matchesRoleFilter ? currentItems.map((item) => - item.id === updatedUser.id ? updatedUser : item, + item.stableUserId === updatedUser.stableUserId ? updatedUser : item, + ) + : currentItems.filter( + (item) => item.stableUserId !== updatedUser.stableUserId, ) - : currentItems.filter((item) => item.id !== updatedUser.id) : currentItems // reset() invalidates any in-flight load-more so a page fetched before // the mutation cannot merge stale rows or counts back in afterward. @@ -454,12 +454,12 @@ export function AdminUsersRoute(handle: Handle) { hasMore: nextItems.length < payload.total, totalCount: payload.total, }) - const selectedUserId = getSelectedUserIdFromHref(href) + const selectedStableUserId = getSelectedStableUserIdFromHref(href) selectedUserFallback = payload.selectedUser ?? (updatedUser && - selectedUserId != null && - updatedUser.id === selectedUserId + selectedStableUserId != null && + updatedUser.stableUserId === selectedStableUserId ? updatedUser : selectedUserFallback) resetPlanDraft() @@ -484,7 +484,7 @@ export function AdminUsersRoute(handle: Handle) { credentials: 'include', body: JSON.stringify({ action, - userId: selectedUser.id, + stableUserId: selectedUser.stableUserId, role: selectedRoleToAssign, }), }) @@ -535,7 +535,7 @@ export function AdminUsersRoute(handle: Handle) { credentials: 'include', body: JSON.stringify({ action: 'update_plan', - userId: selectedUser.id, + stableUserId: selectedUser.stableUserId, plan, }), }) @@ -585,7 +585,7 @@ export function AdminUsersRoute(handle: Handle) { credentials: 'include', body: JSON.stringify({ action, - userId: selectedUser.id, + stableUserId: selectedUser.stableUserId, }), }) if (response.status === 401) { @@ -662,26 +662,28 @@ export function AdminUsersRoute(handle: Handle) { const { items: users, hasMore, totalCount, isLoadingMore } = usersSnapshot const filters = readFilterState(currentHref) const hasActiveFilters = Boolean(filters.search || filters.role) - const selectedUserId = getSelectedUserIdFromHref(currentHref) + const selectedStableUserId = getSelectedStableUserIdFromHref(currentHref) const selectedUser = resolveSelectedUser(currentHref) const isMutating = actionState !== 'idle' if ( selectedUser && typeof document !== 'undefined' && - usageLoadedForUserId !== selectedUser.id && - usageLoadingForUserId !== selectedUser.id && - usageFailedForUserId !== selectedUser.id + usageLoadedForStableUserId !== selectedUser.stableUserId && + usageLoadingForStableUserId !== selectedUser.stableUserId && + usageFailedForStableUserId !== selectedUser.stableUserId ) { usageStatus = 'loading' - usageLoadingForUserId = selectedUser.id - const usageUserId = selectedUser.id - handle.queueTask(() => loadUserUsage(usageUserId)) + usageLoadingForStableUserId = selectedUser.stableUserId + const usageStableUserId = selectedUser.stableUserId + handle.queueTask(() => loadUserUsage(usageStableUserId)) } // Never render one account's usage under another account's header // while the drill-down request is still in flight. const selectedUsage = - selectedUser && usageData && usageData.userId === selectedUser.id + selectedUser && + usageData && + usageData.stableUserId === selectedUser.stableUserId ? usageData : null const usageMonthsAscending = selectedUsage @@ -690,8 +692,8 @@ export function AdminUsersRoute(handle: Handle) { // Re-seed the plan draft whenever a different user becomes selected so // the select always starts from that user's stored plan. - if (selectedUser && selectedUser.id !== planDraftUserId) { - planDraftUserId = selectedUser.id + if (selectedUser && selectedUser.stableUserId !== planDraftStableUserId) { + planDraftStableUserId = selectedUser.stableUserId selectedPlanChoice = selectedUser.plan ?? 'free' } @@ -766,13 +768,13 @@ export function AdminUsersRoute(handle: Handle) { <> {users.map((user) => ( -
  • +
  • { if (isMutating) return - navigate(buildUserDetailHref(user.id)) + navigate(buildUserDetailHref(user.stableUserId)) }} > @@ -873,7 +875,10 @@ export function AdminUsersRoute(handle: Handle) { ? (selectedUser.email_verified_at ?? 'Verified') : 'No', }, - { label: 'User id', value: String(selectedUser.id) }, + { + label: 'Stable user id', + value: selectedUser.stableUserId, + }, { label: 'Roles', value: @@ -1090,7 +1095,7 @@ export function AdminUsersRoute(handle: Handle) {

    ) : null} {usageStatus === 'error' && - usageFailedForUserId === selectedUser.id && + usageFailedForStableUserId === selectedUser.stableUserId && usageMessage ? ( {usageMessage} diff --git a/packages/worker/src/admin/user-usage-data.node.test.ts b/packages/worker/src/admin/user-usage-data.node.test.ts index 611c9f310f..b7e91e8228 100644 --- a/packages/worker/src/admin/user-usage-data.node.test.ts +++ b/packages/worker/src/admin/user-usage-data.node.test.ts @@ -91,10 +91,10 @@ function createAdminUserUsageTestDb(input: { async first() { if ( normalizedQuery.includes( - 'select id, username, email, plan, stripe_plan, stable_user_id from users where id = ?', + 'select id, username, email, plan, stripe_plan, stable_user_id from users where stable_user_id = ?', ) ) { - return (users.find((user) => user.id === Number(params[0])) ?? + return (users.find((user) => user.stable_user_id === params[0]) ?? null) as T | null } if (normalizedQuery.includes('from entitlement_daily_counters')) { @@ -162,7 +162,7 @@ test('loadAdminUserUsageData returns null for unknown users and zeroed usage for expect( await loadAdminUserUsageData( { APP_DB: emptyDb } as Env, - 42, + 'missing-stable-user', new Date('2026-07-05T12:00:00.000Z'), ), ).toBeNull() @@ -186,13 +186,13 @@ test('loadAdminUserUsageData returns null for unknown users and zeroed usage for const data = await loadAdminUserUsageData( { APP_DB: db } as Env, - 1, + usageUserId, new Date('2026-07-05T12:00:00.000Z'), ) expect(data?.currentMonth).toBe('2026-07') expect(data?.today).toBe('2026-07-05') - expect(data?.userId).toBe(1) + expect(data?.stableUserId).toBe(usageUserId) expect(data?.currentMonthUsage.every((row) => row.eventCount === 0)).toBe( true, ) @@ -255,11 +255,11 @@ test('loadAdminUserUsageData warns above eighty percent of plan limits', async ( const data = await loadAdminUserUsageData( { APP_DB: db } as Env, - 2, + usageUserId, new Date('2026-07-05T12:00:00.000Z'), ) - expect(data?.userId).toBe(2) + expect(data?.stableUserId).toBe(usageUserId) expect(getEventCount(data?.currentMonthUsage, 'job_run')).toBe(4) expect(data?.monthUsage.map((month) => month.month)).toEqual([ '2026-07', @@ -300,7 +300,7 @@ test('loadAdminUserUsageData rejects an invalid stored plan', async () => { await expect( loadAdminUserUsageData( { APP_DB: db } as Env, - 1, + usageUserId, new Date('2026-07-05T12:00:00.000Z'), ), ).rejects.toThrow('Stored plan is not a registered plan name.') @@ -364,7 +364,7 @@ test('loadAdminUserUsageData caches rollup reads in KV and serves repeat loads f const env = { APP_DB: countingDb, BUNDLE_ARTIFACTS_KV: kv } as Env const now = new Date('2026-07-05T12:00:00.000Z') - const first = await loadAdminUserUsageData(env, 1, now) + const first = await loadAdminUserUsageData(env, usageUserId, now) expect(getEventCount(first?.currentMonthUsage, 'execute')).toBe(7) const queriesAfterFirstLoad = rollupQueryCount expect(queriesAfterFirstLoad).toBeGreaterThan(0) @@ -373,7 +373,7 @@ test('loadAdminUserUsageData caches rollup reads in KV and serves repeat loads f expect(key.startsWith('derived-cache:v1:usage-rollups:')).toBe(true) } - const second = await loadAdminUserUsageData(env, 1, now) + const second = await loadAdminUserUsageData(env, usageUserId, now) expect(getEventCount(second?.currentMonthUsage, 'execute')).toBe(7) expect(second?.monthUsage[0]?.month).toBe('2026-07') // The repeat load is served from KV: no additional rollup queries. @@ -414,7 +414,7 @@ test('loadAdminUserUsageData keeps current-month and month-over-month rollups on const data = await loadAdminUserUsageData( { APP_DB: db } as Env, - 1, + usageUserId, new Date('2026-07-01T00:00:00.000Z'), ) diff --git a/packages/worker/src/admin/user-usage-data.ts b/packages/worker/src/admin/user-usage-data.ts index aa8b694d6d..9a1c29deea 100644 --- a/packages/worker/src/admin/user-usage-data.ts +++ b/packages/worker/src/admin/user-usage-data.ts @@ -82,13 +82,13 @@ type AdminUsageRollupRow = { */ export async function loadAdminUserUsageData( env: Env, - userId: number, + stableUserId: string, now: Date = new Date(), ): Promise { const row = await env.APP_DB.prepare( - `SELECT id, username, email, plan, stripe_plan, stable_user_id FROM users WHERE id = ?`, + `SELECT id, username, email, plan, stripe_plan, stable_user_id FROM users WHERE stable_user_id = ?`, ) - .bind(userId) + .bind(stableUserId) .first() if (!row) return null @@ -127,7 +127,7 @@ export async function loadAdminUserUsageData( return { ok: true, - userId: row.id, + stableUserId: usageUserId, username: row.username, plan, currentMonth, diff --git a/packages/worker/src/admin/users-data.ts b/packages/worker/src/admin/users-data.ts index 755163b4e9..e9120f535c 100644 --- a/packages/worker/src/admin/users-data.ts +++ b/packages/worker/src/admin/users-data.ts @@ -15,9 +15,10 @@ import { chunkArray, maxD1BoundParameters, } from '@kody-internal/shared/chunk.ts' +import { isStableUserId, normalizeStableUserId } from '#worker/user-id.ts' export const adminUserListItemFieldNames = [ - 'id', + 'stableUserId', 'username', 'email', 'email_verified', @@ -34,7 +35,7 @@ export type AdminUserListItemFieldName = (typeof adminUserListItemFieldNames)[number] export type AdminUserListItem = Record & { - id: number + stableUserId: string username: string email: string email_verified: boolean @@ -57,15 +58,15 @@ type AdminUserListFilters = { } /** - * Resolve the selected account id from an HTML path param, a detail + * Resolve the selected account's stable id from an HTML path param, a detail * pathname, or the JSON API's `?selected=` query (in that order). Invalid - * / non-numeric values yield null so the client can show "User not found." + * values yield null so the client can show "User not found." */ -export function readAdminUsersSelectedUserId( +export function readAdminUsersSelectedStableUserId( requestUrl: string, - pathUserId?: string, -): number | null { - const fromPathParam = parseSelectedUserId(pathUserId) + pathStableUserId?: string, +): string | null { + const fromPathParam = parseSelectedStableUserId(pathStableUserId) if (fromPathParam != null) return fromPathParam const url = new URL(requestUrl, 'http://localhost') @@ -73,12 +74,12 @@ export function readAdminUsersSelectedUserId( if (url.pathname.startsWith(detailPrefix)) { const segment = decodePathSegment(url.pathname.slice(detailPrefix.length)) if (segment && !segment.includes('/')) { - const fromPath = parseSelectedUserId(segment) + const fromPath = parseSelectedStableUserId(segment) if (fromPath != null) return fromPath } } - return parseSelectedUserId(url.searchParams.get('selected')) + return parseSelectedStableUserId(url.searchParams.get('selected')) } function decodePathSegment(value: string) { @@ -86,20 +87,16 @@ function decodePathSegment(value: string) { return decodeURIComponent(value) } catch { // Malformed percent-encoding (e.g. a literal `%`) must not throw; - // the raw segment simply fails numeric parsing below. + // the raw segment simply fails stable-id parsing below. return value } } -function parseSelectedUserId(value: string | null | undefined): number | null { - if (!value?.trim()) return null - const trimmed = value.trim() - const parsed = Number.parseInt(trimmed, 10) - if (!Number.isFinite(parsed) || parsed < 1) return null - // Reject leftovers like "12abc" / "usage.json" so only pure numeric ids - // resolve; unknown ids still load as null from the database below. - if (String(parsed) !== trimmed) return null - return parsed +function parseSelectedStableUserId( + value: string | null | undefined, +): string | null { + const stableUserId = normalizeStableUserId(value) + return isStableUserId(stableUserId) ? stableUserId : null } /** Read the `q` and `role` filter query params shared by the page and API. */ @@ -143,7 +140,7 @@ function buildAdminUserListWhereClause(filters: AdminUserListFilters) { export async function loadAdminUsersData( env: Env, requestUrl: string, - pathUserId?: string, + pathStableUserId?: string, ): Promise { const url = new URL(requestUrl, 'http://localhost') const { page, pageSize, offset } = readPagination(url, { @@ -152,14 +149,17 @@ export async function loadAdminUsersData( }) const filters = readAdminUserListFilters(url) const { whereClause, params } = buildAdminUserListWhereClause(filters) - const selectedUserId = readAdminUsersSelectedUserId(requestUrl, pathUserId) + const selectedStableUserId = readAdminUsersSelectedStableUserId( + requestUrl, + pathStableUserId, + ) const [totalResult, userRows, selectedUser] = await Promise.all([ env.APP_DB.prepare(`SELECT COUNT(*) AS total FROM users ${whereClause}`) .bind(...params) .first<{ total: number }>(), env.APP_DB.prepare( - `SELECT id, username, email, email_verified_at, plan, suspended_at, + `SELECT id, stable_user_id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at FROM users ${whereClause} @@ -168,8 +168,10 @@ export async function loadAdminUsersData( ) .bind(...params, pageSize, offset) .all(), - selectedUserId - ? loadAdminUserByIdOrEmail(env.APP_DB, { id: selectedUserId }) + selectedStableUserId + ? loadAdminUserByTarget(env.APP_DB, { + stableUserId: selectedStableUserId, + }) : Promise.resolve(null), ]) const total = totalResult?.total ?? 0 @@ -191,32 +193,53 @@ export async function loadAdminUsersData( } } -export async function loadAdminUserByIdOrEmail( +export type AdminUserTarget = { + stableUserId?: string + email?: string + username?: string +} + +export async function loadAdminUserByTarget( db: D1Database, - input: { id?: number; email?: string }, + input: AdminUserTarget, ): Promise { + const stableUserId = normalizeStableUserId(input.stableUserId) const email = input.email?.trim() ?? '' - const userRow = input.id + const username = input.username?.trim() ?? '' + if (input.stableUserId !== undefined && !isStableUserId(stableUserId)) { + return null + } + const userRow = stableUserId ? await db .prepare( - `SELECT id, username, email, email_verified_at, plan, suspended_at, + `SELECT id, stable_user_id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at FROM users - WHERE id = ?`, + WHERE stable_user_id = ?`, ) - .bind(input.id) + .bind(stableUserId) .first() : email ? await db .prepare( - `SELECT id, username, email, email_verified_at, plan, suspended_at, + `SELECT id, stable_user_id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at FROM users WHERE email = ? COLLATE NOCASE`, ) .bind(email) .first() - : null + : username + ? await db + .prepare( + `SELECT id, stable_user_id, username, email, email_verified_at, plan, suspended_at, + email_outbound_paused_at, created_at, updated_at + FROM users + WHERE username = ? COLLATE NOCASE`, + ) + .bind(username) + .first() + : null if (!userRow) return null const rolesByUserId = await loadRolesByUserIds(db, [userRow.id]) @@ -226,21 +249,26 @@ export async function loadAdminUserByIdOrEmail( /** * Set the entitlement plan on one user account. Nullish inputs map to `free`, * the normal default plan; writers never persist NULL. Returns the updated - * account metadata record, or null when no user matches `id`/`email`. + * account metadata record, or null when no user matches the target. */ export async function updateAdminUserPlan( db: D1Database, - input: { id?: number; email?: string; plan: PlanName | null }, + input: AdminUserTarget & { plan: PlanName | null }, ): Promise { - const existing = await loadAdminUserByIdOrEmail(db, input) + const existing = await loadAdminUserByTarget(db, input) if (!existing) return null + const existingRow = await loadAdminUserRowByStableUserId( + db, + existing.stableUserId, + ) + if (!existingRow) return null await db .prepare(`UPDATE users SET plan = ?, updated_at = ? WHERE id = ?`) - .bind(resolvePlanWrite(input.plan), utcSqliteTimestamp(), existing.id) + .bind(resolvePlanWrite(input.plan), utcSqliteTimestamp(), existingRow.id) .run() - return loadAdminUserByIdOrEmail(db, { id: existing.id }) + return loadAdminUserByTarget(db, { stableUserId: existing.stableUserId }) } /** @@ -251,9 +279,9 @@ export async function updateAdminUserPlan( */ export async function updateAdminUserSuspension( db: D1Database, - input: { id: number; suspended: boolean }, + input: { stableUserId: string; suspended: boolean }, ): Promise { - const existing = await loadAdminUserByIdOrEmail(db, { id: input.id }) + const existing = await loadAdminUserRowByStableUserId(db, input.stableUserId) if (!existing) return null const now = utcSqliteTimestamp() @@ -262,7 +290,7 @@ export async function updateAdminUserSuspension( .bind(input.suspended ? now : null, now, existing.id) .run() - return loadAdminUserByIdOrEmail(db, { id: existing.id }) + return loadAdminUserByTarget(db, { stableUserId: input.stableUserId }) } /** @@ -272,9 +300,9 @@ export async function updateAdminUserSuspension( */ export async function clearAdminUserEmailOutboundPause( db: D1Database, - input: { id: number }, + input: { stableUserId: string }, ): Promise { - const existing = await loadAdminUserByIdOrEmail(db, { id: input.id }) + const existing = await loadAdminUserRowByStableUserId(db, input.stableUserId) if (!existing) return null await db @@ -284,7 +312,7 @@ export async function clearAdminUserEmailOutboundPause( .bind(utcSqliteTimestamp(), existing.id) .run() - return loadAdminUserByIdOrEmail(db, { id: existing.id }) + return loadAdminUserByTarget(db, { stableUserId: input.stableUserId }) } export async function loadRolesByUserIds( @@ -324,6 +352,7 @@ export async function loadRolesByUserIds( type AdminUserRow = { id: number + stable_user_id: string username: string email: string email_verified_at: string | null @@ -339,7 +368,7 @@ function toAdminUserListItem( roles: Array, ): AdminUserListItem { return { - id: row.id, + stableUserId: row.stable_user_id, username: row.username, email: row.email, email_verified: Boolean(row.email_verified_at), @@ -353,6 +382,22 @@ function toAdminUserListItem( } } +export async function loadAdminUserRowByStableUserId( + db: D1Database, + stableUserId: string, +): Promise { + if (!isStableUserId(stableUserId)) return null + return await db + .prepare( + `SELECT id, stable_user_id, username, email, email_verified_at, plan, suspended_at, + email_outbound_paused_at, created_at, updated_at + FROM users + WHERE stable_user_id = ?`, + ) + .bind(stableUserId) + .first() +} + function isRoleName(value: string): value is RoleName { return (roleNames as ReadonlyArray).includes(value) } diff --git a/packages/worker/src/app/admin-invites-data.ts b/packages/worker/src/app/admin-invites-data.ts index 7404121ff7..f653619604 100644 --- a/packages/worker/src/app/admin-invites-data.ts +++ b/packages/worker/src/app/admin-invites-data.ts @@ -3,7 +3,7 @@ import { parseStoredPlanName, planNames } from '#worker/entitlements/plans.ts' type InviteRow = { code: string - created_by: number | null + created_by_stable_user_id: string | null created_by_email: string | null note: string max_uses: number @@ -19,7 +19,7 @@ export async function loadAdminInvitesData( ): Promise { const result = await env.APP_DB.prepare( `SELECT i.code, - i.created_by, + u.stable_user_id AS created_by_stable_user_id, u.email AS created_by_email, i.note, i.max_uses, @@ -38,7 +38,7 @@ export async function loadAdminInvitesData( ok: true, invites: (result.results ?? []).map((row) => ({ code: row.code, - createdBy: row.created_by, + createdByStableUserId: row.created_by_stable_user_id, createdByEmail: row.created_by_email, note: row.note, maxUses: row.max_uses, diff --git a/packages/worker/src/app/auth-redirect.node.test.ts b/packages/worker/src/app/auth-redirect.node.test.ts index 6eff71c8f5..8e8639c6ff 100644 --- a/packages/worker/src/app/auth-redirect.node.test.ts +++ b/packages/worker/src/app/auth-redirect.node.test.ts @@ -65,7 +65,7 @@ test('redirectToLogin attaches Set-Cookie when provided', async () => { test('redirectToLoginWhenUnauthenticated clears a stale session cookie', async () => { setAuthSessionSecret(testCookieSecret) const session: AuthSession = { - id: '99', + stableUserId: 'f'.repeat(64), email: 'missing@example.com', rememberMe: false, } diff --git a/packages/worker/src/app/auth-session.node.test.ts b/packages/worker/src/app/auth-session.node.test.ts index 19377ff7a4..9766d8a6ec 100644 --- a/packages/worker/src/app/auth-session.node.test.ts +++ b/packages/worker/src/app/auth-session.node.test.ts @@ -1,4 +1,5 @@ import { expect, test } from 'vitest' +import { createCookie } from '@remix-run/cookie' import { createAuthCookie, isAuthSessionInvalidatedByPasswordChange, @@ -13,7 +14,11 @@ test('createAuthCookie stamps issuedAt for password-change invalidation', async setAuthSessionSecret(testCookieSecret) const now = 1_700_000_000_000 const cookie = await createAuthCookie( - { id: '1', email: 'user@example.com', rememberMe: false }, + { + stableUserId: '1'.repeat(64), + email: 'user@example.com', + rememberMe: false, + }, false, now, ) @@ -25,6 +30,29 @@ test('createAuthCookie stamps issuedAt for password-change invalidation', async expect(parsed?.session.rememberMe).toBe(false) }) +test('legacy numeric-id session cookies fail closed', async () => { + setAuthSessionSecret(testCookieSecret) + const legacyCookie = createCookie('kody_session', { + httpOnly: true, + sameSite: 'Lax', + path: '/', + secrets: [testCookieSecret], + }) + const cookie = await legacyCookie.serialize( + JSON.stringify({ + id: '42', + email: 'user@example.com', + rememberMe: false, + issuedAt: Date.now(), + }), + ) + const request = new Request('https://example.com/', { + headers: { Cookie: cookie.split(';')[0]! }, + }) + + await expect(readParsedAuthSession(request)).resolves.toBeNull() +}) + test('password-change invalidation covers legacy cookies, second-precision SQLite, and re-login', () => { expect(parsePasswordChangedAtMs(null)).toBeNull() expect(parsePasswordChangedAtMs('')).toBeNull() diff --git a/packages/worker/src/app/auth-session.ts b/packages/worker/src/app/auth-session.ts index d5a19e62be..f343bee939 100644 --- a/packages/worker/src/app/auth-session.ts +++ b/packages/worker/src/app/auth-session.ts @@ -1,17 +1,19 @@ import { createCookie } from '@remix-run/cookie' +import { isStableUserId } from '#worker/user-id.ts' const defaultSessionMaxAgeSeconds = 60 * 60 * 24 * 7 const rememberedSessionMaxAgeSeconds = 60 * 60 * 24 * 30 const rememberedSessionRenewAfterMs = 1000 * 60 * 60 * 24 * 14 export type AuthSession = { - id: string + stableUserId: string email: string rememberMe: boolean } type StoredAuthSession = { - id: string + v: 2 + stableUserId: string email: string rememberMe?: boolean issuedAt?: number @@ -62,8 +64,8 @@ function isStoredAuthSession(value: unknown): value is StoredAuthSession { if (!value || typeof value !== 'object') return false const record = value as Record return ( - typeof record.id === 'string' && - record.id.length > 0 && + record.v === 2 && + isStableUserId(record.stableUserId) && typeof record.email === 'string' && record.email.length > 0 && (record.rememberMe === undefined || @@ -88,7 +90,8 @@ function createStoredAuthSession( // Always stamp issuedAt so password resets can invalidate every browser // session, not only remember-me cookies. return { - id: session.id, + v: 2, + stableUserId: session.stableUserId, email: session.email, rememberMe: session.rememberMe ? true : undefined, issuedAt: now, @@ -111,7 +114,7 @@ export function isAuthSessionInvalidatedByPasswordChange(input: { function normalizeAuthSession(session: StoredAuthSession): AuthSession { return { - id: session.id, + stableUserId: session.stableUserId, email: session.email, rememberMe: session.rememberMe === true, } diff --git a/packages/worker/src/app/authenticated-user.node.test.ts b/packages/worker/src/app/authenticated-user.node.test.ts index 0ea0df35b4..40081170ed 100644 --- a/packages/worker/src/app/authenticated-user.node.test.ts +++ b/packages/worker/src/app/authenticated-user.node.test.ts @@ -26,11 +26,11 @@ test('readAuthenticatedAppUser only requires the session cookie secret from env' expect(user).toBeNull() }) -test('readAuthenticatedAppUser rejects partially numeric session ids', async () => { +test('readAuthenticatedAppUser rejects unknown stable user ids', async () => { setAuthSessionSecret(testCookieSecret) const cookie = await createAuthCookie( { - id: '1abc', + stableUserId: 'f'.repeat(64), email: 'user@example.com', rememberMe: false, } satisfies AuthSession, @@ -55,7 +55,17 @@ test('readAuthenticatedAppUser rejects partially numeric session ids', async () function createAuthenticatedUserTestDb() { return { prepare() { - throw new Error('Malformed session id should not query users.') + return { + bind() { + return this + }, + async first() { + return null + }, + async all() { + return { results: [] } + }, + } }, async exec() { return @@ -67,7 +77,7 @@ test('readAuthenticatedAppUser fails closed to empty roles when the rbac query e setAuthSessionSecret(testCookieSecret) const cookie = await createAuthCookie( { - id: '7', + stableUserId: testStableUserIdFromEmail('user@example.com'), email: 'user@example.com', rememberMe: false, } satisfies AuthSession, @@ -135,7 +145,7 @@ test('deleting accounts are invalid for normal requests but can retry deletion', setAuthSessionSecret(testCookieSecret) const cookie = await createAuthCookie( { - id: '7', + stableUserId: testStableUserIdFromEmail('user@example.com'), email: 'user@example.com', rememberMe: false, } satisfies AuthSession, diff --git a/packages/worker/src/app/email-change.ts b/packages/worker/src/app/email-change.ts index 40807a790b..765074f10f 100644 --- a/packages/worker/src/app/email-change.ts +++ b/packages/worker/src/app/email-change.ts @@ -144,7 +144,13 @@ export async function createEmailChangeVerification(input: { } export type VerifyEmailChangeResult = - | { ok: true; userId: number; oldEmail: string; newEmail: string } + | { + ok: true + userId: number + stableUserId: string + oldEmail: string + newEmail: string + } | { ok: false reason: @@ -233,6 +239,7 @@ export async function verifyEmailChangeToken(input: { return { ok: true, userId: record.user_id, + stableUserId, oldEmail: record.email, newEmail, } diff --git a/packages/worker/src/app/handlers/account-billing.ts b/packages/worker/src/app/handlers/account-billing.ts index f04a2a8347..b22ca4e2a2 100644 --- a/packages/worker/src/app/handlers/account-billing.ts +++ b/packages/worker/src/app/handlers/account-billing.ts @@ -138,7 +138,7 @@ export function createAccountBillingCheckoutApiHandler(env: Env) { } catch (error) { if (error instanceof StripeApiError) { console.error('billing_checkout_failed', { - userId: user.userId, + stableUserId: user.mcpUser.userId, error: error.message, }) return jsonResponse( @@ -252,7 +252,7 @@ export function createAccountBillingPortalHandler(env: Env) { return billingErrorRedirect(request, 'billing_not_configured') } console.error('billing_portal_failed', { - userId: user.userId, + stableUserId: user.mcpUser.userId, error: error instanceof Error ? error.message : String(error), }) return billingErrorRedirect(request, 'portal_failed') diff --git a/packages/worker/src/app/handlers/account-email-change.node.test.ts b/packages/worker/src/app/handlers/account-email-change.node.test.ts index 4e8513c063..704565ba15 100644 --- a/packages/worker/src/app/handlers/account-email-change.node.test.ts +++ b/packages/worker/src/app/handlers/account-email-change.node.test.ts @@ -12,6 +12,7 @@ import { hashVerificationToken } from '#app/email-verification.ts' import { createStableUserIdFromEmail } from '#worker/user-id.ts' import { createPasswordHash } from '@kody-internal/shared/password-hash.ts' import { consoleWarn } from '#worker/test-support/console-spies.ts' +import { testStableUserIdFromEmail } from '#worker/test-support/stable-user-id.ts' import { createAccountEmailChangeHandler } from './account-email-change.ts' const testCookieSecret = 'test-cookie-secret-0123456789abcdef0123456789' @@ -199,7 +200,7 @@ test('email change requests require the current password and create a pending ve }) const handler = createAccountEmailChangeHandler(createAppEnv(db)) const session = { - id: '1', + stableUserId: testStableUserIdFromEmail('old@example.com'), email: 'old@example.com', rememberMe: false, } @@ -295,7 +296,7 @@ test('email change requests reject emails already owned by another account', asy handler, await createRequest({ session: { - id: '1', + stableUserId: testStableUserIdFromEmail('old@example.com'), email: 'old@example.com', rememberMe: false, }, @@ -338,6 +339,7 @@ test('email change verification updates email and preserves stable user id', asy expect(result).toEqual({ ok: true, userId: 1, + stableUserId: oldStableUserId, oldEmail: 'old@example.com', newEmail: 'new@example.com', }) diff --git a/packages/worker/src/app/handlers/account-profile.node.test.ts b/packages/worker/src/app/handlers/account-profile.node.test.ts index a33b76b7dd..55588f7576 100644 --- a/packages/worker/src/app/handlers/account-profile.node.test.ts +++ b/packages/worker/src/app/handlers/account-profile.node.test.ts @@ -54,10 +54,11 @@ function createProfileTestDb(initialUsers: Array) { const normalizedQuery = query.replace(/\s+/g, ' ').trim().toLowerCase() return { bind(...params: Array) { - const readUserById = () => { - const id = Number(params[0]) - return users.get(id) ?? null - } + const readUserByStableUserId = () => + [...users.values()].find( + (user) => user.stable_user_id === params[0], + ) ?? null + const readUserById = () => users.get(Number(params[0])) ?? null const readUserByUsername = () => { const username = String(params[0] ?? '').toLowerCase() return ( @@ -92,6 +93,17 @@ function createProfileTestDb(initialUsers: Array) { meta: { changes: user ? 1 : 0, last_row_id: 0 }, } } + if ( + normalizedQuery.startsWith('select') && + normalizedQuery.includes('from "users"') && + /"stable_user_id"\s*=/.test(normalizedQuery) + ) { + const user = readUserByStableUserId() + return { + results: user ? [{ ...user }] : [], + meta: { changes: 0, last_row_id: 0 }, + } + } if ( normalizedQuery.startsWith('select') && normalizedQuery.includes('from "users"') && @@ -232,7 +244,7 @@ test('account profile API returns email and username for the signed-in user', as handler, await createRequest({ session: { - id: '1', + stableUserId: testStableUserIdFromEmail('current-user@example.com'), email: 'current-user@example.com', rememberMe: false, }, @@ -281,7 +293,7 @@ test('account profile API updates username for the signed-in user', async () => handler, await createRequest({ session: { - id: '1', + stableUserId: testStableUserIdFromEmail('current-user@example.com'), email: 'current-user@example.com', rememberMe: false, }, @@ -337,7 +349,11 @@ test('account profile API treats an unchanged username as a no-op so grandfather const response = await runHandler( handler, await createRequest({ - session: { id: '1', email: 'kody@example.com', rememberMe: false }, + session: { + stableUserId: testStableUserIdFromEmail('kody@example.com'), + email: 'kody@example.com', + rememberMe: false, + }, method: 'POST', body: { username: 'kody', displayName: 'Kody the Koala', bio: 'Hi' }, }), @@ -370,7 +386,7 @@ test('account profile API rejects username changes when package updates fail', a handler, await createRequest({ session: { - id: '1', + stableUserId: testStableUserIdFromEmail('current-user@example.com'), email: 'current-user@example.com', rememberMe: false, }, @@ -403,7 +419,7 @@ test('account profile API rejects invalid or duplicate usernames', async () => { ]) const handler = createAccountProfileApiHandler(createEnv(testDb.db)) const session = { - id: '1', + stableUserId: testStableUserIdFromEmail('current-user@example.com'), email: 'current-user@example.com', rememberMe: false, } @@ -464,7 +480,7 @@ test('account profile API rounds trip displayName, bio, and visibility', async ( const env = createEnv(testDb.db) const handler = createAccountProfileApiHandler(env) const session = { - id: '1', + stableUserId: testStableUserIdFromEmail('current-user@example.com'), email: 'current-user@example.com', rememberMe: false, } @@ -546,7 +562,7 @@ test('account profile API validates profile field updates', async () => { const testDb = createProfileTestDb([createUser(1, 'current-user')]) const handler = createAccountProfileApiHandler(createEnv(testDb.db)) const session = { - id: '1', + stableUserId: testStableUserIdFromEmail('current-user@example.com'), email: 'current-user@example.com', rememberMe: false, } diff --git a/packages/worker/src/app/handlers/account-resend-verification.node.test.ts b/packages/worker/src/app/handlers/account-resend-verification.node.test.ts index 2a354cd2c2..69567eb454 100644 --- a/packages/worker/src/app/handlers/account-resend-verification.node.test.ts +++ b/packages/worker/src/app/handlers/account-resend-verification.node.test.ts @@ -138,7 +138,7 @@ async function runHandler( } const session: AuthSession = { - id: '1', + stableUserId: testStableUserIdFromEmail('resend-user@example.com'), email: 'resend-user@example.com', rememberMe: false, } diff --git a/packages/worker/src/app/handlers/account.node.test.ts b/packages/worker/src/app/handlers/account.node.test.ts index 90d6d155d0..60c9663f4c 100644 --- a/packages/worker/src/app/handlers/account.node.test.ts +++ b/packages/worker/src/app/handlers/account.node.test.ts @@ -58,7 +58,7 @@ function createStaleSessionTestEnv() { test('account handler redirects to login with a session-destroy cookie for stale sessions', async () => { setAuthSessionSecret(testCookieSecret) const session: AuthSession = { - id: '99', + stableUserId: 'f'.repeat(64), email: 'missing@example.com', rememberMe: false, } diff --git a/packages/worker/src/app/handlers/admin-feature-flags.node.test.ts b/packages/worker/src/app/handlers/admin-feature-flags.node.test.ts index 9f2ede9f78..fd06bc8258 100644 --- a/packages/worker/src/app/handlers/admin-feature-flags.node.test.ts +++ b/packages/worker/src/app/handlers/admin-feature-flags.node.test.ts @@ -45,6 +45,11 @@ type OverrideRow = { type UserRow = { id: number username: string + stable_user_id?: string +} + +function stableUserId(id: number) { + return id.toString(16).padStart(64, '0') } function createAdminActor(roles: Array) { @@ -61,7 +66,7 @@ function createAdminActor(roles: Array) { permissions, artifactOwnerIds: ['1'], mcpUser: { - userId: 'stable-admin', + userId: stableUserId(1), email: 'admin@example.com', username: 'admin-user', displayName: 'admin-user', @@ -85,7 +90,12 @@ function createFeatureFlagsTestEnv( { ...row }, ]), ) - const users = new Map((input.users ?? []).map((row) => [row.id, { ...row }])) + const users = new Map( + (input.users ?? []).map((row) => [ + row.id, + { ...row, stable_user_id: row.stable_user_id ?? stableUserId(row.id) }, + ]), + ) let clock = 0 function nextTimestamp() { @@ -104,15 +114,30 @@ function createFeatureFlagsTestEnv( return createStatement(query, nextParams) }, async first() { - if (normalized.includes('select id from users where id = ?')) { - const user = users.get(Number(params[0])) - return (user ? { id: user.id } : null) as T | null + if ( + normalized.includes( + 'select id, stable_user_id from users where stable_user_id = ?', + ) + ) { + const user = [...users.values()].find( + (row) => row.stable_user_id === params[0], + ) + return ( + user ? { id: user.id, stable_user_id: user.stable_user_id } : null + ) as T | null } - if (normalized.includes('select id from users where username = ?')) { + if ( + normalized.includes( + 'select id, stable_user_id from users where username = ?', + ) + ) { const username = String(params[0]) for (const user of users.values()) { if (user.username === username) { - return { id: user.id } as T + return { + id: user.id, + stable_user_id: user.stable_user_id, + } as T } } return null @@ -146,7 +171,11 @@ function createFeatureFlagsTestEnv( !normalized.includes('where') ) { return { - results: [...globals.values()].map((row) => ({ ...row })), + results: [...globals.values()].map((row) => ({ + ...row, + updated_by_stable_user_id: + users.get(row.updated_by ?? -1)?.stable_user_id ?? null, + })), meta: { changes: 0 }, } as { results: Array; meta: { changes: number } } } @@ -164,6 +193,7 @@ function createFeatureFlagsTestEnv( enabled: row.enabled, updated_at: row.updated_at, username: user.username, + stable_user_id: user.stable_user_id, } }) .filter((row) => row !== null) @@ -360,7 +390,7 @@ test('admin feature flags HTTP lifecycle: auth, list, set_global, and validation enabled: true, rolloutPercent: 25, note: 'canary', - updatedBy: 1, + updatedByStableUserId: null, }, }, { @@ -418,8 +448,12 @@ test('admin feature flags set_user_override validates user identity and existenc const handler = createAdminFeatureFlagsApiHandler( createFeatureFlagsTestEnv({ users: [ - { id: 1, username: 'admin-user' }, - { id: 2, username: 'jane' }, + { + id: 1, + username: 'admin-user', + stable_user_id: stableUserId(1), + }, + { id: 2, username: 'jane', stable_user_id: stableUserId(2) }, ], }) as unknown as Env, ) @@ -447,7 +481,7 @@ test('admin feature flags set_user_override validates user identity and existenc action: 'set_user_override', key: 'demo-indicator', enabled: true, - userId: 2, + stableUserId: stableUserId(2), username: 'jane', }, }), @@ -465,7 +499,7 @@ test('admin feature flags set_user_override validates user identity and existenc action: 'set_user_override', key: 'demo-indicator', enabled: true, - userId: 404, + stableUserId: stableUserId(404), }, }), ) @@ -494,7 +528,7 @@ test('admin feature flags set_user_override validates user identity and existenc key: 'demo-indicator', overrides: [ expect.objectContaining({ - userId: 2, + stableUserId: stableUserId(2), username: 'jane', enabled: true, }), diff --git a/packages/worker/src/app/handlers/admin-feature-flags.ts b/packages/worker/src/app/handlers/admin-feature-flags.ts index e1a64ae577..d01c58c2c6 100644 --- a/packages/worker/src/app/handlers/admin-feature-flags.ts +++ b/packages/worker/src/app/handlers/admin-feature-flags.ts @@ -14,6 +14,7 @@ import { setFeatureFlagGlobalState, setFeatureFlagUserOverride, } from '#worker/feature-flags/service.ts' +import { isStableUserId, normalizeStableUserId } from '#worker/user-id.ts' export function createAdminFeatureFlagsHandler(env: Env) { return { @@ -197,7 +198,8 @@ async function handleSetUserOverrideAction(input: { if (resolvedUserId.status === 'not_found') { return jsonResponse({ ok: false, error: 'User not found.' }, 404) } - const targetUserId = resolvedUserId.userId + const targetUserId = resolvedUserId.dbUserId + const targetStableUserId = resolvedUserId.stableUserId await setFeatureFlagUserOverride(input.env.APP_DB, { key, @@ -216,7 +218,7 @@ async function handleSetUserOverrideAction(input: { path: input.url.pathname, reason: [ `key=${key}`, - `target_user_id=${targetUserId}`, + `target_stable_user_id=${targetStableUserId}`, `enabled=${enabled}`, ].join(';'), }) @@ -239,14 +241,20 @@ async function handleClearUserOverrideAction(input: { ) } - const userId = readPositiveIntField(input.body, 'userId') - if (userId === null) { - return jsonResponse({ ok: false, error: 'userId is required.' }, 400) + const stableUserId = readStableUserIdField(input.body) + if (stableUserId === null) { + return jsonResponse({ ok: false, error: 'stableUserId is required.' }, 400) + } + const target = await resolveOverrideUserId(input.env.APP_DB, { + stableUserId, + }) + if (target.status !== 'ok') { + return jsonResponse({ ok: false, error: 'User not found.' }, 404) } const cleared = await clearFeatureFlagUserOverride(input.env.APP_DB, { key, - userId, + userId: target.dbUserId, }) if (!cleared) { return jsonResponse({ ok: false, error: 'User override not found.' }, 404) @@ -260,7 +268,7 @@ async function handleClearUserOverrideAction(input: { email: input.actor.email, ip: requestIp, path: input.url.pathname, - reason: [`key=${key}`, `target_user_id=${userId}`].join(';'), + reason: [`key=${key}`, `target_stable_user_id=${stableUserId}`].join(';'), }) return jsonResponse(await loadAdminFeatureFlagsData(input.env)) @@ -317,7 +325,7 @@ async function handleDeleteStaleAction(input: { } type ResolveOverrideUserIdResult = - | { status: 'ok'; userId: number } + | { status: 'ok'; dbUserId: number; stableUserId: string } | { status: 'invalid'; error: string } | { status: 'not_found' } @@ -326,55 +334,64 @@ async function resolveOverrideUserId( body: object, ): Promise { const record = body as Record - const hasUserId = Object.hasOwn(record, 'userId') && record.userId != null + const stableUserId = readStableUserIdField(body) + const hasStableUserId = + Object.hasOwn(record, 'stableUserId') && record.stableUserId != null const username = readNonEmptyTrimmedStringOrNumber(body, 'username') const hasUsername = username !== null - if (!hasUserId && !hasUsername) { + if (!hasStableUserId && !hasUsername) { return { status: 'invalid', - error: 'Provide either userId or username.', + error: 'Provide either stableUserId or username.', } } - if (hasUserId && hasUsername) { + if (hasStableUserId && hasUsername) { return { status: 'invalid', - error: 'Provide either userId or username, not both.', + error: 'Provide either stableUserId or username, not both.', } } - if (hasUserId) { - const userId = readPositiveIntField(body, 'userId') - if (userId === null) { + if (hasStableUserId) { + if (stableUserId === null) { return { status: 'invalid', - error: 'userId must be a positive integer.', + error: 'stableUserId must be a valid stable user id.', } } const row = await db - .prepare(`SELECT id FROM users WHERE id = ?`) - .bind(userId) - .first<{ id: number }>() + .prepare(`SELECT id, stable_user_id FROM users WHERE stable_user_id = ?`) + .bind(stableUserId) + .first<{ id: number; stable_user_id: string }>() if (!row) { return { status: 'not_found' } } - return { status: 'ok', userId: row.id } + return { + status: 'ok', + dbUserId: row.id, + stableUserId: row.stable_user_id, + } } if (!username) { return { status: 'invalid', - error: 'Provide either userId or username.', + error: 'Provide either stableUserId or username.', } } const row = await db - .prepare(`SELECT id FROM users WHERE username = ?`) + .prepare(`SELECT id, stable_user_id FROM users WHERE username = ?`) .bind(username) - .first<{ id: number }>() + .first<{ id: number; stable_user_id: string }>() if (!row) { return { status: 'not_found' } } - return { status: 'ok', userId: row.id } + return { + status: 'ok', + dbUserId: row.id, + stableUserId: row.stable_user_id, + } } function readRolloutPercent(body: object): number | null | false { @@ -406,16 +423,9 @@ function readBoolean(body: object, key: string): boolean | null { return null } -function readPositiveIntField(body: object, key: string): number | null { - const value = (body as Record)[key] - if (typeof value === 'number' && Number.isInteger(value) && value > 0) { - return value - } - if (typeof value === 'string' && value.trim()) { - const parsed = Number(value.trim()) - if (Number.isInteger(parsed) && parsed > 0) { - return parsed - } - } - return null +function readStableUserIdField(body: object): string | null { + const value = (body as Record).stableUserId + const stableUserId = + typeof value === 'string' ? normalizeStableUserId(value) : '' + return isStableUserId(stableUserId) ? stableUserId : null } diff --git a/packages/worker/src/app/handlers/admin-invites.ts b/packages/worker/src/app/handlers/admin-invites.ts index b0e2ba2ea6..e8a59f91cb 100644 --- a/packages/worker/src/app/handlers/admin-invites.ts +++ b/packages/worker/src/app/handlers/admin-invites.ts @@ -118,15 +118,16 @@ async function handleCreateUserAction(input: { ip: requestIp, path: input.url.pathname, reason: [ - `actor_user_id=${input.actor.userId}`, - `target_user_id=${createdUser.userId}`, + `actor_stable_user_id=${input.actor.mcpUser.userId}`, + `target_stable_user_id=${createdUser.stableUserId}`, `target_email=${redactEmailRecipient(createdUser.email)}`, ].join(';'), }) + const { userId: _userId, ...boundaryUser } = createdUser return jsonResponse({ ...(await loadAdminInvitesData(input.env)), - createdUser, + createdUser: boundaryUser, }) } catch (error) { const message = diff --git a/packages/worker/src/app/handlers/admin-users.node.test.ts b/packages/worker/src/app/handlers/admin-users.node.test.ts index e4ced5ec9b..e5eebb6cc3 100644 --- a/packages/worker/src/app/handlers/admin-users.node.test.ts +++ b/packages/worker/src/app/handlers/admin-users.node.test.ts @@ -30,6 +30,7 @@ vi.mock('#worker/audit-log.ts', async (importOriginal) => { type UserRow = { id: number + stable_user_id?: string username: string email: string email_verified_at?: string | null @@ -42,6 +43,10 @@ type UserRow = { type UserRoleRow = { user_id: number; role_name: RoleName } +function stableUserId(id: number) { + return id.toString(16).padStart(64, '0') +} + function createAdminActor(roles: Array) { const permissions: Array = roles.includes('admin') ? ['read:user:any', 'update:user:any'] @@ -56,7 +61,7 @@ function createAdminActor(roles: Array) { permissions, artifactOwnerIds: ['1'], mcpUser: { - userId: 'stable-admin', + userId: stableUserId(1), email: 'admin@example.com', username: 'admin-user', displayName: 'admin-user', @@ -73,6 +78,7 @@ function createAdminTestEnv(input: { user.id, { ...user, + stable_user_id: user.stable_user_id ?? stableUserId(user.id), // Normal fixtures default to free; unknown/null stay // explicit so the dedicated stored-plan coercion test can warn. plan: user.plan === undefined ? 'free' : user.plan, @@ -148,7 +154,11 @@ function createAdminTestEnv(input: { bind(...params: Array) { return { async all() { - if (normalizedQuery.startsWith('select id, username, email')) { + if ( + normalizedQuery.startsWith( + 'select id, stable_user_id, username, email', + ) + ) { const { rows, paramIndex } = applyListFilters(params) const pageSize = Number(params[paramIndex]) const offset = Number(params[paramIndex + 1]) @@ -193,18 +203,12 @@ function createAdminTestEnv(input: { } if ( normalizedQuery.includes( - 'select id, email from users where id =', + 'select id, stable_user_id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at from users where stable_user_id =', ) ) { - const user = users.get(Number(params[0])) - return user ? ({ id: user.id, email: user.email } as T) : null - } - if ( - normalizedQuery.includes( - 'select id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at from users where id =', + const user = Array.from(users.values()).find( + (row) => row.stable_user_id === params[0], ) - ) { - const user = users.get(Number(params[0])) return user ? ({ ...user } as T) : null } return null @@ -427,27 +431,36 @@ test('admin users selected param resolves outside the current page and filter', } // Selected user on a later page is still returned for the detail pane. - const paged = await listUsers('?pageSize=1&page=1&selected=3') - expect(paged.users.map((user: { id: number }) => user.id)).toEqual([1]) + const paged = await listUsers( + `?pageSize=1&page=1&selected=${stableUserId(3)}`, + ) + expect( + paged.users.map((user: { stableUserId: string }) => user.stableUserId), + ).toEqual([stableUserId(1)]) expect(paged.selectedUser).toEqual( expect.objectContaining({ - id: 3, + stableUserId: stableUserId(3), username: 'another-member', email: 'another@example.com', }), ) // Selected user excluded by the active role filter is still returned. - const filtered = await listUsers('?role=admin&selected=2') - expect(filtered.users.map((user: { id: number }) => user.id)).toEqual([1]) + const filtered = await listUsers(`?role=admin&selected=${stableUserId(2)}`) + expect( + filtered.users.map((user: { stableUserId: string }) => user.stableUserId), + ).toEqual([stableUserId(1)]) expect(filtered.selectedUser).toEqual( - expect.objectContaining({ id: 2, username: 'member' }), + expect.objectContaining({ + stableUserId: stableUserId(2), + username: 'member', + }), ) - const missing = await listUsers('?selected=99999') + const missing = await listUsers(`?selected=${stableUserId(99)}`) expect(missing.selectedUser).toBeNull() - const invalid = await listUsers('?selected=not-a-number') + const invalid = await listUsers('?selected=123') expect(invalid.selectedUser).toBeNull() }) @@ -501,13 +514,19 @@ test('admin users list applies q and role filters to the slice and total', async // q matches username or email; total reflects the filtered set. const searchPayload = await listUsers('?q=searchable') expect(searchPayload.total).toBe(2) - expect(searchPayload.users.map((user: { id: number }) => user.id)).toEqual([ - 2, 3, - ]) + expect( + searchPayload.users.map( + (user: { stableUserId: string }) => user.stableUserId, + ), + ).toEqual([stableUserId(2), stableUserId(3)]) const rolePayload = await listUsers('?role=admin') expect(rolePayload.total).toBe(1) - expect(rolePayload.users.map((user: { id: number }) => user.id)).toEqual([1]) + expect( + rolePayload.users.map( + (user: { stableUserId: string }) => user.stableUserId, + ), + ).toEqual([stableUserId(1)]) const combinedPayload = await listUsers('?q=searchable&role=admin') expect(combinedPayload.total).toBe(0) @@ -520,7 +539,11 @@ test('admin users list applies q and role filters to the slice and total', async // Filters and pagination compose. const pagedPayload = await listUsers('?q=searchable&pageSize=1&page=2') expect(pagedPayload.total).toBe(2) - expect(pagedPayload.users.map((user: { id: number }) => user.id)).toEqual([3]) + expect( + pagedPayload.users.map( + (user: { stableUserId: string }) => user.stableUserId, + ), + ).toEqual([stableUserId(3)]) }) test('assign role action updates user roles and logs audit event', async () => { @@ -551,7 +574,7 @@ test('assign role action updates user roles and logs audit event', async () => { }, body: JSON.stringify({ action: 'assign_role', - userId: 2, + stableUserId: stableUserId(2), role: 'admin', }), }), @@ -566,7 +589,7 @@ test('assign role action updates user roles and logs audit event', async () => { // an infinite-scroll window without resetting to the first page. expect(payload.updatedUser).toEqual( expect.objectContaining({ - id: 2, + stableUserId: stableUserId(2), roles: expect.arrayContaining(['admin', 'user']), }), ) @@ -602,7 +625,7 @@ test('remove role rejects removing the last admin account', async () => { }, body: JSON.stringify({ action: 'remove_role', - userId: 1, + stableUserId: stableUserId(1), role: 'admin', }), }), @@ -651,7 +674,7 @@ test('remove role removes admin when another admin remains', async () => { }, body: JSON.stringify({ action: 'remove_role', - userId: 2, + stableUserId: stableUserId(2), role: 'admin', }), }), @@ -662,7 +685,7 @@ test('remove role removes admin when another admin remains', async () => { expect(response.status).toBe(200) const payload = await response.json() const secondAdmin = payload.users.find( - (user: { id: number }) => user.id === 2, + (user: { stableUserId: string }) => user.stableUserId === stableUserId(2), ) expect(secondAdmin.roles).not.toContain('admin') expect(logAuditEventSpy).toHaveBeenCalledWith( @@ -709,7 +732,7 @@ test('update plan action sets, maps null to free, validates, and scopes plan cha const setPlanResponse = await postUpdatePlan({ action: 'update_plan', - userId: 2, + stableUserId: stableUserId(2), plan: 'pro', }) expect(setPlanResponse.status).toBe(200) @@ -719,13 +742,13 @@ test('update plan action sets, maps null to free, validates, and scopes plan cha category: 'admin', action: 'update_plan', result: 'success', - reason: 'target_user_id=2;plan=pro', + reason: `target_stable_user_id=${stableUserId(2)};plan=pro`, }), ) const clearPlanResponse = await postUpdatePlan({ action: 'update_plan', - userId: 2, + stableUserId: stableUserId(2), plan: null, }) expect(clearPlanResponse.status).toBe(200) @@ -735,20 +758,25 @@ test('update plan action sets, maps null to free, validates, and scopes plan cha category: 'admin', action: 'update_plan', result: 'success', - reason: 'target_user_id=2;plan=free', + reason: `target_stable_user_id=${stableUserId(2)};plan=free`, }), ) for (const body of [ - { action: 'update_plan', userId: 2, plan: 'enterprise' }, - { action: 'update_plan', userId: 2 }, + { + action: 'update_plan', + stableUserId: stableUserId(2), + plan: 'enterprise', + }, + { action: 'update_plan', stableUserId: stableUserId(2) }, + { action: 'update_plan', stableUserId: 2, plan: 'pro' }, ]) { expect((await postUpdatePlan(body)).status).toBe(400) } const missingUserResponse = await postUpdatePlan({ action: 'update_plan', - userId: 42, + stableUserId: stableUserId(42), plan: 'pro', }) expect(missingUserResponse.status).toBe(404) @@ -789,7 +817,7 @@ test('suspend, unsuspend, and resume email actions update flags and log audit ev const suspendResponse = await postAction({ action: 'suspend_user', - userId: 2, + stableUserId: stableUserId(2), }) expect(suspendResponse.status).toBe(200) const suspended = await suspendResponse.json() @@ -799,13 +827,13 @@ test('suspend, unsuspend, and resume email actions update flags and log audit ev category: 'admin', action: 'suspend_user', result: 'success', - reason: 'target_user_id=2', + reason: `target_stable_user_id=${stableUserId(2)}`, }), ) const unsuspendResponse = await postAction({ action: 'unsuspend_user', - userId: 2, + stableUserId: stableUserId(2), }) expect(unsuspendResponse.status).toBe(200) expect((await unsuspendResponse.json()).users[0].suspended_at).toBeNull() @@ -814,13 +842,13 @@ test('suspend, unsuspend, and resume email actions update flags and log audit ev category: 'admin', action: 'unsuspend_user', result: 'success', - reason: 'target_user_id=2', + reason: `target_stable_user_id=${stableUserId(2)}`, }), ) const resumeResponse = await postAction({ action: 'resume_email_outbound', - userId: 2, + stableUserId: stableUserId(2), }) expect(resumeResponse.status).toBe(200) expect( @@ -831,7 +859,7 @@ test('suspend, unsuspend, and resume email actions update flags and log audit ev category: 'admin', action: 'resume_email_outbound', result: 'success', - reason: 'target_user_id=2', + reason: `target_stable_user_id=${stableUserId(2)}`, }), ) @@ -840,6 +868,7 @@ test('suspend, unsuspend, and resume email actions update flags and log audit ev users: [ { id: 1, + stable_user_id: stableUserId(1), username: 'admin-user', email: 'admin@example.com', created_at: '2026-01-01 00:00:00', @@ -858,7 +887,10 @@ test('suspend, unsuspend, and resume email actions update flags and log audit ev Accept: 'application/json', 'Content-Type': 'application/json', }, - body: JSON.stringify({ action: 'suspend_user', userId: 1 }), + body: JSON.stringify({ + action: 'suspend_user', + stableUserId: stableUserId(1), + }), }), params: {}, url: new URL('https://example.com/admin/users.json'), @@ -866,7 +898,12 @@ test('suspend, unsuspend, and resume email actions update flags and log audit ev expect(selfResponse.status).toBe(400) expect( - (await postAction({ action: 'suspend_user', userId: 42 })).status, + ( + await postAction({ + action: 'suspend_user', + stableUserId: stableUserId(42), + }) + ).status, ).toBe(404) }) diff --git a/packages/worker/src/app/handlers/admin-users.ts b/packages/worker/src/app/handlers/admin-users.ts index d1508917b6..baa69bf238 100644 --- a/packages/worker/src/app/handlers/admin-users.ts +++ b/packages/worker/src/app/handlers/admin-users.ts @@ -1,11 +1,11 @@ -import { readPositiveInt } from '#worker/query-params.ts' import { jsonResponse } from '#worker/json-response.ts' import { type Action } from 'remix/router' import { getRequestIp, logAuditEvent } from '#worker/audit-log.ts' import { loadAdminUserUsageData } from '#worker/admin/user-usage-data.ts' import { clearAdminUserEmailOutboundPause, - loadAdminUserByIdOrEmail, + loadAdminUserByTarget, + loadAdminUserRowByStableUserId, loadAdminUsersData, loadRolesByUserIds, adminUserListItemFieldNames, @@ -29,6 +29,7 @@ import { import { type RoleName, roleNames } from '#worker/identity/permissions.ts' import { readNonEmptyTrimmedStringOrNumber } from '#app/request-body.ts' import { type routes } from '#app/routes.ts' +import { isStableUserId, normalizeStableUserId } from '#worker/user-id.ts' export { adminUserListItemFieldNames, type AdminUserListItem } @@ -59,17 +60,17 @@ export function createAdminUsersHandler(env: Env) { // not anchor the list past the rows it can never load. const pageUrl = new URL(request.url) pageUrl.searchParams.delete('page') - const pathUserId = + const pathStableUserId = typeof params === 'object' && params !== null && - 'userId' in params && - typeof params.userId === 'string' - ? params.userId + 'stableUserId' in params && + typeof params.stableUserId === 'string' + ? params.stableUserId : undefined const adminUsers = await loadAdminUsersData( env, pageUrl.toString(), - pathUserId, + pathStableUserId, ) return renderAppPage({ @@ -181,11 +182,14 @@ export function createAdminUserUsageApiHandler(env: Env) { try { await requireUserWithPermission(request, env, 'read:user:any') const url = new URL(request.url) - const userId = readPositiveInt(url.searchParams.get('userId'), 0) - if (!userId) { - return jsonResponse({ ok: false, error: 'userId is required.' }, 400) + const stableUserId = url.searchParams.get('stableUserId')?.trim() ?? '' + if (!isStableUserId(stableUserId)) { + return jsonResponse( + { ok: false, error: 'stableUserId is required.' }, + 400, + ) } - const payload = await loadAdminUserUsageData(env, userId) + const payload = await loadAdminUserUsageData(env, stableUserId) if (!payload) { return jsonResponse({ ok: false, error: 'User not found.' }, 404) } @@ -205,30 +209,29 @@ async function handleAssignRoleAction(input: { actor: Awaited> body: object }) { - const targetUserId = readPositiveInt( - readNonEmptyTrimmedStringOrNumber(input.body, 'userId'), - 0, - ) + const targetStableUserId = readStableUserIdField(input.body) const roleName = readRoleName(input.body, 'role') - if (!targetUserId) { - return jsonResponse({ ok: false, error: 'User id is required.' }, 400) + if (!targetStableUserId) { + return jsonResponse( + { ok: false, error: 'Stable user id is required.' }, + 400, + ) } if (!roleName) { return jsonResponse({ ok: false, error: 'Role is required.' }, 400) } - const targetUser = await input.env.APP_DB.prepare( - `SELECT id, email FROM users WHERE id = ?`, + const targetUser = await loadAdminUserRowByStableUserId( + input.env.APP_DB, + targetStableUserId, ) - .bind(targetUserId) - .first<{ id: number; email: string }>() if (!targetUser) { return jsonResponse({ ok: false, error: 'User not found.' }, 404) } await assignUserRole({ db: input.env.APP_DB, - userId: targetUserId, + userId: targetUser.id, roleName, }) @@ -240,10 +243,10 @@ async function handleAssignRoleAction(input: { email: input.actor.email, ip: requestIp, path: input.url.pathname, - reason: `target_user_id=${targetUserId};role=${roleName}`, + reason: `target_stable_user_id=${targetStableUserId};role=${roleName}`, }) - return buildMutationResponse(input.env, input.request.url, targetUserId) + return buildMutationResponse(input.env, input.request.url, targetStableUserId) } /** @@ -254,11 +257,11 @@ async function handleAssignRoleAction(input: { async function buildMutationResponse( env: Env, requestUrl: string, - targetUserId: number, + targetStableUserId: string, ) { const [payload, updatedUser] = await Promise.all([ loadAdminUsersData(env, requestUrl), - loadAdminUserByIdOrEmail(env.APP_DB, { id: targetUserId }), + loadAdminUserByTarget(env.APP_DB, { stableUserId: targetStableUserId }), ]) return jsonResponse({ ...payload, updatedUser }) } @@ -270,23 +273,22 @@ async function handleRemoveRoleAction(input: { actor: Awaited> body: object }) { - const targetUserId = readPositiveInt( - readNonEmptyTrimmedStringOrNumber(input.body, 'userId'), - 0, - ) + const targetStableUserId = readStableUserIdField(input.body) const roleName = readRoleName(input.body, 'role') - if (!targetUserId) { - return jsonResponse({ ok: false, error: 'User id is required.' }, 400) + if (!targetStableUserId) { + return jsonResponse( + { ok: false, error: 'Stable user id is required.' }, + 400, + ) } if (!roleName) { return jsonResponse({ ok: false, error: 'Role is required.' }, 400) } - const targetUser = await input.env.APP_DB.prepare( - `SELECT id, email FROM users WHERE id = ?`, + const targetUser = await loadAdminUserRowByStableUserId( + input.env.APP_DB, + targetStableUserId, ) - .bind(targetUserId) - .first<{ id: number; email: string }>() if (!targetUser) { return jsonResponse({ ok: false, error: 'User not found.' }, 404) } @@ -297,13 +299,13 @@ async function handleRemoveRoleAction(input: { // deployment with zero admins. const { removed } = await removeAdminRolePreservingLastAdmin({ db: input.env.APP_DB, - userId: targetUserId, + userId: targetUser.id, }) if (!removed) { const targetRoles = await loadRolesByUserIds(input.env.APP_DB, [ - targetUserId, + targetUser.id, ]) - const targetStillAdmin = (targetRoles.get(targetUserId) ?? []).includes( + const targetStillAdmin = (targetRoles.get(targetUser.id) ?? []).includes( 'admin', ) if (targetStillAdmin) { @@ -332,7 +334,7 @@ async function handleRemoveRoleAction(input: { } else { await removeUserRole({ db: input.env.APP_DB, - userId: targetUserId, + userId: targetUser.id, roleName, }) } @@ -345,10 +347,10 @@ async function handleRemoveRoleAction(input: { email: input.actor.email, ip: requestIp, path: input.url.pathname, - reason: `target_user_id=${targetUserId};role=${roleName}`, + reason: `target_stable_user_id=${targetStableUserId};role=${roleName}`, }) - return buildMutationResponse(input.env, input.request.url, targetUserId) + return buildMutationResponse(input.env, input.request.url, targetStableUserId) } async function handleUpdatePlanAction(input: { @@ -358,12 +360,12 @@ async function handleUpdatePlanAction(input: { actor: Awaited> body: object }) { - const targetUserId = readPositiveInt( - readNonEmptyTrimmedStringOrNumber(input.body, 'userId'), - 0, - ) - if (!targetUserId) { - return jsonResponse({ ok: false, error: 'User id is required.' }, 400) + const targetStableUserId = readStableUserIdField(input.body) + if (!targetStableUserId) { + return jsonResponse( + { ok: false, error: 'Stable user id is required.' }, + 400, + ) } const planUpdate = readPlanUpdate(input.body) if (!planUpdate.ok) { @@ -377,7 +379,7 @@ async function handleUpdatePlanAction(input: { } const updatedUser = await updateAdminUserPlan(input.env.APP_DB, { - id: targetUserId, + stableUserId: targetStableUserId, plan: planUpdate.plan, }) if (!updatedUser) { @@ -392,10 +394,10 @@ async function handleUpdatePlanAction(input: { email: input.actor.email, ip: requestIp, path: input.url.pathname, - reason: `target_user_id=${targetUserId};plan=${planUpdate.plan}`, + reason: `target_stable_user_id=${targetStableUserId};plan=${planUpdate.plan}`, }) - return buildMutationResponse(input.env, input.request.url, targetUserId) + return buildMutationResponse(input.env, input.request.url, targetStableUserId) } /** @@ -411,14 +413,14 @@ async function handleSuspensionAction(input: { body: object suspended: boolean }) { - const targetUserId = readPositiveInt( - readNonEmptyTrimmedStringOrNumber(input.body, 'userId'), - 0, - ) - if (!targetUserId) { - return jsonResponse({ ok: false, error: 'User id is required.' }, 400) + const targetStableUserId = readStableUserIdField(input.body) + if (!targetStableUserId) { + return jsonResponse( + { ok: false, error: 'Stable user id is required.' }, + 400, + ) } - if (input.suspended && targetUserId === input.actor.userId) { + if (input.suspended && targetStableUserId === input.actor.mcpUser.userId) { return jsonResponse( { ok: false, error: 'You cannot suspend your own account.' }, 400, @@ -426,7 +428,7 @@ async function handleSuspensionAction(input: { } const updatedUser = await updateAdminUserSuspension(input.env.APP_DB, { - id: targetUserId, + stableUserId: targetStableUserId, suspended: input.suspended, }) if (!updatedUser) { @@ -441,10 +443,10 @@ async function handleSuspensionAction(input: { email: input.actor.email, ip: requestIp, path: input.url.pathname, - reason: `target_user_id=${targetUserId}`, + reason: `target_stable_user_id=${targetStableUserId}`, }) - return buildMutationResponse(input.env, input.request.url, targetUserId) + return buildMutationResponse(input.env, input.request.url, targetStableUserId) } /** @@ -458,16 +460,16 @@ async function handleResumeEmailOutboundAction(input: { actor: Awaited> body: object }) { - const targetUserId = readPositiveInt( - readNonEmptyTrimmedStringOrNumber(input.body, 'userId'), - 0, - ) - if (!targetUserId) { - return jsonResponse({ ok: false, error: 'User id is required.' }, 400) + const targetStableUserId = readStableUserIdField(input.body) + if (!targetStableUserId) { + return jsonResponse( + { ok: false, error: 'Stable user id is required.' }, + 400, + ) } const updatedUser = await clearAdminUserEmailOutboundPause(input.env.APP_DB, { - id: targetUserId, + stableUserId: targetStableUserId, }) if (!updatedUser) { return jsonResponse({ ok: false, error: 'User not found.' }, 404) @@ -481,10 +483,10 @@ async function handleResumeEmailOutboundAction(input: { email: input.actor.email, ip: requestIp, path: input.url.pathname, - reason: `target_user_id=${targetUserId}`, + reason: `target_stable_user_id=${targetStableUserId}`, }) - return buildMutationResponse(input.env, input.request.url, targetUserId) + return buildMutationResponse(input.env, input.request.url, targetStableUserId) } /** @@ -515,3 +517,10 @@ function readRoleName(body: object, key: string): RoleName | null { const value = readNonEmptyTrimmedStringOrNumber(body, key) return value && isRoleName(value) ? value : null } + +function readStableUserIdField(body: object): string | null { + const value = (body as Record).stableUserId + if (typeof value !== 'string') return null + const stableUserId = normalizeStableUserId(value) + return isStableUserId(stableUserId) ? stableUserId : null +} diff --git a/packages/worker/src/app/handlers/auth-handler.node.test.ts b/packages/worker/src/app/handlers/auth-handler.node.test.ts index c56d8e2bc8..456db03343 100644 --- a/packages/worker/src/app/handlers/auth-handler.node.test.ts +++ b/packages/worker/src/app/handlers/auth-handler.node.test.ts @@ -12,6 +12,7 @@ import { auditEventSummaries, logAuditEventSpy, } from '#worker/test-support/audit-log-spy.ts' +import { createStableUserIdFromEmail } from '#worker/user-id.ts' const testCookieSecret = 'test-cookie-secret-0123456789abcdef0123456789' @@ -78,6 +79,7 @@ type TestUser = { username: string password_hash: string plan: string + stable_user_id: string } type TestInvite = { @@ -126,6 +128,7 @@ function createTestDb(options: { failRoleAssignment?: boolean } = {}) { const username = String(values.username ?? '') const email = String(values.email ?? '') const passwordHash = String(values.password_hash ?? '') + const stableUserId = String(values.stable_user_id ?? '') const plan = values.plan === undefined || values.plan === null ? null @@ -148,6 +151,7 @@ function createTestDb(options: { failRoleAssignment?: boolean } = {}) { username, password_hash: passwordHash, plan, + stable_user_id: stableUserId, } nextId += 1 users.set(normalizedEmail, user) @@ -311,6 +315,7 @@ function createTestDb(options: { failRoleAssignment?: boolean } = {}) { username, password_hash: passwordHash, plan: 'free', + stable_user_id: await createStableUserIdFromEmail(email), } nextId += 1 users.set(email.toLowerCase(), user) diff --git a/packages/worker/src/app/handlers/auth-page.node.test.ts b/packages/worker/src/app/handlers/auth-page.node.test.ts index f4af3e91d9..5f86bd37ae 100644 --- a/packages/worker/src/app/handlers/auth-page.node.test.ts +++ b/packages/worker/src/app/handlers/auth-page.node.test.ts @@ -58,7 +58,7 @@ function createStaleSessionTestEnv() { test('auth page renders login for a stale session instead of redirecting away', async () => { setAuthSessionSecret(testCookieSecret) const session: AuthSession = { - id: '99', + stableUserId: 'f'.repeat(64), email: 'missing@example.com', rememberMe: false, } diff --git a/packages/worker/src/app/handlers/auth-provider.node.test.ts b/packages/worker/src/app/handlers/auth-provider.node.test.ts index 7904cc559a..fd6f76c9fa 100644 --- a/packages/worker/src/app/handlers/auth-provider.node.test.ts +++ b/packages/worker/src/app/handlers/auth-provider.node.test.ts @@ -546,7 +546,11 @@ test('signed-in users link and disconnect providers from their account', async ( }) const sessionCookiePair = getCookiePair( await createAuthCookie( - { id: '11', email: 'linker@example.com', rememberMe: false }, + { + stableUserId: await createStableUserIdFromEmail('linker@example.com'), + email: 'linker@example.com', + rememberMe: false, + }, false, ), ) @@ -603,7 +607,11 @@ test('signed-in users link and disconnect providers from their account', async ( }) const otherSessionCookiePair = getCookiePair( await createAuthCookie( - { id: '12', email: 'other@example.com', rememberMe: false }, + { + stableUserId: await createStableUserIdFromEmail('other@example.com'), + email: 'other@example.com', + rememberMe: false, + }, false, ), ) diff --git a/packages/worker/src/app/handlers/auth-provider.ts b/packages/worker/src/app/handlers/auth-provider.ts index 19312aa353..934041fb2a 100644 --- a/packages/worker/src/app/handlers/auth-provider.ts +++ b/packages/worker/src/app/handlers/auth-provider.ts @@ -56,7 +56,10 @@ import { resolvePlanWrite, type PlanName, } from '#worker/entitlements/plans.ts' -import { createStableUserIdFromEmail } from '#worker/user-id.ts' +import { + createStableUserIdFromEmail, + resolveUserStableId, +} from '#worker/user-id.ts' /** * Accounts created through social login have no usable password until the @@ -292,14 +295,19 @@ export function createAuthProviderCallbackHandler(env: Env) { return fail('provider-error', 'provider_exchange_failed') } - async function issueLogin(user: { id: number; email: string }) { + async function issueLogin(user: { + id: number + stable_user_id: string | null + email: string + }) { + const stableUserId = resolveUserStableId(user) // Two-factor accounts get the same pending-verification gate as // password and passkey logins; the session cookie is only // issued once the TOTP code passes. if (await isTwoFactorEnabled(env.APP_DB, user.id)) { setVerifySessionSecret(env.COOKIE_SECRET) const verifyCookie = await createVerifySessionCookie( - { id: String(user.id), email: user.email, rememberMe: false }, + { stableUserId, email: user.email, rememberMe: false }, secure, ) void logAuditEvent({ @@ -322,7 +330,7 @@ export function createAuthProviderCallbackHandler(env: Env) { } const sessionCookie = await createAuthCookie( - { id: String(user.id), email: user.email, rememberMe: false }, + { stableUserId, email: user.email, rememberMe: false }, secure, ) void logAuditEvent({ @@ -352,7 +360,7 @@ export function createAuthProviderCallbackHandler(env: Env) { // account switch). if (session) { const currentUser = await db.findOne(usersTable, { - where: { id: Number(session.id) }, + where: { stable_user_id: session.stableUserId }, }) if (!currentUser) { return fail('account-error', 'session_user_missing') @@ -470,7 +478,11 @@ export function createAuthProviderCallbackHandler(env: Env) { // transient failure after consumeInviteCode still releases the invite. let username: string let stableUserId: string - let newUser: { id: number } | null = null + let newUser: { + id: number + stable_user_id: string + email: string + } | null = null try { username = await getAvailableUsernameFromBase( env.APP_DB, @@ -489,7 +501,7 @@ export function createAuthProviderCallbackHandler(env: Env) { }, { returnRow: true }, ) - newUser = { id: createdUser.id } + newUser = { id: createdUser.id, stable_user_id: stableUserId, email } } catch (error) { await releaseConsumedInvite() if (getUniqueConstraintField(error)) { @@ -576,10 +588,10 @@ export function createAuthProviderCallbackHandler(env: Env) { email, ip: requestIp, path: url.pathname, - reason: `invite_code=${consumedInviteCode};user_id=${newUser.id};provider=${provider};plan=${resolvePlanWrite(consumedInvitePlan)}`, + reason: `invite_code=${consumedInviteCode};stable_user_id=${stableUserId};provider=${provider};plan=${resolvePlanWrite(consumedInvitePlan)}`, }) } - return issueLogin({ id: newUser.id, email }) + return issueLogin(newUser) }, } satisfies Action } diff --git a/packages/worker/src/app/handlers/auth.ts b/packages/worker/src/app/handlers/auth.ts index dd7686a4ce..d30f13d289 100644 --- a/packages/worker/src/app/handlers/auth.ts +++ b/packages/worker/src/app/handlers/auth.ts @@ -35,7 +35,10 @@ import { } from '#worker/entitlements/plans.ts' import { ensureDefaultEmailInbox } from '#worker/email/default-inbox.ts' import { getPlatformEmailDomain } from '#worker/email/platform-address.ts' -import { createStableUserIdFromEmail } from '#worker/user-id.ts' +import { + createStableUserIdFromEmail, + resolveUserStableId, +} from '#worker/user-id.ts' import { createPasswordHash, verifyPassword, @@ -247,7 +250,7 @@ export function createAuthHandler(env: Env) { consumedInvitePlan = parseStoredPlanName(inviteResult.invite.plan) } - let record: { id: number } | null = null + let record: { id: number; stableUserId: string } | null = null try { const stableUserId = await createStableUserIdFromEmail(normalizedEmail) @@ -264,7 +267,7 @@ export function createAuthHandler(env: Env) { returnRow: true, }, ) - record = { id: createdUser.id } + record = { id: createdUser.id, stableUserId } } catch (error) { const uniqueField = getUniqueConstraintField(error) if (uniqueField === 'email' || uniqueField === 'username') { @@ -419,7 +422,7 @@ export function createAuthHandler(env: Env) { const cookie = await createAuthCookie( { - id: String(record.id), + stableUserId: record.stableUserId, email: normalizedEmail, rememberMe: false, }, @@ -441,7 +444,7 @@ export function createAuthHandler(env: Env) { email: normalizedEmail, ip: requestIp, path: url.pathname, - reason: `invite_code=${consumedInviteCode};user_id=${record.id};plan=${resolvePlanWrite(consumedInvitePlan)}`, + reason: `invite_code=${consumedInviteCode};stable_user_id=${record.stableUserId};plan=${resolvePlanWrite(consumedInvitePlan)}`, }) } return Response.json( @@ -495,7 +498,7 @@ export function createAuthHandler(env: Env) { const secure = isSecureRequest(request) const verifyCookie = await createVerifySessionCookie( { - id: String(userRecord.id), + stableUserId: resolveUserStableId(userRecord), email: normalizedEmail, rememberMe, }, @@ -522,7 +525,7 @@ export function createAuthHandler(env: Env) { const cookie = await createAuthCookie( { - id: String(userRecord.id), + stableUserId: resolveUserStableId(userRecord), email: normalizedEmail, rememberMe, }, diff --git a/packages/worker/src/app/handlers/passkeys.node.test.ts b/packages/worker/src/app/handlers/passkeys.node.test.ts index 63b2a5bfcd..e6c37b18d4 100644 --- a/packages/worker/src/app/handlers/passkeys.node.test.ts +++ b/packages/worker/src/app/handlers/passkeys.node.test.ts @@ -14,6 +14,7 @@ import { } from '#app/handlers/webauthn.ts' import { createStableUserIdFromEmail } from '#worker/user-id.ts' import { createPasswordHash } from '@kody-internal/shared/password-hash.ts' +import { testStableUserIdFromEmail } from '#worker/test-support/stable-user-id.ts' const testCookieSecret = 'test-cookie-secret-0123456789abcdef0123456789' @@ -208,7 +209,7 @@ function initTestSecrets() { } const userOneSession: AuthSession = { - id: '1', + stableUserId: testStableUserIdFromEmail('one@example.com'), email: 'one@example.com', rememberMe: false, } diff --git a/packages/worker/src/app/handlers/pending-verification.node.test.ts b/packages/worker/src/app/handlers/pending-verification.node.test.ts index 09378cf8f2..f41fd8e932 100644 --- a/packages/worker/src/app/handlers/pending-verification.node.test.ts +++ b/packages/worker/src/app/handlers/pending-verification.node.test.ts @@ -80,7 +80,7 @@ function createUserEnv(options: { test('pending verification requires a live session, preserves redirectTo after verify, and renders when unverified', async () => { setAuthSessionSecret(testCookieSecret) const session: AuthSession = { - id: '1', + stableUserId: testStableUserIdFromEmail('pending@example.com'), email: 'pending@example.com', rememberMe: false, } diff --git a/packages/worker/src/app/handlers/session-handler.node.test.ts b/packages/worker/src/app/handlers/session-handler.node.test.ts index 637ec2ce51..5fbfaf68a8 100644 --- a/packages/worker/src/app/handlers/session-handler.node.test.ts +++ b/packages/worker/src/app/handlers/session-handler.node.test.ts @@ -10,7 +10,7 @@ import { testStableUserIdFromEmail } from '#worker/test-support/stable-user-id.t const testCookieSecret = 'test-cookie-secret-0123456789abcdef0123456789' const rememberedSession: AuthSession = { - id: '1', + stableUserId: testStableUserIdFromEmail('user@example.com'), email: 'user@example.com', rememberMe: true, } @@ -47,9 +47,11 @@ function createSessionTestDb() { if ( normalizedQuery.startsWith('select') && normalizedQuery.includes('from "users"') && - /"id"\s*=/.test(normalizedQuery) + /"stable_user_id"\s*=/.test(normalizedQuery) ) { - const user = users.get(Number(params[0])) + const user = [...users.values()].find( + (row) => row.stable_user_id === params[0], + ) return { results: user ? [{ ...user }] : [], meta: { changes: 0, last_row_id: 0 }, @@ -173,13 +175,13 @@ test('session handler only renews remembered sessions after the renewal window', } }) -test('session handler clears invalid session cookies for missing users and malformed ids', async () => { +test('session handler clears cookies for unknown stable user ids', async () => { setAuthSessionSecret(testCookieSecret) const session = createSessionHandler(createEnv()) const invalidCookies = await Promise.all([ createAuthCookie( { - id: '404', + stableUserId: 'f'.repeat(64), email: 'missing@example.com', rememberMe: false, }, @@ -187,7 +189,7 @@ test('session handler clears invalid session cookies for missing users and malfo ), createAuthCookie( { - id: '1abc', + stableUserId: 'e'.repeat(64), email: 'user@example.com', rememberMe: false, }, diff --git a/packages/worker/src/app/handlers/two-factor.node.test.ts b/packages/worker/src/app/handlers/two-factor.node.test.ts index c33cef47a2..54a735d9c7 100644 --- a/packages/worker/src/app/handlers/two-factor.node.test.ts +++ b/packages/worker/src/app/handlers/two-factor.node.test.ts @@ -19,6 +19,7 @@ import { auditEventSummaries, logAuditEventSpy, } from '#worker/test-support/audit-log-spy.ts' +import { testStableUserIdFromEmail } from '#worker/test-support/stable-user-id.ts' const testCookieSecret = 'test-cookie-secret-0123456789abcdef0123456789' @@ -227,7 +228,7 @@ function initTestSecrets() { } const session: AuthSession = { - id: '1', + stableUserId: testStableUserIdFromEmail('kody@example.com'), email: 'kody@example.com', rememberMe: false, } diff --git a/packages/worker/src/app/handlers/verify-email-change.ts b/packages/worker/src/app/handlers/verify-email-change.ts index 4f8c120855..b1f433a768 100644 --- a/packages/worker/src/app/handlers/verify-email-change.ts +++ b/packages/worker/src/app/handlers/verify-email-change.ts @@ -69,10 +69,10 @@ export function createVerifyEmailChangeHandler(env: Env) { const { session } = await readAuthSessionResult(request) const setCookie = - session?.id === String(result.userId) + session?.stableUserId === result.stableUserId ? await createAuthCookie( { - id: session.id, + stableUserId: session.stableUserId, email: result.newEmail, rememberMe: session.rememberMe, }, diff --git a/packages/worker/src/app/handlers/verify.ts b/packages/worker/src/app/handlers/verify.ts index c5a83c5bfb..9ce3cfaef3 100644 --- a/packages/worker/src/app/handlers/verify.ts +++ b/packages/worker/src/app/handlers/verify.ts @@ -19,6 +19,7 @@ import { readVerifySession, setVerifySessionSecret, } from '#app/verify-session.ts' +import { createDb, usersTable } from '#worker/db.ts' export function createVerifyHandler(env: Env) { return { @@ -80,12 +81,15 @@ export function createTwoFactorVerifyApiHandler(env: Env) { ) } - const userId = Number(pendingSession.id) + const db = createDb(env.APP_DB) + const userRecord = await db.findOne(usersTable, { + where: { stable_user_id: pendingSession.stableUserId }, + }) const codeValid = - Number.isInteger(userId) && + userRecord != null && (await verifyTwoFactorCode({ db: env.APP_DB, - userId, + userId: userRecord.id, code, type: twoFactorVerificationType, })) @@ -111,7 +115,7 @@ export function createTwoFactorVerifyApiHandler(env: Env) { 'Set-Cookie', await createAuthCookie( { - id: pendingSession.id, + stableUserId: pendingSession.stableUserId, email: pendingSession.email, rememberMe: pendingSession.rememberMe, }, diff --git a/packages/worker/src/app/handlers/webauthn.ts b/packages/worker/src/app/handlers/webauthn.ts index 4f2f2192bf..3ec8661c4f 100644 --- a/packages/worker/src/app/handlers/webauthn.ts +++ b/packages/worker/src/app/handlers/webauthn.ts @@ -32,6 +32,7 @@ import { setWebAuthnChallengeSecret, } from '#app/webauthn.ts' import { createDb, usersTable } from '#worker/db.ts' +import { resolveUserStableId } from '#worker/user-id.ts' export function createWebauthnRegistrationHandler(env: Env) { return { @@ -55,7 +56,7 @@ export function createWebauthnRegistrationHandler(env: Env) { rpName: config.rpName, rpID: config.rpID, userName: user.username, - userID: new TextEncoder().encode(String(user.userId)), + userID: new TextEncoder().encode(user.mcpUser.userId), userDisplayName: user.displayName || user.email, attestationType: 'none', excludeCredentials: existingPasskeys.map((passkey) => ({ @@ -78,7 +79,7 @@ export function createWebauthnRegistrationHandler(env: Env) { { challenge: options.challenge, webauthnUserId: options.user.id, - userId: user.userId, + stableUserId: user.mcpUser.userId, }, secure, ), @@ -99,7 +100,7 @@ export function createWebauthnRegistrationHandler(env: Env) { // wrong account. if ( !challengeData?.webauthnUserId || - challengeData.userId !== user.userId + challengeData.stableUserId !== user.mcpUser.userId ) { return jsonResponse( { @@ -335,7 +336,7 @@ export function createWebauthnAuthenticationHandler(env: Env) { 'Set-Cookie', await createAuthCookie( { - id: String(userRecord.id), + stableUserId: resolveUserStableId(userRecord), email: userRecord.email, rememberMe, }, diff --git a/packages/worker/src/app/loader-data.ts b/packages/worker/src/app/loader-data.ts index c4275bf996..93f6d45fc6 100644 --- a/packages/worker/src/app/loader-data.ts +++ b/packages/worker/src/app/loader-data.ts @@ -119,7 +119,7 @@ export type CommunityStargazersLoaderData = { * share these types with the JSON API response shapes. */ export type AdminUserListItem = { - id: number + stableUserId: string username: string email: string email_verified: boolean @@ -188,7 +188,7 @@ export type AdminCommunityReportsLoaderData = { export type AdminInviteListItem = { code: string - createdBy: number | null + createdByStableUserId: string | null createdByEmail: string | null note: string maxUses: number @@ -316,7 +316,7 @@ export type AdminUsageMonthRollup = { */ export type AdminUserUsageLoaderData = { ok: true - userId: number + stableUserId: string username: string plan: AdminPlanName currentMonth: string @@ -546,7 +546,7 @@ export type AdminPlatformFeedbackLoaderData = { } export type AdminCreatedUserSetup = { - userId: number + stableUserId: string email: string username: string setupLink: string diff --git a/packages/worker/src/app/package-app-handoff.node.test.ts b/packages/worker/src/app/package-app-handoff.node.test.ts index 4536b1d029..414e3d9a1b 100644 --- a/packages/worker/src/app/package-app-handoff.node.test.ts +++ b/packages/worker/src/app/package-app-handoff.node.test.ts @@ -16,6 +16,7 @@ import { } from '#app/package-app-session.ts' const cookieSecret = 'PACKAGE_APP_TEST_COOKIE_SECRET_32_CHARS_MINIMUM' +const ownerStableUserId = '1'.repeat(64) function createTestEnv(input: { cookieSecret?: string; kv?: boolean } = {}) { const store = new Map() @@ -32,7 +33,7 @@ function createTestEnv(input: { cookieSecret?: string; kv?: boolean } = {}) { } const claims = { - userId: '17', + stableUserId: ownerStableUserId, username: 'owner', kodyId: 'daily-notes', } @@ -144,7 +145,7 @@ test('the package-app session cookie is not interchangeable with the app session const setCookie = await createPackageAppSessionCookie({ env, - session: { userId: '17', username: 'owner' }, + session: { stableUserId: ownerStableUserId, username: 'owner' }, secure: true, }) expect(setCookie).toContain('kody_pkg_session=') @@ -165,7 +166,7 @@ test('the package-app session cookie is not interchangeable with the app session env, }), ).resolves.toMatchObject({ - session: { userId: '17', username: 'owner' }, + session: { stableUserId: ownerStableUserId, username: 'owner' }, }) // Same secret material, different derived signing key: replaying the @@ -181,7 +182,11 @@ test('the package-app session cookie is not interchangeable with the app session // And the reverse: an app session cookie value is not a package-app session. const appSetCookie = await createAuthCookie( - { id: '17', email: 'owner@example.com', rememberMe: false }, + { + stableUserId: ownerStableUserId, + email: 'owner@example.com', + rememberMe: false, + }, true, ) const appCookieValue = (appSetCookie.split(';')[0] ?? '').split('=')[1] ?? '' diff --git a/packages/worker/src/app/package-app-handoff.ts b/packages/worker/src/app/package-app-handoff.ts index 1548a7c681..8dcc83491a 100644 --- a/packages/worker/src/app/package-app-handoff.ts +++ b/packages/worker/src/app/package-app-handoff.ts @@ -3,6 +3,7 @@ import { bytesToBase64Url, utf8ToBase64Url, } from '@kody-internal/shared/base64.ts' +import { isStableUserId } from '#worker/user-id.ts' /** * Cross-site auth handoff for hosted package apps. @@ -22,22 +23,21 @@ import { export const packageAppHandoffQueryParam = '__kody_handoff' const handoffTokenTtlMs = 60_000 -const handoffSignaturePurpose = 'kody-package-app-handoff:v1' +const handoffSignaturePurpose = 'kody-package-app-handoff:v2' const handoffReplayKeyPrefix = 'package-app-handoff:' // Cloudflare KV enforces a 60 second minimum expiration TTL, which matches the // token lifetime. const handoffReplayTtlSeconds = 60 export type PackageAppHandoffClaims = { - /** Numeric app user id, as stored in the `kody_session` cookie payload. */ - userId: string + stableUserId: string username: string kodyId: string } type StoredHandoffPayload = { - v: 1 - uid: string + v: 2 + stableUserId: string usr: string pkg: string exp: number @@ -48,9 +48,8 @@ function isStoredHandoffPayload(value: unknown): value is StoredHandoffPayload { if (!value || typeof value !== 'object') return false const record = value as Record return ( - record.v === 1 && - typeof record.uid === 'string' && - record.uid.length > 0 && + record.v === 2 && + isStableUserId(record.stableUserId) && typeof record.usr === 'string' && record.usr.length > 0 && typeof record.pkg === 'string' && @@ -88,8 +87,8 @@ export async function createPackageAppHandoffToken(input: { const now = input.now ?? Date.now() const payload = utf8ToBase64Url( JSON.stringify({ - v: 1, - uid: input.claims.userId, + v: 2, + stableUserId: input.claims.stableUserId, usr: input.claims.username, pkg: input.claims.kodyId, exp: now + handoffTokenTtlMs, @@ -169,7 +168,7 @@ export async function consumePackageAppHandoffToken(input: { } return { - userId: parsed.uid, + stableUserId: parsed.stableUserId, username: parsed.usr, kodyId: parsed.pkg, } diff --git a/packages/worker/src/app/package-app-origin.ts b/packages/worker/src/app/package-app-origin.ts index 783fe4b949..5a8327e731 100644 --- a/packages/worker/src/app/package-app-origin.ts +++ b/packages/worker/src/app/package-app-origin.ts @@ -9,7 +9,7 @@ import { createPackageAppHandoffToken, packageAppHandoffQueryParam, } from '#app/package-app-handoff.ts' -import { resolvePackageAppOwnerByUserId } from '#app/package-app-owner.ts' +import { resolvePackageAppOwnerByStableUserId } from '#app/package-app-owner.ts' import { createPackageAppSessionCookie, readPackageAppSession, @@ -173,7 +173,7 @@ async function redirectAppOriginToPackageAppOrigin(input: { await createPackageAppHandoffToken({ env, claims: { - userId: String(user.userId), + stableUserId: user.mcpUser.userId, username: user.username, kodyId: packagePath.kodyId, }, @@ -216,7 +216,10 @@ async function handleRequestOnPackageAppOrigin(input: { status: 302, setCookie: await createPackageAppSessionCookie({ env, - session: { userId: claims.userId, username: claims.username }, + session: { + stableUserId: claims.stableUserId, + username: claims.username, + }, secure: isSecureRequest(request), }), }) @@ -225,9 +228,9 @@ async function handleRequestOnPackageAppOrigin(input: { const parsedSession = await readPackageAppSession({ request, env }) const owner = parsedSession - ? await resolvePackageAppOwnerByUserId({ + ? await resolvePackageAppOwnerByStableUserId({ env, - userId: parsedSession.session.userId, + stableUserId: parsedSession.session.stableUserId, issuedAt: parsedSession.issuedAt, }) : null diff --git a/packages/worker/src/app/package-app-origin.workers.test.ts b/packages/worker/src/app/package-app-origin.workers.test.ts index 0336b35e17..288fedf936 100644 --- a/packages/worker/src/app/package-app-origin.workers.test.ts +++ b/packages/worker/src/app/package-app-origin.workers.test.ts @@ -9,6 +9,7 @@ import { ensureRbacTestSchema, seedAccount, } from '#worker/test-support/workers-seed.ts' +import { createStableUserIdFromEmail } from '#worker/user-id.ts' // Different ports on purpose: swapping origins by mutating a `URL` keeps the // original port, and identical ports would hide that. @@ -70,14 +71,18 @@ async function seedOwnerSessionCookie() { ]) { await env.APP_DB.prepare(statement).run() } - const userId = await seedAccount({ + await seedAccount({ db: env.APP_DB, email: ownerEmail, username: ownerUsername, }) setAuthSessionSecret(env.COOKIE_SECRET) const setCookie = await createAuthCookie( - { id: String(userId), email: ownerEmail, rememberMe: false }, + { + stableUserId: await createStableUserIdFromEmail(ownerEmail), + email: ownerEmail, + rememberMe: false, + }, true, ) return setCookie.split(';')[0] ?? '' diff --git a/packages/worker/src/app/package-app-owner.ts b/packages/worker/src/app/package-app-owner.ts index 4283cf58c4..bd9d47d532 100644 --- a/packages/worker/src/app/package-app-owner.ts +++ b/packages/worker/src/app/package-app-owner.ts @@ -1,7 +1,7 @@ import { isSessionInvalidatedByStoredPasswordChange } from '#app/request-auth-cache.ts' import { resolveDisplayName } from '#worker/identity/username.ts' import { createDb, usersTable } from '#worker/db.ts' -import { resolveUserStableId } from '#worker/user-id.ts' +import { isStableUserId, resolveUserStableId } from '#worker/user-id.ts' /** * The account a hosted package app runs on behalf of. @@ -25,16 +25,17 @@ export type PackageAppOwner = { * accounts being deleted, suspended accounts, and sessions issued at or before * a password change are all refused. */ -export async function resolvePackageAppOwnerByUserId(input: { +export async function resolvePackageAppOwnerByStableUserId(input: { env: Env - userId: string + stableUserId: string issuedAt: number }): Promise { - const userId = /^\d+$/.test(input.userId) ? Number(input.userId) : NaN - if (!Number.isSafeInteger(userId) || userId <= 0) return null + if (!isStableUserId(input.stableUserId)) return null const db = createDb(input.env.APP_DB) - const userRecord = await db.findOne(usersTable, { where: { id: userId } }) + const userRecord = await db.findOne(usersTable, { + where: { stable_user_id: input.stableUserId }, + }) if (!userRecord) return null if (userRecord.deleting_at || userRecord.suspended_at) return null diff --git a/packages/worker/src/app/package-app-session.ts b/packages/worker/src/app/package-app-session.ts index 352a2c91f5..8960557fd3 100644 --- a/packages/worker/src/app/package-app-session.ts +++ b/packages/worker/src/app/package-app-session.ts @@ -1,5 +1,6 @@ import { createCookie } from '@remix-run/cookie' import { sha256Base64Url } from '@kody-internal/shared/sha256.ts' +import { isStableUserId } from '#worker/user-id.ts' /** * Host-scoped session for the package-app origin. @@ -18,17 +19,16 @@ import { sha256Base64Url } from '@kody-internal/shared/sha256.ts' const packageAppSessionCookieName = 'kody_pkg_session' const packageAppSessionMaxAgeSeconds = 60 * 60 * 12 -const packageAppSessionSecretPurpose = 'kody-package-app-session:v1' +const packageAppSessionSecretPurpose = 'kody-package-app-session:v2' export type PackageAppSession = { - /** Numeric app user id, as stored in the `kody_session` cookie payload. */ - userId: string + stableUserId: string username: string } type StoredPackageAppSession = { - v: 1 - pkgUserId: string + v: 2 + stableUserId: string pkgUsername: string issuedAt: number } @@ -75,9 +75,8 @@ function isStoredPackageAppSession( if (!value || typeof value !== 'object') return false const record = value as Record return ( - record.v === 1 && - typeof record.pkgUserId === 'string' && - record.pkgUserId.length > 0 && + record.v === 2 && + isStableUserId(record.stableUserId) && typeof record.pkgUsername === 'string' && record.pkgUsername.length > 0 && typeof record.issuedAt === 'number' && @@ -95,8 +94,8 @@ export async function createPackageAppSessionCookie(input: { const cookie = await getPackageAppSessionCookie(input.env) return await cookie.serialize( JSON.stringify({ - v: 1, - pkgUserId: input.session.userId, + v: 2, + stableUserId: input.session.stableUserId, pkgUsername: input.session.username, issuedAt: input.now ?? Date.now(), } satisfies StoredPackageAppSession), @@ -132,7 +131,7 @@ export async function readPackageAppSession(input: { if (!isStoredPackageAppSession(parsed)) return null return { session: { - userId: parsed.pkgUserId, + stableUserId: parsed.stableUserId, username: parsed.pkgUsername, }, issuedAt: parsed.issuedAt, diff --git a/packages/worker/src/app/permissions-server.node.test.ts b/packages/worker/src/app/permissions-server.node.test.ts index bfec41b25d..935185efc1 100644 --- a/packages/worker/src/app/permissions-server.node.test.ts +++ b/packages/worker/src/app/permissions-server.node.test.ts @@ -185,9 +185,11 @@ function createAuthenticatedUserEnv(input: { if ( normalizedQuery.startsWith('select') && normalizedQuery.includes('from "users"') && - /"id"\s*=/.test(normalizedQuery) + /"stable_user_id"\s*=/.test(normalizedQuery) ) { - const user = users.get(Number(params[0])) + const user = [...users.values()].find( + (row) => row.stable_user_id === params[0], + ) return { results: user ? [{ ...user }] : [], meta: { changes: 0 }, @@ -255,7 +257,7 @@ test('userHasPermission and userHasRole perform pure membership checks', () => { test('requireUserWithPermission and requireUserWithRole enforce auth and authorization', async () => { setAuthSessionSecret(testCookieSecret) const session: AuthSession = { - id: '1', + stableUserId: testStableUserIdFromEmail('user@example.com'), email: 'user@example.com', rememberMe: false, } diff --git a/packages/worker/src/app/request-auth-cache.ts b/packages/worker/src/app/request-auth-cache.ts index 985e502845..1e36965e09 100644 --- a/packages/worker/src/app/request-auth-cache.ts +++ b/packages/worker/src/app/request-auth-cache.ts @@ -61,16 +61,14 @@ async function resolveRequestAuth( } const { session, issuedAt, setCookie } = parsedSession - const userId = /^\d+$/.test(session.id) ? Number(session.id) : NaN const db = createDb(env.APP_DB) - const userRecord = - Number.isSafeInteger(userId) && userId > 0 - ? await db.findOne(usersTable, { where: { id: userId } }) - : null + const userRecord = await db.findOne(usersTable, { + where: { stable_user_id: session.stableUserId }, + }) if (!userRecord) { return { - sessionUserId: session.id, + sessionUserId: session.stableUserId, setCookie: await destroyAuthCookie(isSecureRequest(request)), user: null, } @@ -83,7 +81,7 @@ async function resolveRequestAuth( }) ) { return { - sessionUserId: session.id, + sessionUserId: session.stableUserId, setCookie: await destroyAuthCookie(isSecureRequest(request)), user: null, } @@ -94,7 +92,7 @@ async function resolveRequestAuth( try { ;({ roles, permissions } = await getUserRolesAndPermissions( env.APP_DB, - userId, + userRecord.id, )) } catch (error) { console.error('Failed to load roles for authenticated user:', error) @@ -116,10 +114,10 @@ async function resolveRequestAuth( } return { - sessionUserId: session.id, + sessionUserId: session.stableUserId, setCookie: setCookie ?? undefined, user: { - userId, + userId: userRecord.id, email: userRecord.email, emailVerified: Boolean(userRecord.email_verified_at), username: userRecord.username, @@ -134,9 +132,7 @@ async function resolveRequestAuth( username: userRecord.username, displayName, }, - artifactOwnerIds: Array.from( - new Set([session.id, stableUserId].filter(Boolean)), - ), + artifactOwnerIds: [stableUserId], }, } } diff --git a/packages/worker/src/app/routes.ts b/packages/worker/src/app/routes.ts index f3b161a258..2775ea01da 100644 --- a/packages/worker/src/app/routes.ts +++ b/packages/worker/src/app/routes.ts @@ -83,7 +83,7 @@ export const routes = route({ accountExport: '/account/export.json', admin: '/admin', adminUsers: '/admin/users', - adminUserDetail: '/admin/users/:userId', + adminUserDetail: '/admin/users/:stableUserId', adminUsersApi: '/admin/users.json', adminUsersApiPost: post('/admin/users.json'), adminRoles: '/admin/roles', diff --git a/packages/worker/src/app/ssr-render.node.test.ts b/packages/worker/src/app/ssr-render.node.test.ts index d7e617e6a2..dc72af8036 100644 --- a/packages/worker/src/app/ssr-render.node.test.ts +++ b/packages/worker/src/app/ssr-render.node.test.ts @@ -81,9 +81,11 @@ function createUserTestDb(users: Array) { if ( normalizedQuery.startsWith('select') && normalizedQuery.includes('from "users"') && - /"id"\s*=/.test(normalizedQuery) + /"stable_user_id"\s*=/.test(normalizedQuery) ) { - const user = userRecords.get(Number(params[0])) + const user = [...userRecords.values()].find( + (row) => row.stable_user_id === params[0], + ) return { results: user ? [{ ...user }] : [], meta: { changes: 0, last_row_id: 0 }, @@ -249,7 +251,7 @@ test('SSR HTML routes render page content and embedded loader data', async () => const accountCookie = await createAuthCookie( { - id: '1', + stableUserId: testStableUserIdFromEmail('user@example.com'), email: 'user@example.com', rememberMe: false, } satisfies AuthSession, diff --git a/packages/worker/src/app/verify-session.ts b/packages/worker/src/app/verify-session.ts index 3bed2f54b2..5ca84324ec 100644 --- a/packages/worker/src/app/verify-session.ts +++ b/packages/worker/src/app/verify-session.ts @@ -1,4 +1,5 @@ import { createCookie } from '@remix-run/cookie' +import { isStableUserId } from '#worker/user-id.ts' /** * Short-lived signed cookie that parks a password- or passkey-verified login @@ -9,11 +10,15 @@ import { createCookie } from '@remix-run/cookie' const pendingSessionMaxAgeSeconds = 60 * 10 export type PendingTwoFactorSession = { - id: string + stableUserId: string email: string rememberMe: boolean } +type StoredPendingTwoFactorSession = PendingTwoFactorSession & { + v: 2 +} + let pendingCookie: ReturnType | null = null let pendingSecret: string | null = null @@ -48,12 +53,12 @@ function getPendingCookie() { function isPendingTwoFactorSession( value: unknown, -): value is PendingTwoFactorSession { +): value is StoredPendingTwoFactorSession { if (!value || typeof value !== 'object') return false const record = value as Record return ( - typeof record.id === 'string' && - record.id.length > 0 && + record.v === 2 && + isStableUserId(record.stableUserId) && typeof record.email === 'string' && record.email.length > 0 && typeof record.rememberMe === 'boolean' @@ -64,7 +69,13 @@ export async function createVerifySessionCookie( session: PendingTwoFactorSession, secure: boolean, ) { - return getPendingCookie().serialize(JSON.stringify(session), { secure }) + return getPendingCookie().serialize( + JSON.stringify({ + ...session, + v: 2, + } satisfies StoredPendingTwoFactorSession), + { secure }, + ) } export async function destroyVerifySessionCookie(secure: boolean) { @@ -87,7 +98,11 @@ export async function readVerifySession( try { const parsed = JSON.parse(stored) if (isPendingTwoFactorSession(parsed)) { - return parsed + return { + stableUserId: parsed.stableUserId, + email: parsed.email, + rememberMe: parsed.rememberMe, + } } } catch { return null diff --git a/packages/worker/src/app/webauthn.ts b/packages/worker/src/app/webauthn.ts index e7fc2effc2..8d121d7f2f 100644 --- a/packages/worker/src/app/webauthn.ts +++ b/packages/worker/src/app/webauthn.ts @@ -1,5 +1,6 @@ import { createCookie } from '@remix-run/cookie' import { isSecureRequest } from '#app/auth-session.ts' +import { isStableUserId } from '#worker/user-id.ts' /** * WebAuthn ceremony state. The challenge lives in a short-lived signed @@ -12,9 +13,11 @@ export type WebAuthnChallenge = { challenge: string webauthnUserId?: string /** Registration only: the app user the ceremony was started for. */ - userId?: number + stableUserId?: string } +type StoredWebAuthnChallenge = WebAuthnChallenge & { v: 2 } + let challengeCookie: ReturnType | null = null let challengeSecret: string | null = null @@ -47,15 +50,16 @@ function getChallengeCookie() { return challengeCookie } -function isWebAuthnChallenge(value: unknown): value is WebAuthnChallenge { +function isWebAuthnChallenge(value: unknown): value is StoredWebAuthnChallenge { if (!value || typeof value !== 'object') return false const record = value as Record return ( + record.v === 2 && typeof record.challenge === 'string' && record.challenge.length > 0 && (record.webauthnUserId === undefined || typeof record.webauthnUserId === 'string') && - (record.userId === undefined || typeof record.userId === 'number') + (record.stableUserId === undefined || isStableUserId(record.stableUserId)) ) } @@ -63,7 +67,10 @@ export async function createWebAuthnChallengeCookie( data: WebAuthnChallenge, secure: boolean, ) { - return getChallengeCookie().serialize(JSON.stringify(data), { secure }) + return getChallengeCookie().serialize( + JSON.stringify({ ...data, v: 2 } satisfies StoredWebAuthnChallenge), + { secure }, + ) } export async function destroyWebAuthnChallengeCookie(secure: boolean) { @@ -86,7 +93,11 @@ export async function readWebAuthnChallenge( try { const parsed = JSON.parse(stored) if (isWebAuthnChallenge(parsed)) { - return parsed + return { + challenge: parsed.challenge, + webauthnUserId: parsed.webauthnUserId, + stableUserId: parsed.stableUserId, + } } } catch { return null diff --git a/packages/worker/src/feature-flags/service.node.test.ts b/packages/worker/src/feature-flags/service.node.test.ts index a3d4dab7ff..b2027794eb 100644 --- a/packages/worker/src/feature-flags/service.node.test.ts +++ b/packages/worker/src/feature-flags/service.node.test.ts @@ -30,6 +30,7 @@ type OverrideRow = { type UserRow = { id: number username: string + stable_user_id?: string } function createFeatureFlagsTestDb( @@ -48,7 +49,12 @@ function createFeatureFlagsTestDb( { ...row }, ]), ) - const users = new Map((input.users ?? []).map((row) => [row.id, { ...row }])) + const users = new Map( + (input.users ?? []).map((row) => [ + row.id, + { ...row, stable_user_id: row.stable_user_id ?? `stable-${row.id}` }, + ]), + ) let clock = 0 function nextTimestamp() { @@ -96,7 +102,11 @@ function createFeatureFlagsTestDb( !normalized.includes('where') ) { return { - results: [...globals.values()].map((row) => ({ ...row })), + results: [...globals.values()].map((row) => ({ + ...row, + updated_by_stable_user_id: + users.get(row.updated_by ?? -1)?.stable_user_id ?? null, + })), meta: { changes: 0 }, } as { results: Array; meta: { changes: number } } } @@ -129,6 +139,7 @@ function createFeatureFlagsTestDb( enabled: row.enabled, updated_at: row.updated_at, username: user.username, + stable_user_id: user.stable_user_id, } }) .filter((row) => row !== null) @@ -504,11 +515,11 @@ test('listFeatureFlagsForAdmin includes registry flags and stale DB-only keys', enabled: true, rolloutPercent: 25, note: 'rolling out', - updatedBy: 1, + updatedByStableUserId: null, }, overrides: [ { - userId: 4, + stableUserId: 'stable-4', username: 'bob', enabled: true, }, @@ -538,7 +549,7 @@ test('listFeatureFlagsForAdmin includes registry flags and stale DB-only keys', enabled: false, rolloutPercent: null, note: 'leftover', - updatedBy: null, + updatedByStableUserId: null, updatedAt: '2026-06-01T00:00:00.000Z', }, overrides: [], @@ -553,7 +564,7 @@ test('listFeatureFlagsForAdmin includes registry flags and stale DB-only keys', global: null, overrides: [ { - userId: 3, + stableUserId: 'stable-3', username: 'alice', enabled: false, updatedAt: '2026-07-03T00:00:00.000Z', diff --git a/packages/worker/src/feature-flags/service.ts b/packages/worker/src/feature-flags/service.ts index 60918a082b..bfc172b49e 100644 --- a/packages/worker/src/feature-flags/service.ts +++ b/packages/worker/src/feature-flags/service.ts @@ -17,7 +17,7 @@ type GlobalFlagRow = { enabled: number rollout_percent: number | null note: string - updated_by: number | null + updated_by_stable_user_id: string | null updated_at: string } @@ -27,6 +27,7 @@ type OverrideFlagRow = { enabled: number updated_at: string username: string + stable_user_id: string } type OverrideEnabledRow = { @@ -260,8 +261,10 @@ export async function listFeatureFlagsForAdmin( ): Promise> { const globalResult = await db .prepare( - `SELECT key, enabled, rollout_percent, note, updated_by, updated_at - FROM feature_flags`, + `SELECT f.key, f.enabled, f.rollout_percent, f.note, + u.stable_user_id AS updated_by_stable_user_id, f.updated_at + FROM feature_flags f + LEFT JOIN users u ON u.id = f.updated_by`, ) .all() const globalByKey = new Map( @@ -270,7 +273,8 @@ export async function listFeatureFlagsForAdmin( const overrideResult = await db .prepare( - `SELECT o.flag_key, o.user_id, o.enabled, o.updated_at, u.username + `SELECT o.flag_key, o.user_id, o.enabled, o.updated_at, u.username, + u.stable_user_id FROM feature_flag_user_overrides o JOIN users u ON u.id = o.user_id ORDER BY o.flag_key ASC, u.username ASC`, @@ -283,7 +287,7 @@ export async function listFeatureFlagsForAdmin( for (const row of overrideResult.results ?? []) { const list = overridesByKey.get(row.flag_key) ?? [] list.push({ - userId: row.user_id, + stableUserId: row.stable_user_id, username: row.username, enabled: row.enabled === 1, updatedAt: row.updated_at, @@ -307,7 +311,7 @@ export async function listFeatureFlagsForAdmin( enabled: global.enabled === 1, rolloutPercent: global.rollout_percent, note: global.note, - updatedBy: global.updated_by, + updatedByStableUserId: global.updated_by_stable_user_id, updatedAt: global.updated_at, } : null, @@ -335,7 +339,7 @@ export async function listFeatureFlagsForAdmin( enabled: global.enabled === 1, rolloutPercent: global.rollout_percent, note: global.note, - updatedBy: global.updated_by, + updatedByStableUserId: global.updated_by_stable_user_id, updatedAt: global.updated_at, } : null, diff --git a/packages/worker/src/feature-flags/types.ts b/packages/worker/src/feature-flags/types.ts index e6dd5f85cb..7f8fb68cdb 100644 --- a/packages/worker/src/feature-flags/types.ts +++ b/packages/worker/src/feature-flags/types.ts @@ -12,11 +12,11 @@ export type AdminFeatureFlag = { enabled: boolean rolloutPercent: number | null note: string - updatedBy: number | null + updatedByStableUserId: string | null updatedAt: string } | null overrides: Array<{ - userId: number + stableUserId: string username: string enabled: boolean updatedAt: string diff --git a/packages/worker/src/identity/admin-user-creation.ts b/packages/worker/src/identity/admin-user-creation.ts index 2522b3fb84..f53b183edc 100644 --- a/packages/worker/src/identity/admin-user-creation.ts +++ b/packages/worker/src/identity/admin-user-creation.ts @@ -38,6 +38,7 @@ export class AdminCreateUserError extends Error { export type AdminCreatedUser = { userId: number + stableUserId: string email: string username: string setupLink: string @@ -181,6 +182,7 @@ export async function adminCreateUserWithPasswordSetup(input: { return { userId, + stableUserId, email, username, setupTokenExpiresAt, diff --git a/packages/worker/src/mcp/capabilities/admin/admin-capabilities.node.test.ts b/packages/worker/src/mcp/capabilities/admin/admin-capabilities.node.test.ts index 543329a008..95451cd0f8 100644 --- a/packages/worker/src/mcp/capabilities/admin/admin-capabilities.node.test.ts +++ b/packages/worker/src/mcp/capabilities/admin/admin-capabilities.node.test.ts @@ -13,6 +13,7 @@ import { adminUserGetCapability } from './admin-user-get.ts' import { adminUserListCapability } from './admin-user-list.ts' import { adminUserUpdateCapability } from './admin-user-update.ts' import { testStableUserIdFromEmail } from '#worker/test-support/stable-user-id.ts' +import { loadAdminUserByTarget } from '#worker/admin/users-data.ts' type UserRow = { id: number @@ -179,18 +180,18 @@ function createAdminCapabilityTestDb(input: { } if ( normalizedQuery.includes( - 'select id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at from users where id = ?', + 'select id, stable_user_id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at from users where stable_user_id = ?', ) ) { - return (users.find((user) => user.id === params[0]) ?? + return (users.find((user) => user.stable_user_id === params[0]) ?? null) as T | null } if ( normalizedQuery.includes( - 'select id, username, email, plan, stripe_plan, stable_user_id from users where id = ?', + 'select id, username, email, plan, stripe_plan, stable_user_id from users where stable_user_id = ?', ) ) { - const user = users.find((row) => row.id === Number(params[0])) + const user = users.find((row) => row.stable_user_id === params[0]) return ( user ? { @@ -206,13 +207,23 @@ function createAdminCapabilityTestDb(input: { } if ( normalizedQuery.includes( - 'select id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at from users where email = ? collate nocase', + 'select id, stable_user_id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at from users where email = ? collate nocase', ) ) { const email = String(params[0]).toLowerCase() return (users.find((user) => user.email.toLowerCase() === email) ?? null) as T | null } + if ( + normalizedQuery.includes( + 'select id, stable_user_id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at from users where username = ? collate nocase', + ) + ) { + const username = String(params[0]).toLowerCase() + return (users.find( + (user) => user.username.toLowerCase() === username, + ) ?? null) as T | null + } if (normalizedQuery.includes('select id from users where email')) { const email = String(params[0]).toLowerCase() const user = users.find((row) => row.email.toLowerCase() === email) @@ -282,7 +293,7 @@ function createAdminCapabilityTestDb(input: { async all() { if ( normalizedQuery.includes( - 'select id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at from users order by id asc limit ? offset ?', + 'select id, stable_user_id, username, email, email_verified_at, plan, suspended_at, email_outbound_paused_at, created_at, updated_at from users order by id asc limit ? offset ?', ) ) { const pageSize = Number(params[0]) @@ -551,14 +562,14 @@ test('admin capabilities list and get account metadata and query sanitized audit pageSize: 10, users: [ expect.objectContaining({ - id: 1, + stableUserId: testStableUserIdFromEmail('admin@example.com'), email: 'admin@example.com', email_verified: true, email_verified_at: '2026-01-01T00:00:00.000Z', roles: ['admin', 'user'], }), expect.objectContaining({ - id: 2, + stableUserId: testStableUserIdFromEmail('jane@example.com'), email: 'jane@example.com', email_verified: false, email_verified_at: null, @@ -572,15 +583,18 @@ test('admin capabilities list and get account metadata and query sanitized audit ctx, ) expect(getByEmail.user).toMatchObject({ - id: 2, + stableUserId: testStableUserIdFromEmail('jane@example.com'), username: 'jane', email: 'jane@example.com', roles: ['user'], }) - const usage = await adminUserUsageCapability.handler({ id: 2 }, ctx) + const usage = await adminUserUsageCapability.handler( + { username: 'jane' }, + ctx, + ) expect(usage.usage).toMatchObject({ - userId: 2, + stableUserId: testStableUserIdFromEmail('jane@example.com'), username: 'jane', plan: 'free', }) @@ -771,7 +785,7 @@ test('admin_user_create records audit metadata and assigns the default role', as ) expect(result.createdUser).toMatchObject({ - userId: 2, + stableUserId: testStableUserIdFromEmail('person+launch@example.com'), email: 'person+launch@example.com', }) expect(users.find((user) => user.id === 2)).toMatchObject({ @@ -784,7 +798,7 @@ test('admin_user_create records audit metadata and assigns the default role', as expect.objectContaining({ action: 'admin_user_create', result: 'success', - reason: 'target_user_id=2;target_email=***@example.com', + reason: `target_stable_user_id=${testStableUserIdFromEmail('person+launch@example.com')};target_email=***@example.com`, }), ]) }) @@ -821,7 +835,7 @@ test('admin_user_update sets plan and maps null clear to free with audit metadat ctx, ) expect(setByEmail.user).toMatchObject({ - id: 2, + stableUserId: testStableUserIdFromEmail('jane@example.com'), username: 'jane', plan: 'pro', roles: ['user'], @@ -829,22 +843,28 @@ test('admin_user_update sets plan and maps null clear to free with audit metadat expect(users.find((user) => user.id === 2)?.plan).toBe('pro') const clearById = await adminUserUpdateCapability.handler( - { id: 2, plan: null }, + { + stableUserId: testStableUserIdFromEmail('jane@example.com'), + plan: null, + }, ctx, ) - expect(clearById.user).toMatchObject({ id: 2, plan: 'free' }) + expect(clearById.user).toMatchObject({ + stableUserId: testStableUserIdFromEmail('jane@example.com'), + plan: 'free', + }) expect(users.find((user) => user.id === 2)?.plan).toBe('free') expect(auditEvents).toEqual([ expect.objectContaining({ action: 'admin_user_update', result: 'success', - reason: 'target_user_id=2;plan=pro', + reason: `target_stable_user_id=${testStableUserIdFromEmail('jane@example.com')};plan=pro`, }), expect.objectContaining({ action: 'admin_user_update', result: 'success', - reason: 'target_user_id=2;plan=free', + reason: `target_stable_user_id=${testStableUserIdFromEmail('jane@example.com')};plan=free`, }), ]) }) @@ -885,3 +905,25 @@ test('admin_user_update rejects unknown users and unknown plan names', async () ), ).rejects.toThrow() }) + +test('admin user lookup does not fall through from an invalid stable id', async () => { + const { db } = createAdminCapabilityTestDb({ + users: [ + adminTestUser({ + id: 1, + username: 'admin', + email: 'admin@example.com', + created_at: '2026-01-01 00:00:00', + updated_at: '2026-01-02 00:00:00', + }), + ], + userRoles: [{ user_id: 1, role_name: 'admin' }], + }) + + await expect( + loadAdminUserByTarget(db, { + stableUserId: 'not-a-stable-id', + email: 'admin@example.com', + }), + ).resolves.toBeNull() +}) diff --git a/packages/worker/src/mcp/capabilities/admin/admin-feature-flag-capabilities.node.test.ts b/packages/worker/src/mcp/capabilities/admin/admin-feature-flag-capabilities.node.test.ts index 97af82d130..f33143ceab 100644 --- a/packages/worker/src/mcp/capabilities/admin/admin-feature-flag-capabilities.node.test.ts +++ b/packages/worker/src/mcp/capabilities/admin/admin-feature-flag-capabilities.node.test.ts @@ -5,6 +5,7 @@ vi.unmock('#worker/audit-log.ts') import { adminFeatureFlagListCapability } from './admin-feature-flag-list.ts' import { adminFeatureFlagOverrideCapability } from './admin-feature-flag-override.ts' import { adminFeatureFlagSetCapability } from './admin-feature-flag-set.ts' +import { testStableUserIdFromEmail } from '#worker/test-support/stable-user-id.ts' type UserRow = { id: number @@ -94,10 +95,19 @@ function createFeatureFlagCapabilityTestDb(input: { return (users.find((user) => user.id === Number(params[0])) ?? null) as T | null } - if (normalized.includes('select id from users where username = ?')) { + if ( + normalized.includes( + 'select id, stable_user_id from users where username = ?', + ) + ) { const username = String(params[0]) const user = users.find((row) => row.username === username) - return user ? ({ id: user.id } as T) : null + return user + ? ({ + id: user.id, + stable_user_id: user.stable_user_id, + } as T) + : null } if ( normalized.includes('from feature_flag_user_overrides') && @@ -130,6 +140,9 @@ function createFeatureFlagCapabilityTestDb(input: { return { results: [...globals.values()].map((row) => ({ ...row, + updated_by_stable_user_id: + users.find((user) => user.id === row.updated_by) + ?.stable_user_id ?? null, })) as Array, } } @@ -147,6 +160,7 @@ function createFeatureFlagCapabilityTestDb(input: { enabled: row.enabled, updated_at: row.updated_at, username: user.username, + stable_user_id: user.stable_user_id, } }) .filter((row) => row !== null) @@ -270,7 +284,7 @@ function createAdminCapabilityContext(db: D1Database) { callerContext: createMcpCallerContext({ baseUrl: 'https://example.com', user: { - userId: 'admin-stable', + userId: testStableUserIdFromEmail('admin@example.com'), email: 'admin@example.com', displayName: 'admin', roles: ['admin'], @@ -287,13 +301,13 @@ test('admin feature flag MCP capabilities: list, set, override, and audit wiring id: 1, username: 'admin', email: 'admin@example.com', - stable_user_id: 'admin-stable', + stable_user_id: testStableUserIdFromEmail('admin@example.com'), }, { id: 2, username: 'jane', email: 'jane@example.com', - stable_user_id: 'jane-stable', + stable_user_id: testStableUserIdFromEmail('jane@example.com'), }, ], }) @@ -336,7 +350,7 @@ test('admin feature flag MCP capabilities: list, set, override, and audit wiring enabled: true, rolloutPercent: 25, note: 'gradual rollout', - updatedBy: 1, + updatedByStableUserId: testStableUserIdFromEmail('admin@example.com'), }, }) expect(globals.get('demo-indicator')).toMatchObject({ @@ -353,7 +367,7 @@ test('admin feature flag MCP capabilities: list, set, override, and audit wiring ).rejects.toThrow(/Unknown feature flag key/) const setByUsername = await adminFeatureFlagOverrideCapability.handler( - { key: 'demo-indicator', username: 'jane', enabled: true }, + { key: 'demo-indicator', username: 'JANE', enabled: true }, ctx, ) expect(setByUsername).toMatchObject({ @@ -362,7 +376,7 @@ test('admin feature flag MCP capabilities: list, set, override, and audit wiring key: 'demo-indicator', overrides: [ expect.objectContaining({ - userId: 2, + stableUserId: testStableUserIdFromEmail('jane@example.com'), username: 'jane', enabled: true, }), @@ -375,7 +389,11 @@ test('admin feature flag MCP capabilities: list, set, override, and audit wiring }) const cleared = await adminFeatureFlagOverrideCapability.handler( - { key: 'demo-indicator', userId: 2, clear: true }, + { + key: 'demo-indicator', + stableUserId: testStableUserIdFromEmail('jane@example.com'), + clear: true, + }, ctx, ) expect(cleared.cleared).toBe(true) diff --git a/packages/worker/src/mcp/capabilities/admin/admin-feature-flag-override.ts b/packages/worker/src/mcp/capabilities/admin/admin-feature-flag-override.ts index c7eea0ba8a..eb1ed42033 100644 --- a/packages/worker/src/mcp/capabilities/admin/admin-feature-flag-override.ts +++ b/packages/worker/src/mcp/capabilities/admin/admin-feature-flag-override.ts @@ -10,27 +10,25 @@ import { import { adminMutationCapabilityAccess, auditAdminCapabilityInvocation, + stableUserIdSchema, } from './admin-shared.ts' import { adminFeatureFlagSchema, assertFeatureFlagKey, resolveActingAdminUserId, - resolveTargetUserId, + resolveTargetUser, } from './feature-flag-shared.ts' const inputSchema = z .object({ key: z.string().min(1).describe('Feature flag key from the code registry.'), - userId: z - .number() - .int() - .positive() - .optional() - .describe('Numeric users.id for the override target.'), + stableUserId: stableUserIdSchema.optional(), username: z .string() .optional() - .describe('Username for the override target when userId is omitted.'), + .describe( + 'Username for the override target when stableUserId is omitted.', + ), enabled: z .boolean() .optional() @@ -58,17 +56,17 @@ const inputSchema = z path: ['enabled'], }) } - if (value.userId === undefined && value.username === undefined) { + if (value.stableUserId === undefined && value.username === undefined) { context.addIssue({ code: 'custom', - message: 'Provide either userId or username.', - path: ['userId'], + message: 'Provide either stableUserId or username.', + path: ['stableUserId'], }) } - if (value.userId !== undefined && value.username !== undefined) { + if (value.stableUserId !== undefined && value.username !== undefined) { context.addIssue({ code: 'custom', - message: 'Provide either userId or username, not both.', + message: 'Provide either stableUserId or username, not both.', path: ['username'], }) } @@ -85,7 +83,7 @@ export const adminFeatureFlagOverrideCapability = defineDomainCapability( ...adminMutationCapabilityAccess, name: 'admin_feature_flag_override', description: - 'Set or clear a per-user feature flag override by userId or username. Admin-only; never returns user content.', + 'Set or clear a per-user feature flag override by stable user id or username. Admin-only; never returns user content.', keywords: [ 'admin', 'feature flags', @@ -102,26 +100,26 @@ export const adminFeatureFlagOverrideCapability = defineDomainCapability( 'admin_feature_flag_override', async () => { const key = assertFeatureFlagKey(args.key) - const targetUserId = await resolveTargetUserId(ctx.env.APP_DB, { - userId: args.userId, + const target = await resolveTargetUser(ctx.env.APP_DB, { + stableUserId: args.stableUserId, username: args.username, }) const clear = args.clear === true if (clear) { const cleared = await clearFeatureFlagUserOverride(ctx.env.APP_DB, { key, - userId: targetUserId, + userId: target.dbUserId, }) if (!cleared) { throw new Error( - `No override exists for feature flag "${key}" and userId ${targetUserId}.`, + `No override exists for feature flag "${key}" and stableUserId ${target.stableUserId}.`, ) } } else { const updatedBy = await resolveActingAdminUserId(ctx) await setFeatureFlagUserOverride(ctx.env.APP_DB, { key, - userId: targetUserId, + userId: target.dbUserId, enabled: args.enabled === true, updatedBy, }) diff --git a/packages/worker/src/mcp/capabilities/admin/admin-platform-account-create.ts b/packages/worker/src/mcp/capabilities/admin/admin-platform-account-create.ts index ac9242e186..a13b84bcb3 100644 --- a/packages/worker/src/mcp/capabilities/admin/admin-platform-account-create.ts +++ b/packages/worker/src/mcp/capabilities/admin/admin-platform-account-create.ts @@ -6,6 +6,7 @@ import { adminMutationCapabilityAccess, auditAdminCapabilityInvocation, buildCreatedUserAuditReason, + stableUserIdSchema, } from './admin-shared.ts' const inputSchema = z.object({ @@ -20,7 +21,7 @@ const inputSchema = z.object({ const outputSchema = z.object({ platformAccount: z.object({ - userId: z.number().int().positive(), + stableUserId: stableUserIdSchema, email: z.string(), username: z.string(), }), @@ -56,7 +57,7 @@ export const adminPlatformAccountCreateCapability = defineDomainCapability( }) return { platformAccount: { - userId: created.userId, + stableUserId: created.stableUserId, email: created.email, username: created.username, }, @@ -65,7 +66,7 @@ export const adminPlatformAccountCreateCapability = defineDomainCapability( { successReason: ({ platformAccount }) => buildCreatedUserAuditReason({ - userId: platformAccount.userId, + stableUserId: platformAccount.stableUserId, email: platformAccount.email, }), }, diff --git a/packages/worker/src/mcp/capabilities/admin/admin-shared.ts b/packages/worker/src/mcp/capabilities/admin/admin-shared.ts index 0fdda45bec..6284c4b914 100644 --- a/packages/worker/src/mcp/capabilities/admin/admin-shared.ts +++ b/packages/worker/src/mcp/capabilities/admin/admin-shared.ts @@ -22,8 +22,13 @@ export const roleNameSchema = z.enum(roleNames) export const planNameSchema = z.enum(planNames) +export const stableUserIdSchema = z + .string() + .regex(/^[a-f0-9]{64}$/) + .describe('Stable users.stable_user_id.') + export const adminUserMetadataSchema = z.object({ - id: z.number().int().positive(), + stableUserId: stableUserIdSchema, username: z.string(), email: z.string(), email_verified: z @@ -96,11 +101,11 @@ export async function auditAdminCapabilityInvocation( } export function buildCreatedUserAuditReason(input: { - userId: number + stableUserId: string email: string }) { return [ - `target_user_id=${input.userId}`, + `target_stable_user_id=${input.stableUserId}`, `target_email=${redactEmailRecipient(input.email)}`, ].join(';') } diff --git a/packages/worker/src/mcp/capabilities/admin/admin-user-create.ts b/packages/worker/src/mcp/capabilities/admin/admin-user-create.ts index 976acd061e..429c3d55f5 100644 --- a/packages/worker/src/mcp/capabilities/admin/admin-user-create.ts +++ b/packages/worker/src/mcp/capabilities/admin/admin-user-create.ts @@ -6,6 +6,7 @@ import { adminMutationCapabilityAccess, auditAdminCapabilityInvocation, buildCreatedUserAuditReason, + stableUserIdSchema, } from './admin-shared.ts' const inputSchema = z.object({ @@ -21,7 +22,7 @@ const inputSchema = z.object({ const outputSchema = z.object({ createdUser: z.object({ - userId: z.number().int().positive(), + stableUserId: stableUserIdSchema, email: z.string(), username: z.string(), setupLink: z.string(), @@ -58,12 +59,13 @@ export const adminUserCreateCapability = defineDomainCapability( username: args.username, setupLinkOrigin: ctx.callerContext.baseUrl, }) - return { createdUser } + const { userId: _userId, ...boundaryUser } = createdUser + return { createdUser: boundaryUser } }, { successReason: ({ createdUser }) => buildCreatedUserAuditReason({ - userId: createdUser.userId, + stableUserId: createdUser.stableUserId, email: createdUser.email, }), }, diff --git a/packages/worker/src/mcp/capabilities/admin/admin-user-get.ts b/packages/worker/src/mcp/capabilities/admin/admin-user-get.ts index 3d9c4b5901..9e15015354 100644 --- a/packages/worker/src/mcp/capabilities/admin/admin-user-get.ts +++ b/packages/worker/src/mcp/capabilities/admin/admin-user-get.ts @@ -1,26 +1,27 @@ import { z } from 'zod' -import { loadAdminUserByIdOrEmail } from '#worker/admin/users-data.ts' +import { loadAdminUserByTarget } from '#worker/admin/users-data.ts' import { defineDomainCapability } from '#mcp/capabilities/define-domain-capability.ts' import { capabilityDomainNames } from '#mcp/capabilities/domain-metadata.ts' import { adminCapabilityAccess, adminUserMetadataSchema, auditAdminCapabilityInvocation, + stableUserIdSchema, } from './admin-shared.ts' const inputSchema = z .object({ - id: z - .number() - .int() - .positive() - .optional() - .describe('Numeric users.id to look up.'), + stableUserId: stableUserIdSchema.optional(), email: z.string().email().optional().describe('Email address to look up.'), + username: z.string().min(1).optional().describe('Username to look up.'), }) - .refine((value) => value.id !== undefined || value.email !== undefined, { - message: 'Provide either id or email.', - }) + .refine( + (value) => + [value.stableUserId, value.email, value.username].filter( + (item) => item !== undefined, + ).length === 1, + { message: 'Provide exactly one of stableUserId, email, or username.' }, + ) const outputSchema = z.object({ user: adminUserMetadataSchema.nullable(), @@ -32,13 +33,13 @@ export const adminUserGetCapability = defineDomainCapability( ...adminCapabilityAccess, name: 'admin_user_get', description: - 'Get one user account metadata record and roles by id or email. Admin-only; never returns user content.', + 'Get one user account metadata record and roles by stable user id, email, or username. Admin-only; never returns user content.', keywords: ['admin', 'user', 'account', 'roles', 'lookup', 'rbac'], inputSchema, outputSchema, async handler(args, ctx) { return auditAdminCapabilityInvocation(ctx, 'admin_user_get', async () => { - const user = await loadAdminUserByIdOrEmail(ctx.env.APP_DB, args) + const user = await loadAdminUserByTarget(ctx.env.APP_DB, args) return { user } }) }, diff --git a/packages/worker/src/mcp/capabilities/admin/admin-user-update.ts b/packages/worker/src/mcp/capabilities/admin/admin-user-update.ts index 0b4fd0fc14..19c759fb86 100644 --- a/packages/worker/src/mcp/capabilities/admin/admin-user-update.ts +++ b/packages/worker/src/mcp/capabilities/admin/admin-user-update.ts @@ -8,26 +8,27 @@ import { adminUserMetadataSchema, auditAdminCapabilityInvocation, planNameSchema, + stableUserIdSchema, } from './admin-shared.ts' const inputSchema = z .object({ - id: z - .number() - .int() - .positive() - .optional() - .describe('Numeric users.id to update.'), + stableUserId: stableUserIdSchema.optional(), email: z.string().email().optional().describe('Email address to update.'), + username: z.string().min(1).optional().describe('Username to update.'), plan: planNameSchema .nullable() .describe( 'Entitlement plan to set. Null maps to free (never persists NULL).', ), }) - .refine((value) => value.id !== undefined || value.email !== undefined, { - message: 'Provide either id or email.', - }) + .refine( + (value) => + [value.stableUserId, value.email, value.username].filter( + (item) => item !== undefined, + ).length === 1, + { message: 'Provide exactly one of stableUserId, email, or username.' }, + ) const outputSchema = z.object({ user: adminUserMetadataSchema, @@ -39,7 +40,7 @@ export const adminUserUpdateCapability = defineDomainCapability( ...adminMutationCapabilityAccess, name: 'admin_user_update', description: - 'Update account metadata for one user by id or email. Supports setting the entitlement plan (null maps to free). Admin-only; never touches user content.', + 'Update account metadata for one user by stable user id, email, or username. Supports setting the entitlement plan (null maps to free). Admin-only; never touches user content.', keywords: ['admin', 'user', 'update', 'account', 'plan', 'entitlements'], inputSchema, outputSchema, @@ -49,8 +50,9 @@ export const adminUserUpdateCapability = defineDomainCapability( 'admin_user_update', async () => { const user = await updateAdminUserPlan(ctx.env.APP_DB, { - id: args.id, + stableUserId: args.stableUserId, email: args.email, + username: args.username, plan: resolvePlanWrite(args.plan), }) if (!user) { @@ -60,7 +62,7 @@ export const adminUserUpdateCapability = defineDomainCapability( }, { successReason: ({ user }) => - `target_user_id=${user.id};plan=${user.plan}`, + `target_stable_user_id=${user.stableUserId};plan=${user.plan}`, }, ) }, diff --git a/packages/worker/src/mcp/capabilities/admin/admin-user-usage.ts b/packages/worker/src/mcp/capabilities/admin/admin-user-usage.ts index 2dfa4210c1..14f7f843b6 100644 --- a/packages/worker/src/mcp/capabilities/admin/admin-user-usage.ts +++ b/packages/worker/src/mcp/capabilities/admin/admin-user-usage.ts @@ -1,12 +1,13 @@ import { z } from 'zod' import { planNames } from '#worker/entitlements/plans.ts' -import { loadAdminUserByIdOrEmail } from '#worker/admin/users-data.ts' +import { loadAdminUserByTarget } from '#worker/admin/users-data.ts' import { loadAdminUserUsageData } from '#worker/admin/user-usage-data.ts' import { defineDomainCapability } from '#mcp/capabilities/define-domain-capability.ts' import { capabilityDomainNames } from '#mcp/capabilities/domain-metadata.ts' import { adminCapabilityAccess, auditAdminCapabilityInvocation, + stableUserIdSchema, } from './admin-shared.ts' const usageMetricSchema = z.enum([ @@ -62,22 +63,22 @@ const entitlementConsumptionSchema = z.object({ const inputSchema = z .object({ - id: z - .number() - .int() - .positive() - .optional() - .describe('Numeric users.id to look up.'), + stableUserId: stableUserIdSchema.optional(), email: z.string().email().optional().describe('Email address to look up.'), + username: z.string().min(1).optional().describe('Username to look up.'), }) - .refine((value) => value.id !== undefined || value.email !== undefined, { - message: 'Provide either id or email.', - }) + .refine( + (value) => + [value.stableUserId, value.email, value.username].filter( + (item) => item !== undefined, + ).length === 1, + { message: 'Provide exactly one of stableUserId, email, or username.' }, + ) const outputSchema = z.object({ usage: z .object({ - userId: z.number().int().positive(), + stableUserId: stableUserIdSchema, username: z.string(), plan: planSchema, currentMonth: z.string(), @@ -101,7 +102,7 @@ export const adminUserUsageCapability = defineDomainCapability( ...adminCapabilityAccess, name: 'admin_user_usage', description: - 'Read usage rollups, entitlement counters, and plan-limit consumption for one user account by id or email. Admin-only; never returns user content.', + 'Read usage rollups, entitlement counters, and plan-limit consumption for one user account by stable user id, email, or username. Admin-only; never returns user content.', keywords: ['admin', 'usage', 'quotas', 'entitlements', 'plans', 'metering'], inputSchema, outputSchema, @@ -110,9 +111,9 @@ export const adminUserUsageCapability = defineDomainCapability( ctx, 'admin_user_usage', async () => { - const user = await loadAdminUserByIdOrEmail(ctx.env.APP_DB, args) + const user = await loadAdminUserByTarget(ctx.env.APP_DB, args) if (!user) return { usage: null } - const data = await loadAdminUserUsageData(ctx.env, user.id) + const data = await loadAdminUserUsageData(ctx.env, user.stableUserId) if (!data) return { usage: null } const { ok: _ok, ...usage } = data return { usage } diff --git a/packages/worker/src/mcp/capabilities/admin/feature-flag-shared.ts b/packages/worker/src/mcp/capabilities/admin/feature-flag-shared.ts index c7f364c542..b5ea49d24c 100644 --- a/packages/worker/src/mcp/capabilities/admin/feature-flag-shared.ts +++ b/packages/worker/src/mcp/capabilities/admin/feature-flag-shared.ts @@ -6,10 +6,11 @@ import { isFeatureFlagKey, type FeatureFlagKey, } from '#worker/feature-flags/registry.ts' -import { normalizeStableUserId } from '#worker/user-id.ts' +import { isStableUserId, normalizeStableUserId } from '#worker/user-id.ts' +import { stableUserIdSchema } from './admin-shared.ts' export const adminFeatureFlagOverrideSchema = z.object({ - userId: z.number().int().positive(), + stableUserId: stableUserIdSchema, username: z.string(), enabled: z.boolean(), updatedAt: z.string(), @@ -25,7 +26,7 @@ export const adminFeatureFlagSchema = z.object({ enabled: z.boolean(), rolloutPercent: z.number().int().min(0).max(100).nullable(), note: z.string(), - updatedBy: z.number().int().positive().nullable(), + updatedByStableUserId: stableUserIdSchema.nullable(), updatedAt: z.string(), }) .nullable(), @@ -60,36 +61,40 @@ export async function resolveActingAdminUserId( return row.id } -export async function resolveTargetUserId( +export async function resolveTargetUser( db: D1Database, - input: { userId?: number; username?: string }, -): Promise { - if (input.userId !== undefined && input.username !== undefined) { - throw new Error('Provide either userId or username, not both.') + input: { stableUserId?: string; username?: string }, +): Promise<{ dbUserId: number; stableUserId: string }> { + if (input.stableUserId !== undefined && input.username !== undefined) { + throw new Error('Provide either stableUserId or username, not both.') } - if (input.userId !== undefined) { + if (input.stableUserId !== undefined) { + const stableUserId = normalizeStableUserId(input.stableUserId) + if (!isStableUserId(stableUserId)) { + throw new Error('stableUserId must be a valid stable user id.') + } const row = await db - .prepare(`SELECT id FROM users WHERE id = ?`) - .bind(input.userId) - .first<{ id: number }>() + .prepare(`SELECT id, stable_user_id FROM users WHERE stable_user_id = ?`) + .bind(stableUserId) + .first<{ id: number; stable_user_id: string }>() if (!row) { - throw new Error(`User not found for userId ${input.userId}.`) + throw new Error(`User not found for stableUserId ${stableUserId}.`) } - return row.id + return { dbUserId: row.id, stableUserId: row.stable_user_id } } if (input.username !== undefined) { - const username = input.username.trim() + const username = input.username.trim().toLowerCase() if (!username) { throw new Error('username must not be empty.') } const row = await db - .prepare(`SELECT id FROM users WHERE username = ?`) + .prepare(`SELECT id, stable_user_id FROM users WHERE username = ?`) .bind(username) - .first<{ id: number }>() + .first<{ id: number; stable_user_id: string }>() if (!row) { throw new Error(`User not found for username "${username}".`) } - return row.id + return { dbUserId: row.id, stableUserId: row.stable_user_id } } - throw new Error('Provide either userId or username.') + throw new Error('Provide either stableUserId or username.') } diff --git a/packages/worker/src/oauth-handlers.ts b/packages/worker/src/oauth-handlers.ts index 357180398d..4d820cae95 100644 --- a/packages/worker/src/oauth-handlers.ts +++ b/packages/worker/src/oauth-handlers.ts @@ -888,11 +888,11 @@ export async function handleAuthorizeRequest( approvedUserId = resolveUserStableId(userRecord) } else if (sessionEmail) { const db = createDb(env.APP_DB) - const sessionDbUserId = Number(session?.id) - const userRecord = - Number.isSafeInteger(sessionDbUserId) && sessionDbUserId > 0 - ? await db.findOne(usersTable, { where: { id: sessionDbUserId } }) - : await db.findOne(usersTable, { where: { email: sessionEmail } }) + const userRecord = session?.stableUserId + ? await db.findOne(usersTable, { + where: { stable_user_id: session.stableUserId }, + }) + : await db.findOne(usersTable, { where: { email: sessionEmail } }) if (!userRecord) { void logAuditEvent({ category: 'oauth', @@ -924,7 +924,7 @@ export async function handleAuthorizeRequest( if (session && approvedEmail !== sessionEmail) { setCookie = await createAuthCookie( { - id: session.id, + stableUserId: session.stableUserId, email: approvedEmail, rememberMe: session.rememberMe, }, diff --git a/packages/worker/src/oauth-handlers.workers.test.ts b/packages/worker/src/oauth-handlers.workers.test.ts index 1188fa5c97..f0ed6add6e 100644 --- a/packages/worker/src/oauth-handlers.workers.test.ts +++ b/packages/worker/src/oauth-handlers.workers.test.ts @@ -408,7 +408,11 @@ test('authorize info, denial, approval, and default scopes follow the OAuth work }) setAuthSessionSecret(cookieSecret) const cookie = await createAuthCookie( - { id: 'session-id', email: 'user@example.com', rememberMe: false }, + { + stableUserId: await createStableUserIdFromEmail('user@example.com'), + email: 'user@example.com', + rememberMe: false, + }, false, ) @@ -559,9 +563,9 @@ test('Gemini-shaped authorize requests default resource to /mcp when omitted', a expect(geminiAuthRequestWithoutResource.resource).toBeUndefined() }) -test('session approval uses database user id when cookie email is stale', async () => { +test('session approval uses stable user id when cookie email is stale', async () => { const currentEmail = `changed-oauth-${crypto.randomUUID()}@example.com` - const userId = await seedWorkerUser(currentEmail, 'password123') + await seedWorkerUser(currentEmail, 'password123') let capturedOptions: CompleteAuthorizationOptions | null = null const helpers = createHelpers({ async completeAuthorization(options) { @@ -572,7 +576,7 @@ test('session approval uses database user id when cookie email is stale', async setAuthSessionSecret(cookieSecret) const cookie = await createAuthCookie( { - id: String(userId), + stableUserId: await createStableUserIdFromEmail(currentEmail), email: `old-${currentEmail}`, rememberMe: false, }, @@ -603,7 +607,10 @@ test('session approval uses database user id when cookie email is stale', async }), ), ).resolves.toMatchObject({ - session: { id: String(userId), email: currentEmail }, + session: { + stableUserId: await createStableUserIdFromEmail(currentEmail), + email: currentEmail, + }, }) }) @@ -637,7 +644,11 @@ test('authorize rejects unverified accounts before creating a grant', async () = setAuthSessionSecret(cookieSecret) const cookie = await createAuthCookie( - { id: 'session-id', email: 'user@example.com', rememberMe: false }, + { + stableUserId: await createStableUserIdFromEmail('user@example.com'), + email: 'user@example.com', + rememberMe: false, + }, false, ) const sessionUnverifiedResponse = await handleAuthorizeRequest( @@ -923,7 +934,11 @@ test('reset client deletes matching grants for redirect-uri, client-id, and auth const appDb = await createDatabase('password123') setAuthSessionSecret(cookieSecret) const cookie = await createAuthCookie( - { id: 'session-id', email: 'user@example.com', rememberMe: false }, + { + stableUserId: userId, + email: 'user@example.com', + rememberMe: false, + }, false, ) diff --git a/packages/worker/src/user-id.ts b/packages/worker/src/user-id.ts index 9556329dae..fcf7875ac9 100644 --- a/packages/worker/src/user-id.ts +++ b/packages/worker/src/user-id.ts @@ -1,5 +1,7 @@ import { toHex } from '@kody-internal/shared/hex.ts' +const stableUserIdPattern = /^[a-f0-9]{64}$/ + /** * Initial stable MCP user id for a new account: SHA-256 hex of the trimmed * lowercase email. After signup the stored `users.stable_user_id` is @@ -16,6 +18,13 @@ export function normalizeStableUserId(value: string | null | undefined) { return value?.trim() ?? '' } +export function isStableUserId(value: unknown): value is string { + return ( + typeof value === 'string' && + stableUserIdPattern.test(normalizeStableUserId(value)) + ) +} + /** * Read the authoritative stored stable id. `users.stable_user_id` is NOT NULL * (migration 0075); never derive identity from the current email here — email