Skip to content
Open
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
311 changes: 144 additions & 167 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
},
"dependencies": {
"@actions/core": "^2.0.0",
"@actions/github": "^7.0.0",
"@actions/github": "^9.1.1",
"@actions/io": "^1.1.3",
"axios": "^1.7.7",
"chalk": "^5.3.0",
Expand Down
7 changes: 7 additions & 0 deletions src/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export interface CheckResult {
}

const MAX_REDIRECTS = 10;
/** Upper bound on a response body pulled into memory during the GET fallback. */
const MAX_RESPONSE_BYTES = 5 * 1024 * 1024;

/**
* Checks a single URL and classifies the result. HTTP is always attempted
Expand Down Expand Up @@ -126,6 +128,8 @@ export async function performRequest(url: string, timeout: number): Promise<RawR
const client = axios.create({
timeout,
maxRedirects: 0,
maxContentLength: MAX_RESPONSE_BYTES,
maxBodyLength: MAX_RESPONSE_BYTES,
validateStatus: () => true,
headers: {
'User-Agent': 'urldn-link-check (+https://github.com/urldn/link-check)',
Expand All @@ -148,6 +152,9 @@ export async function performRequest(url: string, timeout: number): Promise<RawR

if (response.status >= 300 && response.status < 400 && response.headers.location) {
const nextUrl = new URL(String(response.headers.location), currentUrl).toString();
if (!isValidUrl(nextUrl)) {
throw new Error('Redirect target uses an unsupported protocol');
}
redirectChain.push(currentUrl);
currentUrl = nextUrl;
continue;
Expand Down
1 change: 1 addition & 0 deletions src/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export async function runAction(): Promise<void> {
const output = core.getInput('output') || undefined;
const commentOnPr = getBooleanInput('comment-on-pr', true);
const token = core.getInput('github-token') || process.env.GITHUB_TOKEN;
if (token) core.setSecret(token);

const config = resolveConfig({
path,
Expand Down
32 changes: 25 additions & 7 deletions src/report.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { writeFile } from 'node:fs/promises';
import type { ScanReport, ScannedLinkResult } from './scanner.js';
import { redactUrlCredentials } from './utils.js';

const URLDN_SHORTENER_URL = 'https://www.urldn.com';

Expand Down Expand Up @@ -29,11 +30,11 @@ export function toJsonReport(report: ScanReport): JsonReport {
summary: report.summary,
files: report.files,
links: report.results.map((result) => ({
url: result.url,
url: redactUrlCredentials(result.url),
status: result.status,
statusCode: result.statusCode,
redirectChain: result.redirectChain,
finalUrl: result.finalUrl,
redirectChain: result.redirectChain.map(redactUrlCredentials),
finalUrl: result.finalUrl ? redactUrlCredentials(result.finalUrl) : undefined,
error: result.error,
isHttp: result.isHttp,
isDuplicate: result.isDuplicate,
Expand Down Expand Up @@ -89,14 +90,17 @@ export function toMarkdownReport(report: ScanReport): string {
lines.push('');

for (const result of problems) {
lines.push(`#### ${statusEmoji(result)} \`${result.url}\``);
lines.push(`#### ${statusEmoji(result)} ${inlineCode(redactUrlCredentials(result.url))}`);
for (const occurrence of result.occurrences) {
lines.push(`- ${occurrence.file}:${occurrence.line}:${occurrence.column}`);
lines.push(`- ${inlineCode(`${occurrence.file}:${occurrence.line}:${occurrence.column}`)}`);
}
if (result.error) lines.push(`- Error: ${result.error}`);
if (result.error) lines.push(`- Error: ${inlineCode(result.error)}`);
if (result.statusCode) lines.push(`- HTTP status: ${result.statusCode}`);
if (result.redirectChain.length > 0) {
lines.push(`- Redirect chain: ${[...result.redirectChain, result.finalUrl].join(' → ')}`);
const chain = [...result.redirectChain, result.finalUrl ?? '']
.filter((hop) => hop.length > 0)
.map((hop) => inlineCode(redactUrlCredentials(hop)));
lines.push(`- Redirect chain: ${chain.join(' → ')}`);
}
if (result.isHttp) {
lines.push('- ⚠️ Uses insecure `http://` — consider migrating to `https://`.');
Expand All @@ -116,6 +120,20 @@ export function toMarkdownReport(report: ScanReport): string {
return lines.join('\n');
}

/**
* Renders arbitrary text as a Markdown inline code span that cannot be
* escaped. Content comes from scanned documents (URLs, file paths, server
* error messages), so it is untrusted: newlines are collapsed and the
* fence is grown to be longer than any backtick run inside the value.
*/
function inlineCode(value: string): string {
const text = value.replace(/[\r\n]+/g, ' ');
const longestRun = Math.max(0, ...Array.from(text.matchAll(/`+/g), (m) => m[0].length));
const fence = '`'.repeat(longestRun + 1);
const padded = text.startsWith('`') || text.endsWith('`') ? ` ${text} ` : text;
return `${fence}${padded}${fence}`;
}

function statusEmoji(result: ScannedLinkResult): string {
switch (result.status) {
case 'ok':
Expand Down
20 changes: 19 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,23 @@ export function isInsecureHttp(candidate: string): boolean {
}
}

/**
* Removes any `user:password@` userinfo from a URL so that credentials
* embedded in a link are never echoed into logs, reports, or PR comments.
* Non-URL strings are returned unchanged.
*/
export function redactUrlCredentials(candidate: string): string {
try {
const parsed = new URL(candidate);
if (!parsed.username && !parsed.password) return candidate;
if (parsed.username) parsed.username = '***';
if (parsed.password) parsed.password = '***';
return parsed.toString();
} catch {
return candidate;
}
}

/**
* Very small glob-ish matcher for ignore patterns. Supports `*` (any run of
* non-slash characters) and `**` (any run of characters, including `/`).
Expand Down Expand Up @@ -80,7 +97,8 @@ export function formatDuration(ms: number): string {
}

/** Truncates a URL for display purposes, keeping the start and end visible. */
export function truncateUrl(url: string, maxLength = 70): string {
export function truncateUrl(rawUrl: string, maxLength = 70): string {
const url = redactUrlCredentials(rawUrl);
if (url.length <= maxLength) return url;
const headLength = Math.ceil((maxLength - 3) * 0.6);
const tailLength = maxLength - 3 - headLength;
Expand Down
48 changes: 46 additions & 2 deletions test/checker.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest';
import { checkUrl } from '../src/checker.js';
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { afterEach, describe, expect, it } from 'vitest';
import { checkUrl, performRequest } from '../src/checker.js';

describe('checkUrl', () => {
it('classifies a 200 response as ok', async () => {
Expand Down Expand Up @@ -92,3 +94,45 @@ describe('checkUrl', () => {
expect(result.error).toContain('ENOTFOUND');
});
});

describe('performRequest', () => {
let server: Server | undefined;

afterEach(async () => {
if (!server) return;
await new Promise<void>((resolve) => server?.close(() => resolve()));
server = undefined;
});

async function listen(handler: Parameters<typeof createServer>[1]): Promise<string> {
server = createServer(handler);
await new Promise<void>((resolve) => server?.listen(0, '127.0.0.1', () => resolve()));
const { port } = server.address() as AddressInfo;
return `http://127.0.0.1:${port}`;
}

it('refuses to follow a redirect to a non-http(s) protocol', async () => {
const base = await listen((_req, res) => {
res.writeHead(302, { location: 'file:///etc/passwd' });
res.end();
});

await expect(performRequest(`${base}/redirect`, 5000)).rejects.toThrow(
/unsupported protocol/i,
);
});

it('rejects responses whose body exceeds the size limit', async () => {
const base = await listen((req, res) => {
if (req.method === 'HEAD') {
res.writeHead(405);
res.end();
return;
}
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('x'.repeat(6 * 1024 * 1024));
});

await expect(performRequest(`${base}/huge`, 10_000)).rejects.toThrow(/maxContentLength|size/i);
});
});
29 changes: 29 additions & 0 deletions test/report.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,35 @@ describe('toMarkdownReport', () => {
expect(markdown).not.toContain('No issues found');
});

it('redacts credentials embedded in scanned URLs', () => {
const credentialResult: ScannedLinkResult = {
...brokenResult,
url: 'https://user:hunter2@example.com/private',
redirectChain: ['https://user:hunter2@example.com/private'],
finalUrl: 'https://user:hunter2@example.com/moved',
};
const report = buildReport([credentialResult]);

const markdown = toMarkdownReport(report);
expect(markdown).not.toContain('hunter2');
expect(markdown).toContain('https://***:***@example.com/private');

const json = toJsonReport(report);
expect(JSON.stringify(json)).not.toContain('hunter2');
});

it('neutralizes Markdown injected through a URL or error message', () => {
const injectedResult: ScannedLinkResult = {
...brokenResult,
url: 'https://example.com/`</details><img src=x>',
error: 'boom`\n\n### injected heading',
};
const markdown = toMarkdownReport(buildReport([injectedResult]));

expect(markdown).toContain('``https://example.com/`</details><img src=x>``');
expect(markdown).not.toContain('\n### injected heading');
});

it('suggests URLDN for long URLs', () => {
const longResult: ScannedLinkResult = {
...okResult,
Expand Down
15 changes: 15 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,25 @@ import {
isInsecureHttp,
isValidUrl,
matchesIgnorePattern,
redactUrlCredentials,
runWithConcurrency,
truncateUrl,
} from '../src/utils.js';

describe('redactUrlCredentials', () => {
it('replaces basic-auth userinfo with a placeholder', () => {
expect(redactUrlCredentials('https://alice:s3cret@example.com/docs')).toBe(
'https://***:***@example.com/docs',
);
expect(redactUrlCredentials('https://token@example.com/')).toBe('https://***@example.com/');
});

it('leaves URLs without credentials and non-URLs untouched', () => {
expect(redactUrlCredentials('https://example.com/docs')).toBe('https://example.com/docs');
expect(redactUrlCredentials('not a url')).toBe('not a url');
});
});

describe('isValidUrl', () => {
it('accepts http and https URLs', () => {
expect(isValidUrl('https://example.com')).toBe(true);
Expand Down
Loading