@openape/apes 1.28.12 → 1.28.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-DYSFQ26B.js → chunk-PEA2RDWK.js} +6 -153
- package/dist/chunk-PEA2RDWK.js.map +1 -0
- package/dist/cli.js +8 -8
- package/dist/index.js +1 -1
- package/dist/{orchestrator-BDX3WK7Q.js → orchestrator-REICEX3F.js} +2 -2
- package/dist/{server-OAINN75J.js → server-JGX5FIDP.js} +3 -3
- package/package.json +5 -5
- package/dist/chunk-DYSFQ26B.js.map +0 -1
- /package/dist/{orchestrator-BDX3WK7Q.js.map → orchestrator-REICEX3F.js.map} +0 -0
- /package/dist/{server-OAINN75J.js.map → server-JGX5FIDP.js.map} +0 -0
|
@@ -614,132 +614,7 @@ function resolveCapabilityRequest(loaded, params) {
|
|
|
614
614
|
}
|
|
615
615
|
|
|
616
616
|
// src/shapes/parser.ts
|
|
617
|
-
import {
|
|
618
|
-
function parseOptionArgs(tokens, valueOptions) {
|
|
619
|
-
const options = {};
|
|
620
|
-
const positionals = [];
|
|
621
|
-
const takesValue = new Set(valueOptions ?? []);
|
|
622
|
-
for (let index = 0; index < tokens.length; index += 1) {
|
|
623
|
-
const token = tokens[index];
|
|
624
|
-
if (token.startsWith("--")) {
|
|
625
|
-
const stripped = token.slice(2);
|
|
626
|
-
const eqIndex = stripped.indexOf("=");
|
|
627
|
-
if (eqIndex >= 0) {
|
|
628
|
-
options[stripped.slice(0, eqIndex)] = stripped.slice(eqIndex + 1);
|
|
629
|
-
continue;
|
|
630
|
-
}
|
|
631
|
-
const next = tokens[index + 1];
|
|
632
|
-
if (next && !next.startsWith("-")) {
|
|
633
|
-
options[stripped] = next;
|
|
634
|
-
index += 1;
|
|
635
|
-
continue;
|
|
636
|
-
}
|
|
637
|
-
options[stripped] = "true";
|
|
638
|
-
} else if (token.startsWith("-") && token.length > 1 && !/^-\d/.test(token)) {
|
|
639
|
-
const key = token.slice(1);
|
|
640
|
-
if (key.length === 1 && !takesValue.has(key)) {
|
|
641
|
-
options[key] = "true";
|
|
642
|
-
} else {
|
|
643
|
-
const next = tokens[index + 1];
|
|
644
|
-
if (next && !next.startsWith("-")) {
|
|
645
|
-
options[key] = next;
|
|
646
|
-
index += 1;
|
|
647
|
-
} else {
|
|
648
|
-
options[key] = "true";
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
} else {
|
|
652
|
-
positionals.push(token);
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
return { options, positionals };
|
|
656
|
-
}
|
|
657
|
-
function resolveBindingToken(binding, bindings) {
|
|
658
|
-
const match = binding.match(/^\{([^}|]+)(?:\|([^}]+))?\}$/);
|
|
659
|
-
if (!match)
|
|
660
|
-
return binding;
|
|
661
|
-
const [, name, transform] = match;
|
|
662
|
-
const value = bindings[name];
|
|
663
|
-
if (!value)
|
|
664
|
-
throw new Error(`Missing binding: ${name}`);
|
|
665
|
-
if (!transform)
|
|
666
|
-
return value;
|
|
667
|
-
if (transform === "owner" || transform === "name") {
|
|
668
|
-
const [owner, repo] = value.split("/");
|
|
669
|
-
if (!owner || !repo)
|
|
670
|
-
throw new Error(`Binding ${name} must be in owner/name form`);
|
|
671
|
-
return transform === "owner" ? owner : repo;
|
|
672
|
-
}
|
|
673
|
-
throw new Error(`Unsupported binding transform: ${transform}`);
|
|
674
|
-
}
|
|
675
|
-
function renderTemplate(template, bindings) {
|
|
676
|
-
return template.replace(/\{([^}]+)\}/g, (_, expression) => resolveBindingToken(`{${expression}}`, bindings));
|
|
677
|
-
}
|
|
678
|
-
function parseResourceChain(chain, bindings) {
|
|
679
|
-
return chain.map((entry) => {
|
|
680
|
-
const [resource, selectorSpec = "*"] = entry.split(":", 2);
|
|
681
|
-
if (!resource)
|
|
682
|
-
throw new Error(`Invalid resource chain entry: ${entry}`);
|
|
683
|
-
if (selectorSpec === "*") {
|
|
684
|
-
return { resource };
|
|
685
|
-
}
|
|
686
|
-
const selector = Object.fromEntries(
|
|
687
|
-
selectorSpec.split(",").map((segment) => {
|
|
688
|
-
const [key, rawValue] = segment.split("=", 2);
|
|
689
|
-
if (!key || !rawValue)
|
|
690
|
-
throw new Error(`Invalid selector segment: ${segment}`);
|
|
691
|
-
return [key, renderTemplate(rawValue, bindings)];
|
|
692
|
-
})
|
|
693
|
-
);
|
|
694
|
-
return { resource, selector };
|
|
695
|
-
});
|
|
696
|
-
}
|
|
697
|
-
function matchOperation(operation, argv) {
|
|
698
|
-
if (argv.length < operation.command.length)
|
|
699
|
-
return null;
|
|
700
|
-
const prefix = argv.slice(0, operation.command.length);
|
|
701
|
-
if (prefix.join("\0") !== operation.command.join("\0"))
|
|
702
|
-
return null;
|
|
703
|
-
const remainder = argv.slice(operation.command.length);
|
|
704
|
-
const { options, positionals } = parseOptionArgs(remainder, operation.required_options);
|
|
705
|
-
const expectedPositionals = operation.positionals ?? [];
|
|
706
|
-
if (positionals.length !== expectedPositionals.length)
|
|
707
|
-
return null;
|
|
708
|
-
for (const option of operation.required_options ?? []) {
|
|
709
|
-
if (!options[option])
|
|
710
|
-
return null;
|
|
711
|
-
}
|
|
712
|
-
const bindings = { ...options };
|
|
713
|
-
for (let index = 0; index < expectedPositionals.length; index += 1) {
|
|
714
|
-
const name = expectedPositionals[index];
|
|
715
|
-
const value = positionals[index];
|
|
716
|
-
if (name.startsWith("=")) {
|
|
717
|
-
if (value !== name.slice(1))
|
|
718
|
-
return null;
|
|
719
|
-
continue;
|
|
720
|
-
}
|
|
721
|
-
bindings[name] = value;
|
|
722
|
-
}
|
|
723
|
-
return bindings;
|
|
724
|
-
}
|
|
725
|
-
function expandCombinedFlags(argv) {
|
|
726
|
-
return argv.flatMap((token) => {
|
|
727
|
-
if (token.startsWith("-") && !token.startsWith("--") && token.length > 2 && /^-[a-z]+$/i.test(token)) {
|
|
728
|
-
return Array.from(token.slice(1), (c) => `-${c}`);
|
|
729
|
-
}
|
|
730
|
-
return [token];
|
|
731
|
-
});
|
|
732
|
-
}
|
|
733
|
-
function tryMatch(operations, argv) {
|
|
734
|
-
return operations.flatMap((operation) => {
|
|
735
|
-
try {
|
|
736
|
-
const bindings = matchOperation(operation, argv);
|
|
737
|
-
return bindings ? [{ operation, bindings }] : [];
|
|
738
|
-
} catch {
|
|
739
|
-
return [];
|
|
740
|
-
}
|
|
741
|
-
});
|
|
742
|
-
}
|
|
617
|
+
import { buildCliAuthDetail, computeArgvHash as computeArgvHash2, matchArgvToOperation } from "@openape/grants";
|
|
743
618
|
async function resolveCommand(loaded, fullArgv) {
|
|
744
619
|
const [executable, ...commandArgv] = fullArgv;
|
|
745
620
|
if (!executable) {
|
|
@@ -748,34 +623,12 @@ async function resolveCommand(loaded, fullArgv) {
|
|
|
748
623
|
if (executable !== loaded.adapter.cli.executable) {
|
|
749
624
|
throw new Error(`Adapter ${loaded.adapter.cli.id} expects executable ${loaded.adapter.cli.executable}, got ${executable}`);
|
|
750
625
|
}
|
|
751
|
-
|
|
752
|
-
if (
|
|
753
|
-
const expanded = expandCombinedFlags(commandArgv);
|
|
754
|
-
if (expanded.length !== commandArgv.length) {
|
|
755
|
-
matches = tryMatch(loaded.adapter.operations, expanded);
|
|
756
|
-
}
|
|
757
|
-
}
|
|
758
|
-
if (matches.length === 0) {
|
|
626
|
+
const match = matchArgvToOperation(loaded.adapter.operations, commandArgv);
|
|
627
|
+
if (!match) {
|
|
759
628
|
throw new Error(`No adapter operation matched: ${fullArgv.join(" ")}`);
|
|
760
629
|
}
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
matches = [matches[0]];
|
|
764
|
-
}
|
|
765
|
-
const { operation, bindings } = matches[0];
|
|
766
|
-
const resource_chain = parseResourceChain(operation.resource_chain, bindings);
|
|
767
|
-
const detail = {
|
|
768
|
-
type: "openape_cli",
|
|
769
|
-
cli_id: loaded.adapter.cli.id,
|
|
770
|
-
operation_id: operation.id,
|
|
771
|
-
resource_chain,
|
|
772
|
-
action: operation.action,
|
|
773
|
-
permission: "",
|
|
774
|
-
display: renderTemplate(operation.display, bindings),
|
|
775
|
-
risk: operation.risk,
|
|
776
|
-
...operation.exact_command ? { constraints: { exact_command: true } } : {}
|
|
777
|
-
};
|
|
778
|
-
detail.permission = canonicalizeCliPermission3(detail);
|
|
630
|
+
const { operation, bindings } = match;
|
|
631
|
+
const detail = buildCliAuthDetail(loaded.adapter.cli.id, operation, bindings);
|
|
779
632
|
return {
|
|
780
633
|
adapter: loaded.adapter,
|
|
781
634
|
source: loaded.source,
|
|
@@ -1212,4 +1065,4 @@ export {
|
|
|
1212
1065
|
buildExactCommandGrantRequest,
|
|
1213
1066
|
buildStructuredCliGrantRequest
|
|
1214
1067
|
};
|
|
1215
|
-
//# sourceMappingURL=chunk-
|
|
1068
|
+
//# sourceMappingURL=chunk-PEA2RDWK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/shapes/adapters.ts","../src/shapes/toml.ts","../src/shapes/generic.ts","../src/shapes/audit.ts","../src/shapes/installer.ts","../src/shapes/registry.ts","../src/shapes/shell-parser.ts","../src/shapes/capabilities.ts","../src/shapes/parser.ts","../src/shapes/commands/explain.ts","../src/shapes/grants.ts","../src/shapes/config.ts","../src/shapes/http.ts","../src/audit/generic-log.ts","../src/shapes/request-builders.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { basename, join } from 'node:path'\nimport type { LoadedAdapter, ResolvedCommand } from './types.js'\nimport { parseAdapterToml } from './toml.js'\nimport { buildGenericResolved } from './generic.js'\n\nfunction digest(content: string): string {\n return `SHA-256:${createHash('sha256').update(content).digest('hex')}`\n}\n\nfunction adapterDirs(): string[] {\n return [\n join(process.cwd(), '.openape', 'shapes', 'adapters'),\n join(homedir(), '.openape', 'shapes', 'adapters'),\n join('/etc', 'openape', 'shapes', 'adapters'),\n ]\n}\n\nfunction findByExecutable(executable: string): string | undefined {\n for (const dir of adapterDirs()) {\n if (!existsSync(dir))\n continue\n try {\n const files = readdirSync(dir).filter(f => f.endsWith('.toml'))\n for (const file of files) {\n const path = join(dir, file)\n const content = readFileSync(path, 'utf-8')\n const match = content.match(/^\\s*executable\\s*=\\s*\"([^\"]+)\"/m)\n if (match && match[1] === executable)\n return path\n }\n }\n catch {\n // directory not readable\n }\n }\n return undefined\n}\n\nexport function resolveAdapterPath(cliId: string, explicitPath?: string): string {\n if (explicitPath) {\n if (existsSync(explicitPath))\n return explicitPath\n throw new Error(`Adapter file not found: ${explicitPath}`)\n }\n\n // Try direct lookup by ID\n const candidates = adapterDirs().map(dir => join(dir, `${cliId}.toml`))\n const match = candidates.find(path => existsSync(path))\n if (match)\n return match\n\n // Fallback: scan for adapter with matching executable name\n const byExec = findByExecutable(cliId)\n if (byExec)\n return byExec\n\n throw new Error(`No adapter found for ${cliId}`)\n}\n\nexport function loadAdapter(cliId: string, explicitPath?: string): LoadedAdapter {\n const source = resolveAdapterPath(cliId, explicitPath)\n const content = readFileSync(source, 'utf-8')\n const adapter = parseAdapterToml(content)\n\n // Accept if either the adapter ID or the executable matches the requested cliId\n const idMatch = adapter.cli.id === cliId\n const fileMatch = basename(source) === `${cliId}.toml`\n const execMatch = adapter.cli.executable === cliId\n if (!idMatch && !fileMatch && !execMatch)\n throw new Error(`Adapter ${source} does not match requested CLI ${cliId}`)\n\n return {\n adapter,\n source,\n digest: digest(content),\n }\n}\n\n/**\n * Called by `run.ts` when `loadAdapter(cliId)` has already failed with\n * \"No adapter found\". If generic-fallback mode is enabled in config,\n * return a synthetic `ResolvedCommand` that bypasses the parser. If\n * disabled, re-throw the original error (restoring legacy behaviour).\n *\n * @param cliId The CLI that had no registered shape\n * @param fullArgv Argv to execute (including the executable itself)\n * @param opts `genericEnabled: true` → return synthetic resolved;\n * `false` → throw `\"No adapter found for <cliId>\"`.\n */\nexport async function resolveGenericOrReject(\n cliId: string,\n fullArgv: string[],\n opts: { genericEnabled: boolean },\n): Promise<ResolvedCommand> {\n if (!opts.genericEnabled)\n throw new Error(`No adapter found for ${cliId}`)\n return await buildGenericResolved(cliId, fullArgv)\n}\n\n/** Try to load an adapter locally, return null instead of throwing when not found. */\nexport function tryLoadAdapter(cliId: string, explicitPath?: string): LoadedAdapter | null {\n try {\n return loadAdapter(cliId, explicitPath)\n }\n catch {\n return null\n }\n}\n","import type { ShapesAdapter, ShapesOperation } from './types.js'\n\ninterface AdapterTomlFile {\n schema?: string\n cli?: ShapesAdapter['cli']\n operation?: ShapesOperation[]\n}\n\nfunction parseKeyValue(line: string): { key: string, value: string } | null {\n const eqIndex = line.indexOf('=')\n if (eqIndex === -1)\n return null\n const key = line.slice(0, eqIndex).trim()\n const value = line.slice(eqIndex + 1).trim()\n if (!key || !value)\n return null\n return { key, value }\n}\n\nfunction parseTomlValue(raw: string): unknown {\n const trimmed = raw.trim()\n\n if (trimmed.startsWith('\"') && trimmed.endsWith('\"'))\n return trimmed.slice(1, -1)\n if (trimmed === 'true')\n return true\n if (trimmed === 'false')\n return false\n if (trimmed.startsWith('[') && trimmed.endsWith(']')) {\n const inner = trimmed.slice(1, -1).trim()\n if (!inner)\n return []\n return inner.split(',').map(value => value.trim().replace(/^\"|\"$/g, ''))\n }\n\n return trimmed\n}\n\nexport function parseAdapterToml(content: string): ShapesAdapter {\n const result: AdapterTomlFile = {}\n const operations: ShapesOperation[] = []\n let currentSection: 'root' | 'cli' | 'operation' = 'root'\n let currentEntry: Record<string, unknown> = {}\n\n const flushOperation = () => {\n if (currentSection === 'operation' && Object.keys(currentEntry).length > 0) {\n operations.push(currentEntry as unknown as ShapesOperation)\n currentEntry = {}\n }\n }\n\n for (const rawLine of content.split('\\n')) {\n const line = rawLine.trim()\n if (!line || line.startsWith('#'))\n continue\n\n if (line === '[cli]') {\n flushOperation()\n currentSection = 'cli'\n result.cli = {} as ShapesAdapter['cli']\n continue\n }\n\n if (line === '[[operation]]') {\n flushOperation()\n currentSection = 'operation'\n currentEntry = {}\n continue\n }\n\n const kv = parseKeyValue(line)\n if (!kv)\n continue\n\n const value = parseTomlValue(kv.value)\n if (currentSection === 'root') {\n ;(result as Record<string, unknown>)[kv.key] = value\n }\n else if (currentSection === 'cli') {\n ;(result.cli as Record<string, unknown>)[kv.key] = value\n }\n else {\n currentEntry[kv.key] = value\n }\n }\n\n flushOperation()\n result.operation = operations\n\n if (result.schema !== 'openape-shapes/v1') {\n throw new Error(`Unsupported adapter schema: ${result.schema ?? 'missing'}`)\n }\n if (!result.cli?.id || !result.cli.executable) {\n throw new Error('Adapter is missing cli.id or cli.executable')\n }\n if (!result.operation?.length) {\n throw new Error('Adapter must define at least one [[operation]] entry')\n }\n\n return {\n schema: result.schema,\n cli: {\n id: String(result.cli.id),\n executable: String(result.cli.executable),\n ...(result.cli.audience ? { audience: String(result.cli.audience) } : {}),\n ...(result.cli.version ? { version: String(result.cli.version) } : {}),\n },\n operations: result.operation.map((operation) => {\n if (!Array.isArray(operation.command) || operation.command.some(token => typeof token !== 'string')) {\n throw new Error(`Operation ${String(operation.id ?? '<unknown>')} is missing command[]`)\n }\n if (!Array.isArray(operation.resource_chain) || operation.resource_chain.some(token => typeof token !== 'string')) {\n throw new Error(`Operation ${String(operation.id ?? '<unknown>')} is missing resource_chain[]`)\n }\n if (typeof operation.id !== 'string' || typeof operation.display !== 'string' || typeof operation.action !== 'string') {\n throw new TypeError('Operation must define id, display, and action')\n }\n return {\n id: operation.id,\n command: operation.command as string[],\n ...(Array.isArray(operation.positionals) ? { positionals: operation.positionals as string[] } : {}),\n ...(Array.isArray(operation.required_options) ? { required_options: operation.required_options as string[] } : {}),\n display: operation.display,\n action: operation.action,\n risk: (operation.risk as ShapesOperation['risk']) || 'low',\n resource_chain: operation.resource_chain as string[],\n ...(operation.exact_command !== undefined ? { exact_command: Boolean(operation.exact_command) } : {}),\n }\n }),\n }\n}\n","import type { OpenApeCliAuthorizationDetail } from '@openape/core'\nimport { canonicalizeCliPermission, computeArgvHash } from '@openape/grants'\nimport type { LoadedAdapter, ResolvedCommand, ShapesAdapter } from './types.js'\n\n/**\n * The synthetic operation ID used for generic-fallback grants. Downstream\n * code (audit logging, UI banner) keys off this exact string.\n */\nexport const GENERIC_OPERATION_ID = '_generic.exec'\n\n/**\n * Schema version for synthetic adapters. Not persisted anywhere — exists\n * only so the in-memory adapter shape matches `ShapesAdapter`.\n */\nconst SYNTHETIC_SCHEMA = 'openape-shapes/v1'\n\n/**\n * Build a synthetic in-memory `LoadedAdapter` for a CLI that has no\n * registered shape. The adapter is marked with `synthetic: true` so\n * callers can branch on it if needed.\n *\n * NOTE: This does NOT produce a parser-matchable adapter. The generic\n * pipeline bypasses `resolveCommand()` entirely — see `buildGenericResolved()`.\n * This function exists for flow-control markers and tests.\n */\nexport function buildGenericAdapter(cliId: string): LoadedAdapter {\n const adapter: ShapesAdapter = {\n schema: SYNTHETIC_SCHEMA,\n cli: {\n id: cliId,\n executable: cliId,\n audience: 'shapes',\n version: 'synthetic',\n },\n operations: [],\n }\n return {\n adapter,\n source: '<synthetic>',\n digest: 'synthetic',\n synthetic: true,\n }\n}\n\n/**\n * Build a `ResolvedCommand` directly for a CLI that has no registered shape.\n *\n * Unlike the normal flow (loadAdapter → resolveCommand), the generic path\n * bypasses the parser entirely. Rationale:\n *\n * - `resolveCommand()` matches argv against declarative operation specs\n * via `matchOperation()`, which requires `positionals.length ===\n * operation.positionals.length`. A \"match-all\" spec (`command: []`,\n * `positionals: []`) would reject any non-empty argv.\n *\n * - Synthetic adapters have no declarative spec — we already know what\n * to execute. Running the parser is theatre.\n *\n * The returned `ResolvedCommand` has:\n * - `detail.operation_id === GENERIC_OPERATION_ID` — marker consumed by\n * the audit-log hook in `verifyAndExecute`.\n * - `detail.risk === 'high'` — forced.\n * - `detail.constraints.exact_command === true` — forced, binds the\n * grant to this exact argv via `argv_hash`.\n * - `resource_chain = [{resource: 'cli', selector: {name: cliId}},\n * {resource: 'argv', selector: {hash: <sha256>}}]`\n */\nexport async function buildGenericResolved(\n cliId: string,\n fullArgv: string[],\n): Promise<ResolvedCommand> {\n if (fullArgv.length === 0)\n throw new Error('buildGenericResolved: fullArgv must include the executable')\n const executable = fullArgv[0]!\n const commandArgv = fullArgv.slice(1)\n const argvHash = await computeArgvHash(fullArgv)\n\n const display = `Execute (unshaped): \\`${cliId} ${commandArgv.join(' ')}\\``\n\n const detail: OpenApeCliAuthorizationDetail = {\n type: 'openape_cli',\n cli_id: cliId,\n operation_id: GENERIC_OPERATION_ID,\n resource_chain: [\n { resource: 'cli', selector: { name: cliId } },\n { resource: 'argv', selector: { hash: argvHash } },\n ],\n action: 'exec',\n permission: '',\n display,\n risk: 'high',\n constraints: { exact_command: true },\n }\n detail.permission = canonicalizeCliPermission(detail)\n\n const adapter = buildGenericAdapter(cliId)\n\n return {\n adapter: adapter.adapter,\n source: adapter.source,\n digest: adapter.digest,\n executable,\n commandArgv,\n bindings: {},\n detail,\n executionContext: {\n argv: fullArgv,\n argv_hash: argvHash,\n adapter_id: cliId,\n adapter_version: SYNTHETIC_SCHEMA,\n adapter_digest: adapter.digest,\n resolved_executable: executable,\n context_bindings: {},\n },\n permission: detail.permission,\n }\n}\n\n/**\n * Type guard: does this `ResolvedCommand` come from the generic fallback path?\n */\nexport function isGenericResolved(resolved: ResolvedCommand): boolean {\n return resolved.detail.operation_id === GENERIC_OPERATION_ID\n}\n","import { appendFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\n\n/** Single audit log entry. Always includes a timestamp and an action string. */\nexport interface AuditEntry {\n action: string\n timestamp: number\n [key: string]: unknown\n}\n\nfunction auditPath(): string {\n return join(homedir(), '.config', 'apes', 'audit.jsonl')\n}\n\n/**\n * Append a single entry to the audit log at ~/.config/apes/audit.jsonl.\n * Failures are swallowed — the audit log should never break the actual flow.\n */\nexport function appendAuditLog(entry: { action: string, timestamp?: number } & Record<string, unknown>): void {\n const full: AuditEntry = {\n ...entry,\n action: entry.action,\n timestamp: entry.timestamp ?? Date.now(),\n }\n const path = auditPath()\n const dir = dirname(path)\n try {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n appendFileSync(path, `${JSON.stringify(full)}\\n`)\n }\n catch {\n // intentionally ignored — audit log must never break the flow\n }\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { RegistryEntry } from './types.js'\n\nfunction adapterDir(local: boolean): string {\n const base = local ? process.cwd() : homedir()\n return join(base, '.openape', 'shapes', 'adapters')\n}\n\nfunction adapterPath(id: string, local: boolean): string {\n return join(adapterDir(local), `${id}.toml`)\n}\n\nfunction sha256(content: string): string {\n return `SHA-256:${createHash('sha256').update(content).digest('hex')}`\n}\n\nexport interface InstallResult {\n id: string\n path: string\n digest: string\n updated: boolean\n}\n\nexport async function installAdapter(entry: RegistryEntry, options: { local?: boolean } = {}): Promise<InstallResult> {\n const local = options.local ?? false\n const dest = adapterPath(entry.id, local)\n const dir = adapterDir(local)\n\n const response = await fetch(entry.download_url)\n if (!response.ok)\n throw new Error(`Failed to download adapter ${entry.id}: ${response.status} ${response.statusText}`)\n\n const content = await response.text()\n const digest = sha256(content)\n\n if (digest !== entry.digest)\n throw new Error(`Digest mismatch for ${entry.id}: expected ${entry.digest}, got ${digest}`)\n\n const updated = existsSync(dest)\n\n if (!existsSync(dir))\n mkdirSync(dir, { recursive: true })\n\n writeFileSync(dest, content)\n\n return { id: entry.id, path: dest, digest, updated }\n}\n\nexport function getInstalledDigest(id: string, local: boolean): string | null {\n const path = adapterPath(id, local)\n if (!existsSync(path))\n return null\n\n const content = readFileSync(path, 'utf-8')\n return sha256(content)\n}\n\nexport function isInstalled(id: string, local: boolean): boolean {\n return existsSync(adapterPath(id, local))\n}\n\nexport function getInstalledPath(id: string, local: boolean): string {\n return adapterPath(id, local)\n}\n\nexport function removeAdapter(id: string, local: boolean): boolean {\n const path = adapterPath(id, local)\n if (!existsSync(path))\n return false\n unlinkSync(path)\n return true\n}\n\nexport interface ConflictingAdapter {\n file: string\n path: string\n adapterId: string\n executable: string\n}\n\nexport function findConflictingAdapters(executable: string, excludeId: string): ConflictingAdapter[] {\n const conflicts: ConflictingAdapter[] = []\n const dirs = [\n join(process.cwd(), '.openape', 'shapes', 'adapters'),\n join(homedir(), '.openape', 'shapes', 'adapters'),\n ]\n\n for (const dir of dirs) {\n if (!existsSync(dir))\n continue\n try {\n for (const file of readdirSync(dir).filter(f => f.endsWith('.toml'))) {\n const path = join(dir, file)\n const content = readFileSync(path, 'utf-8')\n const execMatch = content.match(/^\\s*executable\\s*=\\s*\"([^\"]+)\"/m)\n const idMatch = content.match(/^\\s*id\\s*=\\s*\"([^\"]+)\"/m)\n if (execMatch?.[1] === executable && idMatch?.[1] !== excludeId) {\n conflicts.push({ file, path, adapterId: idMatch?.[1] ?? file, executable })\n }\n }\n }\n catch {\n // directory not readable\n }\n }\n\n return conflicts\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { RegistryEntry, RegistryIndex } from './types.js'\n\nconst REGISTRY_URL = process.env.SHAPES_REGISTRY_URL\n ?? 'https://raw.githubusercontent.com/openape-ai/shapes-registry/main/registry.json'\n\nconst CACHE_TTL_MS = 60 * 60 * 1000 // 1 hour\n\nfunction cacheDir(): string {\n return join(homedir(), '.openape', 'shapes', 'cache')\n}\n\nfunction cachePath(): string {\n return join(cacheDir(), 'registry.json')\n}\n\nfunction readCache(): RegistryIndex | null {\n const path = cachePath()\n if (!existsSync(path))\n return null\n\n try {\n const raw = readFileSync(path, 'utf-8')\n const stat = JSON.parse(raw) as RegistryIndex & { _cached_at?: number }\n if (stat._cached_at && Date.now() - stat._cached_at > CACHE_TTL_MS)\n return null\n return stat\n }\n catch {\n return null\n }\n}\n\nfunction writeCache(index: RegistryIndex): void {\n const dir = cacheDir()\n if (!existsSync(dir))\n mkdirSync(dir, { recursive: true })\n\n writeFileSync(cachePath(), JSON.stringify({ ...index, _cached_at: Date.now() }, null, 2))\n}\n\nexport async function fetchRegistry(forceRefresh = false): Promise<RegistryIndex> {\n if (!forceRefresh) {\n const cached = readCache()\n if (cached)\n return cached\n }\n\n const response = await fetch(REGISTRY_URL)\n if (!response.ok)\n throw new Error(`Failed to fetch registry: ${response.status} ${response.statusText}`)\n\n const index = await response.json() as RegistryIndex\n writeCache(index)\n return index\n}\n\nexport function searchAdapters(index: RegistryIndex, query: string): RegistryEntry[] {\n const q = query.toLowerCase()\n return index.adapters.filter(a =>\n a.id.includes(q)\n || a.name.toLowerCase().includes(q)\n || a.description.toLowerCase().includes(q)\n || a.tags.some(t => t.includes(q))\n || a.category.includes(q),\n )\n}\n\n/**\n * Look up a registry entry by its id or its executable field. This lets callers\n * pass either the registry id (\"o365\") or the binary name (\"o365-cli\"); most\n * adapters have id === executable, but the two can diverge.\n */\nexport function findAdapter(index: RegistryIndex, idOrExecutable: string): RegistryEntry | undefined {\n return index.adapters.find(\n a => a.id === idOrExecutable || a.executable === idOrExecutable,\n )\n}\n","import { basename } from 'node:path'\nimport consola from 'consola'\nimport { parse as shellParse } from 'shell-quote'\nimport { loadAdapter, tryLoadAdapter } from './adapters.js'\nimport { installAdapter } from './installer.js'\nimport { fetchRegistry, findAdapter } from './registry.js'\nimport { appendAuditLog } from './audit.js'\nimport type { LoadedAdapter } from './types.js'\n\n/** A parsed shell command string with the executable and its argv extracted. */\nexport interface ParsedShellCommand {\n /** The program to run (first token, e.g. \"rm\") */\n executable: string\n /** Remaining tokens after the executable (e.g. [\"-f\", \"/tmp/foo.txt\"]) */\n argv: string[]\n /**\n * true if the command contains compound operators (&&, ||, ;, |),\n * subshells ($(...)), or backticks. These cannot be safely handled\n * by the adapter mode and must fall back to the generic shell grant flow.\n */\n isCompound: boolean\n /** The original command string for display/logging */\n raw: string\n}\n\nconst COMPOUND_OPERATORS = new Set(['&&', '||', ';', '|', '&', '>', '>>', '<'])\n\ntype ShellQuoteToken = string | { op: string } | { comment: string } | { pattern: string }\n\n/**\n * Parse a shell command string like `rm /tmp/foo.txt` or `git commit -m \"hello\"` into\n * its executable and argv. Uses `shell-quote` to handle quoting correctly.\n *\n * Returns null for empty/whitespace-only input.\n */\nexport function parseShellCommand(raw: string): ParsedShellCommand | null {\n const trimmed = raw.trim()\n if (trimmed.length === 0) return null\n\n let tokens: ShellQuoteToken[]\n try {\n tokens = shellParse(trimmed) as ShellQuoteToken[]\n }\n catch {\n return null\n }\n\n // Detect compound operators and subshells\n const hasShellExpansion = /\\$\\(|`/.test(trimmed)\n const hasOperatorToken = tokens.some(t => typeof t === 'object' && t !== null && 'op' in t && COMPOUND_OPERATORS.has(t.op))\n const isCompound = hasShellExpansion || hasOperatorToken\n\n // Extract leading string tokens up to the first operator object\n const stringTokens: string[] = []\n for (const t of tokens) {\n if (typeof t === 'string') {\n stringTokens.push(t)\n }\n else {\n break\n }\n }\n\n if (stringTokens.length === 0) return null\n\n return {\n executable: stringTokens[0]!,\n argv: stringTokens.slice(1),\n isCompound,\n raw: trimmed,\n }\n}\n\n/**\n * Extract the command string from an `apes run --shell -- bash -c \"…\"` argv.\n * Returns null if the argv does not follow that shape.\n */\nexport function extractShellCommandString(command: string[]): string | null {\n if (command.length < 3) return null\n if (command[0] !== 'bash' && command[0] !== 'sh') return null\n if (command[1] !== '-c') return null\n // Everything after `-c` is the quoted command string\n return command.slice(2).join(' ')\n}\n\n/**\n * Load an adapter for the given CLI id. If the adapter is not installed locally,\n * try to fetch it from the shapes registry and auto-install it.\n *\n * Returns null when no adapter exists in either location, or when any step fails.\n * Failures are logged but never thrown — callers should fall back to the generic flow.\n */\nexport async function loadOrInstallAdapter(cliId: string): Promise<LoadedAdapter | null> {\n // Absolute or relative paths like `/usr/local/bin/o365-cli` must be reduced\n // to the binary name before any lookup — neither the local file scan nor the\n // registry knows how to match a path.\n const lookupId = basename(cliId)\n\n // 1. Try local\n const local = tryLoadAdapter(lookupId)\n if (local) return local\n\n // 2. Remote registry lookup + auto-install.\n // findAdapter matches both `id` and `executable`, so a bare binary name\n // like `o365-cli` resolves to a registry entry whose id is `o365`.\n try {\n const index = await fetchRegistry()\n const entry = findAdapter(index, lookupId)\n if (!entry) return null\n\n consola.info(`Installing shapes adapter for ${entry.id} from registry...`)\n await installAdapter(entry, { local: false })\n appendAuditLog({\n action: 'adapter-auto-install',\n cli_id: entry.id,\n digest: entry.digest,\n source: 'ape-shell',\n })\n\n // Adapters are installed under their registry `id` — always reload by id\n // even if the caller passed the executable name.\n return tryLoadAdapter(entry.id)\n }\n catch (err) {\n consola.debug(`ape-shell adapter auto-install failed for ${lookupId}:`, err)\n return null\n }\n}\n\n// Re-export loadAdapter so callers can import everything from one module\nexport { loadAdapter }\n","import type { OpenApeCliAuthorizationDetail, OpenApeCliResourceRef } from '@openape/core'\nimport { canonicalizeCliPermission } from '@openape/grants'\nimport type { LoadedAdapter, ResolvedCapability, ShapesOperation } from './types.js'\n\ninterface ParsedOperationChainEntry {\n resource: string\n selectorKeys: string[]\n}\n\nfunction parseOperationChainEntry(entry: string): ParsedOperationChainEntry {\n const [resource, selectorSpec = '*'] = entry.split(':', 2)\n if (!resource) {\n throw new Error(`Invalid resource chain entry: ${entry}`)\n }\n\n if (selectorSpec === '*') {\n return { resource, selectorKeys: [] }\n }\n\n const selectorKeys = selectorSpec.split(',')\n .map((segment) => {\n const [key] = segment.split('=', 2)\n if (!key)\n throw new Error(`Invalid selector segment: ${segment}`)\n return key\n })\n\n return { resource, selectorKeys }\n}\n\nfunction operationChain(operation: ShapesOperation): ParsedOperationChainEntry[] {\n return operation.resource_chain.map(parseOperationChainEntry)\n}\n\nfunction knownSelectorKeys(operations: ShapesOperation[], resource: string): string[] {\n const keys = new Set<string>()\n for (const operation of operations) {\n for (const entry of operationChain(operation)) {\n if (entry.resource !== resource)\n continue\n for (const key of entry.selectorKeys) {\n keys.add(key)\n }\n }\n }\n return Array.from(keys).sort()\n}\n\nfunction parseResourceSelector(raw: string): { resource: string, key: string, value: string } {\n const [lhs, value] = raw.split('=', 2)\n if (!lhs || !value) {\n throw new Error(`Invalid selector: ${raw}`)\n }\n\n const [resource, key] = lhs.split('.', 2)\n if (!resource || !key) {\n throw new Error(`Selectors must be in resource.key=value form: ${raw}`)\n }\n\n return { resource, key, value }\n}\n\nfunction formatSelector(selector?: Record<string, string>): string {\n if (!selector || Object.keys(selector).length === 0)\n return '*'\n return Object.entries(selector)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, value]) => `${key}=${value}`)\n .join(',')\n}\n\nfunction summarizeDetail(detail: OpenApeCliAuthorizationDetail): string {\n const chain = detail.resource_chain\n .map(resource => `${resource.resource}[${formatSelector(resource.selector)}]`)\n .join(' -> ')\n return `Allow ${detail.action} on ${detail.cli_id} ${chain}`\n}\n\nexport function resolveCapabilityRequest(\n loaded: LoadedAdapter,\n params: {\n resources: string[]\n selectors?: string[]\n actions: string[]\n },\n): ResolvedCapability {\n if (params.resources.length === 0) {\n throw new Error('At least one --resource is required')\n }\n if (params.actions.length === 0) {\n throw new Error('At least one --action is required')\n }\n\n const selectorMap = new Map<string, Record<string, string>>()\n for (const rawSelector of params.selectors ?? []) {\n const { resource, key, value } = parseResourceSelector(rawSelector)\n const current = selectorMap.get(resource) ?? {}\n current[key] = value\n selectorMap.set(resource, current)\n }\n\n const resource_chain: OpenApeCliResourceRef[] = params.resources.map((resource) => {\n const selector = selectorMap.get(resource)\n const knownKeys = knownSelectorKeys(loaded.adapter.operations, resource)\n if (selector) {\n for (const key of Object.keys(selector)) {\n if (!knownKeys.includes(key)) {\n throw new Error(`Unknown selector ${resource}.${key} for adapter ${loaded.adapter.cli.id}`)\n }\n }\n }\n return selector && Object.keys(selector).length > 0 ? { resource, selector } : { resource }\n })\n\n const requestedSequence = params.resources.join('\\0')\n const matchingOperations = loaded.adapter.operations.filter((operation) => {\n const sequence = operationChain(operation).map(entry => entry.resource).join('\\0')\n return sequence === requestedSequence || sequence.startsWith(`${requestedSequence}\\0`)\n })\n\n if (matchingOperations.length === 0) {\n throw new Error(`No adapter operation supports resource chain: ${params.resources.join(' -> ')}`)\n }\n\n const details = params.actions.map((action) => {\n const matchingActionOps = matchingOperations.filter(operation => operation.action === action)\n if (matchingActionOps.length === 0) {\n throw new Error(`Action ${action} is not valid for resource chain: ${params.resources.join(' -> ')}`)\n }\n\n const exact_command = matchingActionOps.every(operation => operation.exact_command === true)\n const risks = ['low', 'medium', 'high', 'critical'] as const\n const risk = matchingActionOps.reduce<typeof risks[number]>((current, operation) => {\n return risks.indexOf(operation.risk) > risks.indexOf(current) ? operation.risk : current\n }, 'low')\n\n const detail: OpenApeCliAuthorizationDetail = {\n type: 'openape_cli',\n cli_id: loaded.adapter.cli.id,\n operation_id: `capability.${action}`,\n resource_chain,\n action,\n permission: '',\n display: '',\n risk,\n ...(exact_command ? { constraints: { exact_command: true } } : {}),\n }\n detail.permission = canonicalizeCliPermission(detail)\n detail.display = summarizeDetail(detail)\n return detail\n })\n\n return {\n adapter: loaded.adapter,\n source: loaded.source,\n digest: loaded.digest,\n executable: loaded.adapter.cli.executable,\n details,\n executionContext: {\n adapter_id: loaded.adapter.cli.id,\n adapter_version: loaded.adapter.cli.version ?? loaded.adapter.schema,\n adapter_digest: loaded.digest,\n resolved_executable: loaded.adapter.cli.executable,\n context_bindings: Object.fromEntries(\n Array.from(selectorMap.entries()).flatMap(([resource, selector]) =>\n Object.entries(selector).map(([key, value]) => [`${resource}.${key}`, value] as const),\n ),\n ),\n },\n permissions: details.map(detail => detail.permission),\n summary: details.map(detail => detail.display).join('; '),\n }\n}\n","import { buildCliAuthDetail, computeArgvHash, matchArgvToOperation } from '@openape/grants'\nimport type { LoadedAdapter, ResolvedCommand } from './types.js'\n\nexport async function resolveCommand(loaded: LoadedAdapter, fullArgv: string[]): Promise<ResolvedCommand> {\n const [executable, ...commandArgv] = fullArgv\n if (!executable) {\n throw new Error('Missing wrapped command')\n }\n if (executable !== loaded.adapter.cli.executable) {\n throw new Error(`Adapter ${loaded.adapter.cli.id} expects executable ${loaded.adapter.cli.executable}, got ${executable}`)\n }\n\n const match = matchArgvToOperation(loaded.adapter.operations, commandArgv)\n if (!match) {\n throw new Error(`No adapter operation matched: ${fullArgv.join(' ')}`)\n }\n const { operation, bindings } = match\n\n const detail = buildCliAuthDetail(loaded.adapter.cli.id, operation, bindings)\n\n return {\n adapter: loaded.adapter,\n source: loaded.source,\n digest: loaded.digest,\n executable,\n commandArgv,\n bindings,\n detail,\n executionContext: {\n argv: fullArgv,\n argv_hash: await computeArgvHash(fullArgv),\n adapter_id: loaded.adapter.cli.id,\n adapter_version: loaded.adapter.cli.version ?? loaded.adapter.schema,\n adapter_digest: loaded.digest,\n resolved_executable: executable,\n context_bindings: bindings,\n },\n permission: detail.permission,\n }\n}\n","import { defineCommand } from 'citty'\nimport { loadAdapter } from '../adapters.js'\nimport { resolveCommand } from '../parser.js'\n\nexport const explainCommand = defineCommand({\n meta: {\n name: 'explain',\n description: 'Show what permission a wrapped command would need',\n },\n args: {\n adapter: {\n type: 'string',\n description: 'Explicit path to adapter TOML file',\n },\n _: {\n type: 'positional',\n description: 'Wrapped command (after --)',\n required: false,\n },\n },\n async run({ rawArgs }) {\n const command = extractWrappedCommand(rawArgs ?? [])\n if (command.length === 0)\n throw new Error('Missing wrapped command. Usage: shapes explain [--adapter <file>] -- <cli> ...')\n\n const adapterOpt = extractOption(rawArgs ?? [], 'adapter')\n const loaded = loadAdapter(command[0]!, adapterOpt)\n const resolved = await resolveCommand(loaded, command)\n\n process.stdout.write(`${JSON.stringify({\n adapter: resolved.adapter.cli.id,\n source: resolved.source,\n operation: resolved.detail.operation_id,\n display: resolved.detail.display,\n permission: resolved.permission,\n resource_chain: resolved.detail.resource_chain,\n exact_command: resolved.detail.constraints?.exact_command ?? false,\n adapter_digest: resolved.digest,\n }, null, 2)}\\n`)\n },\n})\n\nexport function extractWrappedCommand(args: string[]): string[] {\n const delimiter = args.indexOf('--')\n return delimiter >= 0 ? args.slice(delimiter + 1) : []\n}\n\nexport function extractOption(args: string[], name: string): string | undefined {\n const delimiter = args.indexOf('--')\n const optionArgs = delimiter >= 0 ? args.slice(0, delimiter) : args\n const index = optionArgs.indexOf(`--${name}`)\n if (index >= 0 && index + 1 < optionArgs.length)\n return optionArgs[index + 1]\n return undefined\n}\n","import type { OpenApeCliAuthorizationDetail, OpenApeGrant } from '@openape/core'\nimport { computeCmdHash } from '@openape/core'\nimport { cliAuthorizationDetailCovers, verifyAuthzJWT } from '@openape/grants'\nimport { execFileSync } from 'node:child_process'\nimport { hostname } from 'node:os'\nimport consola from 'consola'\nimport { getRequesterIdentity } from './config.js'\nimport { getGenericAuditLogPath } from '../config.js'\nimport { resolveCommand } from './parser.js'\nimport { loadOrInstallAdapter } from './shell-parser.js'\nimport type { ResolvedCommand } from './types.js'\nimport { apiFetch, discoverEndpoints, getGrantsEndpoint } from './http.js'\nimport { appendGenericCallLog } from '../audit/generic-log.js'\nimport { isGenericResolved } from './generic.js'\n\nfunction decodePayload(token: string): Record<string, unknown> {\n const [, payload] = token.split('.')\n if (!payload)\n throw new Error('Invalid JWT')\n return JSON.parse(Buffer.from(payload, 'base64url').toString('utf-8')) as Record<string, unknown>\n}\n\ninterface SimilarGrantsInfo {\n similar_grants: Array<{ grant: { id: string }, similar_detail_indices: number[] }>\n widened_details: Array<{ permission: string }>\n merged_details: Array<{ permission: string }>\n}\n\nexport async function createShapesGrant(\n resolved: ResolvedCommand,\n params: {\n idp: string\n approval: 'once' | 'timed' | 'always'\n reason?: string\n },\n): Promise<{ id: string, status: string, similar_grants?: SimilarGrantsInfo }> {\n const grantsEndpoint = await getGrantsEndpoint(params.idp)\n const requester = getRequesterIdentity()\n if (!requester) {\n throw new Error('No requester identity available. Run `apes login` first.')\n }\n return apiFetch<{ id: string, status: string, similar_grants?: SimilarGrantsInfo }>(grantsEndpoint, {\n method: 'POST',\n idp: params.idp,\n body: {\n requester,\n target_host: hostname(),\n audience: resolved.adapter.cli.audience ?? 'shapes',\n grant_type: params.approval,\n command: resolved.executionContext.argv,\n reason: params.reason ?? resolved.detail.display,\n permissions: [resolved.permission],\n authorization_details: [resolved.detail],\n execution_context: resolved.executionContext,\n },\n })\n}\n\nexport async function waitForGrantStatus(idp: string, grantId: string): Promise<'approved' | 'denied' | 'revoked'> {\n const grantsEndpoint = await getGrantsEndpoint(idp)\n const deadline = Date.now() + 300_000\n\n while (Date.now() < deadline) {\n const grant = await apiFetch<{ status: 'pending' | 'approved' | 'denied' | 'revoked' }>(`${grantsEndpoint}/${grantId}`, { idp })\n if (grant.status === 'approved' || grant.status === 'denied' || grant.status === 'revoked')\n return grant.status\n await new Promise(resolve => setTimeout(resolve, 3000))\n }\n\n throw new Error('Timed out waiting for grant approval')\n}\n\nexport async function fetchGrantToken(idp: string, grantId: string): Promise<string> {\n const grantsEndpoint = await getGrantsEndpoint(idp)\n const response = await apiFetch<{ authz_jwt: string }>(`${grantsEndpoint}/${grantId}/token`, {\n method: 'POST',\n idp,\n })\n return response.authz_jwt\n}\n\nfunction grantedCliDetails(claims: Record<string, unknown>): OpenApeCliAuthorizationDetail[] {\n const details = claims.authorization_details\n if (!Array.isArray(details))\n return []\n\n return details.filter((detail): detail is OpenApeCliAuthorizationDetail =>\n typeof detail === 'object'\n && detail !== null\n && (detail as Record<string, unknown>).type === 'openape_cli',\n )\n}\n\nfunction hasStructuredCliGrant(claims: Record<string, unknown>): boolean {\n return grantedCliDetails(claims).length > 0\n}\n\n/**\n * Verifies a grant token against the resolved command and marks the grant\n * as consumed on the IdP. Does NOT execute anything — callers that want\n * the one-shot behavior should use `verifyAndExecute`, callers that want\n * to run the command themselves (e.g. the interactive REPL piping through\n * a persistent bash pty) should call this and then do their own execution.\n *\n * Split out so the interactive shell can re-use the verify + consume path\n * without being forced into the `execFileSync`-based one-shot execution.\n */\nexport async function verifyAndConsume(token: string, resolved: ResolvedCommand): Promise<void> {\n const payload = decodePayload(token)\n const issuer = String(payload.iss ?? '')\n if (!issuer)\n throw new Error('Grant token is missing issuer')\n\n const discovery = await discoverEndpoints(issuer)\n const jwksUri = String(discovery.jwks_uri ?? `${issuer}/.well-known/jwks.json`)\n const result = await verifyAuthzJWT(token, {\n expectedIss: issuer,\n expectedAud: resolved.adapter.cli.audience ?? 'shapes',\n jwksUri,\n })\n\n if (!result.valid || !result.claims) {\n throw new Error(result.error ?? 'Grant verification failed')\n }\n\n const claims = result.claims\n const details = grantedCliDetails(claims as unknown as Record<string, unknown>)\n\n if (claims.execution_context?.adapter_digest && claims.execution_context.adapter_digest !== resolved.digest) {\n throw new Error('Adapter digest mismatch')\n }\n\n if (!hasStructuredCliGrant(claims as unknown as Record<string, unknown>)) {\n const argv = resolved.executionContext.argv\n if (!argv?.length) {\n throw new Error('Resolved command is missing argv')\n }\n const expectedCmdHash = await computeCmdHash(argv.join(' '))\n if (claims.command?.join('\\0') !== argv.join('\\0')) {\n throw new Error('Granted command does not match current argv')\n }\n if (claims.cmd_hash && claims.cmd_hash !== expectedCmdHash) {\n throw new Error('Granted command does not match current argv')\n }\n if (!claims.command?.length && !claims.cmd_hash) {\n throw new Error('Grant is not a structured CLI grant and is missing command binding')\n }\n }\n else {\n if (!details.some(detail => cliAuthorizationDetailCovers(detail, resolved.detail))) {\n throw new Error(`Grant does not cover required permission: ${resolved.permission}`)\n }\n\n const exactRequired = details.some(detail =>\n cliAuthorizationDetailCovers(detail, resolved.detail) && detail.constraints?.exact_command,\n )\n\n const isOnce = claims.grant_type === 'once' || claims.approval === 'once'\n const enforceArgvHash = exactRequired || (isOnce && !!claims.execution_context?.argv_hash)\n\n if (enforceArgvHash && claims.execution_context?.argv_hash !== resolved.executionContext.argv_hash) {\n throw new Error('Granted command does not match current argv')\n }\n }\n\n const grantsEndpoint = await getGrantsEndpoint(issuer)\n const consume = await fetch(`${grantsEndpoint}/${claims.grant_id}/consume`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n })\n\n if (!consume.ok) {\n throw new Error(`Consume failed: ${consume.status} ${consume.statusText}`)\n }\n\n const consumeResult = await consume.json() as { error?: string }\n if (consumeResult.error) {\n throw new Error(`Grant rejected at consume step: ${consumeResult.error}`)\n }\n}\n\n/**\n * Execute a verified + consumed resolved command directly via execFileSync,\n * inheriting stdio so the caller's terminal is handed to the child. Used by\n * the one-shot `apes run --shell` path.\n */\nexport function executeResolvedViaExec(resolved: ResolvedCommand): void {\n consola.info(`Executing ${(resolved.executionContext.argv ?? [resolved.executable, ...resolved.commandArgv]).join(' ')}`)\n execFileSync(resolved.executable, resolved.commandArgv, { stdio: 'inherit' })\n}\n\n/**\n * One-shot verify + consume + execute. Preserves the legacy behavior of\n * the `apes run --shell` path so existing callers keep working unchanged.\n *\n * When `resolved` carries the generic-fallback operation id\n * (`_generic.exec`), a JSONL audit entry is appended to the generic-calls\n * log after the child process exits. `grantId` is needed to write the\n * entry — callers that know the grant id should pass it; if omitted, the\n * log entry is skipped (the audit hook is best-effort, not a hard gate).\n *\n * This is the central exec path for sync (`--wait`), async-default\n * (`apes grants run <id> --wait`), and REPL one-shot, so a hook here\n * covers all three flows without duplicating logic in each caller.\n */\nexport async function verifyAndExecute(\n token: string,\n resolved: ResolvedCommand,\n grantId?: string,\n): Promise<void> {\n await verifyAndConsume(token, resolved)\n\n const isGeneric = isGenericResolved(resolved)\n const start = Date.now()\n let exitCode = 0\n try {\n executeResolvedViaExec(resolved)\n }\n catch (err) {\n exitCode = (err as { status?: number })?.status ?? 1\n throw err\n }\n finally {\n if (isGeneric && grantId) {\n // Best-effort: swallow log errors so a broken audit file never\n // blocks a successful command.\n try {\n await appendGenericCallLog(\n {\n ts: new Date().toISOString(),\n cli: resolved.detail.cli_id,\n argv: resolved.executionContext.argv ?? [resolved.executable, ...resolved.commandArgv],\n argv_hash: resolved.executionContext.argv_hash ?? '',\n grant_id: grantId,\n exit_code: exitCode,\n duration_ms: Date.now() - start,\n },\n getGenericAuditLogPath(),\n )\n }\n catch (logErr) {\n consola.debug('Failed to append generic-call audit entry:', logErr)\n }\n }\n }\n}\n\n/**\n * Re-resolve a ResolvedCommand from a previously-created grant's recorded\n * request (argv + adapter digest). Used by `apes grants run <id>` to replay\n * an approved grant locally after the async approval step.\n *\n * Throws when the grant is missing argv, when the adapter cannot be loaded,\n * or when the locally installed adapter's digest no longer matches what the\n * grant was issued against.\n */\nexport async function resolveFromGrant(\n grant: {\n request: {\n command?: string[]\n execution_context?: { adapter_digest?: string, argv_hash?: string }\n authorization_details?: Array<{ type?: string, permission?: string }>\n }\n },\n): Promise<ResolvedCommand> {\n const argv = grant.request?.command\n if (!argv || argv.length === 0)\n throw new Error('Grant request is missing command argv')\n\n const executable = argv[0]\n const adapter = await loadOrInstallAdapter(executable)\n if (!adapter)\n throw new Error(`No shapes adapter found for ${executable}`)\n\n const resolved = await resolveCommand(adapter, argv)\n\n const grantDigest = grant.request.execution_context?.adapter_digest\n if (grantDigest && grantDigest !== resolved.digest) {\n throw new Error(\n `Adapter digest mismatch: grant was created against adapter ${grantDigest}, but local adapter is ${resolved.digest}. Reinstall or revert the adapter.`,\n )\n }\n\n return resolved\n}\n\nexport async function findExistingGrant(\n resolved: ResolvedCommand,\n idp: string,\n): Promise<string | null> {\n const grantsEndpoint = await getGrantsEndpoint(idp)\n const response = await apiFetch<{ data: OpenApeGrant[] }>(\n `${grantsEndpoint}?status=approved`,\n { idp },\n )\n\n const now = Math.floor(Date.now() / 1000)\n const expectedAudience = resolved.adapter.cli.audience ?? 'shapes'\n\n for (const grant of response.data) {\n const req = grant.request\n if (req.grant_type === 'once')\n continue\n if (req.grant_type === 'timed' && grant.expires_at && grant.expires_at <= now)\n continue\n if (req.audience !== expectedAudience)\n continue\n if (req.execution_context?.adapter_digest && req.execution_context.adapter_digest !== resolved.digest)\n continue\n\n const cliDetails = (req.authorization_details ?? []).filter(\n (d): d is OpenApeCliAuthorizationDetail => d.type === 'openape_cli',\n )\n\n if (cliDetails.length > 0) {\n if (cliDetails.some(detail => cliAuthorizationDetailCovers(detail, resolved.detail)))\n return grant.id\n }\n else if (req.permissions?.includes(resolved.permission)) {\n return grant.id\n }\n }\n\n return null\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\ninterface AuthData {\n idp: string\n access_token: string\n email: string\n expires_at: number\n}\n\nconst AUTH_FILE = join(homedir(), '.config', 'apes', 'auth.json')\n\nexport function loadAuth(): AuthData | null {\n if (!existsSync(AUTH_FILE))\n return null\n try {\n return JSON.parse(readFileSync(AUTH_FILE, 'utf-8')) as AuthData\n }\n catch {\n return null\n }\n}\n\nexport function getIdpUrl(explicit?: string): string | null {\n if (explicit)\n return explicit\n if (process.env.APES_IDP)\n return process.env.APES_IDP\n if (process.env.SHAPES_IDP)\n return process.env.SHAPES_IDP\n return loadAuth()?.idp ?? null\n}\n\nexport function getAuthToken(): string | null {\n const auth = loadAuth()\n if (!auth)\n return null\n if (auth.expires_at && Date.now() / 1000 > auth.expires_at - 30)\n return null\n return auth.access_token\n}\n\nexport function getRequesterIdentity(): string | null {\n return loadAuth()?.email ?? null\n}\n","import { getAuthToken, getIdpUrl } from './config.js'\n\nexport async function discoverEndpoints(idpUrl: string): Promise<Record<string, unknown>> {\n const response = await fetch(`${idpUrl}/.well-known/openid-configuration`)\n if (!response.ok)\n return {}\n return response.json() as Promise<Record<string, unknown>>\n}\n\nexport async function getGrantsEndpoint(idpUrl: string): Promise<string> {\n const discovery = await discoverEndpoints(idpUrl)\n return String(discovery.openape_grants_endpoint ?? `${idpUrl}/api/grants`)\n}\n\nexport async function apiFetch<T>(\n path: string,\n options: {\n method?: string\n body?: unknown\n idp?: string\n token?: string\n } = {},\n): Promise<T> {\n const token = options.token ?? getAuthToken()\n if (!token)\n throw new Error('Not authenticated. Run `apes login` first.')\n\n const idp = options.idp ?? getIdpUrl()\n if (!path.startsWith('http') && !idp)\n throw new Error('No IdP URL configured. Use --idp or log in with apes.')\n\n const url = path.startsWith('http') ? path : `${idp}${path}`\n const response = await fetch(url, {\n method: options.method ?? 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: options.body ? JSON.stringify(options.body) : undefined,\n })\n\n if (!response.ok) {\n const text = await response.text()\n throw new Error(text || `${response.status} ${response.statusText}`)\n }\n\n return response.json() as Promise<T>\n}\n","import { mkdir, appendFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\n\n/**\n * A single successful generic-fallback execution entry.\n * Denied, timeout, and cancelled grants are NOT logged here — they are\n * captured by the IdP's server-side audit trail.\n */\nexport interface GenericCallLogEntry {\n /** ISO 8601 timestamp of execution completion */\n ts: string\n /** CLI id as requested by the user (e.g. \"kubectl\") */\n cli: string\n /** Full argv as executed, including the executable */\n argv: string[]\n /** SHA-256 of the argv — matches the `argv:hash` selector in resource_chain */\n argv_hash: string\n /** Grant that authorized this execution */\n grant_id: string\n /** Process exit code */\n exit_code: number\n /** Wall-clock duration from grant-approval to process exit, milliseconds */\n duration_ms: number\n}\n\n/**\n * Default audit log location. Lives under `~/.config/apes/` for consistency\n * with the rest of apes' client state (`config.toml`, `auth.json`, …).\n */\nexport function defaultGenericLogPath(): string {\n return join(homedir(), '.config', 'apes', 'generic-calls.log')\n}\n\n/**\n * Append a single generic-call entry to the audit log in JSONL format.\n * Creates the containing directory if needed.\n *\n * @param entry The call record to append\n * @param logPath Optional override (usually from `config.generic.audit_log`)\n */\nexport async function appendGenericCallLog(\n entry: GenericCallLogEntry,\n logPath?: string,\n): Promise<void> {\n const path = logPath ?? defaultGenericLogPath()\n await mkdir(dirname(path), { recursive: true })\n await appendFile(path, `${JSON.stringify(entry)}\\n`, 'utf-8')\n}\n","import { computeCmdHash } from '@openape/core'\nimport type { BuiltGrantRequest, GrantRequestOptions, ResolvedCapability, ResolvedCommand } from './types.js'\n\nexport async function buildExactCommandGrantRequest(\n command: string[],\n options: GrantRequestOptions & {\n audience: string\n },\n): Promise<BuiltGrantRequest> {\n return {\n request: {\n requester: options.requester,\n target_host: options.target_host,\n audience: options.audience,\n grant_type: options.grant_type,\n command,\n cmd_hash: await computeCmdHash(command.join(' ')),\n ...(options.reason ? { reason: options.reason } : {}),\n ...(options.run_as ? { run_as: options.run_as } : {}),\n },\n }\n}\n\nexport async function buildStructuredCliGrantRequest(\n resolved: ResolvedCommand | ResolvedCapability,\n options: GrantRequestOptions,\n): Promise<BuiltGrantRequest> {\n const details = 'detail' in resolved ? [resolved.detail] : resolved.details\n const permissions = 'permission' in resolved ? [resolved.permission] : resolved.permissions\n const command = 'executionContext' in resolved && resolved.executionContext.argv?.length\n ? resolved.executionContext.argv\n : undefined\n\n return {\n request: {\n requester: options.requester,\n target_host: options.target_host,\n audience: resolved.adapter.cli.audience ?? 'shapes',\n grant_type: options.grant_type,\n permissions,\n authorization_details: details,\n execution_context: resolved.executionContext,\n ...(command ? { command } : {}),\n ...(options.reason ? { reason: options.reason } : { reason: 'summary' in resolved ? resolved.summary : details[0]?.display }),\n ...(options.run_as ? { run_as: options.run_as } : {}),\n },\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,aAAa,oBAAoB;AACtD,SAAS,eAAe;AACxB,SAAS,UAAU,YAAY;;;ACK/B,SAAS,cAAc,MAAqD;AAC1E,QAAM,UAAU,KAAK,QAAQ,GAAG;AAChC,MAAI,YAAY;AACd,WAAO;AACT,QAAM,MAAM,KAAK,MAAM,GAAG,OAAO,EAAE,KAAK;AACxC,QAAM,QAAQ,KAAK,MAAM,UAAU,CAAC,EAAE,KAAK;AAC3C,MAAI,CAAC,OAAO,CAAC;AACX,WAAO;AACT,SAAO,EAAE,KAAK,MAAM;AACtB;AAEA,SAAS,eAAe,KAAsB;AAC5C,QAAM,UAAU,IAAI,KAAK;AAEzB,MAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG;AACjD,WAAO,QAAQ,MAAM,GAAG,EAAE;AAC5B,MAAI,YAAY;AACd,WAAO;AACT,MAAI,YAAY;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E,SAAS,iBAAiB,OAC1B;AAEJ,SAAO;AAAA,IACL,SAAS;AAAA,MACP,WAAW,QAAQ;AAAA,MACnB,aAAa,QAAQ;AAAA,MACrB,UAAU,SAAS,QAAQ,IAAI,YAAY;AAAA,MAC3C,YAAY,QAAQ;AAAA,MACpB;AAAA,MACA,uBAAuB;AAAA,MACvB,mBAAmB,SAAS;AAAA,MAC5B,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,MAC7B,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,EAAE,QAAQ,aAAa,WAAW,SAAS,UAAU,QAAQ,CAAC,GAAG,QAAQ;AAAA,MAC3H,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,IACrD;AAAA,EACF;AACF;","names":["existsSync","homedir","join","createHash","existsSync","mkdirSync","readdirSync","readFileSync","homedir","join","digest","existsSync","join","homedir","readdirSync","readFileSync","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","join","basename","basename","canonicalizeCliPermission","computeArgvHash","consola","existsSync","readFileSync","homedir","join","homedir","dirname","join","consola","computeCmdHash"]}
|
package/dist/cli.js
CHANGED
|
@@ -50,7 +50,7 @@ import {
|
|
|
50
50
|
searchAdapters,
|
|
51
51
|
verifyAndExecute,
|
|
52
52
|
waitForGrantStatus
|
|
53
|
-
} from "./chunk-
|
|
53
|
+
} from "./chunk-PEA2RDWK.js";
|
|
54
54
|
import {
|
|
55
55
|
ApiError,
|
|
56
56
|
apiFetch,
|
|
@@ -7009,7 +7009,7 @@ var mcpCommand = defineCommand52({
|
|
|
7009
7009
|
if (transport !== "stdio" && transport !== "sse") {
|
|
7010
7010
|
throw new Error('Transport must be "stdio" or "sse"');
|
|
7011
7011
|
}
|
|
7012
|
-
const { startMcpServer } = await import("./server-
|
|
7012
|
+
const { startMcpServer } = await import("./server-JGX5FIDP.js");
|
|
7013
7013
|
await startMcpServer(transport, port);
|
|
7014
7014
|
}
|
|
7015
7015
|
});
|
|
@@ -7647,7 +7647,7 @@ async function bestEffortGrantCount(idp) {
|
|
|
7647
7647
|
}
|
|
7648
7648
|
}
|
|
7649
7649
|
async function runHealth(args) {
|
|
7650
|
-
const version = true ? "1.28.
|
|
7650
|
+
const version = true ? "1.28.13" : "0.0.0";
|
|
7651
7651
|
const auth = loadAuth();
|
|
7652
7652
|
if (!auth) {
|
|
7653
7653
|
throw new CliError("Not logged in. Run `apes login` first.", 1);
|
|
@@ -7920,10 +7920,10 @@ if (shellRewrite) {
|
|
|
7920
7920
|
if (shellRewrite.action === "rewrite") {
|
|
7921
7921
|
process.argv = shellRewrite.argv;
|
|
7922
7922
|
} else if (shellRewrite.action === "version") {
|
|
7923
|
-
console.log(`ape-shell ${"1.28.
|
|
7923
|
+
console.log(`ape-shell ${"1.28.13"} (OpenApe DDISA shell wrapper)`);
|
|
7924
7924
|
process.exit(0);
|
|
7925
7925
|
} else if (shellRewrite.action === "help") {
|
|
7926
|
-
console.log(`ape-shell ${"1.28.
|
|
7926
|
+
console.log(`ape-shell ${"1.28.13"} \u2014 OpenApe DDISA shell wrapper`);
|
|
7927
7927
|
console.log("");
|
|
7928
7928
|
console.log("Usage:");
|
|
7929
7929
|
console.log(" ape-shell Start interactive grant-mediated REPL");
|
|
@@ -7938,7 +7938,7 @@ if (shellRewrite) {
|
|
|
7938
7938
|
console.log(" --help, -h Show this help message");
|
|
7939
7939
|
process.exit(0);
|
|
7940
7940
|
} else if (shellRewrite.action === "interactive") {
|
|
7941
|
-
const { runInteractiveShell } = await import("./orchestrator-
|
|
7941
|
+
const { runInteractiveShell } = await import("./orchestrator-REICEX3F.js");
|
|
7942
7942
|
await runInteractiveShell();
|
|
7943
7943
|
process.exit(0);
|
|
7944
7944
|
} else {
|
|
@@ -7981,7 +7981,7 @@ var configCommand = defineCommand64({
|
|
|
7981
7981
|
var main = defineCommand64({
|
|
7982
7982
|
meta: {
|
|
7983
7983
|
name: "apes",
|
|
7984
|
-
version: "1.28.
|
|
7984
|
+
version: "1.28.13",
|
|
7985
7985
|
description: "Unified CLI for OpenApe"
|
|
7986
7986
|
},
|
|
7987
7987
|
subCommands: {
|
|
@@ -8039,7 +8039,7 @@ async function maybeRefreshAuth() {
|
|
|
8039
8039
|
}
|
|
8040
8040
|
}
|
|
8041
8041
|
await maybeRefreshAuth();
|
|
8042
|
-
await maybeWarnStaleVersion("1.28.
|
|
8042
|
+
await maybeWarnStaleVersion("1.28.13").catch(() => {
|
|
8043
8043
|
});
|
|
8044
8044
|
runMain(main).catch((err) => {
|
|
8045
8045
|
if (err instanceof CliExit) {
|
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
resolveCommand,
|
|
15
15
|
verifyAndConsume,
|
|
16
16
|
waitForGrantStatus
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-PEA2RDWK.js";
|
|
18
18
|
import {
|
|
19
19
|
apiFetch,
|
|
20
20
|
getGrantsEndpoint
|
|
@@ -777,4 +777,4 @@ async function runInteractiveShell() {
|
|
|
777
777
|
export {
|
|
778
778
|
runInteractiveShell
|
|
779
779
|
};
|
|
780
|
-
//# sourceMappingURL=orchestrator-
|
|
780
|
+
//# sourceMappingURL=orchestrator-REICEX3F.js.map
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
loadAdapter,
|
|
6
6
|
resolveCommand,
|
|
7
7
|
verifyAndExecute
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-PEA2RDWK.js";
|
|
9
9
|
import {
|
|
10
10
|
apiFetch,
|
|
11
11
|
getGrantsEndpoint
|
|
@@ -303,7 +303,7 @@ function registerAdapterTools(server) {
|
|
|
303
303
|
async function startMcpServer(transport, port) {
|
|
304
304
|
const server = new McpServer({
|
|
305
305
|
name: "apes",
|
|
306
|
-
version: true ? "1.28.
|
|
306
|
+
version: true ? "1.28.13" : "0.1.0"
|
|
307
307
|
});
|
|
308
308
|
registerStaticTools(server);
|
|
309
309
|
registerAdapterTools(server);
|
|
@@ -331,4 +331,4 @@ async function startMcpServer(transport, port) {
|
|
|
331
331
|
export {
|
|
332
332
|
startMcpServer
|
|
333
333
|
};
|
|
334
|
-
//# sourceMappingURL=server-
|
|
334
|
+
//# sourceMappingURL=server-JGX5FIDP.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openape/apes",
|
|
3
|
-
"version": "1.28.
|
|
3
|
+
"version": "1.28.13",
|
|
4
4
|
"turbo": {
|
|
5
5
|
"tags": [
|
|
6
6
|
"publishable"
|
|
@@ -32,9 +32,9 @@
|
|
|
32
32
|
"shell-quote": "^1.8.3",
|
|
33
33
|
"zod": "^4.3.6",
|
|
34
34
|
"@openape/cli-auth": "0.5.0",
|
|
35
|
-
"@openape/
|
|
36
|
-
"@openape/
|
|
37
|
-
"@openape/
|
|
35
|
+
"@openape/proxy": "0.4.5",
|
|
36
|
+
"@openape/core": "0.17.1",
|
|
37
|
+
"@openape/grants": "0.12.0"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@types/node": "^25.3.5",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"tsup": "^8.5.1",
|
|
46
46
|
"typescript": "^5.8.2",
|
|
47
47
|
"vitest": "^4.1.7",
|
|
48
|
-
"@openape/server": "0.3.
|
|
48
|
+
"@openape/server": "0.3.13"
|
|
49
49
|
},
|
|
50
50
|
"license": "MIT",
|
|
51
51
|
"author": "Patrick Hofmann <phofmann@delta-mind.at>",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/shapes/adapters.ts","../src/shapes/toml.ts","../src/shapes/generic.ts","../src/shapes/audit.ts","../src/shapes/installer.ts","../src/shapes/registry.ts","../src/shapes/shell-parser.ts","../src/shapes/capabilities.ts","../src/shapes/parser.ts","../src/shapes/commands/explain.ts","../src/shapes/grants.ts","../src/shapes/config.ts","../src/shapes/http.ts","../src/audit/generic-log.ts","../src/shapes/request-builders.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { basename, join } from 'node:path'\nimport type { LoadedAdapter, ResolvedCommand } from './types.js'\nimport { parseAdapterToml } from './toml.js'\nimport { buildGenericResolved } from './generic.js'\n\nfunction digest(content: string): string {\n return `SHA-256:${createHash('sha256').update(content).digest('hex')}`\n}\n\nfunction adapterDirs(): string[] {\n return [\n join(process.cwd(), '.openape', 'shapes', 'adapters'),\n join(homedir(), '.openape', 'shapes', 'adapters'),\n join('/etc', 'openape', 'shapes', 'adapters'),\n ]\n}\n\nfunction findByExecutable(executable: string): string | undefined {\n for (const dir of adapterDirs()) {\n if (!existsSync(dir))\n continue\n try {\n const files = readdirSync(dir).filter(f => f.endsWith('.toml'))\n for (const file of files) {\n const path = join(dir, file)\n const content = readFileSync(path, 'utf-8')\n const match = content.match(/^\\s*executable\\s*=\\s*\"([^\"]+)\"/m)\n if (match && match[1] === executable)\n return path\n }\n }\n catch {\n // directory not readable\n }\n }\n return undefined\n}\n\nexport function resolveAdapterPath(cliId: string, explicitPath?: string): string {\n if (explicitPath) {\n if (existsSync(explicitPath))\n return explicitPath\n throw new Error(`Adapter file not found: ${explicitPath}`)\n }\n\n // Try direct lookup by ID\n const candidates = adapterDirs().map(dir => join(dir, `${cliId}.toml`))\n const match = candidates.find(path => existsSync(path))\n if (match)\n return match\n\n // Fallback: scan for adapter with matching executable name\n const byExec = findByExecutable(cliId)\n if (byExec)\n return byExec\n\n throw new Error(`No adapter found for ${cliId}`)\n}\n\nexport function loadAdapter(cliId: string, explicitPath?: string): LoadedAdapter {\n const source = resolveAdapterPath(cliId, explicitPath)\n const content = readFileSync(source, 'utf-8')\n const adapter = parseAdapterToml(content)\n\n // Accept if either the adapter ID or the executable matches the requested cliId\n const idMatch = adapter.cli.id === cliId\n const fileMatch = basename(source) === `${cliId}.toml`\n const execMatch = adapter.cli.executable === cliId\n if (!idMatch && !fileMatch && !execMatch)\n throw new Error(`Adapter ${source} does not match requested CLI ${cliId}`)\n\n return {\n adapter,\n source,\n digest: digest(content),\n }\n}\n\n/**\n * Called by `run.ts` when `loadAdapter(cliId)` has already failed with\n * \"No adapter found\". If generic-fallback mode is enabled in config,\n * return a synthetic `ResolvedCommand` that bypasses the parser. If\n * disabled, re-throw the original error (restoring legacy behaviour).\n *\n * @param cliId The CLI that had no registered shape\n * @param fullArgv Argv to execute (including the executable itself)\n * @param opts `genericEnabled: true` → return synthetic resolved;\n * `false` → throw `\"No adapter found for <cliId>\"`.\n */\nexport async function resolveGenericOrReject(\n cliId: string,\n fullArgv: string[],\n opts: { genericEnabled: boolean },\n): Promise<ResolvedCommand> {\n if (!opts.genericEnabled)\n throw new Error(`No adapter found for ${cliId}`)\n return await buildGenericResolved(cliId, fullArgv)\n}\n\n/** Try to load an adapter locally, return null instead of throwing when not found. */\nexport function tryLoadAdapter(cliId: string, explicitPath?: string): LoadedAdapter | null {\n try {\n return loadAdapter(cliId, explicitPath)\n }\n catch {\n return null\n }\n}\n","import type { ShapesAdapter, ShapesOperation } from './types.js'\n\ninterface AdapterTomlFile {\n schema?: string\n cli?: ShapesAdapter['cli']\n operation?: ShapesOperation[]\n}\n\nfunction parseKeyValue(line: string): { key: string, value: string } | null {\n const eqIndex = line.indexOf('=')\n if (eqIndex === -1)\n return null\n const key = line.slice(0, eqIndex).trim()\n const value = line.slice(eqIndex + 1).trim()\n if (!key || !value)\n return null\n return { key, value }\n}\n\nfunction parseTomlValue(raw: string): unknown {\n const trimmed = raw.trim()\n\n if (trimmed.startsWith('\"') && trimmed.endsWith('\"'))\n return trimmed.slice(1, -1)\n if (trimmed === 'true')\n return true\n if (trimmed === 'false')\n return false\n if (trimmed.startsWith('[') && trimmed.endsWith(']')) {\n const inner = trimmed.slice(1, -1).trim()\n if (!inner)\n return []\n return inner.split(',').map(value => value.trim().replace(/^\"|\"$/g, ''))\n }\n\n return trimmed\n}\n\nexport function parseAdapterToml(content: string): ShapesAdapter {\n const result: AdapterTomlFile = {}\n const operations: ShapesOperation[] = []\n let currentSection: 'root' | 'cli' | 'operation' = 'root'\n let currentEntry: Record<string, unknown> = {}\n\n const flushOperation = () => {\n if (currentSection === 'operation' && Object.keys(currentEntry).length > 0) {\n operations.push(currentEntry as unknown as ShapesOperation)\n currentEntry = {}\n }\n }\n\n for (const rawLine of content.split('\\n')) {\n const line = rawLine.trim()\n if (!line || line.startsWith('#'))\n continue\n\n if (line === '[cli]') {\n flushOperation()\n currentSection = 'cli'\n result.cli = {} as ShapesAdapter['cli']\n continue\n }\n\n if (line === '[[operation]]') {\n flushOperation()\n currentSection = 'operation'\n currentEntry = {}\n continue\n }\n\n const kv = parseKeyValue(line)\n if (!kv)\n continue\n\n const value = parseTomlValue(kv.value)\n if (currentSection === 'root') {\n ;(result as Record<string, unknown>)[kv.key] = value\n }\n else if (currentSection === 'cli') {\n ;(result.cli as Record<string, unknown>)[kv.key] = value\n }\n else {\n currentEntry[kv.key] = value\n }\n }\n\n flushOperation()\n result.operation = operations\n\n if (result.schema !== 'openape-shapes/v1') {\n throw new Error(`Unsupported adapter schema: ${result.schema ?? 'missing'}`)\n }\n if (!result.cli?.id || !result.cli.executable) {\n throw new Error('Adapter is missing cli.id or cli.executable')\n }\n if (!result.operation?.length) {\n throw new Error('Adapter must define at least one [[operation]] entry')\n }\n\n return {\n schema: result.schema,\n cli: {\n id: String(result.cli.id),\n executable: String(result.cli.executable),\n ...(result.cli.audience ? { audience: String(result.cli.audience) } : {}),\n ...(result.cli.version ? { version: String(result.cli.version) } : {}),\n },\n operations: result.operation.map((operation) => {\n if (!Array.isArray(operation.command) || operation.command.some(token => typeof token !== 'string')) {\n throw new Error(`Operation ${String(operation.id ?? '<unknown>')} is missing command[]`)\n }\n if (!Array.isArray(operation.resource_chain) || operation.resource_chain.some(token => typeof token !== 'string')) {\n throw new Error(`Operation ${String(operation.id ?? '<unknown>')} is missing resource_chain[]`)\n }\n if (typeof operation.id !== 'string' || typeof operation.display !== 'string' || typeof operation.action !== 'string') {\n throw new TypeError('Operation must define id, display, and action')\n }\n return {\n id: operation.id,\n command: operation.command as string[],\n ...(Array.isArray(operation.positionals) ? { positionals: operation.positionals as string[] } : {}),\n ...(Array.isArray(operation.required_options) ? { required_options: operation.required_options as string[] } : {}),\n display: operation.display,\n action: operation.action,\n risk: (operation.risk as ShapesOperation['risk']) || 'low',\n resource_chain: operation.resource_chain as string[],\n ...(operation.exact_command !== undefined ? { exact_command: Boolean(operation.exact_command) } : {}),\n }\n }),\n }\n}\n","import type { OpenApeCliAuthorizationDetail } from '@openape/core'\nimport { canonicalizeCliPermission, computeArgvHash } from '@openape/grants'\nimport type { LoadedAdapter, ResolvedCommand, ShapesAdapter } from './types.js'\n\n/**\n * The synthetic operation ID used for generic-fallback grants. Downstream\n * code (audit logging, UI banner) keys off this exact string.\n */\nexport const GENERIC_OPERATION_ID = '_generic.exec'\n\n/**\n * Schema version for synthetic adapters. Not persisted anywhere — exists\n * only so the in-memory adapter shape matches `ShapesAdapter`.\n */\nconst SYNTHETIC_SCHEMA = 'openape-shapes/v1'\n\n/**\n * Build a synthetic in-memory `LoadedAdapter` for a CLI that has no\n * registered shape. The adapter is marked with `synthetic: true` so\n * callers can branch on it if needed.\n *\n * NOTE: This does NOT produce a parser-matchable adapter. The generic\n * pipeline bypasses `resolveCommand()` entirely — see `buildGenericResolved()`.\n * This function exists for flow-control markers and tests.\n */\nexport function buildGenericAdapter(cliId: string): LoadedAdapter {\n const adapter: ShapesAdapter = {\n schema: SYNTHETIC_SCHEMA,\n cli: {\n id: cliId,\n executable: cliId,\n audience: 'shapes',\n version: 'synthetic',\n },\n operations: [],\n }\n return {\n adapter,\n source: '<synthetic>',\n digest: 'synthetic',\n synthetic: true,\n }\n}\n\n/**\n * Build a `ResolvedCommand` directly for a CLI that has no registered shape.\n *\n * Unlike the normal flow (loadAdapter → resolveCommand), the generic path\n * bypasses the parser entirely. Rationale:\n *\n * - `resolveCommand()` matches argv against declarative operation specs\n * via `matchOperation()`, which requires `positionals.length ===\n * operation.positionals.length`. A \"match-all\" spec (`command: []`,\n * `positionals: []`) would reject any non-empty argv.\n *\n * - Synthetic adapters have no declarative spec — we already know what\n * to execute. Running the parser is theatre.\n *\n * The returned `ResolvedCommand` has:\n * - `detail.operation_id === GENERIC_OPERATION_ID` — marker consumed by\n * the audit-log hook in `verifyAndExecute`.\n * - `detail.risk === 'high'` — forced.\n * - `detail.constraints.exact_command === true` — forced, binds the\n * grant to this exact argv via `argv_hash`.\n * - `resource_chain = [{resource: 'cli', selector: {name: cliId}},\n * {resource: 'argv', selector: {hash: <sha256>}}]`\n */\nexport async function buildGenericResolved(\n cliId: string,\n fullArgv: string[],\n): Promise<ResolvedCommand> {\n if (fullArgv.length === 0)\n throw new Error('buildGenericResolved: fullArgv must include the executable')\n const executable = fullArgv[0]!\n const commandArgv = fullArgv.slice(1)\n const argvHash = await computeArgvHash(fullArgv)\n\n const display = `Execute (unshaped): \\`${cliId} ${commandArgv.join(' ')}\\``\n\n const detail: OpenApeCliAuthorizationDetail = {\n type: 'openape_cli',\n cli_id: cliId,\n operation_id: GENERIC_OPERATION_ID,\n resource_chain: [\n { resource: 'cli', selector: { name: cliId } },\n { resource: 'argv', selector: { hash: argvHash } },\n ],\n action: 'exec',\n permission: '',\n display,\n risk: 'high',\n constraints: { exact_command: true },\n }\n detail.permission = canonicalizeCliPermission(detail)\n\n const adapter = buildGenericAdapter(cliId)\n\n return {\n adapter: adapter.adapter,\n source: adapter.source,\n digest: adapter.digest,\n executable,\n commandArgv,\n bindings: {},\n detail,\n executionContext: {\n argv: fullArgv,\n argv_hash: argvHash,\n adapter_id: cliId,\n adapter_version: SYNTHETIC_SCHEMA,\n adapter_digest: adapter.digest,\n resolved_executable: executable,\n context_bindings: {},\n },\n permission: detail.permission,\n }\n}\n\n/**\n * Type guard: does this `ResolvedCommand` come from the generic fallback path?\n */\nexport function isGenericResolved(resolved: ResolvedCommand): boolean {\n return resolved.detail.operation_id === GENERIC_OPERATION_ID\n}\n","import { appendFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\n\n/** Single audit log entry. Always includes a timestamp and an action string. */\nexport interface AuditEntry {\n action: string\n timestamp: number\n [key: string]: unknown\n}\n\nfunction auditPath(): string {\n return join(homedir(), '.config', 'apes', 'audit.jsonl')\n}\n\n/**\n * Append a single entry to the audit log at ~/.config/apes/audit.jsonl.\n * Failures are swallowed — the audit log should never break the actual flow.\n */\nexport function appendAuditLog(entry: { action: string, timestamp?: number } & Record<string, unknown>): void {\n const full: AuditEntry = {\n ...entry,\n action: entry.action,\n timestamp: entry.timestamp ?? Date.now(),\n }\n const path = auditPath()\n const dir = dirname(path)\n try {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n appendFileSync(path, `${JSON.stringify(full)}\\n`)\n }\n catch {\n // intentionally ignored — audit log must never break the flow\n }\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { RegistryEntry } from './types.js'\n\nfunction adapterDir(local: boolean): string {\n const base = local ? process.cwd() : homedir()\n return join(base, '.openape', 'shapes', 'adapters')\n}\n\nfunction adapterPath(id: string, local: boolean): string {\n return join(adapterDir(local), `${id}.toml`)\n}\n\nfunction sha256(content: string): string {\n return `SHA-256:${createHash('sha256').update(content).digest('hex')}`\n}\n\nexport interface InstallResult {\n id: string\n path: string\n digest: string\n updated: boolean\n}\n\nexport async function installAdapter(entry: RegistryEntry, options: { local?: boolean } = {}): Promise<InstallResult> {\n const local = options.local ?? false\n const dest = adapterPath(entry.id, local)\n const dir = adapterDir(local)\n\n const response = await fetch(entry.download_url)\n if (!response.ok)\n throw new Error(`Failed to download adapter ${entry.id}: ${response.status} ${response.statusText}`)\n\n const content = await response.text()\n const digest = sha256(content)\n\n if (digest !== entry.digest)\n throw new Error(`Digest mismatch for ${entry.id}: expected ${entry.digest}, got ${digest}`)\n\n const updated = existsSync(dest)\n\n if (!existsSync(dir))\n mkdirSync(dir, { recursive: true })\n\n writeFileSync(dest, content)\n\n return { id: entry.id, path: dest, digest, updated }\n}\n\nexport function getInstalledDigest(id: string, local: boolean): string | null {\n const path = adapterPath(id, local)\n if (!existsSync(path))\n return null\n\n const content = readFileSync(path, 'utf-8')\n return sha256(content)\n}\n\nexport function isInstalled(id: string, local: boolean): boolean {\n return existsSync(adapterPath(id, local))\n}\n\nexport function getInstalledPath(id: string, local: boolean): string {\n return adapterPath(id, local)\n}\n\nexport function removeAdapter(id: string, local: boolean): boolean {\n const path = adapterPath(id, local)\n if (!existsSync(path))\n return false\n unlinkSync(path)\n return true\n}\n\nexport interface ConflictingAdapter {\n file: string\n path: string\n adapterId: string\n executable: string\n}\n\nexport function findConflictingAdapters(executable: string, excludeId: string): ConflictingAdapter[] {\n const conflicts: ConflictingAdapter[] = []\n const dirs = [\n join(process.cwd(), '.openape', 'shapes', 'adapters'),\n join(homedir(), '.openape', 'shapes', 'adapters'),\n ]\n\n for (const dir of dirs) {\n if (!existsSync(dir))\n continue\n try {\n for (const file of readdirSync(dir).filter(f => f.endsWith('.toml'))) {\n const path = join(dir, file)\n const content = readFileSync(path, 'utf-8')\n const execMatch = content.match(/^\\s*executable\\s*=\\s*\"([^\"]+)\"/m)\n const idMatch = content.match(/^\\s*id\\s*=\\s*\"([^\"]+)\"/m)\n if (execMatch?.[1] === executable && idMatch?.[1] !== excludeId) {\n conflicts.push({ file, path, adapterId: idMatch?.[1] ?? file, executable })\n }\n }\n }\n catch {\n // directory not readable\n }\n }\n\n return conflicts\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { RegistryEntry, RegistryIndex } from './types.js'\n\nconst REGISTRY_URL = process.env.SHAPES_REGISTRY_URL\n ?? 'https://raw.githubusercontent.com/openape-ai/shapes-registry/main/registry.json'\n\nconst CACHE_TTL_MS = 60 * 60 * 1000 // 1 hour\n\nfunction cacheDir(): string {\n return join(homedir(), '.openape', 'shapes', 'cache')\n}\n\nfunction cachePath(): string {\n return join(cacheDir(), 'registry.json')\n}\n\nfunction readCache(): RegistryIndex | null {\n const path = cachePath()\n if (!existsSync(path))\n return null\n\n try {\n const raw = readFileSync(path, 'utf-8')\n const stat = JSON.parse(raw) as RegistryIndex & { _cached_at?: number }\n if (stat._cached_at && Date.now() - stat._cached_at > CACHE_TTL_MS)\n return null\n return stat\n }\n catch {\n return null\n }\n}\n\nfunction writeCache(index: RegistryIndex): void {\n const dir = cacheDir()\n if (!existsSync(dir))\n mkdirSync(dir, { recursive: true })\n\n writeFileSync(cachePath(), JSON.stringify({ ...index, _cached_at: Date.now() }, null, 2))\n}\n\nexport async function fetchRegistry(forceRefresh = false): Promise<RegistryIndex> {\n if (!forceRefresh) {\n const cached = readCache()\n if (cached)\n return cached\n }\n\n const response = await fetch(REGISTRY_URL)\n if (!response.ok)\n throw new Error(`Failed to fetch registry: ${response.status} ${response.statusText}`)\n\n const index = await response.json() as RegistryIndex\n writeCache(index)\n return index\n}\n\nexport function searchAdapters(index: RegistryIndex, query: string): RegistryEntry[] {\n const q = query.toLowerCase()\n return index.adapters.filter(a =>\n a.id.includes(q)\n || a.name.toLowerCase().includes(q)\n || a.description.toLowerCase().includes(q)\n || a.tags.some(t => t.includes(q))\n || a.category.includes(q),\n )\n}\n\n/**\n * Look up a registry entry by its id or its executable field. This lets callers\n * pass either the registry id (\"o365\") or the binary name (\"o365-cli\"); most\n * adapters have id === executable, but the two can diverge.\n */\nexport function findAdapter(index: RegistryIndex, idOrExecutable: string): RegistryEntry | undefined {\n return index.adapters.find(\n a => a.id === idOrExecutable || a.executable === idOrExecutable,\n )\n}\n","import { basename } from 'node:path'\nimport consola from 'consola'\nimport { parse as shellParse } from 'shell-quote'\nimport { loadAdapter, tryLoadAdapter } from './adapters.js'\nimport { installAdapter } from './installer.js'\nimport { fetchRegistry, findAdapter } from './registry.js'\nimport { appendAuditLog } from './audit.js'\nimport type { LoadedAdapter } from './types.js'\n\n/** A parsed shell command string with the executable and its argv extracted. */\nexport interface ParsedShellCommand {\n /** The program to run (first token, e.g. \"rm\") */\n executable: string\n /** Remaining tokens after the executable (e.g. [\"-f\", \"/tmp/foo.txt\"]) */\n argv: string[]\n /**\n * true if the command contains compound operators (&&, ||, ;, |),\n * subshells ($(...)), or backticks. These cannot be safely handled\n * by the adapter mode and must fall back to the generic shell grant flow.\n */\n isCompound: boolean\n /** The original command string for display/logging */\n raw: string\n}\n\nconst COMPOUND_OPERATORS = new Set(['&&', '||', ';', '|', '&', '>', '>>', '<'])\n\ntype ShellQuoteToken = string | { op: string } | { comment: string } | { pattern: string }\n\n/**\n * Parse a shell command string like `rm /tmp/foo.txt` or `git commit -m \"hello\"` into\n * its executable and argv. Uses `shell-quote` to handle quoting correctly.\n *\n * Returns null for empty/whitespace-only input.\n */\nexport function parseShellCommand(raw: string): ParsedShellCommand | null {\n const trimmed = raw.trim()\n if (trimmed.length === 0) return null\n\n let tokens: ShellQuoteToken[]\n try {\n tokens = shellParse(trimmed) as ShellQuoteToken[]\n }\n catch {\n return null\n }\n\n // Detect compound operators and subshells\n const hasShellExpansion = /\\$\\(|`/.test(trimmed)\n const hasOperatorToken = tokens.some(t => typeof t === 'object' && t !== null && 'op' in t && COMPOUND_OPERATORS.has(t.op))\n const isCompound = hasShellExpansion || hasOperatorToken\n\n // Extract leading string tokens up to the first operator object\n const stringTokens: string[] = []\n for (const t of tokens) {\n if (typeof t === 'string') {\n stringTokens.push(t)\n }\n else {\n break\n }\n }\n\n if (stringTokens.length === 0) return null\n\n return {\n executable: stringTokens[0]!,\n argv: stringTokens.slice(1),\n isCompound,\n raw: trimmed,\n }\n}\n\n/**\n * Extract the command string from an `apes run --shell -- bash -c \"…\"` argv.\n * Returns null if the argv does not follow that shape.\n */\nexport function extractShellCommandString(command: string[]): string | null {\n if (command.length < 3) return null\n if (command[0] !== 'bash' && command[0] !== 'sh') return null\n if (command[1] !== '-c') return null\n // Everything after `-c` is the quoted command string\n return command.slice(2).join(' ')\n}\n\n/**\n * Load an adapter for the given CLI id. If the adapter is not installed locally,\n * try to fetch it from the shapes registry and auto-install it.\n *\n * Returns null when no adapter exists in either location, or when any step fails.\n * Failures are logged but never thrown — callers should fall back to the generic flow.\n */\nexport async function loadOrInstallAdapter(cliId: string): Promise<LoadedAdapter | null> {\n // Absolute or relative paths like `/usr/local/bin/o365-cli` must be reduced\n // to the binary name before any lookup — neither the local file scan nor the\n // registry knows how to match a path.\n const lookupId = basename(cliId)\n\n // 1. Try local\n const local = tryLoadAdapter(lookupId)\n if (local) return local\n\n // 2. Remote registry lookup + auto-install.\n // findAdapter matches both `id` and `executable`, so a bare binary name\n // like `o365-cli` resolves to a registry entry whose id is `o365`.\n try {\n const index = await fetchRegistry()\n const entry = findAdapter(index, lookupId)\n if (!entry) return null\n\n consola.info(`Installing shapes adapter for ${entry.id} from registry...`)\n await installAdapter(entry, { local: false })\n appendAuditLog({\n action: 'adapter-auto-install',\n cli_id: entry.id,\n digest: entry.digest,\n source: 'ape-shell',\n })\n\n // Adapters are installed under their registry `id` — always reload by id\n // even if the caller passed the executable name.\n return tryLoadAdapter(entry.id)\n }\n catch (err) {\n consola.debug(`ape-shell adapter auto-install failed for ${lookupId}:`, err)\n return null\n }\n}\n\n// Re-export loadAdapter so callers can import everything from one module\nexport { loadAdapter }\n","import type { OpenApeCliAuthorizationDetail, OpenApeCliResourceRef } from '@openape/core'\nimport { canonicalizeCliPermission } from '@openape/grants'\nimport type { LoadedAdapter, ResolvedCapability, ShapesOperation } from './types.js'\n\ninterface ParsedOperationChainEntry {\n resource: string\n selectorKeys: string[]\n}\n\nfunction parseOperationChainEntry(entry: string): ParsedOperationChainEntry {\n const [resource, selectorSpec = '*'] = entry.split(':', 2)\n if (!resource) {\n throw new Error(`Invalid resource chain entry: ${entry}`)\n }\n\n if (selectorSpec === '*') {\n return { resource, selectorKeys: [] }\n }\n\n const selectorKeys = selectorSpec.split(',')\n .map((segment) => {\n const [key] = segment.split('=', 2)\n if (!key)\n throw new Error(`Invalid selector segment: ${segment}`)\n return key\n })\n\n return { resource, selectorKeys }\n}\n\nfunction operationChain(operation: ShapesOperation): ParsedOperationChainEntry[] {\n return operation.resource_chain.map(parseOperationChainEntry)\n}\n\nfunction knownSelectorKeys(operations: ShapesOperation[], resource: string): string[] {\n const keys = new Set<string>()\n for (const operation of operations) {\n for (const entry of operationChain(operation)) {\n if (entry.resource !== resource)\n continue\n for (const key of entry.selectorKeys) {\n keys.add(key)\n }\n }\n }\n return Array.from(keys).sort()\n}\n\nfunction parseResourceSelector(raw: string): { resource: string, key: string, value: string } {\n const [lhs, value] = raw.split('=', 2)\n if (!lhs || !value) {\n throw new Error(`Invalid selector: ${raw}`)\n }\n\n const [resource, key] = lhs.split('.', 2)\n if (!resource || !key) {\n throw new Error(`Selectors must be in resource.key=value form: ${raw}`)\n }\n\n return { resource, key, value }\n}\n\nfunction formatSelector(selector?: Record<string, string>): string {\n if (!selector || Object.keys(selector).length === 0)\n return '*'\n return Object.entries(selector)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, value]) => `${key}=${value}`)\n .join(',')\n}\n\nfunction summarizeDetail(detail: OpenApeCliAuthorizationDetail): string {\n const chain = detail.resource_chain\n .map(resource => `${resource.resource}[${formatSelector(resource.selector)}]`)\n .join(' -> ')\n return `Allow ${detail.action} on ${detail.cli_id} ${chain}`\n}\n\nexport function resolveCapabilityRequest(\n loaded: LoadedAdapter,\n params: {\n resources: string[]\n selectors?: string[]\n actions: string[]\n },\n): ResolvedCapability {\n if (params.resources.length === 0) {\n throw new Error('At least one --resource is required')\n }\n if (params.actions.length === 0) {\n throw new Error('At least one --action is required')\n }\n\n const selectorMap = new Map<string, Record<string, string>>()\n for (const rawSelector of params.selectors ?? []) {\n const { resource, key, value } = parseResourceSelector(rawSelector)\n const current = selectorMap.get(resource) ?? {}\n current[key] = value\n selectorMap.set(resource, current)\n }\n\n const resource_chain: OpenApeCliResourceRef[] = params.resources.map((resource) => {\n const selector = selectorMap.get(resource)\n const knownKeys = knownSelectorKeys(loaded.adapter.operations, resource)\n if (selector) {\n for (const key of Object.keys(selector)) {\n if (!knownKeys.includes(key)) {\n throw new Error(`Unknown selector ${resource}.${key} for adapter ${loaded.adapter.cli.id}`)\n }\n }\n }\n return selector && Object.keys(selector).length > 0 ? { resource, selector } : { resource }\n })\n\n const requestedSequence = params.resources.join('\\0')\n const matchingOperations = loaded.adapter.operations.filter((operation) => {\n const sequence = operationChain(operation).map(entry => entry.resource).join('\\0')\n return sequence === requestedSequence || sequence.startsWith(`${requestedSequence}\\0`)\n })\n\n if (matchingOperations.length === 0) {\n throw new Error(`No adapter operation supports resource chain: ${params.resources.join(' -> ')}`)\n }\n\n const details = params.actions.map((action) => {\n const matchingActionOps = matchingOperations.filter(operation => operation.action === action)\n if (matchingActionOps.length === 0) {\n throw new Error(`Action ${action} is not valid for resource chain: ${params.resources.join(' -> ')}`)\n }\n\n const exact_command = matchingActionOps.every(operation => operation.exact_command === true)\n const risks = ['low', 'medium', 'high', 'critical'] as const\n const risk = matchingActionOps.reduce<typeof risks[number]>((current, operation) => {\n return risks.indexOf(operation.risk) > risks.indexOf(current) ? operation.risk : current\n }, 'low')\n\n const detail: OpenApeCliAuthorizationDetail = {\n type: 'openape_cli',\n cli_id: loaded.adapter.cli.id,\n operation_id: `capability.${action}`,\n resource_chain,\n action,\n permission: '',\n display: '',\n risk,\n ...(exact_command ? { constraints: { exact_command: true } } : {}),\n }\n detail.permission = canonicalizeCliPermission(detail)\n detail.display = summarizeDetail(detail)\n return detail\n })\n\n return {\n adapter: loaded.adapter,\n source: loaded.source,\n digest: loaded.digest,\n executable: loaded.adapter.cli.executable,\n details,\n executionContext: {\n adapter_id: loaded.adapter.cli.id,\n adapter_version: loaded.adapter.cli.version ?? loaded.adapter.schema,\n adapter_digest: loaded.digest,\n resolved_executable: loaded.adapter.cli.executable,\n context_bindings: Object.fromEntries(\n Array.from(selectorMap.entries()).flatMap(([resource, selector]) =>\n Object.entries(selector).map(([key, value]) => [`${resource}.${key}`, value] as const),\n ),\n ),\n },\n permissions: details.map(detail => detail.permission),\n summary: details.map(detail => detail.display).join('; '),\n }\n}\n","import type { OpenApeCliAuthorizationDetail, OpenApeCliResourceRef } from '@openape/core'\nimport { canonicalizeCliPermission, computeArgvHash } from '@openape/grants'\nimport type { LoadedAdapter, ResolvedCommand, ShapesOperation } from './types.js'\n\nfunction parseOptionArgs(tokens: string[], valueOptions?: string[]): { options: Record<string, string>, positionals: string[] } {\n const options: Record<string, string> = {}\n const positionals: string[] = []\n const takesValue = new Set(valueOptions ?? [])\n\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]!\n\n if (token.startsWith('--')) {\n // Long option: --name value or --name=value\n const stripped = token.slice(2)\n const eqIndex = stripped.indexOf('=')\n if (eqIndex >= 0) {\n options[stripped.slice(0, eqIndex)] = stripped.slice(eqIndex + 1)\n continue\n }\n\n const next = tokens[index + 1]\n if (next && !next.startsWith('-')) {\n options[stripped] = next\n index += 1\n continue\n }\n\n options[stripped] = 'true'\n }\n else if (token.startsWith('-') && token.length > 1 && !/^-\\d/.test(token)) {\n // Short option: -name value, -f value, or -l (boolean)\n const key = token.slice(1)\n\n if (key.length === 1 && !takesValue.has(key)) {\n // Single-char flag not in required_options → boolean\n options[key] = 'true'\n }\n else {\n // Multi-char option (-name) or known value option (-f) → consume next as value\n const next = tokens[index + 1]\n if (next && !next.startsWith('-')) {\n options[key] = next\n index += 1\n }\n else {\n options[key] = 'true'\n }\n }\n }\n else {\n positionals.push(token)\n }\n }\n\n return { options, positionals }\n}\n\nfunction resolveBindingToken(binding: string, bindings: Record<string, string>): string {\n const match = binding.match(/^\\{([^}|]+)(?:\\|([^}]+))?\\}$/)\n if (!match)\n return binding\n\n const [, name, transform] = match\n const value = bindings[name]\n if (!value)\n throw new Error(`Missing binding: ${name}`)\n if (!transform)\n return value\n\n if (transform === 'owner' || transform === 'name') {\n const [owner, repo] = value.split('/')\n if (!owner || !repo)\n throw new Error(`Binding ${name} must be in owner/name form`)\n return transform === 'owner' ? owner : repo\n }\n\n throw new Error(`Unsupported binding transform: ${transform}`)\n}\n\nfunction renderTemplate(template: string, bindings: Record<string, string>): string {\n return template.replace(/\\{([^}]+)\\}/g, (_, expression: string) => resolveBindingToken(`{${expression}}`, bindings))\n}\n\nfunction parseResourceChain(chain: string[], bindings: Record<string, string>): OpenApeCliResourceRef[] {\n return chain.map((entry) => {\n const [resource, selectorSpec = '*'] = entry.split(':', 2)\n if (!resource)\n throw new Error(`Invalid resource chain entry: ${entry}`)\n\n if (selectorSpec === '*') {\n return { resource }\n }\n\n const selector = Object.fromEntries(\n selectorSpec.split(',').map((segment) => {\n const [key, rawValue] = segment.split('=', 2)\n if (!key || !rawValue)\n throw new Error(`Invalid selector segment: ${segment}`)\n return [key, renderTemplate(rawValue, bindings)]\n }),\n )\n\n return { resource, selector }\n })\n}\n\nfunction matchOperation(operation: ShapesOperation, argv: string[]): Record<string, string> | null {\n if (argv.length < operation.command.length)\n return null\n\n const prefix = argv.slice(0, operation.command.length)\n if (prefix.join('\\0') !== operation.command.join('\\0'))\n return null\n\n const remainder = argv.slice(operation.command.length)\n const { options, positionals } = parseOptionArgs(remainder, operation.required_options)\n\n const expectedPositionals = operation.positionals ?? []\n if (positionals.length !== expectedPositionals.length)\n return null\n\n for (const option of operation.required_options ?? []) {\n if (!options[option])\n return null\n }\n\n const bindings: Record<string, string> = { ...options }\n for (let index = 0; index < expectedPositionals.length; index += 1) {\n const name = expectedPositionals[index]!\n const value = positionals[index]!\n if (name.startsWith('=')) {\n if (value !== name.slice(1))\n return null\n continue\n }\n bindings[name] = value\n }\n return bindings\n}\n\nfunction expandCombinedFlags(argv: string[]): string[] {\n return argv.flatMap((token) => {\n // Expand -rl into -r, -l (only single-letter combined flags)\n if (token.startsWith('-') && !token.startsWith('--') && token.length > 2 && /^-[a-z]+$/i.test(token)) {\n return Array.from(token.slice(1), c => `-${c}`)\n }\n return [token]\n })\n}\n\nfunction tryMatch(operations: ShapesOperation[], argv: string[]) {\n return operations.flatMap((operation) => {\n try {\n const bindings = matchOperation(operation, argv)\n return bindings ? [{ operation, bindings }] : []\n }\n catch {\n return []\n }\n })\n}\n\nexport async function resolveCommand(loaded: LoadedAdapter, fullArgv: string[]): Promise<ResolvedCommand> {\n const [executable, ...commandArgv] = fullArgv\n if (!executable) {\n throw new Error('Missing wrapped command')\n }\n if (executable !== loaded.adapter.cli.executable) {\n throw new Error(`Adapter ${loaded.adapter.cli.id} expects executable ${loaded.adapter.cli.executable}, got ${executable}`)\n }\n\n // Pass 1: exact match\n let matches = tryMatch(loaded.adapter.operations, commandArgv)\n\n // Pass 2: try with expanded combined flags (e.g. -rl → -r -l)\n if (matches.length === 0) {\n const expanded = expandCombinedFlags(commandArgv)\n if (expanded.length !== commandArgv.length) {\n matches = tryMatch(loaded.adapter.operations, expanded)\n }\n }\n\n if (matches.length === 0) {\n throw new Error(`No adapter operation matched: ${fullArgv.join(' ')}`)\n }\n if (matches.length > 1) {\n // Prefer the most specific match (longest command prefix)\n matches.sort((a, b) => b.operation.command.length - a.operation.command.length)\n matches = [matches[0]!]\n }\n\n const { operation, bindings } = matches[0]!\n const resource_chain = parseResourceChain(operation.resource_chain, bindings)\n const detail: OpenApeCliAuthorizationDetail = {\n type: 'openape_cli',\n cli_id: loaded.adapter.cli.id,\n operation_id: operation.id,\n resource_chain,\n action: operation.action,\n permission: '',\n display: renderTemplate(operation.display, bindings),\n risk: operation.risk,\n ...(operation.exact_command ? { constraints: { exact_command: true } } : {}),\n }\n detail.permission = canonicalizeCliPermission(detail)\n\n return {\n adapter: loaded.adapter,\n source: loaded.source,\n digest: loaded.digest,\n executable,\n commandArgv,\n bindings,\n detail,\n executionContext: {\n argv: fullArgv,\n argv_hash: await computeArgvHash(fullArgv),\n adapter_id: loaded.adapter.cli.id,\n adapter_version: loaded.adapter.cli.version ?? loaded.adapter.schema,\n adapter_digest: loaded.digest,\n resolved_executable: executable,\n context_bindings: bindings,\n },\n permission: detail.permission,\n }\n}\n","import { defineCommand } from 'citty'\nimport { loadAdapter } from '../adapters.js'\nimport { resolveCommand } from '../parser.js'\n\nexport const explainCommand = defineCommand({\n meta: {\n name: 'explain',\n description: 'Show what permission a wrapped command would need',\n },\n args: {\n adapter: {\n type: 'string',\n description: 'Explicit path to adapter TOML file',\n },\n _: {\n type: 'positional',\n description: 'Wrapped command (after --)',\n required: false,\n },\n },\n async run({ rawArgs }) {\n const command = extractWrappedCommand(rawArgs ?? [])\n if (command.length === 0)\n throw new Error('Missing wrapped command. Usage: shapes explain [--adapter <file>] -- <cli> ...')\n\n const adapterOpt = extractOption(rawArgs ?? [], 'adapter')\n const loaded = loadAdapter(command[0]!, adapterOpt)\n const resolved = await resolveCommand(loaded, command)\n\n process.stdout.write(`${JSON.stringify({\n adapter: resolved.adapter.cli.id,\n source: resolved.source,\n operation: resolved.detail.operation_id,\n display: resolved.detail.display,\n permission: resolved.permission,\n resource_chain: resolved.detail.resource_chain,\n exact_command: resolved.detail.constraints?.exact_command ?? false,\n adapter_digest: resolved.digest,\n }, null, 2)}\\n`)\n },\n})\n\nexport function extractWrappedCommand(args: string[]): string[] {\n const delimiter = args.indexOf('--')\n return delimiter >= 0 ? args.slice(delimiter + 1) : []\n}\n\nexport function extractOption(args: string[], name: string): string | undefined {\n const delimiter = args.indexOf('--')\n const optionArgs = delimiter >= 0 ? args.slice(0, delimiter) : args\n const index = optionArgs.indexOf(`--${name}`)\n if (index >= 0 && index + 1 < optionArgs.length)\n return optionArgs[index + 1]\n return undefined\n}\n","import type { OpenApeCliAuthorizationDetail, OpenApeGrant } from '@openape/core'\nimport { computeCmdHash } from '@openape/core'\nimport { cliAuthorizationDetailCovers, verifyAuthzJWT } from '@openape/grants'\nimport { execFileSync } from 'node:child_process'\nimport { hostname } from 'node:os'\nimport consola from 'consola'\nimport { getRequesterIdentity } from './config.js'\nimport { getGenericAuditLogPath } from '../config.js'\nimport { resolveCommand } from './parser.js'\nimport { loadOrInstallAdapter } from './shell-parser.js'\nimport type { ResolvedCommand } from './types.js'\nimport { apiFetch, discoverEndpoints, getGrantsEndpoint } from './http.js'\nimport { appendGenericCallLog } from '../audit/generic-log.js'\nimport { isGenericResolved } from './generic.js'\n\nfunction decodePayload(token: string): Record<string, unknown> {\n const [, payload] = token.split('.')\n if (!payload)\n throw new Error('Invalid JWT')\n return JSON.parse(Buffer.from(payload, 'base64url').toString('utf-8')) as Record<string, unknown>\n}\n\ninterface SimilarGrantsInfo {\n similar_grants: Array<{ grant: { id: string }, similar_detail_indices: number[] }>\n widened_details: Array<{ permission: string }>\n merged_details: Array<{ permission: string }>\n}\n\nexport async function createShapesGrant(\n resolved: ResolvedCommand,\n params: {\n idp: string\n approval: 'once' | 'timed' | 'always'\n reason?: string\n },\n): Promise<{ id: string, status: string, similar_grants?: SimilarGrantsInfo }> {\n const grantsEndpoint = await getGrantsEndpoint(params.idp)\n const requester = getRequesterIdentity()\n if (!requester) {\n throw new Error('No requester identity available. Run `apes login` first.')\n }\n return apiFetch<{ id: string, status: string, similar_grants?: SimilarGrantsInfo }>(grantsEndpoint, {\n method: 'POST',\n idp: params.idp,\n body: {\n requester,\n target_host: hostname(),\n audience: resolved.adapter.cli.audience ?? 'shapes',\n grant_type: params.approval,\n command: resolved.executionContext.argv,\n reason: params.reason ?? resolved.detail.display,\n permissions: [resolved.permission],\n authorization_details: [resolved.detail],\n execution_context: resolved.executionContext,\n },\n })\n}\n\nexport async function waitForGrantStatus(idp: string, grantId: string): Promise<'approved' | 'denied' | 'revoked'> {\n const grantsEndpoint = await getGrantsEndpoint(idp)\n const deadline = Date.now() + 300_000\n\n while (Date.now() < deadline) {\n const grant = await apiFetch<{ status: 'pending' | 'approved' | 'denied' | 'revoked' }>(`${grantsEndpoint}/${grantId}`, { idp })\n if (grant.status === 'approved' || grant.status === 'denied' || grant.status === 'revoked')\n return grant.status\n await new Promise(resolve => setTimeout(resolve, 3000))\n }\n\n throw new Error('Timed out waiting for grant approval')\n}\n\nexport async function fetchGrantToken(idp: string, grantId: string): Promise<string> {\n const grantsEndpoint = await getGrantsEndpoint(idp)\n const response = await apiFetch<{ authz_jwt: string }>(`${grantsEndpoint}/${grantId}/token`, {\n method: 'POST',\n idp,\n })\n return response.authz_jwt\n}\n\nfunction grantedCliDetails(claims: Record<string, unknown>): OpenApeCliAuthorizationDetail[] {\n const details = claims.authorization_details\n if (!Array.isArray(details))\n return []\n\n return details.filter((detail): detail is OpenApeCliAuthorizationDetail =>\n typeof detail === 'object'\n && detail !== null\n && (detail as Record<string, unknown>).type === 'openape_cli',\n )\n}\n\nfunction hasStructuredCliGrant(claims: Record<string, unknown>): boolean {\n return grantedCliDetails(claims).length > 0\n}\n\n/**\n * Verifies a grant token against the resolved command and marks the grant\n * as consumed on the IdP. Does NOT execute anything — callers that want\n * the one-shot behavior should use `verifyAndExecute`, callers that want\n * to run the command themselves (e.g. the interactive REPL piping through\n * a persistent bash pty) should call this and then do their own execution.\n *\n * Split out so the interactive shell can re-use the verify + consume path\n * without being forced into the `execFileSync`-based one-shot execution.\n */\nexport async function verifyAndConsume(token: string, resolved: ResolvedCommand): Promise<void> {\n const payload = decodePayload(token)\n const issuer = String(payload.iss ?? '')\n if (!issuer)\n throw new Error('Grant token is missing issuer')\n\n const discovery = await discoverEndpoints(issuer)\n const jwksUri = String(discovery.jwks_uri ?? `${issuer}/.well-known/jwks.json`)\n const result = await verifyAuthzJWT(token, {\n expectedIss: issuer,\n expectedAud: resolved.adapter.cli.audience ?? 'shapes',\n jwksUri,\n })\n\n if (!result.valid || !result.claims) {\n throw new Error(result.error ?? 'Grant verification failed')\n }\n\n const claims = result.claims\n const details = grantedCliDetails(claims as unknown as Record<string, unknown>)\n\n if (claims.execution_context?.adapter_digest && claims.execution_context.adapter_digest !== resolved.digest) {\n throw new Error('Adapter digest mismatch')\n }\n\n if (!hasStructuredCliGrant(claims as unknown as Record<string, unknown>)) {\n const argv = resolved.executionContext.argv\n if (!argv?.length) {\n throw new Error('Resolved command is missing argv')\n }\n const expectedCmdHash = await computeCmdHash(argv.join(' '))\n if (claims.command?.join('\\0') !== argv.join('\\0')) {\n throw new Error('Granted command does not match current argv')\n }\n if (claims.cmd_hash && claims.cmd_hash !== expectedCmdHash) {\n throw new Error('Granted command does not match current argv')\n }\n if (!claims.command?.length && !claims.cmd_hash) {\n throw new Error('Grant is not a structured CLI grant and is missing command binding')\n }\n }\n else {\n if (!details.some(detail => cliAuthorizationDetailCovers(detail, resolved.detail))) {\n throw new Error(`Grant does not cover required permission: ${resolved.permission}`)\n }\n\n const exactRequired = details.some(detail =>\n cliAuthorizationDetailCovers(detail, resolved.detail) && detail.constraints?.exact_command,\n )\n\n const isOnce = claims.grant_type === 'once' || claims.approval === 'once'\n const enforceArgvHash = exactRequired || (isOnce && !!claims.execution_context?.argv_hash)\n\n if (enforceArgvHash && claims.execution_context?.argv_hash !== resolved.executionContext.argv_hash) {\n throw new Error('Granted command does not match current argv')\n }\n }\n\n const grantsEndpoint = await getGrantsEndpoint(issuer)\n const consume = await fetch(`${grantsEndpoint}/${claims.grant_id}/consume`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n })\n\n if (!consume.ok) {\n throw new Error(`Consume failed: ${consume.status} ${consume.statusText}`)\n }\n\n const consumeResult = await consume.json() as { error?: string }\n if (consumeResult.error) {\n throw new Error(`Grant rejected at consume step: ${consumeResult.error}`)\n }\n}\n\n/**\n * Execute a verified + consumed resolved command directly via execFileSync,\n * inheriting stdio so the caller's terminal is handed to the child. Used by\n * the one-shot `apes run --shell` path.\n */\nexport function executeResolvedViaExec(resolved: ResolvedCommand): void {\n consola.info(`Executing ${(resolved.executionContext.argv ?? [resolved.executable, ...resolved.commandArgv]).join(' ')}`)\n execFileSync(resolved.executable, resolved.commandArgv, { stdio: 'inherit' })\n}\n\n/**\n * One-shot verify + consume + execute. Preserves the legacy behavior of\n * the `apes run --shell` path so existing callers keep working unchanged.\n *\n * When `resolved` carries the generic-fallback operation id\n * (`_generic.exec`), a JSONL audit entry is appended to the generic-calls\n * log after the child process exits. `grantId` is needed to write the\n * entry — callers that know the grant id should pass it; if omitted, the\n * log entry is skipped (the audit hook is best-effort, not a hard gate).\n *\n * This is the central exec path for sync (`--wait`), async-default\n * (`apes grants run <id> --wait`), and REPL one-shot, so a hook here\n * covers all three flows without duplicating logic in each caller.\n */\nexport async function verifyAndExecute(\n token: string,\n resolved: ResolvedCommand,\n grantId?: string,\n): Promise<void> {\n await verifyAndConsume(token, resolved)\n\n const isGeneric = isGenericResolved(resolved)\n const start = Date.now()\n let exitCode = 0\n try {\n executeResolvedViaExec(resolved)\n }\n catch (err) {\n exitCode = (err as { status?: number })?.status ?? 1\n throw err\n }\n finally {\n if (isGeneric && grantId) {\n // Best-effort: swallow log errors so a broken audit file never\n // blocks a successful command.\n try {\n await appendGenericCallLog(\n {\n ts: new Date().toISOString(),\n cli: resolved.detail.cli_id,\n argv: resolved.executionContext.argv ?? [resolved.executable, ...resolved.commandArgv],\n argv_hash: resolved.executionContext.argv_hash ?? '',\n grant_id: grantId,\n exit_code: exitCode,\n duration_ms: Date.now() - start,\n },\n getGenericAuditLogPath(),\n )\n }\n catch (logErr) {\n consola.debug('Failed to append generic-call audit entry:', logErr)\n }\n }\n }\n}\n\n/**\n * Re-resolve a ResolvedCommand from a previously-created grant's recorded\n * request (argv + adapter digest). Used by `apes grants run <id>` to replay\n * an approved grant locally after the async approval step.\n *\n * Throws when the grant is missing argv, when the adapter cannot be loaded,\n * or when the locally installed adapter's digest no longer matches what the\n * grant was issued against.\n */\nexport async function resolveFromGrant(\n grant: {\n request: {\n command?: string[]\n execution_context?: { adapter_digest?: string, argv_hash?: string }\n authorization_details?: Array<{ type?: string, permission?: string }>\n }\n },\n): Promise<ResolvedCommand> {\n const argv = grant.request?.command\n if (!argv || argv.length === 0)\n throw new Error('Grant request is missing command argv')\n\n const executable = argv[0]\n const adapter = await loadOrInstallAdapter(executable)\n if (!adapter)\n throw new Error(`No shapes adapter found for ${executable}`)\n\n const resolved = await resolveCommand(adapter, argv)\n\n const grantDigest = grant.request.execution_context?.adapter_digest\n if (grantDigest && grantDigest !== resolved.digest) {\n throw new Error(\n `Adapter digest mismatch: grant was created against adapter ${grantDigest}, but local adapter is ${resolved.digest}. Reinstall or revert the adapter.`,\n )\n }\n\n return resolved\n}\n\nexport async function findExistingGrant(\n resolved: ResolvedCommand,\n idp: string,\n): Promise<string | null> {\n const grantsEndpoint = await getGrantsEndpoint(idp)\n const response = await apiFetch<{ data: OpenApeGrant[] }>(\n `${grantsEndpoint}?status=approved`,\n { idp },\n )\n\n const now = Math.floor(Date.now() / 1000)\n const expectedAudience = resolved.adapter.cli.audience ?? 'shapes'\n\n for (const grant of response.data) {\n const req = grant.request\n if (req.grant_type === 'once')\n continue\n if (req.grant_type === 'timed' && grant.expires_at && grant.expires_at <= now)\n continue\n if (req.audience !== expectedAudience)\n continue\n if (req.execution_context?.adapter_digest && req.execution_context.adapter_digest !== resolved.digest)\n continue\n\n const cliDetails = (req.authorization_details ?? []).filter(\n (d): d is OpenApeCliAuthorizationDetail => d.type === 'openape_cli',\n )\n\n if (cliDetails.length > 0) {\n if (cliDetails.some(detail => cliAuthorizationDetailCovers(detail, resolved.detail)))\n return grant.id\n }\n else if (req.permissions?.includes(resolved.permission)) {\n return grant.id\n }\n }\n\n return null\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\ninterface AuthData {\n idp: string\n access_token: string\n email: string\n expires_at: number\n}\n\nconst AUTH_FILE = join(homedir(), '.config', 'apes', 'auth.json')\n\nexport function loadAuth(): AuthData | null {\n if (!existsSync(AUTH_FILE))\n return null\n try {\n return JSON.parse(readFileSync(AUTH_FILE, 'utf-8')) as AuthData\n }\n catch {\n return null\n }\n}\n\nexport function getIdpUrl(explicit?: string): string | null {\n if (explicit)\n return explicit\n if (process.env.APES_IDP)\n return process.env.APES_IDP\n if (process.env.SHAPES_IDP)\n return process.env.SHAPES_IDP\n return loadAuth()?.idp ?? null\n}\n\nexport function getAuthToken(): string | null {\n const auth = loadAuth()\n if (!auth)\n return null\n if (auth.expires_at && Date.now() / 1000 > auth.expires_at - 30)\n return null\n return auth.access_token\n}\n\nexport function getRequesterIdentity(): string | null {\n return loadAuth()?.email ?? null\n}\n","import { getAuthToken, getIdpUrl } from './config.js'\n\nexport async function discoverEndpoints(idpUrl: string): Promise<Record<string, unknown>> {\n const response = await fetch(`${idpUrl}/.well-known/openid-configuration`)\n if (!response.ok)\n return {}\n return response.json() as Promise<Record<string, unknown>>\n}\n\nexport async function getGrantsEndpoint(idpUrl: string): Promise<string> {\n const discovery = await discoverEndpoints(idpUrl)\n return String(discovery.openape_grants_endpoint ?? `${idpUrl}/api/grants`)\n}\n\nexport async function apiFetch<T>(\n path: string,\n options: {\n method?: string\n body?: unknown\n idp?: string\n token?: string\n } = {},\n): Promise<T> {\n const token = options.token ?? getAuthToken()\n if (!token)\n throw new Error('Not authenticated. Run `apes login` first.')\n\n const idp = options.idp ?? getIdpUrl()\n if (!path.startsWith('http') && !idp)\n throw new Error('No IdP URL configured. Use --idp or log in with apes.')\n\n const url = path.startsWith('http') ? path : `${idp}${path}`\n const response = await fetch(url, {\n method: options.method ?? 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: options.body ? JSON.stringify(options.body) : undefined,\n })\n\n if (!response.ok) {\n const text = await response.text()\n throw new Error(text || `${response.status} ${response.statusText}`)\n }\n\n return response.json() as Promise<T>\n}\n","import { mkdir, appendFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\n\n/**\n * A single successful generic-fallback execution entry.\n * Denied, timeout, and cancelled grants are NOT logged here — they are\n * captured by the IdP's server-side audit trail.\n */\nexport interface GenericCallLogEntry {\n /** ISO 8601 timestamp of execution completion */\n ts: string\n /** CLI id as requested by the user (e.g. \"kubectl\") */\n cli: string\n /** Full argv as executed, including the executable */\n argv: string[]\n /** SHA-256 of the argv — matches the `argv:hash` selector in resource_chain */\n argv_hash: string\n /** Grant that authorized this execution */\n grant_id: string\n /** Process exit code */\n exit_code: number\n /** Wall-clock duration from grant-approval to process exit, milliseconds */\n duration_ms: number\n}\n\n/**\n * Default audit log location. Lives under `~/.config/apes/` for consistency\n * with the rest of apes' client state (`config.toml`, `auth.json`, …).\n */\nexport function defaultGenericLogPath(): string {\n return join(homedir(), '.config', 'apes', 'generic-calls.log')\n}\n\n/**\n * Append a single generic-call entry to the audit log in JSONL format.\n * Creates the containing directory if needed.\n *\n * @param entry The call record to append\n * @param logPath Optional override (usually from `config.generic.audit_log`)\n */\nexport async function appendGenericCallLog(\n entry: GenericCallLogEntry,\n logPath?: string,\n): Promise<void> {\n const path = logPath ?? defaultGenericLogPath()\n await mkdir(dirname(path), { recursive: true })\n await appendFile(path, `${JSON.stringify(entry)}\\n`, 'utf-8')\n}\n","import { computeCmdHash } from '@openape/core'\nimport type { BuiltGrantRequest, GrantRequestOptions, ResolvedCapability, ResolvedCommand } from './types.js'\n\nexport async function buildExactCommandGrantRequest(\n command: string[],\n options: GrantRequestOptions & {\n audience: string\n },\n): Promise<BuiltGrantRequest> {\n return {\n request: {\n requester: options.requester,\n target_host: options.target_host,\n audience: options.audience,\n grant_type: options.grant_type,\n command,\n cmd_hash: await computeCmdHash(command.join(' ')),\n ...(options.reason ? { reason: options.reason } : {}),\n ...(options.run_as ? { run_as: options.run_as } : {}),\n },\n }\n}\n\nexport async function buildStructuredCliGrantRequest(\n resolved: ResolvedCommand | ResolvedCapability,\n options: GrantRequestOptions,\n): Promise<BuiltGrantRequest> {\n const details = 'detail' in resolved ? [resolved.detail] : resolved.details\n const permissions = 'permission' in resolved ? [resolved.permission] : resolved.permissions\n const command = 'executionContext' in resolved && resolved.executionContext.argv?.length\n ? resolved.executionContext.argv\n : undefined\n\n return {\n request: {\n requester: options.requester,\n target_host: options.target_host,\n audience: resolved.adapter.cli.audience ?? 'shapes',\n grant_type: options.grant_type,\n permissions,\n authorization_details: details,\n execution_context: resolved.executionContext,\n ...(command ? { command } : {}),\n ...(options.reason ? { reason: options.reason } : { reason: 'summary' in resolved ? resolved.summary : details[0]?.display }),\n ...(options.run_as ? { run_as: options.run_as } : {}),\n },\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,aAAa,oBAAoB;AACtD,SAAS,eAAe;AACxB,SAAS,UAAU,YAAY;;;ACK/B,SAAS,cAAc,MAAqD;AAC1E,QAAM,UAAU,KAAK,QAAQ,GAAG;AAChC,MAAI,YAAY;AACd,WAAO;AACT,QAAM,MAAM,KAAK,MAAM,GAAG,OAAO,EAAE,KAAK;AACxC,QAAM,QAAQ,KAAK,MAAM,UAAU,CAAC,EAAE,KAAK;AAC3C,MAAI,CAAC,OAAO,CAAC;AACX,WAAO;AACT,SAAO,EAAE,KAAK,MAAM;AACtB;AAEA,SAAS,eAAe,KAAsB;AAC5C,QAAM,UAAU,IAAI,KAAK;AAEzB,MAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG;AACjD,WAAO,QAAQ,MAAM,GAAG,EAAE;AAC5B,MAAI,YAAY;AACd,WAAO;AACT,MAAI,YAAY;AACd,WAAO;AACT,MAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,GAAG;AACpD,UAAM,QAAQ,QAAQ,MAAM,GAAG,EAAE,EAAE,KAAK;AACxC,QAAI,CAAC;AACH,aAAO,CAAC;AACV,WAAO,MAAM,MAAM,GAAG,EAAE,IAAI,WAAS,MAAM,KAAK,EAAE,QAAQ,UAAU,EAAE,CAAC;AAAA,EACzE;AAEA,SAAO;AACT;AAEO,SAAS,iBAAiB,SAAgC;AAC/D,QAAM,SAA0B,CAAC;AACjC,QAAM,a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pB;AAAA,MACA,UAAU,MAAMA,gBAAe,QAAQ,KAAK,GAAG,CAAC;AAAA,MAChD,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,MACnD,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,IACrD;AAAA,EACF;AACF;AAEA,eAAsB,+BACpB,UACA,SAC4B;AAC5B,QAAM,UAAU,YAAY,WAAW,CAAC,SAAS,MAAM,IAAI,SAAS;AACpE,QAAM,cAAc,gBAAgB,WAAW,CAAC,SAAS,UAAU,IAAI,SAAS;AAChF,QAAM,UAAU,sBAAsB,YAAY,SAAS,iBAAiB,MAAM,SAC9E,SAAS,iBAAiB,OAC1B;AAEJ,SAAO;AAAA,IACL,SAAS;AAAA,MACP,WAAW,QAAQ;AAAA,MACnB,aAAa,QAAQ;AAAA,MACrB,UAAU,SAAS,QAAQ,IAAI,YAAY;AAAA,MAC3C,YAAY,QAAQ;AAAA,MACpB;AAAA,MACA,uBAAuB;AAAA,MACvB,mBAAmB,SAAS;AAAA,MAC5B,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,MAC7B,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,EAAE,QAAQ,aAAa,WAAW,SAAS,UAAU,QAAQ,CAAC,GAAG,QAAQ;AAAA,MAC3H,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,IACrD;AAAA,EACF;AACF;","names":["existsSync","homedir","join","createHash","existsSync","mkdirSync","readdirSync","readFileSync","homedir","join","digest","existsSync","join","homedir","readdirSync","readFileSync","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","join","basename","basename","canonicalizeCliPermission","canonicalizeCliPermission","computeArgvHash","consola","existsSync","readFileSync","homedir","join","homedir","dirname","join","consola","computeCmdHash"]}
|
|
File without changes
|
|
File without changes
|