ref0-git 0.6.0 → 0.8.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 (59) hide show
  1. package/app/apps/github/README.md +3 -7
  2. package/app/apps/github/generated/git-rest.ts +17 -20
  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/components/signin/device-card.tsx +2 -2
  9. package/app/apps/github/src/context/context.ts +5 -5
  10. package/app/apps/github/src/context/host.ts +115 -0
  11. package/app/apps/github/src/ingress.ts +28 -0
  12. package/app/apps/github/src/policy.ts +113 -78
  13. package/app/apps/github/src/private-repos.ts +7 -7
  14. package/app/apps/github/src/pulls/review.ts +2 -1
  15. package/app/apps/github/src/releases/release-form.tsx +40 -4
  16. package/app/apps/github/src/releases/releases.ts +148 -22
  17. package/app/apps/github/src/routes/uploads/$owner/$repo/$release.tsx +9 -2
  18. package/app/apps/github/src/seed/seed.ts +68 -38
  19. package/app/apps/github/src/server.ts +28 -11
  20. package/app/apps/github/src/signin/approval.ts +20 -15
  21. package/app/apps/github/src/signin/attempts.ts +306 -0
  22. package/app/apps/github/src/signin/auth.ts +9 -0
  23. package/app/apps/github/src/signin/device-code.ts +2 -2
  24. package/app/apps/github/src/signin/device-prompt.ts +6 -6
  25. package/app/apps/github/src/signin/host-session.ts +30 -18
  26. package/app/apps/github/src/signin/limits.ts +35 -0
  27. package/app/pnpm-workspace.yaml +39 -38
  28. package/dist/cli/events.mjs +10 -13
  29. package/dist/cli/failure.mjs +4 -10
  30. package/dist/cli/hosts.mjs +2 -2
  31. package/dist/cli/queue.mjs +14 -23
  32. package/dist/cli/repos.mjs +10 -19
  33. package/dist/cli/resources.mjs +2 -2
  34. package/dist/cli/setup.mjs +33 -40
  35. package/dist/cli/sign-in.mjs +4 -4
  36. package/dist/cli/tokens.mjs +7 -11
  37. package/dist/cli/vendor.mjs +21 -1
  38. package/dist/init/app.mjs +45 -23
  39. package/dist/init/astro.mjs +2 -2
  40. package/dist/init/cloudflare.mjs +100 -51
  41. package/dist/init/create.mjs +1 -1
  42. package/dist/init/detect.mjs +7 -5
  43. package/dist/init/files.mjs +6 -1
  44. package/dist/init/git-module.mjs +89 -32
  45. package/dist/init/metadata.mjs +12 -7
  46. package/dist/init/mounts.mjs +12 -20
  47. package/dist/init/next.mjs +1 -1
  48. package/dist/init/node-app.mjs +5 -2
  49. package/dist/init/node.mjs +24 -35
  50. package/dist/init/nuxt.mjs +6 -7
  51. package/dist/init/react-router.mjs +2 -2
  52. package/dist/init/routes.mjs +13 -22
  53. package/dist/init/stores.mjs +3 -2
  54. package/dist/init/sveltekit.mjs +3 -3
  55. package/dist/init/template.mjs +14 -15
  56. package/dist/init/templates.mjs +76 -81
  57. package/dist/init/vercel.mjs +18 -22
  58. package/dist/init/versions.mjs +32 -4
  59. 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
  });
@@ -1,7 +1,9 @@
1
1
  import type { CreatedToken, GitError, Oid, RefName, RepoName, Result, Signature } from '@ref0/git';
2
- import { createRestClient } from '@ref0/git/rest';
2
+ import { RestClient } from '@ref0/git';
3
+ import type { RestClientCalls } from '@ref0/git';
3
4
  import type { Change, Committed, Read, Scope, Snapshot } from '@ref0/infra';
4
- import type { RestClient } from '@ref0/git/rest';
5
+ import * as Effect from 'effect/Effect';
6
+ import * as FetchHttpClient from 'effect/http/FetchHttpClient';
5
7
  import * as Schema from 'effect/Schema';
6
8
 
7
9
  import { org, pip, repos } from './acme.ts';
@@ -54,6 +56,15 @@ const day = 24 * 60 * 60 * 1000;
54
56
  /** How long a person's seed token lasts: the seed revokes it when it ends, and a cut one expires. */
55
57
  const tokenLife = 60 * 60 * 1000;
56
58
 
59
+ /** `call` run once, to Git's `Result`. */
60
+ const answer = <A>(call: Effect.Effect<A, GitError>): Promise<Result<A>> =>
61
+ Effect.runPromise(
62
+ Effect.match(call, {
63
+ onSuccess: (value): Result<A> => ({ kind: 'success', value }),
64
+ onFailure: (error): Result<A> => ({ kind: 'error', error }),
65
+ }),
66
+ );
67
+
57
68
  const value = <A>(result: Result<A>, doing: string): A => {
58
69
  if (result.kind === 'success') return result.value;
59
70
 
@@ -87,11 +98,11 @@ const saveProgress = async (store: SeedRecords, version: number, progress: Progr
87
98
  * The progress to go on from: a cut seed's, or a new one when the host holds no repos. A host
88
99
  * whose seed is done, or that has repos of its own, gets none.
89
100
  */
90
- const begin = async (store: SeedRecords, admin: RestClient): Promise<Progress | undefined> => {
101
+ const begin = async (store: SeedRecords, admin: RestClientCalls): Promise<Progress | undefined> => {
91
102
  const { version, progress } = await readProgress(store);
92
103
  if (progress !== undefined) return progress.state === 'running' ? progress : undefined;
93
104
 
94
- const listed = value(await admin.repos.list({ page: { limit: 1 } }), 'list the repos');
105
+ const listed = value(await answer(admin.repos.list({ page: { limit: 1 } })), 'list the repos');
95
106
  if (listed.items.length > 0) return undefined;
96
107
 
97
108
  const started: Progress = { state: 'running', since: Date.now() };
@@ -109,7 +120,14 @@ const signature = (person: Person, since: number, daysAgo: number): Signature =>
109
120
  });
110
121
 
111
122
  /** 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[]>>;
123
+ const Body = Schema.Record(
124
+ Schema.String,
125
+ Schema.Union([Schema.String, Schema.Number, Schema.Array(Schema.String)]),
126
+ );
127
+
128
+ type Body = typeof Body.Type;
129
+
130
+ const encodeBody = Schema.encodeSync(Schema.fromJsonString(Body));
113
131
 
114
132
  /**
115
133
  * One drop-in call as `person`, and its answer's status and text: a lookup's 404 is an answer,
@@ -132,7 +150,7 @@ const dropInCall =
132
150
 
133
151
  if (body !== undefined) {
134
152
  headers.set('content-type', 'application/json');
135
- init.body = JSON.stringify(body);
153
+ init.body = encodeBody(body);
136
154
  }
137
155
 
138
156
  const response = await host.fetch(new Request(new URL(`/api/v3${path}`, host.origin), init));
@@ -209,9 +227,9 @@ const decodeTitled = Schema.decodeUnknownSync(
209
227
  * drop-in calls.
210
228
  */
211
229
  interface Cast {
212
- readonly admin: RestClient;
230
+ readonly admin: RestClientCalls;
213
231
  readonly adminCall: Call;
214
- readonly git: (person: Person) => RestClient;
232
+ readonly git: (person: Person) => RestClientCalls;
215
233
  readonly call: (person: Person) => Call;
216
234
  }
217
235
 
@@ -219,7 +237,7 @@ const ensureRepo = async (cast: Cast, id: RepoName, path: string, description: s
219
237
  const found = await cast.adminCall('GET', path);
220
238
 
221
239
  if (found.status === 404) {
222
- value(await cast.admin.repos.create({ name: id, public: true }), `make ${id}`);
240
+ value(await answer(cast.admin.repos.create({ name: id, public: true })), `make ${id}`);
223
241
  } else if (decodeDescribed(found.text).description === (description || null)) {
224
242
  return;
225
243
  }
@@ -230,7 +248,7 @@ const ensureRepo = async (cast: Cast, id: RepoName, path: string, description: s
230
248
 
231
249
  /** Each commit in turn on `parent`, as `git commit` makes them; their IDs, oldest first. */
232
250
  const commitAll = async (
233
- git: RestClient,
251
+ git: RestClientCalls,
234
252
  id: RepoName,
235
253
  parent: Oid | undefined,
236
254
  commits: readonly SeedCommit[],
@@ -240,12 +258,14 @@ const commitAll = async (
240
258
  let tip = parent;
241
259
 
242
260
  for (const commit of commits) {
243
- const created = await git.commits.create(id, {
244
- parents: tip === undefined ? [] : [tip],
245
- changes: Object.entries(commit.files).map(([path, content]) => ({ path, content })),
246
- message: `${commit.message}\n`,
247
- author: signature(commit.by, since, commit.daysAgo),
248
- });
261
+ const created = await answer(
262
+ git.commits.create(id, {
263
+ parents: tip === undefined ? [] : [tip],
264
+ changes: Object.entries(commit.files).map(([path, content]) => ({ path, content })),
265
+ message: `${commit.message}\n`,
266
+ author: signature(commit.by, since, commit.daysAgo),
267
+ }),
268
+ );
249
269
  tip = value(created, `commit "${commit.message}" to ${id}`).oid;
250
270
  made.push(tip);
251
271
  }
@@ -258,7 +278,7 @@ const commitAll = async (
258
278
  * makes the same objects, then each branch and the tag that isn't there yet, at once. Checks the
259
279
  * expected refs first so a resumed seed skips rebuilding commits and tags once every ref exists.
260
280
  */
261
- const pushHistory = async (git: RestClient, id: RepoName, repo: SeedRepo, since: number) => {
281
+ const pushHistory = async (git: RestClientCalls, id: RepoName, repo: SeedRepo, since: number) => {
262
282
  const { release } = repo;
263
283
  const targets: readonly {
264
284
  readonly ref: RefName;
@@ -277,12 +297,14 @@ const pushHistory = async (git: RestClient, id: RepoName, repo: SeedRepo, since:
277
297
  ref: `refs/tags/${release.tag}`,
278
298
  build: async (main: readonly Oid[]) => {
279
299
  const tagged = repo.main[release.at];
280
- const tag = await git.tags.create(id, {
281
- object: main[release.at] ?? '',
282
- tag: release.tag,
283
- tagger: signature(pip, since, (tagged?.daysAgo ?? 0) - 1),
284
- message: `${release.title}\n`,
285
- });
300
+ const tag = await answer(
301
+ git.tags.create(id, {
302
+ object: main[release.at] ?? '',
303
+ tag: release.tag,
304
+ tagger: signature(pip, since, (tagged?.daysAgo ?? 0) - 1),
305
+ message: `${release.title}\n`,
306
+ }),
307
+ );
286
308
 
287
309
  return value(tag, `tag ${release.tag}`).oid;
288
310
  },
@@ -293,7 +315,7 @@ const pushHistory = async (git: RestClient, id: RepoName, repo: SeedRepo, since:
293
315
  const missingRefs = new Set<RefName>();
294
316
 
295
317
  for (const { ref } of targets) {
296
- const found = await git.refs.get(id, { ref });
318
+ const found = await answer(git.refs.get(id, { ref }));
297
319
  if (found.kind === 'success') continue;
298
320
 
299
321
  if (!missing(found.error)) value(found, `read ${ref}`);
@@ -310,7 +332,10 @@ const pushHistory = async (git: RestClient, id: RepoName, repo: SeedRepo, since:
310
332
  if (missingRefs.has(ref)) absent.push({ ref, from: null, to });
311
333
  }
312
334
 
313
- const updated = value(await git.refs.update(id, { updates: absent, atomic: true }), 'push');
335
+ const updated = value(
336
+ await answer(git.refs.update(id, { updates: absent, atomic: true })),
337
+ 'push',
338
+ );
314
339
  const refused = updated.updates.find((update) => update.kind === 'rejected');
315
340
  if (refused !== undefined) throw new Error(`The seed's push of ${refused.ref} was refused`);
316
341
  };
@@ -513,14 +538,14 @@ const members: ReadonlySet<string> = new Set(org.members.map((person) => person.
513
538
  * its ID, was lost, or its revoke never came. The host's own tokens expire at other times.
514
539
  */
515
540
  const revokeLeft = async (
516
- admin: RestClient,
541
+ admin: RestClientCalls,
517
542
  expiries: ReadonlySet<number>,
518
543
  after?: string,
519
544
  ): Promise<void> => {
520
545
  const active = { state: 'active' as const };
521
546
  const input = after === undefined ? active : { ...active, page: { after } };
522
547
  const page = value(
523
- await admin.tokens.list({ prefix: `${org.login}/` }, input),
548
+ await answer(admin.tokens.list({ prefix: `${org.login}/` }, input)),
524
549
  'list the tokens a cut seed left',
525
550
  );
526
551
  const left = page.items.filter(
@@ -528,7 +553,8 @@ const revokeLeft = async (
528
553
  expiries.has(token.expiresAt) && token.scope === 'write' && members.has(token.subject.id),
529
554
  );
530
555
 
531
- for (const token of left) value(await admin.tokens.revoke(token.id), 'revoke a token it left');
556
+ for (const token of left)
557
+ value(await answer(admin.tokens.revoke(token.id)), 'revoke a token it left');
532
558
 
533
559
  if (page.next !== undefined) await revokeLeft(admin, expiries, page.next);
534
560
  };
@@ -544,7 +570,13 @@ const revokeLeft = async (
544
570
  */
545
571
  export const seed = async (host: SeedHost): Promise<SeedOutcome> => {
546
572
  const client = (token: string) =>
547
- createRestClient({ url: host.origin, credentials: { token }, transport: host.fetch });
573
+ Effect.runSync(
574
+ Effect.provide(
575
+ RestClient.make({ url: host.origin, credentials: { token }, transport: host.fetch }),
576
+ // @effect-diagnostics-next-line unstableApiUsage:off
577
+ FetchHttpClient.layer,
578
+ ),
579
+ );
548
580
  const admin = client(host.adminToken);
549
581
 
550
582
  const progress = await begin(host.store, admin);
@@ -570,18 +602,16 @@ export const seed = async (host: SeedHost): Promise<SeedOutcome> => {
570
602
 
571
603
  try {
572
604
  for (const person of org.members) {
573
- const token = await admin.tokens.create(
574
- { prefix: `${org.login}/` },
575
- {
576
- scope: 'write',
577
- subject: { id: person.login },
578
- expiresAt: tokensExpire,
579
- },
605
+ const token = await answer(
606
+ admin.tokens.create(
607
+ { prefix: `${org.login}/` },
608
+ { scope: 'write', subject: { id: person.login }, expiresAt: tokensExpire },
609
+ ),
580
610
  );
581
611
  issued.set(person.login, value(token, `make ${person.login}'s token`));
582
612
  }
583
613
 
584
- const gitClients = new Map<string, RestClient>();
614
+ const gitClients = new Map<string, RestClientCalls>();
585
615
  const dropInCalls = new Map<string, Call>();
586
616
  const secret = (person: Person) => issued.get(person.login)?.secret ?? '';
587
617
  const memo = <A>(cache: Map<string, A>, person: Person, make: (token: string) => A): A => {
@@ -604,7 +634,7 @@ export const seed = async (host: SeedHost): Promise<SeedOutcome> => {
604
634
  for (const repo of repos) await seedRepo(cast, repo, progress.since);
605
635
  } finally {
606
636
  // One at a time: revokes at once in one scope miss each other's writes, and some run out of tries.
607
- for (const token of issued.values()) revoked.push(await admin.tokens.revoke(token.id));
637
+ for (const token of issued.values()) revoked.push(await answer(admin.tokens.revoke(token.id)));
608
638
  }
609
639
 
610
640
  // A revoke that failed leaves the seed running, so the next call revokes what it left.
@@ -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
+ });