Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions packages/worker/client/routes/account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type AccountProfilePayload = {
}

const resendVerificationApiPath = '/account/resend-verification.json'
const emailChangeApiPath = '/account/email-change.json'

function isAccountPath(href: string) {
return new URL(href, 'http://localhost').pathname === '/account'
Expand Down Expand Up @@ -64,14 +65,19 @@ export function AccountRoute(handle: Handle) {
let status: AccountStatus = 'loading'
let saveStatus: 'idle' | 'saving' = 'idle'
let resendStatus: 'idle' | 'sending' = 'idle'
let emailChangeStatus: 'idle' | 'sending' = 'idle'
let resendMessage: string | null = null
let resendTone: 'error' | 'info' = 'info'
let email = ''
let emailVerified = false
let username = ''
let draftUsername = ''
let draftEmail = ''
let emailChangePassword = ''
let message: string | null = null
let messageTone: 'error' | 'info' = 'info'
let emailChangeMessage: string | null = null
let emailChangeTone: 'error' | 'info' = 'info'
let lastLoadedHref = ''

async function loadAccountProfile(signal: AbortSignal) {
Expand All @@ -97,6 +103,7 @@ export function AccountRoute(handle: Handle) {
emailVerified = payload.emailVerified
username = payload.username
draftUsername = payload.username
draftEmail = payload.email
status = 'ready'
message = null
messageTone = 'info'
Expand Down Expand Up @@ -158,6 +165,86 @@ export function AccountRoute(handle: Handle) {
handle.update()
}

function updateDraftEmail(event: InputEvent) {
if (!(event.currentTarget instanceof HTMLInputElement)) return
draftEmail = event.currentTarget.value
handle.update()
}

function updateEmailChangePassword(event: InputEvent) {
if (!(event.currentTarget instanceof HTMLInputElement)) return
emailChangePassword = event.currentTarget.value
handle.update()
}

async function handleEmailChangeSubmit(event: SubmitEvent) {
event.preventDefault()
const nextEmail = draftEmail.trim().toLowerCase()
if (!nextEmail || !emailChangePassword) {
emailChangeMessage = 'New email and current password are required.'
emailChangeTone = 'error'
handle.update()
return
}
if (nextEmail === email.trim().toLowerCase()) {
emailChangeMessage = 'Enter a different email address.'
emailChangeTone = 'error'
handle.update()
return
}

emailChangeStatus = 'sending'
emailChangeMessage = null
emailChangeTone = 'info'
handle.update()

try {
const response = await fetch(emailChangeApiPath, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({
email: nextEmail,
password: emailChangePassword,
}),
})
if (response.status === 401) {
const payload = await readJson<{ error?: string }>(response)
if (payload?.error === 'Password is incorrect.') {
throw new Error(payload.error)
}
window.location.assign('/login')
return
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const payload = await readJson<{
ok?: boolean
message?: string
error?: string
}>(response)
if (!response.ok || !payload?.ok) {
throw new Error(
payload?.error || 'Unable to send the email change verification.',
)
}
emailChangePassword = ''
emailChangeMessage =
payload.message ?? 'Verification email sent to your new address.'
emailChangeTone = 'info'
} catch (error) {
emailChangeMessage =
error instanceof Error
? error.message
: 'Unable to send the email change verification.'
emailChangeTone = 'error'
} finally {
emailChangeStatus = 'idle'
handle.update()
}
}

async function handleUsernameSubmit(event: SubmitEvent) {
event.preventDefault()
const nextUsername = draftUsername.trim()
Expand Down Expand Up @@ -218,6 +305,7 @@ export function AccountRoute(handle: Handle) {
emailVerified = routeData.emailVerified
username = routeData.username
draftUsername = routeData.username
draftEmail = routeData.email
status = 'ready'
message = null
messageTone = 'info'
Expand All @@ -244,7 +332,9 @@ export function AccountRoute(handle: Handle) {
handle.queueTask(loadAccountProfile)
}
const isSaving = saveStatus === 'saving'
const isSendingEmailChange = emailChangeStatus === 'sending'
const normalizedDraftUsername = draftUsername.trim().toLowerCase()
const normalizedDraftEmail = draftEmail.trim().toLowerCase()

return (
<section
Expand Down Expand Up @@ -371,6 +461,88 @@ export function AccountRoute(handle: Handle) {
</button>
</div>
</form>
<form
mix={[
css({
display: 'grid',
gap: spacing.md,
marginTop: spacing.lg,
paddingTop: spacing.lg,
borderTop: `1px solid ${colors.border}`,
}),
on('submit', handleEmailChangeSubmit),
]}
>
<div mix={css({ display: 'grid', gap: spacing.xs })}>
<h3
mix={css({
fontSize: typography.fontSize.base,
fontWeight: typography.fontWeight.semibold,
color: colors.text,
margin: 0,
})}
>
Change email
</h3>
<p mix={css(descriptionCss)}>
Enter your current password. We will send a verification
link to the new address before changing your account email.
</p>
</div>
<label mix={css(fieldCss)}>
<span mix={css(fieldLabelCss)}>New email</span>
<input
type="email"
name="email"
required
autoComplete="email"
value={draftEmail}
mix={[css(inputCss), on('input', updateDraftEmail)]}
/>
</label>
<label mix={css(fieldCss)}>
<span mix={css(fieldLabelCss)}>Current password</span>
<input
type="password"
name="password"
required
autoComplete="current-password"
value={emailChangePassword}
mix={[
css(inputCss),
on('input', updateEmailChangePassword),
]}
/>
</label>
<div>
<button
type="submit"
disabled={
isSendingEmailChange ||
normalizedDraftEmail === email.trim().toLowerCase()
}
mix={css(primaryButtonCss)}
>
{isSendingEmailChange
? 'Sending...'
: 'Send verification link'}
</button>
</div>
{emailChangeMessage ? (
<p
role="status"
mix={css({
color:
emailChangeTone === 'error'
? colors.error
: colors.text,
margin: 0,
})}
>
{emailChangeMessage}
</p>
) : null}
</form>
</section>
<section mix={css(cardCss)}>
<h2 mix={css(cardTitleCss)}>Secret management</h2>
Expand Down
1 change: 1 addition & 0 deletions packages/worker/client/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export const clientRoutes = {
'/signup': <LoginRoute />,
'/reset-password': <ResetPasswordRoute />,
'/verify-email': <VerifyEmailRoute />,
'/verify-email-change': <VerifyEmailRoute />,
'/connect/oauth': <ConnectOauthRoute />,
'/oauth/authorize': <OAuthAuthorizeRoute />,
'/oauth/callback': <OAuthCallbackRoute />,
Expand Down
12 changes: 10 additions & 2 deletions packages/worker/client/routes/verify-email.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,23 @@ export function VerifyEmailRoute(handle: Handle) {
error:
'Open the verification link from your email to verify your account.',
} satisfies EmailVerificationLoaderData)
const title = data.ok ? 'Email verified' : 'Email verification'
const isEmailChange =
data.ok && data.message.includes('email has been changed')
const title = data.ok
? isEmailChange
? 'Email changed'
: 'Email verified'
: 'Email verification'

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return (
<section mix={css(pageCss)}>
<header mix={css(pageHeaderCss)}>
<h1 mix={css(pageTitleCss)}>{title}</h1>
<p mix={css(pageDescriptionCss)}>
{data.ok
? 'Your Kody account can now send outbound email.'
? isEmailChange
? 'Your Kody account now uses the new email address.'
: 'Your Kody account can now send outbound email.'
: 'We could not verify your email address.'}
</p>
</header>
Expand Down
24 changes: 24 additions & 0 deletions packages/worker/migrations/0052-stable-user-id-email-changes.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
ALTER TABLE users ADD COLUMN stable_user_id TEXT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_users_stable_user_id
ON users(stable_user_id)
WHERE stable_user_id IS NOT NULL;

CREATE TABLE IF NOT EXISTS pending_email_changes (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
user_id INTEGER NOT NULL,
new_email TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
expires_at INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_pending_email_changes_user_id
ON pending_email_changes(user_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_pending_email_changes_new_email
ON pending_email_changes(new_email);

CREATE INDEX IF NOT EXISTS idx_pending_email_changes_token_hash
ON pending_email_changes(token_hash);
2 changes: 2 additions & 0 deletions packages/worker/src/app/account-data-targets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,14 @@ export const accountUserDataTargets: ReadonlyArray<UserScopedDataTarget> = [
// stable mcp string user id), so it must be handled with the database
// integer id rather than the mcp user id.
{ kind: 'db_user_id', table: 'email_verifications' },
{ kind: 'db_user_id', table: 'pending_email_changes' },
{ kind: 'db_user_id', table: 'password_resets' },
{ kind: 'db_user_id', table: 'user_roles' },
]

export function getAccountD1UserColumnCoverage() {
const covered = new Set<string>()
covered.add('users.stable_user_id')
for (const target of accountUserDataTargets) {
switch (target.kind) {
case 'user_id':
Expand Down
18 changes: 9 additions & 9 deletions packages/worker/src/app/account-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { buildCommunitySnapshotKvKey } from '#worker/community/snapshot.ts'
import { storageRunnerRpc } from '#worker/storage-runner.ts'
import { userScopedConnectorSessionKey } from '#worker/remote-connector/connector-session-key.ts'
import { type RemoteConnectorSessionExport } from '#worker/remote-connector/types.ts'
import { createStableUserIdFromEmail } from '#worker/user-id.ts'
import { resolveUserStableId } from '#worker/user-id.ts'

const accountExportSchemaVersion = 1
const defaultExportPageSize = 100
Expand All @@ -32,6 +32,7 @@ const redactedColumnsByTable: Readonly<Record<string, ReadonlyArray<string>>> =
email_verifications: ['token_hash'],
package_invocation_tokens: ['token_hash'],
password_resets: ['token_hash'],
pending_email_changes: ['token_hash'],
remote_connector_settings: ['encrypted_shared_secret'],
secret_entries: ['encrypted_value', 'lookup_hash'],
users: ['password_hash'],
Expand Down Expand Up @@ -1107,20 +1108,19 @@ export async function resolveAccountExportDbUserId(input: {
if (!email) {
throw new Error('Account export requires an authenticated user email.')
}
const stableUserId = await createStableUserIdFromEmail(email)
if (stableUserId !== input.mcpUserId) {
throw new Error(
'Authenticated user identity did not match the account email.',
)
}
const row = await input.env.APP_DB.prepare(
`SELECT id FROM users WHERE email = ?`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Export lookup breaks after change

Medium Severity

Account export resolves the database user only by the caller email. After an email change, MCP export can still pass the previous address, the row is not found, and export fails even when mcpUserId still matches the preserved stable id.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 0036e4f. Configure here.

`SELECT id, email, stable_user_id FROM users WHERE email = ?`,
)
.bind(email)
.first<{ id: number }>()
.first<{ id: number; email: string; stable_user_id: string | null }>()
if (!row) {
throw new Error('Authenticated account was not found.')
}
if ((await resolveUserStableId(row)) !== input.mcpUserId) {
throw new Error(
'Authenticated user identity did not match the account email.',
)
}
return row.id
}

Expand Down
9 changes: 5 additions & 4 deletions packages/worker/src/app/admin-usage-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
readEntitlementResourceUsage,
utcDayKey,
} from '#worker/entitlements/service.ts'
import { createStableUserIdFromEmail } from '#worker/user-id.ts'
import { resolveUserStableIdByEmail } from '#worker/user-id.ts'
import {
type AdminUsageDailyCounter,
type AdminUsageEntitlementConsumption,
Expand Down Expand Up @@ -121,7 +121,7 @@ export async function loadAdminUsageData(
.all<AdminUsageUserRow>(),
])

const users = await addUsageIds(userRows.results ?? [])
const users = await addUsageIds(env.APP_DB, userRows.results ?? [])
const selectedUser = await loadSelectedUser({
db: env.APP_DB,
users,
Expand Down Expand Up @@ -166,6 +166,7 @@ export async function loadAdminUsageData(
}

async function addUsageIds(
db: D1Database,
rows: Array<AdminUsageUserRow>,
): Promise<Array<UserWithUsageId>> {
return await Promise.all(
Expand All @@ -174,7 +175,7 @@ async function addUsageIds(
username: row.username,
email: row.email,
plan: parsePlanName(row.plan),
usageUserId: await createStableUserIdFromEmail(row.email),
usageUserId: await resolveUserStableIdByEmail({ db, email: row.email }),
})),
)
}
Expand All @@ -196,7 +197,7 @@ async function loadSelectedUser(input: {
.bind(input.selectedUserId)
.first<AdminUsageUserRow>()
if (!row) return input.users[0] ?? null
const [user] = await addUsageIds([row])
const [user] = await addUsageIds(input.db, [row])
return user ?? null
}

Expand Down
Loading
Loading