ref0-git 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/app/apps/github/.dev.vars.example +2 -1
  2. package/app/apps/github/generated/git-rest.ts +191 -25
  3. package/app/apps/github/generated/routeTree.gen.ts +21 -0
  4. package/app/apps/github/package.json +1 -1
  5. package/app/apps/github/src/branches/branch-list.tsx +8 -4
  6. package/app/apps/github/src/branches/branches.ts +10 -5
  7. package/app/apps/github/src/camo/addresses.ts +120 -0
  8. package/app/apps/github/src/camo/client.ts +125 -0
  9. package/app/apps/github/src/camo/fetch.ts +201 -0
  10. package/app/apps/github/src/camo/lookup.ts +23 -0
  11. package/app/apps/github/src/camo/node.ts +50 -0
  12. package/app/apps/github/src/camo/proxy.ts +116 -0
  13. package/app/apps/github/src/camo/sign-images.ts +307 -0
  14. package/app/apps/github/src/camo/signing.ts +80 -0
  15. package/app/apps/github/src/clients/allowed.ts +111 -18
  16. package/app/apps/github/src/clients/clients.ts +76 -61
  17. package/app/apps/github/src/clients/transport.ts +13 -0
  18. package/app/apps/github/src/code/code-tree.tsx +3 -1
  19. package/app/apps/github/src/code/file-view.tsx +15 -6
  20. package/app/apps/github/src/code/files.ts +26 -19
  21. package/app/apps/github/src/code/go-to-file.tsx +2 -1
  22. package/app/apps/github/src/code/load.ts +41 -23
  23. package/app/apps/github/src/code/markdown-files.ts +13 -2
  24. package/app/apps/github/src/code/ref-pages.ts +14 -5
  25. package/app/apps/github/src/code/ref-switcher.tsx +4 -3
  26. package/app/apps/github/src/code/refs.ts +42 -8
  27. package/app/apps/github/src/code/repo-home.tsx +6 -2
  28. package/app/apps/github/src/code/repo.ts +12 -6
  29. package/app/apps/github/src/code/saved.ts +5 -3
  30. package/app/apps/github/src/code/trees.ts +11 -9
  31. package/app/apps/github/src/components/markdown/markdown.css +6 -0
  32. package/app/apps/github/src/components/markdown/markdown.tsx +95 -10
  33. package/app/apps/github/src/components/owner-card.tsx +3 -1
  34. package/app/apps/github/src/components/repos/your-repos.tsx +3 -1
  35. package/app/apps/github/src/components/shell/owner-repos.tsx +7 -12
  36. package/app/apps/github/src/components/shell/repo-switcher.tsx +10 -16
  37. package/app/apps/github/src/components/signin/device-card.tsx +9 -2
  38. package/app/apps/github/src/components/user-avatar.tsx +2 -1
  39. package/app/apps/github/src/context/context.ts +13 -0
  40. package/app/apps/github/src/diffs/blobs.ts +37 -14
  41. package/app/apps/github/src/diffs/diff-job.ts +53 -0
  42. package/app/apps/github/src/diffs/diff-worker.ts +6 -0
  43. package/app/apps/github/src/diffs/diffing.ts +136 -0
  44. package/app/apps/github/src/diffs/files.ts +4 -3
  45. package/app/apps/github/src/diffs/hunks.tsx +101 -53
  46. package/app/apps/github/src/diffs/patch.ts +20 -11
  47. package/app/apps/github/src/history/commit-diff.ts +10 -5
  48. package/app/apps/github/src/history/commit-list.tsx +3 -1
  49. package/app/apps/github/src/history/commit-page.tsx +4 -2
  50. package/app/apps/github/src/history/history.ts +12 -10
  51. package/app/apps/github/src/hooks/allowed.ts +9 -9
  52. package/app/apps/github/src/hooks/avatars.ts +3 -3
  53. package/app/apps/github/src/hooks/open-counts.ts +5 -4
  54. package/app/apps/github/src/hooks/profiles.ts +26 -12
  55. package/app/apps/github/src/hooks/repos.ts +78 -25
  56. package/app/apps/github/src/inbox/count.ts +30 -29
  57. package/app/apps/github/src/inbox/inbox-item.tsx +3 -1
  58. package/app/apps/github/src/inbox/inbox-page.tsx +5 -2
  59. package/app/apps/github/src/inbox/marks.ts +26 -15
  60. package/app/apps/github/src/inbox/release-tags.ts +7 -6
  61. package/app/apps/github/src/inbox/subjects.ts +5 -4
  62. package/app/apps/github/src/inbox/subscription-controls.tsx +14 -5
  63. package/app/apps/github/src/inbox/subscriptions.ts +95 -35
  64. package/app/apps/github/src/inbox/threads.ts +6 -6
  65. package/app/apps/github/src/issues/changes.ts +40 -16
  66. package/app/apps/github/src/issues/counts.ts +8 -5
  67. package/app/apps/github/src/issues/issue-list.tsx +20 -6
  68. package/app/apps/github/src/issues/issue-page.tsx +30 -14
  69. package/app/apps/github/src/issues/issues.ts +195 -46
  70. package/app/apps/github/src/issues/label-dialog.tsx +8 -11
  71. package/app/apps/github/src/issues/labels-page.tsx +35 -3
  72. package/app/apps/github/src/issues/milestone-dialog.tsx +197 -0
  73. package/app/apps/github/src/issues/milestones-page.tsx +269 -0
  74. package/app/apps/github/src/issues/new-issue.tsx +3 -1
  75. package/app/apps/github/src/issues/sidebar.tsx +8 -6
  76. package/app/apps/github/src/markdown/README.md +22 -17
  77. package/app/apps/github/src/markdown/context.ts +83 -10
  78. package/app/apps/github/src/markdown/images.ts +3 -2
  79. package/app/apps/github/src/markdown/lookup.ts +9 -8
  80. package/app/apps/github/src/markdown/page-budget.ts +50 -0
  81. package/app/apps/github/src/markdown/patches.ts +74 -32
  82. package/app/apps/github/src/markdown/query.ts +7 -2
  83. package/app/apps/github/src/markdown/remote.ts +106 -0
  84. package/app/apps/github/src/markdown/render.ts +101 -24
  85. package/app/apps/github/src/markdown/texts.ts +43 -0
  86. package/app/apps/github/src/markdown/words-module.d.ts +5 -0
  87. package/app/apps/github/src/markdown/words-plugin.ts +135 -0
  88. package/app/apps/github/src/names/repos.ts +1 -1
  89. package/app/apps/github/src/palette/palette.tsx +7 -4
  90. package/app/apps/github/src/palette/rows.tsx +54 -33
  91. package/app/apps/github/src/palette/server.ts +5 -5
  92. package/app/apps/github/src/palette/targets.ts +1 -0
  93. package/app/apps/github/src/policy.ts +131 -61
  94. package/app/apps/github/src/private-repos.ts +2 -2
  95. package/app/apps/github/src/pulls/compare-page.tsx +6 -3
  96. package/app/apps/github/src/pulls/files-tab.tsx +480 -214
  97. package/app/apps/github/src/pulls/held-summary.ts +178 -0
  98. package/app/apps/github/src/pulls/live.ts +6 -4
  99. package/app/apps/github/src/pulls/merge-box.tsx +17 -10
  100. package/app/apps/github/src/pulls/pull-list.tsx +6 -3
  101. package/app/apps/github/src/pulls/pull-page.tsx +19 -10
  102. package/app/apps/github/src/pulls/pull.ts +68 -40
  103. package/app/apps/github/src/pulls/pulls.ts +39 -22
  104. package/app/apps/github/src/pulls/review-drafts.ts +131 -0
  105. package/app/apps/github/src/pulls/review.ts +374 -99
  106. package/app/apps/github/src/pulls/threads.tsx +152 -0
  107. package/app/apps/github/src/queue/queue-page.tsx +15 -8
  108. package/app/apps/github/src/queue/queue.ts +35 -20
  109. package/app/apps/github/src/releases/latest-release.tsx +3 -1
  110. package/app/apps/github/src/releases/overview.tsx +4 -2
  111. package/app/apps/github/src/releases/release-form.tsx +8 -5
  112. package/app/apps/github/src/releases/release-list.tsx +8 -5
  113. package/app/apps/github/src/releases/release-view.tsx +1 -0
  114. package/app/apps/github/src/releases/releases.ts +33 -23
  115. package/app/apps/github/src/releases/tag-list.tsx +3 -1
  116. package/app/apps/github/src/router.tsx +5 -2
  117. package/app/apps/github/src/routes/$owner/$repo/_code/blob/$.tsx +7 -1
  118. package/app/apps/github/src/routes/$owner/$repo/_code/tree/$.tsx +6 -1
  119. package/app/apps/github/src/routes/$owner/$repo/_releases/releases/index.tsx +2 -1
  120. package/app/apps/github/src/routes/$owner/$repo/_releases/tags.tsx +1 -1
  121. package/app/apps/github/src/routes/$owner/$repo/branches.tsx +5 -1
  122. package/app/apps/github/src/routes/$owner/$repo/commit/$sha.tsx +1 -1
  123. package/app/apps/github/src/routes/$owner/$repo/commits/$.tsx +6 -1
  124. package/app/apps/github/src/routes/$owner/$repo/index.tsx +1 -1
  125. package/app/apps/github/src/routes/$owner/$repo/issues/$number.tsx +4 -2
  126. package/app/apps/github/src/routes/$owner/$repo/issues/index.tsx +2 -2
  127. package/app/apps/github/src/routes/$owner/$repo/issues/new.tsx +5 -2
  128. package/app/apps/github/src/routes/$owner/$repo/labels.tsx +2 -1
  129. package/app/apps/github/src/routes/$owner/$repo/milestones.tsx +36 -0
  130. package/app/apps/github/src/routes/$owner/$repo/pull/$number/route.tsx +4 -2
  131. package/app/apps/github/src/routes/$owner/$repo/pulls/index.tsx +2 -2
  132. package/app/apps/github/src/routes/$owner/$repo/queue.tsx +2 -1
  133. package/app/apps/github/src/routes/$owner/$repo/releases/edit/$.tsx +5 -2
  134. package/app/apps/github/src/routes/$owner/$repo/releases/new.tsx +2 -1
  135. package/app/apps/github/src/routes/$owner/$repo/releases/tag/$.tsx +4 -2
  136. package/app/apps/github/src/routes/$owner/$repo/route.tsx +9 -5
  137. package/app/apps/github/src/routes/$owner/$repo/settings/hooks/index.tsx +3 -1
  138. package/app/apps/github/src/routes/$owner/$repo/settings/index.tsx +3 -1
  139. package/app/apps/github/src/routes/-nav.tsx +10 -2
  140. package/app/apps/github/src/routes/-root-testing.ts +29 -6
  141. package/app/apps/github/src/routes/__root.tsx +9 -4
  142. package/app/apps/github/src/routes/index.tsx +3 -1
  143. package/app/apps/github/src/routes/orgs/$owner/route.tsx +4 -1
  144. package/app/apps/github/src/routes/orgs/$owner/settings.tsx +4 -1
  145. package/app/apps/github/src/seed/acme.ts +1 -1
  146. package/app/apps/github/src/seed/seed.ts +199 -110
  147. package/app/apps/github/src/server.ts +24 -15
  148. package/app/apps/github/src/settings/account-avatar.tsx +4 -1
  149. package/app/apps/github/src/settings/general-settings.tsx +3 -1
  150. package/app/apps/github/src/settings/general.ts +4 -4
  151. package/app/apps/github/src/settings/hook-form.tsx +3 -1
  152. package/app/apps/github/src/settings/hook-list.tsx +5 -2
  153. package/app/apps/github/src/settings/hooks.ts +7 -7
  154. package/app/apps/github/src/settings/org-settings.tsx +3 -1
  155. package/app/apps/github/src/settings/orgs.ts +21 -11
  156. package/app/apps/github/src/settings/settings-layout.tsx +3 -1
  157. package/app/apps/github/src/signin/approval.ts +4 -3
  158. package/app/apps/github/src/signin/auth.ts +9 -2
  159. package/app/apps/github/src/signin/device-code.ts +8 -3
  160. package/app/apps/github/src/signin/device-prompt.ts +28 -3
  161. package/app/apps/github/src/signin/revoke.ts +36 -0
  162. package/app/apps/github/tsconfig.json +4 -1
  163. package/app/apps/github/vite.config.ts +8 -0
  164. package/app/pnpm-workspace.yaml +9 -5
  165. package/app/tsconfig.base.json +1 -0
  166. package/dist/cli/child.mjs +1 -1
  167. package/dist/cli/credentials.mjs +4 -4
  168. package/dist/cli/documents.mjs +32 -22
  169. package/dist/cli/events.mjs +1 -1
  170. package/dist/cli/failure.mjs +20 -7
  171. package/dist/cli/folders.mjs +2 -2
  172. package/dist/cli/git-remote-ref0.mjs +47 -22
  173. package/dist/cli/git.mjs +1 -1
  174. package/dist/cli/helpers.mjs +2 -2
  175. package/dist/cli/hosts.mjs +3 -3
  176. package/dist/cli/output.mjs +2 -2
  177. package/dist/cli/prompt.mjs +1 -1
  178. package/dist/cli/queue.mjs +7 -7
  179. package/dist/cli/ref0-git.mjs +2 -2
  180. package/dist/cli/repos.mjs +35 -18
  181. package/dist/cli/resources.mjs +5 -5
  182. package/dist/cli/retry-after.mjs +8 -0
  183. package/dist/cli/setup.mjs +172 -66
  184. package/dist/cli/sign-in.mjs +65 -23
  185. package/dist/cli/sign-ins.mjs +4 -4
  186. package/dist/cli/sqlite.mjs +2 -2
  187. package/dist/cli/tokens.mjs +3 -3
  188. package/dist/cli/vendor.mjs +1 -1
  189. package/dist/init/app.mjs +18 -20
  190. package/dist/init/choices.mjs +1 -1
  191. package/dist/init/cloudflare.mjs +15 -19
  192. package/dist/init/create.mjs +3 -2
  193. package/dist/init/detect.mjs +4 -4
  194. package/dist/init/files.mjs +120 -13
  195. package/dist/init/frameworks.mjs +16 -0
  196. package/dist/init/git-module.mjs +22 -7
  197. package/dist/init/jsonc.mjs +9 -7
  198. package/dist/init/metadata.mjs +9 -3
  199. package/dist/init/mounts.mjs +13 -10
  200. package/dist/init/next.mjs +2 -2
  201. package/dist/init/node-app.mjs +3 -3
  202. package/dist/init/node.mjs +42 -45
  203. package/dist/init/nuxt.mjs +153 -27
  204. package/dist/init/stores.mjs +14 -9
  205. package/dist/init/sveltekit.mjs +4 -2
  206. package/dist/init/template.mjs +9 -6
  207. package/dist/init/templates.mjs +63 -47
  208. package/dist/init/vercel.mjs +37 -37
  209. package/dist/init/versions.mjs +3 -3
  210. package/package.json +6 -5
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Which hosts the image proxy may fetch from (Q860): a public address, or a name that isn't one
3
+ * the host's own network answers. Every other address, private, loopback, link-local, shared,
4
+ * multicast, reserved or for documentation, IPv4 or IPv6, is refused, as is a name a resolver
5
+ * answers locally.
6
+ */
7
+
8
+ /** An IPv4 range, as its first address's 32 bits and its prefix's length. */
9
+ type Range4 = readonly [first: number, bits: number];
10
+
11
+ const v4 = (a: number, b: number, c: number, d: number) =>
12
+ ((a << 24) | (b << 16) | (c << 8) | d) >>> 0;
13
+
14
+ /** IANA's special-purpose IPv4 ranges, none of them a public host's: RFC 6890 and its updates. */
15
+ const refused4: readonly Range4[] = [
16
+ [v4(0, 0, 0, 0), 8],
17
+ [v4(10, 0, 0, 0), 8],
18
+ [v4(100, 64, 0, 0), 10],
19
+ [v4(127, 0, 0, 0), 8],
20
+ [v4(169, 254, 0, 0), 16],
21
+ [v4(172, 16, 0, 0), 12],
22
+ [v4(192, 0, 0, 0), 24],
23
+ [v4(192, 0, 2, 0), 24],
24
+ [v4(192, 88, 99, 0), 24],
25
+ [v4(192, 168, 0, 0), 16],
26
+ [v4(198, 18, 0, 0), 15],
27
+ [v4(198, 51, 100, 0), 24],
28
+ [v4(203, 0, 113, 0), 24],
29
+ [v4(224, 0, 0, 0), 4],
30
+ [v4(240, 0, 0, 0), 4],
31
+ ];
32
+
33
+ const inRange4 = (address: number, [first, bits]: Range4) =>
34
+ bits === 0 || address >>> (32 - bits) === first >>> (32 - bits);
35
+
36
+ /** Four decimal octets, as WHATWG `URL` writes every IPv4 host, or `undefined`. */
37
+ const parsed4 = (text: string) => {
38
+ const parts = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(text)?.slice(1).map(Number);
39
+ if (parts === undefined || parts.some((part) => part > 255)) return undefined;
40
+ const [a = 0, b = 0, c = 0, d = 0] = parts;
41
+
42
+ return v4(a, b, c, d);
43
+ };
44
+
45
+ /**
46
+ * The eight 16-bit groups of an IPv6 address, or `undefined`. A last 32 bits written as IPv4 is
47
+ * checked and counted as two groups, left zero: `refused6` reads only the first 32 bits.
48
+ */
49
+ const parsed6 = (text: string): readonly number[] | undefined => {
50
+ const tail = /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(text)?.[1];
51
+ const four = tail === undefined ? undefined : parsed4(tail);
52
+ if (tail !== undefined && four === undefined) return undefined;
53
+
54
+ // The IPv4 tail holds two groups' place.
55
+ const head = tail === undefined ? text : `${text.slice(0, -tail.length)}0:0`;
56
+ const halves = head.split('::');
57
+ if (halves.length > 2) return undefined;
58
+
59
+ const groups = halves.map((half) => (half === '' ? [] : half.split(':')));
60
+ const [left = [], right = []] = groups;
61
+ const missing = 8 - left.length - right.length;
62
+ if (halves.length === 1 ? missing !== 0 : missing < 1) return undefined;
63
+
64
+ const all = [...left, ...Array<string>(halves.length === 1 ? 0 : missing).fill('0'), ...right];
65
+ const words = all.map((group) =>
66
+ /^[\da-f]{1,4}$/i.test(group) ? Number.parseInt(group, 16) : NaN,
67
+ );
68
+ if (words.some(Number.isNaN)) return undefined;
69
+
70
+ return words;
71
+ };
72
+
73
+ /**
74
+ * Whether an IPv6 address is one the proxy refuses: anything outside `2000::/3`, the global
75
+ * unicast block, which holds the unspecified and loopback addresses, IPv4-mapped and translated
76
+ * ones, unique-local, link-local, site-local and multicast; and inside it the IETF's protocol
77
+ * block `2001::/23`, Teredo's among them, documentation's `2001:db8::/32`, and 6to4's `2002::/16`,
78
+ * which wraps an IPv4 address.
79
+ */
80
+ const refused6 = (words: readonly number[]) => {
81
+ const [first = 0, second = 0] = words;
82
+
83
+ return (
84
+ first >>> 13 !== 0b001 ||
85
+ (first === 0x2001 && second >>> 9 === 0) ||
86
+ (first === 0x2001 && second === 0x0db8) ||
87
+ first === 0x2002
88
+ );
89
+ };
90
+
91
+ /**
92
+ * Whether `address`, an IP address as a resolver or `URL` writes one, IPv6 with or without its
93
+ * brackets, is one the proxy refuses. Text that's no address at all is refused too.
94
+ */
95
+ export const refusedAddress = (address: string) => {
96
+ const bare = address.startsWith('[') && address.endsWith(']') ? address.slice(1, -1) : address;
97
+ const four = parsed4(bare);
98
+ if (four !== undefined) return refused4.some((range) => inRange4(four, range));
99
+
100
+ const six = bare.includes(':') ? parsed6(bare.replace(/%.*$/, '')) : undefined;
101
+
102
+ return six === undefined || refused6(six);
103
+ };
104
+
105
+ /** Names a resolver answers on the host's own network, never on the internet's (RFC 6761, 6762, 8375). */
106
+ const localNames = /(^|\.)(localhost|local|internal|intranet|lan|home\.arpa|localdomain)\.?$/i;
107
+
108
+ /**
109
+ * Whether the proxy refuses `hostname`, as WHATWG `URL` gives it, lowercased and its IPv4 forms
110
+ * written out: an address it refuses, a name with no dot, which a resolver looks up in its own
111
+ * search domains, or a local name. A public name passes here, and the fetch checks what it
112
+ * resolves to where the platform lets it.
113
+ */
114
+ export const refusedHost = (hostname: string) => {
115
+ if (hostname.startsWith('[') || parsed4(hostname) !== undefined) return refusedAddress(hostname);
116
+
117
+ const name = hostname.replace(/\.$/, '');
118
+
119
+ return name === '' || !name.includes('.') || localNames.test(name);
120
+ };
@@ -0,0 +1,125 @@
1
+ import { candidatesOf, remoteImageAt, srcsetOf } from '../markdown/remote.ts';
2
+ import type { TextAddress } from '../markdown/texts.ts';
3
+ import { previewsMost, type SignedImages, signImages, textsMost } from './sign-images.ts';
4
+
5
+ /** Where a drawn text came from: where it's kept, or the viewer's own unsaved text. */
6
+ export type TextSource = { readonly address: TextAddress } | { readonly preview: string };
7
+
8
+ interface Waiting {
9
+ readonly texts: TextAddress[];
10
+ readonly previews: string[];
11
+ readonly answered: ((answer: SignedImages | undefined) => void)[];
12
+ }
13
+
14
+ let waiting: Waiting | undefined;
15
+
16
+ const chunks = <A>(all: readonly A[], size: number): A[][] =>
17
+ Array.from({ length: Math.ceil(all.length / size) }, (_, at) =>
18
+ all.slice(at * size, at * size + size),
19
+ );
20
+
21
+ /** The texts and previews asked for since the last call, in one call, or a few past its caps. */
22
+ const send = async ({ texts, previews }: Waiting): Promise<SignedImages | undefined> => {
23
+ const unique = [...new Map(texts.map((text) => [JSON.stringify(text), text])).values()];
24
+ const textChunks = chunks(unique, textsMost);
25
+ const previewChunks = chunks([...new Set(previews)], previewsMost);
26
+ const calls = Array.from({ length: Math.max(textChunks.length, previewChunks.length) }, (_, at) =>
27
+ signImages({ data: { texts: textChunks[at] ?? [], previews: previewChunks[at] ?? [] } }),
28
+ );
29
+
30
+ try {
31
+ const answers = await Promise.all(calls);
32
+
33
+ return {
34
+ off: answers.some((answer) => answer.off),
35
+ images: Object.fromEntries(answers.flatMap((answer) => Object.entries(answer.images))),
36
+ unsigned: answers.flatMap((answer) => answer.unsigned),
37
+ };
38
+ } catch {
39
+ return undefined;
40
+ }
41
+ };
42
+
43
+ /**
44
+ * The proxy's paths for `source`'s remote images, asked with every other text the page draws in
45
+ * the same turn, in one call: `undefined` when the call fails.
46
+ */
47
+ export const signedImages = (source: TextSource): Promise<SignedImages | undefined> =>
48
+ new Promise((answered) => {
49
+ if (waiting === undefined) {
50
+ const batch: Waiting = { texts: [], previews: [], answered: [] };
51
+ waiting = batch;
52
+ setTimeout(() => {
53
+ waiting = undefined;
54
+ void send(batch).then((answer) => {
55
+ for (const each of batch.answered) each(answer);
56
+ });
57
+ }, 0);
58
+ }
59
+
60
+ if ('address' in source) waiting.texts.push(source.address);
61
+ else waiting.previews.push(source.preview);
62
+
63
+ waiting.answered.push(answered);
64
+ });
65
+
66
+ /**
67
+ * An image the proxy won't load, drawn as its alt text, as GitHub draws one: linked to its source,
68
+ * unless it's already in a link, which keeps its own.
69
+ */
70
+ const refused = (image: HTMLImageElement, url: string) => {
71
+ const text = image.alt === '' ? url : image.alt;
72
+
73
+ if (image.closest('a') !== null) {
74
+ image.replaceWith(text);
75
+
76
+ return;
77
+ }
78
+
79
+ const link = document.createElement('a');
80
+ link.href = url;
81
+ link.rel = 'nofollow noopener noreferrer';
82
+ link.textContent = text;
83
+ image.replaceWith(link);
84
+ };
85
+
86
+ /** Whether `image` sits in a `<picture>` that still has a source to draw, as a refused one doesn't. */
87
+ const sourced = (image: HTMLImageElement) =>
88
+ image.parentElement?.tagName === 'PICTURE' &&
89
+ image.parentElement.querySelector('source[srcset]') !== null;
90
+
91
+ /**
92
+ * Each of `container`'s remote images drawn by `answer`: through the proxy where it's signed, from
93
+ * its own origin with the proxy off, and as its alt text where it's refused, as it is when the
94
+ * proxy then refuses it. A `srcset` keeps the candidates the proxy signed, and the rest as written,
95
+ * and a `<picture>`'s refused `<img>` stays while one of its sources is left to draw.
96
+ */
97
+ export const drawRemoteImages = (container: Element, answer: SignedImages | undefined) => {
98
+ for (const source of container.querySelectorAll<HTMLSourceElement>(
99
+ 'source[data-remote-srcset]',
100
+ )) {
101
+ const written = source.dataset['remoteSrcset'] ?? '';
102
+ const kept = candidatesOf(written).flatMap((candidate) => {
103
+ const remote = remoteImageAt(candidate.url);
104
+ if (remote === undefined || answer?.off === true) return [candidate];
105
+
106
+ const path = answer?.images[remote];
107
+
108
+ return path === undefined ? [] : [{ ...candidate, url: path }];
109
+ });
110
+ if (kept.length === 0) source.remove();
111
+ else source.srcset = srcsetOf(kept);
112
+ }
113
+
114
+ for (const image of container.querySelectorAll<HTMLImageElement>('img[data-remote]')) {
115
+ const url = image.dataset['remote'] ?? '';
116
+ const path = answer?.images[url];
117
+ if (answer?.off === true) image.src = url;
118
+ else if (path === undefined) {
119
+ if (!sourced(image)) refused(image, url);
120
+ } else {
121
+ image.addEventListener('error', () => refused(image, url), { once: true });
122
+ image.src = path;
123
+ }
124
+ }
125
+ };
@@ -0,0 +1,201 @@
1
+ import { bytesUpTo } from '../clients/icon-bytes.ts';
2
+ import { refusedHost } from './addresses.ts';
3
+
4
+ /**
5
+ * How the proxy fetches a URL on its platform: one request, never following a redirect, sending
6
+ * only `headers`, and stopping when `signal` does, the body's read too. On Workers it's `fetch`
7
+ * with `redirect: 'manual'`; on Node, `node.ts`'s, which refuses an address as it connects.
8
+ */
9
+ export type Fetcher = (
10
+ url: URL,
11
+ init: { readonly headers: Headers; readonly signal: AbortSignal },
12
+ ) => Promise<Response>;
13
+
14
+ /** The proxy's `Fetcher` on Workers: `fetch`, from Cloudflare's edge, which reaches no host's network. */
15
+ export const workersFetch: Fetcher = (url, { headers, signal }) =>
16
+ fetch(url, { headers, signal, redirect: 'manual' });
17
+
18
+ /** The most an image's body may hold, GitHub's camo's cap: past it, the image is refused. */
19
+ export const imageBytesMost = 5 * 1024 * 1024;
20
+
21
+ /** How long one image may take, every redirect and its body included. */
22
+ export const fetchMs = 10_000;
23
+
24
+ /** How many redirects an image may take, each one checked as the first URL was. */
25
+ export const hopsMost = 4;
26
+
27
+ /** The longest a served image is cached, by the browser and the Worker's cache, in seconds. */
28
+ export const servedSeconds = 86_400;
29
+
30
+ /** How long a refusal is cached, so a broken image isn't fetched again on every view. */
31
+ export const refusedSeconds = 300;
32
+
33
+ /**
34
+ * What an answer from the proxy may do once it's opened as a page of its own: nothing. An SVG's
35
+ * script doesn't run, the page has an origin of its own, and no other site's page frames it.
36
+ */
37
+ const sandboxed =
38
+ "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox; frame-ancestors 'none'";
39
+
40
+ /**
41
+ * Headers on every answer: no sniffing, the sandbox, and `same-origin` for CORP, so another site's
42
+ * page can't draw through the proxy, as a browser refuses it the image.
43
+ */
44
+ const answerHeaders = (more: Readonly<Record<string, string>>) =>
45
+ new Headers({
46
+ 'x-content-type-options': 'nosniff',
47
+ 'content-security-policy': sandboxed,
48
+ 'cross-origin-resource-policy': 'same-origin',
49
+ ...more,
50
+ });
51
+
52
+ /** The proxy's refusal: a bare 404, which says nothing of why or of what's behind it. */
53
+ export const refusal = () =>
54
+ new Response(null, {
55
+ status: 404,
56
+ headers: answerHeaders({ 'cache-control': `public, max-age=${refusedSeconds}` }),
57
+ });
58
+
59
+ /**
60
+ * Whether the proxy may ask `url`: `http:` or `https:`, with no user or password, on its scheme's
61
+ * own port, not the app's origin, and on a host `refusedHost` passes.
62
+ */
63
+ export const fetchable = (url: URL, appOrigin: string) =>
64
+ (url.protocol === 'https:' || url.protocol === 'http:') &&
65
+ url.username === '' &&
66
+ url.password === '' &&
67
+ url.port === '' &&
68
+ url.origin !== new URL(appOrigin).origin &&
69
+ !refusedHost(url.hostname);
70
+
71
+ /** The image types the proxy serves, by the names an origin may label them with. */
72
+ const labels = new Map([
73
+ ['image/png', 'image/png'],
74
+ ['image/apng', 'image/png'],
75
+ ['image/jpeg', 'image/jpeg'],
76
+ ['image/jpg', 'image/jpeg'],
77
+ ['image/pjpeg', 'image/jpeg'],
78
+ ['image/gif', 'image/gif'],
79
+ ['image/webp', 'image/webp'],
80
+ ['image/avif', 'image/avif'],
81
+ ['image/bmp', 'image/bmp'],
82
+ ['image/x-ms-bmp', 'image/bmp'],
83
+ ['image/x-icon', 'image/x-icon'],
84
+ ['image/vnd.microsoft.icon', 'image/x-icon'],
85
+ ['image/svg+xml', 'image/svg+xml'],
86
+ ]);
87
+
88
+ const starts = (bytes: Uint8Array, at: number, ...expected: readonly number[]) =>
89
+ expected.every((byte, index) => bytes[at + index] === byte);
90
+
91
+ const ascii = (text: string) => Array.from(text, (char) => char.charCodeAt(0));
92
+
93
+ /** An SVG's start: an XML declaration, comments and a doctype, then its `<svg` element. */
94
+ const svgStart = /^\s*(<\?xml[^>]*>\s*)?((<!--[\s\S]*?-->|<!doctype[^>]*>)\s*)*<svg[\s>/]/i;
95
+
96
+ /** The type an image's first bytes say it is, or `undefined` for bytes of none the proxy serves. */
97
+ export const sniffedType = (bytes: Uint8Array): string | undefined => {
98
+ if (starts(bytes, 0, 0x89, ...ascii('PNG\r\n'), 0x1a, 0x0a)) return 'image/png';
99
+
100
+ if (starts(bytes, 0, 0xff, 0xd8, 0xff)) return 'image/jpeg';
101
+
102
+ if (starts(bytes, 0, ...ascii('GIF87a')) || starts(bytes, 0, ...ascii('GIF89a')))
103
+ return 'image/gif';
104
+
105
+ if (starts(bytes, 0, ...ascii('RIFF')) && starts(bytes, 8, ...ascii('WEBP'))) return 'image/webp';
106
+
107
+ if (starts(bytes, 4, ...ascii('ftypavif')) || starts(bytes, 4, ...ascii('ftypavis'))) {
108
+ return 'image/avif';
109
+ }
110
+
111
+ if (starts(bytes, 0, ...ascii('BM'))) return 'image/bmp';
112
+
113
+ if (starts(bytes, 0, 0, 0, 1, 0)) return 'image/x-icon';
114
+
115
+ const head = new TextDecoder('utf-8', { ignoreBOM: false }).decode(bytes.subarray(0, 4096));
116
+
117
+ return svgStart.test(head) ? 'image/svg+xml' : undefined;
118
+ };
119
+
120
+ /** The served image's `cache-control`: `no-store` when its origin's says so, else the shorter age. */
121
+ const cacheOf = (said: string | null) => {
122
+ const directives = (said ?? '').toLowerCase();
123
+ if (/(^|,)\s*(no-store|private|no-cache)\s*(,|$)/.test(directives)) return 'no-store';
124
+
125
+ const age = /(^|,)\s*max-age\s*=\s*(\d+)/.exec(directives)?.[2];
126
+ const seconds = age === undefined ? servedSeconds : Math.min(Number(age), servedSeconds);
127
+
128
+ return `public, max-age=${seconds}`;
129
+ };
130
+
131
+ /** A validator header worth passing on: printable and short, or left out. */
132
+ const validator = (value: string | null) =>
133
+ value !== null && value.length <= 256 && /^[\x20-\x7e]*$/.test(value) ? value : undefined;
134
+
135
+ /** The image an origin's final answer is, served, or the refusal. */
136
+ const served = async (answer: Response) => {
137
+ const declared = Number(answer.headers.get('content-length') ?? '0');
138
+ const label =
139
+ (answer.headers.get('content-type') ?? '').split(';')[0]?.trim().toLowerCase() ?? '';
140
+ const type = labels.get(label);
141
+
142
+ if (answer.status !== 200 || type === undefined || declared > imageBytesMost) {
143
+ await answer.body?.cancel();
144
+
145
+ return refusal();
146
+ }
147
+
148
+ const bytes = await bytesUpTo(answer.body, imageBytesMost);
149
+ if (bytes === undefined || sniffedType(bytes) !== type) return refusal();
150
+
151
+ const headers = answerHeaders({
152
+ 'content-type': type,
153
+ 'content-length': String(bytes.length),
154
+ 'cache-control': cacheOf(answer.headers.get('cache-control')),
155
+ });
156
+ const etag = validator(answer.headers.get('etag'));
157
+ if (etag !== undefined) headers.set('etag', etag);
158
+ const modified = validator(answer.headers.get('last-modified'));
159
+ if (modified !== undefined) headers.set('last-modified', modified);
160
+
161
+ // Copied onto an ArrayBuffer of its own, which a response's body takes.
162
+ return new Response(new Uint8Array(bytes), { status: 200, headers });
163
+ };
164
+
165
+ const redirects = new Set([301, 302, 303, 307, 308]);
166
+
167
+ /**
168
+ * `url`'s image, fetched with no word of who asked, or the refusal: each URL on its way checked
169
+ * with `fetchable` before it's asked, redirects followed by hand up to `hopsMost`, and all of it
170
+ * within `fetchMs`.
171
+ */
172
+ export const proxiedImage = async (
173
+ url: string,
174
+ { fetch, appOrigin }: { readonly fetch: Fetcher; readonly appOrigin: string },
175
+ ): Promise<Response> => {
176
+ const stop = new AbortController();
177
+ const timer = setTimeout(() => stop.abort(), fetchMs);
178
+ const { signal } = stop;
179
+ const headers = () => new Headers({ accept: 'image/*', 'user-agent': 'ref0-camo' });
180
+
181
+ try {
182
+ let at = URL.parse(url);
183
+
184
+ for (let hop = 0; at !== null && hop <= hopsMost; hop += 1) {
185
+ if (!fetchable(at, appOrigin)) return refusal();
186
+
187
+ const answer = await fetch(at, { headers: headers(), signal });
188
+ if (!redirects.has(answer.status)) return await served(answer);
189
+
190
+ const location = answer.headers.get('location');
191
+ await answer.body?.cancel();
192
+ at = location === null ? null : URL.parse(location, at);
193
+ }
194
+
195
+ return refusal();
196
+ } catch {
197
+ return refusal();
198
+ } finally {
199
+ clearTimeout(timer);
200
+ }
201
+ };
@@ -0,0 +1,23 @@
1
+ import { type LookupAddress, lookup } from 'node:dns';
2
+ import type { LookupFunction } from 'node:net';
3
+
4
+ import { refusedAddress } from './addresses.ts';
5
+
6
+ /**
7
+ * Node's lookup, refusing a name any of whose addresses the proxy refuses: the socket connects to
8
+ * what this answers, so a name that resolves elsewhere between a check and a connect can't reach
9
+ * the host's own network, as it could if the name were checked first and fetched after.
10
+ */
11
+ export const checkedLookup: LookupFunction = (hostname, options, done) => {
12
+ lookup(hostname, { ...options, all: true }, (error, found: LookupAddress[]) => {
13
+ if (error !== null) return done(error, '', 0);
14
+
15
+ const refused = found.length === 0 || found.some(({ address }) => refusedAddress(address));
16
+ if (refused) return done(new Error(`${hostname} resolves to a refused address`), '', 0);
17
+
18
+ const [first] = found;
19
+ if (options.all === true) return done(null, found);
20
+
21
+ return done(null, first?.address ?? '', first?.family ?? 4);
22
+ });
23
+ };
@@ -0,0 +1,50 @@
1
+ import { request as httpRequest } from 'node:http';
2
+ import { request as httpsRequest } from 'node:https';
3
+ import { Readable } from 'node:stream';
4
+
5
+ import type { Fetcher } from './fetch.ts';
6
+ import { checkedLookup } from './lookup.ts';
7
+
8
+ /** Statuses a `Response` holds no body with. */
9
+ const empty = new Set([101, 204, 205, 304]);
10
+
11
+ /**
12
+ * The proxy's `Fetcher` on Node: one `GET` through `node:http` or `node:https`, connecting only to
13
+ * an address `checkedLookup` passes, never following a redirect, and stopped by `signal`.
14
+ */
15
+ export const nodeFetch: Fetcher = (url, { headers, signal }) =>
16
+ new Promise((resolve, reject) => {
17
+ const send = url.protocol === 'https:' ? httpsRequest : httpRequest;
18
+ const asked = send(
19
+ url,
20
+ { method: 'GET', headers: Object.fromEntries(headers), lookup: checkedLookup, signal },
21
+ (answer) => {
22
+ const status = answer.statusCode ?? 0;
23
+
24
+ if (status < 200 || status > 599) {
25
+ answer.destroy();
26
+
27
+ return reject(new Error(`${status} is no answer`));
28
+ }
29
+
30
+ try {
31
+ const said = new Headers();
32
+
33
+ for (let at = 0; at + 1 < answer.rawHeaders.length; at += 2) {
34
+ said.append(answer.rawHeaders[at] ?? '', answer.rawHeaders[at + 1] ?? '');
35
+ }
36
+
37
+ const body = empty.has(status) ? null : Readable.toWeb(answer);
38
+ // SAFETY: `Readable.toWeb` answers `node:stream/web`'s `ReadableStream`, the stream a
39
+ // `Response` takes; only the two declarations of its type differ.
40
+ resolve(new Response(body as BodyInit | null, { status, headers: said }));
41
+ } catch (cause) {
42
+ // A header no `Headers` takes: the answer is refused, as any other failed fetch.
43
+ answer.destroy();
44
+ reject(cause);
45
+ }
46
+ },
47
+ );
48
+ asked.on('error', reject);
49
+ asked.end();
50
+ });
@@ -0,0 +1,116 @@
1
+ import type { ImageSigner } from '../context/context.ts';
2
+ import { type Fetcher, fetchable, proxiedImage, refusal } from './fetch.ts';
3
+ import { camoKey, camoPrefix, openedUrl, signedPath, urlBytesMost } from './signing.ts';
4
+
5
+ /**
6
+ * Where served images are kept between requests: the Worker's `caches.default`, or none on Node.
7
+ * Both the DOM's `Cache` and workers-types' fit it.
8
+ */
9
+ export interface ImageCache {
10
+ readonly match: (request: Request) => Promise<Response | undefined>;
11
+ readonly put: (request: Request, response: Response) => Promise<void>;
12
+ }
13
+
14
+ /** What the host makes the proxy with, in `server.ts`. */
15
+ export interface ImageProxyOptions {
16
+ /** The host's `SESSION_SECRET`, which the proxy's key is HKDF'd from. */
17
+ readonly secret: string;
18
+ /** Where the app is served: the proxy never fetches from it. */
19
+ readonly appOrigin: string;
20
+ /** The host's `IMAGE_PROXY`: `off` turns the proxy off. */
21
+ readonly setting: string | undefined;
22
+ /** How the platform fetches one URL: see `Fetcher`. */
23
+ readonly fetch: Fetcher;
24
+ readonly cache?: ImageCache | undefined;
25
+ }
26
+
27
+ /** The pages' `img-src`: the app's own origin, its blob and data images, or any with the proxy off. */
28
+ const imgSrc = (off: boolean) => (off ? 'img-src * data: blob:' : "img-src 'self' data: blob:");
29
+
30
+ /** The image proxy, as `server.ts` wires it: its route, its signer, and the pages' CSP. */
31
+ export interface ImageProxy extends ImageSigner {
32
+ /** `/_camo/…`'s answer, or `undefined` for any other URL. */
33
+ readonly route: (request: Request) => Promise<Response | undefined>;
34
+ /** A page's answer, with the CSP that loads images only through the proxy. */
35
+ readonly page: (answer: Response) => Response;
36
+ /** `serve`, with the proxy's route before it and the pages' CSP on its answers. */
37
+ readonly around: (
38
+ serve: (request: Request) => Promise<Response>,
39
+ ) => (request: Request) => Promise<Response>;
40
+ }
41
+
42
+ const encoder = new TextEncoder();
43
+
44
+ /**
45
+ * The remote-image proxy (Q860), as GitHub's camo: a text's images load from the app's origin
46
+ * through `/_camo/{sig}/{hex url}`, so the image's host learns nothing of who reads the text.
47
+ */
48
+ export const imageProxy = (options: ImageProxyOptions): ImageProxy => {
49
+ const off = options.setting === 'off';
50
+ const key = camoKey(options.secret);
51
+ // A short secret refuses every route and sign, when each awaits the key, and nothing before.
52
+ key.catch(() => undefined);
53
+
54
+ const route = async (request: Request) => {
55
+ const url = new URL(request.url);
56
+ if (!url.pathname.startsWith(camoPrefix)) return undefined;
57
+
58
+ if (off || (request.method !== 'GET' && request.method !== 'HEAD')) return refusal();
59
+
60
+ const keyed = new Request(new URL(url.pathname, url.origin));
61
+ const cached = await options.cache?.match(keyed);
62
+ const answer =
63
+ cached ??
64
+ (await (async () => {
65
+ const opened = await openedUrl(await key, url.pathname);
66
+ const fetched =
67
+ opened === undefined
68
+ ? refusal()
69
+ : await proxiedImage(opened, { fetch: options.fetch, appOrigin: options.appOrigin });
70
+
71
+ if (fetched.headers.get('cache-control') !== 'no-store') {
72
+ await options.cache?.put(keyed, fetched.clone()).catch(() => undefined);
73
+ }
74
+
75
+ return fetched;
76
+ })());
77
+
78
+ return request.method === 'HEAD' ? new Response(null, answer) : answer;
79
+ };
80
+
81
+ const sign = async (urls: readonly string[]) => {
82
+ const signed = new Map<string, string>();
83
+ if (off) return signed;
84
+
85
+ for (const text of new Set(urls)) {
86
+ const url = URL.parse(text);
87
+ if (url === null || encoder.encode(text).length > urlBytesMost) continue;
88
+
89
+ if (fetchable(url, options.appOrigin)) signed.set(text, await signedPath(await key, text));
90
+ }
91
+
92
+ return signed;
93
+ };
94
+
95
+ const page = (answer: Response) => {
96
+ const type = answer.headers.get('content-type') ?? '';
97
+
98
+ if (!type.startsWith('text/html') || answer.headers.has('content-security-policy')) {
99
+ return answer;
100
+ }
101
+
102
+ const headers = new Headers(answer.headers);
103
+ headers.set('content-security-policy', imgSrc(off));
104
+
105
+ return new Response(answer.body, {
106
+ status: answer.status,
107
+ statusText: answer.statusText,
108
+ headers,
109
+ });
110
+ };
111
+
112
+ const around = (serve: (request: Request) => Promise<Response>) => async (request: Request) =>
113
+ (await route(request)) ?? page(await serve(request));
114
+
115
+ return { off, route, sign, page, around };
116
+ };