feat: hideable company settings pages, with import floored on cloud-managed instances (#12199)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The app can run self-hosted or as a cloud-managed instance, where a
hosting platform provisions the instance with its company already
materialized (the existing `isCloudManagedInstance()` predicate and
`cloud_managed` floors)
> - The company Import/Export surface lets an operator materialize whole
companies from an export bundle; on a cloud-managed instance this
bypasses the existing `cloud_managed` company-creation floor and
conflicts with platform-owned provisioning
> - Importing should be disabled on cloud-managed instances, while
export stays open as the data-portability escape hatch
> - This pull request floors every import route with 403
`code=cloud_managed` on cloud-managed instances and hides the Import UI
there, using the existing predicate and the established floor pattern
> - It also extends the operator-hidden settings registry with keys for
every top-level company settings page, so a hosting operator can hide
any of them with `PAPERCLIP_HIDDEN_SETTINGS` alone next time
> - The benefit is one consistent managed-instance policy: cloud-managed
instances cannot import companies, self-hosted installs keep the full
import surface unchanged

## Linked Issues or Issue Description

No public issue exists; the underlying problem follows the enhancement
template.

**What existing behavior does this improve?**

The company import surface (`/api/companies/import*`,
`/api/companies/:companyId/imports/*`) and its UI entry points on
cloud-managed instances.

**Subsystem affected**

Server routes (`server/src/routes/companies.ts`) and UI navigation/pages
(settings sidebar, settings tabs, org chart, `/company/import` route).

**Current behavior**

A cloud-managed instance floors direct company creation (`POST
/api/companies` answers 403 `cloud_managed`), but the import routes
still accept company bundles, so an import can materialize companies the
hosting platform did not provision. The UI offers Import entry points
that lead to a surface that is not available on cloud-managed instances.

**Proposed behavior**

On instances where `isCloudManagedInstance()` is true, every import
route answers 403 `code=cloud_managed` before auth and body work, and
the Import UI (sidebar entry, settings tab, org-chart button,
`/company/import` route) is hidden or redirected. Export remains fully
available. Self-hosted instances are unchanged.

**Reason and benefit**

Cloud-managed instances keep one consistent provisioning authority, and
users do not see an Import surface that dead-ends in a 403.

## What Changed

- `server/src/routes/companies.ts`: a router-level floor mounted at the
`/import` and `/:companyId/imports` prefixes. It covers the single-shot
upload, preview, job polling, chunked transfer
declare/part-upload/status/preview/apply, and the agent-safe per-company
import routes. It throws `forbidden(..., { code: "cloud_managed" })` on
cloud-managed instances, or `403 settings_operator_managed` when the
operator hides `company.import` — both before auth and body validation,
mirroring the company-creation floor.
- `packages/shared/src/settings-visibility.ts`: new
`HIDEABLE_COMPANY_PAGES` registry group — `company.members`,
`company.invites`, `company.secrets`, `company.export`, `company.import`
— with a `hidesCompanyPage` helper. The company General page stays
non-hideable (settings root). `company.import` floors its API; the other
keys are UI-visibility only, as documented in the registry, so
membership/invite/secret/export APIs stay live for agents.
- `ui/src/components/CloudManagedPageGate.tsx` (new): route gate that
redirects cloud-managed instances to `/company/settings`, modeled on
`HiddenSettingsPageGate`.
- `ui/src/App.tsx`: wraps the `company/import` route in
`CloudManagedPageGate`.
- `ui/src/components/CompanySettingsSidebar.tsx`,
`ui/src/components/access/CompanySettingsNav.tsx`,
`ui/src/pages/OrgChart.tsx`: hide the Import entry points when
`useCloudInstance()` reports a managed instance, and honor the new
`company.*` hidden-settings keys for every company page entry (sidebar
item, tab, org-chart buttons).
- `ui/src/App.tsx`: `HiddenSettingsPageGate` route gates for the members
(incl. the legacy access route), invites, secrets, export, and import
pages under their `company.*` keys.
- `docs/deploy/environment-variables.md`: documents the new keys and
their semantics; the CLI and board-operator guides note that import is
unavailable on cloud-managed instances.
- Tests: new `server/src/__tests__/company-import-cloud-floor.test.ts`
and `ui/src/components/CloudManagedPageGate.test.tsx`, registry cases in
`packages/shared/src/settings-visibility.test.ts`, plus cloud and
hidden-key cases in the sidebar, settings-nav, and org-chart suites.

## Verification

- TypeScript typechecks pass for every workspace package (`tsc` in
shared, server, ui; the runner's Rust leg needs a local cargo toolchain
and is covered by CI).
- `pnpm test` on this branch fails only in 9 files that also fail on a
clean `origin/master` checkout on the same machine
(environment-dependent suites: live-listener probes,
workspace/native-runtime spawns, skill materialization). Zero
branch-only failures against that baseline; every suite touched by this
change passes.
- `server/src/__tests__/company-import-cloud-floor.test.ts` asserts:
every import route answers 403 `cloud_managed` under the server-token
signal; the managed-config signal alone also floors; every import route
answers 403 `settings_operator_managed` when `company.import` is hidden;
hiding other company pages leaves import open; the floor applies before
auth and body validation; export stays open on cloud-managed instances;
self-hosted import preview and job polling still work.
- `packages/shared/src/settings-visibility.test.ts` covers the new
`company.*` keys and `hidesCompanyPage`.
- UI suites assert the Import tab, sidebar entry, and org-chart button
disappear on a cloud-managed instance while Export stays, that
`/company/import` redirects through the gate, and that the `company.*`
keys hide their sidebar entries and tabs.

## Risks

- Low risk for self-hosted installs: the floor is inert unless a cloud
signal (`PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` or
`PAPERCLIP_MANAGED_CONFIG`) is present, and the self-hosted paths are
regression-tested.
- On cloud-managed instances this is a deliberate behavioral removal:
import (including agent-driven safe imports and resumable transfers)
stops working the moment an instance runs this build. In-flight chunked
transfers on such instances cannot be applied afterward; they answer
403.
- CLI import commands against a cloud-managed instance now fail with the
`cloud_managed` error; the message names the reason.
- The new `company.*` keys change nothing unless an operator sets them:
`PAPERCLIP_HIDDEN_SETTINGS` unset keeps behavior identical, and older
images ignore unknown keys by design. The four non-import company keys
hide UI only; their APIs stay live, which the registry documents
explicitly.

## Model Used

Claude Fable 5 (`claude-fable-5`, Anthropic) via Claude Code — agentic
coding session with tool use (code search, editing, local test
execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Devin Foley authored and GitHub committed 2026-08-25 16:06:35 -07:00
1 parent a5c2add7be
commit 9c03443c48
18 files changed
+589 -54

No files matched your search

@@ -0,0 +1,205 @@
import express from "express";
import request from "supertest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mockPortabilityService = vi.hoisted(() => ({
previewExport: vi.fn(),
exportBundle: vi.fn(),
previewImport: vi.fn(),
importBundle: vi.fn(),
}));
const mockTransferRunService = vi.hoisted(() => ({
resumeOrCreate: vi.fn(),
getRunForActor: vi.fn(),
recordCompletedPart: vi.fn(),
claimApply: vi.fn(),
releaseApplyClaim: vi.fn(),
completeRun: vi.fn(),
failRun: vi.fn(),
}));
const mockLogActivity = vi.hoisted(() => vi.fn());
vi.mock("../services/index.js", () => ({
accessService: () => ({}),
agentService: () => ({}),
budgetService: () => ({}),
companyArtifactsService: () => ({}),
companyPortabilityService: () => mockPortabilityService,
companyService: () => ({}),
feedbackService: () => ({}),
logActivity: mockLogActivity,
workTimelineService: () => ({}),
}));
vi.mock("../services/company-transfer-runs.js", () => ({
companyTransferRunService: mockTransferRunService,
}));
const TRANSFER_ID = "6e0a4f6e-6f7d-4a37-9a83-0b8f2f9f2b11";
/**
* Every route in the company-import surface. The floor must answer all of
* them, including the read-only polling routes: with imports disabled no job
* or transfer can exist, so a uniform 403 is clearer than a mixed surface.
*/
const IMPORT_ROUTES: Array<{ method: "get" | "post" | "put"; path: string }> = [
{ method: "post", path: "/api/companies/import/preview" },
{ method: "post", path: "/api/companies/import" },
{ method: "get", path: "/api/companies/import/jobs/some-job" },
{ method: "post", path: "/api/companies/import/transfers" },
{ method: "put", path: `/api/companies/import/transfers/${TRANSFER_ID}/parts/0` },
{ method: "get", path: `/api/companies/import/transfers/${TRANSFER_ID}` },
{ method: "post", path: `/api/companies/import/transfers/${TRANSFER_ID}/preview` },
{ method: "post", path: `/api/companies/import/transfers/${TRANSFER_ID}/apply` },
{ method: "post", path: "/api/companies/11111111-2222-4333-8444-555555555555/imports/preview" },
{ method: "post", path: "/api/companies/11111111-2222-4333-8444-555555555555/imports/apply" },
];
async function createApp(actor: Record<string, unknown>) {
const [{ companyRoutes }, { errorHandler }] = await Promise.all([
import("../routes/companies.js"),
import("../middleware/index.js"),
]);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = actor;
next();
});
app.use("/api/companies", companyRoutes({} as any));
app.use(errorHandler);
return app;
}
const boardAdmin = {
type: "board",
source: "local_implicit",
userId: "local-user",
isInstanceAdmin: true,
};
function expectNoImportWork() {
expect(mockPortabilityService.previewImport).not.toHaveBeenCalled();
expect(mockPortabilityService.importBundle).not.toHaveBeenCalled();
expect(mockTransferRunService.resumeOrCreate).not.toHaveBeenCalled();
expect(mockTransferRunService.getRunForActor).not.toHaveBeenCalled();
}
describe("company import Cloud floor", () => {
beforeEach(() => {
vi.clearAllMocks();
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
delete process.env.PAPERCLIP_MANAGED_CONFIG;
delete process.env.PAPERCLIP_HIDDEN_SETTINGS;
});
afterEach(() => {
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
delete process.env.PAPERCLIP_MANAGED_CONFIG;
delete process.env.PAPERCLIP_HIDDEN_SETTINGS;
});
it("returns 403 cloud_managed on every import route on a cloud-managed instance", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-secret";
const app = await createApp(boardAdmin);
for (const route of IMPORT_ROUTES) {
const res = await request(app)[route.method](route.path).send({});
expect(res.status, `${route.method.toUpperCase()} ${route.path}`).toBe(403);
expect(res.body, `${route.method.toUpperCase()} ${route.path}`).toMatchObject({
code: "cloud_managed",
});
}
expectNoImportWork();
});
it("floors on the managed-config signal alone", async () => {
process.env.PAPERCLIP_MANAGED_CONFIG = JSON.stringify({ v: 1, mode: "cloud" });
const app = await createApp(boardAdmin);
const res = await request(app).post("/api/companies/import").send({});
expect(res.status).toBe(403);
expect(res.body).toMatchObject({ code: "cloud_managed" });
expectNoImportWork();
});
it("applies the floor before auth and request-body validation", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-secret";
// An agent actor never passes the import routes' own assertBoard, and the
// body is not schema-valid either — the floor must still answer first so a
// Cloud caller sees one consistent refusal.
const app = await createApp({ type: "agent", agentId: "agent-1", companyId: "company-1" });
const res = await request(app)
.post("/api/companies/import/transfers")
.send({ nonsense: true });
expect(res.status).toBe(403);
expect(res.body).toMatchObject({ code: "cloud_managed" });
expectNoImportWork();
});
it("floors every import route with settings_operator_managed when company.import is hidden", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS = "company.import";
const app = await createApp(boardAdmin);
for (const route of IMPORT_ROUTES) {
const res = await request(app)[route.method](route.path).send({});
expect(res.status, `${route.method.toUpperCase()} ${route.path}`).toBe(403);
expect(res.body, `${route.method.toUpperCase()} ${route.path}`).toMatchObject({
code: "settings_operator_managed",
});
}
expectNoImportWork();
});
it("keeps import open when only other company pages are hidden", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS = "company.secrets,company.members";
const app = await createApp(boardAdmin);
const res = await request(app).get("/api/companies/import/jobs/unknown-job");
expect(res.status).toBe(404);
expect(res.body).toMatchObject({ error: "Import job not found" });
});
it("keeps company export open on a cloud-managed instance", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-secret";
mockPortabilityService.exportBundle.mockResolvedValue({ ok: true });
const app = await createApp(boardAdmin);
const res = await request(app)
.post("/api/companies/11111111-2222-4333-8444-555555555555/exports")
.send({});
expect(res.status).toBe(200);
expect(mockPortabilityService.exportBundle).toHaveBeenCalledTimes(1);
});
it("preserves self-hosted import preview", async () => {
mockPortabilityService.previewImport.mockResolvedValue({ companies: [] });
const app = await createApp(boardAdmin);
const res = await request(app)
.post("/api/companies/import/preview")
.send({
source: { type: "github", url: "https://github.com/example/export" },
target: { mode: "new_company" },
});
expect(res.status).toBe(200);
expect(mockPortabilityService.previewImport).toHaveBeenCalledTimes(1);
});
it("preserves self-hosted import job polling", async () => {
const app = await createApp(boardAdmin);
const res = await request(app).get("/api/companies/import/jobs/unknown-job");
expect(res.status).toBe(404);
expect(res.body).toMatchObject({ error: "Import job not found" });
});
});
@@ -859,9 +859,12 @@ describe.sequential("company portability routes", () => {
expect(mockLogActivity).not.toHaveBeenCalled();
});
it.sequential("keeps Cloud-managed global import apply synchronous when async opt-in is absent", async () => {
it.sequential("floors global import apply on a cloud-managed instance, even for the trusted tenant actor", async () => {
// The trusted-tenant tests above run without the cloud env signal on
// purpose: the import floor keys on isCloudManagedInstance(), not on the
// actor. With the signal present, even the trusted tenant actor is
// floored — importing is disabled on cloud-managed instances outright.
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-secret");
mockCompanyPortabilityService.importBundle.mockResolvedValueOnce(createImportResult("created"));
try {
const app = await createApp(cloudTenantActor());
@@ -870,15 +873,10 @@ describe.sequential("company portability routes", () => {
.set(cloudHeaders)
.send(importRequest);
expect(res.status).toBe(200);
expect(res.body.company.id).toBe(companyId);
expect(res.body.company.action).toBe("created");
expect(res.body.job).toBeUndefined();
expect(mockCompanyPortabilityService.importBundle).toHaveBeenCalledWith(importRequest, "cloud-user-1", { pauseAutomations: false });
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "company.imported",
companyId,
}));
expect(res.status).toBe(403);
expect(res.body).toMatchObject({ code: "cloud_managed" });
expect(mockCompanyPortabilityService.importBundle).not.toHaveBeenCalled();
expect(mockLogActivity).not.toHaveBeenCalled();
} finally {
vi.unstubAllEnvs();
}
+38 -1
View File
@@ -1,5 +1,5 @@
import { createHash, randomUUID } from "node:crypto";
import express, { Router, type Request, type Response } from "express";
import express, { Router, type NextFunction, type Request, type Response } from "express";
import multer from "multer";
import { and, count as countFn, eq } from "drizzle-orm";
import { z } from "zod";
@@ -13,6 +13,7 @@ import {
} from "@paperclipai/shared/portability-zip";
import {
DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION,
SETTINGS_OPERATOR_MANAGED_ERROR_CODE,
companyArtifactsQuerySchema,
companyPortabilityExportSchema,
companyPortabilityImportSchema,
@@ -21,6 +22,7 @@ import {
feedbackTargetTypeSchema,
feedbackTraceStatusSchema,
feedbackVoteValueSchema,
hidesCompanyPage,
updateCompanyBrandingSchema,
updateCompanySchema,
} from "@paperclipai/shared";
@@ -61,6 +63,7 @@ import {
workTimelineService,
} from "../services/index.js";
import { isCloudManagedInstance } from "../services/cloud-instance.js";
import { getHiddenSettings } from "../services/settings-visibility.js";
import type { StorageService } from "../storage/types.js";
import { assertBoard, assertCompanyAccess, assertInstanceAdmin, getActorInfo, hasCompanyAccess } from "./authz.js";
import { COMPANY_IMPORT_ROUTE_PATH } from "./company-import-paths.js";
@@ -503,6 +506,40 @@ export function companyRoutes(db: Db, storage?: StorageService, options?: Compan
res.json(buildExportFidelityReport(companyId, counts));
});
/**
* Floor for the whole company-import surface: single-shot upload, preview,
* job polling, chunked transfers, and the per-company agent-safe import
* routes. Two independent signals close it, both checked up front — before
* auth or body work, the same way the company-creation floor does:
*
* - a cloud-managed instance (`cloud_managed`): the hosting platform
* provisions the company, so materializing imported companies on a
* managed instance is disabled unconditionally;
* - the operator hiding the Import page (`company.import` in
* `PAPERCLIP_HIDDEN_SETTINGS` → `settings_operator_managed`): hiding the
* page also disables its API, so the hide is real rather than cosmetic.
*
* Export routes stay open either way — they are the tenant's
* data-portability escape hatch.
*/
const importFloor = (_req: Request, _res: Response, next: NextFunction) => {
if (isCloudManagedInstance()) {
throw forbidden("Company import is disabled on cloud-managed instances", {
code: "cloud_managed",
});
}
if (hidesCompanyPage(getHiddenSettings(), "company.import")) {
throw forbidden("Company import is hidden by the hosting operator", {
code: SETTINGS_OPERATOR_MANAGED_ERROR_CODE,
});
}
next();
};
// COMPANY_IMPORT_TRANSFERS_ROUTE_PATH nests under the import path, so these
// two prefixes cover every import route registered below.
router.use(COMPANY_IMPORT_ROUTE_PATH, importFloor);
router.use("/:companyId/imports", importFloor);
router.post("/import/preview", async (req, res) => {
assertBoard(req);
const body = companyPortabilityPreviewSchema.parse(await resolveImportPayload(req, res));