ref0-git 0.6.0 → 0.7.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 (39) hide show
  1. package/app/apps/github/README.md +3 -7
  2. package/app/apps/github/generated/git-rest.ts +12 -12
  3. package/app/apps/github/src/clients/allowed.ts +7 -9
  4. package/app/apps/github/src/clients/avatars.ts +5 -3
  5. package/app/apps/github/src/clients/graphql.ts +12 -2
  6. package/app/apps/github/src/clients/host-calls.ts +2 -1
  7. package/app/apps/github/src/clients/transfers.ts +56 -19
  8. package/app/apps/github/src/context/context.ts +5 -5
  9. package/app/apps/github/src/context/host.ts +115 -0
  10. package/app/apps/github/src/ingress.ts +28 -0
  11. package/app/apps/github/src/policy.ts +113 -78
  12. package/app/apps/github/src/private-repos.ts +7 -7
  13. package/app/apps/github/src/pulls/review.ts +2 -1
  14. package/app/apps/github/src/releases/release-form.tsx +40 -4
  15. package/app/apps/github/src/releases/releases.ts +148 -22
  16. package/app/apps/github/src/routes/uploads/$owner/$repo/$release.tsx +9 -2
  17. package/app/apps/github/src/seed/seed.ts +9 -2
  18. package/app/apps/github/src/server.ts +28 -11
  19. package/app/apps/github/src/signin/approval.ts +20 -15
  20. package/app/apps/github/src/signin/attempts.ts +306 -0
  21. package/app/apps/github/src/signin/auth.ts +9 -0
  22. package/app/apps/github/src/signin/host-session.ts +30 -18
  23. package/app/apps/github/src/signin/limits.ts +35 -0
  24. package/app/pnpm-workspace.yaml +37 -36
  25. package/dist/cli/setup.mjs +1 -1
  26. package/dist/init/app.mjs +43 -23
  27. package/dist/init/cloudflare.mjs +8 -4
  28. package/dist/init/create.mjs +1 -1
  29. package/dist/init/detect.mjs +5 -3
  30. package/dist/init/files.mjs +6 -1
  31. package/dist/init/git-module.mjs +4 -6
  32. package/dist/init/metadata.mjs +6 -6
  33. package/dist/init/node-app.mjs +5 -2
  34. package/dist/init/stores.mjs +3 -2
  35. package/dist/init/template.mjs +13 -7
  36. package/dist/init/templates.mjs +51 -39
  37. package/dist/init/vercel.mjs +1 -1
  38. package/dist/init/versions.mjs +1 -1
  39. package/package.json +13 -13
@@ -4,6 +4,7 @@ import * as Option from 'effect/Option';
4
4
  import * as Schema from 'effect/Schema';
5
5
 
6
6
  import type { Clients } from '../clients/clients.ts';
7
+ import { assetBytesMost, partBytes } from '../clients/transfers.ts';
7
8
  import type { RepoPlace } from '../code/places.ts';
8
9
  import { everyNamedPage, failure } from '../hooks/answers.ts';
9
10
  import { readRefPage } from '../code/ref-pages.ts';
@@ -220,39 +221,164 @@ const UploadedAsset = Schema.Struct({
220
221
 
221
222
  const uploadedOf = Schema.decodeUnknownOption(UploadedAsset);
222
223
 
224
+ /** What an upload tells the page as it goes, and how the page stops it. */
225
+ export interface UploadWatch {
226
+ /** Called before a failure when a request got no answer and the asset may have landed. */
227
+ readonly lost: () => void;
228
+ /** The bytes the drop-in has taken so far, as each part lands. */
229
+ readonly sent: (bytes: number) => void;
230
+ /** Called once every part has landed, as the complete reads them back for the digest. */
231
+ readonly checking: () => void;
232
+ /** Once aborted, the upload sends nothing more, and an upload in parts is aborted. */
233
+ readonly signal: AbortSignal;
234
+ }
235
+
236
+ /** An upload in parts, as the drop-in begins it. */
237
+ const Begun = Schema.Struct({
238
+ id: Schema.String,
239
+ part_bytes: Schema.Int.check(Schema.isGreaterThan(0)),
240
+ parts: Schema.Int,
241
+ });
242
+
243
+ const begunOf = Schema.decodeUnknownOption(Begun);
244
+
245
+ /** The most parts a file at the drop-in's limit takes. */
246
+ const partsMost = Math.ceil(assetBytesMost / partBytes);
247
+
248
+ const typeOf = (file: File) => (file.type === '' ? 'application/octet-stream' : file.type);
249
+
250
+ const noAnswer = (file: File) =>
251
+ new Error(`${file.name}'s upload got no answer: submit again to finish`);
252
+
253
+ const stopped = (file: File) => new Error(`${file.name}'s upload stopped: submit again to send it`);
254
+
255
+ /** Why `file` didn't upload, from the drop-in's refusal. */
256
+ const refusal = async (file: File, answer: Response) => {
257
+ const said: unknown = await answer.json().catch(() => undefined);
258
+
259
+ // The host's platform may cap a request below the drop-in's limit, as Cloudflare's plans do.
260
+ if (answer.status === 413) {
261
+ return new Error(`${file.name} didn't upload: it's larger than this host takes in one request`);
262
+ }
263
+
264
+ return failure(`${file.name} didn't upload`, { error: said, response: answer });
265
+ };
266
+
223
267
  /**
224
- * Uploads `file` to release `id`, streamed from the browser through the app's upload route,
225
- * which adds the session; the page never holds its bytes. Answers the asset it made. When no
226
- * answer comes, the upload may still have landed: `lost` is called before it fails.
268
+ * The asset an upload's last answer lists, or why it lists none. A 2xx whose body can't be read
269
+ * listed the asset all the same, so `lost` is called before it fails, and a submit again finds it.
227
270
  */
228
- export const uploadAsset = async (
229
- place: RepoPlace,
230
- id: number,
231
- file: File,
232
- lost: () => void,
233
- ): Promise<Asset> => {
234
- const path = `/uploads/${segment(place.owner)}/${segment(place.repo)}/${id}`;
235
- const sent = fetch(`${path}?name=${segment(file.name)}`, {
271
+ const assetOf = async (file: File, answer: Response, lost: () => void) => {
272
+ if (!answer.ok) throw await refusal(file, answer);
273
+
274
+ const said: unknown = await answer.json().catch(() => undefined);
275
+
276
+ return Option.getOrThrowWith(uploadedOf(said), () => {
277
+ lost();
278
+
279
+ return noAnswer(file);
280
+ });
281
+ };
282
+
283
+ /** `file` in the one request, streamed whole. A stopped or unanswered request may have landed. */
284
+ const uploadWhole = async (path: string, file: File, { lost, sent, signal }: UploadWatch) => {
285
+ const answer = await fetch(`${path}?name=${segment(file.name)}`, {
236
286
  method: 'POST',
237
287
  body: file,
238
- headers: { 'content-type': file.type === '' ? 'application/octet-stream' : file.type },
239
- });
240
- const answer = await sent.catch(() => {
288
+ headers: { 'content-type': typeOf(file) },
289
+ signal,
290
+ }).catch(() => {
241
291
  lost();
242
- throw new Error(`${file.name}'s upload got no answer: submit again to finish`);
292
+ throw signal.aborted ? stopped(file) : noAnswer(file);
243
293
  });
244
- const said: unknown = await answer.json().catch(() => undefined);
294
+ const asset = await assetOf(file, answer, lost);
295
+ sent(file.size);
296
+
297
+ return asset;
298
+ };
245
299
 
246
- if (answer.ok) {
247
- return Option.getOrThrowWith(uploadedOf(said), () => new Error(`${file.name}: no asset`));
300
+ /**
301
+ * `file` in parts: begun, each part sent in order, then completed. A part that fails, a stop, or
302
+ * a complete refused aborts the upload, so the drop-in removes its parts and a submit again
303
+ * begins it anew. Only the complete lists the asset, so only a complete stopped or with no answer
304
+ * may have landed: a stop then aborts what's left, which the drop-in refuses once the asset is
305
+ * listed.
306
+ */
307
+ const uploadParts = async (
308
+ path: string,
309
+ file: File,
310
+ { lost, sent, checking, signal }: UploadWatch,
311
+ ) => {
312
+ const begin = await fetch(`${path}?name=${segment(file.name)}&parts`, {
313
+ method: 'POST',
314
+ body: JSON.stringify({ size: file.size, content_type: typeOf(file) }),
315
+ headers: { 'content-type': 'application/json' },
316
+ signal,
317
+ }).catch(() => {
318
+ throw signal.aborted ? stopped(file) : noAnswer(file);
319
+ });
320
+ if (!begin.ok) throw await refusal(file, begin);
321
+
322
+ const begun = Option.getOrUndefined(begunOf(await begin.json().catch(() => undefined)));
323
+ const parts = begun === undefined ? 0 : Math.ceil(file.size / begun.part_bytes);
324
+
325
+ if (begun === undefined || begun.parts !== parts || parts > partsMost) {
326
+ throw new Error(`${file.name}: no upload`);
248
327
  }
249
328
 
250
- // The host's platform may cap a request below the drop-in's limit, as Cloudflare's plans do.
251
- if (answer.status === 413) {
252
- throw new Error(`${file.name} didn't upload: it's larger than this host takes in one request`);
329
+ const at = `${path}?upload=${segment(begun.id)}`;
330
+ const aborted = async (error: Error) => {
331
+ await fetch(at, { method: 'DELETE' }).then(
332
+ (answer) => answer.body?.cancel(),
333
+ () => undefined,
334
+ );
335
+
336
+ return error;
337
+ };
338
+
339
+ for (let part = 0; part < parts; part += 1) {
340
+ const start = part * begun.part_bytes;
341
+ const body = file.slice(start, start + begun.part_bytes);
342
+ const answer = await fetch(`${at}&part=${part}`, {
343
+ method: 'PUT',
344
+ body,
345
+ headers: { 'content-type': 'application/octet-stream' },
346
+ signal,
347
+ }).catch(() => undefined);
348
+ if (answer === undefined) throw await aborted(signal.aborted ? stopped(file) : noAnswer(file));
349
+
350
+ if (!answer.ok) throw await aborted(await refusal(file, answer));
351
+
352
+ await answer.body?.cancel();
353
+ sent(start + body.size);
354
+ }
355
+
356
+ if (signal.aborted) throw await aborted(stopped(file));
357
+
358
+ // A 2 GiB complete takes about a minute to read its parts back, with nothing left to send.
359
+ checking();
360
+ const completed = await fetch(at, { method: 'POST', signal }).catch(() => undefined);
361
+
362
+ if (completed === undefined) {
363
+ lost();
364
+ throw signal.aborted ? await aborted(stopped(file)) : noAnswer(file);
253
365
  }
254
366
 
255
- throw failure(`${file.name} didn't upload`, { error: said, response: answer });
367
+ if (!completed.ok) throw await aborted(await refusal(file, completed));
368
+
369
+ return assetOf(file, completed, lost);
370
+ };
371
+
372
+ /**
373
+ * Uploads `file` to release `id`, streamed from the browser through the app's upload route,
374
+ * which adds the session; the page never holds its bytes. A file past `partBytes` goes in parts,
375
+ * each a request a host takes. Answers the asset it made. When no answer comes, the upload may
376
+ * still have landed: `watch.lost` is called before it fails.
377
+ */
378
+ export const uploadAsset = (place: RepoPlace, id: number, file: File, watch: UploadWatch) => {
379
+ const path = `/uploads/${segment(place.owner)}/${segment(place.repo)}/${id}`;
380
+
381
+ return file.size > partBytes ? uploadParts(path, file, watch) : uploadWhole(path, file, watch);
256
382
  };
257
383
 
258
384
  /** A plain link to `asset`'s bytes, which the app's download route streams with the session. */
@@ -2,9 +2,16 @@ import { createFileRoute } from '@tanstack/react-router';
2
2
 
3
3
  import { forwardUpload } from '../../../../clients/transfers.ts';
4
4
 
5
- /** An asset's upload from the app's release form, streamed to the drop-in as the session's holder. */
5
+ /**
6
+ * An asset's upload from the app's release form, in one request or in parts, each step streamed
7
+ * to the drop-in as the session's holder.
8
+ */
6
9
  export const Route = createFileRoute('/uploads/$owner/$repo/$release')({
7
10
  server: {
8
- handlers: { POST: ({ request, context, params }) => forwardUpload(context, request, params) },
11
+ handlers: {
12
+ POST: ({ request, context, params }) => forwardUpload(context, request, params),
13
+ PUT: ({ request, context, params }) => forwardUpload(context, request, params),
14
+ DELETE: ({ request, context, params }) => forwardUpload(context, request, params),
15
+ },
9
16
  },
10
17
  });
@@ -109,7 +109,14 @@ const signature = (person: Person, since: number, daysAgo: number): Signature =>
109
109
  });
110
110
 
111
111
  /** A drop-in call's JSON body: the fields GitHub's REST takes for each of the seed's writes. */
112
- type Body = Readonly<Record<string, string | number | readonly string[]>>;
112
+ const Body = Schema.Record(
113
+ Schema.String,
114
+ Schema.Union([Schema.String, Schema.Number, Schema.Array(Schema.String)]),
115
+ );
116
+
117
+ type Body = typeof Body.Type;
118
+
119
+ const encodeBody = Schema.encodeSync(Schema.fromJsonString(Body));
113
120
 
114
121
  /**
115
122
  * One drop-in call as `person`, and its answer's status and text: a lookup's 404 is an answer,
@@ -132,7 +139,7 @@ const dropInCall =
132
139
 
133
140
  if (body !== undefined) {
134
141
  headers.set('content-type', 'application/json');
135
- init.body = JSON.stringify(body);
142
+ init.body = encodeBody(body);
136
143
  }
137
144
 
138
145
  const response = await host.fetch(new Request(new URL(`/api/v3${path}`, host.origin), init));
@@ -1,23 +1,37 @@
1
+ import { Git } from '@ref0/git';
1
2
  import { Records } from '@ref0/infra';
2
3
  import handler, { createServerEntry } from '@tanstack/react-start/server-entry';
4
+ import * as Effect from 'effect/Effect';
3
5
 
4
6
  import { workersFetch } from './camo/fetch.ts';
5
7
  import { imageProxy } from './camo/proxy.ts';
6
8
  import type { AppContext } from './context/context.ts';
7
- import { auth, directory, env, git, github, pictures, policy, rest, sessionKey } from './git.ts';
9
+ import { auth, directory, env, pictures, policy, run, runtime, sessionKey } from './git.ts';
10
+ import { repoListOn, routeOn, tokenCallsOn } from './context/host.ts';
11
+ import { ingressOf } from './ingress.ts';
8
12
  import { hostRules } from './policy.ts';
9
13
  import { shownRules } from './settings/rules.ts';
10
- import { sessionCookieOf, sessionEnder, sessionFrom } from './signin/auth.ts';
14
+ import { deviceAttemptAnswer, deviceAttemptGate } from './signin/attempts.ts';
15
+ import { sessionCookieOf, sessionEnder, sessionFrom, sessionIdFrom } from './signin/auth.ts';
11
16
  import { withoutHostSession } from './signin/host-session.ts';
12
17
 
13
18
  export { Jobs, Records } from './git.ts';
14
19
 
15
- /** The drop-in's URLs, then Git's Smart HTTP and sign-in, then its REST: a URL one of them owns. */
16
- const owned = async (request: Request) =>
17
- (await github.route(request)) ?? (await git.route(request)) ?? (await rest.route(request));
20
+ /**
21
+ * The device page's attempts (#1962), counted in Git's records, by the address the platform sets
22
+ * and the session Better Auth checks, before Git reads a code.
23
+ */
24
+ const gate = deviceAttemptGate({
25
+ answer: (who) => runtime.runPromise(deviceAttemptAnswer(who)),
26
+ addressHeader: 'cf-connecting-ip',
27
+ session: async (request) => sessionIdFrom(await auth())(request),
28
+ });
29
+
30
+ /** The front door, then Git's routes, the drop-in's among them, for outside and the app alike. */
31
+ const { owned, api } = ingressOf({ gate, git: routeOn(runtime) });
18
32
 
19
- /** Git's answer for a URL it doesn't own: the app's server calls never reach the app. */
20
- const api = async (request: Request) => (await owned(request)) ?? rest.fetch(request);
33
+ /** Git's own calls, as host calls read them. */
34
+ const git = { repos: { list: repoListOn(run) }, tokens: tokenCallsOn(run) };
21
35
 
22
36
  /**
23
37
  * The image proxy (Q860): a text's remote images load through `/_camo/`, and the pages' CSP loads
@@ -59,14 +73,17 @@ const seeded = () => {
59
73
  adminToken: env.ADMIN_TOKEN,
60
74
  // Git's records, on its runtime, keep the seed's progress beside Git's own.
61
75
  store: {
62
- read: (scope, reads) => git.runtime.runPromise(Records.read(scope, reads)),
63
- commit: (scope, change) => git.runtime.runPromise(Records.commit(scope, change)),
76
+ read: (scope, reads) => runtime.runPromise(Records.read(scope, reads)),
77
+ commit: (scope, change) => runtime.runPromise(Records.commit(scope, change)),
64
78
  },
65
79
  });
66
80
  })
67
81
  .then(
68
82
  () => undefined,
69
- (cause: unknown) => console.error('The seed stopped, and goes on at the next start:', cause),
83
+ (cause: unknown) =>
84
+ runtime.runPromise(
85
+ Effect.logError('The seed stopped, and goes on at the next start', cause),
86
+ ),
70
87
  );
71
88
 
72
89
  return seeding;
@@ -91,7 +108,7 @@ export default createServerEntry({
91
108
  session: async (each) => sessionFrom(await auth(), sessionKey)(each),
92
109
  endSession: async (each) => sessionEnder(await auth())(each),
93
110
  sessionCookie: async () => sessionCookieOf(await auth())(),
94
- identify: git.identify,
111
+ identify: (each) => run(Git.identify(each)),
95
112
  authorize: policy.authorize,
96
113
  authorizeGitHub: policy.authorizeGitHub,
97
114
  rules,
@@ -1,3 +1,4 @@
1
+ import * as Effect from 'effect/Effect';
1
2
  import type {
2
3
  ApprovalPageInput,
3
4
  Caller,
@@ -127,34 +128,36 @@ const shown = async (
127
128
  * prompt, never the sealed one, granting `tokenScopeOf` its scopes, and Git checks the code is still
128
129
  * pending as it settles.
129
130
  */
130
- const decided = async (
131
+ const decided = Effect.fnUntraced(function* (
131
132
  input: ConfirmApprovalPage,
132
133
  prompt: DeviceApproval,
133
134
  form: URLSearchParams,
134
135
  options: StarterApprovalOptions,
135
- ) => {
136
+ ) {
136
137
  const sealed = form.get('prompt') ?? '';
137
138
  const signInFirst = seeOther(
138
139
  `/login?${new URLSearchParams({ return_to: codePageWith({ prompt: sealed }) }).toString()}`,
139
140
  );
140
141
  if (!fromApp(input.request, options)) return signInFirst;
141
142
 
142
- const login = await signedIn(input, options);
143
+ const login = yield* Effect.promise(() => signedIn(input, options));
143
144
  if (login === undefined) return signInFirst;
144
145
 
145
- const opened = await openPrompt(await options.sealKey, sealed, login, Date.now());
146
+ const opened = yield* Effect.promise(async () =>
147
+ openPrompt(await options.sealKey, sealed, login, Date.now()),
148
+ );
146
149
  if (opened?.userCode !== prompt.userCode)
147
150
  return seeOther(codePageWith({ error: 'expired-code' }));
148
151
 
149
152
  const decision = form.get('decision');
150
- if (decision === 'deny') return settled(await input.decide({ kind: 'deny' }), 'denied');
153
+ if (decision === 'deny') return settled(yield* input.decide({ kind: 'deny' }), 'denied');
151
154
 
152
155
  if (decision !== 'approve') return seeOther(codePageWith({ prompt: sealed }));
153
156
 
154
157
  const problem = ownerProblem(login);
155
158
  if (problem !== undefined) return plain(403, problem);
156
159
 
157
- const approved = await input.decide({
160
+ const approved = yield* input.decide({
158
161
  kind: 'approve',
159
162
  actor: { id: login },
160
163
  target: { prefix: '' },
@@ -163,25 +166,27 @@ const decided = async (
163
166
  });
164
167
 
165
168
  return settled(approved, 'approved');
166
- };
169
+ });
167
170
 
168
171
  /**
169
172
  * The starter's `approvalPage`, which keeps no HTML: Git's pages become redirects to the app's
170
173
  * `/login/code`, which shows a code's prompt sealed from Git's record, and whose Card posts the
171
174
  * signed-in person's decision back here. A host with its own accounts decides with its own.
172
175
  */
173
- export const starterApprovalPage =
174
- (options: StarterApprovalOptions) =>
175
- async (input: ApprovalPageInput): Promise<Response> => {
176
- if (input.kind === 'enter-code') return enterCode(input, options);
176
+ export const starterApprovalPage = (options: StarterApprovalOptions) =>
177
+ Effect.fnUntraced(function* (input: ApprovalPageInput) {
178
+ if (input.kind === 'enter-code') return yield* Effect.promise(() => enterCode(input, options));
177
179
 
178
180
  const { prompt } = input;
179
181
  if (prompt.kind === 'web') return plain(400, 'This host signs people in at /login');
180
182
 
181
183
  // A code arrives posted too, from the Code field: only the Card's own post names a decision.
182
184
  const form =
183
- input.request.method === 'POST' ? new URLSearchParams(await input.request.text()) : undefined;
184
- if (form?.has('decision') !== true) return shown(input, prompt, options);
185
+ input.request.method === 'POST'
186
+ ? new URLSearchParams(yield* Effect.promise(() => input.request.text()))
187
+ : undefined;
188
+ if (form?.has('decision') !== true)
189
+ return yield* Effect.promise(() => shown(input, prompt, options));
185
190
 
186
- return decided(input, prompt, form, options);
187
- };
191
+ return yield* decided(input, prompt, form, options);
192
+ });