import type { SavedPackageRecord } from '#worker/package-registry/types.ts' import { reportHandledError } from '#worker/outbound/typed-failure.ts' import { loadAccountPackageDetail } from '#app/account-packages-data.ts' import { loadCommunityDetailData } from '#app/community-data.ts' import { readAuthenticatedAppUser } from '#app/authenticated-user.ts' import { loadSavedPackageViewerAccess, savedPackageViewerAllows, savedPackageViewerMayRunApp, viewerCanReadSavedPackage, } from '#app/package-viewer-access.ts' import { resolvePackageAppLinks } from '#app/package-repo-actions.ts' import { getAppBaseUrl } from '#worker/app-base-url.ts' import { loadOwnerProfilePublic } from '#worker/orgs/org-public-profile.ts' import { isRetryableD1LockError, runD1WithRetry, transientDatabaseUnavailableMessage, } from '#worker/d1-retry.ts' import { findPublicOwnerIdentityByHandle } from '#worker/identity/user-lookup.ts' import { normalizeUsername } from '#worker/identity/username.ts' import { memoizePerRequest, recordServerTiming, } from '#worker/request-context.ts' import { getCommunityPackageHref, resolvePackagePageUrl, } from '#worker/community/package-url.ts' import { isPlainRepoPackageShapedAtCommit } from '#mcp/capabilities/repo/plain-repo-package-shaped.ts' import { resolveCachedArtifactSourceHead } from '#worker/repo/artifact-head-cache.ts' import { getEntitySourceByEntity, getEntitySourceByIdForUser, } from '#worker/repo/entity-sources.ts' import { getUserRepoByName } from '#worker/repo/user-repos.ts' import { andLiveDeletedAtSql } from '#worker/soft-delete/live-sql.ts' import { viewerOrgsFollowTarget } from '#worker/follow/repo.ts' import type { FollowTargetKind } from '#worker/follow/types.ts' import type { AccountPackageDetail, CommunityDetailLoaderData, } from '#universal/loader-data.ts' import type { McpUserContext } from '@kody-internal/shared/chat.ts' import { loadPublicPackageSecurityAudit } from '#worker/package-capabilities/security-audit-state.ts' import { countOpenPackageMergeRequests } from '#worker/package-capabilities/merge-requests-repo.ts' import type { PackageSecurityAuditView } from '#universal/package-security-audit-rubric.ts' import type { OrgPermission } from '@kody-internal/shared/org-permissions.ts' type PackageTabOwner = { repoId?: string | null } & Pick< AccountPackageDetail, | 'id' | 'name' | 'description' | 'isPrivate' | 'hasApp' | 'sourceId' | 'lockedAt' | 'hasCommunityListing' | 'publishedCommit' > export type PackagePageAccess = | { kind: 'redirect'; to: string; shared: boolean } | { kind: 'not_found' /** * Set for a signed-out visitor when the owner sends package page * visitors to an internet-visible app. Only the app URL leaks. */ appRedirectHref?: string } | { kind: 'unauthorized' } /** * Signed-in viewer reached a real saved package they cannot read. Distinct * from `not_found` so a shared private-app link never looks like the * package was deleted — show "you don't have access" with a request path. * Anonymous visitors still get `not_found` so private packages stay opaque. */ | { kind: 'no_access' username: string kodyId: string packageName: string viewerUsername: string /** * Canonical hosted origin when the app is internet-visible. The * package page is closed, but the app itself is not. */ packageAppHref?: string | null redirectsToApp?: boolean /** Public graded audit, only when the package is internet-visible. */ securityAudit?: PackageSecurityAuditView } | { kind: 'page' username: string kodyId: string listing: CommunityDetailLoaderData | null ownerPackage: OwnerPackage | null /** * True when this URL resolves to a saved package (or its listing). * False for plain `user_repos` pages that share the same chrome. */ hasPackage: boolean /** * Plain repos only: promote guidance for org members outside the Files * view, based on root `package.json` at HEAD or the indexed/published * commit if HEAD cannot be resolved. */ packageShaped?: boolean /** The viewer may open the private view (details, source files). */ viewerIsOwner: boolean /** The viewer may change package settings. */ viewerCanManage: boolean viewerCanPublish: boolean viewerCanDelete: boolean /** May change who can use the package (`package:manage_access`). */ viewerCanManageAccess: boolean /** Sees the Connected people tab (Manage on a package with an app). */ viewerCanSeeConnectedPeople: boolean openMergeRequestCount?: number /** May adopt a community fork (Owner or Admin of the owning org). */ viewerCanAdoptCommunityFork: boolean /** * The viewer may run this package's hosted app (`app:execute`). * Distinct from `viewerIsOwner`, which is `package:read`. */ viewerMayRun?: boolean /** The owner sends browser visitors of this page to the app. */ redirectsToApp?: boolean loggedIn: boolean /** Saved package or plain repo a Follow control acts on. */ followTarget: { kind: FollowTargetKind; id: string } | null /** One of the viewer's orgs follows this target (active or paused). */ viewerFollowing?: boolean invocationUrlOrigin: string ownerUserId: string /** True when `/@owner` is publicly reachable. */ ownerProfilePublic: boolean } export type PackagePagePrivacySource = { ownerPackage: { isPrivate: boolean } | null } export function packagePageIsPrivate(page: PackagePagePrivacySource): boolean { return page.ownerPackage?.isPrivate ?? false } /** * Client JSON must not leak internal source ids for plain repos to guests. * Owners keep sourceId for settings/debug surfaces; packages keep current * behavior (source ids already appear on saved-package payloads). */ export function ownerPackageForClient(input: { ownerPackage: AccountPackageDetail | null hasPackage: boolean viewerIsOwner: boolean }): AccountPackageDetail | null { const ownerPackage = input.ownerPackage if (!ownerPackage) return null if (input.hasPackage || input.viewerIsOwner) return ownerPackage if (!ownerPackage.sourceId) return ownerPackage return { ...ownerPackage, sourceId: '' } } function isPublicSavedPackage(pkg: { hidden: boolean; isPrivate: boolean }) { return !pkg.hidden && !pkg.isPrivate } async function resolvePackagePageOwnerProfilePublic(input: { env: Env username: string listing: CommunityDetailLoaderData | null }) { if (typeof input.listing?.ownerProfilePublic === 'boolean') { return input.listing.ownerProfilePublic } return await loadOwnerProfilePublic(input.env.APP_DB, input.username) } function sameKodyId(left: string, right: string) { return left.trim().toLowerCase() === right.trim().toLowerCase() } /** * Package page APP_DB reads have no per-query `runD1WithRetry`. Nightly DR * exports lock D1 (`Currently processing a long-running export`); without a * retry the raw D1 error dehydrates into the TanStack Start document and the * browser SDK reports it (KODY-B7). Retry the whole load, then remap exhausted * blips to the public storage-unavailable message so the client never sees * the platform sentence. */ type PackagePageInput = { env: Env request: Request username: string kodyId: string /** * Viewer already authenticated another way (a `kody_at_` bearer on raw * file reads). Omit to read the session cookie. Null is anonymous. */ viewer?: McpUserContext | null /** Org whose community installs badge the page (`?org=`). */ installOrg?: string | null view?: 'tab' | 'files' /** Include owner controls used by the Settings page. */ includeManagementDetails?: boolean /** Include the badge count when rendering the repository tab row. */ includeOpenMergeRequestCount?: boolean } async function loadPackagePageWithD1Retry( input: PackagePageInput, ): Promise> { try { return await runD1WithRetry(() => loadPackagePageUncached(input)) } catch (error) { if (!isRetryableD1LockError(error)) throw error throw new Error(transientDatabaseUnavailableMessage, { cause: error }) } } /** * Resolve package access and memoize per request and view. Tab and Files views * load only the owner fields they need instead of the full package detail. */ export function loadPackagePage( input: PackagePageInput & { view: 'tab' | 'files' }, ): Promise> export function loadPackagePage( input: PackagePageInput & { view?: undefined }, ): Promise export function loadPackagePage( input: PackagePageInput, ): Promise> { const viewerKey = input.viewer === undefined ? 'session' : `viewer:${input.viewer?.userId ?? 'anonymous'}` return memoizePerRequest({ request: input.request, key: `package-page:${input.username}:${input.kodyId}:${viewerKey}:${input.installOrg ?? ''}:${input.view ?? 'detail'}:${input.includeManagementDetails !== false}:${input.includeOpenMergeRequestCount === true}`, load: () => recordServerTiming( 'package-page', () => loadPackagePageWithD1Retry(input), input.request, ), }) } async function viewerIsPlainRepoOrgMember(input: { env: Env viewer: McpUserContext | null ownerUserId: string }) { if (!input.viewer) return false const membership = await input.env.APP_DB.prepare( `SELECT 1 AS ok FROM org_memberships WHERE org_id = ? AND user_id = ?${andLiveDeletedAtSql()}`, ) .bind(input.ownerUserId, input.viewer.userId) .first<{ ok: number }>() return membership != null } function toPlainRepoOwnerPackage(input: { username: string repo: { id: string name: string description: string | null isPrivate: boolean createdAt: string updatedAt: string } sourceId: string iconCommit: string | null }): AccountPackageDetail { return { id: input.repo.id, name: `@${input.username}/${input.repo.name}`, kodyId: input.repo.name, description: input.repo.description ?? '', tags: [], hasApp: false, sourceId: input.sourceId, lockedAt: null, codemodsOptedOutAt: null, createdAt: input.repo.createdAt, updatedAt: input.repo.updatedAt, hidden: false, isPrivate: input.repo.isPrivate, isInternetVisible: false, redirectPageToApp: false, hasCommunityListing: false, listingNeedsRepublish: false, listingAhead: null, forkAhead: null, searchText: null, exports: null, publishedCommit: input.iconCommit, pendingCommit: input.iconCommit, pendingCommitKnown: true, publishedVersion: null, unpublishedChangeCount: null, ownerIsPersonal: true, communityFork: null, } } async function loadPlainRepoPage(input: { env: Env request: Request username: string kodyId: string viewer: McpUserContext | null view?: PackagePageInput['view'] }): Promise { const username = normalizeUsername(input.username.trim()) const slug = input.kodyId.trim().toLowerCase() if (!username || !slug) return { kind: 'not_found' } const identity = await findPublicOwnerIdentityByHandle({ db: input.env.APP_DB, handle: username, }) if (!identity) return { kind: 'not_found' } const repo = await getUserRepoByName(input.env.APP_DB, { userId: identity.ownerId, name: slug, }) if (!repo) return { kind: 'not_found' } const viewer = input.viewer const viewerIsMember = await viewerIsPlainRepoOrgMember({ env: input.env, viewer, ownerUserId: identity.ownerId, }) if (repo.isPrivate && !viewerIsMember) return { kind: 'not_found' } const source = await getEntitySourceByEntity(input.env.APP_DB, { userId: identity.ownerId, entityKind: 'repo', entityId: repo.id, }) const iconCommit = source?.indexed_commit ?? source?.published_commit ?? null // Match repoGet: probe package.json at live HEAD (not a possibly stale // indexed icon commit). Fall back to iconCommit when HEAD resolve fails. let headCommit = iconCommit if (input.view !== 'files' && source?.repo_id) { try { const head = await resolveCachedArtifactSourceHead( input.env, source.repo_id, { request: input.request }, ) headCommit = head.commit } catch (error) { reportHandledError('load-plain-repo-page-head-read', error) headCommit = iconCommit } } let packageShaped = false if (input.view !== 'files' && viewerIsMember && source?.repo_id) { try { packageShaped = await isPlainRepoPackageShapedAtCommit({ env: input.env, repoId: source.repo_id, commit: headCommit, }) } catch (error) { reportHandledError('load-plain-repo-page-package-shape-read', error) packageShaped = false } } const ownerProfilePublic = await resolvePackagePageOwnerProfilePublic({ env: input.env, username: identity.handle, listing: null, }) return { kind: 'page', username: identity.handle, kodyId: repo.name, listing: null, ownerPackage: toPlainRepoOwnerPackage({ username: identity.handle, repo, // Keep sourceId server-side for owner README. Public JSON strips it // so guests never see internal ids. sourceId: source?.id ?? '', iconCommit, }), hasPackage: false, packageShaped, viewerIsOwner: viewerIsMember, // Plain repos have no package settings/publish/delete surface here. viewerCanManage: false, viewerCanPublish: false, viewerCanDelete: false, viewerCanManageAccess: false, viewerCanSeeConnectedPeople: false, viewerCanAdoptCommunityFork: false, loggedIn: Boolean(viewer), viewerMayRun: false, followTarget: { kind: 'repo', id: repo.id }, invocationUrlOrigin: getAppBaseUrl({ env: input.env, requestUrl: input.request.url, }), ownerUserId: identity.ownerId, ownerProfilePublic, } } async function loadPackagePageUncached( input: PackagePageInput, ): Promise> { // The URL lookup only needs the pair; the viewer lookup only needs the // cookie. Neither waits on the other. const [target, viewer] = await Promise.all([ recordServerTiming( 'resolve-url', () => resolvePackagePageUrl({ db: input.env.APP_DB, username: input.username, kodyId: input.kodyId, }), input.request, ), input.viewer === undefined ? recordServerTiming( 'auth', async () => (await readAuthenticatedAppUser(input.request, input.env)) ?.mcpUser ?? null, input.request, ) : input.viewer, ]) const page = await resolvePackagePageForViewer(input, target, viewer) if (page.kind !== 'page' || !viewer || input.view) return page const followTarget = page.followTarget if (!followTarget) return page return { ...page, viewerFollowing: await recordServerTiming( 'viewer-follow', () => viewerOrgsFollowTarget(input.env.APP_DB, { personId: viewer.userId, targetKind: followTarget.kind, targetId: followTarget.id, }), input.request, ), } } function savedPackageRedirectsToApp( savedPackage: Pick | null, ) { return ( savedPackage?.hasApp === true && savedPackage.redirectPageToApp === true ) } async function resolvePackagePageForViewer( input: PackagePageInput, target: Awaited>, viewer: McpUserContext | null, ): Promise> { if (!target) { return await loadPlainRepoPage({ env: input.env, request: input.request, username: input.username, kodyId: input.kodyId, viewer, view: input.view, }) } if (target.kind === 'redirect') { // A listing move is public. An unlisted rename must not leak the new // pair: only viewers who can see the package are sent to the current URL. if ( !target.listingId && !(await viewerCanReadSavedPackage({ env: input.env, viewer, ownerId: target.userId, packageId: target.packageId, })) ) { return { kind: 'not_found' } } const listingKodyId = target.listingKodyId const shared = Boolean(target.listingId) && (listingKodyId == null || sameKodyId(target.kodyId, listingKodyId)) return { kind: 'redirect', to: getCommunityPackageHref({ username: target.username, kodyId: target.kodyId, }), // Shared caches may only store hops to the listing public pair. shared, } } // One compile answers every viewer flag below, so the page reads the // org's access_epoch once instead of once per flag. const viewerAccess = target.savedPackage ? await loadSavedPackageViewerAccess({ env: input.env, viewer, ownerId: target.userId, }) : null const viewerIsOwner = target.savedPackage ? savedPackageViewerAllows(viewerAccess, 'package:read', { ownerId: target.userId, packageId: target.savedPackage.id, }) : false const listingKodyId = target.listingKodyId const savedKodyId = target.savedPackage?.kodyId ?? null if (listingKodyId && savedKodyId && !sameKodyId(listingKodyId, savedKodyId)) { // Listing kody_id lags a local rename until republish. Owners may // hop to the unpublished pair; visitors stay on (or return to) the // listing URL. if (viewerIsOwner && sameKodyId(input.kodyId, listingKodyId)) { return { kind: 'redirect', to: getCommunityPackageHref({ username: target.username, kodyId: savedKodyId, }), shared: false, } } if (!viewerIsOwner && sameKodyId(input.kodyId, savedKodyId)) { return { kind: 'redirect', to: getCommunityPackageHref({ username: target.username, kodyId: listingKodyId, }), shared: true, } } } const invocationUrlOrigin = getAppBaseUrl({ env: input.env, requestUrl: input.request.url, }) if (viewerIsOwner && target.savedPackage) { const pkg = target.savedPackage const packageId = pkg.id const ownerId = target.userId const allows = (permission: OrgPermission) => savedPackageViewerAllows(viewerAccess, permission, { ownerId, packageId, }) const viewerCanManage = allows('package:write') const viewerCanPublish = allows('package:publish') const viewerCanDelete = allows('package:delete') const viewerCanManageAccess = allows('package:manage_access') const viewerCanAdoptCommunityFork = viewerAccess?.binding.role === 'owner' || viewerAccess?.binding.role === 'admin' const viewerMayRun = savedPackageViewerMayRunApp(viewerAccess, { ownerId, appId: packageId, }) const ownerProfilePublicPromise = target.listingId ? null : resolvePackagePageOwnerProfilePublic({ env: input.env, username: target.username, listing: null, }) // Handle rejection now while preserving it for the await below. void ownerProfilePublicPromise?.catch((error) => { reportHandledError('package-page-owner-profile', error) }) const [listing, ownerPackage, openMergeRequestCount] = await Promise.all([ target.listingId ? loadCommunityDetailData( input.env, input.request, target.listingId, input.installOrg ?? null, ) : Promise.resolve(null), input.view ? recordServerTiming( 'owner-package', async () => { const source = await getEntitySourceByIdForUser( input.env.APP_DB, { id: pkg.sourceId, userId: target.userId, }, ) return { id: pkg.id, name: pkg.name, description: pkg.description, isPrivate: pkg.isPrivate, hasApp: pkg.hasApp, lockedAt: pkg.lockedAt, sourceId: pkg.sourceId, hasCommunityListing: target.listingId !== null, publishedCommit: source?.published_commit ?? null, repoId: source?.repo_id ?? null, } satisfies PackageTabOwner }, input.request, ) : loadAccountPackageDetail({ env: input.env, requestUrl: input.request.url, userId: target.userId, ...(viewerCanManage && input.includeManagementDetails !== false ? { ownerUsername: target.username } : {}), packageId, }), input.includeOpenMergeRequestCount ? countOpenPackageMergeRequests(input.env.APP_DB, { ownerUserId: ownerId, packageId, }) : undefined, ]) const ownerProfilePublic = (await ownerProfilePublicPromise) ?? (await resolvePackagePageOwnerProfilePublic({ env: input.env, username: target.username, listing, })) return { kind: 'page', username: target.username, kodyId: target.kodyId, listing, ownerPackage, hasPackage: true, viewerIsOwner: true, viewerCanManage, viewerCanPublish, viewerCanDelete, viewerCanManageAccess, viewerCanSeeConnectedPeople: viewerCanManage && ownerPackage?.hasApp === true, openMergeRequestCount, viewerCanAdoptCommunityFork, viewerMayRun, redirectsToApp: savedPackageRedirectsToApp(target.savedPackage), loggedIn: true, followTarget: { kind: 'package', id: packageId }, invocationUrlOrigin, ownerUserId: target.userId, ownerProfilePublic, } } if (target.listingId) { const listing = await loadCommunityDetailData( input.env, input.request, target.listingId, input.installOrg ?? null, ) const viewerMayRun = target.savedPackage ? savedPackageViewerMayRunApp(viewerAccess, { ownerId: target.userId, appId: target.savedPackage.id, }) : false if (!listing) return { kind: 'not_found' } return { kind: 'page', username: target.username, kodyId: target.kodyId, listing, ownerPackage: null, hasPackage: true, viewerIsOwner: false, viewerCanManage: false, viewerCanPublish: false, viewerCanDelete: false, viewerCanManageAccess: false, viewerCanSeeConnectedPeople: false, viewerCanAdoptCommunityFork: false, viewerMayRun, redirectsToApp: savedPackageRedirectsToApp(target.savedPackage), loggedIn: Boolean(viewer), followTarget: target.savedPackage ? { kind: 'package', id: target.savedPackage.id } : null, invocationUrlOrigin, ownerUserId: target.userId, ownerProfilePublic: listing.ownerProfilePublic, } } if (!target.savedPackage || !isPublicSavedPackage(target.savedPackage)) { // Package exists (or is hidden/private) but this viewer cannot open it. // Signed-in outsiders get an explicit no-access page — never the // generic "doesn't quite connect" 404 that made shared private-app // handoffs look like the package was gone. Anonymous visitors still // get not_found, so private packages stay opaque without a session. // Revealing existence to signed-in people who already know the URL // (share links / handoffs) is intentional product policy. if (viewer && target.savedPackage) { const mayRun = target.savedPackage.hasApp ? savedPackageViewerMayRunApp(viewerAccess, { ownerId: target.userId, appId: target.savedPackage.id, }) : false const links = target.savedPackage.hasApp ? await resolvePackageAppLinks({ env: input.env, username: target.username, kodyId: target.kodyId, viewerMayRun: mayRun, hasPackage: true, ownerUserId: target.userId, hasApp: true, }) : null const packageAppHref = links?.packageAppHref ?? null const securityAudit = await loadPublicPackageSecurityAudit( input.env.APP_DB, target.savedPackage, ) return { kind: 'no_access', username: target.username, kodyId: target.kodyId, packageName: target.savedPackage.name, viewerUsername: viewer.username ?? 'unknown', ...(packageAppHref ? { packageAppHref } : {}), ...(savedPackageRedirectsToApp(target.savedPackage) ? { redirectsToApp: true } : {}), ...(securityAudit ? { securityAudit } : {}), } } if (savedPackageRedirectsToApp(target.savedPackage)) { const links = await resolvePackageAppLinks({ env: input.env, username: target.username, kodyId: target.kodyId, viewerMayRun: false, hasPackage: true, ownerUserId: target.userId, hasApp: true, }) if (links?.packageAppHref) { return { kind: 'not_found', appRedirectHref: links.packageAppHref } } } return { kind: 'not_found' } } return { kind: 'unauthorized' } }