@carbonaitech/ottofiles-mcp 0.0.0-stage → 1.0.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 (86) hide show
  1. package/README.md +110 -2
  2. package/dist/auth.js +67 -0
  3. package/dist/auth.js.map +1 -0
  4. package/dist/config.js +104 -0
  5. package/dist/config.js.map +1 -0
  6. package/dist/elicit.js +15 -0
  7. package/dist/elicit.js.map +1 -0
  8. package/dist/gateway.js +116 -0
  9. package/dist/gateway.js.map +1 -0
  10. package/dist/guard.js +69 -0
  11. package/dist/guard.js.map +1 -0
  12. package/dist/index.js +488 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/oauth.js +259 -0
  15. package/dist/oauth.js.map +1 -0
  16. package/dist/tools/addWorkspaceDocuments.js +172 -0
  17. package/dist/tools/addWorkspaceDocuments.js.map +1 -0
  18. package/dist/tools/addWorkspaceMember.js +139 -0
  19. package/dist/tools/addWorkspaceMember.js.map +1 -0
  20. package/dist/tools/createWorkspace.js +203 -0
  21. package/dist/tools/createWorkspace.js.map +1 -0
  22. package/dist/tools/deleteDocument.js +98 -0
  23. package/dist/tools/deleteDocument.js.map +1 -0
  24. package/dist/tools/deleteWorkspace.js +81 -0
  25. package/dist/tools/deleteWorkspace.js.map +1 -0
  26. package/dist/tools/documentAccessRoster.js +36 -0
  27. package/dist/tools/documentAccessRoster.js.map +1 -0
  28. package/dist/tools/editMetadata.js +248 -0
  29. package/dist/tools/editMetadata.js.map +1 -0
  30. package/dist/tools/getDocument.js +40 -0
  31. package/dist/tools/getDocument.js.map +1 -0
  32. package/dist/tools/getDocumentHistory.js +69 -0
  33. package/dist/tools/getDocumentHistory.js.map +1 -0
  34. package/dist/tools/getDocumentVersions.js +25 -0
  35. package/dist/tools/getDocumentVersions.js.map +1 -0
  36. package/dist/tools/getPolicyStats.js +24 -0
  37. package/dist/tools/getPolicyStats.js.map +1 -0
  38. package/dist/tools/groupDocuments.js +51 -0
  39. package/dist/tools/groupDocuments.js.map +1 -0
  40. package/dist/tools/guarded.js +92 -0
  41. package/dist/tools/guarded.js.map +1 -0
  42. package/dist/tools/listCompanies.js +18 -0
  43. package/dist/tools/listCompanies.js.map +1 -0
  44. package/dist/tools/listPolicies.js +50 -0
  45. package/dist/tools/listPolicies.js.map +1 -0
  46. package/dist/tools/listWorkspaces.js +32 -0
  47. package/dist/tools/listWorkspaces.js.map +1 -0
  48. package/dist/tools/lockDocument.js +101 -0
  49. package/dist/tools/lockDocument.js.map +1 -0
  50. package/dist/tools/manageAccess.js +353 -0
  51. package/dist/tools/manageAccess.js.map +1 -0
  52. package/dist/tools/myAccess.js +48 -0
  53. package/dist/tools/myAccess.js.map +1 -0
  54. package/dist/tools/policyAccessRoster.js +35 -0
  55. package/dist/tools/policyAccessRoster.js.map +1 -0
  56. package/dist/tools/reactivateWorkspace.js +105 -0
  57. package/dist/tools/reactivateWorkspace.js.map +1 -0
  58. package/dist/tools/removeWorkspaceDocument.js +82 -0
  59. package/dist/tools/removeWorkspaceDocument.js.map +1 -0
  60. package/dist/tools/removeWorkspaceMember.js +85 -0
  61. package/dist/tools/removeWorkspaceMember.js.map +1 -0
  62. package/dist/tools/restoreDocument.js +101 -0
  63. package/dist/tools/restoreDocument.js.map +1 -0
  64. package/dist/tools/searchContent.js +70 -0
  65. package/dist/tools/searchContent.js.map +1 -0
  66. package/dist/tools/searchDocuments.js +98 -0
  67. package/dist/tools/searchDocuments.js.map +1 -0
  68. package/dist/tools/setStatus.js +133 -0
  69. package/dist/tools/setStatus.js.map +1 -0
  70. package/dist/tools/shareDocument.js +187 -0
  71. package/dist/tools/shareDocument.js.map +1 -0
  72. package/dist/tools/shareHelpers.js +50 -0
  73. package/dist/tools/shareHelpers.js.map +1 -0
  74. package/dist/tools/switchCompany.js +35 -0
  75. package/dist/tools/switchCompany.js.map +1 -0
  76. package/dist/tools/unlockDocument.js +155 -0
  77. package/dist/tools/unlockDocument.js.map +1 -0
  78. package/dist/tools/unshareDocument.js +154 -0
  79. package/dist/tools/unshareDocument.js.map +1 -0
  80. package/dist/tools/uploadVersion.js +395 -0
  81. package/dist/tools/uploadVersion.js.map +1 -0
  82. package/dist/tools/workspaceHelpers.js +153 -0
  83. package/dist/tools/workspaceHelpers.js.map +1 -0
  84. package/dist/ttl.js +54 -0
  85. package/dist/ttl.js.map +1 -0
  86. package/package.json +35 -4
package/README.md CHANGED
@@ -1,3 +1,111 @@
1
- # Temporary Holding Version
1
+ # @carbonaitech/ottofiles-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Model Context Protocol](https://modelcontextprotocol.io) server that exposes
4
+ OttoFiles read tools to an LLM, over the existing gateway, with real per-user
5
+ authorization. You **log in with your own account** (interactive OAuth) — no
6
+ secret to paste, no per-user provisioning. Every result is scoped to your own
7
+ security tier and ACLs: exactly what you'd see signed into OttoFiles.
8
+
9
+ ## Install
10
+
11
+ Published on public npm as `@carbonaitech/ottofiles-mcp` — no registry auth or
12
+ token needed to install.
13
+
14
+ **dev environment:**
15
+
16
+ ```bash
17
+ # Claude Code
18
+ claude mcp add ottofiles \
19
+ --env OTTOFILES_ISSUER=https://id.dev.carbonai.ca \
20
+ --env OTTOFILES_GATEWAY_URL=https://gateways.ottofiles.dev.carbonai.ca \
21
+ --env OTTOFILES_CLIENT_ID=ottofiles_mcp_cli \
22
+ -- npx -y @carbonaitech/ottofiles-mcp
23
+ ```
24
+
25
+ On the first tool call it opens your browser to sign in; the token (with a
26
+ refresh token) is cached under `~/.ottofiles-mcp/` and stays valid ~7 days. The
27
+ three URLs are per-environment and identical for every user.
28
+
29
+ ## Tools
30
+
31
+ All read-only except `switch_company` and the write tools below, all scoped to the signed-in user's security tier and ACLs.
32
+
33
+ | Tool | Wraps | Purpose |
34
+ |------|-------|---------|
35
+ | `search_documents` | `POST /api/search/documents` | Find documents by text, number, type, status, policy, tier, or date — paged and sorted. |
36
+ | `group_documents` | `POST /api/search/documents/group` | Per-bucket counts + last-modified over the whole tier-visible corpus (the "group summary"). |
37
+ | `list_policies` | `GET /api/policies` | List accessible policies with code, name, state, and document count. |
38
+ | `get_policy_stats` | `GET /api/policies/{id}/stats` | Aggregate a policy: document count, storage, counts by type/status, top contributors. |
39
+ | `policy_access_roster` | `GET /api/policies/{id}/access-roster` | Who can access a policy and who is denied, with effective tier rank. |
40
+ | `get_document` | `GET /documents/{id}` | Full detail for one document: status, version, file metadata, anchors, lock state. |
41
+ | `get_document_versions` | `GET /documents/{id}/versions` | Every version — increment, label, file, upload status, who and when. |
42
+ | `document_access_roster` | `GET /api/documents/{id}/access-roster` | Who can access a document and who is denied, with effective tier rank. |
43
+ | `list_workspaces` | `GET /api/workspaces` | External share spaces — title, document and member counts, expiry state. |
44
+ | `search_content` | `POST /api/search/documents` (`ContentSearch: true`) | Search inside extracted file-body text, with a snippet and `matchedInContent` flag per hit. |
45
+ | `get_document_history` | `GET /audits/streams/scope` (`Type=Document`) | A document's audit trail — who did what and when, with before/after values. Access-checked via `GET /documents/{id}`. |
46
+ | `my_access` | `GET /profile`, `GET /api/tiers/users/{id}`, `GET /api/tiers/users/{id}/policy-overrides`, `GET /api/policies` | The signed-in user's roles, security tier, policy tier overrides, and visible policies. |
47
+ | `list_companies` | `GET /profile/companies` | The companies (id, name) the signed-in user belongs to. Optional `showInactive`. |
48
+ | `switch_company` | `POST /profile/switch/companies/{id}`, token refresh, `GET /profile` | **State-changing.** Switch the active company for the whole MCP session (shared token cache, so other instances are affected) and return the new one. Interactive OAuth only; errors in headless mode. |
49
+
50
+ ## Write tools
51
+
52
+ `set_status`, `edit_metadata`, `manage_access`, `upload_version`, `lock_document`, `unlock_document`, `share_document`, `unshare_document`, `create_workspace`, `delete_workspace`, `reactivate_workspace`, `add_workspace_member`, `remove_workspace_member`, `add_workspace_documents` and `remove_workspace_document` change data. All are interactive-OAuth only.
53
+
54
+ **Do NOT allowlist or auto-approve the write tools in your MCP client.** Leave them on per-call approval. The preview token and confirmation prompts below cannot create a human gate that the client has approved away; an agent that controls both the preview and the confirm call (for example through prompt injection in a document it read) can still satisfy the token.
55
+
56
+ - **Preview, then confirm.** Every write tool previews first (`confirm` omitted or `false`; nothing changes). The preview returns a `previewToken`. `confirm:true` is refused unless it carries a valid, unexpired `previewToken` from a preview with identical effect-defining arguments. The token is an HMAC signed with a per-process random key (not persisted; restarting the server invalidates outstanding tokens) and lives 10 minutes (`OTTOFILES_PREVIEW_TTL_SECONDS`, clamped to 30-3600).
57
+ - **External disclosure.** When a tool would expose documents to someone outside the company (`create_workspace`, `add_workspace_member`, `add_workspace_documents`, `reactivate_workspace`), the client is asked via MCP elicitation, naming the recipients. If the client does not support elicitation, the call is refused unless `confirmedExternalEmails` contains exactly the external emails from the preview. `manage_access` deny and revoke also ask via elicitation when available.
58
+ - **Local file uploads.** `upload_version` reads a file from this machine and is **disabled by default**. Set `OTTOFILES_UPLOAD_ROOTS` to the absolute directories it may read from (separated by `:` on Linux/macOS, `;` on Windows, or commas). Paths are resolved through symlinks and must sit under one of the roots; anything else is refused without revealing whether it exists.
59
+ - **Workspaces.** `expiresAt` must be within 90 days; `message` is capped at 500 characters, titles at 200, member names at 100. All three are sent verbatim in the invitation email and shown in the preview.
60
+ - Duplicate-submission guards are per process and are lost when the server restarts.
61
+
62
+ ## Authentication
63
+
64
+ Two modes; the server picks one from its config.
65
+
66
+ **Interactive (default).** `authorization_code` + PKCE against IdentityServer,
67
+ with a loopback redirect (`http://127.0.0.1:8765-8767/callback`, RFC 8252). On
68
+ first use it opens the browser, you sign in as yourself, and it caches a
69
+ reference token + refresh token under `~/.ottofiles-mcp/` (7-day refresh; the MCP
70
+ sends `prompt=login`). The gateway introspects the same claims a web session
71
+ carries, so your tenant scoping and per-user tier/ACL checks apply unchanged. Set
72
+ only `OTTOFILES_CLIENT_ID` — the public PKCE client (`ottofiles_mcp_cli`),
73
+ registered in Identity by `ClientLoader`. No secret is stored.
74
+
75
+ **Headless (CI / no browser).** Set `OTTOFILES_CLIENT_SECRET` to a
76
+ `client_credentials` client (mint one with `provision/mint-mcp-credential.sh`)
77
+ and the server switches to that mode automatically. `OTTOFILES_AUTH_MODE` can
78
+ force either mode explicitly.
79
+
80
+ ## From source (local dev)
81
+
82
+ ```bash
83
+ npm install
84
+ npm run build
85
+ ```
86
+
87
+ The server is a plain **stdio Node process** the MCP client spawns — not a
88
+ container. Point it at a local `otto` stack; `docker ps` is the source of truth
89
+ for ports (`:8133` gateway, `:8101` identity — note `:8151` is the document-api
90
+ and `:8001` is another environment's identity, neither is what you want).
91
+ Register the local OAuth client once, then run it:
92
+
93
+ ```bash
94
+ # one-time: seed ottofiles_mcp_cli into the local identity DB
95
+ bash provision/register-oauth-client.sh
96
+
97
+ OTTOFILES_ISSUER=http://localhost:8101 \
98
+ OTTOFILES_GATEWAY_URL=http://localhost:8133 \
99
+ OTTOFILES_CLIENT_ID=ottofiles_mcp_cli \
100
+ npm run inspect # Inspector UI over the built server
101
+ # or: npm run dev # tsx src/index.ts over stdio
102
+ ```
103
+
104
+ Config is read from the environment, or from a `.env` in the package root (see
105
+ `.env.example`) — never from the current working directory. `provision/` holds
106
+ the credential scripts and their own README.
107
+
108
+ ## Roadmap
109
+
110
+ - Server-side detection of agent-originated writes (client discriminator, out-of-band confirmation, velocity limits) — a backend track.
111
+ - Blob / download streaming for document bytes.
package/dist/auth.js ADDED
@@ -0,0 +1,67 @@
1
+ // Refresh a little before actual expiry so an in-flight request never races the
2
+ // boundary.
3
+ const EXPIRY_SAFETY_MARGIN_MS = 60_000;
4
+ /**
5
+ * Mints and caches an OttoFiles reference token via the OAuth client_credentials
6
+ * grant. The client is a per-user "external client" (see
7
+ * IdentityCreateExternalClientConsumer in Services.Identity) whose user_id /
8
+ * company_id are baked into the client itself, so the token the gateway
9
+ * introspects carries the acting user's identity and the full per-user ACL /
10
+ * tier enforcement applies downstream unchanged.
11
+ */
12
+ export class TokenProvider {
13
+ config;
14
+ cached = null;
15
+ inFlight = null;
16
+ constructor(config) {
17
+ this.config = config;
18
+ }
19
+ /** Drop the cached token so the next getToken() re-mints. */
20
+ invalidate() {
21
+ this.cached = null;
22
+ }
23
+ async getToken() {
24
+ if (this.cached && Date.now() < this.cached.expiresAt) {
25
+ return this.cached.accessToken;
26
+ }
27
+ // Collapse concurrent refreshes into one token request.
28
+ if (this.inFlight)
29
+ return this.inFlight;
30
+ this.inFlight = this.fetchToken().finally(() => {
31
+ this.inFlight = null;
32
+ });
33
+ return this.inFlight;
34
+ }
35
+ async fetchToken() {
36
+ if (!this.config.clientSecret) {
37
+ throw new Error("client_credentials mode requires a client secret.");
38
+ }
39
+ const tokenEndpoint = `${this.config.issuer}/connect/token`;
40
+ const body = new URLSearchParams({
41
+ grant_type: "client_credentials",
42
+ client_id: this.config.clientId,
43
+ client_secret: this.config.clientSecret,
44
+ scope: this.config.scopes,
45
+ });
46
+ const res = await fetch(tokenEndpoint, {
47
+ method: "POST",
48
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
49
+ body,
50
+ });
51
+ if (!res.ok) {
52
+ const detail = await res.text().catch(() => "");
53
+ throw new Error(`Token request to ${tokenEndpoint} failed (${res.status} ${res.statusText}): ${detail}`);
54
+ }
55
+ const json = (await res.json());
56
+ if (!json.access_token) {
57
+ throw new Error("Token endpoint returned no access_token");
58
+ }
59
+ const expiresInMs = (json.expires_in ?? 3600) * 1000;
60
+ this.cached = {
61
+ accessToken: json.access_token,
62
+ expiresAt: Date.now() + Math.max(0, expiresInMs - EXPIRY_SAFETY_MARGIN_MS),
63
+ };
64
+ return json.access_token;
65
+ }
66
+ }
67
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAeA,gFAAgF;AAChF,YAAY;AACZ,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAEvC;;;;;;;GAOG;AACH,MAAM,OAAO,aAAa;IAIK;IAHrB,MAAM,GAAuB,IAAI,C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mCAAmC,EAAE;YAChE,IAAI;SACL,CAAC,CAAC;QAEH,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;YACZ,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YAChD,MAAM,IAAI,KAAK,CACb,oBAAoB,aAAa,YAAY,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,UAAU,MAAM,MAAM,EAAE,CACxF,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAkB,CAAC;QACjD,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;YACvB,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;QAC7D,CAAC;QAED,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC;QACrD,IAAI,CAAC,MAAM,GAAG;YACZ,WAAW,EAAE,IAAI,CAAC,YAAY;YAC9B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,WAAW,GAAG,uBAAuB,CAAC;SAC3E,CAAC;QACF,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF"}
package/dist/config.js ADDED
@@ -0,0 +1,104 @@
1
+ import { readFileSync, existsSync } from "node:fs";
2
+ import path, { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ // Minimal .env loader (no dependency). Values already present in the real
5
+ // environment win — so an MCP client that injects env via its JSON config
6
+ // stays authoritative, and .env only fills the gaps for local `npm run dev` /
7
+ // `inspect`. Looks in the cwd and in the package root (one level up from the
8
+ // compiled file).
9
+ function loadDotEnv() {
10
+ const here = dirname(fileURLToPath(import.meta.url));
11
+ // Load ONLY from the package root (dist/../.env), NEVER process.cwd(). The MCP
12
+ // host spawns this server with cwd = the user's current project dir, so a `.env`
13
+ // there could belong to an untrusted repo and silently override
14
+ // OTTOFILES_GATEWAY_URL/ISSUER/TOKEN_CACHE — redirecting an already-cached
15
+ // reference token to an attacker host. An explicit OTTOFILES_ENV_FILE overrides.
16
+ const explicit = process.env.OTTOFILES_ENV_FILE;
17
+ const candidates = explicit ? [explicit] : [join(here, "..", ".env")];
18
+ for (const path of candidates) {
19
+ if (!existsSync(path))
20
+ continue;
21
+ for (const raw of readFileSync(path, "utf8").split("\n")) {
22
+ const line = raw.trim();
23
+ if (!line || line.startsWith("#"))
24
+ continue;
25
+ const eq = line.indexOf("=");
26
+ if (eq === -1)
27
+ continue;
28
+ const key = line.slice(0, eq).trim();
29
+ if (key in process.env)
30
+ continue;
31
+ let value = line.slice(eq + 1).trim();
32
+ if ((value.startsWith('"') && value.endsWith('"')) ||
33
+ (value.startsWith("'") && value.endsWith("'"))) {
34
+ value = value.slice(1, -1);
35
+ }
36
+ process.env[key] = value;
37
+ }
38
+ break; // first file found wins
39
+ }
40
+ }
41
+ // OttoFiles per-user external clients are provisioned with these scopes
42
+ // (mirrors CreatePortalCredential in Services.Workspace). Search only strictly
43
+ // needs lukla_search_api, but the wider set keeps the same credential usable as
44
+ // more read tools are added.
45
+ const DEFAULT_SCOPES = "lukla_search_api lukla_document_api lukla_bin_api lukla_workspace_api lukla_permission_api lukla_storage_api lukla_profile_api lukla_auditing_api";
46
+ function required(name) {
47
+ const value = process.env[name];
48
+ if (!value || value.trim() === "") {
49
+ throw new Error(`Missing required environment variable ${name}. See .env.example for the full list.`);
50
+ }
51
+ return value.trim();
52
+ }
53
+ export function loadConfig() {
54
+ loadDotEnv();
55
+ // A secret selects headless client_credentials; without one we do the
56
+ // interactive browser login (Path A). OTTOFILES_AUTH_MODE can force either.
57
+ const secret = process.env.OTTOFILES_CLIENT_SECRET?.trim() || null;
58
+ const forced = process.env.OTTOFILES_AUTH_MODE?.trim();
59
+ const mode = forced === "client_credentials" || (!forced && secret)
60
+ ? "client_credentials"
61
+ : "interactive";
62
+ if (mode === "client_credentials" && !secret) {
63
+ throw new Error("OTTOFILES_AUTH_MODE=client_credentials requires OTTOFILES_CLIENT_SECRET.");
64
+ }
65
+ return {
66
+ // The OttoFiles YARP gateway (container ottofiles-ottofiles-gateway),
67
+ // e.g. http://localhost:8133 locally.
68
+ gatewayUrl: required("OTTOFILES_GATEWAY_URL").replace(/\/+$/, ""),
69
+ // IdentityServer authority (container ottofiles-identity-api),
70
+ // e.g. http://localhost:8101 locally.
71
+ issuer: required("OTTOFILES_ISSUER").replace(/\/+$/, ""),
72
+ clientId: required("OTTOFILES_CLIENT_ID"),
73
+ clientSecret: secret,
74
+ scopes: (process.env.OTTOFILES_SCOPES ?? DEFAULT_SCOPES).trim(),
75
+ mode,
76
+ redirectPort: parseRedirectPort(process.env.OTTOFILES_REDIRECT_PORT),
77
+ uploadRoots: parseUploadRoots(process.env.OTTOFILES_UPLOAD_ROOTS),
78
+ };
79
+ }
80
+ export function parseUploadRoots(raw) {
81
+ if (!raw || raw.trim() === "")
82
+ return [];
83
+ const roots = [];
84
+ for (const part of raw.split(new RegExp(`[${path.delimiter},]`))) {
85
+ const v = part.trim();
86
+ if (!v)
87
+ continue;
88
+ if (!path.isAbsolute(v)) {
89
+ throw new Error(`OTTOFILES_UPLOAD_ROOTS entries must be absolute directories (got "${v}").`);
90
+ }
91
+ roots.push(path.resolve(v));
92
+ }
93
+ return roots;
94
+ }
95
+ function parseRedirectPort(raw) {
96
+ if (raw === undefined || raw.trim() === "")
97
+ return 8765;
98
+ const n = Number(raw);
99
+ if (!Number.isInteger(n) || n < 1 || n > 65533) {
100
+ throw new Error(`OTTOFILES_REDIRECT_PORT must be an integer 1-65533 (got "${raw}"). It must also match a registered redirect URI.`);
101
+ }
102
+ return n;
103
+ }
104
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE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AC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,qEAAqE,CAAC,KAAK,CAAC,CAAC;QAC/F,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,iBAAiB,CAAC,GAAuB;IAChD,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,IAAI,CAAC;IACxD,MAAM,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IACtB,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CACb,4DAA4D,GAAG,mDAAmD,CACnH,CAAC;IACJ,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC"}
package/dist/elicit.js ADDED
@@ -0,0 +1,15 @@
1
+ let elicitor = null;
2
+ export function setElicitor(fn) {
3
+ elicitor = fn;
4
+ }
5
+ export async function askHuman(message) {
6
+ if (!elicitor)
7
+ return "unsupported";
8
+ try {
9
+ return await elicitor(message);
10
+ }
11
+ catch {
12
+ return "declined";
13
+ }
14
+ }
15
+ //# sourceMappingURL=elicit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"elicit.js","sourceRoot":"","sources":["../src/elicit.ts"],"names":[],"mappings":"AAGA,IAAI,QAAQ,GAAoB,IAAI,CAAC;AAErC,MAAM,UAAU,WAAW,CAAC,EAAmB;IAC7C,QAAQ,GAAG,EAAE,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,OAAe;IAC5C,IAAI,CAAC,QAAQ;QAAE,OAAO,aAAa,CAAC;IACpC,IAAI,CAAC;QACH,OAAO,MAAM,QAAQ,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,UAAU,CAAC;IACpB,CAAC;AACH,CAAC"}
@@ -0,0 +1,116 @@
1
+ export class GatewayError extends Error {
2
+ status;
3
+ body;
4
+ constructor(message, status, body) {
5
+ super(message);
6
+ this.status = status;
7
+ this.body = body;
8
+ this.name = "GatewayError";
9
+ }
10
+ }
11
+ /**
12
+ * Thin authed HTTP client for the OttoFiles gateway. Attaches the bearer token
13
+ * and retries exactly once on a 401 with a freshly-minted token (covers a token
14
+ * that expired or was revoked between cache and call).
15
+ */
16
+ export class GatewayClient {
17
+ config;
18
+ tokens;
19
+ // Cap concurrent in-flight requests so an LLM fanning out tool calls can't
20
+ // burst the gateway. Small pool; requests beyond it queue.
21
+ maxConcurrent = 4;
22
+ active = 0;
23
+ queue = [];
24
+ // Cap on 429 retries per request before giving up.
25
+ static MAX_429_RETRIES = 4;
26
+ // Per-request timeout so a stalled socket cannot hang past the upload session.
27
+ static REQUEST_TIMEOUT_MS = 120_000;
28
+ constructor(config, tokens) {
29
+ this.config = config;
30
+ this.tokens = tokens;
31
+ }
32
+ async postJson(path, payload) {
33
+ return this.gate(() => this.request("POST", path, payload));
34
+ }
35
+ async putJson(path, payload) {
36
+ return this.gate(() => this.request("PUT", path, payload));
37
+ }
38
+ /** PUT raw bytes (application/octet-stream), e.g. one upload chunk. */
39
+ async putBytes(path, bytes) {
40
+ return this.gate(() => this.request("PUT", path, bytes));
41
+ }
42
+ async deleteJson(path) {
43
+ return this.gate(() => this.request("DELETE", path));
44
+ }
45
+ async getJson(path) {
46
+ return this.gate(() => this.request("GET", path));
47
+ }
48
+ /** Run `fn` under the concurrency limit. */
49
+ async gate(fn) {
50
+ if (this.active >= this.maxConcurrent) {
51
+ await new Promise((resolve) => this.queue.push(resolve));
52
+ }
53
+ this.active++;
54
+ try {
55
+ return await fn();
56
+ }
57
+ finally {
58
+ this.active--;
59
+ this.queue.shift()?.();
60
+ }
61
+ }
62
+ static sleep(ms) {
63
+ return new Promise((r) => setTimeout(r, ms));
64
+ }
65
+ async request(method, path, payload, isRetry = false, retry429 = 0) {
66
+ const token = await this.tokens.getToken();
67
+ const url = `${this.config.gatewayUrl}${path}`;
68
+ const isBytes = payload instanceof Uint8Array;
69
+ const res = await fetch(url, {
70
+ signal: AbortSignal.timeout(GatewayClient.REQUEST_TIMEOUT_MS),
71
+ method,
72
+ headers: {
73
+ Authorization: `Bearer ${token}`,
74
+ Accept: "application/json",
75
+ ...(payload !== undefined
76
+ ? {
77
+ "Content-Type": isBytes
78
+ ? "application/octet-stream"
79
+ : "application/json",
80
+ }
81
+ : {}),
82
+ },
83
+ body: payload === undefined
84
+ ? undefined
85
+ : isBytes
86
+ ? payload
87
+ : JSON.stringify(payload),
88
+ });
89
+ // Respect server-side rate limiting: honour Retry-After when present, else
90
+ // exponential backoff, up to a cap. Cooperates with any gateway throttle.
91
+ if (res.status === 429 && retry429 < GatewayClient.MAX_429_RETRIES) {
92
+ const retryAfter = Number(res.headers.get("retry-after"));
93
+ // Honour Retry-After, but cap it so a hostile/misconfigured header can't
94
+ // park a request (and its concurrency slot) for an hour.
95
+ const waitMs = Number.isFinite(retryAfter) && retryAfter > 0
96
+ ? Math.min(retryAfter * 1000, 30_000)
97
+ : Math.min(1000 * 2 ** retry429, 8000);
98
+ await GatewayClient.sleep(waitMs);
99
+ return this.request(method, path, payload, isRetry, retry429 + 1);
100
+ }
101
+ if (res.status === 401 && !isRetry) {
102
+ // Drop the cached token so getToken() actually re-acquires (refresh, or
103
+ // re-mint) rather than replaying the same rejected token, then retry once.
104
+ this.tokens.invalidate();
105
+ return this.request(method, path, payload, true);
106
+ }
107
+ if (!res.ok) {
108
+ const body = await res.text().catch(() => "");
109
+ throw new GatewayError(`OttoFiles gateway ${method} ${path} failed: ${res.status} ${res.statusText}`, res.status, body);
110
+ }
111
+ // 204 or empty body
112
+ const text = await res.text();
113
+ return (text ? JSON.parse(text) : undefined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,IAAI,QAAQ,EAAE,IAAI,CAAC,CAAC;YACzC,MAAM,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAClC,OAAO,IAAI,CAAC,OAAO,CAAI,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,GAAG,CAAC,CAAC,CAAC;QACvE,CAAC;QAED,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;YACnC,wEAAwE;YACxE,2EAA2E;YAC3E,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;YACzB,OAAO,IAAI,CAAC,OAAO,CAAI,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;QACtD,CAAC;QAED,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;YACZ,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YAC9C,MAAM,IAAI,YAAY,CACpB,qBAAqB,MAAM,IAAI,IAAI,YAAY,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,UAAU,EAAE,EAC7E,GAAG,CAAC,MAAM,EACV,IAAI,CACL,CAAC;QACJ,CAAC;QAED,oBAAoB;QACpB,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;QAC9B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAM,CAAC;IACpD,CAAC"}
package/dist/guard.js ADDED
@@ -0,0 +1,69 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { z } from "zod";
3
+ // Preview tokens bind a confirm call to the preview that preceded it: the token is an
4
+ // HMAC over the tool name, the canonical effect-defining arguments, and an issue/expiry
5
+ // time. The key is minted per process and never leaves it. This stops preview-skipping and
6
+ // arg drift between preview and confirm. It is NOT a human gate: an agent that controls
7
+ // both calls can still obtain and present a token. Human gating is elicitation plus
8
+ // leaving these tools on per-call client approval.
9
+ const KEY = randomBytes(32);
10
+ // Tokens are intentionally replayable within the TTL (not single-use): a confirm whose outcome
11
+ // is ambiguous must be retryable with the same token; the writes themselves are idempotent or guarded.
12
+ const DEFAULT_TTL_SECONDS = 600;
13
+ const MIN_TTL_SECONDS = 30;
14
+ const MAX_TTL_SECONDS = 3600;
15
+ let clock = () => Date.now();
16
+ export function setClockForTests(fn) {
17
+ clock = fn ?? (() => Date.now());
18
+ }
19
+ export const previewTokenField = z
20
+ .string()
21
+ .trim()
22
+ .max(512)
23
+ .optional()
24
+ .describe("Required when confirm is true: the previewToken returned by the preview call with identical arguments. Expires after a few minutes; re-run the preview if the arguments change or it expires.");
25
+ export const TOKEN_REFUSAL = "REFUSED: re-run preview; args changed or token expired. confirm:true requires the previewToken from a preview call with identical arguments.";
26
+ function ttlMs() {
27
+ const raw = Number(process.env.OTTOFILES_PREVIEW_TTL_SECONDS);
28
+ const s = Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_TTL_SECONDS;
29
+ return Math.min(MAX_TTL_SECONDS, Math.max(MIN_TTL_SECONDS, s)) * 1000;
30
+ }
31
+ export function canonicalJson(value) {
32
+ if (value === null || typeof value !== "object")
33
+ return JSON.stringify(value) ?? "null";
34
+ if (Array.isArray(value))
35
+ return `[${value.map((v) => canonicalJson(v === undefined ? null : v)).join(",")}]`;
36
+ const obj = value;
37
+ const keys = Object.keys(obj)
38
+ .filter((k) => obj[k] !== undefined)
39
+ .sort();
40
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`).join(",")}}`;
41
+ }
42
+ function mac(tool, payload, iat, exp) {
43
+ return createHmac("sha256", KEY)
44
+ .update(canonicalJson({ tool, payload, iat, exp }))
45
+ .digest();
46
+ }
47
+ export function issuePreviewToken(tool, payload) {
48
+ const iat = clock();
49
+ const exp = iat + ttlMs();
50
+ const token = `${iat}.${exp}.${mac(tool, payload, iat, exp).toString("base64url")}`;
51
+ return { token, expiresAt: new Date(exp).toISOString() };
52
+ }
53
+ export function verifyPreviewToken(tool, payload, token) {
54
+ if (typeof token !== "string")
55
+ throw new Error(TOKEN_REFUSAL);
56
+ const m = /^(\d{1,15})\.(\d{1,15})\.([A-Za-z0-9_-]{43})$/.exec(token.trim());
57
+ if (!m)
58
+ throw new Error(TOKEN_REFUSAL);
59
+ const iat = Number(m[1]);
60
+ const exp = Number(m[2]);
61
+ const now = clock();
62
+ if (exp <= now || iat > now + 60_000 || exp - iat > MAX_TTL_SECONDS * 1000)
63
+ throw new Error(TOKEN_REFUSAL);
64
+ const given = Buffer.from(m[3], "base64url");
65
+ const want = mac(tool, payload, iat, exp);
66
+ if (given.length !== want.length || !timingSafeEqual(given, want))
67
+ throw new Error(TOKEN_REFUSAL);
68
+ }
69
+ //# sourceMappingURL=guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guard.js","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,sFAAsF;AACtF,wFAAwF;AACxF,2FAA2F;AAC3F,wFAAwF;AACxF,oFAAoF;AACpF,mDAAmD;AACnD,MAAM,GAAG,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC;AAC5B,+FAA+F;AAC/F,uGAAuG;AAEvG,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,eAAe,GAAG,IAAI,CAAC;AAE7B,IAAI,KAAK,GAAiB,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;AAE3C,MAAM,UAAU,gBAAgB,CAAC,EAAyB;IACxD,KAAK,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC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