@safekb/mcp 0.12.1 → 0.13.0

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/README.md CHANGED
@@ -377,15 +377,15 @@ custom fields and the key name of every custom field (sealed ones too) stay read
377
377
  sealed credentials start with the tenant default (Settings → Sealed credentials; `use_only` until
378
378
  set). Only you make anything more visible, in the SafeKB app; `set_sealed_credential_llm_visibility`
379
379
  only tightens. The client enforces this: a client older than 0.11.0 reveals every sealed credential, and 0.11.0 ignores field overrides.
380
- - Using a secret without showing it (0.12.0): `secret_exec` runs a program with it in env or stdin
381
- (never argv), `secret_http` sends one request with it in the url, headers or body (redirects are not
382
- followed), and `secret_adb_input` types it on an Android device (`adb shell input text`, value on stdin;
383
- printable ASCII only). The agent names it by handle, `{{secret://<credential_id>/<field>}}`; a `totp`
384
- handle becomes the current code. `|form`, `|json` or `|url` encodes the value for where it goes
385
- (`{{secret://<id>/password|form}}` in a form body); without one it goes in as is, URL-encoded in a url.
386
- `visible` and `use_only` fields can be used; `human_only` fields never.
387
- Output comes back scrubbed of the value, in any mix of percent-, form-, JSON- and adb-encoding and as
388
- base64 or hex, with the credentials and fields used. Scrubbing stops careless leaks, not a program written to leak one.
380
+ - Using a secret without showing it: SafeKB only provides the value. `secret_exec` runs your own
381
+ program with it in env, stdin or a temp file (`files`, mode 0600, deleted afterwards), never argv;
382
+ every integration (HTTP API, browser form, `adb shell input text`, ssh, wallet, `cryptsetup`, …) is
383
+ that program. The agent names a secret by handle, `{{secret://<credential_id>/<field>}}`; a `totp`
384
+ handle becomes the current code, and `|form`, `|json` or `|url` encodes the value for where the
385
+ program puts it unchanged. `visible` and `use_only` fields can be used; `human_only` fields never.
386
+ Output comes back scrubbed of the value, in any mix of percent-, form- and JSON-encoding and as
387
+ base64 or hex, with the credentials and fields used. Scrubbing stops careless leaks, not a program
388
+ written to leak one.
389
389
  - Visible fields can be edited without the secret. Such an edit is flagged (`visible_tampered`) with the
390
390
  changed fields until a signed save accepts it (`accept_visible_changes`).
391
391
 
@@ -2581,7 +2581,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
2581
2581
  // package.json
2582
2582
  var package_default = {
2583
2583
  name: "@safekb/mcp",
2584
- version: "0.12.1",
2584
+ version: "0.13.0",
2585
2585
  description: "SafeKB local MCP client: proxies the hosted SafeKB tools and adds zero-knowledge sealed documents.",
2586
2586
  license: "SEE LICENSE IN LICENSE",
2587
2587
  author: "Mustafa Öztürk",
@@ -8971,7 +8971,7 @@ class CredentialAccess {
8971
8971
  return this.decrypt(await this.ctx.api.fetchSealedCredential(credentialId));
8972
8972
  }
8973
8973
  async openForReveal(credentialId, field) {
8974
- return this.openAllowing(credentialId, field, REVEALABLE, (visibility) => visibility === "use_only" ? "it is never shown to an LLM. Use it without seeing it: secret_exec, secret_http or secret_adb_input with the handle secret://<credential_id>/<field>." : "it is never shown to an LLM and never handed to a tool: ask the user to enter it.");
8974
+ return this.openAllowing(credentialId, field, REVEALABLE, (visibility) => visibility === "use_only" ? "it is never shown to an LLM. Use it without seeing it: secret_exec hands it to your own program with the handle {{secret://<credential_id>/<field>}}." : "it is never shown to an LLM and never handed to a tool: ask the user to enter it.");
8975
8975
  }
8976
8976
  async openForUse(credentialId, field) {
8977
8977
  return this.openAllowing(credentialId, field, USABLE, () => "no tool may use it: ask the user to enter it.");
@@ -9105,14 +9105,6 @@ function hasHandle(text) {
9105
9105
  function fillHandles(text, lookup, fallback = "raw") {
9106
9106
  return text.replace(HANDLE, (_, credentialId, field, encoding2) => ENCODINGS[encodingOf(encoding2, fallback)](lookup({ credentialId, field })));
9107
9107
  }
9108
- function requireHandlesAfterOrigin(url) {
9109
- const first = url.search(ANY_HANDLE);
9110
- if (first === -1)
9111
- return;
9112
- if (!/^https?:\/\/[^/?#{}]+[/?#]/.test(url.slice(0, first))) {
9113
- throw new ClientError("A secret handle can go in the path, query or fragment of a url, never in its scheme, host or port.");
9114
- }
9115
- }
9116
9108
 
9117
9109
  // src/sinks/secretResolver.ts
9118
9110
  var TOTP_FIELD = "totp";
@@ -35921,6 +35913,11 @@ function keyTools(parts) {
35921
35913
  ];
35922
35914
  }
35923
35915
 
35916
+ // src/sinks/execSink.ts
35917
+ import { mkdtemp, rm as rm4, writeFile } from "node:fs/promises";
35918
+ import { tmpdir } from "node:os";
35919
+ import { join as join9 } from "node:path";
35920
+
35924
35921
  // src/sinks/processRunner.ts
35925
35922
  import { spawn as spawn3 } from "node:child_process";
35926
35923
  var MAX_CAPTURE_BYTES = 1024 * 1024;
@@ -36005,74 +36002,9 @@ async function runProcess(request) {
36005
36002
  });
36006
36003
  }
36007
36004
 
36008
- // src/sinks/adbSink.ts
36009
- var ADB_TIMEOUT_MS = 15000;
36010
- var PRINTABLE_ASCII = /^[\x20-\x7e]*$/;
36011
- var FOCUSED_PACKAGE = /mCurrentFocus=Window\{\S+ \S+ ([^/\s}]+)/;
36012
- function adbInputCommand(value) {
36013
- if (!PRINTABLE_ASCII.test(value)) {
36014
- throw new ClientError("adb input text types printable ASCII only; this value has other characters. The user has to enter it.");
36015
- }
36016
- if (value.includes("%s")) {
36017
- throw new ClientError("adb input text reads %s as a space, so this value cannot be typed exactly. The user has to enter it.");
36018
- }
36019
- const quoted = value.replaceAll(" ", "%s").replaceAll("'", `'\\''`);
36020
- return `input text '${quoted}'
36021
- `;
36022
- }
36023
-
36024
- class AdbSink {
36025
- resolver;
36026
- adb;
36027
- constructor(resolver, adb = "adb") {
36028
- this.resolver = resolver;
36029
- this.adb = adb;
36030
- }
36031
- async input(args) {
36032
- if (refsIn(args.text).length === 0) {
36033
- throw new ClientError("text needs a secret handle: {{secret://<credential_id>/<field>}}");
36034
- }
36035
- const target = args.serial === undefined ? [] : ["-s", args.serial];
36036
- const secrets = await this.resolver.resolve([args.text]);
36037
- const value = secrets.fill(args.text);
36038
- const command = adbInputCommand(value);
36039
- await this.requireFocus(target, args.expect_package);
36040
- await this.shell(target, command, secrets);
36041
- return {
36042
- entered_length: value.length,
36043
- package: args.expect_package,
36044
- used: secrets.used()
36045
- };
36046
- }
36047
- async requireFocus(target, expected) {
36048
- const outcome = await runProcess({
36049
- argv: [this.adb, ...target, "shell", "dumpsys", "window"],
36050
- timeoutMs: ADB_TIMEOUT_MS
36051
- });
36052
- if (outcome.exitCode !== 0) {
36053
- throw new ClientError(`adb could not read the focused window: ${outcome.stderr.trim()}`);
36054
- }
36055
- const focused = FOCUSED_PACKAGE.exec(outcome.stdout)?.[1];
36056
- if (focused === undefined) {
36057
- throw new ClientError("No focused app found on the device (is it locked?); nothing was typed.");
36058
- }
36059
- if (focused !== expected) {
36060
- throw new ClientError(`The focused app is ${focused}, not ${expected}; nothing was typed.`);
36061
- }
36062
- }
36063
- async shell(target, command, secrets) {
36064
- const outcome = await runProcess({
36065
- argv: [this.adb, ...target, "shell", "-T"],
36066
- stdin: command,
36067
- timeoutMs: ADB_TIMEOUT_MS
36068
- });
36069
- if (outcome.exitCode !== 0 || outcome.timedOut) {
36070
- throw new ClientError(`adb input text failed (exit ${outcome.exitCode}${outcome.timedOut ? ", timed out" : ""}): ${secrets.redact(`${outcome.stderr}${outcome.stdout}`).trim()}`);
36071
- }
36072
- }
36073
- }
36074
-
36075
36005
  // src/sinks/execSink.ts
36006
+ var filled = (texts, secrets) => Object.fromEntries(Object.entries(texts).map(([name, text2]) => [name, secrets.fill(text2)]));
36007
+
36076
36008
  class ExecSink {
36077
36009
  resolver;
36078
36010
  constructor(resolver) {
@@ -36080,108 +36012,49 @@ class ExecSink {
36080
36012
  }
36081
36013
  async run(args) {
36082
36014
  if (args.argv.some(hasHandle)) {
36083
- throw new ClientError("A secret handle cannot go in argv, which other processes can read: pass it in env or stdin.");
36015
+ throw new ClientError("A secret handle cannot go in argv, which other processes can read: pass it in env, stdin or files.");
36084
36016
  }
36085
36017
  const env = args.env ?? {};
36018
+ const files = args.files ?? {};
36019
+ const clash = Object.keys(files).find((name) => Object.hasOwn(env, name));
36020
+ if (clash !== undefined) {
36021
+ throw new ClientError(`${clash} is named in both env and files`);
36022
+ }
36086
36023
  const secrets = await this.resolver.resolve([
36087
36024
  ...Object.values(env),
36025
+ ...Object.values(files),
36088
36026
  args.stdin ?? ""
36089
36027
  ]);
36090
36028
  if (secrets.used().length === 0) {
36091
- throw new ClientError("secret_exec needs a secret handle in env or stdin; run other programs without it.");
36092
- }
36093
- const outcome = await runProcess({
36094
- argv: args.argv,
36095
- cwd: args.cwd,
36096
- env: Object.fromEntries(Object.entries(env).map(([name, value]) => [name, secrets.fill(value)])),
36097
- stdin: args.stdin === undefined ? undefined : secrets.fill(args.stdin),
36098
- timeoutMs: args.timeout_s * 1000
36099
- });
36100
- const stdout = secrets.shown(outcome.stdout, outcome.stdoutCut);
36101
- const stderr = secrets.shown(outcome.stderr, outcome.stderrCut);
36102
- return {
36103
- exit_code: outcome.exitCode,
36104
- signal: outcome.signal,
36105
- timed_out: outcome.timedOut,
36106
- stdout: stdout.text,
36107
- stderr: stderr.text,
36108
- output_truncated: stdout.truncated || stderr.truncated,
36109
- used: secrets.used()
36110
- };
36111
- }
36112
- }
36113
-
36114
- // src/sinks/httpSink.ts
36115
- var MAX_READ_BYTES = 1024 * 1024;
36116
- async function cappedText(response) {
36117
- const reader = response.body?.getReader();
36118
- if (reader === undefined)
36119
- return { text: "", cut: false };
36120
- const chunks = [];
36121
- let size = 0;
36122
- while (size < MAX_READ_BYTES) {
36123
- const { done, value } = await reader.read();
36124
- if (done) {
36125
- return { text: Buffer.concat(chunks).toString("utf8"), cut: false };
36029
+ throw new ClientError("secret_exec needs a secret handle in env, stdin or files; run other programs without it.");
36126
36030
  }
36127
- chunks.push(value);
36128
- size += value.length;
36129
- }
36130
- await reader.cancel();
36131
- return {
36132
- text: Buffer.concat(chunks).subarray(0, MAX_READ_BYTES).toString("utf8"),
36133
- cut: true
36134
- };
36135
- }
36136
- function causeOf(error48) {
36137
- if (!(error48 instanceof Error))
36138
- return String(error48);
36139
- const cause = error48.cause instanceof Error ? `: ${error48.cause.message}` : "";
36140
- return `${error48.message}${cause}`;
36141
- }
36142
-
36143
- class HttpSink {
36144
- resolver;
36145
- constructor(resolver) {
36146
- this.resolver = resolver;
36147
- }
36148
- async send(args) {
36149
- requireHandlesAfterOrigin(args.url);
36150
- const headers = args.headers ?? {};
36151
- const secrets = await this.resolver.resolve([
36152
- args.url,
36153
- ...Object.keys(headers),
36154
- ...Object.values(headers),
36155
- args.body ?? ""
36156
- ]);
36157
- const { response, text: text2, cut } = await this.exchange(args, headers, secrets);
36158
- const body = secrets.shown(text2, cut);
36159
- return {
36160
- status: response.status,
36161
- headers: Object.fromEntries([...response.headers].map(([name, value]) => [
36162
- name,
36163
- secrets.redact(value)
36164
- ])),
36165
- body: body.text,
36166
- body_truncated: body.truncated,
36167
- used: secrets.used()
36168
- };
36169
- }
36170
- async exchange(args, headers, secrets) {
36031
+ const dir = await mkdtemp(join9(tmpdir(), "safekb-secret-"));
36171
36032
  try {
36172
- const response = await fetch(secrets.fill(args.url, "url"), {
36173
- method: args.method,
36174
- headers: Object.fromEntries(Object.entries(headers).map(([name, value]) => [
36175
- secrets.fill(name),
36176
- secrets.fill(value)
36177
- ])),
36178
- body: args.body === undefined ? undefined : secrets.fill(args.body),
36179
- redirect: "manual",
36180
- signal: AbortSignal.timeout(args.timeout_s * 1000)
36033
+ const paths = {};
36034
+ for (const [name, content] of Object.entries(filled(files, secrets))) {
36035
+ paths[name] = join9(dir, name);
36036
+ await writeFile(paths[name], content, { mode: 384, flag: "wx" });
36037
+ }
36038
+ const outcome = await runProcess({
36039
+ argv: args.argv,
36040
+ cwd: args.cwd,
36041
+ env: { ...filled(env, secrets), ...paths },
36042
+ stdin: args.stdin === undefined ? undefined : secrets.fill(args.stdin),
36043
+ timeoutMs: args.timeout_s * 1000
36181
36044
  });
36182
- return { response, ...await cappedText(response) };
36183
- } catch (error48) {
36184
- throw new ClientError(`The request failed: ${secrets.redact(causeOf(error48))}`);
36045
+ const stdout = secrets.shown(outcome.stdout, outcome.stdoutCut);
36046
+ const stderr = secrets.shown(outcome.stderr, outcome.stderrCut);
36047
+ return {
36048
+ exit_code: outcome.exitCode,
36049
+ signal: outcome.signal,
36050
+ timed_out: outcome.timedOut,
36051
+ stdout: stdout.text,
36052
+ stderr: stderr.text,
36053
+ output_truncated: stdout.truncated || stderr.truncated,
36054
+ used: secrets.used()
36055
+ };
36056
+ } finally {
36057
+ await rm4(dir, { recursive: true, force: true });
36185
36058
  }
36186
36059
  }
36187
36060
  }
@@ -36381,30 +36254,32 @@ function documentTools(creator, documents, search, names) {
36381
36254
  }
36382
36255
 
36383
36256
  // src/tools/sinkTools.ts
36384
- var HANDLE_NOTE = "Name a secret by its handle {{secret://<credential_id>/<field>}} (field: password, totp, sealed_notes or custom:{key}); it is decrypted on this machine and the value never enters the conversation. A totp handle becomes the current code. Add |form, |json or |url to encode the value for where it goes, e.g. {{secret://<id>/password|form}} in a form body; without it the value goes in as is (in a url: URL-encoded). Fields whose llm_visibility is human_only are refused.";
36385
- var SCRUB_NOTE = "What comes back is scrubbed of the values (as is, URL-encoded, base64, hex, JSON-escaped) and names the secrets used. Scrubbing guards against careless output, not against a program written to leak: run only code you trust.";
36386
- var timeout = (fallback) => exports_external.number().int().min(1).max(600).default(fallback).describe("Seconds.");
36387
- function sinkTools(exec, http, adb) {
36257
+ var ENV_NAME = exports_external.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
36258
+ var DESCRIPTION = `Use a sealed secret without seeing it: run your own program with the secret in its environment, on its stdin or in a temp file. This is the only way to use a secret without revealing it. SafeKB only provides the value; every integration (HTTP API, browser form, Android typing, ssh, wallet, disk unlock, radio, ...) is your own program.
36259
+
36260
+ Name a secret by its handle {{secret://<credential_id>/<field>}} (field: password, totp, sealed_notes or custom:{key}). It is decrypted on this machine and never enters the conversation. A totp handle becomes the current code. Add |url, |form or |json to encode the value for where your program puts it unchanged (e.g. a form body in stdin: "a={{secret://<id>/password|form}}"); without one it goes in as is. Fields whose llm_visibility is human_only are refused.
36261
+
36262
+ Examples:
36263
+ - HTTP API key: env {"API_KEY": "{{secret://<id>/password}}"}, argv ["uv", "run", "call_api.py"]
36264
+ - Android typing: env {"PW": "{{secret://<id>/password}}"}, argv ["uv", "run", "adb_type.py", "--expect-package", "com.example.bank"] (your script runs adb shell input text)
36265
+ - Browser form: env {"PW": "{{secret://<id>/password}}"}, argv ["node", "fill.js"] (your script attaches to the open browser with patchright over CDP)
36266
+ - ssh with a key: files {"KEY_FILE": "{{secret://<id>/custom:private key}}"}, argv ["sh", "-c", "ssh -i \\"$KEY_FILE\\" host uptime"]
36267
+ - ssh with a password: env {"SSHPASS": "{{secret://<id>/password}}"}, argv ["sshpass", "-e", "ssh", "host", "uptime"]
36268
+ - LUKS: stdin "{{secret://<id>/password}}", argv ["sudo", "cryptsetup", "open", "--key-file=-", "/dev/sdb1", "vault"]
36269
+ - Wallet unlock, a LoRa radio write, anything else: your script reads the value from env, stdin or a file
36270
+ - One-time code: env {"OTP": "{{secret://<id>/totp}}"}
36271
+
36272
+ Rules: never put a handle in argv (other processes can read it; it is refused). Your program must not print the value. What comes back is scrubbed of it (as is, in any mix of percent-, form- and JSON-encoding, as base64 or hex) and names the secrets used, but scrubbing is a guard against carelessness, not a guarantee: a program can still leak a value it transforms. The program inherits this client's environment and runs without a shell.`;
36273
+ function sinkTools(exec) {
36388
36274
  return [
36389
- defineTool("secret_exec", `Run a program with secrets in its environment or on its stdin, without seeing them. ${HANDLE_NOTE} At least one handle is needed; handles are refused in argv, which other processes can read. The program inherits this client's environment. No shell: argv is run as is. ${SCRUB_NOTE}`, {
36275
+ defineTool("secret_exec", DESCRIPTION, {
36390
36276
  argv: exports_external.array(exports_external.string()).min(1).describe('Program and arguments, e.g. ["uv", "run", "script.py"].'),
36391
36277
  cwd: absolutePath("Working directory."),
36392
- env: exports_external.record(exports_external.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), exports_external.string()).describe('Added to the environment; values may hold handles, e.g. {"API_KEY": "{{secret://<id>/password}}"}.').optional(),
36278
+ env: exports_external.record(ENV_NAME, exports_external.string()).describe('Added to the environment; values may hold handles, e.g. {"API_KEY": "{{secret://<id>/password}}"}.').optional(),
36393
36279
  stdin: exports_external.string().describe("Written to stdin, then closed; may hold handles.").optional(),
36394
- timeout_s: timeout(60)
36395
- }, (args) => exec.run(args)),
36396
- defineTool("secret_http", `Send one HTTP request with secrets in its url, headers or body, without seeing them. ${HANDLE_NOTE} Handles go in the path, query or fragment of the url (URL-encoded for you), never its host. A redirect is returned, not followed. ${SCRUB_NOTE}`, {
36397
- method: exports_external.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"]),
36398
- url: exports_external.string().url().describe("May hold handles, e.g. in the query."),
36399
- headers: exports_external.record(exports_external.string(), exports_external.string()).describe('e.g. {"Authorization": "Bearer {{secret://<id>/password}}"}.').optional(),
36400
- body: exports_external.string().describe("May hold handles.").optional(),
36401
- timeout_s: timeout(30)
36402
- }, (args) => http.send(args)),
36403
- defineTool("secret_adb_input", `Type a secret into the focused field of an Android device with adb (input text), without seeing it. ${HANDLE_NOTE} Only printable ASCII can be typed; anything else is refused, never typed differently. Returns only the length typed.`, {
36404
- text: exports_external.string().min(1).describe("What to type, holding a handle: {{secret://<id>/password}}."),
36405
- serial: exports_external.string().min(1).describe("adb -s: which device, when several are connected.").optional(),
36406
- expect_package: exports_external.string().min(1).describe("Type only if this app has the focus, e.g. com.example.bank.")
36407
- }, (args) => adb.input(args))
36280
+ files: exports_external.record(ENV_NAME, exports_external.string()).describe('Each value (holding handles) is written to a temp file only you can read and deleted when the program ends; the env variable of that name holds its path, e.g. {"KEY_FILE": "{{secret://<id>/custom:private key}}"}.').optional(),
36281
+ timeout_s: exports_external.number().int().min(1).max(600).default(60).describe("Seconds.")
36282
+ }, (args) => exec.run(args))
36408
36283
  ];
36409
36284
  }
36410
36285
 
@@ -36462,7 +36337,7 @@ A credential with \`sealed: true\` belongs to a seal root. Its title, username,
36462
36337
 
36463
36338
  - Reveal a secret only when the task needs it, and prefer get_sealed_totp over revealing a TOTP seed.
36464
36339
  - llm_visibility is set per credential, and llm_field_visibility overrides it for single sealed fields. reveal_sealed_credential and get_sealed_totp work only on a field that is visible. Only the user makes anything visible, in the SafeKB app.
36465
- - To use a secret without seeing it (visible or use_only fields): secret_exec (a program gets it in env or stdin), secret_http (one request gets it in url, headers or body) or secret_adb_input (typed on an Android device). Name it by handle, {{secret://<credential_id>/<field>}}; a totp handle becomes the current code. Prefer these over revealing, even for a visible field. A human_only field is never used by a tool: ask the user to enter it.
36340
+ - To use a secret without seeing it (visible or use_only fields): secret_exec runs your own program with it in env, stdin or a temp file; every integration (HTTP, browser, adb, ssh, ...) is that program. Name it by handle, {{secret://<credential_id>/<field>}}; a totp handle becomes the current code. Prefer this over revealing, even for a visible field. A human_only field is never used by a tool: ask the user to enter it.
36466
36341
  - visible_tampered means the visible fields were changed without the key since the last sealed save. Do not trust the url or username of such a credential until the user has reviewed the change.`;
36467
36342
  function createSealedTools(ctx) {
36468
36343
  const services = createSealedServices(ctx);
@@ -36474,7 +36349,7 @@ function createSealedTools(ctx) {
36474
36349
  ...attachmentTools(services.attachments),
36475
36350
  ...depositTools(services.deposits, names),
36476
36351
  ...credentialTools(services.credentials, services.migration, names),
36477
- ...sinkTools(new ExecSink(services.secrets), new HttpSink(services.secrets), new AdbSink(services.secrets))
36352
+ ...sinkTools(new ExecSink(services.secrets))
36478
36353
  ];
36479
36354
  }
36480
36355
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@safekb/mcp",
3
- "version": "0.12.1",
3
+ "version": "0.13.0",
4
4
  "description": "SafeKB local MCP client: proxies the hosted SafeKB tools and adds zero-knowledge sealed documents.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Mustafa Öztürk",