UNPKG

akm-cli

Version:

akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur

113 lines (112 loc) • 5.86 kB
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. /** * Environment asset type (`env`) — whole `.env` file storage. * * An `env` asset holds a GROUP of related CONFIGURATION for an app or service * (URLs, feature flags, and any credentials it needs) in a single `.env` file, * sourced/injected wholesale. Values may or may not be sensitive — akm protects * them all the same. For a single sensitive value used on its own for * authentication (a token, key, or cert), use the `secret` type instead. * * akm does not manage individual keys — edit the `.env` file with your own * editor. Values are quoted/escaped only when necessary and round-trip * through `dotenv`; the shell-load safety guarantee lives on the READ path * (see `buildShellExportScript` + `akm env export`). * * Invariant: nothing from an env file except key NAMES may be written to * stdout, returned through the indexer, the `akm show` renderer, or any * structured output channel. Key NAMES are surfaced for discoverability; * comment text is NOT — real .env files routinely carry commented-out * `KEY=value` lines and free-text notes containing live credentials, so * comments are treated exactly like values. The supported value-load paths * are: * * - `akm run --env <ref> scripts/<file>` — values injected into the child * process env (never via a shell), see `parseEnvText` (loaded by * `env-binding.ts#resolveEnvBinding`). This is the primary path and the * only one safe for AI agents (no values ever reach stdout). The * Deprecated `akm env run <ref> -- <command>` does the same for one command * until 0.11. * - `akm env export <ref> --out <file>` — write parse-then-reserialized safe * `export KEY='value'` lines to a file (mode 0600) for `source`-ing. Values * are re-emitted single-quoted so a raw `.env` containing `X=$(cmd)` cannot * execute on load. `export` never prints values to stdout (would leak into * an agent's context); `path` prints only the file path. * * Value parsing is delegated to the `dotenv` package. * * Ref-token substitution: env VALUES may embed `${ref}` tokens (a secret's * value, or any other asset's path), replaced when the env is injected (see * `substituteRefTokens` in core/ref-token.ts and `resolveEnvBinding`). * Substitution applies to values only, never keys; shell-style `${VAR}` / * `$VAR` are left untouched. */ import dotenv from "dotenv"; /** * One env-line shape. It mirrors dotenv's LINE pattern, so the two agree on which lines are assignments, * except that the unquoted alternative takes the rest of the line so `unquotedValue` can decide where a * comment starts. */ const ENV_ASSIGNMENT = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^\r\n]+)?\s*(?:#.*)?$/gm; /** The unquoted value on a line's remainder: a `#` starts a comment only after a space or tab. */ function unquotedValue(rest) { for (let i = 0; i < rest.length; i++) { if (rest[i] === "#" && (rest[i - 1] === " " || rest[i - 1] === "\t")) return rest.slice(0, i).trim(); } return rest.trim(); } /** * Parse env file text into KEY/value pairs. This is the one parser every env-file read uses. * * dotenv parses the text (quoting, `export`, multi-line values, escapes). In an unquoted value a `#` * starts a comment only after a space or tab (as bash `source` and docker * compose read it), so `URL=http://x/y#frag` keeps its `#`: each unquoted assignment's value is set from * `unquotedValue`, in file order, so a later quoted assignment of the same key still wins. */ export function parseEnvText(content) { const text = content.toString().replace(/\r\n?/g, "\n"); const unquoted = new Map(); for (const [, key, rest] of text.matchAll(ENV_ASSIGNMENT)) { if (key === undefined) continue; if (rest === undefined || /^\s*['"`]/.test(rest)) unquoted.delete(key); else unquoted.set(key, unquotedValue(rest)); } return { ...dotenv.parse(text), ...Object.fromEntries(unquoted) }; } /** * Serialise an env file's values as a POSIX shell script of `export KEY='value'` * lines, with single-quote escaping (`'\''`). Every line is an assignment of a * literal string — there is no expansion, command substitution, or * non-assignment content, so `eval`-ing the output is safe regardless of what * the source file contains. * * This is the trust boundary for shell loading: a raw `.env` may contain * `X=$(rm -rf ~)`, which would execute if `source`d directly, but dotenv parses * it to the literal string `$(rm -rf ~)` and we re-emit it single-quoted. This * backs `akm env export <ref> --out <file>` (file-only; never printed to stdout). * * NOTE: `${ref}` token substitution is intentionally NOT applied here. The * export path emits values single-quoted as literals, so an unsubstituted * `${secrets/name}` is written verbatim (it would expand to nothing under POSIX * shells, never to the secret). Token resolution is scoped to the value * injection path only; see `resolveEnvBinding`. */ export function buildShellExportScript(envText) { const env = parseEnvText(envText); const lines = []; for (const [key, value] of Object.entries(env)) { // Defence in depth: dotenv already validates key shape, but reject any // key we wouldn't be able to export safely. if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue; const escaped = value.replace(/'/g, "'\\''"); lines.push(`export ${key}='${escaped}'`); } return lines.length > 0 ? `${lines.join("\n")}\n` : ""; }