feat(onboarding): sign in to an agent provider during onboarding (#12440)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - New organizations create their first agent through the onboarding
wizard
> - The wizard does not show provider sign-in when a host credential is
absent or unknown
> - The create step also gives unclear feedback when the provider needs
authentication
> - This pull request adds a safe auth signal and a provider sign-in
step for sandbox drivers
> - The benefit is a clearer onboarding path with no token or account
data in the signal

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (server API, shared types, and UI)

**Problem or motivation**

The onboarding wizard can fail when the selected provider needs
authentication. It does not tell the person how to complete sign-in.

**Proposed solution**

Add a status-only provider auth signal. Show the sign-in panel for
sandbox drivers when the signal says `absent` or `unknown`. Apply a
stored Claude login to the new agent and block creation when the adapter
test reports missing authentication.

**Alternatives considered**

The wizard could hide the sign-in panel when the signal read fails. This
would hide a needed action, so this pull request shows the panel when
the signal is unknown.

**Roadmap alignment**

The change supports the roadmap goal for scoped and audited credential
bindings.

**Additional context**

The auth signal returns only `present`, `absent`, or `unknown`. It never
returns a token, identifier, or account name.

## What Changed

- Add `GET /api/companies/:companyId/adapters/:type/auth-signal` with
company and permission checks.
- Add shared auth-signal types and the UI query path.
- Apply a stored Claude login by reference without reading its token.
- Show the provider sign-in panel only for sandbox drivers with
interactive terminal support.
- Block agent creation when the provider test reports missing
authentication.
- Add route, wizard, and end-to-end test coverage.

## Verification

- `pnpm --filter @paperclipai/server test adapter-auth-signal-routes`
passes 50 tests.
- `pnpm --filter @paperclipai/ui test OnboardingWizard` passes 69 tests.
- `pnpm --filter @paperclipai/ui exec tsc --noEmit` exits with code 0.
- The `e2e_shards` lane runs `tests/e2e/onboarding.spec.ts`.

## Risks

The route reads a host-local readiness signal. It returns `unknown` on
read errors and never exposes credential data. The UI may add a sign-in
step when the signal is unavailable.

## Model Used

OpenAI Codex, GPT-5, extended reasoning, tool use, and code execution.
The exact context window was not provided.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-08-28 10:20:37 -07:00
1 parent 66e1c0df8b
commit d9449e636e
13 files changed
+1554 -23

No files matched your search

@@ -0,0 +1,415 @@
import express from "express";
import request from "supertest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// The cheap host-local authentication-signal route. It reads no sandbox and
// runs no shell command or model process, so every test drives it through a
// plain in-process Express app with fake services -- no database, no
// sandbox provider, and no adapter execution.
const COMPANY_1 = "company-1";
const OTHER_COMPANY = "company-2";
const OWNER_A = "user-a";
const ENVIRONMENT_1 = "11111111-1111-4111-8111-111111111111";
const mockAgentService = vi.hoisted(() => ({
getById: vi.fn(),
getChainOfCommand: vi.fn(async () => []),
}));
const mockAccessService = vi.hoisted(() => ({
canUser: vi.fn(),
decide: vi.fn(),
hasPermission: vi.fn(),
getMembership: vi.fn(async () => null),
listPrincipalGrants: vi.fn(async () => []),
}));
const mockSecretService = vi.hoisted(() => ({
normalizeAdapterConfigForPersistence: vi.fn(async (_companyId: string, config: Record<string, unknown>) => config),
resolveAdapterConfigForRuntime: vi.fn(async (_companyId: string, config: Record<string, unknown>) => ({ config })),
collectMissingRuntimeBindings: vi.fn(async () => [] as Array<Record<string, unknown>>),
resolveEnvBindings: vi.fn(async () => ({
env: {} as Record<string, string>,
secretKeys: new Set<string>(),
manifest: [],
})),
readClaudeOAuthUserSecretStatus: vi.fn(async () => null as { secretId: string; latestVersion: number } | null),
}));
const mockEnvironmentService = vi.hoisted(() => ({
getById: vi.fn(),
releaseLease: vi.fn(),
listBoundCompanyIds: vi.fn(async () => [] as string[]),
}));
const mockEnvironmentRuntime = vi.hoisted(() => ({
acquireRunLease: vi.fn(),
realizeWorkspace: vi.fn(),
getDriver: vi.fn(() => ({ releaseRunLease: vi.fn(async () => undefined) })),
}));
const mockResolveEnvironmentExecutionTarget = vi.hoisted(() => vi.fn());
const mockInstanceSettingsService = vi.hoisted(() => ({
getGeneral: vi.fn(async () => ({ censorUsernameInLogs: false })),
getExperimental: vi.fn(async () => ({ enableManagedSandboxOnly: false })),
}));
// The one host-local Codex readiness predictor the route calls. The test
// controls its resolved value and its failure, so it stays independent of a
// real Codex home on disk.
const mockEvaluateCodexCredentialReadiness = vi.hoisted(() => vi.fn());
vi.mock("../services/index.js", () => ({
agentService: () => mockAgentService,
agentInstructionsService: () => ({}),
accessService: () => mockAccessService,
approvalService: () => ({}),
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
companySkillService: () => ({
listRuntimeSkillEntries: vi.fn(async () => []),
resolveRequestedSkillKeys: vi.fn(async () => []),
}),
budgetService: () => ({}),
heartbeatService: () => ({
wakeup: vi.fn(),
cancelActiveForAgent: vi.fn(),
}),
ISSUE_LIST_DEFAULT_LIMIT: 50,
issueApprovalService: () => ({}),
issueRecoveryActionService: () => ({}),
issueService: () => ({}),
logActivity: vi.fn(),
syncInstructionsBundleConfigFromFilePath: vi.fn((_agent, config) => config),
workspaceOperationService: () => ({}),
}));
vi.mock("../services/environments.js", () => ({
environmentService: () => mockEnvironmentService,
}));
vi.mock("../services/secrets.js", () => ({
secretService: () => mockSecretService,
}));
vi.mock("../services/environment-runtime.js", () => ({
environmentRuntimeService: () => mockEnvironmentRuntime,
}));
vi.mock("../services/environment-execution-target.js", () => ({
resolveEnvironmentExecutionTarget: mockResolveEnvironmentExecutionTarget,
}));
vi.mock("../services/instance-settings.js", () => ({
instanceSettingsService: () => mockInstanceSettingsService,
}));
vi.mock("@paperclipai/adapter-codex-local/server", async (importOriginal) => {
const actual = await importOriginal<typeof import("@paperclipai/adapter-codex-local/server")>();
return {
...actual,
evaluateCodexCredentialReadiness: mockEvaluateCodexCredentialReadiness,
};
});
let currentActor: Record<string, unknown>;
function boardActor(userId: string, companyIds: string[] = [COMPANY_1, OTHER_COMPANY]): Record<string, unknown> {
return {
type: "board",
userId,
companyIds,
source: "local_implicit",
isInstanceAdmin: false,
};
}
async function createApp() {
const [{ agentRoutes }, { errorHandler }] = await Promise.all([
vi.importActual<typeof import("../routes/agents.js")>("../routes/agents.js"),
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
]);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as unknown as { actor: unknown }).actor = currentActor;
next();
});
app.use("/api", agentRoutes({} as never));
app.use(errorHandler);
return app;
}
const authSignalPath = (companyId: string, type: string, environmentId?: string) =>
`/api/companies/${companyId}/adapters/${type}/auth-signal${environmentId ? `?environmentId=${environmentId}` : ""}`;
describe("adapter auth-signal route", () => {
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
currentActor = boardActor(OWNER_A);
mockAccessService.decide.mockResolvedValue({
allowed: true,
reason: "allow_explicit_grant",
explanation: "Allowed by test grant",
});
mockEnvironmentService.getById.mockResolvedValue({
id: ENVIRONMENT_1,
companyId: COMPANY_1,
name: "Sandbox QA",
driver: "sandbox",
status: "active",
config: { provider: "fake-plugin" },
envVars: {},
});
mockEnvironmentService.listBoundCompanyIds.mockResolvedValue([]);
mockSecretService.resolveEnvBindings.mockResolvedValue({
env: {},
secretKeys: new Set<string>(),
manifest: [],
});
mockSecretService.readClaudeOAuthUserSecretStatus.mockResolvedValue(null);
mockEvaluateCodexCredentialReadiness.mockResolvedValue({
managed: true,
authMode: "subscription",
ready: false,
effectiveHome: "/tmp/codex-home",
sharedSourceHome: "/tmp/codex-shared-home",
});
});
afterEach(() => {
vi.clearAllMocks();
});
it("returns present for codex_local when the readiness predictor reports ready", async () => {
mockEvaluateCodexCredentialReadiness.mockResolvedValueOnce({
managed: true,
authMode: "subscription",
ready: true,
effectiveHome: "/tmp/codex-home",
sharedSourceHome: "/tmp/codex-shared-home",
});
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "codex_local"));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "present" });
expect(mockEvaluateCodexCredentialReadiness).toHaveBeenCalledWith(
expect.objectContaining({ companyId: COMPANY_1 }),
);
});
it("returns absent for codex_local when the readiness predictor reports not ready", async () => {
mockEvaluateCodexCredentialReadiness.mockResolvedValueOnce({
managed: true,
authMode: "subscription",
ready: false,
effectiveHome: "/tmp/codex-home",
sharedSourceHome: "/tmp/codex-shared-home",
});
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "codex_local"));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "absent" });
});
it("returns unknown for codex_local when the readiness predictor throws", async () => {
mockEvaluateCodexCredentialReadiness.mockRejectedValueOnce(new Error("boom"));
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "codex_local"));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "unknown" });
});
it("returns unknown for codex_local on a sandbox environment even when the host reports ready", async () => {
// The host readiness predictor is ready, but the selected sandbox holds no
// credential of its own. The route must not let the unrelated host login
// hide the sandbox's own sign-in panel.
mockEvaluateCodexCredentialReadiness.mockResolvedValueOnce({
managed: true,
authMode: "subscription",
ready: true,
effectiveHome: "/tmp/codex-home",
sharedSourceHome: "/tmp/codex-shared-home",
});
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "codex_local", ENVIRONMENT_1));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "unknown" });
expect(mockEvaluateCodexCredentialReadiness).not.toHaveBeenCalled();
});
it("returns present for codex_local on a sandbox environment that holds its own API key", async () => {
mockEnvironmentService.getById.mockResolvedValue({
id: ENVIRONMENT_1,
companyId: COMPANY_1,
name: "Sandbox QA",
driver: "sandbox",
status: "active",
config: { provider: "fake-plugin" },
envVars: {
OPENAI_API_KEY: { type: "secret_ref", secretId: "secret-1" },
},
});
mockSecretService.resolveEnvBindings.mockResolvedValueOnce({
env: { OPENAI_API_KEY: "resolved-key" },
secretKeys: new Set(["OPENAI_API_KEY"]),
manifest: [],
});
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "codex_local", ENVIRONMENT_1));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "present" });
expect(mockEvaluateCodexCredentialReadiness).not.toHaveBeenCalled();
});
it("uses the host readiness predictor for codex_local on a local-driver environment", async () => {
mockEnvironmentService.getById.mockResolvedValue({
id: ENVIRONMENT_1,
companyId: COMPANY_1,
name: "Local host",
driver: "local",
status: "active",
config: {},
envVars: {},
});
mockEvaluateCodexCredentialReadiness.mockResolvedValueOnce({
managed: true,
authMode: "subscription",
ready: true,
effectiveHome: "/tmp/codex-home",
sharedSourceHome: "/tmp/codex-shared-home",
});
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "codex_local", ENVIRONMENT_1));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "present" });
expect(mockEvaluateCodexCredentialReadiness).toHaveBeenCalledWith(
expect.objectContaining({ companyId: COMPANY_1 }),
);
});
it("returns present for claude_local when the environment holds a non-empty token", async () => {
mockEnvironmentService.getById.mockResolvedValue({
id: ENVIRONMENT_1,
companyId: COMPANY_1,
name: "Sandbox QA",
driver: "sandbox",
status: "active",
config: { provider: "fake-plugin" },
envVars: {
CLAUDE_CODE_OAUTH_TOKEN: { type: "secret_ref", secretId: "secret-1" },
},
});
mockSecretService.resolveEnvBindings.mockResolvedValueOnce({
env: { CLAUDE_CODE_OAUTH_TOKEN: "resolved-token" },
secretKeys: new Set(["CLAUDE_CODE_OAUTH_TOKEN"]),
manifest: [],
});
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "claude_local", ENVIRONMENT_1));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "present" });
expect(mockSecretService.readClaudeOAuthUserSecretStatus).not.toHaveBeenCalled();
});
it("returns present for claude_local when the owner holds a stored login and the environment holds no key", async () => {
mockSecretService.readClaudeOAuthUserSecretStatus.mockResolvedValueOnce({
secretId: "secret-1",
latestVersion: 1,
});
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "claude_local", ENVIRONMENT_1));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "present" });
expect(mockSecretService.readClaudeOAuthUserSecretStatus).toHaveBeenCalledWith(COMPANY_1, OWNER_A);
});
it("returns absent for claude_local when neither source holds a value", async () => {
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "claude_local"));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "absent" });
});
it("returns unknown for an adapter type that has no cheap signal", async () => {
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "cursor_local"));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toEqual({ status: "unknown" });
expect(mockEvaluateCodexCredentialReadiness).not.toHaveBeenCalled();
expect(mockSecretService.readClaudeOAuthUserSecretStatus).not.toHaveBeenCalled();
});
it("rejects an environment that belongs to another company", async () => {
mockEnvironmentService.listBoundCompanyIds.mockResolvedValueOnce([OTHER_COMPANY]);
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "claude_local", ENVIRONMENT_1));
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(mockSecretService.resolveEnvBindings).not.toHaveBeenCalled();
expect(mockSecretService.readClaudeOAuthUserSecretStatus).not.toHaveBeenCalled();
});
it("rejects a caller who cannot create agents for the company", async () => {
mockAccessService.decide.mockResolvedValue({
allowed: false,
reason: "deny_no_grant",
explanation: "Not allowed by any grant",
});
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "claude_local"));
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(mockEnvironmentService.getById).not.toHaveBeenCalled();
expect(mockSecretService.readClaudeOAuthUserSecretStatus).not.toHaveBeenCalled();
});
it("returns a response body that holds only the status field", async () => {
mockEvaluateCodexCredentialReadiness.mockResolvedValueOnce({
managed: true,
authMode: "subscription",
ready: true,
effectiveHome: "/tmp/codex-home",
sharedSourceHome: "/tmp/codex-shared-home",
});
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "codex_local"));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(Object.keys(res.body)).toEqual(["status"]);
});
it("takes no sandbox lease and starts no model process", async () => {
const app = await createApp();
const res = await request(app).get(authSignalPath(COMPANY_1, "codex_local", ENVIRONMENT_1));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockEnvironmentRuntime.acquireRunLease).not.toHaveBeenCalled();
expect(mockResolveEnvironmentExecutionTarget).not.toHaveBeenCalled();
});
});
+122
View File
@@ -80,6 +80,8 @@ import type {
AdapterEnvironmentTestResult,
AdapterModelProfileDefinition,
} from "@paperclipai/adapter-utils";
import { evaluateCodexCredentialReadiness } from "@paperclipai/adapter-codex-local/server";
import type { AdapterAuthSignal, AdapterAuthSignalResponse } from "@paperclipai/shared";
import { getDisabledAdapterTypes } from "../services/adapter-plugin-store.js";
import { skillVersionSelectionMap } from "../services/runtime-skill-selections.js";
import { secretService } from "../services/secrets.js";
@@ -2696,6 +2698,126 @@ export function agentRoutes(
},
);
// The claude_local branch of the auth-signal read. It checks two host-local
// sources for a usable Claude Code OAuth token: the resolved envVars of the
// caller's selected environment, and the caller's own stored Claude login. It
// returns "present" the moment either source holds a non-empty token, so it
// never resolves more than the one env key it needs.
async function evaluateClaudeAuthSignal(
req: Request,
companyId: string,
environmentId: string | null,
): Promise<AdapterAuthSignal> {
if (environmentId) {
const environment = await environmentsSvc.getById(environmentId);
const environmentEnv = Object.fromEntries(
Object.entries(parseObject(environment?.envVars)).filter(
([key]) => !isForbiddenConfigEnvKey(key),
),
);
const tokenBinding = environmentEnv.CLAUDE_CODE_OAUTH_TOKEN;
if (tokenBinding !== undefined) {
const resolution = await secretsSvc.resolveEnvBindings(
companyId,
{ CLAUDE_CODE_OAUTH_TOKEN: tokenBinding },
buildActorSecretContext(req, { consumerType: "environment", consumerId: environmentId }),
);
if (asNonEmptyString(resolution.env.CLAUDE_CODE_OAUTH_TOKEN)) {
return "present";
}
}
}
const ownerUserId = req.actor.userId;
if (ownerUserId) {
const stored = await secretsSvc.readClaudeOAuthUserSecretStatus(companyId, ownerUserId);
if (stored) return "present";
}
return "absent";
}
// The codex_local branch of the auth-signal read. The host filesystem check
// (`evaluateCodexCredentialReadiness` against `process.env`) describes only
// the Paperclip host, so it is authoritative for the null-environment and
// "local" driver cases, where the host is the execution target. For a
// non-local environment (a sandbox), the host's own credential state says
// nothing about that sandbox, so the route checks the environment's own
// OPENAI_API_KEY binding instead and otherwise reports "unknown" -- never
// "present" from a host login the sandbox does not share.
async function evaluateCodexAuthSignal(
req: Request,
companyId: string,
environmentId: string | null,
): Promise<AdapterAuthSignal> {
if (environmentId) {
const environment = await environmentsSvc.getById(environmentId);
if (environment && environment.driver !== "local") {
const environmentEnv = Object.fromEntries(
Object.entries(parseObject(environment.envVars)).filter(
([key]) => !isForbiddenConfigEnvKey(key),
),
);
const apiKeyBinding = environmentEnv.OPENAI_API_KEY;
if (apiKeyBinding !== undefined) {
const resolution = await secretsSvc.resolveEnvBindings(
companyId,
{ OPENAI_API_KEY: apiKeyBinding },
buildActorSecretContext(req, { consumerType: "environment", consumerId: environmentId }),
);
if (asNonEmptyString(resolution.env.OPENAI_API_KEY)) {
return "present";
}
}
return "unknown";
}
}
const readiness = await evaluateCodexCredentialReadiness({
env: process.env,
companyId,
configuredCodexHome: null,
configuredApiKey: null,
});
return readiness.ready ? "present" : "absent";
}
// The cheap host-local authentication signal for one adapter type. The route
// reads host-local state only: a stored Claude login, a resolved environment
// env var, or the local Codex credential readiness check. It leases no
// sandbox, starts no shell command, and starts no model request. The two
// access gates below run before any read, so a caller who cannot create
// agents for the company and a foreign environment both fail closed before
// the route touches a credential source.
router.get(
"/companies/:companyId/adapters/:type/auth-signal",
async (req, res) => {
const companyId = req.params.companyId as string;
const type = req.params.type as string;
await assertCanCreateAgentsForCompany(req, companyId);
const environmentId = asNonEmptyString(req.query.environmentId);
if (environmentId) {
await assertAdapterTestEnvironmentForCompany(companyId, environmentId);
}
res.setHeader("Cache-Control", "no-store");
let status: AdapterAuthSignal = "unknown";
try {
if (type === "claude_local") {
status = await evaluateClaudeAuthSignal(req, companyId, environmentId);
} else if (type === "codex_local") {
status = await evaluateCodexAuthSignal(req, companyId, environmentId);
}
} catch {
// A failed read is never a claim that the credential is absent. Report
// the neutral "unknown" signal instead, so the wizard falls back to
// showing the login panel.
status = "unknown";
}
const body: AdapterAuthSignalResponse = { status };
res.json(body);
},
);
// Start a company-scoped adapter device login. The create form has no agent
// identifier, so the route keys on the company and the adapter. The owner
// helper requires a board actor with the configuration permission, and it
+12
View File
@@ -2187,6 +2187,18 @@ registry.registerPath({
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
});
registry.registerPath({
method: "get",
path: "/api/companies/{companyId}/adapters/{type}/auth-signal",
tags: ["adapters"],
summary: "Read the cheap host-local authentication signal for an adapter type",
request: {
params: z.object({ companyId: z.string(), type: z.string() }),
query: z.object({ environmentId: z.string().optional() }),
},
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
});
registry.registerPath({
method: "post",
path: "/api/companies/{companyId}/adapters/{type}/login-sessions",