Skip to content

Extract preview media loading from previewMediaRoutes into a reusable, authorization-preserving service #2603

Closed

Description

@propr-dev

Context

packages/api/routes/previewMediaRoutes.ts contains the only code that can securely load a published visual preview (screenshot/video) attached to a pull request or completion comment: it checks the repository has visual previews enabled, reads the PR/comment through the user's GitHub credential (proving access), verifies the asset is one ProPR published (parsePublishedVisualPreviews), resolves GitHub's signed URL from body_html, follows at most 3 redirects to trusted hosts only, validates the content type, and bounds the body (10 MiB images, 100 MiB videos).

The upcoming MCP preview tools need exactly the same pipeline, but the logic is private to the Express handler (serve) and writes directly to res. Duplicating it would fork a security boundary. This issue extracts it into a service with no behaviour change for the HTTP routes.

Requirements

  1. New packages/api/services/previewMediaFetch.ts exporting:
    • PreviewAssociation ({ kind: 'pull' | 'comment'; repository: string; number: number }),
    • loadPublishedPreview({ association, assetId, token, octokit, fetch, reader, maxBytes? }) → { preview: PublishedVisualPreview, contentType, body: Buffer } or throws PreviewMediaError(status, code, message),
    • listPublishedPreviews({ association, octokit, reader }) → PublishedVisualPreview[] with assetId for each (only trusted GitHub attachment URLs),
    • the existing helpers signedMediaUrl, trustedFetchTarget, fetchMedia, boundedBody moved unchanged.
  2. PreviewMediaError carries a stable code: PREVIEW_NOT_FOUND (404), PREVIEWS_DISABLED (404 — do not reveal policy), PREVIEW_SOURCE_REJECTED (502), PREVIEW_TOO_LARGE (413), PREVIEW_INVALID_TYPE (502), PREVIEW_UNAVAILABLE (502).
  3. previewMediaRoutes.ts becomes a thin adapter: parse params → loadPublishedPreview → set the same headers and send; errors map to the same status codes and JSON bodies as today ({ error: message }), and GitHub access errors still go through handleGitHubRepositoryAccessError.
  4. maxBytes defaults to the current limits by media type; callers may pass a lower bound (never higher).
  5. All existing tests in packages/api/test/previewMediaRoutes.test.ts and previewMediaProjection.test.ts pass unchanged; add packages/api/test/previewMediaFetch.test.ts for the service directly (listing, not-found, disabled repository, oversized body).

Implementation Specification

  • New packages/api/services/previewMediaFetch.ts.
  • Edit packages/api/routes/previewMediaRoutes.ts to delegate.
  • New tests as above.

Acceptance Criteria

  • previewMediaRoutes.test.ts passes without modification.
  • listPublishedPreviews for a PR body with two published previews and one unpublished attachment returns exactly the two, each with assetId, title, type, description.
  • loadPublishedPreview with maxBytes: 1024 on a 2 KiB image throws PREVIEW_TOO_LARGE.
  • A repository with previews disabled throws PREVIEWS_DISABLED without calling GitHub.
  • No new code path forwards the user's Authorization header to non-github.com hosts (existing redirect test still passes).

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Pure refactor: move the security-sensitive pipeline into a service, keep the HTTP route as an adapter. We return a Buffer (not a stream) because both consumers already need the full bounded body (the route sends it with Content-Length; the MCP tool will downscale/base64-encode it). Keeping the existing byte limits as ceilings that callers may only lower preserves the route's guarantees while letting MCP ask for less.

    File: packages/api/services/previewMediaFetch.ts (new file)

    Why this file: One implementation of "load a preview this user may see", shared by HTTP and MCP.

    import type { Octokit } from '@octokit/core';
    import { parsePublishedVisualPreviews } from '@propr/core';
    import type { PublishedVisualPreview } from '@propr/shared';
    import type { previewMediaReader } from './previewMediaProjection.js';
    
    // ---- moved verbatim from routes/previewMediaRoutes.ts ----
    const MAX_REDIRECTS = 3;
    export const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
    export const MAX_VIDEO_BYTES = 100 * 1024 * 1024;
    const MEDIA_TYPES = new Set(['image/gif', 'image/jpeg', 'image/png', 'image/svg+xml', 'image/webp', 'video/mp4', 'video/quicktime', 'video/webm']);
    const SIGNED_MEDIA_HOSTS = new Set(['private-user-images.githubusercontent.com', 'secured-user-images.githubusercontent.com',
      'user-images.githubusercontent.com', 'github-production-user-asset-6210df.s3.amazonaws.com']);
    // signedMediaUrl, trustedFetchTarget, fetchMedia, boundedBody: move the existing
    // function bodies here unchanged, replacing `throw new MediaResponseError(status, message)`
    // with `throw new PreviewMediaError(status, CODE, message)` using the codes below.
    // ----------------------------------------------------------
    
    export type PreviewMediaErrorCode = 'PREVIEW_NOT_FOUND' | 'PREVIEWS_DISABLED' | 'PREVIEW_SOURCE_REJECTED'
      | 'PREVIEW_TOO_LARGE' | 'PREVIEW_INVALID_TYPE' | 'PREVIEW_UNAVAILABLE';
    
    export class PreviewMediaError extends Error {
      constructor(readonly status: number, readonly code: PreviewMediaErrorCode, message: string) { super(message); }
    }
    
    export interface PreviewAssociation { kind: 'pull' | 'comment'; repository: string; number: number }
    export interface ListedPreview extends PublishedVisualPreview { assetId: string }
    
    type Reader = Pick<typeof previewMediaReader, 'enabledRepositories'>;
    type GitHub = Pick<Octokit, 'request'>;
    
    /** Read the PR/comment with the caller's credential; this read is the access check. */
    async function readPublishedBody(octokit: GitHub, association: PreviewAssociation) {
      const [owner, repo] = association.repository.split('/');
      const endpoint = association.kind === 'pull' ? 'GET /repos/{owner}/{repo}/pulls/{pull_number}' : 'GET /repos/{owner}/{repo}/issues/comments/{comment_id}';
      const identity = association.kind === 'pull' ? { pull_number: association.number } : { comment_id: association.number };
      const response = await octokit.request(endpoint, { owner, repo, ...identity, mediaType: { format: 'full' },
        request: { signal: AbortSignal.timeout(5_000) } }) as { data: { body?: unknown; body_html?: unknown } };
      return response.data;
    }
    
    async function assertEnabled(reader: Reader, repository: string): Promise<void> {
      // Same 404 as "not found": never reveal a repository's preview policy.
      if (!(await reader.enabledRepositories([repository])).has(repository)) {
        throw new PreviewMediaError(404, 'PREVIEWS_DISABLED', 'Preview media not found');
      }
    }
    
    const ASSET = /^https:\/\/github\.com\/user-attachments\/assets\/([A-Za-z0-9_-]{1,128})$/;
    
    export async function listPublishedPreviews(options: { association: PreviewAssociation; octokit: GitHub; reader: Reader }): Promise<ListedPreview[]> {
      await assertEnabled(options.reader, options.association.repository);
      const data = await readPublishedBody(options.octokit, options.association);
      return parsePublishedVisualPreviews(data.body).flatMap(preview => {
        const match = ASSET.exec(preview.url);
        return match ? [{ ...preview, assetId: match[1] }] : [];
      });
    }
    
    export async function loadPublishedPreview(options: {
      association: PreviewAssociation; assetId: string; token: string; octokit: GitHub; fetch: typeof fetch; reader: Reader; maxBytes?: number;
    }): Promise<{ preview: PublishedVisualPreview; contentType: string; body: Buffer }> {
      const { association, assetId } = options;
      await assertEnabled(options.reader, association.repository);
      const data = await readPublishedBody(options.octokit, association);
      const sourceUrl = `https://github.com/user-attachments/assets/${assetId}`;
      const preview = parsePublishedVisualPreviews(data.body).find(item => item.url === sourceUrl);
      if (!preview) throw new PreviewMediaError(404, 'PREVIEW_NOT_FOUND', 'Preview media not found');
      const source = signedMediaUrl(data.body_html, assetId) ?? new URL(sourceUrl);
      const media = await fetchMedia(source, assetId, options.token, options.fetch);
      if (!media.ok) {
        try { await media.body?.cancel(); } catch { /* best effort */ }
        throw media.status === 404
          ? new PreviewMediaError(404, 'PREVIEW_NOT_FOUND', 'Preview media is unavailable')
          : new PreviewMediaError(502, 'PREVIEW_UNAVAILABLE', 'Preview media could not be loaded');
      }
      const contentType = media.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase() ?? '';
      if (!MEDIA_TYPES.has(contentType) || (preview.type === 'image') !== contentType.startsWith('image/')) {
        try { await media.body?.cancel(); } catch { /* best effort */ }
        throw new PreviewMediaError(502, 'PREVIEW_INVALID_TYPE', 'Preview media returned an invalid content type');
      }
      const ceiling = contentType.startsWith('image/') ? MAX_IMAGE_BYTES : MAX_VIDEO_BYTES;
      // Callers may lower the bound, never raise it.
      const limit = Math.min(ceiling, options.maxBytes ?? ceiling);
      return { preview, contentType, body: await boundedBody(media, limit) };
    }

    File: packages/api/routes/previewMediaRoutes.ts

    Why this file: Becomes a thin HTTP adapter; response headers and status codes are unchanged.

    --- a/packages/api/routes/previewMediaRoutes.ts
    +++ b/packages/api/routes/previewMediaRoutes.ts
    @@
    -import { parsePublishedVisualPreviews } from '@propr/core';
    +import { loadPublishedPreview, PreviewMediaError } from '../services/previewMediaFetch.js';
    @@ (remove MAX_*, MEDIA_TYPES, SIGNED_MEDIA_HOSTS, MediaResponseError, signedMediaUrl, trustedFetchTarget, fetchMedia, boundedBody, sendMediaResponse body checks)
       const serve = (kind: Association['kind']) => async (req: Request, res: Response): Promise<void> => {
         if (!req.user?.id) { res.status(401).json({ error: 'Authentication required' }); return; }
         const parsed = parseRequest(req, kind);
         if (!parsed) { res.status(400).json({ error: 'Invalid preview media identity' }); return; }
         try {
    -      if (!(await reader.enabledRepositories([parsed.repository])).has(parsed.repository)) { ... }
    -      const token = await resolveToken(req);
    -      ... (GitHub read, publication check, fetchMedia, sendMediaResponse)
    +      const token = await resolveToken(req);
    +      const { contentType, body } = await loadPublishedPreview({ association: { ...parsed.association, repository: parsed.repository },
    +        assetId: parsed.assetId, token, octokit: createOctokit(token), fetch: fetcher, reader });
    +      res.set({ 'Cache-Control': 'private, no-store', 'Content-Security-Policy': "default-src 'none'; sandbox",
    +        'Content-Type': contentType, 'Content-Length': String(body.byteLength), Vary: 'Authorization, Cookie', 'X-Content-Type-Options': 'nosniff' });
    +      res.status(200).send(body);
         } catch (error) {
           if (await handleGitHubRepositoryAccessError(req, res, error)) return;
    -      if (error instanceof MediaResponseError) { res.status(error.status).json({ error: error.message }); return; }
    +      if (error instanceof PreviewMediaError) { res.status(error.status).json({ error: error.message }); return; }
           res.status(502).json({ error: 'Preview media is temporarily unavailable' });
         }
       };

    Order note: the original handler checked the enabled policy before resolving the token. loadPublishedPreview still checks policy before any GitHub call, but the token is now resolved first. If previewMediaRoutes.test.ts asserts that no token is resolved for a disabled repository, call reader.enabledRepositories in the route before resolveToken as well (cheap, cached) to keep that ordering.

    File: packages/api/test/previewMediaFetch.test.ts (new file)

    Why this file: Tests the service contract that the MCP tools will rely on.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import { closeConnection } from '@propr/core';
    import { listPublishedPreviews, loadPublishedPreview, PreviewMediaError } from '../services/previewMediaFetch.js';
    
    after(closeConnection);
    const asset = (id: string) => `https://github.com/user-attachments/assets/${id}`;
    const body = `<!-- propr-visual-preview -->\n### Desktop\n\n![Desktop](${asset('a1')})\nChanged dialog\n### Mobile\n\n![Mobile](${asset('a2')})\n`;
    const reader = (enabled: boolean) => ({ enabledRepositories: async () => new Set(enabled ? ['acme/web'] : []) });
    const octokit = { request: async () => ({ data: { body: `${body}\n![unpublished](${asset('zz')})`, body_html: '' } }) } as never;
    const association = { kind: 'pull' as const, repository: 'acme/web', number: 7 };
    
    test('lists only published previews with asset ids', async () => {
      const listed = await listPublishedPreviews({ association, octokit, reader: reader(true) });
      assert.deepEqual(listed.map(item => item.assetId), ['a1', 'a2']);
    });
    
    test('disabled repositories never reach GitHub', async () => {
      let called = false;
      await assert.rejects(listPublishedPreviews({ association, octokit: { request: async () => { called = true; return { data: {} }; } } as never, reader: reader(false) }),
        (error: unknown) => error instanceof PreviewMediaError && error.code === 'PREVIEWS_DISABLED');
      assert.equal(called, false);
    });
    
    test('callers can lower but not raise the byte ceiling', async () => {
      const fetcher = (async () => new Response(Buffer.alloc(2048), { status: 200, headers: { 'Content-Type': 'image/png' } })) as typeof fetch;
      await assert.rejects(loadPublishedPreview({ association, assetId: 'a1', token: 't', octokit, fetch: fetcher, reader: reader(true), maxBytes: 1024 }),
        (error: unknown) => error instanceof PreviewMediaError && error.code === 'PREVIEW_TOO_LARGE');
    });
  2. propr-dev commented on Sep 29, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 2603/gpt-5.6-sol-extract-preview-media-loa-20260929-2118-az3
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2603-20260929-2118-gpt-5.6-sol-az3

    🔍 Track Task Execution

  3. added a commit that references this issue on Sep 29, 2026
  4. added a commit that references this issue on Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions