ref0-git 0.10.0 → 0.11.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.
@@ -337,7 +337,14 @@ const mayChange = async (
337
337
  return allowed.includes('repo.update');
338
338
  };
339
339
 
340
- /** Whose avatar `change` is for, once `mayChange` lets its changer make it. Else the refusal. */
340
+ /** The account or repo at `place` as `changer` reads it, or `undefined`. */
341
+ const targetFor = (context: AvatarContext, changer: Changer, place: AvatarPlace) =>
342
+ readTarget(context, changer.origin, changer.admin ? undefined : changer.token, place);
343
+
344
+ /**
345
+ * Whose avatar `change` is for, and who makes it, once `mayChange` lets its changer make it. Else
346
+ * the refusal.
347
+ */
341
348
  const changeable = async (
342
349
  context: AvatarContext,
343
350
  request: Request,
@@ -347,14 +354,13 @@ const changeable = async (
347
354
  const changer = await changerOf(context, request);
348
355
  if (changer instanceof Response) return changer;
349
356
 
350
- const token = changer.admin ? undefined : changer.token;
351
- const target = await readTarget(context, changer.origin, token, place);
357
+ const target = await targetFor(context, changer, place);
352
358
  if (target === undefined) return notFound();
353
359
 
354
360
  if (!(await mayChange(context, request, changer, change, place, target)))
355
361
  return refused(403, changer.admin ? adminRefusal : changers[target.kind]);
356
362
 
357
- return target;
363
+ return { changer, target };
358
364
  };
359
365
 
360
366
  /** Why the instance admin's upload is refused: their token only removes. */
@@ -365,7 +371,8 @@ export const adminRefusal = "The instance admin removes a picture but doesn't up
365
371
  * A body that names more than 1 MB is refused before it's read, and one that sends more is refused
366
372
  * once the count passes it (413). Bytes that aren't PNG, JPEG or WebP by their signature, or whose
367
373
  * header can't be read, are refused whatever their Content-Type says (415), and a picture over 1024
368
- * pixels a side is refused by its header (422).
374
+ * pixels a side is refused by its header (422). A repo its uploader no longer reads once the icon
375
+ * is written, deleted while its body came in, has the icon removed again and answers 404.
369
376
  */
370
377
  export const uploadAvatar = async (
371
378
  context: AvatarContext,
@@ -375,9 +382,10 @@ export const uploadAvatar = async (
375
382
  const length = Number(request.headers.get('content-length') ?? 0);
376
383
  if (!(length <= iconBytesMost)) return refused(413, iconTypeRefusal);
377
384
 
378
- const target = await changeable(context, request, place, 'upload');
379
- if (target instanceof Response) return target;
385
+ const allowed = await changeable(context, request, place, 'upload');
386
+ if (allowed instanceof Response) return allowed;
380
387
 
388
+ const { changer, target } = allowed;
381
389
  const bytes = await bytesUpTo(request.body, iconBytesMost);
382
390
  if (bytes === undefined) return refused(413, iconTypeRefusal);
383
391
 
@@ -391,6 +399,15 @@ export const uploadAvatar = async (
391
399
  const hash = await hashOf(bytes);
392
400
  await context.avatars.put(target.kind, target.id, { type: sniffed.type, bytes, hash });
393
401
 
402
+ // A repo deleted while its body came in may have had its icon removed by `repo.deleted` before
403
+ // this write landed. Read after the write: a delete that committed first is seen here, and one
404
+ // that commits later removes this row on its own event (#2223).
405
+ if (target.kind === 'repo' && (await targetFor(context, changer, place))?.id !== target.id) {
406
+ await context.avatars.remove(target.kind, target.id);
407
+
408
+ return notFound();
409
+ }
410
+
394
411
  return Response.json({ hash }, { headers: { 'cache-control': 'no-store' } });
395
412
  };
396
413
 
@@ -403,10 +420,10 @@ export const removeAvatar = async (
403
420
  request: Request,
404
421
  place: AvatarPlace,
405
422
  ): Promise<Response> => {
406
- const target = await changeable(context, request, place, 'remove');
407
- if (target instanceof Response) return target;
423
+ const allowed = await changeable(context, request, place, 'remove');
424
+ if (allowed instanceof Response) return allowed;
408
425
 
409
- await context.avatars.remove(target.kind, target.id);
426
+ await context.avatars.remove(allowed.target.kind, allowed.target.id);
410
427
 
411
428
  return new Response(null, { status: 204 });
412
429
  };
@@ -1,7 +1,6 @@
1
1
  import { createServerFn } from '@tanstack/react-start';
2
2
  import { getRequest } from '@tanstack/react-start/server';
3
3
  import * as Effect from 'effect/Effect';
4
- import * as Option from 'effect/Option';
5
4
  import * as Schema from 'effect/Schema';
6
5
 
7
6
  import type { TokenRecord as GitTokenRecord, TokenTarget } from '@ref0/git';
@@ -70,13 +69,12 @@ export type HostAsk = typeof HostAsk.Type;
70
69
  export type HostOperation = HostAsk['operation'];
71
70
 
72
71
  /**
73
- * What `hostCallFor` asks with: the Worker's APIs, the session key, Git's `identify`, the repo
74
- * icons a repo's delete deletes, the person's orgs, and Git's direct lists an org's tokens are read
75
- * through.
72
+ * What `hostCallFor` asks with: the Worker's APIs, the session key, Git's `identify`, the
73
+ * person's orgs, and Git's direct lists an org's tokens are read through.
76
74
  */
77
75
  export type HostContext = Pick<
78
76
  AppContext,
79
- 'api' | 'sealKey' | 'identify' | 'session' | 'avatars' | 'accounts' | 'git'
77
+ 'api' | 'sealKey' | 'identify' | 'session' | 'accounts' | 'git'
80
78
  >;
81
79
 
82
80
  /** A token of the person's, as Git's REST lists it. */
@@ -182,8 +180,6 @@ const segment = encodeURIComponent;
182
180
  const repoPath = (owner: string, repo: string) =>
183
181
  `/api/v3/repos/${segment(owner)}/${segment(repo)}`;
184
182
 
185
- const repoId = Schema.decodeUnknownOption(Schema.Struct({ id: Schema.Number }));
186
-
187
183
  /** A token place's list as host code reads it, `rows` at most, and whether more followed. */
188
184
  const listed = async (tokens: TokenLists, target: TokenTarget, rows: number) => {
189
185
  const items: GitTokenRecord[] = [];
@@ -283,32 +279,15 @@ const repoWrite = (ask: HostAsk, login: string) => {
283
279
  path: repoPath(ask.owner, ask.repo),
284
280
  json: encodeRepoSettings(ask.settings),
285
281
  };
282
+
283
+ // Its icon goes on Git's `repo.deleted`, as one deleted through the API does (`repo-icons.ts`).
284
+ case 'repo.delete':
285
+ return { method: 'DELETE', path: repoPath(ask.owner, ask.repo) };
286
286
  default:
287
287
  return undefined;
288
288
  }
289
289
  };
290
290
 
291
- /**
292
- * The repo deleted as `login`, and its icon with it, by the repo's REST `id`, read first, since the
293
- * delete answers none. A repo deleted around the app, straight through the API, keeps its icon's row.
294
- */
295
- const deleteRepo = async (
296
- context: HostContext,
297
- origin: string,
298
- login: string,
299
- place: { readonly owner: string; readonly repo: string },
300
- ) => {
301
- const path = repoPath(place.owner, place.repo);
302
- const found = await callAs(context, origin, login, { method: 'GET', path });
303
- const repo = found.ok ? Option.getOrUndefined(repoId(await found.json())) : undefined;
304
- if (!found.ok) await found.body?.cancel();
305
-
306
- const deleted = await callAs(context, origin, login, { method: 'DELETE', path });
307
- if (deleted.ok && repo !== undefined) await context.avatars.remove('repo', String(repo.id));
308
-
309
- return deleted;
310
- };
311
-
312
291
  /**
313
292
  * `ask`, made as the session's person through the host's sign-in, or refused (Q520): only a POST
314
293
  * from the app's own origin, only for a session whose token Git still takes, so sign-out ends it.
@@ -340,8 +319,6 @@ export const hostCallFor = async (
340
319
  }
341
320
 
342
321
  const login = session.login;
343
- if (ask.operation === 'repo.delete') return deleteRepo(context, origin, login, ask);
344
-
345
322
  const write = repoWrite(ask, login);
346
323
  if (write !== undefined) return callAs(context, origin, login, write);
347
324
 
@@ -0,0 +1,39 @@
1
+ import { Git, GitEvents } from '@ref0/git';
2
+ import { repoNumber } from '@ref0/github';
3
+ import * as Effect from 'effect/Effect';
4
+ import * as Schema from 'effect/Schema';
5
+
6
+ import type { Avatars } from './context.ts';
7
+
8
+ /** A deleted repo's icon the store didn't remove, by the repo's REST `id`: the run is sent again. */
9
+ class RepoIconUnremoved extends Schema.TaggedError<RepoIconUnremoved>()('RepoIconUnremoved', {
10
+ repo: Schema.Number,
11
+ cause: Schema.Unknown,
12
+ }) {}
13
+
14
+ /**
15
+ * A deleted repo's icon removed from `avatars`, however the repo was deleted: through the app, the
16
+ * API or `gh`. Git's `repo.deleted` names the repo by its internal ID, and its icon is kept under
17
+ * the REST `id` that `repoNumber` gives it. A remove that fails fails the run, which Git tries
18
+ * again as its delivery's retry says; once those tries are spent, the job stays failed, and its
19
+ * cursor holds, until the host retries or discards it (#2223).
20
+ */
21
+ export const repoIcons = (avatars: Avatars) =>
22
+ Git.addDelivery(
23
+ 'repo-icons',
24
+ GitEvents.group((on) =>
25
+ on.handle('repo.deleted', ({ events }) =>
26
+ Effect.forEach(
27
+ events,
28
+ ({ internalId }) =>
29
+ Effect.flatMap(repoNumber(internalId), (id) =>
30
+ Effect.tryPromise({
31
+ try: () => avatars.remove('repo', String(id)),
32
+ catch: (cause) => new RepoIconUnremoved({ repo: id, cause }),
33
+ }),
34
+ ),
35
+ { discard: true },
36
+ ),
37
+ ),
38
+ ),
39
+ );
@@ -25,6 +25,7 @@ import type {
25
25
  PeopleFor,
26
26
  PeopleInput,
27
27
  PeopleMembers,
28
+ PeopleEmails,
28
29
  PeopleMembership,
29
30
  PeopleOrg,
30
31
  PeopleSearch,
@@ -82,6 +83,7 @@ const refusedLookup = (input: PeopleInput): PeopleAnswer => {
82
83
  case 'teams':
83
84
  case 'team-members':
84
85
  return { items: [] };
86
+ case 'emails':
85
87
  case 'membership':
86
88
  return [];
87
89
  case 'search':
@@ -599,6 +601,15 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
599
601
  return { ...found, name: person.name, ...picture } satisfies GitHubUser;
600
602
  });
601
603
 
604
+ // A login's commit addresses, the default's, for a person the app holds: none for a login
605
+ // with no account, as its user lookup answers none.
606
+ const emails = Effect.fnUntraced(function* (input: PeopleEmails) {
607
+ const person = yield* read(() => orgs.person(input.login));
608
+ if (person === undefined) return [];
609
+
610
+ return yield* base(input);
611
+ });
612
+
602
613
  const org = Effect.fnUntraced(function* (input: PeopleOrg) {
603
614
  return (yield* read(() => orgs.org(input.org))) ? yield* orgOf(input.org) : undefined;
604
615
  });
@@ -660,6 +671,8 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
660
671
  return search(input);
661
672
  case 'members':
662
673
  return members(input);
674
+ case 'emails':
675
+ return emails(input);
663
676
  case 'membership':
664
677
  return read(() => orgs.among(input.org, input.logins));
665
678
  case 'team-members':
@@ -680,6 +693,7 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
680
693
  input: PeopleMembers | PeopleTeamMembers,
681
694
  ): Effect.Effect<Listed<GitHubUser>, GitError>;
682
695
  function lookup(input: PeopleTeams): Effect.Effect<Listed<GitHubTeam>, GitError>;
696
+ function lookup(input: PeopleEmails): Effect.Effect<readonly string[], GitError>;
683
697
  function lookup(input: PeopleMembership): Effect.Effect<readonly string[], GitError>;
684
698
  function lookup(input: PeopleTeam): Effect.Effect<GitHubTeam | undefined, GitError>;
685
699
  function lookup(input: PeopleSearch): Effect.Effect<PeopleSearchAnswer, GitError>;
package/dist/init/app.mjs CHANGED
@@ -156,7 +156,7 @@ const dialectOn = {
156
156
  const nodeHead = (choices) => {
157
157
  const queue = choices.queue === "on";
158
158
  const dialect = dialectOn[choices.records];
159
- return lines(firstImports(choices, false), dialect !== false && `${dialect}\n`, gitImport(choices), queue && "import type { MergeInput, MergePlan } from '@ref0/git';", githubImport(choices), "import * as Languages from '@ref0/github/languages';", infraImports(choices), "import { xdiff } from '@ref0/xdiff-wasm/node';", "import * as FetchHttpClient from 'effect/http/FetchHttpClient';", "import * as Layer from 'effect/Layer';", "import * as ManagedRuntime from 'effect/ManagedRuntime';", "", "import { hostLayer, peopleOver, repoListOn, runOn, tokenCallsOn } from './context/host.ts';", `import { env${partsOf(choices).length > 0 ? ", need" : ""} } from './env.ts';`, "import { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';", "import { privateReposOf } from './private-repos.ts';", "import { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';", "import { avatars } from './signin/avatars.ts';", "import { clientIpHeader } from './signin/client-ip.ts';", "import { appAuth } from './signin/host-session.ts';", "import { orgsOver } from './signin/orgs.ts';", "import { sealKey } from './signin/seal.ts';", "", "/** What the app reads from `.env`, as the server's entry reads it here. */", "export { env };", "", storeLines(choices), bucketLines(choices), "", peopleOn[choices.records], "");
159
+ return lines(firstImports(choices, false), dialect !== false && `${dialect}\n`, gitImport(choices), queue && "import type { MergeInput, MergePlan } from '@ref0/git';", githubImport(choices), "import * as Languages from '@ref0/github/languages';", infraImports(choices), "import { xdiff } from '@ref0/xdiff-wasm/node';", "import * as FetchHttpClient from 'effect/http/FetchHttpClient';", "import * as Layer from 'effect/Layer';", "import * as ManagedRuntime from 'effect/ManagedRuntime';", "", "import { hostLayer, peopleOver, repoListOn, runOn, tokenCallsOn } from './context/host.ts';", "import { repoIcons } from './context/repo-icons.ts';", `import { env${partsOf(choices).length > 0 ? ", need" : ""} } from './env.ts';`, "import { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';", "import { privateReposOf } from './private-repos.ts';", "import { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';", "import { avatars } from './signin/avatars.ts';", "import { clientIpHeader } from './signin/client-ip.ts';", "import { appAuth } from './signin/host-session.ts';", "import { orgsOver } from './signin/orgs.ts';", "import { sealKey } from './signin/seal.ts';", "", "/** What the app reads from `.env`, as the server's entry reads it here. */", "export { env };", "", storeLines(choices), bucketLines(choices), "", peopleOn[choices.records], "");
160
160
  };
161
161
  /** The app's `src/git.ts` on Node: `apps/github`'s own past its head, Node's head and parts in Cloudflare's place. */
162
162
  const nodeGit = (choices) => filled(templates.appGitNode, {
@@ -70,7 +70,7 @@ const effectImports = (choices, admins = false) => lines(admins && "import * as
70
70
  /** Who `ADMIN_TOKEN` signs in as. */
71
71
  const adminLines = lines("/** Who `ADMIN_TOKEN` signs in as: it makes repos and tokens, and never pushes. */", "const admin = { id: '_admin' };", "");
72
72
  /** How the queue writes an entry onto `main`, when there's a queue. */
73
- const mergeLines = (choices) => choices.queue === "on" && lines("/** How the queue writes an entry onto `main`: a merge commit, by whoever added it. */", "const merge = ({ entry }: MergeInput): MergePlan => ({", " method: 'merge',", " message: `Merge ${entry.source.replace(/^refs\\/heads\\//, '')}\\n`,", " author: {", " name: entry.actor.id,", " email: `${entry.actor.id}@users.noreply.git`,", " at: Date.now(),", " offset: 0,", " },", "});", "");
73
+ const mergeLines = (choices) => choices.queue === "on" && lines("/** How the queue writes an entry onto `main`: a merge commit, by whoever added it. */", "const merge = ({ entry, at }: MergeInput): MergePlan => ({", " method: 'merge',", " message: `Merge ${entry.source.replace(/^refs\\/heads\\//, '')}\\n`,", " author: {", " name: entry.actor.id,", " email: `${entry.actor.id}@users.noreply.git`,", " at,", " offset: 0,", " },", "});", "");
74
74
  /** Who may do what: the admin's and a visitor's limits, as `Policy` decides them. */
75
75
  const policyLines = lines("/**", " * Who may do what: a visitor signs in first, and the admin makes repos and tokens but never", " * pushes.", " */", "const policy = Policy.make(({ caller: { actor }, operation }) => {", " if (actor.anonymous === true) return Policy.reject({ message: 'Sign in first' });", "", " if (actor.id === admin.id && operation.kind === 'push') {", " return Policy.reject({", " message: \"The admin token can't push\",", " hint: 'Make a write token for yourself: npx ref0-git tokens create --help',", " });", " }", "", " return Policy.accept();", "});", "");
76
76
  /** What one push may carry into `Objects.layerRecords()`, as `@ref0/git` holds it. */
@@ -1,6 +1,6 @@
1
1
  // src/init/metadata.ts
2
2
  /** The version `ref0-git`, `create-ref0-git` and Git's packages release at, all at once (Q738). */
3
- const release = "0.10.0";
3
+ const release = "0.11.0";
4
4
  /** The packages the app depends on, by their folder in a checkout's `packages/`. */
5
5
  const appPackages = [
6
6
  "infra",
@@ -19,7 +19,7 @@ var templates_default = {
19
19
  "slot": "infraImport",
20
20
  "text": "import {\n layer,\n layerR2,\n layerR2Signed,\n toJobObject,\n toRecordsObject,\n} from '@ref0/infra/cloudflare';"
21
21
  },
22
- "\nimport xdiff from '@ref0/xdiff-wasm/xdiff.wasm';\nimport { env as bindings } from 'cloudflare:workers';\nimport * as FetchHttpClient from 'effect/http/FetchHttpClient';\nimport * as Layer from 'effect/Layer';\nimport * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport { hostLayer, peopleOver, repoListOn, runOn, tokenCallsOn } from './context/host.ts';\nimport type { Env } from './env.ts';\nimport { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';\nimport { privateReposOf } from './private-repos.ts';\nimport { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';\nimport { avatars } from './signin/avatars.ts';\nimport { appAuth } from './signin/host-session.ts';\nimport { orgsOver } from './signin/orgs.ts';\nimport { sealKey } from './signin/seal.ts';\n\n// SAFETY: `wrangler.jsonc` ",
22
+ "\nimport xdiff from '@ref0/xdiff-wasm/xdiff.wasm';\nimport { env as bindings } from 'cloudflare:workers';\nimport * as FetchHttpClient from 'effect/http/FetchHttpClient';\nimport * as Layer from 'effect/Layer';\nimport * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport { hostLayer, peopleOver, repoListOn, runOn, tokenCallsOn } from './context/host.ts';\nimport { repoIcons } from './context/repo-icons.ts';\nimport type { Env } from './env.ts';\nimport { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';\nimport { privateReposOf } from './private-repos.ts';\nimport { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';\nimport { avatars } from './signin/avatars.ts';\nimport { appAuth } from './signin/host-session.ts';\nimport { orgsOver } from './signin/orgs.ts';\nimport { sealKey } from './signin/seal.ts';\n\n// SAFETY: `wrangler.jsonc` ",
23
23
  {
24
24
  "slot": "safety",
25
25
  "text": "binds the objects, the bucket and D1"
@@ -31,7 +31,7 @@ var templates_default = {
31
31
  },
32
32
  {
33
33
  "slot": "queueMerge",
34
- "text": "/**\n * How the queue writes an entry's link onto `main`: a merge commit, by the person who added it, as\n * a pull request's merge button writes one, and titled as GitHub titles it for a pull request's\n * entry, keyed `pr-<number>`.\n */\nconst queueMerge = ({ entry }: MergeInput): MergePlan => {\n const [owner = ''] = entry.repo.split('/');\n const branch = entry.source.replace(/^refs\\/heads\\//, '');\n const pull = /^pr-([1-9]\\d*)$/.exec(entry.key)?.[1];\n const title =\n pull === undefined ? `Merge ${branch}` : `Merge pull request #${pull} from ${owner}/${branch}`;\n const login = entry.subject?.id ?? entry.actor.id;\n const hostname = new URL(env.APP_ORIGIN).hostname;\n\n return {\n method: 'merge',\n message: `${title}\\n`,\n author: { name: login, email: `${login}@users.noreply.${hostname}`, at: Date.now(), offset: 0 },\n };\n};\n\n"
34
+ "text": "/**\n * How the queue writes an entry's link onto `main`: a merge commit, by the person who added it, as\n * a pull request's merge button writes one, and titled as GitHub titles it for a pull request's\n * entry, keyed `pr-<number>`.\n */\nconst queueMerge = ({ entry, at }: MergeInput): MergePlan => {\n const [owner = ''] = entry.repo.split('/');\n const branch = entry.source.replace(/^refs\\/heads\\//, '');\n const pull = /^pr-([1-9]\\d*)$/.exec(entry.key)?.[1];\n const title =\n pull === undefined ? `Merge ${branch}` : `Merge pull request #${pull} from ${owner}/${branch}`;\n const login = entry.subject?.id ?? entry.actor.id;\n const hostname = new URL(env.APP_ORIGIN).hostname;\n\n return {\n method: 'merge',\n message: `${title}\\n`,\n author: { name: login, email: `${login}@users.noreply.${hostname}`, at, offset: 0 },\n };\n};\n\n"
35
35
  },
36
36
  "/** The key sessions and host sessions are sealed under, derived once an isolate from its secret. */\nexport const sessionKey = sealKey(env.SESSION_SECRET);\n\n/**\n * Who owns what, and the drop-in's people and orgs, over Better Auth's tables, which `auth` makes\n * at the first request that reads them.\n */\nexport const directory = orgsOver(async () => readyAdapter(await auth()));\n\n/** People's, orgs' and repos' pictures, in Better Auth's database, as `directory` reads it. */\nexport const pictures = avatars(async () => readyAdapter(await auth()));\n\nexport const policy = hostPolicy(directory, {\n origin: env.APP_ORIGIN,\n avatars: pictures,\n privateRepos: async (prefix, most, host) => privateReposOf(repoListOn(run))(prefix, most, host),\n repoName: async (internalId, signal) =>\n (await runtime.runPromise(RepoRecords.record(internalId), { signal }))?.name,\n});\n\n",
37
37
  {
@@ -48,7 +48,7 @@ var templates_default = {
48
48
  "slot": "releases",
49
49
  "text": " // A release's assets, in the bucket beside the packs.\n Releases.layer(),\n"
50
50
  },
51
- " // `org:` and `user:` search an owner's repos, its private ones by the policy's hook.\n Search.layer({ readableRepos: policy.readableRepos }),\n // Without it, a repo's `language` and `license` answer null.\n Languages.layer(),\n // A repo's and an org's hooks, each delivery a `fetch`, and GitHub Apps, whose hooks they send.\n // @effect-diagnostics-next-line unstableApiUsage:off\n Layer.provideMerge(Apps.layer(), Webhooks.layer().pipe(Layer.provide(FetchHttpClient.layer))),\n // GitHub's Event Streams over Git's event feeds, which a pull request's page follows.\n Streams.layer(),\n).pipe(\n Layer.provideMerge(GitHub.layer()),\n Layer.provideMerge(peopleOver(policy.people)),\n Layer.provideMerge(\n Layer.mergeAll(\n Rest.layer(),\n",
51
+ " // `org:` and `user:` search an owner's repos, its private ones by the policy's hook.\n Search.layer({ readableRepos: policy.readableRepos }),\n // Without it, a repo's `language` and `license` answer null.\n Languages.layer(),\n // A repo's and an org's hooks, each delivery a `fetch`, and GitHub Apps, whose hooks they send.\n // @effect-diagnostics-next-line unstableApiUsage:off\n Layer.provideMerge(Apps.layer(), Webhooks.layer().pipe(Layer.provide(FetchHttpClient.layer))),\n // GitHub's Event Streams over Git's event feeds, which a pull request's page follows.\n Streams.layer(),\n // A deleted repo's icon, removed however the repo was deleted.\n repoIcons(pictures),\n).pipe(\n Layer.provideMerge(GitHub.layer()),\n Layer.provideMerge(peopleOver(policy.people)),\n Layer.provideMerge(\n Layer.mergeAll(\n Rest.layer(),\n",
52
52
  {
53
53
  "slot": "lfs",
54
54
  "text": " // Git LFS, its objects in the bucket beside the packs. An upload through the Worker may use\n // `limits.cpu_ms` from wrangler.jsonc: raise both together.\n Lfs.layer({ cpuMs: 300_000 }),\n"
@@ -66,11 +66,11 @@ var templates_default = {
66
66
  appGitNode: [
67
67
  {
68
68
  "slot": "head",
69
- "text": "import {\n Git,\n Lfs,\n Merges,\n MergeQueue,\n Objects,\n RepoRecords,\n Rest,\n SignIn,\n Tokens,\n} from '@ref0/git';\nimport type { MergeInput, MergePlan } from '@ref0/git';\nimport {\n Apps,\n Deployments,\n GitHub,\n Inbox,\n Releases,\n Search,\n Streams,\n Webhooks,\n} from '@ref0/github';\nimport * as Languages from '@ref0/github/languages';\nimport {\n layer,\n layerR2,\n layerR2Signed,\n toJobObject,\n toRecordsObject,\n} from '@ref0/infra/cloudflare';\nimport xdiff from '@ref0/xdiff-wasm/xdiff.wasm';\nimport { env as bindings } from 'cloudflare:workers';\nimport * as FetchHttpClient from 'effect/http/FetchHttpClient';\nimport * as Layer from 'effect/Layer';\nimport * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport { hostLayer, peopleOver, repoListOn, runOn, tokenCallsOn } from './context/host.ts';\nimport type { Env } from './env.ts';\nimport { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';\nimport { privateReposOf } from './private-repos.ts';\nimport { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';\nimport { avatars } from './signin/avatars.ts';\nimport { appAuth } from './signin/host-session.ts';\nimport { orgsOver } from './signin/orgs.ts';\nimport { sealKey } from './signin/seal.ts';\n\n// SAFETY: `wrangler.jsonc` binds the objects, the bucket and D1 and sets `APP_ORIGIN`; the\n// secrets come from `wrangler secret put`, or `.dev.vars` locally.\nexport const env = bindings as Env;\n\nconst {\n R2_ACCOUNT_ID: accountId,\n R2_ACCESS_KEY_ID: accessKeyId,\n R2_SECRET_ACCESS_KEY: secretAccessKey,\n} = env;\n\n// With R2's S3 credentials, the bucket signs parts, and a push's pack past 64 MiB may upload to\n// it in parts, past Workers' 100 MB body.\nconst signed =\n accountId === undefined || accessKeyId === undefined || secretAccessKey === undefined\n ? undefined\n : layerR2Signed(env.PACKS, {\n accountId,\n bucket: env.PACKS_BUCKET,\n accessKeyId,\n secretAccessKey,\n });\n\nconst bucket = signed ?? layerR2(env.PACKS);\n\nconst uploads =\n signed === undefined\n ? Layer.empty\n : Layer.provide(Git.layerUploads({ above: 64 * 1024 * 1024 }), signed);\n\n"
69
+ "text": "import {\n Git,\n Lfs,\n Merges,\n MergeQueue,\n Objects,\n RepoRecords,\n Rest,\n SignIn,\n Tokens,\n} from '@ref0/git';\nimport type { MergeInput, MergePlan } from '@ref0/git';\nimport {\n Apps,\n Deployments,\n GitHub,\n Inbox,\n Releases,\n Search,\n Streams,\n Webhooks,\n} from '@ref0/github';\nimport * as Languages from '@ref0/github/languages';\nimport {\n layer,\n layerR2,\n layerR2Signed,\n toJobObject,\n toRecordsObject,\n} from '@ref0/infra/cloudflare';\nimport xdiff from '@ref0/xdiff-wasm/xdiff.wasm';\nimport { env as bindings } from 'cloudflare:workers';\nimport * as FetchHttpClient from 'effect/http/FetchHttpClient';\nimport * as Layer from 'effect/Layer';\nimport * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport { hostLayer, peopleOver, repoListOn, runOn, tokenCallsOn } from './context/host.ts';\nimport { repoIcons } from './context/repo-icons.ts';\nimport type { Env } from './env.ts';\nimport { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';\nimport { privateReposOf } from './private-repos.ts';\nimport { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';\nimport { avatars } from './signin/avatars.ts';\nimport { appAuth } from './signin/host-session.ts';\nimport { orgsOver } from './signin/orgs.ts';\nimport { sealKey } from './signin/seal.ts';\n\n// SAFETY: `wrangler.jsonc` binds the objects, the bucket and D1 and sets `APP_ORIGIN`; the\n// secrets come from `wrangler secret put`, or `.dev.vars` locally.\nexport const env = bindings as Env;\n\nconst {\n R2_ACCOUNT_ID: accountId,\n R2_ACCESS_KEY_ID: accessKeyId,\n R2_SECRET_ACCESS_KEY: secretAccessKey,\n} = env;\n\n// With R2's S3 credentials, the bucket signs parts, and a push's pack past 64 MiB may upload to\n// it in parts, past Workers' 100 MB body.\nconst signed =\n accountId === undefined || accessKeyId === undefined || secretAccessKey === undefined\n ? undefined\n : layerR2Signed(env.PACKS, {\n accountId,\n bucket: env.PACKS_BUCKET,\n accessKeyId,\n secretAccessKey,\n });\n\nconst bucket = signed ?? layerR2(env.PACKS);\n\nconst uploads =\n signed === undefined\n ? Layer.empty\n : Layer.provide(Git.layerUploads({ above: 64 * 1024 * 1024 }), signed);\n\n"
70
70
  },
71
71
  {
72
72
  "slot": "queueMerge",
73
- "text": "/**\n * How the queue writes an entry's link onto `main`: a merge commit, by the person who added it, as\n * a pull request's merge button writes one, and titled as GitHub titles it for a pull request's\n * entry, keyed `pr-<number>`.\n */\nconst queueMerge = ({ entry }: MergeInput): MergePlan => {\n const [owner = ''] = entry.repo.split('/');\n const branch = entry.source.replace(/^refs\\/heads\\//, '');\n const pull = /^pr-([1-9]\\d*)$/.exec(entry.key)?.[1];\n const title =\n pull === undefined ? `Merge ${branch}` : `Merge pull request #${pull} from ${owner}/${branch}`;\n const login = entry.subject?.id ?? entry.actor.id;\n const hostname = new URL(env.APP_ORIGIN).hostname;\n\n return {\n method: 'merge',\n message: `${title}\\n`,\n author: { name: login, email: `${login}@users.noreply.${hostname}`, at: Date.now(), offset: 0 },\n };\n};\n\n"
73
+ "text": "/**\n * How the queue writes an entry's link onto `main`: a merge commit, by the person who added it, as\n * a pull request's merge button writes one, and titled as GitHub titles it for a pull request's\n * entry, keyed `pr-<number>`.\n */\nconst queueMerge = ({ entry, at }: MergeInput): MergePlan => {\n const [owner = ''] = entry.repo.split('/');\n const branch = entry.source.replace(/^refs\\/heads\\//, '');\n const pull = /^pr-([1-9]\\d*)$/.exec(entry.key)?.[1];\n const title =\n pull === undefined ? `Merge ${branch}` : `Merge pull request #${pull} from ${owner}/${branch}`;\n const login = entry.subject?.id ?? entry.actor.id;\n const hostname = new URL(env.APP_ORIGIN).hostname;\n\n return {\n method: 'merge',\n message: `${title}\\n`,\n author: { name: login, email: `${login}@users.noreply.${hostname}`, at, offset: 0 },\n };\n};\n\n"
74
74
  },
75
75
  "/** The key sessions and host sessions are sealed under, derived once an isolate from its secret. */\nexport const sessionKey = sealKey(env.SESSION_SECRET);\n\n/**\n * Who owns what, and the drop-in's people and orgs, over Better Auth's tables, which `auth` makes\n * at the first request that reads them.\n */\nexport const directory = orgsOver(async () => readyAdapter(await auth()));\n\n/** People's, orgs' and repos' pictures, in Better Auth's database, as `directory` reads it. */\nexport const pictures = avatars(async () => readyAdapter(await auth()));\n\nexport const policy = hostPolicy(directory, {\n origin: env.APP_ORIGIN,\n avatars: pictures,\n privateRepos: async (prefix, most, host) => privateReposOf(repoListOn(run))(prefix, most, host),\n repoName: async (internalId, signal) =>\n (await runtime.runPromise(RepoRecords.record(internalId), { signal }))?.name,\n});\n\n",
76
76
  {
@@ -87,7 +87,7 @@ var templates_default = {
87
87
  "slot": "releases",
88
88
  "text": " // A release's assets, in the bucket beside the packs.\n Releases.layer(),\n"
89
89
  },
90
- " // `org:` and `user:` search an owner's repos, its private ones by the policy's hook.\n Search.layer({ readableRepos: policy.readableRepos }),\n // Without it, a repo's `language` and `license` answer null.\n Languages.layer(),\n // A repo's and an org's hooks, each delivery a `fetch`, and GitHub Apps, whose hooks they send.\n // @effect-diagnostics-next-line unstableApiUsage:off\n Layer.provideMerge(Apps.layer(), Webhooks.layer().pipe(Layer.provide(FetchHttpClient.layer))),\n // GitHub's Event Streams over Git's event feeds, which a pull request's page follows.\n Streams.layer(),\n).pipe(\n Layer.provideMerge(GitHub.layer()),\n Layer.provideMerge(peopleOver(policy.people)),\n Layer.provideMerge(\n Layer.mergeAll(\n Rest.layer(),\n",
90
+ " // `org:` and `user:` search an owner's repos, its private ones by the policy's hook.\n Search.layer({ readableRepos: policy.readableRepos }),\n // Without it, a repo's `language` and `license` answer null.\n Languages.layer(),\n // A repo's and an org's hooks, each delivery a `fetch`, and GitHub Apps, whose hooks they send.\n // @effect-diagnostics-next-line unstableApiUsage:off\n Layer.provideMerge(Apps.layer(), Webhooks.layer().pipe(Layer.provide(FetchHttpClient.layer))),\n // GitHub's Event Streams over Git's event feeds, which a pull request's page follows.\n Streams.layer(),\n // A deleted repo's icon, removed however the repo was deleted.\n repoIcons(pictures),\n).pipe(\n Layer.provideMerge(GitHub.layer()),\n Layer.provideMerge(peopleOver(policy.people)),\n Layer.provideMerge(\n Layer.mergeAll(\n Rest.layer(),\n",
91
91
  {
92
92
  "slot": "lfs",
93
93
  "text": " // Git LFS, its objects in the bucket beside the packs. An upload through the Worker may use\n // `limits.cpu_ms` from wrangler.jsonc: raise both together.\n Lfs.layer({ cpuMs: 300_000 }),\n"
@@ -219,7 +219,7 @@ var templates_default = {
219
219
  },
220
220
  {
221
221
  "slot": "merge",
222
- "text": "/** How the queue writes an entry onto `main`: a merge commit, by whoever added it. */\nconst merge = ({ entry }: MergeInput): MergePlan => ({\n method: 'merge',\n message: `Merge ${entry.source.replace(/^refs\\/heads\\//, '')}\\n`,\n author: {\n name: entry.actor.id,\n email: `${entry.actor.id}@users.noreply.git`,\n at: Date.now(),\n offset: 0,\n },\n});\n\n"
222
+ "text": "/** How the queue writes an entry onto `main`: a merge commit, by whoever added it. */\nconst merge = ({ entry, at }: MergeInput): MergePlan => ({\n method: 'merge',\n message: `Merge ${entry.source.replace(/^refs\\/heads\\//, '')}\\n`,\n author: {\n name: entry.actor.id,\n email: `${entry.actor.id}@users.noreply.git`,\n at,\n offset: 0,\n },\n});\n\n"
223
223
  },
224
224
  "/** How much of the whole host's tokens the bootstrap reads to find an admin's: pages of 200. */\nconst bootstrapReads = { pages: 10, limit: 200 };\n\n/**\n * Whether an admin in `admins` holds an active `admin` token, which retires the bootstrap. It\n * reads the whole host's tokens from `runtime`, which `policy` is part of. Past `bootstrapReads`,\n * or with no `Tokens` to read, it can't tell, and answers yes.\n */\nconst adminSignedIn = Effect.gen(function* () {\n const tokens = Context.getOption(yield* runtime.contextEffect, Tokens.Tokens);\n if (Option.isNone(tokens)) return true;\n\n let after: string | undefined;\n\n for (let read = 0; read < bootstrapReads.pages; read += 1) {\n const page =\n after === undefined\n ? { limit: bootstrapReads.limit }\n : { limit: bootstrapReads.limit, after };\n const listed = yield* tokens.value.list({ prefix: '' }, { page });\n const held = listed.items.some(\n (token) => token.scope === 'admin' && admins.has(token.subject.id),\n );\n if (held) return true;\n\n if (listed.next === undefined) return false;\n\n after = listed.next;\n }\n\n return true;\n});\n\n/**\n * What the bootstrap may do: say who it is, as `ref0-git login` asks, and mint an `admin` token for\n * a login in `admins`, until one of them holds one. Then it's retired, and `ADMIN_TOKEN` is deleted.\n */\nconst bootstrapped = (operation: Policy.Input['operation']) =>\n Effect.gen(function* () {\n if (admins.size === 0) {\n return yield* Policy.reject({\n message: 'ADMINS names no one',\n hint: \"Add your login to ADMINS in wrangler.jsonc's vars, then deploy\",\n });\n }\n\n if (yield* adminSignedIn) {\n return yield* Policy.reject({\n message: 'The bootstrap secret is retired: an admin in ADMINS signs in. Delete ADMIN_TOKEN',\n hint: 'wrangler secret delete ADMIN_TOKEN',\n });\n }\n\n if (operation.kind === 'me') return yield* Policy.accept();\n\n const minted =\n operation.kind === 'token.create' &&\n operation.scope === 'admin' &&\n 'prefix' in operation &&\n operation.prefix === '' &&\n admins.has(operation.subject.id);\n if (minted) return yield* Policy.accept();\n\n return yield* Policy.reject({\n message: \"The bootstrap secret mints only an admin's first token\",\n hint: \"npx ref0-git tokens create --prefix '' --scope admin --subject <a login in ADMINS> --show-token\",\n });\n });\n\n/** Whether `caller` is the bootstrap: `ADMIN_TOKEN` signed in, not a token. */\nconst isBootstrap = ({ actor, token }: Policy.Input['caller']) =>\n actor.anonymous !== true && actor.id === bootstrap.id && token === undefined;\n\n/** Whether `caller` holds an `admin` token that isn't an admin's in `admins`. */\nconst adminOutside = ({ actor, subject, token }: Policy.Input['caller']) =>\n token?.scope === 'admin' &&\n !admins.has(subject?.id ?? (actor.anonymous === true ? '' : actor.id));\n\n/**\n * Who may do what: a visitor signs in first, the bootstrap only mints an admin's first token, and\n * an `admin` token is only ever an admin's. Every other caller does what its token reaches.\n */\nconst policy = Policy.make(({ caller, operation }) =>\n Effect.gen(function* () {\n if (caller.actor.anonymous === true) return yield* Policy.reject({ message: 'Sign in first' });\n\n if (isBootstrap(caller)) return yield* bootstrapped(operation);\n\n if (adminOutside(caller)) {\n return yield* Policy.reject({ message: 'An admin token works only for an admin in ADMINS' });\n }\n\n const mintsAdmin = operation.kind === 'token.create' && operation.scope === 'admin';\n\n if (mintsAdmin && !admins.has(operation.subject.id)) {\n return yield* Policy.reject({ message: 'An admin token is only for an admin in ADMINS' });\n }\n\n return yield* Policy.accept();\n }),\n);\n\n",
225
225
  {
@@ -56,5 +56,5 @@ const initPacked = (name, at) => {
56
56
  * the release, or the tarball `--from-checkout` names for that package. One it wrote moves to this
57
57
  * run's spec; any other is the person's, a tarball of their own in `vendor/` too, and stays.
58
58
  */
59
- const initWrote = (name, spec) => spec === "0.10.0" || spec !== void 0 && packedPath(name).test(spec);
59
+ const initWrote = (name, spec) => spec === "0.11.0" || spec !== void 0 && packedPath(name).test(spec);
60
60
  export { catalog, contentNamed, frameworkPackages, initPacked, initWrote, nodeAppPackages, nodePackages, peerPackages, published, release, specOf, storePackages, unpacked, vercelPackages };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ref0-git",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "private": false,
5
5
  "description": "ref0-git, the CLI for a Git host built on @ref0/git, and git-remote-ref0, its remote helper",
6
6
  "license": "Apache-2.0",
@@ -24,8 +24,8 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@effect/platform-node-shared": "4.1.7",
27
- "@ref0/git": "0.10.0",
28
- "@ref0/infra": "0.10.0",
27
+ "@ref0/git": "0.11.0",
28
+ "@ref0/infra": "0.11.0",
29
29
  "diff": "9.0.0",
30
30
  "effect": "^4.1.7"
31
31
  },
@@ -34,8 +34,8 @@
34
34
  "@effect/vitest": "4.1.7",
35
35
  "@libsql/client": "0.18.0",
36
36
  "@libsql/kysely-libsql": "0.4.1",
37
- "@ref0/github": "0.10.0",
38
- "@ref0/xdiff-wasm": "0.10.0",
37
+ "@ref0/github": "0.11.0",
38
+ "@ref0/xdiff-wasm": "0.11.0",
39
39
  "@tanstack/react-start": "1.169.7",
40
40
  "@types/node": "24.19.4",
41
41
  "@types/pg": "8.23.1",