farseer-cli 1.11.2 → 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 +88 -10
- package/dist/commands/app.js +54 -4
- package/dist/commands/app.js.map +2 -2
- 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/prompts/workflows.js +2 -0
- package/dist/mcp/prompts/workflows.js.map +2 -2
- package/dist/mcp/tools/appTools.js +54 -4
- package/dist/mcp/tools/appTools.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/appSyncService.js +33 -1
- package/dist/services/appSyncService.js.map +2 -2
- package/dist/services/apps.js +199 -9
- package/dist/services/apps.js.map +3 -3
- 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 +95 -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/docs/cli-guide.md +16 -0
- package/package.json +1 -1
|
@@ -33,7 +33,8 @@ __export(farseerService_exports, {
|
|
|
33
33
|
getFreshAccessToken: () => getFreshAccessToken,
|
|
34
34
|
loginWithBrowser: () => loginWithBrowser,
|
|
35
35
|
refreshAccessToken: () => refreshAccessToken,
|
|
36
|
-
resolveRealm: () => resolveRealm
|
|
36
|
+
resolveRealm: () => resolveRealm,
|
|
37
|
+
revokeRefreshToken: () => revokeRefreshToken
|
|
37
38
|
});
|
|
38
39
|
module.exports = __toCommonJS(farseerService_exports);
|
|
39
40
|
var farseer = __toESM(require("farseer-client"));
|
|
@@ -64,10 +65,10 @@ function failureReason(error) {
|
|
|
64
65
|
}
|
|
65
66
|
return "server-error";
|
|
66
67
|
}
|
|
67
|
-
function freshTokenMiddleware() {
|
|
68
|
+
function freshTokenMiddleware(realm) {
|
|
68
69
|
return {
|
|
69
70
|
async pre({ url, init }) {
|
|
70
|
-
const accessToken = await getFreshAccessToken();
|
|
71
|
+
const accessToken = await getFreshAccessToken(realm);
|
|
71
72
|
if (!accessToken) {
|
|
72
73
|
return { url, init };
|
|
73
74
|
}
|
|
@@ -84,7 +85,7 @@ class FarseerService {
|
|
|
84
85
|
this.client = new farseer.FarseerClient({
|
|
85
86
|
basePath: basePathOf(auth),
|
|
86
87
|
headers: authHeaders(auth),
|
|
87
|
-
middleware: auth.kind === "jwt" ? [freshTokenMiddleware()] : []
|
|
88
|
+
middleware: auth.kind === "jwt" ? [freshTokenMiddleware(auth.realm)] : []
|
|
88
89
|
});
|
|
89
90
|
}
|
|
90
91
|
/**
|
|
@@ -400,6 +401,17 @@ class FarseerService {
|
|
|
400
401
|
}
|
|
401
402
|
return app;
|
|
402
403
|
}
|
|
404
|
+
async getRunnerImageRepositories() {
|
|
405
|
+
const response = await this.apiRequest("/remoteJobs/runnerImages", "GET");
|
|
406
|
+
return {
|
|
407
|
+
registryPrefix: response?.registryPrefix ?? "",
|
|
408
|
+
repositories: response?.repositories ?? []
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
async getRunners() {
|
|
412
|
+
const response = await this.apiRequest("/remoteJobs/runners", "GET");
|
|
413
|
+
return response?.runners ?? [];
|
|
414
|
+
}
|
|
403
415
|
// Never swallow a failure into an empty array: `resolveAppItemNodeId` reads
|
|
404
416
|
// "no match" as "this app doesn't exist".
|
|
405
417
|
async resolveRemoteJobItems(remoteJobIds) {
|
|
@@ -573,7 +585,7 @@ class FarseerService {
|
|
|
573
585
|
*/
|
|
574
586
|
async apiRequest(endpoint, method, body) {
|
|
575
587
|
const url = `${basePathOf(this.auth)}${endpoint}`;
|
|
576
|
-
const auth = this.auth.kind === "jwt" ? { ...this.auth, accessToken: await getFreshAccessToken() ?? this.auth.accessToken } : this.auth;
|
|
588
|
+
const auth = this.auth.kind === "jwt" ? { ...this.auth, accessToken: await getFreshAccessToken(this.auth.realm) ?? this.auth.accessToken } : this.auth;
|
|
577
589
|
const headers = {
|
|
578
590
|
"Content-Type": "application/json",
|
|
579
591
|
// The SDK stamps this from its own generated constant, and these
|
|
@@ -681,19 +693,42 @@ function getErrorPage(title, message) {
|
|
|
681
693
|
</html>
|
|
682
694
|
`;
|
|
683
695
|
}
|
|
684
|
-
async function loginWithBrowser(realm = "master") {
|
|
696
|
+
async function loginWithBrowser(realm = "master", { idpHint, viaMasterSession = false } = {}) {
|
|
685
697
|
const http = await import("http");
|
|
686
698
|
const crypto = await import("crypto");
|
|
687
699
|
const { exec } = await import("child_process");
|
|
688
700
|
const { promisify } = await import("util");
|
|
689
701
|
const execAsync = promisify(exec);
|
|
690
|
-
const
|
|
702
|
+
const keycloakBase = (r) => `https://login.farseer.io/auth/realms/${r}/protocol/openid-connect`;
|
|
691
703
|
const CLIENT_ID = "auth";
|
|
692
704
|
const REDIRECT_PORT = 8787;
|
|
693
705
|
const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`;
|
|
694
706
|
const codeVerifier = crypto.randomBytes(32).toString("base64url");
|
|
695
707
|
const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
|
|
696
708
|
const state = crypto.randomBytes(16).toString("hex");
|
|
709
|
+
const authorizationUrl = (legRealm, scope, legState, challenge, hint) => {
|
|
710
|
+
const authUrl = new URL(`${keycloakBase(legRealm)}/auth`);
|
|
711
|
+
authUrl.searchParams.set("client_id", CLIENT_ID);
|
|
712
|
+
authUrl.searchParams.set("redirect_uri", REDIRECT_URI);
|
|
713
|
+
authUrl.searchParams.set("response_type", "code");
|
|
714
|
+
authUrl.searchParams.set("scope", scope);
|
|
715
|
+
authUrl.searchParams.set("state", legState);
|
|
716
|
+
authUrl.searchParams.set("code_challenge", challenge);
|
|
717
|
+
authUrl.searchParams.set("code_challenge_method", "S256");
|
|
718
|
+
if (hint) {
|
|
719
|
+
authUrl.searchParams.set("kc_idp_hint", hint);
|
|
720
|
+
}
|
|
721
|
+
return authUrl.toString();
|
|
722
|
+
};
|
|
723
|
+
const loginUrl = authorizationUrl(realm, "openid offline_access", state, codeChallenge, idpHint);
|
|
724
|
+
const masterState = crypto.randomBytes(16).toString("hex");
|
|
725
|
+
const masterUrl = authorizationUrl(
|
|
726
|
+
import_configService.DEFAULT_REALM,
|
|
727
|
+
"openid",
|
|
728
|
+
masterState,
|
|
729
|
+
crypto.createHash("sha256").update(crypto.randomBytes(32).toString("base64url")).digest("base64url")
|
|
730
|
+
);
|
|
731
|
+
let masterSessionOpened = false;
|
|
697
732
|
return new Promise((resolve) => {
|
|
698
733
|
const server = http.createServer(async (req, res) => {
|
|
699
734
|
const url = new URL(req.url || "", `http://localhost:${REDIRECT_PORT}`);
|
|
@@ -701,22 +736,33 @@ async function loginWithBrowser(realm = "master") {
|
|
|
701
736
|
const code = url.searchParams.get("code");
|
|
702
737
|
const returnedState = url.searchParams.get("state");
|
|
703
738
|
const error = url.searchParams.get("error");
|
|
739
|
+
if (error === "login_required" && returnedState === state && viaMasterSession && !masterSessionOpened) {
|
|
740
|
+
masterSessionOpened = true;
|
|
741
|
+
res.writeHead(302, { Location: masterUrl });
|
|
742
|
+
res.end();
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
704
745
|
if (error) {
|
|
705
746
|
res.writeHead(200, { "Content-Type": "text/html" });
|
|
706
747
|
res.end(getErrorPage("Login Failed", `Error: ${error}`));
|
|
707
748
|
server.close();
|
|
708
|
-
resolve(
|
|
749
|
+
resolve({ ok: false, error });
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (code && returnedState === masterState && masterSessionOpened) {
|
|
753
|
+
res.writeHead(302, { Location: loginUrl });
|
|
754
|
+
res.end();
|
|
709
755
|
return;
|
|
710
756
|
}
|
|
711
757
|
if (!code || returnedState !== state) {
|
|
712
758
|
res.writeHead(400, { "Content-Type": "text/html" });
|
|
713
759
|
res.end(getErrorPage("Invalid Response", "Missing code or state mismatch."));
|
|
714
760
|
server.close();
|
|
715
|
-
resolve(
|
|
761
|
+
resolve({ ok: false });
|
|
716
762
|
return;
|
|
717
763
|
}
|
|
718
764
|
try {
|
|
719
|
-
const tokenResponse = await fetch(`${
|
|
765
|
+
const tokenResponse = await fetch(`${keycloakBase(realm)}/token`, {
|
|
720
766
|
method: "POST",
|
|
721
767
|
headers: {
|
|
722
768
|
"Content-Type": "application/x-www-form-urlencoded"
|
|
@@ -807,6 +853,7 @@ async function loginWithBrowser(realm = "master") {
|
|
|
807
853
|
`);
|
|
808
854
|
server.close();
|
|
809
855
|
resolve({
|
|
856
|
+
ok: true,
|
|
810
857
|
accessToken: data.access_token,
|
|
811
858
|
refreshToken: data.refresh_token,
|
|
812
859
|
expiresIn: data.expires_in
|
|
@@ -815,20 +862,12 @@ async function loginWithBrowser(realm = "master") {
|
|
|
815
862
|
res.writeHead(500, { "Content-Type": "text/html" });
|
|
816
863
|
res.end(getErrorPage("Token Exchange Failed", "Could not complete login."));
|
|
817
864
|
server.close();
|
|
818
|
-
resolve(
|
|
865
|
+
resolve({ ok: false });
|
|
819
866
|
}
|
|
820
867
|
}
|
|
821
868
|
});
|
|
822
869
|
server.listen(REDIRECT_PORT, async () => {
|
|
823
|
-
const
|
|
824
|
-
authUrl.searchParams.set("client_id", CLIENT_ID);
|
|
825
|
-
authUrl.searchParams.set("redirect_uri", REDIRECT_URI);
|
|
826
|
-
authUrl.searchParams.set("response_type", "code");
|
|
827
|
-
authUrl.searchParams.set("scope", "openid offline_access");
|
|
828
|
-
authUrl.searchParams.set("state", state);
|
|
829
|
-
authUrl.searchParams.set("code_challenge", codeChallenge);
|
|
830
|
-
authUrl.searchParams.set("code_challenge_method", "S256");
|
|
831
|
-
const url = authUrl.toString();
|
|
870
|
+
const url = loginUrl;
|
|
832
871
|
try {
|
|
833
872
|
if (process.platform === "darwin") {
|
|
834
873
|
await execAsync(`open "${url}"`);
|
|
@@ -847,20 +886,23 @@ ${url}
|
|
|
847
886
|
setTimeout(
|
|
848
887
|
() => {
|
|
849
888
|
server.close();
|
|
850
|
-
resolve(
|
|
889
|
+
resolve({ ok: false });
|
|
851
890
|
},
|
|
852
891
|
5 * 60 * 1e3
|
|
853
892
|
);
|
|
854
893
|
});
|
|
855
894
|
}
|
|
856
|
-
|
|
857
|
-
function getFreshAccessToken() {
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
895
|
+
const refreshesInFlight = /* @__PURE__ */ new Map();
|
|
896
|
+
function getFreshAccessToken(realm = import_configService.DEFAULT_REALM) {
|
|
897
|
+
let inFlight = refreshesInFlight.get(realm);
|
|
898
|
+
if (!inFlight) {
|
|
899
|
+
inFlight = mintAccessToken(realm).finally(() => refreshesInFlight.delete(realm));
|
|
900
|
+
refreshesInFlight.set(realm, inFlight);
|
|
901
|
+
}
|
|
902
|
+
return inFlight;
|
|
861
903
|
}
|
|
862
|
-
async function mintAccessToken() {
|
|
863
|
-
const auth = (0, import_configService.getUserAuth)();
|
|
904
|
+
async function mintAccessToken(realm) {
|
|
905
|
+
const auth = (0, import_configService.getUserAuth)(realm);
|
|
864
906
|
if (!auth) {
|
|
865
907
|
return null;
|
|
866
908
|
}
|
|
@@ -868,19 +910,35 @@ async function mintAccessToken() {
|
|
|
868
910
|
return auth.accessToken;
|
|
869
911
|
}
|
|
870
912
|
import_logger.logger.dim("Token expired, refreshing...");
|
|
871
|
-
const refreshed = await refreshAccessToken(auth.refreshToken,
|
|
913
|
+
const refreshed = await refreshAccessToken(auth.refreshToken, realm);
|
|
872
914
|
if (!refreshed) {
|
|
873
915
|
return null;
|
|
874
916
|
}
|
|
875
|
-
(0, import_configService.setUserAuth)(
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
917
|
+
(0, import_configService.setUserAuth)(
|
|
918
|
+
{
|
|
919
|
+
accessToken: refreshed.accessToken,
|
|
920
|
+
refreshToken: refreshed.refreshToken,
|
|
921
|
+
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
922
|
+
realm
|
|
923
|
+
},
|
|
924
|
+
{ refresh: true }
|
|
925
|
+
);
|
|
881
926
|
import_logger.logger.dim("Token refreshed");
|
|
882
927
|
return refreshed.accessToken;
|
|
883
928
|
}
|
|
929
|
+
async function revokeRefreshToken(realm, refreshToken) {
|
|
930
|
+
try {
|
|
931
|
+
const response = await fetch(`https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/logout`, {
|
|
932
|
+
method: "POST",
|
|
933
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
934
|
+
body: new URLSearchParams({ client_id: "auth", refresh_token: refreshToken }),
|
|
935
|
+
signal: AbortSignal.timeout(1e4)
|
|
936
|
+
});
|
|
937
|
+
return response.ok;
|
|
938
|
+
} catch {
|
|
939
|
+
return false;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
884
942
|
async function refreshAccessToken(refreshToken, realm = "master") {
|
|
885
943
|
const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;
|
|
886
944
|
try {
|
|
@@ -915,6 +973,7 @@ async function refreshAccessToken(refreshToken, realm = "master") {
|
|
|
915
973
|
getFreshAccessToken,
|
|
916
974
|
loginWithBrowser,
|
|
917
975
|
refreshAccessToken,
|
|
918
|
-
resolveRealm
|
|
976
|
+
resolveRealm,
|
|
977
|
+
revokeRefreshToken
|
|
919
978
|
});
|
|
920
979
|
//# sourceMappingURL=farseerService.js.map
|
|
@@ -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 REMOTE_JOB_ITEM_TYPE,\n RemoteApp,\n ResolvedFolderItem,\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 // 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,kBAUO;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,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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;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YAAY,GAAI,EAAE,YAAY;AAAA,MACzE;AAAA,IACJ;AAAA,IACA,EAAE,SAAS,KAAK;AAAA,EACpB;AACA,uBAAO,IAAI,iBAAiB;AAC5B,SAAO,UAAU;AACrB;AAOA,eAAsB,mBAAmB,OAAe,cAAwC;AAC5F,MAAI;AACA,UAAM,WAAW,MAAM,MAAM,wCAAwC,KAAK,mCAAmC;AAAA,MACzG,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,MAC/D,MAAM,IAAI,gBAAgB,EAAE,WAAW,QAAQ,eAAe,aAAa,CAAC;AAAA,MAC5E,QAAQ,YAAY,QAAQ,GAAK;AAAA,IACrC,CAAC;AACD,WAAO,SAAS;AAAA,EACpB,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;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;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -38,6 +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") {
|