Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: make JIRA expired-token detection Cloud-aware (#2235)

Adam Eivy4da8cf19660a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 57b4e7eec9..1dc9055e2a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -113,6 +113,7 @@
## Integrations
- **JIRA instances now support Jira Cloud (`*.atlassian.net`), not just Server / Data Center.** The JIRA client authenticated every instance with `Authorization: Bearer <token>` — correct for a Server/DC Personal Access Token, but Jira Cloud rejects that: a Cloud personal API token must be sent as HTTP Basic (`base64("email:token")`). PortOS now picks the scheme per instance by host — a `*.atlassian.net` base URL authenticates as Basic using the instance's email + API token (both already stored and required by the instance form), and any other host keeps the Bearer PAT — so Cloud and Server instances work side by side with no new fields or migration. Create a Cloud API token at id.atlassian.com → Security → API tokens and paste it into the instance's token field. (`server/services/jira.js`)
+- **[issue-2235] Expired-token detection is now Cloud-aware, so a Jira Cloud token expiry gives the same friendly "regenerate your token" message as Server.** The JIRA client's expiry detector only recognized the Server/DC signal — a 200 response whose body is the HTML login page (`<!DOCTYPE`) — so a Cloud instance, which instead returns a JSON **401** on an invalid/expired token, never hit the friendly branch and surfaced the raw HTTP 401 instead. Detection is now instance-type-aware alongside the auth header: the `<!DOCTYPE` heuristic is gated to Server (so a Cloud JSON payload can't accidentally trip on the marker string), and a 401 from either instance type maps to one shared "token expired or invalid — regenerate your token" error. Both instance types now report expiry from one place. (`server/services/jira.js`)
- **Configuring an app's JIRA integration now auto-detects the workspace instead of hand-typing ids.** When you pick a JIRA instance + project in an app's JIRA settings, PortOS now detects that project's **boards** and offers them as a dropdown (`id — name (type)`) rather than a free-text "Board ID" field — the field where a board id silently went stale. If the app's saved board id isn't among the project's live boards (e.g. carried over from a Server instance after a Cloud migration, where ids are reassigned), it's flagged with an amber "pick a current one" warning; the selected board also shows its current **active sprint** as confirmation. The **Epic Key** field gained live search-by-name (type a name → pick from matching epics) and validates a typed/pasted key against the instance — confirming it resolves as an Epic, or warning when it's the wrong type or no longer resolves. New read-only endpoints back this: `GET /jira/instances/:id/projects/:key/boards` and `GET /jira/instances/:id/issues/:key`. (`server/services/jira.js`, `server/routes/jira.js`, `client/src/components/apps/EditAppDrawer.jsx`)
## Internal
diff --git a/server/services/jira.js b/server/services/jira.js
index bdac986286..d6bf8b4417 100644
--- a/server/services/jira.js
+++ b/server/services/jira.js
@@ -117,21 +117,38 @@ export function createJiraClient(instance) {
allowSelfSigned: instance.allowSelfSigned
});
- // Detect expired token (JIRA returns HTML login page instead of JSON)
+ // Expired/invalid token surfaces differently per instance type, so detection is
+ // instance-type-aware alongside jiraAuthHeader — both funnel to one friendly error:
+ // - Jira Server/DC: 200 response whose body is the HTML login page (not JSON).
+ // - Jira Cloud: JSON 401 (createHttpClient throws HTTP 401), never an HTML page.
+ const isCloud = isCloudInstance(instance.baseUrl);
+ const expiredTokenError = () => {
+ const err = new Error('JIRA token expired or invalid — regenerate your token (Server: PAT; Cloud: API token).');
+ err.status = 401;
+ return err;
+ };
+
+ // Success path: only Server serves an HTML login page in place of JSON, so gate the
+ // heuristic to Server — a Cloud JSON payload can't accidentally trip on "<!DOCTYPE".
const checkToken = res => {
- if (typeof res.data === 'string' && res.data.includes('<!DOCTYPE')) {
- const err = new Error('JIRA token expired — received login page instead of JSON. Regenerate your token (Server: PAT; Cloud: API token).');
- err.status = 401;
- throw err;
+ if (!isCloud && typeof res.data === 'string' && res.data.includes('<!DOCTYPE')) {
+ throw expiredTokenError();
}
return res;
};
+ // Error path: a 401 (Cloud's expired-token signal, and Server's when it 401s rather
+ // than serving HTML) maps to the same friendly error. Other errors bubble unchanged.
+ const mapAuthError = err => {
+ if (err?.status === 401) throw expiredTokenError();
+ throw err;
+ };
+
return {
- get: (...args) => base.get(...args).then(checkToken),
- post: (...args) => base.post(...args).then(checkToken),
- put: (...args) => base.put(...args).then(checkToken),
- delete: (...args) => base.delete(...args).then(checkToken)
+ get: (...args) => base.get(...args).then(checkToken, mapAuthError),
+ post: (...args) => base.post(...args).then(checkToken, mapAuthError),
+ put: (...args) => base.put(...args).then(checkToken, mapAuthError),
+ delete: (...args) => base.delete(...args).then(checkToken, mapAuthError)
};
}
diff --git a/server/services/jira.test.js b/server/services/jira.test.js
index 422cba397e..7bbde90ede 100644
--- a/server/services/jira.test.js
+++ b/server/services/jira.test.js
@@ -1,5 +1,5 @@
-import { describe, it, expect } from 'vitest';
-import { buildColumnsFromBoardConfig, buildColumnsFromStatuses, isCloudInstance, jiraAuthHeader } from './jira.js';
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { buildColumnsFromBoardConfig, buildColumnsFromStatuses, createJiraClient, isCloudInstance, jiraAuthHeader } from './jira.js';
describe('isCloudInstance', () => {
it('treats *.atlassian.net hosts as Cloud', () => {
@@ -33,6 +33,62 @@ describe('jiraAuthHeader', () => {
});
});
+describe('createJiraClient expired-token detection', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ // Helper: stub global fetch with a single response so createHttpClient's request()
+ // observes exactly what the given JIRA instance type would return on an expired token.
+ const stubFetch = ({ ok, status, contentType, body }) => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok,
+ status,
+ headers: { get: name => (name.toLowerCase() === 'content-type' ? contentType : null) },
+ json: async () => body,
+ text: async () => body
+ }));
+ };
+
+ it('maps a Server HTML login page (200 + <!DOCTYPE) to the friendly expiry error', async () => {
+ stubFetch({ ok: true, status: 200, contentType: 'text/html', body: '<!DOCTYPE html><html><body>login</body></html>' });
+ const client = createJiraClient({ baseUrl: 'https://jira.example.com', apiToken: 'pat' });
+ await expect(client.get('/rest/api/2/myself')).rejects.toMatchObject({
+ status: 401,
+ message: expect.stringContaining('token expired or invalid')
+ });
+ });
+
+ it('maps a Cloud JSON 401 to the same friendly expiry error', async () => {
+ stubFetch({
+ ok: false,
+ status: 401,
+ contentType: 'application/json',
+ body: { errorMessages: ['Client must be authenticated to access this resource.'], errors: {} }
+ });
+ const client = createJiraClient({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'tok' });
+ await expect(client.get('/rest/api/2/myself')).rejects.toMatchObject({
+ status: 401,
+ message: expect.stringContaining('token expired or invalid')
+ });
+ });
+
+ it('does not trip the HTML heuristic on a Cloud JSON payload that contains "<!DOCTYPE"', async () => {
+ // A Cloud instance returns JSON; even if a field value contained the marker string,
+ // the heuristic is gated off for Cloud so a valid response passes through untouched.
+ stubFetch({ ok: true, status: 200, contentType: 'application/json', body: { note: '<!DOCTYPE lives in this field' } });
+ const client = createJiraClient({ baseUrl: 'https://example.atlassian.net', email: '[email protected]', apiToken: 'tok' });
+ const res = await client.get('/rest/api/2/myself');
+ expect(res.data).toEqual({ note: '<!DOCTYPE lives in this field' });
+ });
+
+ it('lets non-401 errors bubble unchanged', async () => {
+ stubFetch({ ok: false, status: 500, contentType: 'application/json', body: { errorMessages: ['boom'] } });
+ const client = createJiraClient({ baseUrl: 'https://jira.example.com', apiToken: 'pat' });
+ await expect(client.get('/rest/api/2/myself')).rejects.toMatchObject({ status: 500 });
+ });
+});
+
describe('buildColumnsFromBoardConfig', () => {
const statusById = new Map([
['1', { name: 'To Do', category: 'To Do' }],