@j0hanz/filesystem-mcp 2.7.5 → 2.8.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.
Files changed (118) hide show
  1. package/README.md +290 -394
  2. package/dist/cli-help.d.ts.map +1 -1
  3. package/dist/cli-help.js +15 -7
  4. package/dist/cli-help.js.map +1 -1
  5. package/dist/cli.d.ts +1 -9
  6. package/dist/cli.d.ts.map +1 -1
  7. package/dist/cli.js.map +1 -1
  8. package/dist/core/concurrency.d.ts +7 -0
  9. package/dist/core/concurrency.d.ts.map +1 -1
  10. package/dist/core/concurrency.js +19 -0
  11. package/dist/core/concurrency.js.map +1 -1
  12. package/dist/core/errors.d.ts +4 -3
  13. package/dist/core/errors.d.ts.map +1 -1
  14. package/dist/core/errors.js +5 -16
  15. package/dist/core/errors.js.map +1 -1
  16. package/dist/core/fs.d.ts +19 -11
  17. package/dist/core/fs.d.ts.map +1 -1
  18. package/dist/core/fs.js +168 -53
  19. package/dist/core/fs.js.map +1 -1
  20. package/dist/core/glob.d.ts +8 -0
  21. package/dist/core/glob.d.ts.map +1 -1
  22. package/dist/core/glob.js +192 -29
  23. package/dist/core/glob.js.map +1 -1
  24. package/dist/core/input-required.d.ts +12 -0
  25. package/dist/core/input-required.d.ts.map +1 -1
  26. package/dist/core/input-required.js +7 -2
  27. package/dist/core/input-required.js.map +1 -1
  28. package/dist/core/observability.d.ts +2 -0
  29. package/dist/core/observability.d.ts.map +1 -1
  30. package/dist/core/observability.js +7 -0
  31. package/dist/core/observability.js.map +1 -1
  32. package/dist/core/path-completer.d.ts.map +1 -1
  33. package/dist/core/path-completer.js +11 -30
  34. package/dist/core/path-completer.js.map +1 -1
  35. package/dist/core/path.d.ts +7 -18
  36. package/dist/core/path.d.ts.map +1 -1
  37. package/dist/core/path.js +22 -55
  38. package/dist/core/path.js.map +1 -1
  39. package/dist/core/read.d.ts +4 -1
  40. package/dist/core/read.d.ts.map +1 -1
  41. package/dist/core/read.js +25 -16
  42. package/dist/core/read.js.map +1 -1
  43. package/dist/core/schema.d.ts +6 -1
  44. package/dist/core/schema.d.ts.map +1 -1
  45. package/dist/core/schema.js +17 -3
  46. package/dist/core/schema.js.map +1 -1
  47. package/dist/core/search.d.ts +7 -0
  48. package/dist/core/search.d.ts.map +1 -1
  49. package/dist/core/search.js +154 -66
  50. package/dist/core/search.js.map +1 -1
  51. package/dist/core/store.d.ts +36 -1
  52. package/dist/core/store.d.ts.map +1 -1
  53. package/dist/core/store.js +71 -6
  54. package/dist/core/store.js.map +1 -1
  55. package/dist/core/util.d.ts +37 -0
  56. package/dist/core/util.d.ts.map +1 -1
  57. package/dist/core/util.js +62 -0
  58. package/dist/core/util.js.map +1 -1
  59. package/dist/index.js +5 -16
  60. package/dist/index.js.map +1 -1
  61. package/dist/resources.d.ts +5 -1
  62. package/dist/resources.d.ts.map +1 -1
  63. package/dist/resources.js +45 -22
  64. package/dist/resources.js.map +1 -1
  65. package/dist/server.d.ts +10 -5
  66. package/dist/server.d.ts.map +1 -1
  67. package/dist/server.js +8 -8
  68. package/dist/server.js.map +1 -1
  69. package/dist/tools/create.d.ts.map +1 -1
  70. package/dist/tools/create.js +93 -90
  71. package/dist/tools/create.js.map +1 -1
  72. package/dist/tools/define.d.ts +10 -6
  73. package/dist/tools/define.d.ts.map +1 -1
  74. package/dist/tools/define.js +49 -16
  75. package/dist/tools/define.js.map +1 -1
  76. package/dist/tools/delete.d.ts.map +1 -1
  77. package/dist/tools/delete.js +39 -21
  78. package/dist/tools/delete.js.map +1 -1
  79. package/dist/tools/edit.d.ts.map +1 -1
  80. package/dist/tools/edit.js +37 -39
  81. package/dist/tools/edit.js.map +1 -1
  82. package/dist/tools/find-files.d.ts.map +1 -1
  83. package/dist/tools/find-files.js +49 -60
  84. package/dist/tools/find-files.js.map +1 -1
  85. package/dist/tools/index.d.ts +2 -10
  86. package/dist/tools/index.d.ts.map +1 -1
  87. package/dist/tools/index.js +1 -8
  88. package/dist/tools/index.js.map +1 -1
  89. package/dist/tools/list.d.ts.map +1 -1
  90. package/dist/tools/list.js +59 -69
  91. package/dist/tools/list.js.map +1 -1
  92. package/dist/tools/move.d.ts.map +1 -1
  93. package/dist/tools/move.js +39 -5
  94. package/dist/tools/move.js.map +1 -1
  95. package/dist/tools/patch.d.ts.map +1 -1
  96. package/dist/tools/patch.js +88 -86
  97. package/dist/tools/patch.js.map +1 -1
  98. package/dist/tools/read.d.ts.map +1 -1
  99. package/dist/tools/read.js +30 -24
  100. package/dist/tools/read.js.map +1 -1
  101. package/dist/tools/replace-text.d.ts.map +1 -1
  102. package/dist/tools/replace-text.js +60 -46
  103. package/dist/tools/replace-text.js.map +1 -1
  104. package/dist/tools/search-text.d.ts.map +1 -1
  105. package/dist/tools/search-text.js +48 -64
  106. package/dist/tools/search-text.js.map +1 -1
  107. package/dist/transport/http.d.ts.map +1 -1
  108. package/dist/transport/http.js +2 -1
  109. package/dist/transport/http.js.map +1 -1
  110. package/dist/transport/shared.d.ts +7 -5
  111. package/dist/transport/shared.d.ts.map +1 -1
  112. package/dist/transport/shared.js +8 -2
  113. package/dist/transport/shared.js.map +1 -1
  114. package/dist/transport/stdio.d.ts +4 -1
  115. package/dist/transport/stdio.d.ts.map +1 -1
  116. package/dist/transport/stdio.js +46 -12
  117. package/dist/transport/stdio.js.map +1 -1
  118. package/package.json +3 -2
@@ -1 +1 @@
1
- {"version":3,"file":"input-required.js","sourceRoot":"","sources":["../../src/core/input-required.ts"],"names":[],"mappings":"AAoBA,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,aAAa,EACb,aAAa,GACd,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAyD5C;;;;;;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;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CAChC,SAA8C,EAC9C,GAAW;IAEX,OAAO,eAAe,CAAC,SAAS,EAAE,GAAG,EAAE,aAAa,CAAC,EAAE,MAAM,CAAC;AAChE,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,uBAAuB,CACrC,SAA8C,EAC9C,GAAW;IAEX,OAAO,eAAe,CAAC,SAAS,EAAE,GAAG,EAAE,kBAAkB,CAAC,EAAE,MAAM,CAAC;AACrE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAC7B,GAAoE,EACpE,GAAW;IAEX,IAAI,GAAG,CAAC,wBAAwB,EAAE,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAChD,OAAO,8GAA8G,CAAC;IACxH,CAAC;IACD,MAAM,IAAI,GAAG,aAAa,CAAC,GAAG,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;IACpD,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,cAAc,CAAC;IAClD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;QAAE,OAAO,sBAAsB,CAAC;IAC7D,IAAI,IAAI,CAAC,MAAM,KAAK,QAAQ;QAAE,OAAO,uBAAuB,CAAC;IAC7D,OAAO,iCAAiC,CAAC;AAC3C,CAAC;AAED;;;;;GAKG;AACH,SAAS,UAAU,CAAC,CAAoB,EAAE,CAAoB;IAC5D,4EAA4E;IAC5E,8EAA8E;IAC9E,wEAAwE;IACxE,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChF,CAAC","sourcesContent":["// Shared infrastructure for the SEP-2577 `input_required` multi-round-trip\n// destructive-confirmation flows (recursive delete, move overwrite, out-of-root\n// access grant). A handler returns `inputRequired(...)` instead of the deprecated\n// push-style server-to-client elicitation request; the client retries the same\n// `tools/call` carrying `inputResponses`, and the handler re-enters from the top\n// reading the verified `requestState` and the accepted responses.\n//\n// `requestState` round-trips through the client (attacker-controlled on\n// re-entry), so it is sealed with the SDK's HMAC-SHA256 codec. The payload binds\n// each confirmation to its operation kind and sorted target-path set (spec R9,\n// R10); the handler additionally rejects any retry whose decoded paths do not\n// match the retried request's parameters (the codec only proves the state was\n// not tampered — it cannot see the current args).\nimport type {\n ClientCapabilities,\n InputRequest,\n InputRequiredResult,\n RequestStateCodec,\n ServerContext,\n} from '@modelcontextprotocol/server';\nimport {\n acceptedContent,\n createRequestStateCodec,\n inputRequired,\n inputResponse,\n} from '@modelcontextprotocol/server';\n\nimport { randomBytes } from 'node:crypto';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, FsError } from './errors.ts';\nimport { Logger } from './observability.ts';\n\n/** The destructive operation a pending confirmation authorizes. */\ntype PendingOp = 'delete' | 'move' | 'copy' | 'create' | 'grant';\n\n/**\n * Integrity-protected state minted into an `input_required` result and echoed\n * back by the client on retry. `paths` is the sorted canonical set of target\n * paths the confirmation covers; the handler compares it to the retried\n * request's parameters and rejects a mismatch (R9).\n */\nexport interface PendingState {\n readonly op: PendingOp;\n readonly paths: readonly string[];\n /**\n * Set on the state of a round minted because the previous round's answer\n * was dropped by the SDK (`droppedInputResponseKeys`). Sealed in the HMAC\n * payload, so a client cannot clear it: the re-issue happens once.\n */\n readonly reissued?: true;\n}\n\n/** The per-round confirmation context; `ToolCtx` satisfies it structurally. */\nexport interface PendingCtx {\n readonly requestState?: (() => PendingState | undefined) | undefined;\n /**\n * What the client declared it can do, or `undefined` when this connection\n * cannot say. Only positively-absent form support short-circuits; see\n * {@link assertCanElicit}.\n */\n readonly clientCapabilities?: ClientCapabilities | undefined;\n /** `ctx.mcpReq.droppedInputResponseKeys` for this round; see `ToolCtx`. */\n readonly droppedInputResponseKeys?: readonly string[] | undefined;\n readonly inputResponses?: Record<string, unknown> | undefined;\n /** The live handler context; the codec binds the minted state to its method and caller. */\n readonly serverCtx: ServerContext;\n}\n\n/** One embedded form-mode confirmation, keyed within the call. */\nexport interface PendingInput {\n /** Server-assigned key, unique within the `tools/call`. */\n readonly key: string;\n /** Human-readable prompt for this item. */\n readonly message: string;\n /**\n * When set, the form offers a single-select enum (`choice` field) over\n * these values instead of a boolean `confirm`.\n */\n readonly choices?: readonly string[];\n /**\n * When set with `choices`, the form offers a multi-select enum: `choice` is\n * a string array (`MultiSelectEnumSchema` shape) and the caller reads the\n * accepted set with `readAcceptedMultiChoice`. Single-select otherwise.\n */\n readonly multi?: boolean;\n}\n\n/**\n * HMAC key for the requestState codec. Read once from\n * `FS_REQUEST_STATE_KEY` (UTF-8, must be >=32 bytes); a random\n * 32-byte key is generated at boot when the env var is unset or too short. A\n * per-process key is correct for stdio and the single-node HTTP leg (decision\n * record 11). A server restart invalidates in-flight tokens; the client\n * re-requests, which is fail-closed and safe.\n */\nfunction configuredRequestStateKey(): Uint8Array | undefined {\n const env = process.env['FS_REQUEST_STATE_KEY'];\n if (env) {\n const bytes = Buffer.from(env, 'utf8');\n if (bytes.length >= 32) return bytes;\n Logger.warn(\n `FS_REQUEST_STATE_KEY is ${String(bytes.length)} bytes; 32 are required. Falling back to a random per-boot key — in-flight input_required rounds will not survive a restart.`,\n );\n }\n return undefined;\n}\n\n/**\n * What a minted `requestState` is bound to: the JSON-RPC method of the\n * request that minted it and the authenticated caller (`ctx.http` is absent\n * on stdio, so the caller part is empty there and constant across rounds).\n * The SDK stores an HMAC tag of this value in the token and refuses an echo\n * whose context yields a different value.\n */\nfunction requestStateBinding(ctx: ServerContext): string {\n return `${ctx.mcpReq.method}\\0${ctx.http?.authInfo?.clientId ?? ''}`;\n}\n\n/**\n * The codec: `mint` seals a `PendingState` into the opaque wire string a\n * handler returns from `inputRequired({ requestState })`; `verify` drops into\n * `ServerOptions.requestState.verify` and throws on tamper, expiry, or bind\n * mismatch (the seam answers with the frozen `-32602`).\n */\nexport const requestStateCodec: RequestStateCodec<PendingState> =\n createRequestStateCodec<PendingState>({\n key: configuredRequestStateKey() ?? randomBytes(32),\n bind: requestStateBinding,\n });\n\n// Response shapes handed to the SDK's schema-aware `acceptedContent` overload:\n// it returns `undefined` for a missing key, a decline/cancel, a non-elicit\n// response, AND a payload that fails validation — one call covers every refusal\n// case the readers below used to hand-check. `buildInputRequired` reuses\n// `ConfirmContent` as the no-choices form schema (below), so these sit above it.\nconst ConfirmContent = z.object({ confirm: z.boolean().meta({ title: 'Confirm' }) });\nconst ChoiceContent = z.object({ choice: z.string() });\nconst MultiChoiceContent = z.object({ choice: z.array(z.string()) });\n\n/**\n * The form the client renders for one pending input, as the Zod schema the\n * SDK converts to the elicitation wire shape. A boolean `confirm` when no\n * choices are offered; otherwise a `choice` enum over the offered values,\n * wrapped in an array for multi-select so the client may accept a subset.\n * The offered lists are never empty by construction (single-select always\n * offers two literals; multi-select only runs with two or more grant dirs),\n * so no empty-array guard is added. Each field carries a `title` so a host\n * that renders the form labels it instead of showing the property name.\n */\nfunction requestedSchemaFor(input: PendingInput): z.ZodObject {\n if (!input.choices) return ConfirmContent;\n const value = z.enum(input.choices);\n return z.object({\n choice: input.multi ? z.array(value).meta({ title: 'Allow' }) : value.meta({ title: 'Action' }),\n });\n}\n\n/**\n * Build an `input_required` result carrying one boolean confirmation per pending\n * item, plus the integrity-protected `requestState` sealing the operation kind\n * and sorted target paths. `mint` is async (HMAC + base64url).\n */\nexport async function buildInputRequired(\n pending: PendingState,\n inputs: readonly PendingInput[],\n ctx: ServerContext,\n): Promise<InputRequiredResult> {\n const inputRequests: Record<string, InputRequest> = {};\n for (const input of inputs) {\n inputRequests[input.key] = inputRequired.elicit({\n message: input.message,\n requestedSchema: requestedSchemaFor(input),\n });\n }\n const requestState = await requestStateCodec.mint(\n {\n op: pending.op,\n paths: [...pending.paths].sort(),\n ...(pending.reissued ? { reissued: true as const } : {}),\n },\n ctx,\n );\n return inputRequired({ inputRequests, requestState });\n}\n\n/**\n * The shared read-state → `buildInputRequired` → mismatch-throw flow used by\n * every destructive-confirmation handler (delete, move, grant). No verified\n * state, OR a verified state belonging to a different `op` (e.g. a chained\n * call's grant round already resolved and this is now that same call's own\n * delete/move confirmation round), mints a fresh `input_required` for this\n * op. A retry whose verified state matches this op but not the pending path\n * set throws `FsError(INVALID_INPUT)` (R9) — uniformly surfaced as an\n * `isError` tool result by the handler's catch. Returns `undefined` on a\n * matching same-op retry so the caller proceeds.\n *\n * One home for the R9 binding check means a future fix cannot miss two of three\n * sites. The caller passes the round's `PendingCtx` and supplies `buildInputs`\n * so only the prompt text varies.\n */\ninterface PendingRoundTripOpts {\n readonly op: PendingOp;\n readonly pending: readonly string[];\n readonly buildInputs: (pending: readonly string[]) => readonly PendingInput[];\n}\n\n/**\n * What to tell the model when the round-trip cannot happen. Each names the way\n * forward that does not need a confirmation, or says plainly that there is\n * none — a dead end the model can report is worth more than a retry loop.\n */\nconst NO_ELICITATION_HINT: Readonly<Record<PendingOp, string>> = {\n delete:\n 'Deleting a non-empty directory needs a confirmation this client cannot show. ' +\n 'Delete the entries inside it individually, or connect a client that declares the elicitation capability.',\n move:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Delete the destination first, or move to a path that does not exist yet.',\n copy:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Pass overwrite=true to replace it without confirming, or copy to a path that does not exist yet.',\n create:\n 'Overwriting an existing file needs a confirmation this client cannot show. ' +\n 'Pass overwrite: true on that entry to replace it without confirming, append: true to add to it, or read it and use edit.',\n grant:\n 'Granting access to a directory outside the allowed roots needs a confirmation this client cannot show. ' +\n 'Call list_roots and use a path under one of the roots it returns.',\n};\n\n/**\n * Fail early, and legibly, when the client cannot answer an embedded form.\n * The SDK checks each `inputRequests` entry against the declared client\n * capabilities and rejects the whole call with `-32021` before anything reaches\n * the wire — a protocol error the model never sees. Throwing `FsError` here\n * instead lands in the tool executor's catch and reaches the model as an\n * `isError` result carrying the workaround.\n *\n * `undefined` capabilities mean the connection cannot report them, NOT that the\n * client has none: proceed and let the SDK decide, exactly as before this check\n * existed.\n */\nfunction assertCanElicit(op: PendingOp, capabilities: ClientCapabilities | undefined): void {\n if (capabilities === undefined) return;\n const elicitation = capabilities.elicitation;\n if (\n elicitation !== undefined &&\n (elicitation.form !== undefined || elicitation.url === undefined)\n ) {\n return;\n }\n throw new FsError(ErrorCode.INVALID_INPUT, `${op}: ${NO_ELICITATION_HINT[op]}`);\n}\n\nexport async function pendingRoundTrip(\n ctx: PendingCtx,\n opts: PendingRoundTripOpts,\n): Promise<InputRequiredResult | undefined> {\n const state = ctx.requestState?.();\n // No verified state yet, OR the verified state belongs to a different\n // flow (e.g. an access-grant round's state is still the retried request's\n // requestState after the grant was applied, and this call is now the\n // destructive-confirmation round for the SAME tool call) — either way,\n // this op has not yet had its own round-trip, so mint a fresh\n // input_required rather than treating a foreign-but-valid state as a\n // tamper/mismatch error.\n if (state?.op !== opts.op) {\n assertCanElicit(opts.op, ctx.clientCapabilities);\n return buildInputRequired(\n { op: opts.op, paths: opts.pending },\n opts.buildInputs(opts.pending),\n ctx.serverCtx,\n );\n }\n // Retry for THIS op (R9): the verified state must bind the same pending set.\n if (!pathsEqual(state.paths, opts.pending)) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `${opts.op}: confirmation does not match the requested paths`,\n );\n }\n // The client answered, but in a shape the SDK discards before the handler\n // runs (`{ method, result }` around the bare result). Ask the same question\n // once more rather than report a refusal the user never made; the sealed\n // `reissued` flag stops a second retry from looping.\n if (state.reissued !== true && ctx.droppedInputResponseKeys?.length) {\n const dropped = new Set(ctx.droppedInputResponseKeys);\n const inputs = opts.buildInputs(opts.pending);\n if (inputs.some((input) => dropped.has(input.key))) {\n return buildInputRequired(\n { op: opts.op, paths: opts.pending, reissued: true },\n inputs,\n ctx.serverCtx,\n );\n }\n }\n return undefined;\n}\n\n/**\n * Round-trip key for `pendingSorted[index]` — the single home of the\n * `confirm_${i}` convention. The build side mints it with the map index; the\n * read side re-derives it from the same sorted pending set the requestState\n * binds (R9), so a format change lands here once instead of at six call\n * sites.\n */\nexport function confirmKey(index: number): string {\n return `confirm_${index}`;\n}\n\n/**\n * Read one pending item's boolean confirmation from a retried request's\n * `inputResponses`. Returns `true` only when the client explicitly accepted AND\n * the `confirm` field is `true`; every other outcome (decline, cancel, missing\n * key, accept-without-confirm) returns `false`, which the caller reports as\n * `CANCELLED` (R3 proceed, R4/R5 cancelled).\n */\nexport function readAcceptedConfirm(\n responses: Record<string, unknown> | undefined,\n key: string,\n): boolean {\n return acceptedContent(responses, key, ConfirmContent)?.confirm === true;\n}\n\n/**\n * Read one pending item's enum selection from a retried request's\n * `inputResponses`. Returns the chosen `value` only when the client explicitly\n * accepted AND the `choice` field is a string; every other outcome (decline,\n * cancel, missing key, accept-without-choice) returns `undefined`, which the\n * caller reports as `CANCELLED` — same contract as the boolean reader.\n *\n * The shape is SDK-validated, but the returned value is NOT checked for\n * membership in the `choices` offered in the request schema. Callers must\n * compare against the expected values (e.g. `choice === 'overwrite'`) before\n * acting — never echo the string back into a path or trust it as an enum\n * member.\n */\nexport function readAcceptedChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n return acceptedContent(responses, key, ChoiceContent)?.choice;\n}\n\n/**\n * Read one pending item's multi-select enum selection from a retried request's\n * `inputResponses`. Returns the accepted `value`s only when the client\n * explicitly accepted AND `choice` is a string array of strings; every other\n * outcome (decline, cancel, missing key, accept-without-choice, non-array\n * `choice`, non-string elements) returns `undefined`, which the caller reports\n * as `CANCELLED` — same contract as the single-select reader.\n *\n * As with `readAcceptedChoice`, the returned values are NOT checked for\n * membership in the offered `choices`; callers must compare against the\n * expected set before acting.\n */\nexport function readAcceptedMultiChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string[] | undefined {\n return acceptedContent(responses, key, MultiChoiceContent)?.choice;\n}\n\n/**\n * Refusal wording for the `CANCELLED` error; call after a `readAccepted*` reader\n * returned nothing. Pass the round's ctx so a dropped answer is named as such\n * rather than as 'not answered'.\n */\nexport function describeRefusal(\n ctx: Pick<PendingCtx, 'inputResponses' | 'droppedInputResponseKeys'>,\n key: string,\n): string {\n if (ctx.droppedInputResponseKeys?.includes(key)) {\n return 'answered in a shape this server cannot read (a wrapped result instead of the bare elicitation result), twice';\n }\n const view = inputResponse(ctx.inputResponses, key);\n if (view.kind !== 'elicit') return 'not answered';\n if (view.action === 'decline') return 'declined by the user';\n if (view.action === 'cancel') return 'dismissed by the user';\n return 'answered without a valid choice';\n}\n\n/**\n * Order-independent equality of two sorted, de-duplicated path lists. Used to\n * compare a recomputed pending set against the `requestState`-bound set (R9):\n * both are sorted by construction, so a straight element-wise compare settles\n * it without allocating.\n */\nfunction pathsEqual(a: readonly string[], b: readonly string[]): boolean {\n // The length check is load-bearing, not an early-out: `every` alone returns\n // true whenever `a` is a prefix of a longer `b`, so a confirmation minted for\n // ['/x'] would authorize a retry for ['/x', '/y'] — a direct R9 bypass.\n return a.length === b.length && a.every((value, index) => value === b[index]);\n}\n"]}
1
+ {"version":3,"file":"input-required.js","sourceRoot":"","sources":["../../src/core/input-required.ts"],"names":[],"mappings":"AAoBA,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,aAAa,EACb,aAAa,GACd,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAoE5C;;;;;;;GAOG;AACH,SAAS,yBAAyB;IAChC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAChD,IAAI,GAAG,EAAE,CAAC;QACR,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM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AC;AAC3E,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CAChC,SAA8C,EAC9C,GAAW;IAEX,OAAO,eAAe,CAAC,SAAS,EAAE,GAAG,EAAE,aAAa,CAAC,EAAE,MAAM,CAAC;AAChE,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,uBAAuB,CACrC,SAA8C,EAC9C,GAAW;IAEX,OAAO,eAAe,CAAC,SAAS,EAAE,GAAG,EAAE,kBAAkB,CAAC,EAAE,MAAM,CAAC;AACrE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAC7B,GAAoE,EACpE,GAAW;IAEX,IAAI,GAAG,CAAC,wBAAwB,EAAE,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAChD,OAAO,8GAA8G,CAAC;IACxH,CAAC;IACD,MAAM,IAAI,GAAG,aAAa,CAAC,GAAG,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;IACpD,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,cAAc,CAAC;IAClD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;QAAE,OAAO,sBAAsB,CAAC;IAC7D,IAAI,IAAI,CAAC,MAAM,KAAK,QAAQ;QAAE,OAAO,uBAAuB,CAAC;IAC7D,OAAO,iCAAiC,CAAC;AAC3C,CAAC;AAED;;;;;GAKG;AACH,SAAS,UAAU,CAAC,CAAoB,EAAE,CAAoB;IAC5D,4EAA4E;IAC5E,8EAA8E;IAC9E,wEAAwE;IACxE,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AAChF,CAAC","sourcesContent":["// Shared infrastructure for the SEP-2577 `input_required` multi-round-trip\n// destructive-confirmation flows (recursive delete, move overwrite, out-of-root\n// access grant). A handler returns `inputRequired(...)` instead of the deprecated\n// push-style server-to-client elicitation request; the client retries the same\n// `tools/call` carrying `inputResponses`, and the handler re-enters from the top\n// reading the verified `requestState` and the accepted responses.\n//\n// `requestState` round-trips through the client (attacker-controlled on\n// re-entry), so it is sealed with the SDK's HMAC-SHA256 codec. The payload binds\n// each confirmation to its operation kind and sorted target-path set (spec R9,\n// R10); the handler additionally rejects any retry whose decoded paths do not\n// match the retried request's parameters (the codec only proves the state was\n// not tampered — it cannot see the current args).\nimport type {\n ClientCapabilities,\n InputRequest,\n InputRequiredResult,\n RequestStateCodec,\n ServerContext,\n} from '@modelcontextprotocol/server';\nimport {\n acceptedContent,\n createRequestStateCodec,\n inputRequired,\n inputResponse,\n} from '@modelcontextprotocol/server';\n\nimport { randomBytes } from 'node:crypto';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, FsError } from './errors.ts';\nimport type { FileType } from './fs.ts';\nimport { Logger } from './observability.ts';\n\n/** The destructive operation a pending confirmation authorizes. */\ntype PendingOp = 'delete' | 'move' | 'copy' | 'create' | 'grant';\n\n/** The original filesystem object covered by a recursive-delete confirmation. */\nexport interface PendingDeleteIdentity {\n readonly path: string;\n readonly itemType: FileType;\n readonly dev: number;\n readonly ino: number;\n readonly birthtimeMs: number;\n}\n\n/**\n * Integrity-protected state minted into an `input_required` result and echoed\n * back by the client on retry. `paths` is the sorted canonical set of target\n * paths the confirmation covers; the handler compares it to the retried\n * request's parameters and rejects a mismatch (R9).\n */\nexport interface PendingState {\n readonly op: PendingOp;\n readonly paths: readonly string[];\n /** Original objects, preserved on reissue; legacy tokens without these cannot authorize delete. */\n readonly deleteIdentities?: readonly PendingDeleteIdentity[];\n /**\n * Set on the state of a round minted because the previous round's answer\n * was dropped by the SDK (`droppedInputResponseKeys`). Sealed in the HMAC\n * payload, so a client cannot clear it: the re-issue happens once.\n */\n readonly reissued?: true;\n}\n\n/** The per-round confirmation context; `ToolCtx` satisfies it structurally. */\nexport interface PendingCtx {\n readonly requestState?: (() => PendingState | undefined) | undefined;\n /**\n * What the client declared it can do, or `undefined` when this connection\n * cannot say. Only positively-absent form support short-circuits; see\n * {@link assertCanElicit}.\n */\n readonly clientCapabilities?: ClientCapabilities | undefined;\n /** `ctx.mcpReq.droppedInputResponseKeys` for this round; see `ToolCtx`. */\n readonly droppedInputResponseKeys?: readonly string[] | undefined;\n readonly inputResponses?: Record<string, unknown> | undefined;\n /** The live handler context; the codec binds the minted state to its method and caller. */\n readonly serverCtx: ServerContext;\n}\n\n/** One embedded form-mode confirmation, keyed within the call. */\nexport interface PendingInput {\n /** Server-assigned key, unique within the `tools/call`. */\n readonly key: string;\n /** Human-readable prompt for this item. */\n readonly message: string;\n /**\n * When set, the form offers a single-select enum (`choice` field) over\n * these values instead of a boolean `confirm`.\n */\n readonly choices?: readonly string[];\n /**\n * When set with `choices`, the form offers a multi-select enum: `choice` is\n * a string array (`MultiSelectEnumSchema` shape) and the caller reads the\n * accepted set with `readAcceptedMultiChoice`. Single-select otherwise.\n */\n readonly multi?: boolean;\n}\n\n/**\n * HMAC key for the requestState codec. Read once from\n * `FS_REQUEST_STATE_KEY` (UTF-8, must be >=32 bytes); a random\n * 32-byte key is generated at boot when the env var is unset or too short. A\n * per-process key is correct for stdio and the single-node HTTP leg (decision\n * record 11). A server restart invalidates in-flight tokens; the client\n * re-requests, which is fail-closed and safe.\n */\nfunction configuredRequestStateKey(): Uint8Array | undefined {\n const env = process.env['FS_REQUEST_STATE_KEY'];\n if (env) {\n const bytes = Buffer.from(env, 'utf8');\n if (bytes.length >= 32) return bytes;\n Logger.warn(\n `FS_REQUEST_STATE_KEY is ${String(bytes.length)} bytes; 32 are required. Falling back to a random per-boot key — in-flight input_required rounds will not survive a restart.`,\n );\n }\n return undefined;\n}\n\n/**\n * What a minted `requestState` is bound to: the JSON-RPC method of the\n * request that minted it and the authenticated caller (`ctx.http` is absent\n * on stdio, so the caller part is empty there and constant across rounds).\n * The SDK stores an HMAC tag of this value in the token and refuses an echo\n * whose context yields a different value.\n */\nfunction requestStateBinding(ctx: ServerContext): string {\n return `${ctx.mcpReq.method}\\0${ctx.http?.authInfo?.clientId ?? ''}`;\n}\n\n/**\n * The codec: `mint` seals a `PendingState` into the opaque wire string a\n * handler returns from `inputRequired({ requestState })`; `verify` drops into\n * `ServerOptions.requestState.verify` and throws on tamper, expiry, or bind\n * mismatch (the seam answers with the frozen `-32602`).\n */\nexport const requestStateCodec: RequestStateCodec<PendingState> =\n createRequestStateCodec<PendingState>({\n key: configuredRequestStateKey() ?? randomBytes(32),\n bind: requestStateBinding,\n });\n\n// Response shapes handed to the SDK's schema-aware `acceptedContent` overload:\n// it returns `undefined` for a missing key, a decline/cancel, a non-elicit\n// response, AND a payload that fails validation — one call covers every refusal\n// case the readers below used to hand-check. `buildInputRequired` reuses\n// `ConfirmContent` as the no-choices form schema (below), so these sit above it.\nconst ConfirmContent = z.object({ confirm: z.boolean().meta({ title: 'Confirm' }) });\nconst ChoiceContent = z.object({ choice: z.string() });\nconst MultiChoiceContent = z.object({ choice: z.array(z.string()) });\n\n/**\n * The form the client renders for one pending input, as the Zod schema the\n * SDK converts to the elicitation wire shape. A boolean `confirm` when no\n * choices are offered; otherwise a `choice` enum over the offered values,\n * wrapped in an array for multi-select so the client may accept a subset.\n * The offered lists are never empty by construction (single-select always\n * offers two literals; multi-select only runs with two or more grant dirs),\n * so no empty-array guard is added. Each field carries a `title` so a host\n * that renders the form labels it instead of showing the property name.\n */\nfunction requestedSchemaFor(input: PendingInput): z.ZodObject {\n if (!input.choices) return ConfirmContent;\n const value = z.enum(input.choices);\n return z.object({\n choice: input.multi ? z.array(value).meta({ title: 'Allow' }) : value.meta({ title: 'Action' }),\n });\n}\n\n/**\n * Build an `input_required` result carrying one boolean confirmation per pending\n * item, plus the integrity-protected `requestState` sealing the operation kind\n * and sorted target paths. `mint` is async (HMAC + base64url).\n */\nexport async function buildInputRequired(\n pending: PendingState,\n inputs: readonly PendingInput[],\n ctx: ServerContext,\n): Promise<InputRequiredResult> {\n const inputRequests: Record<string, InputRequest> = {};\n for (const input of inputs) {\n inputRequests[input.key] = inputRequired.elicit({\n message: input.message,\n requestedSchema: requestedSchemaFor(input),\n });\n }\n const requestState = await requestStateCodec.mint(\n {\n op: pending.op,\n paths: [...pending.paths].sort(),\n ...(pending.deleteIdentities ? { deleteIdentities: pending.deleteIdentities } : {}),\n ...(pending.reissued ? { reissued: true as const } : {}),\n },\n ctx,\n );\n return inputRequired({ inputRequests, requestState });\n}\n\n/**\n * The shared read-state → `buildInputRequired` → mismatch-throw flow used by\n * every destructive-confirmation handler (delete, move, grant). No verified\n * state, OR a verified state belonging to a different `op` (e.g. a chained\n * call's grant round already resolved and this is now that same call's own\n * delete/move confirmation round), mints a fresh `input_required` for this\n * op. A retry whose verified state matches this op but not the pending path\n * set throws `FsError(INVALID_INPUT)` (R9) — uniformly surfaced as an\n * `isError` tool result by the handler's catch. Returns `undefined` on a\n * matching same-op retry so the caller proceeds.\n *\n * One home for the R9 binding check means a future fix cannot miss two of three\n * sites. The caller passes the round's `PendingCtx` and supplies `buildInputs`\n * so only the prompt text varies.\n */\ninterface PendingRoundTripOpts {\n readonly op: PendingOp;\n readonly pending: readonly string[];\n readonly deleteIdentities?: readonly PendingDeleteIdentity[];\n readonly buildInputs: (pending: readonly string[]) => readonly PendingInput[];\n}\n\n/**\n * What to tell the model when the round-trip cannot happen. Each names the way\n * forward that does not need a confirmation, or says plainly that there is\n * none — a dead end the model can report is worth more than a retry loop.\n */\nconst NO_ELICITATION_HINT: Readonly<Record<PendingOp, string>> = {\n delete:\n 'Deleting a non-empty directory needs a confirmation this client cannot show. ' +\n 'Delete the entries inside it individually, or connect a client that declares the elicitation capability.',\n move:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Delete the destination first, or move to a path that does not exist yet.',\n copy:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Pass overwrite=true to replace it without confirming, or copy to a path that does not exist yet.',\n create:\n 'Overwriting an existing file needs a confirmation this client cannot show. ' +\n 'Pass overwrite: true on that entry to replace it without confirming, append: true to add to it, or read it and use edit.',\n grant:\n 'Granting access to a directory outside the allowed roots needs a confirmation this client cannot show. ' +\n 'Call list_roots and use a path under one of the roots it returns.',\n};\n\n/**\n * Fail early, and legibly, when the client cannot answer an embedded form.\n * The SDK checks each `inputRequests` entry against the declared client\n * capabilities and rejects the whole call with `-32021` before anything reaches\n * the wire — a protocol error the model never sees. Throwing `FsError` here\n * instead lands in the tool executor's catch and reaches the model as an\n * `isError` result carrying the workaround.\n *\n * `undefined` capabilities mean the connection cannot report them, NOT that the\n * client has none: proceed and let the SDK decide, exactly as before this check\n * existed.\n */\nfunction assertCanElicit(op: PendingOp, capabilities: ClientCapabilities | undefined): void {\n if (capabilities === undefined) return;\n const elicitation = capabilities.elicitation;\n if (\n elicitation !== undefined &&\n (elicitation.form !== undefined || elicitation.url === undefined)\n ) {\n return;\n }\n throw new FsError(ErrorCode.INVALID_INPUT, `${op}: ${NO_ELICITATION_HINT[op]}`);\n}\n\nexport async function pendingRoundTrip(\n ctx: PendingCtx,\n opts: PendingRoundTripOpts,\n): Promise<InputRequiredResult | undefined> {\n const state = ctx.requestState?.();\n // No verified state yet, OR the verified state belongs to a different\n // flow (e.g. an access-grant round's state is still the retried request's\n // requestState after the grant was applied, and this call is now the\n // destructive-confirmation round for the SAME tool call) — either way,\n // this op has not yet had its own round-trip, so mint a fresh\n // input_required rather than treating a foreign-but-valid state as a\n // tamper/mismatch error.\n if (state?.op !== opts.op) {\n assertCanElicit(opts.op, ctx.clientCapabilities);\n return buildInputRequired(\n {\n op: opts.op,\n paths: opts.pending,\n ...(opts.deleteIdentities ? { deleteIdentities: opts.deleteIdentities } : {}),\n },\n opts.buildInputs(opts.pending),\n ctx.serverCtx,\n );\n }\n // Retry for THIS op (R9): the verified state must bind the same pending set.\n if (!pathsEqual(state.paths, opts.pending)) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `${opts.op}: confirmation does not match the requested paths`,\n );\n }\n // The client answered, but in a shape the SDK discards before the handler\n // runs (`{ method, result }` around the bare result). Ask the same question\n // once more rather than report a refusal the user never made; the sealed\n // `reissued` flag stops a second retry from looping.\n if (state.reissued !== true && ctx.droppedInputResponseKeys?.length) {\n const dropped = new Set(ctx.droppedInputResponseKeys);\n const inputs = opts.buildInputs(opts.pending);\n if (inputs.some((input) => dropped.has(input.key))) {\n return buildInputRequired({ ...state, reissued: true }, inputs, ctx.serverCtx);\n }\n }\n return undefined;\n}\n\n/**\n * Round-trip key for `pendingSorted[index]` — the single home of the\n * `confirm_${i}` convention. The build side mints it with the map index; the\n * read side re-derives it from the same sorted pending set the requestState\n * binds (R9), so a format change lands here once instead of at six call\n * sites.\n */\nexport function confirmKey(index: number): string {\n return `confirm_${index}`;\n}\n\n/**\n * Read one pending item's boolean confirmation from a retried request's\n * `inputResponses`. Returns `true` only when the client explicitly accepted AND\n * the `confirm` field is `true`; every other outcome (decline, cancel, missing\n * key, accept-without-confirm) returns `false`, which the caller reports as\n * `CANCELLED` (R3 proceed, R4/R5 cancelled).\n */\nexport function readAcceptedConfirm(\n responses: Record<string, unknown> | undefined,\n key: string,\n): boolean {\n return acceptedContent(responses, key, ConfirmContent)?.confirm === true;\n}\n\n/**\n * Read one pending item's enum selection from a retried request's\n * `inputResponses`. Returns the chosen `value` only when the client explicitly\n * accepted AND the `choice` field is a string; every other outcome (decline,\n * cancel, missing key, accept-without-choice) returns `undefined`, which the\n * caller reports as `CANCELLED` — same contract as the boolean reader.\n *\n * The shape is SDK-validated, but the returned value is NOT checked for\n * membership in the `choices` offered in the request schema. Callers must\n * compare against the expected values (e.g. `choice === 'overwrite'`) before\n * acting — never echo the string back into a path or trust it as an enum\n * member.\n */\nexport function readAcceptedChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n return acceptedContent(responses, key, ChoiceContent)?.choice;\n}\n\n/**\n * Read one pending item's multi-select enum selection from a retried request's\n * `inputResponses`. Returns the accepted `value`s only when the client\n * explicitly accepted AND `choice` is a string array of strings; every other\n * outcome (decline, cancel, missing key, accept-without-choice, non-array\n * `choice`, non-string elements) returns `undefined`, which the caller reports\n * as `CANCELLED` — same contract as the single-select reader.\n *\n * As with `readAcceptedChoice`, the returned values are NOT checked for\n * membership in the offered `choices`; callers must compare against the\n * expected set before acting.\n */\nexport function readAcceptedMultiChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string[] | undefined {\n return acceptedContent(responses, key, MultiChoiceContent)?.choice;\n}\n\n/**\n * Refusal wording for the `CANCELLED` error; call after a `readAccepted*` reader\n * returned nothing. Pass the round's ctx so a dropped answer is named as such\n * rather than as 'not answered'.\n */\nexport function describeRefusal(\n ctx: Pick<PendingCtx, 'inputResponses' | 'droppedInputResponseKeys'>,\n key: string,\n): string {\n if (ctx.droppedInputResponseKeys?.includes(key)) {\n return 'answered in a shape this server cannot read (a wrapped result instead of the bare elicitation result), twice';\n }\n const view = inputResponse(ctx.inputResponses, key);\n if (view.kind !== 'elicit') return 'not answered';\n if (view.action === 'decline') return 'declined by the user';\n if (view.action === 'cancel') return 'dismissed by the user';\n return 'answered without a valid choice';\n}\n\n/**\n * Order-independent equality of two sorted, de-duplicated path lists. Used to\n * compare a recomputed pending set against the `requestState`-bound set (R9):\n * both are sorted by construction, so a straight element-wise compare settles\n * it without allocating.\n */\nfunction pathsEqual(a: readonly string[], b: readonly string[]): boolean {\n // The length check is load-bearing, not an early-out: `every` alone returns\n // true whenever `a` is a prefix of a longer `b`, so a confirmation minted for\n // ['/x'] would authorize a retry for ['/x', '/y'] — a direct R9 bypass.\n return a.length === b.length && a.every((value, index) => value === b[index]);\n}\n"]}
@@ -15,5 +15,7 @@ export declare const Logger: {
15
15
  error: (message: string, ...args: unknown[]) => void;
16
16
  debug: (message: string, ...args: unknown[]) => void;
17
17
  };
18
+ /** A failed notify means the connection went away: nothing to recover, so log and drop it. */
19
+ export declare function voidSend(send: Promise<unknown> | undefined, label: string, fields?: object): void;
18
20
  export declare function logRuntimeFailure(id: string, scope: string, method: string, error: unknown): void;
19
21
  //# sourceMappingURL=observability.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,YAAY,GACtB,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,OAAO,GAAG,WAAW,CAAC;AA2DzF;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,SAAM,GAAG,MAAM,CAEjE;AAED,eAAO,MAAM,MAAM;kBACH,YAAY,WAAW,MAAM;oBAG3B,MAAM,WAAW,OAAO,EAAE;oBAG1B,MAAM,WAAW,OAAO,EAAE;qBAGzB,MAAM,WAAW,OAAO,EAAE;qBAG1B,MAAM,WAAW,OAAO,EAAE;CAG5C,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAEjG"}
1
+ {"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,YAAY,GACtB,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,OAAO,GAAG,WAAW,CAAC;AA2DzF;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,SAAM,GAAG,MAAM,CAEjE;AAED,eAAO,MAAM,MAAM;kBACH,YAAY,WAAW,MAAM;oBAG3B,MAAM,WAAW,OAAO,EAAE;oBAG1B,MAAM,WAAW,OAAO,EAAE;qBAGzB,MAAM,WAAW,OAAO,EAAE;qBAG1B,MAAM,WAAW,OAAO,EAAE;CAG5C,CAAC;AAEF,8FAA8F;AAC9F,wBAAgB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAIjG;AAED,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAEjG"}
@@ -1,4 +1,5 @@
1
1
  import { cli } from "./config.js";
2
+ import { formatUnknownErrorMessage } from "./errors.js";
2
3
  import { warnInvalidSetting } from "./path-utils.js";
3
4
  // RFC 5424 severities, most severe first. A message is emitted when its
4
5
  // severity is at least as high as the configured minimum.
@@ -82,6 +83,12 @@ export const Logger = {
82
83
  write('debug', message, args);
83
84
  },
84
85
  };
86
+ /** A failed notify means the connection went away: nothing to recover, so log and drop it. */
87
+ export function voidSend(send, label, fields) {
88
+ void send?.catch((error) => {
89
+ Logger.debug(`${label} not delivered`, { ...fields, error: formatUnknownErrorMessage(error) });
90
+ });
91
+ }
85
92
  export function logRuntimeFailure(id, scope, method, error) {
86
93
  write('error', `Runtime failure: ${id} [${scope}.${method}]`, [error]);
87
94
  }
@@ -1 +1 @@
1
- {"version":3,"file":"observability.js","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAKrD,wEAAwE;AACxE,0DAA0D;AAC1D,MAAM,WAAW,GAA4B;IAC3C,WAAW;IACX,OAAO;IACP,UAAU;IACV,OAAO;IACP,SAAS;IACT,QAAQ;IACR,MAAM;IACN,OAAO;CACR,CAAC;AAEF,SAAS,cAAc,CAAC,KAAa;IACnC,OAAQ,WAAiC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,aAAa,CAAC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AAU,gBAAgB,CAAC,KAAa,EAAE,GAAG,GAAG,GAAG;IACvD,OAAO,KAAK,CAAC,OAAO,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AACrE,CAAC;AAED,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB,IAAI,EAAE,CAAC,KAAmB,EAAE,OAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;IAC5B,CAAC;IACD,IAAI,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC5C,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC;IACD,IAAI,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC5C,KAAK,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;IACD,KAAK,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;IACD,KAAK,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;CACF,CAAC;AAEF,MAAM,UAAU,iBAAiB,CAAC,EAAU,EAAE,KAAa,EAAE,MAAc,EAAE,KAAc;IACzF,KAAK,CAAC,OAAO,EAAE,oBAAoB,EAAE,KAAK,KAAK,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import { cli } from './config.ts';\nimport { warnInvalidSetting } from './path-utils.ts';\n\nexport type LoggingLevel =\n 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';\n\n// RFC 5424 severities, most severe first. A message is emitted when its\n// severity is at least as high as the configured minimum.\nconst LEVEL_ORDER: readonly LoggingLevel[] = [\n 'emergency',\n 'alert',\n 'critical',\n 'error',\n 'warning',\n 'notice',\n 'info',\n 'debug',\n];\n\nfunction isLoggingLevel(value: string): value is LoggingLevel {\n return (LEVEL_ORDER as readonly string[]).includes(value);\n}\n\nfunction parseLogLevel(raw: string | undefined): LoggingLevel {\n if (!raw) return 'info';\n // `warn` is the common short form; the canonical RFC 5424 level is `warning`.\n if (raw === 'warn') return 'warning';\n if (isLoggingLevel(raw)) return raw;\n warnInvalidSetting('FS_LOG_LEVEL', raw, LEVEL_ORDER.join('|'), 'info');\n return 'info';\n}\n\n// Seeded to the value `parseLogLevel(undefined)` returns, so an unset\n// FS_LOG_LEVEL — the initial `cachedRaw` — needs no first-call special case.\nlet cachedRaw: string | undefined;\nlet cachedLevel: LoggingLevel = 'info';\n\n/**\n * Minimum severity that reaches stderr, from `FS_LOG_LEVEL` / `--log-level`.\n * Memoized on the raw value, not resolved once: `cli.logLevel` lands after\n * `parseArgs`, and writes happen before that. Keying on the raw string keeps it\n * live while the invalid-value warning fires once per setting, not per line.\n */\nfunction getLogLevel(): LoggingLevel {\n const raw = (cli.logLevel ?? process.env['FS_LOG_LEVEL'])?.trim().toLowerCase();\n if (raw !== cachedRaw) {\n cachedRaw = raw;\n cachedLevel = parseLogLevel(raw);\n }\n return cachedLevel;\n}\n\n/** True when `level` is at least as severe as the configured minimum. */\nfunction isLevelEnabled(level: LoggingLevel, minimum: LoggingLevel = getLogLevel()): boolean {\n return LEVEL_ORDER.indexOf(level) <= LEVEL_ORDER.indexOf(minimum);\n}\n\nfunction write(level: LoggingLevel, message: string, args: readonly unknown[]): void {\n if (!isLevelEnabled(level)) return;\n const prefix = `[${level}]`;\n console.error(`${prefix} ${message}`, ...args);\n}\n\n/**\n * A client-supplied value (a JSON-RPC id, a `traceparent`, a tool's own log\n * message) made safe for one stderr line: a control character or a Unicode\n * line/paragraph separator (U+2028/U+2029, which `\\p{Cc}` misses) would let\n * a caller forge extra log lines, and an unbounded value would let it flood\n * one. `max` bounds the value; pass `Infinity` for free text that is only\n * flattened.\n */\nexport function sanitizeLogField(value: string, max = 128): string {\n return value.replace(/[\\p{Cc}\\p{Zl}\\p{Zp}]+/gu, ' ').slice(0, max);\n}\n\nexport const Logger = {\n emit: (level: LoggingLevel, message: string) => {\n write(level, message, []);\n },\n info: (message: string, ...args: unknown[]) => {\n write('info', message, args);\n },\n warn: (message: string, ...args: unknown[]) => {\n write('warning', message, args);\n },\n error: (message: string, ...args: unknown[]) => {\n write('error', message, args);\n },\n debug: (message: string, ...args: unknown[]) => {\n write('debug', message, args);\n },\n};\n\nexport function logRuntimeFailure(id: string, scope: string, method: string, error: unknown): void {\n write('error', `Runtime failure: ${id} [${scope}.${method}]`, [error]);\n}\n"]}
1
+ {"version":3,"file":"observability.js","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAKrD,wEAAwE;AACxE,0DAA0D;AAC1D,MAAM,WAAW,GAA4B;IAC3C,WAAW;IACX,OAAO;IACP,UAAU;IACV,OAAO;IACP,SAAS;IACT,QAAQ;IACR,MAAM;IACN,OAAO;CACR,CAAC;AAEF,SAAS,cAAc,CAAC,KAAa;IACnC,OAAQ,WAAiC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,aAAa,CAAC,GAAuB;IAC5C,IAAI,CAAC,GAAG;QAAE,OAAO,MAAM,CAAC;IACxB,8EAA8E;IAC9E,IAAI,GAAG,KAAK,MAAM;QAAE,OAAO,SAAS,CAAC;IACrC,IAAI,cAAc,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,CAAC;IACpC,kBAAkB,CAAC,cAAc,EA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InvalidSetting } from './path-utils.ts';\n\nexport type LoggingLevel =\n 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';\n\n// RFC 5424 severities, most severe first. A message is emitted when its\n// severity is at least as high as the configured minimum.\nconst LEVEL_ORDER: readonly LoggingLevel[] = [\n 'emergency',\n 'alert',\n 'critical',\n 'error',\n 'warning',\n 'notice',\n 'info',\n 'debug',\n];\n\nfunction isLoggingLevel(value: string): value is LoggingLevel {\n return (LEVEL_ORDER as readonly string[]).includes(value);\n}\n\nfunction parseLogLevel(raw: string | undefined): LoggingLevel {\n if (!raw) return 'info';\n // `warn` is the common short form; the canonical RFC 5424 level is `warning`.\n if (raw === 'warn') return 'warning';\n if (isLoggingLevel(raw)) return raw;\n warnInvalidSetting('FS_LOG_LEVEL', raw, LEVEL_ORDER.join('|'), 'info');\n return 'info';\n}\n\n// Seeded to the value `parseLogLevel(undefined)` returns, so an unset\n// FS_LOG_LEVEL — the initial `cachedRaw` — needs no first-call special case.\nlet cachedRaw: string | undefined;\nlet cachedLevel: LoggingLevel = 'info';\n\n/**\n * Minimum severity that reaches stderr, from `FS_LOG_LEVEL` / `--log-level`.\n * Memoized on the raw value, not resolved once: `cli.logLevel` lands after\n * `parseArgs`, and writes happen before that. Keying on the raw string keeps it\n * live while the invalid-value warning fires once per setting, not per line.\n */\nfunction getLogLevel(): LoggingLevel {\n const raw = (cli.logLevel ?? process.env['FS_LOG_LEVEL'])?.trim().toLowerCase();\n if (raw !== cachedRaw) {\n cachedRaw = raw;\n cachedLevel = parseLogLevel(raw);\n }\n return cachedLevel;\n}\n\n/** True when `level` is at least as severe as the configured minimum. */\nfunction isLevelEnabled(level: LoggingLevel, minimum: LoggingLevel = getLogLevel()): boolean {\n return LEVEL_ORDER.indexOf(level) <= LEVEL_ORDER.indexOf(minimum);\n}\n\nfunction write(level: LoggingLevel, message: string, args: readonly unknown[]): void {\n if (!isLevelEnabled(level)) return;\n const prefix = `[${level}]`;\n console.error(`${prefix} ${message}`, ...args);\n}\n\n/**\n * A client-supplied value (a JSON-RPC id, a `traceparent`, a tool's own log\n * message) made safe for one stderr line: a control character or a Unicode\n * line/paragraph separator (U+2028/U+2029, which `\\p{Cc}` misses) would let\n * a caller forge extra log lines, and an unbounded value would let it flood\n * one. `max` bounds the value; pass `Infinity` for free text that is only\n * flattened.\n */\nexport function sanitizeLogField(value: string, max = 128): string {\n return value.replace(/[\\p{Cc}\\p{Zl}\\p{Zp}]+/gu, ' ').slice(0, max);\n}\n\nexport const Logger = {\n emit: (level: LoggingLevel, message: string) => {\n write(level, message, []);\n },\n info: (message: string, ...args: unknown[]) => {\n write('info', message, args);\n },\n warn: (message: string, ...args: unknown[]) => {\n write('warning', message, args);\n },\n error: (message: string, ...args: unknown[]) => {\n write('error', message, args);\n },\n debug: (message: string, ...args: unknown[]) => {\n write('debug', message, args);\n },\n};\n\n/** A failed notify means the connection went away: nothing to recover, so log and drop it. */\nexport function voidSend(send: Promise<unknown> | undefined, label: string, fields?: object): void {\n void send?.catch((error: unknown) => {\n Logger.debug(`${label} not delivered`, { ...fields, error: formatUnknownErrorMessage(error) });\n });\n}\n\nexport function logRuntimeFailure(id: string, scope: string, method: string, error: unknown): void {\n write('error', `Runtime failure: ${id} [${scope}.${method}]`, [error]);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"path-completer.d.ts","sourceRoot":"","sources":["../../src/core/path-completer.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAyK3C;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CA6BzF"}
1
+ {"version":3,"file":"path-completer.d.ts","sourceRoot":"","sources":["../../src/core/path-completer.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAyJ3C;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAyBzF"}
@@ -1,9 +1,8 @@
1
- import { opendir, stat } from 'node:fs/promises';
1
+ import { opendir } from 'node:fs/promises';
2
2
  import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';
3
3
  import { isSkippableErrno, rethrowIfAborted } from "./errors.js";
4
4
  import { Logger } from "./observability.js";
5
- import { isPathWithinDirectories, isSamePath, isSlash, normalizePath, toPosixPath, } from "./path-utils.js";
6
- import { resolveRealPath } from "./path.js";
5
+ import { isSamePath, isSlash, normalizePath, toPosixPath } from "./path-utils.js";
7
6
  // ─── pure path-completion helpers ───────────────────────────────────────────
8
7
  function hasTrailingSeparator(value) {
9
8
  return value.length > 0 && isSlash(value.charCodeAt(value.length - 1));
@@ -43,26 +42,6 @@ function resolveNamedRootContext(currentValue, allowed) {
43
42
  const trailingSeparator = hasTrailingSeparator(currentValue);
44
43
  return resolveFromBase(root, parsed.remainder, trailingSeparator);
45
44
  }
46
- async function isAllowedCompletionDirectory(path, allowed) {
47
- if (!isPathWithinDirectories(path, allowed))
48
- return false;
49
- try {
50
- const stats = await stat(path);
51
- if (!stats.isDirectory())
52
- return false;
53
- const real = await resolveRealPath(path);
54
- return real !== null && isPathWithinDirectories(real, allowed);
55
- }
56
- catch (err) {
57
- if (!isSkippableErrno(err)) {
58
- Logger.debug('isAllowedCompletionDirectory: unexpected probe error', {
59
- path,
60
- error: String(err),
61
- });
62
- }
63
- return false;
64
- }
65
- }
66
45
  function withDirectorySeparator(value) {
67
46
  return value.endsWith(sep) ? value : `${value}${sep}`;
68
47
  }
@@ -87,9 +66,13 @@ function mergeCompletionMatches(dirMatches, rootMatches) {
87
66
  const isDir = (v) => v.endsWith(sep);
88
67
  return [...new Set([...dirMatches, ...rootMatches])].sort((left, right) => Number(isDir(right)) - Number(isDir(left)) || left.localeCompare(right));
89
68
  }
90
- async function findMatchesInDirectory(searchDir, prefix, allowed, isSensitive) {
69
+ async function findMatchesInDirectory(searchDir, prefix, pathGuard) {
91
70
  const matches = [];
92
- if (!(await isAllowedCompletionDirectory(searchDir, allowed)))
71
+ // The guard owns what a listing may enter: containment through the real
72
+ // path, device names, the sensitive list, is-a-directory. A refusal is
73
+ // "nothing to list", never an error, so root suggestions survive it.
74
+ const listable = await pathGuard.validateExistingDirectory(searchDir).then(() => true, () => false);
75
+ if (!listable)
93
76
  return matches;
94
77
  try {
95
78
  // Stream via opendir and collect every match. Do not cap here: the
@@ -105,7 +88,7 @@ async function findMatchesInDirectory(searchDir, prefix, allowed, isSensitive) {
105
88
  if (prefix !== '' && !entry.name.toLowerCase().startsWith(lowerPrefix))
106
89
  continue;
107
90
  const fullPath = join(searchDir, entry.name);
108
- if (isSensitive?.(fullPath))
91
+ if (pathGuard.isSensitive(fullPath))
109
92
  continue;
110
93
  matches.push(entry.isDirectory() ? `${fullPath}${sep}` : fullPath);
111
94
  }
@@ -147,10 +130,8 @@ function getSearchContext(currentValue, allowed) {
147
130
  * every match, sorted; the SDK truncates to 100 and reports the total.
148
131
  */
149
132
  export async function suggestPaths(pathGuard, value) {
150
- // Roots to pick, name and list; the containment set also holds each root's
151
- // realpath alias, so it only gates what a directory listing may enter.
133
+ // Roots to pick, name and list.
152
134
  const roots = pathGuard.getRoots();
153
- const allowed = pathGuard.getAllowedDirectories();
154
135
  try {
155
136
  if (!value) {
156
137
  return roots;
@@ -160,7 +141,7 @@ export async function suggestPaths(pathGuard, value) {
160
141
  return findRootPrefixMatches(value, roots);
161
142
  }
162
143
  const { searchDir, prefix } = context;
163
- const dirMatches = await findMatchesInDirectory(searchDir, prefix, allowed, (p) => pathGuard.isSensitive(p));
144
+ const dirMatches = await findMatchesInDirectory(searchDir, prefix, pathGuard);
164
145
  const rootMatches = findMatchingRoots(searchDir, prefix, roots);
165
146
  return mergeCompletionMatches(dirMatches, rootMatches);
166
147
  }
@@ -1 +1 @@
1
-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AW,CAAC,CAAC;IACzD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,gBAAgB,CAAC,KAAK,CAAC,CAAC;QACxB,MAAM,CAAC,IAAI,CAAC,uDAAuD,EAAE;YACnE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;SAC/E,CAAC,CAAC;QACH,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["import { opendir, stat } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';\n\nimport { isSkippableErrno, rethrowIfAborted } from './errors.ts';\nimport { Logger } from './observability.ts';\nimport {\n isPathWithinDirectories,\n isSamePath,\n isSlash,\n normalizePath,\n toPosixPath,\n} from './path-utils.ts';\nimport type { PathGuard } from './path.ts';\nimport { resolveRealPath } from './path.ts';\n\n// ─── pure path-completion helpers ───────────────────────────────────────────\n\nfunction hasTrailingSeparator(value: string): boolean {\n return value.length > 0 && isSlash(value.charCodeAt(value.length - 1));\n}\n\nfunction resolveFromBase(\n base: string,\n rawValue: string,\n trailingSeparator: boolean,\n): { searchDir: string; prefix: string } {\n const normalizedValue = normalizePath(resolve(base, rawValue));\n if (trailingSeparator) return { searchDir: normalizedValue, prefix: '' };\n return {\n searchDir: dirname(normalizedValue),\n prefix: basename(normalizedValue),\n };\n}\n\nfunction parseNamedRootInput(value: string): { rootName: string; remainder: string } | undefined {\n const normalizedInput = toPosixPath(value);\n if (!normalizedInput) return undefined;\n const slashIndex = normalizedInput.indexOf('/');\n if (slashIndex === -1) return { rootName: normalizedInput, remainder: '' };\n const rootName = normalizedInput.slice(0, slashIndex);\n if (!rootName) return undefined;\n return { rootName, remainder: normalizedInput.slice(slashIndex + 1) };\n}\n\nfunction findAllowedRootByName(rootName: string, allowed: readonly string[]): string | undefined {\n const normalizedRootName = rootName.toLowerCase();\n return allowed.find((candidate) => basename(candidate).toLowerCase() === normalizedRootName);\n}\n\nfunction resolveNamedRootContext(\n currentValue: string,\n allowed: readonly string[],\n): { searchDir: string; prefix: string } | undefined {\n const parsed = parseNamedRootInput(currentValue);\n if (!parsed) return undefined;\n const root = findAllowedRootByName(parsed.rootName, allowed);\n if (!root) return undefined;\n const trailingSeparator = hasTrailingSeparator(currentValue);\n return resolveFromBase(root, parsed.remainder, trailingSeparator);\n}\n\nasync function isAllowedCompletionDirectory(\n path: string,\n allowed: readonly string[],\n): Promise<boolean> {\n if (!isPathWithinDirectories(path, allowed)) return false;\n try {\n const stats = await stat(path);\n if (!stats.isDirectory()) return false;\n const real = await resolveRealPath(path);\n return real !== null && isPathWithinDirectories(real, allowed);\n } catch (err) {\n if (!isSkippableErrno(err)) {\n Logger.debug('isAllowedCompletionDirectory: unexpected probe error', {\n path,\n error: String(err),\n });\n }\n return false;\n }\n}\n\nfunction withDirectorySeparator(value: string): string {\n return value.endsWith(sep) ? value : `${value}${sep}`;\n}\n\nfunction collectAllowedRoots(\n allowed: readonly string[],\n predicate: (root: string) => boolean,\n): string[] {\n return allowed.filter(predicate).map(withDirectorySeparator);\n}\n\nfunction findRootPrefixMatches(currentValue: string, allowed: readonly string[]): string[] {\n const rootPrefix = parseNamedRootInput(currentValue)?.rootName.toLowerCase() ?? '';\n return collectAllowedRoots(allowed, (root) =>\n basename(root).toLowerCase().startsWith(rootPrefix),\n );\n}\n\nfunction findMatchingRoots(\n searchDir: string,\n prefix: string,\n allowed: readonly string[],\n): string[] {\n const lowerPrefix = prefix.toLowerCase();\n const normalizedSearchDir = normalizePath(searchDir);\n return collectAllowedRoots(allowed, (root) => {\n const rootDir = dirname(root);\n if (!isSamePath(rootDir, normalizedSearchDir)) return false;\n return basename(root).toLowerCase().startsWith(lowerPrefix);\n });\n}\n\nfunction mergeCompletionMatches(\n dirMatches: readonly string[],\n rootMatches: readonly string[],\n): string[] {\n const isDir = (v: string): boolean => v.endsWith(sep);\n return [...new Set([...dirMatches, ...rootMatches])].sort(\n (left, right) => Number(isDir(right)) - Number(isDir(left)) || left.localeCompare(right),\n );\n}\n\nasync function findMatchesInDirectory(\n searchDir: string,\n prefix: string,\n allowed: readonly string[],\n isSensitive?: (path: string) => boolean,\n): Promise<string[]> {\n const matches: string[] = [];\n if (!(await isAllowedCompletionDirectory(searchDir, allowed))) return matches;\n try {\n // Stream via opendir and collect every match. Do not cap here: the\n // SDK's completion result keeps the first 100 values and reports the\n // full length as `total` / `hasMore`, so the list must reach it whole\n // and already sorted (mergeCompletionMatches). Capping here would\n // keep the opendir-first 100, not the alphabetically-first 100, and\n // hide the true count from the client.\n const dir = await opendir(searchDir);\n try {\n const lowerPrefix = prefix.toLowerCase();\n for await (const entry of dir) {\n if (prefix !== '' && !entry.name.toLowerCase().startsWith(lowerPrefix)) continue;\n const fullPath = join(searchDir, entry.name);\n if (isSensitive?.(fullPath)) continue;\n matches.push(entry.isDirectory() ? `${fullPath}${sep}` : fullPath);\n }\n } finally {\n await dir.close().catch(() => {\n /* dir already closed or opendir never resolved */\n });\n }\n } catch (err) {\n if (!isSkippableErrno(err)) {\n Logger.warn('PathCompleter.findMatchesInDirectory: readdir failed', {\n searchDir,\n error: String(err),\n });\n }\n }\n return matches;\n}\n\nfunction getSearchContext(\n currentValue: string,\n allowed: readonly string[],\n): { searchDir: string; prefix: string } | undefined {\n const trailingSeparator = hasTrailingSeparator(currentValue);\n if (isAbsolute(currentValue)) {\n return resolveFromBase(parse(currentValue).root || sep, currentValue, trailingSeparator);\n }\n const namedRootContext = resolveNamedRootContext(currentValue, allowed);\n if (namedRootContext) return namedRootContext;\n if (allowed.length === 1) {\n const base = allowed[0];\n if (base) return resolveFromBase(base, currentValue, trailingSeparator);\n }\n return undefined;\n}\n\n/**\n * Path suggestions for `completion/complete` on the file template. One\n * `opendir` per call; clients debounce, so nothing is cached here. Returns\n * every match, sorted; the SDK truncates to 100 and reports the total.\n */\nexport async function suggestPaths(pathGuard: PathGuard, value: string): Promise<string[]> {\n // Roots to pick, name and list; the containment set also holds each root's\n // realpath alias, so it only gates what a directory listing may enter.\n const roots = pathGuard.getRoots();\n const allowed = pathGuard.getAllowedDirectories();\n\n try {\n if (!value) {\n return roots;\n }\n\n const context = getSearchContext(value, roots);\n if (!context) {\n return findRootPrefixMatches(value, roots);\n }\n\n const { searchDir, prefix } = context;\n const dirMatches = await findMatchesInDirectory(searchDir, prefix, allowed, (p) =>\n pathGuard.isSensitive(p),\n );\n const rootMatches = findMatchingRoots(searchDir, prefix, roots);\n return mergeCompletionMatches(dirMatches, rootMatches);\n } catch (error) {\n rethrowIfAborted(error);\n Logger.warn('suggestPaths: completion failed, returning empty list', {\n error: error instanceof Error ? (error.stack ?? error.message) : String(error),\n });\n return [];\n }\n}\n"]}
1
+ {"version":3,"file":"path-completer.js","sourceRoot":"","sources":["../../src/core/path-completer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAErF,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGlF,+EAA+E;AAE/E,SAAS,oBAAoB,CAAC,KAAa;IACzC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;AACzE,CAAC;AAED,SAAS,eAAe,CACtB,IAAY,EACZ,QAAgB,EAChB,iBAA0B;IAE1B,MAAM,eAAe,GAAG,a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,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;SAC/E,CAAC,CAAC;QACH,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["import { opendir } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';\n\nimport { isSkippableErrno, rethrowIfAborted } from './errors.ts';\nimport { Logger } from './observability.ts';\nimport { isSamePath, isSlash, normalizePath, toPosixPath } from './path-utils.ts';\nimport type { PathGuard } from './path.ts';\n\n// ─── pure path-completion helpers ───────────────────────────────────────────\n\nfunction hasTrailingSeparator(value: string): boolean {\n return value.length > 0 && isSlash(value.charCodeAt(value.length - 1));\n}\n\nfunction resolveFromBase(\n base: string,\n rawValue: string,\n trailingSeparator: boolean,\n): { searchDir: string; prefix: string } {\n const normalizedValue = normalizePath(resolve(base, rawValue));\n if (trailingSeparator) return { searchDir: normalizedValue, prefix: '' };\n return {\n searchDir: dirname(normalizedValue),\n prefix: basename(normalizedValue),\n };\n}\n\nfunction parseNamedRootInput(value: string): { rootName: string; remainder: string } | undefined {\n const normalizedInput = toPosixPath(value);\n if (!normalizedInput) return undefined;\n const slashIndex = normalizedInput.indexOf('/');\n if (slashIndex === -1) return { rootName: normalizedInput, remainder: '' };\n const rootName = normalizedInput.slice(0, slashIndex);\n if (!rootName) return undefined;\n return { rootName, remainder: normalizedInput.slice(slashIndex + 1) };\n}\n\nfunction findAllowedRootByName(rootName: string, allowed: readonly string[]): string | undefined {\n const normalizedRootName = rootName.toLowerCase();\n return allowed.find((candidate) => basename(candidate).toLowerCase() === normalizedRootName);\n}\n\nfunction resolveNamedRootContext(\n currentValue: string,\n allowed: readonly string[],\n): { searchDir: string; prefix: string } | undefined {\n const parsed = parseNamedRootInput(currentValue);\n if (!parsed) return undefined;\n const root = findAllowedRootByName(parsed.rootName, allowed);\n if (!root) return undefined;\n const trailingSeparator = hasTrailingSeparator(currentValue);\n return resolveFromBase(root, parsed.remainder, trailingSeparator);\n}\n\nfunction withDirectorySeparator(value: string): string {\n return value.endsWith(sep) ? value : `${value}${sep}`;\n}\n\nfunction collectAllowedRoots(\n allowed: readonly string[],\n predicate: (root: string) => boolean,\n): string[] {\n return allowed.filter(predicate).map(withDirectorySeparator);\n}\n\nfunction findRootPrefixMatches(currentValue: string, allowed: readonly string[]): string[] {\n const rootPrefix = parseNamedRootInput(currentValue)?.rootName.toLowerCase() ?? '';\n return collectAllowedRoots(allowed, (root) =>\n basename(root).toLowerCase().startsWith(rootPrefix),\n );\n}\n\nfunction findMatchingRoots(\n searchDir: string,\n prefix: string,\n allowed: readonly string[],\n): string[] {\n const lowerPrefix = prefix.toLowerCase();\n const normalizedSearchDir = normalizePath(searchDir);\n return collectAllowedRoots(allowed, (root) => {\n const rootDir = dirname(root);\n if (!isSamePath(rootDir, normalizedSearchDir)) return false;\n return basename(root).toLowerCase().startsWith(lowerPrefix);\n });\n}\n\nfunction mergeCompletionMatches(\n dirMatches: readonly string[],\n rootMatches: readonly string[],\n): string[] {\n const isDir = (v: string): boolean => v.endsWith(sep);\n return [...new Set([...dirMatches, ...rootMatches])].sort(\n (left, right) => Number(isDir(right)) - Number(isDir(left)) || left.localeCompare(right),\n );\n}\n\nasync function findMatchesInDirectory(\n searchDir: string,\n prefix: string,\n pathGuard: PathGuard,\n): Promise<string[]> {\n const matches: string[] = [];\n // The guard owns what a listing may enter: containment through the real\n // path, device names, the sensitive list, is-a-directory. A refusal is\n // \"nothing to list\", never an error, so root suggestions survive it.\n const listable = await pathGuard.validateExistingDirectory(searchDir).then(\n () => true,\n () => false,\n );\n if (!listable) return matches;\n try {\n // Stream via opendir and collect every match. Do not cap here: the\n // SDK's completion result keeps the first 100 values and reports the\n // full length as `total` / `hasMore`, so the list must reach it whole\n // and already sorted (mergeCompletionMatches). Capping here would\n // keep the opendir-first 100, not the alphabetically-first 100, and\n // hide the true count from the client.\n const dir = await opendir(searchDir);\n try {\n const lowerPrefix = prefix.toLowerCase();\n for await (const entry of dir) {\n if (prefix !== '' && !entry.name.toLowerCase().startsWith(lowerPrefix)) continue;\n const fullPath = join(searchDir, entry.name);\n if (pathGuard.isSensitive(fullPath)) continue;\n matches.push(entry.isDirectory() ? `${fullPath}${sep}` : fullPath);\n }\n } finally {\n await dir.close().catch(() => {\n /* dir already closed or opendir never resolved */\n });\n }\n } catch (err) {\n if (!isSkippableErrno(err)) {\n Logger.warn('PathCompleter.findMatchesInDirectory: readdir failed', {\n searchDir,\n error: String(err),\n });\n }\n }\n return matches;\n}\n\nfunction getSearchContext(\n currentValue: string,\n allowed: readonly string[],\n): { searchDir: string; prefix: string } | undefined {\n const trailingSeparator = hasTrailingSeparator(currentValue);\n if (isAbsolute(currentValue)) {\n return resolveFromBase(parse(currentValue).root || sep, currentValue, trailingSeparator);\n }\n const namedRootContext = resolveNamedRootContext(currentValue, allowed);\n if (namedRootContext) return namedRootContext;\n if (allowed.length === 1) {\n const base = allowed[0];\n if (base) return resolveFromBase(base, currentValue, trailingSeparator);\n }\n return undefined;\n}\n\n/**\n * Path suggestions for `completion/complete` on the file template. One\n * `opendir` per call; clients debounce, so nothing is cached here. Returns\n * every match, sorted; the SDK truncates to 100 and reports the total.\n */\nexport async function suggestPaths(pathGuard: PathGuard, value: string): Promise<string[]> {\n // Roots to pick, name and list.\n const roots = pathGuard.getRoots();\n\n try {\n if (!value) {\n return roots;\n }\n\n const context = getSearchContext(value, roots);\n if (!context) {\n return findRootPrefixMatches(value, roots);\n }\n\n const { searchDir, prefix } = context;\n const dirMatches = await findMatchesInDirectory(searchDir, prefix, pathGuard);\n const rootMatches = findMatchingRoots(searchDir, prefix, roots);\n return mergeCompletionMatches(dirMatches, rootMatches);\n } catch (error) {\n rethrowIfAborted(error);\n Logger.warn('suggestPaths: completion failed, returning empty list', {\n error: error instanceof Error ? (error.stack ?? error.message) : String(error),\n });\n return [];\n }\n}\n"]}
@@ -11,21 +11,17 @@ export interface ServerOptions {
11
11
  /** `path.relative` with forward slashes, so displayed paths match across platforms. */
12
12
  export declare function toPosixRelative(from: string, to: string): string;
13
13
  export declare function normalizeAllowedDirectories(dirs: readonly string[]): string[];
14
- export declare function resolveRealPath(normalized: string, signal?: AbortSignal): Promise<string | null>;
15
14
  export declare function resolveAllowedDirectoriesState(dirs: readonly string[], signal?: AbortSignal): Promise<string[]>;
16
15
  /**
17
- * Accepted risk: validation methods resolve/verify a path (symlinks, boundaries,
18
- * sensitivity) and then return a plain string; the actual fs operation happens
19
- * afterward as a separate syscall (classic TOCTOU). A symlink swapped in that
20
- * exact window could redirect the follow-up operation. This is mitigated by
21
- * re-validating the resolved real path (not just the requested path) and by
22
- * walking ancestors to catch escapes before the target exists, but it is not
23
- * eliminated — doing so would require fd-based operations (open with
24
- * O_NOFOLLOW / operate on the resolved fd) throughout core/fs.ts. Acceptable
25
- * tradeoff for a local, single-user filesystem server today.
16
+ * TOCTOU note: validation returns a plain string and the fs operation is a
17
+ * later syscall, so a symlink swapped in between could redirect it. Reads and
18
+ * appends in core/fs.ts and core/read.ts open with O_NOFOLLOW (final component)
19
+ * and re-check the fd's real path on Linux (ancestor swap). Residual: write
20
+ * paths that resolve a parent by name (`rename`, `mkdir`, `rm`, `cp`) would
21
+ * need openat()-relative-to-dirfd, which Node lacks; non-Linux skips the fd
22
+ * re-check.
26
23
  */
27
24
  export declare class PathGuard {
28
- #private;
29
25
  private allowedDirectoriesState;
30
26
  /** One entry per configured or granted root, without the realpath aliases. */
31
27
  private rootsState;
@@ -54,12 +50,6 @@ export declare class PathGuard {
54
50
  */
55
51
  initialize(expanded: readonly string[], roots?: readonly string[]): void;
56
52
  isInitialized(): boolean;
57
- /**
58
- * Run `fn` as the next holder of the guard's single mutation lock. Every
59
- * change to the allowed set goes through this so concurrent grants cannot
60
- * interleave their read-`await`-write and lose a grant (GRANT-1).
61
- */
62
- private runExclusive;
63
53
  getAllowedDirectories(): string[];
64
54
  /**
65
55
  * The allowed directory that contains `resolvedPath` — the longest match,
@@ -128,7 +118,6 @@ export declare class PathGuard {
128
118
  */
129
119
  applyGrant(targetDir: string): Promise<boolean>;
130
120
  private isWithinBoundary;
131
- private validateAccessAndSensitivity;
132
121
  private validateAccess;
133
122
  private handleRealpathError;
134
123
  validateExistingPathDetailed(requestedPath: string): Promise<ValidatedPathDetails>;
@@ -1 +1 @@
1
- {"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../../src/core/path.ts"],"names":[],"mappings":"AAuCA,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAsDD,uFAAuF;AACvF,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAEhE;AAMD,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAE7E;AAED,wBAAsB,eAAe,CACnC,UAAU,EAAE,MAAM,EAClB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAexB;AAED,wBAAsB,8BAA8B,CAClD,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,EAAE,CAAC,CAWnB;AAMD;;;;;;;;;;GAUG;AACH,qBAAa,SAAS;;IACpB,OAAO,CAAC,uBAAuB,CAAuB;IACtD,8EAA8E;IAC9E,OAAO,CAAC,UAAU,CAAuB;IACzC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA0B;IACpD;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,kBAAkB,CAAgB;IAC1C,OAAO,CAAC,cAAc,CAAgB;IAOtC,OAAO,CAAC,QAAQ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B5D,qBAAqB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAoE7D,2BAA2B,IAAI,OAAO,CAAC,IAAI,CAAC;CAwDnD"}
package/dist/core/path.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { lstat, readlink, realpath, stat } from 'node:fs/promises';
2
2
  import { homedir } from 'node:os';
3
3
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
- import { withAbort } from "./concurrency.js";
4
+ import { runExclusive, withAbort } from "./concurrency.js";
5
5
  import { cli } from "./config.js";
6
6
  import { classifyCauseChain, ErrorCode, FsError, isFsError, isNotFoundErrno, isSkippableErrno, rethrowIfAborted, SKIPPABLE_FS_CODES, } from "./errors.js";
7
7
  import { Logger } from "./observability.js";
@@ -63,7 +63,7 @@ export function toPosixRelative(from, to) {
63
63
  export function normalizeAllowedDirectories(dirs) {
64
64
  return [...new Set(dirs.map(normalizeAllowedDirectory).filter((entry) => entry.length > 0))];
65
65
  }
66
- export async function resolveRealPath(normalized, signal) {
66
+ async function resolveRealPath(normalized, signal) {
67
67
  try {
68
68
  signal?.throwIfAborted();
69
69
  const realPath = await withAbort(realpath(normalized), signal);
@@ -90,19 +90,14 @@ export async function resolveAllowedDirectoriesState(dirs, signal) {
90
90
  })),
91
91
  ];
92
92
  }
93
- // ---------------------------------------------------------------------------
94
- // Windows helpers
95
- // ---------------------------------------------------------------------------
96
93
  /**
97
- * Accepted risk: validation methods resolve/verify a path (symlinks, boundaries,
98
- * sensitivity) and then return a plain string; the actual fs operation happens
99
- * afterward as a separate syscall (classic TOCTOU). A symlink swapped in that
100
- * exact window could redirect the follow-up operation. This is mitigated by
101
- * re-validating the resolved real path (not just the requested path) and by
102
- * walking ancestors to catch escapes before the target exists, but it is not
103
- * eliminated — doing so would require fd-based operations (open with
104
- * O_NOFOLLOW / operate on the resolved fd) throughout core/fs.ts. Acceptable
105
- * tradeoff for a local, single-user filesystem server today.
94
+ * TOCTOU note: validation returns a plain string and the fs operation is a
95
+ * later syscall, so a symlink swapped in between could redirect it. Reads and
96
+ * appends in core/fs.ts and core/read.ts open with O_NOFOLLOW (final component)
97
+ * and re-check the fd's real path on Linux (ancestor swap). Residual: write
98
+ * paths that resolve a parent by name (`rename`, `mkdir`, `rm`, `cp`) would
99
+ * need openat()-relative-to-dirfd, which Node lacks; non-Linux skips the fd
100
+ * re-check.
106
101
  */
107
102
  export class PathGuard {
108
103
  allowedDirectoriesState;
@@ -125,10 +120,6 @@ export class PathGuard {
125
120
  */
126
121
  grantedDirectories = [];
127
122
  rootBoundaries = [];
128
- // ponytail: one mutex per PathGuard. If per-session grant throughput ever
129
- // matters, split into per-grant-dir locks; a single lock is correct for the
130
- // stdio + InMemoryEventStore single-process model.
131
- #mutex = Promise.resolve();
132
123
  options;
133
124
  constructor(options) {
134
125
  this.options = options;
@@ -144,16 +135,6 @@ export class PathGuard {
144
135
  isInitialized() {
145
136
  return this.allowedDirectoriesState !== undefined;
146
137
  }
147
- /**
148
- * Run `fn` as the next holder of the guard's single mutation lock. Every
149
- * change to the allowed set goes through this so concurrent grants cannot
150
- * interleave their read-`await`-write and lose a grant (GRANT-1).
151
- */
152
- async runExclusive(fn) {
153
- const result = this.#mutex.then(fn, fn);
154
- this.#mutex = result.then(() => undefined, () => undefined);
155
- return result;
156
- }
157
138
  getAllowedDirectories() {
158
139
  if (!this.allowedDirectoriesState) {
159
140
  return [];
@@ -331,7 +312,7 @@ export class PathGuard {
331
312
  // Read + write under the mutation lock so a concurrent grant cannot
332
313
  // interleave and lose this grant (GRANT-1). runExclusive is not reentrant:
333
314
  // nothing in this body may take the lock again.
334
- return this.runExclusive(async () => {
315
+ return runExclusive(this, async () => {
335
316
  const previous = this.grantedDirectories;
336
317
  this.grantedDirectories = [...previous, normalizePath(targetDir)];
337
318
  try {
@@ -353,33 +334,17 @@ export class PathGuard {
353
334
  return false;
354
335
  });
355
336
  }
356
- // The guard already realpath-resolved FS_ROOT_BOUNDARY into rootBoundaries
357
- // during recomputeAllowedDirectories. Reuse that single source of truth so
358
- // grant paths check the same boundary the rest of the guard enforces,
359
- // instead of re-reading the env and re-resolving each entry.
337
+ // One boundary rule for startup roots and grants: a missing target is
338
+ // projected through its nearest existing ancestor, an unresolvable one is
339
+ // refused. No boundary configured means no constraint; partitionRootsWithin
340
+ // with no bounds would drop everything, so that case returns first.
360
341
  async isWithinBoundary(targetDir) {
361
342
  if (this.rootBoundaries.length === 0) {
362
343
  return true;
363
344
  }
364
- let resolved;
365
- try {
366
- resolved = normalizePath(await realpath(targetDir));
367
- }
368
- catch {
369
- resolved = normalizePath(targetDir);
370
- }
371
- return isPathWithinDirectories(resolved, this.rootBoundaries);
345
+ const { kept } = await partitionRootsWithin([targetDir], this.rootBoundaries);
346
+ return kept.length > 0;
372
347
  }
373
- validateAccessAndSensitivity(requestedPath) {
374
- const result = this.validateAccess(requestedPath);
375
- this.assertNotSensitiveFile(requestedPath, requestedPath);
376
- this.assertNotSensitiveFile(result.normalizedRequested, requestedPath);
377
- return result;
378
- }
379
- // Synchronous since the access-grant round-trip moved to the executor's
380
- // pre-check: validateAccess only does lexical containment math and throws,
381
- // no async I/O remains. Callers still `await` it for uniform control-flow;
382
- // awaiting a non-thenable returns it unchanged.
383
348
  validateAccess(requestedPath) {
384
349
  if (!this.allowedDirectoriesState) {
385
350
  throw new FsError(ErrorCode.UNKNOWN, 'PathGuard not initialized. Call initialize() first.', requestedPath);
@@ -406,6 +371,8 @@ export class PathGuard {
406
371
  // never pre-checked — fail closed.
407
372
  this.throwAccessDenied(requestedPath, accessDeniedHint);
408
373
  }
374
+ this.assertNotSensitiveFile(requestedPath, requestedPath);
375
+ this.assertNotSensitiveFile(normalizedRequested, requestedPath);
409
376
  return {
410
377
  normalizedRequested,
411
378
  allowedDirs: this.allowedDirectoriesState,
@@ -437,7 +404,7 @@ export class PathGuard {
437
404
  throw new FsError(mapped.code, 'Cannot access path', requestedPath, error instanceof Error ? error : undefined);
438
405
  }
439
406
  async validateExistingPathDetailed(requestedPath) {
440
- const { normalizedRequested, allowedDirs, accessDeniedHint } = this.validateAccessAndSensitivity(requestedPath);
407
+ const { normalizedRequested, allowedDirs, accessDeniedHint } = this.validateAccess(requestedPath);
441
408
  let realPath;
442
409
  try {
443
410
  realPath = await realpath(normalizedRequested);
@@ -502,7 +469,7 @@ export class PathGuard {
502
469
  // resolution must be verified separately (e.g. via validateExistingPath).
503
470
  assertNotSensitiveFile(checkPath, requestedPath) {
504
471
  if (this.isSensitive(checkPath)) {
505
- throw new FsError(ErrorCode.ACCESS_DENIED, 'Sensitive file blocked. Start the server with --allow-sensitive (or FS_ALLOW_SENSITIVE=1) to override.', requestedPath);
472
+ throw new FsError(ErrorCode.ACCESS_DENIED, 'Sensitive file blocked by the server denylist. To unblock one built-in secret-file pattern, restart the server with --allow <pattern> (or FS_ALLOWLIST); --allow-sensitive (or FS_ALLOW_SENSITIVE=1) turns the whole built-in list off. Paths blocked with --deny or FS_DENYLIST stay blocked.', requestedPath);
506
473
  }
507
474
  }
508
475
  throwAccessDenied(requestedPath, hint) {
@@ -552,7 +519,7 @@ export class PathGuard {
552
519
  }
553
520
  }
554
521
  async validatePathForWrite(requestedPath) {
555
- const { normalizedRequested, allowedDirs, accessDeniedHint } = this.validateAccessAndSensitivity(requestedPath);
522
+ const { normalizedRequested, allowedDirs, accessDeniedHint } = this.validateAccess(requestedPath);
556
523
  const { realAncestor, resolvedTarget } = await this.resolveNearestExistingAncestor(requestedPath, normalizedRequested);
557
524
  if (!isPathWithinDirectories(realAncestor, allowedDirs) ||
558
525
  !isPathWithinDirectories(resolvedTarget, allowedDirs)) {
@@ -564,7 +531,7 @@ export class PathGuard {
564
531
  return resolvedTarget;
565
532
  }
566
533
  async validatePathForDelete(requestedPath) {
567
- const { normalizedRequested, allowedDirs, accessDeniedHint } = this.validateAccessAndSensitivity(requestedPath);
534
+ const { normalizedRequested, allowedDirs, accessDeniedHint } = this.validateAccess(requestedPath);
568
535
  // A workspace root is refused here, before the parent-containment check
569
536
  // below reaches for a parent that is out-of-root by construction and
570
537
  // reports "Outside allowed directories" for the one directory the caller