ref0-git 0.12.0 → 0.14.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 (36) hide show
  1. package/app/apps/github/generated/git-rest.ts +152 -3
  2. package/app/apps/github/migrations/postgres/0001_auth.sql +8 -1
  3. package/app/apps/github/migrations/sql/0005_repo_grants.sql +10 -0
  4. package/app/apps/github/src/clients/allowed.ts +9 -4
  5. package/app/apps/github/src/components/repos/your-repos.tsx +57 -11
  6. package/app/apps/github/src/context/context.ts +45 -2
  7. package/app/apps/github/src/context/repo-grants.ts +35 -0
  8. package/app/apps/github/src/hooks/repos.ts +14 -3
  9. package/app/apps/github/src/policy.ts +485 -92
  10. package/app/apps/github/src/routes/$owner/$repo/settings/access.tsx +1 -1
  11. package/app/apps/github/src/routes/index.tsx +2 -1
  12. package/app/apps/github/src/settings/access-page.tsx +308 -0
  13. package/app/apps/github/src/settings/access.ts +156 -0
  14. package/app/apps/github/src/settings/settings-layout.tsx +0 -16
  15. package/app/apps/github/src/signin/auth.ts +2 -0
  16. package/app/apps/github/src/signin/orgs.ts +57 -14
  17. package/app/apps/github/src/signin/repo-grants.ts +141 -0
  18. package/app/pnpm-workspace.yaml +2 -2
  19. package/dist/cli/child.mjs +73 -3
  20. package/dist/cli/commands.mjs +2 -0
  21. package/dist/cli/documents.mjs +42 -2
  22. package/dist/cli/keys.mjs +431 -0
  23. package/dist/cli/main.mjs +148 -0
  24. package/dist/cli/prompt.mjs +40 -1
  25. package/dist/cli/ref0-git.mjs +4 -141
  26. package/dist/cli/setup.mjs +115 -13
  27. package/dist/cli/sign-in.mjs +1 -1
  28. package/dist/cli/tools-node.mjs +20 -0
  29. package/dist/cli/tools.mjs +12 -0
  30. package/dist/init/app.mjs +3 -1
  31. package/dist/init/git-module.mjs +11 -6
  32. package/dist/init/metadata.mjs +1 -1
  33. package/dist/init/template.mjs +1 -0
  34. package/dist/init/templates.mjs +15 -10
  35. package/dist/init/versions.mjs +1 -1
  36. package/package.json +5 -5
@@ -1,4 +1,4 @@
1
- import { accept, gitError, Policy, Rules, reject } from '@ref0/git';
1
+ import { gitError, Policy, Rules } from '@ref0/git';
2
2
  import type {
3
3
  ActorId,
4
4
  AuthorizeInput,
@@ -6,25 +6,37 @@ import type {
6
6
  GitError,
7
7
  InternalRepoId,
8
8
  NamedActor,
9
+ Operation,
9
10
  PushRule,
10
11
  RefName,
12
+ RepoAccess,
11
13
  RepoName,
12
14
  TokenInfo,
13
15
  TokenOperation,
14
16
  } from '@ref0/git';
15
- import { defaultOrg, defaultPeople, People } from '@ref0/github';
17
+ import {
18
+ defaultOrg,
19
+ defaultPeople,
20
+ defaultUser,
21
+ People,
22
+ RepoGrants,
23
+ repoGrantsMost,
24
+ } from '@ref0/github';
16
25
  import type {
17
26
  GitHubAuthorization,
18
27
  GitHubAuthorize,
19
28
  GitHubOrg,
20
29
  GitHubReadableRepos,
21
30
  GitHubReadableReposInput,
31
+ GitHubRepoOperation,
22
32
  GitHubTeam,
23
33
  GitHubUser,
24
34
  PeopleAnswer,
25
35
  PeopleFor,
26
36
  PeopleInput,
27
37
  PeopleMembers,
38
+ PeopleAccounts,
39
+ PeopleAccountsAnswer,
28
40
  PeopleEmails,
29
41
  PeopleMembership,
30
42
  PeopleOrg,
@@ -35,17 +47,30 @@ import type {
35
47
  PeopleTeams,
36
48
  PeopleUser,
37
49
  PeopleViewer,
50
+ GrantRepo,
51
+ PersonGrant,
52
+ RepoGrantsInput,
53
+ RepoGrantsList,
54
+ RepoGrantsMovedAnswer,
55
+ RepoGrantsPut,
56
+ RepoGrantsRemove,
57
+ RepoGrantsRole,
58
+ RepoGrantsShared,
59
+ RepoGrantsMoved,
60
+ RepoRole,
61
+ TeamGrant,
38
62
  } from '@ref0/github';
39
63
  import * as Clock from 'effect/Clock';
40
64
  import * as Effect from 'effect/Effect';
41
65
 
42
66
  import { type StarterApprovalOptions, starterApprovalPage } from './signin/approval.ts';
43
- import type { Account, Avatars, Membership } from './context/context.ts';
67
+ import type { Account, Avatars, Grant, Grants, Membership } from './context/context.ts';
44
68
  import { admin } from './names/owners.ts';
45
69
 
46
70
  export { admin };
47
71
 
48
72
  import { orgTokenView, type Orgs } from './signin/orgs.ts';
73
+ import { grantsPage } from './signin/repo-grants.ts';
49
74
 
50
75
  /**
51
76
  * The host's say, as a starter writes it: anyone reads a public repo, a person signed in owns the
@@ -63,18 +88,27 @@ interface Listed<Item> {
63
88
  readonly next?: string;
64
89
  }
65
90
 
66
- /** A membership the policy read, and when, by the `Clock`. */
67
- interface KeptMembership {
91
+ /** A membership or a grant the policy read, and when, by the `Clock`. */
92
+ interface Kept<A> {
68
93
  readonly at: number;
69
- readonly answer: Promise<Membership | undefined>;
94
+ readonly answer: Promise<A>;
70
95
  }
71
96
 
72
97
  /**
73
- * How long, in milliseconds, a membership read is kept on its actor: past one request's reads, and
74
- * well under a stream's 9-second heartbeat, whose check then reads it again.
98
+ * How long, in milliseconds, a membership or a grant read is kept on its actor: past one request's
99
+ * reads, and well under a stream's 9-second heartbeat, whose check then reads it again.
75
100
  */
76
101
  const membershipLife = 1_000;
77
102
 
103
+ /**
104
+ * The Git store reads one shared repo's name takes: `git.ts`' `repoName` is `RepoRecords.record`,
105
+ * which reads the record, its catalogue entry and the record again.
106
+ */
107
+ export const nameReads = 3;
108
+
109
+ /** The store calls `readableRepos` may make for each owner past `most`, as its contract says. */
110
+ const ownerCallsPast = 6;
111
+
78
112
  /** What a people lookup answers a token that no longer holds: no one, and nothing listed. */
79
113
  const refusedLookup = (input: PeopleInput): PeopleAnswer => {
80
114
  switch (input.kind) {
@@ -86,6 +120,8 @@ const refusedLookup = (input: PeopleInput): PeopleAnswer => {
86
120
  case 'emails':
87
121
  case 'membership':
88
122
  return [];
123
+ case 'accounts':
124
+ return {};
89
125
  case 'search':
90
126
  return { found: [], incomplete: false };
91
127
  default:
@@ -97,7 +133,7 @@ const refusedLookup = (input: PeopleInput): PeopleAnswer => {
97
133
  * A read of the starter's own tables, as the directory's Effect: one that rejects fails closed as
98
134
  * Git's `UNAVAILABLE`, in fixed words, so neither D1's error nor its words reach the drop-in.
99
135
  */
100
- const read = <A>(run: () => Promise<A>): Effect.Effect<A, GitError> =>
136
+ const read = <A>(run: (signal: AbortSignal) => Promise<A>): Effect.Effect<A, GitError> =>
101
137
  Effect.tryPromise({
102
138
  try: run,
103
139
  catch: () => gitError('UNAVAILABLE', "The starter's directory can't be read now"),
@@ -123,6 +159,33 @@ const reaches = (input: PeopleOrgs, org: string) => {
123
159
  return under.startsWith(token.prefix) || token.prefix.startsWith(under);
124
160
  };
125
161
 
162
+ /** Each role's rank: a role holds what every role below it holds. */
163
+ const roleRank: Readonly<Record<RepoRole, number>> = { read: 0, write: 1, admin: 2 };
164
+
165
+ /** Whether a grant of `role` holds what `needs` asks. */
166
+ const roleHolds = (role: RepoRole | undefined, needs: RepoRole) =>
167
+ role !== undefined && roleRank[role] >= roleRank[needs];
168
+
169
+ /**
170
+ * The role a grant needs for one of Git's operations (#1998): `read` to read and fetch, `admin` to
171
+ * change or delete the repo, set its private refs or lift its file rules on a push, and `write`
172
+ * for the rest, a push, its objects, a fork's sync and the merge queue among them.
173
+ */
174
+ const gitNeeds = (kind: Operation['kind']): RepoRole => {
175
+ switch (kind) {
176
+ case 'read':
177
+ case 'fetch':
178
+ return 'read';
179
+ case 'repo.update':
180
+ case 'repo.delete':
181
+ case 'refs.private':
182
+ case 'files.allow':
183
+ return 'admin';
184
+ default:
185
+ return 'write';
186
+ }
187
+ };
188
+
126
189
  /** What anyone signed in may do on a public repo they don't own, as on GitHub. */
127
190
  const contributions: ReadonlySet<string> = new Set([
128
191
  'issue.create',
@@ -147,10 +210,20 @@ const authorsOwn: ReadonlySet<string> = new Set([
147
210
  'review.resolve',
148
211
  ]);
149
212
 
150
- const signInFirstRefusal = { message: 'Sign in first' };
213
+ /**
214
+ * The role a grant needs for one of the drop-in's operations (#1998): `read` for a read and for
215
+ * what anyone signed in may do on a public repo, `admin` for a hook's and for a change to the
216
+ * repo's collaborators, and `write` for the rest.
217
+ */
218
+ const gitHubNeeds = (kind: GitHubRepoOperation['kind']): RepoRole => {
219
+ if (kind.startsWith('hook.')) return 'admin';
151
220
 
152
- /** `signInFirstRefusal`, as the drop-in's half answers it. */
153
- const signInFirst = reject(signInFirstRefusal);
221
+ if (kind.startsWith('collaborator.') && kind !== 'collaborator.read') return 'admin';
222
+
223
+ return kind.endsWith('.read') || contributions.has(kind) ? 'read' : 'write';
224
+ };
225
+
226
+ const signInFirstRefusal = { message: 'Sign in first' };
154
227
 
155
228
  /**
156
229
  * The owner a token reaches past its subject's own login, if any: a repo token's repo's owner, by
@@ -179,21 +252,24 @@ const orgCoverage = (operation: TokenOperation) => {
179
252
  return org !== '' && !org.includes('/') ? org : undefined;
180
253
  };
181
254
 
182
- /** Who a call's token holds for, a token's caller or the host's own sign-in. */
255
+ /**
256
+ * Who a call's token holds for, a token's caller or the host's own sign-in, and the repo the call
257
+ * names, when it names one.
258
+ */
183
259
  interface Holder {
184
260
  readonly actor: AuthorizeInput['actor'] | Caller['actor'];
185
261
  readonly subject?: ActorId;
186
262
  readonly token?: TokenInfo;
263
+ readonly repo?: RepoAccess | undefined;
187
264
  }
188
265
 
189
266
  /**
190
267
  * The refusal of a token whose person left the org it's over, or joined it again after it was
191
268
  * made: it works for nothing, public reads included, as GitHub's inactive token (Q740).
192
269
  */
193
- const tokenEndedRefusal = { message: "This token's person no longer holds the org it's over" };
194
-
195
- /** `tokenEndedRefusal`, as the drop-in's half answers it. */
196
- const tokenEnded = reject(tokenEndedRefusal);
270
+ const tokenEndedRefusal = {
271
+ message: "This token's person no longer holds the org or the shared repo it's over",
272
+ };
197
273
 
198
274
  /** At most `most` of an owner's private repos the caller may read, as the owner index asks. */
199
275
  export type ReadableRepos = (
@@ -211,6 +287,11 @@ export interface HostPolicy {
211
287
  readonly readableRepos: ReadableRepos;
212
288
  }
213
289
 
290
+ /** The host's policy over its repos' grants, with the drop-in's `RepoGrants` over the same rows. */
291
+ export interface GrantsPolicy extends HostPolicy {
292
+ readonly repoGrants: RepoGrants.RepoGrants['Service'];
293
+ }
294
+
214
295
  /**
215
296
  * At most `most` of the private repos under `prefix`, and whether it holds more past them, listed
216
297
  * through `host`, the drop-in's unchecked `repos.list` (Q788).
@@ -230,6 +311,9 @@ export interface Pictures {
230
311
  readonly avatars: Pick<Avatars, 'hash'>;
231
312
  }
232
313
 
314
+ /** The internal ID of the repo named `name` now, `undefined` when none is. */
315
+ export type RepoIdOf = (name: RepoName, signal: AbortSignal) => Promise<InternalRepoId | undefined>;
316
+
233
317
  /** The name `internalId`'s repo has now, `undefined` once none holds it. */
234
318
  export type RepoNameOf = (
235
319
  internalId: InternalRepoId,
@@ -238,14 +322,21 @@ export type RepoNameOf = (
238
322
 
239
323
  /**
240
324
  * What the starter's policy reads past its orgs: its `Pictures`, both or neither,
241
- * `privateRepos`, which lists an owner's private repos for the owner index's hook, and
242
- * `repoName`, which the drop-in's owner check reads. With no `privateRepos`, it names no private
243
- * repo, and with no `repoName`, the owner check reads the name the request named.
325
+ * `privateRepos`, which lists an owner's private repos for the owner index's hook, `repoName`,
326
+ * which the drop-in's owner check reads, and `grants`, its repos' grants to people (#1998), with
327
+ * `repoId`, which finds the repo a token over one names. With no `privateRepos`, it names no
328
+ * private repo; with no `repoName`, the owner check reads the name the request named; and with no
329
+ * `grants`, only an owner reaches a private repo.
244
330
  */
245
331
  export type HostPolicyOptions = (
246
332
  | Pictures
247
333
  | { readonly origin?: undefined; readonly avatars?: undefined }
248
- ) & { readonly privateRepos?: PrivateRepos; readonly repoName?: RepoNameOf };
334
+ ) & {
335
+ readonly privateRepos?: PrivateRepos;
336
+ readonly repoName?: RepoNameOf;
337
+ readonly grants?: Grants;
338
+ readonly repoId?: RepoIdOf;
339
+ };
249
340
 
250
341
  /**
251
342
  * What of `owner`'s repos `token` covers: every one, those under the token's longer prefix, its
@@ -263,16 +354,31 @@ const coverOf = (owner: string, token: GitHubReadableReposInput['token']) => {
263
354
  return token.prefix.startsWith(under) ? { prefix: token.prefix } : undefined;
264
355
  };
265
356
 
357
+ /** What of an owner's repos a token covers, as `coverOf` answers it. */
358
+ type Cover = NonNullable<ReturnType<typeof coverOf>>;
359
+
360
+ /** Whether `cover` covers the repo `name`. */
361
+ const covers = (cover: Cover, name: RepoName) =>
362
+ cover.repo === undefined ? name.startsWith(cover.prefix) : name === cover.repo;
363
+
266
364
  /**
267
- * The starter's policy over `orgs`: who owns what, by an org's `member` rows, and the drop-in's
268
- * directory of people and orgs, by Better Auth's tables, with what `options` adds.
365
+ * The starter's policy over `orgs`: who owns what, by an org's `member` rows, and who else may do
366
+ * what on a repo, by its grants, and the drop-in's directory of people and orgs, by Better Auth's
367
+ * tables, with what `options` adds. With `grants`, it answers the drop-in's `RepoGrants` too.
269
368
  */
270
- export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPolicy => {
369
+ export function hostPolicy(
370
+ orgs: Orgs,
371
+ options: HostPolicyOptions & { readonly grants: Grants },
372
+ ): GrantsPolicy;
373
+ export function hostPolicy(orgs: Orgs, options?: HostPolicyOptions): HostPolicy;
374
+ export function hostPolicy(orgs: Orgs, options: HostPolicyOptions = {}): HostPolicy | GrantsPolicy {
271
375
  const {
272
376
  origin,
273
377
  avatars,
274
378
  privateRepos = async () => ({ names: [], more: false }),
275
379
  repoName,
380
+ grants,
381
+ repoId,
276
382
  } = options;
277
383
 
278
384
  /**
@@ -288,6 +394,21 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
288
394
  return { avatar_url: `${origin}/icons/${encodeURIComponent(login)}?v=${hash}` };
289
395
  };
290
396
 
397
+ /**
398
+ * A person who signed up, under the login they hold however `login` spells it, by the name they
399
+ * go by, as GitHub names someone who set one, so a merge the drop-in makes for them is authored
400
+ * under it, and with their upload's `avatar_url`. None for a login no one signed up as.
401
+ */
402
+ const personShown = Effect.fnUntraced(function* (login: string) {
403
+ const person = yield* read(() => orgs.person(login));
404
+ if (person === undefined) return undefined;
405
+
406
+ const found = yield* defaultUser(person.login);
407
+ const picture = yield* read(() => pictureOf(person.login, { kind: 'user', id: person.id }));
408
+
409
+ return { ...found, name: person.name, ...picture } satisfies GitHubUser;
410
+ });
411
+
291
412
  /** An org as `defaultOrg` makes it, with its upload's `avatar_url` when it has one. */
292
413
  const orgOf = Effect.fnUntraced(function* (login: string) {
293
414
  const org = yield* defaultOrg(login);
@@ -297,28 +418,68 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
297
418
  });
298
419
 
299
420
  /**
300
- * Each org's membership of an actor, kept on the actor Git's `identify` made for the request, so
301
- * a page that checks 32 of an org's repos asks D1 once (Q739), and for `membershipLife` at most.
302
- * `identify` and `appAuth` make a new actor for each request, but a stream holds one caller for
303
- * as long as it's open and asks `authorize` again before each batch and each heartbeat, so an
304
- * answer kept for the request alone would let a member who left go on reading it (Q740).
421
+ * `ask`'s answer about `actor` under `key`, kept on the actor Git's `identify` made for the
422
+ * request, so a page that checks 32 of an org's repos asks D1 once (Q739), and for
423
+ * `membershipLife` at most. `identify` and `appAuth` make a new actor for each request, but a
424
+ * stream holds one caller for as long as it's open and asks `authorize` again before each batch
425
+ * and each heartbeat, so an answer kept for the request alone would let a member who left, or a
426
+ * collaborator removed, go on reading it (Q740).
305
427
  */
306
- const memberships = new WeakMap<ActorId, Map<string, KeptMembership>>();
428
+ const keptOn = <A>(
429
+ kept: WeakMap<ActorId, Map<string, Kept<A>>>,
430
+ actor: ActorId,
431
+ key: string,
432
+ ask: () => Promise<A>,
433
+ ) =>
434
+ Effect.flatMap(Clock.currentTimeMillis, (now) => {
435
+ const held = kept.get(actor) ?? new Map<string, Kept<A>>();
436
+ kept.set(actor, held);
437
+
438
+ const found = held.get(key);
439
+ if (found !== undefined && now - found.at < membershipLife) return read(() => found.answer);
440
+
441
+ const answer = ask();
442
+ held.set(key, { at: now, answer });
443
+
444
+ return read(() => answer);
445
+ });
446
+
447
+ const memberships = new WeakMap<ActorId, Map<string, Kept<Membership | undefined>>>();
307
448
 
308
449
  /** `actor`'s membership of the org `org`, asked once a request, and again past its life. */
309
450
  const membershipOf = (actor: ActorId, org: string) =>
310
- Effect.flatMap(Clock.currentTimeMillis, (now) => {
311
- const held = memberships.get(actor) ?? new Map<string, KeptMembership>();
312
- memberships.set(actor, held);
451
+ keptOn(memberships, actor, org, () => orgs.membership(org, actor.id));
452
+
453
+ const keptGrants = new WeakMap<ActorId, Map<string, Kept<Grant | undefined>>>();
313
454
 
314
- const kept = held.get(org);
315
- if (kept !== undefined && now - kept.at < membershipLife) return read(() => kept.answer);
455
+ /**
456
+ * `actor`'s grant on the repo `internalId`, kept as a membership is, so a stream's next check
457
+ * stops a collaborator whose grant was removed. None on a host with no grants.
458
+ */
459
+ const grantOf = (actor: ActorId, internalId: InternalRepoId) => {
460
+ if (grants === undefined) return Effect.succeed(undefined);
316
461
 
317
- const answer = orgs.membership(org, actor.id);
318
- held.set(org, { at: now, answer });
462
+ return keptOn(keptGrants, actor, internalId, async () => {
463
+ const person = await orgs.person(actor.id);
319
464
 
320
- return read(() => answer);
465
+ return person === undefined ? undefined : grants.get(internalId, person.id);
321
466
  });
467
+ };
468
+
469
+ /**
470
+ * The internal ID of the repo `name`: `access`'s, when that's the repo the call names, or else
471
+ * `repoId`'s read of it. None with no `repoId`.
472
+ */
473
+ const repoIdOf = (
474
+ name: RepoName,
475
+ access: RepoAccess | undefined,
476
+ ): Effect.Effect<InternalRepoId | undefined, GitError> => {
477
+ if (access?.name === name) return Effect.succeed(access.internalId);
478
+
479
+ return repoId === undefined
480
+ ? Effect.succeed(undefined)
481
+ : read((signal) => repoId(name, signal));
482
+ };
322
483
 
323
484
  /** Whether `actor` belongs to the org `org`, in any role. */
324
485
  const belongs = (actor: ActorId, org: string) =>
@@ -326,12 +487,14 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
326
487
 
327
488
  /**
328
489
  * Whether a call's token holds (Q740): one over an owner other than its subject holds only while
329
- * the subject belongs to that owner, by a membership no newer than the token, so a leave refuses
330
- * it at once and a rejoin doesn't bring it back. Within the second of a join, as the same
331
- * Worker's clock reads both, a token made then holds. A session's token, the host's own sign-in
332
- * and a token over the subject's own login hold as they are.
490
+ * the subject belongs to that owner, by a membership no newer than the token, or, over one repo,
491
+ * while the subject holds a grant on it no newer than the token (#1998). So a leave or a grant's
492
+ * removal refuses it at once, and a rejoin or a grant made again doesn't bring it back. Within
493
+ * the second of a join or a grant, as the same Worker's clock reads both, a token made then
494
+ * holds. A session's token, the host's own sign-in and a token over the subject's own login hold
495
+ * as they are.
333
496
  */
334
- const tokenHolds = Effect.fnUntraced(function* ({ actor, subject, token }: Holder) {
497
+ const tokenHolds = Effect.fnUntraced(function* ({ actor, subject, token, repo }: Holder) {
335
498
  if (token === undefined || actor.anonymous === true) return true;
336
499
 
337
500
  const person = subject !== undefined && subject.id !== actor.id ? subject : actor;
@@ -339,8 +502,14 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
339
502
  if (owner === undefined || owner === person.id) return true;
340
503
 
341
504
  const membership = yield* membershipOf(person, owner);
505
+ if (membership !== undefined && membership.since <= token.createdAt) return true;
506
+
507
+ if (token.repo === undefined) return false;
342
508
 
343
- return membership !== undefined && membership.since <= token.createdAt;
509
+ const internalId = yield* repoIdOf(token.repo, repo);
510
+ const grant = internalId === undefined ? undefined : yield* grantOf(person, internalId);
511
+
512
+ return grant !== undefined && grant.createdAt <= token.createdAt;
344
513
  });
345
514
 
346
515
  /** Whether `actor` owns what `owner` holds: their own login's, and each org's they belong to. */
@@ -378,7 +547,7 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
378
547
  ) {
379
548
  const { caller, operation, repo } = input;
380
549
  const { actor } = caller;
381
- if (!(yield* tokenHolds(caller))) return yield* Policy.reject(tokenEndedRefusal);
550
+ if (!(yield* tokenHolds({ ...caller, repo }))) return yield* Policy.reject(tokenEndedRefusal);
382
551
 
383
552
  // Who the caller is, at Git's `/me`: theirs, once their token holds.
384
553
  if (operation.kind === 'me') {
@@ -436,7 +605,7 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
436
605
  operation.kind === 'token.list' ||
437
606
  operation.kind === 'token.revoke'
438
607
  ) {
439
- return yield* tokenRule(actor, operation);
608
+ return yield* tokenRule(actor, operation, repo);
440
609
  }
441
610
 
442
611
  // A fork lands under its holder, from any repo the person may read.
@@ -446,9 +615,16 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
446
615
  : Policy.reject({ message: 'Fork under your own login' });
447
616
  }
448
617
 
449
- const mine = 'repo' in operation && (yield* owns(actor, ownerOf(operation.repo)));
618
+ if (!('repo' in operation)) return yield* Policy.reject({ message: 'Not yours' });
619
+
620
+ if (yield* owns(actor, ownerOf(operation.repo))) return yield* Policy.accept();
450
621
 
451
- return yield* mine ? Policy.accept() : Policy.reject({ message: 'Not yours' });
622
+ // A grant decides by the repo the call acts on, by its internal ID, so a rename keeps it.
623
+ const grant = repo === undefined ? undefined : yield* grantOf(actor, repo.internalId);
624
+
625
+ return yield* roleHolds(grant?.role, gitNeeds(operation.kind))
626
+ ? Policy.accept()
627
+ : Policy.reject({ message: 'Not yours' });
452
628
  });
453
629
 
454
630
  /**
@@ -459,12 +635,14 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
459
635
  * a revoke of another's token there, which is theirs (Q521);
460
636
  * - a create over an org they belong to at that moment: all its repos, `<org>/`, or one of
461
637
  * them, never a deeper prefix;
638
+ * - a create over one repo they hold a grant on, in any role (#1998);
462
639
  * - a list, or a revoke of another's token, over an org they're an owner or an admin of,
463
640
  * read at this call.
464
641
  */
465
642
  const tokenRule = Effect.fnUntraced(function* (
466
643
  actor: NamedActor | ActorId,
467
644
  operation: TokenOperation,
645
+ access: RepoAccess | undefined,
468
646
  ) {
469
647
  if (operation.kind === 'token.revoke' && operation.subject.id === actor.id) {
470
648
  return yield* Policy.accept();
@@ -480,9 +658,16 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
480
658
  const membership = org === undefined ? undefined : yield* membershipOf(actor, org);
481
659
 
482
660
  if (operation.kind === 'token.create') {
483
- return yield* membership === undefined
661
+ if (membership !== undefined) return yield* Policy.accept();
662
+
663
+ const internalId =
664
+ operation.repo === undefined ? undefined : yield* repoIdOf(operation.repo, access);
665
+ const grant = internalId === undefined ? undefined : yield* grantOf(actor, internalId);
666
+
667
+ return yield* grant === undefined
484
668
  ? Policy.reject({
485
- message: 'Only tokens over your own repos, or an org you belong to',
669
+ message:
670
+ 'Only tokens over your own repos, an org you belong to, or a repo shared with you',
486
671
  hint: "Over an org, a token covers all of its repos or one: '<org>/' or '<org>/<repo>'",
487
672
  })
488
673
  : Policy.accept();
@@ -502,24 +687,25 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
502
687
  * author's alone, as on GitHub: not the owner's, nor the admin's unless they wrote it. An org's members, teams and hooks are its
503
688
  * own members' alone, as GitHub shows outsiders only public members and this host keeps none
504
689
  * public (#644). A person's own account, such as their notifications, is theirs once signed in.
505
- * Everything else is the owner's and the admin's. A token that no longer holds gets nothing, as
506
- * in Git's, its own account included.
690
+ * Everything else is the owner's and the admin's, and a collaborator's whose role holds it
691
+ * (#1998). A token that no longer holds gets nothing, as in Git's, its own account included.
507
692
  */
508
693
  const authorizeGitHub: GitHubAuthorize = Effect.fnUntraced(function* (
509
694
  input: GitHubAuthorization,
510
695
  ) {
511
696
  const { actor, operation } = input;
512
- if (!(yield* tokenHolds(input))) return tokenEnded;
697
+ if (!(yield* tokenHolds(input))) return yield* Policy.reject(tokenEndedRefusal);
513
698
 
514
699
  if ('org' in operation) {
515
- if (actor.anonymous === true) return signInFirst;
700
+ if (actor.anonymous === true) return yield* Policy.reject(signInFirstRefusal);
516
701
 
517
- return actor.id === admin.id || (yield* owns(actor, operation.org))
518
- ? accept()
519
- : reject({ message: "Only the org's members may do this" });
702
+ return yield* actor.id === admin.id || (yield* owns(actor, operation.org))
703
+ ? Policy.accept()
704
+ : Policy.reject({ message: "Only the org's members may do this" });
520
705
  }
521
706
 
522
- if (!('repo' in operation)) return actor.anonymous === true ? signInFirst : accept();
707
+ if (!('repo' in operation))
708
+ return yield* actor.anonymous === true ? Policy.reject(signInFirstRefusal) : Policy.accept();
523
709
 
524
710
  // Visibility as Git's read of the repo answered this caller. A repo operation that reaches
525
711
  // here without it is refused as a private repo's, for a caller outside TypeScript.
@@ -527,48 +713,87 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
527
713
  // A hook's settings and deliveries are its owner's, even on a public repo: they hold payloads
528
714
  // signed for its receiver, and the receiver's answers.
529
715
  const ownersOnly = operation.kind.startsWith('hook.');
530
- if (visible && operation.kind.endsWith('.read') && !ownersOnly) return accept();
716
+ if (visible && operation.kind.endsWith('.read') && !ownersOnly) return yield* Policy.accept();
531
717
 
532
- if (actor.anonymous === true) return signInFirst;
718
+ if (actor.anonymous === true) return yield* Policy.reject(signInFirstRefusal);
533
719
 
534
720
  // GitHub lets only a review's author edit its body, so no one else does here, the admin
535
721
  // included: the drop-in asks it as the author only once its own read shows the caller wrote it.
536
722
  if (operation.kind === 'review.edit') {
537
- return operation.asAuthor === true
538
- ? accept()
539
- : reject({ message: "Only a review's author can edit its body" });
723
+ return yield* operation.asAuthor === true
724
+ ? Policy.accept()
725
+ : Policy.reject({ message: "Only a review's author can edit its body" });
540
726
  }
541
727
 
542
- if (actor.id === admin.id || (visible && contributions.has(operation.kind))) return accept();
728
+ if (actor.id === admin.id || (visible && contributions.has(operation.kind)))
729
+ return yield* Policy.accept();
543
730
 
544
731
  // The drop-in asks an issue's edit, or a comment's or a review comment's edit or delete, as its
545
732
  // author only once its own read shows the caller wrote it (Q857), so the caller's token
546
733
  // holding the repo is all that's left to ask.
547
- if (operation.asAuthor === true && authorsOwn.has(operation.kind)) return accept();
734
+ if (operation.asAuthor === true && authorsOwn.has(operation.kind))
735
+ return yield* Policy.accept();
736
+
737
+ if (yield* owns(actor, yield* ownerNow(operation.repo, input))) return yield* Policy.accept();
548
738
 
549
- return (yield* owns(actor, yield* ownerNow(operation.repo, input)))
550
- ? accept()
551
- : reject({ message: 'Only the owner may do this' });
739
+ const grant =
740
+ input.repo === undefined ? undefined : yield* grantOf(actor, input.repo.internalId);
741
+
742
+ return yield* roleHolds(grant?.role, gitHubNeeds(operation.kind))
743
+ ? Policy.accept()
744
+ : Policy.reject({ message: 'Only the owner may do this' });
745
+ });
746
+
747
+ /**
748
+ * The repos shared with `actor` that `cover` covers, at most `most`, by their names now, from the
749
+ * first of their grants: only as many as the hook's `most` and 6 store calls name, at
750
+ * `nameReads` a name, and `more` once others are left unread.
751
+ */
752
+ const sharedNames = Effect.fnUntraced(function* (actor: ActorId, cover: Cover, most: number) {
753
+ const none = { names: [], more: false };
754
+ if (grants === undefined || repoName === undefined) return none;
755
+
756
+ const person = yield* read(() => orgs.person(actor.id));
757
+ if (person === undefined) return none;
758
+
759
+ const named = Math.min(grantsPage, Math.floor((most + ownerCallsPast) / nameReads));
760
+ const page = yield* read(() => grants.shared(person.id, { limit: named }));
761
+ const names = yield* Effect.forEach(
762
+ page.items,
763
+ (internalId) => read((signal) => repoName(internalId, signal)),
764
+ { concurrency: 8 },
765
+ );
766
+ const covered = names.filter(
767
+ (name): name is RepoName => name !== undefined && covers(cover, name),
768
+ );
769
+
770
+ return {
771
+ names: covered.slice(0, most),
772
+ more: covered.length > most || page.next !== undefined,
773
+ };
552
774
  });
553
775
 
554
776
  /**
555
777
  * The owner index's hook: every private repo under `owner` for its owner, a person's own login
556
- * or an org they belong to, and the admin, as `authorizeGitHub` lets them read it; none for
557
- * anyone else. Only those the caller's token covers, listed under what it covers alone, so a
558
- * token's own repos get the checks, and neither the names nor `more` show how many it can't read.
559
- * A token over one repo names it alone, which `authorize` holds as any name. Git lists them newest
560
- * made first, since it keeps no time a repo was updated.
778
+ * or an org they belong to, and the admin, as `authorizeGitHub` lets them read it; for anyone
779
+ * else, those of the owner's repos shared with them (#1998). Only those the caller's token
780
+ * covers, listed under what it covers alone, so a token's own repos get the checks, and neither
781
+ * the names nor `more` show how many it can't read. A token over one repo names it alone, which
782
+ * `authorize` holds as any name. Git lists them newest made first, since it keeps no time a repo
783
+ * was updated.
561
784
  */
562
785
  const readableRepos: ReadableRepos = Effect.fnUntraced(function* (input) {
563
786
  const { actor, owner, most, token, host } = input;
564
787
  const none = { names: [], more: false };
565
788
  if (actor.anonymous === true || !(yield* tokenHolds(input))) return none;
566
789
 
567
- if (actor.id !== admin.id && !(yield* owns(actor, owner))) return none;
568
-
569
790
  const cover = coverOf(owner, token);
570
791
  if (cover === undefined || most <= 0) return none;
571
792
 
793
+ if (actor.id !== admin.id && !(yield* owns(actor, owner))) {
794
+ return yield* sharedNames(actor, cover, most);
795
+ }
796
+
572
797
  if (cover.repo !== undefined) return { names: [cover.repo], more: false };
573
798
 
574
799
  const { prefix } = cover;
@@ -581,25 +806,14 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
581
806
  * once it's made, and a person's orgs, an org's members and which of some logins are its members
582
807
  * from `member` rows, each shaped as the drop-in's default shapes it: a person through its
583
808
  * calls, and an org as `defaultOrg` makes it, repos or none, as anyone may see a person who
584
- * signed up. The starter keeps no two-factor record, so a two-factor filter lists no one, and
809
+ * signed up. A login or an org asked in any case answers under the one it's held as, as GitHub
810
+ * does (Q853). The starter keeps no two-factor record, so a two-factor filter lists no one, and
585
811
  * teams are the default's: none.
586
812
  */
587
813
  const people: PeopleFor = (context) => {
588
814
  const base = defaultPeople(context);
589
815
 
590
- // A person by the name they go by, as GitHub names someone who set one: a merge the drop-in
591
- // makes for them is authored under it.
592
- const user = Effect.fnUntraced(function* (input: PeopleUser) {
593
- const person = yield* read(() => orgs.person(input.login));
594
- if (person === undefined) return undefined;
595
-
596
- const found = yield* base(input);
597
- if (found === undefined) return undefined;
598
-
599
- const picture = yield* read(() => pictureOf(input.login, { kind: 'user', id: person.id }));
600
-
601
- return { ...found, name: person.name, ...picture } satisfies GitHubUser;
602
- });
816
+ const user = (input: PeopleUser) => personShown(input.login);
603
817
 
604
818
  // A login's commit addresses, the default's, for a person the app holds: none for a login
605
819
  // with no account, as its user lookup answers none.
@@ -607,11 +821,37 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
607
821
  const person = yield* read(() => orgs.person(input.login));
608
822
  if (person === undefined) return [];
609
823
 
610
- return yield* base(input);
824
+ return yield* base({ ...input, login: person.login });
825
+ });
826
+
827
+ // The default's accounts for a page's addresses, for a person the app holds, as its user
828
+ // lookup answers them: by the name they go by and their picture, and none for a login with no
829
+ // account. Each login is looked up once, however many addresses name it.
830
+ const accounts = Effect.fnUntraced(function* (input: PeopleAccounts) {
831
+ const found = Object.entries(yield* base(input));
832
+ const logins = [...new Set(found.map(([, account]) => account.login))];
833
+ const users = new Map(
834
+ yield* Effect.forEach(
835
+ logins,
836
+ (login) =>
837
+ Effect.map(user({ ...input, kind: 'user', login }), (each) => [login, each] as const),
838
+ { concurrency: 'unbounded' },
839
+ ),
840
+ );
841
+
842
+ return Object.fromEntries(
843
+ found.flatMap(([email, account]) => {
844
+ const each = users.get(account.login);
845
+
846
+ return each === undefined ? [] : [[email, each] as const];
847
+ }),
848
+ ) satisfies PeopleAccountsAnswer;
611
849
  });
612
850
 
613
851
  const org = Effect.fnUntraced(function* (input: PeopleOrg) {
614
- return (yield* read(() => orgs.org(input.org))) ? yield* orgOf(input.org) : undefined;
852
+ const slug = yield* read(() => orgs.org(input.org));
853
+
854
+ return slug === undefined ? undefined : yield* orgOf(slug);
615
855
  });
616
856
 
617
857
  const members = Effect.fnUntraced(function* (input: PeopleMembers) {
@@ -673,6 +913,8 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
673
913
  return members(input);
674
914
  case 'emails':
675
915
  return emails(input);
916
+ case 'accounts':
917
+ return accounts(input);
676
918
  case 'membership':
677
919
  return read(() => orgs.among(input.org, input.logins));
678
920
  case 'team-members':
@@ -694,6 +936,7 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
694
936
  ): Effect.Effect<Listed<GitHubUser>, GitError>;
695
937
  function lookup(input: PeopleTeams): Effect.Effect<Listed<GitHubTeam>, GitError>;
696
938
  function lookup(input: PeopleEmails): Effect.Effect<readonly string[], GitError>;
939
+ function lookup(input: PeopleAccounts): Effect.Effect<PeopleAccountsAnswer, GitError>;
697
940
  function lookup(input: PeopleMembership): Effect.Effect<readonly string[], GitError>;
698
941
  function lookup(input: PeopleTeam): Effect.Effect<GitHubTeam | undefined, GitError>;
699
942
  function lookup(input: PeopleSearch): Effect.Effect<PeopleSearchAnswer, GitError>;
@@ -708,7 +951,157 @@ export const hostPolicy = (orgs: Orgs, options: HostPolicyOptions = {}): HostPol
708
951
  return People.make(lookup);
709
952
  };
710
953
 
711
- return { authorize, authorizeGitHub, people, readableRepos };
954
+ const policy = { authorize, authorizeGitHub, people, readableRepos };
955
+
956
+ return grants === undefined
957
+ ? policy
958
+ : { ...policy, repoGrants: repoGrantsOver(orgs, grants, personShown, repoName) };
959
+ }
960
+
961
+ /** A refusal of a team's grant: the starter has no teams. */
962
+ const noTeam = () => gitError('NOT_FOUND', 'This host has no teams');
963
+
964
+ /** A refusal of a login no one signed up as. */
965
+ const noPerson = (login: string) => gitError('NOT_FOUND', `No one signed up as ${login}`);
966
+
967
+ /**
968
+ * The starter's `RepoGrants` (#1998), over `grants`, the rows its policy reads, so the drop-in's
969
+ * collaborators' routes show and change what decides: people's grants alone, as the starter has
970
+ * no teams, so a repo's teams list none, a team's grant is refused as no such team, and a move
971
+ * drops none, however often it's asked. The repo's owner, a person or any member of its org, is
972
+ * its admin, and can't be its collaborator too. A person is shown as the policy's directory shows
973
+ * them, and a shared repo by the name `repoName` reads now, leaving out a repo none holds.
974
+ */
975
+ const repoGrantsOver = (
976
+ orgs: Orgs,
977
+ grants: Grants,
978
+ personShown: (login: string) => Effect.Effect<GitHubUser | undefined, GitError>,
979
+ repoName: RepoNameOf | undefined,
980
+ ): RepoGrants.RepoGrants['Service'] => {
981
+ const personOf = (login: string) => read(() => orgs.person(login));
982
+
983
+ const listPeople = Effect.fnUntraced(function* (input: RepoGrantsList) {
984
+ const page = yield* read(() =>
985
+ grants.list(input.repo.internalId, { after: input.page?.after, limit: input.page?.limit }),
986
+ );
987
+ const logins = yield* read(() => orgs.loginsById(page.items.map((row) => row.userId)));
988
+ const found = yield* Effect.forEach(
989
+ page.items,
990
+ ({ userId, role }) => {
991
+ const login = logins.get(userId);
992
+ if (login === undefined) return Effect.succeed(undefined);
993
+
994
+ return Effect.map(personShown(login), (user) =>
995
+ user === undefined ? undefined : ({ user, role } satisfies PersonGrant),
996
+ );
997
+ },
998
+ { concurrency: 8 },
999
+ );
1000
+ const items = found.filter((each) => each !== undefined);
1001
+
1002
+ return (
1003
+ page.next === undefined ? { items } : { items, next: page.next }
1004
+ ) satisfies Listed<PersonGrant>;
1005
+ });
1006
+
1007
+ const roleOf = Effect.fnUntraced(function* (input: RepoGrantsRole) {
1008
+ const owner = ownerOf(input.repo.name);
1009
+ if (owner === input.login) return 'admin' satisfies RepoRole;
1010
+
1011
+ const person = yield* personOf(input.login);
1012
+ if (person === undefined || owner === undefined) return undefined;
1013
+
1014
+ if (person.login === owner) return 'admin' satisfies RepoRole;
1015
+
1016
+ const membership = yield* read(() => orgs.membership(owner, person.login));
1017
+ if (membership !== undefined) return 'admin' satisfies RepoRole;
1018
+
1019
+ const grant = yield* read(() => grants.get(input.repo.internalId, person.id));
1020
+
1021
+ return grant?.role;
1022
+ });
1023
+
1024
+ const change = Effect.fnUntraced(function* (input: RepoGrantsPut | RepoGrantsRemove) {
1025
+ const { to } = input;
1026
+ if (to.kind === 'team') return yield* Effect.fail(noTeam());
1027
+
1028
+ const person = yield* personOf(to.login);
1029
+ if (person === undefined) return yield* Effect.fail(noPerson(to.login));
1030
+
1031
+ // The login the person holds, as `to.login` may name them in another case.
1032
+ if (input.kind === 'put' && person.login === ownerOf(input.repo.name)) {
1033
+ return yield* Effect.fail(
1034
+ gitError('INVALID_ARGUMENT', "A repo's owner is its admin, never its collaborator"),
1035
+ );
1036
+ }
1037
+
1038
+ const { internalId } = input.repo;
1039
+ if (input.kind === 'remove') return yield* read(() => grants.remove(internalId, person.id));
1040
+
1041
+ const put = yield* read(() => grants.put(internalId, person.id, input.role));
1042
+
1043
+ if (put === 'full') {
1044
+ return yield* Effect.fail(
1045
+ gitError('RESOURCE_EXHAUSTED', `A repo holds at most ${repoGrantsMost} grants`),
1046
+ );
1047
+ }
1048
+ });
1049
+
1050
+ const shared = Effect.fnUntraced(function* (input: RepoGrantsShared) {
1051
+ const person = yield* personOf(input.login);
1052
+ if (person === undefined || repoName === undefined)
1053
+ return { items: [] } satisfies Listed<GrantRepo>;
1054
+
1055
+ const page = yield* read(() =>
1056
+ grants.shared(person.id, { after: input.page?.after, limit: input.page?.limit }),
1057
+ );
1058
+ const named = yield* Effect.forEach(
1059
+ page.items,
1060
+ (internalId) =>
1061
+ Effect.map(
1062
+ read((signal) => repoName(internalId, signal)),
1063
+ (name) => (name === undefined ? undefined : ({ name, internalId } satisfies GrantRepo)),
1064
+ ),
1065
+ { concurrency: 8 },
1066
+ );
1067
+ const under = input.owner === undefined ? undefined : `${input.owner}/`;
1068
+ const items = named.filter(
1069
+ (repo): repo is GrantRepo =>
1070
+ repo !== undefined && (under === undefined || repo.name.startsWith(under)),
1071
+ );
1072
+
1073
+ return (
1074
+ page.next === undefined ? { items } : { items, next: page.next }
1075
+ ) satisfies Listed<GrantRepo>;
1076
+ });
1077
+
1078
+ function answer(
1079
+ input: RepoGrantsList & { readonly of: 'person' },
1080
+ ): Effect.Effect<Listed<PersonGrant>, GitError>;
1081
+ function answer(
1082
+ input: RepoGrantsList & { readonly of: 'team' },
1083
+ ): Effect.Effect<Listed<TeamGrant>, GitError>;
1084
+ function answer(input: RepoGrantsRole): Effect.Effect<RepoRole | undefined, GitError>;
1085
+ function answer(input: RepoGrantsPut | RepoGrantsRemove): Effect.Effect<void, GitError>;
1086
+ function answer(input: RepoGrantsShared): Effect.Effect<Listed<GrantRepo>, GitError>;
1087
+ function answer(input: RepoGrantsMoved): Effect.Effect<RepoGrantsMovedAnswer, GitError>;
1088
+ function answer(input: RepoGrantsInput): Effect.Effect<unknown, GitError> {
1089
+ switch (input.kind) {
1090
+ case 'list':
1091
+ return input.of === 'person' ? listPeople(input) : Effect.succeed({ items: [] });
1092
+ case 'role':
1093
+ return roleOf(input);
1094
+ case 'put':
1095
+ case 'remove':
1096
+ return change(input);
1097
+ case 'shared':
1098
+ return shared(input);
1099
+ case 'moved':
1100
+ return Effect.succeed({ dropped: [] } satisfies RepoGrantsMovedAnswer);
1101
+ }
1102
+ }
1103
+
1104
+ return RepoGrants.make(answer);
712
1105
  };
713
1106
 
714
1107
  /** One of the host's push rules, beside the refs it covers on every repo. */