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/services/farseerService.ts"],
|
|
4
|
-
"sourcesContent": ["import * as farseer from 'farseer-client';\nimport { API_VERSION } from 'farseer-client/dist/generated/apiVersion';\nimport { getUserAuth, setUserAuth, isUserAuthValid } from './configService';\nimport type { ApiKeyCredential } from './configService';\nimport {\n AppListItem,\n AppUpdateChanges,\n ConnectedRunner,\n REMOTE_JOB_ITEM_TYPE,\n RemoteApp,\n ResolvedFolderItem,\n RunnerImageRepositories,\n SourceFolderResolution,\n mergeAppUpdate,\n remoteJobReverseReferences,\n resolveAppItemNodeId,\n} from './apps';\nimport {\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n ModelExportVariable,\n loadDimensionTableViaEntitiesApi,\n} from './modelExport';\nimport { toError } from '../utils/errorFormatter';\nimport { matchFolderSegment } from '../utils/folderMatch';\nimport { HttpError } from './httpError';\nimport { mentionsUnknownTenant } from './authErrors';\nimport { logger } from '../utils/logger';\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\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// 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 * Why a credential probe failed. Four reasons rather than two because the advice\n * differs for each: a rejected credential means replace it, an unknown tenant\n * means the organisation is wrong and the credential is fine, a server error\n * means the host answered and nothing is wrong locally, and unreachable means\n * nothing answered at all.\n */\nexport type ConnectionFailure = 'rejected' | 'tenant-unknown' | 'server-error' | 'unreachable';\n\nexport type ConnectionCheck = { ok: true } | { ok: false; reason: ConnectionFailure; message: string };\n\nexport interface FolderItem {\n id: number;\n name: string;\n type: string;\n reference?: string;\n}\n\n/** Where a credential's requests go, and who they say they are. */\nexport function basePathOf(auth: ResolvedAuth): string {\n return auth.kind === 'jwt' ? auth.basePath : auth.credential.basePath;\n}\n\nfunction authHeaders(auth: ResolvedAuth): Record<string, string> {\n return auth.kind === 'jwt'\n ? { 'X-TENANT-ID': auth.tenant, Authorization: `Bearer ${auth.accessToken}` }\n : { 'X-TENANT-ID': auth.credential.tenantId, 'X-API-KEY': auth.credential.apiKey };\n}\n\n/**\n * Which of the four failures a thrown probe error is. A 403 is read two ways:\n * the backend answers it both for a credential it will not accept and for a\n * tenant the organisation does not have, and only the body tells them apart.\n */\nfunction failureReason(error: unknown): ConnectionFailure {\n if (!(error instanceof HttpError)) {\n return 'unreachable';\n }\n if (error.status === 403 && mentionsUnknownTenant(error.message)) {\n return 'tenant-unknown';\n }\n if (error.status === 401 || error.status === 403) {\n return 'rejected';\n }\n return 'server-error';\n}\n\n/**\n * Re-stamp the Authorization header on every request from a browser login.\n *\n * The SDK's `accessToken` option is inert here \u2014 the spec declares no bearer\n * scheme, so the generator emitted nothing that reads it \u2014 so the token goes in\n * as a plain header, and a header fixed at construction goes stale.\n */\nfunction freshTokenMiddleware(): farseer.Middleware {\n return {\n async pre({ url, init }) {\n const accessToken = await getFreshAccessToken();\n if (!accessToken) {\n // Nothing to mint; let it go out as built and fail on its own terms.\n return { url, init };\n }\n return {\n url,\n init: { ...init, headers: { ...init.headers, Authorization: `Bearer ${accessToken}` } },\n };\n },\n };\n}\n\n/**\n * The CLI's client, over the SDK. The credential is decided upstream (see\n * ResolvedAuth) and only changes the headers.\n */\nexport class FarseerService {\n private client: farseer.FarseerClient;\n private auth: ResolvedAuth;\n\n constructor(auth: ResolvedAuth) {\n this.auth = auth;\n this.client = new farseer.FarseerClient({\n basePath: basePathOf(auth),\n headers: authHeaders(auth),\n middleware: auth.kind === 'jwt' ? [freshTokenMiddleware()] : [],\n });\n }\n\n /**\n * The SDK client underneath, for the read/query surface that wants it raw.\n *\n * The same instance this class uses, deliberately: a second one would derive\n * the host and headers a second time, and the SDK caches its tag map per\n * instance, so two of them pay for it twice.\n */\n get native(): farseer.FarseerClient {\n return this.client;\n }\n\n /**\n * Is this credential good? Asked of `/organization`, which answers it\n * directly \u2014 401 for a credential the server rejects, 200 otherwise, the\n * same for both kinds. Nothing about the tenant's folders can make a valid\n * credential look invalid.\n *\n * The ways it can fail are not interchangeable: \"log in again\" is useless\n * advice for a dropped connection, and \"your key was rejected\" is worse than\n * useless for a key that works at an organisation without this tenant.\n */\n async checkConnection(): Promise<ConnectionCheck> {\n try {\n await this.getOrganizationInfo();\n return { ok: true };\n } catch (error) {\n return {\n ok: false,\n reason: failureReason(error),\n message: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n async getOrganizationInfo(): Promise<OrganizationInfo> {\n return this.apiRequest<OrganizationInfo>('/organization', 'GET');\n }\n\n async getFilesFolder(): Promise<FolderItem | null> {\n return this.findFolder(['Files']);\n }\n\n /**\n * The folder at `folderPath`, for callers that need its id. Exposed because\n * the SDK's own getItemByPath is not a path lookup \u2014 see findFolder.\n */\n async getFolderByPath(folderPath: string[]): Promise<FolderItem | null> {\n return this.findFolder(folderPath);\n }\n\n /**\n * Every failure throws. An empty list is a claim rather than a shrug:\n * SyncService.checkRemoteChanges derives what was deleted on the server by\n * subtracting this listing from sync state, so `[]` says the tenant was\n * emptied and a mirroring pull acts on it.\n */\n async listFiles(folderPath: string[] = ['Files']): Promise<RemoteFile[]> {\n const folder = await this.requireFolderForListing(folderPath);\n return this.listFilesUnder(folder.id, folderPath);\n }\n\n /**\n * Resolving the root of the walk is the only part that needs a path. Every\n * level below it recurses on the id already present in its parent's\n * listing \u2014 walking the path again per subfolder turned a four-deep tree\n * into fourteen requests where five do.\n */\n private async listFilesUnder(folderId: number, folderPath: string[]): Promise<RemoteFile[]> {\n let items: farseer.FolderItemRepresentation[];\n try {\n const folderContent = await this.client.folders.listItemsBatch([{ id: folderId }]);\n items = folderContent[0]?.items ?? [];\n } catch (error) {\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n\n const files: RemoteFile[] = [];\n\n // Recursion sits outside the read so a failure deeper in the tree keeps\n // its own folder in the message instead of being re-wrapped at each level.\n for (const item of items) {\n const itemPath = [...folderPath.slice(1), item.name].join('/');\n\n if (item.type === farseer.FolderItemType.Folder) {\n const subFiles = await this.listFilesUnder(item.id, [...folderPath, item.name]);\n files.push(...subFiles);\n } else if (item.type === farseer.FolderItemType.FarseerFile && 'reference' in item) {\n files.push({\n name: item.name,\n path: itemPath,\n reference: item.reference as string,\n });\n }\n }\n\n return files;\n }\n\n /** The listing root, with the path kept in the message on failure. */\n private async requireFolderForListing(folderPath: string[]): Promise<FolderItem> {\n try {\n return await this.requireFolder(folderPath);\n } catch (error) {\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n }\n\n async getFileContent(reference: string): Promise<string> {\n const blob = await this.client.farseerFiles.get(reference);\n return await blob.text();\n }\n\n /**\n * Build a WebFile with an explicit Content-Type.\n *\n * When a File-like object is appended to FormData with no `type`, undici\n * (Node's fetch backend) auto-detects MIME from the filename \u2014 `.ts`\n * resolves to `video/mp2t` (MPEG transport stream), a part-level\n * Content-Type that some WAFs and proxies reject. Setting `type` on the\n * outer WebFile is what actually changes the wire bytes; setting it on\n * an inner Blob does NOT propagate to the wrapping WebFile and is a\n * no-op for the eventual multipart serialization.\n */\n private toUploadFile(content: string | Buffer, fileName: string): farseer.WebFile {\n const parts = [content] as BlobPart[];\n return new farseer.WebFile(parts, fileName, { type: 'application/octet-stream' });\n }\n\n async createFile(content: string | Buffer, fileName: string, folderPath: string[] = ['Files']): Promise<void> {\n // Ensure folder structure exists\n await this.ensureFolderPath(folderPath);\n\n const folder = await this.requireFolder(folderPath);\n const file = this.toUploadFile(content, fileName);\n try {\n await this.client.farseerFiles.create(file, 'GENERAL', folder.id.toString());\n } catch (error) {\n // toError preserves the original Response (or Error) as `cause` so\n // fileLogger.serializeError can capture status/url/body into the\n // JSON log \u2014 useful for diagnosing backend 4xx/5xx after the fact.\n throw await toError(error, `Failed to create file \"${fileName}\"`);\n }\n }\n\n async updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void> {\n const file = this.toUploadFile(content, fileName);\n try {\n await this.client.farseerFiles.update(reference, file);\n } catch (error) {\n throw await toError(error, `Failed to update file \"${fileName}\" (ref: ${reference})`);\n }\n }\n\n async deleteFile(reference: string): Promise<void> {\n try {\n await this.client.farseerFiles.remove(reference);\n } catch (error) {\n throw await toError(error, `Failed to delete file (ref: ${reference})`);\n }\n }\n\n async ensureFolderPath(folderPath: string[]): Promise<void> {\n const currentPath: string[] = [];\n\n for (const segment of folderPath) {\n currentPath.push(segment);\n if (!(await this.findFolder(currentPath))) {\n // Folder doesn't exist, create it.\n //\n // `allowedTypes: null` is critical \u2014 DO NOT pass `[]`.\n // Backend semantics (itemNodeService.ts:657-708):\n // \u2022 null \u2192 inherit parent's allowedTypes (Files root is\n // ['FARSEER_FILE', 'FOLDER'], which is what we want).\n // \u2022 [] \u2192 \"nothing allowed\". Subsequent createFile in\n // the new folder fails with HTTP 400 \"Invalid parent \u2014\n // item type 'FARSEER_FILE' is not allowed in this\n // folder (allowed types: )\".\n //\n // The web UI sends `null`, which is why folders created via\n // UI always work. The CLI used to send `[]`, producing a\n // dead-end folder that couldn't host any files. Reproduced\n // on 2026-04-29 against fs-personal/ivan-kikic.\n if (currentPath.length > 1) {\n const parent = await this.requireFolder(currentPath.slice(0, -1));\n await this.client.folders.create({\n parentId: parent.id,\n name: segment,\n allowedTypes: null,\n });\n }\n }\n }\n }\n\n /**\n * The file at `filePath`, or null when there isn't one.\n *\n * Absence is a legitimate answer here \u2014 the path is user-supplied \u2014 but a\n * failed request is not: the one consumer is SyncService.getFileDiff, which\n * would read it as the file having no remote content. `findFolder` keeps the\n * two apart.\n */\n async getFileByPath(filePath: string): Promise<RemoteFile | null> {\n const pathParts = ['Files', ...filePath.split('/')];\n const fileName = pathParts.pop()!;\n\n const folder = await this.findFolder(pathParts);\n if (!folder) {\n return null;\n }\n\n const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);\n const match = (folderContent[0]?.items ?? []).find(\n (item) => item.name === fileName && item.type === farseer.FolderItemType.FarseerFile && 'reference' in item,\n );\n\n return match ? { name: match.name, path: filePath, reference: match.reference as string } : null;\n }\n\n /**\n * The folder at `folderPath`, or null when a segment of it isn't there. Only\n * absence returns null; a failed listing throws.\n *\n * Not the SDK's `getItemByPath`: for a single-segment path it ignores the\n * path entirely and name-searches the whole tenant across folders,\n * dashboards, sheets, dimension tables and variables, capped at 20 results.\n * The match itself is exact, so a near-miss name is harmless \u2014 but a second\n * item named exactly `Files` anywhere in the tenant makes it refuse, and 20\n * prefix matches crowd the real folder off the only page it looks at. A path\n * is a path, so each segment is matched inside its parent's listing.\n */\n private async findFolder(folderPath: string[]): Promise<FolderItem | null> {\n let parentId: number | null = null;\n let found: FolderItem | null = null;\n\n for (const segment of folderPath) {\n const contents = await this.client.folders.listItemsBatch([{ id: parentId }]);\n const folders = (contents[0]?.items ?? []).filter((item) => item.type === farseer.FolderItemType.Folder);\n const match = matchFolderSegment(folders, segment);\n if (!match) {\n return null;\n }\n found = { id: match.id, name: match.name, type: match.type };\n parentId = match.id;\n }\n\n return found;\n }\n\n /** Same walk, for callers that can only proceed if the folder is there. */\n private async requireFolder(folderPath: string[]): Promise<FolderItem> {\n const folder = await this.findFolder(folderPath);\n if (!folder) {\n throw new Error(`Folder not found: ${folderPath.join('/')}`);\n }\n return folder;\n }\n\n async getFileMetadata(reference: string): Promise<FileMetadata | null> {\n try {\n const metadata = await this.client.farseerFiles.getMetadata(reference);\n\n return {\n uploadTime: metadata.uploadTime?.toISOString(),\n uploader: metadata.uploader\n ? {\n id: metadata.uploader.id,\n email: metadata.uploader.email || '',\n firstName: metadata.uploader.firstName || '',\n lastName: metadata.uploader.lastName || '',\n }\n : undefined,\n size: metadata.size,\n };\n } catch (error) {\n // Metadata fetch failed - non-critical, continue without it\n return null;\n }\n }\n\n async getFileContentAsBuffer(reference: string): Promise<Buffer> {\n const blob = await this.client.farseerFiles.get(reference);\n const arrayBuffer = await blob.arrayBuffer();\n return Buffer.from(arrayBuffer);\n }\n\n // ==================== Apps (Remote Jobs) API ====================\n\n /**\n * List all apps (Remote Jobs) on the tenant\n */\n async listApps(): Promise<AppListItem[]> {\n const response = await this.client.remoteJobs.list();\n return response.map((app) => ({\n name: app.name,\n type: REMOTE_JOB_ITEM_TYPE,\n reference: String(app.id),\n }));\n }\n\n /**\n * Get app details by reference ID\n */\n async getApp(referenceId: string): Promise<RemoteApp | null> {\n try {\n const app = await this.apiRequest<RemoteApp>(`/remoteJobs/${referenceId}`, 'GET');\n\n // scriptFiles is a legacy field no longer populated by the backend.\n // Resolve scripts from the source folder instead.\n if (app && (!app.scriptFiles || app.scriptFiles.length === 0) && app.sourceFolderId) {\n app.scriptFiles = await this.resolveAppScripts(app.sourceFolderId);\n }\n\n return app;\n } catch (error) {\n // A 404 means the app is gone, which is an answer. Anything else\n // means we could not ask \u2014 and AppSyncService drops an app it cannot\n // see, so reporting that as absence quietly changes what syncs.\n if (error instanceof HttpError && error.status === 404) {\n return null;\n }\n throw await toError(error, `Failed to load app ${referenceId}`);\n }\n }\n\n /**\n * Resolve script files from an app's source folder\n */\n private async resolveAppScripts(sourceFolderId: number): Promise<{ id: string; name: string }[]> {\n try {\n const folderContent = await this.client.folders.listItemsBatch([{ id: sourceFolderId }]);\n return (folderContent[0]?.items || [])\n .filter((item) => item.type === farseer.FolderItemType.FarseerFile && 'reference' in item)\n .map((item) => ({ id: item.reference as string, name: item.name }));\n } catch (error) {\n // Gone (404) is an answer about the folder; nothing else is. A 403\n // is deliberately NOT swallowed: the backend also returns it when\n // the caller lacks the tenant-wide GET_ITEMS_BATCH permission, which\n // says nothing about this folder, and \"I may not look\" is not \"there\n // are no scripts\" either way. The empty list reaches AppSyncService\n // as `entrypoint: null` and pull saves that over the local app, so\n // guessing here silently rewrites the user's config. The SDK throws\n // the raw Response, so the status is read off the thrown value.\n const status = (error as { status?: unknown } | null)?.status;\n if (status === 404) {\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Null means the folder is not there. A failed request throws, so a caller\n * reporting \"no such folder\" cannot say it about a 500 or a dropped\n * connection.\n */\n async resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution | null> {\n const segments = relativePath\n .split('/')\n .map((s) => s.trim())\n .filter(Boolean);\n const folder = await this.findFolder(['Files', ...segments]);\n if (!folder) {\n return null;\n }\n const scripts = await this.resolveAppScripts(folder.id);\n return { id: folder.id, scripts };\n }\n\n /**\n * Create a new app\n */\n async createApp(name: string): Promise<RemoteApp> {\n // Get Apps folder ID first\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n throw new Error('Apps folder not found');\n }\n\n return await this.apiRequest<RemoteApp>('/remoteJobs', 'POST', {\n folderId: appsFolderId,\n name,\n });\n }\n\n /**\n * Update an app\n */\n async updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp> {\n // The PUT replaces the whole record, so merge the changes onto currentApp.\n await this.apiRequest(`/remoteJobs/${referenceId}`, 'PUT', mergeAppUpdate(currentApp, update));\n // API returns 204 No Content, so fetch the updated app.\n const app = await this.getApp(referenceId);\n if (!app) {\n throw new Error(`Failed to fetch updated app ${referenceId}`);\n }\n return app;\n }\n\n async getRunnerImageRepositories(): Promise<RunnerImageRepositories> {\n const response = await this.apiRequest<RunnerImageRepositories>('/remoteJobs/runnerImages', 'GET');\n return {\n registryPrefix: response?.registryPrefix ?? '',\n repositories: response?.repositories ?? [],\n };\n }\n\n async getRunners(): Promise<ConnectedRunner[]> {\n const response = await this.apiRequest<{ runners?: ConnectedRunner[] }>('/remoteJobs/runners', 'GET');\n return response?.runners ?? [];\n }\n\n // Never swallow a failure into an empty array: `resolveAppItemNodeId` reads\n // \"no match\" as \"this app doesn't exist\".\n private async resolveRemoteJobItems(remoteJobIds: readonly string[]): Promise<ResolvedFolderItem[]> {\n if (remoteJobIds.length === 0) {\n return [];\n }\n try {\n return await this.client.folders.resolveItems(remoteJobReverseReferences(remoteJobIds));\n } catch (error) {\n throw await toError(error, `Failed to resolve folder items for Remote Job(s): ${remoteJobIds.join(', ')}`);\n }\n }\n\n // Takes the Remote Job id and resolves the folder-item id itself, so no\n // caller can hand this a raw node id. See `resolveAppItemNodeId`.\n async deleteApp(remoteJobId: string): Promise<void> {\n const items = await this.resolveRemoteJobItems([remoteJobId]);\n const itemNodeId = resolveAppItemNodeId(remoteJobId, items);\n try {\n // remoteJobs has no DELETE, so apps go through the folder API.\n await this.client.folders.deleteItemsBatch([{ id: itemNodeId }]);\n } catch (error) {\n throw await toError(error, `Failed to delete app (Remote Job id: ${remoteJobId})`);\n }\n }\n\n /**\n * Get script files available for apps\n */\n async getScriptFiles(): Promise<{ id: string; name: string }[]> {\n const allFiles = await this.listFiles(['Files']);\n return allFiles\n .filter((f) => f.name.endsWith('.ts') || f.name.endsWith('.js'))\n .map((f) => ({\n id: f.reference,\n name: f.path, // Full path, not the file name: scripts live in subfolders.\n }));\n }\n\n /**\n * Export the entire model structure.\n * Tries the generated API first, falls back to initTagMap() for older server versions.\n */\n async exportModel(options: ModelExportOptions = {}): Promise<ModelExport> {\n // Default scope: tables + variables, no member rows. Pulling\n // the full member matrix is what makes the call hang on\n // larger tenants \u2014 once the response crosses the Cloud Run /\n // proxy limit the connection drops mid-flight and the client\n // sees \"socket hang up\". Callers that actually need members\n // pass { types: ['DTAB','DMEM'], tableGids: [...] }.\n const requestedTypes = options.types ?? ['DTAB', 'VAR'];\n const apiTypes = requestedTypes\n .map((t) => {\n if (t === 'DTAB') return farseer.ModelObjectType.DIMENSION_TABLE;\n if (t === 'DMEM') return farseer.ModelObjectType.DIMENSION_MEMBER;\n if (t === 'VAR') return farseer.ModelObjectType.VARIABLE;\n return undefined;\n })\n .filter((t): t is farseer.ModelObjectType => t !== undefined);\n\n try {\n const result = await this.client.model.exportModel({\n types: apiTypes,\n tableGids: options.tableGids,\n variableGids: options.variableGids,\n });\n return this.mapModelRepresentationToExport(result);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger.dim(`/model/export failed (${message}); falling back to initTagMap.`);\n return this.buildModelFromTagMaps(options);\n }\n }\n\n private mapModelRepresentationToExport(result: farseer.ModelRepresentation): ModelExport {\n // The server actually responds with `ExportModelRepresentation`,\n // which carries `gid` per table/variable. The generated client\n // schema strips it (the OpenAPI spec uses `ModelRepresentation`\n // for the response type instead of `ExportModelRepresentation`),\n // so we read it back through a cast \u2014 needed by `dimension\n // details` to scope a follow-up DMEM fetch.\n //\n // TODO(cli): durable fix is to update the OpenAPI spec\n // (`backend/app/openapi/v3/documentation/model/export.yaml`)\n // to declare `ExportModelRepresentation` and regenerate\n // farseer-client. Tactical cast is fine for now.\n return {\n tables: result.tables.map((t) => ({\n gid: (t as unknown as { gid?: number }).gid,\n name: t.name,\n columns: t.columns.map((c) => ({\n name: c.name,\n type: c.type,\n foreignKeyTableName: c.foreignKeyTableName,\n })),\n rows: t.rows,\n defaultMember: t.defaultMember,\n folderPath: t.folderPath,\n autoIncrementTemplate: t.autoIncrementTemplate,\n })),\n variables: result.variables.map((v) => ({\n gid: (v as unknown as { gid?: number }).gid,\n name: v.name,\n description: v.description,\n // `model export --json` is documented as the raw export, and the\n // browser-login client used to hand it back unmapped.\n notes: v.notes,\n formula: v.formula,\n tables: v.tables,\n members: v.members ?? [],\n rollupType: v.rollupType,\n dataType: v.dataType,\n numberFormat: v.numberFormat as ModelExportVariable['numberFormat'],\n numberValidation: v.numberValidation as ModelExportVariable['numberValidation'],\n topDownMapping: v.topDownMapping,\n readonly: v.readonly,\n calculateOnDemand: v.calculateOnDemand,\n zConstraint: v.zConstraint,\n active: v.active,\n optimizeCalculation: v.optimizeCalculation,\n useHierarchy: v.useHierarchy,\n folderPath: v.folderPath,\n })),\n dependencies: result.dependencies ?? { tables: [], members: [], variables: [] },\n };\n }\n\n /**\n * Scoped through the entities API rather than `exportModel({ tableGids })`,\n * which 500s for some tables on large tenants.\n */\n async loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null> {\n return loadDimensionTableViaEntitiesApi(this.client, name);\n }\n\n private async buildModelFromTagMaps(options: ModelExportOptions = {}): Promise<ModelExport> {\n const types = options.types ?? ['DTAB', 'VAR'];\n const wantTables = types.includes('DTAB');\n const wantMembers = types.includes('DMEM');\n const wantVariables = types.includes('VAR');\n\n let tagMaps: farseer.TagMaps;\n try {\n tagMaps = await this.client.initTagMap();\n } catch (err: any) {\n if (err && typeof err.status === 'number' && typeof err.url === 'string') {\n const text = typeof err.text === 'function' ? await err.text().catch(() => '') : '';\n throw new Error(`initTagMap failed: HTTP ${err.status} ${text}`.trim());\n }\n throw err;\n }\n\n // initTagMap unconditionally pulls all three entity types from\n // the server, so this fallback can't avoid the wire cost the\n // way `/model/export` can. Respect `options` on the way out so\n // the shape matches the primary path.\n const tables: ModelExportTable[] = [];\n if (wantTables) {\n const tableGidFilter =\n options.tableGids && options.tableGids.length > 0 ? new Set(options.tableGids) : null;\n for (const [name, tag] of tagMaps.dimensionTableMapByName) {\n if (tableGidFilter && !tableGidFilter.has(tag.id)) continue;\n const members = wantMembers ? tagMaps.dimensionMemberMapsByTableId.get(tag.id) : undefined;\n tables.push({\n gid: tag.id,\n name,\n columns:\n tag.columns?.map((c) => ({\n name: c.name,\n type: c.foreignKey ? 'FOREIGN_KEY' : c.primaryKey ? 'PRIMARY_KEY' : String(c.type),\n foreignKeyTableName: c.foreignKey ? tagMaps.mapById.get(c.refTableGid)?.name : undefined,\n })) ?? [],\n rows: members ? Array.from(members.values()).map((m) => [m.name]) : [],\n });\n }\n }\n\n const variables: ModelExportVariable[] = [];\n if (wantVariables) {\n const variableGidFilter =\n options.variableGids && options.variableGids.length > 0 ? new Set(options.variableGids) : null;\n for (const [name, tag] of tagMaps.variableMapByName) {\n if (variableGidFilter && !variableGidFilter.has(tag.id)) continue;\n const dimNames = (tag.dimensionTagIds ?? [])\n .map((id) => tagMaps.mapById.get(id)?.name)\n .filter((n): n is string => Boolean(n));\n variables.push({\n gid: tag.id,\n name,\n tables: dimNames,\n members: [],\n rollupType: tag.rollupType ?? 'SUM',\n dataType: tag.dataType ?? 'DECIMAL',\n readonly: tag.readonly ?? false,\n calculateOnDemand: tag.calculateOnDemand ?? false,\n formula: tag.expression ?? null,\n description: tag.description ?? null,\n });\n }\n }\n\n return { tables, variables, dependencies: { tables: [], members: [], variables: [] } };\n }\n\n /**\n * Get the Apps folder ID\n */\n private async getAppsFolderId(): Promise<number | null> {\n return (await this.findFolder(['Apps']))?.id ?? null;\n }\n\n /**\n * Make a direct API request (for endpoints not in farseer-client)\n */\n private async apiRequest<T>(\n endpoint: string,\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n body?: unknown,\n ): Promise<T> {\n const url = `${basePathOf(this.auth)}${endpoint}`;\n\n // This path bypasses the SDK, so the middleware's refresh never runs.\n const auth: ResolvedAuth =\n this.auth.kind === 'jwt'\n ? { ...this.auth, accessToken: (await getFreshAccessToken()) ?? this.auth.accessToken }\n : this.auth;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n // The SDK stamps this from its own generated constant, and these\n // requests have to agree with it. Deep path because the package root\n // re-exports the models but not API_VERSION.\n 'x-api-version': API_VERSION,\n ...authHeaders(auth),\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n throw new HttpError(response.status, `HTTP ${response.status}: ${await response.text()}`);\n }\n\n if (response.status === 204) {\n return undefined as unknown as T;\n }\n\n return response.json() as Promise<T>;\n }\n}\n\n/**\n * Resolve realm name by checking if it exists on Keycloak.\n * Tries the provided name first, then uppercase variant.\n * Returns the resolved realm name or null if not found.\n */\nexport async function resolveRealm(realm: string): Promise<string | null> {\n const candidates = [realm];\n const upper = realm.toUpperCase();\n if (upper !== realm) {\n candidates.push(upper);\n }\n const lower = realm.toLowerCase();\n if (lower !== realm && lower !== upper) {\n candidates.push(lower);\n }\n\n for (const candidate of candidates) {\n try {\n const response = await fetch(`https://login.farseer.io/auth/realms/${candidate}`, { method: 'GET' });\n if (response.ok) {\n return candidate;\n }\n } catch {\n // Network error, continue to next candidate\n }\n }\n\n return null;\n}\n\nfunction getErrorPage(title: string, message: string): string {\n return `\n <html>\n <head>\n <title>Farseer CLI - Error</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #fafafa;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .container {\n text-align: center;\n padding: 48px;\n }\n .error-icon {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .error-icon svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n fill: none;\n }\n h1 {\n color: #18181b;\n font-size: 24px;\n font-weight: 600;\n margin-bottom: 8px;\n }\n p {\n color: #71717a;\n font-size: 15px;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"error-icon\">\n <svg viewBox=\"0 0 24 24\">\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line>\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>\n </svg>\n </div>\n <h1>${title}</h1>\n <p>${message}</p>\n <p style=\"margin-top: 16px;\">You can close this window.</p>\n </div>\n </body>\n </html>\n `;\n}\n\n// Browser-based OAuth login with PKCE\nexport async function loginWithBrowser(realm: string = 'master'): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresIn: number;\n} | null> {\n const http = await import('http');\n const crypto = await import('crypto');\n const { exec } = await import('child_process');\n const { promisify } = await import('util');\n const execAsync = promisify(exec);\n\n const KEYCLOAK_BASE = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect`;\n const CLIENT_ID = 'auth'; // Use auth client with full scope access\n const REDIRECT_PORT = 8787;\n const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`;\n\n // Generate PKCE code verifier and challenge\n const codeVerifier = crypto.randomBytes(32).toString('base64url');\n const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');\n\n // Generate state for CSRF protection\n const state = crypto.randomBytes(16).toString('hex');\n\n return new Promise((resolve) => {\n const server = http.createServer(async (req, res) => {\n const url = new URL(req.url || '', `http://localhost:${REDIRECT_PORT}`);\n\n if (url.pathname === '/callback') {\n const code = url.searchParams.get('code');\n const returnedState = url.searchParams.get('state');\n const error = url.searchParams.get('error');\n\n if (error) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Login Failed', `Error: ${error}`));\n server.close();\n resolve(null);\n return;\n }\n\n if (!code || returnedState !== state) {\n res.writeHead(400, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Invalid Response', 'Missing code or state mismatch.'));\n server.close();\n resolve(null);\n return;\n }\n\n // Exchange code for tokens\n try {\n const tokenResponse = await fetch(`${KEYCLOAK_BASE}/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: CLIENT_ID,\n code: code,\n redirect_uri: REDIRECT_URI,\n code_verifier: codeVerifier,\n }),\n });\n\n if (!tokenResponse.ok) {\n throw new Error('Token exchange failed');\n }\n\n const data = (await tokenResponse.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <head>\n <title>Farseer CLI - Login</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #fafafa;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .container {\n text-align: center;\n padding: 48px;\n }\n .checkmark {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n animation: scale-in 0.3s ease-out;\n }\n .checkmark svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n fill: none;\n animation: draw 0.4s ease-out 0.2s forwards;\n stroke-dasharray: 50;\n stroke-dashoffset: 50;\n }\n @keyframes scale-in {\n from { transform: scale(0); }\n to { transform: scale(1); }\n }\n @keyframes draw {\n to { stroke-dashoffset: 0; }\n }\n h1 {\n color: #18181b;\n font-size: 24px;\n font-weight: 600;\n margin-bottom: 8px;\n }\n p {\n color: #71717a;\n font-size: 15px;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"checkmark\">\n <svg viewBox=\"0 0 24 24\">\n <polyline points=\"20 6 9 17 4 12\"></polyline>\n </svg>\n </div>\n <h1>Login Successful</h1>\n <p>You can close this window and return to the terminal.</p>\n </div>\n </body>\n </html>\n `);\n\n server.close();\n resolve({\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresIn: data.expires_in,\n });\n } catch {\n res.writeHead(500, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Token Exchange Failed', 'Could not complete login.'));\n server.close();\n resolve(null);\n }\n }\n });\n\n server.listen(REDIRECT_PORT, async () => {\n // Build authorization URL\n const authUrl = new URL(`${KEYCLOAK_BASE}/auth`);\n authUrl.searchParams.set('client_id', CLIENT_ID);\n authUrl.searchParams.set('redirect_uri', REDIRECT_URI);\n authUrl.searchParams.set('response_type', 'code');\n authUrl.searchParams.set('scope', 'openid offline_access');\n authUrl.searchParams.set('state', state);\n authUrl.searchParams.set('code_challenge', codeChallenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n\n // Open browser\n const url = authUrl.toString();\n try {\n if (process.platform === 'darwin') {\n await execAsync(`open \"${url}\"`);\n } else if (process.platform === 'win32') {\n await execAsync(`start \"${url}\"`);\n } else {\n await execAsync(`xdg-open \"${url}\"`);\n }\n } catch {\n // If we can't open browser, show URL to user\n console.log(`\\nOpen this URL in your browser:\\n${url}\\n`);\n }\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n server.close();\n resolve(null);\n },\n 5 * 60 * 1000,\n );\n });\n}\n\nlet refreshInFlight: Promise<string | null> | null = null;\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 *\n * One refresh at a time. Requests run 15-wide (fetchWithConcurrency) and the\n * middleware asks for a token on every one of them, so without coalescing a\n * single expiry spends the same refresh token fifteen times \u2014 and on a realm\n * that rotates refresh tokens, fourteen of those lose.\n */\nexport function getFreshAccessToken(): Promise<string | null> {\n return (refreshInFlight ??= mintAccessToken().finally(() => {\n refreshInFlight = null;\n }));\n}\n\nasync function mintAccessToken(): Promise<string | null> {\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n if (isUserAuthValid(auth)) {\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 async function refreshAccessToken(\n refreshToken: string,\n realm: string = 'master',\n): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresIn: number;\n} | null> {\n const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;\n\n try {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: 'auth',\n refresh_token: refreshToken,\n }),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const data = (await response.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresIn: data.expires_in,\n };\n } catch {\n return null;\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAAyB;AACzB,wBAA4B;AAC5B,2BAA0D;AAE1D,kBAYO;AACP,yBAMO;AACP,4BAAwB;AACxB,yBAAmC;AACnC,uBAA0B;AAC1B,wBAAsC;AACtC,oBAAuB;AAkEhB,SAAS,WAAW,MAA4B;AACnD,SAAO,KAAK,SAAS,QAAQ,KAAK,WAAW,KAAK,WAAW;AACjE;AAEA,SAAS,YAAY,MAA4C;AAC7D,SAAO,KAAK,SAAS,QACf,EAAE,eAAe,KAAK,QAAQ,eAAe,UAAU,KAAK,WAAW,GAAG,IAC1E,EAAE,eAAe,KAAK,WAAW,UAAU,aAAa,KAAK,WAAW,OAAO;AACzF;AAOA,SAAS,cAAc,OAAmC;AACtD,MAAI,EAAE,iBAAiB,6BAAY;AAC/B,WAAO;AAAA,EACX;AACA,MAAI,MAAM,WAAW,WAAO,yCAAsB,MAAM,OAAO,GAAG;AAC9D,WAAO;AAAA,EACX;AACA,MAAI,MAAM,WAAW,OAAO,MAAM,WAAW,KAAK;AAC9C,WAAO;AAAA,EACX;AACA,SAAO;AACX;AASA,SAAS,uBAA2C;AAChD,SAAO;AAAA,IACH,MAAM,IAAI,EAAE,KAAK,KAAK,GAAG;AACrB,YAAM,cAAc,MAAM,oBAAoB;AAC9C,UAAI,CAAC,aAAa;AAEd,eAAO,EAAE,KAAK,KAAK;AAAA,MACvB;AACA,aAAO;AAAA,QACH;AAAA,QACA,MAAM,EAAE,GAAG,MAAM,SAAS,EAAE,GAAG,KAAK,SAAS,eAAe,UAAU,WAAW,GAAG,EAAE;AAAA,MAC1F;AAAA,IACJ;AAAA,EACJ;AACJ;AAMO,MAAM,eAAe;AAAA,EAIxB,YAAY,MAA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AK,cAAc,KAAK,SAAS,QAAQ;AACpF,MAAI,CAAC,WAAW;AACZ,WAAO;AAAA,EACX;AACA,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;AACD,uBAAO,IAAI,iBAAiB;AAC5B,SAAO,UAAU;AACrB;AAEA,eAAsB,mBAClB,cACA,QAAgB,UAKV;AACN,QAAM,WAAW,wCAAwC,KAAK;AAE9D,MAAI;AACA,UAAM,WAAW,MAAM,MAAM,UAAU;AAAA,MACnC,QAAQ;AAAA,MACR,SAAS;AAAA,QACL,gBAAgB;AAAA,MACpB;AAAA,MACA,MAAM,IAAI,gBAAgB;AAAA,QACtB,YAAY;AAAA,QACZ,WAAW;AAAA,QACX,eAAe;AAAA,MACnB,CAAC;AAAA,IACL,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AACd,aAAO;AAAA,IACX;AAEA,UAAM,OAAQ,MAAM,SAAS,KAAK;AAKlC,WAAO;AAAA,MACH,aAAa,KAAK;AAAA,MAClB,cAAc,KAAK;AAAA,MACnB,WAAW,KAAK;AAAA,IACpB;AAAA,EACJ,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;",
|
|
4
|
+
"sourcesContent": ["import * as farseer from 'farseer-client';\nimport { API_VERSION } from 'farseer-client/dist/generated/apiVersion';\nimport { DEFAULT_REALM, getUserAuth, setUserAuth, isUserAuthValid } from './configService';\nimport type { ApiKeyCredential } from './configService';\nimport {\n AppListItem,\n AppUpdateChanges,\n ConnectedRunner,\n REMOTE_JOB_ITEM_TYPE,\n RemoteApp,\n ResolvedFolderItem,\n RunnerImageRepositories,\n SourceFolderResolution,\n mergeAppUpdate,\n remoteJobReverseReferences,\n resolveAppItemNodeId,\n} from './apps';\nimport {\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n ModelExportVariable,\n loadDimensionTableViaEntitiesApi,\n} from './modelExport';\nimport { toError } from '../utils/errorFormatter';\nimport { matchFolderSegment } from '../utils/folderMatch';\nimport { HttpError } from './httpError';\nimport { mentionsUnknownTenant } from './authErrors';\nimport { logger } from '../utils/logger';\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\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// 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; realm: string }\n | { kind: 'apiKey'; credential: ApiKeyCredential };\n\n/**\n * Why a credential probe failed. Four reasons rather than two because the advice\n * differs for each: a rejected credential means replace it, an unknown tenant\n * means the organisation is wrong and the credential is fine, a server error\n * means the host answered and nothing is wrong locally, and unreachable means\n * nothing answered at all.\n */\nexport type ConnectionFailure = 'rejected' | 'tenant-unknown' | 'server-error' | 'unreachable';\n\nexport type ConnectionCheck = { ok: true } | { ok: false; reason: ConnectionFailure; message: string };\n\nexport interface FolderItem {\n id: number;\n name: string;\n type: string;\n reference?: string;\n}\n\n/** Where a credential's requests go, and who they say they are. */\nexport function basePathOf(auth: ResolvedAuth): string {\n return auth.kind === 'jwt' ? auth.basePath : auth.credential.basePath;\n}\n\nfunction authHeaders(auth: ResolvedAuth): Record<string, string> {\n return auth.kind === 'jwt'\n ? { 'X-TENANT-ID': auth.tenant, Authorization: `Bearer ${auth.accessToken}` }\n : { 'X-TENANT-ID': auth.credential.tenantId, 'X-API-KEY': auth.credential.apiKey };\n}\n\n/**\n * Which of the four failures a thrown probe error is. A 403 is read two ways:\n * the backend answers it both for a credential it will not accept and for a\n * tenant the organisation does not have, and only the body tells them apart.\n */\nfunction failureReason(error: unknown): ConnectionFailure {\n if (!(error instanceof HttpError)) {\n return 'unreachable';\n }\n if (error.status === 403 && mentionsUnknownTenant(error.message)) {\n return 'tenant-unknown';\n }\n if (error.status === 401 || error.status === 403) {\n return 'rejected';\n }\n return 'server-error';\n}\n\n/**\n * Re-stamp the Authorization header on every request from a browser login.\n *\n * The SDK's `accessToken` option is inert here \u2014 the spec declares no bearer\n * scheme, so the generator emitted nothing that reads it \u2014 so the token goes in\n * as a plain header, and a header fixed at construction goes stale.\n */\nfunction freshTokenMiddleware(realm: string): farseer.Middleware {\n return {\n async pre({ url, init }) {\n const accessToken = await getFreshAccessToken(realm);\n if (!accessToken) {\n // Nothing to mint; let it go out as built and fail on its own terms.\n return { url, init };\n }\n return {\n url,\n init: { ...init, headers: { ...init.headers, Authorization: `Bearer ${accessToken}` } },\n };\n },\n };\n}\n\n/**\n * The CLI's client, over the SDK. The credential is decided upstream (see\n * ResolvedAuth) and only changes the headers.\n */\nexport class FarseerService {\n private client: farseer.FarseerClient;\n private auth: ResolvedAuth;\n\n constructor(auth: ResolvedAuth) {\n this.auth = auth;\n this.client = new farseer.FarseerClient({\n basePath: basePathOf(auth),\n headers: authHeaders(auth),\n middleware: auth.kind === 'jwt' ? [freshTokenMiddleware(auth.realm)] : [],\n });\n }\n\n /**\n * The SDK client underneath, for the read/query surface that wants it raw.\n *\n * The same instance this class uses, deliberately: a second one would derive\n * the host and headers a second time, and the SDK caches its tag map per\n * instance, so two of them pay for it twice.\n */\n get native(): farseer.FarseerClient {\n return this.client;\n }\n\n /**\n * Is this credential good? Asked of `/organization`, which answers it\n * directly \u2014 401 for a credential the server rejects, 200 otherwise, the\n * same for both kinds. Nothing about the tenant's folders can make a valid\n * credential look invalid.\n *\n * The ways it can fail are not interchangeable: \"log in again\" is useless\n * advice for a dropped connection, and \"your key was rejected\" is worse than\n * useless for a key that works at an organisation without this tenant.\n */\n async checkConnection(): Promise<ConnectionCheck> {\n try {\n await this.getOrganizationInfo();\n return { ok: true };\n } catch (error) {\n return {\n ok: false,\n reason: failureReason(error),\n message: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n async getOrganizationInfo(): Promise<OrganizationInfo> {\n return this.apiRequest<OrganizationInfo>('/organization', 'GET');\n }\n\n async getFilesFolder(): Promise<FolderItem | null> {\n return this.findFolder(['Files']);\n }\n\n /**\n * The folder at `folderPath`, for callers that need its id. Exposed because\n * the SDK's own getItemByPath is not a path lookup \u2014 see findFolder.\n */\n async getFolderByPath(folderPath: string[]): Promise<FolderItem | null> {\n return this.findFolder(folderPath);\n }\n\n /**\n * Every failure throws. An empty list is a claim rather than a shrug:\n * SyncService.checkRemoteChanges derives what was deleted on the server by\n * subtracting this listing from sync state, so `[]` says the tenant was\n * emptied and a mirroring pull acts on it.\n */\n async listFiles(folderPath: string[] = ['Files']): Promise<RemoteFile[]> {\n const folder = await this.requireFolderForListing(folderPath);\n return this.listFilesUnder(folder.id, folderPath);\n }\n\n /**\n * Resolving the root of the walk is the only part that needs a path. Every\n * level below it recurses on the id already present in its parent's\n * listing \u2014 walking the path again per subfolder turned a four-deep tree\n * into fourteen requests where five do.\n */\n private async listFilesUnder(folderId: number, folderPath: string[]): Promise<RemoteFile[]> {\n let items: farseer.FolderItemRepresentation[];\n try {\n const folderContent = await this.client.folders.listItemsBatch([{ id: folderId }]);\n items = folderContent[0]?.items ?? [];\n } catch (error) {\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n\n const files: RemoteFile[] = [];\n\n // Recursion sits outside the read so a failure deeper in the tree keeps\n // its own folder in the message instead of being re-wrapped at each level.\n for (const item of items) {\n const itemPath = [...folderPath.slice(1), item.name].join('/');\n\n if (item.type === farseer.FolderItemType.Folder) {\n const subFiles = await this.listFilesUnder(item.id, [...folderPath, item.name]);\n files.push(...subFiles);\n } else if (item.type === farseer.FolderItemType.FarseerFile && 'reference' in item) {\n files.push({\n name: item.name,\n path: itemPath,\n reference: item.reference as string,\n });\n }\n }\n\n return files;\n }\n\n /** The listing root, with the path kept in the message on failure. */\n private async requireFolderForListing(folderPath: string[]): Promise<FolderItem> {\n try {\n return await this.requireFolder(folderPath);\n } catch (error) {\n throw await toError(error, `Failed to list files in ${folderPath.join('/') || 'root'}`);\n }\n }\n\n async getFileContent(reference: string): Promise<string> {\n const blob = await this.client.farseerFiles.get(reference);\n return await blob.text();\n }\n\n /**\n * Build a WebFile with an explicit Content-Type.\n *\n * When a File-like object is appended to FormData with no `type`, undici\n * (Node's fetch backend) auto-detects MIME from the filename \u2014 `.ts`\n * resolves to `video/mp2t` (MPEG transport stream), a part-level\n * Content-Type that some WAFs and proxies reject. Setting `type` on the\n * outer WebFile is what actually changes the wire bytes; setting it on\n * an inner Blob does NOT propagate to the wrapping WebFile and is a\n * no-op for the eventual multipart serialization.\n */\n private toUploadFile(content: string | Buffer, fileName: string): farseer.WebFile {\n const parts = [content] as BlobPart[];\n return new farseer.WebFile(parts, fileName, { type: 'application/octet-stream' });\n }\n\n async createFile(content: string | Buffer, fileName: string, folderPath: string[] = ['Files']): Promise<void> {\n // Ensure folder structure exists\n await this.ensureFolderPath(folderPath);\n\n const folder = await this.requireFolder(folderPath);\n const file = this.toUploadFile(content, fileName);\n try {\n await this.client.farseerFiles.create(file, 'GENERAL', folder.id.toString());\n } catch (error) {\n // toError preserves the original Response (or Error) as `cause` so\n // fileLogger.serializeError can capture status/url/body into the\n // JSON log \u2014 useful for diagnosing backend 4xx/5xx after the fact.\n throw await toError(error, `Failed to create file \"${fileName}\"`);\n }\n }\n\n async updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void> {\n const file = this.toUploadFile(content, fileName);\n try {\n await this.client.farseerFiles.update(reference, file);\n } catch (error) {\n throw await toError(error, `Failed to update file \"${fileName}\" (ref: ${reference})`);\n }\n }\n\n async deleteFile(reference: string): Promise<void> {\n try {\n await this.client.farseerFiles.remove(reference);\n } catch (error) {\n throw await toError(error, `Failed to delete file (ref: ${reference})`);\n }\n }\n\n async ensureFolderPath(folderPath: string[]): Promise<void> {\n const currentPath: string[] = [];\n\n for (const segment of folderPath) {\n currentPath.push(segment);\n if (!(await this.findFolder(currentPath))) {\n // Folder doesn't exist, create it.\n //\n // `allowedTypes: null` is critical \u2014 DO NOT pass `[]`.\n // Backend semantics (itemNodeService.ts:657-708):\n // \u2022 null \u2192 inherit parent's allowedTypes (Files root is\n // ['FARSEER_FILE', 'FOLDER'], which is what we want).\n // \u2022 [] \u2192 \"nothing allowed\". Subsequent createFile in\n // the new folder fails with HTTP 400 \"Invalid parent \u2014\n // item type 'FARSEER_FILE' is not allowed in this\n // folder (allowed types: )\".\n //\n // The web UI sends `null`, which is why folders created via\n // UI always work. The CLI used to send `[]`, producing a\n // dead-end folder that couldn't host any files. Reproduced\n // on 2026-04-29 against fs-personal/ivan-kikic.\n if (currentPath.length > 1) {\n const parent = await this.requireFolder(currentPath.slice(0, -1));\n await this.client.folders.create({\n parentId: parent.id,\n name: segment,\n allowedTypes: null,\n });\n }\n }\n }\n }\n\n /**\n * The file at `filePath`, or null when there isn't one.\n *\n * Absence is a legitimate answer here \u2014 the path is user-supplied \u2014 but a\n * failed request is not: the one consumer is SyncService.getFileDiff, which\n * would read it as the file having no remote content. `findFolder` keeps the\n * two apart.\n */\n async getFileByPath(filePath: string): Promise<RemoteFile | null> {\n const pathParts = ['Files', ...filePath.split('/')];\n const fileName = pathParts.pop()!;\n\n const folder = await this.findFolder(pathParts);\n if (!folder) {\n return null;\n }\n\n const folderContent = await this.client.folders.listItemsBatch([{ id: folder.id }]);\n const match = (folderContent[0]?.items ?? []).find(\n (item) => item.name === fileName && item.type === farseer.FolderItemType.FarseerFile && 'reference' in item,\n );\n\n return match ? { name: match.name, path: filePath, reference: match.reference as string } : null;\n }\n\n /**\n * The folder at `folderPath`, or null when a segment of it isn't there. Only\n * absence returns null; a failed listing throws.\n *\n * Not the SDK's `getItemByPath`: for a single-segment path it ignores the\n * path entirely and name-searches the whole tenant across folders,\n * dashboards, sheets, dimension tables and variables, capped at 20 results.\n * The match itself is exact, so a near-miss name is harmless \u2014 but a second\n * item named exactly `Files` anywhere in the tenant makes it refuse, and 20\n * prefix matches crowd the real folder off the only page it looks at. A path\n * is a path, so each segment is matched inside its parent's listing.\n */\n private async findFolder(folderPath: string[]): Promise<FolderItem | null> {\n let parentId: number | null = null;\n let found: FolderItem | null = null;\n\n for (const segment of folderPath) {\n const contents = await this.client.folders.listItemsBatch([{ id: parentId }]);\n const folders = (contents[0]?.items ?? []).filter((item) => item.type === farseer.FolderItemType.Folder);\n const match = matchFolderSegment(folders, segment);\n if (!match) {\n return null;\n }\n found = { id: match.id, name: match.name, type: match.type };\n parentId = match.id;\n }\n\n return found;\n }\n\n /** Same walk, for callers that can only proceed if the folder is there. */\n private async requireFolder(folderPath: string[]): Promise<FolderItem> {\n const folder = await this.findFolder(folderPath);\n if (!folder) {\n throw new Error(`Folder not found: ${folderPath.join('/')}`);\n }\n return folder;\n }\n\n async getFileMetadata(reference: string): Promise<FileMetadata | null> {\n try {\n const metadata = await this.client.farseerFiles.getMetadata(reference);\n\n return {\n uploadTime: metadata.uploadTime?.toISOString(),\n uploader: metadata.uploader\n ? {\n id: metadata.uploader.id,\n email: metadata.uploader.email || '',\n firstName: metadata.uploader.firstName || '',\n lastName: metadata.uploader.lastName || '',\n }\n : undefined,\n size: metadata.size,\n };\n } catch (error) {\n // Metadata fetch failed - non-critical, continue without it\n return null;\n }\n }\n\n async getFileContentAsBuffer(reference: string): Promise<Buffer> {\n const blob = await this.client.farseerFiles.get(reference);\n const arrayBuffer = await blob.arrayBuffer();\n return Buffer.from(arrayBuffer);\n }\n\n // ==================== Apps (Remote Jobs) API ====================\n\n /**\n * List all apps (Remote Jobs) on the tenant\n */\n async listApps(): Promise<AppListItem[]> {\n const response = await this.client.remoteJobs.list();\n return response.map((app) => ({\n name: app.name,\n type: REMOTE_JOB_ITEM_TYPE,\n reference: String(app.id),\n }));\n }\n\n /**\n * Get app details by reference ID\n */\n async getApp(referenceId: string): Promise<RemoteApp | null> {\n try {\n const app = await this.apiRequest<RemoteApp>(`/remoteJobs/${referenceId}`, 'GET');\n\n // scriptFiles is a legacy field no longer populated by the backend.\n // Resolve scripts from the source folder instead.\n if (app && (!app.scriptFiles || app.scriptFiles.length === 0) && app.sourceFolderId) {\n app.scriptFiles = await this.resolveAppScripts(app.sourceFolderId);\n }\n\n return app;\n } catch (error) {\n // A 404 means the app is gone, which is an answer. Anything else\n // means we could not ask \u2014 and AppSyncService drops an app it cannot\n // see, so reporting that as absence quietly changes what syncs.\n if (error instanceof HttpError && error.status === 404) {\n return null;\n }\n throw await toError(error, `Failed to load app ${referenceId}`);\n }\n }\n\n /**\n * Resolve script files from an app's source folder\n */\n private async resolveAppScripts(sourceFolderId: number): Promise<{ id: string; name: string }[]> {\n try {\n const folderContent = await this.client.folders.listItemsBatch([{ id: sourceFolderId }]);\n return (folderContent[0]?.items || [])\n .filter((item) => item.type === farseer.FolderItemType.FarseerFile && 'reference' in item)\n .map((item) => ({ id: item.reference as string, name: item.name }));\n } catch (error) {\n // Gone (404) is an answer about the folder; nothing else is. A 403\n // is deliberately NOT swallowed: the backend also returns it when\n // the caller lacks the tenant-wide GET_ITEMS_BATCH permission, which\n // says nothing about this folder, and \"I may not look\" is not \"there\n // are no scripts\" either way. The empty list reaches AppSyncService\n // as `entrypoint: null` and pull saves that over the local app, so\n // guessing here silently rewrites the user's config. The SDK throws\n // the raw Response, so the status is read off the thrown value.\n const status = (error as { status?: unknown } | null)?.status;\n if (status === 404) {\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Null means the folder is not there. A failed request throws, so a caller\n * reporting \"no such folder\" cannot say it about a 500 or a dropped\n * connection.\n */\n async resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution | null> {\n const segments = relativePath\n .split('/')\n .map((s) => s.trim())\n .filter(Boolean);\n const folder = await this.findFolder(['Files', ...segments]);\n if (!folder) {\n return null;\n }\n const scripts = await this.resolveAppScripts(folder.id);\n return { id: folder.id, scripts };\n }\n\n /**\n * Create a new app\n */\n async createApp(name: string): Promise<RemoteApp> {\n // Get Apps folder ID first\n const appsFolderId = await this.getAppsFolderId();\n if (!appsFolderId) {\n throw new Error('Apps folder not found');\n }\n\n return await this.apiRequest<RemoteApp>('/remoteJobs', 'POST', {\n folderId: appsFolderId,\n name,\n });\n }\n\n /**\n * Update an app\n */\n async updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp> {\n // The PUT replaces the whole record, so merge the changes onto currentApp.\n await this.apiRequest(`/remoteJobs/${referenceId}`, 'PUT', mergeAppUpdate(currentApp, update));\n // API returns 204 No Content, so fetch the updated app.\n const app = await this.getApp(referenceId);\n if (!app) {\n throw new Error(`Failed to fetch updated app ${referenceId}`);\n }\n return app;\n }\n\n async getRunnerImageRepositories(): Promise<RunnerImageRepositories> {\n const response = await this.apiRequest<RunnerImageRepositories>('/remoteJobs/runnerImages', 'GET');\n return {\n registryPrefix: response?.registryPrefix ?? '',\n repositories: response?.repositories ?? [],\n };\n }\n\n async getRunners(): Promise<ConnectedRunner[]> {\n const response = await this.apiRequest<{ runners?: ConnectedRunner[] }>('/remoteJobs/runners', 'GET');\n return response?.runners ?? [];\n }\n\n // Never swallow a failure into an empty array: `resolveAppItemNodeId` reads\n // \"no match\" as \"this app doesn't exist\".\n private async resolveRemoteJobItems(remoteJobIds: readonly string[]): Promise<ResolvedFolderItem[]> {\n if (remoteJobIds.length === 0) {\n return [];\n }\n try {\n return await this.client.folders.resolveItems(remoteJobReverseReferences(remoteJobIds));\n } catch (error) {\n throw await toError(error, `Failed to resolve folder items for Remote Job(s): ${remoteJobIds.join(', ')}`);\n }\n }\n\n // Takes the Remote Job id and resolves the folder-item id itself, so no\n // caller can hand this a raw node id. See `resolveAppItemNodeId`.\n async deleteApp(remoteJobId: string): Promise<void> {\n const items = await this.resolveRemoteJobItems([remoteJobId]);\n const itemNodeId = resolveAppItemNodeId(remoteJobId, items);\n try {\n // remoteJobs has no DELETE, so apps go through the folder API.\n await this.client.folders.deleteItemsBatch([{ id: itemNodeId }]);\n } catch (error) {\n throw await toError(error, `Failed to delete app (Remote Job id: ${remoteJobId})`);\n }\n }\n\n /**\n * Get script files available for apps\n */\n async getScriptFiles(): Promise<{ id: string; name: string }[]> {\n const allFiles = await this.listFiles(['Files']);\n return allFiles\n .filter((f) => f.name.endsWith('.ts') || f.name.endsWith('.js'))\n .map((f) => ({\n id: f.reference,\n name: f.path, // Full path, not the file name: scripts live in subfolders.\n }));\n }\n\n /**\n * Export the entire model structure.\n * Tries the generated API first, falls back to initTagMap() for older server versions.\n */\n async exportModel(options: ModelExportOptions = {}): Promise<ModelExport> {\n // Default scope: tables + variables, no member rows. Pulling\n // the full member matrix is what makes the call hang on\n // larger tenants \u2014 once the response crosses the Cloud Run /\n // proxy limit the connection drops mid-flight and the client\n // sees \"socket hang up\". Callers that actually need members\n // pass { types: ['DTAB','DMEM'], tableGids: [...] }.\n const requestedTypes = options.types ?? ['DTAB', 'VAR'];\n const apiTypes = requestedTypes\n .map((t) => {\n if (t === 'DTAB') return farseer.ModelObjectType.DIMENSION_TABLE;\n if (t === 'DMEM') return farseer.ModelObjectType.DIMENSION_MEMBER;\n if (t === 'VAR') return farseer.ModelObjectType.VARIABLE;\n return undefined;\n })\n .filter((t): t is farseer.ModelObjectType => t !== undefined);\n\n try {\n const result = await this.client.model.exportModel({\n types: apiTypes,\n tableGids: options.tableGids,\n variableGids: options.variableGids,\n });\n return this.mapModelRepresentationToExport(result);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger.dim(`/model/export failed (${message}); falling back to initTagMap.`);\n return this.buildModelFromTagMaps(options);\n }\n }\n\n private mapModelRepresentationToExport(result: farseer.ModelRepresentation): ModelExport {\n // The server actually responds with `ExportModelRepresentation`,\n // which carries `gid` per table/variable. The generated client\n // schema strips it (the OpenAPI spec uses `ModelRepresentation`\n // for the response type instead of `ExportModelRepresentation`),\n // so we read it back through a cast \u2014 needed by `dimension\n // details` to scope a follow-up DMEM fetch.\n //\n // TODO(cli): durable fix is to update the OpenAPI spec\n // (`backend/app/openapi/v3/documentation/model/export.yaml`)\n // to declare `ExportModelRepresentation` and regenerate\n // farseer-client. Tactical cast is fine for now.\n return {\n tables: result.tables.map((t) => ({\n gid: (t as unknown as { gid?: number }).gid,\n name: t.name,\n columns: t.columns.map((c) => ({\n name: c.name,\n type: c.type,\n foreignKeyTableName: c.foreignKeyTableName,\n })),\n rows: t.rows,\n defaultMember: t.defaultMember,\n folderPath: t.folderPath,\n autoIncrementTemplate: t.autoIncrementTemplate,\n })),\n variables: result.variables.map((v) => ({\n gid: (v as unknown as { gid?: number }).gid,\n name: v.name,\n description: v.description,\n // `model export --json` is documented as the raw export, and the\n // browser-login client used to hand it back unmapped.\n notes: v.notes,\n formula: v.formula,\n tables: v.tables,\n members: v.members ?? [],\n rollupType: v.rollupType,\n dataType: v.dataType,\n numberFormat: v.numberFormat as ModelExportVariable['numberFormat'],\n numberValidation: v.numberValidation as ModelExportVariable['numberValidation'],\n topDownMapping: v.topDownMapping,\n readonly: v.readonly,\n calculateOnDemand: v.calculateOnDemand,\n zConstraint: v.zConstraint,\n active: v.active,\n optimizeCalculation: v.optimizeCalculation,\n useHierarchy: v.useHierarchy,\n folderPath: v.folderPath,\n })),\n dependencies: result.dependencies ?? { tables: [], members: [], variables: [] },\n };\n }\n\n /**\n * Scoped through the entities API rather than `exportModel({ tableGids })`,\n * which 500s for some tables on large tenants.\n */\n async loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null> {\n return loadDimensionTableViaEntitiesApi(this.client, name);\n }\n\n private async buildModelFromTagMaps(options: ModelExportOptions = {}): Promise<ModelExport> {\n const types = options.types ?? ['DTAB', 'VAR'];\n const wantTables = types.includes('DTAB');\n const wantMembers = types.includes('DMEM');\n const wantVariables = types.includes('VAR');\n\n let tagMaps: farseer.TagMaps;\n try {\n tagMaps = await this.client.initTagMap();\n } catch (err: any) {\n if (err && typeof err.status === 'number' && typeof err.url === 'string') {\n const text = typeof err.text === 'function' ? await err.text().catch(() => '') : '';\n throw new Error(`initTagMap failed: HTTP ${err.status} ${text}`.trim());\n }\n throw err;\n }\n\n // initTagMap unconditionally pulls all three entity types from\n // the server, so this fallback can't avoid the wire cost the\n // way `/model/export` can. Respect `options` on the way out so\n // the shape matches the primary path.\n const tables: ModelExportTable[] = [];\n if (wantTables) {\n const tableGidFilter =\n options.tableGids && options.tableGids.length > 0 ? new Set(options.tableGids) : null;\n for (const [name, tag] of tagMaps.dimensionTableMapByName) {\n if (tableGidFilter && !tableGidFilter.has(tag.id)) continue;\n const members = wantMembers ? tagMaps.dimensionMemberMapsByTableId.get(tag.id) : undefined;\n tables.push({\n gid: tag.id,\n name,\n columns:\n tag.columns?.map((c) => ({\n name: c.name,\n type: c.foreignKey ? 'FOREIGN_KEY' : c.primaryKey ? 'PRIMARY_KEY' : String(c.type),\n foreignKeyTableName: c.foreignKey ? tagMaps.mapById.get(c.refTableGid)?.name : undefined,\n })) ?? [],\n rows: members ? Array.from(members.values()).map((m) => [m.name]) : [],\n });\n }\n }\n\n const variables: ModelExportVariable[] = [];\n if (wantVariables) {\n const variableGidFilter =\n options.variableGids && options.variableGids.length > 0 ? new Set(options.variableGids) : null;\n for (const [name, tag] of tagMaps.variableMapByName) {\n if (variableGidFilter && !variableGidFilter.has(tag.id)) continue;\n const dimNames = (tag.dimensionTagIds ?? [])\n .map((id) => tagMaps.mapById.get(id)?.name)\n .filter((n): n is string => Boolean(n));\n variables.push({\n gid: tag.id,\n name,\n tables: dimNames,\n members: [],\n rollupType: tag.rollupType ?? 'SUM',\n dataType: tag.dataType ?? 'DECIMAL',\n readonly: tag.readonly ?? false,\n calculateOnDemand: tag.calculateOnDemand ?? false,\n formula: tag.expression ?? null,\n description: tag.description ?? null,\n });\n }\n }\n\n return { tables, variables, dependencies: { tables: [], members: [], variables: [] } };\n }\n\n /**\n * Get the Apps folder ID\n */\n private async getAppsFolderId(): Promise<number | null> {\n return (await this.findFolder(['Apps']))?.id ?? null;\n }\n\n /**\n * Make a direct API request (for endpoints not in farseer-client)\n */\n private async apiRequest<T>(\n endpoint: string,\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n body?: unknown,\n ): Promise<T> {\n const url = `${basePathOf(this.auth)}${endpoint}`;\n\n // This path bypasses the SDK, so the middleware's refresh never runs.\n const auth: ResolvedAuth =\n this.auth.kind === 'jwt'\n ? { ...this.auth, accessToken: (await getFreshAccessToken(this.auth.realm)) ?? this.auth.accessToken }\n : this.auth;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n // The SDK stamps this from its own generated constant, and these\n // requests have to agree with it. Deep path because the package root\n // re-exports the models but not API_VERSION.\n 'x-api-version': API_VERSION,\n ...authHeaders(auth),\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n throw new HttpError(response.status, `HTTP ${response.status}: ${await response.text()}`);\n }\n\n if (response.status === 204) {\n return undefined as unknown as T;\n }\n\n return response.json() as Promise<T>;\n }\n}\n\n/**\n * Resolve realm name by checking if it exists on Keycloak.\n * Tries the provided name first, then uppercase variant.\n * Returns the resolved realm name or null if not found.\n */\nexport async function resolveRealm(realm: string): Promise<string | null> {\n const candidates = [realm];\n const upper = realm.toUpperCase();\n if (upper !== realm) {\n candidates.push(upper);\n }\n const lower = realm.toLowerCase();\n if (lower !== realm && lower !== upper) {\n candidates.push(lower);\n }\n\n for (const candidate of candidates) {\n try {\n const response = await fetch(`https://login.farseer.io/auth/realms/${candidate}`, { method: 'GET' });\n if (response.ok) {\n return candidate;\n }\n } catch {\n // Network error, continue to next candidate\n }\n }\n\n return null;\n}\n\nfunction getErrorPage(title: string, message: string): string {\n return `\n <html>\n <head>\n <title>Farseer CLI - Error</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #fafafa;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .container {\n text-align: center;\n padding: 48px;\n }\n .error-icon {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .error-icon svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n fill: none;\n }\n h1 {\n color: #18181b;\n font-size: 24px;\n font-weight: 600;\n margin-bottom: 8px;\n }\n p {\n color: #71717a;\n font-size: 15px;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"error-icon\">\n <svg viewBox=\"0 0 24 24\">\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line>\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>\n </svg>\n </div>\n <h1>${title}</h1>\n <p>${message}</p>\n <p style=\"margin-top: 16px;\">You can close this window.</p>\n </div>\n </body>\n </html>\n `;\n}\n\nexport type BrowserLoginResult =\n | { ok: true; accessToken: string; refreshToken: string; expiresIn: number }\n // `error` is Keycloak's OAuth error code when it sent one (e.g. `login_required`).\n | { ok: false; error?: string };\n\nexport interface BrowserLoginOptions {\n idpHint?: string;\n /**\n * The hinted broker only rides an existing master session (it asks master\n * with prompt=none). When it finds none, open one in the same tab and go\n * through the broker again.\n */\n viaMasterSession?: boolean;\n}\n\n// Browser-based OAuth login with PKCE\nexport async function loginWithBrowser(\n realm: string = 'master',\n { idpHint, viaMasterSession = false }: BrowserLoginOptions = {},\n): Promise<BrowserLoginResult> {\n const http = await import('http');\n const crypto = await import('crypto');\n const { exec } = await import('child_process');\n const { promisify } = await import('util');\n const execAsync = promisify(exec);\n\n const keycloakBase = (r: string) => `https://login.farseer.io/auth/realms/${r}/protocol/openid-connect`;\n const CLIENT_ID = 'auth'; // Use auth client with full scope access\n const REDIRECT_PORT = 8787;\n const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`;\n\n // Generate PKCE code verifier and challenge\n const codeVerifier = crypto.randomBytes(32).toString('base64url');\n const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');\n\n // Generate state for CSRF protection\n const state = crypto.randomBytes(16).toString('hex');\n\n const authorizationUrl = (legRealm: string, scope: string, legState: string, challenge: string, hint?: string) => {\n const authUrl = new URL(`${keycloakBase(legRealm)}/auth`);\n authUrl.searchParams.set('client_id', CLIENT_ID);\n authUrl.searchParams.set('redirect_uri', REDIRECT_URI);\n authUrl.searchParams.set('response_type', 'code');\n authUrl.searchParams.set('scope', scope);\n authUrl.searchParams.set('state', legState);\n authUrl.searchParams.set('code_challenge', challenge);\n authUrl.searchParams.set('code_challenge_method', 'S256');\n if (hint) {\n authUrl.searchParams.set('kc_idp_hint', hint);\n }\n return authUrl.toString();\n };\n const loginUrl = authorizationUrl(realm, 'openid offline_access', state, codeChallenge, idpHint);\n\n // The master leg only has to leave a session in the browser, so its code is\n // never exchanged \u2014 and it asks for no `offline_access`: exchanging a code\n // that carries it ends the browser's session, the one thing this leg is for.\n const masterState = crypto.randomBytes(16).toString('hex');\n const masterUrl = authorizationUrl(\n DEFAULT_REALM,\n 'openid',\n masterState,\n crypto.createHash('sha256').update(crypto.randomBytes(32).toString('base64url')).digest('base64url'),\n );\n let masterSessionOpened = false;\n\n return new Promise<BrowserLoginResult>((resolve) => {\n const server = http.createServer(async (req, res) => {\n const url = new URL(req.url || '', `http://localhost:${REDIRECT_PORT}`);\n\n if (url.pathname === '/callback') {\n const code = url.searchParams.get('code');\n const returnedState = url.searchParams.get('state');\n const error = url.searchParams.get('error');\n\n if (error === 'login_required' && returnedState === state && viaMasterSession && !masterSessionOpened) {\n masterSessionOpened = true;\n res.writeHead(302, { Location: masterUrl });\n res.end();\n return;\n }\n\n if (error) {\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Login Failed', `Error: ${error}`));\n server.close();\n resolve({ ok: false, error });\n return;\n }\n\n if (code && returnedState === masterState && masterSessionOpened) {\n // The master session exists now: back through the broker, same tab.\n res.writeHead(302, { Location: loginUrl });\n res.end();\n return;\n }\n\n if (!code || returnedState !== state) {\n res.writeHead(400, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Invalid Response', 'Missing code or state mismatch.'));\n server.close();\n resolve({ ok: false });\n return;\n }\n\n // Exchange code for tokens\n try {\n const tokenResponse = await fetch(`${keycloakBase(realm)}/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: CLIENT_ID,\n code: code,\n redirect_uri: REDIRECT_URI,\n code_verifier: codeVerifier,\n }),\n });\n\n if (!tokenResponse.ok) {\n throw new Error('Token exchange failed');\n }\n\n const data = (await tokenResponse.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <html>\n <head>\n <title>Farseer CLI - Login</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background: #fafafa;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .container {\n text-align: center;\n padding: 48px;\n }\n .checkmark {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n animation: scale-in 0.3s ease-out;\n }\n .checkmark svg {\n width: 40px;\n height: 40px;\n stroke: white;\n stroke-width: 3;\n fill: none;\n animation: draw 0.4s ease-out 0.2s forwards;\n stroke-dasharray: 50;\n stroke-dashoffset: 50;\n }\n @keyframes scale-in {\n from { transform: scale(0); }\n to { transform: scale(1); }\n }\n @keyframes draw {\n to { stroke-dashoffset: 0; }\n }\n h1 {\n color: #18181b;\n font-size: 24px;\n font-weight: 600;\n margin-bottom: 8px;\n }\n p {\n color: #71717a;\n font-size: 15px;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <div class=\"checkmark\">\n <svg viewBox=\"0 0 24 24\">\n <polyline points=\"20 6 9 17 4 12\"></polyline>\n </svg>\n </div>\n <h1>Login Successful</h1>\n <p>You can close this window and return to the terminal.</p>\n </div>\n </body>\n </html>\n `);\n\n server.close();\n resolve({\n ok: true,\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresIn: data.expires_in,\n });\n } catch {\n res.writeHead(500, { 'Content-Type': 'text/html' });\n res.end(getErrorPage('Token Exchange Failed', 'Could not complete login.'));\n server.close();\n resolve({ ok: false });\n }\n }\n });\n\n server.listen(REDIRECT_PORT, async () => {\n // Open browser\n const url = loginUrl;\n try {\n if (process.platform === 'darwin') {\n await execAsync(`open \"${url}\"`);\n } else if (process.platform === 'win32') {\n await execAsync(`start \"${url}\"`);\n } else {\n await execAsync(`xdg-open \"${url}\"`);\n }\n } catch {\n // If we can't open browser, show URL to user\n console.log(`\\nOpen this URL in your browser:\\n${url}\\n`);\n }\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n server.close();\n resolve({ ok: false });\n },\n 5 * 60 * 1000,\n );\n });\n}\n\nconst refreshesInFlight = new Map<string, Promise<string | null>>();\n\n/**\n * Return a usable browser-login access token for a realm, refreshing it first\n * if it has expired. Null when there's no login for that realm, or the refresh\n * failed (caller should fall back to an API key).\n *\n * One refresh at a time per realm. Requests run 15-wide (fetchWithConcurrency) and the\n * middleware asks for a token on every one of them, so without coalescing a\n * single expiry spends the same refresh token fifteen times \u2014 and on a realm\n * that rotates refresh tokens, fourteen of those lose.\n */\nexport function getFreshAccessToken(realm: string = DEFAULT_REALM): Promise<string | null> {\n let inFlight = refreshesInFlight.get(realm);\n if (!inFlight) {\n inFlight = mintAccessToken(realm).finally(() => refreshesInFlight.delete(realm));\n refreshesInFlight.set(realm, inFlight);\n }\n return inFlight;\n}\n\nasync function mintAccessToken(realm: string): Promise<string | null> {\n const auth = getUserAuth(realm);\n if (!auth) {\n return null;\n }\n if (isUserAuthValid(auth)) {\n return auth.accessToken;\n }\n\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, realm);\n if (!refreshed) {\n return null;\n }\n setUserAuth(\n {\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm,\n },\n { refresh: true },\n );\n logger.dim('Token refreshed');\n return refreshed.accessToken;\n}\n\n/**\n * End a login's session at Keycloak, so its refresh token stops working rather\n * than outliving the logout (an offline one would for weeks). False when\n * Keycloak could not be reached or refused; the caller clears it locally anyway.\n */\nexport async function revokeRefreshToken(realm: string, refreshToken: string): Promise<boolean> {\n try {\n const response = await fetch(`https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/logout`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ client_id: 'auth', refresh_token: refreshToken }),\n signal: AbortSignal.timeout(10000),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n\nexport async function refreshAccessToken(\n refreshToken: string,\n realm: string = 'master',\n): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresIn: number;\n} | null> {\n const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;\n\n try {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: 'auth',\n refresh_token: refreshToken,\n }),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const data = (await response.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresIn: data.expires_in,\n };\n } catch {\n return null;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAAyB;AACzB,wBAA4B;AAC5B,2BAAyE;AAEzE,kBAYO;AACP,yBAMO;AACP,4BAAwB;AACxB,yBAAmC;AACnC,uBAA0B;AAC1B,wBAAsC;AACtC,oBAAuB;AAkEhB,SAAS,WAAW,MAA4B;AACnD,SAAO,KAAK,SAAS,QAAQ,KAAK,WAAW,KAAK,WAAW;AACjE;AAEA,SAAS,YAAY,MAA4C;AAC7D,SAAO,KAAK,SAAS,QACf,EAAE,eAAe,KAAK,QAAQ,eAAe,UAAU,KAAK,WAAW,GAAG,IAC1E,EAAE,eAAe,KAAK,WAAW,UAAU,aAAa,KAAK,WAAW,OAAO;AACzF;AAOA,SAAS,cAAc,OAAmC;AACtD,MAAI,EAAE,iBAAiB,6BAAY;AAC/B,WAAO;AAAA,EACX;AACA,MAAI,MAAM,WAAW,WAAO,yCAAsB,MAAM,OAAO,GAAG;AAC9D,WAAO;AAAA,EACX;AACA,MAAI,MAAM,WAAW,OAAO,MAAM,WAAW,KAAK;AAC9C,WAAO;AAAA,EACX;AACA,SAAO;AACX;AASA,SAAS,qBAAqB,OAAmC;AAC7D,SAAO;AAAA,IACH,MAAM,IAAI,EAAE,KAAK,KAAK,GAAG;AACrB,YAAM,cAAc,MAAM,oBAAoB,KAAK;AACnD,UAAI,CAAC,aAAa;AAEd,eAAO,EAAE,KAAK,KAAK;AAAA,MACvB;AACA,aAAO;AAAA,QACH;AAAA,QACA,MAAM,EAAE,GAAG,MAAM,SAAS,EAAE,GAAG,KAAK,SAAS,eAAe,UAAU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+38,7 @@ var fs = __toESM(require("fs"));
|
|
|
38
38
|
var import_credentials = require("./credentials");
|
|
39
39
|
var import_authErrors = require("./authErrors");
|
|
40
40
|
var import_organisation = require("./organisation");
|
|
41
|
+
var import_realms = require("./realms");
|
|
41
42
|
var import_configService = require("./configService");
|
|
42
43
|
var import_helpers = require("../utils/helpers");
|
|
43
44
|
var import_logger = require("../utils/logger");
|
|
@@ -89,7 +90,7 @@ function sessionFrom(organisation, tenant, auth) {
|
|
|
89
90
|
return { organisation, tenant, client, native: client.native, authType: auth.kind };
|
|
90
91
|
}
|
|
91
92
|
async function validatePairing(organisation, tenant) {
|
|
92
|
-
const accessToken = await (0, import_credentials.getFreshAccessToken)();
|
|
93
|
+
const accessToken = await (0, import_credentials.getFreshAccessToken)(await (0, import_realms.realmForOrganisation)(organisation));
|
|
93
94
|
if (!accessToken) {
|
|
94
95
|
return { status: "unvalidated" };
|
|
95
96
|
}
|
|
@@ -132,7 +133,7 @@ function hostOf(basePath) {
|
|
|
132
133
|
}
|
|
133
134
|
function reportSessionFailure(failure) {
|
|
134
135
|
if (failure.reason === "no-credentials") {
|
|
135
|
-
(0, import_authErrors.showLoginPrompt)(failure.tenant);
|
|
136
|
+
(0, import_authErrors.showLoginPrompt)(failure.tenant, failure.organisation);
|
|
136
137
|
return;
|
|
137
138
|
}
|
|
138
139
|
if (failure.reason === "org-unknown") {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/preflight.ts"],
|
|
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 { FarseerService, ResolvedAuth } from './farseerService';\nimport { buildClient, getFreshAccessToken, resolveAuth, resolveAuthByProbe } from './credentials';\nimport { showLoginPrompt } from './authErrors';\nimport { checkTenantAtOrganisation, fetchOrganisationTenants } from './organisation';\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: FarseerService;\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 // One client per session. `native` is the SDK object the facade already\n // holds, not a second one built from the same credential.\n const client = buildClient(auth);\n return { organisation, tenant, client, native: client.native, authType: auth.kind };\n}\n\n// `unvalidated` means we couldn't ask, not that the answer was no.\n\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 fetchOrganisationTenants(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,yBAAkF;AAClF,wBAAgC;AAChC,0BAAoE;AACpE,2BAAsE;AACtE,qBAA+D;AAC/D,oBAAuB;AA+BvB,eAAsB,UAAU,MAAe,MAAe,OAAsB,CAAC,GAA2B;AAC5G,QAAM,EAAE,cAAc,OAAO,QAAI,4CAA4B,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E,QAAQ,wBAAwB,cAAc,QAAQ,KAAK,WAAW,UAAU,MAAM,OAAO,QAAQ,EAAE;AACpH;AAGO,SAAS,YAAY,cAAsB,QAAgB,MAAmC;AAGjG,QAAM,aAAS,gCAAY,IAAI;AAC/B,SAAO,EAAE,cAAc,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,UAAU,KAAK,KAAK;AACtF;AAcA,eAAe,gBAAgB,cAAsB,QAA4C;AAC7F,QAAM,cAAc,UAAM,wCAAoB;
|
|
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 { FarseerService, ResolvedAuth } from './farseerService';\nimport { buildClient, getFreshAccessToken, resolveAuth, resolveAuthByProbe } from './credentials';\nimport { showLoginPrompt } from './authErrors';\nimport { checkTenantAtOrganisation, fetchOrganisationTenants } from './organisation';\nimport { realmForOrganisation } from './realms';\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: FarseerService;\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 // One client per session. `native` is the SDK object the facade already\n // holds, not a second one built from the same credential.\n const client = buildClient(auth);\n return { organisation, tenant, client, native: client.native, authType: auth.kind };\n}\n\n// `unvalidated` means we couldn't ask, not that the answer was no.\n\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(await realmForOrganisation(organisation));\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 fetchOrganisationTenants(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, failure.organisation);\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,yBAAkF;AAClF,wBAAgC;AAChC,0BAAoE;AACpE,oBAAqC;AACrC,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,KAA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AAgC,QAAQ,YAAY,KAAK,QAAQ,WAAW,KAAK,IAAI,CAAC,EAAE;AAAA,EACvG;AACA,uBAAO,IAAI,4FAA4F;AACvG,uBAAO,IAAI,sFAAiF;AAChG;AAGA,SAAS,sBAAsB,QAAsB;AACjD,QAAM,eAAW,kCAAkB,MAAM;AACzC,MAAI,CAAC,GAAG,WAAW,QAAQ,GAAG;AAC1B,yBAAO,MAAM,kCAAkC,MAAM,IAAI;AACzD,yBAAO,IAAI,qBAAqB,MAAM,uBAAuB;AAC7D,YAAQ,KAAK,CAAC;AAAA,EAClB;AACJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var realms_exports = {};
|
|
20
|
+
__export(realms_exports, {
|
|
21
|
+
fetchOrganisationKeycloakConfig: () => fetchOrganisationKeycloakConfig,
|
|
22
|
+
knownRealmForOrganisation: () => knownRealmForOrganisation,
|
|
23
|
+
realmForOrganisation: () => realmForOrganisation
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(realms_exports);
|
|
26
|
+
var import_configService = require("./configService");
|
|
27
|
+
const LOOKUP_TIMEOUT_MS = 1e4;
|
|
28
|
+
async function fetchOrganisationKeycloakConfig(organisation) {
|
|
29
|
+
try {
|
|
30
|
+
const response = await fetch(`${(0, import_configService.generateBasePath)(organisation)}/keycloakConfigurations/default`, {
|
|
31
|
+
signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS)
|
|
32
|
+
});
|
|
33
|
+
if (!response.ok) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
const body = await response.json();
|
|
37
|
+
if (typeof body.realm !== "string" || !body.realm) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
const idpHint = body["idp-hint"];
|
|
41
|
+
return { realm: body.realm, idpHint: typeof idpHint === "string" && idpHint ? idpHint : void 0 };
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function realmForOrganisation(organisation) {
|
|
47
|
+
const known = (0, import_configService.getOrganisationRealm)(organisation);
|
|
48
|
+
if (known) {
|
|
49
|
+
return known;
|
|
50
|
+
}
|
|
51
|
+
const config = await fetchOrganisationKeycloakConfig(organisation);
|
|
52
|
+
if (!config) {
|
|
53
|
+
return import_configService.DEFAULT_REALM;
|
|
54
|
+
}
|
|
55
|
+
(0, import_configService.saveOrganisationRealm)(organisation, config.realm);
|
|
56
|
+
return config.realm;
|
|
57
|
+
}
|
|
58
|
+
function knownRealmForOrganisation(organisation) {
|
|
59
|
+
return (0, import_configService.getOrganisationRealm)(organisation) ?? import_configService.DEFAULT_REALM;
|
|
60
|
+
}
|
|
61
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
62
|
+
0 && (module.exports = {
|
|
63
|
+
fetchOrganisationKeycloakConfig,
|
|
64
|
+
knownRealmForOrganisation,
|
|
65
|
+
realmForOrganisation
|
|
66
|
+
});
|
|
67
|
+
//# sourceMappingURL=realms.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/services/realms.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Which Keycloak realm an organisation's tenants authenticate against.\n *\n * The backend verifies a bearer token against the signing keys of the tenant's\n * own realm, so a master-realm token is rejected at an organisation whose\n * tenants live in, say, `JGL`. The organisation publishes its realm on an\n * unauthenticated endpoint \u2014 the one the web app reads before it logs in.\n */\n\nimport { DEFAULT_REALM, generateBasePath, getOrganisationRealm, saveOrganisationRealm } from './configService';\n\nconst LOOKUP_TIMEOUT_MS = 10000;\n\nexport interface OrganisationKeycloakConfig {\n realm: string;\n /** The identity provider the web app sends this organisation's users to, if any. */\n idpHint?: string;\n}\n\n/** Ask the organisation. Null when it cannot be reached or does not answer with a realm. */\nexport async function fetchOrganisationKeycloakConfig(\n organisation: string,\n): Promise<OrganisationKeycloakConfig | null> {\n try {\n const response = await fetch(`${generateBasePath(organisation)}/keycloakConfigurations/default`, {\n signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS),\n });\n if (!response.ok) {\n return null;\n }\n const body = (await response.json()) as { realm?: unknown; 'idp-hint'?: unknown };\n if (typeof body.realm !== 'string' || !body.realm) {\n return null;\n }\n const idpHint = body['idp-hint'];\n return { realm: body.realm, idpHint: typeof idpHint === 'string' && idpHint ? idpHint : undefined };\n } catch {\n return null;\n }\n}\n\n/**\n * The realm to take a token from for this organisation. Remembered once learned\n * (an org does not change realms); an org that cannot be asked falls back to\n * master, which is what every login was before realms were per organisation.\n */\nexport async function realmForOrganisation(organisation: string): Promise<string> {\n const known = getOrganisationRealm(organisation);\n if (known) {\n return known;\n }\n const config = await fetchOrganisationKeycloakConfig(organisation);\n if (!config) {\n return DEFAULT_REALM;\n }\n saveOrganisationRealm(organisation, config.realm);\n return config.realm;\n}\n\n/** Synchronous best guess, for callers that only compare state after a realm was resolved. */\nexport function knownRealmForOrganisation(organisation: string): string {\n return getOrganisationRealm(organisation) ?? DEFAULT_REALM;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,2BAA6F;AAE7F,MAAM,oBAAoB;AAS1B,eAAsB,gCAClB,cAC0C;AAC1C,MAAI;AACA,UAAM,WAAW,MAAM,MAAM,OAAG,uCAAiB,YAAY,CAAC,mCAAmC;AAAA,MAC7F,QAAQ,YAAY,QAAQ,iBAAiB;AAAA,IACjD,CAAC;AACD,QAAI,CAAC,SAAS,IAAI;AACd,aAAO;AAAA,IACX;AACA,UAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,QAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,OAAO;AAC/C,aAAO;AAAA,IACX;AACA,UAAM,UAAU,KAAK,UAAU;AAC/B,WAAO,EAAE,OAAO,KAAK,OAAO,SAAS,OAAO,YAAY,YAAY,UAAU,UAAU,OAAU;AAAA,EACtG,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAOA,eAAsB,qBAAqB,cAAuC;AAC9E,QAAM,YAAQ,2CAAqB,YAAY;AAC/C,MAAI,OAAO;AACP,WAAO;AAAA,EACX;AACA,QAAM,SAAS,MAAM,gCAAgC,YAAY;AACjE,MAAI,CAAC,QAAQ;AACT,WAAO;AAAA,EACX;AACA,kDAAsB,cAAc,OAAO,KAAK;AAChD,SAAO,OAAO;AAClB;AAGO,SAAS,0BAA0B,cAA8B;AACpE,aAAO,2CAAqB,YAAY,KAAK;AACjD;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|