Skip to content

Validate redirects with security registry #56

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion packages/blinks-core/src/api/BlinkInstance/BlinkInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
isProxified,
proxify,
proxifyImage,
secureFetch,
} from '../../utils';
import { isUrlSameOrigin } from '../../utils/security.ts';
import type { BlinkAdapter } from '../BlinkAdapter.ts';
Expand Down Expand Up @@ -313,7 +314,7 @@ export class BlinkInstance {
id?: string,
) {
const { url: proxyUrl, headers: proxyHeaders } = proxify(apiUrl);
const response = await fetch(proxyUrl, {
const response = await secureFetch(proxyUrl.toString(), {
headers: {
Accept: 'application/json',
...proxyHeaders,
Expand Down
1 change: 1 addition & 0 deletions packages/blinks-core/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export { isProxified, proxify, proxifyImage, setProxyUrl } from './proxify';
export { checkSecurity, type SecurityLevel } from './security';
export * from './supportability.ts';
export * from './url-mapper.ts';
export * from './secure-fetch.ts';
46 changes: 46 additions & 0 deletions packages/blinks-core/src/utils/secure-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { BlinksRegistry, type LookupType } from '../api';

/**
* Fetch a resource while validating any redirect URL using BlinksRegistry.
* If a redirect response is returned, only follow it when the target URL
* is marked as `trusted` in the registry. Throws otherwise.
*/
export async function secureFetch(
url: string,
init: RequestInit & { abortController?: AbortController } = {},
lookupType: LookupType = 'blink',
): Promise<Response> {
let currentUrl = url;
let redirectCount = 0;
const { abortController, ...rest } = init;

while (redirectCount < 5) {
const response = await fetch(currentUrl, {
...rest,
redirect: 'manual',
signal: abortController?.signal,
});

if (
response.status >= 300 &&
response.status < 400 &&
response.headers.has('location')
) {
const locationHeader = response.headers.get('location')!;
const nextUrl = new URL(locationHeader, currentUrl).toString();
const { state } = BlinksRegistry.getInstance().lookup(nextUrl, lookupType);
if (state !== 'trusted') {
throw new Error(
`Redirect target failed security validation: ${nextUrl}`,
);
}
currentUrl = nextUrl;
redirectCount++;
continue;
}

return response;
}

throw new Error('Too many redirects');
Copy link
Preview

Copilot AI Jun 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider enhancing the error message by including the number of redirects attempted and the final URL, which would aid in debugging redirect loops.

Suggested change
throw new Error('Too many redirects');
throw new Error(`Too many redirects: attempted ${redirectCount} redirects, final URL was ${currentUrl}`);

Copilot uses AI. Check for mistakes.

}
68 changes: 68 additions & 0 deletions packages/blinks-core/test/api/secure-fetch.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { describe, expect, test } from 'bun:test';
import { secureFetch, BlinksRegistry, type BlinksRegistryConfig } from '../../src';

function withMockedFetch(mock: typeof fetch, fn: () => Promise<void>) {
const originalFetch = globalThis.fetch;
globalThis.fetch = mock as any;
return fn().finally(() => {
globalThis.fetch = originalFetch;
});
}

describe('secureFetch', () => {
test('follows redirect when target is trusted', async () => {
const fetchMock = async (url: RequestInfo | URL): Promise<Response> => {
const u = url.toString();
if (u.endsWith('/redirect')) {
return new Response(null, { status: 302, headers: { location: '/final' } });
}
if (u.endsWith('/final')) {
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}
return new Response(null, { status: 404 });
};

const config: BlinksRegistryConfig = {
actions: [{ host: 'example.com', state: 'trusted' }],
websites: [],
interstitials: [],
};
BlinksRegistry.getInstance(config);

await withMockedFetch(fetchMock, async () => {
const response = await secureFetch('https://example.com/redirect');
const data = await response.json();
expect(data).toEqual({ ok: true });
});
});

test('throws on redirect to malicious url', async () => {
const fetchMock = async (url: RequestInfo | URL): Promise<Response> => {
const u = url.toString();
if (u.endsWith('/redirect')) {
return new Response(null, {
status: 302,
headers: { location: 'https://evil.com/final' },
});
}
return new Response(null, { status: 404 });
};

const config: BlinksRegistryConfig = {
actions: [
{ host: 'example.com', state: 'trusted' },
{ host: 'evil.com', state: 'malicious' },
],
websites: [],
interstitials: [],
};
BlinksRegistry.getInstance(config);

await withMockedFetch(fetchMock, async () => {
await expect(secureFetch('https://example.com/redirect')).rejects.toThrow();
});
});
});