farseer-cli 1.12.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -10
- package/dist/commands/login.js +60 -26
- package/dist/commands/login.js.map +2 -2
- package/dist/commands/logout.js +37 -12
- package/dist/commands/logout.js.map +3 -3
- package/dist/commands/run.js +10 -27
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/whoami.js +10 -14
- package/dist/commands/whoami.js.map +2 -2
- package/dist/mcp/tools/authTools.js +5 -2
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +5 -18
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +16 -6
- package/dist/mcp/utils/helpers.js.map +3 -3
- package/dist/mcp/utils/session.js +14 -9
- package/dist/mcp/utils/session.js.map +2 -2
- package/dist/services/authErrors.js +2 -2
- package/dist/services/authErrors.js.map +2 -2
- package/dist/services/configService.js +45 -9
- package/dist/services/configService.js.map +2 -2
- package/dist/services/credentials.js +10 -7
- package/dist/services/credentials.js.map +2 -2
- package/dist/services/farseerService.js +84 -36
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/preflight.js +3 -2
- package/dist/services/preflight.js.map +2 -2
- package/dist/services/realms.js +67 -0
- package/dist/services/realms.js.map +7 -0
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/authTools.ts"],
|
|
4
|
-
"sourcesContent": ["/** Authentication and tenant binding. See tenantPin.ts for the binding rules. */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { getTenantOrg } from '../../services/configService';\nimport { openTenantSession } from '../../services/preflight';\nimport {\n getAuthStatus,\n successResponse,\n errorResponse,\n describeSessionFailure,\n describeSessionWarning,\n} from '../utils/helpers';\nimport { getSessionWarning, rememberSession } from '../utils/session';\nimport { selectTenant, getTenantPin, isLaunchPinned } from '../utils/tenantPin';\n\n// Defined outside registration to avoid deep zod type instantiation.\nconst selectTenantSchema = {\n tenant: z.string().describe('Tenant to bind this session to (e.g. \"salvus-prodaja\"), from the user\\'s request.'),\n organisation: z\n .string()\n .optional()\n .describe('Organisation subdomain. Defaults to the saved mapping for the tenant, else the tenant name.'),\n};\n\nexport function registerAuthTools(server: McpServer): void {\n // farseer_whoami - Auth status + the tenant this session is bound to\n server.tool(\n 'farseer_whoami',\n `Check Farseer authentication status and the tenant this session is bound to.\n\nReturns:\n- Whether a JWT (browser login) is valid and when it expires\n- The tenant this session operates on, and whether it is locked\n- Tenants with API keys configured\n\nIf not authenticated, run \"farseer login
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAkB;AAClB,2BAA6B;AAC7B,uBAAkC;AAClC,qBAMO;AACP,qBAAmD;AACnD,uBAA2D;AAG3D,MAAM,qBAAqB;AAAA,EACvB,QAAQ,aAAE,OAAO,EAAE,SAAS,kFAAmF;AAAA,EAC/G,cAAc,aACT,OAAO,EACP,SAAS,EACT,SAAS,6FAA6F;AAC/G;AAEO,SAAS,kBAAkB,QAAyB;AAEvD,SAAO;AAAA,IACH;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["/** Authentication and tenant binding. See tenantPin.ts for the binding rules. */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { getTenantOrg } from '../../services/configService';\nimport { openTenantSession } from '../../services/preflight';\nimport {\n getAuthStatus,\n successResponse,\n errorResponse,\n describeSessionFailure,\n describeSessionWarning,\n} from '../utils/helpers';\nimport { getSessionWarning, rememberSession } from '../utils/session';\nimport { selectTenant, getTenantPin, isLaunchPinned } from '../utils/tenantPin';\n\n// Defined outside registration to avoid deep zod type instantiation.\nconst selectTenantSchema = {\n tenant: z.string().describe('Tenant to bind this session to (e.g. \"salvus-prodaja\"), from the user\\'s request.'),\n organisation: z\n .string()\n .optional()\n .describe('Organisation subdomain. Defaults to the saved mapping for the tenant, else the tenant name.'),\n};\n\nexport function registerAuthTools(server: McpServer): void {\n // farseer_whoami - Auth status + the tenant this session is bound to\n server.tool(\n 'farseer_whoami',\n `Check Farseer authentication status and the tenant this session is bound to.\n\nReturns:\n- Whether a JWT (browser login) is valid for this tenant's Keycloak realm, and when it expires\n- Every browser login, one per realm\n- The tenant this session operates on, and whether it is locked\n- Tenants with API keys configured\n\nIf not authenticated, run \"farseer login --org <organisation>\" in a terminal.`,\n {},\n async () => {\n const status = getAuthStatus();\n const pin = status.tenant;\n const message = !pin\n ? 'No tenant selected yet. Tell me which tenant/client to work on and I will call farseer_select_tenant to connect (once per session).'\n : status.launchPinned\n ? `This session is locked to tenant \"${pin.tenant}\" (org: ${pin.organisation}), fixed at launch.`\n : `This session is working on tenant \"${pin.tenant}\" (org: ${pin.organisation}), selected and locked for the session.`;\n const warning = getSessionWarning();\n return successResponse({\n jwtValid: status.jwtValid,\n jwtExpiresAt: status.jwtExpiresAt,\n jwtRealm: status.jwtRealm,\n logins: status.logins,\n tenant: pin,\n tenantLocked: !!pin,\n configuredTenants: status.configuredTenants,\n warning: warning && describeSessionWarning(warning),\n message: warning ? `${message} ${describeSessionWarning(warning)}` : message,\n });\n },\n );\n\n // farseer_select_tenant - Bind this session to a tenant, once\n server.tool(\n 'farseer_select_tenant',\n `Bind this MCP session to a Farseer tenant. Call this once when the user says which tenant/client to work on.\n\nRules:\n- Works only if the server was launched without --tenant. If it was launched with --tenant, it is already locked and this returns an error.\n- Can be called only ONCE. After the first selection the tenant is locked for the session and cannot be changed. To work on a different tenant, start a new session.\n- The tenant must be reachable (you must be logged in). If it can't be connected \u2014 wrong name or not logged in \u2014 selection fails WITHOUT locking, so you can correct it and call again.\n\nUse this before any other farseer tool when no tenant is set yet (farseer_whoami tells you).`,\n selectTenantSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { tenant: string; organisation?: string }) => {\n const { tenant, organisation } = params;\n\n // A locked session can't change tenant. Reject before any network\n // call, and don't verify a tenant we won't bind to.\n if (isLaunchPinned()) {\n return errorResponse(\n `This server is pinned to tenant \"${getTenantPin()!.tenant}\" via --tenant; the tenant cannot be changed from here.`,\n 'VALIDATION_ERROR',\n );\n }\n const bound = getTenantPin();\n if (bound) {\n return errorResponse(\n `This session is already working on tenant \"${bound.tenant}\" and the tenant cannot be changed. Start a new session to use a different tenant.`,\n 'VALIDATION_ERROR',\n );\n }\n\n const org = organisation || getTenantOrg(tenant) || tenant;\n\n // Before locking: selection is one-shot, so this is the last moment a\n // wrong organisation is still correctable. Costs no extra round trip.\n const outcome = await openTenantSession(org, tenant);\n if (!outcome.ok) {\n return describeSessionFailure(outcome.failure, 'Correct it and call farseer_select_tenant again.');\n }\n\n const result = selectTenant({ organisation: org, tenant });\n if (!result.ok) {\n // Lost a race to a concurrent selection between the check above\n // and here \u2014 treat as already-bound.\n return errorResponse(\n `This session is already working on tenant \"${result.current.tenant}\" and the tenant cannot be changed. Start a new session to use a different tenant.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // The pair is proven and can no longer change, so the first tool call\n // has nothing left to ask.\n rememberSession(result.checkout, outcome.auth, outcome.warning);\n\n const selected = `Selected tenant \"${result.checkout.tenant}\" (org: ${result.checkout.organisation}). This session is now locked to it for its lifetime.`;\n return successResponse({\n tenant: result.checkout,\n warning: outcome.warning && describeSessionWarning(outcome.warning),\n message: outcome.warning ? `${selected} ${describeSessionWarning(outcome.warning)}` : selected,\n });\n },\n );\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAAkB;AAClB,2BAA6B;AAC7B,uBAAkC;AAClC,qBAMO;AACP,qBAAmD;AACnD,uBAA2D;AAG3D,MAAM,qBAAqB;AAAA,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AAa,MAAM,KAAK;AAIpD,YAAM,UAAU,UAAM,oCAAkB,KAAK,MAAM;AACnD,UAAI,CAAC,QAAQ,IAAI;AACb,mBAAO,uCAAuB,QAAQ,SAAS,kDAAkD;AAAA,MACrG;AAEA,YAAM,aAAS,+BAAa,EAAE,cAAc,KAAK,OAAO,CAAC;AACzD,UAAI,CAAC,OAAO,IAAI;AAGZ,mBAAO;AAAA,UACH,8CAA8C,OAAO,QAAQ,MAAM;AAAA,UACnE;AAAA,QACJ;AAAA,MACJ;AAIA,0CAAgB,OAAO,UAAU,QAAQ,MAAM,QAAQ,OAAO;AAE9D,YAAM,WAAW,oBAAoB,OAAO,SAAS,MAAM,WAAW,OAAO,SAAS,YAAY;AAClG,iBAAO,gCAAgB;AAAA,QACnB,QAAQ,OAAO;AAAA,QACf,SAAS,QAAQ,eAAW,uCAAuB,QAAQ,OAAO;AAAA,QAClE,SAAS,QAAQ,UAAU,GAAG,QAAQ,QAAI,uCAAuB,QAAQ,OAAO,CAAC,KAAK;AAAA,MAC1F,CAAC;AAAA,IACL;AAAA,EACJ;AACJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -38,6 +38,7 @@ var path = __toESM(require("path"));
|
|
|
38
38
|
var import_session = require("../utils/session");
|
|
39
39
|
var import_configService = require("../../services/configService");
|
|
40
40
|
var import_farseerService = require("../../services/farseerService");
|
|
41
|
+
var import_realms = require("../../services/realms");
|
|
41
42
|
var import_helpers = require("../../utils/helpers");
|
|
42
43
|
var import_packageManager = require("../../utils/packageManager");
|
|
43
44
|
var import_helpers2 = require("../utils/helpers");
|
|
@@ -67,27 +68,13 @@ async function getRunCredentials(organisation, tenant) {
|
|
|
67
68
|
basePath: credential.basePath
|
|
68
69
|
};
|
|
69
70
|
}
|
|
70
|
-
const
|
|
71
|
-
if (!
|
|
71
|
+
const accessToken = await (0, import_farseerService.getFreshAccessToken)(await (0, import_realms.realmForOrganisation)(organisation));
|
|
72
|
+
if (!accessToken) {
|
|
72
73
|
return null;
|
|
73
74
|
}
|
|
74
|
-
if (!(0, import_configService.isUserAuthValid)()) {
|
|
75
|
-
const refreshed = await (0, import_farseerService.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
|
|
76
|
-
if (!refreshed) {
|
|
77
|
-
return null;
|
|
78
|
-
}
|
|
79
|
-
(0, import_configService.setUserAuth)({
|
|
80
|
-
accessToken: refreshed.accessToken,
|
|
81
|
-
refreshToken: refreshed.refreshToken,
|
|
82
|
-
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
83
|
-
realm: auth.realm
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
const updatedAuth = (0, import_configService.getUserAuth)();
|
|
87
|
-
if (!updatedAuth) return null;
|
|
88
75
|
return {
|
|
89
76
|
tenantId: tenant,
|
|
90
|
-
accessToken
|
|
77
|
+
accessToken,
|
|
91
78
|
basePath: (0, import_configService.generateBasePath)(organisation)
|
|
92
79
|
};
|
|
93
80
|
}
|
|
@@ -148,7 +135,7 @@ Arguments not overridden use their default values from app config.`,
|
|
|
148
135
|
}
|
|
149
136
|
const credentials = await getRunCredentials(organisation, tenant);
|
|
150
137
|
if (!credentials) {
|
|
151
|
-
return (0, import_helpers2.authRequiredResponse)(tenant);
|
|
138
|
+
return (0, import_helpers2.authRequiredResponse)(tenant, organisation);
|
|
152
139
|
}
|
|
153
140
|
const tenantDir = (0, import_helpers.getTenantDir)(tenant);
|
|
154
141
|
const srcDir = (0, import_helpers.getTenantSrcDir)(tenant);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/runTools.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * App Execution Tools\n *\n * Tools for running Farseer apps locally.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { requireSession } from '../utils/session';\nimport {\n getCredential,\n getUserAuth,\n isUserAuthValid,\n setUserAuth,\n generateBasePath,\n} from '../../services/configService';\nimport { refreshAccessToken } from '../../services/farseerService';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir } from '../../utils/helpers';\nimport { ensurePackageJson, parsePackageSpec } from '../../utils/packageManager';\nimport {\n getSessionTenant,\n successResponse,\n errorResponse,\n authRequiredResponse,\n tenantRequiredResponse,\n resolveAppForMcp,\n} from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n/**\n * Find a script file recursively in a directory.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) return null;\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n if (item.isFile() && item.name === scriptName) return itemRelPath;\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n return null;\n };\n return search(baseDir);\n}\n\ninterface RunCredentials {\n tenantId: string;\n apiKey?: string;\n accessToken?: string;\n basePath: string;\n}\n\nasync function getRunCredentials(organisation: string, tenant: string): Promise<RunCredentials | null> {\n // First try API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // Try user auth (browser login)\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n\n // Check if token needs refresh\n if (!isUserAuthValid()) {\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\n // Save refreshed token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n }\n\n const updatedAuth = getUserAuth();\n if (!updatedAuth) return null;\n\n return {\n tenantId: tenant,\n accessToken: updatedAuth.accessToken,\n basePath: generateBasePath(organisation),\n };\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst runAppSchema = {\n appName: z.string().optional().describe('Name of the app to run. Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n argumentOverrides: z\n .record(z.string(), z.string())\n .optional()\n .describe('Override argument values (Name: Value pairs)'),\n};\n\nexport function registerRunTools(server: McpServer): void {\n // farseer_run_app - Run an app locally\n server.tool(\n 'farseer_run_app',\n `Run a Farseer app locally.\n\nThis executes the app's entrypoint script using npx tsx with credentials automatically injected.\nThe script's FarseerClient() constructor picks up the injected env vars - no hardcoded credentials needed.\n\nHow it works:\n1. Looks up app configuration to find the entrypoint script\n2. Injects credentials as environment variables:\n - TENANT_ID: The tenant identifier\n - FARSEER_URL: Base API URL (e.g., https://myorg.farseer.io/api/v3)\n - FARSEER_API_KEY or FARSEER_TOKEN: Authentication credentials from login\n3. Passes app arguments via command line in the order defined by app config\n4. Executes the script using npx tsx in the tenant directory\n\nRequirements:\n- Scripts must be pulled locally first (farseer_pull)\n- Dependencies must be installed (run \"farseer install <tenant>\" in terminal)\n- All CLI commands must be run from the repository root (the directory containing farseer-apps/)\n\nArguments can be overridden using the argumentOverrides parameter.\nArguments not overridden use their default values from app config.`,\n runAppSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { appName?: string; appId?: string; argumentOverrides?: Record<string, string> }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client } = gate.session;\n\n try {\n // Get app details\n const resolution = await resolveAppForMcp(client, {\n appName: params.appName,\n id: params.appId,\n });\n if ('error' in resolution) {\n return resolution.error;\n }\n const app = resolution.app;\n\n const runScripts = app.scriptFiles ?? [];\n if (!app.mainScriptFileId || runScripts.length === 0) {\n return errorResponse(\n `App \"${app.name}\" has no scripts configured. Configure it with farseer_configure_app.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Find entrypoint script\n const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);\n if (!mainScript) {\n return errorResponse(`Entrypoint script not found for app \"${app.name}\"`, 'NOT_FOUND');\n }\n\n // Get run credentials\n const credentials = await getRunCredentials(organisation, tenant);\n if (!credentials) {\n return authRequiredResponse(tenant);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Normalize script name - strip Scripts/ prefix if present\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Find script: try Scripts/ first, then search recursively in files/\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try full relative path under files/ first (e.g. Scripts/MyApp/index.ts \u2192 files/Scripts/MyApp/index.ts)\n const fullRelPath = path.resolve(filesDir, mainScript.name);\n if (fs.existsSync(fullRelPath)) {\n scriptPath = fullRelPath;\n relativeScriptPath = `files/${mainScript.name}`;\n } else {\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n }\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n return errorResponse(\n `Script not found locally: ${scriptName}. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n return errorResponse(\n `Dependencies not installed. Run \"farseer install ${tenant}\" in terminal first.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Build arguments\n const appArgs: Record<string, string> = {};\n\n // Start with defaults. defaultValue is optional on the API\n // type; treat missing as '' so we always hand a string to\n // the runner.\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue ?? '';\n }\n\n // Apply overrides\n if (params.argumentOverrides) {\n for (const [name, value] of Object.entries(params.argumentOverrides)) {\n appArgs[name] = value;\n }\n }\n\n // Build environment\n const envVars: Record<string, string> = {\n ...(process.env as Record<string, string>),\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_TOKEN = credentials.accessToken;\n }\n\n // Build command line arguments (in order)\n const cmdArgs: string[] = [];\n for (const arg of app.expectedArguments) {\n cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue ?? '');\n }\n\n // Run the script\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npx', ['tsx', relativeScriptPath, ...cmdArgs], {\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n resolve(\n successResponse({\n tenant,\n app: app.name,\n script: mainScript.name,\n arguments: appArgs,\n exitCode: code ?? 0,\n stdout: stdout.slice(0, 10000), // Limit output size\n stderr: stderr.slice(0, 5000),\n truncated: stdout.length > 10000 || stderr.length > 5000,\n }),\n );\n });\n\n child.on('error', (err) => {\n resolve(\n errorResponse(\n `Failed to run script: ${err.message}. Make sure tsx is installed: npm install -g tsx`,\n 'UNKNOWN',\n ),\n );\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('Script execution timed out after 5 minutes', 'UNKNOWN'));\n },\n 5 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Run app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_install - Install dependencies for a tenant\n server.tool(\n 'farseer_install',\n `Install npm dependencies for a Farseer tenant.\n\nEnsures the tenant directory has a package.json with farseer-client, then runs npm install.\nIf package.json doesn't exist, it is auto-created with farseer-client as a dependency.\n\nYou can also add extra npm packages (e.g., axios, lodash) that a script needs.\nThese are added to package.json and installed in one step.\n\nTypical workflow:\n1. farseer_pull \u2192 farseer_install \u2192 farseer_run_app\n\nAll commands must run from the repository root (the directory containing farseer-apps/).`,\n {\n packages: z\n .array(z.string())\n .optional()\n .describe('Additional npm packages to install (e.g., [\"axios\", \"lodash@4\"])'),\n },\n async (params: { packages?: string[] }) => {\n // Not behind requireSession: this never reaches the tenant, so there\n // is nothing to validate. `farseer install` is excluded for the same reason.\n const resolved = getSessionTenant();\n if (!resolved) return tenantRequiredResponse();\n const { tenant } = resolved;\n\n const tenantDir = getTenantDir(tenant);\n\n if (!fs.existsSync(tenantDir)) {\n return errorResponse(\n `Tenant folder not found: farseer-apps/${tenant}/. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n try {\n // Auto-create or update package.json using shared utility\n const addedPackages = [...ensurePackageJson(tenantDir, tenant)];\n\n // Add extra packages if requested\n if (params.packages && params.packages.length > 0) {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n pkg.dependencies = pkg.dependencies || {};\n\n for (const pkgSpec of params.packages) {\n const { name, version } = parsePackageSpec(pkgSpec);\n if (!pkg.dependencies[name]) {\n pkg.dependencies[name] = version;\n addedPackages.push(pkgSpec);\n }\n }\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\\n');\n }\n\n // Run npm install\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npm', ['install'], {\n cwd: tenantDir,\n shell: true,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n if (code === 0) {\n resolve(\n successResponse({\n tenant,\n tenantDir: `farseer-apps/${tenant}/`,\n addedPackages,\n exitCode: 0,\n message: `Dependencies installed successfully${addedPackages.length ? ` (${addedPackages.join(', ')})` : ''}`,\n }),\n );\n } else {\n resolve(\n errorResponse(\n `npm install failed (exit code ${code}):\\n${stderr.slice(0, 3000)}`,\n 'UNKNOWN',\n ),\n );\n }\n });\n\n child.on('error', (err) => {\n resolve(errorResponse(`Failed to run npm install: ${err.message}`, 'UNKNOWN'));\n });\n\n // Timeout after 2 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('npm install timed out after 2 minutes', 'UNKNOWN'));\n },\n 2 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Install failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,2BAAsB;AACtB,SAAoB;AACpB,WAAsB;AACtB,qBAA+B;AAC/B,
|
|
4
|
+
"sourcesContent": ["/**\n * App Execution Tools\n *\n * Tools for running Farseer apps locally.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { requireSession } from '../utils/session';\nimport { getCredential, generateBasePath } from '../../services/configService';\nimport { getFreshAccessToken } from '../../services/farseerService';\nimport { realmForOrganisation } from '../../services/realms';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir } from '../../utils/helpers';\nimport { ensurePackageJson, parsePackageSpec } from '../../utils/packageManager';\nimport {\n getSessionTenant,\n successResponse,\n errorResponse,\n authRequiredResponse,\n tenantRequiredResponse,\n resolveAppForMcp,\n} from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n/**\n * Find a script file recursively in a directory.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) return null;\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n if (item.isFile() && item.name === scriptName) return itemRelPath;\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n return null;\n };\n return search(baseDir);\n}\n\ninterface RunCredentials {\n tenantId: string;\n apiKey?: string;\n accessToken?: string;\n basePath: string;\n}\n\nasync function getRunCredentials(organisation: string, tenant: string): Promise<RunCredentials | null> {\n // First try API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // Try user auth (browser login) for the organisation's realm\n const accessToken = await getFreshAccessToken(await realmForOrganisation(organisation));\n if (!accessToken) {\n return null;\n }\n\n return {\n tenantId: tenant,\n accessToken,\n basePath: generateBasePath(organisation),\n };\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst runAppSchema = {\n appName: z.string().optional().describe('Name of the app to run. Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n argumentOverrides: z\n .record(z.string(), z.string())\n .optional()\n .describe('Override argument values (Name: Value pairs)'),\n};\n\nexport function registerRunTools(server: McpServer): void {\n // farseer_run_app - Run an app locally\n server.tool(\n 'farseer_run_app',\n `Run a Farseer app locally.\n\nThis executes the app's entrypoint script using npx tsx with credentials automatically injected.\nThe script's FarseerClient() constructor picks up the injected env vars - no hardcoded credentials needed.\n\nHow it works:\n1. Looks up app configuration to find the entrypoint script\n2. Injects credentials as environment variables:\n - TENANT_ID: The tenant identifier\n - FARSEER_URL: Base API URL (e.g., https://myorg.farseer.io/api/v3)\n - FARSEER_API_KEY or FARSEER_TOKEN: Authentication credentials from login\n3. Passes app arguments via command line in the order defined by app config\n4. Executes the script using npx tsx in the tenant directory\n\nRequirements:\n- Scripts must be pulled locally first (farseer_pull)\n- Dependencies must be installed (run \"farseer install <tenant>\" in terminal)\n- All CLI commands must be run from the repository root (the directory containing farseer-apps/)\n\nArguments can be overridden using the argumentOverrides parameter.\nArguments not overridden use their default values from app config.`,\n runAppSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { appName?: string; appId?: string; argumentOverrides?: Record<string, string> }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client } = gate.session;\n\n try {\n // Get app details\n const resolution = await resolveAppForMcp(client, {\n appName: params.appName,\n id: params.appId,\n });\n if ('error' in resolution) {\n return resolution.error;\n }\n const app = resolution.app;\n\n const runScripts = app.scriptFiles ?? [];\n if (!app.mainScriptFileId || runScripts.length === 0) {\n return errorResponse(\n `App \"${app.name}\" has no scripts configured. Configure it with farseer_configure_app.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Find entrypoint script\n const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);\n if (!mainScript) {\n return errorResponse(`Entrypoint script not found for app \"${app.name}\"`, 'NOT_FOUND');\n }\n\n // Get run credentials\n const credentials = await getRunCredentials(organisation, tenant);\n if (!credentials) {\n return authRequiredResponse(tenant, organisation);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Normalize script name - strip Scripts/ prefix if present\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Find script: try Scripts/ first, then search recursively in files/\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try full relative path under files/ first (e.g. Scripts/MyApp/index.ts \u2192 files/Scripts/MyApp/index.ts)\n const fullRelPath = path.resolve(filesDir, mainScript.name);\n if (fs.existsSync(fullRelPath)) {\n scriptPath = fullRelPath;\n relativeScriptPath = `files/${mainScript.name}`;\n } else {\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n }\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n return errorResponse(\n `Script not found locally: ${scriptName}. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n return errorResponse(\n `Dependencies not installed. Run \"farseer install ${tenant}\" in terminal first.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Build arguments\n const appArgs: Record<string, string> = {};\n\n // Start with defaults. defaultValue is optional on the API\n // type; treat missing as '' so we always hand a string to\n // the runner.\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue ?? '';\n }\n\n // Apply overrides\n if (params.argumentOverrides) {\n for (const [name, value] of Object.entries(params.argumentOverrides)) {\n appArgs[name] = value;\n }\n }\n\n // Build environment\n const envVars: Record<string, string> = {\n ...(process.env as Record<string, string>),\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_TOKEN = credentials.accessToken;\n }\n\n // Build command line arguments (in order)\n const cmdArgs: string[] = [];\n for (const arg of app.expectedArguments) {\n cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue ?? '');\n }\n\n // Run the script\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npx', ['tsx', relativeScriptPath, ...cmdArgs], {\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n resolve(\n successResponse({\n tenant,\n app: app.name,\n script: mainScript.name,\n arguments: appArgs,\n exitCode: code ?? 0,\n stdout: stdout.slice(0, 10000), // Limit output size\n stderr: stderr.slice(0, 5000),\n truncated: stdout.length > 10000 || stderr.length > 5000,\n }),\n );\n });\n\n child.on('error', (err) => {\n resolve(\n errorResponse(\n `Failed to run script: ${err.message}. Make sure tsx is installed: npm install -g tsx`,\n 'UNKNOWN',\n ),\n );\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('Script execution timed out after 5 minutes', 'UNKNOWN'));\n },\n 5 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Run app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_install - Install dependencies for a tenant\n server.tool(\n 'farseer_install',\n `Install npm dependencies for a Farseer tenant.\n\nEnsures the tenant directory has a package.json with farseer-client, then runs npm install.\nIf package.json doesn't exist, it is auto-created with farseer-client as a dependency.\n\nYou can also add extra npm packages (e.g., axios, lodash) that a script needs.\nThese are added to package.json and installed in one step.\n\nTypical workflow:\n1. farseer_pull \u2192 farseer_install \u2192 farseer_run_app\n\nAll commands must run from the repository root (the directory containing farseer-apps/).`,\n {\n packages: z\n .array(z.string())\n .optional()\n .describe('Additional npm packages to install (e.g., [\"axios\", \"lodash@4\"])'),\n },\n async (params: { packages?: string[] }) => {\n // Not behind requireSession: this never reaches the tenant, so there\n // is nothing to validate. `farseer install` is excluded for the same reason.\n const resolved = getSessionTenant();\n if (!resolved) return tenantRequiredResponse();\n const { tenant } = resolved;\n\n const tenantDir = getTenantDir(tenant);\n\n if (!fs.existsSync(tenantDir)) {\n return errorResponse(\n `Tenant folder not found: farseer-apps/${tenant}/. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n try {\n // Auto-create or update package.json using shared utility\n const addedPackages = [...ensurePackageJson(tenantDir, tenant)];\n\n // Add extra packages if requested\n if (params.packages && params.packages.length > 0) {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n pkg.dependencies = pkg.dependencies || {};\n\n for (const pkgSpec of params.packages) {\n const { name, version } = parsePackageSpec(pkgSpec);\n if (!pkg.dependencies[name]) {\n pkg.dependencies[name] = version;\n addedPackages.push(pkgSpec);\n }\n }\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\\n');\n }\n\n // Run npm install\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npm', ['install'], {\n cwd: tenantDir,\n shell: true,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n if (code === 0) {\n resolve(\n successResponse({\n tenant,\n tenantDir: `farseer-apps/${tenant}/`,\n addedPackages,\n exitCode: 0,\n message: `Dependencies installed successfully${addedPackages.length ? ` (${addedPackages.join(', ')})` : ''}`,\n }),\n );\n } else {\n resolve(\n errorResponse(\n `npm install failed (exit code ${code}):\\n${stderr.slice(0, 3000)}`,\n 'UNKNOWN',\n ),\n );\n }\n });\n\n child.on('error', (err) => {\n resolve(errorResponse(`Failed to run npm install: ${err.message}`, 'UNKNOWN'));\n });\n\n // Timeout after 2 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('npm install timed out after 2 minutes', 'UNKNOWN'));\n },\n 2 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Install failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,2BAAsB;AACtB,SAAoB;AACpB,WAAsB;AACtB,qBAA+B;AAC/B,2BAAgD;AAChD,4BAAoC;AACpC,oBAAqC;AACrC,qBAAiE;AACjE,4BAAoD;AACpD,IAAAA,kBAOO;AACP,4BAAkC;AAKlC,SAAS,sBAAsB,SAAiB,YAAmC;AAC/E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AAU,KAAK,SAAS;AAAA,UAC5B,CAAC;AAED,gBAAM,QAAQ,GAAG,QAAQ,CAAC,SAAiB;AACvC,sBAAU,KAAK,SAAS;AAAA,UAC5B,CAAC;AAED,gBAAM,GAAG,SAAS,CAAC,SAAS;AACxB,gBAAI,SAAS,GAAG;AACZ;AAAA,oBACI,iCAAgB;AAAA,kBACZ;AAAA,kBACA,WAAW,gBAAgB,MAAM;AAAA,kBACjC;AAAA,kBACA,UAAU;AAAA,kBACV,SAAS,sCAAsC,cAAc,SAAS,KAAK,cAAc,KAAK,IAAI,CAAC,MAAM,EAAE;AAAA,gBAC/G,CAAC;AAAA,cACL;AAAA,YACJ,OAAO;AACH;AAAA,oBACI;AAAA,kBACI,iCAAiC,IAAI;AAAA,EAAO,OAAO,MAAM,GAAG,GAAI,CAAC;AAAA,kBACjE;AAAA,gBACJ;AAAA,cACJ;AAAA,YACJ;AAAA,UACJ,CAAC;AAED,gBAAM,GAAG,SAAS,CAAC,QAAQ;AACvB,wBAAQ,+BAAc,8BAA8B,IAAI,OAAO,IAAI,SAAS,CAAC;AAAA,UACjF,CAAC;AAGD;AAAA,YACI,MAAM;AACF,oBAAM,KAAK;AACX,0BAAQ,+BAAc,yCAAyC,SAAS,CAAC;AAAA,YAC7E;AAAA,YACA,IAAI,KAAK;AAAA,UACb;AAAA,QACJ,CAAC;AAAA,MACL,SAAS,OAAO;AACZ,mBAAO,+BAAc,mBAAmB,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MAC7F;AAAA,IACJ;AAAA,EACJ;AACJ;",
|
|
6
6
|
"names": ["import_helpers"]
|
|
7
7
|
}
|
|
@@ -42,6 +42,7 @@ __export(helpers_exports, {
|
|
|
42
42
|
});
|
|
43
43
|
module.exports = __toCommonJS(helpers_exports);
|
|
44
44
|
var import_configService = require("../../services/configService");
|
|
45
|
+
var import_realms = require("../../services/realms");
|
|
45
46
|
var import_tenantPin = require("./tenantPin");
|
|
46
47
|
var import_fileLogger = require("../../utils/fileLogger");
|
|
47
48
|
var import_nameResolver = require("../../utils/nameResolver");
|
|
@@ -123,8 +124,9 @@ async function resolveAppForMcp(client, selector) {
|
|
|
123
124
|
}
|
|
124
125
|
return { app };
|
|
125
126
|
}
|
|
126
|
-
function authRequiredResponse(tenant) {
|
|
127
|
-
const
|
|
127
|
+
function authRequiredResponse(tenant, organisation) {
|
|
128
|
+
const login = `farseer login${organisation ? ` --org ${organisation}` : ""}`;
|
|
129
|
+
const message = tenant ? `Authentication required for tenant "${tenant}". Run "${login}" to authenticate.` : `Authentication required. Run "${login}" to authenticate.`;
|
|
128
130
|
return errorResponse(message, "AUTH_REQUIRED");
|
|
129
131
|
}
|
|
130
132
|
function tenantRequiredResponse() {
|
|
@@ -143,12 +145,20 @@ function tenantRequiredResponse() {
|
|
|
143
145
|
);
|
|
144
146
|
}
|
|
145
147
|
function getAuthStatus() {
|
|
146
|
-
const auth = (0, import_configService.getUserAuth)();
|
|
147
148
|
const pin = (0, import_tenantPin.getTenantPin)();
|
|
148
149
|
const credentials = (0, import_configService.listCredentials)();
|
|
150
|
+
const logins = Object.entries((0, import_configService.listUserAuths)()).map(([realm2, login2]) => ({
|
|
151
|
+
realm: realm2,
|
|
152
|
+
valid: (0, import_configService.isUserAuthValid)(login2),
|
|
153
|
+
expiresAt: login2.expiresAt
|
|
154
|
+
}));
|
|
155
|
+
const realm = pin ? (0, import_realms.knownRealmForOrganisation)(pin.organisation) : void 0;
|
|
156
|
+
const login = realm ? logins.find((l) => l.realm === realm) : logins.find((l) => l.valid) ?? logins[0];
|
|
149
157
|
return {
|
|
150
|
-
jwtValid:
|
|
151
|
-
jwtExpiresAt:
|
|
158
|
+
jwtValid: !!login?.valid,
|
|
159
|
+
jwtExpiresAt: login?.expiresAt,
|
|
160
|
+
jwtRealm: login?.realm ?? realm,
|
|
161
|
+
logins,
|
|
152
162
|
tenant: pin,
|
|
153
163
|
launchPinned: (0, import_tenantPin.isLaunchPinned)(),
|
|
154
164
|
configuredTenants: Object.keys(credentials)
|
|
@@ -157,7 +167,7 @@ function getAuthStatus() {
|
|
|
157
167
|
function describeSessionFailure(failure, remedy) {
|
|
158
168
|
switch (failure.reason) {
|
|
159
169
|
case "no-credentials":
|
|
160
|
-
return authRequiredResponse(failure.tenant);
|
|
170
|
+
return authRequiredResponse(failure.tenant, failure.organisation);
|
|
161
171
|
case "org-unknown":
|
|
162
172
|
return errorResponse(`No Farseer organisation at "${failure.organisation}". ${remedy}`, "VALIDATION_ERROR");
|
|
163
173
|
case "pair-refuted": {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/utils/helpers.ts"],
|
|
4
|
-
"sourcesContent": ["/** Response shapes and wording shared by the MCP tools. */\n\nimport { getUserAuth, isUserAuthValid, listCredentials } from '../../services/configService';\nimport type { SessionFailure, SessionWarning } from '../../services/preflight';\nimport { getTenantPin, isLaunchPinned } from './tenantPin';\nimport { fileLogger } from '../../utils/fileLogger';\nimport type { FarseerService } from '../../services/farseerService';\nimport type { AppListItem, RemoteApp } from '../../services/apps';\nimport { selectByNameOrId, formatAmbiguous } from '../../utils/nameResolver';\nimport { resolveSheet, resolveDashboard, describeAmbiguity, type NamedEntity } from '../../utils/entityResolver';\nimport * as farseer from 'farseer-client';\n\n/**\n * The tenant this server is bound to, or null if nothing is bound yet. The env\n * is read once at launch (see launchPin.ts), so re-exporting FARSEER_TENANT\n * mid-session cannot retarget a running server.\n */\nexport function getSessionTenant(): { organisation: string; tenant: string } | null {\n return getTenantPin() ?? null;\n}\n\nexport function successResponse(data: Record<string, unknown>): { content: Array<{ type: 'text'; text: string }> } {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ success: true, ...data }, null, 2),\n },\n ],\n };\n}\n\nexport type McpErrorResponse = { content: Array<{ type: 'text'; text: string }>; isError: true };\n\nexport function errorResponse(\n message: string,\n errorCode?: 'AUTH_REQUIRED' | 'NOT_FOUND' | 'NETWORK_ERROR' | 'VALIDATION_ERROR' | 'UNKNOWN',\n): McpErrorResponse {\n // Log MCP tool errors to file for diagnostics\n fileLogger.error('mcp-tool', message, { errorCode: errorCode || 'UNKNOWN' });\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n success: false,\n error: message,\n errorCode: errorCode || 'UNKNOWN',\n },\n null,\n 2,\n ),\n },\n ],\n isError: true,\n };\n}\n\n/**\n * Resolve an app to its folder list item, or to an error response ready to\n * return. An explicit `appId` wins; a name that matches more than one app is a\n * validation error listing the candidates, never a guess.\n *\n * Callers take `.reference` to fetch details and `.id` to delete \u2014 the two ids\n * are different and their number spaces overlap.\n */\nexport async function resolveAppItemForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ item: AppListItem } | { error: ReturnType<typeof errorResponse> }> {\n const selection = selectByNameOrId(\n await client.listApps(),\n { name: selector.appName, id: selector.id },\n (a) => a.reference,\n );\n if (selection.kind === 'found') {\n return { item: selection.entity };\n }\n if (selection.kind === 'ambiguous') {\n // Names are not unique \u2014 refuse to guess which colliding app was meant.\n return {\n error: errorResponse(\n formatAmbiguous('apps', selector.appName ?? '', selection.matches, (a) => a.reference),\n 'VALIDATION_ERROR',\n ),\n };\n }\n if (selection.kind === 'conflict') {\n return {\n error: errorResponse(\n `App ${selection.entity.reference} is \"${selection.entity.name}\", not \"${selection.name}\". The id and the name point at different apps, so nothing was done \u2014 pass one of them.`,\n 'VALIDATION_ERROR',\n ),\n };\n }\n return {\n error: errorResponse(\n selector.id ? `App not found: id ${selector.id}` : `App \"${selector.appName}\" not found`,\n 'NOT_FOUND',\n ),\n };\n}\n\n/**\n * Resolve an app for an MCP tool to its full details. Wraps\n * `resolveAppItemForMcp` + `getApp` so the tools that need the whole\n * `RemoteApp` (get, configure, run) don't repeat the fetch.\n */\nexport async function resolveAppForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ app: RemoteApp } | { error: ReturnType<typeof errorResponse> }> {\n const resolution = await resolveAppItemForMcp(client, selector);\n if ('error' in resolution) {\n return resolution;\n }\n const app = await client.getApp(resolution.item.reference);\n if (!app) {\n return { error: errorResponse('Failed to load app details', 'NETWORK_ERROR') };\n }\n return { app };\n}\n\nexport function authRequiredResponse(tenant?: string): McpErrorResponse {\n const message = tenant\n ? `Authentication required for tenant \"${tenant}\". Run \"farseer login\" to authenticate.`\n : 'Authentication required. Run \"farseer login\" to authenticate.';\n\n return errorResponse(message, 'AUTH_REQUIRED');\n}\n\n/** No usable tenant for this call. States only how to fix the current situation. */\nexport function tenantRequiredResponse(): McpErrorResponse {\n const pin = getTenantPin();\n if (pin) {\n return errorResponse(\n `This session works only on tenant \"${pin.tenant}\". The tenant is locked for the session \u2014 to work on a different tenant, start a new session.`,\n 'VALIDATION_ERROR',\n );\n }\n // Agent-facing: the in-session fix is farseer_select_tenant, not a CLI\n // command or config edit. Configured API-key tenants are offered as a hint\n // when present (a browser-login user may reach others not listed).\n const configured = Object.keys(listCredentials());\n const hint = configured.length > 0 ? ` Configured tenants include: ${configured.join(', ')}.` : '';\n return errorResponse(\n `No tenant is selected for this session yet. Call farseer_select_tenant with the tenant to work on (the client the user named). It can be selected once, then locks for the session.${hint}`,\n 'VALIDATION_ERROR',\n );\n}\n\nexport function getAuthStatus(): {\n jwtValid: boolean;\n jwtExpiresAt?: string;\n tenant?: { organisation: string; tenant: string };\n launchPinned: boolean;\n configuredTenants: string[];\n} {\n const auth = getUserAuth();\n const pin = getTenantPin();\n const credentials = listCredentials();\n\n return {\n jwtValid: isUserAuthValid(),\n jwtExpiresAt: auth?.expiresAt,\n tenant: pin,\n launchPinned: isLaunchPinned(),\n configuredTenants: Object.keys(credentials),\n };\n}\n\n/**\n * The diagnosis is the guard's; `remedy` is the caller's, because the same\n * refusal is fixable in-session before the tenant locks and not after.\n */\nexport function describeSessionFailure(failure: SessionFailure, remedy: string): McpErrorResponse {\n switch (failure.reason) {\n case 'no-credentials':\n return authRequiredResponse(failure.tenant);\n\n case 'org-unknown':\n return errorResponse(`No Farseer organisation at \"${failure.organisation}\". ${remedy}`, 'VALIDATION_ERROR');\n\n case 'pair-refuted': {\n const known =\n failure.orgTenants.length > 0\n ? ` Tenants you can access under \"${failure.organisation}\": ${failure.orgTenants.join(', ')}.`\n : '';\n return errorResponse(\n `Tenant \"${failure.tenant}\" is not available under organisation \"${failure.organisation}\".${known} ${remedy}`,\n 'VALIDATION_ERROR',\n );\n }\n }\n}\n\n/** The CLI's warning without the \"you typed it\" framing \u2014 an agent did not type it. */\nexport function describeSessionWarning(warning: SessionWarning): string {\n return (\n `Organisation \"${warning.organisation}\" is not being used: the stored API key for \"${warning.tenant}\" ` +\n `carries its own host (${warning.host}). The tenant is the bound one; the organisation has no effect.`\n );\n}\n\n/**\n * A sheet or dashboard for an MCP tool, or an error response ready to return.\n * A name matching more than one is a validation error listing the candidates by\n * folder \u2014 several of these tools write, so guessing corrupts the other one.\n */\nexport async function resolveEntityForMcp(\n client: farseer.FarseerClient,\n kind: 'sheet' | 'dashboard',\n nameOrId: string,\n): Promise<{ entity: NamedEntity } | { error: McpErrorResponse }> {\n const sheet = kind === 'sheet';\n const selection = sheet ? await resolveSheet(client, nameOrId) : await resolveDashboard(client, nameOrId);\n\n if (selection.kind === 'found') {\n return { entity: selection.entity };\n }\n if (selection.kind === 'ambiguous') {\n const itemType = sheet ? farseer.FolderItemType.Sheet : farseer.FolderItemType.Dashboard;\n const message = await describeAmbiguity(client, `${kind}s`, nameOrId, selection.matches, itemType);\n return { error: errorResponse(message, 'VALIDATION_ERROR') };\n }\n return { error: errorResponse(`${sheet ? 'Sheet' : 'Dashboard'} \"${nameOrId}\" not found`, 'NOT_FOUND') };\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,
|
|
6
|
-
"names": []
|
|
4
|
+
"sourcesContent": ["/** Response shapes and wording shared by the MCP tools. */\n\nimport { isUserAuthValid, listCredentials, listUserAuths } from '../../services/configService';\nimport { knownRealmForOrganisation } from '../../services/realms';\nimport type { SessionFailure, SessionWarning } from '../../services/preflight';\nimport { getTenantPin, isLaunchPinned } from './tenantPin';\nimport { fileLogger } from '../../utils/fileLogger';\nimport type { FarseerService } from '../../services/farseerService';\nimport type { AppListItem, RemoteApp } from '../../services/apps';\nimport { selectByNameOrId, formatAmbiguous } from '../../utils/nameResolver';\nimport { resolveSheet, resolveDashboard, describeAmbiguity, type NamedEntity } from '../../utils/entityResolver';\nimport * as farseer from 'farseer-client';\n\n/**\n * The tenant this server is bound to, or null if nothing is bound yet. The env\n * is read once at launch (see launchPin.ts), so re-exporting FARSEER_TENANT\n * mid-session cannot retarget a running server.\n */\nexport function getSessionTenant(): { organisation: string; tenant: string } | null {\n return getTenantPin() ?? null;\n}\n\nexport function successResponse(data: Record<string, unknown>): { content: Array<{ type: 'text'; text: string }> } {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ success: true, ...data }, null, 2),\n },\n ],\n };\n}\n\nexport type McpErrorResponse = { content: Array<{ type: 'text'; text: string }>; isError: true };\n\nexport function errorResponse(\n message: string,\n errorCode?: 'AUTH_REQUIRED' | 'NOT_FOUND' | 'NETWORK_ERROR' | 'VALIDATION_ERROR' | 'UNKNOWN',\n): McpErrorResponse {\n // Log MCP tool errors to file for diagnostics\n fileLogger.error('mcp-tool', message, { errorCode: errorCode || 'UNKNOWN' });\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n success: false,\n error: message,\n errorCode: errorCode || 'UNKNOWN',\n },\n null,\n 2,\n ),\n },\n ],\n isError: true,\n };\n}\n\n/**\n * Resolve an app to its folder list item, or to an error response ready to\n * return. An explicit `appId` wins; a name that matches more than one app is a\n * validation error listing the candidates, never a guess.\n *\n * Callers take `.reference` to fetch details and `.id` to delete \u2014 the two ids\n * are different and their number spaces overlap.\n */\nexport async function resolveAppItemForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ item: AppListItem } | { error: ReturnType<typeof errorResponse> }> {\n const selection = selectByNameOrId(\n await client.listApps(),\n { name: selector.appName, id: selector.id },\n (a) => a.reference,\n );\n if (selection.kind === 'found') {\n return { item: selection.entity };\n }\n if (selection.kind === 'ambiguous') {\n // Names are not unique \u2014 refuse to guess which colliding app was meant.\n return {\n error: errorResponse(\n formatAmbiguous('apps', selector.appName ?? '', selection.matches, (a) => a.reference),\n 'VALIDATION_ERROR',\n ),\n };\n }\n if (selection.kind === 'conflict') {\n return {\n error: errorResponse(\n `App ${selection.entity.reference} is \"${selection.entity.name}\", not \"${selection.name}\". The id and the name point at different apps, so nothing was done \u2014 pass one of them.`,\n 'VALIDATION_ERROR',\n ),\n };\n }\n return {\n error: errorResponse(\n selector.id ? `App not found: id ${selector.id}` : `App \"${selector.appName}\" not found`,\n 'NOT_FOUND',\n ),\n };\n}\n\n/**\n * Resolve an app for an MCP tool to its full details. Wraps\n * `resolveAppItemForMcp` + `getApp` so the tools that need the whole\n * `RemoteApp` (get, configure, run) don't repeat the fetch.\n */\nexport async function resolveAppForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ app: RemoteApp } | { error: ReturnType<typeof errorResponse> }> {\n const resolution = await resolveAppItemForMcp(client, selector);\n if ('error' in resolution) {\n return resolution;\n }\n const app = await client.getApp(resolution.item.reference);\n if (!app) {\n return { error: errorResponse('Failed to load app details', 'NETWORK_ERROR') };\n }\n return { app };\n}\n\nexport function authRequiredResponse(tenant?: string, organisation?: string): McpErrorResponse {\n // A login is per realm, so name the org: `login --org` picks its realm.\n const login = `farseer login${organisation ? ` --org ${organisation}` : ''}`;\n const message = tenant\n ? `Authentication required for tenant \"${tenant}\". Run \"${login}\" to authenticate.`\n : `Authentication required. Run \"${login}\" to authenticate.`;\n\n return errorResponse(message, 'AUTH_REQUIRED');\n}\n\n/** No usable tenant for this call. States only how to fix the current situation. */\nexport function tenantRequiredResponse(): McpErrorResponse {\n const pin = getTenantPin();\n if (pin) {\n return errorResponse(\n `This session works only on tenant \"${pin.tenant}\". The tenant is locked for the session \u2014 to work on a different tenant, start a new session.`,\n 'VALIDATION_ERROR',\n );\n }\n // Agent-facing: the in-session fix is farseer_select_tenant, not a CLI\n // command or config edit. Configured API-key tenants are offered as a hint\n // when present (a browser-login user may reach others not listed).\n const configured = Object.keys(listCredentials());\n const hint = configured.length > 0 ? ` Configured tenants include: ${configured.join(', ')}.` : '';\n return errorResponse(\n `No tenant is selected for this session yet. Call farseer_select_tenant with the tenant to work on (the client the user named). It can be selected once, then locks for the session.${hint}`,\n 'VALIDATION_ERROR',\n );\n}\n\nexport function getAuthStatus(): {\n jwtValid: boolean;\n jwtExpiresAt?: string;\n jwtRealm?: string;\n logins: { realm: string; valid: boolean; expiresAt: string }[];\n tenant?: { organisation: string; tenant: string };\n launchPinned: boolean;\n configuredTenants: string[];\n} {\n const pin = getTenantPin();\n const credentials = listCredentials();\n const logins = Object.entries(listUserAuths()).map(([realm, login]) => ({\n realm,\n valid: isUserAuthValid(login),\n expiresAt: login.expiresAt,\n }));\n // Bound: the login that tenant needs. Unbound: any usable one.\n const realm = pin ? knownRealmForOrganisation(pin.organisation) : undefined;\n const login = realm ? logins.find((l) => l.realm === realm) : (logins.find((l) => l.valid) ?? logins[0]);\n\n return {\n jwtValid: !!login?.valid,\n jwtExpiresAt: login?.expiresAt,\n jwtRealm: login?.realm ?? realm,\n logins,\n tenant: pin,\n launchPinned: isLaunchPinned(),\n configuredTenants: Object.keys(credentials),\n };\n}\n\n/**\n * The diagnosis is the guard's; `remedy` is the caller's, because the same\n * refusal is fixable in-session before the tenant locks and not after.\n */\nexport function describeSessionFailure(failure: SessionFailure, remedy: string): McpErrorResponse {\n switch (failure.reason) {\n case 'no-credentials':\n return authRequiredResponse(failure.tenant, failure.organisation);\n\n case 'org-unknown':\n return errorResponse(`No Farseer organisation at \"${failure.organisation}\". ${remedy}`, 'VALIDATION_ERROR');\n\n case 'pair-refuted': {\n const known =\n failure.orgTenants.length > 0\n ? ` Tenants you can access under \"${failure.organisation}\": ${failure.orgTenants.join(', ')}.`\n : '';\n return errorResponse(\n `Tenant \"${failure.tenant}\" is not available under organisation \"${failure.organisation}\".${known} ${remedy}`,\n 'VALIDATION_ERROR',\n );\n }\n }\n}\n\n/** The CLI's warning without the \"you typed it\" framing \u2014 an agent did not type it. */\nexport function describeSessionWarning(warning: SessionWarning): string {\n return (\n `Organisation \"${warning.organisation}\" is not being used: the stored API key for \"${warning.tenant}\" ` +\n `carries its own host (${warning.host}). The tenant is the bound one; the organisation has no effect.`\n );\n}\n\n/**\n * A sheet or dashboard for an MCP tool, or an error response ready to return.\n * A name matching more than one is a validation error listing the candidates by\n * folder \u2014 several of these tools write, so guessing corrupts the other one.\n */\nexport async function resolveEntityForMcp(\n client: farseer.FarseerClient,\n kind: 'sheet' | 'dashboard',\n nameOrId: string,\n): Promise<{ entity: NamedEntity } | { error: McpErrorResponse }> {\n const sheet = kind === 'sheet';\n const selection = sheet ? await resolveSheet(client, nameOrId) : await resolveDashboard(client, nameOrId);\n\n if (selection.kind === 'found') {\n return { entity: selection.entity };\n }\n if (selection.kind === 'ambiguous') {\n const itemType = sheet ? farseer.FolderItemType.Sheet : farseer.FolderItemType.Dashboard;\n const message = await describeAmbiguity(client, `${kind}s`, nameOrId, selection.matches, itemType);\n return { error: errorResponse(message, 'VALIDATION_ERROR') };\n }\n return { error: errorResponse(`${sheet ? 'Sheet' : 'Dashboard'} \"${nameOrId}\" not found`, 'NOT_FOUND') };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,2BAAgE;AAChE,oBAA0C;AAE1C,uBAA6C;AAC7C,wBAA2B;AAG3B,0BAAkD;AAClD,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AAAA,EACtC;AACA,MAAI,UAAU,SAAS,aAAa;AAChC,UAAM,WAAW,QAAQ,QAAQ,eAAe,QAAQ,QAAQ,eAAe;AAC/E,UAAM,UAAU,UAAM,yCAAkB,QAAQ,GAAG,IAAI,KAAK,UAAU,UAAU,SAAS,QAAQ;AACjG,WAAO,EAAE,OAAO,cAAc,SAAS,kBAAkB,EAAE;AAAA,EAC/D;AACA,SAAO,EAAE,OAAO,cAAc,GAAG,QAAQ,UAAU,WAAW,KAAK,QAAQ,eAAe,WAAW,EAAE;AAC3G;",
|
|
6
|
+
"names": ["realm", "login"]
|
|
7
7
|
}
|
|
@@ -26,19 +26,24 @@ __export(session_exports, {
|
|
|
26
26
|
module.exports = __toCommonJS(session_exports);
|
|
27
27
|
var import_configService = require("../../services/configService");
|
|
28
28
|
var import_credentials = require("../../services/credentials");
|
|
29
|
+
var import_realms = require("../../services/realms");
|
|
29
30
|
var import_preflight = require("../../services/preflight");
|
|
30
31
|
var import_helpers = require("./helpers");
|
|
31
32
|
var import_tenantPin = require("./tenantPin");
|
|
32
33
|
let validated;
|
|
33
|
-
function credentialState(
|
|
34
|
-
const credential = (0, import_configService.getCredential)(tenant);
|
|
34
|
+
function credentialState(pin, passedOverLogin) {
|
|
35
|
+
const credential = (0, import_configService.getCredential)(pin.tenant);
|
|
35
36
|
const key = credential ? `${credential.basePath}|${credential.tenantId}|${credential.apiKey}` : "none";
|
|
36
|
-
const login = (0, import_configService.getUserAuth)();
|
|
37
|
+
const login = (0, import_configService.getUserAuth)((0, import_realms.knownRealmForOrganisation)(pin.organisation));
|
|
37
38
|
const who = !login ? "none" : passedOverLogin ? `unusable:${login.refreshToken}` : `session:${loginSession(login)}`;
|
|
38
39
|
return `${who}|${key}`;
|
|
39
40
|
}
|
|
40
|
-
function passedOver(auth) {
|
|
41
|
-
|
|
41
|
+
function passedOver(pin, auth) {
|
|
42
|
+
if (auth.kind !== "apiKey") {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
const login = (0, import_configService.getUserAuth)((0, import_realms.knownRealmForOrganisation)(pin.organisation));
|
|
46
|
+
return !!login && !(0, import_configService.isUserAuthValid)(login);
|
|
42
47
|
}
|
|
43
48
|
function loginSession(login) {
|
|
44
49
|
for (const token of [login.refreshToken, login.accessToken]) {
|
|
@@ -57,11 +62,11 @@ async function requireSession() {
|
|
|
57
62
|
if (!pin) {
|
|
58
63
|
return { ok: false, response: (0, import_helpers.tenantRequiredResponse)() };
|
|
59
64
|
}
|
|
60
|
-
if (validated?.pin === pin && validated.credentials === credentialState(pin
|
|
65
|
+
if (validated?.pin === pin && validated.credentials === credentialState(pin, validated.passedOverLogin)) {
|
|
61
66
|
const auth = await (0, import_credentials.refreshAuth)(validated.auth);
|
|
62
67
|
if (!auth) {
|
|
63
68
|
validated = void 0;
|
|
64
|
-
return { ok: false, response: (0, import_helpers.authRequiredResponse)(pin.tenant) };
|
|
69
|
+
return { ok: false, response: (0, import_helpers.authRequiredResponse)(pin.tenant, pin.organisation) };
|
|
65
70
|
}
|
|
66
71
|
return { ok: true, session: (0, import_preflight.sessionFrom)(pin.organisation, pin.tenant, auth) };
|
|
67
72
|
}
|
|
@@ -76,8 +81,8 @@ function rememberSession(pin, auth, warning) {
|
|
|
76
81
|
remember(pin, auth, warning);
|
|
77
82
|
}
|
|
78
83
|
function remember(pin, auth, warning) {
|
|
79
|
-
const passedOverLogin = passedOver(auth);
|
|
80
|
-
validated = { pin, auth, credentials: credentialState(pin
|
|
84
|
+
const passedOverLogin = passedOver(pin, auth);
|
|
85
|
+
validated = { pin, auth, credentials: credentialState(pin, passedOverLogin), passedOverLogin, warning };
|
|
81
86
|
}
|
|
82
87
|
function getSessionWarning() {
|
|
83
88
|
const pin = (0, import_tenantPin.getTenantPin)();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/utils/session.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The tenant guard for MCP tools: the checks a CLI command runs, minus the exit.\n *\n * The pin cannot change for the life of the process, so the verdict is reached\n * once per credential. What is kept is the verdict and the credential, not a\n * built client \u2014 a browser token expires long before a long-lived server does.\n */\n\nimport {\n getCredential,\n getUserAuth,\n isUserAuthValid,\n type CurrentCheckout,\n type UserAuth,\n} from '../../services/configService';\nimport { refreshAuth } from '../../services/credentials';\nimport type { ResolvedAuth } from '../../services/farseerService';\nimport { openTenantSession, sessionFrom, type SessionWarning, type TenantSession } from '../../services/preflight';\nimport { authRequiredResponse, describeSessionFailure, tenantRequiredResponse } from './helpers';\nimport type { McpErrorResponse } from './helpers';\nimport { getTenantPin } from './tenantPin';\n\nexport type SessionResult = { ok: true; session: TenantSession } | { ok: false; response: McpErrorResponse };\n\n// Safe only because each server is a stdio process with a single client, on the\n// same terms as the pin it mirrors.\nlet validated:\n | {\n pin: CurrentCheckout;\n auth: ResolvedAuth;\n credentials: string;\n passedOverLogin: boolean;\n warning?: SessionWarning;\n }\n | undefined;\n\n/**\n * What the credential choice was made from, as one comparable value.\n *\n * A browser login is identified by its Keycloak session (`sid`), which token\n * rotation keeps and a new `farseer login` replaces \u2014 so the ordinary case, a\n * token renewed about once a minute, never re-runs the guard.\n *\n * A login the guard passed over for a key is the exception. Its refresh token\n * already failed, so nothing can rotate it, and a login made to recover can land\n * in the same Keycloak session when the browser still holds one. There the\n * refresh token itself is the identity: only replacing the login changes it.\n *\n * Without both, a key that stops working is reused until the process restarts,\n * while `farseer_whoami`, which reads the config directly, reports the new login\n * as valid.\n */\nfunction credentialState(
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,2BAMO;AACP,yBAA4B;
|
|
4
|
+
"sourcesContent": ["/**\n * The tenant guard for MCP tools: the checks a CLI command runs, minus the exit.\n *\n * The pin cannot change for the life of the process, so the verdict is reached\n * once per credential. What is kept is the verdict and the credential, not a\n * built client \u2014 a browser token expires long before a long-lived server does.\n */\n\nimport {\n getCredential,\n getUserAuth,\n isUserAuthValid,\n type CurrentCheckout,\n type UserAuth,\n} from '../../services/configService';\nimport { refreshAuth } from '../../services/credentials';\nimport { knownRealmForOrganisation } from '../../services/realms';\nimport type { ResolvedAuth } from '../../services/farseerService';\nimport { openTenantSession, sessionFrom, type SessionWarning, type TenantSession } from '../../services/preflight';\nimport { authRequiredResponse, describeSessionFailure, tenantRequiredResponse } from './helpers';\nimport type { McpErrorResponse } from './helpers';\nimport { getTenantPin } from './tenantPin';\n\nexport type SessionResult = { ok: true; session: TenantSession } | { ok: false; response: McpErrorResponse };\n\n// Safe only because each server is a stdio process with a single client, on the\n// same terms as the pin it mirrors.\nlet validated:\n | {\n pin: CurrentCheckout;\n auth: ResolvedAuth;\n credentials: string;\n passedOverLogin: boolean;\n warning?: SessionWarning;\n }\n | undefined;\n\n/**\n * What the credential choice was made from, as one comparable value.\n *\n * A browser login is identified by its Keycloak session (`sid`), which token\n * rotation keeps and a new `farseer login` replaces \u2014 so the ordinary case, a\n * token renewed about once a minute, never re-runs the guard.\n *\n * A login the guard passed over for a key is the exception. Its refresh token\n * already failed, so nothing can rotate it, and a login made to recover can land\n * in the same Keycloak session when the browser still holds one. There the\n * refresh token itself is the identity: only replacing the login changes it.\n *\n * Without both, a key that stops working is reused until the process restarts,\n * while `farseer_whoami`, which reads the config directly, reports the new login\n * as valid.\n */\nfunction credentialState(pin: CurrentCheckout, passedOverLogin: boolean): string {\n const credential = getCredential(pin.tenant);\n const key = credential ? `${credential.basePath}|${credential.tenantId}|${credential.apiKey}` : 'none';\n const login = getUserAuth(knownRealmForOrganisation(pin.organisation));\n const who = !login ? 'none' : passedOverLogin ? `unusable:${login.refreshToken}` : `session:${loginSession(login)}`;\n return `${who}|${key}`;\n}\n\n/**\n * Read straight after a decision, when the guard has just tried to renew the\n * login: one that is still expired is one the refresh could not renew.\n */\nfunction passedOver(pin: CurrentCheckout, auth: ResolvedAuth): boolean {\n if (auth.kind !== 'apiKey') {\n return false;\n }\n const login = getUserAuth(knownRealmForOrganisation(pin.organisation));\n return !!login && !isUserAuthValid(login);\n}\n\nfunction loginSession(login: UserAuth): string {\n for (const token of [login.refreshToken, login.accessToken]) {\n try {\n const sid = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf-8')).sid;\n if (typeof sid === 'string' && sid) {\n return sid;\n }\n } catch {\n // Not a JWT; try the other token.\n }\n }\n // Unreadable, so the token itself: re-decides on every rotation \u2014 more often\n // than needed, never less.\n return login.refreshToken;\n}\n\n/** The gate every tool that talks to a tenant goes through. */\nexport async function requireSession(): Promise<SessionResult> {\n const pin = getTenantPin();\n if (!pin) {\n return { ok: false, response: tenantRequiredResponse() };\n }\n\n // Identity, not value: a different object means a different binding, and an\n // extra check is the safe way to be wrong. The credentials are part of the\n // key for the same reason \u2014 a verdict reached over one says nothing about\n // another. The pin survives either way; only the credential is re-decided.\n if (validated?.pin === pin && validated.credentials === credentialState(pin, validated.passedOverLogin)) {\n const auth = await refreshAuth(validated.auth);\n if (!auth) {\n // Drop the verdict rather than reuse a credential we can no longer mint.\n validated = undefined;\n return { ok: false, response: authRequiredResponse(pin.tenant, pin.organisation) };\n }\n return { ok: true, session: sessionFrom(pin.organisation, pin.tenant, auth) };\n }\n\n const outcome = await openTenantSession(pin.organisation, pin.tenant);\n if (!outcome.ok) {\n return { ok: false, response: describeSessionFailure(outcome.failure, LOCKED_REMEDY) };\n }\n\n remember(pin, outcome.auth, outcome.warning);\n return { ok: true, session: sessionFrom(outcome.organisation, outcome.tenant, outcome.auth) };\n}\n\n/** Adopt a verdict reached elsewhere \u2014 `farseer_select_tenant` validates before it binds. */\nexport function rememberSession(pin: CurrentCheckout, auth: ResolvedAuth, warning?: SessionWarning): void {\n remember(pin, auth, warning);\n}\n\nfunction remember(pin: CurrentCheckout, auth: ResolvedAuth, warning?: SessionWarning): void {\n const passedOverLogin = passedOver(pin, auth);\n validated = { pin, auth, credentials: credentialState(pin, passedOverLogin), passedOverLogin, warning };\n}\n\n/** Reported by `farseer_whoami`: true about this session, but not a failure. */\nexport function getSessionWarning(): SessionWarning | undefined {\n const pin = getTenantPin();\n return validated?.pin === pin ? validated?.warning : undefined;\n}\n\nexport function resetSessionCache(): void {\n validated = undefined;\n}\n\n// Past the lock there is no in-session fix.\nconst LOCKED_REMEDY =\n 'This session is locked to that pair for its lifetime \u2014 start a new server with the right organisation (--org, or FARSEER_ORG).';\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,2BAMO;AACP,yBAA4B;AAC5B,oBAA0C;AAE1C,uBAAwF;AACxF,qBAAqF;AAErF,uBAA6B;AAM7B,IAAI;AA0BJ,SAAS,gBAAgB,KAAsB,iBAAkC;AAC7E,QAAM,iBAAa,oCAAc,IAAI,MAAM;AAC3C,QAAM,MAAM,aAAa,GAAG,WAAW,QAAQ,IAAI,WAAW,QAAQ,IAAI,WAAW,MAAM,KAAK;AAChG,QAAM,YAAQ,sCAAY,yCAA0B,IAAI,YAAY,CAAC;AACrE,QAAM,MAAM,CAAC,QAAQ,SAAS,kBAAkB,YAAY,MAAM,YAAY,KAAK,WAAW,aAAa,KAAK,CAAC;AACjH,SAAO,GAAG,GAAG,IAAI,GAAG;AACxB;AAMA,SAAS,WAAW,KAAsB,MAA6B;AACnE,MAAI,KAAK,SAAS,UAAU;AACxB,WAAO;AAAA,EACX;AACA,QAAM,YAAQ,sCAAY,yCAA0B,IAAI,YAAY,CAAC;AACrE,SAAO,CAAC,CAAC,SAAS,KAAC,sCAAgB,KAAK;AAC5C;AAEA,SAAS,aAAa,OAAyB;AAC3C,aAAW,SAAS,CAAC,MAAM,cAAc,MAAM,WAAW,GAAG;AACzD,QAAI;AACA,YAAM,MAAM,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,WAAW,EAAE,SAAS,OAAO,CAAC,EAAE;AACxF,UAA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AU;AACzD;AAEO,SAAS,oBAA0B;AACtC,cAAY;AAChB;AAGA,MAAM,gBACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -59,12 +59,12 @@ function statusOf(value) {
|
|
|
59
59
|
const status = value?.status;
|
|
60
60
|
return typeof status === "number" ? status : void 0;
|
|
61
61
|
}
|
|
62
|
-
function showLoginPrompt(tenant) {
|
|
62
|
+
function showLoginPrompt(tenant, organisation) {
|
|
63
63
|
import_logger.logger.error("Authentication required.");
|
|
64
64
|
if (tenant) {
|
|
65
65
|
import_logger.logger.dim(`No valid credentials found for tenant "${tenant}".`);
|
|
66
66
|
}
|
|
67
|
-
import_logger.logger.info(
|
|
67
|
+
import_logger.logger.info(`Run "farseer login${organisation ? ` --org ${organisation}` : ""}" to authenticate via browser.`);
|
|
68
68
|
import_logger.logger.dim('Or use "farseer config set <tenant> --api-key <key>" for API key auth.');
|
|
69
69
|
}
|
|
70
70
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/authErrors.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Telling an authentication failure from everything else.\n *\n * The 403 is the hard one: the backend answers it both for a credential it will\n * not accept and for a tenant the organisation does not have. The second is not\n * a credentials problem \u2014 every tenant-scoped request carries X-TENANT-ID, and\n * an organisation without that tenant refuses on that alone \u2014 so \"log in again\"\n * would send the user to fix the one thing that works. Only the body tells them\n * apart, which is why this is a shared decision and not a status check at each\n * call site.\n */\n\nimport { logger } from '../utils/logger';\n\n/** The wrong-organisation 403: `{\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`. */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * Apart from isTenantNotFoundError because that sentence reaches us two ways:\n * inside an Error the SDK threw, and as the `message` of a 403 body the\n * organisation probe reads straight off the response.\n */\nexport function mentionsUnknownTenant(text: string | undefined): boolean {\n if (!text) {\n return false;\n }\n const msg = text.toLowerCase();\n return msg.includes('does not exist') && msg.includes('tenant');\n}\n\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n // Status first; the message is only a fallback, and messages now carry\n // folder paths and Remote Job ids \u2014 \"Failed to load app 1403\" is not a 403.\n const status = statusOf(error) ?? statusOf((error as { cause?: unknown } | null)?.cause);\n if (status !== undefined) {\n if (status === 401) {\n return true;\n }\n // The exclusion above reads a message and a raw Response carries none,\n // so for a bare 403 it never ran \u2014 claiming an auth failure here would\n // guess against the case this module exists to catch.\n return status === 403 && error instanceof Error;\n }\n if (error instanceof Error) {\n return mentionsAuthStatus(error.message);\n }\n return false;\n}\n\n/**\n * Only reached when nothing carried a status. The number must be presented as\n * one to count: a bare `includes('403')` read a folder named `403-reports` as\n * an auth failure.\n */\nfunction mentionsAuthStatus(message: string): boolean {\n const msg = message.toLowerCase();\n return (\n /(?:code|status|http)\\s*:?\\s*(?:401|403)\\b/.test(msg) ||\n msg.includes('unauthorized') ||\n msg.includes('forbidden')\n );\n}\n\n/** The HTTP status of an HttpError or a raw fetch Response, when there is one. */\nfunction statusOf(value: unknown): number | undefined {\n const status = (value as { status?: unknown } | null | undefined)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\nexport function showLoginPrompt(tenant?: string): void {\n logger.error('Authentication required.');\n if (tenant) {\n logger.dim(`No valid credentials found for tenant \"${tenant}\".`);\n }\n logger.info(
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,oBAAuB;AAGhB,SAAS,sBAAsB,OAAyB;AAC3D,SAAO,iBAAiB,SAAS,sBAAsB,MAAM,OAAO;AACxE;AAOO,SAAS,sBAAsB,MAAmC;AACrE,MAAI,CAAC,MAAM;AACP,WAAO;AAAA,EACX;AACA,QAAM,MAAM,KAAK,YAAY;AAC7B,SAAO,IAAI,SAAS,gBAAgB,KAAK,IAAI,SAAS,QAAQ;AAClE;AAEO,SAAS,YAAY,OAAyB;AACjD,MAAI,sBAAsB,KAAK,GAAG;AAC9B,WAAO;AAAA,EACX;AAGA,QAAM,SAAS,SAAS,KAAK,KAAK,SAAU,OAAsC,KAAK;AACvF,MAAI,WAAW,QAAW;AACtB,QAAI,WAAW,KAAK;AAChB,aAAO;AAAA,IACX;AAIA,WAAO,WAAW,OAAO,iBAAiB;AAAA,EAC9C;AACA,MAAI,iBAAiB,OAAO;AACxB,WAAO,mBAAmB,MAAM,OAAO;AAAA,EAC3C;AACA,SAAO;AACX;AAOA,SAAS,mBAAmB,SAA0B;AAClD,QAAM,MAAM,QAAQ,YAAY;AAChC,SACI,4CAA4C,KAAK,GAAG,KACpD,IAAI,SAAS,cAAc,KAC3B,IAAI,SAAS,WAAW;AAEhC;AAGA,SAAS,SAAS,OAAoC;AAClD,QAAM,SAAU,OAAmD;AACnE,SAAO,OAAO,WAAW,WAAW,SAAS;AACjD;AAEO,SAAS,gBAAgB,
|
|
4
|
+
"sourcesContent": ["/**\n * Telling an authentication failure from everything else.\n *\n * The 403 is the hard one: the backend answers it both for a credential it will\n * not accept and for a tenant the organisation does not have. The second is not\n * a credentials problem \u2014 every tenant-scoped request carries X-TENANT-ID, and\n * an organisation without that tenant refuses on that alone \u2014 so \"log in again\"\n * would send the user to fix the one thing that works. Only the body tells them\n * apart, which is why this is a shared decision and not a status check at each\n * call site.\n */\n\nimport { logger } from '../utils/logger';\n\n/** The wrong-organisation 403: `{\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`. */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * Apart from isTenantNotFoundError because that sentence reaches us two ways:\n * inside an Error the SDK threw, and as the `message` of a 403 body the\n * organisation probe reads straight off the response.\n */\nexport function mentionsUnknownTenant(text: string | undefined): boolean {\n if (!text) {\n return false;\n }\n const msg = text.toLowerCase();\n return msg.includes('does not exist') && msg.includes('tenant');\n}\n\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n // Status first; the message is only a fallback, and messages now carry\n // folder paths and Remote Job ids \u2014 \"Failed to load app 1403\" is not a 403.\n const status = statusOf(error) ?? statusOf((error as { cause?: unknown } | null)?.cause);\n if (status !== undefined) {\n if (status === 401) {\n return true;\n }\n // The exclusion above reads a message and a raw Response carries none,\n // so for a bare 403 it never ran \u2014 claiming an auth failure here would\n // guess against the case this module exists to catch.\n return status === 403 && error instanceof Error;\n }\n if (error instanceof Error) {\n return mentionsAuthStatus(error.message);\n }\n return false;\n}\n\n/**\n * Only reached when nothing carried a status. The number must be presented as\n * one to count: a bare `includes('403')` read a folder named `403-reports` as\n * an auth failure.\n */\nfunction mentionsAuthStatus(message: string): boolean {\n const msg = message.toLowerCase();\n return (\n /(?:code|status|http)\\s*:?\\s*(?:401|403)\\b/.test(msg) ||\n msg.includes('unauthorized') ||\n msg.includes('forbidden')\n );\n}\n\n/** The HTTP status of an HttpError or a raw fetch Response, when there is one. */\nfunction statusOf(value: unknown): number | undefined {\n const status = (value as { status?: unknown } | null | undefined)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\nexport function showLoginPrompt(tenant?: string, organisation?: string): void {\n logger.error('Authentication required.');\n if (tenant) {\n logger.dim(`No valid credentials found for tenant \"${tenant}\".`);\n }\n // A login is per realm, so name the org: `login --org` picks its realm.\n logger.info(`Run \"farseer login${organisation ? ` --org ${organisation}` : ''}\" to authenticate via browser.`);\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,oBAAuB;AAGhB,SAAS,sBAAsB,OAAyB;AAC3D,SAAO,iBAAiB,SAAS,sBAAsB,MAAM,OAAO;AACx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