ref0-git 0.12.0 → 0.20.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 (63) hide show
  1. package/app/apps/github/generated/git-rest.ts +320 -4
  2. package/app/apps/github/generated/routeTree.gen.ts +42 -21
  3. package/app/apps/github/migrations/postgres/0001_auth.sql +8 -1
  4. package/app/apps/github/migrations/sql/0005_repo_grants.sql +10 -0
  5. package/app/apps/github/src/clients/allowed.ts +9 -4
  6. package/app/apps/github/src/clients/host-calls.ts +59 -34
  7. package/app/apps/github/src/components/repos/your-repos.tsx +57 -11
  8. package/app/apps/github/src/components/states/states.tsx +1 -19
  9. package/app/apps/github/src/components/view-tabs.tsx +6 -2
  10. package/app/apps/github/src/context/context.ts +51 -5
  11. package/app/apps/github/src/context/host.ts +72 -36
  12. package/app/apps/github/src/context/repo-grants.ts +35 -0
  13. package/app/apps/github/src/hooks/repos.ts +14 -3
  14. package/app/apps/github/src/issues/issue-list.tsx +11 -3
  15. package/app/apps/github/src/issues/issues.ts +11 -8
  16. package/app/apps/github/src/lists/across-list.tsx +358 -0
  17. package/app/apps/github/src/lists/across.ts +239 -0
  18. package/app/apps/github/src/names/owners.ts +3 -1
  19. package/app/apps/github/src/palette/targets.ts +3 -2
  20. package/app/apps/github/src/policy.ts +493 -102
  21. package/app/apps/github/src/private-repos.ts +24 -24
  22. package/app/apps/github/src/pulls/pulls.ts +2 -1
  23. package/app/apps/github/src/routes/$owner/$repo/settings/access.tsx +1 -1
  24. package/app/apps/github/src/routes/-nav.tsx +40 -12
  25. package/app/apps/github/src/routes/index.tsx +2 -1
  26. package/app/apps/github/src/routes/issues.tsx +15 -0
  27. package/app/apps/github/src/routes/orgs/$owner/-org-list.ts +31 -0
  28. package/app/apps/github/src/routes/orgs/$owner/issues.tsx +10 -3
  29. package/app/apps/github/src/routes/orgs/$owner/pulls.tsx +10 -3
  30. package/app/apps/github/src/routes/pulls.tsx +15 -0
  31. package/app/apps/github/src/seed/seed.ts +104 -52
  32. package/app/apps/github/src/server.ts +17 -7
  33. package/app/apps/github/src/settings/access-page.tsx +308 -0
  34. package/app/apps/github/src/settings/access.ts +156 -0
  35. package/app/apps/github/src/settings/settings-layout.tsx +0 -16
  36. package/app/apps/github/src/signin/approval.ts +24 -16
  37. package/app/apps/github/src/signin/auth.ts +29 -19
  38. package/app/apps/github/src/signin/orgs.ts +57 -14
  39. package/app/apps/github/src/signin/repo-grants.ts +141 -0
  40. package/app/apps/github/src/signin/revoke.ts +9 -17
  41. package/app/apps/github/src/signin/unborn.ts +33 -20
  42. package/app/pnpm-workspace.yaml +2 -2
  43. package/dist/cli/child.mjs +73 -3
  44. package/dist/cli/commands.mjs +2 -0
  45. package/dist/cli/documents.mjs +42 -2
  46. package/dist/cli/keys.mjs +431 -0
  47. package/dist/cli/main.mjs +148 -0
  48. package/dist/cli/prompt.mjs +40 -1
  49. package/dist/cli/ref0-git.mjs +4 -141
  50. package/dist/cli/setup.mjs +118 -16
  51. package/dist/cli/sign-in.mjs +1 -1
  52. package/dist/cli/tools-node.mjs +20 -0
  53. package/dist/cli/tools.mjs +12 -0
  54. package/dist/init/app.mjs +5 -2
  55. package/dist/init/cloudflare.mjs +8 -3
  56. package/dist/init/git-module.mjs +13 -8
  57. package/dist/init/metadata.mjs +1 -1
  58. package/dist/init/node.mjs +1 -1
  59. package/dist/init/template.mjs +1 -0
  60. package/dist/init/templates.mjs +24 -19
  61. package/dist/init/versions.mjs +1 -1
  62. package/package.json +5 -5
  63. package/app/apps/github/src/routes/orgs/$owner/releases.tsx +0 -8
@@ -0,0 +1,308 @@
1
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
2
+ import { LockIcon } from 'lucide-react';
3
+ import { useState, type FormEvent } from 'react';
4
+ import { toast } from 'sonner';
5
+
6
+ import { useClients } from '../clients/clients.ts';
7
+ import type { RepoPlace } from '../code/places.ts';
8
+ import { ConfirmAction } from '../components/confirm-action.tsx';
9
+ import { LoadFailed } from '../components/states/states.tsx';
10
+ import { UserAvatar } from '../components/user-avatar.tsx';
11
+ import { Alert, AlertDescription } from '../components/ui/alert.tsx';
12
+ import { Button } from '../components/ui/button.tsx';
13
+ import { Field, FieldError, FieldGroup, FieldLabel } from '../components/ui/field.tsx';
14
+ import { Input } from '../components/ui/input.tsx';
15
+ import {
16
+ Select,
17
+ SelectContent,
18
+ SelectGroup,
19
+ SelectItem,
20
+ SelectTrigger,
21
+ SelectValue,
22
+ } from '../components/ui/select.tsx';
23
+ import { Skeleton } from '../components/ui/skeleton.tsx';
24
+ import {
25
+ Table,
26
+ TableBody,
27
+ TableCell,
28
+ TableHead,
29
+ TableHeader,
30
+ TableRow,
31
+ } from '../components/ui/table.tsx';
32
+ import { useAllowed } from '../hooks/allowed.ts';
33
+ import {
34
+ accessKey,
35
+ collaboratorList,
36
+ grantRole,
37
+ removePerson,
38
+ roles,
39
+ teamList,
40
+ type Person,
41
+ type Role,
42
+ } from './access.ts';
43
+
44
+ /** A role's name, as the settings show it. */
45
+ const roleName = (role: Role) => roles.find(([each]) => each === role)?.[1] ?? role;
46
+
47
+ /** A role picked from `roles`, labelled `label`, for the field `id`. */
48
+ function RolePicker({
49
+ id,
50
+ label,
51
+ role,
52
+ disabled = false,
53
+ onPick,
54
+ }: {
55
+ readonly id: string;
56
+ readonly label: string;
57
+ readonly role: Role;
58
+ readonly disabled?: boolean;
59
+ readonly onPick: (role: Role) => void;
60
+ }) {
61
+ return (
62
+ <Select<Role>
63
+ items={roles.map(([value, name]) => ({ value, label: name }))}
64
+ value={role}
65
+ disabled={disabled}
66
+ onValueChange={(picked: Role | null) => {
67
+ if (picked !== null && picked !== role) onPick(picked);
68
+ }}
69
+ >
70
+ <SelectTrigger id={id} aria-label={label} className="w-28">
71
+ <SelectValue />
72
+ </SelectTrigger>
73
+ <SelectContent>
74
+ <SelectGroup>
75
+ {roles.map(([value, name]) => (
76
+ <SelectItem key={value} value={value}>
77
+ {name}
78
+ </SelectItem>
79
+ ))}
80
+ </SelectGroup>
81
+ </SelectContent>
82
+ </Select>
83
+ );
84
+ }
85
+
86
+ /**
87
+ * One person with access: the repo's owner reads Owner, with no control; anyone else their role,
88
+ * a picker for whoever may change it, and Remove, asked in a dialog first, for whoever may remove
89
+ * them.
90
+ */
91
+ function PersonRow({
92
+ place,
93
+ person,
94
+ changes,
95
+ removes,
96
+ }: {
97
+ readonly place: RepoPlace;
98
+ readonly person: Person;
99
+ readonly changes: boolean;
100
+ readonly removes: boolean;
101
+ }) {
102
+ const clients = useClients();
103
+ const client = useQueryClient();
104
+ const refresh = () => client.invalidateQueries({ queryKey: accessKey(place) });
105
+ const changed = useMutation({
106
+ mutationFn: (role: Role) => grantRole(clients, place, person.login, role),
107
+ onSuccess: refresh,
108
+ });
109
+ const removed = useMutation({
110
+ mutationFn: () => removePerson(clients, place, person.login),
111
+ onSuccess: refresh,
112
+ });
113
+ const owner = person.login.toLowerCase() === place.owner.toLowerCase();
114
+ const failed = changed.error ?? removed.error;
115
+
116
+ return (
117
+ <TableRow>
118
+ <TableCell className="whitespace-normal">
119
+ <div className="flex flex-col gap-1">
120
+ <span className="flex items-center gap-2">
121
+ <UserAvatar login={person.login} upload={person.upload} size="sm" account="user" />
122
+ <a href={`/${person.login}`} className="font-medium hover:underline">
123
+ {person.login}
124
+ </a>
125
+ </span>
126
+ {failed !== null && (
127
+ <Alert variant="destructive">
128
+ <AlertDescription>{failed.message}</AlertDescription>
129
+ </Alert>
130
+ )}
131
+ </div>
132
+ </TableCell>
133
+ <TableCell>
134
+ {owner ? (
135
+ <span className="text-muted-foreground">Owner</span>
136
+ ) : changes ? (
137
+ <RolePicker
138
+ id={`access-role-${person.login}`}
139
+ label={`${person.login}'s role`}
140
+ role={person.role}
141
+ disabled={changed.isPending}
142
+ onPick={(role) => changed.mutate(role)}
143
+ />
144
+ ) : (
145
+ roleName(person.role)
146
+ )}
147
+ </TableCell>
148
+ <TableCell className="text-right">
149
+ {removes && !owner && (
150
+ <ConfirmAction
151
+ label="Remove"
152
+ title={`Remove ${person.login}'s access to ${place.owner}/${place.repo}?`}
153
+ description="They can't read or change it any more, unless the host lets them some other way."
154
+ confirm="Remove access"
155
+ disabled={removed.isPending}
156
+ onConfirm={() => removed.mutate()}
157
+ />
158
+ )}
159
+ </TableCell>
160
+ </TableRow>
161
+ );
162
+ }
163
+
164
+ /** Gives someone, by their login, a role on the repo at once: there's no invitation to accept. */
165
+ function AddPerson({ place }: { readonly place: RepoPlace }) {
166
+ const clients = useClients();
167
+ const client = useQueryClient();
168
+ const [login, setLogin] = useState('');
169
+ const [role, setRole] = useState<Role>('write');
170
+ const [tried, setTried] = useState(false);
171
+ const added = useMutation({
172
+ mutationFn: () => grantRole(clients, place, login.trim(), role),
173
+ onSuccess: async () => {
174
+ toast.success(`Gave ${login.trim()} ${roleName(role)} access`);
175
+ setLogin('');
176
+ setTried(false);
177
+ await client.invalidateQueries({ queryKey: accessKey(place) });
178
+ },
179
+ });
180
+ const problem = login.trim() === '' ? 'Enter the login of someone who has signed up' : undefined;
181
+
182
+ const submit = (event: FormEvent<HTMLFormElement>) => {
183
+ event.preventDefault();
184
+ setTried(true);
185
+
186
+ if (problem === undefined && !added.isPending) added.mutate();
187
+ };
188
+
189
+ return (
190
+ <form noValidate aria-label="Add people" onSubmit={submit} className="flex flex-col gap-3">
191
+ <FieldGroup className="flex-row flex-wrap items-end gap-3">
192
+ <Field data-invalid={tried && problem !== undefined} className="min-w-48 flex-1">
193
+ <FieldLabel htmlFor="access-login">Login</FieldLabel>
194
+ <Input
195
+ id="access-login"
196
+ autoComplete="off"
197
+ aria-invalid={tried && problem !== undefined}
198
+ value={login}
199
+ onChange={(event) => setLogin(event.target.value)}
200
+ />
201
+ {tried && <FieldError>{problem}</FieldError>}
202
+ </Field>
203
+ <Field className="w-auto">
204
+ <FieldLabel htmlFor="access-role">Role</FieldLabel>
205
+ <RolePicker id="access-role" label="Role" role={role} onPick={setRole} />
206
+ </Field>
207
+ <Button type="submit" disabled={added.isPending}>
208
+ Add
209
+ </Button>
210
+ </FieldGroup>
211
+ {added.error !== null && (
212
+ <Alert variant="destructive">
213
+ <AlertDescription>{added.error.message}</AlertDescription>
214
+ </Alert>
215
+ )}
216
+ </form>
217
+ );
218
+ }
219
+
220
+ /** The owning org's teams with access, read only, drawn only where the host lists some. */
221
+ function TeamList({ place }: { readonly place: RepoPlace }) {
222
+ const teams = useQuery(teamList(useClients(), place));
223
+ if (teams.data === undefined || teams.data.length === 0) return null;
224
+
225
+ return (
226
+ <Table aria-label="Teams with access" className="border">
227
+ <TableHeader>
228
+ <TableRow>
229
+ <TableHead>Team</TableHead>
230
+ <TableHead>Role</TableHead>
231
+ </TableRow>
232
+ </TableHeader>
233
+ <TableBody>
234
+ {teams.data.map((team) => (
235
+ <TableRow key={team.slug}>
236
+ <TableCell className="font-medium">{team.name}</TableCell>
237
+ <TableCell>{roleName(team.role)}</TableCell>
238
+ </TableRow>
239
+ ))}
240
+ </TableBody>
241
+ </Table>
242
+ );
243
+ }
244
+
245
+ /**
246
+ * Who may read and write the repo, as the host's grants say (#1998): its people, the owner first,
247
+ * and its teams, with Add, a role's change and Remove for whoever the drop-in lets make each call.
248
+ * It's drawn inside the settings, which open only for the repo's admins, as GitHub's do: an admin
249
+ * whose token is too narrow for a change sees the list alone. A host that shares no repos keeps it
250
+ * to its policy, and the page says so.
251
+ */
252
+ export function AccessPage({ place }: { readonly place: RepoPlace }) {
253
+ const clients = useClients();
254
+ const access = useQuery(collaboratorList(clients, place));
255
+ const allowed = useAllowed(place);
256
+ const changes = allowed.has('collaborator.create');
257
+
258
+ return (
259
+ <section aria-label="Collaborators and teams" className="flex flex-col gap-3">
260
+ <h2 className="text-lg font-semibold">Collaborators and teams</h2>
261
+ {access.error !== null ? (
262
+ <LoadFailed message={access.error.message} />
263
+ ) : access.data === undefined ? (
264
+ <Skeleton className="h-24" />
265
+ ) : access.data.kind === 'host' ? (
266
+ <Alert>
267
+ <LockIcon />
268
+ <AlertDescription>
269
+ Access is set by the host. Who may read and write {place.owner}/{place.repo} is decided
270
+ by its policy, and can't be changed here.
271
+ </AlertDescription>
272
+ </Alert>
273
+ ) : (
274
+ <>
275
+ {changes && <AddPerson place={place} />}
276
+ <Table aria-label="People with access" className="border">
277
+ <TableHeader>
278
+ <TableRow>
279
+ <TableHead>Person</TableHead>
280
+ <TableHead>Role</TableHead>
281
+ <TableHead>
282
+ <span className="sr-only">Remove</span>
283
+ </TableHead>
284
+ </TableRow>
285
+ </TableHeader>
286
+ <TableBody>
287
+ {access.data.people.map((person) => (
288
+ <PersonRow
289
+ key={person.login}
290
+ place={place}
291
+ person={person}
292
+ changes={changes}
293
+ removes={allowed.has('collaborator.delete')}
294
+ />
295
+ ))}
296
+ </TableBody>
297
+ </Table>
298
+ {access.data.more && (
299
+ <p className="text-sm text-muted-foreground">
300
+ More people have access than are shown here.
301
+ </p>
302
+ )}
303
+ <TeamList place={place} />
304
+ </>
305
+ )}
306
+ </section>
307
+ );
308
+ }
@@ -0,0 +1,156 @@
1
+ import type { components } from '@octokit/openapi-types';
2
+ import { queryOptions } from '@tanstack/react-query';
3
+
4
+ import type { Clients } from '../clients/clients.ts';
5
+ import type { RepoPlace } from '../code/places.ts';
6
+ import { everyPage, failure } from '../hooks/answers.ts';
7
+ import { uploadOf } from '../hooks/avatars.ts';
8
+
9
+ type RestCollaborator = components['schemas']['collaborator'];
10
+
11
+ type RestTeam = components['schemas']['team'];
12
+
13
+ /** A role a repo's grant gives, as the settings name it. */
14
+ export type Role = 'read' | 'write' | 'admin';
15
+
16
+ /** The roles in the order the settings offer them, each with its name. */
17
+ export const roles: readonly (readonly [Role, string])[] = [
18
+ ['read', 'Read'],
19
+ ['write', 'Write'],
20
+ ['admin', 'Admin'],
21
+ ];
22
+
23
+ /** GitHub's `permission` a write names for each role. */
24
+ const permissionOf: Readonly<Record<Role, 'pull' | 'push' | 'admin'>> = {
25
+ read: 'pull',
26
+ write: 'push',
27
+ admin: 'admin',
28
+ };
29
+
30
+ /** The role GitHub's `role_name` or `permission` names, `read` for one it holds less than write. */
31
+ const roleOf = (name: string): Role =>
32
+ name === 'admin' ? 'admin' : name === 'write' || name === 'push' ? 'write' : 'read';
33
+
34
+ /** One person with access to the repo, as its settings list them. */
35
+ export interface Person {
36
+ readonly login: string;
37
+ /** Their uploaded picture, or `null` for none, as `uploadOf` reads the answer's `avatar_url`. */
38
+ readonly upload: string | null;
39
+ readonly role: Role;
40
+ }
41
+
42
+ /** One of the owning org's teams with access to the repo, as its settings list them. */
43
+ export interface Team {
44
+ readonly slug: string;
45
+ readonly name: string;
46
+ readonly role: Role;
47
+ }
48
+
49
+ /**
50
+ * Who the repo is shared with: its people, the owner first, as the drop-in lists them, and whether
51
+ * more were left past what's read; or `host` where the host shares no repos, whose drop-in answers
52
+ * the list 404 on a repo the settings already read.
53
+ */
54
+ export type Access =
55
+ | { readonly kind: 'host' }
56
+ | { readonly kind: 'shared'; readonly people: readonly Person[]; readonly more: boolean };
57
+
58
+ const personOf = (person: RestCollaborator): Person => ({
59
+ login: person.login,
60
+ upload: uploadOf(person.avatar_url),
61
+ role: roleOf(person.role_name),
62
+ });
63
+
64
+ const teamOf = (team: RestTeam): Team => ({
65
+ slug: team.slug,
66
+ name: team.name,
67
+ role: roleOf(team.permission),
68
+ });
69
+
70
+ /** The query key of the repo's people and teams, which each change refreshes. */
71
+ export const accessKey = (place: RepoPlace) => ['access', place.owner, place.repo] as const;
72
+
73
+ /** Thrown inside the list's read for its 404, which `collaboratorList` answers as `host`. */
74
+ class NotShared extends Error {}
75
+
76
+ /**
77
+ * Whether the repo still reads for the caller, asked now: a collaborator route's 404 means the
78
+ * host shares no repos, or no one signed up as the login, only while it does. Otherwise the repo
79
+ * is gone, or out of the caller's reach, since the page's cached read of it.
80
+ */
81
+ const stillReads = async (clients: Clients, place: RepoPlace) =>
82
+ (await clients.github.GET('/repos/{owner}/{repo}', { params: { path: place } })).response.ok;
83
+
84
+ /**
85
+ * The repo's people, every page to `pagesMost`, or `host` where the host shares no repos: a 404 on
86
+ * a repo that no longer reads fails as the 404 it is.
87
+ */
88
+ export const collaboratorList = (clients: Clients, place: RepoPlace) =>
89
+ queryOptions({
90
+ queryKey: [...accessKey(place), 'people'],
91
+ queryFn: async (): Promise<Access> => {
92
+ try {
93
+ const people = await everyPage(async (after) => {
94
+ // `after` is the drop-in's cursor, which GitHub's types don't name: a spread passes it.
95
+ const answer = await clients.github.GET('/repos/{owner}/{repo}/collaborators', {
96
+ params: { path: place, query: { ...{ per_page: 100, after } } },
97
+ });
98
+
99
+ if (answer.response.status === 404 && (await stillReads(clients, place))) {
100
+ throw new NotShared();
101
+ }
102
+
103
+ if (answer.data === undefined) throw failure("Who has access didn't load", answer);
104
+
105
+ return { rows: answer.data.map(personOf), link: answer.response.headers.get('link') };
106
+ });
107
+
108
+ return { kind: 'shared', people: people.rows, more: people.more };
109
+ } catch (error) {
110
+ if (error instanceof NotShared) return { kind: 'host' };
111
+
112
+ throw error;
113
+ }
114
+ },
115
+ });
116
+
117
+ /** The repo's teams, their first 100, which a host with no teams lists empty. */
118
+ export const teamList = (clients: Clients, place: RepoPlace) =>
119
+ queryOptions({
120
+ queryKey: [...accessKey(place), 'teams'],
121
+ queryFn: async (): Promise<readonly Team[]> => {
122
+ const answer = await clients.github.GET('/repos/{owner}/{repo}/teams', {
123
+ params: { path: place, query: { per_page: 100 } },
124
+ });
125
+ if (answer.response.status === 404) return [];
126
+
127
+ if (answer.data === undefined) throw failure("The teams didn't load", answer);
128
+
129
+ return answer.data.map(teamOf);
130
+ },
131
+ });
132
+
133
+ /**
134
+ * Gives `login` `role` on the repo, at once, as the drop-in grants it: a new person or a changed
135
+ * role alike. A login no one signed up as says so, while the repo still reads.
136
+ */
137
+ export const grantRole = async (clients: Clients, place: RepoPlace, login: string, role: Role) => {
138
+ const answer = await clients.github.PUT('/repos/{owner}/{repo}/collaborators/{username}', {
139
+ params: { path: { ...place, username: login } },
140
+ body: { permission: permissionOf[role] },
141
+ });
142
+
143
+ if (answer.response.status === 404 && (await stillReads(clients, place))) {
144
+ throw new Error(`No one has signed up as ${login}`);
145
+ }
146
+
147
+ if (!answer.response.ok) throw failure(`${login} wasn't given access`, answer);
148
+ };
149
+
150
+ /** Takes `login`'s access to the repo away. */
151
+ export const removePerson = async (clients: Clients, place: RepoPlace, login: string) => {
152
+ const answer = await clients.github.DELETE('/repos/{owner}/{repo}/collaborators/{username}', {
153
+ params: { path: { ...place, username: login } },
154
+ });
155
+ if (!answer.response.ok) throw failure(`${login}'s access wasn't removed`, answer);
156
+ };
@@ -98,19 +98,3 @@ export function SettingsLayout({
98
98
  </div>
99
99
  );
100
100
  }
101
-
102
- /** Who may read and write the repo: the host's policy decides, and nothing here changes it. */
103
- export function AccessPage({ place }: { readonly place: RepoPlace }) {
104
- return (
105
- <section aria-label="Collaborators and teams" className="flex flex-col gap-3">
106
- <h2 className="text-lg font-semibold">Collaborators and teams</h2>
107
- <Alert>
108
- <LockIcon />
109
- <AlertDescription>
110
- Access is set by the host. Who may read and write {place.owner}/{place.repo} is decided by
111
- its policy, and can't be changed here.
112
- </AlertDescription>
113
- </Alert>
114
- </section>
115
- );
116
- }
@@ -1,11 +1,12 @@
1
1
  import * as Effect from 'effect/Effect';
2
+ import * as Option from 'effect/Option';
2
3
  import type {
3
4
  ApprovalPageInput,
4
5
  Caller,
5
6
  ConfirmApprovalPage,
6
7
  DeviceApproval,
7
8
  DeviceCodePage,
8
- Result,
9
+ GitError,
9
10
  } from '@ref0/git';
10
11
 
11
12
  import { ownerProblem } from '../names/owners.ts';
@@ -18,8 +19,11 @@ export interface StarterApprovalOptions {
18
19
  readonly auth: () => Promise<StarterAuth>;
19
20
  /** The key prompts and sessions' Git tokens are sealed under, from `SESSION_SECRET`. */
20
21
  readonly sealKey: Promise<CryptoKey>;
21
- /** Git's `identify`: whether the session's Git token still names its person. */
22
- readonly identify: (request: Request) => Promise<Result<Caller>>;
22
+ /**
23
+ * Git's `identify`, in the page's own fiber: whether the session's Git token still names its
24
+ * person.
25
+ */
26
+ readonly identify: (request: Request) => Effect.Effect<Caller, GitError>;
23
27
  /** `APP_ORIGIN`: the one origin a decision is posted from. */
24
28
  readonly origin: string;
25
29
  /** How long a token the person approves lasts. */
@@ -92,35 +96,40 @@ const fromApp = (request: Request, options: StarterApprovalOptions) =>
92
96
  request.method === 'POST' && request.headers.get('origin') === new URL(options.origin).origin;
93
97
 
94
98
  /** The session's login, when the browser has one and its Git token still names that person. */
95
- const signedIn = async (input: ConfirmApprovalPage, options: StarterApprovalOptions) => {
96
- const session = await sessionOf(input.request, options);
99
+ const signedIn = Effect.fnUntraced(function* (
100
+ input: ConfirmApprovalPage,
101
+ options: StarterApprovalOptions,
102
+ ) {
103
+ const session = yield* Effect.promise(() => sessionOf(input.request, options));
97
104
  if (session === undefined) return undefined;
98
105
 
99
106
  const headers = { authorization: `Bearer ${session.token}` };
100
- const held = await options.identify(new Request(options.origin, { headers }));
101
- const actor = held.kind === 'success' ? held.value.actor : undefined;
107
+ const held = yield* Effect.option(options.identify(new Request(options.origin, { headers })));
108
+ const actor = Option.isSome(held) ? held.value.actor : undefined;
102
109
 
103
110
  return actor?.anonymous !== true && actor?.id === session.login ? session.login : undefined;
104
- };
111
+ });
105
112
 
106
113
  /**
107
114
  * A code posted from the Code field, by a live session: Git's prompt, sealed for that person. A
108
115
  * link or another site's form that names a code gets the empty Code field, so no one is shown a
109
116
  * code they didn't type.
110
117
  */
111
- const shown = async (
118
+ const shown = Effect.fnUntraced(function* (
112
119
  input: ConfirmApprovalPage,
113
120
  prompt: DeviceApproval,
114
121
  options: StarterApprovalOptions,
115
- ) => {
116
- const login = fromApp(input.request, options) ? await signedIn(input, options) : undefined;
122
+ ) {
123
+ const login = fromApp(input.request, options) ? yield* signedIn(input, options) : undefined;
117
124
  if (login === undefined) return seeOther(codePage);
118
125
 
119
126
  const grant = { login, days: options.tokenDays };
120
- const sealed = await sealPrompt(await options.sealKey, prompt, grant, Date.now());
127
+ const sealed = yield* Effect.promise(async () =>
128
+ sealPrompt(await options.sealKey, prompt, grant, Date.now()),
129
+ );
121
130
 
122
131
  return seeOther(codePageWith({ prompt: sealed }));
123
- };
132
+ });
124
133
 
125
134
  /**
126
135
  * A decision posted from the Card: from the app's own page, by a live session, with the sealed
@@ -140,7 +149,7 @@ const decided = Effect.fnUntraced(function* (
140
149
  );
141
150
  if (!fromApp(input.request, options)) return signInFirst;
142
151
 
143
- const login = yield* Effect.promise(() => signedIn(input, options));
152
+ const login = yield* signedIn(input, options);
144
153
  if (login === undefined) return signInFirst;
145
154
 
146
155
  const opened = yield* Effect.promise(async () =>
@@ -185,8 +194,7 @@ export const starterApprovalPage = (options: StarterApprovalOptions) =>
185
194
  input.request.method === 'POST'
186
195
  ? new URLSearchParams(yield* Effect.promise(() => input.request.text()))
187
196
  : undefined;
188
- if (form?.has('decision') !== true)
189
- return yield* Effect.promise(() => shown(input, prompt, options));
197
+ if (form?.has('decision') !== true) return yield* shown(input, prompt, options);
190
198
 
191
199
  return yield* decided(input, prompt, form, options);
192
200
  });
@@ -1,5 +1,5 @@
1
1
  import type { D1Database } from '@cloudflare/workers-types';
2
- import type { TokenCalls } from '@ref0/git';
2
+ import type { Tokens } from '@ref0/git';
3
3
  import { passkey } from '@better-auth/passkey';
4
4
  import {
5
5
  type Auth,
@@ -12,6 +12,8 @@ import {
12
12
  import { APIError, createAuthMiddleware, getSessionFromCtx } from 'better-auth/api';
13
13
  import { organization } from 'better-auth/plugins/organization';
14
14
  import { username } from 'better-auth/plugins/username';
15
+ import * as Effect from 'effect/Effect';
16
+ import * as Exit from 'effect/Exit';
15
17
  import * as Option from 'effect/Option';
16
18
  import * as Schema from 'effect/Schema';
17
19
  import type { Dialect } from 'kysely';
@@ -31,6 +33,7 @@ import {
31
33
  import { revokeRetrying } from './revoke.ts';
32
34
  import { open, seal } from './seal.ts';
33
35
  import { avatarTable, avatars } from './avatars.ts';
36
+ import { repoGrantTable } from './repo-grants.ts';
34
37
  import { type Unborn, forgetUnborn } from './unborn.ts';
35
38
 
36
39
  /** A Kysely dialect, and the SQL it speaks, as Better Auth takes one: libSQL's, or Postgres's. */
@@ -74,10 +77,13 @@ export interface StarterAuthOptions {
74
77
  readonly signUp: boolean;
75
78
  /** The key a session's Git token is sealed under in D1. */
76
79
  readonly key: Promise<CryptoKey>;
77
- /** Git's tokens, which each session mints its own from, and revokes at its end. */
78
- readonly tokens: TokenCalls;
80
+ /**
81
+ * Git's tokens, which each session mints its own from, and revokes at its end, each an Effect
82
+ * Better Auth's hook runs.
83
+ */
84
+ readonly tokens: Tokens.Tokens['Service'];
79
85
  /** Whether Git holds a repo under `<login>/`, or couldn't say: such a person is never forgotten. */
80
- readonly ownsRepos: (login: string) => Promise<boolean>;
86
+ readonly ownsRepos: (login: string) => Effect.Effect<boolean>;
81
87
  /**
82
88
  * The header Better Auth keys its rate limits on, which only the platform sets: Cloudflare's
83
89
  * `cf-connecting-ip`, or on Node `clientIpHeader`, which the server sets from the caller's
@@ -440,6 +446,7 @@ export const starterAuth = (options: StarterAuthOptions): Auth => {
440
446
  }),
441
447
  ownerNames(),
442
448
  avatarTable(),
449
+ repoGrantTable(),
443
450
  // A credential ID names one passkey only, since the plugin finds a sign-in's passkey by it.
444
451
  // Its schema only indexes the column, so this makes it unique, in each dialect's migration.
445
452
  {
@@ -579,16 +586,18 @@ export const starterAuth = (options: StarterAuthOptions): Auth => {
579
586
  const login = loginOf(namedOf(user));
580
587
  if (context === undefined || login === undefined) return;
581
588
 
582
- const made = await options.tokens.create(
583
- { prefix: '' },
584
- {
585
- scope: 'write',
586
- subject: { id: login },
587
- expiresAt: session.expiresAt,
588
- key: sessionKeyOf(session.id),
589
- },
589
+ const made = await Effect.runPromiseExit(
590
+ options.tokens.create(
591
+ { prefix: '' },
592
+ {
593
+ scope: 'write',
594
+ subject: { id: login },
595
+ expiresAt: session.expiresAt,
596
+ key: sessionKeyOf(session.id),
597
+ },
598
+ ),
590
599
  );
591
- if (made.kind !== 'success') return;
600
+ if (Exit.isFailure(made)) return;
592
601
 
593
602
  const gitToken = await seal(await options.key, purpose, made.value.secret);
594
603
  const held = await context.adapter.update({
@@ -602,9 +611,10 @@ export const starterAuth = (options: StarterAuthOptions): Auth => {
602
611
  // Only a row with no token takes it; `returning` answers nothing for one it skipped.
603
612
  if (held !== null && held !== undefined) return;
604
613
 
605
- const revoked = await revokeRetrying(() => options.tokens.revoke(made.value.id));
606
- if (revoked.kind !== 'success')
607
- console.error(`Git didn't revoke token ${made.value.id}`);
614
+ const revoked = await Effect.runPromiseExit(
615
+ revokeRetrying(options.tokens.revoke(made.value.id)),
616
+ );
617
+ if (Exit.isFailure(revoked)) console.error(`Git didn't revoke token ${made.value.id}`);
608
618
  },
609
619
  },
610
620
  delete: {
@@ -613,10 +623,10 @@ export const starterAuth = (options: StarterAuthOptions): Auth => {
613
623
  // on it, and one still to come is refused until the session would end.
614
624
  const key = sessionKeyOf(session.id);
615
625
  const until = session.expiresAt;
616
- const revoked = await revokeRetrying(() =>
617
- options.tokens.revokeKey({ prefix: '' }, key, { until }),
626
+ const revoked = await Effect.runPromiseExit(
627
+ revokeRetrying(options.tokens.revokeKey({ prefix: '' }, key, { until })),
618
628
  );
619
- if (revoked.kind !== 'success') console.error(`Git didn't revoke session token ${key}`);
629
+ if (Exit.isFailure(revoked)) console.error(`Git didn't revoke session token ${key}`);
620
630
  },
621
631
  },
622
632
  },