farseer-cli 1.10.0 → 1.10.2
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/dist/commands/app.js +2 -2
- package/dist/commands/app.js.map +2 -2
- package/dist/commands/cells.js +2 -4
- package/dist/commands/cells.js.map +2 -2
- package/dist/commands/dashboards.js +2 -4
- package/dist/commands/dashboards.js.map +2 -2
- package/dist/commands/dimensions.js +3 -6
- package/dist/commands/dimensions.js.map +2 -2
- package/dist/commands/formula.js +1 -2
- package/dist/commands/formula.js.map +2 -2
- package/dist/commands/sheets.js +4 -8
- package/dist/commands/sheets.js.map +2 -2
- package/dist/commands/variables.js +3 -6
- package/dist/commands/variables.js.map +2 -2
- package/dist/mcp/tools/appTools.js +6 -4
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/authTools.js +12 -9
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +22 -7
- package/dist/mcp/utils/helpers.js.map +2 -2
- package/dist/mcp/utils/session.js +97 -0
- package/dist/mcp/utils/session.js.map +7 -0
- package/dist/mcp/utils/tenantPin.js.map +2 -2
- package/dist/services/farseerApi.js +56 -12
- package/dist/services/farseerApi.js.map +3 -3
- package/dist/services/farseerFactory.js +70 -108
- package/dist/services/farseerFactory.js.map +2 -2
- package/dist/services/farseerService.js +24 -8
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/preflight.js +78 -24
- package/dist/services/preflight.js.map +2 -2
- package/dist/utils/fileValidation.js +1 -0
- package/dist/utils/fileValidation.js.map +2 -2
- package/package.json +1 -1
|
@@ -30,6 +30,8 @@ var farseerFactory_exports = {};
|
|
|
30
30
|
__export(farseerFactory_exports, {
|
|
31
31
|
DEFAULT_SCRIPT_EXTENSIONS: () => DEFAULT_SCRIPT_EXTENSIONS,
|
|
32
32
|
DEFAULT_SYNC_EXTENSIONS: () => DEFAULT_SYNC_EXTENSIONS,
|
|
33
|
+
buildClient: () => buildClient,
|
|
34
|
+
buildNativeClient: () => buildNativeClient,
|
|
33
35
|
checkTenantAtOrganisation: () => checkTenantAtOrganisation,
|
|
34
36
|
ensureFreshToken: () => ensureFreshToken,
|
|
35
37
|
fetchOrganizationTenants: () => fetchOrganizationTenants,
|
|
@@ -40,6 +42,9 @@ __export(farseerFactory_exports, {
|
|
|
40
42
|
getNativeFarseerClient: () => getNativeFarseerClient,
|
|
41
43
|
isAuthError: () => isAuthError,
|
|
42
44
|
isTenantNotFoundError: () => isTenantNotFoundError,
|
|
45
|
+
refreshAuth: () => refreshAuth,
|
|
46
|
+
resolveAuth: () => resolveAuth,
|
|
47
|
+
resolveAuthByProbe: () => resolveAuthByProbe,
|
|
43
48
|
showLoginPrompt: () => showLoginPrompt
|
|
44
49
|
});
|
|
45
50
|
module.exports = __toCommonJS(farseerFactory_exports);
|
|
@@ -149,42 +154,69 @@ async function fetchOrganizationTenants(organisation, accessToken) {
|
|
|
149
154
|
return [];
|
|
150
155
|
}
|
|
151
156
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
157
|
+
function jwtAuth(accessToken, organisation, tenant) {
|
|
158
|
+
return { kind: "jwt", accessToken, basePath: (0, import_configService.generateBasePath)(organisation), tenant };
|
|
159
|
+
}
|
|
160
|
+
function buildClient(auth) {
|
|
161
|
+
return auth.kind === "jwt" ? new import_farseerApi.FarseerApi(auth.accessToken, auth.basePath, auth.tenant) : new import_farseerService.FarseerService(auth.credential);
|
|
162
|
+
}
|
|
163
|
+
function buildNativeClient(auth) {
|
|
164
|
+
if (auth.kind === "jwt") {
|
|
165
|
+
return new farseer.FarseerClient({
|
|
166
|
+
basePath: auth.basePath,
|
|
167
|
+
headers: { "X-TENANT-ID": auth.tenant, Authorization: `Bearer ${auth.accessToken}` }
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
return new farseer.FarseerClient({
|
|
171
|
+
basePath: auth.credential.basePath,
|
|
172
|
+
headers: { "X-TENANT-ID": auth.credential.tenantId, "X-API-KEY": auth.credential.apiKey }
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
async function resolveAuth(organisation, tenant) {
|
|
176
|
+
const accessToken = await getFreshAccessToken();
|
|
177
|
+
if (accessToken) {
|
|
178
|
+
return jwtAuth(accessToken, organisation, tenant);
|
|
179
|
+
}
|
|
180
|
+
const credential = (0, import_configService.getCredential)(tenant);
|
|
181
|
+
return credential ? { kind: "apiKey", credential } : null;
|
|
182
|
+
}
|
|
183
|
+
async function resolveAuthByProbe(organisation, tenant) {
|
|
184
|
+
const accessToken = await getFreshAccessToken();
|
|
185
|
+
if (accessToken) {
|
|
186
|
+
const auth = jwtAuth(accessToken, organisation, tenant);
|
|
187
|
+
if (await connects(auth)) {
|
|
188
|
+
return auth;
|
|
177
189
|
}
|
|
190
|
+
import_logger.logger.dim("JWT auth failed for this tenant, trying API key...");
|
|
178
191
|
}
|
|
179
192
|
const credential = (0, import_configService.getCredential)(tenant);
|
|
180
193
|
if (credential) {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
}
|
|
194
|
+
const auth = { kind: "apiKey", credential };
|
|
195
|
+
if (await connects(auth)) {
|
|
196
|
+
return auth;
|
|
197
|
+
}
|
|
198
|
+
import_logger.logger.dim("API key auth failed.");
|
|
185
199
|
}
|
|
186
200
|
return null;
|
|
187
201
|
}
|
|
202
|
+
async function refreshAuth(auth) {
|
|
203
|
+
if (auth.kind === "apiKey") {
|
|
204
|
+
return auth;
|
|
205
|
+
}
|
|
206
|
+
const accessToken = await getFreshAccessToken();
|
|
207
|
+
return accessToken ? { ...auth, accessToken } : null;
|
|
208
|
+
}
|
|
209
|
+
async function connects(auth) {
|
|
210
|
+
try {
|
|
211
|
+
return await buildClient(auth).testConnection();
|
|
212
|
+
} catch {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
async function getFarseerClient(organisation, tenant) {
|
|
217
|
+
const auth = await resolveAuth(organisation, tenant);
|
|
218
|
+
return auth ? { client: buildClient(auth), authType: auth.kind } : null;
|
|
219
|
+
}
|
|
188
220
|
function getAvailableAuth(tenant) {
|
|
189
221
|
const credential = (0, import_configService.getCredential)(tenant);
|
|
190
222
|
const auth = (0, import_configService.getUserAuth)();
|
|
@@ -195,48 +227,8 @@ function getAvailableAuth(tenant) {
|
|
|
195
227
|
};
|
|
196
228
|
}
|
|
197
229
|
async function getFarseerClientWithFallback(organisation, tenant) {
|
|
198
|
-
const auth = (
|
|
199
|
-
|
|
200
|
-
if (auth) {
|
|
201
|
-
let accessToken = auth.accessToken;
|
|
202
|
-
if (!(0, import_configService.isUserAuthValid)()) {
|
|
203
|
-
import_logger.logger.dim("Token expired, refreshing...");
|
|
204
|
-
const refreshed = await (0, import_farseerService2.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
|
|
205
|
-
if (refreshed) {
|
|
206
|
-
(0, import_configService.setUserAuth)({
|
|
207
|
-
accessToken: refreshed.accessToken,
|
|
208
|
-
refreshToken: refreshed.refreshToken,
|
|
209
|
-
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
210
|
-
realm: auth.realm
|
|
211
|
-
});
|
|
212
|
-
accessToken = refreshed.accessToken;
|
|
213
|
-
import_logger.logger.dim("Token refreshed");
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
if ((0, import_configService.isUserAuthValid)()) {
|
|
217
|
-
const jwtClient = new import_farseerApi.FarseerApi(accessToken, organisation, tenant);
|
|
218
|
-
try {
|
|
219
|
-
const connected = await jwtClient.testConnection();
|
|
220
|
-
if (connected) {
|
|
221
|
-
return { client: jwtClient, authType: "jwt" };
|
|
222
|
-
}
|
|
223
|
-
} catch (error) {
|
|
224
|
-
import_logger.logger.dim("JWT auth failed for this tenant, trying API key...");
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
if (credential) {
|
|
229
|
-
const apiKeyClient = new import_farseerService.FarseerService(credential);
|
|
230
|
-
try {
|
|
231
|
-
const connected = await apiKeyClient.testConnection();
|
|
232
|
-
if (connected) {
|
|
233
|
-
return { client: apiKeyClient, authType: "apiKey" };
|
|
234
|
-
}
|
|
235
|
-
} catch {
|
|
236
|
-
import_logger.logger.dim("API key auth failed.");
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
return null;
|
|
230
|
+
const auth = await resolveAuthByProbe(organisation, tenant);
|
|
231
|
+
return auth ? { client: buildClient(auth), authType: auth.kind } : null;
|
|
240
232
|
}
|
|
241
233
|
async function ensureFreshToken(client) {
|
|
242
234
|
const auth = (0, import_configService.getUserAuth)();
|
|
@@ -269,48 +261,15 @@ async function ensureFreshToken(client) {
|
|
|
269
261
|
return false;
|
|
270
262
|
}
|
|
271
263
|
async function getNativeFarseerClient(organisation, tenant) {
|
|
272
|
-
const
|
|
273
|
-
|
|
274
|
-
if (auth) {
|
|
275
|
-
let accessToken = auth.accessToken;
|
|
276
|
-
if (!(0, import_configService.isUserAuthValid)()) {
|
|
277
|
-
const refreshed = await (0, import_farseerService2.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
|
|
278
|
-
if (refreshed) {
|
|
279
|
-
(0, import_configService.setUserAuth)({
|
|
280
|
-
accessToken: refreshed.accessToken,
|
|
281
|
-
refreshToken: refreshed.refreshToken,
|
|
282
|
-
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
283
|
-
realm: auth.realm
|
|
284
|
-
});
|
|
285
|
-
accessToken = refreshed.accessToken;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
if ((0, import_configService.isUserAuthValid)()) {
|
|
289
|
-
return new farseer.FarseerClient({
|
|
290
|
-
basePath,
|
|
291
|
-
headers: {
|
|
292
|
-
"X-TENANT-ID": tenant,
|
|
293
|
-
Authorization: `Bearer ${accessToken}`
|
|
294
|
-
}
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
const credential = (0, import_configService.getCredential)(tenant);
|
|
299
|
-
if (credential) {
|
|
300
|
-
return new farseer.FarseerClient({
|
|
301
|
-
basePath: credential.basePath,
|
|
302
|
-
headers: {
|
|
303
|
-
"X-TENANT-ID": credential.tenantId,
|
|
304
|
-
"X-API-KEY": credential.apiKey
|
|
305
|
-
}
|
|
306
|
-
});
|
|
307
|
-
}
|
|
308
|
-
return null;
|
|
264
|
+
const auth = await resolveAuth(organisation, tenant);
|
|
265
|
+
return auth ? buildNativeClient(auth) : null;
|
|
309
266
|
}
|
|
310
267
|
// Annotate the CommonJS export names for ESM import in node:
|
|
311
268
|
0 && (module.exports = {
|
|
312
269
|
DEFAULT_SCRIPT_EXTENSIONS,
|
|
313
270
|
DEFAULT_SYNC_EXTENSIONS,
|
|
271
|
+
buildClient,
|
|
272
|
+
buildNativeClient,
|
|
314
273
|
checkTenantAtOrganisation,
|
|
315
274
|
ensureFreshToken,
|
|
316
275
|
fetchOrganizationTenants,
|
|
@@ -321,6 +280,9 @@ async function getNativeFarseerClient(organisation, tenant) {
|
|
|
321
280
|
getNativeFarseerClient,
|
|
322
281
|
isAuthError,
|
|
323
282
|
isTenantNotFoundError,
|
|
283
|
+
refreshAuth,
|
|
284
|
+
resolveAuth,
|
|
285
|
+
resolveAuthByProbe,
|
|
324
286
|
showLoginPrompt
|
|
325
287
|
});
|
|
326
288
|
//# sourceMappingURL=farseerFactory.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/farseerFactory.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Factory for creating Farseer API client based on available authentication\n *\n * Priority:\n * 1. JWT token (from browser login) - try first\n * 2. API key (from config) - fallback if JWT fails or unavailable\n * 3. Prompt user to login - if nothing works\n */\n\nimport axios from 'axios';\nimport * as farseer from 'farseer-client';\nimport { FarseerService } from './farseerService';\nimport { FarseerApi } from './farseerApi';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { logger } from '../utils/logger';\n\n/**\n * A tenant the backend couldn't resolve at this host \u2014 it answers\n * `403 {\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`.\n * Despite the 403 this is NOT a credentials problem: it's what a wrong\n * organisation for an otherwise-valid tenant looks like, because every\n * tenant-scoped request carries X-TENANT-ID and the org's backend has no such\n * tenant. Telling the user to log in again would send them to fix the one thing\n * that isn't broken.\n */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * The backend's \"no such tenant at this host\" phrasing. Lives apart from\n * isTenantNotFoundError because the same sentence reaches us two ways: inside a\n * thrown Error from the SDK, and as the `message` field of an axios 403 body \u2014\n * where `error.message` is only ever \"Request failed with status code 403\".\n */\nfunction mentionsUnknownTenant(text: string | undefined): boolean {\n if (!text) {\n return false;\n }\n const msg = text.toLowerCase();\n return msg.includes('does not exist') && msg.includes('tenant');\n}\n\n/**\n * Check if an error is an authentication error (401/403).\n *\n * A 403 that names an unresolvable tenant is deliberately excluded \u2014 see\n * isTenantNotFoundError. Callers that show a login prompt on true would\n * otherwise misdiagnose a wrong-org command as expired credentials.\n */\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n return msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('forbidden');\n }\n return false;\n}\n\n/**\n * Show a consistent \"please login\" message\n */\nexport function showLoginPrompt(tenant?: string): void {\n logger.error('Authentication required.');\n if (tenant) {\n logger.dim(`No valid credentials found for tenant \"${tenant}\".`);\n }\n logger.info('Run \"farseer login\" to authenticate via browser.');\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n\nexport interface FileMetadata {\n uploadTime?: string; // ISO timestamp\n uploader?: {\n id: number;\n email: string;\n firstName: string;\n lastName: string;\n };\n size?: number;\n}\n\n/**\n * Canonical RemoteFile shape used by every layer of the CLI. Both\n * FarseerApi (JWT path) and FarseerService (API-key path) re-export this\n * type so downstream code (SyncService, MCP tools, tests) can rely on a\n * single definition. Earlier each layer declared its own copy that drifted\n * \u2014 three different shapes that disagreed on which optional fields existed,\n * which made it impossible to tell from a function signature what the\n * caller could assume was set.\n *\n * Optional fields are populated lazily:\n * - `content` \u2014 only set by callers that already fetched body bytes\n * (some legacy paths combined list + download in a single helper).\n * - `metadata` \u2014 populated by listFiles for the JWT path. The API-key\n * path doesn't return it, so consumers must handle absence.\n */\nexport interface RemoteFile {\n name: string;\n path: string;\n reference: string;\n content?: string;\n metadata?: FileMetadata;\n}\n\n// Mirrors the backend `OrganizationInfo` schema returned by GET /organization\n// (backend/app/openapi/v3/documentation/overseer/components.yaml). The org is\n// resolved from the request host (`<org>.farseer.io`); `tenants` is the\n// authoritative list of tenants that org actually owns in overseer. `checkout`\n// uses it to confirm the org+tenant pair the user typed is real \u2014 the backend\n// resolves a tenant from the X-TENANT-ID header alone and never checks it\n// against the org, so without this the org argument is an unvalidated routing\n// hint.\nexport interface OrganizationTenant {\n name: string;\n isDefault: boolean;\n}\n\nexport interface OrganizationInfo {\n id: string;\n host: string;\n version: string;\n tenants: OrganizationTenant[];\n}\n\n// Narrow set of \"script\" extensions \u2014 used by `farseer files list` and\n// `farseer list` to default to source-code style files when listing a\n// folder. NOT the default sync scope; see DEFAULT_SYNC_EXTENSIONS below.\nexport const DEFAULT_SCRIPT_EXTENSIONS = ['.ts', '.js'];\n\n// Default sync scope \u2014 the curated set of files a developer AUTHORS in an\n// editor. NARROWER than the backend's accepted extension list\n// (`cli/src/utils/fileValidation.ts:BACKEND_EXTENSION_WHITELIST`, which\n// mirrors `farseer/backend/app/openapi/v3/services/farseerFileService.ts`).\n// The earlier \"default sync = everything backend accepts\" expanded the\n// default scope to 25 entries including binary / data formats (.csv,\n// .parquet, .xlsx, .pdf, images) \u2014 large files no one edits in a code\n// editor that dominated first-pull time and made `status` noisy.\n//\n// Users opt into the rest of the backend whitelist (data / docs /\n// archives) via `--include-ext <ext>` or persistent\n// `farseer config include`. Anything still outside the backend whitelist\n// requires `--all` or `--include-folder`.\n//\n// Subset contract: every entry here must also be in\n// `BACKEND_EXTENSION_WHITELIST`, otherwise push pre-flight will reject\n// in-scope files (extension not allowed) \u2014 defeats the purpose of the\n// default scope. Asserted by `defaultSyncExtensionsParity.test.ts`.\nexport const DEFAULT_SYNC_EXTENSIONS = [\n // Code (frontend / scripts)\n '.ts',\n '.js',\n // Code (Python)\n '.py',\n // Config / data\n '.yml',\n '.yaml',\n '.json',\n // Docs\n '.md',\n];\n\nimport {\n AppListItem,\n AppUpdateChanges,\n RemoteApp,\n SourceFolderResolution,\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n} from './farseerApi';\n\n// Common interface that both FarseerService and FarseerApi implement\nexport interface IFarseerClient {\n testConnection(): Promise<boolean>;\n getOrganizationInfo(): Promise<OrganizationInfo>;\n getFilesFolder(): Promise<{ id: number; name: string; type: string } | null>;\n listFiles(folderPath?: string[]): Promise<RemoteFile[]>;\n getFileContent(reference: string): Promise<string>;\n getFileContentAsBuffer(reference: string): Promise<Buffer>;\n createFile(content: string | Buffer, fileName: string, folderPath?: string[]): Promise<void>;\n updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void>;\n deleteFile(reference: string): Promise<void>;\n getFileByPath(filePath: string): Promise<RemoteFile | null>;\n getFileMetadata(reference: string): Promise<FileMetadata | null>;\n isTextFile(filename: string): boolean;\n isBinaryFile(filename: string): boolean;\n // Apps API methods\n listApps(): Promise<AppListItem[]>;\n getApp(referenceId: string): Promise<RemoteApp | null>;\n getAppByName(name: string): Promise<RemoteApp | null>;\n createApp(name: string): Promise<RemoteApp>;\n updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp>;\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n deleteApp(itemNodeId: number): Promise<void>;\n getScriptFiles(): Promise<{ id: string; name: string }[]>;\n // Model export\n exportModel(options?: ModelExportOptions): Promise<ModelExport>;\n /**\n * Fetch a single dimension table with its members. Goes through\n * `entities/search` + `getRelations` + `getMany`, which scope the\n * fetch to one table \u2014 unlike `exportModel` with `tableGids`,\n * which currently 500s for some tables on large tenants\n * (rama-side scoping bug, tracked separately).\n */\n loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null>;\n // Token management (optional - only FarseerApi implements this)\n updateAccessToken?(newToken: string): void;\n}\n\nexport interface FarseerClientResult {\n client: IFarseerClient;\n authType: 'apiKey' | 'jwt';\n}\n\n/**\n * Return a usable browser-login access token, refreshing it first if it has\n * expired. Null when there's no browser login, or the refresh failed (caller\n * should fall back to an API key).\n */\nexport async function getFreshAccessToken(): Promise<string | null> {\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n if (isUserAuthValid()) {\n return auth.accessToken;\n }\n\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n logger.dim('Token refreshed');\n return refreshed.accessToken;\n}\n\nexport type TenantCheck =\n | { status: 'ok' }\n | { status: 'tenant-unknown' }\n | { status: 'no-such-org' }\n | { status: 'unauthorized' }\n | { status: 'unreachable'; message: string };\n\n/**\n * Ask an organisation, in one request, whether it has this tenant.\n *\n * `/organization` is resolved from the request host, and sending X-TENANT-ID\n * puts the request through the same tenant-resolution middleware every\n * tenant-scoped call passes through \u2014 so the answer is the real one rather than\n * an inference:\n *\n * 200 the pair resolves, and the token works\n * 403 \"Tenant with id <t> does not exist\" the org does not have this tenant\n * 404 no Farseer organisation at this host\n * 401 the token is no good\n *\n * The alternative \u2014 asking without the header and looking for the tenant in the\n * response list \u2014 cannot refute a pair, because that list holds only what the\n * CALLER can enumerate and that is a different permission: an account that gets\n * `[]` for org `kiwi` still has `X-TENANT-ID: kiwi` accepted at that same host.\n *\n * The 403 was originally read as an auth failure, which is why the header was\n * avoided at first; `isTenantNotFoundError` tells the two apart from the body,\n * so it no longer is. Any OTHER 403 stays inconclusive \u2014 an org-level\n * permission problem is not this tenant failing to exist.\n */\nexport async function checkTenantAtOrganisation(\n organisation: string,\n tenant: string,\n accessToken: string,\n): Promise<TenantCheck> {\n try {\n await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}`, 'X-TENANT-ID': tenant },\n timeout: 30000,\n });\n return { status: 'ok' };\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n return { status: 'unauthorized' };\n }\n if (error.response?.status === 404) {\n return { status: 'no-such-org' };\n }\n const body = error.response?.data;\n const detail = typeof body === 'string' ? body : (body as { message?: string } | undefined)?.message;\n if (error.response?.status === 403 && mentionsUnknownTenant(detail)) {\n return { status: 'tenant-unknown' };\n }\n }\n return { status: 'unreachable', message: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/**\n * The tenants an organisation will admit to, for the CALLER. Best-effort and\n * hint-only: used to name the alternatives when a pair has already been refuted,\n * never to decide anything. Sends no tenant header \u2014 the pair is known bad by\n * this point, and including it would just 403 again.\n */\nexport async function fetchOrganizationTenants(organisation: string, accessToken: string): Promise<string[]> {\n try {\n const response = await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n timeout: 30000,\n });\n return (response.data.tenants ?? []).map((t) => t.name);\n } catch {\n return [];\n }\n}\n\n/**\n * Get a Farseer client for the given organisation and tenant.\n * Tries JWT token first (supports apps), then falls back to API key.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClient(organisation: string, tenant: string): Promise<FarseerClientResult | null> {\n // 1. Try JWT token from browser login first (supports apps sync)\n const auth = getUserAuth();\n if (auth) {\n // Check if token needs refresh\n let accessToken = auth.accessToken;\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n logger.warning('Could not refresh token. Please login again with: farseer login');\n // Fall through to API key\n } else {\n // Save refreshed token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n accessToken = refreshed.accessToken;\n logger.dim('Token refreshed');\n }\n }\n\n if (isUserAuthValid()) {\n return {\n client: new FarseerApi(accessToken, organisation, tenant),\n authType: 'jwt',\n };\n }\n }\n\n // 2. Fall back to API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n client: new FarseerService(credential),\n authType: 'apiKey',\n };\n }\n\n return null;\n}\n\n/**\n * Check what authentication methods are available\n */\nexport function getAvailableAuth(tenant: string): {\n hasApiKey: boolean;\n hasJwt: boolean;\n jwtValid: boolean;\n} {\n const credential = getCredential(tenant);\n const auth = getUserAuth();\n\n return {\n hasApiKey: !!credential,\n hasJwt: !!auth,\n jwtValid: isUserAuthValid(),\n };\n}\n\n/**\n * Get a Farseer client with automatic fallback and connection testing.\n * This is the recommended way to get a client for commands.\n *\n * Flow:\n * 1. Try JWT if available and valid\n * 2. If JWT fails or unavailable, try API key\n * 3. If nothing works, return null (caller should show login prompt)\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClientWithFallback(\n organisation: string,\n tenant: string,\n): Promise<FarseerClientResult | null> {\n const auth = getUserAuth();\n const credential = getCredential(tenant);\n\n // 1. Try JWT token first\n if (auth) {\n let accessToken = auth.accessToken;\n\n // Refresh token if needed\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n accessToken = refreshed.accessToken;\n logger.dim('Token refreshed');\n }\n }\n\n if (isUserAuthValid()) {\n const jwtClient = new FarseerApi(accessToken, organisation, tenant);\n\n // Test JWT connection\n try {\n const connected = await jwtClient.testConnection();\n if (connected) {\n return { client: jwtClient, authType: 'jwt' };\n }\n } catch (error) {\n // JWT failed, will try API key\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n }\n }\n\n // 2. Try API key\n if (credential) {\n const apiKeyClient = new FarseerService(credential);\n\n try {\n const connected = await apiKeyClient.testConnection();\n if (connected) {\n return { client: apiKeyClient, authType: 'apiKey' };\n }\n } catch {\n // API key also failed\n logger.dim('API key auth failed.');\n }\n }\n\n // 3. Nothing worked\n return null;\n}\n\n/**\n * Ensure the token is fresh and update the client if needed.\n * Call this before long-running operations to avoid token expiration.\n *\n * @returns true if token was refreshed, false if no refresh needed or API key auth\n */\nexport async function ensureFreshToken(client: IFarseerClient): Promise<boolean> {\n const auth = getUserAuth();\n if (!auth) {\n return false; // No JWT auth, probably using API key\n }\n\n // Check if token needs refresh (give 30 second buffer)\n const expiresAt = new Date(auth.expiresAt);\n const now = new Date();\n const bufferMs = 30 * 1000; // 30 seconds\n\n if (expiresAt.getTime() - now.getTime() > bufferMs) {\n return false; // Token is still fresh enough\n }\n\n // Refresh the token\n logger.dim('Refreshing token before operation...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n\n if (!refreshed) {\n logger.warning('Could not refresh token.');\n return false;\n }\n\n // Save the new token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n\n // Update the client's token if it supports it\n if (client.updateAccessToken) {\n client.updateAccessToken(refreshed.accessToken);\n logger.dim('Token refreshed');\n return true;\n }\n\n return false;\n}\n\n/**\n * Get a native farseer-client FarseerClient instance.\n * This provides access to the full farseer-client API (export, import jobs, file creation, etc.)\n * that isn't available through the simplified IFarseerClient interface.\n *\n * Tries JWT first, then API key. Handles token refresh automatically.\n *\n * TECH DEBT \u2014 two parallel client stacks. `getFarseerClientWithFallback`\n * returns an `IFarseerClient` (a curated facade over the hand-rolled axios\n * `FarseerApi` for JWT and the SDK-wrapping `FarseerService` for API keys),\n * while this returns the raw SDK client for the richer read/query surface. The\n * duality is historical (the JWT path was hand-rolled instead of using the\n * SDK), not necessary \u2014 the SDK handles JWT fine. Because of it, `preflight`\n * runs its guard with the IFarseerClient and read/query commands then build a\n * second (native) client here from the same validated pair. Collapsing these\n * into one authenticated SDK client is planned as a follow-up; until then the\n * extra construction is deliberate.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header\n */\nexport async function getNativeFarseerClient(\n organisation: string,\n tenant: string,\n): Promise<farseer.FarseerClient | null> {\n const basePath = generateBasePath(organisation);\n\n // 1. Try JWT token first\n const auth = getUserAuth();\n if (auth) {\n let accessToken = auth.accessToken;\n\n if (!isUserAuthValid()) {\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n accessToken = refreshed.accessToken;\n }\n }\n\n if (isUserAuthValid()) {\n return new farseer.FarseerClient({\n basePath,\n headers: {\n 'X-TENANT-ID': tenant,\n Authorization: `Bearer ${accessToken}`,\n },\n });\n }\n }\n\n // 2. Try API key\n const credential = getCredential(tenant);\n if (credential) {\n return new farseer.FarseerClient({\n basePath: credential.basePath,\n headers: {\n 'X-TENANT-ID': credential.tenantId,\n 'X-API-KEY': credential.apiKey,\n },\n });\n }\n\n return null;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;
|
|
4
|
+
"sourcesContent": ["/**\n * Deciding which credential to use, and building clients from it.\n *\n * A browser login is preferred when there is a usable one, a stored API key\n * otherwise. The decision is made once, as a ResolvedAuth, and every client is\n * built from that.\n */\n\nimport axios from 'axios';\nimport * as farseer from 'farseer-client';\nimport { FarseerService } from './farseerService';\nimport { FarseerApi } from './farseerApi';\nimport type { ApiKeyCredential } from './configService';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from './configService';\nimport { refreshAccessToken } from './farseerService';\nimport { logger } from '../utils/logger';\n\n/**\n * A tenant the backend couldn't resolve at this host \u2014 it answers\n * `403 {\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`.\n * Despite the 403 this is NOT a credentials problem: it's what a wrong\n * organisation for an otherwise-valid tenant looks like, because every\n * tenant-scoped request carries X-TENANT-ID and the org's backend has no such\n * tenant. Telling the user to log in again would send them to fix the one thing\n * that isn't broken.\n */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * The backend's \"no such tenant at this host\" phrasing. Lives apart from\n * isTenantNotFoundError because the same sentence reaches us two ways: inside a\n * thrown Error from the SDK, and as the `message` field of an axios 403 body \u2014\n * where `error.message` is only ever \"Request failed with status code 403\".\n */\nfunction mentionsUnknownTenant(text: string | undefined): boolean {\n if (!text) {\n return false;\n }\n const msg = text.toLowerCase();\n return msg.includes('does not exist') && msg.includes('tenant');\n}\n\n/**\n * Check if an error is an authentication error (401/403).\n *\n * A 403 that names an unresolvable tenant is deliberately excluded \u2014 see\n * isTenantNotFoundError. Callers that show a login prompt on true would\n * otherwise misdiagnose a wrong-org command as expired credentials.\n */\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n if (error instanceof Error) {\n const msg = error.message.toLowerCase();\n return msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('forbidden');\n }\n return false;\n}\n\n/**\n * Show a consistent \"please login\" message\n */\nexport function showLoginPrompt(tenant?: string): void {\n logger.error('Authentication required.');\n if (tenant) {\n logger.dim(`No valid credentials found for tenant \"${tenant}\".`);\n }\n logger.info('Run \"farseer login\" to authenticate via browser.');\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n\nexport interface FileMetadata {\n uploadTime?: string; // ISO timestamp\n uploader?: {\n id: number;\n email: string;\n firstName: string;\n lastName: string;\n };\n size?: number;\n}\n\n/**\n * Canonical RemoteFile shape used by every layer of the CLI. Both\n * FarseerApi (JWT path) and FarseerService (API-key path) re-export this\n * type so downstream code (SyncService, MCP tools, tests) can rely on a\n * single definition. Earlier each layer declared its own copy that drifted\n * \u2014 three different shapes that disagreed on which optional fields existed,\n * which made it impossible to tell from a function signature what the\n * caller could assume was set.\n *\n * Optional fields are populated lazily:\n * - `content` \u2014 only set by callers that already fetched body bytes\n * (some legacy paths combined list + download in a single helper).\n * - `metadata` \u2014 populated by listFiles for the JWT path. The API-key\n * path doesn't return it, so consumers must handle absence.\n */\nexport interface RemoteFile {\n name: string;\n path: string;\n reference: string;\n content?: string;\n metadata?: FileMetadata;\n}\n\n// Mirrors the backend `OrganizationInfo` schema returned by GET /organization\n// (backend/app/openapi/v3/documentation/overseer/components.yaml). The org is\n// resolved from the request host (`<org>.farseer.io`); `tenants` is the\n// authoritative list of tenants that org actually owns in overseer. `checkout`\n// uses it to confirm the org+tenant pair the user typed is real \u2014 the backend\n// resolves a tenant from the X-TENANT-ID header alone and never checks it\n// against the org, so without this the org argument is an unvalidated routing\n// hint.\nexport interface OrganizationTenant {\n name: string;\n isDefault: boolean;\n}\n\nexport interface OrganizationInfo {\n id: string;\n host: string;\n version: string;\n tenants: OrganizationTenant[];\n}\n\n// Narrow set of \"script\" extensions \u2014 used by `farseer files list` and\n// `farseer list` to default to source-code style files when listing a\n// folder. NOT the default sync scope; see DEFAULT_SYNC_EXTENSIONS below.\nexport const DEFAULT_SCRIPT_EXTENSIONS = ['.ts', '.js'];\n\n// Default sync scope \u2014 the curated set of files a developer AUTHORS in an\n// editor. NARROWER than the backend's accepted extension list\n// (`cli/src/utils/fileValidation.ts:BACKEND_EXTENSION_WHITELIST`, which\n// mirrors `farseer/backend/app/openapi/v3/services/farseerFileService.ts`).\n// The earlier \"default sync = everything backend accepts\" expanded the\n// default scope to 25 entries including binary / data formats (.csv,\n// .parquet, .xlsx, .pdf, images) \u2014 large files no one edits in a code\n// editor that dominated first-pull time and made `status` noisy.\n//\n// Users opt into the rest of the backend whitelist (data / docs /\n// archives) via `--include-ext <ext>` or persistent\n// `farseer config include`. Anything still outside the backend whitelist\n// requires `--all` or `--include-folder`.\n//\n// Subset contract: every entry here must also be in\n// `BACKEND_EXTENSION_WHITELIST`, otherwise push pre-flight will reject\n// in-scope files (extension not allowed) \u2014 defeats the purpose of the\n// default scope. Asserted by `defaultSyncExtensionsParity.test.ts`.\nexport const DEFAULT_SYNC_EXTENSIONS = [\n // Code (frontend / scripts)\n '.ts',\n '.js',\n // Code (Python)\n '.py',\n // Config / data\n '.yml',\n '.yaml',\n '.json',\n // Docs\n '.md',\n];\n\nimport {\n AppListItem,\n AppUpdateChanges,\n RemoteApp,\n SourceFolderResolution,\n ModelExport,\n ModelExportOptions,\n ModelExportTable,\n} from './farseerApi';\n\n// Common interface that both FarseerService and FarseerApi implement\nexport interface IFarseerClient {\n testConnection(): Promise<boolean>;\n getOrganizationInfo(): Promise<OrganizationInfo>;\n getFilesFolder(): Promise<{ id: number; name: string; type: string } | null>;\n listFiles(folderPath?: string[]): Promise<RemoteFile[]>;\n getFileContent(reference: string): Promise<string>;\n getFileContentAsBuffer(reference: string): Promise<Buffer>;\n createFile(content: string | Buffer, fileName: string, folderPath?: string[]): Promise<void>;\n updateFile(reference: string, content: string | Buffer, fileName: string): Promise<void>;\n deleteFile(reference: string): Promise<void>;\n getFileByPath(filePath: string): Promise<RemoteFile | null>;\n getFileMetadata(reference: string): Promise<FileMetadata | null>;\n isTextFile(filename: string): boolean;\n isBinaryFile(filename: string): boolean;\n // Apps API methods\n listApps(): Promise<AppListItem[]>;\n getApp(referenceId: string): Promise<RemoteApp | null>;\n getAppByName(name: string): Promise<RemoteApp | null>;\n createApp(name: string): Promise<RemoteApp>;\n updateApp(referenceId: string, update: AppUpdateChanges, currentApp: RemoteApp): Promise<RemoteApp>;\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution>;\n deleteApp(remoteJobId: string): Promise<void>;\n getScriptFiles(): Promise<{ id: string; name: string }[]>;\n // Model export\n exportModel(options?: ModelExportOptions): Promise<ModelExport>;\n /**\n * Fetch a single dimension table with its members. Goes through\n * `entities/search` + `getRelations` + `getMany`, which scope the\n * fetch to one table \u2014 unlike `exportModel` with `tableGids`,\n * which currently 500s for some tables on large tenants\n * (rama-side scoping bug, tracked separately).\n */\n loadDimensionTableWithMembers(name: string): Promise<ModelExportTable | null>;\n // Token management (optional - only FarseerApi implements this)\n updateAccessToken?(newToken: string): void;\n}\n\nexport interface FarseerClientResult {\n client: IFarseerClient;\n authType: 'apiKey' | 'jwt';\n}\n\n/**\n * Return a usable browser-login access token, refreshing it first if it has\n * expired. Null when there's no browser login, or the refresh failed (caller\n * should fall back to an API key).\n */\nexport async function getFreshAccessToken(): Promise<string | null> {\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n if (isUserAuthValid()) {\n return auth.accessToken;\n }\n\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n logger.dim('Token refreshed');\n return refreshed.accessToken;\n}\n\nexport type TenantCheck =\n | { status: 'ok' }\n | { status: 'tenant-unknown' }\n | { status: 'no-such-org' }\n | { status: 'unauthorized' }\n | { status: 'unreachable'; message: string };\n\n/**\n * Ask an organisation, in one request, whether it has this tenant.\n *\n * `/organization` is resolved from the request host, and sending X-TENANT-ID\n * puts the request through the same tenant-resolution middleware every\n * tenant-scoped call passes through \u2014 so the answer is the real one rather than\n * an inference:\n *\n * 200 the pair resolves, and the token works\n * 403 \"Tenant with id <t> does not exist\" the org does not have this tenant\n * 404 no Farseer organisation at this host\n * 401 the token is no good\n *\n * The alternative \u2014 asking without the header and looking for the tenant in the\n * response list \u2014 cannot refute a pair, because that list holds only what the\n * CALLER can enumerate and that is a different permission: an account that gets\n * `[]` for org `kiwi` still has `X-TENANT-ID: kiwi` accepted at that same host.\n *\n * The 403 was originally read as an auth failure, which is why the header was\n * avoided at first; `isTenantNotFoundError` tells the two apart from the body,\n * so it no longer is. Any OTHER 403 stays inconclusive \u2014 an org-level\n * permission problem is not this tenant failing to exist.\n */\nexport async function checkTenantAtOrganisation(\n organisation: string,\n tenant: string,\n accessToken: string,\n): Promise<TenantCheck> {\n try {\n await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}`, 'X-TENANT-ID': tenant },\n timeout: 30000,\n });\n return { status: 'ok' };\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.response?.status === 401) {\n return { status: 'unauthorized' };\n }\n if (error.response?.status === 404) {\n return { status: 'no-such-org' };\n }\n const body = error.response?.data;\n const detail = typeof body === 'string' ? body : (body as { message?: string } | undefined)?.message;\n if (error.response?.status === 403 && mentionsUnknownTenant(detail)) {\n return { status: 'tenant-unknown' };\n }\n }\n return { status: 'unreachable', message: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/**\n * The tenants an organisation will admit to, for the CALLER. Best-effort and\n * hint-only: used to name the alternatives when a pair has already been refuted,\n * never to decide anything. Sends no tenant header \u2014 the pair is known bad by\n * this point, and including it would just 403 again.\n */\nexport async function fetchOrganizationTenants(organisation: string, accessToken: string): Promise<string[]> {\n try {\n const response = await axios.get<OrganizationInfo>(`${generateBasePath(organisation)}/organization`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n timeout: 30000,\n });\n return (response.data.tenants ?? []).map((t) => t.name);\n } catch {\n return [];\n }\n}\n\n// Decided once and handed to the builders, so the credential the guard\n// validated is the one the command runs on.\nexport type ResolvedAuth =\n | { kind: 'jwt'; accessToken: string; basePath: string; tenant: string }\n | { kind: 'apiKey'; credential: ApiKeyCredential };\n\n/**\n * Always the organisation that was typed. A stored key's basePath belongs to\n * that key; letting it stand in here made the host depend on whether a key\n * happened to be named after the organisation.\n */\nfunction jwtAuth(accessToken: string, organisation: string, tenant: string): ResolvedAuth {\n return { kind: 'jwt', accessToken, basePath: generateBasePath(organisation), tenant };\n}\n\n/** The curated CLI-level view \u2014 file sync, apps, model export. */\nexport function buildClient(auth: ResolvedAuth): IFarseerClient {\n return auth.kind === 'jwt'\n ? new FarseerApi(auth.accessToken, auth.basePath, auth.tenant)\n : new FarseerService(auth.credential);\n}\n\n/** The full SDK surface, for the read/query commands. Constructs only \u2014 no request. */\nexport function buildNativeClient(auth: ResolvedAuth): farseer.FarseerClient {\n if (auth.kind === 'jwt') {\n return new farseer.FarseerClient({\n basePath: auth.basePath,\n headers: { 'X-TENANT-ID': auth.tenant, Authorization: `Bearer ${auth.accessToken}` },\n });\n }\n return new farseer.FarseerClient({\n basePath: auth.credential.basePath,\n headers: { 'X-TENANT-ID': auth.credential.tenantId, 'X-API-KEY': auth.credential.apiKey },\n });\n}\n\n/** Pick by what's available. Nothing is sent, so it can't tell whether the credential works. */\nexport async function resolveAuth(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n return jwtAuth(accessToken, organisation, tenant);\n }\n\n const credential = getCredential(tenant);\n return credential ? { kind: 'apiKey', credential } : null;\n}\n\n/**\n * Pick one that actually connects. The probe is the point: a key is the only\n * thing that still works once the organisation route is dead.\n */\nexport async function resolveAuthByProbe(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n const auth = jwtAuth(accessToken, organisation, tenant);\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n\n const credential = getCredential(tenant);\n if (credential) {\n const auth: ResolvedAuth = { kind: 'apiKey', credential };\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('API key auth failed.');\n }\n\n return null;\n}\n\n/**\n * The same decision with a fresh browser token. A CLI command lives for one\n * request; an MCP server runs for hours, so the token is the part it re-takes.\n */\nexport async function refreshAuth(auth: ResolvedAuth): Promise<ResolvedAuth | null> {\n if (auth.kind === 'apiKey') {\n return auth;\n }\n const accessToken = await getFreshAccessToken();\n return accessToken ? { ...auth, accessToken } : null;\n}\n\nasync function connects(auth: ResolvedAuth): Promise<boolean> {\n try {\n return await buildClient(auth).testConnection();\n } catch {\n return false;\n }\n}\n\n/**\n * Get a Farseer client for the given organisation and tenant.\n * Tries JWT token first (supports apps), then falls back to API key.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClient(organisation: string, tenant: string): Promise<FarseerClientResult | null> {\n const auth = await resolveAuth(organisation, tenant);\n return auth ? { client: buildClient(auth), authType: auth.kind } : null;\n}\n\n/**\n * Check what authentication methods are available\n */\nexport function getAvailableAuth(tenant: string): {\n hasApiKey: boolean;\n hasJwt: boolean;\n jwtValid: boolean;\n} {\n const credential = getCredential(tenant);\n const auth = getUserAuth();\n\n return {\n hasApiKey: !!credential,\n hasJwt: !!auth,\n jwtValid: isUserAuthValid(),\n };\n}\n\n/**\n * Get a Farseer client with automatic fallback and connection testing.\n * This is the recommended way to get a client for commands.\n *\n * Flow:\n * 1. Try JWT if available and valid\n * 2. If JWT fails or unavailable, try API key\n * 3. If nothing works, return null (caller should show login prompt)\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header (e.g., \"tt-hotels-hr-dev\")\n */\nexport async function getFarseerClientWithFallback(\n organisation: string,\n tenant: string,\n): Promise<FarseerClientResult | null> {\n const auth = await resolveAuthByProbe(organisation, tenant);\n return auth ? { client: buildClient(auth), authType: auth.kind } : null;\n}\n\n/**\n * Ensure the token is fresh and update the client if needed.\n * Call this before long-running operations to avoid token expiration.\n *\n * @returns true if token was refreshed, false if no refresh needed or API key auth\n */\nexport async function ensureFreshToken(client: IFarseerClient): Promise<boolean> {\n const auth = getUserAuth();\n if (!auth) {\n return false; // No JWT auth, probably using API key\n }\n\n // Check if token needs refresh (give 30 second buffer)\n const expiresAt = new Date(auth.expiresAt);\n const now = new Date();\n const bufferMs = 30 * 1000; // 30 seconds\n\n if (expiresAt.getTime() - now.getTime() > bufferMs) {\n return false; // Token is still fresh enough\n }\n\n // Refresh the token\n logger.dim('Refreshing token before operation...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n\n if (!refreshed) {\n logger.warning('Could not refresh token.');\n return false;\n }\n\n // Save the new token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n\n // Update the client's token if it supports it\n if (client.updateAccessToken) {\n client.updateAccessToken(refreshed.accessToken);\n logger.dim('Token refreshed');\n return true;\n }\n\n return false;\n}\n\n/**\n * Get a native farseer-client FarseerClient instance for callers that resolve\n * their own target \u2014 the MCP tools, which don't run the preflight yet. Commands\n * take the one on PreflightResult instead, so the client they use is built from\n * the credential the guard validated.\n *\n * TECH DEBT \u2014 two client shapes over the same credential. `buildClient` returns\n * an `IFarseerClient` (a curated facade over the hand-rolled axios `FarseerApi`\n * for JWT and the SDK-wrapping `FarseerService` for API keys) while\n * `buildNativeClient` returns the raw SDK client for the richer read/query\n * surface. The split is historical \u2014 the JWT path was hand-rolled instead of\n * using the SDK, which the SDK handles fine \u2014 and collapsing the two into one\n * class is a follow-up. They can no longer disagree about *which* credential\n * they carry, which was the part that mattered.\n *\n * @param organisation - The organisation hostname (e.g., \"jgl\" for jgl.farseer.io)\n * @param tenant - Tenant name for X-TENANT-ID header\n */\nexport async function getNativeFarseerClient(\n organisation: string,\n tenant: string,\n): Promise<farseer.FarseerClient | null> {\n const auth = await resolveAuth(organisation, tenant);\n return auth ? buildNativeClient(auth) : null;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,mBAAkB;AAClB,cAAyB;AACzB,4BAA+B;AAC/B,wBAA2B;AAE3B,2BAA2F;AAC3F,IAAAA,yBAAmC;AACnC,oBAAuB;AAWhB,SAAS,sBAAsB,OAAyB;AAC3D,SAAO,iBAAiB,SAAS,sBAAsB,MAAM,OAAO;AACxE;AAQA,SAAS,sBAAsB,MAAmC;AAC9D,MAAI,CAAC,MAAM;AACP,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A,IACR,aAAa,UAAU;AAAA,IACvB,cAAc,UAAU;AAAA,IACxB,WAAW,IAAI,KAAK,KAAK,IAAI,IAAI,UAAU,YAAY,GAAI,EAAE,YAAY;AAAA,IACzE,OAAO,KAAK;AAAA,EAChB,CAAC;AAGD,MAAI,OAAO,mBAAmB;AAC1B,WAAO,kBAAkB,UAAU,WAAW;AAC9C,yBAAO,IAAI,iBAAiB;AAC5B,WAAO;AAAA,EACX;AAEA,SAAO;AACX;AAoBA,eAAsB,uBAClB,cACA,QACqC;AACrC,QAAM,OAAO,MAAM,YAAY,cAAc,MAAM;AACnD,SAAO,OAAO,kBAAkB,IAAI,IAAI;AAC5C;",
|
|
6
6
|
"names": ["import_farseerService", "axios"]
|
|
7
7
|
}
|
|
@@ -234,11 +234,10 @@ class FarseerService {
|
|
|
234
234
|
* List all apps (Remote Jobs) on the tenant
|
|
235
235
|
*/
|
|
236
236
|
async listApps() {
|
|
237
|
-
const response = await this.
|
|
237
|
+
const response = await this.client.remoteJobs.list();
|
|
238
238
|
return response.map((app) => ({
|
|
239
|
-
id: app.id,
|
|
240
239
|
name: app.name,
|
|
241
|
-
type:
|
|
240
|
+
type: import_farseerApi.REMOTE_JOB_ITEM_TYPE,
|
|
242
241
|
reference: String(app.id)
|
|
243
242
|
}));
|
|
244
243
|
}
|
|
@@ -308,11 +307,28 @@ class FarseerService {
|
|
|
308
307
|
}
|
|
309
308
|
return app;
|
|
310
309
|
}
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
310
|
+
// Never swallow a failure into an empty array: `resolveAppItemNodeId` reads
|
|
311
|
+
// "no match" as "this app doesn't exist".
|
|
312
|
+
async resolveRemoteJobItems(remoteJobIds) {
|
|
313
|
+
if (remoteJobIds.length === 0) {
|
|
314
|
+
return [];
|
|
315
|
+
}
|
|
316
|
+
try {
|
|
317
|
+
return await this.client.folders.resolveItems((0, import_farseerApi.remoteJobReverseReferences)(remoteJobIds));
|
|
318
|
+
} catch (error) {
|
|
319
|
+
throw await (0, import_errorFormatter.toError)(error, `Failed to resolve folder items for Remote Job(s): ${remoteJobIds.join(", ")}`);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// Takes the Remote Job id and resolves the folder-item id itself, so no
|
|
323
|
+
// caller can hand this a raw node id. See `resolveAppItemNodeId`.
|
|
324
|
+
async deleteApp(remoteJobId) {
|
|
325
|
+
const items = await this.resolveRemoteJobItems([remoteJobId]);
|
|
326
|
+
const itemNodeId = (0, import_farseerApi.resolveAppItemNodeId)(remoteJobId, items);
|
|
327
|
+
try {
|
|
328
|
+
await this.client.folders.deleteItemsBatch([{ id: itemNodeId }]);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
throw await (0, import_errorFormatter.toError)(error, `Failed to delete app (Remote Job id: ${remoteJobId})`);
|
|
331
|
+
}
|
|
316
332
|
}
|
|
317
333
|
/**
|
|
318
334
|
* Get script files available for apps
|