pi-keeper 0.1.0 → 0.1.1

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.
@@ -21,23 +21,116 @@ const TEXT_HEAD = 120;
21
21
  const VALUE = String.raw`"[^"]*"|'[^']*'|[^\s"']+`;
22
22
  /** Credential-like flag names: whole `-`/`_`-separated parts (`--token`, `--api-key`, `--password`), not `--author`. */
23
23
  const SECRET_FLAG = /^--(?:[\w-]*[-_])?(?:token|tokens|password|passwd|pass|secret|secrets|credentials?|auth|apikey|api[-_]key)(?:[-_][\w-]*)?$/i;
24
+ /** Credential-like header and field names (`X-Api-Key`, `Cookie`, `PRIVATE-TOKEN`, `Authorization`; `auth` alone, not `author`). */
25
+ const SECRET_HEADER = /api[-_]?key|token|cookie|secret|password|passwd|authorization|auth(?!or)/i;
26
+ /**
27
+ * Bounded scan between a command word and its option: keeps every match linear in the text
28
+ * (an unbounded scan from each `mysql ` in a long run is quadratic).
29
+ */
30
+ const SCAN = "{0,200}?";
31
+
32
+ /** Keeps the user of a `user:password` value and hides the password; a value without a colon is kept. */
33
+ function hidePassword(value: string): string {
34
+ const colon = value.indexOf(":");
35
+ return colon < 0 ? value : `${value.slice(0, colon + 1)}***`;
36
+ }
24
37
 
25
38
  /**
26
39
  * The command text as the session log keeps it: the values of `Authorization:`
27
40
  * headers, `Bearer` tokens, credential-like `--flag value` / `--flag=value`
28
41
  * options and credential-like `NAME=value` assignments become `***`; the rest
29
42
  * of the command is kept. Judged by the same secret names as the rules
30
- * (SECRET_ENV_NAME), so a plain `--author` or `GIT_AUTHOR_NAME` is untouched.
43
+ * (SECRET_ENV_NAME), so a plain `--author` is untouched (a name holding
44
+ * `AUTH`, such as `GIT_AUTHOR_NAME`, counts as credential-like and is hidden).
31
45
  */
32
46
  export function redactCommand(command: string): string {
33
47
  return command
34
48
  .replace(new RegExp(String.raw`(authorization:\s*)(?:(?:bearer|basic|token)\s+)?(?:${VALUE})`, "gi"), "$1***")
35
49
  .replace(new RegExp(String.raw`(\bbearer\s+)(?:${VALUE})`, "gi"), "$1***")
50
+ // `-u user:password` / `--user user:password`: the user name stays, the password goes
51
+ .replace(new RegExp(String.raw`(?<![\w-])(--user(?:\s+|=)|-u\s+)(${VALUE})`, "g"), (match, flag: string, value: string) => {
52
+ const quote = value.startsWith('"') || value.startsWith("'") ? value[0] : "";
53
+ const inner = quote === "" ? value : value.slice(1, -1);
54
+ const hidden = hidePassword(inner);
55
+ return hidden === inner ? match : `${flag}${quote}${hidden}${quote}`;
56
+ })
57
+ // `-u:secret` / `-uuser:secret` (attached): the whole value goes
58
+ .replace(/(?<![\w-])-u(?=[^\s"']*:)[^\s"']+/g, "-u***")
59
+ // `scheme://user:password@host`: the password goes; a match starts only at a scheme boundary, so this is linear
60
+ .replace(/(?<![a-z0-9+.-])([a-z][a-z0-9+.-]*:\/\/[^\s:/@"']+):[^\s/@"']+@/gi, "$1:***@")
61
+ // `-H "Name: value"`, `--header 'Name: value'`, `--header=Name: value`, `-HName:value`: a credential-like header's value goes
62
+ .replace(/(-H\s*|--header(?:\s+|=))(["'])([\w-]+)(:\s*)[^"'\n]*\2/gi, (match, flag: string, quote: string, name: string, sep: string) =>
63
+ SECRET_HEADER.test(name) ? `${flag}${quote}${name}${sep}***${quote}` : match,
64
+ )
65
+ .replace(/(-H\s*|--header(?:\s+|=))([\w-]+)(:\s*)[^\s"']+/gi, (match, flag: string, name: string, sep: string) => (SECRET_HEADER.test(name) ? `${flag}${name}${sep}***` : match))
66
+ // a bare header line or `name: value` with a credential-like name, at the start or after a space or quote
67
+ .replace(/(^|[\s"'])([\w-]+)(:[ \t]*)[^\s"']+/g, (match, lead: string, name: string, sep: string) => (SECRET_HEADER.test(name) ? `${lead}${name}${sep}***` : match))
68
+ // `mysql -psecret`, `sshpass -psecret` (attached): the password goes, `-p` stays
69
+ .replace(new RegExp(String.raw`(\b(?:mysql|mysqldump|mariadb|sshpass)\b[^;&|]${SCAN}\s)-p(?=\S)\S+`, "g"), "$1-p***")
70
+ // `docker login -p secret`, `sshpass -p secret`
71
+ .replace(new RegExp(String.raw`(\b(?:docker\s+login|sshpass)\b[^;&|]${SCAN}\s-p\s+)(?:${VALUE})`, "g"), "$1***")
72
+ // `redis-cli -a secret`
73
+ .replace(new RegExp(String.raw`(\bredis-cli\b[^;&|]${SCAN}\s-a\s+)(?:${VALUE})`, "g"), "$1***")
36
74
  .replace(/(--[\w-]+)(=|\s+)(?:"[^"]*"|'[^']*'|[^\s"'-][^\s"']*)/g, (match, flag: string, sep: string) => (SECRET_FLAG.test(flag) ? `${flag}${sep}***` : match))
37
75
  // not after `-` (that is a flag's `--name=value`, judged above)
38
76
  .replace(new RegExp(String.raw`(?<![\w-])([A-Za-z_][A-Za-z0-9_]*)=(?:${VALUE})`, "g"), (match, name: string) => (SECRET_ENV_NAME.test(name) ? `${name}=***` : match));
39
77
  }
40
78
 
79
+ /** A string that is a JSON object or array is redacted as the JSON it is; its own text is kept when nothing in it is hidden. */
80
+ function redactJsonText(text: string): string {
81
+ const trimmed = text.trim();
82
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return redactCommand(text);
83
+ let parsed: unknown;
84
+ try {
85
+ parsed = JSON.parse(trimmed);
86
+ } catch {
87
+ return redactCommand(text);
88
+ }
89
+ const redacted = JSON.stringify(redactInput(parsed));
90
+ return redacted === JSON.stringify(parsed) ? text : redacted;
91
+ }
92
+
93
+ /** The name a record names itself by (`name`, else `key`), for the `{name, value}` shape. */
94
+ function labelOf(record: Record<string, unknown>): string | undefined {
95
+ if (typeof record.name === "string") return record.name;
96
+ return typeof record.key === "string" ? record.key : undefined;
97
+ }
98
+
99
+ /**
100
+ * A copy of a non-bash input for the log: a string under a secret-named key (at any depth, SECRET_ENV_NAME or
101
+ * a credential-like header name) becomes "***", the element after a secret flag or `-u` in an array is masked,
102
+ * the `value` of a `{name, value}` object naming a credential is masked, and every other string goes through
103
+ * redactCommand (or, when it is JSON, through this function again).
104
+ */
105
+ function redactInput(value: unknown, secret = false): unknown {
106
+ if (typeof value === "string") return secret ? "***" : redactJsonText(value);
107
+ if (Array.isArray(value)) {
108
+ let next: "secret" | "user" | undefined;
109
+ return value.map((item) => {
110
+ const mask = next;
111
+ next = undefined;
112
+ if (typeof item === "string" && mask !== undefined) return mask === "secret" ? "***" : hidePassword(item);
113
+ if (typeof item === "string") {
114
+ if (SECRET_FLAG.test(item)) next = "secret";
115
+ else if (item === "-u" || item === "--user") next = "user";
116
+ }
117
+ return redactInput(item, secret);
118
+ });
119
+ }
120
+ if (value !== null && typeof value === "object") {
121
+ const record = value as Record<string, unknown>;
122
+ const label = labelOf(record);
123
+ const namedSecret = label !== undefined && SECRET_HEADER.test(label);
124
+ return Object.fromEntries(
125
+ Object.entries(record).map(([key, inner]) => [
126
+ key,
127
+ redactInput(inner, secret || SECRET_ENV_NAME.test(key) || SECRET_HEADER.test(key) || (namedSecret && key === "value")),
128
+ ]),
129
+ );
130
+ }
131
+ return value;
132
+ }
133
+
41
134
  function shrink(text: string, limit: number): string {
42
135
  return text.length > limit ? `${text.slice(0, limit)}…` : text;
43
136
  }
@@ -58,7 +151,7 @@ export function targetOf(call: ToolCall): string {
58
151
  if (call.toolName === "bash" || call.toolName === "powershell") return redactCommand(commandOf(call.input));
59
152
  const path = pathOf(call.input);
60
153
  if (path !== "") return path;
61
- return JSON.stringify(call.input ?? {});
154
+ return JSON.stringify(redactInput(call.input ?? {}));
62
155
  }
63
156
 
64
157
  /** A permission decision on a tool call ("decide"), or its re-evaluation after a queued dialog ("redecide"). */
@@ -118,6 +211,10 @@ export type ChoiceOutcome =
118
211
  | "remote-auto-deny"
119
212
  | "remote-cancelled"
120
213
  | "parent-gone"
214
+ // background asks were turned off in the parent while the request waited
215
+ | "asks-off"
216
+ // a request the parent already allowed for the session when its dialog came up: no dialog, not the user's answer
217
+ | "covered"
121
218
  // a background child's own ask, sent to its parent (the choice holds the answer)
122
219
  | "parent-ask";
123
220
 
@@ -62,6 +62,8 @@ export interface UiRelaySessionRules {
62
62
  outsideReadDirs?: readonly string[];
63
63
  /** Hosts granted for curl/wget GETs ("Yes, allow fetching from <host> this session"). Optional: an older parent publishes none. */
64
64
  fetchHosts?: readonly string[];
65
+ /** Realpaths of git repo roots granted for the session ("Yes, and allow git in <repo>/ this session"). Optional: an older parent publishes none. */
66
+ gitRepos?: readonly string[];
65
67
  /** The parent session's working directory: a child's cwd must lie in its project (child-cwd.ts). Optional: an older parent publishes none. */
66
68
  cwd?: string;
67
69
  /** The parent session's current thinking level (`/keeper subagent-thinking: follow` runs the child at the higher of this and its own). Optional: an older parent publishes none. */
@@ -95,6 +97,8 @@ export interface UiRelay {
95
97
  grantReadDirs?(dirs: readonly string[]): void;
96
98
  /** Add hosts to the parent's fetch grants (answered in a child). Optional: an older parent lacks it and the child keeps the grant locally. */
97
99
  grantFetchHosts?(hosts: readonly string[]): void;
100
+ /** Add git repo roots to the parent's session grants (answered in a child). Optional: an older parent lacks it and the child keeps the grant locally. */
101
+ grantGitRepos?(roots: readonly string[]): void;
98
102
  }
99
103
 
100
104
  export interface RelayOptions {
@@ -115,7 +119,8 @@ function isRelay(value: unknown): value is UiRelay {
115
119
  typeof candidate.rememberSession === "function" &&
116
120
  typeof candidate.setSessionFlag === "function" &&
117
121
  (candidate.grantReadDirs === undefined || typeof candidate.grantReadDirs === "function") &&
118
- (candidate.grantFetchHosts === undefined || typeof candidate.grantFetchHosts === "function")
122
+ (candidate.grantFetchHosts === undefined || typeof candidate.grantFetchHosts === "function") &&
123
+ (candidate.grantGitRepos === undefined || typeof candidate.grantGitRepos === "function")
119
124
  );
120
125
  }
121
126