Files
Primora/apps/cli/src/commands/context.ts
T
Tomas DvorakandDevin 2d6135121e security: harden agent surface — vault_exec allow-list, SSRF, error hygiene
Stress-test remediation across MCP, CLI, and backend:

- primora_vault_exec rewritten as an allow-list (was deny-list):
  colon-form single-token commands bypassed it, leaking every vault
  secret; verbatim env-name injection allowed NODE_OPTIONS=--require
  host RCE. Now fixed read-mostly command set, arg/path deny regex,
  strict env-name grammar, loader-hook name blocklist. All prior
  bypasses verified denied; allowed commands still inject.
- SSRF: webhook/job URL validation now blocks cloud metadata IPs
  (169.254.169.254, fd00:ec2::254) inside the link-local allowance
  and non-canonical IP encodings (decimal/hex bare hosts) smuggled
  as "docker service names".
- Path params encodeURIComponent in all client consumers — encodeURI
  left ?#& intact, smuggling query segments through {name} params.
- primora_upload_object strict-validates contentBase64 — Buffer.from
  silently dropped invalid chars.
- MCP no-creds startup degrades instead of crashing mid-handshake.
- GET /api/v1/context — API-key self-discovery; fixes the CLI dead
  end (login --api-key validates the key + seeds org/project,
  use/context/whoami work under key auth).
- CLI: unknown commands / bare group exit 1 with hints; mri numeric
  coercion reversed via raw-argv restore (007 stays "007");
  login --json; orgs:rm / projects:rm / buckets:rm behind --yes;
  fetch-failed errors name the cause.
- Error hygiene: pgx.ErrNoRows -> 404, pgconn codes -> clean
  400/409 without SQLSTATE leaks, validator failures formatted,
  services.InputError maps input faults to 400 (webhook URL/event
  errors were 500s), presign on local driver -> 400.
- Webhook events accept wildcard patterns (*, ns.*, custom.*)
  matched via SQL LIKE — client-published events can be webhooked.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-24 21:56:11 +02:00

128 lines
4.7 KiB
TypeScript

import * as p from "@clack/prompts";
import { PlatformService } from "@primora/api-client";
import { loadConfig, saveConfig } from "../config.js";
import { configureClient, requireAuth } from "../http.js";
import { dim, isJson, printJson, success } from "../out.js";
interface UseOptions {
org?: string;
project?: string;
}
/** Match an id or slug against a {id, slug, name} record. */
function matchRef<T extends { id: string; slug: string; name: string }>(
items: T[],
ref: string,
): T | undefined {
return items.find((i) => i.id === ref || i.slug === ref || i.name === ref);
}
export async function cmdUse(options: UseOptions): Promise<void> {
const cfg = loadConfig();
requireAuth(cfg);
configureClient(cfg);
// API keys are bound to one org+project — resolve the scope directly.
if (cfg.auth?.type === "apiKey") {
const ctx = await PlatformService.getActorContext();
if (options.org && ctx.organization && options.org !== ctx.organization.id && options.org !== ctx.organization.slug) {
throw new Error(`API key is scoped to ${ctx.organization.slug} — cannot switch to "${options.org}".`);
}
if (options.project && ctx.project && options.project !== ctx.project.id && options.project !== ctx.project.slug) {
throw new Error(`API key is scoped to ${ctx.project.slug} — cannot switch to "${options.project}".`);
}
if (ctx.organization) cfg.organizationId = ctx.organization.id;
if (ctx.project) cfg.projectId = ctx.project.id;
saveConfig(cfg);
success(`Context → ${ctx.organization?.slug ?? "—"} / ${ctx.project?.slug ?? "—"}`);
return;
}
const me = await PlatformService.getMe();
const orgs = me.organizations;
if (orgs.length === 0) {
dim("No organizations yet — create one with `primora orgs create <name>`.");
return;
}
if (options.org) {
const org = matchRef(orgs, options.org);
if (!org) throw new Error(`Organization "${options.org}" not found.`);
cfg.organizationId = org.id;
if (!org.projects.some((pr) => pr.id === cfg.projectId)) delete cfg.projectId;
} else if (process.stdin.isTTY) {
const picked = await p.select({
message: "Organization",
options: orgs.map((o) => ({ value: o.id, label: o.name, hint: o.slug })),
initialValue: cfg.organizationId,
});
if (p.isCancel(picked)) return;
cfg.organizationId = picked;
if (!orgs.find((o) => o.id === picked)?.projects.some((pr) => pr.id === cfg.projectId)) {
delete cfg.projectId;
}
}
const org = orgs.find((o) => o.id === cfg.organizationId);
if (!org) throw new Error("No organization selected.");
if (options.project) {
const project = matchRef(org.projects, options.project);
if (!project) throw new Error(`Project "${options.project}" not found in ${org.name}.`);
cfg.projectId = project.id;
} else if (process.stdin.isTTY && org.projects.length > 0) {
const picked = await p.select({
message: "Project",
options: org.projects.map((pr) => ({ value: pr.id, label: pr.name, hint: pr.slug })),
initialValue: cfg.projectId,
});
if (p.isCancel(picked)) {
saveConfig(cfg);
return;
}
cfg.projectId = picked;
}
saveConfig(cfg);
success(`Context → ${org.slug}${cfg.projectId ? ` / ${org.projects.find((pr) => pr.id === cfg.projectId)?.slug ?? cfg.projectId}` : ""}`);
}
export async function cmdContext(options: { json?: boolean }): Promise<void> {
const cfg = loadConfig();
requireAuth(cfg);
configureClient(cfg);
if (cfg.auth?.type === "apiKey") {
const ctx = await PlatformService.getActorContext();
if (isJson(options)) {
printJson({ baseUrl: cfg.baseUrl, auth: "apiKey", ...ctx });
return;
}
dim(`url ${cfg.baseUrl}`);
dim(`auth api_key (${ctx.key_prefix}…, scopes: ${ctx.scopes?.join(", ") || "none"})`);
process.stdout.write(`org ${ctx.organization ? `${ctx.organization.name} (${ctx.organization.slug})` : "—"}\n`);
process.stdout.write(`project ${ctx.project ? `${ctx.project.name} (${ctx.project.slug})` : "—"}\n`);
return;
}
const me = await PlatformService.getMe();
const org = me.organizations.find((o) => o.id === cfg.organizationId);
const project = org?.projects.find((pr) => pr.id === cfg.projectId);
if (isJson(options)) {
printJson({
baseUrl: cfg.baseUrl,
auth: cfg.auth?.type ?? null,
organization: org ?? null,
project: project ?? null,
});
return;
}
dim(`url ${cfg.baseUrl}`);
dim(`auth ${cfg.auth?.type ?? "none"}`);
process.stdout.write(`org ${org ? `${org.name} (${org.slug})` : "—"}\n`);
process.stdout.write(`project ${project ? `${project.name} (${project.slug})` : "—"}\n`);
}