import type * as RepoModule from '#worker/package-registry/repo.ts' import type * as ComputePackageCapabilitySetModule from '#worker/package-capabilities/compute-package-capability-set.ts' import { DatabaseSync } from 'node:sqlite' import { consoleError } from '#worker/test-support/console-spies.ts' import { auditEventSummaries, logAuditEventSpy, } from '#worker/test-support/audit-log-spy.ts' import { ownerIdFromStored } from '@kody-internal/shared/owner-person-ids.ts' import type { RequestContext } from '@kody-internal/shared/request-context.ts' import { expect, test, vi } from 'vitest' import { z } from 'zod' import type { SurfacePermission } from '#worker/authorization/authorize.ts' import { isMcpCallerError } from '#worker/mcp/caller-error.ts' import { assertTriggeredRunCanAccessSiteCapability } from '#worker/mcp/capabilities/triggered-site-access.ts' import { defineCapability } from '#worker/mcp/capabilities/define-capability.ts' import { createMcpCallerContext } from '#mcp/context.ts' import type { McpCallerContext } from '@kody-internal/shared/chat.ts' import { provisionPersonalOrg } from '#worker/orgs/provision.ts' import type { AuthoredPackageJson } from '#worker/package-registry/types.ts' import { grantPackageToProfile, listPackageProfileGrants, } from '#worker/profiles/package-grants.ts' import { getProfile, type ProfilesCaller } from '#worker/profiles/service.ts' import { loadProfileGrants, revokeProfileRow } from '#worker/profiles/store.ts' import { applyAllMigrations } from '#worker/test-support/apply-all-migrations.ts' import { createD1FromSqlite } from '#worker/test-support/create-d1-from-sqlite.ts' import { forgetPackageAppRunsAs, loadPackageAppRunsAs, packageAppProfileIsCurrent, packageAppRunsAsUnavailableMessages, recordPackageAppPublisher, recordPackageAppPublisherUnknown, } from './package-app-authority.ts' import { ensurePackageAppProfile, loadPackageAppProfileGrantNeeds, loadPackageAppProfileSiteRoleNeed, loadPublisherAccess, packageAppProfileNeeds, PackageAppProfileGrantsMissingError, recordPackageAppProfileGrantNeeds, replacePackageAppProfileGrants, resolvePackageAppProfileNeeds, } from './package-app-profile.ts' import { applyApprovedPackageAppProfileGrants, scanPackageAppForProfile, } from './package-app-profile-publish.ts' const savedApp = vi.hoisted(() => ({ hasApp: false, isInternetVisible: false })) const capabilitySet = vi.hoisted(() => ({ entries: [] as Array })) vi.mock('#worker/package-registry/repo.ts', async (importOriginal) => { const actual = await importOriginal() return { ...actual, getSavedPackageById: async ( ...args: Parameters ) => savedApp.hasApp ? { hasApp: true, isInternetVisible: savedApp.isInternetVisible } : await actual.getSavedPackageById(...args), } }) // The capability set is computed from stored sources this test does not seed. vi.mock( '#worker/package-capabilities/compute-package-capability-set.ts', async (importOriginal) => ({ ...(await importOriginal()), computePackageCapabilitySet: async () => ({ capabilitySet: { entries: capabilitySet.entries }, dependencySnapshot: { dependencies: [] }, }), }), ) vi.mock( '#worker/test-support/apply-all-migrations.ts', async (importOriginal) => ( await import('#worker/credentials/cached-migrations.test-support.ts') ).withCachedMigrations(await importOriginal()), ) const now = '2026-11-28T08:00:00.000Z' async function setup() { savedApp.hasApp = false savedApp.isInternetVisible = false capabilitySet.entries = [] const sqlite = new DatabaseSync(':memory:') applyAllMigrations(sqlite, new URL('../../migrations/', import.meta.url)) const db = createD1FromSqlite(sqlite) const env = { APP_DB: db } as Env let nextId = 1 async function seedUser(username: string) { const stableUserId = `user-${username}-${crypto.randomUUID()}` sqlite .prepare( `INSERT INTO users (id, username, email, stable_user_id, password_hash, email_verified_at) VALUES (?, ?, ?, ?, 'unused', ?)`, ) .run(nextId++, username, `${username}@example.com`, stableUserId, now) await provisionPersonalOrg(db, { stableUserId, username }) return stableUserId } const owner = await seedUser('owner') const member = await seedUser('member') const orgId = ownerIdFromStored(`org-${crypto.randomUUID()}`) sqlite .prepare( `INSERT INTO orgs (id, slug, plan, created_at, updated_at) VALUES (?, 'acme', 'pro', ?, ?)`, ) .run(orgId, now, now) for (const [userId, role] of [ [owner, 'owner'], [member, 'member'], ] as const) { sqlite .prepare( `INSERT INTO org_memberships (org_id, user_id, role, created_at) VALUES (?, ?, ?, ?)`, ) .run(orgId, userId, role, now) } const scope = { orgId, packageId: `pkg-${crypto.randomUUID()}` } async function runsAs() { forgetPackageAppRunsAs(scope) return await loadPackageAppRunsAs({ env, scope }) } async function publishAs(personId: string) { await recordPackageAppPublisher({ db, scope, personId }) return await ensurePackageAppProfile({ db, orgId, packageId: scope.packageId, publisherId: personId, now: new Date().toISOString(), }) } return { sqlite, db, env, owner, member, orgId, scope, runsAs, publishAs } } function appManifest(capabilities: Array) { return { name: '@acme/board', kody: { description: 'Board.', app: { entry: 'src/index.ts', capabilities }, }, } as unknown as AuthoredPackageJson } const noPackages = async () => null test('a clean scan names the declared capabilities the app calls', async () => { expect( await scanPackageAppForProfile({ manifest: appManifest(['secretList', 'packageList']), sourceFiles: { 'src/index.ts': "import { kody } from 'kody:runtime'\nexport default async () => { await kody.secretList({}); await kody.metaGetCurrentUser({}) }\n", }, appPackageId: 'pkg-1', loadPackage: noPackages, }), ).toEqual({ status: 'clean', capabilities: ['secretList'] }) }) test('literal kody.mcp server tool calls are declared names and keep the scan clean', async () => { const manifest = appManifest([ 'mcp:obsidian:list_notes', 'mcp:obsidian:get_note', ]) const scan = async (source: string) => await scanPackageAppForProfile({ manifest, sourceFiles: { 'src/index.ts': `import { kody } from 'kody:runtime'\n${source}\n`, }, appPackageId: 'pkg-1', loadPackage: noPackages, }) expect( await scan( "export default async () => { await kody.mcp.obsidian.list_notes({}); await kody.mcp['obsidian']?.['get_note']({ path: 'a.md' }) }", ), ).toEqual({ status: 'clean', capabilities: ['mcp:obsidian:get_note', 'mcp:obsidian:list_notes'], }) expect( await scan( 'export default async (server) => await kody.mcp[server].list_notes({})', ), ).toMatchObject({ status: 'uncertain' }) expect( await scan( 'const mcp = kody.mcp\nexport default async () => await mcp.obsidian.list_notes({})', ), ).toMatchObject({ status: 'uncertain' }) }) test('runtime host functions need no declaration and keep the scan clean', async () => { expect( await scanPackageAppForProfile({ manifest: appManifest(['secretList']), sourceFiles: { 'src/index.ts': "import { kody } from 'kody:runtime'\nexport default async () => { await kody.appPublisherGet(); await kody.appSpendGet(); await kody.appRateLimit({ key: 'k' }); await kody.secretList({}) }\n", }, appPackageId: 'pkg-1', loadPackage: noPackages, }), ).toEqual({ status: 'clean', capabilities: ['secretList'] }) }) test('a name picked at run time or an undeclared call makes the scan uncertain', async () => { const computed = await scanPackageAppForProfile({ manifest: appManifest(['secretList']), sourceFiles: { 'src/index.ts': "import { kody } from 'kody:runtime'\nexport default async (name) => kody[name]({})\n", }, appPackageId: 'pkg-1', loadPackage: noPackages, }) expect(computed.status).toBe('uncertain') const undeclared = await scanPackageAppForProfile({ manifest: appManifest([]), sourceFiles: { 'src/index.ts': "import { kody } from 'kody:runtime'\nexport default async () => kody.secretList({})\n", }, appPackageId: 'pkg-1', loadPackage: noPackages, }) expect(undeclared).toMatchObject({ status: 'uncertain' }) if (undeclared.status !== 'uncertain') throw new Error('expected uncertain') expect(undeclared.reasons.join('\n')).toContain('`secretList`') }) test('the app acts as its publisher profile', async () => { const t = await setup() const { profileId } = await t.publishAs(t.member) const runsAs = await t.runsAs() expect(runsAs).toMatchObject({ status: 'ready', personId: t.member, source: 'publisher', }) if (runsAs.status !== 'ready') throw new Error('expected ready') expect(runsAs.request.credential.profileId).toBe(profileId) expect(runsAs.request.credential.profileChain).toEqual([profileId]) }) test('no profile, or a revoked one, fails closed instead of running as the publisher', async () => { const t = await setup() await recordPackageAppPublisher({ db: t.db, scope: t.scope, personId: t.member, }) const unavailable = { status: 'unavailable', reason: 'profile-unavailable', message: packageAppRunsAsUnavailableMessages['profile-unavailable'], } expect(await t.runsAs()).toEqual(unavailable) const { profileId } = await t.publishAs(t.member) expect(await t.runsAs()).toMatchObject({ status: 'ready' }) await revokeProfileRow(t.db, { orgId: t.orgId, profileId, revokedByUserId: t.owner, now: new Date().toISOString(), }) expect(await t.runsAs()).toEqual(unavailable) }) test('publishing the live commit again reconciles once an unattributed publish forgot the publisher', async () => { const t = await setup() savedApp.hasApp = true await t.publishAs(t.owner) const input = { db: t.db, scope: t.scope, personId: t.owner, commit: 'commit-1', } // Grants never recorded for this commit, such as before a site role existed. expect(await packageAppProfileIsCurrent(input)).toBe(false) await recordPackageAppProfileGrantNeeds({ db: t.db, orgId: t.orgId, packageId: t.scope.packageId, commit: 'commit-1', grants: [], siteRole: null, }) expect(await packageAppProfileIsCurrent(input)).toBe(true) await recordPackageAppPublisherUnknown({ db: t.db, scope: t.scope }) expect(await packageAppProfileIsCurrent(input)).toBe(false) }) test('with no known publisher a team app fails closed', async () => { const t = await setup() expect(await t.runsAs()).toMatchObject({ status: 'unavailable', reason: 'not-set', }) }) test('a profile in another org fails closed', async () => { const t = await setup() const { profileId } = await t.publishAs(t.member) t.sqlite .prepare(`UPDATE profiles SET org_id = 'org-elsewhere' WHERE id = ?`) .run(profileId) expect(await t.runsAs()).toMatchObject({ status: 'unavailable', reason: 'profile-unavailable', }) }) test('a new publisher gets a new profile and the old one is revoked', async () => { const t = await setup() const first = await t.publishAs(t.member) const again = await t.publishAs(t.member) expect(again).toEqual({ profileId: first.profileId, created: false }) const second = await t.publishAs(t.owner) expect(second.created).toBe(true) expect(second.profileId).not.toBe(first.profileId) const old = t.sqlite .prepare(`SELECT revoked_at FROM profiles WHERE id = ?`) .get(first.profileId) as { revoked_at: string | null } expect(old.revoked_at).not.toBeNull() expect(await t.runsAs()).toMatchObject({ status: 'ready', personId: t.owner }) }) test('the app profile is hidden from profile surfaces', async () => { const t = await setup() const { profileId } = await t.publishAs(t.owner) const caller = { env: t.env, orgId: t.orgId, actor: { userId: t.owner, profileId: null, isOwner: true }, holds: () => true, } as unknown as ProfilesCaller await expect(getProfile(caller, profileId)).rejects.toMatchObject({ status: 404, }) const request = { org: { id: t.orgId }, actor: { userId: t.owner }, credential: { profileId: null }, } as unknown as RequestContext await expect( grantPackageToProfile({ env: t.env, request, packageId: t.scope.packageId, profileId, preset: 'read', }), ).rejects.toThrow('No profile with that id in this organization.') await replacePackageAppProfileGrants({ db: t.db, orgId: t.orgId, profileId, publisherId: t.owner, grants: [ { resourceType: 'package', resourceId: t.scope.packageId, permissions: ['package:read'], }, ], now: new Date().toISOString(), }) expect( await listPackageProfileGrants({ db: t.db, orgId: t.orgId, packageId: t.scope.packageId, }), ).toEqual([]) }) test('grants come only from what the publisher holds live, and a gap names what is missing', async () => { const t = await setup() const memberAccess = await loadPublisherAccess({ env: t.env, orgId: t.orgId, publisherId: t.member, }) if (!memberAccess) throw new Error('expected access') const surfaces: Record = { readThing: 'org:read', readAudit: 'audit:read', editMembers: 'member:write', } const needs = packageAppProfileNeeds({ orgId: t.orgId, packageId: t.scope.packageId, capabilities: Object.keys(surfaces), surfacePermissionOf: (name) => surfaces[name] ?? null, capabilityEntries: [], importedPackages: [], }) const resolved = resolvePackageAppProfileNeeds({ needs, publisherAccess: memberAccess, }) expect(resolved.grants).toEqual([ { resourceType: 'org', resourceId: t.orgId, permissions: ['org:read'] }, ]) expect(resolved.missing).toEqual([ { label: '`readAudit`', permission: 'audit:read' }, ]) expect(resolved.ungranted).toEqual(['`editMembers`']) const missingError = new PackageAppProfileGrantsMissingError({ missing: resolved.missing, }) expect(missingError.message).toContain('audit:read for `readAudit`') // Callers can fix it from the message, so APIs answer 400 with it. expect(isMcpCallerError(missingError)).toBe(true) }) test('a concrete grant covers a capability surface check, so no org grant is added', async () => { const t = await setup() const ownerAccess = await loadPublisherAccess({ env: t.env, orgId: t.orgId, publisherId: t.owner, }) if (!ownerAccess) throw new Error('expected access') const resolved = resolvePackageAppProfileNeeds({ publisherAccess: ownerAccess, needs: packageAppProfileNeeds({ orgId: t.orgId, packageId: t.scope.packageId, capabilities: ['useSecret'], surfacePermissionOf: () => 'secret:use', capabilityEntries: [ { kind: 'credential', credentialId: 'cred_1', credentialKind: 'secret', hosts: [], via: [], }, ], importedPackages: [], }), }) expect(resolved).toEqual({ grants: [ { resourceType: 'credential', resourceId: 'cred_1', permissions: ['secret:use'], }, ], missing: [], ungranted: [], }) }) test('republishing replaces the grant set and reports only what it added', async () => { const t = await setup() const { profileId } = await t.publishAs(t.owner) const write = async (permissions: Array<'org:read' | 'search:read'>) => await replacePackageAppProfileGrants({ db: t.db, orgId: t.orgId, profileId, publisherId: t.owner, grants: [{ resourceType: 'org', resourceId: t.orgId, permissions }], now: new Date().toISOString(), }) expect(await write(['org:read'])).toHaveLength(1) expect(await write(['org:read', 'search:read'])).toEqual([ { resourceType: 'org', resourceId: t.orgId, permissions: ['search:read'], }, ]) const grants = await loadProfileGrants(t.db, { orgId: t.orgId, profileIds: [profileId], }) expect( grants .get(profileId) ?.flatMap((grant) => grant.permissions) .sort(), ).toEqual(['org:read', 'search:read']) }) test('grant needs are kept per commit for the approved fingerprint', async () => { const t = await setup() await t.publishAs(t.owner) const grants = [ { resourceType: 'org' as const, resourceId: t.orgId, permissions: ['org:read' as const], }, ] await recordPackageAppProfileGrantNeeds({ db: t.db, orgId: t.orgId, packageId: t.scope.packageId, commit: 'commit-1', grants, siteRole: null, }) const load = (commit: string) => loadPackageAppProfileGrantNeeds({ db: t.db, orgId: t.orgId, packageId: t.scope.packageId, commit, }) expect(await load('commit-1')).toEqual(grants) // A newer commit has no needs until its publish records them. expect(await load('commit-2')).toBeNull() }) test('persisted app authority restores old credential permissions', async () => { const t = await setup() await t.publishAs(t.owner) t.sqlite .prepare( 'UPDATE package_app_authority SET profile_grants_commit = ?, profile_grants_json = ? WHERE package_id = ?', ) .run( 'compat', JSON.stringify([ { resourceType: 'credential', resourceId: 'secret', permissions: ['secret:read', 'secret:view'], }, { resourceType: 'credential', resourceId: 'integration', permissions: ['integration:view', 'integration:read'], }, ]), t.scope.packageId, ) expect( await loadPackageAppProfileGrantNeeds({ db: t.db, orgId: t.orgId, packageId: t.scope.packageId, commit: 'compat', }), ).toEqual([ { resourceType: 'credential', resourceId: 'secret', permissions: ['secret:read_local'], }, { resourceType: 'credential', resourceId: 'integration', permissions: ['integration:read'], }, ]) }) test('an approval applies only grants the publisher still holds live', async () => { // This test env has no audit binding; the audit write is best effort. consoleError.mockImplementation(() => {}) const t = await setup() const { profileId } = await t.publishAs(t.owner) const approve = async ( permissions: Array<'org:read' | 'audit:read'>, approvedByUserId = t.owner, ) => { await recordPackageAppProfileGrantNeeds({ db: t.db, orgId: t.orgId, packageId: t.scope.packageId, commit: 'commit-1', grants: [{ resourceType: 'org', resourceId: t.orgId, permissions }], siteRole: null, }) return await applyApprovedPackageAppProfileGrants({ env: t.env, orgId: t.orgId, packageId: t.scope.packageId, commit: 'commit-1', approvedByUserId, }) } expect(await approve(['org:read'])).toEqual({ status: 'granted', added: 1 }) expect(consoleError).toHaveBeenCalledWith( 'package-app-profile-audit-failed', expect.any(Error), ) const grants = await loadProfileGrants(t.db, { orgId: t.orgId, profileIds: [profileId], }) expect(grants.get(profileId)?.flatMap((grant) => grant.permissions)).toEqual([ 'org:read', ]) // An approver who lacks the access cannot hand it to the app. expect(await approve(['org:read', 'audit:read'], t.member)).toMatchObject({ status: 'missing', missing: [ expect.objectContaining({ permission: 'audit:read', label: expect.stringContaining('approver: '), }), ], }) await t.publishAs(t.member) expect(await approve(['org:read', 'audit:read'])).toMatchObject({ status: 'missing', missing: [expect.objectContaining({ permission: 'audit:read' })], }) }) test('a site role needs the publisher and approver to hold it live', async () => { consoleError.mockImplementation(() => {}) const t = await setup() const { profileId } = await t.publishAs(t.owner) const approve = async (approvedByUserId = t.owner) => { await recordPackageAppProfileGrantNeeds({ db: t.db, orgId: t.orgId, packageId: t.scope.packageId, commit: 'commit-1', grants: [], siteRole: 'admin', }) return await applyApprovedPackageAppProfileGrants({ env: t.env, orgId: t.orgId, packageId: t.scope.packageId, commit: 'commit-1', approvedByUserId, }) } const siteRoleOf = () => t.sqlite .prepare('SELECT site_role FROM profiles WHERE id = ?') .get(profileId) as { site_role: string | null } expect(await approve()).toMatchObject({ status: 'missing', missing: [ { permission: 'admin site role', label: 'this site' }, { permission: 'admin site role', label: 'approver: this site' }, ], }) expect(siteRoleOf().site_role).toBeNull() // Owner (users.id 1) becomes a site admin (roles.id 2). t.sqlite.exec('INSERT INTO user_roles (user_id, role_id) VALUES (1, 2)') expect(await approve()).toMatchObject({ status: 'granted' }) expect(siteRoleOf().site_role).toBe('admin') expect( await loadPackageAppProfileSiteRoleNeed({ db: t.db, orgId: t.orgId, packageId: t.scope.packageId, commit: 'commit-2', }), ).toBeNull() }) test('a site-admin call needs the profile site role and the live role', async () => { consoleError.mockImplementation(() => {}) const t = await setup() const { profileId } = await t.publishAs(t.owner) const runsAs = await t.runsAs() if (runsAs.status !== 'ready') throw new Error('expected ready') let orgId: string = t.orgId const call = () => assertTriggeredRunCanAccessSiteCapability({ env: t.env, callerContext: { request: runsAs.request, profileId, user: { userId: runsAs.personId }, orgBinding: { org: { id: orgId, slug: 'acme' }, role: 'owner' }, } as unknown as McpCallerContext, capability: { name: 'admin_list_users', requiredRole: 'admin' }, trigger: { type: 'package-app', credentialId: null }, }) const setSiteRole = (siteRole: string | null) => t.sqlite .prepare('UPDATE profiles SET site_role = ? WHERE id = ?') .run(siteRole, profileId) // A profile from another org does not count. orgId = ownerIdFromStored('org-other') setSiteRole('admin') t.sqlite.exec('INSERT INTO user_roles (user_id, role_id) VALUES (1, 2)') await expect(call()).rejects.toThrow(/was not granted/) orgId = t.orgId setSiteRole(null) t.sqlite.exec('DELETE FROM user_roles WHERE user_id = 1 AND role_id = 2') // The publisher holds the role, but the profile has no site-role grant. t.sqlite.exec('INSERT INTO user_roles (user_id, role_id) VALUES (1, 2)') await expect(call()).rejects.toThrow(/was not granted the "admin" site role/) setSiteRole('admin') await expect(call()).resolves.toBeUndefined() // Losing the live role denies the next call. t.sqlite.exec('DELETE FROM user_roles WHERE user_id = 1 AND role_id = 2') await expect(call()).rejects.toThrow(/lacks required role "admin"/) t.sqlite.exec('INSERT INTO user_roles (user_id, role_id) VALUES (1, 2)') t.sqlite .prepare('UPDATE profiles SET revoked_at = ? WHERE id = ?') .run(now, profileId) await expect(call()).rejects.toThrow(/was not granted/) }) test('an app calls a declared site-admin capability while its publisher is a site admin', async () => { consoleError.mockImplementation(() => {}) const t = await setup() const { profileId } = await t.publishAs(t.owner) const runsAs = await t.runsAs() if (runsAs.status !== 'ready') throw new Error('expected ready') t.sqlite .prepare('UPDATE profiles SET site_role = ? WHERE id = ?') .run('admin', profileId) const adminOnly = defineCapability({ name: 'adminExampleList', domain: 'meta', description: 'Site-admin capability for package-app tests.', keywords: [], readOnly: true, idempotent: true, destructive: false, orgPermission: 'none', contextRuns: 'deny', requiredRole: 'admin', inputSchema: z.object({}), async handler() { return { ok: true } }, }) // The same caller the package-app bridge builds: no site roles on it. const callerContext = createMcpCallerContext({ baseUrl: 'https://example.com', executionOrigin: 'background', user: { userId: runsAs.personId, email: runsAs.email, username: runsAs.username, displayName: runsAs.displayName, }, orgBinding: { org: { id: t.orgId, slug: runsAs.request.org.slug }, role: runsAs.role, }, source: { kind: 'package-app' }, profileId: runsAs.request.credential.profileId ?? null, profileChain: runsAs.request.credential.profileChain ?? null, profileOrgId: runsAs.request.credential.profileOrgId ?? null, }) const call = () => adminOnly.handler({}, { env: t.env, callerContext }) // Not a site admin: fails closed. await expect(call()).rejects.toThrow(/lacks required role "admin"/) // Owner (users.id 1) becomes a site admin (roles.id 2). t.sqlite.exec('INSERT INTO user_roles (user_id, role_id) VALUES (1, 2)') await expect(call()).resolves.toEqual({ ok: true }) expect(logAuditEventSpy.mock.calls.at(-1)?.[0]).toMatchObject({ category: 'admin', action: 'adminExampleList', result: 'success', reason: expect.stringContaining('trigger=package-app'), }) // Losing the role denies the next call. t.sqlite.exec('DELETE FROM user_roles WHERE user_id = 1 AND role_id = 2') await expect(call()).rejects.toThrow(/lacks required role "admin"/) expect(auditEventSummaries()).toEqual([ 'mcp_capability_denied:failure', 'adminExampleList:success', 'mcp_capability_denied:failure', ]) }) test('a new publisher of an approved public commit keeps only what was approved', async () => { consoleError.mockImplementation(() => {}) const t = await setup() savedApp.hasApp = true savedApp.isInternetVisible = true await t.publishAs(t.owner) // Both people are site admins (users.id 1 and 2, roles.id 2). t.sqlite.exec( 'INSERT INTO user_roles (user_id, role_id) VALUES (1, 2), (2, 2)', ) const { reconcilePackageAppProfile } = await import('./package-app-profile-publish.ts') const { insertPackageCapabilityApproval } = await import('#worker/package-capabilities/capability-approvals-repo.ts') // The member publishes; the publish records them only after this runs. const republish = async (commit: string) => await reconcilePackageAppProfile({ env: t.env, source: { id: 'source-1', user_id: t.orgId, entity_id: t.scope.packageId, manifest_path: 'package.json', source_root: '', }, publishedCommit: commit, publisherId: t.member, files: { 'package.json': JSON.stringify(appManifest(['communitySetFeatured'])), 'src/index.ts': 'export default {}', }, baseUrl: 'https://example.com', }) // The saved package is mocked, so skip its foreign key. t.sqlite.exec('PRAGMA foreign_keys = OFF') const approve = async (id: string, approvedAt: string, entries: unknown) => await insertPackageCapabilityApproval(t.db, { id, package_id: t.scope.packageId, owner_user_id: t.orgId, published_commit: 'commit-1', fingerprint: id, capability_set_json: JSON.stringify(entries), dependency_snapshot_json: '[]', approved_by_user_id: t.owner, approved_at: approvedAt, }) // An approval from before the site role was part of the set grants nothing. await approve('approval-1', now, []) expect(await republish('commit-1')).toMatchObject({ status: 'needs-approval', }) await approve('approval-2', '2026-11-28T09:00:00.000Z', [ { kind: 'profile-grant', hosts: [], via: ['site'], profileGrant: { resourceType: 'site_role', resourceId: 'admin', permissions: ['admin'], }, }, ]) expect(await republish('commit-1')).toMatchObject({ status: 'granted' }) // A commit nobody approved still waits for an owner. expect(await republish('commit-2')).toMatchObject({ status: 'needs-approval', }) }) test('publishing a private app that calls a bound MCP server grants its connection', async () => { const t = await setup() // This test env has no audit database. consoleError.mockImplementation(() => {}) savedApp.hasApp = true const serverId = `mcp_${crypto.randomUUID()}` capabilitySet.entries = [ { kind: 'credential', credentialId: serverId, name: 'obsidian', source: 'need', needKey: 'obsidian', credentialKind: 'mcp', hosts: [], placement: null, via: [], }, ] await recordPackageAppPublisher({ db: t.db, scope: t.scope, personId: t.owner, }) const { reconcilePackageAppProfile } = await import('./package-app-profile-publish.ts') expect( await reconcilePackageAppProfile({ env: t.env, source: { id: 'source-1', user_id: t.orgId, entity_id: t.scope.packageId, manifest_path: 'package.json', source_root: '', }, publishedCommit: 'commit-1', publisherId: t.owner, files: { 'package.json': JSON.stringify( appManifest(['mcp:obsidian:get_note', 'mcp:obsidian:list_notes']), ), 'src/index.ts': "import { kody } from 'kody:runtime'\nexport default async () => [await kody.mcp.obsidian.list_notes({}), await kody.mcp.obsidian.get_note({ path: 'a.md' })]\n", }, baseUrl: 'https://example.com', } as never), ).toMatchObject({ status: 'granted', added: 1 }) const runsAs = await t.runsAs() if (runsAs.status !== 'ready') throw new Error('expected a ready profile') const { authorize } = await import('#worker/authorization/authorize.ts') const { credentialResource } = await import('#worker/credentials/credential-ids.ts') await expect( authorize( { env: t.env, request: runsAs.request }, 'integration:use', credentialResource(t.orgId, { id: serverId, name: 'obsidian' }), ), ).resolves.toBeUndefined() })