proton-drive-mcp 1.10.0 → 1.10.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.10.1 — 2026-11-19
4
+
5
+ ### Security
6
+ - Local path checks (upload, download, sync plan, photo tools) now ignore letter case on macOS and Windows and resolve existing paths with `realpath.native`, so `~/.SSH` is treated like `~/.ssh`. Linux stays case-sensitive. Windows behaviour is untested in CI.
7
+ - The local deny list also covers shell start-up files (`.zshrc`, `.bashrc`, `.profile`, the logout files and the other login-shell files) and `LaunchAgents`/`LaunchDaemons` folders.
8
+ - Downloads are checked under the name each item gets inside the destination folder, and a downloaded folder may not contain a protected location.
9
+ - Readonly mode: `drive_download` and `photos_download` refuse the `remove` conflict strategies, which delete existing local files. Plain downloads stay available. Documented in the README and THREAT_MODEL.
10
+ - Folder uploads are checked entry by entry, not only at the top. An upload is refused, with a message naming the entry, if the folder holds a folder named `.ssh`, `.aws` or `.gnupg`, a secret-looking file (`.env*`, keys and certificates, `.netrc`, `.npmrc`, `.pgpass`, `.git-credentials`, the gcloud files `credentials.db`, `access_tokens.db`, `application_default_credentials.json` and `legacy_credentials`, `.docker/config.json`, `.kube/config`, `.config/gcloud`), or a symlink that leads out of the folder. Other folders named `.docker`, `.kube` or `gcloud` are allowed. Files such as `.env.example` are refused too unless `PROTON_DRIVE_ALLOW_SENSITIVE_PATHS=1` is set. With `PROTON_DRIVE_LOCAL_ROOT` set only the symlink check applies. Folders with more than 200,000 entries are now refused, because they cannot be checked. Checks go by name: a renamed copy of a credential folder is not recognised.
11
+ - Local write tools: a download is refused when the path an item will be written to equals or lies inside the audit log, its `.lock` or a `.versions` snapshot folder of the sync folder, or (for a folder item) would contain them. The download folder itself may sit above them. A remote path without an item name is refused. A downloaded drive root (`/my-files`, `/photos`, ...) is written by the CLI as `<folder>/root`, so that name is checked, and for such a download the folder itself may not hold the audit log or a `.versions` folder. `drive_write_file` refuses `.versions` paths.
12
+
13
+ ### Fixed
14
+ - `PROTON_DRIVE_REMOTE_ROOTS`: the final path of `drive_move`, `drive_copy`, `drive_rename` and `drive_bulk_move` is now checked against the roots, not only the path arguments; `drive_move` can no longer target a root folder itself.
15
+
16
+ ### Changed
17
+ - THREAT_MODEL.md and the README now state that `confirmed: true` is an argument the model sets, not human approval, that bulk apply calls are not tied to a plan, and which controls do protect (readonly mode, remote roots, audit log, client tool approval, elicitation where supported). No behavior change.
18
+
3
19
  ## 1.10.0 — 2026-11-18
4
20
 
5
21
  ### Added
package/README.md CHANGED
@@ -86,7 +86,7 @@ Both only read; they change nothing, and link URLs are left out of the results.
86
86
  Ask: "Move all the PDFs in /Downloads into /Documents/Inbox. Show me the plan first."
87
87
 
88
88
  1. `drive_bulk_move` (or `drive_bulk_trash` for clean-up) without `confirmed` returns a plan and any problems and changes nothing.
89
- 2. Read the plan. If it is right, say so, and Claude repeats the call with `confirmed=true`. It applies only if there are no problems.
89
+ 2. Read the plan. If it is right, say so, and Claude repeats the call with `confirmed=true`. It applies only if there are no problems. The server does not check the second call against the plan (there is no plan token) and `confirmed=true` is set by the model, so approving each tool call in your client is the real check ([threat model](THREAT_MODEL.md)).
90
90
  3. Trash is reversible: `drive_restore` brings an item back (`drive_list_trash` shows what is there). `drive_empty_trash` and `drive_delete` are permanent, so do not ask for those during a tidy-up.
91
91
 
92
92
  Each call handles up to 200 items. For a first attempt on important data, use the [guard layer](#guard-layer-opt-in) (`PROTON_DRIVE_REMOTE_ROOTS` limits the folders Claude can touch).
@@ -529,7 +529,7 @@ The server offers four MCP prompts (also declared in the MCPB manifest): `organi
529
529
  ## Operational notes
530
530
 
531
531
  - Long listings are paginated (`limit` / `offset`, response `{total, offset, limit, hasMore, items}`) to keep responses small. Responses are compact JSON.
532
- - Local paths passed to upload/download/photos tools are checked: credential locations (`~/.ssh`, `~/.aws`, `~/.gnupg`, `~/.claude*`, keychains, `.env` files, …) are refused. Set `PROTON_DRIVE_LOCAL_ROOT` to allow only specific directories.
532
+ - Local paths passed to upload/download/photos tools are checked: credential and autostart locations (`~/.ssh`, `~/.aws`, `~/.gnupg`, `~/.claude*`, keychains, shell start-up files, `LaunchAgents`, `.env` files, …) are refused, ignoring letter case on macOS and Windows. A folder upload is checked entry by entry (a secret-looking file or a symlink out of the folder refuses it), and a download is checked under the name each item will get inside the folder. Set `PROTON_DRIVE_LOCAL_ROOT` to allow only specific directories.
533
533
  - The sync-folder tools (`drive_read_file` / `drive_write_file`) refuse to follow symlinks out of `PROTON_DRIVE_SYNC_PATH`.
534
534
  - Error messages come from the CLI's own output; the command line (and therefore any `--password`) is never echoed back.
535
535
  - `drive_move` accepts a full destination path (parent + new name) for a familiar interface, but the underlying CLI only has separate `move` (change parent) and `rename` (change name) commands — this MCP translates automatically, issuing one or both as needed.
@@ -552,7 +552,7 @@ Left out of `core` (use `full`): permanent deletion (`drive_delete`, `drive_empt
552
552
 
553
553
  Four environment variables limit what a model (or a prompt-injected one) can do with your Drive. All are read once at startup and are off by default. They apply to the MCP server only: the companion CLI (`proton-drive-cli`) is a tool you run yourself and is not restricted by them.
554
554
 
555
- - **`PROTON_DRIVE_MODE=readonly`** hides every tool that changes Drive or the account from `tools/list` and refuses it at call time (no CLI command runs). Hidden: `drive_upload`, `drive_mkdir`, `drive_rename`, `drive_move`, `drive_copy`, `drive_trash`, `drive_restore`, `drive_delete`, `drive_empty_trash`, `drive_bulk_move`, `drive_bulk_trash`, `drive_write_file`, `drive_auth_logout`, every `drive_share_*` that changes sharing (`invite`, `revoke`, `set_url`, `remove_url`, `remove_all`, `leave`), `drive_invitation_accept`/`reject`, and `photos_create_album`, `photos_update_album`, `photos_delete_album`, `photos_add_to_album`, `photos_remove_from_album`, `photos_upload`. Reads, analytics and downloads to local disk stay. An invalid value is treated as `readonly`. Prompts that name a hidden tool are not offered.
555
+ - **`PROTON_DRIVE_MODE=readonly`** hides every tool that changes Drive or the account from `tools/list` and refuses it at call time (no CLI command runs). Hidden: `drive_upload`, `drive_mkdir`, `drive_rename`, `drive_move`, `drive_copy`, `drive_trash`, `drive_restore`, `drive_delete`, `drive_empty_trash`, `drive_bulk_move`, `drive_bulk_trash`, `drive_write_file`, `drive_auth_logout`, every `drive_share_*` that changes sharing (`invite`, `revoke`, `set_url`, `remove_url`, `remove_all`, `leave`), `drive_invitation_accept`/`reject`, and `photos_create_album`, `photos_update_album`, `photos_delete_album`, `photos_add_to_album`, `photos_remove_from_album`, `photos_upload`. Reads, analytics and downloads to local disk stay, except that the `remove` conflict strategies of `drive_download` and `photos_download` (they delete existing local files) are refused. An invalid value is treated as `readonly`. Prompts that name a hidden tool are not offered.
556
556
  - **`PROTON_DRIVE_REMOTE_ROOTS`** (list separated by `:` on macOS/Linux, `;` on Windows, e.g. `/my-files/Projects/X`) confines every Drive path argument to those folders. Paths are matched by whole segment and case-sensitively (`/my-files/AB` is not inside `/my-files/A`); `..` and empty (`//`) segments are refused. Paths include sources, destinations, bulk lists, walk roots (`drive_tree`, `drive_search`, `drive_usage`, `drive_find_duplicates`, `drive_sharing_audit`, `drive_share_expiry_report`, `drive_recent_changes`, `drive_refresh_index`, `drive_sync_plan`, and the optional `path` of `drive_content_index` and `drive_search_content`, whose results outside the roots are dropped; their default `/my-files` is refused, so pass a `path`) and the sync-file tools. The root folder itself cannot be renamed, moved, trashed or left (`drive_share_leave`). `drive_usage` leaves out the account-wide trash summary. An entry that is not a clean absolute path is dropped with a warning; if none is left everything is refused. **These tools cannot be limited to a folder and are refused while roots are set:** `drive_auth_logout`, `drive_delete`, `drive_restore`, `drive_empty_trash`, `drive_list_trash` (trash is account-wide and addressed by name or UID), `drive_audit_log`, `drive_list_invitations`, `drive_invitation_accept`, `drive_invitation_reject`, and all ten `photos_*` tools. `drive_audit_log` is refused too, because its entries name paths outside the roots (read the file directly). `drive_auth_status` and `drive_version` touch no Drive content and keep working.
557
557
  - **`PROTON_DRIVE_AUDIT_LOG=/absolute/path/audit.jsonl`** appends one JSON line per tool call, refused calls included: `ts`, `seq`, `tool`, redacted `args`, `outcome` (`ok`, `error` or `refused`), a short `code` (`roots`, `readonly`, `tier`, `confirm`, `audit`, `snapshot`, `invalid`, `cli_error`, ...), `durationMs`, and `prev`/`hash`, a SHA-256 chain over the previous hash and the record. The file is created `0600` (its folder `0700` if missing). Passwords and message bodies are never written; for `drive_write_file` only the byte length of the content is, and arguments a tool does not declare are recorded as present, never by value. If the log cannot be written, tools that change Drive are refused (reads continue, with a warning on stderr). `drive_audit_log` returns the newest entries (default 50, full tier only, not available while roots are set) and `verification`: `{ok: true, entries, head}` or the first broken `seq`. The chain detects edited, inserted, reordered and mid-file removed lines, not removal of the newest lines: keep `head` somewhere else if you need that. Several servers can share one file (appends are serialized with a `<log>.lock` file; if it cannot be taken within a few seconds the write counts as failed). The server refuses to start when the log lies inside `PROTON_DRIVE_SYNC_PATH`. **An entry is written after the call finishes, so a crash or kill in the middle of an operation can leave a change that was never recorded.** The hash chain is only as trustworthy as the account that can write the file.
558
558
  - **`PROTON_DRIVE_SNAPSHOT_BEFORE_OVERWRITE=1`** keeps the previous version before an overwrite (the result carries `snapshot`), as `<same folder>/.versions/<name>.<UTC timestamp>`. `drive_write_file` overwrites the local sync copy, so it copies the existing **local** file inside the sync folder (the sync client uploads the copy; unsynced local edits and files never uploaded are preserved). `drive_upload` with `fileConflictStrategy: replace` copies the existing **remote** file. If the copy fails, or the remote state cannot be determined (for example the CLI is missing), the overwrite is refused. Replacing a folder is not versioned and is refused too: `drive_upload` of a folder with a `replace` strategy, or onto a remote folder, while snapshots are on. A file that does not exist yet has nothing to preserve. Snapshots are never pruned.
package/dist/cli.js CHANGED
@@ -21,7 +21,7 @@ import { resolve } from "node:path";
21
21
  import { driveSearch, driveTree } from "./services/find.js";
22
22
  import { readDriveContent } from "./services/content.js";
23
23
  import { driveUsage, driveFindDuplicates, driveSharingAudit } from "./services/analytics.js";
24
- import { validateRemotePath, validateRemotePathList, validateLocalPath, validateEmail, validateMessage, validateName, validateFlagValue } from "./utils/validation.js";
24
+ import { validateRemotePath, validateRemotePathList, validateLocalPath, validateDownloadTarget, validateEmail, validateMessage, validateName, validateFlagValue } from "./utils/validation.js";
25
25
  const drive = new DriveService();
26
26
  const args = process.argv.slice(2);
27
27
  const jsonMode = args.includes("--json");
@@ -290,7 +290,7 @@ async function run() {
290
290
  }
291
291
  let local;
292
292
  try {
293
- local = validateLocalPath(rawLocal, { scan: true });
293
+ local = validateLocalPath(rawLocal, { scan: true, upload: true });
294
294
  }
295
295
  catch (e) {
296
296
  console.error(e instanceof Error ? e.message : String(e));
@@ -325,7 +325,7 @@ async function run() {
325
325
  }
326
326
  let local;
327
327
  try {
328
- local = validateLocalPath(rawLocal2);
328
+ local = validateDownloadTarget(rawLocal2, [remote]);
329
329
  }
330
330
  catch (e) {
331
331
  console.error(e instanceof Error ? e.message : String(e));
@@ -728,7 +728,7 @@ async function run() {
728
728
  const photoPaths = positionals.slice(0, -1).map((p) => requirePath(p, "photo download <photo>... <local-folder>"));
729
729
  let localFolderValidated;
730
730
  try {
731
- localFolderValidated = validateLocalPath(localFolder);
731
+ localFolderValidated = validateDownloadTarget(localFolder, photoPaths);
732
732
  }
733
733
  catch (e) {
734
734
  console.error(e instanceof Error ? e.message : String(e));
@@ -754,7 +754,7 @@ async function run() {
754
754
  const localPaths = [];
755
755
  for (const p of positionals) {
756
756
  try {
757
- localPaths.push(validateLocalPath(p, { scan: true }));
757
+ localPaths.push(validateLocalPath(p, { scan: true, upload: true }));
758
758
  }
759
759
  catch (e) {
760
760
  console.error(e instanceof Error ? e.message : String(e));
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import { PROMPTS, getPromptText } from "./prompts.js";
11
11
  import { isMainModule } from "./utils/isMainModule.js";
12
12
  import { checkCliAvailable, runDriveRaw, callContext, killAllChildren } from "./utils/subprocess.js";
13
13
  import { DriveCliNotFoundError, DriveCliError, DriveNotAuthenticatedError, DriveParseError, NeedsConfirmationError, } from "./utils/errors.js";
14
- import { validateRemotePath, validateRemotePathList, validateLocalPath, validateEmail, validateMessage, validateName, validateFlagValue } from "./utils/validation.js";
14
+ import { validateRemotePath, validateRemotePathList, validateLocalPath, validateDownloadTarget, validateEmail, validateMessage, validateName, validateFlagValue } from "./utils/validation.js";
15
15
  import { logger } from "./utils/logger.js";
16
16
  import { cliCompatWarning } from "./utils/cliVersion.js";
17
17
  import { driveSearch, driveTree } from "./services/find.js";
@@ -1262,7 +1262,7 @@ export const REMOTE_PATH_ARGS = {
1262
1262
  drive_content_index: [{ arg: "path" }], drive_search_content: [{ arg: "path" }],
1263
1263
  drive_upload: [{ arg: "remotePath" }], drive_download: [{ arg: "remotePath" }],
1264
1264
  drive_rename: [{ arg: "path", strict: true }], drive_trash: [{ arg: "path", strict: true }],
1265
- drive_move: [{ arg: "sourcePath", strict: true }, { arg: "destinationPath" }],
1265
+ drive_move: [{ arg: "sourcePath", strict: true }, { arg: "destinationPath", strict: true }], // destinationPath is the final path of the item
1266
1266
  drive_copy: [{ arg: "sourcePath" }, { arg: "destinationPath" }],
1267
1267
  drive_bulk_move: [{ arg: "sources", list: true, strict: true }, { arg: "destinationFolder" }],
1268
1268
  drive_bulk_trash: [{ arg: "paths", list: true, strict: true }],
@@ -1298,8 +1298,31 @@ export function rootsRefusal(name, a, roots) {
1298
1298
  return `${name} refused: ${arg} ${showValue(p)} ${why} (allowed: ${roots.map((r) => showValue(r)).join(", ") || "nothing, no valid root is configured"}).`;
1299
1299
  }
1300
1300
  }
1301
+ // The path each item ends up at is checked as well, not only the folder argument it was derived from.
1302
+ for (const p of resultingPaths(name, a)) {
1303
+ if (!pathInRoots(p, roots, true))
1304
+ return `${name} refused: the resulting path ${showValue(p)} is outside PROTON_DRIVE_REMOTE_ROOTS (allowed: ${roots.map((r) => showValue(r)).join(", ") || "nothing, no valid root is configured"}).`;
1305
+ }
1301
1306
  return undefined;
1302
1307
  }
1308
+ function resultingPaths(name, a) {
1309
+ const base = (p) => p.slice(p.lastIndexOf("/") + 1); // validated paths have no trailing slash
1310
+ const join = (dir, leaf) => `${dir === "/" ? "" : dir}/${leaf}`;
1311
+ const parentOf = (p) => p.slice(0, p.lastIndexOf("/")) || "/";
1312
+ if (name === "drive_move")
1313
+ return [validateRemotePath(a.destinationPath)];
1314
+ if (name === "drive_rename")
1315
+ return [join(parentOf(validateRemotePath(a.path)), validateName(a.newName))];
1316
+ if (name === "drive_copy") {
1317
+ const src = validateRemotePath(a.sourcePath);
1318
+ return [join(validateRemotePath(a.destinationPath), typeof a.newName === "string" ? validateName(a.newName) : base(src))];
1319
+ }
1320
+ if (name === "drive_bulk_move") {
1321
+ const dst = validateRemotePath(a.destinationFolder);
1322
+ return validateRemotePathList(a.sources, "sources").map((s) => join(dst, base(s)));
1323
+ }
1324
+ return [];
1325
+ }
1303
1326
  export { showValue };
1304
1327
  export function describeArgs(args) {
1305
1328
  return Object.entries(args).filter(([k]) => k !== "confirmed").map(([k, v]) => {
@@ -1475,7 +1498,7 @@ export async function main() {
1475
1498
  if ((fcs === "replace" || dcs2 === "replace") && a.confirmed !== true) {
1476
1499
  throw new NeedsConfirmationError("drive_upload with strategy 'replace' trashes the existing remote item. Describe this to the user, get their explicit OK, then call again with confirmed=true.");
1477
1500
  }
1478
- const uploadLocal = validateLocalPath(a.localPath, { scan: true });
1501
+ const uploadLocal = validateLocalPath(a.localPath, { scan: true, upload: true });
1479
1502
  const uploadRemote = validateRemotePath(a.remotePath);
1480
1503
  const uploadExtra = {};
1481
1504
  if (snapshotEnabled() && (fcs === "replace" || dcs2 === "replace")) {
@@ -1509,10 +1532,14 @@ export async function main() {
1509
1532
  if (!["skip", "merge", "rename", "remove"].includes(fodcs)) {
1510
1533
  return fail(`folderConflictStrategy must be skip, merge, rename, or remove`);
1511
1534
  }
1535
+ if (mode === "readonly" && (fdcs === "remove" || fodcs === "remove")) {
1536
+ return refuse("readonly", "drive_download with strategy 'remove' deletes existing local files and is not available in readonly mode. Use 'skip' or 'rename', or set PROTON_DRIVE_MODE=full and restart the server.");
1537
+ }
1512
1538
  if ((fdcs === "remove" || fodcs === "remove") && a.confirmed !== true) {
1513
1539
  throw new NeedsConfirmationError("drive_download with strategy 'remove' deletes the existing LOCAL file or folder before downloading. Describe this to the user, get their explicit OK, then call again with confirmed=true.");
1514
1540
  }
1515
- const downloadResult = await drive.download(validateRemotePath(a.remotePath), validateLocalPath(a.localPath), fdcs, fodcs);
1541
+ const downloadRemote = validateRemotePath(a.remotePath);
1542
+ const downloadResult = await drive.download(downloadRemote, validateDownloadTarget(a.localPath, [downloadRemote]), fdcs, fodcs);
1516
1543
  if (downloadResult.failed > 0) {
1517
1544
  return fail(`Download completed with ${downloadResult.failed} failed file(s). downloaded=${downloadResult.downloaded} skipped=${downloadResult.skipped}`);
1518
1545
  }
@@ -1810,10 +1837,13 @@ export async function main() {
1810
1837
  if (!Array.isArray(a.photoPaths) || a.photoPaths.length === 0)
1811
1838
  return fail("photoPaths must be a non-empty array of strings");
1812
1839
  const downloadPaths = a.photoPaths.map((p) => validateRemotePath(p));
1813
- const downloadFolder = validateLocalPath(a.localFolder);
1840
+ const downloadFolder = validateDownloadTarget(a.localFolder, downloadPaths);
1814
1841
  const pdcs = typeof a.conflictStrategy === "string" ? a.conflictStrategy : "skip";
1815
1842
  if (!["skip", "rename", "remove"].includes(pdcs))
1816
1843
  return fail("conflictStrategy must be skip, rename, or remove");
1844
+ if (mode === "readonly" && pdcs === "remove") {
1845
+ return refuse("readonly", "photos_download with conflictStrategy 'remove' deletes existing local files and is not available in readonly mode. Use 'skip' or 'rename', or set PROTON_DRIVE_MODE=full and restart the server.");
1846
+ }
1817
1847
  if (pdcs === "remove" && a.confirmed !== true) {
1818
1848
  throw new NeedsConfirmationError("photos_download with conflictStrategy 'remove' deletes the existing LOCAL file before downloading. Describe this to the user, get their explicit OK, then call again with confirmed=true.");
1819
1849
  }
@@ -1826,7 +1856,7 @@ export async function main() {
1826
1856
  case "photos_upload": {
1827
1857
  if (!Array.isArray(a.localPaths) || a.localPaths.length === 0)
1828
1858
  return fail("localPaths must be a non-empty array of strings");
1829
- const uploadPaths = a.localPaths.map((p) => validateLocalPath(p, { scan: true }));
1859
+ const uploadPaths = a.localPaths.map((p) => validateLocalPath(p, { scan: true, upload: true }));
1830
1860
  const pucs = typeof a.conflictStrategy === "string" ? a.conflictStrategy : "skip";
1831
1861
  if (!["skip", "rename"].includes(pucs))
1832
1862
  return fail("conflictStrategy must be skip or rename");
@@ -1,4 +1,4 @@
1
- import { realpathSync, lstatSync, readlinkSync, statSync } from "node:fs";
1
+ import { realpathSync, lstatSync, readlinkSync, readdirSync, statSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { resolve, dirname, basename, join, relative, isAbsolute, sep, delimiter } from "node:path";
4
4
  const HOME_DENY = [
@@ -15,11 +15,36 @@ const HOME_DENY = [
15
15
  ".claude.json",
16
16
  "Library/Keychains",
17
17
  "Library/Application Support/Claude",
18
+ // Autostart locations and shell start-up files: a file written here runs later with the user's rights.
19
+ "Library/LaunchAgents",
20
+ "Library/LaunchDaemons",
21
+ ".zshrc",
22
+ ".zshenv",
23
+ ".zprofile",
24
+ ".zlogin",
25
+ ".bashrc",
26
+ ".bash_profile",
27
+ ".bash_login",
28
+ ".profile",
29
+ ".zlogout",
30
+ ".bash_logout",
18
31
  ];
19
- const ABS_DENY = ["/etc", "/private/etc", "/var/root"];
20
- const NAME_DENY = [/^\.env(\..*)?$/, /^id_rsa/, /^id_ed25519/, /\.pem$/, /\.p12$/, /\.pfx$/, /\.keychain/];
32
+ const ABS_DENY = ["/etc", "/private/etc", "/var/root", "/Library/LaunchAgents", "/Library/LaunchDaemons"];
33
+ const MAX_TREE_ENTRIES = 200_000;
34
+ const NAME_DENY = [
35
+ /^\.env(\..*)?$/, /^id_rsa/, /^id_ed25519/, /^id_ecdsa/, /^id_dsa/, /\.pem$/, /\.p12$/, /\.pfx$/, /\.keychain/,
36
+ /^\.netrc$/, /^\.npmrc$/, /^\.pgpass$/, /^\.git-credentials$/,
37
+ // gcloud credential files and folder, so a copied gcloud config is caught under any folder name
38
+ /^credentials\.db$/, /^access_tokens\.db$/, /^application_default_credentials\.json$/, /^legacy_credentials$/,
39
+ ];
40
+ // Folders that hold nothing but credentials wherever they sit: a copied ~/.ssh inside an upload folder is a credential tree.
41
+ const SECRET_DIR_NAMES = new Set([".ssh", ".aws", ".gnupg"]);
42
+ // Ordinary folders of tools that also keep one credential file in them: refuse that file (or folder), not the whole folder.
43
+ const SECRET_UNDER = new Map([[".docker", ["config.json"]], [".kube", ["config"]], [".config", ["gcloud"]]]);
44
+ // macOS and Windows file systems are case-insensitive by default: ~/.SSH is ~/.ssh there, so the comparison must be too.
45
+ const fold = (p) => (process.platform === "darwin" || process.platform === "win32" ? p.toLowerCase() : p);
21
46
  function isInside(root, target) {
22
- const rel = relative(root, target);
47
+ const rel = relative(fold(root), fold(target));
23
48
  if (rel === "")
24
49
  return true;
25
50
  if (isAbsolute(rel))
@@ -32,7 +57,8 @@ function realResolve(p, depth = 0) {
32
57
  let cur = resolve(p);
33
58
  for (;;) {
34
59
  try {
35
- const real = realpathSync(cur);
60
+ // .native returns the on-disk spelling of existing components, not the spelling the caller typed.
61
+ const real = realpathSync.native(cur);
36
62
  return rest.length ? join(real, ...rest.reverse()) : real;
37
63
  }
38
64
  catch (e) {
@@ -89,28 +115,130 @@ export function isProtectedEntry(fullPath, name) {
89
115
  const denied = deniedPaths();
90
116
  if (!denied)
91
117
  return false;
118
+ const lexical = resolve(fullPath);
119
+ return isDeniedEntry(denied, name, realResolve(lexical), lexical);
120
+ }
121
+ function isDeniedEntry(denied, name, real, lexical) {
92
122
  if (nameDenied(name))
93
123
  return true;
94
- const lexical = resolve(fullPath);
95
- const real = realResolve(lexical);
96
124
  for (const d of denied)
97
125
  if (isInside(d, real) || isInside(d, lexical))
98
126
  return true;
99
127
  return false;
100
128
  }
129
+ /**
130
+ * Walks a folder that is about to be uploaded: no entry may have a secret name (or be a credential file inside a tool
131
+ * folder such as .docker/config.json), and no symlink may lead out of the folder (the upload tool would read through
132
+ * it). Protected locations inside the folder were already refused by the caller, so entries are only checked by name.
133
+ * `realRoot` is already symlink-free.
134
+ */
135
+ function assertTreeAllowed(realRoot, checkNames, label) {
136
+ const stack = [realRoot];
137
+ let seen = 0;
138
+ while (stack.length) {
139
+ const dir = stack.pop();
140
+ const parentName = fold(basename(dir));
141
+ let entries;
142
+ try {
143
+ entries = readdirSync(dir, { withFileTypes: true });
144
+ }
145
+ catch {
146
+ continue;
147
+ }
148
+ for (const e of entries) {
149
+ if (++seen > MAX_TREE_ENTRIES) {
150
+ throw new Error(`local folder has more than ${MAX_TREE_ENTRIES} entries, too many to check for protected files: ${label}; pick a smaller folder`);
151
+ }
152
+ const full = join(dir, e.name);
153
+ const rel = relative(realRoot, full);
154
+ if (e.isSymbolicLink()) {
155
+ const target = realResolve(full);
156
+ if (!isInside(realRoot, target))
157
+ throw new Error(`local folder contains a symlink that points outside it and cannot be uploaded: ${rel} in ${label}`);
158
+ continue;
159
+ }
160
+ const lower = fold(e.name);
161
+ if (checkNames && (nameDenied(e.name) || (e.isDirectory() && SECRET_DIR_NAMES.has(lower)) || SECRET_UNDER.get(parentName)?.includes(lower))) {
162
+ throw new Error(`local folder contains a protected or secret file and cannot be uploaded: ${rel} in ${label} (set PROTON_DRIVE_ALLOW_SENSITIVE_PATHS=1 to disable this check)`);
163
+ }
164
+ if (e.isDirectory())
165
+ stack.push(full);
166
+ }
167
+ }
168
+ }
169
+ /** True when a `.versions` folder exists anywhere under `dir`. Throws when the folder is too big to finish checking (fail closed). */
170
+ function hasVersionsDir(dir) {
171
+ const stack = [dir];
172
+ let seen = 0;
173
+ while (stack.length) {
174
+ const d = stack.pop();
175
+ let entries;
176
+ try {
177
+ entries = readdirSync(d, { withFileTypes: true });
178
+ }
179
+ catch {
180
+ continue;
181
+ }
182
+ for (const e of entries) {
183
+ if (++seen > MAX_TREE_ENTRIES)
184
+ throw new Error(`local folder has more than ${MAX_TREE_ENTRIES} entries, too many to check for .versions snapshot folders: ${dir}`);
185
+ if (!e.isDirectory())
186
+ continue;
187
+ if (e.name.toLowerCase() === ".versions")
188
+ return true;
189
+ stack.push(join(d, e.name));
190
+ }
191
+ }
192
+ return false;
193
+ }
194
+ /**
195
+ * The audit log and the sync folder's .versions snapshots must not be reachable through a local write destination:
196
+ * the path may not be, or lie inside, one of them. `contains: true` is for the path an item will be written to
197
+ * (download folder + remote name): the CLI writes everything below it, so it may not hold them either.
198
+ */
199
+ function assertNotWriteProtected(lexical, real, absPath, contains) {
200
+ const log = process.env["PROTON_DRIVE_AUDIT_LOG"];
201
+ if (log && isAbsolute(log)) {
202
+ for (const f of [log, log + ".lock"]) {
203
+ const rf = realResolve(f);
204
+ if (isInside(rf, real) || isInside(rf, lexical))
205
+ throw new Error(`local path is the audit log and cannot be written: ${absPath}`);
206
+ if (contains && (isInside(real, rf) || isInside(lexical, rf)))
207
+ throw new Error(`the item would be written over a folder that holds the audit log, which cannot be written: ${absPath}`);
208
+ }
209
+ }
210
+ const sync = process.env["PROTON_DRIVE_SYNC_PATH"];
211
+ if (sync && isAbsolute(sync)) {
212
+ const syncReal = realResolve(sync);
213
+ const inSync = isInside(syncReal, real);
214
+ if (inSync && fold(relative(syncReal, real)).split(sep).includes(".versions")) {
215
+ throw new Error(`local path is inside a .versions snapshot folder and cannot be written: ${absPath}`);
216
+ }
217
+ if (contains && ((isInside(real, syncReal) && !inSync) || (inSync && isDirectory(real) && hasVersionsDir(real)))) {
218
+ throw new Error(`the item would be written over a folder that holds a .versions snapshot folder, which cannot be written: ${absPath}`);
219
+ }
220
+ }
221
+ }
101
222
  /**
102
223
  * `scan: true` is for operations that READ a directory recursively (sync plan, folder upload): the target must
103
- * not contain a protected location either. Leave it off for write destinations such as download folders.
224
+ * not contain a protected location either. `upload: true` (with `scan`) is for a folder that is handed to the CLI
225
+ * as a whole: it is checked entry by entry (symlinks out of it, secret-file and secret-folder names). `ancestors: true` is only
226
+ * the "contains a protected location" part, for write targets (a downloaded folder named like a parent of a protected
227
+ * location). `writeTarget: true` (for the path an item is written to) also refuses a path that holds the audit log or a `.versions` folder of the sync folder.
104
228
  */
105
229
  export function assertLocalPathAllowed(absPath, opts = {}) {
106
230
  const lexical = resolve(absPath);
107
231
  const real = realResolve(lexical);
232
+ if (!opts.scan)
233
+ assertNotWriteProtected(lexical, real, absPath, opts.writeTarget === true);
108
234
  const roots = rootsEnv();
109
235
  if (roots.length > 0) {
110
236
  const ok = roots.some((r) => isInside(realResolve(r), real));
111
237
  if (!ok) {
112
238
  throw new Error(`local path is outside PROTON_DRIVE_LOCAL_ROOT: ${absPath}`);
113
239
  }
240
+ if (opts.upload && isDirectory(real))
241
+ assertTreeAllowed(real, false, absPath);
114
242
  return;
115
243
  }
116
244
  const denied = deniedPaths();
@@ -128,7 +256,7 @@ export function assertLocalPathAllowed(absPath, opts = {}) {
128
256
  `(set PROTON_DRIVE_ALLOW_SENSITIVE_PATHS=1 to disable this check)`);
129
257
  }
130
258
  }
131
- if (opts.scan && isDirectory(real)) {
259
+ if ((opts.scan || opts.ancestors) && isDirectory(real)) {
132
260
  for (const d of denied) {
133
261
  if (isInside(real, d) || isInside(lexical, d)) {
134
262
  throw new Error(`local folder contains protected locations and cannot be scanned: ${absPath}; pick a subfolder ` +
@@ -136,6 +264,8 @@ export function assertLocalPathAllowed(absPath, opts = {}) {
136
264
  }
137
265
  }
138
266
  }
267
+ if (opts.upload && isDirectory(real))
268
+ assertTreeAllowed(real, true, absPath);
139
269
  }
140
270
  function isDirectory(p) {
141
271
  try {
@@ -158,6 +158,10 @@ export async function writeSyncFile(syncRoot, remotePath, content) {
158
158
  throw new Error(`content is ${bytes} bytes — too large to write (limit 5 MB). Use drive_upload instead.`);
159
159
  }
160
160
  const full = resolveSyncPath(syncRoot, remotePath);
161
+ // .versions holds the pre-overwrite snapshots; a write tool must not be able to rewrite them.
162
+ if (relative(resolve(syncRoot), full).toLowerCase().split(sep).includes(".versions")) {
163
+ throw new Error(`refusing to write inside a .versions snapshot folder: ${remotePath}`);
164
+ }
161
165
  const realRoot = await realRootOf(syncRoot, remotePath);
162
166
  const name = basename(full);
163
167
  const parent = dirname(full);
@@ -1,4 +1,4 @@
1
- import { isAbsolute } from "node:path";
1
+ import { isAbsolute, join } from "node:path";
2
2
  import { assertLocalPathAllowed } from "./localguard.js";
3
3
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
4
4
  // Control chars: 0x00-0x1F, DEL (0x7F), Unicode separators U+2028 and U+2029.
@@ -108,6 +108,28 @@ export function validateLocalPath(path, opts = {}) {
108
108
  assertLocalPathAllowed(p, opts);
109
109
  return p;
110
110
  }
111
+ /**
112
+ * Download destination folder. The CLI writes each item into it under its remote name, so the path the item will get
113
+ * (folder + remote name; `root` for a drive root, which the CLI names that way) must pass the same guard: a remote item named like a shell start-up file or a protected folder
114
+ * would otherwise land in a protected place through an allowed folder.
115
+ */
116
+ export function validateDownloadTarget(folder, remotePaths) {
117
+ const dir = validateLocalPath(folder);
118
+ for (const remote of remotePaths) {
119
+ const segments = remote.split("/").filter(Boolean);
120
+ const name = segments[segments.length - 1];
121
+ if (!name)
122
+ throw new Error(`remote path has no item name to download: ${remote}`);
123
+ // A drive root (/my-files, /photos, ...) is written by the CLI as <folder>/root, not under its own name, and brings a
124
+ // whole drive tree with it, so the folder itself must not hold the audit log or a .versions folder either.
125
+ const names = segments.length === 1 ? ["root", name] : [name];
126
+ if (segments.length === 1)
127
+ validateLocalPath(dir, { writeTarget: true });
128
+ for (const n of names)
129
+ validateLocalPath(join(dir, n), { ancestors: true, writeTarget: true });
130
+ }
131
+ return dir;
132
+ }
111
133
  export function validateEmail(email) {
112
134
  const e = asString(email, "email").trim();
113
135
  if (e.startsWith("-"))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proton-drive-mcp",
3
- "version": "1.10.0",
3
+ "version": "1.10.1",
4
4
  "mcpName": "io.github.googlarz/proton-drive-mcp",
5
5
  "description": "MCP server and CLI that gives Claude full access to Proton Drive — upload, download, share, and manage your end-to-end encrypted files without leaving the conversation.",
6
6
  "type": "module",