Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

githubMedia.ts

51 lines1.9 KB

1/**
2 * Only hosts where a credential is what decides the answer belong here. `objects.githubusercontent.com`
3 * and the `private-user-images` links GitHub's own HTML carries are already signed and load on their
4 * own, and a token does nothing for them once that signature expires.
5 */
6​
7const RAW_HOST = "raw.githubusercontent.com";
8const LFS_HOST = "media.githubusercontent.com";
9const ATTACHMENT_PATH_PATTERN = /^\/user-attachments\/assets\/[\w-]+$/u;
10const LEGACY_ATTACHMENT_PATH_PATTERN = /^\/[^/]+\/[^/]+\/assets\/\d+\/[\w-]+$/u;
11/** `blob` and `raw` both address file bytes; `raw` is the one the token is honoured on. */
12const REPOSITORY_FILE_PATTERN = /^\/([^/]+)\/([^/]+)\/(?:raw|blob)\/(.*[^/])$/u;
13​
14function canonicalUrl(host: string, url: URL): string {
15 return `https://${host}${url.pathname}${url.search}`;
17​
18export function githubMediaFetchUrl(source: string): string | null {
19 let url: URL;
20 try {
21 url = new URL(source);
22 } catch {
23 return null;
24 }
25 if (url.protocol !== "https:") return null;
26 const host = url.hostname.toLowerCase();
27 if (host === RAW_HOST || host === LFS_HOST) return canonicalUrl(host, url);
28 if (host !== "github.com" && host !== "www.github.com") return null;
29 if (
30 ATTACHMENT_PATH_PATTERN.test(url.pathname) ||
31 LEGACY_ATTACHMENT_PATH_PATTERN.test(url.pathname)
32 ) {
33 return `https://github.com${url.pathname}`;
34 }
35 const repositoryFile = REPOSITORY_FILE_PATTERN.exec(url.pathname);
36 return repositoryFile
37 ? `https://${RAW_HOST}/${repositoryFile[1]}/${repositoryFile[2]}/${repositoryFile[3]}`
38 : null;
40​
41export function githubMediaFileName(fetchUrl: string): string {
42 const segment = new URL(fetchUrl).pathname.split("/").pop() ?? "";
43 let decoded: string;
44 try {
45 decoded = decodeURIComponent(segment);
46 } catch {
47 decoded = segment;
48 }
49 const name = decoded.replace(/[\p{Cc}\\/]/gu, "");
50 return name.length > 0 ? name : "github-media";