Skip to content
Closed
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
37 changes: 37 additions & 0 deletions apps/api/src/modules/misc/misc.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ import { createMock } from '@golevelup/ts-jest';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { MiscService } from '../misc/misc.service';
import { ApiKeyService } from '../auth/api-key.service';
import { PrismaService } from '../common/prisma.service';

describe('MiscController', () => {
let controller: MiscController;

const configService = createMock<ConfigService>();
const jwtService = createMock<JwtService>();
const miscService = createMock<MiscService>();
const apiKeyService = createMock<ApiKeyService>();
const prismaService = createMock<PrismaService>();

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
Expand All @@ -19,6 +23,8 @@ describe('MiscController', () => {
{ provide: ConfigService, useValue: configService },
{ provide: JwtService, useValue: jwtService },
{ provide: MiscService, useValue: miscService },
{ provide: ApiKeyService, useValue: apiKeyService },
{ provide: PrismaService, useValue: prismaService },
],
}).compile();

Expand All @@ -28,4 +34,35 @@ describe('MiscController', () => {
it('should be defined', () => {
expect(controller).toBeDefined();
});

describe('buildCorsHeaders', () => {
const buildCorsHeaders = (origin?: string) =>
(controller as any).buildCorsHeaders(origin) as Record<string, string>;

beforeEach(() => {
configService.get.mockReturnValue('https://app.refly.ai, https://refly.ai');
});

it('reflects origin and allows credentials for allowlisted origins', () => {
const headers = buildCorsHeaders('https://app.refly.ai');
expect(headers['Access-Control-Allow-Origin']).toBe('https://app.refly.ai');
expect(headers['Access-Control-Allow-Credentials']).toBe('true');
expect(headers['Vary']).toBe('Origin');
expect(headers['Cross-Origin-Resource-Policy']).toBe('cross-origin');
});

it('does not reflect non-allowlisted origins', () => {
const headers = buildCorsHeaders('https://evil.example.com');
expect(headers['Access-Control-Allow-Origin']).toBeUndefined();
expect(headers['Access-Control-Allow-Credentials']).toBeUndefined();
// no-cors embedding (e.g. <img>) must keep working
expect(headers['Cross-Origin-Resource-Policy']).toBe('cross-origin');
});

it('omits CORS headers when no Origin header is present', () => {
const headers = buildCorsHeaders(undefined);
expect(headers['Access-Control-Allow-Origin']).toBeUndefined();
expect(headers['Access-Control-Allow-Credentials']).toBeUndefined();
});
});
});
41 changes: 33 additions & 8 deletions apps/api/src/modules/misc/misc.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
Query,
} from '@nestjs/common';
import path from 'node:path';
import { ConfigService } from '@nestjs/config';
import { JwtAuthGuard } from '../auth/guard/jwt-auth.guard';
import { MiscService } from '../misc/misc.service';
import {
Expand All @@ -32,7 +33,37 @@ import { checkHttpCache, send304NotModified, applyCacheHeaders } from '../../uti

@Controller('v1/misc')
export class MiscController {
constructor(private readonly miscService: MiscService) {}
constructor(
private readonly miscService: MiscService,
private readonly configService: ConfigService,
) {}

/**
* Build CORS headers for file-serving endpoints.
* Only origins in the ORIGIN allowlist (same source as the global CORS
* config in main.ts) get credentialed access; other origins receive no
* Access-Control-Allow-Origin header, so browsers block cross-origin reads
* of authenticated responses. Cross-Origin-Resource-Policy stays
* 'cross-origin' so legitimate no-cors embedding (e.g. <img>) keeps working.
*/
private buildCorsHeaders(origin: string | undefined): Record<string, string> {
const allowedOrigins = (this.configService.get<string>('origin') ?? '')
.split(',')
.map((o) => o.trim())
.filter(Boolean);

const headers: Record<string, string> = {
'Cross-Origin-Resource-Policy': 'cross-origin',
};

if (origin && allowedOrigins.includes(origin)) {
headers['Access-Control-Allow-Origin'] = origin;
headers['Access-Control-Allow-Credentials'] = 'true';
headers['Vary'] = 'Origin';
}
Comment on lines +55 to +63

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Set Vary: Origin for all responses.

This response varies by request Origin, but rejected-origin responses omit Vary: Origin. A cache can store that variant as origin-independent and reuse it for an allowlisted origin. Set Vary: Origin in headers before the conditional. Add assertions for Vary in the rejected-origin and missing-origin tests.

Proposed fix
     const headers: Record<string, string> = {
       'Cross-Origin-Resource-Policy': 'cross-origin',
+      'Vary': 'Origin',
     };
 
     if (origin && allowedOrigins.includes(origin)) {
       headers['Access-Control-Allow-Origin'] = origin;
       headers['Access-Control-Allow-Credentials'] = 'true';
-      headers['Vary'] = 'Origin';
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const headers: Record<string, string> = {
'Cross-Origin-Resource-Policy': 'cross-origin',
};
if (origin && allowedOrigins.includes(origin)) {
headers['Access-Control-Allow-Origin'] = origin;
headers['Access-Control-Allow-Credentials'] = 'true';
headers['Vary'] = 'Origin';
}
const headers: Record<string, string> = {
'Cross-Origin-Resource-Policy': 'cross-origin',
'Vary': 'Origin',
};
if (origin && allowedOrigins.includes(origin)) {
headers['Access-Control-Allow-Origin'] = origin;
headers['Access-Control-Allow-Credentials'] = 'true';
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/api/src/modules/misc/misc.controller.ts` around lines 55 - 63,
Initialize headers with Vary: Origin before the origin allowlist conditional so
every response, including rejected- and missing-origin cases, carries it. Keep
the existing allowed-origin headers unchanged, and update the corresponding
rejected-origin and missing-origin tests to assert the Vary header.


return headers;
}

@UseGuards(JwtAuthGuard)
@Post('scrape')
Expand Down Expand Up @@ -104,7 +135,7 @@ export class MiscController {
): Promise<void> {
const storageKey = `static/${objectKey}`;
const filename = path.basename(objectKey);
const origin = req.headers.origin;
const corsHeaders = this.buildCorsHeaders(req.headers.origin);

// First, get only metadata (no file content loaded yet)
const { contentType, lastModified } = await this.miscService.getInternalFileMetadata(
Expand All @@ -120,12 +151,6 @@ export class MiscController {
immutable: false,
});

const corsHeaders = {
'Access-Control-Allow-Origin': origin || '*',
'Access-Control-Allow-Credentials': 'true',
'Cross-Origin-Resource-Policy': 'cross-origin',
};

// If client has valid cache, return 304 Not Modified (without loading file content)
if (cacheResult.useCache) {
send304NotModified(res, cacheResult, corsHeaders);
Expand Down