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 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
4 changes: 3 additions & 1 deletion packages/blinks-core/src/BlinkContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,9 @@ export const BlinkContainer = ({
let timeout: any; // NodeJS.Timeout
const fetcher = async () => {
try {
const newBlink = await blink.refresh();
const newBlink = await blink.refresh(
normalizedSecurityLevel.actions,
);

// if after refresh user clicked started execution, we should not update the action
if (executionState.status === 'idle') {
Expand Down
23 changes: 17 additions & 6 deletions packages/blinks-core/src/api/BlinkInstance/BlinkInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
isProxified,
proxify,
proxifyImage,
secureFetch,
type SecurityLevel,
} from '../../utils';
import { isUrlSameOrigin } from '../../utils/security.ts';
import type { BlinkAdapter } from '../BlinkAdapter.ts';
Expand Down Expand Up @@ -311,14 +313,20 @@ export class BlinkInstance {
supportStrategy: BlinkSupportStrategy = defaultBlinkSupportStrategy,
chainMetadata?: BlinkChainMetadata,
id?: string,
securityLevel: SecurityLevel = 'only-trusted',
) {
const { url: proxyUrl, headers: proxyHeaders } = proxify(apiUrl);
const response = await fetch(proxyUrl, {
headers: {
Accept: 'application/json',
...proxyHeaders,
const response = await secureFetch(
proxyUrl.toString(),
{
headers: {
Accept: 'application/json',
...proxyHeaders,
},
},
});
'blink',
securityLevel,
);

if (!response.ok) {
throw new Error(
Expand All @@ -343,6 +351,7 @@ export class BlinkInstance {
static async fetch(
apiUrl: string,
supportStrategy: BlinkSupportStrategy = defaultBlinkSupportStrategy,
securityLevel: SecurityLevel = 'only-trusted',
) {
const id = nanoid();
return BlinkInstance._fetch(
Expand All @@ -352,15 +361,17 @@ export class BlinkInstance {
isChained: false,
},
id,
securityLevel,
);
}

refresh() {
refresh(securityLevel: SecurityLevel = 'only-trusted') {
return BlinkInstance._fetch(
this.url,
this._supportStrategy,
this._chainMetadata,
this._id,
securityLevel,
);
}

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';
48 changes: 48 additions & 0 deletions packages/blinks-core/src/utils/secure-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { BlinksRegistry, type LookupType } from '../api';
import { checkSecurity, type SecurityLevel } from './security.ts';

/**
* 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',
securityLevel: SecurityLevel = 'only-trusted',
): 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 (!checkSecurity(state, securityLevel)) {
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.

}
109 changes: 109 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,109 @@
import { describe, expect, test, jest } from 'bun:test';
import { secureFetch, BlinksRegistry, type BlinksRegistryConfig } from '../../src';

describe('secureFetch', () => {
test('follows redirect when target is trusted', async () => {
const fetchMock = jest.fn(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);

const spy = jest.spyOn(globalThis, 'fetch').mockImplementation(fetchMock);

try {
const response = await secureFetch('https://example.com/redirect');
const data = await response.json();
expect(data).toEqual({ ok: true });
} finally {
spy.mockRestore();
}
});

test('throws on redirect to malicious url', async () => {
const fetchMock = jest.fn(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);

const spy = jest.spyOn(globalThis, 'fetch').mockImplementation(fetchMock);

try {
await expect(secureFetch('https://example.com/redirect')).rejects.toThrow();
} finally {
spy.mockRestore();
}
});

test('allows redirect to unknown url when securityLevel is non-malicious', async () => {
const fetchMock = jest.fn(async (url: RequestInfo | URL): Promise<Response> => {
const u = url.toString();
if (u.endsWith('/redirect')) {
return new Response(null, {
status: 302,
headers: { location: 'https://unknown.com/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);

const spy = jest.spyOn(globalThis, 'fetch').mockImplementation(fetchMock);

try {
const response = await secureFetch(
'https://example.com/redirect',
{},
'blink',
'non-malicious',
);
const data = await response.json();
expect(data).toEqual({ ok: true });
} finally {
spy.mockRestore();
}
});
});
1 change: 1 addition & 0 deletions packages/blinks/src/ext/twitter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ async function handleNewNode(
const blink = await BlinkInstance.fetch(
blinkApiUrl,
options.supportStrategy,
options.securityLevel.actions,
).catch(noop);

if (!blink) {
Expand Down