farseer-cli 1.10.1 → 1.10.3
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 +2 -0
- package/dist/commands/cells.js +2 -4
- package/dist/commands/cells.js.map +2 -2
- package/dist/commands/dashboards.js +2 -4
- package/dist/commands/dashboards.js.map +2 -2
- package/dist/commands/dimensions.js +3 -6
- package/dist/commands/dimensions.js.map +2 -2
- package/dist/commands/formula.js +1 -2
- package/dist/commands/formula.js.map +2 -2
- package/dist/commands/sheets.js +4 -8
- package/dist/commands/sheets.js.map +2 -2
- package/dist/commands/variables.js +3 -6
- package/dist/commands/variables.js.map +2 -2
- package/dist/mcp/tools/appTools.js +27 -57
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/authTools.js +12 -9
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/tools/cellTools.js +4 -6
- package/dist/mcp/tools/cellTools.js.map +2 -2
- package/dist/mcp/tools/dashboardTools.js +34 -56
- package/dist/mcp/tools/dashboardTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +13 -37
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/folderTools.js +7 -11
- package/dist/mcp/tools/folderTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +59 -111
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +5 -11
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +31 -51
- package/dist/mcp/tools/sheetTools.js.map +2 -2
- package/dist/mcp/tools/syncTools.js +27 -57
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +22 -7
- package/dist/mcp/utils/helpers.js.map +2 -2
- package/dist/mcp/utils/session.js +97 -0
- package/dist/mcp/utils/session.js.map +7 -0
- package/dist/mcp/utils/tenantPin.js.map +2 -2
- package/dist/services/farseerApi.js +7 -5
- package/dist/services/farseerApi.js.map +2 -2
- package/dist/services/farseerFactory.js +66 -116
- package/dist/services/farseerFactory.js.map +2 -2
- package/dist/services/preflight.js +78 -24
- package/dist/services/preflight.js.map +2 -2
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/farseerFactory.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Factory for creating Farseer API client based on available authentication\n *\n * Priority:\n * 1. JWT token (from browser login) - try first\n * 2. API key (from config) - fallback if JWT fails or unavailable\n * 3. Prompt user to login - if nothing works\n */\n\nimport axios from 'axios';\nimport * as farseer from 'farseer-client';\nimport { FarseerService } from './farseerService';\nimport { FarseerApi } from './farseerApi';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { logger } from '../utils/logger';\n\n/**\n * A tenant the backend couldn't resolve at this host \u2014 it answers\n * `403 {\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`.\n * Despite the 403 this is NOT a credentials problem: it's what a wrong\n * organisation for an otherwise-valid tenant looks like, because every\n * tenant-scoped request carries X-TENANT-ID and the org's backend has no such\n * tenant. Telling the user to log in again would send them to fix the one thing\n * that isn't broken.\n */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * The backend's \"no such tenant at this host\" phrasing. Lives apart from\n * isTenantNotFoundError because the same sentence reaches us two ways: inside a\n * thrown Error from the SDK, and as the `message` field of an axios 403 body \u2014\n * where `error.message` is only ever \"Request failed with status code 403\".\n */\nfunction 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\n/**\n * Check if an error is an authentication error (401/403).\n *\n * A 403 that names an unresolvable tenant is deliberately excluded \u2014 see\n * isTenantNotFoundError. Callers that show a login prompt on true would\n * otherwise misdiagnose a wrong-org command as expired credentials.\n */\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n return msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('forbidden');\n }\n return false;\n}\n\n/**\n * Show a consistent \"please login\" message\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('Run \"farseer login\" to authenticate via browser.');\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n\nexport interface FileMetadata {\n uploadTime?: string; // ISO timestamp\n uploader?: {\n id: number;\n email: string;\n firstName: string;\n lastName: string;\n };\n size?: number;\n}\n\n/**\n * Canonical RemoteFile shape used by every layer of the CLI. Both\n * FarseerApi (JWT path) and FarseerService (API-key path) re-export this\n * type so downstream code (SyncService, MCP tools, tests) can rely on a\n * single definition. Earlier each layer declared its own copy that drifted\n * \u2014 three different shapes that disagreed on which optional fields existed,\n * which made it impossible to tell from a function signature what the\n * caller could assume was set.\n *\n * Optional fields are populated lazily:\n * - `content` \u2014 only set by callers that already fetched body bytes\n * (some legacy paths combined list + download in a single helper).\n * - `metadata` \u2014 populated by listFiles for the JWT path. The API-key\n * path doesn't return it, so consumers must handle absence.\n */\nexport interface RemoteFile {\n name: string;\n path: string;\n reference: string;\n content?: string;\n metadata?: FileMetadata;\n}\n\n// Mirrors the backend `OrganizationInfo` schema returned by GET /organization\n// (backend/app/openapi/v3/documentation/overseer/components.yaml). The org is\n// resolved from the request host (`<org>.farseer.io`); `tenants` is the\n// authoritative list of tenants that org actually owns in overseer. `checkout`\n// uses it to confirm the org+tenant pair the user typed is real \u2014 the backend\n// resolves a tenant from the X-TENANT-ID header alone and never checks it\n// against the org, so without this the org argument is an unvalidated routing\n// hint.\nexport interface OrganizationTenant {\n name: string;\n isDefault: boolean;\n}\n\nexport interface OrganizationInfo {\n id: string;\n host: string;\n version: string;\n tenants: OrganizationTenant[];\n}\n\n// Narrow set of \"script\" extensions \u2014 used by `farseer files list` and\n// `farseer list` to default to source-code style files when listing a\n// folder. NOT the default sync scope; see DEFAULT_SYNC_EXTENSIONS below.\nexport const DEFAULT_SCRIPT_EXTENSIONS = ['.ts', '.js'];\n\n// Default sync scope \u2014 the curated set of files a developer AUTHORS in an\n// editor. NARROWER than the backend's accepted extension list\n// (`cli/src/utils/fileValidation.ts:BACKEND_EXTENSION_WHITELIST`, which\n// mirrors `farseer/backend/app/openapi/v3/services/farseerFileService.ts`).\n// The earlier \"default sync = everything backend accepts\" expanded the\n// default scope to 25 entries including binary / data formats (.csv,\n// .parquet, .xlsx, .pdf, images) \u2014 large files no one edits in a code\n// editor that dominated first-pull time and made `status` noisy.\n//\n// Users opt into the rest of the backend whitelist (data / docs /\n// archives) via `--include-ext <ext>` or persistent\n// `farseer config include`. Anything still outside the backend whitelist\n// requires `--all` or `--include-folder`.\n//\n// Subset contract: every entry here must also be in\n// `BACKEND_EXTENSION_WHITELIST`, otherwise push pre-flight will reject\n// in-scope files (extension not allowed) \u2014 defeats the purpose of the\n// default scope. Asserted by `defaultSyncExtensionsParity.test.ts`.\nexport const DEFAULT_SYNC_EXTENSIONS = [\n // Code (frontend / scripts)\n '.ts',\n '.js',\n // Code (Python)\n '.py',\n // Config / data\n '.yml',\n '.yaml',\n '.json',\n // Docs\n '.md',\n];\n\nimport {\n AppListItem,\n AppUpdateChanges,\n RemoteApp,\n SourceFolderResolution,\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n} from './farseerApi';\n\n// Common interface that both FarseerService and FarseerApi implement\nexport interface IFarseerClient {\n testConnection(): Promise<boolean>;\n getOrganizationInfo(): Promise<OrganizationInfo>;\n getFilesFolder(): Promise<{ id: number; name: string; type: string } | null>;\n listFiles(folderPath?: string[]): Promise<RemoteFile[]>;\n getFileContent(reference: string): Promise<string>;\n getFileContentAsBuffer(reference: string): Promise<Buffer>;\n createFile(content: string | Buffer, fileName: string, folderPath?: string[]): Promise<void>;\n updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void>;\n deleteFile(reference: string): Promise<void>;\n getFileByPath(filePath: string): Promise<RemoteFile | null>;\n getFileMetadata(reference: string): Promise<FileMetadata | null>;\n isTextFile(filename: string): boolean;\n isBinaryFile(filename: string): boolean;\n // Apps API methods\n listApps(): Promise<AppListItem[]>;\n getApp(referenceId: string): Promise<RemoteApp | null>;\n getAppByName(name: string): Promise<RemoteApp | null>;\n createApp(name: string): Promise<RemoteApp>;\n updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp>;\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n deleteApp(remoteJobId: string): Promise<void>;\n getScriptFiles(): Promise<{ id: string; name: string }[]>;\n // Model export\n exportModel(options?: ModelExportOptions): Promise<ModelExport>;\n /**\n * Fetch a single dimension table with its members. Goes through\n * `entities/search` + `getRelations` + `getMany`, which scope the\n * fetch to one table \u2014 unlike `exportModel` with `tableGids`,\n * which currently 500s for some tables on large tenants\n * (rama-side scoping bug, tracked separately).\n */\n loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null>;\n // Token management (optional - only FarseerApi implements this)\n updateAccessToken?(newToken: string): void;\n}\n\nexport interface FarseerClientResult {\n client: IFarseerClient;\n authType: 'apiKey' | 'jwt';\n}\n\n/**\n * Return a usable browser-login access token, refreshing it first if it has\n * expired. Null when there's no browser login, or the refresh failed (caller\n * should fall back to an API key).\n */\nexport async function getFreshAccessToken(): Promise<string | null> {\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n if (isUserAuthValid()) {\n return auth.accessToken;\n }\n\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\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 logger.dim('Token refreshed');\n return refreshed.accessToken;\n}\n\nexport type TenantCheck =\n | { status: 'ok' }\n | { status: 'tenant-unknown' }\n | { status: 'no-such-org' }\n | { status: 'unauthorized' }\n | { status: 'unreachable'; message: string };\n\n/**\n * Ask an organisation, in one request, whether it has this tenant.\n *\n * `/organization` is resolved from the request host, and sending X-TENANT-ID\n * puts the request through the same tenant-resolution middleware every\n * tenant-scoped call passes through \u2014 so the answer is the real one rather than\n * an inference:\n *\n * 200 the pair resolves, and the token works\n * 403 \"Tenant with id <t> does not exist\" the org does not have this tenant\n * 404 no Farseer organisation at this host\n * 401 the token is no good\n *\n * The alternative \u2014 asking without the header and looking for the tenant in the\n * response list \u2014 cannot refute a pair, because that list holds only what the\n * CALLER can enumerate and that is a different permission: an account that gets\n * `[]` for org `kiwi` still has `X-TENANT-ID: kiwi` accepted at that same host.\n *\n * The 403 was originally read as an auth failure, which is why the header was\n * avoided at first; `isTenantNotFoundError` tells the two apart from the body,\n * so it no longer is. Any OTHER 403 stays inconclusive \u2014 an org-level\n * permission problem is not this tenant failing to exist.\n */\nexport async function checkTenantAtOrganisation(\n organisation: string,\n tenant: string,\n accessToken: string,\n): Promise<TenantCheck> {\n try {\n await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}`, 'X-TENANT-ID': tenant },\n timeout: 30000,\n });\n return { status: 'ok' };\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n return { status: 'unauthorized' };\n }\n if (error.response?.status === 404) {\n return { status: 'no-such-org' };\n }\n const body = error.response?.data;\n const detail = typeof body === 'string' ? body : (body as { message?: string } | undefined)?.message;\n if (error.response?.status === 403 && mentionsUnknownTenant(detail)) {\n return { status: 'tenant-unknown' };\n }\n }\n return { status: 'unreachable', message: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/**\n * The tenants an organisation will admit to, for the CALLER. Best-effort and\n * hint-only: used to name the alternatives when a pair has already been refuted,\n * never to decide anything. Sends no tenant header \u2014 the pair is known bad by\n * this point, and including it would just 403 again.\n */\nexport async function fetchOrganizationTenants(organisation: string, accessToken: string): Promise<string[]> {\n try {\n const response = await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n timeout: 30000,\n });\n return (response.data.tenants ?? []).map((t) => t.name);\n } catch {\n return [];\n }\n}\n\n/**\n * Get a Farseer client for the given organisation and tenant.\n * Tries JWT token first (supports apps), then falls back to API key.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClient(organisation: string, tenant: string): Promise<FarseerClientResult | null> {\n // 1. Try JWT token from browser login first (supports apps sync)\n const auth = getUserAuth();\n if (auth) {\n // Check if token needs refresh\n let accessToken = auth.accessToken;\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n logger.warning('Could not refresh token. Please login again with: farseer login');\n // Fall through to API key\n } else {\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 accessToken = refreshed.accessToken;\n logger.dim('Token refreshed');\n }\n }\n\n if (isUserAuthValid()) {\n return {\n client: new FarseerApi(accessToken, organisation, tenant),\n authType: 'jwt',\n };\n }\n }\n\n // 2. Fall back to API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n client: new FarseerService(credential),\n authType: 'apiKey',\n };\n }\n\n return null;\n}\n\n/**\n * Check what authentication methods are available\n */\nexport function getAvailableAuth(tenant: string): {\n hasApiKey: boolean;\n hasJwt: boolean;\n jwtValid: boolean;\n} {\n const credential = getCredential(tenant);\n const auth = getUserAuth();\n\n return {\n hasApiKey: !!credential,\n hasJwt: !!auth,\n jwtValid: isUserAuthValid(),\n };\n}\n\n/**\n * Get a Farseer client with automatic fallback and connection testing.\n * This is the recommended way to get a client for commands.\n *\n * Flow:\n * 1. Try JWT if available and valid\n * 2. If JWT fails or unavailable, try API key\n * 3. If nothing works, return null (caller should show login prompt)\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClientWithFallback(\n organisation: string,\n tenant: string,\n): Promise<FarseerClientResult | null> {\n const auth = getUserAuth();\n const credential = getCredential(tenant);\n\n // 1. Try JWT token first\n if (auth) {\n let accessToken = auth.accessToken;\n\n // Refresh token if needed\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\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 accessToken = refreshed.accessToken;\n logger.dim('Token refreshed');\n }\n }\n\n if (isUserAuthValid()) {\n const jwtClient = new FarseerApi(accessToken, organisation, tenant);\n\n // Test JWT connection\n try {\n const connected = await jwtClient.testConnection();\n if (connected) {\n return { client: jwtClient, authType: 'jwt' };\n }\n } catch (error) {\n // JWT failed, will try API key\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n }\n }\n\n // 2. Try API key\n if (credential) {\n const apiKeyClient = new FarseerService(credential);\n\n try {\n const connected = await apiKeyClient.testConnection();\n if (connected) {\n return { client: apiKeyClient, authType: 'apiKey' };\n }\n } catch {\n // API key also failed\n logger.dim('API key auth failed.');\n }\n }\n\n // 3. Nothing worked\n return null;\n}\n\n/**\n * Ensure the token is fresh and update the client if needed.\n * Call this before long-running operations to avoid token expiration.\n *\n * @returns true if token was refreshed, false if no refresh needed or API key auth\n */\nexport async function ensureFreshToken(client: IFarseerClient): Promise<boolean> {\n const auth = getUserAuth();\n if (!auth) {\n return false; // No JWT auth, probably using API key\n }\n\n // Check if token needs refresh (give 30 second buffer)\n const expiresAt = new Date(auth.expiresAt);\n const now = new Date();\n const bufferMs = 30 * 1000; // 30 seconds\n\n if (expiresAt.getTime() - now.getTime() > bufferMs) {\n return false; // Token is still fresh enough\n }\n\n // Refresh the token\n logger.dim('Refreshing token before operation...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n\n if (!refreshed) {\n logger.warning('Could not refresh token.');\n return false;\n }\n\n // Save the new 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 // Update the client's token if it supports it\n if (client.updateAccessToken) {\n client.updateAccessToken(refreshed.accessToken);\n logger.dim('Token refreshed');\n return true;\n }\n\n return false;\n}\n\n/**\n * Get a native farseer-client FarseerClient instance.\n * This provides access to the full farseer-client API (export, import jobs, file creation, etc.)\n * that isn't available through the simplified IFarseerClient interface.\n *\n * Tries JWT first, then API key. Handles token refresh automatically.\n *\n * TECH DEBT \u2014 two parallel client stacks. `getFarseerClientWithFallback`\n * returns an `IFarseerClient` (a curated facade over the hand-rolled axios\n * `FarseerApi` for JWT and the SDK-wrapping `FarseerService` for API keys),\n * while this returns the raw SDK client for the richer read/query surface. The\n * duality is historical (the JWT path was hand-rolled instead of using the\n * SDK), not necessary \u2014 the SDK handles JWT fine. Because of it, `preflight`\n * runs its guard with the IFarseerClient and read/query commands then build a\n * second (native) client here from the same validated pair. Collapsing these\n * into one authenticated SDK client is planned as a follow-up; until then the\n * extra construction is deliberate.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header\n */\nexport async function getNativeFarseerClient(\n organisation: string,\n tenant: string,\n): Promise<farseer.FarseerClient | null> {\n const basePath = generateBasePath(organisation);\n\n // 1. Try JWT token first\n const auth = getUserAuth();\n if (auth) {\n let accessToken = auth.accessToken;\n\n if (!isUserAuthValid()) {\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\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 accessToken = refreshed.accessToken;\n }\n }\n\n if (isUserAuthValid()) {\n return new farseer.FarseerClient({\n basePath,\n headers: {\n 'X-TENANT-ID': tenant,\n Authorization: `Bearer ${accessToken}`,\n },\n });\n }\n }\n\n // 2. Try API key\n const credential = getCredential(tenant);\n if (credential) {\n return new farseer.FarseerClient({\n basePath: credential.basePath,\n headers: {\n 'X-TENANT-ID': credential.tenantId,\n 'X-API-KEY': credential.apiKey,\n },\n });\n }\n\n return null;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;
|
|
4
|
+
"sourcesContent": ["/**\n * Deciding which credential to use, and building clients from it.\n *\n * A browser login is preferred when there is a usable one, a stored API key\n * otherwise. The decision is made once, as a ResolvedAuth, and every client is\n * built from that.\n */\n\nimport axios from 'axios';\nimport * as farseer from 'farseer-client';\nimport { FarseerService } from './farseerService';\nimport { FarseerApi } from './farseerApi';\nimport type { ApiKeyCredential } from './configService';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { logger } from '../utils/logger';\n\n/**\n * A tenant the backend couldn't resolve at this host \u2014 it answers\n * `403 {\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`.\n * Despite the 403 this is NOT a credentials problem: it's what a wrong\n * organisation for an otherwise-valid tenant looks like, because every\n * tenant-scoped request carries X-TENANT-ID and the org's backend has no such\n * tenant. Telling the user to log in again would send them to fix the one thing\n * that isn't broken.\n */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * The backend's \"no such tenant at this host\" phrasing. Lives apart from\n * isTenantNotFoundError because the same sentence reaches us two ways: inside a\n * thrown Error from the SDK, and as the `message` field of an axios 403 body \u2014\n * where `error.message` is only ever \"Request failed with status code 403\".\n */\nfunction 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\n/**\n * Check if an error is an authentication error (401/403).\n *\n * A 403 that names an unresolvable tenant is deliberately excluded \u2014 see\n * isTenantNotFoundError. Callers that show a login prompt on true would\n * otherwise misdiagnose a wrong-org command as expired credentials.\n */\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n return msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('forbidden');\n }\n return false;\n}\n\n/**\n * Show a consistent \"please login\" message\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('Run \"farseer login\" to authenticate via browser.');\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n\nexport interface FileMetadata {\n uploadTime?: string; // ISO timestamp\n uploader?: {\n id: number;\n email: string;\n firstName: string;\n lastName: string;\n };\n size?: number;\n}\n\n/**\n * Canonical RemoteFile shape used by every layer of the CLI. Both\n * FarseerApi (JWT path) and FarseerService (API-key path) re-export this\n * type so downstream code (SyncService, MCP tools, tests) can rely on a\n * single definition. Earlier each layer declared its own copy that drifted\n * \u2014 three different shapes that disagreed on which optional fields existed,\n * which made it impossible to tell from a function signature what the\n * caller could assume was set.\n *\n * Optional fields are populated lazily:\n * - `content` \u2014 only set by callers that already fetched body bytes\n * (some legacy paths combined list + download in a single helper).\n * - `metadata` \u2014 populated by listFiles for the JWT path. The API-key\n * path doesn't return it, so consumers must handle absence.\n */\nexport interface RemoteFile {\n name: string;\n path: string;\n reference: string;\n content?: string;\n metadata?: FileMetadata;\n}\n\n// Mirrors the backend `OrganizationInfo` schema returned by GET /organization\n// (backend/app/openapi/v3/documentation/overseer/components.yaml). The org is\n// resolved from the request host (`<org>.farseer.io`); `tenants` is the\n// authoritative list of tenants that org actually owns in overseer. `checkout`\n// uses it to confirm the org+tenant pair the user typed is real \u2014 the backend\n// resolves a tenant from the X-TENANT-ID header alone and never checks it\n// against the org, so without this the org argument is an unvalidated routing\n// hint.\nexport interface OrganizationTenant {\n name: string;\n isDefault: boolean;\n}\n\nexport interface OrganizationInfo {\n id: string;\n host: string;\n version: string;\n tenants: OrganizationTenant[];\n}\n\n// Narrow set of \"script\" extensions \u2014 used by `farseer files list` and\n// `farseer list` to default to source-code style files when listing a\n// folder. NOT the default sync scope; see DEFAULT_SYNC_EXTENSIONS below.\nexport const DEFAULT_SCRIPT_EXTENSIONS = ['.ts', '.js'];\n\n// Default sync scope \u2014 the curated set of files a developer AUTHORS in an\n// editor. NARROWER than the backend's accepted extension list\n// (`cli/src/utils/fileValidation.ts:BACKEND_EXTENSION_WHITELIST`, which\n// mirrors `farseer/backend/app/openapi/v3/services/farseerFileService.ts`).\n// The earlier \"default sync = everything backend accepts\" expanded the\n// default scope to 25 entries including binary / data formats (.csv,\n// .parquet, .xlsx, .pdf, images) \u2014 large files no one edits in a code\n// editor that dominated first-pull time and made `status` noisy.\n//\n// Users opt into the rest of the backend whitelist (data / docs /\n// archives) via `--include-ext <ext>` or persistent\n// `farseer config include`. Anything still outside the backend whitelist\n// requires `--all` or `--include-folder`.\n//\n// Subset contract: every entry here must also be in\n// `BACKEND_EXTENSION_WHITELIST`, otherwise push pre-flight will reject\n// in-scope files (extension not allowed) \u2014 defeats the purpose of the\n// default scope. Asserted by `defaultSyncExtensionsParity.test.ts`.\nexport const DEFAULT_SYNC_EXTENSIONS = [\n // Code (frontend / scripts)\n '.ts',\n '.js',\n // Code (Python)\n '.py',\n // Config / data\n '.yml',\n '.yaml',\n '.json',\n // Docs\n '.md',\n];\n\nimport {\n AppListItem,\n AppUpdateChanges,\n RemoteApp,\n SourceFolderResolution,\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n} from './farseerApi';\n\n// Common interface that both FarseerService and FarseerApi implement\nexport interface IFarseerClient {\n testConnection(): Promise<boolean>;\n getOrganizationInfo(): Promise<OrganizationInfo>;\n getFilesFolder(): Promise<{ id: number; name: string; type: string } | null>;\n listFiles(folderPath?: string[]): Promise<RemoteFile[]>;\n getFileContent(reference: string): Promise<string>;\n getFileContentAsBuffer(reference: string): Promise<Buffer>;\n createFile(content: string | Buffer, fileName: string, folderPath?: string[]): Promise<void>;\n updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void>;\n deleteFile(reference: string): Promise<void>;\n getFileByPath(filePath: string): Promise<RemoteFile | null>;\n getFileMetadata(reference: string): Promise<FileMetadata | null>;\n isTextFile(filename: string): boolean;\n isBinaryFile(filename: string): boolean;\n // Apps API methods\n listApps(): Promise<AppListItem[]>;\n getApp(referenceId: string): Promise<RemoteApp | null>;\n getAppByName(name: string): Promise<RemoteApp | null>;\n createApp(name: string): Promise<RemoteApp>;\n updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp>;\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n deleteApp(remoteJobId: string): Promise<void>;\n getScriptFiles(): Promise<{ id: string; name: string }[]>;\n // Model export\n exportModel(options?: ModelExportOptions): Promise<ModelExport>;\n /**\n * Fetch a single dimension table with its members. Goes through\n * `entities/search` + `getRelations` + `getMany`, which scope the\n * fetch to one table \u2014 unlike `exportModel` with `tableGids`,\n * which currently 500s for some tables on large tenants\n * (rama-side scoping bug, tracked separately).\n */\n loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null>;\n // Token management (optional - only FarseerApi implements this)\n updateAccessToken?(newToken: string): void;\n}\n\nexport interface FarseerClientResult {\n client: IFarseerClient;\n authType: 'apiKey' | 'jwt';\n}\n\n/**\n * Return a usable browser-login access token, refreshing it first if it has\n * expired. Null when there's no browser login, or the refresh failed (caller\n * should fall back to an API key).\n */\nexport async function getFreshAccessToken(): Promise<string | null> {\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n if (isUserAuthValid()) {\n return auth.accessToken;\n }\n\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\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 logger.dim('Token refreshed');\n return refreshed.accessToken;\n}\n\nexport type TenantCheck =\n | { status: 'ok' }\n | { status: 'tenant-unknown' }\n | { status: 'no-such-org' }\n | { status: 'unauthorized' }\n | { status: 'unreachable'; message: string };\n\n/**\n * Ask an organisation, in one request, whether it has this tenant.\n *\n * `/organization` is resolved from the request host, and sending X-TENANT-ID\n * puts the request through the same tenant-resolution middleware every\n * tenant-scoped call passes through \u2014 so the answer is the real one rather than\n * an inference:\n *\n * 200 the pair resolves, and the token works\n * 403 \"Tenant with id <t> does not exist\" the org does not have this tenant\n * 404 no Farseer organisation at this host\n * 401 the token is no good\n *\n * The alternative \u2014 asking without the header and looking for the tenant in the\n * response list \u2014 cannot refute a pair, because that list holds only what the\n * CALLER can enumerate and that is a different permission: an account that gets\n * `[]` for org `kiwi` still has `X-TENANT-ID: kiwi` accepted at that same host.\n *\n * The 403 was originally read as an auth failure, which is why the header was\n * avoided at first; `isTenantNotFoundError` tells the two apart from the body,\n * so it no longer is. Any OTHER 403 stays inconclusive \u2014 an org-level\n * permission problem is not this tenant failing to exist.\n */\nexport async function checkTenantAtOrganisation(\n organisation: string,\n tenant: string,\n accessToken: string,\n): Promise<TenantCheck> {\n try {\n await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}`, 'X-TENANT-ID': tenant },\n timeout: 30000,\n });\n return { status: 'ok' };\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n return { status: 'unauthorized' };\n }\n if (error.response?.status === 404) {\n return { status: 'no-such-org' };\n }\n const body = error.response?.data;\n const detail = typeof body === 'string' ? body : (body as { message?: string } | undefined)?.message;\n if (error.response?.status === 403 && mentionsUnknownTenant(detail)) {\n return { status: 'tenant-unknown' };\n }\n }\n return { status: 'unreachable', message: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/**\n * The tenants an organisation will admit to, for the CALLER. Best-effort and\n * hint-only: used to name the alternatives when a pair has already been refuted,\n * never to decide anything. Sends no tenant header \u2014 the pair is known bad by\n * this point, and including it would just 403 again.\n */\nexport async function fetchOrganizationTenants(organisation: string, accessToken: string): Promise<string[]> {\n try {\n const response = await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n timeout: 30000,\n });\n return (response.data.tenants ?? []).map((t) => t.name);\n } catch {\n return [];\n }\n}\n\n// Decided once and handed to the builders, so the credential the guard\n// validated is the one the command runs on.\nexport type ResolvedAuth =\n | { kind: 'jwt'; accessToken: string; basePath: string; tenant: string }\n | { kind: 'apiKey'; credential: ApiKeyCredential };\n\n/**\n * Always the organisation that was typed. A stored key's basePath belongs to\n * that key; letting it stand in here made the host depend on whether a key\n * happened to be named after the organisation.\n */\nfunction jwtAuth(accessToken: string, organisation: string, tenant: string): ResolvedAuth {\n return { kind: 'jwt', accessToken, basePath: generateBasePath(organisation), tenant };\n}\n\n/**\n * The curated CLI-level view \u2014 file sync, apps, model export.\n *\n * TECH DEBT \u2014 two client shapes over the same credential. This one returns an\n * `IFarseerClient` (a facade over the hand-rolled axios `FarseerApi` for JWT and\n * the SDK-wrapping `FarseerService` for API keys) while `buildNativeClient`\n * returns the raw SDK client for the richer read/query surface. The split is\n * historical \u2014 the JWT path was hand-rolled instead of using the SDK, which the\n * SDK handles fine \u2014 and collapsing the two into one class is a follow-up. They\n * can no longer disagree about *which* credential they carry, which was the part\n * that mattered.\n */\nexport function buildClient(auth: ResolvedAuth): IFarseerClient {\n return auth.kind === 'jwt'\n ? new FarseerApi(auth.accessToken, auth.basePath, auth.tenant)\n : new FarseerService(auth.credential);\n}\n\n/** The full SDK surface, for the read/query commands. Constructs only \u2014 no request. */\nexport function buildNativeClient(auth: ResolvedAuth): farseer.FarseerClient {\n if (auth.kind === 'jwt') {\n return new farseer.FarseerClient({\n basePath: auth.basePath,\n headers: { 'X-TENANT-ID': auth.tenant, Authorization: `Bearer ${auth.accessToken}` },\n });\n }\n return new farseer.FarseerClient({\n basePath: auth.credential.basePath,\n headers: { 'X-TENANT-ID': auth.credential.tenantId, 'X-API-KEY': auth.credential.apiKey },\n });\n}\n\n/** Pick by what's available. Nothing is sent, so it can't tell whether the credential works. */\nexport async function resolveAuth(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n return jwtAuth(accessToken, organisation, tenant);\n }\n\n const credential = getCredential(tenant);\n return credential ? { kind: 'apiKey', credential } : null;\n}\n\n/**\n * Pick one that actually connects. The probe is the point: a key is the only\n * thing that still works once the organisation route is dead.\n */\nexport async function resolveAuthByProbe(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n const auth = jwtAuth(accessToken, organisation, tenant);\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n\n const credential = getCredential(tenant);\n if (credential) {\n const auth: ResolvedAuth = { kind: 'apiKey', credential };\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('API key auth failed.');\n }\n\n return null;\n}\n\n/**\n * The same decision with a fresh browser token. A CLI command lives for one\n * request; an MCP server runs for hours, so the token is the part it re-takes.\n */\nexport async function refreshAuth(auth: ResolvedAuth): Promise<ResolvedAuth | null> {\n if (auth.kind === 'apiKey') {\n return auth;\n }\n const accessToken = await getFreshAccessToken();\n return accessToken ? { ...auth, accessToken } : null;\n}\n\nasync function connects(auth: ResolvedAuth): Promise<boolean> {\n try {\n return await buildClient(auth).testConnection();\n } catch {\n return false;\n }\n}\n\n/**\n * Get a Farseer client for the given organisation and tenant.\n * Tries JWT token first (supports apps), then falls back to API key.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClient(organisation: string, tenant: string): Promise<FarseerClientResult | null> {\n const auth = await resolveAuth(organisation, tenant);\n return auth ? { client: buildClient(auth), authType: auth.kind } : null;\n}\n\n/**\n * Check what authentication methods are available\n */\nexport function getAvailableAuth(tenant: string): {\n hasApiKey: boolean;\n hasJwt: boolean;\n jwtValid: boolean;\n} {\n const credential = getCredential(tenant);\n const auth = getUserAuth();\n\n return {\n hasApiKey: !!credential,\n hasJwt: !!auth,\n jwtValid: isUserAuthValid(),\n };\n}\n\n/**\n * Ensure the token is fresh and update the client if needed.\n * Call this before long-running operations to avoid token expiration.\n *\n * @returns true if token was refreshed, false if no refresh needed or API key auth\n */\nexport async function ensureFreshToken(client: IFarseerClient): Promise<boolean> {\n const auth = getUserAuth();\n if (!auth) {\n return false; // No JWT auth, probably using API key\n }\n\n // Check if token needs refresh (give 30 second buffer)\n const expiresAt = new Date(auth.expiresAt);\n const now = new Date();\n const bufferMs = 30 * 1000; // 30 seconds\n\n if (expiresAt.getTime() - now.getTime() > bufferMs) {\n return false; // Token is still fresh enough\n }\n\n // Refresh the token\n logger.dim('Refreshing token before operation...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n\n if (!refreshed) {\n logger.warning('Could not refresh token.');\n return false;\n }\n\n // Save the new 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 // Update the client's token if it supports it\n if (client.updateAccessToken) {\n client.updateAccessToken(refreshed.accessToken);\n logger.dim('Token refreshed');\n return true;\n }\n\n return false;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,mBAAkB;AAClB,cAAyB;AACzB,4BAA+B;AAC/B,wBAA2B;AAE3B,2BAA2F;AAC3F,IAAAA,yBAAmC;AACnC,oBAAuB;AAWhB,SAAS,sBAAsB,OAAyB;AAC3D,SAAO,iBAAiB,SAAS,sBAAsB,MAAM,OAAO;AACxE;AAQA,SAAS,sBAAsB,MAAmC;AAC9D,MAAI,CAAC,MAAM;AACP,WAAO;AAAA,EACX;AACA,QAAM,MAAM,KAAK,YAAY;AAC7B,SAAO,IAAI,SAAS,gBAAgB,KAAK,IAAI,SAAS,QAAQ;AAClE;AASO,SAAS,YAAY,OAAyB;AACjD,MAAI,sBAAsB,KAAK,GAAG;AAC9B,WAAO;AAAA,EACX;AACA,MAAI,iBAAiB,OAAO;AACxB,UAAM,MAAM,MAAM,QAAQ,YAAY;AACtC,WAAO,IAAI,SAAS,KAAK,KAAK,IAAI,SAAS,KAAK,KAAK,IAAI,SAAS,cAAc,KAAK,IAAI,SAAS,WAAW;AAAA,EACjH;AACA,SAAO;AACX;AAKO,SAAS,gBAAgB,QAAuB;AACnD,uBAAO,MAAM,0BAA0B;AACvC,MAAI,QAAQ;AACR,yBAAO,IAA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,QAAM,WAAO,kCAAY;AAEzB,SAAO;AAAA,IACH,WAAW,CAAC,CAAC;AAAA,IACb,QAAQ,CAAC,CAAC;AAAA,IACV,cAAU,sCAAgB;AAAA,EAC9B;AACJ;AAQA,eAAsB,iBAAiB,QAA0C;AAC7E,QAAM,WAAO,kCAAY;AACzB,MAAI,CAAC,MAAM;AACP,WAAO;AAAA,EACX;AAGA,QAAM,YAAY,IAAI,KAAK,KAAK,SAAS;AACzC,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,WAAW,KAAK;AAEtB,MAAI,UAAU,QAAQ,IAAI,IAAI,QAAQ,IAAI,UAAU;AAChD,WAAO;AAAA,EACX;AAGA,uBAAO,IAAI,sCAAsC;AACjD,QAAM,YAAY,UAAM,2CAAmB,KAAK,cAAc,KAAK,SAAS,QAAQ;AAEpF,MAAI,CAAC,WAAW;AACZ,yBAAO,QAAQ,0BAA0B;AACzC,WAAO;AAAA,EACX;AAGA,wCAAY;AAAA,IACR,aAAa,UAAU;AAAA,IACvB,cAAc,UAAU;AAAA,IACxB,WAAW,IAAI,KAAK,KAAK,IAAI,IAAI,UAAU,YAAY,GAAI,EAAE,YAAY;AAAA,IACzE,OAAO,KAAK;AAAA,EAChB,CAAC;AAGD,MAAI,OAAO,mBAAmB;AAC1B,WAAO,kBAAkB,UAAU,WAAW;AAC9C,yBAAO,IAAI,iBAAiB;AAC5B,WAAO;AAAA,EACX;AAEA,SAAO;AACX;",
|
|
6
6
|
"names": ["import_farseerService", "axios"]
|
|
7
7
|
}
|
|
@@ -28,8 +28,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
28
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
29
|
var preflight_exports = {};
|
|
30
30
|
__export(preflight_exports, {
|
|
31
|
+
openTenantSession: () => openTenantSession,
|
|
31
32
|
preflight: () => preflight,
|
|
32
|
-
preflightForPair: () => preflightForPair
|
|
33
|
+
preflightForPair: () => preflightForPair,
|
|
34
|
+
sessionFrom: () => sessionFrom
|
|
33
35
|
});
|
|
34
36
|
module.exports = __toCommonJS(preflight_exports);
|
|
35
37
|
var fs = __toESM(require("fs"));
|
|
@@ -42,28 +44,52 @@ async function preflight(arg1, arg2, opts = {}) {
|
|
|
42
44
|
return preflightForPair(organisation, tenant, opts);
|
|
43
45
|
}
|
|
44
46
|
async function preflightForPair(organisation, tenant, opts = {}) {
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
reportDeadRoute(validation, organisation, tenant);
|
|
47
|
+
const outcome = await openTenantSession(organisation, tenant);
|
|
48
|
+
if (!outcome.ok) {
|
|
49
|
+
reportSessionFailure(outcome.failure);
|
|
49
50
|
process.exit(1);
|
|
50
51
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
52
|
+
if (outcome.warning) {
|
|
53
|
+
reportSessionWarning(outcome.warning);
|
|
54
|
+
}
|
|
55
|
+
if (opts.requiresWorkspace) {
|
|
56
|
+
ensureWorkspaceOrExit(tenant);
|
|
57
|
+
}
|
|
58
|
+
return sessionFrom(outcome.organisation, outcome.tenant, outcome.auth);
|
|
59
|
+
}
|
|
60
|
+
async function openTenantSession(organisation, tenant) {
|
|
61
|
+
const validation = await validatePairing(organisation, tenant);
|
|
62
|
+
const deadRoute = deadRouteFailure(validation, organisation, tenant);
|
|
63
|
+
if (deadRoute && !(0, import_configService.getCredential)(tenant)) {
|
|
64
|
+
return { ok: false, failure: deadRoute };
|
|
65
|
+
}
|
|
66
|
+
const auth = validation.status === "jwt-validated" ? await (0, import_farseerFactory.resolveAuth)(organisation, tenant) : await (0, import_farseerFactory.resolveAuthByProbe)(organisation, tenant);
|
|
67
|
+
if (!auth) {
|
|
68
|
+
return { ok: false, failure: deadRoute ?? { reason: "no-credentials", organisation, tenant } };
|
|
59
69
|
}
|
|
60
70
|
if (validation.status === "jwt-validated") {
|
|
61
71
|
(0, import_configService.saveTenantOrgMapping)(tenant, organisation);
|
|
62
72
|
}
|
|
63
|
-
|
|
64
|
-
|
|
73
|
+
return { ok: true, organisation, tenant, auth, warning: organisationIgnored(organisation, auth) };
|
|
74
|
+
}
|
|
75
|
+
function organisationIgnored(organisation, auth) {
|
|
76
|
+
if (auth.kind !== "apiKey") {
|
|
77
|
+
return void 0;
|
|
78
|
+
}
|
|
79
|
+
const basePath = auth.credential.basePath;
|
|
80
|
+
if (basePath === (0, import_configService.generateBasePath)(organisation)) {
|
|
81
|
+
return void 0;
|
|
65
82
|
}
|
|
66
|
-
return { organisation,
|
|
83
|
+
return { reason: "organisation-ignored", organisation, tenant: auth.credential.tenantId, host: hostOf(basePath) };
|
|
84
|
+
}
|
|
85
|
+
function sessionFrom(organisation, tenant, auth) {
|
|
86
|
+
return {
|
|
87
|
+
organisation,
|
|
88
|
+
tenant,
|
|
89
|
+
client: (0, import_farseerFactory.buildClient)(auth),
|
|
90
|
+
native: (0, import_farseerFactory.buildNativeClient)(auth),
|
|
91
|
+
authType: auth.kind
|
|
92
|
+
};
|
|
67
93
|
}
|
|
68
94
|
async function validatePairing(organisation, tenant) {
|
|
69
95
|
const accessToken = await (0, import_farseerFactory.getFreshAccessToken)();
|
|
@@ -85,16 +111,42 @@ async function validatePairing(organisation, tenant) {
|
|
|
85
111
|
return { status: "unvalidated" };
|
|
86
112
|
}
|
|
87
113
|
}
|
|
88
|
-
function
|
|
89
|
-
|
|
90
|
-
|
|
114
|
+
function deadRouteFailure(validation, organisation, tenant) {
|
|
115
|
+
switch (validation.status) {
|
|
116
|
+
case "pair-refuted":
|
|
117
|
+
return { reason: "pair-refuted", organisation, tenant, orgTenants: validation.orgTenants };
|
|
118
|
+
case "org-unknown":
|
|
119
|
+
return { reason: "org-unknown", organisation, tenant };
|
|
120
|
+
default:
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function reportSessionWarning(warning) {
|
|
125
|
+
import_logger.logger.warning(`Organisation "${warning.organisation}" was ignored.`);
|
|
126
|
+
import_logger.logger.dim(`The stored API key for "${warning.tenant}" carries its own host: ${warning.host}.`);
|
|
127
|
+
import_logger.logger.dim("The tenant is the one you asked for; the organisation had no effect on where this went.");
|
|
128
|
+
}
|
|
129
|
+
function hostOf(basePath) {
|
|
130
|
+
try {
|
|
131
|
+
return new URL(basePath).host;
|
|
132
|
+
} catch {
|
|
133
|
+
return basePath;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function reportSessionFailure(failure) {
|
|
137
|
+
if (failure.reason === "no-credentials") {
|
|
138
|
+
(0, import_farseerFactory.showLoginPrompt)(failure.tenant);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (failure.reason === "org-unknown") {
|
|
142
|
+
import_logger.logger.error(`No Farseer organisation at "${failure.organisation}".`);
|
|
91
143
|
import_logger.logger.dim("Check the spelling, then pass the pair explicitly:");
|
|
92
|
-
import_logger.logger.dim(` farseer <command> <organisation> ${tenant}`);
|
|
144
|
+
import_logger.logger.dim(` farseer <command> <organisation> ${failure.tenant}`);
|
|
93
145
|
return;
|
|
94
146
|
}
|
|
95
|
-
import_logger.logger.error(`Tenant "${tenant}" is not available under organisation "${organisation}".`);
|
|
96
|
-
if (
|
|
97
|
-
import_logger.logger.dim(`Tenants you can access under ${organisation}: ${
|
|
147
|
+
import_logger.logger.error(`Tenant "${failure.tenant}" is not available under organisation "${failure.organisation}".`);
|
|
148
|
+
if (failure.orgTenants.length > 0) {
|
|
149
|
+
import_logger.logger.dim(`Tenants you can access under ${failure.organisation}: ${failure.orgTenants.join(", ")}`);
|
|
98
150
|
}
|
|
99
151
|
import_logger.logger.dim("Either the organisation is wrong for this tenant (set FARSEER_ORG or pass <org> <tenant>),");
|
|
100
152
|
import_logger.logger.dim("or you don't have access to it \u2014 check you're logged in with the right account.");
|
|
@@ -109,7 +161,9 @@ function ensureWorkspaceOrExit(tenant) {
|
|
|
109
161
|
}
|
|
110
162
|
// Annotate the CommonJS export names for ESM import in node:
|
|
111
163
|
0 && (module.exports = {
|
|
164
|
+
openTenantSession,
|
|
112
165
|
preflight,
|
|
113
|
-
preflightForPair
|
|
166
|
+
preflightForPair,
|
|
167
|
+
sessionFrom
|
|
114
168
|
});
|
|
115
169
|
//# sourceMappingURL=preflight.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/preflight.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Shared per-command preflight: resolve the target, confirm the organisation has\n * that tenant, return an authenticated client, and \u2014 for commands that touch\n * local files \u2014 check the workspace exists. Every command that talks to a tenant\n * runs it; `install` is the exception (local npm only).\n *\n * The contract: if this returns, the credentials work and the org/tenant pair is\n * real. It does not prove the caller may perform a given operation \u2014 that\n * surfaces on the command's own first call \u2014 and on the API-key path the\n * organisation is never checked at all, since the credential carries its own host.\n *\n * Nothing is cached. A remembered \"this pair was fine once\" would hide a tenant\n * that moved organisations, and the check is already paid for: see\n * checkTenantAtOrganisation, which is where the org question is actually asked.\n *\n * TECH DEBT: returns an `IFarseerClient`, which suits the sync commands; the\n * read/query commands need the native SDK client and build a second one from the\n * validated pair. Unifying the two stacks is a follow-up \u2014 see\n * getNativeFarseerClient.\n */\n\nimport * as fs from 'fs';\nimport type { IFarseerClient } from './farseerFactory';\nimport {\n checkTenantAtOrganisation,\n fetchOrganizationTenants,\n getFarseerClient,\n getFarseerClientWithFallback,\n getFreshAccessToken,\n showLoginPrompt,\n} from './farseerFactory';\nimport { getCredential, saveTenantOrgMapping } from './configService';\nimport { resolveTenantWithOrgMapping, getTenantFilesDir } from '../utils/helpers';\nimport { logger } from '../utils/logger';\n\nexport interface PreflightResult {\n organisation: string;\n tenant: string;\n client: IFarseerClient;\n authType: 'jwt' | 'apiKey';\n}\n\nexport interface PreflightOpts {\n // Set by commands that read or write local files. `pull` leaves it unset \u2014\n // it creates the workspace itself.\n requiresWorkspace?: boolean;\n}\n\n/**\n * Entry point for commands whose positional args are `[org] [tenant]`. Variadic\n * ones (run/app) resolve the pair themselves and call preflightForPair.\n */\nexport async function preflight(arg1?: string, arg2?: string, opts: PreflightOpts = {}): Promise<PreflightResult> {\n const { organisation, tenant } = resolveTenantWithOrgMapping(arg1, arg2);\n return preflightForPair(organisation, tenant, opts);\n}\n\n/**\n * Same checks for an already-resolved pair, and the only place that exits.\n */\nexport async function preflightForPair(\n organisation: string,\n tenant: string,\n opts: PreflightOpts = {},\n): Promise<PreflightResult> {\n const validation = await validatePairing(organisation, tenant);\n const routeIsDead = validation.status === 'pair-refuted' || validation.status === 'org-unknown';\n\n // An API key carries its own host, so it's the one thing that still works\n // once the org route is dead. Without one, refuse now rather than spend a\n // round trip confirming what the org already said.\n if (routeIsDead && !getCredential(tenant)) {\n reportDeadRoute(validation, organisation, tenant);\n process.exit(1);\n }\n\n // A 200 already proved the token, so that path needs no second probe.\n const clientResult =\n validation.status === 'jwt-validated'\n ? await getFarseerClient(organisation, tenant)\n : await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n // Reaching here with a dead route means the API key we deferred to also\n // failed; a login prompt would point at the one thing that isn't broken.\n if (routeIsDead) {\n reportDeadRoute(validation, organisation, tenant);\n } else {\n showLoginPrompt(tenant);\n }\n process.exit(1);\n }\n\n // Only what the org confirmed. The other outcomes can still succeed on an\n // API key, which ignores the org \u2014 so success there proves nothing about the\n // org that was typed, and recording it would pin a bad host to this tenant.\n if (validation.status === 'jwt-validated') {\n saveTenantOrgMapping(tenant, organisation);\n }\n\n if (opts.requiresWorkspace) {\n ensureWorkspaceOrExit(tenant);\n }\n\n return { organisation, tenant, client: clientResult.client, authType: clientResult.authType };\n}\n\n// `orgTenants` is what the org does have, for the error message \u2014 empty when the\n// caller isn't allowed to enumerate them, which weakens the hint, not the\n// refusal. `unvalidated` means we couldn't ask, not that the answer was no.\ntype ValidationOutcome =\n | { status: 'jwt-validated' }\n | { status: 'pair-refuted'; orgTenants: string[] }\n | { status: 'org-unknown' }\n | { status: 'unvalidated' };\n\n/**\n * Ask the organisation whether it has this tenant. Browser-login only \u2014 an API\n * key ignores the org, so there is nothing to ask about.\n *\n * Reports, never decides: no path here exits. The answer is definitive both ways\n * \u2014 see checkTenantAtOrganisation for why the tenant header is what makes it so.\n */\nasync function validatePairing(organisation: string, tenant: string): Promise<ValidationOutcome> {\n const accessToken = await getFreshAccessToken();\n if (!accessToken) {\n return { status: 'unvalidated' };\n }\n\n const check = await checkTenantAtOrganisation(organisation, tenant, accessToken);\n\n switch (check.status) {\n case 'ok':\n return { status: 'jwt-validated' };\n\n case 'tenant-unknown':\n // Only now spend a second request, to name what the org does have.\n return { status: 'pair-refuted', orgTenants: await fetchOrganizationTenants(organisation, accessToken) };\n\n case 'no-such-org':\n return { status: 'org-unknown' };\n\n case 'unauthorized':\n // Say nothing \u2014 let the client factory try an API key, or prompt.\n return { status: 'unvalidated' };\n\n case 'unreachable':\n logger.dim(`Could not verify that \"${tenant}\" belongs to \"${organisation}\"; proceeding.`);\n return { status: 'unvalidated' };\n }\n}\n\n/** Says which way the org route is dead, and what to do about it. */\nfunction reportDeadRoute(validation: ValidationOutcome, organisation: string, tenant: string): void {\n if (validation.status === 'org-unknown') {\n logger.error(`No Farseer organisation at \"${organisation}\".`);\n logger.dim('Check the spelling, then pass the pair explicitly:');\n logger.dim(` farseer <command> <organisation> ${tenant}`);\n return;\n }\n\n logger.error(`Tenant \"${tenant}\" is not available under organisation \"${organisation}\".`);\n if (validation.status === 'pair-refuted' && validation.orgTenants.length > 0) {\n logger.dim(`Tenants you can access under ${organisation}: ${validation.orgTenants.join(', ')}`);\n }\n logger.dim('Either the organisation is wrong for this tenant (set FARSEER_ORG or pass <org> <tenant>),');\n logger.dim(\"or you don't have access to it \u2014 check you're logged in with the right account.\");\n}\n\n/** For commands that read or write local files. */\nfunction ensureWorkspaceOrExit(tenant: string): void {\n const filesDir = getTenantFilesDir(tenant);\n if (!fs.existsSync(filesDir)) {\n logger.error(`No local workspace for tenant \"${tenant}\".`);\n logger.dim(`Run \"farseer pull ${tenant}\" to set it up first.`);\n process.exit(1);\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;
|
|
4
|
+
"sourcesContent": ["/**\n * Shared tenant guard: confirm the organisation has the tenant, and hand back\n * clients built from the one credential that was checked.\n *\n * Two entry points because two surfaces need the same checks with different\n * endings. `preflightForPair` reports and exits, which is right for a CLI\n * command; `openTenantSession` returns the outcome, which is what lets the MCP\n * server run the same checks without killing the process an agent is talking to.\n *\n * Past a successful call the credentials work and the pair is real. It does not\n * prove the caller may perform an operation, and on the API-key path the\n * organisation is not checked at all \u2014 a key carries its own host.\n *\n * Nothing is cached: a remembered \"fine once\" would hide a tenant that moved\n * organisations, and the check is already paid for.\n */\n\nimport * as fs from 'fs';\nimport type * as farseer from 'farseer-client';\nimport type { IFarseerClient, ResolvedAuth } from './farseerFactory';\nimport {\n buildClient,\n buildNativeClient,\n checkTenantAtOrganisation,\n fetchOrganizationTenants,\n getFreshAccessToken,\n resolveAuth,\n resolveAuthByProbe,\n showLoginPrompt,\n} from './farseerFactory';\nimport { generateBasePath, getCredential, saveTenantOrgMapping } from './configService';\nimport { resolveTenantWithOrgMapping, getTenantFilesDir } from '../utils/helpers';\nimport { logger } from '../utils/logger';\n\nexport interface TenantSession {\n organisation: string;\n tenant: string;\n client: IFarseerClient;\n native: farseer.FarseerClient;\n authType: 'jwt' | 'apiKey';\n}\n\n// Data, not a rendered string: \"pass <org> <tenant>\" is useless advice to an\n// agent in a locked session, so each surface words it itself.\nexport type SessionFailure =\n | { reason: 'pair-refuted'; organisation: string; tenant: string; orgTenants: string[] }\n | { reason: 'org-unknown'; organisation: string; tenant: string }\n | { reason: 'no-credentials'; organisation: string; tenant: string };\n\n// True and worth saying, but not a reason to stop. Carried, not printed, for\n// the same reason a failure is.\nexport type SessionWarning = { reason: 'organisation-ignored'; organisation: string; tenant: string; host: string };\n\nexport type SessionOutcome =\n | { ok: true; organisation: string; tenant: string; auth: ResolvedAuth; warning?: SessionWarning }\n | { ok: false; failure: SessionFailure };\n\nexport interface PreflightOpts {\n /** Commands that read or write local files. `pull` creates the workspace itself. */\n requiresWorkspace?: boolean;\n}\n\n/** For commands whose positional args are `[org] [tenant]`; variadic ones call preflightForPair. */\nexport async function preflight(arg1?: string, arg2?: string, opts: PreflightOpts = {}): Promise<TenantSession> {\n const { organisation, tenant } = resolveTenantWithOrgMapping(arg1, arg2);\n return preflightForPair(organisation, tenant, opts);\n}\n\n/** Same checks for an already-resolved pair, and the only place that exits. */\nexport async function preflightForPair(\n organisation: string,\n tenant: string,\n opts: PreflightOpts = {},\n): Promise<TenantSession> {\n const outcome = await openTenantSession(organisation, tenant);\n if (!outcome.ok) {\n reportSessionFailure(outcome.failure);\n process.exit(1);\n }\n\n if (outcome.warning) {\n reportSessionWarning(outcome.warning);\n }\n\n if (opts.requiresWorkspace) {\n ensureWorkspaceOrExit(tenant);\n }\n\n return sessionFrom(outcome.organisation, outcome.tenant, outcome.auth);\n}\n\n/**\n * The checks, with no opinion about what to do when they fail. The credential is\n * part of the answer, not something the caller re-derives afterwards.\n */\nexport async function openTenantSession(organisation: string, tenant: string): Promise<SessionOutcome> {\n const validation = await validatePairing(organisation, tenant);\n const deadRoute = deadRouteFailure(validation, organisation, tenant);\n\n // An API key carries its own host, so it's the one thing that still works\n // once the org route is dead. Without one, refuse now rather than spend a\n // round trip confirming what the org already said.\n if (deadRoute && !getCredential(tenant)) {\n return { ok: false, failure: deadRoute };\n }\n\n // A 200 already proved the token, so that path needs no second probe.\n const auth =\n validation.status === 'jwt-validated'\n ? await resolveAuth(organisation, tenant)\n : await resolveAuthByProbe(organisation, tenant);\n\n if (!auth) {\n // Reaching here with a dead route means the API key we deferred to also\n // failed; naming the login would point at the one thing that isn't broken.\n return { ok: false, failure: deadRoute ?? { reason: 'no-credentials', organisation, tenant } };\n }\n\n // Only what the org confirmed. The other outcomes can still succeed on an\n // API key, which ignores the org \u2014 so success there proves nothing about the\n // org that was typed, and recording it would pin a bad host to this tenant.\n if (validation.status === 'jwt-validated') {\n saveTenantOrgMapping(tenant, organisation);\n }\n\n return { ok: true, organisation, tenant, auth, warning: organisationIgnored(organisation, auth) };\n}\n\n/**\n * An API key carries its own host and ignores the organisation, so a pair the\n * guard would have refused on a browser login goes through unremarked. The\n * tenant is still the one that was asked for \u2014 nothing operates on the wrong\n * data \u2014 but silence lets a typo sit in a script for months.\n *\n * Only when the two actually disagree.\n */\nfunction organisationIgnored(organisation: string, auth: ResolvedAuth): SessionWarning | undefined {\n if (auth.kind !== 'apiKey') {\n return undefined;\n }\n const basePath = auth.credential.basePath;\n if (basePath === generateBasePath(organisation)) {\n return undefined;\n }\n return { reason: 'organisation-ignored', organisation, tenant: auth.credential.tenantId, host: hostOf(basePath) };\n}\n\n/** Materialise both client shapes over one credential. Constructs only. */\nexport function sessionFrom(organisation: string, tenant: string, auth: ResolvedAuth): TenantSession {\n return {\n organisation,\n tenant,\n client: buildClient(auth),\n native: buildNativeClient(auth),\n authType: auth.kind,\n };\n}\n\n// `unvalidated` means we couldn't ask, not that the answer was no.\ntype ValidationOutcome =\n | { status: 'jwt-validated' }\n | { status: 'pair-refuted'; orgTenants: string[] }\n | { status: 'org-unknown' }\n | { status: 'unvalidated' };\n\n/**\n * Ask the organisation whether it has this tenant. Browser-login only \u2014 a key\n * ignores the organisation, so there is nothing to ask. Reports, never decides.\n */\nasync function validatePairing(organisation: string, tenant: string): Promise<ValidationOutcome> {\n const accessToken = await getFreshAccessToken();\n if (!accessToken) {\n return { status: 'unvalidated' };\n }\n\n const check = await checkTenantAtOrganisation(organisation, tenant, accessToken);\n\n switch (check.status) {\n case 'ok':\n return { status: 'jwt-validated' };\n\n case 'tenant-unknown':\n // Only now spend a second request, to name what the org does have.\n return { status: 'pair-refuted', orgTenants: await fetchOrganizationTenants(organisation, accessToken) };\n\n case 'no-such-org':\n return { status: 'org-unknown' };\n\n case 'unauthorized':\n // Say nothing \u2014 let the credential resolution try an API key, or prompt.\n return { status: 'unvalidated' };\n\n case 'unreachable':\n logger.dim(`Could not verify that \"${tenant}\" belongs to \"${organisation}\"; proceeding.`);\n return { status: 'unvalidated' };\n }\n}\n\n/** The org's answer, as a failure \u2014 or null when the org route is still open. */\nfunction deadRouteFailure(validation: ValidationOutcome, organisation: string, tenant: string): SessionFailure | null {\n switch (validation.status) {\n case 'pair-refuted':\n return { reason: 'pair-refuted', organisation, tenant, orgTenants: validation.orgTenants };\n case 'org-unknown':\n return { reason: 'org-unknown', organisation, tenant };\n default:\n return null;\n }\n}\n\nfunction reportSessionWarning(warning: SessionWarning): void {\n logger.warning(`Organisation \"${warning.organisation}\" was ignored.`);\n logger.dim(`The stored API key for \"${warning.tenant}\" carries its own host: ${warning.host}.`);\n logger.dim('The tenant is the one you asked for; the organisation had no effect on where this went.');\n}\n\n/** The full base path is noise in a message. */\nfunction hostOf(basePath: string): string {\n try {\n return new URL(basePath).host;\n } catch {\n return basePath;\n }\n}\n\n/** Says which way the route is dead, and what to do about it, for a CLI user. */\nfunction reportSessionFailure(failure: SessionFailure): void {\n if (failure.reason === 'no-credentials') {\n showLoginPrompt(failure.tenant);\n return;\n }\n\n if (failure.reason === 'org-unknown') {\n logger.error(`No Farseer organisation at \"${failure.organisation}\".`);\n logger.dim('Check the spelling, then pass the pair explicitly:');\n logger.dim(` farseer <command> <organisation> ${failure.tenant}`);\n return;\n }\n\n logger.error(`Tenant \"${failure.tenant}\" is not available under organisation \"${failure.organisation}\".`);\n if (failure.orgTenants.length > 0) {\n logger.dim(`Tenants you can access under ${failure.organisation}: ${failure.orgTenants.join(', ')}`);\n }\n logger.dim('Either the organisation is wrong for this tenant (set FARSEER_ORG or pass <org> <tenant>),');\n logger.dim(\"or you don't have access to it \u2014 check you're logged in with the right account.\");\n}\n\n/** For commands that read or write local files. */\nfunction ensureWorkspaceOrExit(tenant: string): void {\n const filesDir = getTenantFilesDir(tenant);\n if (!fs.existsSync(filesDir)) {\n logger.error(`No local workspace for tenant \"${tenant}\".`);\n logger.dim(`Run \"farseer pull ${tenant}\" to set it up first.`);\n process.exit(1);\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,SAAoB;AAGpB,4BASO;AACP,2BAAsE;AACtE,qBAA+D;AAC/D,oBAAuB;AA+BvB,eAAsB,UAAU,MAAe,MAAe,OAAsB,CAAC,GAA2B;AAC5G,QAAM,EAAE,cAAc,OAAO,QAAI,4CAA4B,MAAM,IAAI;AACvE,SAAO,iBAAiB,cAAc,QAAQ,IAAI;AACtD;AAGA,eAAsB,iBAClB,cACA,QACA,OAAsB,CAAC,GACD;AACtB,QAAM,UAAU,MAAM,kBAAkB,cAAc,MAAM;AAC5D,MAAI,CAAC,QAAQ,IAAI;AACb,yBAAqB,QAAQ,OAAO;AACpC,YAAQ,KAAK,CAAC;AAAA,EAClB;AAEA,MAAI,QAAQ,SAAS;AACjB,yBAAqB,QAAQ,OAAO;AAAA,EACxC;AAEA,MAAI,KAAK,mBAAmB;AACxB,0BAAsB,MAAM;AAAA,EAChC;AAEA,SAAO,YAAY,QAAQ,cAAc,QAAQ,QAAQ,QAAQ,IAAI;AACzE;AAMA,eAAsB,kBAAkB,cAAsB,QAAyC;AACnG,QAAM,aAAa,MAAM,gBAAgB,cAAc,MAAM;AAC7D,QAAM,YAAY,iBAAiB,YAAY,cAAc,MAAM;AAKnE,MAAI,aAAa,KAAC,oCAAc,MAAM,GAAG;AACrC,WAAO,EAAE,IAAI,OAAO,SAAS,UAAU;AAAA,EAC3C;AAGA,QAAM,OACF,WAAW,WAAW,kBAChB,UAAM,mCAAY,cAAc,MAAM,IACtC,UAAM,0CAAmB,cAAc,MAAM;AAEvD,MAAI,CAAC,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