Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 4 additions & 1 deletion docs/use/community-packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,10 @@ formats.

Re-running `community_publish` updates the public listing to the package's
current published commit. Private edits after publishing do not change the
listing until you publish again and re-run `community_publish`.
listing until you publish again and re-run `community_publish`. When you change
your username on `/account`, Kody republishes any of your listings that were
already pinned to the package's latest commit so the public `@{username}/…` name
stays current.

`community_unpublish` removes an active listing you own. If an admin **delists**
a listing, the owner cannot unpublish or re-publish it; only an admin hard
Expand Down
8 changes: 7 additions & 1 deletion docs/use/packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,13 @@ Important fields:

For predictable package resolution, saved packages must use a scoped
`package.json.name`, and the leaf segment must match `kody.id`. For example,
`@scope/my-package` must use `"kody": { "id": "my-package" }`.
`@scope/my-package` must use `"kody": { "id": "my-package" }`. The scope is the
account username. Changing your username on `/account` rewrites every saved
package to the new `@{username}/…` name (including same-account `kody:@` imports
and `kody.dependencies`), publishes an automatic update commit per package, and
republishes any community listing that was already pinned to that package's
latest commit. Third-party integrations and dynamic invocations that hard-code
the old `@{username}` scope still need to be updated by their owners.

### npm dependencies

Expand Down
32 changes: 29 additions & 3 deletions packages/worker/client/routes/account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,13 @@ export function AccountRoute(handle: Handle) {
return
}
const payload = await readJson<
AccountProfileLoaderData & { error?: string }
AccountProfileLoaderData & {
error?: string
packagesUpdated?: number
communityListingsRepublished?: number
packageUpdateMessage?: string
communityUpdateWarning?: string
}
>(response)
if (!response.ok || !payload?.ok) {
throw new Error(payload?.error || 'Unable to save username.')
Expand All @@ -424,8 +430,18 @@ export function AccountRoute(handle: Handle) {
emailVerified = payload.emailVerified
username = payload.username
draftUsername = payload.username
message = 'Username saved.'
messageTone = 'info'
const packageMessage =
typeof payload.packageUpdateMessage === 'string'
? payload.packageUpdateMessage
: null
const communityWarning =
typeof payload.communityUpdateWarning === 'string'
? payload.communityUpdateWarning
: null
message = ['Username saved.', packageMessage, communityWarning]
.filter(Boolean)
.join(' ')
messageTone = communityWarning ? 'error' : 'info'
queueSessionRefresh()
} catch (error) {
message =
Expand Down Expand Up @@ -555,6 +571,16 @@ export function AccountRoute(handle: Handle) {
<p mix={css({ color: colors.textMuted, margin: 0 })}>
Email: {email} ({emailVerified ? 'verified' : 'unverified'})
</p>
{normalizedDraftUsername !== username ? (
<p mix={css({ color: colors.textMuted, margin: 0 })}>
Changing your username updates every saved package to the
new <code>@{normalizedDraftUsername}</code> scope with an
automatic commit. That can affect third-party integrations
and dynamic invocations that still reference{' '}
<code>@{username}</code>. Community listings already pinned
to the latest package commit are republished automatically.
</p>
) : null}
<div>
<button
type="submit"
Expand Down
102 changes: 101 additions & 1 deletion packages/worker/src/app/handlers/account-profile.node.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
import { beforeAll, expect, test, vi } from 'vitest'
import { beforeAll, beforeEach, expect, test, vi } from 'vitest'

const mocks = vi.hoisted(() => ({
updatePackagesForUsernameChange: vi.fn(),
republishCommunityListingsAfterUsernameChange: vi.fn(),
}))

vi.mock('#worker/package-registry/username-change-packages.ts', () => ({
updatePackagesForUsernameChange: (...args: Array<unknown>) =>
mocks.updatePackagesForUsernameChange(...args),
republishCommunityListingsAfterUsernameChange: (...args: Array<unknown>) =>
mocks.republishCommunityListingsAfterUsernameChange(...args),
}))

import {
createAuthCookie,
setAuthSessionSecret,
Expand Down Expand Up @@ -155,6 +168,7 @@ function createEnv(db: D1Database) {
return {
APP_DB: db,
COOKIE_SECRET: testCookieSecret,
APP_BASE_URL: 'http://example.com',
} as Env
}

Expand All @@ -173,6 +187,19 @@ beforeAll(() => {
setAuthSessionSecret(testCookieSecret)
})

beforeEach(() => {
mocks.updatePackagesForUsernameChange.mockReset()
mocks.republishCommunityListingsAfterUsernameChange.mockReset()
mocks.updatePackagesForUsernameChange.mockResolvedValue({
updatedPackages: [],
skippedPackages: [],
})
mocks.republishCommunityListingsAfterUsernameChange.mockResolvedValue({
republishedPackageIds: [],
warnings: [],
})
})

test('account profile API returns email and username for the signed-in user', async () => {
const testDb = createProfileTestDb([createUser(1, 'current-user')])
const handler = createAccountProfileApiHandler(createEnv(testDb.db))
Expand All @@ -198,11 +225,30 @@ test('account profile API returns email and username for the signed-in user', as
})
// Reads are not audited.
expect(logAuditEventSpy).not.toHaveBeenCalled()
expect(mocks.updatePackagesForUsernameChange).not.toHaveBeenCalled()
})

test('account profile API updates username for the signed-in user', async () => {
const testDb = createProfileTestDb([createUser(1, 'current-user')])
const handler = createAccountProfileApiHandler(createEnv(testDb.db))
mocks.updatePackagesForUsernameChange.mockResolvedValueOnce({
updatedPackages: [
{
packageId: 'pkg-1',
kodyId: 'demo',
previousName: '@current-user/demo',
nextName: '@next_user/demo',
publishedCommit: 'abc',
changedPaths: ['package.json'],
shouldRepublishCommunityListing: true,
},
],
skippedPackages: [],
})
mocks.republishCommunityListingsAfterUsernameChange.mockResolvedValueOnce({
republishedPackageIds: ['pkg-1'],
warnings: [],
})

const response = await runHandler(
handler,
Expand All @@ -223,8 +269,24 @@ test('account profile API updates username for the signed-in user', async () =>
email: 'current-user@example.com',
username: 'next_user',
displayName: 'next_user',
packagesUpdated: 1,
communityListingsRepublished: 1,
packageUpdateMessage: 'Updated 1 package to the new @next_user scope.',
})
expect(testDb.users.get(1)?.username).toBe('next_user')
expect(mocks.updatePackagesForUsernameChange).toHaveBeenCalledWith(
expect.objectContaining({
previousUsername: 'current-user',
nextUsername: 'next_user',
}),
)
expect(
mocks.republishCommunityListingsAfterUsernameChange,
).toHaveBeenCalledWith(
expect.objectContaining({
packageIds: ['pkg-1'],
}),
)
expect(logAuditEventSpy).toHaveBeenCalledTimes(1)
expect(logAuditEventSpy).toHaveBeenCalledWith(
expect.objectContaining({
Expand All @@ -235,6 +297,43 @@ test('account profile API updates username for the signed-in user', async () =>
)
})

test('account profile API rejects username changes when package updates fail', async () => {
const testDb = createProfileTestDb([createUser(1, 'current-user')])
const handler = createAccountProfileApiHandler(createEnv(testDb.db))
mocks.updatePackagesForUsernameChange.mockRejectedValueOnce(
new Error('sync failed'),
)

const response = await runHandler(
handler,
await createRequest({
session: {
id: '1',
email: 'current-user@example.com',
rememberMe: false,
},
method: 'POST',
body: { username: 'next_user' },
}),
)

expect(response.status).toBe(500)
expect(await response.json()).toEqual({
ok: false,
error:
'Username was not changed because package updates failed: sync failed',
})
expect(testDb.users.get(1)?.username).toBe('current-user')
expect(logAuditEventSpy).toHaveBeenCalledWith(
expect.objectContaining({
category: 'account',
action: 'update_username',
result: 'failure',
reason: 'package_scope_update_failed',
}),
)
})

test('account profile API rejects invalid or duplicate usernames', async () => {
const testDb = createProfileTestDb([
createUser(1, 'current-user'),
Expand Down Expand Up @@ -285,6 +384,7 @@ test('account profile API rejects invalid or duplicate usernames', async () => {
error: 'Username already registered.',
})
expect(testDb.users.get(1)?.username).toBe('current-user')
expect(mocks.updatePackagesForUsernameChange).not.toHaveBeenCalled()
// Only the duplicate attempt is audited; validation rejections are not.
expect(logAuditEventSpy).toHaveBeenCalledTimes(1)
expect(logAuditEventSpy).toHaveBeenCalledWith(
Expand Down
97 changes: 94 additions & 3 deletions packages/worker/src/app/handlers/account-profile.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import { utcSqliteTimestamp } from '@kody-internal/shared/date-keys.ts'
import { getErrorMessage } from '@kody-internal/shared/error-message.ts'
import { jsonResponse } from '#worker/json-response.ts'
import { type Action } from 'remix/router'
import { getRequestIp, logAuditEvent } from '#app/audit-log.ts'
import {
buildAccountProfilePayload,
loadAccountProfileData,
} from '#app/account-profile-data.ts'
import { getAppBaseUrl } from '#app/app-base-url.ts'
import { readAuthenticatedAppUser } from '#app/authenticated-user.ts'
import { getUniqueConstraintField } from '#app/database-errors.ts'
import { type routes } from '#app/routes.ts'
import { getUsernameValidationError, normalizeUsername } from '#app/username.ts'
import {
republishCommunityListingsAfterUsernameChange,
updatePackagesForUsernameChange,
} from '#worker/package-registry/username-change-packages.ts'
import { createDb, usersTable } from '#worker/db.ts'

type AuthenticatedUser = NonNullable<
Expand Down Expand Up @@ -49,6 +55,11 @@ export function createAccountProfileApiHandler(env: Env) {
}

const requestIp = getRequestIp(request) ?? undefined
const previousUsername = user.username
if (username === previousUsername) {
return jsonResponse(buildAccountProfilePayload(user))
}

const existingUsername = await db.findOne(usersTable, {
where: { username },
})
Expand All @@ -68,12 +79,62 @@ export function createAccountProfileApiHandler(env: Env) {
)
}

const baseUrl = getAppBaseUrl({ env, requestUrl: request.url })
const packageUserId = user.mcpUser.userId
let packageUpdate
try {
packageUpdate = await updatePackagesForUsernameChange({
env,
baseUrl,
userId: packageUserId,
previousUsername,
nextUsername: username,
})
} catch (error) {
void logAuditEvent({
category: 'account',
action: 'update_username',
result: 'failure',
email: user.email,
ip: requestIp,
path: url.pathname,
reason: 'package_scope_update_failed',
})
return jsonResponse(
{
ok: false,
error: `Username was not changed because package updates failed: ${getErrorMessage(error)}`,
},
500,
)

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.

Rollback failure misreports username

High Severity

On package cascade failure the handler tries to restore the previous username, but if that rollback update fails it only logs the error and still responds that the username was not changed. The database can retain the new username while the client is told the rename was aborted.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 215c34c. Configure here.

}

try {
await db.update(usersTable, user.userId, {
username,
updated_at: utcSqliteTimestamp(),
})
} catch (error) {
if (packageUpdate.updatedPackages.length > 0) {
try {
await updatePackagesForUsernameChange({
env,
baseUrl,
userId: packageUserId,
previousUsername: username,
nextUsername: previousUsername,
})
} catch (compensateError) {
console.error(
JSON.stringify({
message:
'username-change package compensation after username update failure failed',
userId: packageUserId,
error: getErrorMessage(compensateError),
}),
)
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (getUniqueConstraintField(error) === 'username') {
void logAuditEvent({
category: 'account',
Expand All @@ -92,6 +153,19 @@ export function createAccountProfileApiHandler(env: Env) {
throw error
}

const communityPackageIds = packageUpdate.updatedPackages
.filter((entry) => entry.shouldRepublishCommunityListing)
.map((entry) => entry.packageId)
const communityRepublish =
communityPackageIds.length > 0
? await republishCommunityListingsAfterUsernameChange({
env,
baseUrl,
userId: packageUserId,
packageIds: communityPackageIds,
})
: { republishedPackageIds: [], warnings: [] }

void logAuditEvent({
category: 'account',
action: 'update_username',
Expand All @@ -101,14 +175,31 @@ export function createAccountProfileApiHandler(env: Env) {
path: url.pathname,
})

return jsonResponse(
buildAccountProfilePayload({
const packageCount = packageUpdate.updatedPackages.length
const packageSummary =
packageCount === 0
? null
: `Updated ${packageCount} package${packageCount === 1 ? '' : 's'} to the new @${username} scope.`
const communityWarning =
communityRepublish.warnings.length > 0
? communityRepublish.warnings.join(' ')
: null

return jsonResponse({
...buildAccountProfilePayload({
...user,
username,
displayName: username,
mcpUser: { ...user.mcpUser, displayName: username },
} satisfies AuthenticatedUser),
)
packagesUpdated: packageCount,
communityListingsRepublished:
communityRepublish.republishedPackageIds.length,
...(packageSummary ? { packageUpdateMessage: packageSummary } : {}),
...(communityWarning
? { communityUpdateWarning: communityWarning }
: {}),
})
},
} satisfies Action<typeof routes.accountProfileApi>
}
Loading
Loading