Files
PaperClipAI/cli/src/commands/client/secrets.ts
T
655d6c9d8e fix(cli): make -C/--company-id optional on client commands enforced via resolveCommandContext (#11601)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The `paperclipai` CLI is how humans and other agents drive Paperclip
from a terminal or script
> - Many `client/*` command files declare `-C, --company-id` with
`.requiredOption(...)`, so commander aborts argument parsing before the
command's action ever runs
> - Every one of those same actions calls `resolveCommandContext(opts, {
requireCompany: true })`, which already resolves the company id from
`--company-id` -> `PAPERCLIP_COMPANY_ID` -> the context profile, and
throws a clear error only when all three are empty
> - So a command like `agent list` fails immediately on a bare parse
error even when the caller has `PAPERCLIP_COMPANY_ID` exported or a
context profile set, while a sibling command like `issue list` (no
`requiredOption`) works fine from the same environment — same resolver,
inconsistent enforcement point
> - This pull request replaces `.requiredOption("-C, --company-id <id>",
...)` with `.option(...)` at every site backed by
`resolveCommandContext(..., { requireCompany: true })`, leaving
`requireCompany: true` untouched so the resolver still enforces the
requirement, just with its existing, more informative error message
> - The benefit is that `--company-id` behaves consistently across every
client command: env var and context-profile fallback always work, and
the error message when nothing is set comes from one place instead of
commander's generic "required option not specified"

## Linked Issues or Issue Description

No public GitHub issue exists for this yet, so following the Enhancement
proposal template inline:

**What existing behavior does this improve?**
The `-C, --company-id` option on CLI client commands under
`cli/src/commands/client/`.

**Subsystem affected**
Unsure / cross-cutting within the CLI — this is not one of the listed
subsystems (server/, ui/, packages/db, packages/shared,
packages/adapters, packages/plugins); it is
`cli/src/commands/client/**`.

**Current behavior**
28 commands across
`cli/src/commands/client/{activity,agent,approval,company,goal,plugin,project,secrets,token}.ts`
declare `-C, --company-id` via commander's `.requiredOption(...)`.
Commander enforces that flag at argument-parse time and exits with a
generic `error: required option '-C, --company-id <id>' not specified`
before the command's action function runs — even though every one of
those actions calls `resolveCommandContext(opts, { requireCompany: true
})`, which is fully capable of resolving the company id from
`PAPERCLIP_COMPANY_ID` or the context profile. Other commands in the
same CLI (e.g. `issue list`) use `.option(...)` for the same flag and
already work from env/profile. The result is an inconsistent, confusing
failure mode depending on which command you call.

**Proposed behavior**
All 28 sites use `.option("-C, --company-id <id>", ...)` instead of
`.requiredOption(...)`. `requireCompany: true` stays in
`resolveCommandContext`, so a company id is still required end-to-end —
it can now come from `--company-id`, `PAPERCLIP_COMPANY_ID`, or the
context profile, uniformly, with one shared, descriptive error message
when none of the three are set.

**Breaking changes**
None for correctly-configured callers. A caller that relied on
commander's parse-time rejection (rather than the resolver's `Company ID
is required...` message) would see a different error message, but the
exit-code behavior (non-zero, no company id resolved) is unchanged. No
response shape, output format, or successful-path behavior changes.

## What Changed

- Replaced `.requiredOption("-C, --company-id <id>", ...)` with
`.option("-C, --company-id <id>", ...)` at all 28 call sites across
`cli/src/commands/client/activity.ts`, `agent.ts`, `approval.ts`,
`company.ts`, `goal.ts`, `plugin.ts`, `project.ts`, `secrets.ts`, and
`token.ts`.
- Left `resolveCommandContext(opts, { requireCompany: true })` unchanged
everywhere — enforcement still happens there, with its existing error
message.
- Added `cli/src/__tests__/company-id-option.test.ts`, a regression test
modelled on `auth-command-registration.test.ts` that registers every
affected command family (`company`, `issue`, `agent`, `approval`,
`activity`, `dashboard`, `feedback`, `goal`, `plugin`, `project`,
`secrets`, `token`), walks the full command tree, and asserts
`--company-id` is never `mandatory` (commander's `.requiredOption`
discriminator) and never declared more than once on the same command.

## Verification

```
$ grep -rn 'requiredOption("-C' cli/src/commands/client/
# exit code 1, no matches
```

```
$ cd cli && pnpm exec vitest run src/__tests__/company-id-option.test.ts
 Test Files  1 passed (1)
      Tests  2 passed (2)
```

Red on the unpatched tree (reverting only the fix files reproduces 9+
offending commands):

```
$ git stash push -- cli/src/commands/client/*.ts
$ pnpm exec vitest run src/__tests__/company-id-option.test.ts
 ❯ … 1 failed
AssertionError: --company-id must never be mandatory; offending commands: …
$ git stash pop
```

```
$ pnpm -C cli build
# green (tsc --noEmit at the repo root reports ~139 pre-existing errors in
# server/src/** from a missing built @paperclipai/plugin-sdk dist, present
# identically on the unpatched tree and unrelated to this diff;
# cli/src/commands/client/** itself has zero new type errors)
```

Behavioral check via `cli/src/index.ts`:

```
$ PAPERCLIP_COMPANY_ID=test-co-123 PAPERCLIP_API_KEY=fake pnpm exec tsx src/index.ts agent list --json
API error 401: Unauthorized
# past argument parsing, into an HTTP/auth error — this is the intended fix

$ pnpm exec tsx src/index.ts agent list --json --context /tmp/pc-empty-context.json
Company ID is required. Pass --company-id, set PAPERCLIP_COMPANY_ID, or set context profile companyId via `paperclipai context set`.
```

## Risks

Low risk. This only relaxes a commander-level parse constraint; the
underlying requirement (`requireCompany: true`) is untouched, so every
affected command still refuses to proceed without a resolvable company
id. The main behavioral shift is the error message and the point at
which the error surfaces (resolver instead of commander), which is
strictly more informative. No API, schema, or persisted-data changes.

## Model Used

Claude (Anthropic), Claude Opus, extended thinking / chain-of-thought
reasoning enabled, with tool use (repo grep/read/edit, test execution)
throughout implementation and verification.

## 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
- [ ] 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

## Related PRs found during duplicate search

- #4276 (`feat(cli): unify issue flag matrix (A+B) — -C optional +
per-subcommand guards`) — open, overlapping intent (also makes `-C`
optional) but scoped to `issue create` only plus a separate flag-hint
feature; does not touch the other 27 sites this PR fixes. Not a
duplicate.
- #2538 (`Refine CLI company commands behavior, tests`) — open, touches
`company.ts` but for import-adapter validation, unrelated to
`--company-id` enforcement. Not a duplicate.

No exact duplicate of this PR's scope (making `--company-id` a
non-mandatory option across all 28 client-command call sites while
keeping resolver-level enforcement) was found in the open or closed PR
list.

---------

Co-authored-by: dzianisv <dzianisv@gmail.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-04 11:25:29 -08:00

727 lines
25 KiB
TypeScript

import { Command } from "commander";
import pc from "picocolors";
import type {
Agent,
AgentEnvConfig,
CompanyPortabilityEnvInput,
CompanyPortabilityExportPreviewResult,
CompanyPortabilityInclude,
CompanySecret,
EnvBinding,
SecretProvider,
SecretProviderDescriptor,
} from "@paperclipai/shared";
import {
addCommonClientOptions,
apiPath,
formatInlineRecord,
handleCommandError,
printOutput,
resolveCommandContext,
type BaseClientOptions,
} from "./common.js";
interface SecretListOptions extends BaseClientOptions {
companyId?: string;
}
interface SecretDeclarationsOptions extends BaseClientOptions {
companyId?: string;
include?: string;
kind?: "all" | "secret" | "plain";
}
interface SecretCreateOptions extends BaseClientOptions {
companyId?: string;
name?: string;
key?: string;
provider?: SecretProvider;
value?: string;
valueEnv?: string;
description?: string;
}
interface SecretUpdateOptions extends BaseClientOptions {
payloadJson?: string;
}
interface SecretRotateOptions extends BaseClientOptions {
value?: string;
valueEnv?: string;
}
interface SecretDeleteOptions extends BaseClientOptions {
yes?: boolean;
confirm?: string;
}
interface SecretLinkOptions extends BaseClientOptions {
companyId?: string;
name?: string;
key?: string;
provider?: SecretProvider;
externalRef?: string;
providerVersionRef?: string;
description?: string;
}
interface SecretDoctorOptions extends BaseClientOptions {
companyId?: string;
}
interface SecretMigrateInlineEnvOptions extends BaseClientOptions {
companyId?: string;
apply?: boolean;
}
interface SecretJsonOptions extends BaseClientOptions {
companyId?: string;
payloadJson?: string;
}
interface SecretProviderHealth {
provider: SecretProvider;
status: "ok" | "warn" | "error";
message: string;
warnings?: string[];
backupGuidance?: string[];
details?: Record<string, unknown>;
}
interface SecretProviderHealthResponse {
providers: SecretProviderHealth[];
}
export interface InlineSecretMigrationCandidate {
agentId: string;
agentName: string;
envKey: string;
secretName: string;
existingSecretId: string | null;
}
const SENSITIVE_ENV_KEY_RE =
/(^token$|[-_]?token$|api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i;
const DEFAULT_DECLARATION_INCLUDE: CompanyPortabilityInclude = {
company: true,
agents: true,
projects: true,
issues: false,
skills: false,
};
export function parseSecretsInclude(input: string | undefined): CompanyPortabilityInclude {
if (!input?.trim()) return { ...DEFAULT_DECLARATION_INCLUDE };
const values = input.split(",").map((part) => part.trim().toLowerCase()).filter(Boolean);
const include = {
company: values.includes("company"),
agents: values.includes("agents"),
projects: values.includes("projects"),
issues: values.includes("issues") || values.includes("tasks"),
skills: values.includes("skills"),
};
if (!Object.values(include).some(Boolean)) {
throw new Error("Invalid --include value. Use one or more of: company,agents,projects,issues,tasks,skills");
}
return include;
}
export function isSensitiveEnvKey(key: string): boolean {
return SENSITIVE_ENV_KEY_RE.test(key);
}
export function toPlainEnvValue(binding: unknown): string | null {
if (typeof binding === "string") return binding;
if (typeof binding !== "object" || binding === null || Array.isArray(binding)) return null;
const record = binding as Record<string, unknown>;
if (record.type === "plain" && typeof record.value === "string") return record.value;
return null;
}
export function buildInlineMigrationSecretName(agentId: string, key: string): string {
return `agent_${agentId.slice(0, 8)}_${key.toLowerCase()}`;
}
export function collectInlineSecretMigrationCandidates(
agents: Agent[],
existingSecrets: CompanySecret[],
): InlineSecretMigrationCandidate[] {
const secretByName = new Map(existingSecrets.map((secret) => [secret.name, secret]));
const candidates: InlineSecretMigrationCandidate[] = [];
for (const agent of agents) {
const env = asRecord(agent.adapterConfig.env);
if (!env) continue;
for (const [envKey, binding] of Object.entries(env)) {
if (!isSensitiveEnvKey(envKey)) continue;
const plain = toPlainEnvValue(binding);
if (plain === null || plain.trim().length === 0) continue;
const secretName = buildInlineMigrationSecretName(agent.id, envKey);
candidates.push({
agentId: agent.id,
agentName: agent.name,
envKey,
secretName,
existingSecretId: secretByName.get(secretName)?.id ?? null,
});
}
}
return candidates;
}
export function buildMigratedAgentEnv(
env: Record<string, unknown>,
secretIdByEnvKey: Map<string, string>,
): AgentEnvConfig {
const next: AgentEnvConfig = { ...(env as Record<string, EnvBinding>) };
for (const [envKey, secretId] of secretIdByEnvKey) {
next[envKey] = {
type: "secret_ref",
secretId,
version: "latest",
};
}
return next;
}
function asRecord(value: unknown): Record<string, unknown> | null {
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
return value as Record<string, unknown>;
}
function readValueFromOptions(opts: { value?: string; valueEnv?: string }): string {
if (opts.value !== undefined && opts.valueEnv !== undefined) {
throw new Error("Use only one of --value or --value-env.");
}
if (opts.valueEnv !== undefined) {
const value = process.env[opts.valueEnv];
if (!value) throw new Error(`Environment variable ${opts.valueEnv} is empty or unset.`);
return value;
}
if (opts.value !== undefined) return opts.value;
throw new Error("Secret value is required. Pass --value or --value-env.");
}
function renderDeclaration(input: CompanyPortabilityEnvInput): Record<string, unknown> {
const scope = input.agentSlug
? `agent:${input.agentSlug}`
: input.projectSlug
? `project:${input.projectSlug}`
: "company";
return {
key: input.key,
scope,
kind: input.kind,
requirement: input.requirement,
portability: input.portability,
hasDefault: input.defaultValue !== null && input.defaultValue.length > 0,
description: input.description,
};
}
function renderSecret(secret: CompanySecret): Record<string, unknown> {
return {
id: secret.id,
name: secret.name,
key: secret.key,
provider: secret.provider,
status: secret.status,
managedMode: secret.managedMode,
latestVersion: secret.latestVersion,
externalRef: secret.externalRef ? "yes" : "no",
};
}
function printProviderHealth(rows: SecretProviderHealth[], json: boolean): void {
if (json) {
printOutput(rows, { json: true });
return;
}
if (rows.length === 0) {
printOutput([], { json: false });
return;
}
for (const row of rows) {
console.log(
formatInlineRecord({
id: row.provider,
status: row.status,
message: row.message,
}),
);
for (const warning of row.warnings ?? []) {
console.log(pc.yellow(`warning=${warning}`));
}
const missingConfig = asStringArray(row.details?.missingConfig);
if (missingConfig.length > 0) {
console.log(pc.dim(`missingConfig=${missingConfig.join(",")}`));
}
const credentialSource = typeof row.details?.credentialSource === "string"
? row.details.credentialSource
: null;
if (credentialSource) {
console.log(pc.dim(`credentialSource=${credentialSource}`));
}
const detectedCredentialSources = asStringArray(row.details?.detectedCredentialSources);
if (detectedCredentialSources.length > 0) {
console.log(pc.dim(`detectedCredentialSources=${detectedCredentialSources.join(",")}`));
}
for (const guidance of row.backupGuidance ?? []) {
console.log(pc.dim(`backup=${guidance}`));
}
}
}
function asStringArray(value: unknown): string[] {
return Array.isArray(value)
? value.filter((entry): entry is string => typeof entry === "string" && entry.length > 0)
: [];
}
async function migrateInlineEnv(opts: SecretMigrateInlineEnvOptions): Promise<void> {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const companyId = ctx.companyId!;
const agents = (await ctx.api.get<Agent[]>(apiPath`/api/companies/${companyId}/agents`)) ?? [];
const secrets = (await ctx.api.get<CompanySecret[]>(apiPath`/api/companies/${companyId}/secrets`)) ?? [];
const candidates = collectInlineSecretMigrationCandidates(agents, secrets);
if (!opts.apply) {
printOutput(
{
apply: false,
agentsToUpdate: new Set(candidates.map((candidate) => candidate.agentId)).size,
secretsToCreate: candidates.filter((candidate) => !candidate.existingSecretId).length,
secretsToRotate: candidates.filter((candidate) => candidate.existingSecretId).length,
candidates,
},
{ json: ctx.json },
);
if (!ctx.json) {
console.log(pc.dim("Re-run with --apply to create/rotate secrets and update agent env bindings."));
}
return;
}
const createdOrRotated = new Map<string, string>();
let createdSecrets = 0;
let rotatedSecrets = 0;
for (const candidate of candidates) {
const agent = agents.find((row) => row.id === candidate.agentId);
const env = asRecord(agent?.adapterConfig.env);
const value = env ? toPlainEnvValue(env[candidate.envKey]) : null;
if (!value) continue;
if (candidate.existingSecretId) {
await ctx.api.post(apiPath`/api/secrets/${candidate.existingSecretId}/rotate`, { value });
createdOrRotated.set(`${candidate.agentId}:${candidate.envKey}`, candidate.existingSecretId);
rotatedSecrets += 1;
continue;
}
const created = await ctx.api.post<CompanySecret>(apiPath`/api/companies/${companyId}/secrets`, {
name: candidate.secretName,
provider: "local_encrypted",
value,
description: `Migrated from agent ${candidate.agentId} env ${candidate.envKey}`,
});
if (!created) throw new Error(`Secret create returned no data for ${candidate.secretName}`);
createdOrRotated.set(`${candidate.agentId}:${candidate.envKey}`, created.id);
createdSecrets += 1;
}
let updatedAgents = 0;
for (const agent of agents) {
const env = asRecord(agent.adapterConfig.env);
if (!env) continue;
const secretIdByEnvKey = new Map<string, string>();
for (const [key] of Object.entries(env)) {
const secretId = createdOrRotated.get(`${agent.id}:${key}`);
if (secretId) secretIdByEnvKey.set(key, secretId);
}
if (secretIdByEnvKey.size === 0) continue;
const adapterConfig = {
...agent.adapterConfig,
env: buildMigratedAgentEnv(env, secretIdByEnvKey),
};
await ctx.api.patch(apiPath`/api/agents/${agent.id}`, {
adapterConfig,
replaceAdapterConfig: true,
});
updatedAgents += 1;
}
printOutput(
{
apply: true,
updatedAgents,
createdSecrets,
rotatedSecrets,
},
{ json: ctx.json },
);
}
export function registerSecretCommands(program: Command): void {
const secrets = program.command("secrets").description("Secret declaration and provider operations");
addCommonClientOptions(
secrets
.command("list")
.description("List secret metadata for a company")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: SecretListOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const rows = (await ctx.api.get<CompanySecret[]>(apiPath`/api/companies/${ctx.companyId}/secrets`)) ?? [];
printOutput(ctx.json ? rows : rows.map(renderSecret), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("declarations")
.description("List portable env declarations emitted by company export")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--include <values>", "Comma-separated include set: company,agents,projects,issues,tasks,skills", "company,agents,projects")
.option("--kind <kind>", "Filter declarations: all | secret | plain", "all")
.action(async (opts: SecretDeclarationsOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const kind = opts.kind ?? "all";
if (!["all", "secret", "plain"].includes(kind)) {
throw new Error("Invalid --kind value. Use: all, secret, plain");
}
const preview = await ctx.api.post<CompanyPortabilityExportPreviewResult>(
apiPath`/api/companies/${ctx.companyId}/exports/preview`,
{ include: parseSecretsInclude(opts.include) },
);
const declarations = (preview?.manifest.envInputs ?? [])
.filter((entry) => kind === "all" || entry.kind === kind);
printOutput(ctx.json ? declarations : declarations.map(renderDeclaration), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("create")
.description("Create a Paperclip-managed secret")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--name <name>", "Secret display name")
.option("--key <key>", "Portable secret key")
.option("--provider <provider>", "Secret provider id")
.option("--value <value>", "Secret value")
.option("--value-env <name>", "Read secret value from an environment variable")
.option("--description <text>", "Description")
.action(async (opts: SecretCreateOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const created = await ctx.api.post<CompanySecret>(apiPath`/api/companies/${ctx.companyId}/secrets`, {
name: opts.name,
key: opts.key,
provider: opts.provider,
value: readValueFromOptions(opts),
description: opts.description,
});
printOutput(ctx.json ? created : renderSecret(created!), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("link")
.description("Link an external provider-owned secret without storing its value in Paperclip")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--name <name>", "Secret display name")
.requiredOption("--provider <provider>", "Secret provider id")
.requiredOption("--external-ref <ref>", "Provider secret ARN/name/path/reference")
.option("--key <key>", "Portable secret key")
.option("--provider-version-ref <ref>", "Provider version id or label")
.option("--description <text>", "Description")
.action(async (opts: SecretLinkOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const created = await ctx.api.post<CompanySecret>(apiPath`/api/companies/${ctx.companyId}/secrets`, {
name: opts.name,
key: opts.key,
provider: opts.provider,
managedMode: "external_reference",
externalRef: opts.externalRef,
providerVersionRef: opts.providerVersionRef,
description: opts.description,
});
printOutput(ctx.json ? created : renderSecret(created!), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("update")
.description("Update secret metadata")
.argument("<secretId>", "Secret ID")
.requiredOption("--payload-json <json>", "UpdateSecret JSON payload")
.action(async (secretId: string, opts: SecretUpdateOptions) => {
try {
const ctx = resolveCommandContext(opts);
printOutput(await ctx.api.patch(apiPath`/api/secrets/${secretId}`, parseJson(opts.payloadJson ?? "{}")), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("rotate")
.description("Rotate a Paperclip-managed secret value")
.argument("<secretId>", "Secret ID")
.option("--value <value>", "New secret value")
.option("--value-env <name>", "Read new secret value from an environment variable")
.action(async (secretId: string, opts: SecretRotateOptions) => {
try {
const ctx = resolveCommandContext(opts);
printOutput(await ctx.api.post(apiPath`/api/secrets/${secretId}/rotate`, { value: readValueFromOptions(opts) }), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("usage")
.description("Show where a secret is referenced")
.argument("<secretId>", "Secret ID")
.action(async (secretId: string, opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
printOutput(await ctx.api.get(apiPath`/api/secrets/${secretId}/usage`), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("access-events")
.description("List secret access events")
.argument("<secretId>", "Secret ID")
.action(async (secretId: string, opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
printOutput(await ctx.api.get(apiPath`/api/secrets/${secretId}/access-events`), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("delete")
.description("Delete a secret")
.argument("<secretId>", "Secret ID")
.option("--yes", "Required safety flag to confirm destructive action", false)
.option("--confirm <secretId>", "Repeat the secret ID to confirm deletion")
.action(async (secretId: string, opts: SecretDeleteOptions) => {
try {
if (!opts.yes) throw new Error("Deletion requires --yes.");
if (opts.confirm !== secretId) {
throw new Error("Deletion requires --confirm <secretId> matching the secret ID.");
}
const ctx = resolveCommandContext(opts);
printOutput(await ctx.api.delete(apiPath`/api/secrets/${secretId}`), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("doctor")
.description("Run secret provider health checks through the Paperclip API")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: SecretDoctorOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const health = await ctx.api.get<SecretProviderHealthResponse>(
apiPath`/api/companies/${ctx.companyId}/secret-providers/health`,
);
printProviderHealth(health?.providers ?? [], ctx.json);
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("providers")
.description("List configured secret provider descriptors")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: SecretDoctorOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const rows = (await ctx.api.get<SecretProviderDescriptor[]>(
apiPath`/api/companies/${ctx.companyId}/secret-providers`,
)) ?? [];
printOutput(rows, { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
secrets
.command("provider-configs")
.description("List company secret provider vault configs")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: SecretDoctorOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
printOutput(await ctx.api.get(apiPath`/api/companies/${ctx.companyId}/secret-provider-configs`), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
addCompanySecretJsonPost(secrets, "provider-config:create", "Create a secret provider vault config", "secret-provider-configs");
addCompanySecretJsonPost(
secrets,
"provider-config:discovery-preview",
"Preview provider vault secret discovery",
"secret-provider-configs/discovery/preview",
);
addSecretProviderConfigGet(secrets, "provider-config:get", "Get a secret provider vault config", "");
addSecretProviderConfigPatch(secrets, "provider-config:update", "Update a secret provider vault config", "");
addSecretProviderConfigPost(secrets, "provider-config:default", "Set the default provider vault config", "default");
addSecretProviderConfigPost(secrets, "provider-config:health", "Check provider vault health", "health");
addSecretProviderConfigDelete(secrets, "provider-config:delete", "Delete a secret provider vault config");
addCompanySecretJsonPost(secrets, "remote-import:preview", "Preview remote secret import", "secrets/remote-import/preview");
addCompanySecretJsonPost(secrets, "remote-import", "Import selected remote secrets", "secrets/remote-import");
addCommonClientOptions(
secrets
.command("migrate-inline-env")
.description("Migrate inline sensitive agent env values into secret references")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--apply", "Persist changes; default is a dry run", false)
.action(async (opts: SecretMigrateInlineEnvOptions) => {
try {
await migrateInlineEnv(opts);
} catch (err) {
handleCommandError(err);
}
}),
);
}
function addCompanySecretJsonPost(parent: Command, name: string, description: string, path: string): void {
addCommonClientOptions(
parent
.command(name)
.description(description)
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--payload-json <json>", "JSON payload")
.action(async (opts: SecretJsonOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
printOutput(await ctx.api.post(`${apiPath`/api/companies/${ctx.companyId}`}/${path}`, parseJson(opts.payloadJson ?? "{}")), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
}
function addSecretProviderConfigGet(parent: Command, name: string, description: string, suffix: string): void {
addCommonClientOptions(
parent
.command(name)
.description(description)
.argument("<configId>", "Provider config ID")
.action(async (configId: string, opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
printOutput(await ctx.api.get(`${apiPath`/api/secret-provider-configs/${configId}`}${suffix ? `/${suffix}` : ""}`), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
}
function addSecretProviderConfigPatch(parent: Command, name: string, description: string, suffix: string): void {
addCommonClientOptions(
parent
.command(name)
.description(description)
.argument("<configId>", "Provider config ID")
.requiredOption("--payload-json <json>", "JSON payload")
.action(async (configId: string, opts: SecretJsonOptions) => {
try {
const ctx = resolveCommandContext(opts);
printOutput(await ctx.api.patch(`${apiPath`/api/secret-provider-configs/${configId}`}${suffix ? `/${suffix}` : ""}`, parseJson(opts.payloadJson ?? "{}")), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
}
function addSecretProviderConfigPost(parent: Command, name: string, description: string, suffix: string): void {
addCommonClientOptions(
parent
.command(name)
.description(description)
.argument("<configId>", "Provider config ID")
.action(async (configId: string, opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
printOutput(await ctx.api.post(`${apiPath`/api/secret-provider-configs/${configId}`}/${suffix}`, {}), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
}
function addSecretProviderConfigDelete(parent: Command, name: string, description: string): void {
addCommonClientOptions(
parent
.command(name)
.description(description)
.argument("<configId>", "Provider config ID")
.action(async (configId: string, opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
printOutput(await ctx.api.delete(apiPath`/api/secret-provider-configs/${configId}`), { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
}
function parseJson(value: string): unknown {
return JSON.parse(value) as unknown;
}