farseer-cli 1.12.0 → 1.14.1

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.
Files changed (101) hide show
  1. package/README.md +51 -18
  2. package/dist/commands/login.js +60 -26
  3. package/dist/commands/login.js.map +2 -2
  4. package/dist/commands/logout.js +37 -12
  5. package/dist/commands/logout.js.map +3 -3
  6. package/dist/commands/pipeline.js +158 -0
  7. package/dist/commands/pipeline.js.map +7 -0
  8. package/dist/commands/run.js +10 -27
  9. package/dist/commands/run.js.map +2 -2
  10. package/dist/commands/variables.js +17 -8
  11. package/dist/commands/variables.js.map +2 -2
  12. package/dist/commands/whoami.js +10 -14
  13. package/dist/commands/whoami.js.map +2 -2
  14. package/dist/index.js +40 -46
  15. package/dist/index.js.map +2 -2
  16. package/dist/mcp/prompts/workflows.js +13 -68
  17. package/dist/mcp/prompts/workflows.js.map +2 -2
  18. package/dist/mcp/resources/documentation.js +14 -0
  19. package/dist/mcp/resources/documentation.js.map +2 -2
  20. package/dist/mcp/server.js +14 -2
  21. package/dist/mcp/server.js.map +2 -2
  22. package/dist/mcp/skills.js +59 -0
  23. package/dist/mcp/skills.js.map +7 -0
  24. package/dist/mcp/tools/appTools.js +4 -0
  25. package/dist/mcp/tools/appTools.js.map +2 -2
  26. package/dist/mcp/tools/authTools.js +5 -2
  27. package/dist/mcp/tools/authTools.js.map +2 -2
  28. package/dist/mcp/tools/dataTools.js +2 -0
  29. package/dist/mcp/tools/dataTools.js.map +2 -2
  30. package/dist/mcp/tools/modelTools.js +6 -41
  31. package/dist/mcp/tools/modelTools.js.map +2 -2
  32. package/dist/mcp/tools/pipelineContract.js +317 -0
  33. package/dist/mcp/tools/pipelineContract.js.map +7 -0
  34. package/dist/mcp/tools/pipelineTools.js +111 -0
  35. package/dist/mcp/tools/pipelineTools.js.map +7 -0
  36. package/dist/mcp/tools/runTools.js +7 -18
  37. package/dist/mcp/tools/runTools.js.map +2 -2
  38. package/dist/mcp/tools/syncTools.js +4 -0
  39. package/dist/mcp/tools/syncTools.js.map +2 -2
  40. package/dist/mcp/utils/helpers.js +16 -6
  41. package/dist/mcp/utils/helpers.js.map +3 -3
  42. package/dist/mcp/utils/session.js +14 -9
  43. package/dist/mcp/utils/session.js.map +2 -2
  44. package/dist/pipeline/compatibility.js +53 -0
  45. package/dist/pipeline/compatibility.js.map +7 -0
  46. package/dist/pipeline/connect.js +139 -0
  47. package/dist/pipeline/connect.js.map +7 -0
  48. package/dist/pipeline/create.js +158 -0
  49. package/dist/pipeline/create.js.map +7 -0
  50. package/dist/pipeline/errors.js +45 -0
  51. package/dist/pipeline/errors.js.map +7 -0
  52. package/dist/pipeline/generated-reference.json +115 -0
  53. package/dist/pipeline/guide.js +33 -0
  54. package/dist/pipeline/guide.js.map +7 -0
  55. package/dist/pipeline/init.js +204 -0
  56. package/dist/pipeline/init.js.map +7 -0
  57. package/dist/pipeline/operations.js +103 -0
  58. package/dist/pipeline/operations.js.map +7 -0
  59. package/dist/pipeline/query.js +103 -0
  60. package/dist/pipeline/query.js.map +7 -0
  61. package/dist/pipeline/queryWorker.js +119 -0
  62. package/dist/pipeline/queryWorker.js.map +7 -0
  63. package/dist/pipeline/readiness.js +55 -0
  64. package/dist/pipeline/readiness.js.map +7 -0
  65. package/dist/pipeline/reference.js +72 -0
  66. package/dist/pipeline/reference.js.map +7 -0
  67. package/dist/pipeline/requests.js +122 -0
  68. package/dist/pipeline/requests.js.map +7 -0
  69. package/dist/pipeline/runArguments.js +68 -0
  70. package/dist/pipeline/runArguments.js.map +7 -0
  71. package/dist/pipeline/runtime.js +105 -0
  72. package/dist/pipeline/runtime.js.map +7 -0
  73. package/dist/pipeline/service.js +967 -0
  74. package/dist/pipeline/service.js.map +7 -0
  75. package/dist/services/agentApprovalFetch.js +86 -0
  76. package/dist/services/agentApprovalFetch.js.map +7 -0
  77. package/dist/services/authErrors.js +2 -2
  78. package/dist/services/authErrors.js.map +2 -2
  79. package/dist/services/configService.js +74 -9
  80. package/dist/services/configService.js.map +2 -2
  81. package/dist/services/credentials.js +12 -7
  82. package/dist/services/credentials.js.map +2 -2
  83. package/dist/services/farseerService.js +94 -39
  84. package/dist/services/farseerService.js.map +2 -2
  85. package/dist/services/preflight.js +7 -2
  86. package/dist/services/preflight.js.map +2 -2
  87. package/dist/services/realms.js +67 -0
  88. package/dist/services/realms.js.map +7 -0
  89. package/dist/services/syncService.js +6 -0
  90. package/dist/services/syncService.js.map +2 -2
  91. package/dist/skills/pipeline.js +71 -0
  92. package/dist/skills/pipeline.js.map +7 -0
  93. package/dist/utils/helpers.js +2 -1
  94. package/dist/utils/helpers.js.map +2 -2
  95. package/dist/utils/variableValues.js +78 -0
  96. package/dist/utils/variableValues.js.map +7 -0
  97. package/docs/pipeline-client-guide.md +67 -0
  98. package/docs/pipeline-reference.md +2064 -0
  99. package/package.json +5 -1
  100. package/skills/pipeline-authoring/SKILL.md +95 -0
  101. package/skills/pipeline-authoring/practices.md +325 -0
@@ -27,26 +27,31 @@ __export(credentials_exports, {
27
27
  module.exports = __toCommonJS(credentials_exports);
28
28
  var import_farseerService = require("./farseerService");
29
29
  var import_configService = require("./configService");
30
+ var import_realms = require("./realms");
30
31
  var import_logger = require("../utils/logger");
31
32
  var import_farseerService2 = require("./farseerService");
32
- function jwtAuth(accessToken, organisation, tenant) {
33
- return { kind: "jwt", accessToken, basePath: (0, import_configService.generateBasePath)(organisation), tenant };
33
+ function jwtAuth(accessToken, organisation, tenant, realm) {
34
+ return { kind: "jwt", accessToken, basePath: (0, import_configService.generateBasePath)(organisation), tenant, realm };
34
35
  }
35
36
  function buildClient(auth) {
36
37
  return new import_farseerService.FarseerService(auth);
37
38
  }
38
39
  async function resolveAuth(organisation, tenant) {
39
- const accessToken = await (0, import_farseerService.getFreshAccessToken)();
40
+ if ((0, import_configService.environmentCredential)()) return { kind: "apiKey", credential: (0, import_configService.getCredential)(tenant) };
41
+ const realm = await (0, import_realms.realmForOrganisation)(organisation);
42
+ const accessToken = await (0, import_farseerService.getFreshAccessToken)(realm);
40
43
  if (accessToken) {
41
- return jwtAuth(accessToken, organisation, tenant);
44
+ return jwtAuth(accessToken, organisation, tenant, realm);
42
45
  }
43
46
  const credential = (0, import_configService.getCredential)(tenant);
44
47
  return credential ? { kind: "apiKey", credential } : null;
45
48
  }
46
49
  async function resolveAuthByProbe(organisation, tenant) {
47
- const accessToken = await (0, import_farseerService.getFreshAccessToken)();
50
+ if ((0, import_configService.environmentCredential)()) return { kind: "apiKey", credential: (0, import_configService.getCredential)(tenant) };
51
+ const realm = await (0, import_realms.realmForOrganisation)(organisation);
52
+ const accessToken = await (0, import_farseerService.getFreshAccessToken)(realm);
48
53
  if (accessToken) {
49
- const auth = jwtAuth(accessToken, organisation, tenant);
54
+ const auth = jwtAuth(accessToken, organisation, tenant, realm);
50
55
  if (await connects(auth)) {
51
56
  return auth;
52
57
  }
@@ -66,7 +71,7 @@ async function refreshAuth(auth) {
66
71
  if (auth.kind === "apiKey") {
67
72
  return auth;
68
73
  }
69
- const accessToken = await (0, import_farseerService.getFreshAccessToken)();
74
+ const accessToken = await (0, import_farseerService.getFreshAccessToken)(auth.realm);
70
75
  return accessToken ? { ...auth, accessToken } : null;
71
76
  }
72
77
  async function connects(auth) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/services/credentials.ts"],
4
- "sourcesContent": ["/**\n * Deciding which credential a command runs on.\n *\n * A browser login is preferred when there is a usable one, a stored API key\n * otherwise. The decision is made once, as a ResolvedAuth, and the client is\n * built from that \u2014 nothing downstream re-derives it.\n */\n\nimport { FarseerService, getFreshAccessToken, type ResolvedAuth } from './farseerService';\nimport { getCredential, generateBasePath } from './configService';\nimport { logger } from '../utils/logger';\n\n// Defined next to the refresh it calls, re-exported where callers look for it.\nexport { getFreshAccessToken } from './farseerService';\n\n/**\n * Always the organisation that was typed. A stored key's basePath belongs to\n * that key; letting it stand in here made the host depend on whether a key\n * happened to be named after the organisation.\n */\nfunction jwtAuth(accessToken: string, organisation: string, tenant: string): ResolvedAuth {\n return { kind: 'jwt', accessToken, basePath: generateBasePath(organisation), tenant };\n}\n\nexport function buildClient(auth: ResolvedAuth): FarseerService {\n return new FarseerService(auth);\n}\n\n/** Pick by what's available. Nothing is sent, so it can't tell whether the credential works. */\nexport async function resolveAuth(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n return jwtAuth(accessToken, organisation, tenant);\n }\n\n const credential = getCredential(tenant);\n return credential ? { kind: 'apiKey', credential } : null;\n}\n\n/**\n * Pick one that actually connects. The probe is the point: a key is the only\n * thing that still works once the organisation route is dead.\n */\nexport async function resolveAuthByProbe(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n const auth = jwtAuth(accessToken, organisation, tenant);\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n\n const credential = getCredential(tenant);\n if (credential) {\n const auth: ResolvedAuth = { kind: 'apiKey', credential };\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('API key auth failed.');\n }\n\n return null;\n}\n\n/**\n * The same decision with a fresh browser token. A CLI command lives for one\n * request; an MCP server runs for hours, so the token is the part it re-takes.\n */\nexport async function refreshAuth(auth: ResolvedAuth): Promise<ResolvedAuth | null> {\n if (auth.kind === 'apiKey') {\n return auth;\n }\n const accessToken = await getFreshAccessToken();\n return accessToken ? { ...auth, accessToken } : null;\n}\n\nasync function connects(auth: ResolvedAuth): Promise<boolean> {\n const connection = await buildClient(auth).checkConnection();\n if (!connection.ok && connection.reason !== 'rejected') {\n // Nothing rejected the credential. Say so here: the caller's only\n // remaining move is \"no credential worked\", which blames the wrong thing.\n logger.dim(`The credential could not be checked: ${connection.message}`);\n }\n return connection.ok;\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,4BAAuE;AACvE,2BAAgD;AAChD,oBAAuB;AAGvB,IAAAA,yBAAoC;AAOpC,SAAS,QAAQ,aAAqB,cAAsB,QAA8B;AACtF,SAAO,EAAE,MAAM,OAAO,aAAa,cAAU,uCAAiB,YAAY,GAAG,OAAO;AACxF;AAEO,SAAS,YAAY,MAAoC;AAC5D,SAAO,IAAI,qCAAe,IAAI;AAClC;AAGA,eAAsB,YAAY,cAAsB,QAA8C;AAClG,QAAM,cAAc,UAAM,2CAAoB;AAC9C,MAAI,aAAa;AACb,WAAO,QAAQ,aAAa,cAAc,MAAM;AAAA,EACpD;AAEA,QAAM,iBAAa,oCAAc,MAAM;AACvC,SAAO,aAAa,EAAE,MAAM,UAAU,WAAW,IAAI;AACzD;AAMA,eAAsB,mBAAmB,cAAsB,QAA8C;AACzG,QAAM,cAAc,UAAM,2CAAoB;AAC9C,MAAI,aAAa;AACb,UAAM,OAAO,QAAQ,aAAa,cAAc,MAAM;AACtD,QAAI,MAAM,SAAS,IAAI,GAAG;AACtB,aAAO;AAAA,IACX;AACA,yBAAO,IAAI,oDAAoD;AAAA,EACnE;AAEA,QAAM,iBAAa,oCAAc,MAAM;AACvC,MAAI,YAAY;AACZ,UAAM,OAAqB,EAAE,MAAM,UAAU,WAAW;AACxD,QAAI,MAAM,SAAS,IAAI,GAAG;AACtB,aAAO;AAAA,IACX;AACA,yBAAO,IAAI,sBAAsB;AAAA,EACrC;AAEA,SAAO;AACX;AAMA,eAAsB,YAAY,MAAkD;AAChF,MAAI,KAAK,SAAS,UAAU;AACxB,WAAO;AAAA,EACX;AACA,QAAM,cAAc,UAAM,2CAAoB;AAC9C,SAAO,cAAc,EAAE,GAAG,MAAM,YAAY,IAAI;AACpD;AAEA,eAAe,SAAS,MAAsC;AAC1D,QAAM,aAAa,MAAM,YAAY,IAAI,EAAE,gBAAgB;AAC3D,MAAI,CAAC,WAAW,MAAM,WAAW,WAAW,YAAY;AAGpD,yBAAO,IAAI,wCAAwC,WAAW,OAAO,EAAE;AAAA,EAC3E;AACA,SAAO,WAAW;AACtB;",
4
+ "sourcesContent": ["/**\n * Deciding which credential a command runs on.\n *\n * A browser login is preferred when there is a usable one, a stored API key\n * otherwise. The decision is made once, as a ResolvedAuth, and the client is\n * built from that \u2014 nothing downstream re-derives it.\n */\n\nimport { FarseerService, getFreshAccessToken, type ResolvedAuth } from './farseerService';\nimport { getCredential, generateBasePath, environmentCredential } from './configService';\nimport { realmForOrganisation } from './realms';\nimport { logger } from '../utils/logger';\n\n// Defined next to the refresh it calls, re-exported where callers look for it.\nexport { getFreshAccessToken } from './farseerService';\n\n/**\n * Always the organisation that was typed. A stored key's basePath belongs to\n * that key; letting it stand in here made the host depend on whether a key\n * happened to be named after the organisation.\n */\nfunction jwtAuth(accessToken: string, organisation: string, tenant: string, realm: string): ResolvedAuth {\n return { kind: 'jwt', accessToken, basePath: generateBasePath(organisation), tenant, realm };\n}\n\nexport function buildClient(auth: ResolvedAuth): FarseerService {\n return new FarseerService(auth);\n}\n\n/** Pick by what's available. Nothing is sent, so it can't tell whether the credential works. */\nexport async function resolveAuth(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n if (environmentCredential()) return { kind: 'apiKey', credential: getCredential(tenant)! };\n const realm = await realmForOrganisation(organisation);\n const accessToken = await getFreshAccessToken(realm);\n if (accessToken) {\n return jwtAuth(accessToken, organisation, tenant, realm);\n }\n\n const credential = getCredential(tenant);\n return credential ? { kind: 'apiKey', credential } : null;\n}\n\n/**\n * Pick one that actually connects. The probe is the point: a key is the only\n * thing that still works once the organisation route is dead.\n */\nexport async function resolveAuthByProbe(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n if (environmentCredential()) return { kind: 'apiKey', credential: getCredential(tenant)! };\n const realm = await realmForOrganisation(organisation);\n const accessToken = await getFreshAccessToken(realm);\n if (accessToken) {\n const auth = jwtAuth(accessToken, organisation, tenant, realm);\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n\n const credential = getCredential(tenant);\n if (credential) {\n const auth: ResolvedAuth = { kind: 'apiKey', credential };\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('API key auth failed.');\n }\n\n return null;\n}\n\n/**\n * The same decision with a fresh browser token. A CLI command lives for one\n * request; an MCP server runs for hours, so the token is the part it re-takes.\n */\nexport async function refreshAuth(auth: ResolvedAuth): Promise<ResolvedAuth | null> {\n if (auth.kind === 'apiKey') {\n return auth;\n }\n const accessToken = await getFreshAccessToken(auth.realm);\n return accessToken ? { ...auth, accessToken } : null;\n}\n\nasync function connects(auth: ResolvedAuth): Promise<boolean> {\n const connection = await buildClient(auth).checkConnection();\n if (!connection.ok && connection.reason !== 'rejected') {\n // Nothing rejected the credential. Say so here: the caller's only\n // remaining move is \"no credential worked\", which blames the wrong thing.\n logger.dim(`The credential could not be checked: ${connection.message}`);\n }\n return connection.ok;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,4BAAuE;AACvE,2BAAuE;AACvE,oBAAqC;AACrC,oBAAuB;AAGvB,IAAAA,yBAAoC;AAOpC,SAAS,QAAQ,aAAqB,cAAsB,QAAgB,OAA6B;AACrG,SAAO,EAAE,MAAM,OAAO,aAAa,cAAU,uCAAiB,YAAY,GAAG,QAAQ,MAAM;AAC/F;AAEO,SAAS,YAAY,MAAoC;AAC5D,SAAO,IAAI,qCAAe,IAAI;AAClC;AAGA,eAAsB,YAAY,cAAsB,QAA8C;AAClG,UAAI,4CAAsB,EAAG,QAAO,EAAE,MAAM,UAAU,gBAAY,oCAAc,MAAM,EAAG;AACzF,QAAM,QAAQ,UAAM,oCAAqB,YAAY;AACrD,QAAM,cAAc,UAAM,2CAAoB,KAAK;AACnD,MAAI,aAAa;AACb,WAAO,QAAQ,aAAa,cAAc,QAAQ,KAAK;AAAA,EAC3D;AAEA,QAAM,iBAAa,oCAAc,MAAM;AACvC,SAAO,aAAa,EAAE,MAAM,UAAU,WAAW,IAAI;AACzD;AAMA,eAAsB,mBAAmB,cAAsB,QAA8C;AACzG,UAAI,4CAAsB,EAAG,QAAO,EAAE,MAAM,UAAU,gBAAY,oCAAc,MAAM,EAAG;AACzF,QAAM,QAAQ,UAAM,oCAAqB,YAAY;AACrD,QAAM,cAAc,UAAM,2CAAoB,KAAK;AACnD,MAAI,aAAa;AACb,UAAM,OAAO,QAAQ,aAAa,cAAc,QAAQ,KAAK;AAC7D,QAAI,MAAM,SAAS,IAAI,GAAG;AACtB,aAAO;AAAA,IACX;AACA,yBAAO,IAAI,oDAAoD;AAAA,EACnE;AAEA,QAAM,iBAAa,oCAAc,MAAM;AACvC,MAAI,YAAY;AACZ,UAAM,OAAqB,EAAE,MAAM,UAAU,WAAW;AACxD,QAAI,MAAM,SAAS,IAAI,GAAG;AACtB,aAAO;AAAA,IACX;AACA,yBAAO,IAAI,sBAAsB;AAAA,EACrC;AAEA,SAAO;AACX;AAMA,eAAsB,YAAY,MAAkD;AAChF,MAAI,KAAK,SAAS,UAAU;AACxB,WAAO;AAAA,EACX;AACA,QAAM,cAAc,UAAM,2CAAoB,KAAK,KAAK;AACxD,SAAO,cAAc,EAAE,GAAG,MAAM,YAAY,IAAI;AACpD;AAEA,eAAe,SAAS,MAAsC;AAC1D,QAAM,aAAa,MAAM,YAAY,IAAI,EAAE,gBAAgB;AAC3D,MAAI,CAAC,WAAW,MAAM,WAAW,WAAW,YAAY;AAGpD,yBAAO,IAAI,wCAAwC,WAAW,OAAO,EAAE;AAAA,EAC3E;AACA,SAAO,WAAW;AACtB;",
6
6
  "names": ["import_farseerService"]
7
7
  }
@@ -33,9 +33,12 @@ __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);
40
+ var import_constants = require("../utils/constants");
41
+ var import_requests = require("../pipeline/requests");
39
42
  var farseer = __toESM(require("farseer-client"));
40
43
  var import_apiVersion = require("farseer-client/dist/generated/apiVersion");
41
44
  var import_configService = require("./configService");
@@ -50,7 +53,8 @@ function basePathOf(auth) {
50
53
  return auth.kind === "jwt" ? auth.basePath : auth.credential.basePath;
51
54
  }
52
55
  function authHeaders(auth) {
53
- return auth.kind === "jwt" ? { "X-TENANT-ID": auth.tenant, Authorization: `Bearer ${auth.accessToken}` } : { "X-TENANT-ID": auth.credential.tenantId, "X-API-KEY": auth.credential.apiKey };
56
+ const common = { "X-FARSEER-CLI-VERSION": import_constants.CLI_VERSION };
57
+ return auth.kind === "jwt" ? { ...common, "X-TENANT-ID": auth.tenant, Authorization: `Bearer ${auth.accessToken}` } : { ...common, "X-TENANT-ID": auth.credential.tenantId, "X-API-KEY": auth.credential.apiKey };
54
58
  }
55
59
  function failureReason(error) {
56
60
  if (!(error instanceof import_httpError.HttpError)) {
@@ -64,10 +68,10 @@ function failureReason(error) {
64
68
  }
65
69
  return "server-error";
66
70
  }
67
- function freshTokenMiddleware() {
71
+ function freshTokenMiddleware(realm) {
68
72
  return {
69
73
  async pre({ url, init }) {
70
- const accessToken = await getFreshAccessToken();
74
+ const accessToken = await getFreshAccessToken(realm);
71
75
  if (!accessToken) {
72
76
  return { url, init };
73
77
  }
@@ -82,9 +86,10 @@ class FarseerService {
82
86
  constructor(auth) {
83
87
  this.auth = auth;
84
88
  this.client = new farseer.FarseerClient({
89
+ fetchApi: (0, import_requests.pipelineFetch)(farseer.patchedFetchApi),
85
90
  basePath: basePathOf(auth),
86
91
  headers: authHeaders(auth),
87
- middleware: auth.kind === "jwt" ? [freshTokenMiddleware()] : []
92
+ middleware: auth.kind === "jwt" ? [freshTokenMiddleware(auth.realm)] : []
88
93
  });
89
94
  }
90
95
  /**
@@ -582,9 +587,12 @@ class FarseerService {
582
587
  /**
583
588
  * Make a direct API request (for endpoints not in farseer-client)
584
589
  */
590
+ async pipelineRequest(method, route, body) {
591
+ return this.apiRequest(route, method, body);
592
+ }
585
593
  async apiRequest(endpoint, method, body) {
586
594
  const url = `${basePathOf(this.auth)}${endpoint}`;
587
- const auth = this.auth.kind === "jwt" ? { ...this.auth, accessToken: await getFreshAccessToken() ?? this.auth.accessToken } : this.auth;
595
+ const auth = this.auth.kind === "jwt" ? { ...this.auth, accessToken: await getFreshAccessToken(this.auth.realm) ?? this.auth.accessToken } : this.auth;
588
596
  const headers = {
589
597
  "Content-Type": "application/json",
590
598
  // The SDK stamps this from its own generated constant, and these
@@ -593,7 +601,7 @@ class FarseerService {
593
601
  "x-api-version": import_apiVersion.API_VERSION,
594
602
  ...authHeaders(auth)
595
603
  };
596
- const response = await fetch(url, {
604
+ const response = await (0, import_requests.pipelineFetch)()(url, {
597
605
  method,
598
606
  headers,
599
607
  body: body ? JSON.stringify(body) : void 0
@@ -692,19 +700,42 @@ function getErrorPage(title, message) {
692
700
  </html>
693
701
  `;
694
702
  }
695
- async function loginWithBrowser(realm = "master") {
703
+ async function loginWithBrowser(realm = "master", { idpHint, viaMasterSession = false } = {}) {
696
704
  const http = await import("http");
697
705
  const crypto = await import("crypto");
698
706
  const { exec } = await import("child_process");
699
707
  const { promisify } = await import("util");
700
708
  const execAsync = promisify(exec);
701
- const KEYCLOAK_BASE = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect`;
709
+ const keycloakBase = (r) => `https://login.farseer.io/auth/realms/${r}/protocol/openid-connect`;
702
710
  const CLIENT_ID = "auth";
703
711
  const REDIRECT_PORT = 8787;
704
712
  const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`;
705
713
  const codeVerifier = crypto.randomBytes(32).toString("base64url");
706
714
  const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
707
715
  const state = crypto.randomBytes(16).toString("hex");
716
+ const authorizationUrl = (legRealm, scope, legState, challenge, hint) => {
717
+ const authUrl = new URL(`${keycloakBase(legRealm)}/auth`);
718
+ authUrl.searchParams.set("client_id", CLIENT_ID);
719
+ authUrl.searchParams.set("redirect_uri", REDIRECT_URI);
720
+ authUrl.searchParams.set("response_type", "code");
721
+ authUrl.searchParams.set("scope", scope);
722
+ authUrl.searchParams.set("state", legState);
723
+ authUrl.searchParams.set("code_challenge", challenge);
724
+ authUrl.searchParams.set("code_challenge_method", "S256");
725
+ if (hint) {
726
+ authUrl.searchParams.set("kc_idp_hint", hint);
727
+ }
728
+ return authUrl.toString();
729
+ };
730
+ const loginUrl = authorizationUrl(realm, "openid offline_access", state, codeChallenge, idpHint);
731
+ const masterState = crypto.randomBytes(16).toString("hex");
732
+ const masterUrl = authorizationUrl(
733
+ import_configService.DEFAULT_REALM,
734
+ "openid",
735
+ masterState,
736
+ crypto.createHash("sha256").update(crypto.randomBytes(32).toString("base64url")).digest("base64url")
737
+ );
738
+ let masterSessionOpened = false;
708
739
  return new Promise((resolve) => {
709
740
  const server = http.createServer(async (req, res) => {
710
741
  const url = new URL(req.url || "", `http://localhost:${REDIRECT_PORT}`);
@@ -712,22 +743,33 @@ async function loginWithBrowser(realm = "master") {
712
743
  const code = url.searchParams.get("code");
713
744
  const returnedState = url.searchParams.get("state");
714
745
  const error = url.searchParams.get("error");
746
+ if (error === "login_required" && returnedState === state && viaMasterSession && !masterSessionOpened) {
747
+ masterSessionOpened = true;
748
+ res.writeHead(302, { Location: masterUrl });
749
+ res.end();
750
+ return;
751
+ }
715
752
  if (error) {
716
753
  res.writeHead(200, { "Content-Type": "text/html" });
717
754
  res.end(getErrorPage("Login Failed", `Error: ${error}`));
718
755
  server.close();
719
- resolve(null);
756
+ resolve({ ok: false, error });
757
+ return;
758
+ }
759
+ if (code && returnedState === masterState && masterSessionOpened) {
760
+ res.writeHead(302, { Location: loginUrl });
761
+ res.end();
720
762
  return;
721
763
  }
722
764
  if (!code || returnedState !== state) {
723
765
  res.writeHead(400, { "Content-Type": "text/html" });
724
766
  res.end(getErrorPage("Invalid Response", "Missing code or state mismatch."));
725
767
  server.close();
726
- resolve(null);
768
+ resolve({ ok: false });
727
769
  return;
728
770
  }
729
771
  try {
730
- const tokenResponse = await fetch(`${KEYCLOAK_BASE}/token`, {
772
+ const tokenResponse = await fetch(`${keycloakBase(realm)}/token`, {
731
773
  method: "POST",
732
774
  headers: {
733
775
  "Content-Type": "application/x-www-form-urlencoded"
@@ -818,6 +860,7 @@ async function loginWithBrowser(realm = "master") {
818
860
  `);
819
861
  server.close();
820
862
  resolve({
863
+ ok: true,
821
864
  accessToken: data.access_token,
822
865
  refreshToken: data.refresh_token,
823
866
  expiresIn: data.expires_in
@@ -826,20 +869,12 @@ async function loginWithBrowser(realm = "master") {
826
869
  res.writeHead(500, { "Content-Type": "text/html" });
827
870
  res.end(getErrorPage("Token Exchange Failed", "Could not complete login."));
828
871
  server.close();
829
- resolve(null);
872
+ resolve({ ok: false });
830
873
  }
831
874
  }
832
875
  });
833
876
  server.listen(REDIRECT_PORT, async () => {
834
- const authUrl = new URL(`${KEYCLOAK_BASE}/auth`);
835
- authUrl.searchParams.set("client_id", CLIENT_ID);
836
- authUrl.searchParams.set("redirect_uri", REDIRECT_URI);
837
- authUrl.searchParams.set("response_type", "code");
838
- authUrl.searchParams.set("scope", "openid offline_access");
839
- authUrl.searchParams.set("state", state);
840
- authUrl.searchParams.set("code_challenge", codeChallenge);
841
- authUrl.searchParams.set("code_challenge_method", "S256");
842
- const url = authUrl.toString();
877
+ const url = loginUrl;
843
878
  try {
844
879
  if (process.platform === "darwin") {
845
880
  await execAsync(`open "${url}"`);
@@ -858,20 +893,23 @@ ${url}
858
893
  setTimeout(
859
894
  () => {
860
895
  server.close();
861
- resolve(null);
896
+ resolve({ ok: false });
862
897
  },
863
898
  5 * 60 * 1e3
864
899
  );
865
900
  });
866
901
  }
867
- let refreshInFlight = null;
868
- function getFreshAccessToken() {
869
- return refreshInFlight ??= mintAccessToken().finally(() => {
870
- refreshInFlight = null;
871
- });
902
+ const refreshesInFlight = /* @__PURE__ */ new Map();
903
+ function getFreshAccessToken(realm = import_configService.DEFAULT_REALM) {
904
+ let inFlight = refreshesInFlight.get(realm);
905
+ if (!inFlight) {
906
+ inFlight = mintAccessToken(realm).finally(() => refreshesInFlight.delete(realm));
907
+ refreshesInFlight.set(realm, inFlight);
908
+ }
909
+ return inFlight;
872
910
  }
873
- async function mintAccessToken() {
874
- const auth = (0, import_configService.getUserAuth)();
911
+ async function mintAccessToken(realm) {
912
+ const auth = (0, import_configService.getUserAuth)(realm);
875
913
  if (!auth) {
876
914
  return null;
877
915
  }
@@ -879,23 +917,39 @@ async function mintAccessToken() {
879
917
  return auth.accessToken;
880
918
  }
881
919
  import_logger.logger.dim("Token expired, refreshing...");
882
- const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || "master");
920
+ const refreshed = await refreshAccessToken(auth.refreshToken, realm);
883
921
  if (!refreshed) {
884
922
  return null;
885
923
  }
886
- (0, import_configService.setUserAuth)({
887
- accessToken: refreshed.accessToken,
888
- refreshToken: refreshed.refreshToken,
889
- expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
890
- realm: auth.realm
891
- });
924
+ (0, import_configService.setUserAuth)(
925
+ {
926
+ accessToken: refreshed.accessToken,
927
+ refreshToken: refreshed.refreshToken,
928
+ expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
929
+ realm
930
+ },
931
+ { refresh: true }
932
+ );
892
933
  import_logger.logger.dim("Token refreshed");
893
934
  return refreshed.accessToken;
894
935
  }
936
+ async function revokeRefreshToken(realm, refreshToken) {
937
+ try {
938
+ const response = await fetch(`https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/logout`, {
939
+ method: "POST",
940
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
941
+ body: new URLSearchParams({ client_id: "auth", refresh_token: refreshToken }),
942
+ signal: AbortSignal.timeout(1e4)
943
+ });
944
+ return response.ok;
945
+ } catch {
946
+ return false;
947
+ }
948
+ }
895
949
  async function refreshAccessToken(refreshToken, realm = "master") {
896
950
  const tokenUrl = `https://login.farseer.io/auth/realms/${realm}/protocol/openid-connect/token`;
897
951
  try {
898
- const response = await fetch(tokenUrl, {
952
+ const response = await (0, import_requests.pipelineFetch)()(tokenUrl, {
899
953
  method: "POST",
900
954
  headers: {
901
955
  "Content-Type": "application/x-www-form-urlencoded"
@@ -926,6 +980,7 @@ async function refreshAccessToken(refreshToken, realm = "master") {
926
980
  getFreshAccessToken,
927
981
  loginWithBrowser,
928
982
  refreshAccessToken,
929
- resolveRealm
983
+ resolveRealm,
984
+ revokeRefreshToken
930
985
  });
931
986
  //# sourceMappingURL=farseerService.js.map