import { packageAppVisitorNeedKeyPattern } from '#worker/package-registry/types.ts' import type { OwnerId } from '@kody-internal/shared/owner-person-ids.ts' import type { RuntimePackageAppIdentity, RuntimePackageAppVisitSession, RuntimePackageAppVisitor, } from '@kody-internal/shared/runtime-worker.ts' import * as Sentry from '@sentry/cloudflare' import { waitUntil as scheduleWorkerWaitUntil } from 'cloudflare:workers' import { isSandboxCpuLimitError, sandboxCpuLimitExecutionMessage, } from '#mcp/sandbox-cpu-limit.ts' import { getErrorMessage } from '@kody-internal/shared/error-message.ts' import { parseJsonWithFallback } from '@kody-internal/shared/json-parsing.ts' import { kodyDevErrorHeader, type KodyDevSerializedError, } from '@kody-internal/shared/kody-dev-error.ts' import { isKodyDevStack } from '#worker/package-runtime/kody-dev-simulation.ts' import { html } from 'remix/html-template' import { createHtmlResponse } from 'remix/response/html' import { buildPackageAppCustomHostnamePath, buildPackageAppPath, buildPackageAppSubdomainPath, packageAppOpenPathSegment, type PackageAppMount, } from '@kody-internal/shared/public-urls.ts' import { isPackageAppHostNonLeafFirstSegment, isPackageAppHostProbeFirstSegment, isPackageAppHostProbePath, packageAppHostLegacyMountSegment, } from '@kody-internal/shared/package-app-host-paths.ts' import { accountCreditsPath } from '#universal/compute-overage.ts' import { packageAppOauthPaths } from '#universal/package-app-oauth-paths.ts' import { renderErrorAgentPromptStaticHtml } from '#universal/error-agent-prompt.ts' import { buildPackageAppErrorAgentPrompt } from '#universal/error-agent-prompt-presets.ts' import { packageAppHandoffQueryParam } from '#app/package-app-handoff.ts' import { needsPackageAppRunConsent, packageAppRunConsentResponse, } from '#app/package-app-run-consent.ts' import { findLivePackageAppOauthGrant, notePackageAppOauthGrantUse, } from '#app/package-app-oauth-grants.ts' import { buildPackagePublishApprovalUrl } from '#worker/package-registry/package-publish-lock.ts' import { resolveCachedArtifactSourceHead } from '#worker/repo/artifact-head-cache.ts' import { isPackageSourceNotPublishedError } from '#worker/repo/source-not-published-error.ts' import { getAppBaseUrl, getCanonicalAppBaseUrl, listPackageAppOrigins, parsePackageAppRequestHost, } from '#worker/app-base-url.ts' import { filterPackageAppSetCookies, logPackageAppSetCookieNamesDropped, logPackageAppSetCookieDomainStripped, } from '#worker/package-runtime/package-app-set-cookie.ts' import { recordPackageAppCookieFindings } from '#worker/package-runtime/package-app-cookie-httponly.ts' import { deferPackageAppResponseRewrite, type PackageAppResponseRewriteReport, } from '#worker/package-runtime/package-app-response-rewrite.ts' import { filterPackageAppRequestCookies, packageAppCookiePrefix, } from '#worker/package-runtime/package-app-cookie-prefix.ts' import { isPackageAppRuntimeThrownResponse, logPackageAppHttpError, packageAppDispatchTimingHeader, packageAppRuntimeRunIdHeader, runtimeRunIdFromError, packageAppRequestIdFromRequest, withForwardedPackageAppRequestId, withPackageAppRequestId, } from '#worker/package-runtime/package-app-diagnostics.ts' import { isComputeOverageLimitError } from '#worker/entitlements/errors.ts' import { beginRunRecord, finishRunRecord } from '#worker/run-records/service.ts' import { getUsernameFormatValidationError } from '#worker/identity/username.ts' import { loadInvokeManifestBySourceId, resolveSavedPackageForPackageAppSlug, } from '#worker/package-invocations/module-artifacts.ts' import type { PackageAppSlugLookup } from '#worker/package-invocations/invoke-contract-cache.ts' import type { EntitySourceRow } from '#worker/repo/types.ts' import { getPackageNameLeaf } from '#worker/package-registry/package-name.ts' import { getPackageAppAnonymousRealtimeMode, getPackageAppClientReadableCookieNames, getPackageAppEntryPath, } from '#worker/package-registry/manifest.ts' import { loadServingPackageSourceBySourceId } from '#worker/package-registry/source.ts' import { newRunCredentialClientBinding } from '#worker/credentials/credential-client-handle.ts' import { loadPublishedCredentialNeeds } from '#worker/credentials/credential-needs-closure.ts' import { savedCredentialNeeds } from '#worker/credentials/credential-needs.ts' import { isPackageCredentialSuppliersEnabled } from '#worker/credentials/credential-suppliers-flag.ts' import { CredentialClientError, openCredentialClient, } from '#worker/credentials/credential-client.ts' import { createPackageAppCredentialAuthority, createPackageAppVisitorPersonalRequest, } from '#worker/package-runtime/package-app-authority.ts' import { buildPackageAppWorker, createPackageAppCallerContext, prefetchPackageAppBuild, } from '#worker/package-runtime/package-app.ts' import { prefetchAnonymousPackageAppUsage } from './package-app-usage-breaker.ts' import { tracePackageAppPhase } from '#worker/package-runtime/package-app-tracing.ts' import { parsePackageAppAssetRequestPath, servePackageAppAssetRequest, } from '#worker/package-runtime/package-app-assets.ts' import { isPublishedRuntimeBundleMissingError } from '#worker/package-runtime/published-source-dependencies.ts' import { buildPackageAppNotFoundMessage, isPackageAppSyntheticRequest, packageAppSyntheticHeaderName, packageAppSyntheticHeaderValue, packageAppVisitorConsentRequiredHeader, type PackageAppTrustedDispatch, } from '#worker/package-runtime/package-app-synthetic.ts' import { resolvePackageAppBilling } from '#worker/package-runtime/package-app-billing.ts' import { withPackageAppVisitorHeader } from '#worker/package-runtime/package-app-visitor-header.ts' import { endPackageAppVisit, withPackageAppVisitTicket, } from '#worker/package-runtime/package-app-visit-ticket.ts' import { packageRealtimeSessionRpc, type PackageRealtimeConnectOptions, } from '#worker/package-runtime/realtime-session.ts' import { decidePublicRealtimeAccess, hashRealtimeClientIp, } from '#worker/package-runtime/package-app-public-realtime.ts' import { isWebSocketUpgradeRequest } from '#worker/package-runtime/websocket-upgrade.ts' import { anonymousRefusalResponse, refuseUnapprovedAnonymousServe, } from '#worker/package-runtime/package-app-anonymous-serve.ts' import { wantsJson } from '#worker/utils.ts' import { applyPackageAppDefaults, isPackageAppPageVisit, } from '#worker/package-runtime/package-app-defaults.ts' import { recordPackageAppLastOpened } from '#app/package-app-last-opened.ts' import { refusePackageAppWriteOverRateLimit } from '#worker/package-runtime/package-app-default-rate-limit.ts' import { pushServerTiming, type ServerTimingEntry, } from '#worker/server-timing.ts' import { getRuntimeWorkerService, hasLocalPackageAppRuntimeBridge, packageAppRuntimeForwardUnavailableMessage, } from '#worker/runtime-worker-service.ts' import { outboundTimeoutMs, withDeadline, } from '@kody-internal/shared/with-deadline.ts' export type PackageAppServeOwner = { userId: OwnerId username: string email: string displayName: string } export { type PackageAppMount } export type PackageAppPath = { username: string kodyId: string restPath: string mount: PackageAppMount /** * True when the app-origin path used `/open` after the package leaf * (`/@user/packages/{name}/open/...`). The segment is platform handoff * markup, not part of the hosted app path. */ openHandoff?: boolean } /** * App path below the package leaf. A trailing slash is part of the URL the * visitor asked for, so it is forwarded as-is: an app that canonicalizes * `/admin` to `/admin/` would otherwise redirect to itself forever. */ function packageAppRestPath(parts: Array, pathname: string) { if (parts.length === 0) return '/' return `/${parts.join('/')}${pathname.endsWith('/') ? '/' : ''}` } export function parsePackageAppPath(pathname: string): PackageAppPath | null { const parts = pathname.split('/').filter(Boolean) const rawUsername = parts[0]?.startsWith('@') ? parts[0].slice(1) : '' if (!rawUsername || parts[1] !== 'packages') return null const rawKodyId = parts[2]?.trim() if (!rawKodyId) return null let username: string let kodyId: string try { username = decodeURIComponent(rawUsername) kodyId = decodeURIComponent(rawKodyId) } catch { return null } if (getUsernameFormatValidationError(username)) return null const afterLeaf = parts.slice(3) const openHandoff = afterLeaf[0] === packageAppOpenPathSegment const restParts = openHandoff ? afterLeaf.slice(1) : afterLeaf return { username, kodyId, restPath: packageAppRestPath(restParts, pathname), mount: 'username-path', ...(openHandoff ? { openHandoff: true } : {}), } } /** * Parse the path shape served on a per-user package-app subdomain, where the * username comes from the hostname. The canonical shape is `/{kodyId}/{rest}`; * the legacy `/packages/{kodyId}/{rest}` mount is still accepted. Reserved * first segments (`-`, `.well-known`, ...) are Kody-owned and never parse as a * package, and a bare `/packages` has no leaf. The caller must already have * validated the subdomain's username label. * Remove when: production `PACKAGE_APP_LEGACY_HOSTS` is empty and legacy `/packages` mount and `/_kody/auth` hits stay at zero. */ export function parsePackageAppSubdomainPath(input: { pathname: string username: string }): PackageAppPath | null { const parts = input.pathname.split('/').filter(Boolean) const rawFirst = parts[0]?.trim() if (!rawFirst) return null const legacyMount = rawFirst === packageAppHostLegacyMountSegment const leafIndex = legacyMount ? 1 : 0 const rawKodyId = parts[leafIndex]?.trim() if (!rawKodyId) return null let kodyId: string try { kodyId = decodeURIComponent(rawKodyId) } catch { return null } if (!legacyMount && isPackageAppHostNonLeafFirstSegment(kodyId)) return null return { username: input.username, kodyId, restPath: packageAppRestPath(parts.slice(leafIndex + 1), input.pathname), mount: 'user-subdomain', } } /** * Path on a verified custom hostname. The username and package slug come from * the hostname mapping; the request path is the app path. An empty pathname * is `/`. */ export function parsePackageAppCustomHostnamePath(input: { pathname: string username: string kodyId: string }): PackageAppPath { const pathname = input.pathname.trim() const parts = pathname.split('/').filter(Boolean) return { username: input.username, kodyId: input.kodyId, restPath: packageAppRestPath(parts, pathname), mount: 'custom-hostname', } } function packageAppBasePath(input: { mount: PackageAppMount username: string kodyId: string }): string { switch (input.mount) { case 'user-subdomain': return buildPackageAppSubdomainPath({ kodyId: input.kodyId }) case 'username-path': return buildPackageAppPath({ username: input.username, kodyId: input.kodyId, }) case 'custom-hostname': return '' default: { input.mount satisfies never throw new Error(`Unknown package app mount: ${String(input.mount)}`) } } } function packageAppLocationPath(input: { mount: PackageAppMount username: string kodyId: string restPath?: string | null }): string { switch (input.mount) { case 'user-subdomain': return buildPackageAppSubdomainPath({ kodyId: input.kodyId, restPath: input.restPath, }) case 'username-path': return buildPackageAppPath({ username: input.username, kodyId: input.kodyId, restPath: input.restPath, }) case 'custom-hostname': return buildPackageAppCustomHostnamePath({ restPath: input.restPath }) default: { input.mount satisfies never throw new Error(`Unknown package app mount: ${String(input.mount)}`) } } } function buildPackageAppLoginUrl(input: { requestUrl: string appLeaf: string }) { const loginUrl = new URL(packageAppOauthPaths.login, input.requestUrl) loginUrl.searchParams.set('app', input.appLeaf) return loginUrl } export function isPackageAppRequestPath(pathname: string) { return parsePackageAppPath(pathname) !== null } // Credentials that must never reach author-supplied package code. `Cookie` // carries the owner's `kody_session`, `Authorization` carries MCP bearer tokens, // and the `X-Kody-*` family is worker-internal auth (connector session keys and // user ids). `Kody-Synthetic` is platform-only and must never be caller-controlled // on public ingress. Stripping is unconditional as defense in depth and is also // required for the non-production inline serving path. const strippedPackageRequestHeaders = [ 'cookie', 'authorization', 'proxy-authorization', packageAppSyntheticHeaderName.toLowerCase(), ] /** * Clone a request for package code with every credential header removed. * * Used for both the forwarded HTTP request and the realtime connect upgrade, * because the realtime `connect` hook receives the request headers too. */ export function createPackageCodeRequest( request: Request, url: string | URL = request.url, options: { cookiePrefix?: string | null } = {}, ) { // The app's redirects go back to whoever asked; serve never follows them. const packageCodeRequest = new Request(new Request(url.toString(), request), { redirect: 'manual', }) for (const headerName of strippedPackageRequestHeaders) { packageCodeRequest.headers.delete(headerName) } if (options.cookiePrefix) { const cookie = filterPackageAppRequestCookies( request.headers.get('Cookie'), options.cookiePrefix, ) if (cookie) packageCodeRequest.headers.set('Cookie', cookie) } // Snapshot names so deletes during this loop do not skip headers. // oxlint-disable-next-line unicorn/no-useless-spread for (const headerName of [...packageCodeRequest.headers.keys()]) { const normalized = headerName.toLowerCase() if ( normalized.startsWith('x-kody-') || normalized === packageAppSyntheticHeaderName.toLowerCase() ) { packageCodeRequest.headers.delete(headerName) } } return packageCodeRequest } export function applyTrustedPackageAppDispatch( request: Request, dispatch: PackageAppTrustedDispatch | undefined, ) { if (dispatch?.synthetic !== true) { return request } const trustedRequest = new Request(request) trustedRequest.headers.set( packageAppSyntheticHeaderName, packageAppSyntheticHeaderValue, ) return trustedRequest } function parsePackageRealtimePath(restPath: string) { const parts = restPath.split('/').filter(Boolean) if (parts[0] !== 'ws') return null if (parts.length > 2) return null const rawFacet = parts[1]?.trim() ?? '' if (!rawFacet) { return { facet: null, } } try { return { facet: decodeURIComponent(rawFacet), } } catch { return null } } function reportPackageAppFailure(input: { error: unknown phase: 'host-setup' | 'realtime-connect' requestUrl: URL kodyId: string packageId: string packageName: string sourceId: string forwardedPath: string realtimePath: string }) { try { if (!Sentry.isInitialized()) return const client = Sentry.getClient() if (!client?.getOptions().dsn) return Sentry.withScope((scope) => { scope.setLevel('error') scope.setTag('package_app.phase', input.phase) scope.setTag('package_app.kody_id', input.kodyId) scope.setTag('package_app.package_id', input.packageId) scope.setTag('package_app.source_id', input.sourceId) scope.setContext('package_app', { phase: input.phase, kodyId: input.kodyId, packageId: input.packageId, packageName: input.packageName, sourceId: input.sourceId, forwardedPath: input.forwardedPath, realtimePath: input.realtimePath, hostPath: input.requestUrl.pathname, }) Sentry.captureException(input.error) }) } catch (sentryError) { console.warn('Failed to report package app failure to Sentry.', sentryError) } } /** * Expected host-setup outcomes that must not open platform Sentry issues. * Matches invoke's `isTransientModuleArtifactError` treatment of a missing * published npm runtime bundle (503, retryable). Stuck rebuilds stay visible * via publish rebuild failures and repeated 503 `package-app-http-error` logs. */ function resolveExpectedPackageAppHostSetupFailure(input: { request: Request error: unknown kodyId: string packageName: string synthetic?: boolean }): Response | null { if (isPackageSourceNotPublishedError(input.error)) { return createPackageAppErrorResponse({ request: input.request, kind: 'not-published', kodyId: input.kodyId, packageName: input.packageName, synthetic: input.synthetic, cause: input.error.message, }) } if (isComputeOverageLimitError(input.error)) { return createPackageAppErrorResponse({ request: input.request, kind: 'include-used-up', kodyId: input.kodyId, packageName: input.packageName, synthetic: input.synthetic, cause: input.error.message, }) } if (isPublishedRuntimeBundleMissingError(input.error)) { return createPackageAppErrorResponse({ request: input.request, kind: 'runtime-bundle-pending', kodyId: input.kodyId, packageName: input.packageName, synthetic: input.synthetic, cause: getErrorMessage(input.error), runtimeRunId: runtimeRunIdFromError(input.error), }) } return null } type PackageAppFailureKind = | 'host-setup' | 'package-entrypoint' | 'realtime-connect' | 'include-used-up' | 'runtime-bundle-pending' | 'not-published' | 'publish-pending' /** Pushed package repo HEAD that is newer than the commit being served. */ type UnpublishedChanges = { publishedCommit: string headCommit: string publishUrl: string } function packageAppFailureStatus(kind: PackageAppFailureKind) { switch (kind) { case 'include-used-up': return 429 case 'runtime-bundle-pending': case 'not-published': return 503 case 'publish-pending': case 'host-setup': case 'package-entrypoint': case 'realtime-connect': return 500 default: { const exhaustive: never = kind void exhaustive return 500 } } } /** * When the served commit fails a page load, tell someone who can publish that * newer pushed commits are waiting. Only owners and admins loading an HTML page * see it; API callers and other visitors keep the app's own response. */ async function resolveUnpublishedChanges(input: { env: Env request: Request visitor: RuntimePackageAppVisitor | null synthetic: boolean repoId: string | null publishedCommit: string | null username: string kodyId: string }): Promise { const role = input.visitor?.role if (role !== 'owner' && role !== 'admin') return null if (input.synthetic || !input.repoId || !input.publishedCommit) return null if (input.request.method !== 'GET' && input.request.method !== 'HEAD') { return null } const accept = input.request.headers.get('accept') ?? '' if (!accept.includes('text/html') || wantsJson(input.request)) return null try { const head = await resolveCachedArtifactSourceHead( input.env, input.repoId, { request: input.request }, ) if (!head.commit || head.commit === input.publishedCommit) return null return { publishedCommit: input.publishedCommit, headCommit: head.commit, publishUrl: buildPackagePublishApprovalUrl({ baseUrl: getCanonicalAppBaseUrl({ env: input.env }), username: input.username, kodyId: input.kodyId, commit: head.commit, }), } } catch (error) { console.warn('Package app unpublished-changes lookup failed:', error) return null } } /** * The Cloudflare ray of the visitor request, shown on the crash page so an * owner can match a report to logs. Only a well-formed ray id is echoed. */ function cloudflareRayIdOf(request: Request) { const ray = request.headers.get('cf-ray')?.trim() ?? '' return /^[0-9a-f]{16}(?:-[A-Z]{3})?$/i.test(ray) ? ray : null } function serializeKodyDevError(error: unknown): KodyDevSerializedError { if (error instanceof Error) { return { name: error.name || 'Error', message: error.message, stack: error.stack ?? '', } } return { name: 'Error', message: getErrorMessage(error), stack: '' } } /** The handler error the app isolate put on its internal 500 (local `kody dev` only). */ async function readKodyDevError( response: Response, ): Promise { const body = parseJsonWithFallback > | null>(await response.text(), null) return { name: typeof body?.name === 'string' ? body.name : 'Error', message: typeof body?.message === 'string' ? body.message : 'The package app handler threw.', stack: typeof body?.stack === 'string' ? body.stack : '', } } /** * Local `kody dev` stack only: hand an uncaught handler error to the dev * proxy, which renders it with its stack, records it as the last error and * prints it. Hosted Kody serves {@link createPackageAppErrorResponse}. */ function createKodyDevErrorResponse(error: KodyDevSerializedError) { return Response.json(error, { status: 500, headers: { [kodyDevErrorHeader]: '1' }, }) } function createPackageAppErrorResponse(input: { request: Request kind: PackageAppFailureKind kodyId: string packageName: string synthetic?: boolean cause?: string runtimeRunId?: string | null /** Overrides the kind's status, e.g. to keep the app's own 5xx. */ status?: number unpublishedChanges?: UnpublishedChanges | null }) { const messages = { 'host-setup': { title: 'Package app could not be prepared', summary: 'Kody could not load or prepare this package app runtime before your request reached the package code.', nextStep: 'This has been reported to Kody. Try again shortly, or ask the package owner to republish the package if it keeps happening.', }, 'package-entrypoint': { title: 'Package app crashed', summary: 'The package app started, but its own request handler failed while processing this request.', nextStep: 'Ask the package owner to check recent runs for this app under Account → Activity.', }, 'realtime-connect': { title: 'Package realtime connection failed', summary: 'Kody could not establish the realtime session for this package app.', nextStep: 'This has been reported to Kody. Try reconnecting, or ask the package owner to retry after checking the package app.', }, 'include-used-up': { title: 'Monthly include used up', summary: 'This month’s included Pro usage is used up and there are no credits left, so the app is paused.', nextStep: `Add credits at ${accountCreditsPath} to keep going, or wait for the include to reset next UTC month.`, }, 'runtime-bundle-pending': { title: 'Package app is still preparing', summary: 'The published runtime for this package app is not ready yet. This is common right after a publish while Kody installs npm dependencies and builds the runtime bundle.', nextStep: 'Try again shortly. If this keeps happening long after publishing, ask the package owner to republish the package.', }, 'not-published': { title: 'Package app not published yet', summary: 'Code has been pushed to this package, but no version has been published, so there is nothing to serve yet.', nextStep: `If you own this package, publish it with \`kody package publish ${input.packageName}\` or from the package page on Kody, then reload.`, }, 'publish-pending': { title: 'Package app has unpublished changes', summary: 'The published version of this package app failed this request. Newer commits have been pushed but are not published yet, so this is still the older version.', nextStep: 'Publish the latest push if it has the fix, then reload. Otherwise check recent runs for this app under Account → Activity.', }, } satisfies Record< PackageAppFailureKind, { title: string; summary: string; nextStep: string } > const message = messages[input.kind] const status = input.status ?? packageAppFailureStatus(input.kind) const unpublished = input.unpublishedChanges ?? null logPackageAppHttpError({ request: input.request, status, phase: input.kind, runtimeRunId: input.runtimeRunId ?? null, }) const requestPath = new URL(input.request.url).pathname const rayId = cloudflareRayIdOf(input.request) const body = { error: message.title, message: message.summary, next_step: message.nextStep, package: { name: input.packageName, kody_id: input.kodyId, }, request_path: requestPath, ...(input.runtimeRunId ? { run_id: input.runtimeRunId } : {}), ...(input.synthetic === true && input.cause ? { cause: input.cause } : {}), ...(unpublished ? { unpublished_changes: { published_commit: unpublished.publishedCommit, head_commit: unpublished.headCommit, publish_url: unpublished.publishUrl, }, } : {}), } if (input.synthetic === true || wantsJson(input.request)) { return Response.json(body, { status }) } return createHtmlResponse( html` ${message.title}

${message.title}

${message.summary}

${message.nextStep}

${ unpublished ? html`

Review and publish ${unpublished.headCommit.slice(0, 7)}

` : '' }
Package
${input.packageName}
Kody ID
${input.kodyId}
Path
${requestPath}
${ unpublished ? html`
Published commit
${unpublished.publishedCommit.slice(0, 7)}
Latest push
${unpublished.headCommit.slice(0, 7)}
` : '' } ${ input.runtimeRunId ? html`
Run ID
${input.runtimeRunId}
` : '' } ${ rayId ? html`
Ray ID
${rayId}
` : '' }
${html.raw`${renderErrorAgentPromptStaticHtml( buildPackageAppErrorAgentPrompt({ kind: input.kind, packageName: input.packageName, kodyId: input.kodyId, path: requestPath, // Visitor HTML must not include host exception text; // JSON synthetic responses still carry `cause`. runtimeRunId: input.runtimeRunId, rayId, }), )}`}
`, { status }, ) } /** * Attach request-scoped Server-Timing phases collected on the package-app * serve path. Clones headers so author responses stay immutable-safe. * * WebSocket upgrades (status 101 with a paired `webSocket`) are returned as-is: * Durable Object upgrade responses have immutable headers, so in-place * `Server-Timing` throws; rebuilding without `webSocket` rejects status 101; * browsers do not expose upgrade response headers to page JS the way fetch does. */ function attachPackageAppServerTiming( response: Response, serverTiming: Array, visitNonce?: string | null, ) { // WebSocket upgrades skip timing inside the rewrite (see function doc). return deferPackageAppResponseRewrite(response, { serverTiming, ...(visitNonce ? { visitNonce } : {}), }) } function recordPackageAppDispatchTiming( timings: Array, response: Response, startedAt: number, endedAt: number, ) { if (response.webSocket || response.status === 101) return const value = response.headers.get(packageAppDispatchTimingHeader) const match = value?.match( /^([01]),([0-9]{1,15}),([0-9]{0,15}),([0-9]{0,15})$/, ) if (!match) return const [, cold, childStartedAt, userModuleMs, handlerMs] = match const dispatchMs = Math.max(0, endedAt - startedAt) timings.push({ name: 'appIsolate', durationMs: Math.max( 0, Math.min(dispatchMs, Number(childStartedAt) - startedAt), ), desc: cold === '1' ? 'cold' : 'warm', }) if (userModuleMs) { timings.push({ name: 'appUserModule', durationMs: Math.min(dispatchMs, Number(userModuleMs)), }) } if (handlerMs) { timings.push({ name: 'appHandler', durationMs: Math.min(dispatchMs, Number(handlerMs)), }) } } /** * OPTIONS is not a package mutation. When the app handler throws instead of * answering, browsers still need a finished preflight rather than the * platform crash page. Apps that return their own OPTIONS response are * unchanged. */ function unhandledPackageAppOptionsResponse() { return new Response(null, { status: 204, headers: { Allow: 'GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS', 'Cache-Control': 'no-store', }, }) } /** * Serve a hosted package app for an already-authenticated owner, acting as * the visitor. * * The owner is resolved by the caller because the package-app origin uses its * own host-scoped `kody_pkg_session` cookie, while the non-production inline * mode uses the `kody_session` cookie (see `package-app-origin.ts`). */ export const packageAppEntrypointFailureMessage = 'The package app worker failed before its request handler ran, so the app code did not see this request. This is a Kody platform failure, not an error in the app.' /** * Record an `app_fetch` error run for a request whose app worker threw before * the wrapper could start its own run. Returns the run id, or null when the run * could not be stored. The host exception text stays out of the run: it * is platform-internal, not something the package owner can act on. The one * exception is the app's own code running past its CPU limit, which the * owner can fix. */ export async function recordPackageAppEntrypointFailure(input: { env: Env ownerId: OwnerId savedPackage: { id: string; kodyId: string; sourceId: string } publishedCommit: string | null name: string method: string error: unknown waitUntil?: (promise: Promise) => void }): Promise { const sink = input.waitUntil ?? scheduleWorkerWaitUntil try { const handle = beginRunRecord({ env: input.env, userId: input.ownerId, context: { packageId: input.savedPackage.id, kodyId: input.savedPackage.kodyId, sourceId: input.savedPackage.sourceId, publishedCommit: input.publishedCommit, surface: 'app_fetch', name: input.name, metadata: { method: input.method, phase: 'package-entrypoint', recordedBy: 'host', }, }, waitUntil: sink, }) if (!handle) return null const failure = new Error( isSandboxCpuLimitError(input.error) ? sandboxCpuLimitExecutionMessage : packageAppEntrypointFailureMessage, ) failure.name = input.error instanceof Error && input.error.name ? input.error.name : 'Error' // Only show a run id on the crash page once the run is really stored. const persisted = await finishRunRecord({ env: input.env, handle, status: 'error', error: failure, waitUntil: sink, }) return persisted ? handle.id : null } catch (recordError) { console.warn('package-app-entrypoint-run-record-failed', recordError) return null } } type ServePackageAppRequestInput = Parameters< typeof servePackageAppRequestWithId >[0] /** * Every served response carries `x-kody-request-id` (alongside * Server-Timing); a sampled request stores CPU and wall time under the same id. */ export async function servePackageAppRequest( input: ServePackageAppRequestInput, ) { // The slim origin forwards to RUNTIME_WORKER, which tags the response itself. if (!hasLocalPackageAppRuntimeBridge()) { return servePackageAppRequestWithId(input) } const tagged = withPackageAppRequestId(input.request) const response = await servePackageAppRequestWithId({ ...input, request: tagged.request, }) return deferPackageAppResponseRewrite(response, { requestId: tagged.requestId, }) } async function servePackageAppRequestWithId(input: { request: Request env: Env owner: PackageAppServeOwner /** Null for an anonymous visitor of an internet-visible app. */ visitor: RuntimePackageAppVisitor | null /** See `RuntimePackageAppServeInput.identity`. Ignored with a visitor. */ identity?: RuntimePackageAppIdentity | null /** See `RuntimePackageAppServeInput.consentPrincipal`. Never reaches the app. */ consentPrincipal?: RuntimePackageAppIdentity | null /** See `RuntimePackageAppServeInput.approvedPublishedCommit`. */ approvedPublishedCommit?: string | null resolvedSlug?: PackageAppSlugLookup resolvedManifestSource?: EntitySourceRow anonymousAssetRequest?: boolean /** See `RuntimePackageAppServeInput.visitSession`. */ visitSession?: RuntimePackageAppVisitSession | null packagePath: PackageAppPath dispatch?: PackageAppTrustedDispatch /** * Optional bag started by host setup (owner lookup). Serve appends its own * phases and writes the combined `Server-Timing` header on the response. */ serverTiming?: Array }) { // Slim origin (production-worker / preview) does not export // PackageAppRuntimeBridge (ADR 0034). HTTP package-app routes are already // forwarded wholesale via isRuntimeWorkerOwnedRequest; this gate covers the // remaining in-process path (stateless MCP appFetch → serve). // One contract: local bridge, or RUNTIME_WORKER RPC — never construct here // without either. if (!hasLocalPackageAppRuntimeBridge()) { const runtime = getRuntimeWorkerService(input.env) if (!runtime) { return createPackageAppErrorResponse({ request: input.request, kind: 'host-setup', kodyId: input.packagePath.kodyId, packageName: input.packagePath.kodyId, synthetic: input.dispatch?.synthetic === true, cause: packageAppRuntimeForwardUnavailableMessage, }) } return runtime.servePackageApp({ request: input.request, owner: input.owner, visitor: input.visitor, identity: input.identity ?? null, consentPrincipal: input.consentPrincipal ?? null, approvedPublishedCommit: input.approvedPublishedCommit, visitSession: input.visitSession, packagePath: input.packagePath, dispatch: input.dispatch, }) } const { request, env, owner, visitor, packagePath, dispatch } = input // Identity rides only on an otherwise anonymous request; a visitor already // names the person. const identity = visitor ? null : (input.identity ?? null) // Only decides whether to offer consent; it is never handed to the app. const consentPerson = visitor ?? identity ?? input.consentPrincipal ?? null const serverTiming = input.serverTiming ?? [] const requestUrl = new URL(request.url) const { kodyId } = packagePath const packageRealtimeRestPath = packagePath.restPath const forwardedPackageRestPath = packagePath.restPath // Scanner / VCS probes never reach package code. 404 before the metered // entitlement seat-count gate (and before slug lookup) so bot noise does // not pay for live seat reads. Custom hostnames bind a package at `/`, so // restPath is the probe; on subdomain mounts the leaf itself may be the // probe segment. if ( isPackageAppHostProbePath(packagePath.restPath) || isPackageAppHostProbeFirstSegment(packagePath.kodyId) ) { return attachPackageAppServerTiming( new Response(buildPackageAppNotFoundMessage(), { status: 404 }), serverTiming, ) } if (owner.username !== packagePath.username) { return attachPackageAppServerTiming( new Response(buildPackageAppNotFoundMessage(), { status: 404 }), serverTiming, ) } // Same freshness-tier cache family as keyless host export invoke, but a // distinct key that may follow slug redirects. A retired slug never serves // on a path that includes the slug: permanent 308 to the current leaf so // cookies, caches, and storage stay on one canonical path (webhooks and // invocations still follow internally). Custom hostnames bind by package // id and have no slug in the URL, so a same-path redirect is skipped. const slugLookup = await pushServerTiming( serverTiming, 'resolveSavedPackage', () => input.resolvedSlug ? Promise.resolve(input.resolvedSlug) : resolveSavedPackageForPackageAppSlug({ db: env.APP_DB, userId: owner.userId, slug: kodyId, }), ) // `hasApp` projects the published commit, and publish moves it before the // serving commit advances, so it only rules packages out. The manifest at // the commit actually served decides below whether an app answers. if (!slugLookup || !slugLookup.savedPackage.hasApp) { return attachPackageAppServerTiming( new Response(buildPackageAppNotFoundMessage(), { status: 404 }), serverTiming, ) } const savedPackage = slugLookup.savedPackage if (slugLookup.retired) { // Location must use the name leaf (Kent: slug = package name leaf), not // savedPackage.kodyId — those can diverge until Phase 2's single writer, // and a mismatch would 308 to the same retired path forever. const currentSlug = getPackageNameLeaf(savedPackage.name) const locationPath = packageAppLocationPath({ mount: packagePath.mount, username: packagePath.username, kodyId: currentSlug, restPath: forwardedPackageRestPath === '/' ? null : forwardedPackageRestPath, }) const location = new URL(locationPath, requestUrl) // Drop a handoff minted for the retired slug — consume would reject it. location.search = requestUrl.search location.searchParams.delete(packageAppHandoffQueryParam) const next = `${location.pathname}${location.search}` const current = `${requestUrl.pathname}${requestUrl.search}` // Custom hostnames bind by package id, so a retired slug does not appear // in the URL. A 308 to the same path would loop; keep serving. if (next !== current) { return attachPackageAppServerTiming( new Response(null, { status: 308, headers: { Location: next, // Source slug can be reclaimed by a later package; positive // freshness would keep sending browsers to the wrong app. 'Cache-Control': 'no-store', }, }), serverTiming, ) } } const overRateLimit = await refusePackageAppWriteOverRateLimit({ request, env, packageId: savedPackage.id, synthetic: dispatch?.synthetic === true, }) if (overRateLimit) { return attachPackageAppServerTiming(overRateLimit, serverTiming) } // Custom hostnames are not the app origin. `getAppBaseUrl(requestUrl)` // would otherwise treat the customer Host as first-party and point // package runtime API calls at the custom domain. const productHost = parsePackageAppRequestHost({ env, url: requestUrl }) const baseUrl = packagePath.mount === 'custom-hostname' || (packagePath.mount === 'user-subdomain' && !productHost) ? getCanonicalAppBaseUrl({ env }) : getAppBaseUrl({ env, requestUrl: request.url }) if ( await needsPackageAppRunConsent({ db: env.APP_DB, packageId: savedPackage.id, visitor, }) ) { return attachPackageAppServerTiming( packageAppRunConsentResponse({ request, baseUrl, packagePath, noRedirect: dispatch !== undefined, fromAppHost: productHost?.kind === 'app-subdomain' || (productHost?.kind === 'user-subdomain' && packagePath.mount === 'custom-hostname'), }), serverTiming, ) } // Every signed-in launch path (handoff, OAuth host, ticket, inline) ends // here, so a person's page visit past consent is the app open. if ( visitor && !visitor.profile && dispatch === undefined && isPackageAppPageVisit(request) ) { recordPackageAppLastOpened(env.APP_DB, { packageId: savedPackage.id, orgId: owner.userId, personId: visitor.userId, }) } const packageRealtimePath = parsePackageRealtimePath(packageRealtimeRestPath) const cookiePrefix = await packageAppCookiePrefix(savedPackage.id) if (packageRealtimePath && isWebSocketUpgradeRequest(request)) { try { // Org members connect as before. Anyone else (anonymous, or signed in // outside the org) needs the app's `kody.app.realtime.anonymous` // opt-in at the commit its owner approved (ADR 0069). let connectOptions: PackageRealtimeConnectOptions if (visitor) { // A member socket is authorized again while it stays open, so it // needs the session it was opened from (realtime-session.ts). if (!input.visitSession) { return attachPackageAppServerTiming( new Response('Realtime needs a signed-in visit session.', { status: 403, headers: { 'Cache-Control': 'no-store' }, }), serverTiming, ) } connectOptions = { visitSession: input.visitSession, access: 'member', visitor: { userId: visitor.userId, username: visitor.username, role: visitor.role, ...(visitor.profile ? { profile: visitor.profile } : {}), }, } } else { const packageManifest = savedPackage.isInternetVisible ? await pushServerTiming(serverTiming, 'manifest', () => loadInvokeManifestBySourceId({ env, userId: owner.userId, sourceId: savedPackage.sourceId, ...(input.resolvedManifestSource && { resolvedSource: input.resolvedManifestSource, }), }), ) : null const access = decidePublicRealtimeAccess({ isInternetVisible: savedPackage.isInternetVisible, mode: packageManifest ? getPackageAppAnonymousRealtimeMode(packageManifest.manifest) : null, approvedPublishedCommit: input.approvedPublishedCommit, publishedCommit: packageManifest?.source.published_commit, }) if (!access.ok) { return attachPackageAppServerTiming( anonymousRefusalResponse(access.message), serverTiming, ) } connectOptions = { access: access.mode, visitor: identity ? { userId: identity.userId, username: identity.username, role: null, } : null, approvedCommit: access.approvedCommit, ipHash: await hashRealtimeClientIp({ packageId: savedPackage.id, request, }), } } const connected = await withDeadline( { label: 'package_realtime_session.connect', timeoutMs: outboundTimeoutMs.durableObject, }, () => packageRealtimeSessionRpc({ env, userId: owner.userId, packageId: savedPackage.id, kodyId: savedPackage.kodyId, sourceId: savedPackage.sourceId, baseUrl, }).connect( createPackageCodeRequest(request, request.url, { cookiePrefix }), packageRealtimePath.facet, connectOptions, ), ) const filtered = filterPackageAppSetCookies(connected, cookiePrefix) logPackageAppSetCookieNamesDropped({ hostname: requestUrl.hostname, pathname: requestUrl.pathname, dropped: filtered.dropped, surface: 'package-app-realtime', }) logPackageAppHttpError({ request, status: filtered.response.status, phase: 'realtime-response', runtimeRunId: filtered.response.headers.get( packageAppRuntimeRunIdHeader, ), }) return attachPackageAppServerTiming(filtered.response, serverTiming) } catch (error) { console.error('Package realtime handler failed:', error) reportPackageAppFailure({ error, phase: 'realtime-connect', requestUrl, kodyId: savedPackage.kodyId, packageId: savedPackage.id, packageName: savedPackage.name, sourceId: savedPackage.sourceId, forwardedPath: forwardedPackageRestPath, realtimePath: packageRealtimeRestPath, }) return attachPackageAppServerTiming( createPackageAppErrorResponse({ request, kind: 'realtime-connect', kodyId: savedPackage.kodyId, packageName: savedPackage.name, synthetic: dispatch?.synthetic === true, cause: getErrorMessage(error), runtimeRunId: runtimeRunIdFromError(error), }), serverTiming, ) } } // Anonymous visitors run the commit its owner approved for them (ADR // 0069). A republish that asks for more is held, so that is the commit // members run too; the pin only covers a cached approval that trails a // serving advance. const anonymousCommit = visitor ? null : (input.approvedPublishedCommit ?? null) const loadSourceFiles = async () => { const packageSource = await loadServingPackageSourceBySourceId({ env, baseUrl, userId: owner.userId, sourceId: savedPackage.sourceId, commit: anonymousCommit, }) return packageSource.files } // Platform-served static surface (`/_assets/*`): the fingerprinted client // module and the declared assets directory never reach author code. const assetRelativePath = parsePackageAppAssetRequestPath( forwardedPackageRestPath, ) if (assetRelativePath !== null) { // Same mount rule as buildPackageAppPublicContext: the username lives in // the hostname on a per-user subdomain and in the path when inline. // URL path segment is the name leaf (Kent: slug = leaf), not kodyId — // those can diverge until Phase 2's single writer. const urlSlug = getPackageNameLeaf(savedPackage.name) const appBasePath = packageAppBasePath({ mount: packagePath.mount, username: packagePath.username, kodyId: urlSlug, }) try { const refusal = refuseUnapprovedAnonymousServe({ visitor, approvedPublishedCommit: anonymousCommit, }) if (refusal) return attachPackageAppServerTiming(refusal, serverTiming) const packageManifest = await pushServerTiming( serverTiming, 'manifest', () => loadInvokeManifestBySourceId({ env, userId: owner.userId, sourceId: savedPackage.sourceId, commit: anonymousCommit, ...(input.resolvedManifestSource && { resolvedSource: input.resolvedManifestSource, }), }), ) if (!getPackageAppEntryPath(packageManifest.manifest)) { return attachPackageAppServerTiming( new Response(buildPackageAppNotFoundMessage(), { status: 404 }), serverTiming, ) } return attachPackageAppServerTiming( await pushServerTiming(serverTiming, 'assets', () => servePackageAppAssetRequest({ request, env, userId: owner.userId, manifest: packageManifest.manifest, savedPackage: { id: savedPackage.id, kodyId: savedPackage.kodyId, sourceId: savedPackage.sourceId, publishedCommit: packageManifest.source.published_commit, manifestPath: packageManifest.source.manifest_path, sourceRoot: packageManifest.source.source_root, }, loadSourceFiles, publicHistoryOnly: anonymousCommit !== null, publicImmutableAssets: input.anonymousAssetRequest === true && !consentPerson && savedPackage.isInternetVisible && anonymousCommit !== null && packageManifest.source.published_commit === anonymousCommit, relativePath: assetRelativePath, appBasePath, hostedUrl: `${requestUrl.origin}${appBasePath}`, }), ), serverTiming, ) } catch (error) { const expected = resolveExpectedPackageAppHostSetupFailure({ request, error, kodyId: savedPackage.kodyId, packageName: savedPackage.name, synthetic: dispatch?.synthetic === true, }) if (expected) { return attachPackageAppServerTiming(expected, serverTiming) } console.error('Package app asset handler failed:', error) reportPackageAppFailure({ error, phase: 'host-setup', requestUrl, kodyId: savedPackage.kodyId, packageId: savedPackage.id, packageName: savedPackage.name, sourceId: savedPackage.sourceId, forwardedPath: forwardedPackageRestPath, realtimePath: packageRealtimeRestPath, }) return attachPackageAppServerTiming( createPackageAppErrorResponse({ request, kind: 'host-setup', kodyId: savedPackage.kodyId, packageName: savedPackage.name, synthetic: dispatch?.synthetic === true, cause: getErrorMessage(error), runtimeRunId: runtimeRunIdFromError(error), }), serverTiming, ) } } let forwardedRequest: Request let entrypoint: { fetch(request: Request): Promise } let servedPublishedCommit: string | null = null let servedRepoId: string | null = null let clientReadableCookieNames: ReadonlyArray = [] let appDescription: string | null = null let visitNonce: string | null = null try { // The supplier flag depends only on the owning org, so it runs beside // the manifest and billing reads instead of after them. const suppliersEnabledPending = pushServerTiming( serverTiming, 'credentialSuppliers', () => isPackageCredentialSuppliersEnabled({ db: env.APP_DB, orgId: owner.userId, request, }), ) // Settled below or abandoned on refusal; never an unhandled rejection. suppliersEnabledPending.catch(() => {}) const refusal = refuseUnapprovedAnonymousServe({ visitor, approvedPublishedCommit: anonymousCommit, }) if (refusal) return attachPackageAppServerTiming(refusal, serverTiming) const usageRead = anonymousCommit ? prefetchAnonymousPackageAppUsage(env, owner.userId) : undefined const buildRead = anonymousCommit ? prefetchPackageAppBuild({ env, baseUrl, userId: owner.userId, savedPackage, publishedCommit: anonymousCommit, runtime: { servingUsername: packagePath.username, hostedOrigin: requestUrl.origin, mount: packagePath.mount, }, }) : undefined const [packageManifest, callerContext] = await Promise.all([ pushServerTiming(serverTiming, 'manifest', () => loadInvokeManifestBySourceId({ env, userId: owner.userId, sourceId: savedPackage.sourceId, commit: anonymousCommit, ...(input.resolvedManifestSource && { resolvedSource: input.resolvedManifestSource, }), }), ), pushServerTiming(serverTiming, 'billing', () => resolvePackageAppBilling({ db: env.APP_DB, ownerId: owner.userId, visitor, internetVisible: savedPackage.isInternetVisible, }), ).then((billing) => createPackageAppCallerContext({ baseUrl, owner, visitor, packageId: savedPackage.id, billing, }), ), ]) if (!getPackageAppEntryPath(packageManifest.manifest)) { return attachPackageAppServerTiming( new Response(buildPackageAppNotFoundMessage(), { status: 404 }), serverTiming, ) } clientReadableCookieNames = getPackageAppClientReadableCookieNames( packageManifest.manifest, ) appDescription = packageManifest.manifest.kody.description const suppliersEnabled = await suppliersEnabledPending const visitorNeeds = suppliersEnabled ? savedCredentialNeeds( await pushServerTiming(serverTiming, 'credentialNeeds', () => loadPublishedCredentialNeeds({ env, userId: owner.userId, sourceId: savedPackage.sourceId, // Every visitor gets the needs of the commit they run. source: packageManifest.source, request: callerContext.request, }), ), ) : [] const executorNeeds = visitorNeeds.filter( (need) => need.supplier === 'executor', ) const requiredExecutorNeeds = executorNeeds.filter( (need) => need.required !== false, ) // A signed-in visitor from outside the org brings their own executor // credentials once they hold a live grant for this app. They get an // executor-only visit: nothing else treats them as a visitor. const executorGrant = !visitor && identity && executorNeeds.length > 0 ? await pushServerTiming(serverTiming, 'executorGrant', () => findLivePackageAppOauthGrant({ db: env.APP_DB, personId: identity.userId, orgUsername: packagePath.username.toLowerCase(), kodyId: savedPackage.kodyId, }), ) : null if (executorGrant) { await notePackageAppOauthGrantUse({ db: env.APP_DB, grant: executorGrant, }) } const executorVisit = identity && executorGrant ? { visitor: { userId: identity.userId, username: identity.username, role: null, }, grantId: executorGrant.id, scopes: executorGrant.scopes, } : null const needVisitor = visitor ?? executorVisit?.visitor ?? null const consentUrl = () => { const loginUrl = buildPackageAppLoginUrl({ requestUrl: request.url, appLeaf: getPackageNameLeaf(savedPackage.name), }) loginUrl.searchParams.set( 'scope', [ 'profile', // Optional needs ride along so consent can offer them; a key // that cannot be a scope is left out rather than failing it. ...executorNeeds.flatMap((item) => item.required !== false || packageAppVisitorNeedKeyPattern.test(item.key) ? [`need:${item.key}`] : [], ), ].join(' '), ) loginUrl.searchParams.set('prompt', 'consent') loginUrl.searchParams.set( 'return_to', `${requestUrl.pathname}${requestUrl.search}`, ) return loginUrl } const consentRedirect = () => attachPackageAppServerTiming( new Response(null, { status: 302, headers: { Location: consentUrl().toString(), 'Cache-Control': 'no-store', }, }), serverTiming, ) // An agent never approves a visitor need. It gets the link the person // opens once, on every method. const visitorConsentRequired = (needKey: string) => attachPackageAppServerTiming( Response.json( { error: 'app_visitor_consent_required', message: `This app needs the person to allow "${needKey}" before it can run for them.`, need: needKey, consent_url: consentUrl().toString(), }, { status: 403, headers: { 'Cache-Control': 'private, no-store', [packageAppVisitorConsentRequiredHeader]: 'required', }, }, ), serverTiming, ) const profileCredentialRequired = (needKey: string) => attachPackageAppServerTiming( Response.json( { error: 'app_profile_credential_required', message: `The person allowed "${needKey}" for this app, but the acting profile has no Use on the credential it maps to. Grant the profile Use on that credential (accessGrant on the credential), or call as the person.`, need: needKey, }, { status: 403, headers: { 'Cache-Control': 'private, no-store' } }, ), serverTiming, ) const openRequiredNeed = async ( need: (typeof requiredExecutorNeeds)[number], visitor: typeof needVisitor, ) => { await openCredentialClient( { env, callerContext, // Only checks the need can open; the handle is discarded. binding: newRunCredentialClientBinding(), packageId: savedPackage.id, runNeeds: async () => new Map(visitorNeeds.map((item) => [item.key, item])), packageAppAuthority: createPackageAppCredentialAuthority({ env, scope: { orgId: owner.userId, packageId: savedPackage.id, }, grantScope: { orgSlug: packagePath.username, kodyId: savedPackage.kodyId, }, visitorRequest: await createPackageAppVisitorPersonalRequest({ db: env.APP_DB, visitor, }), issue: { visitorNeed: need.key }, waitUntil: scheduleWorkerWaitUntil, }), }, { key: need.key }, ) } for (const need of requiredExecutorNeeds) { try { await openRequiredNeed(need, needVisitor) } catch (error) { if (!(error instanceof CredentialClientError)) throw error if (dispatch?.agent) { // When the need opens for the person alone, asking them again // cannot help: the acting profile is what lacks the credential. const profileActs = needVisitor && 'credential' in needVisitor && needVisitor.credential?.profileId const consented = profileActs && (await openRequiredNeed(need, { ...needVisitor, credential: null, }).then( () => true, (personError: unknown) => { if (personError instanceof CredentialClientError) return false throw personError }, )) return consented ? profileCredentialRequired(need.key) : visitorConsentRequired(need.key) } if (request.method !== 'GET' && request.method !== 'HEAD') { throw error } return consentRedirect() } } // Optional needs never block serving, so offer them once: a visitor with // no grant for this app yet goes to consent, and any grant (even one // that declined every optional need) serves the app after that. if ( consentPerson && // An agent cannot give consent, and an optional need never blocks. !dispatch?.agent && (request.method === 'GET' || request.method === 'HEAD') && executorNeeds.some((need) => need.required === false) && !executorGrant && !(await findLivePackageAppOauthGrant({ db: env.APP_DB, personId: consentPerson.userId, orgUsername: packagePath.username.toLowerCase(), kodyId: savedPackage.kodyId, })) ) { return consentRedirect() } if (dispatch?.preflight) { return attachPackageAppServerTiming( new Response(null, { status: 204, headers: { 'Cache-Control': 'private, no-store' }, }), serverTiming, ) } servedPublishedCommit = packageManifest.source.published_commit servedRepoId = packageManifest.source.repo_id const appWorker = await tracePackageAppPhase('kody.app.loader', () => buildPackageAppWorker({ env, baseUrl, userId: owner.userId, surface: 'app_fetch', savedPackage: { id: savedPackage.id, kodyId: savedPackage.kodyId, name: savedPackage.name, sourceId: savedPackage.sourceId, publishedCommit: packageManifest.source.published_commit, manifestPath: packageManifest.source.manifest_path, sourceRoot: packageManifest.source.source_root, }, source: packageManifest.source, manifest: packageManifest.manifest, loadSourceFiles, pinnedCommit: anonymousCommit, ...(usageRead && { usageRead }), ...(buildRead && { buildRead }), serverTiming, runtime: { callerContext, servingUsername: packagePath.username, hostedOrigin: requestUrl.origin, mount: packagePath.mount, executorVisit, }, }), ) entrypoint = appWorker.stub.getEntrypoint(appWorker.entrypointName) visitNonce = appWorker.visit.nonce const forwardedUrl = new URL(requestUrl) forwardedUrl.pathname = forwardedPackageRestPath forwardedRequest = applyTrustedPackageAppDispatch( withPackageAppVisitTicket( withPackageAppVisitorHeader( createPackageCodeRequest(request, forwardedUrl, { cookiePrefix }), { visitor, identity, scopes: appWorker.visit.claims?.scopes ?? ['profile'], }, ), appWorker.visit.ticket, ), dispatch, ) forwardedRequest = withForwardedPackageAppRequestId( forwardedRequest, packageAppRequestIdFromRequest(request), ) } catch (error) { endPackageAppVisit(visitNonce) const expected = resolveExpectedPackageAppHostSetupFailure({ request, error, kodyId: savedPackage.kodyId, packageName: savedPackage.name, synthetic: dispatch?.synthetic === true, }) if (expected) { return attachPackageAppServerTiming(expected, serverTiming) } console.error('Package app handler failed:', error) reportPackageAppFailure({ error, phase: 'host-setup', requestUrl, kodyId: savedPackage.kodyId, packageId: savedPackage.id, packageName: savedPackage.name, sourceId: savedPackage.sourceId, forwardedPath: forwardedPackageRestPath, realtimePath: packageRealtimeRestPath, }) return attachPackageAppServerTiming( createPackageAppErrorResponse({ request, kind: 'host-setup', kodyId: savedPackage.kodyId, packageName: savedPackage.name, synthetic: dispatch?.synthetic === true, cause: getErrorMessage(error), runtimeRunId: runtimeRunIdFromError(error), }), serverTiming, ) } const findUnpublishedChanges = () => resolveUnpublishedChanges({ env, request, visitor, synthetic: dispatch?.synthetic === true, repoId: servedRepoId, publishedCommit: servedPublishedCommit, username: packagePath.username, kodyId: savedPackage.kodyId, }) try { let fetched: Response try { const startedAt = Date.now() fetched = await pushServerTiming(serverTiming, 'entrypoint', () => tracePackageAppPhase('kody.app.dispatch', () => entrypoint.fetch(forwardedRequest), ), ) recordPackageAppDispatchTiming( serverTiming, fetched, startedAt, Date.now(), ) } catch (error) { if (request.method === 'OPTIONS') { return attachPackageAppServerTiming( unhandledPackageAppOptionsResponse(), serverTiming, visitNonce, ) } console.error('Package app entrypoint failed:', error) // The app worker failed before its own handler could record a run, so // record one here. Owners then see the failure in runList and Activity, // and the crash page shows its run id. const runtimeRunId = runtimeRunIdFromError(error) ?? (await recordPackageAppEntrypointFailure({ env, ownerId: owner.userId, savedPackage, publishedCommit: servedPublishedCommit, name: forwardedPackageRestPath, method: request.method, error, })) if (isKodyDevStack(env)) { return attachPackageAppServerTiming( createKodyDevErrorResponse(serializeKodyDevError(error)), serverTiming, visitNonce, ) } const unpublishedChanges = await findUnpublishedChanges() return attachPackageAppServerTiming( createPackageAppErrorResponse({ request, kind: unpublishedChanges ? 'publish-pending' : 'package-entrypoint', kodyId: savedPackage.kodyId, packageName: savedPackage.name, runtimeRunId, unpublishedChanges, }), serverTiming, visitNonce, ) } if (isPackageAppRuntimeThrownResponse(fetched)) { if (request.method === 'OPTIONS') { return attachPackageAppServerTiming( unhandledPackageAppOptionsResponse(), serverTiming, visitNonce, ) } if (isKodyDevStack(env)) { return attachPackageAppServerTiming( createKodyDevErrorResponse(await readKodyDevError(fetched)), serverTiming, visitNonce, ) } const unpublishedChanges = await findUnpublishedChanges() return attachPackageAppServerTiming( createPackageAppErrorResponse({ request, kind: unpublishedChanges ? 'publish-pending' : 'package-entrypoint', kodyId: savedPackage.kodyId, packageName: savedPackage.name, runtimeRunId: fetched.headers.get(packageAppRuntimeRunIdHeader), unpublishedChanges, }), serverTiming, visitNonce, ) } if (fetched.status >= 500) { const unpublishedChanges = await findUnpublishedChanges() if (unpublishedChanges) { await fetched.body?.cancel() return attachPackageAppServerTiming( createPackageAppErrorResponse({ request, kind: 'publish-pending', kodyId: savedPackage.kodyId, packageName: savedPackage.name, runtimeRunId: fetched.headers.get(packageAppRuntimeRunIdHeader), status: fetched.status, unpublishedChanges, }), serverTiming, visitNonce, ) } } // Leave x-kody-runtime-run-id on the response. The origin forward reads // it for the runtime-worker hop log, then strips it before the browser. logPackageAppHttpError({ request, status: fetched.status, phase: 'entrypoint-response', runtimeRunId: fetched.headers.get(packageAppRuntimeRunIdHeader), }) const requestUrl = new URL(request.url) const appName = getPackageNameLeaf(savedPackage.name) const served = await applyPackageAppDefaults({ request, response: fetched, appName, description: appDescription, appHomePath: `${packageAppBasePath({ mount: packagePath.mount, username: packagePath.username, kodyId: appName, })}/`, }) // One pass for cookie scrub/filter/HttpOnly, timing, and the visit // watch; inside the origin boundary it merges with cache headers and // the run-id strip. return deferPackageAppResponseRewrite(served, { domainScrub: { responseHostname: requestUrl.hostname, packageAppApexHostnames: listPackageAppOrigins({ env }).map( (origin) => origin.hostname, ), }, cookiePrefix, httpOnly: { clientReadable: clientReadableCookieNames }, serverTiming, visitNonce, onReport: [ (report) => { recordPackageAppServeCookieReport({ env, packageId: savedPackage.id, requestUrl, report, }) }, ], }) } catch (error) { endPackageAppVisit(visitNonce) throw error } } function recordPackageAppServeCookieReport(input: { env: Env packageId: string requestUrl: URL report: PackageAppResponseRewriteReport }) { const { env, packageId, requestUrl, report } = input if (report.findings.length > 0) { const warningWrite = recordPackageAppCookieFindings({ db: env.APP_DB, packageId, findings: report.findings, hostname: requestUrl.hostname, pathname: requestUrl.pathname, now: Date.now(), }).catch((error) => { console.warn('package-app-cookie-warning-record-failed', { packageId, error: getErrorMessage(error), }) }) try { scheduleWorkerWaitUntil(warningWrite) } catch { void warningWrite } } logPackageAppSetCookieNamesDropped({ hostname: requestUrl.hostname, pathname: requestUrl.pathname, dropped: report.dropped, surface: 'package-app-serve', }) logPackageAppSetCookieDomainStripped({ hostname: requestUrl.hostname, pathname: requestUrl.pathname, stripped: report.stripped, surface: 'package-app-serve', }) } export { isPackageAppSyntheticRequest }