Skip to content

Commit 32e8b25

Browse files
maria-rcksclaude
andauthored
fix(web): show private repository media in pull request tabs (pingdotgg#11706)
Co-authored-by: maria-rcks <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
1 parent 384de08 commit 32e8b25

12 files changed

Lines changed: 615 additions & 28 deletions

File tree

‎apps/server/src/assets/AssetAccess.test.ts‎

Lines changed: 111 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import * as NodeServices from "@effect/platform-node/NodeServices";
33
import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
44
import * as NodeFSP from "node:fs/promises";
5-
import { AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
5+
import { AssetAccessError, AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
66
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
77
import { describe, expect, it } from "@effect/vitest";
88
import * as Crypto from "effect/Crypto";
@@ -11,8 +11,10 @@ import * as FileSystem from "effect/FileSystem";
1111
import * as Layer from "effect/Layer";
1212
import * as Path from "effect/Path";
1313
import * as PlatformError from "effect/PlatformError";
14+
import * as Schema from "effect/Schema";
1415
import * as TestClock from "effect/testing/TestClock";
15-
import { HttpServerResponse } from "effect/unstable/http";
16+
import { HttpClient, HttpClientResponse, HttpServerResponse } from "effect/unstable/http";
17+
import { ChildProcessSpawner } from "effect/unstable/process";
1618
import { vi } from "vite-plus/test";
1719

1820
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -25,6 +27,8 @@ import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.t
2527
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
2628
import { openMediaFile } from "./MediaFile.ts";
2729
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
30+
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
31+
import { githubMediaResponse } from "./GitHubMediaFetch.ts";
2832

2933
vi.mock("node:fs/promises", async (importOriginal) => {
3034
const actual = await importOriginal<typeof NodeFSP>();
@@ -47,6 +51,52 @@ const testLayer = Layer.mergeAll(
4751
).pipe(Layer.provideMerge(NodeServices.layer));
4852

4953
describe("AssetAccess", () => {
54+
it.effect("loads private media immediately after login and reuses the found credential", () => {
55+
let lookups = 0;
56+
const authorizations: Array<string | undefined> = [];
57+
return Effect.gen(function* () {
58+
const asset = {
59+
url: "https://raw.githubusercontent.com/owner/repo/main/shot.png",
60+
cwd: "/repo",
61+
expiresAt: Number.MAX_SAFE_INTEGER,
62+
};
63+
expect((yield* githubMediaResponse(asset, {})).status).toBe(404);
64+
expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
65+
expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
66+
expect(lookups).toBe(2);
67+
expect(authorizations).toEqual([undefined, "Bearer signed-in", "Bearer signed-in"]);
68+
}).pipe(
69+
Effect.provide(
70+
Layer.mock(GitHubCli.GitHubCli)({
71+
execute: () =>
72+
Effect.sync(() => ({
73+
exitCode: ChildProcessSpawner.ExitCode(0),
74+
stdout: ++lookups === 1 ? "" : "signed-in",
75+
stderr: "",
76+
stdoutTruncated: false,
77+
stderrTruncated: false,
78+
})),
79+
}),
80+
),
81+
Effect.provideService(
82+
HttpClient.HttpClient,
83+
HttpClient.make((request) => {
84+
authorizations.push(request.headers.authorization);
85+
return Effect.succeed(
86+
HttpClientResponse.fromWeb(
87+
request,
88+
new Response(null, {
89+
status: request.headers.authorization ? 200 : 404,
90+
headers: { "content-type": "image/png" },
91+
}),
92+
),
93+
);
94+
}),
95+
),
96+
Effect.scoped,
97+
);
98+
});
99+
50100
it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
51101
Effect.gen(function* () {
52102
const fs = yield* FileSystem.FileSystem;
@@ -228,7 +278,7 @@ describe("AssetAccess", () => {
228278
suffix.slice(0, separator),
229279
suffix.slice(separator + 1),
230280
);
231-
if (!asset) throw new Error("Expected a resolved media file");
281+
if (asset?.kind !== "file") throw new Error("Expected a resolved media file");
232282

233283
yield* fs.rename(filePath, savedPath);
234284
yield* fs.symlink(secretPath, filePath);
@@ -391,7 +441,7 @@ describe("AssetAccess", () => {
391441
const name = suffix.slice(separator + 1);
392442
yield* fs.writeFileString(filePath, "in-place edit");
393443
const edited = yield* resolveAsset(token, name);
394-
if (!edited) throw new Error("Expected the edited media file");
444+
if (edited?.kind !== "file") throw new Error("Expected the edited media file");
395445
const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
396446
expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
397447

@@ -407,7 +457,7 @@ describe("AssetAccess", () => {
407457
renewedSuffix.slice(0, renewedSeparator),
408458
renewedSuffix.slice(renewedSeparator + 1),
409459
);
410-
if (!renewedAsset) throw new Error("Expected the replacement media file");
460+
if (renewedAsset?.kind !== "file") throw new Error("Expected the replacement media file");
411461
const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
412462
expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
413463
yield* fs.remove(filePath);
@@ -1062,4 +1112,60 @@ describe("AssetAccess", () => {
10621112
expect(error.cause).toBe(resolutionCause);
10631113
}).pipe(Effect.provide(testLayer)),
10641114
);
1115+
1116+
it.effect("serves GitHub-hosted pull request media through the repository's credential", () =>
1117+
Effect.gen(function* () {
1118+
const resolve = (relativeUrl: string) => {
1119+
const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1120+
const separator = suffix.indexOf("/");
1121+
return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
1122+
};
1123+
const issue = (url: string) =>
1124+
issueAssetUrl({ resource: { _tag: "github-media", cwd: "/repo", url } });
1125+
1126+
const attachment = yield* issue(
1127+
"https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
1128+
);
1129+
expect(attachment.relativeUrl.endsWith("/1a1842fb-6383-492f-873c-57aa0033fa6c")).toBe(true);
1130+
expect(yield* resolve(attachment.relativeUrl)).toEqual({
1131+
kind: "github-media",
1132+
url: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
1133+
cwd: "/repo",
1134+
// The signed URL's own expiry, which is how long a client may keep the bytes.
1135+
expiresAt: attachment.expiresAt,
1136+
});
1137+
1138+
// A `blob` link addresses the page; only the raw host answers a credential with bytes.
1139+
const committed = yield* issue("https://github.com/owner/repo/blob/main/docs/shot.png");
1140+
expect(yield* resolve(committed.relativeUrl)).toMatchObject({
1141+
url: "https://raw.githubusercontent.com/owner/repo/main/docs/shot.png",
1142+
});
1143+
1144+
// The pre-`user-attachments` form, Git LFS bytes, and a name no `decodeURIComponent`
1145+
// accepts all arrive from real bodies.
1146+
const legacy = yield* issue("https://github.com/owner/repo/assets/45952064/1a1842fb");
1147+
expect(yield* resolve(legacy.relativeUrl)).toMatchObject({
1148+
url: "https://github.com/owner/repo/assets/45952064/1a1842fb",
1149+
});
1150+
const lfs = yield* issue("https://media.githubusercontent.com/media/owner/repo/main/a.mp4");
1151+
expect(yield* resolve(lfs.relativeUrl)).toMatchObject({
1152+
url: "https://media.githubusercontent.com/media/owner/repo/main/a.mp4",
1153+
});
1154+
const awkward = yield* issue("https://raw.githubusercontent.com/o/r/main/100%.png");
1155+
expect(awkward.relativeUrl.endsWith("/100%25.png")).toBe(true);
1156+
1157+
for (const url of [
1158+
"https://example.com/shot.png",
1159+
"https://example.com/shot.png?token=private-media-token",
1160+
"http://github.com/user-attachments/assets/1a1842fb",
1161+
"https://github.com/owner/repo/pull/1",
1162+
"https://github.com/owner/repo/blob/main/",
1163+
]) {
1164+
const error = yield* issue(url).pipe(Effect.flip);
1165+
expect(error._tag).toBe("AssetGitHubMediaUrlValidationError");
1166+
const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(AssetAccessError))(error);
1167+
expect(encoded).not.toContain(url);
1168+
}
1169+
}).pipe(Effect.provide(testLayer)),
1170+
);
10651171
});

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { AssetResource } from "@t3tools/contracts";
22
import {
33
AssetAttachmentNotFoundError,
4+
AssetGitHubMediaUrlValidationError,
45
AssetPreviewTypeValidationError,
56
AssetProjectFaviconInspectionError,
67
AssetProjectFaviconNotFoundError,
@@ -27,6 +28,7 @@ import {
2728
readImageDimensions,
2829
type ImageDimensions,
2930
} from "@t3tools/shared/imageDimensions";
31+
import { githubMediaFetchUrl, githubMediaFileName } from "@t3tools/shared/githubMedia";
3032
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
3133
import * as Clock from "effect/Clock";
3234
import * as Crypto from "effect/Crypto";
@@ -135,21 +137,38 @@ const AssetClaimsSchema = Schema.Union([
135137
app: ToolActivityNativeAppReference,
136138
expiresAt: Schema.Number,
137139
}),
140+
Schema.Struct({
141+
version: Schema.Literal(1),
142+
kind: Schema.Literal("github-media"),
143+
/** Already narrowed to a GitHub media host at mint time; the signature is what keeps it there. */
144+
url: Schema.String,
145+
cwd: Schema.String,
146+
expiresAt: Schema.Number,
147+
}),
138148
]);
139149
type AssetClaims = typeof AssetClaimsSchema.Type;
140150

141151
const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
142152
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
143153
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
144154

145-
export type ResolvedAsset = {
146-
readonly kind: "file";
147-
readonly path: string;
148-
readonly download?: boolean;
149-
readonly fileName?: string;
150-
readonly mimeType?: string;
151-
readonly file?: OpenMediaFile;
152-
};
155+
export type ResolvedAsset =
156+
| {
157+
readonly kind: "file";
158+
readonly path: string;
159+
readonly download?: boolean;
160+
readonly fileName?: string;
161+
readonly mimeType?: string;
162+
readonly file?: OpenMediaFile;
163+
}
164+
| {
165+
readonly kind: "github-media";
166+
readonly url: string;
167+
readonly cwd: string;
168+
/** When the signed URL that granted this stops working, which bounds how long a client
169+
may keep the bytes it fetched with it. */
170+
readonly expiresAt: number;
171+
};
153172

154173
function decodeClaims(encodedPayload: string): AssetClaims | null {
155174
try {
@@ -657,6 +676,21 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
657676
fileName = "native-app-icon.png";
658677
break;
659678
}
679+
case "github-media": {
680+
const fetchUrl = githubMediaFetchUrl(input.resource.url);
681+
if (fetchUrl === null) {
682+
return yield* new AssetGitHubMediaUrlValidationError({});
683+
}
684+
claims = {
685+
version: 1,
686+
kind: "github-media",
687+
url: fetchUrl,
688+
cwd: input.resource.cwd,
689+
expiresAt,
690+
};
691+
fileName = githubMediaFileName(fetchUrl);
692+
break;
693+
}
660694
}
661695

662696
const secretStore = yield* ServerSecretStore.ServerSecretStore;
@@ -757,6 +791,15 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
757791
: null;
758792
}
759793

794+
if (claims.kind === "github-media") {
795+
return {
796+
kind: "github-media",
797+
url: claims.url,
798+
cwd: claims.cwd,
799+
expiresAt: claims.expiresAt,
800+
} satisfies ResolvedAsset;
801+
}
802+
760803
if (claims.kind === "native-app-icon") {
761804
const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
762805
const iconPath = yield* nativeAppIconResolver.resolve(claims.app);

0 commit comments

Comments
 (0)