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,144 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { signals } from "./credentials.mjs";
3
- import { failureJson, helpJson } from "./documents.mjs";
4
- import { CliFailure, cancelled, exitCodes, failure, leftovers, snakeCase, usageFailure } from "./failure.mjs";
5
- import { node, written } from "./node.mjs";
6
- import { CliModes, flagOn, modesOf, nextDocument, nextLines, printable, secrets } from "./output.mjs";
7
- import { ref0Git } from "./commands.mjs";
8
- import { runControl } from "./run-end.mjs";
9
- import { layer } from "./runtime.mjs";
10
- import * as Cause from "effect/Cause";
11
- import * as Effect from "effect/Effect";
12
- import * as Exit from "effect/Exit";
13
- import * as Layer from "effect/Layer";
14
- import * as Fiber from "effect/Fiber";
15
- import * as Match from "effect/Match";
16
- import * as Option from "effect/Option";
17
- import * as Predicate from "effect/Predicate";
18
- import * as CliConfig from "effect/cli/CliConfig";
19
- import * as CliError from "effect/cli/CliError";
20
- import * as CliOutput from "effect/cli/CliOutput";
21
- import * as Command from "effect/cli/Command";
22
- import * as GlobalFlag from "effect/cli/GlobalFlag";
2
+ import { main } from "./main.mjs";
3
+ import { nodeTools } from "./tools-node.mjs";
23
4
  // src/cli/ref0-git.ts
24
- /**
25
- * `ref0-git`, as `npx ref0-git`: its commands, and the one place a run ends, saying its failure
26
- * and exiting 0, 1, 2 for usage, or 130; a defect's cause, which could hold a credential, isn't said.
27
- */
28
- const { process } = node;
29
- const formatter = CliOutput.defaultFormatter({ colors: false });
30
- const args = process.argv.slice(2);
31
- const json = flagOn(args, "json");
32
- /** The lifecycle labels a description ends with, in parentheses. */
33
- const labels = ["experimental", "beta"];
34
- /** A description's lifecycle label, in its parentheses, and the words before it. */
35
- const labelled = (description) => {
36
- const label = labels.find((each) => description.endsWith(`(${each})`));
37
- return label === void 0 ? {
38
- description,
39
- lifecycle: "stable"
40
- } : {
41
- description: description.slice(0, -`(${label})`.length).trimEnd(),
42
- lifecycle: label
43
- };
44
- };
45
- /** Help as `--help --json` prints it: the command, its arguments, flags and subcommands. */
46
- const helpDocument = (help) => ({
47
- command: (help.commandPath ?? []).join(" "),
48
- ...labelled(help.description),
49
- usage: help.usage,
50
- arguments: (help.args ?? []).map((arg) => ({
51
- name: arg.name,
52
- description: Option.getOrUndefined(arg.description),
53
- required: arg.required
54
- })),
55
- flags: [...help.flags, ...help.globalFlags ?? []].map((flag) => ({
56
- name: `--${flag.name}`,
57
- description: Option.getOrUndefined(flag.description),
58
- required: flag.required
59
- })),
60
- commands: (help.subcommands ?? []).flatMap((group) => group.commands).map((command) => ({
61
- name: command.name,
62
- ...labelled(command.description)
63
- }))
64
- });
65
- /** Help, as text or, with `--json`, as one document. */
66
- const helpText = (help) => json ? helpJson(helpDocument(help)) : formatter.formatHelpDoc(help);
67
- /** The help a parse showed with no request for it: printed only when nothing failed. */
68
- let implicitHelp;
69
- const printed = (text) => Effect.promise(() => written(process.stdout, `${text}\n`).catch(() => void 0));
70
- /** Help asked for and the version go to stdout; help shown for a refusal waits for the run's end. */
71
- const presenter = { present: Match.type().pipe(Match.tag("Help", (event) => event.reason === "Implicit" ? Effect.sync(() => {
72
- implicitHelp = event.helpDoc;
73
- }) : printed(helpText(event.helpDoc))), Match.tag("Version", (event) => printed(event.version)), Match.tag("InvalidInvocation", () => Effect.void), Match.exhaustive) };
74
- const cliLayer = Layer.mergeAll(layer, CliConfig.layer({ builtIns: [GlobalFlag.Help, GlobalFlag.Version] }), CliOutput.layerPresenter(presenter));
75
- /** A parse's refusal as the CLI's failure, naming the command's help. */
76
- const usageOf = (error) => {
77
- const [first] = error.errors;
78
- const [, ...path] = error.commandPath;
79
- return usageFailure(snakeCase(first?._tag ?? "missing_command"), first?.message ?? `${error.commandPath.join(" ")} needs a command`, {
80
- says: "See its help",
81
- run: [[...path, "--help"]]
82
- });
83
- };
84
- /** A cancelled run's failure: what its command's clean-up says it may have left, if anything. */
85
- const cancelledFailure = () => new CliFailure({
86
- class: "cancelled",
87
- reason: "canceled",
88
- headline: cancelled.left?.headline ?? "Canceled",
89
- next: cancelled.left?.next
90
- });
91
- /** What ended the run, as a failure to say, or `undefined` when it finished. */
92
- const failureOf = (exit) => {
93
- if (Exit.isSuccess(exit)) return void 0;
94
- if (Cause.hasInterruptsOnly(exit.cause)) return cancelledFailure();
95
- const error = Cause.squash(exit.cause);
96
- if (error instanceof CliFailure) return error;
97
- if (CliError.isCliError(error) && Predicate.isTagged(error, "ShowHelp")) return error.errors.length === 0 ? "help" : usageOf(error);
98
- return failure("internal_error", "Unexpected error in ref0-git. This is a bug in ref0-git", "Run it again; if it fails again, report it");
99
- };
100
- /**
101
- * A failure as its words on stderr, after `ref0-git: `, or with `--json` as one line: the
102
- * `cli-design` skill's error document. Every part goes through `printable`, which also takes out
103
- * each secret the run holds, since a hostile host's refusal could echo one.
104
- */
105
- const failureLine = (failed) => {
106
- const next = failed.next === void 0 ? void 0 : {
107
- says: printable(failed.next.says),
108
- run: failed.next.run
109
- };
110
- const document = {
111
- status: failed.class === "usage" ? "action_required" : "error",
112
- reason: failed.reason,
113
- message: printable(failed.headline),
114
- nextStep: next === void 0 ? void 0 : nextDocument(next),
115
- data: failed.findings === void 0 ? failed.data : { findings: failed.findings }
116
- };
117
- const lines = [`ref0-git: ${document.message}`, ...next === void 0 || json ? [] : nextLines(next)];
118
- return json ? `${secrets.scrub(failureJson(document))}\n` : `${lines.join("\n")}\n`;
119
- };
120
- const fiber = Effect.runFork(Command.runWith(ref0Git, {
121
- version: "0.0.0",
122
- renderErrors: false
123
- })(args).pipe(Effect.provide(cliLayer), Effect.provideService(CliModes, modesOf({
124
- json,
125
- nonInteractive: flagOn(args, "non-interactive")
126
- }))));
127
- process.stdout.on("error", () => void 0);
128
- process.stderr.on("error", () => void 0);
129
- /** The run's signals and its end, as one state machine: `run-end.ts`' `runControl`. */
130
- const control = runControl({
131
- stderr: (text) => written(process.stderr, text),
132
- exit: (code) => process.exit(code),
133
- interrupt: () => Effect.runFork(Fiber.interrupt(fiber)),
134
- leftovers: () => leftovers,
135
- cancelledLine: () => failureLine(cancelledFailure())
136
- });
137
- for (const [signal, status] of signals) process.on(signal, () => control.signal(status));
138
- const ended = failureOf(await Effect.runPromise(Fiber.await(fiber)));
139
- if (ended === "help" && implicitHelp !== void 0) await written(process.stdout, `${helpText(implicitHelp)}\n`).catch(() => void 0);
140
- await control.ended({
141
- status: ended instanceof CliFailure ? exitCodes[ended.class] : 0,
142
- failureLine: ended instanceof CliFailure ? failureLine(ended) : void 0
143
- });
5
+ /** `ref0-git`, as `npx ref0-git`: the one entry that runs the real `cf` and `wrangler`. */
6
+ await main(nodeTools);
144
7
  export {};
@@ -28,6 +28,7 @@ import { gitRun } from "./git.mjs";
28
28
  import { node } from "./node.mjs";
29
29
  import { Sqlite } from "./sqlite.mjs";
30
30
  import { CliModes, answer, cliDocument, field, nextDocument, printable, receipt, say, secrets, stderrText } from "./output.mjs";
31
+ import { initKeysDocument, initKeysFields, initKeysNext, keysOnInit } from "./keys.mjs";
31
32
  import { select } from "./prompt.mjs";
32
33
  import * as Effect from "effect/Effect";
33
34
  import * as Exit from "effect/Exit";
@@ -35,6 +36,7 @@ import * as Redacted from "effect/Redacted";
35
36
  import * as Stream from "effect/Stream";
36
37
  import * as ChildProcess from "effect/process/ChildProcess";
37
38
  import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
39
+ import * as FetchHttpClient from "effect/http/FetchHttpClient";
38
40
  import * as Option from "effect/Option";
39
41
  import * as Command from "effect/cli/Command";
40
42
  import * as Schema from "effect/Schema";
@@ -45,6 +47,8 @@ import * as Clock from "effect/Clock";
45
47
  import * as FileSystem from "effect/FileSystem";
46
48
  import * as Path from "effect/Path";
47
49
  import * as Random from "effect/Random";
50
+ import * as HttpClient from "effect/http/HttpClient";
51
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
48
52
  import { joinedBytes } from "@ref0/git/protocol";
49
53
  // src/cli/setup.ts
50
54
  /**
@@ -472,7 +476,26 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
472
476
  const changes = steps.filter((step) => step.text !== void 0 && step.action !== "unchanged");
473
477
  const installed = yield* (yield* FileSystem.FileSystem).exists(`${folder.path}/node_modules/@ref0/git`).pipe(Effect.orElseSucceed(() => false));
474
478
  const installing = flags.install && !flags.dryRun && !output.manual.some((step) => step.path === "pnpm-workspace.yaml") && (changes.some((step) => step.path === "package.json") || !installed);
475
- const documentOf = (ran) => ({
479
+ const signing = settled.platform.value === "cloudflare" && settled.objects.value === "packs" && settled.bucket.value === "r2";
480
+ const keysRun = [["doctor", ...folder.argv], ["keys", ...folder.argv]];
481
+ const keysStep = {
482
+ says: `${output.next}; once it's deployed, put R2's keys on it, so its LFS links sign straight to the bucket`,
483
+ run: keysRun
484
+ };
485
+ const notAskedStep = {
486
+ says: `${output.next}; once it's deployed, put R2's keys on it: keys mints a Cloudflare token; run it yourself`,
487
+ run: keysRun
488
+ };
489
+ const nextOf = (keys) => {
490
+ const recovery = initKeysNext(keys);
491
+ if (recovery !== void 0) return {
492
+ says: `${recovery.says}; then check it`,
493
+ run: [...recovery.run, ["doctor", ...folder.argv]].slice(0, 2)
494
+ };
495
+ if (!signing || keys?.kind === "put" || keys?.kind === "present") return doctorStep;
496
+ return keys?.kind === "notAsked" ? notAskedStep : keysStep;
497
+ };
498
+ const documentOf = (ran, keys) => ({
476
499
  folder: folder.path,
477
500
  project: project.project,
478
501
  dryRun: flags.dryRun,
@@ -522,7 +545,8 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
522
545
  packages: output.packages.map((each) => `${each}@${release}`),
523
546
  ran
524
547
  },
525
- nextStep: nextDocument(doctorStep)
548
+ keys: initKeysDocument(keys),
549
+ nextStep: nextDocument(nextOf(keys))
526
550
  });
527
551
  const manualLines = output.manual.flatMap((step) => [
528
552
  "",
@@ -597,11 +621,13 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
597
621
  data: documentOf(installing)
598
622
  }));
599
623
  }
600
- if (mode.json) return yield* cliDocument(initJson, documentOf(installing));
624
+ const keys = signing ? yield* keysOnInit(folder, platforms.cloudflare.signing, flags.keys) : void 0;
625
+ if (mode.json) return yield* cliDocument(initJson, documentOf(installing, keys));
601
626
  if (!mode.stdoutTerminal || !mode.interactive) yield* answer(folder.path);
602
627
  if (changes.length === 0) return yield* receipt({
603
628
  done: `Nothing to change: ${printable(folder.path)} is set up as init writes it`,
604
- next: doctorStep
629
+ fields: initKeysFields(keys),
630
+ next: nextOf(keys)
605
631
  });
606
632
  const secret = changes.some((step) => step.secrets !== void 0);
607
633
  yield* receipt({
@@ -609,9 +635,10 @@ const finish = /* @__PURE__ */ Effect.fnUntraced(function* (flags, folder, proje
609
635
  fields: [
610
636
  ["Wrote", kept],
611
637
  ...secret ? [["Secret", output.secret]] : [],
612
- ...output.needs.length > 0 ? [["Still needed", output.needs.join(", ")]] : []
638
+ ...output.needs.length > 0 ? [["Still needed", output.needs.join(", ")]] : [],
639
+ ...initKeysFields(keys)
613
640
  ],
614
- next: doctorStep
641
+ next: nextOf(keys)
615
642
  });
616
643
  });
617
644
  /**
@@ -757,7 +784,8 @@ const init = Command.make("init", {
757
784
  install: Flag.Boolean("install").pipe(Flag.withDescription("Install the packages once the files are written, or --no-install"), Flag.withDefault(true)),
758
785
  yes: Flag.Boolean("yes").pipe(Flag.withDescription("Take the recommended answer for each choice the flags and the folder leave open"), Flag.withDefault(false)),
759
786
  fromCheckout: Flag.String("from-checkout").pipe(Flag.withDescription("Take the app, Git's packages and ref0-git from a ref-0/git checkout, packed into vendor/, until they're on npm"), Flag.withMetavar("DIR"), Flag.optional),
760
- dryRun: Flag.Boolean("dry-run").pipe(Flag.withDescription("Print the plan, each file and its action, and change nothing"), Flag.withDefault(false))
787
+ dryRun: Flag.Boolean("dry-run").pipe(Flag.withDescription("Print the plan, each file and its action, and change nothing"), Flag.withDefault(false)),
788
+ keys: Flag.Boolean("keys").pipe(Flag.withDescription("On Cloudflare with R2, put R2's keys on a deployed Worker that lacks them, when a person runs init at a terminal, or --no-keys"), Flag.withDefault(true))
761
789
  }, /* @__PURE__ */ Effect.fnUntraced(function* (flags) {
762
790
  const mode = yield* CliModes;
763
791
  const fileSystem = yield* FileSystem.FileSystem;
@@ -944,6 +972,66 @@ const cutAnswer = (host, call) => call.pipe(Effect.mapError((error) => refused(e
944
972
  }));
945
973
  /** A create's failures that don't say the host made nothing: no answer, or its own failure. */
946
974
  const unsettled = /^(unreachable|unavailable|deadline_exceeded|internal|data_loss)$/;
975
+ /** Git LFS's media type, which its batch API asks for and answers in. */
976
+ const lfsType = "application/vnd.git-lfs+json";
977
+ /** The most bytes of the batch's answer `--verify` reads: one object's links take under 4 KiB. */
978
+ const lfsAnswerMost = 65536;
979
+ /** The object `--verify`'s batch asks to upload, which it never sends: one byte, all zeros' oid. */
980
+ const lfsProbe = {
981
+ oid: "0".repeat(64),
982
+ size: 1
983
+ };
984
+ /** The batch's answer as far as `--verify` reads it: the first object's upload link. */
985
+ const LfsAnswer = /* @__PURE__ */ Schema.Struct({ objects: Schema.Array(Schema.Struct({ actions: Schema.optionalKey(Schema.Struct({ upload: Schema.optionalKey(Schema.Struct({ href: Schema.String })) })) })) });
986
+ const lfsAnswerOf = /* @__PURE__ */ Schema.decodeUnknownOption(Schema.fromJsonString(LfsAnswer));
987
+ const lfsUnread = (reason, message) => ({ lfsUnread: {
988
+ reason,
989
+ message: printable(message)
990
+ } });
991
+ /**
992
+ * One upload batch on the scratch repo at `url`, with its token, read for where the host links an
993
+ * upload: its own origin is the Worker, with no signing key; any other origin reads as a signed
994
+ * link, a host's own proxy or CDN on another origin too. No bytes are uploaded or stored: the
995
+ * batch stores one upload row, which upkeep purges `linkLife` and `uploadGrace` on. Its answer is
996
+ * read to `lfsAnswerMost`, it follows no redirect, and a failure is said, never the check's.
997
+ */
998
+ const lfsOf = (host, url, secret) => {
999
+ let seen = 0;
1000
+ return HttpClient.HttpClient.pipe(Effect.flatMap((client) => client.execute(HttpClientRequest.post(`${url}/info/lfs/objects/batch`).pipe(HttpClientRequest.setHeaders({
1001
+ accept: lfsType,
1002
+ authorization: `Basic ${btoa(`ref0-git-verify:${secret}`)}`
1003
+ }), HttpClientRequest.bodyText(JSON.stringify({
1004
+ operation: "upload",
1005
+ transfers: ["basic"],
1006
+ objects: [lfsProbe]
1007
+ }), lfsType)))), Effect.flatMap((answer) => {
1008
+ if (answer.status === 404) return Effect.succeed({ lfs: "off" });
1009
+ if (answer.status !== 200) return Effect.succeed(lfsUnread("lfs_refused", `${host} answered the batch ${answer.status}`));
1010
+ return answer.stream.pipe(Stream.takeUntil((chunk) => (seen += chunk.length) > lfsAnswerMost), Stream.runCollect, Effect.map((chunks) => {
1011
+ if (seen > lfsAnswerMost) return lfsUnread("lfs_unreadable", `${host}'s batch answered past ${lfsAnswerMost} bytes`);
1012
+ const text = new TextDecoder().decode(joinedBytes(chunks));
1013
+ const href = Option.getOrUndefined(lfsAnswerOf(text))?.objects[0]?.actions?.upload?.href;
1014
+ if (href === void 0 || !URL.canParse(href)) return lfsUnread("lfs_unreadable", `${host}'s batch named no upload link`);
1015
+ return { lfs: new URL(href).origin === new URL(url).origin ? "worker" : "signed" };
1016
+ }));
1017
+ }), Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), Effect.timeoutOrElse({
1018
+ duration: callMs,
1019
+ orElse: () => Effect.succeed(lfsUnread("deadline_exceeded", `${host} didn't answer the batch in ${callMs / 1e3}s`))
1020
+ }), Effect.catch(() => Effect.succeed(lfsUnread("unreachable", `Couldn't reach ${host}'s batch`))));
1021
+ };
1022
+ /** The receipt's LFS row for `read`, and the step that signs the links when they go through the Worker. */
1023
+ const lfsRow = (read) => {
1024
+ if ("lfsUnread" in read) return { says: `Not read: ${read.lfsUnread.message}` };
1025
+ if (read.lfs === "signed") return { says: "Signed links, straight to the bucket" };
1026
+ if (read.lfs === "off") return { says: "Off: the host serves no Git LFS" };
1027
+ return {
1028
+ says: "Through the Worker (no signing key)",
1029
+ next: {
1030
+ says: "Sign LFS's links straight to R2, from the Worker's folder",
1031
+ run: [["keys"]]
1032
+ }
1033
+ };
1034
+ };
947
1035
  /**
948
1036
  * Creates a scratch repo, pushes a commit to it with a token of its own, reads it back and clones
949
1037
  * it, then, in a `finally`, revokes the token, deletes the repo by its name and lists what's left.
@@ -965,6 +1053,8 @@ const verify = /* @__PURE__ */ Effect.fnUntraced(function* (hostOption) {
965
1053
  tokenSent: false
966
1054
  };
967
1055
  const left = [];
1056
+ /** What the scratch repo's one Git LFS batch read, once its clone passed. */
1057
+ let lfs;
968
1058
  const run = (args, env = {}) => Effect.flatMap(gitRun(args, {
969
1059
  cwd: folder,
970
1060
  env
@@ -1055,6 +1145,7 @@ const verify = /* @__PURE__ */ Effect.fnUntraced(function* (hostOption) {
1055
1145
  ])).trim();
1056
1146
  if (cloned !== head) return yield* failure("verify_clone", `The clone of ${repo} has ${cloned}, not ${head}`);
1057
1147
  steps.push("cloned");
1148
+ lfs = yield* lfsOf(host, url, token.secret);
1058
1149
  });
1059
1150
  /** Whether `call` removed `what` in time, or found it gone where `gone` says that's settled. */
1060
1151
  const removed = (what, call, gone = true) => call.pipe(Effect.as(true), Effect.catch((error) => Effect.succeed(gone && error.code === "NOT_FOUND")), Effect.catchDefect(() => Effect.succeed(false)), Effect.timeoutOrElse({
@@ -1081,27 +1172,38 @@ const verify = /* @__PURE__ */ Effect.fnUntraced(function* (hostOption) {
1081
1172
  if (left.length > 0) return yield* cleanUpFailed(`${host} works end to end`);
1082
1173
  const found = yield* leftovers(host, client);
1083
1174
  const row = leftoversRow(host, found);
1175
+ const read = lfs ?? lfsUnread("verify_clone", "the clone ended the check first");
1176
+ const lfsSaid = lfsRow(read);
1177
+ const next = row.next === void 0 || lfsSaid.next === void 0 ? row.next ?? lfsSaid.next : {
1178
+ says: `${row.next.says}, and sign LFS's links from the Worker's folder`,
1179
+ run: [...row.next.run, ...lfsSaid.next.run]
1180
+ };
1084
1181
  if ((yield* CliModes).json) {
1085
1182
  const document = {
1086
1183
  host,
1087
1184
  repo,
1088
1185
  steps,
1089
- ...found
1186
+ ...found,
1187
+ ...read
1090
1188
  };
1091
- return yield* row.next === void 0 ? cliDocument(verifyJson, document) : cliDocument(verifyJson, {
1189
+ return yield* next === void 0 ? cliDocument(verifyJson, document) : cliDocument(verifyJson, {
1092
1190
  ...document,
1093
- nextStep: nextDocument(row.next)
1191
+ nextStep: nextDocument(next)
1094
1192
  });
1095
1193
  }
1096
1194
  const done = `${host} works end to end`;
1097
- const fields = [["Scratch repo", `${repo}: ${steps.join(", ")}`], ["Leftovers", row.says]];
1098
- yield* row.next === void 0 ? receipt({
1195
+ const fields = [
1196
+ ["Scratch repo", `${repo}: ${steps.join(", ")}`],
1197
+ ["Leftovers", row.says],
1198
+ ["LFS", lfsSaid.says]
1199
+ ];
1200
+ yield* next === void 0 ? receipt({
1099
1201
  done,
1100
1202
  fields
1101
1203
  }) : receipt({
1102
1204
  done,
1103
1205
  fields,
1104
- next: row.next
1206
+ next
1105
1207
  });
1106
1208
  });
1107
1209
  /**
@@ -17,9 +17,9 @@ import * as Flag from "effect/cli/Flag";
17
17
  import { RestClient } from "@ref0/git";
18
18
  import * as Argument from "effect/cli/Argument";
19
19
  import * as Clock from "effect/Clock";
20
- import * as Result from "effect/Result";
21
20
  import * as HttpClient from "effect/http/HttpClient";
22
21
  import * as HttpClientRequest from "effect/http/HttpClientRequest";
22
+ import * as Result from "effect/Result";
23
23
  import { deviceGrant, ghClientId, ghWriteScope, readAccessTokenAnswer, readDeviceCodeAnswer, signInPaths } from "@ref0/git/auth";
24
24
  // src/cli/sign-in.ts
25
25
  /**
@@ -0,0 +1,20 @@
1
+ import { runPiped } from "./child.mjs";
2
+ import * as Effect from "effect/Effect";
3
+ import * as FileSystem from "effect/FileSystem";
4
+ import * as Path from "effect/Path";
5
+ // src/cli/tools-node.ts
6
+ /** The project's own `wrangler`, which its install puts in `node_modules/.bin`, else `PATH`'s. */
7
+ const wranglerOf = /* @__PURE__ */ Effect.fnUntraced(function* (folder) {
8
+ const fs = yield* FileSystem.FileSystem;
9
+ const own = (yield* Path.Path).join(folder, "node_modules", ".bin", "wrangler");
10
+ return (yield* fs.exists(own).pipe(Effect.orElseSucceed(() => false))) ? own : "wrangler";
11
+ });
12
+ /**
13
+ * The real `cf` and `wrangler`, which carry the host's login: `cf` from `PATH`, and the project's
14
+ * own `wrangler` before `PATH`'s. Only the `ref0-git` bin gives this runner.
15
+ */
16
+ const nodeTools = { run: /* @__PURE__ */ Effect.fnUntraced(function* (tool, args, cwd, options) {
17
+ const program = tool === "wrangler" ? yield* wranglerOf(cwd) : tool;
18
+ return yield* runPiped([program, ...args], cwd, options);
19
+ }) };
20
+ export { nodeTools };
@@ -0,0 +1,12 @@
1
+ import { failure } from "./failure.mjs";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ // src/cli/tools.ts
5
+ /** The runner a run was given: one that spawns nothing, unless its entry point gives another. */
6
+ const refusing = { run: (tool) => Effect.fail(failure("tools_not_given", `This ref0-git was given no way to run ${tool}, so it ran none of Cloudflare's CLIs`, "Run it as `npx ref0-git`")) };
7
+ /**
8
+ * The runner for `cf` and `wrangler`. Only the `ref0-git` bin gives the real one, so the commands
9
+ * run as a library, by a test or a script, can't reach anyone's Cloudflare login.
10
+ */
11
+ const Tools = Context.Reference("ref0-git/Tools", { defaultValue: () => refusing });
12
+ export { Tools, refusing };
package/dist/init/app.mjs CHANGED
@@ -105,6 +105,7 @@ const githubImport = (choices) => importLine([
105
105
  "GitHub",
106
106
  "Inbox",
107
107
  choices.objects === "packs" && "Releases",
108
+ "RepoGrants",
108
109
  "Search",
109
110
  "Streams",
110
111
  "Webhooks"
@@ -130,6 +131,7 @@ const cloudflareGit = (choices) => {
130
131
  queueTypes: unless(choices.queue === "on", ""),
131
132
  githubImport: githubImport(choices),
132
133
  infraImport: unless(packs, looseInfraImport),
134
+ effectImport: unless(packs, ""),
133
135
  safety: unless(packs, "binds the objects, and D1"),
134
136
  bucket: unless(packs, ""),
135
137
  adapter: unless(packs, "/** The records and job objects. */\nconst adapter = layer({ records: env.RECORDS, jobs: env.JOBS });"),
@@ -156,7 +158,7 @@ const dialectOn = {
156
158
  const nodeHead = (choices) => {
157
159
  const queue = choices.queue === "on";
158
160
  const dialect = dialectOn[choices.records];
159
- return lines(firstImports(choices, false), dialect !== false && `${dialect}\n`, gitImport(choices), queue && "import type { MergeInput, MergePlan } from '@ref0/git';", githubImport(choices), "import * as Languages from '@ref0/github/languages';", infraImports(choices), "import { xdiff } from '@ref0/xdiff-wasm/node';", "import * as FetchHttpClient from 'effect/http/FetchHttpClient';", "import * as Layer from 'effect/Layer';", "import * as ManagedRuntime from 'effect/ManagedRuntime';", "", "import { hostLayer, peopleOver, repoListOn, runOn, tokenCallsOn } from './context/host.ts';", "import { repoIcons } from './context/repo-icons.ts';", `import { env${partsOf(choices).length > 0 ? ", need" : ""} } from './env.ts';`, "import { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';", "import { privateReposOf } from './private-repos.ts';", "import { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';", "import { avatars } from './signin/avatars.ts';", "import { clientIpHeader } from './signin/client-ip.ts';", "import { appAuth } from './signin/host-session.ts';", "import { orgsOver } from './signin/orgs.ts';", "import { sealKey } from './signin/seal.ts';", "", "/** What the app reads from `.env`, as the server's entry reads it here. */", "export { env };", "", storeLines(choices), bucketLines(choices), "", peopleOn[choices.records], "");
161
+ return lines(firstImports(choices, false), dialect !== false && `${dialect}\n`, gitImport(choices), queue && "import type { MergeInput, MergePlan } from '@ref0/git';", githubImport(choices), "import * as Collaborators from '@ref0/github/collaborators';", "import * as Languages from '@ref0/github/languages';", infraImports(choices), "import { xdiff } from '@ref0/xdiff-wasm/node';", "import * as FetchHttpClient from 'effect/http/FetchHttpClient';", "import * as Layer from 'effect/Layer';", "import * as ManagedRuntime from 'effect/ManagedRuntime';", "", "import { hostLayer, peopleOver, repoListOn, runOn, tokenCallsOn } from './context/host.ts';", "import { repoGrantsDropped } from './context/repo-grants.ts';", "import { repoIcons } from './context/repo-icons.ts';", `import { env${partsOf(choices).length > 0 ? ", need" : ""} } from './env.ts';`, "import {", " admin,", " approvalPage,", " type GrantsPolicy,", " hostPolicy,", " hostRules,", " type Identify,", "} from './policy.ts';", "import { privateReposOf } from './private-repos.ts';", "import { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';", "import { avatars } from './signin/avatars.ts';", "import { clientIpHeader } from './signin/client-ip.ts';", "import { appAuth } from './signin/host-session.ts';", "import { orgsOver } from './signin/orgs.ts';", "import { grantsOver } from './signin/repo-grants.ts';", "import { sealKey } from './signin/seal.ts';", "", "/** What the app reads from `.env`, as the server's entry reads it here. */", "export { env };", "", storeLines(choices), bucketLines(choices), "", peopleOn[choices.records], "");
160
162
  };
161
163
  /** The app's `src/git.ts` on Node: `apps/github`'s own past its head, Node's head and parts in Cloudflare's place. */
162
164
  const nodeGit = (choices) => filled(templates.appGitNode, {
@@ -29,7 +29,6 @@ const header = (choices, on) => lines(`// Git on ${on}, ${served[choices.serve]}
29
29
  * that a Worker checks its `ADMINS` against.
30
30
  */
31
31
  const gitNames = (choices, admins) => [
32
- choices.serve === "github" && "accept",
33
32
  "Auth",
34
33
  "Git",
35
34
  choices.objects === "packs" && "Lfs",
@@ -39,8 +38,7 @@ const gitNames = (choices, admins) => [
39
38
  "Policy",
40
39
  choices.serve !== "git" && "Rest",
41
40
  "Tokens",
42
- admins && "maxActorIdLength",
43
- choices.serve === "github" && admins && "reject"
41
+ admins && "maxActorIdLength"
44
42
  ].filter(Predicate.isString);
45
43
  /** The drop-in's names, under `--serve github`: Releases only beside a bucket. */
46
44
  const githubNames = (choices, admins) => [
@@ -75,12 +73,19 @@ const gitImports = (choices, admins = false) => lines(namedImport(gitNames(choic
75
73
  * Effect's imports, which the composition is written in, and with `admins` what a Worker's policy
76
74
  * over its `ADMINS` reads the host's tokens with.
77
75
  */
78
- const effectImports = (choices, admins = false) => lines(admins && "import * as Context from 'effect/Context';", (admins || choices.serve === "github") && "import * as Effect from 'effect/Effect';", choices.serve === "github" && "import * as FetchHttpClient from 'effect/http/FetchHttpClient';", "import * as Layer from 'effect/Layer';", "import * as ManagedRuntime from 'effect/ManagedRuntime';", admins && "import * as Option from 'effect/Option';", "import * as Redacted from 'effect/Redacted';");
76
+ const effectImports = (choices, admins = false) => lines(admins && "import * as Context from 'effect/Context';", admins && "import * as Effect from 'effect/Effect';", choices.serve === "github" && "import * as FetchHttpClient from 'effect/http/FetchHttpClient';", "import * as Layer from 'effect/Layer';", "import * as ManagedRuntime from 'effect/ManagedRuntime';", admins && "import * as Option from 'effect/Option';", "import * as Redacted from 'effect/Redacted';");
79
77
  /** Who `ADMIN_TOKEN` signs in as. */
80
78
  const adminLines = lines("/** Who `ADMIN_TOKEN` signs in as: it makes repos and tokens, and never pushes. */", "const admin = { id: '_admin' };", "");
81
79
  /** How the queue writes an entry onto `main`, when there's a queue. */
82
80
  const mergeLines = (choices) => choices.queue === "on" && lines("/** How the queue writes an entry onto `main`: a merge commit, by whoever added it. */", "const merge = ({ entry, at }: MergeInput): MergePlan => ({", " method: 'merge',", " message: `Merge ${entry.source.replace(/^refs\\/heads\\//, '')}\\n`,", " author: {", " name: entry.actor.id,", " email: `${entry.actor.id}@users.noreply.git`,", " at,", " offset: 0,", " },", "});", "");
83
- /** Who may do what: the admin's and a visitor's limits, as `Policy` decides them. */
81
+ /**
82
+ * Who may do what: the admin's and a visitor's limits, as `Policy` decides them.
83
+ *
84
+ * It accepts every kind but the admin's push for any actor who signs in directly, not by a token:
85
+ * `work.listById` among them, which reads any repo's work, a deleted one's too. Only `_admin`, by
86
+ * `ADMIN_TOKEN`, signs in directly on the hosts `init` writes. A host that adds another sign-in
87
+ * actor adds an explicit admin check for `work.listById`, or that actor reads every repo's work.
88
+ */
84
89
  const policyLines = lines("/**", " * Who may do what: a visitor signs in first, and the admin makes repos and tokens but never", " * pushes.", " */", "const policy = Policy.make(({ caller: { actor }, operation }) => {", " if (actor.anonymous === true) return Policy.reject({ message: 'Sign in first' });", "", " if (actor.id === admin.id && operation.kind === 'push') {", " return Policy.reject({", " message: \"The admin token can't push\",", " hint: 'Make a write token for yourself: npx ref0-git tokens create --help',", " });", " }", "", " return Policy.accept();", "});", "");
85
90
  /** What one push may carry into `Objects.layerRecords()`, as `@ref0/git` holds it. */
86
91
  const looseSays = `up to ${looseLimits.objects.toLocaleString("en-US")} objects and ${looseLimits.bytes / 1024 / 1024} MiB a push`;
@@ -117,7 +122,7 @@ const gitFeatures = (choices, parts) => {
117
122
  */
118
123
  const unstableNextLine = ["// @effect", "diagnostics-next-line unstableApiUsage:off"].join("-");
119
124
  /** The drop-in over Git's features, under `--serve github`: each of its features a line too. */
120
- const githubFeatures = (choices, admins) => lines("/**", " * GitHub's REST, GraphQL, webhooks and Event Streams over Git's, so `gh` and Octokit work, and", " * the drop-in's features, each a line: delete one to turn it off.", " */", "const github = Layer.mergeAll(", " Inbox.layer(),", " Deployments.layer(),", " // Without it, a repo's `language` and `license` answer null.", " Languages.layer(),", " // Repo and user search, and `org:` and `user:` search over an owner's public repos.", " Search.layer(),", " // A repo's and an org's hooks, each delivery a `fetch`, and GitHub Apps, whose hooks they send.", " Layer.provideMerge(Apps.layer(), Webhooks.layer()),", " // GitHub's Event Streams over Git's event feeds.", " Streams.layer(),", " // A repo's import from GitHub, its releases among it.", " Imports.layer(),", ").pipe(", choices.objects === "packs" && " // A release's assets, in the bucket beside the packs.\n Layer.provideMerge(Releases.layer()),", " Layer.provideMerge(GitHub.layer()),", admins ? lines(" // The drop-in narrows nothing past `policy`'s, but its org and account routes ask it alone:", " // it refuses a visitor, the bootstrap, an `admin` token outside ADMINS and work saved for", " // someone who has left, as `policy` does.", " Layer.provideMerge(", " GitHubPolicy.layer(", " GitHubPolicy.make((asker) =>", " Effect.gen(function* () {", " if (asker.actor.anonymous === true || isBootstrap(asker) || adminOutside(asker)) {", " return reject({", " message: 'Only an admin in ADMINS reaches this, with their admin token',", " });", " }", "", " const org = 'org' in asker.operation ? asker.operation.org : undefined;", "", " const needs = scopeFor(asker.operation.kind);", "", " if (yield* savedLeft(asker, asker.repo?.name, org, needs)) {", " return reject({", " message:", " 'Whoever saved this work is out of ADMINS and holds no token that reaches it',", " });", " }", "", " return accept();", " }),", " ),", " ),", " ),") : lines(" // The drop-in's own permissions narrow nothing past `policy`'s.", " Layer.provideMerge(GitHubPolicy.layer(GitHubPolicy.make(() => Effect.succeed(accept())))),"), " Layer.provideMerge(features),", " // A webhook's deliveries and an import's calls to GitHub, each the platform's `fetch`.", ` ${unstableNextLine}`, " Layer.provide(FetchHttpClient.layer),", ");", "");
125
+ const githubFeatures = (choices, admins) => lines("/**", " * GitHub's REST, GraphQL, webhooks and Event Streams over Git's, so `gh` and Octokit work, and", " * the drop-in's features, each a line: delete one to turn it off.", " */", "const github = Layer.mergeAll(", " Inbox.layer(),", " Deployments.layer(),", " // Without it, a repo's `language` and `license` answer null.", " Languages.layer(),", " // Repo and user search, and `org:` and `user:` search over an owner's public repos.", " Search.layer(),", " // A repo's and an org's hooks, each delivery a `fetch`, and GitHub Apps, whose hooks they send.", " Layer.provideMerge(Apps.layer(), Webhooks.layer()),", " // GitHub's Event Streams over Git's event feeds.", " Streams.layer(),", " // A repo's import from GitHub, its releases among it.", " Imports.layer(),", ").pipe(", choices.objects === "packs" && " // A release's assets, in the bucket beside the packs.\n Layer.provideMerge(Releases.layer()),", " Layer.provideMerge(GitHub.layer()),", admins ? lines(" // The drop-in narrows nothing past `policy`'s, but its org and account routes ask it alone:", " // it refuses a visitor, the bootstrap, an `admin` token outside ADMINS and work saved for", " // someone who has left, as `policy` does.", " Layer.provideMerge(", " GitHubPolicy.layer(", " GitHubPolicy.make((asker) =>", " Effect.gen(function* () {", " if (asker.actor.anonymous === true || isBootstrap(asker) || adminOutside(asker)) {", " return yield* Policy.reject({", " message: 'Only an admin in ADMINS reaches this, with their admin token',", " });", " }", "", " const org = 'org' in asker.operation ? asker.operation.org : undefined;", "", " const needs = scopeFor(asker.operation.kind);", "", " if (yield* savedLeft(asker, asker.repo?.name, org, needs)) {", " return yield* Policy.reject({", " message:", " 'Whoever saved this work is out of ADMINS and holds no token that reaches it',", " });", " }", "", " return yield* Policy.accept();", " }),", " ),", " ),", " ),") : lines(" // The drop-in's own permissions narrow nothing past `policy`'s.", " Layer.provideMerge(GitHubPolicy.layer(GitHubPolicy.make(() => Policy.accept()))),"), " Layer.provideMerge(features),", " // A webhook's deliveries and an import's calls to GitHub, each the platform's `fetch`.", ` ${unstableNextLine}`, " Layer.provide(FetchHttpClient.layer),", ");", "");
121
126
  /** Git's features, and the drop-in's over them under `--serve github`. */
122
127
  const featuresLines = (choices, parts) => lines(gitFeatures(choices, parts), choices.serve === "github" && githubFeatures(choices, parts.admins === true));
123
128
  /**
@@ -1,6 +1,6 @@
1
1
  // src/init/metadata.ts
2
2
  /** The version `ref0-git`, `create-ref0-git` and Git's packages release at, all at once (Q738). */
3
- const release = "0.12.0";
3
+ const release = "0.14.0";
4
4
  /** The packages the app depends on, by their folder in a checkout's `packages/`. */
5
5
  const appPackages = [
6
6
  "infra",
@@ -13,6 +13,7 @@ const appGitSlots = [
13
13
  "queueTypes",
14
14
  "githubImport",
15
15
  "infraImport",
16
+ "effectImport",
16
17
  "safety",
17
18
  "bucket",
18
19
  "queueMerge",