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
@@ -0,0 +1,141 @@
1
+ import type { InternalRepoId } from '@ref0/git';
2
+ import { repoGrantsMost, type RepoRole } from '@ref0/github';
3
+ import type { BetterAuthPlugin, DBAdapter } from 'better-auth';
4
+
5
+ import type { Grants, GrantsFrom } from '../context/context.ts';
6
+
7
+ /**
8
+ * A repo's grants to people (#1998), in `AUTH_DB` beside the people they're to, through Better
9
+ * Auth's adapter, as the avatars are. A row is one person's role on one repo, under the repo's
10
+ * internal ID, so a rename or a transfer keeps it and a repo made under a name another left never
11
+ * finds it, and under the person's row ID, whose delete takes their grants with it. The starter has
12
+ * no teams, so it keeps no team's grant.
13
+ */
14
+
15
+ /** Better Auth's model for the grants, and the table it keeps them in. */
16
+ const model = 'repoGrant';
17
+
18
+ /** The most rows one page of a repo's grants, or of a person's, holds. */
19
+ export const grantsPage = 100;
20
+
21
+ /**
22
+ * The plugin that gives Better Auth's adapter `repoGrant`: the repo's internal ID, the person's row
23
+ * ID, the role, and when the grant was first made, which a role's change keeps. Each of the two IDs
24
+ * is indexed, for a repo's list and its delete, and for a person's shared repos.
25
+ */
26
+ export const repoGrantTable = () =>
27
+ ({
28
+ id: 'repo-grants',
29
+ schema: {
30
+ [model]: {
31
+ modelName: 'repo_grant',
32
+ fields: {
33
+ repo: { type: 'string', required: true, index: true },
34
+ userId: {
35
+ type: 'string',
36
+ required: true,
37
+ index: true,
38
+ references: { model: 'user', field: 'id', onDelete: 'cascade' },
39
+ },
40
+ role: { type: 'string', required: true },
41
+ createdAt: { type: 'date', required: true },
42
+ },
43
+ },
44
+ },
45
+ }) satisfies BetterAuthPlugin;
46
+
47
+ interface Row {
48
+ readonly repo: InternalRepoId;
49
+ readonly userId: string;
50
+ readonly role: RepoRole;
51
+ readonly createdAt: Date | number | string;
52
+ }
53
+
54
+ const rowId = (repo: InternalRepoId, userId: string) => `${repo}:${userId}`;
55
+
56
+ const by = (repo: InternalRepoId, userId: string) => [{ field: 'id', value: rowId(repo, userId) }];
57
+
58
+ /** A page of `rows`, read one past `limit`, by the ID `idOf` gives the last one kept. */
59
+ const paged = <A>(rows: readonly A[], limit: number, idOf: (row: A) => string) => {
60
+ const items = rows.slice(0, limit);
61
+ const last = items.at(-1);
62
+
63
+ return rows.length > limit && last !== undefined ? { items, next: idOf(last) } : { items };
64
+ };
65
+
66
+ /** The page `from` asks for, read one past it, so the page knows whether more follow. */
67
+ const window = (field: string, from: GrantsFrom) => {
68
+ const limit = Math.min(Math.max(1, from.limit ?? grantsPage), grantsPage);
69
+ const where =
70
+ from.after === undefined ? [] : [{ field, operator: 'gt' as const, value: from.after }];
71
+
72
+ return { limit, where, read: { limit: limit + 1, sortBy: { field, direction: 'asc' as const } } };
73
+ };
74
+
75
+ /** The grants over Better Auth's adapter, which `adapter` gives once its schema check settled. */
76
+ export const grantsOver = (adapter: () => Promise<DBAdapter>): Grants => ({
77
+ get: async (repo, userId) => {
78
+ const row = await (await adapter()).findOne<Row>({ model, where: by(repo, userId) });
79
+
80
+ return row === null
81
+ ? undefined
82
+ : { role: row.role, createdAt: new Date(row.createdAt).getTime() };
83
+ },
84
+
85
+ put: async (repo, userId, role) => {
86
+ const held = await adapter();
87
+ const where = by(repo, userId);
88
+ if ((await held.updateMany({ model, where, update: { role } })) > 0) return 'put';
89
+
90
+ // A new grant, past a count of the repo's: two made at once may each count the same rows, so
91
+ // the repo holds at most one more than the bound for each made together.
92
+ const count = await held.count({ model, where: [{ field: 'repo', value: repo }] });
93
+ if (count >= repoGrantsMost) return 'full';
94
+
95
+ const data = { repo, userId, role, createdAt: new Date() };
96
+
97
+ // Two first grants at once: the one whose insert loses changes the role instead, and an insert
98
+ // that failed for any other reason, with no row to change, fails it.
99
+ try {
100
+ await held.create({ model, data: { id: rowId(repo, userId), ...data }, forceAllowId: true });
101
+ } catch (error) {
102
+ if ((await held.updateMany({ model, where, update: { role } })) === 0) throw error;
103
+ }
104
+
105
+ return 'put';
106
+ },
107
+
108
+ remove: async (repo, userId) => {
109
+ await (await adapter()).deleteMany({ model, where: by(repo, userId) });
110
+ },
111
+
112
+ list: async (repo, from) => {
113
+ const { limit, where, read } = window('userId', from);
114
+ const rows = await (
115
+ await adapter()
116
+ ).findMany<Row>({ model, where: [{ field: 'repo', value: repo }, ...where], ...read });
117
+
118
+ return paged(
119
+ rows.map((row) => ({ userId: row.userId, role: row.role })),
120
+ limit,
121
+ (row) => row.userId,
122
+ );
123
+ },
124
+
125
+ shared: async (userId, from) => {
126
+ const { limit, where, read } = window('repo', from);
127
+ const rows = await (
128
+ await adapter()
129
+ ).findMany<Row>({ model, where: [{ field: 'userId', value: userId }, ...where], ...read });
130
+
131
+ return paged(
132
+ rows.map((row) => row.repo),
133
+ limit,
134
+ (repo) => repo,
135
+ );
136
+ },
137
+
138
+ drop: async (repo) => {
139
+ await (await adapter()).deleteMany({ model, where: [{ field: 'repo', value: repo }] });
140
+ },
141
+ });
@@ -67,7 +67,7 @@ catalog:
67
67
  # The app's Markdown renderer: words, a WebAssembly parser, with hooks for GitHub's alerts,
68
68
  # anchors, references and URLs (Q213). Apache-2.0.
69
69
  '@pierre/words': 0.3.0
70
- '@ref0/workspace': 0.9.0
70
+ '@ref0/workspace': 0.13.0
71
71
  '@tailwindcss/vite': 4.3.5
72
72
  # The app's stack: TanStack Start, its router and Query, and React, as spike F ran them, at the
73
73
  # newest releases past pnpm's minimum release age.
@@ -221,4 +221,4 @@ allowBuilds:
221
221
  workerd: true
222
222
 
223
223
  minimumReleaseAgeExclude:
224
- - '@ref0/workspace@0.9.0'
224
+ - '@ref0/workspace@0.13.0'
@@ -6,8 +6,16 @@ import * as Stdio from "effect/Stdio";
6
6
  // src/cli/child.ts
7
7
  /** How long a command `init` runs has to stop once a cancel reaches it. */
8
8
  const stopMs = 1e4;
9
- /** The signal Node's spawner names when a child ends by one, rather than with a status. */
10
- const signalled = (error) => /receipt of signal: '([A-Z0-9]+)'/.exec(error.message)?.[1];
9
+ /**
10
+ * The most of a piped command's stdout, and of its stderr, `runPiped` keeps: a page of `cf`'s JSON
11
+ * is well under it, and what's past it is dropped, with `cut` set.
12
+ */
13
+ const pipedMost = 1048576;
14
+ /**
15
+ * The signal Node's spawner names when a child ends by one, rather than with a status: in the
16
+ * message of Node's error, which the spawner keeps as its own's cause.
17
+ */
18
+ const signalled = (error) => /receipt of signal: '([A-Z0-9]+)'/.exec(`${error.message}\n${error.cause instanceof Error ? error.cause.message : ""}`)?.[1];
11
19
  /**
12
20
  * `argv` run in `cwd`, as `init` runs a package manager or a create command: stdin closed, so it
13
21
  * can't prompt, and its output on stderr, so stdout holds only the answer. A cancel sends it
@@ -39,4 +47,66 @@ const runChild = /* @__PURE__ */ Effect.fnUntraced(function* (argv, cwd) {
39
47
  signal: signalled(error) ?? null
40
48
  })));
41
49
  });
42
- export { runChild, stopMs };
50
+ /** A stream's bytes as text, kept to `pipedMost`, and whether more came. */
51
+ const kept = (bytes) => Stream.runFold(bytes, () => ({
52
+ chunks: [],
53
+ size: 0,
54
+ cut: false
55
+ }), (held, chunk) => {
56
+ const room = pipedMost - held.size;
57
+ if (room <= 0) return {
58
+ ...held,
59
+ cut: held.cut || chunk.length > 0
60
+ };
61
+ held.chunks.push(chunk.length > room ? chunk.subarray(0, room) : chunk);
62
+ return {
63
+ chunks: held.chunks,
64
+ size: held.size + Math.min(chunk.length, room),
65
+ cut: chunk.length > room
66
+ };
67
+ }).pipe(Effect.map((held) => ({
68
+ text: new TextDecoder().decode(Buffer.concat(held.chunks)),
69
+ cut: held.cut
70
+ })));
71
+ /**
72
+ * `argv` run in `cwd` as `ref0-git keys` runs `cf` and `wrangler`: `input` on its stdin, closed
73
+ * after it, or nothing; `env` over this process's; and its stdout and stderr kept, not relayed,
74
+ * since a command's output may hold a secret. A cancel stops it as `runChild` does.
75
+ */
76
+ const runPiped = /* @__PURE__ */ Effect.fnUntraced(function* (argv, cwd, options = {}) {
77
+ const [command, ...args] = argv;
78
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
79
+ const started = ChildProcess.make(command, args, {
80
+ cwd,
81
+ stdin: options.input === void 0 ? "ignore" : Stream.make(new TextEncoder().encode(options.input)),
82
+ stdout: "pipe",
83
+ stderr: "pipe",
84
+ env: options.env,
85
+ extendEnv: true,
86
+ killSignal: "SIGINT",
87
+ forceKillAfter: stopMs
88
+ });
89
+ const ran = Effect.gen(function* () {
90
+ const child = yield* spawner.spawn(started);
91
+ const [stdout, stderr, exit] = yield* Effect.all([
92
+ kept(child.stdout),
93
+ kept(child.stderr),
94
+ child.exitCode
95
+ ], { concurrency: "unbounded" });
96
+ return {
97
+ exit,
98
+ signal: null,
99
+ stdout: stdout.text,
100
+ stderr: stderr.text,
101
+ cut: stdout.cut || stderr.cut
102
+ };
103
+ });
104
+ return yield* Effect.scoped(ran).pipe(Effect.catch((error) => Effect.succeed({
105
+ exit: null,
106
+ signal: signalled(error) ?? null,
107
+ stdout: "",
108
+ stderr: "",
109
+ cut: false
110
+ })));
111
+ });
112
+ export { pipedMost, runChild, runPiped, stopMs };
@@ -5,6 +5,7 @@ import { reposCommand, workCommand } from "./repos.mjs";
5
5
  import { setupCommands } from "./setup.mjs";
6
6
  import { signInCommands } from "./sign-in.mjs";
7
7
  import { tokensCommand } from "./tokens.mjs";
8
+ import { keysCommand } from "./keys.mjs";
8
9
  import * as Command from "effect/cli/Command";
9
10
  // src/cli/commands.ts
10
11
  /**
@@ -13,6 +14,7 @@ import * as Command from "effect/cli/Command";
13
14
  */
14
15
  const ref0Git = Command.make("ref0-git").pipe(Command.withDescription("Git hosting from the terminal: sign in, set up and manage a host (experimental)"), Command.withSubcommands([
15
16
  ...setupCommands,
17
+ keysCommand,
16
18
  ...signInCommands,
17
19
  reposCommand,
18
20
  tokensCommand,
@@ -157,6 +157,23 @@ const PlannedFile = /* @__PURE__ */ Schema.Struct({
157
157
  }))
158
158
  }))
159
159
  });
160
+ /**
161
+ * `keys`' document: the Worker and bucket it put R2's keys for, the Access Key ID, how the key came,
162
+ * and, for one `cf` made, its token's name and what became of older tokens of that name.
163
+ */
164
+ const KeysDocument = /* @__PURE__ */ Schema.Struct({
165
+ worker: Schema.String,
166
+ bucket: Schema.String,
167
+ account: Schema.String,
168
+ accessKeyId: Schema.String,
169
+ made: Schema.Literals(["cf", "pasted"]),
170
+ token: Schema.optionalKey(Schema.String),
171
+ older: Schema.optionalKey(Schema.Struct({
172
+ deleted: Schema.Array(Schema.String),
173
+ notDeleted: Schema.optionalKey(Schema.String)
174
+ })),
175
+ nextStep: Schema.optionalKey(NextStepDocument)
176
+ });
160
177
  /** `init`'s receipt as `--json` prints it, and as its failures carry it. */
161
178
  const InitDocument = /* @__PURE__ */ Schema.Struct({
162
179
  folder: Schema.String,
@@ -184,6 +201,15 @@ const InitDocument = /* @__PURE__ */ Schema.Struct({
184
201
  packages: Schema.Array(Schema.String),
185
202
  ran: Schema.Boolean
186
203
  }),
204
+ /**
205
+ * What `init` did about R2's keys, when a person ran it at a terminal on a Worker that's
206
+ * deployed: put them, found them `present` already, or `notPut`, with why.
207
+ */
208
+ keys: Schema.optional(Schema.Union([
209
+ KeysDocument,
210
+ Schema.Struct({ present: Schema.Literal(true) }),
211
+ Schema.Struct({ notPut: Schema.String })
212
+ ])),
187
213
  nextStep: NextStepDocument
188
214
  });
189
215
  /** `doctor`'s document when every check passed, with the step to deploy. */
@@ -195,7 +221,11 @@ const DoctorDocument = /* @__PURE__ */ Schema.Struct({
195
221
  /**
196
222
  * `doctor --verify`'s document: the scratch repo's steps on the host, and what it found left, with
197
223
  * `more` and the step that lists them all when there were more than it names, or `unlisted` with
198
- * why the host didn't list them.
224
+ * why the host didn't list them. Then where its Git LFS links an upload, from one upload batch:
225
+ * `worker` when the link is on the host's own origin, through the host itself with no signing key,
226
+ * whose step runs `keys`; `signed` when it's on any other origin, which a signed link to the bucket
227
+ * is, and so is a host's own proxy or CDN on another origin; or `off`. Or `lfsUnread`, with why the
228
+ * batch couldn't tell.
199
229
  */
200
230
  const VerifyDocument = /* @__PURE__ */ Schema.Struct({
201
231
  host: Schema.String,
@@ -207,6 +237,15 @@ const VerifyDocument = /* @__PURE__ */ Schema.Struct({
207
237
  reason: Schema.String,
208
238
  message: Schema.String
209
239
  })),
240
+ lfs: Schema.optionalKey(Schema.Literals([
241
+ "signed",
242
+ "worker",
243
+ "off"
244
+ ])),
245
+ lfsUnread: Schema.optionalKey(Schema.Struct({
246
+ reason: Schema.String,
247
+ message: Schema.String
248
+ })),
210
249
  nextStep: Schema.optionalKey(NextStepDocument)
211
250
  });
212
251
  /** `logout`'s document: the host it signed out of, if any, and whether a token was removed. */
@@ -220,5 +259,6 @@ const failureJson = /* @__PURE__ */ Schema.encodeSync(Schema.fromJsonString(Fail
220
259
  const initJson = /* @__PURE__ */ Schema.encodeSync(Schema.fromJsonString(InitDocument));
221
260
  const doctorJson = /* @__PURE__ */ Schema.encodeSync(Schema.fromJsonString(DoctorDocument));
222
261
  const verifyJson = /* @__PURE__ */ Schema.encodeSync(Schema.fromJsonString(VerifyDocument));
262
+ const keysJson = /* @__PURE__ */ Schema.encodeSync(Schema.fromJsonString(KeysDocument));
223
263
  const logoutJson = /* @__PURE__ */ Schema.encodeSync(Schema.fromJsonString(LogoutDocument));
224
- export { DoctorDocument, DurationInput, FailureDocument, FindingDocument, HelpDocument, Host, HostInput, InitDocument, LogoutDocument, NextStepDocument, TokenInput, VerifyDocument, doctorJson, failureJson, helpJson, initJson, logoutJson, verifyJson };
264
+ export { DoctorDocument, DurationInput, FailureDocument, FindingDocument, HelpDocument, Host, HostInput, InitDocument, KeysDocument, LogoutDocument, NextStepDocument, TokenInput, VerifyDocument, doctorJson, failureJson, helpJson, initJson, keysJson, logoutJson, verifyJson };