/** * Who a package app acts as (ADRs 0068 and 0104). * * The app acts as its last publisher, through their derived profile. Nobody * picks someone else, and an app with no known publisher fails closed. The * cached resolver checks for a live account, an org role, and a ready * profile. Missing authority returns an owner-facing error. */ import { personIdFromStored, type OwnerId, type PersonId, } from '@kody-internal/shared/owner-person-ids.ts' import type { OrgRole, RequestContext, } from '@kody-internal/shared/request-context.ts' import type { RuntimePackageAppVisitor } from '@kody-internal/shared/runtime-worker.ts' import { findLivePackageAppOauthGrant, touchPackageAppOauthGrantLastUsed, } from '#app/package-app-oauth-grants.ts' import { packageAppVisitorNeedScope } from '#app/package-app-oauth-scopes.ts' import type { PackageAppCredentialAuthority } from '#worker/credentials/credential-client.ts' import { isPackageCredentialSuppliersEnabled } from '#worker/credentials/credential-suppliers-flag.ts' import { PromiseLruCache } from '#worker/package-registry/published-package-cache.ts' import { getSavedPackageById } from '#worker/package-registry/repo.ts' import { loadOrgBindingForOrg, loadOrgBindingForPerson, } from '#worker/orgs/repo.ts' import { deriveRequestContext } from '#worker/request-context/request-context.ts' import { loadPackageAppProfile } from './package-app-profile.ts' import { andLiveDeletedAtSql } from '#worker/soft-delete/live-sql.ts' export class PackageAppCapabilityNotDeclaredError extends Error { readonly capabilityName: string constructor(capabilityName: string) { super( `Package app capability "${capabilityName}" is not listed in kody.app.capabilities. Apps run as their publisher and may call only the Kody capabilities they declare.`, ) this.name = 'PackageAppCapabilityNotDeclaredError' this.capabilityName = capabilityName } } export class PackageAppCapabilityUnavailableError extends Error { constructor(capabilityName: string) { super(`Package app capability "${capabilityName}" is not available.`) this.name = 'PackageAppCapabilityUnavailableError' } } export type PackageAppAuthorityScope = { /** The org that owns the app. */ orgId: OwnerId /** The app package. */ packageId: string } /** Where the runs-as person came from. */ export type PackageAppRunsAsSource = 'publisher' export type PackageAppRunsAs = | { status: 'ready' personId: PersonId source: PackageAppRunsAsSource role: OrgRole email: string username: string displayName: string /** The runs-as person in the owning org, as a package-app credential. */ request: RequestContext } | { status: 'unavailable' reason: 'not-set' | 'person-unavailable' | 'profile-unavailable' message: string } export const packageAppRunsAsUnavailableMessages = { 'not-set': 'This app has no one to run as. An owner of its org must publish it again, as the person the app should act as.', 'person-unavailable': "This app's publisher can no longer act for its org. An owner of its org must publish it again, as the person the app should act as.", 'profile-unavailable': "This app's access was revoked or has not been set up. Its publisher must publish it again, as the person the app should act as.", 'lookup-failed': 'Kody could not check who this app runs as. Try again.', } as const export type PackageAppRunsAsUnavailableReason = keyof typeof packageAppRunsAsUnavailableMessages export class PackageAppRunsAsUnavailableError extends Error { readonly reason: PackageAppRunsAsUnavailableReason constructor( reason: PackageAppRunsAsUnavailableReason, options?: ErrorOptions, ) { super(packageAppRunsAsUnavailableMessages[reason], options) this.name = 'PackageAppRunsAsUnavailableError' this.reason = reason } } /** Answers with the visitor's identity, never the runs-as person's. */ export const packageAppIdentityCapabilityName = 'metaGetCurrentUser' /** `kody.visitorNeed({ need, args })`: a consented call on the visitor's data. */ export const packageAppVisitorNeedCallName = 'visitorNeed' /** * A visitor-data call without a live grant covering its need. Never retried * as the runs-as person: that would hand the publisher's data to an app that * asked for the visitor's. */ export class PackageAppVisitorConsentError extends Error { constructor(message: string) { super(message) this.name = 'PackageAppVisitorConsentError' } } /** * Seconds, not minutes: a removed or suspended runs-as person stops acting * for the app within this window. */ export const packageAppRunsAsCacheTtlMs = 5_000 const runsAsCache = new PromiseLruCache({ ttlMs: packageAppRunsAsCacheTtlMs, limit: 500, }) function cacheKey(scope: PackageAppAuthorityScope) { return JSON.stringify([scope.orgId, scope.packageId]) } export function forgetPackageAppRunsAs(scope: PackageAppAuthorityScope) { runsAsCache.delete(cacheKey(scope)) } export async function loadPackageAppRunsAs(input: { env: Pick scope: PackageAppAuthorityScope }): Promise { return await runsAsCache.getOrCreate({ cacheKey: cacheKey(input.scope), create: () => resolveRunsAs(input.env.APP_DB, input.scope), }) } async function resolvePublisher( db: D1Database, scope: PackageAppAuthorityScope, ): Promise { const row = await db .prepare( `SELECT published_by_person_id FROM package_app_authority WHERE package_id = ? AND owner_id = ?`, ) .bind(scope.packageId, scope.orgId) .first<{ published_by_person_id: string | null }>() return row?.published_by_person_id?.trim() || null } async function resolveRunsAs( db: D1Database, scope: PackageAppAuthorityScope, ): Promise { const publisher = await resolvePublisher(db, scope) if (!publisher) { return { status: 'unavailable', reason: 'not-set', message: packageAppRunsAsUnavailableMessages['not-set'], } } const person = await db .prepare( `SELECT stable_user_id, username, email, display_name FROM users WHERE stable_user_id = ? AND suspended_at IS NULL AND deleting_at IS NULL${andLiveDeletedAtSql()} LIMIT 1`, ) .bind(publisher) .first<{ stable_user_id: string username: string | null email: string | null display_name: string | null }>() const binding = person ? await loadOrgBindingForOrg(db, person.stable_user_id, scope.orgId) : null if (!person || !binding?.role) { return { status: 'unavailable', reason: 'person-unavailable', message: packageAppRunsAsUnavailableMessages['person-unavailable'], } } const personId = personIdFromStored(person.stable_user_id) const username = person.username ?? '' const profile = await loadPackageAppProfile({ db, orgId: scope.orgId, packageId: scope.packageId, publisherId: person.stable_user_id, }) if (profile.status !== 'ready') { return { status: 'unavailable', reason: 'profile-unavailable', message: packageAppRunsAsUnavailableMessages['profile-unavailable'], } } return { status: 'ready', personId, source: 'publisher', role: binding.role, email: person.email ?? '', username, displayName: person.display_name?.trim() || username, request: deriveRequestContext({ user: { userId: personId, username: username || undefined }, source: { kind: 'package-app' }, orgBinding: binding, profileId: profile.profileId, profileChain: profile.chain, profileOrgId: scope.orgId, }), } } /** Record who published the app. Publishing as someone else moves the app to them. */ export async function recordPackageAppPublisher(input: { db: D1Database scope: PackageAppAuthorityScope personId: string attempt?: { sourceId: string; attempt: number } now?: Date }): Promise { const personId = input.personId.trim() if (!personId) return false const insert = input.attempt ? `INSERT INTO package_app_authority (package_id, owner_id, published_by_person_id, updated_at) SELECT ?, ?, ?, ? WHERE EXISTS ( SELECT 1 FROM entity_sources WHERE id = ? AND publish_attempt_seq = ? )` : `INSERT INTO package_app_authority (package_id, owner_id, published_by_person_id, updated_at) VALUES (?, ?, ?, ?)` const result = await input.db .prepare( `${insert} ON CONFLICT(package_id) DO UPDATE SET owner_id = excluded.owner_id, published_by_person_id = excluded.published_by_person_id, publisher_unknown = 0, updated_at = excluded.updated_at`, ) .bind( input.scope.packageId, input.scope.orgId, personId, (input.now ?? new Date()).toISOString(), ...(input.attempt ? [input.attempt.sourceId, input.attempt.attempt] : []), ) .run() const changed = (result.meta.changes ?? 0) > 0 if (changed) forgetPackageAppRunsAs(input.scope) return changed } /** * Clear stale publisher attribution. The app then fails closed until a publish * by a known person records a publisher again. */ export async function recordPackageAppPublisherUnknown(input: { db: D1Database scope: PackageAppAuthorityScope attempt?: { sourceId: string; attempt: number } now?: Date }): Promise { const insert = input.attempt ? `INSERT INTO package_app_authority (package_id, owner_id, publisher_unknown, updated_at) SELECT ?, ?, 1, ? WHERE EXISTS ( SELECT 1 FROM entity_sources WHERE id = ? AND publish_attempt_seq = ? )` : `INSERT INTO package_app_authority (package_id, owner_id, publisher_unknown, updated_at) VALUES (?, ?, 1, ?)` const result = await input.db .prepare( `${insert} ON CONFLICT(package_id) DO UPDATE SET owner_id = excluded.owner_id, published_by_person_id = NULL, publisher_unknown = 1, updated_at = excluded.updated_at`, ) .bind( input.scope.packageId, input.scope.orgId, (input.now ?? new Date()).toISOString(), ...(input.attempt ? [input.attempt.sourceId, input.attempt.attempt] : []), ) .run() const changed = (result.meta.changes ?? 0) > 0 if (changed) forgetPackageAppRunsAs(input.scope) return changed } /** * Note who asked to publish a commit that will finish in the durable * workflow, or who pushed it over git (the five-minute reconcile publishes it * later). Nothing about the live app changes: the person becomes the * publisher only when that commit is published (`recordPackageAppPublish`). * The latest person to ask for a commit, or push it, replaces an earlier one, * so publishing the same commit again as someone else moves the app to them * (ADR 0104). Notes are kept * for a week, so a finish step that is retried still finds its requester. */ export async function notePackageAppPublishRequester(input: { db: D1Database scope: PackageAppAuthorityScope personId: string commit: string now?: Date }) { const now = input.now ?? new Date() await input.db.batch([ input.db .prepare( `DELETE FROM package_app_publish_requests WHERE package_id = ? AND created_at < ?`, ) .bind( input.scope.packageId, new Date(now.getTime() - publishRequestRetentionMs).toISOString(), ), input.db .prepare( `INSERT INTO package_app_publish_requests (package_id, commit_sha, owner_id, person_id, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(package_id, commit_sha) DO UPDATE SET person_id = excluded.person_id, created_at = excluded.created_at`, ) .bind( input.scope.packageId, input.commit, input.scope.orgId, input.personId, now.toISOString(), ), ]) } const publishRequestRetentionMs = 7 * 24 * 60 * 60 * 1000 async function loadPublishRequester( db: D1Database, scope: PackageAppAuthorityScope, commit: string, ) { const row = await db .prepare( `SELECT person_id FROM package_app_publish_requests WHERE package_id = ? AND commit_sha = ? AND owner_id = ?`, ) .bind(scope.packageId, commit, scope.orgId) .first<{ person_id: string | null }>() return row?.person_id?.trim() || null } /** * Record the person behind a publish (null: no known person). Call before the * new code serves. * * A publish that finishes in the durable workflow acts as the owning org, * which is not a person. The publisher is then whoever asked for that commit * (`notePackageAppPublishRequester`). Any other actor who is not a live member * of the owning org counts as no known person, so new code never keeps * running as the previous publisher. */ export async function recordPackageAppPublish(input: { db: D1Database scope: PackageAppAuthorityScope personId: string | null commit?: string | null }) { const personId = await resolvePackageAppPublishingPerson(input) if (personId === null) { await recordPackageAppPublisherUnknown({ db: input.db, scope: input.scope, }) return } await recordPackageAppPublisher({ db: input.db, scope: input.scope, personId, }) } /** * The person with a live binding to the owning org who asked for, or pushed, * this commit (`notePackageAppPublishRequester`), or null. A grant-only * collaborator counts, so their code is recorded as theirs and fails closed * instead of running as the org owner. */ export async function findPackageAppPublishRequester(input: { db: D1Database scope: PackageAppAuthorityScope commit: string }) { const requester = await loadPublishRequester( input.db, input.scope, input.commit, ) if (!requester) return null const binding = await loadOrgBindingForOrg( input.db, requester, input.scope.orgId, ) return binding ? requester : null } /** * Note who minted a write token for a package's git remote. Rows stay until a * reconcile publish settles, so a push held by a lock keeps its pusher. */ export async function notePackageGitWriteMinter(input: { db: D1Database scope: PackageAppAuthorityScope personId: string expiresAt: string }) { await input.db .prepare( `INSERT INTO package_git_write_minters (package_id, owner_id, person_id, expires_at) VALUES (?, ?, ?, ?) ON CONFLICT(package_id, person_id) DO UPDATE SET owner_id = excluded.owner_id, expires_at = MAX(expires_at, excluded.expires_at)`, ) .bind( input.scope.packageId, input.scope.orgId, input.personId, input.expiresAt, ) .run() } /** After a reconcile publish settles: expired tokens cannot push anything newer. */ export async function clearExpiredPackageGitWriteMinters(input: { db: D1Database scope: PackageAppAuthorityScope now?: Date }) { await input.db .prepare( `DELETE FROM package_git_write_minters WHERE package_id = ? AND expires_at < ?`, ) .bind(input.scope.packageId, (input.now ?? new Date()).toISOString()) .run() } /** * Who to publish a pushed HEAD as: whoever pushed that commit through the Kody * git remote, else the one person holding a write token minted since the last * settled publish (tokens push straight to Artifacts). With several holders, a * collaborator without an org role wins so their code fails closed; several * members are unknown. */ export async function findPackageAppPusher(input: { db: D1Database scope: PackageAppAuthorityScope commit: string }) { const pusher = await findPackageAppPublishRequester(input) if (pusher) return pusher const { results } = await input.db .prepare( `SELECT person_id FROM package_git_write_minters WHERE package_id = ? AND owner_id = ?`, ) .bind(input.scope.packageId, input.scope.orgId) .all<{ person_id: string }>() const bound = [] for (const { person_id } of results) { const binding = await loadOrgBindingForOrg( input.db, person_id, input.scope.orgId, ) if (binding) bound.push({ personId: person_id, role: binding.role }) } if (bound.length === 1) return bound[0]!.personId return bound.find((minter) => !minter.role)?.personId ?? null } export async function resolvePackageAppPublishingPerson(input: { db: D1Database scope: PackageAppAuthorityScope personId: string | null commit?: string | null }) { if (input.personId === null) return null const isMember = async (personId: string) => (await loadOrgBindingForOrg(input.db, personId, input.scope.orgId)) !== null if (await isMember(input.personId)) return input.personId if (!input.commit) return null return await findPackageAppPublishRequester({ db: input.db, scope: input.scope, commit: input.commit, }) } /** * False when publishing `commit` again must record a new publisher or * reconcile the app's profile: the person behind the publish is not the * recorded publisher, the app has no ready profile for them, or the grants * `commit` needs were never recorded. */ export async function packageAppProfileIsCurrent(input: { db: D1Database scope: PackageAppAuthorityScope personId: string | null commit: string }) { const publisherId = await resolvePackageAppPublishingPerson(input) if (!publisherId) return true const saved = await getSavedPackageById(input.db, { userId: input.scope.orgId, packageId: input.scope.packageId, }) if (!saved?.hasApp) return true // An unattributed publish forgets the publisher but leaves its profile. const recorded = await input.db .prepare( `SELECT published_by_person_id, profile_grants_commit FROM package_app_authority WHERE package_id = ? AND owner_id = ?`, ) .bind(input.scope.packageId, input.scope.orgId) .first<{ published_by_person_id: string | null profile_grants_commit: string | null }>() if (recorded?.published_by_person_id !== publisherId) return false // Grants this commit needs were never reconciled, such as a site role. if (recorded.profile_grants_commit !== input.commit) return false const profile = await loadPackageAppProfile({ db: input.db, orgId: input.scope.orgId, packageId: input.scope.packageId, publisherId, }) return profile.status === 'ready' } /** The Sign in with Kody grant a visitor gave this app, read live. */ export type PackageAppVisitorGrantScope = { /** The owning org's slug, as grants record it. */ orgSlug: string kodyId: string } /** * True while the visitor's live grant for this app covers `needKey`. A * revoke takes effect on the next call. Marks the grant used. */ export async function packageAppVisitorConsents(input: { db: D1Database visitorPersonId: string | null | undefined grantScope: PackageAppVisitorGrantScope | null | undefined needKey: string waitUntil?: (promise: Promise) => void }): Promise { const personId = input.visitorPersonId?.trim() const grantScope = input.grantScope if (!personId || !grantScope?.orgSlug || !grantScope.kodyId) return false const grant = await findLivePackageAppOauthGrant({ db: input.db, personId, orgUsername: grantScope.orgSlug.toLowerCase(), kodyId: grantScope.kodyId, }) if (!grant?.scopes.includes(packageAppVisitorNeedScope(input.needKey))) { return false } const touched = touchPackageAppOauthGrantLastUsed({ db: input.db, grantId: grant.id, }).catch((error: unknown) => { console.warn('package-app-grant-last-used-failed', error) }) if (input.waitUntil) input.waitUntil(touched) else await touched return true } /** * Who a package app's credential handles resolve as on each use: a `runsAs` * handle as the live runs-as person, a `visitorNeed` handle as the visitor * while their consent covers that need. */ export function createPackageAppCredentialAuthority(input: { env: Pick scope: PackageAppAuthorityScope grantScope: PackageAppVisitorGrantScope | null visitorRequest: RequestContext | null issue: PackageAppCredentialAuthority['issue'] waitUntil?: (promise: Promise) => void }): PackageAppCredentialAuthority { return { issue: input.issue, orgId: input.scope.orgId, runsAsRequest: async () => { const runsAs = await loadPackageAppRunsAs({ env: input.env, scope: input.scope, }) return runsAs.status === 'ready' ? runsAs.request : null }, visitorNeedRequest: async (needKey) => { const grant = await visitorNeedGrant(needKey) return grant?.request ?? null }, visitorNeedGrant: async (needKey) => await visitorNeedGrant(needKey), } async function visitorNeedGrant(needKey: string) { const visitor = input.visitorRequest if ( !visitor?.actor || !input.grantScope?.orgSlug || !input.grantScope.kodyId ) { return null } const grant = await findLivePackageAppOauthGrant({ db: input.env.APP_DB, personId: visitor.actor.userId, orgUsername: input.grantScope.orgSlug.toLowerCase(), kodyId: input.grantScope.kodyId, }) if (!grant?.scopes.includes(packageAppVisitorNeedScope(needKey))) { return null } const touched = touchPackageAppOauthGrantLastUsed({ db: input.env.APP_DB, grantId: grant.id, }).catch((error: unknown) => { console.warn('package-app-grant-last-used-failed', error) }) if (input.waitUntil) input.waitUntil(touched) else await touched return { request: visitor, grantId: grant.id } } } /** * The visitor's request in their own personal org, where the credentials they * supply live. It keeps what the visiting credential narrows them to: an agent * profile's chain and token scopes ride along from the visit, so a profile * reaches only the personal credentials every layer of its chain was granted * use on, whatever the person consented to in a browser. */ export async function createPackageAppVisitorPersonalRequest(input: { db: D1Database visitor: Pick< RuntimePackageAppVisitor, 'userId' | 'username' | 'credential' > | null }) { const visitor = input.visitor if (!visitor) return null const orgBinding = await loadOrgBindingForPerson(input.db, visitor.userId) const narrowing = visitor.credential ?? null return deriveRequestContext({ user: { userId: visitor.userId, username: visitor.username }, source: { kind: 'package-app' }, orgBinding, scopes: narrowing?.scopes ?? null, profileId: narrowing?.profileId ?? null, profileChain: narrowing?.profileChain ?? null, profileOrgId: narrowing?.profileOrgId ?? null, }) } export async function createPackageAppVisitorCredentialRequest(input: { db: D1Database orgId: OwnerId callerRequest: RequestContext | null visitor: Pick< RuntimePackageAppVisitor, 'userId' | 'username' | 'credential' > | null }) { const suppliersEnabled = await isPackageCredentialSuppliersEnabled({ db: input.db, orgId: input.orgId, request: input.callerRequest, }) if (!suppliersEnabled) return input.callerRequest return await createPackageAppVisitorPersonalRequest({ db: input.db, visitor: input.visitor, }) }