main
1import { plyError } from 'ply';
2import { atIndex, captureGroup, chainGet } from '../absent.ts';
3import { unwrapOr } from '../option.ts';
4import { validatePath } from 'ply';
5import { unwrap } from '../ply-result.ts';
6import { VIEWER_CAPS, VIEWER_GIT_LIMITS } from './limits.ts';
7import type { FilterName } from './model.ts';
8import { interpretRemote } from './paste.ts';
9import { extractRequestPath, rawPathHasUnsafeSegment, rawQueryPathUnsafe } from '../pathguard.ts';
10import { allowlistFromEnv, validatePublicRepoUrl, viewerPathFor, withHost, type AllowedHost, type RepoLocation } from './url.ts';
11import { PUBLIC_GIT_HOST, PUBLIC_GIT_ORIGIN, PUBLIC_NAMESPACE, isPublicRepoName, publicRemote, publicRepoOfRemote, publicRepoShortName } from '../public.ts';
13export type ViewerRoute =
14 | { kind: 'css'; hash: string | null }
15 | { kind: 'home' }
16 | { kind: 'namespace' }
17 | { kind: 'redirect'; location: string }
18 | {
19 kind: 'repo';
20 loc: RepoLocation;
21 ref: string | null;
22 path: string;
23 raw: boolean;
24 pack: { want: string; filter: FilterName; offset: number | null } | null;
25 };
27export type RouteOpts = {
28 allowedHosts: readonly AllowedHost[];
29};
31const SECRET_QUERY = /^(access_token|token|password|auth|authorization|git-token|git-authorization)$/i;
32const OID = /^[0-9a-f]{40}$/;
34function bad(message: string): never {
35 throw plyError('bad_request', message);
36}
38export function routeOptsFromEnv(env: unknown): RouteOpts {
39 const extra = chainGet(env, 'VIEWER_EXTRA_HOSTS');
40 const raw = extra.tag === 'some' && typeof extra.value === 'string' ? extra.value : null;
41 return { allowedHosts: allowlistFromEnv(raw) };
42}
44function chosenRef(url: URL, fallback: string | null = null): string | null {
45 const at = url.searchParams.get('at')
46 if (at !== null && at !== '') return parseRef(at)
47 const commit = url.searchParams.get('commit')
48 if (commit !== null && commit !== '') return parseRef(commit)
49 const ref = url.searchParams.get('ref')
50 if (ref !== null && ref !== '') return parseRef(ref)
51 return fallback
52}
54/** `at` and `commit` are aliases of `ref`. A public-namespace page on the long host path canonicalises to `/r/<name>`. */
55function canonicalLocation(url: URL, loc: RepoLocation, ref: string | null, path: string, raw: boolean, pack: Extract<ViewerRoute, { kind: 'repo' }>['pack']): string | null {
56 const alias = url.searchParams.has('at') || url.searchParams.has('commit')
57 const short = publicRepoShortName(loc.host, loc.repoPath)
58 const onShort = short !== null && url.pathname === `/r/${encodeURIComponent(short)}`
59 if (!alias && (short === null || onShort)) return null
60 const query: Record<string, string | null> = {
61 ref,
62 path: path.length > 0 ? path : null,
63 raw: raw ? '1' : null,
64 trace: url.searchParams.get('trace') === '1' ? '1' : null,
65 want: pack === null ? null : pack.want,
66 filter: pack === null ? null : pack.filter,
67 offset: pack !== null && pack.offset !== null ? String(pack.offset) : null,
68 }
69 return viewerPathFor(loc, query)
70}
72function parseRef(raw: string | null): string | null {
73 if (raw === null || raw === '') return null;
74 if (raw.length > 1024) bad('ref is too long');
75 if (raw === 'HEAD') return 'HEAD';
76 if (OID.test(raw)) return raw;
77 if (raw.startsWith('refs/')) {
78 // Control characters are rejected on purpose: a ref is a git name, not free text.
79 // oxlint-disable-next-line no-control-regex
80 if (/[\u0000-\u001f\u007f ~^:?*[\\]|\.\.|@\{|\/\/|\s/.test(raw)) bad('ref is not a valid name');
81 return raw;
82 }
83 if (!/^[A-Za-z0-9._/-]+$/.test(raw) || raw.includes('..') || raw.startsWith('/') || raw.endsWith('/') || raw.endsWith('.lock')) bad('ref is not a valid name');
84 return raw;
85}
87function parsePath(raw: string | null): string {
88 if (raw === null || raw === '') return '';
89 const stripped = raw.replace(/^\/+|\/+$/g, '');
90 if (!stripped) return '';
91 if (stripped.length > 1024) bad('path is too long');
92 unwrap(validatePath(stripped, VIEWER_GIT_LIMITS));
93 return stripped;
94}
96function parseFilter(raw: string | null, wantPresent: boolean): FilterName {
97 if (raw === null || raw === '') return 'tree:0';
98 if (raw === 'tree:0' || raw === 'blob:none') return raw;
99 if (!wantPresent) bad('filter is only valid on a pack map');
100 bad('filter must be tree:0 or blob:none');
101}
103/**
104 * The Artifacts host of the public namespace is served without VIEWER_EXTRA_HOSTS, but only for one repo directly under
105 * /git/<PUBLIC_NAMESPACE>/. Any other path on that host (another namespace, a nested path) is refused before a fetch.
106 */
107function validateLocation(raw: string, opts: RouteOpts): RepoLocation {
108 if (raw.startsWith(`${PUBLIC_GIT_ORIGIN}/`)) {
109 if (publicRepoOfRemote(raw) === null) bad(`only /git/${PUBLIC_NAMESPACE}/<repo> is served from ${PUBLIC_GIT_HOST}`);
110 return validatePublicRepoUrl(raw, { allowedHosts: withHost(opts.allowedHosts, PUBLIC_GIT_HOST), maxLength: VIEWER_CAPS.maxUrlLength });
111 }
112 return validatePublicRepoUrl(raw, { allowedHosts: opts.allowedHosts, maxLength: VIEWER_CAPS.maxUrlLength });
113}
115function locate(host: string, repoPath: string, opts: RouteOpts): RepoLocation {
116 // oxlint-disable-next-line no-control-regex -- hostnames cannot contain controls or whitespace
117 if (!host || host.length > 253 || /[\u0000-\u001f\u007f\s/@\\]/.test(host)) bad(`remote host is not allowed. Supported hosts: ${opts.allowedHosts.join(', ')}.`);
118 return validateLocation(`https://${host.toLowerCase()}/${repoPath}`, opts);
119}
121/** Parse a viewer URL from the raw request target, before `new URL` collapses dot segments. */
122export function parseViewerRequest(raw: string, opts: RouteOpts): ViewerRoute {
123 if (typeof raw !== 'string' || raw.length > VIEWER_CAPS.maxUrlLength * 2) bad('URL is too long');
124 if (raw.includes('\\') || rawPathHasUnsafeSegment(extractRequestPath(raw)) || rawQueryPathUnsafe(raw)) bad('remote path is not allowed');
125 let url: URL;
126 try { url = new URL(raw); }
127 catch { bad('remote path is not allowed'); }
128 if (rawPathHasUnsafeSegment(url.pathname)) bad('remote path is not allowed');
129 return parseViewerRoute(url, opts);
130}
132export function parseViewerRoute(url: URL, opts: RouteOpts): ViewerRoute {
133 if (url.pathname.length > VIEWER_CAPS.maxUrlLength || url.href.length > VIEWER_CAPS.maxUrlLength * 2) bad('URL is too long');
134 if (url.href.includes('\\') || rawPathHasUnsafeSegment(url.pathname) || rawQueryPathUnsafe(url.href)) bad('remote path is not allowed');
135 for (const key of url.searchParams.keys()) if (SECRET_QUERY.test(key)) bad('query must not carry credentials');
136 if (url.pathname === '/view.css') return { kind: 'css', hash: null };
137 const hashed = /^\/view\.([0-9a-f]{12})\.css$/.exec(url.pathname);
138 const hash = captureGroup(hashed, 1);
139 if (hash.tag === 'some' && hash.value) return { kind: 'css', hash: hash.value };
140 if (url.pathname === '/view' || url.pathname === '/view/') {
141 const remote = url.searchParams.get('remote');
142 if (!remote) return { kind: 'home' };
143 const pasted = interpretRemote(remote);
144 const loc = validateLocation(pasted.remote, opts);
145 const ref = chosenRef(url, pasted.ref);
146 return { kind: 'redirect', location: viewerPathFor(loc, { ref, path: pasted.path }) };
147 }
148 if (url.pathname === '/r' || url.pathname === '/r/') return { kind: 'namespace' };
149 let loc: RepoLocation;
150 if (url.pathname.startsWith('/r/')) {
151 const rest = url.pathname.slice('/r/'.length);
152 let name: string;
153 try { name = decodeURIComponent(rest); } catch { throw plyError('not_found', `not a repository in ${PUBLIC_NAMESPACE}`, { miss: { kind: 'repository' } }); }
154 if (name.includes('/') || !isPublicRepoName(name)) throw plyError('not_found', `not a repository in ${PUBLIC_NAMESPACE}`, { miss: { kind: 'repository' } });
155 loc = validateLocation(publicRemote(name), opts);
156 } else {
157 if (!url.pathname.startsWith('/view/')) bad('not a viewer route');
158 let decoded: string;
159 try { decoded = decodeURIComponent(url.pathname.slice('/view/'.length)); } catch { bad('remote path is not allowed'); }
160 if (decoded.includes('%') || decoded.includes('\\') || decoded.includes('\0') || decoded.includes('..')) bad('remote path is not allowed');
161 for (const segment of decoded.split('/')) {
162 if (segment === '.' || segment === '..') bad('remote path is not allowed');
163 }
164 const parts = decoded.split('/').filter(part => part.length > 0);
165 if (parts.length < 2) bad('remote path is not allowed');
166 const host = unwrapOr(atIndex(parts, 0), '');
167 const repoPath = parts.slice(1).join('/');
168 loc = locate(host, repoPath, opts);
169 }
170 const wantRaw = url.searchParams.get('want');
171 const filter = parseFilter(url.searchParams.get('filter'), wantRaw !== null);
172 let pack: { want: string; filter: FilterName; offset: number | null } | null = null;
173 if (wantRaw !== null) {
174 if (!OID.test(wantRaw)) bad('want must be a 40-hex object id');
175 const offsetRaw = url.searchParams.get('offset');
176 let offset: number | null = null;
177 if (offsetRaw !== null && offsetRaw !== '') {
178 if (!/^\d+$/.test(offsetRaw)) bad('offset must be a byte offset');
179 offset = Number(offsetRaw);
180 if (offset > VIEWER_CAPS.maxPackBytes) bad('offset is past the pack cap');
181 }
182 pack = { want: wantRaw, filter, offset };
183 } else if (url.searchParams.get('filter') || url.searchParams.get('offset')) bad('filter and offset need a want');
184 const raw = url.searchParams.get('raw') === '1';
185 if (raw && pack) bad('raw is a file view');
186 const ref = chosenRef(url);
187 const path = parsePath(url.searchParams.get('path'));
188 const location = canonicalLocation(url, loc, ref, path, raw, pack);
189 if (location) return { kind: 'redirect', location };
190 return { kind: 'repo', loc, ref, path, raw, pack };
191}
Diagnostics4 git calls · 28 ms
CallStatusSizeTime028 ms
discover200152 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200145 B · hit3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=145 git.response.cache=HIT git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=145 git.pkt.payload.max=76 git.ls_refs.count=2 git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020040 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=23 git.response.bytes=41349 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=526b305930b8ef382f2d7a1f9c0238730a585921 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=6 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=41349 git.pkt.payload.max=41254 git.sideband.band1.bytes=41253 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=61 git.pack.bytes=41253 git.pack.ofs_delta=0 git.pack.ref_delta=0 git.pack.chain.max=0 git.pack.trailer=ab60efef4b7243678c75de64a4386986ee885c1c git.pack.full=61Open pack map
fetch2003.1 KiB · hit23 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=3211 git.response.cache=HIT git.response.duration_ms=23 git.fetch.wants=b9ded13e3b0399a2b502f678b67ce1f6eb9f040c git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=3211 git.pkt.payload.max=3190 git.sideband.band1.bytes=3189 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply-web.git
- Ref
- refs/heads/main
- Commit
- 526b305930b8ef382f2d7a1f9c0238730a585921
- cf-ray
- a5e307294dfa15db
- Request
- bddd2569…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format