Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 45 additions & 7 deletions lib/confluence-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,34 @@ const parseDocumentWithExplicitClosures = (source) => {
return { document: handler.root, explicitlyClosedNodes };
};

function getUrlPathname(value, baseUrl) {
try {
return new URL(value, baseUrl).pathname;
} catch {
return null;
}
}

/**
* Decode a Confluence tiny link code (e.g. `/x/<code>`) into a page ID.
* Confluence builds the code by base64-encoding the page ID as an 8-byte
* little-endian integer, swapping `/` for `-` and `+` for `_`, and stripping
* trailing `A`s and `=` padding.
* @param {string} code - Tiny link code
* @returns {string|null} Page ID, or null if the code cannot be decoded
*/
function decodeTinyLinkCode(code) {
// Page IDs are 64-bit integers.
// When encoded to base64, they use up to 11 characters (plus trailing `=`).
if (!/^[A-Za-z0-9_-]{1,11}$/.test(code)) {
return null;
}

const base64 = code.replace(/-/g, '/').replace(/_/g, '+').padEnd(11, 'A');
const id = Buffer.from(base64, 'base64').readBigUInt64LE();
return id > 0n ? id.toString() : null;
}

function createSemaphore(limit) {
let active = 0;
const waiters = [];
Expand Down Expand Up @@ -418,8 +446,8 @@ class ConfluenceClient {
return pageIdOrUrl;
}

// Check if it's a Confluence URL
if (pageIdOrUrl.includes(this.domain)) {
// Check if it's a Confluence URL, possibly without the scheme or host
if (pageIdOrUrl.includes(this.domain) || pageIdOrUrl.startsWith('/')) {
// Extract pageId from URL parameter
const pageIdMatch = pageIdOrUrl.match(/pageId=(\d+)/);
if (pageIdMatch) {
Expand All @@ -431,17 +459,27 @@ class ConfluenceClient {
return prettyMatch[1];
}

// Handle tiny links (/wiki/x/<code>)
const tinyLinkMatch = pageIdOrUrl.match(/\/wiki\/x\/([A-Za-z0-9_-]+)/);
// Handle tiny links (<context path>/x/<code>)
const tinyLinkMatch = getUrlPathname(pageIdOrUrl, this.configuredOrigin())?.match(/\/x\/([A-Za-z0-9_-]+)\/?$/);
if (tinyLinkMatch) {
const decodedId = decodeTinyLinkCode(tinyLinkMatch[1]);
if (decodedId) {
return decodedId;
}

// Resolving the tiny link sends the URL through the authenticated
// client, and the substring check above also matches look-alike hosts
// (e.g. "<domain>.attacker.example") and http:// downgrades. Refuse to
// send credentials anywhere but the configured origin. Mirrors the
// rawRequest/download guards.
this.assertSameOrigin(pageIdOrUrl);
// rawRequest/download guards. Host-less paths resolve against the
// configured origin, not the API baseURL.
const origin = this.configuredOrigin();
const tinyUrl = origin && pageIdOrUrl.startsWith('/')
? new URL(pageIdOrUrl, origin).href
: pageIdOrUrl;
this.assertSameOrigin(tinyUrl);
try {
const response = await this.client.get(pageIdOrUrl, {
const response = await this.client.get(tinyUrl, {
maxRedirects: 0,
validateStatus: (status) => status >= 300 && status < 400
});
Expand Down
93 changes: 82 additions & 11 deletions tests/confluence-client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1460,6 +1460,11 @@ describe('ConfluenceClient', () => {
expect(await client.extractPageId(url)).toBe('123456789');
});

test('should extract page ID from URLs without a host', async () => {
expect(await client.extractPageId('/pages/viewpage.action?pageId=987654321')).toBe('987654321');
expect(await client.extractPageId('/wiki/spaces/TEST/pages/123456789/Page+Title')).toBe('123456789');
});

test('should resolve display URLs', async () => {
// Mock the API response for display URL resolution
const mock = new MockAdapter(client.client);
Expand Down Expand Up @@ -1536,35 +1541,75 @@ describe('ConfluenceClient', () => {
}
});

test('should resolve tiny links via redirect', async () => {
test('should decode tiny links without a request', async () => {
const mock = new MockAdapter(client.client);

expect(await client.extractPageId('https://test.atlassian.net/wiki/x/xIKbMAE')).toBe('5110465220');
expect(await client.extractPageId('https://test.atlassian.net/x/xIKbMAE')).toBe('5110465220');
expect(await client.extractPageId('https://test.atlassian.net/x/xIKbMAE/?src=mail#comments')).toBe('5110465220');
expect(await client.extractPageId('test.atlassian.net/x/xIKbMAE')).toBe('5110465220');
expect(await client.extractPageId('/x/xIKbMAE')).toBe('5110465220');
expect(mock.history.get).toHaveLength(0);

mock.restore();
});

test('should decode tiny link codes containing - or _', async () => {
const mock = new MockAdapter(client.client);

// Real tiny links and page IDs from a Confluence Data Center instance
expect(await client.extractPageId('https://test.atlassian.net/wiki/x/e-tQYwE')).toBe('5961218939');
expect(await client.extractPageId('https://test.atlassian.net/wiki/x/h__sXAE')).toBe('5849804679');
expect(mock.history.get).toHaveLength(0);

mock.restore();
});

test('should resolve undecodable tiny links via redirect', async () => {
const mock = new MockAdapter(client.client);

mock.onGet(/\/wiki\/x\//).reply(302, null, {
location: 'https://test.atlassian.net/wiki/spaces/TEST/pages/123456789/Page+Title'
});

const tinyUrl = 'https://test.atlassian.net/wiki/x/aBcDeFg';
const tinyUrl = 'https://test.atlassian.net/wiki/x/aBcDeFgHiJkL';
expect(await client.extractPageId(tinyUrl)).toBe('123456789');

mock.restore();
});

test('should resolve undecodable Server/Data Center tiny links via redirect', async () => {
const serverClient = new ConfluenceClient({
domain: 'wiki.example.com',
token: 'test-token'
});
const mock = new MockAdapter(serverClient.client);

mock.onGet(/\/x\//).reply(302, null, {
location: 'https://wiki.example.com/pages/viewpage.action?pageId=123456789'
});

expect(await serverClient.extractPageId('https://wiki.example.com/x/aBcDeFgHiJkL')).toBe('123456789');

mock.restore();
});

test('should throw error when tiny link cannot be resolved', async () => {
const mock = new MockAdapter(client.client);

mock.onGet(/\/wiki\/x\//).reply(404);

const tinyUrl = 'https://test.atlassian.net/wiki/x/invalidCode';
const tinyUrl = 'https://test.atlassian.net/wiki/x/invalidTinyCode';
await expect(client.extractPageId(tinyUrl)).rejects.toThrow(/Could not resolve page ID from tiny link/);

mock.restore();
});

test.each([
['a look-alike host', 'https://test.atlassian.net.attacker.example/wiki/x/aBcDeFg'],
['a host that only contains the domain in its path', 'https://attacker.example/test.atlassian.net/wiki/x/aBcDeFg'],
['an http:// downgrade', 'http://test.atlassian.net/wiki/x/aBcDeFg'],
['a protocol-relative URL', '//attacker.example/test.atlassian.net/wiki/x/aBcDeFg'],
['a look-alike host', 'https://test.atlassian.net.attacker.example/wiki/x/aBcDeFgHiJkL'],
['a host that only contains the domain in its path', 'https://attacker.example/test.atlassian.net/wiki/x/aBcDeFgHiJkL'],
['an http:// downgrade', 'http://test.atlassian.net/wiki/x/aBcDeFgHiJkL'],
['a protocol-relative URL', '//attacker.example/test.atlassian.net/wiki/x/aBcDeFgHiJkL'],
])('refuses to resolve a tiny link on %s without sending credentials', async (_label, tinyUrl) => {
const mock = new MockAdapter(client.client);
mock.onAny().reply(302, null, {
Expand All @@ -1579,17 +1624,43 @@ describe('ConfluenceClient', () => {
}
});

test('decodes a tiny link on another host locally without sending credentials', async () => {
const mock = new MockAdapter(client.client);

try {
expect(await client.extractPageId('https://test.atlassian.net.attacker.example/wiki/x/xIKbMAE')).toBe('5110465220');
expect(mock.history.get).toHaveLength(0);
} finally {
mock.restore();
}
});

test('resolves host-less undecodable tiny links against the configured origin', async () => {
const mock = new MockAdapter(client.client);
mock.onGet('https://test.atlassian.net/wiki/x/aBcDeFgHiJkL').reply(302, null, {
location: 'https://test.atlassian.net/wiki/spaces/TEST/pages/123456789/Page+Title'
});

try {
expect(await client.extractPageId('/wiki/x/aBcDeFgHiJkL')).toBe('123456789');
expect(mock.history.get.map((request) => request.url))
.toEqual(['https://test.atlassian.net/wiki/x/aBcDeFgHiJkL']);
} finally {
mock.restore();
}
});

test('refuses a tiny-link redirect that points to another origin', async () => {
const mock = new MockAdapter(client.client);
mock.onGet('https://test.atlassian.net/wiki/x/aBcDeFg').reply(302, null, {
location: 'https://attacker.example/test.atlassian.net/wiki/x/hOpPeD'
mock.onGet('https://test.atlassian.net/wiki/x/aBcDeFgHiJkL').reply(302, null, {
location: 'https://attacker.example/test.atlassian.net/wiki/x/hOpPeDhOpPeD'
});

try {
await expect(client.extractPageId('https://test.atlassian.net/wiki/x/aBcDeFg'))
await expect(client.extractPageId('https://test.atlassian.net/wiki/x/aBcDeFgHiJkL'))
.rejects.toThrow(/Refusing to send credentials/);
expect(mock.history.get.map((request) => request.url))
.toEqual(['https://test.atlassian.net/wiki/x/aBcDeFg']);
.toEqual(['https://test.atlassian.net/wiki/x/aBcDeFgHiJkL']);
} finally {
mock.restore();
}
Expand Down
Loading