ref0-git 0.3.0 → 0.6.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 +165 -66
  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 +12 -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 +20 -21
  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,307 @@
1
+ import { createServerFn } from '@tanstack/react-start';
2
+ import { getRequest } from '@tanstack/react-start/server';
3
+ import * as Option from 'effect/Option';
4
+ import * as Schema from 'effect/Schema';
5
+
6
+ import { bytesUpTo } from '../clients/icon-bytes.ts';
7
+ import { type ProxyContext, proxied } from '../clients/proxy.ts';
8
+ import type { AppContext } from '../context/context.ts';
9
+ import { type MarkdownContext, nothingFound } from '../markdown/context.ts';
10
+ import { remoteImagesIn } from '../markdown/remote.ts';
11
+ import { renderMarkdown } from '../markdown/render.ts';
12
+ import { TextAddress } from '../markdown/texts.ts';
13
+
14
+ /** The most texts one page asks about at once, and the most previews. */
15
+ export const textsMost = 100;
16
+
17
+ export const previewsMost = 4;
18
+
19
+ /** The longest preview signed, GitHub's longest comment, and the most bytes of a file read. */
20
+ const previewLengthMost = 65_536;
21
+
22
+ const fileBytesMost = 1_048_576;
23
+
24
+ /**
25
+ * One call's budgets, under one rule: every unit of work, a byte read or a URL signed, is charged
26
+ * to its budget before it's done, and what goes unused comes back. A read reserves up to 1 MiB of
27
+ * what's left and returns what it didn't read, so the call reads no more than its budget in all,
28
+ * and a URL takes its place in `imagesMost` before it's signed.
29
+ *
30
+ * `askBytesMost` is the text one call reads and renders, its previews and texts together. Past it,
31
+ * a text is left unsigned, and its images draw as links to their sources. It bounds the call's
32
+ * CPU, and `readsAtOnce` its memory.
33
+ */
34
+ export const askBytesMost = 2 * 1_048_576;
35
+
36
+ /** The most distinct images one call signs: past it, a text's other images draw as links. */
37
+ export const imagesMost = 1000;
38
+
39
+ /** How many texts one call reads and renders at once, each keeping only its images' URLs. */
40
+ const readsAtOnce = 4;
41
+
42
+ /** A page's ask: the texts it draws, by where they're kept, and the viewer's unsaved ones. */
43
+ const ImageAsk = Schema.Struct({
44
+ texts: Schema.Array(TextAddress).check(Schema.isMaxLength(textsMost)),
45
+ previews: Schema.Array(Schema.String.check(Schema.isMaxLength(previewLengthMost))).check(
46
+ Schema.isMaxLength(previewsMost),
47
+ ),
48
+ });
49
+
50
+ export type ImageAsk = typeof ImageAsk.Type;
51
+
52
+ /**
53
+ * A text the signer left unsigned, and why, with the budget it met: past the call's
54
+ * `askBytesMost`, with the bytes of it read, none or a part, or holding more distinct images than
55
+ * were left of `imagesMost`, with how many it held, the first of which it signed.
56
+ */
57
+ export type UnsignedText =
58
+ | {
59
+ readonly address: TextAddress;
60
+ readonly unsigned: 'read-budget';
61
+ readonly most: number;
62
+ readonly read: number;
63
+ }
64
+ | {
65
+ readonly address: TextAddress;
66
+ readonly unsigned: 'image-budget';
67
+ readonly most: number;
68
+ readonly held: number;
69
+ };
70
+
71
+ /**
72
+ * The signer's answer: whether the proxy is off, each remote image's path on it, and the texts
73
+ * it left unsigned, so a caller tells a cut from a refusal. Both draw as links to their sources.
74
+ */
75
+ export interface SignedImages {
76
+ readonly off: boolean;
77
+ readonly images: Readonly<Record<string, string>>;
78
+ readonly unsigned: readonly UnsignedText[];
79
+ }
80
+
81
+ /** What signing asks of the request's context: the drop-in as the viewer, and the proxy. */
82
+ export type SigningContext = ProxyContext & Pick<AppContext, 'images'>;
83
+
84
+ const segment = encodeURIComponent;
85
+
86
+ /** `owner/name` as the two path segments a call names. */
87
+ const repoPath = (repo: string) => repo.split('/').map(segment).join('/');
88
+
89
+ /** The call that reads `address`'s text, and how its answer holds it. */
90
+ const readOf = (address: TextAddress) => {
91
+ const repo = `/repos/${repoPath(address.repo)}`;
92
+
93
+ switch (address.kind) {
94
+ case 'issue':
95
+ return { path: `${repo}/issues/${address.number}`, raw: false };
96
+ case 'issue-comment':
97
+ return { path: `${repo}/issues/comments/${address.id}`, raw: false };
98
+ case 'review':
99
+ return { path: `${repo}/pulls/${address.number}/reviews/${address.id}`, raw: false };
100
+ case 'review-comment':
101
+ return { path: `${repo}/pulls/comments/${address.id}`, raw: false };
102
+ case 'release':
103
+ return { path: `${repo}/releases/${address.id}`, raw: false };
104
+ case 'file': {
105
+ const file = address.path.split('/').map(segment).join('/');
106
+
107
+ return { path: `${repo}/contents/${file}?ref=${segment(address.ref)}`, raw: true };
108
+ }
109
+ }
110
+ };
111
+
112
+ /** The context `address`'s text renders in, as the page draws it. */
113
+ const contextOf = (address: TextAddress): MarkdownContext =>
114
+ address.kind === 'file'
115
+ ? {
116
+ kind: 'file',
117
+ repo: address.repo,
118
+ ref: address.ref,
119
+ dir: address.path.split('/').slice(0, -1).join('/'),
120
+ }
121
+ : { kind: 'comment', repo: address.repo };
122
+
123
+ /** One key a text, so an address asked twice is read once. */
124
+ const keyOf = (address: TextAddress) =>
125
+ JSON.stringify([
126
+ address.kind,
127
+ address.repo,
128
+ 'number' in address ? address.number : '',
129
+ 'id' in address ? address.id : '',
130
+ address.kind === 'file' ? [address.ref, address.path] : '',
131
+ ]);
132
+
133
+ const encoder = new TextEncoder();
134
+
135
+ /** A comment's, a review's, an issue's or a release's text, as the drop-in answers it. */
136
+ const bodyOf = Schema.decodeUnknownOption(Schema.Struct({ body: Schema.String }));
137
+
138
+ /** The most of a record's JSON read, its text and the fields around it. */
139
+ const recordBytesMost = 1_048_576;
140
+
141
+ /**
142
+ * `address`'s text and its bytes, read from the drop-in as the viewer up to `most` bytes of text:
143
+ * `past` with the bytes read when it holds more, or `undefined` when they can't read it, as a
144
+ * private repo's is to a visitor, or it holds none.
145
+ */
146
+ const textAt = async (
147
+ context: ProxyContext,
148
+ request: Request,
149
+ address: TextAddress,
150
+ most: number,
151
+ ): Promise<
152
+ { readonly text: string; readonly bytes: number } | { readonly past: number } | undefined
153
+ > => {
154
+ const { path, raw } = readOf(address);
155
+ const call = {
156
+ api: 'github',
157
+ method: 'GET',
158
+ path,
159
+ accept: raw ? 'application/vnd.github.raw' : 'application/json',
160
+ } as const;
161
+ const answer = await proxied(context, request, call);
162
+
163
+ if (answer.status !== 200) {
164
+ await answer.body?.cancel();
165
+
166
+ return undefined;
167
+ }
168
+
169
+ if (raw) {
170
+ const bytes = await bytesUpTo(answer.body, most);
171
+ if (bytes === undefined) return { past: most };
172
+
173
+ return { text: new TextDecoder().decode(bytes), bytes: bytes.length };
174
+ }
175
+
176
+ const record = await bytesUpTo(answer.body, recordBytesMost);
177
+ if (record === undefined) return { past: most };
178
+
179
+ const text = Option.getOrUndefined(bodyOf(JSON.parse(new TextDecoder().decode(record))))?.body;
180
+ if (text === undefined) return undefined;
181
+
182
+ const bytes = encoder.encode(text).length;
183
+
184
+ return bytes > most ? { past: most } : { text, bytes };
185
+ };
186
+
187
+ /** Whether the viewer is signed in and Git still takes their token, asked at `/user`. */
188
+ const liveSession = async (context: ProxyContext, request: Request) => {
189
+ if ((await context.session(request)) === undefined) return false;
190
+
191
+ const call = { api: 'github', method: 'GET', path: '/user', accept: 'application/json' } as const;
192
+ const answer = await proxied(context, request, call);
193
+ await answer.body?.cancel();
194
+
195
+ return answer.status === 200;
196
+ };
197
+
198
+ /**
199
+ * The paths on the proxy of the remote images in `ask`'s texts, each read as the viewer, and in
200
+ * its previews when the viewer is signed in: no other URL is signed, so the proxy fetches only
201
+ * what a text the viewer may read holds (Q860).
202
+ */
203
+ export const signedFor = async (
204
+ context: SigningContext,
205
+ request: Request,
206
+ ask: ImageAsk,
207
+ ): Promise<SignedImages> => {
208
+ const images = context.images;
209
+ if (images.off) return { off: true, images: {}, unsigned: [] };
210
+
211
+ const urls = new Set<string>();
212
+ const unsigned: UnsignedText[] = [];
213
+ // Each URL is charged to `imagesMost` before it's signed: past it, its text is named.
214
+ const rendered = (text: string, at: MarkdownContext, address?: TextAddress) => {
215
+ const found = remoteImagesIn(renderMarkdown(text, at, nothingFound));
216
+ const fresh = found.filter((url) => !urls.has(url));
217
+
218
+ for (const url of fresh.slice(0, imagesMost - urls.size)) urls.add(url);
219
+
220
+ if (fresh.some((url) => !urls.has(url)) && address !== undefined) {
221
+ unsigned.push({
222
+ address,
223
+ unsigned: 'image-budget',
224
+ most: imagesMost,
225
+ held: new Set(found).size,
226
+ });
227
+ }
228
+ };
229
+
230
+ // Bytes are reserved before each read and the unread come back, so the 4 readers read no more
231
+ // than `left` in all; a reader that finds none left waits while another may yet return some.
232
+ let left = askBytesMost;
233
+ let reading = 0;
234
+ const settled: (() => void)[] = [];
235
+ const reserved = async () => {
236
+ while (left === 0 && reading > 0) await new Promise<void>((each) => settled.push(each));
237
+
238
+ const most = Math.min(fileBytesMost, left);
239
+ left -= most;
240
+
241
+ if (most > 0) reading += 1;
242
+
243
+ return most;
244
+ };
245
+
246
+ const settle = (unread: number) => {
247
+ left += unread;
248
+ reading -= 1;
249
+
250
+ for (const each of settled.splice(0)) each();
251
+ };
252
+
253
+ // A viewer's own previews come first, out of the same budget: at most 4 of 65,536 characters,
254
+ // and only while Git takes their token, as `proxied` ends a session it refuses.
255
+ const signedIn = ask.previews.length > 0 && (await liveSession(context, request));
256
+
257
+ for (const text of signedIn ? ask.previews : []) {
258
+ left -= Math.min(left, encoder.encode(text).length);
259
+ rendered(text, { kind: 'comment', repo: '' });
260
+ }
261
+
262
+ const waiting = [...new Map(ask.texts.map((address) => [keyOf(address), address])).values()];
263
+ const reader = async () => {
264
+ for (let address = waiting.shift(); address !== undefined; address = waiting.shift()) {
265
+ const most = await reserved();
266
+
267
+ if (most === 0) {
268
+ unsigned.push({ address, unsigned: 'read-budget', most: askBytesMost, read: 0 });
269
+ continue;
270
+ }
271
+
272
+ // A read that fails, as a stream that breaks, reads as one the viewer can't: charged nothing,
273
+ // as no caller chooses the drop-in's failures.
274
+ let read: Awaited<ReturnType<typeof textAt>> | 'failed';
275
+
276
+ try {
277
+ read = await textAt(context, request, address, most);
278
+ } catch {
279
+ read = 'failed';
280
+ }
281
+
282
+ const charged =
283
+ read === 'failed' || read === undefined ? 0 : 'past' in read ? read.past : read.bytes;
284
+ settle(most - charged);
285
+
286
+ if (read === 'failed' || read === undefined) continue;
287
+
288
+ // Past what was left, it's cut; past its own cap, it signs nothing, as a text too long to show.
289
+ if ('past' in read) {
290
+ if (most < fileBytesMost) {
291
+ unsigned.push({ address, unsigned: 'read-budget', most: askBytesMost, read: read.past });
292
+ }
293
+ } else rendered(read.text, contextOf(address), address);
294
+ }
295
+ };
296
+
297
+ await Promise.all(Array.from({ length: readsAtOnce }, reader));
298
+
299
+ const signed = await images.sign([...urls]);
300
+
301
+ return { off: false, images: Object.fromEntries(signed), unsigned };
302
+ };
303
+
304
+ /** The remote images of a page's texts, signed for the image proxy (Q860): one call a page. */
305
+ export const signImages = createServerFn({ method: 'POST' })
306
+ .validator(Schema.decodeUnknownSync(ImageAsk))
307
+ .handler(async ({ data, context }) => signedFor(context, getRequest(), data));
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The image proxy's URLs (Q860): `/_camo/{sig}/{hex url}`, as GitHub's camo writes them, `sig` the
3
+ * HMAC-SHA256 of the URL's text under a key HKDF'd from the host's `SESSION_SECRET`. Only a URL
4
+ * the app signed opens, so the proxy fetches no URL a text didn't hold.
5
+ */
6
+
7
+ /** Where every proxied image is served, under the app's origin. */
8
+ export const camoPrefix = '/_camo/';
9
+
10
+ const encoder = new TextEncoder();
11
+
12
+ const hexOf = (bytes: Uint8Array) =>
13
+ Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
14
+
15
+ /** Hex as its bytes, or `undefined` for text that isn't an even run of hex digits. */
16
+ const bytesOfHex = (hex: string) => {
17
+ if (hex.length % 2 !== 0 || !/^[\da-f]*$/.test(hex)) return undefined;
18
+
19
+ return Uint8Array.from({ length: hex.length / 2 }, (_, at) =>
20
+ Number.parseInt(hex.slice(at * 2, at * 2 + 2), 16),
21
+ );
22
+ };
23
+
24
+ /** The proxy's key, from the host's secret: HKDF, so it signs nothing a session does. */
25
+ export const camoKey = async (secret: string): Promise<CryptoKey> => {
26
+ if (secret.length < 32) throw new Error('SESSION_SECRET must be at least 32 characters');
27
+
28
+ const base = await crypto.subtle.importKey('raw', encoder.encode(secret), 'HKDF', false, [
29
+ 'deriveKey',
30
+ ]);
31
+
32
+ return crypto.subtle.deriveKey(
33
+ {
34
+ name: 'HKDF',
35
+ hash: 'SHA-256',
36
+ salt: new Uint8Array(),
37
+ info: encoder.encode('ref0 image proxy'),
38
+ },
39
+ base,
40
+ { name: 'HMAC', hash: 'SHA-256', length: 256 },
41
+ false,
42
+ ['sign', 'verify'],
43
+ );
44
+ };
45
+
46
+ /** `url`'s path on the proxy: its HMAC and its text, each in hex. */
47
+ export const signedPath = async (key: CryptoKey, url: string) => {
48
+ const bytes = encoder.encode(url);
49
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, bytes));
50
+
51
+ return `${camoPrefix}${hexOf(sig)}/${hexOf(bytes)}`;
52
+ };
53
+
54
+ /** The longest URL the proxy signs or opens, in bytes of its text. */
55
+ export const urlBytesMost = 2048;
56
+
57
+ /**
58
+ * The URL a proxy path names, when its signature is the app's, or `undefined`: a path not the
59
+ * proxy's, a signature or text that isn't hex, a URL past `urlBytesMost` or not UTF-8, and a
60
+ * signature that doesn't verify, which WebCrypto compares in constant time.
61
+ */
62
+ export const openedUrl = async (key: CryptoKey, pathname: string) => {
63
+ const [sigHex = '', urlHex = '', ...rest] = pathname.startsWith(camoPrefix)
64
+ ? pathname.slice(camoPrefix.length).split('/')
65
+ : [];
66
+ const sig = bytesOfHex(sigHex);
67
+ const bytes = bytesOfHex(urlHex);
68
+
69
+ if (sig?.length !== 32 || bytes === undefined || bytes.length > urlBytesMost || rest.length > 0) {
70
+ return undefined;
71
+ }
72
+
73
+ if (!(await crypto.subtle.verify('HMAC', key, sig, bytes))) return undefined;
74
+
75
+ try {
76
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
77
+ } catch {
78
+ return undefined;
79
+ }
80
+ };
@@ -1,8 +1,9 @@
1
- import type { GitAuthorize, TokenScope } from '@ref0/git';
1
+ import type { GitAuthorize, RepoAccess, TokenScope } from '@ref0/git';
2
2
  import type { GitHubOperationKind } from '@ref0/github';
3
- import { authorizeOperation, credentialCeiling } from '@ref0/github';
3
+ import { authorizeOperation, credentialCeiling, repoOfNodeId } from '@ref0/github';
4
4
  import { createServerFn } from '@tanstack/react-start';
5
5
  import { getRequest } from '@tanstack/react-start/server';
6
+ import * as Effect from 'effect/Effect';
6
7
  import * as Schema from 'effect/Schema';
7
8
 
8
9
  import type { AppContext } from '../context/context.ts';
@@ -33,7 +34,10 @@ const gitHubOperations = [
33
34
  'comment.update',
34
35
  'label.create',
35
36
  'label.update',
37
+ 'label.delete',
36
38
  'milestone.create',
39
+ 'milestone.update',
40
+ 'milestone.delete',
37
41
  'pull.create',
38
42
  'pull.update',
39
43
  'pull.merge',
@@ -48,18 +52,41 @@ const gitHubOperations = [
48
52
 
49
53
  type GitHubPageOperation = (typeof gitHubOperations)[number];
50
54
 
51
- /** Every operation a page draws a control for: the drop-in's, then the host calls'. */
52
- export const pageOperations = [...gitHubOperations, ...hostOperations] as const;
55
+ /**
56
+ * An issue's title, body and closing it, and a conversation comment's edit: the full
57
+ * `issue.update`'s or `comment.update`'s, and its author's too where that's refused, as the drop-in
58
+ * lets them (Q857). The page offers a comment's edit only on the viewer's own comments.
59
+ */
60
+ const authorOperations = ['issue.author', 'comment.author'] as const;
61
+
62
+ type AuthorOperation = (typeof authorOperations)[number];
63
+
64
+ /** Every operation a page draws a control for: the drop-in's, the author's, then the host calls'. */
65
+ export const pageOperations = [
66
+ ...gitHubOperations,
67
+ ...authorOperations,
68
+ ...hostOperations,
69
+ ] as const;
53
70
 
54
71
  export type PageOperation = (typeof pageOperations)[number];
55
72
 
56
73
  const isHostOperation = (kind: PageOperation): kind is HostOperation =>
57
74
  hostOperations.some((each) => each === kind);
58
75
 
76
+ const isAuthorOperation = (kind: PageOperation): kind is AuthorOperation =>
77
+ authorOperations.some((each) => each === kind);
78
+
79
+ const IssueAnswer = Schema.Struct({
80
+ user: Schema.NullOr(Schema.Struct({ login: Schema.String })),
81
+ pull_request: Schema.optional(Schema.Unknown),
82
+ });
83
+
84
+ const issueAnswer = Schema.decodeUnknownSync(IssueAnswer);
85
+
59
86
  /**
60
87
  * What the drop-in decides each operation on: the issue, by its number, or the repo alone, as its
61
- * routes ask. A new issue, label, milestone or pull request, an edited comment or label, a release
62
- * and a hook are the repo's. Asking for reviews is `pull.update`, merging or queueing a pull request is
88
+ * routes ask. A new issue, label, milestone or pull request, an edited comment, label or milestone, a
89
+ * deleted label or milestone, a release and a hook are the repo's. Asking for reviews is `pull.update`, merging or queueing a pull request is
63
90
  * `pull.merge`, and a review, a comment on its lines or discarding a pending review is
64
91
  * `pull.review`.
65
92
  */
@@ -70,7 +97,10 @@ const decidedOn: Readonly<Record<GitHubPageOperation, 'issue' | 'repo'>> = {
70
97
  'comment.update': 'repo',
71
98
  'label.create': 'repo',
72
99
  'label.update': 'repo',
100
+ 'label.delete': 'repo',
73
101
  'milestone.create': 'repo',
102
+ 'milestone.update': 'repo',
103
+ 'milestone.delete': 'repo',
74
104
  'pull.create': 'repo',
75
105
  'pull.update': 'issue',
76
106
  'pull.merge': 'issue',
@@ -108,6 +138,7 @@ const Ask = Schema.Struct({
108
138
  });
109
139
 
110
140
  const RepoAnswer = Schema.Struct({
141
+ node_id: Schema.String,
111
142
  full_name: Schema.String,
112
143
  private: Schema.Boolean,
113
144
  permissions: Schema.optional(Schema.Struct({ push: Schema.Boolean, pull: Schema.Boolean })),
@@ -151,11 +182,66 @@ export const allowedFor = async (
151
182
  const caller = identified.value;
152
183
  const repo = repoAnswer(await answered.json());
153
184
  const ceiling = ceilingOf(repo.permissions);
154
- // The repo as the caller's own read of it answered, just above.
155
- const visibility = { id: repo.full_name, public: !repo.private };
185
+ // The repo as the caller's own read of it answered, just above: its name, visibility and which
186
+ // repo it is, all from that one read, so `authorize` decides about the repo it read.
187
+ const internalId = repoOfNodeId(repo.node_id);
188
+ if (internalId === undefined) return [];
189
+
190
+ const visibility: RepoAccess = { name: repo.full_name, public: !repo.private, internalId };
191
+
192
+ /**
193
+ * Whether the caller may edit issue `ask.number` as its author: only when the caller's own read
194
+ * of it names them as who opened it, as the drop-in asks (Q857).
195
+ */
196
+ const asAuthor = async () => {
197
+ const { number } = ask;
198
+ if (number === undefined || caller.actor.anonymous === true) return false;
199
+
200
+ const read = await forward(
201
+ { api: 'github', method: 'GET', path: `${path}/issues/${number}` },
202
+ { origin, token, api: context.api },
203
+ );
204
+ if (!read.ok) return false;
205
+
206
+ const issue = issueAnswer(await read.json());
207
+ if (issue.pull_request !== undefined || issue.user?.login !== caller.actor.id) return false;
208
+
209
+ const refused = await Effect.runPromise(
210
+ authorizeOperation({
211
+ caller,
212
+ ceiling: credentialCeiling(ceiling),
213
+ operation: { kind: 'issue.update', repo: repo.full_name, number, asAuthor: true },
214
+ repo: visibility,
215
+ host: context.authorizeGitHub,
216
+ signal,
217
+ }),
218
+ { signal },
219
+ );
220
+
221
+ return refused === undefined;
222
+ };
223
+
224
+ /** Whether the host lets the caller, signed in, edit their own conversation comments (Q857). */
225
+ const asCommentAuthor = async () => {
226
+ if (caller.actor.anonymous === true) return false;
227
+
228
+ const refused = await Effect.runPromise(
229
+ authorizeOperation({
230
+ caller,
231
+ ceiling: credentialCeiling(ceiling),
232
+ operation: { kind: 'comment.update', repo: repo.full_name, asAuthor: true },
233
+ repo: visibility,
234
+ host: context.authorizeGitHub,
235
+ signal,
236
+ }),
237
+ { signal },
238
+ );
239
+
240
+ return refused === undefined;
241
+ };
156
242
 
157
243
  /** Whether the caller may make `kind` on the repo, or on its issue. */
158
- const allows = async (kind: PageOperation) => {
244
+ const allows = async (kind: PageOperation): Promise<boolean> => {
159
245
  // A host call is made for a session, whose credential is always one of Git's tokens.
160
246
  if (isHostOperation(kind)) {
161
247
  if (caller.token === undefined) return false;
@@ -174,23 +260,30 @@ export const allowedFor = async (
174
260
  return decided.kind === 'accept';
175
261
  }
176
262
 
263
+ if (kind === 'comment.author') return (await allows('comment.update')) || asCommentAuthor();
264
+
265
+ if (isAuthorOperation(kind)) return (await allows('issue.update')) || asAuthor();
266
+
177
267
  const onIssue = decidedOn[kind] === 'issue' && ask.number !== undefined;
178
268
  const target = onIssue
179
269
  ? { repo: repo.full_name, number: ask.number }
180
270
  : { repo: repo.full_name };
181
- const refused = await authorizeOperation({
182
- caller,
183
- ceiling: credentialCeiling(ceiling),
184
- operation: { ...target, kind },
185
- repo: visibility,
186
- host: context.authorizeGitHub,
187
- signal,
188
- });
271
+ const refused = await Effect.runPromise(
272
+ authorizeOperation({
273
+ caller,
274
+ ceiling: credentialCeiling(ceiling),
275
+ operation: { ...target, kind },
276
+ repo: visibility,
277
+ host: context.authorizeGitHub,
278
+ signal,
279
+ }),
280
+ { signal },
281
+ );
189
282
 
190
283
  return refused === undefined;
191
284
  };
192
285
 
193
- // Every check at once: one that throws rejects the whole answer, so no control is half decided.
286
+ // Every check at once: one that fails rejects the whole answer, so no control is half decided.
194
287
  const kinds = [...new Set(ask.kinds)];
195
288
  const decided = await Promise.all(kinds.map(allows));
196
289