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.
- package/app/apps/github/generated/git-rest.ts +152 -3
- package/app/apps/github/migrations/postgres/0001_auth.sql +8 -1
- package/app/apps/github/migrations/sql/0005_repo_grants.sql +10 -0
- package/app/apps/github/src/clients/allowed.ts +9 -4
- package/app/apps/github/src/components/repos/your-repos.tsx +57 -11
- package/app/apps/github/src/context/context.ts +45 -2
- package/app/apps/github/src/context/repo-grants.ts +35 -0
- package/app/apps/github/src/hooks/repos.ts +14 -3
- package/app/apps/github/src/policy.ts +485 -92
- package/app/apps/github/src/routes/$owner/$repo/settings/access.tsx +1 -1
- package/app/apps/github/src/routes/index.tsx +2 -1
- package/app/apps/github/src/settings/access-page.tsx +308 -0
- package/app/apps/github/src/settings/access.ts +156 -0
- package/app/apps/github/src/settings/settings-layout.tsx +0 -16
- package/app/apps/github/src/signin/auth.ts +2 -0
- package/app/apps/github/src/signin/orgs.ts +57 -14
- package/app/apps/github/src/signin/repo-grants.ts +141 -0
- package/app/pnpm-workspace.yaml +2 -2
- package/dist/cli/child.mjs +73 -3
- package/dist/cli/commands.mjs +2 -0
- package/dist/cli/documents.mjs +42 -2
- package/dist/cli/keys.mjs +431 -0
- package/dist/cli/main.mjs +148 -0
- package/dist/cli/prompt.mjs +40 -1
- package/dist/cli/ref0-git.mjs +4 -141
- package/dist/cli/setup.mjs +115 -13
- package/dist/cli/sign-in.mjs +1 -1
- package/dist/cli/tools-node.mjs +20 -0
- package/dist/cli/tools.mjs +12 -0
- package/dist/init/app.mjs +3 -1
- package/dist/init/git-module.mjs +11 -6
- package/dist/init/metadata.mjs +1 -1
- package/dist/init/template.mjs +1 -0
- package/dist/init/templates.mjs +15 -10
- package/dist/init/versions.mjs +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
import { itemsAt, parseJsonc, stringAt } from "../init/jsonc.mjs";
|
|
2
|
+
import { keysJson } from "./documents.mjs";
|
|
3
|
+
import { failure, usageFailure } from "./failure.mjs";
|
|
4
|
+
import { CliModes, answer, cliDocument, nextDocument, printable, receipt, say, secrets } from "./output.mjs";
|
|
5
|
+
import { hidden } from "./prompt.mjs";
|
|
6
|
+
import { Tools } from "./tools.mjs";
|
|
7
|
+
import * as Effect from "effect/Effect";
|
|
8
|
+
import * as Data from "effect/Data";
|
|
9
|
+
import * as Redacted from "effect/Redacted";
|
|
10
|
+
import * as Option from "effect/Option";
|
|
11
|
+
import * as Command from "effect/cli/Command";
|
|
12
|
+
import * as Schema from "effect/Schema";
|
|
13
|
+
import * as Argument from "effect/cli/Argument";
|
|
14
|
+
import * as FileSystem from "effect/FileSystem";
|
|
15
|
+
import * as Path from "effect/Path";
|
|
16
|
+
import * as Result from "effect/Result";
|
|
17
|
+
// src/cli/keys.ts
|
|
18
|
+
/**
|
|
19
|
+
* `keys`: puts R2's S3 keys for the packs' bucket on a deployed Worker, as the secrets
|
|
20
|
+
* `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID` and `R2_SECRET_ACCESS_KEY`, so its LFS links are signed
|
|
21
|
+
* straight to the bucket. It mints them through the host's own `cf` login, as an account token
|
|
22
|
+
* named `ref0-git-<worker>` that may only read and write the bucket's objects, then deletes any
|
|
23
|
+
* older token of that name. Where `cf` can't, it asks for a key pair at a hidden prompt. The
|
|
24
|
+
* secrets reach the Worker on `wrangler secret bulk`'s stdin, and nothing is written to disk.
|
|
25
|
+
* Both CLIs run through `Tools`, which only the `ref0-git` bin gives the real ones.
|
|
26
|
+
*/
|
|
27
|
+
/** The one permission group a key needs to sign the bucket's links, and the scope it's under. */
|
|
28
|
+
const itemWrite = {
|
|
29
|
+
name: "Workers R2 Storage Bucket Item Write",
|
|
30
|
+
scope: "com.cloudflare.edge.r2.bucket"
|
|
31
|
+
};
|
|
32
|
+
/** Where a person makes a key by hand, or deletes a token, in words: Cloudflare gives no deep link. */
|
|
33
|
+
const dashboard = "https://dash.cloudflare.com";
|
|
34
|
+
/** Why `cf` made no key, in words that end the run's sentence. */
|
|
35
|
+
var NotMinted = class extends Data.TaggedError("NotMinted") {};
|
|
36
|
+
/** The token's name: one per Worker, so a run finds the ones before it. */
|
|
37
|
+
const tokenName = (worker) => `ref0-git-${worker}`;
|
|
38
|
+
/**
|
|
39
|
+
* The policy the token holds: Bucket Item Write, on the one bucket. A resource is the account,
|
|
40
|
+
* the jurisdiction and the bucket's name, as R2's docs give it.
|
|
41
|
+
*/
|
|
42
|
+
const policyOf = (group, account, jurisdiction, bucket) => [{
|
|
43
|
+
effect: "allow",
|
|
44
|
+
permission_groups: [{ id: group }],
|
|
45
|
+
resources: { [`${itemWrite.scope}.${account}_${jurisdiction}_${bucket}`]: "*" }
|
|
46
|
+
}];
|
|
47
|
+
/** The policy as `cf accounts tokens create --policies` takes it: JSON, which holds no secret. */
|
|
48
|
+
const policyText = (group, account, worker) => JSON.stringify(policyOf(group, account, worker.jurisdiction, worker.bucket));
|
|
49
|
+
const configFiles = ["wrangler.jsonc", "wrangler.json"];
|
|
50
|
+
/** The Worker in `folder`, or the failure that says why `keys` can't name one. */
|
|
51
|
+
const workerIn = /* @__PURE__ */ Effect.fnUntraced(function* (folder, argv) {
|
|
52
|
+
const fs = yield* FileSystem.FileSystem;
|
|
53
|
+
const path = yield* Path.Path;
|
|
54
|
+
for (const file of configFiles) {
|
|
55
|
+
const text = yield* fs.readFileString(path.join(folder, file)).pipe(Effect.orElseSucceed(() => void 0));
|
|
56
|
+
if (text === void 0) continue;
|
|
57
|
+
const root = parseJsonc(text);
|
|
58
|
+
const name = stringAt(root, ["name"]);
|
|
59
|
+
const packs = itemsAt(root, ["r2_buckets"]).find((item) => stringAt(item, ["binding"]) === "PACKS");
|
|
60
|
+
const bucket = stringAt(packs, ["bucket_name"]);
|
|
61
|
+
if (name === void 0 || bucket === void 0) return yield* failure("no_packs_bucket", `${file} names no Worker and PACKS bucket, which keys signs links to`, {
|
|
62
|
+
says: "Set Git up in it first",
|
|
63
|
+
run: [["init", ...argv]]
|
|
64
|
+
});
|
|
65
|
+
return {
|
|
66
|
+
folder,
|
|
67
|
+
argv,
|
|
68
|
+
name,
|
|
69
|
+
bucket,
|
|
70
|
+
jurisdiction: stringAt(packs, ["jurisdiction"]) ?? "default",
|
|
71
|
+
account: stringAt(root, ["account_id"])
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return yield* failure("no_worker_config", `${printable(folder)} has no wrangler.jsonc or wrangler.json, which keys reads the Worker and its bucket from`, {
|
|
75
|
+
says: "Set Git up in it first",
|
|
76
|
+
run: [["init", ...argv]]
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
/** A child's first line on stderr, made safe to print, or its exit, for a sentence's end. */
|
|
80
|
+
const saidBy = (ran, program) => {
|
|
81
|
+
if (ran.exit === null) return ran.signal === null ? `${program} isn't on PATH` : `${program} stopped on ${ran.signal}`;
|
|
82
|
+
const line = ran.stderr.split("\n").map((each) => each.trim()).find((each) => each !== "");
|
|
83
|
+
return line === void 0 ? `${program} exited ${ran.exit}` : `${program} said "${printable(line).slice(0, 200)}"`;
|
|
84
|
+
};
|
|
85
|
+
/** `cf`'s JSON on stdout as `schema` reads it, bare or in a `result`, or `undefined`. */
|
|
86
|
+
const cfAnswer = (schema) => {
|
|
87
|
+
const bare = Schema.decodeUnknownOption(Schema.fromJsonString(schema));
|
|
88
|
+
const wrapped = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Struct({ result: schema })));
|
|
89
|
+
return (stdout) => Option.getOrUndefined(Option.orElse(bare(stdout), () => Option.map(wrapped(stdout), (read) => read.result)));
|
|
90
|
+
};
|
|
91
|
+
const Group = /* @__PURE__ */ Schema.Struct({
|
|
92
|
+
id: Schema.String,
|
|
93
|
+
name: Schema.String,
|
|
94
|
+
scopes: Schema.optional(Schema.Array(Schema.String))
|
|
95
|
+
});
|
|
96
|
+
const readGroups = cfAnswer(Schema.Array(Group));
|
|
97
|
+
/** A token as `cf` prints one: `issued_on` is when it was made, as Cloudflare's API names it. */
|
|
98
|
+
const Token = /* @__PURE__ */ Schema.Struct({
|
|
99
|
+
id: Schema.String,
|
|
100
|
+
name: Schema.String,
|
|
101
|
+
issued_on: Schema.optional(Schema.String)
|
|
102
|
+
});
|
|
103
|
+
const readMinted = cfAnswer(Schema.Struct({
|
|
104
|
+
id: Schema.String,
|
|
105
|
+
value: Schema.String,
|
|
106
|
+
issued_on: Schema.optional(Schema.String)
|
|
107
|
+
}));
|
|
108
|
+
const readTokens = cfAnswer(Schema.Array(Token));
|
|
109
|
+
const readAccounts = cfAnswer(Schema.Array(Schema.Struct({ id: Schema.String })));
|
|
110
|
+
/** `tool` run by the run's `Tools` in the Worker's folder, on `account` when it's known. */
|
|
111
|
+
const ran = /* @__PURE__ */ Effect.fnUntraced(function* (tool, worker, account, args, input) {
|
|
112
|
+
return yield* (yield* Tools).run(tool, args, worker.folder, {
|
|
113
|
+
env: account === void 0 ? {} : { CLOUDFLARE_ACCOUNT_ID: account },
|
|
114
|
+
input
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
/** `cf` run in the Worker's folder, on `account` when it's known. */
|
|
118
|
+
const cf = (worker, account, args) => ran("cf", worker, account, args);
|
|
119
|
+
/** `wrangler` run in the Worker's folder, on its account, with `input` on its stdin. */
|
|
120
|
+
const wrangler = (worker, account, args, input) => ran("wrangler", worker, account, args, input);
|
|
121
|
+
/**
|
|
122
|
+
* The account the Worker is in: `CLOUDFLARE_ACCOUNT_ID`, then the config's `account_id`, then the
|
|
123
|
+
* one account `cf`'s login sees. With none of those, the run stops: a key made on the wrong
|
|
124
|
+
* account would sign nothing.
|
|
125
|
+
*/
|
|
126
|
+
const accountOf = /* @__PURE__ */ Effect.fnUntraced(function* (worker) {
|
|
127
|
+
const given = process.env["CLOUDFLARE_ACCOUNT_ID"];
|
|
128
|
+
if (given !== void 0 && given !== "") return given;
|
|
129
|
+
if (worker.account !== void 0) return worker.account;
|
|
130
|
+
const listed = yield* cf(worker, void 0, ["accounts", "list"]);
|
|
131
|
+
const accounts = listed.exit === 0 ? readAccounts(listed.stdout) : void 0;
|
|
132
|
+
const [only] = accounts ?? [];
|
|
133
|
+
if (accounts?.length === 1 && only !== void 0) return only.id;
|
|
134
|
+
return yield* usageFailure("account_unknown", accounts === void 0 ? `keys can't tell which Cloudflare account ${printable(worker.name)} is in: ${saidBy(listed, "cf")}` : `cf's login sees ${accounts.length} accounts, and keys can't tell which ${printable(worker.name)} is in`, {
|
|
135
|
+
says: "Set CLOUDFLARE_ACCOUNT_ID to the Worker's account, or account_id in its config, then run it again",
|
|
136
|
+
run: [["keys", ...worker.argv]]
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
const readSecrets = cfAnswer(Schema.Array(Schema.Struct({ name: Schema.String })));
|
|
140
|
+
/**
|
|
141
|
+
* Whether the Worker is deployed, as `wrangler secret list` answers: it reads, and makes nothing,
|
|
142
|
+
* where a put on a Worker that isn't there would publish a placeholder at its name. A deployed
|
|
143
|
+
* Worker's `names` are its secrets', or `undefined` when wrangler's answer doesn't read as a list.
|
|
144
|
+
*/
|
|
145
|
+
const deployed = /* @__PURE__ */ Effect.fnUntraced(function* (worker, account) {
|
|
146
|
+
const listed = yield* wrangler(worker, account, [
|
|
147
|
+
"secret",
|
|
148
|
+
"list",
|
|
149
|
+
"--name",
|
|
150
|
+
worker.name,
|
|
151
|
+
"--format",
|
|
152
|
+
"json"
|
|
153
|
+
]);
|
|
154
|
+
return listed.exit === 0 ? {
|
|
155
|
+
deployed: true,
|
|
156
|
+
names: readSecrets(listed.stdout)?.map((each) => each.name)
|
|
157
|
+
} : {
|
|
158
|
+
deployed: false,
|
|
159
|
+
why: saidBy(listed, "wrangler")
|
|
160
|
+
};
|
|
161
|
+
});
|
|
162
|
+
/** SHA-256 of `text`, in hex: R2's Secret Access Key for a token's value. */
|
|
163
|
+
const sha256Hex = (text) => Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(Effect.map((digest) => Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")));
|
|
164
|
+
/**
|
|
165
|
+
* A token minted through `cf`'s login, holding Bucket Item Write on the bucket alone: its ID is the
|
|
166
|
+
* Access Key ID, and the SHA-256 of its value the Secret Access Key. The group's ID is looked up
|
|
167
|
+
* by its name and scope each run, since Cloudflare's docs call the names cosmetic and give no IDs.
|
|
168
|
+
*/
|
|
169
|
+
const minted = /* @__PURE__ */ Effect.fnUntraced(function* (worker, account) {
|
|
170
|
+
const groups = yield* cf(worker, account, [
|
|
171
|
+
"accounts",
|
|
172
|
+
"tokens",
|
|
173
|
+
"permission-groups",
|
|
174
|
+
"list",
|
|
175
|
+
"--name",
|
|
176
|
+
itemWrite.name,
|
|
177
|
+
"--scope",
|
|
178
|
+
itemWrite.scope
|
|
179
|
+
]);
|
|
180
|
+
if (groups.exit !== 0) return yield* new NotMinted({ why: saidBy(groups, "cf") });
|
|
181
|
+
const group = readGroups(groups.stdout)?.find((each) => each.name === itemWrite.name && (each.scopes ?? [itemWrite.scope]).includes(itemWrite.scope));
|
|
182
|
+
if (group === void 0) return yield* new NotMinted({ why: `cf listed no ${itemWrite.name} group` });
|
|
183
|
+
const made = yield* cf(worker, account, [
|
|
184
|
+
"accounts",
|
|
185
|
+
"tokens",
|
|
186
|
+
"create",
|
|
187
|
+
"--name",
|
|
188
|
+
tokenName(worker.name),
|
|
189
|
+
"--policies",
|
|
190
|
+
policyText(group.id, account, worker)
|
|
191
|
+
]);
|
|
192
|
+
const token = made.exit === 0 ? readMinted(made.stdout) : void 0;
|
|
193
|
+
if (token === void 0) return yield* new NotMinted({ why: saidBy(made, "cf") });
|
|
194
|
+
secrets.hide(token.value);
|
|
195
|
+
const secret = yield* sha256Hex(token.value);
|
|
196
|
+
secrets.hide(secret);
|
|
197
|
+
return {
|
|
198
|
+
id: token.id,
|
|
199
|
+
secret: Redacted.make(secret),
|
|
200
|
+
issued: token.issued_on
|
|
201
|
+
};
|
|
202
|
+
});
|
|
203
|
+
/** Deletes token `id` through `cf`: whether it did, or why not. */
|
|
204
|
+
const deleted = /* @__PURE__ */ Effect.fnUntraced(function* (worker, account, id) {
|
|
205
|
+
const ran = yield* cf(worker, account, [
|
|
206
|
+
"accounts",
|
|
207
|
+
"tokens",
|
|
208
|
+
"delete",
|
|
209
|
+
id,
|
|
210
|
+
"--force"
|
|
211
|
+
]);
|
|
212
|
+
return ran.exit === 0 ? void 0 : saidBy(ran, "cf");
|
|
213
|
+
});
|
|
214
|
+
/**
|
|
215
|
+
* Whether `token` is an older one of `kept`'s: its exact name, and made strictly before it, so a
|
|
216
|
+
* run never deletes the token of a run that started after it.
|
|
217
|
+
*/
|
|
218
|
+
const olderThan = (token, name, kept) => token.name === name && token.id !== kept.id && Date.parse(token.issued_on ?? "") < kept.made;
|
|
219
|
+
/**
|
|
220
|
+
* Deletes every token named as `kept` is and made before it, from at most `tokenPagesMost` pages
|
|
221
|
+
* of `tokenPage`: a re-run's new key replaces the old, which then signs nothing. A list or a
|
|
222
|
+
* delete `cf`'s login refuses stops there, and says why.
|
|
223
|
+
*/
|
|
224
|
+
const olderDeleted = /* @__PURE__ */ Effect.fnUntraced(function* (worker, account, kept) {
|
|
225
|
+
const name = tokenName(worker.name);
|
|
226
|
+
const made = Date.parse(kept.issued ?? "");
|
|
227
|
+
if (Number.isNaN(made)) return {
|
|
228
|
+
deleted: [],
|
|
229
|
+
notDeleted: "cf didn't say when it made the new token, so keys can't tell which are older"
|
|
230
|
+
};
|
|
231
|
+
const found = [];
|
|
232
|
+
for (let page = 1; page <= 20; page += 1) {
|
|
233
|
+
const listed = yield* cf(worker, account, [
|
|
234
|
+
"accounts",
|
|
235
|
+
"tokens",
|
|
236
|
+
"list",
|
|
237
|
+
"--page",
|
|
238
|
+
`${page}`,
|
|
239
|
+
"--per-page",
|
|
240
|
+
`50`
|
|
241
|
+
]);
|
|
242
|
+
const tokens = listed.exit === 0 ? readTokens(listed.stdout) : void 0;
|
|
243
|
+
if (tokens === void 0) return {
|
|
244
|
+
deleted: [],
|
|
245
|
+
notDeleted: saidBy(listed, "cf")
|
|
246
|
+
};
|
|
247
|
+
found.push(...tokens.filter((each) => olderThan(each, name, {
|
|
248
|
+
id: kept.id,
|
|
249
|
+
made
|
|
250
|
+
})).map((each) => each.id));
|
|
251
|
+
if (tokens.length < 50) break;
|
|
252
|
+
}
|
|
253
|
+
const gone = [];
|
|
254
|
+
for (const id of found) {
|
|
255
|
+
const why = yield* deleted(worker, account, id);
|
|
256
|
+
if (why !== void 0) return {
|
|
257
|
+
deleted: gone,
|
|
258
|
+
notDeleted: why
|
|
259
|
+
};
|
|
260
|
+
gone.push(id);
|
|
261
|
+
}
|
|
262
|
+
return { deleted: gone };
|
|
263
|
+
});
|
|
264
|
+
/** The 3 secrets, as `wrangler secret bulk` reads them on stdin: JSON, never a file. */
|
|
265
|
+
const secretsOf = (account, key) => JSON.stringify({
|
|
266
|
+
R2_ACCOUNT_ID: account,
|
|
267
|
+
R2_ACCESS_KEY_ID: key.id,
|
|
268
|
+
R2_SECRET_ACCESS_KEY: Redacted.value(key.secret)
|
|
269
|
+
});
|
|
270
|
+
/** Where a person makes a key by hand, and runs `keys` again to paste it. */
|
|
271
|
+
const byHand = (worker) => ({
|
|
272
|
+
says: `Make an R2 API token with Object Read & Write on ${printable(worker.bucket)}, from R2's Manage API tokens at ${dashboard}, then run keys in a terminal to paste it`,
|
|
273
|
+
run: [["keys", ...worker.argv]]
|
|
274
|
+
});
|
|
275
|
+
/** The words for deleting older tokens by hand. */
|
|
276
|
+
const deleteByHand = (worker) => `Delete any older ${tokenName(printable(worker.name))} token from Manage account > Account API tokens, at ${dashboard}`;
|
|
277
|
+
/** R2's Access Key ID: 32 hex digits. */
|
|
278
|
+
const r2AccessKeyId = /^[0-9a-f]{32}$/i;
|
|
279
|
+
/** R2's Secret Access Key: 64 hex digits, a SHA-256. */
|
|
280
|
+
const r2SecretAccessKey = /^[0-9a-f]{64}$/i;
|
|
281
|
+
/** A key pair typed at hidden prompts, as R2's Manage API tokens shows one. */
|
|
282
|
+
const pasted = /* @__PURE__ */ Effect.fnUntraced(function* (worker, why) {
|
|
283
|
+
yield* say(`cf didn't make the key: ${why}.`, `Make an R2 API token with Object Read & Write on ${printable(worker.bucket)}, from R2's Manage API tokens at ${dashboard}, and paste its keys.`);
|
|
284
|
+
const id = yield* hidden("Access Key ID");
|
|
285
|
+
const secret = yield* hidden("Secret Access Key");
|
|
286
|
+
secrets.hide(id);
|
|
287
|
+
secrets.hide(secret);
|
|
288
|
+
if (id === "" || secret === "") return yield* usageFailure("key_not_given", "No key was pasted, so keys put nothing", byHand(worker));
|
|
289
|
+
if (!r2AccessKeyId.test(id)) return yield* usageFailure("key_malformed", `The Access Key ID pasted is ${id.length} characters, not R2's 32 hex digits, so keys put nothing`, byHand(worker));
|
|
290
|
+
if (!r2SecretAccessKey.test(secret)) return yield* usageFailure("key_malformed", `The Secret Access Key pasted is ${secret.length} characters, not R2's 64 hex digits, so keys put nothing`, byHand(worker));
|
|
291
|
+
return {
|
|
292
|
+
id,
|
|
293
|
+
secret: Redacted.make(secret)
|
|
294
|
+
};
|
|
295
|
+
});
|
|
296
|
+
/**
|
|
297
|
+
* Puts the Worker's keys: mints them through `cf`, or, when `prompt` and `cf` can't, takes them at
|
|
298
|
+
* a hidden prompt, and puts all 3 secrets in one `wrangler secret bulk`. Once they're put, older
|
|
299
|
+
* tokens of its name are deleted. A put that fails may still have reached the Worker, so its token
|
|
300
|
+
* is kept, and named: the next run deletes it as older.
|
|
301
|
+
*/
|
|
302
|
+
const putKeys = /* @__PURE__ */ Effect.fnUntraced(function* (worker, account, prompt) {
|
|
303
|
+
const tried = yield* minted(worker, account).pipe(Effect.map((key) => Result.succeed(key)), Effect.catchTag("NotMinted", (notMinted) => Effect.succeed(Result.fail(notMinted))));
|
|
304
|
+
const key = Result.isSuccess(tried) ? tried.success : prompt ? yield* pasted(worker, tried.failure.why) : yield* usageFailure("key_not_made", `cf didn't make the key: ${tried.failure.why}`, byHand(worker));
|
|
305
|
+
const put = yield* wrangler(worker, account, [
|
|
306
|
+
"secret",
|
|
307
|
+
"bulk",
|
|
308
|
+
"--name",
|
|
309
|
+
worker.name
|
|
310
|
+
], secretsOf(account, key));
|
|
311
|
+
if (put.exit !== 0) return yield* failure("secrets_not_put", `wrangler may not have put the keys on ${printable(worker.name)}: ${saidBy(put, "wrangler")}${Result.isSuccess(tried) ? `. The token ${printable(key.id)} it made stays live, since the Worker may hold it, until keys runs again and deletes it` : ""}`, {
|
|
312
|
+
says: "Run it again",
|
|
313
|
+
run: [["keys", ...worker.argv]]
|
|
314
|
+
});
|
|
315
|
+
const base = {
|
|
316
|
+
worker,
|
|
317
|
+
account,
|
|
318
|
+
accessKeyId: key.id
|
|
319
|
+
};
|
|
320
|
+
if (Result.isFailure(tried)) return {
|
|
321
|
+
...base,
|
|
322
|
+
made: "pasted"
|
|
323
|
+
};
|
|
324
|
+
return {
|
|
325
|
+
...base,
|
|
326
|
+
made: "cf",
|
|
327
|
+
older: yield* olderDeleted(worker, account, tried.success)
|
|
328
|
+
};
|
|
329
|
+
});
|
|
330
|
+
/** A run's receipt rows, as `keys` and `init` print them. */
|
|
331
|
+
const keysFields = (done) => [
|
|
332
|
+
["Worker", printable(done.worker.name)],
|
|
333
|
+
["Bucket", printable(done.worker.bucket)],
|
|
334
|
+
["Key", done.made === "cf" ? `${tokenName(printable(done.worker.name))}, ${printable(done.accessKeyId)}, made with cf` : `${printable(done.accessKeyId)}, pasted`],
|
|
335
|
+
...done.older === void 0 ? [] : [["Older tokens", done.older.notDeleted !== void 0 ? done.older.deleted.length === 0 ? `not deleted: ${done.older.notDeleted}` : `deleted ${done.older.deleted.map(printable).join(", ")}, then no more: ${done.older.notDeleted}` : done.older.deleted.length === 0 ? "none" : `deleted ${done.older.deleted.map(printable).join(", ")}`]]
|
|
336
|
+
];
|
|
337
|
+
/** The step a run leaves, when older tokens may still be live. */
|
|
338
|
+
const keysNext = (done) => done.older?.notDeleted === void 0 ? void 0 : {
|
|
339
|
+
says: deleteByHand(done.worker),
|
|
340
|
+
run: []
|
|
341
|
+
};
|
|
342
|
+
/** `keys`' document, as `--json` prints it. */
|
|
343
|
+
const keysDocument = (done) => {
|
|
344
|
+
const document = {
|
|
345
|
+
worker: done.worker.name,
|
|
346
|
+
bucket: done.worker.bucket,
|
|
347
|
+
account: done.account,
|
|
348
|
+
accessKeyId: done.accessKeyId,
|
|
349
|
+
made: done.made
|
|
350
|
+
};
|
|
351
|
+
if (done.made === "cf") document.token = tokenName(done.worker.name);
|
|
352
|
+
if (done.older !== void 0) document.older = done.older;
|
|
353
|
+
const next = keysNext(done);
|
|
354
|
+
if (next !== void 0) document.nextStep = nextDocument(next);
|
|
355
|
+
return document;
|
|
356
|
+
};
|
|
357
|
+
const keysCommand = Command.make("keys", { dir: Argument.String("DIR").pipe(Argument.withDescription("The Worker's folder: the current one when left out"), Argument.optional) }, /* @__PURE__ */ Effect.fnUntraced(function* (flags) {
|
|
358
|
+
const path = yield* Path.Path;
|
|
359
|
+
const given = Option.getOrUndefined(flags.dir);
|
|
360
|
+
const worker = yield* workerIn(given === void 0 ? process.cwd() : path.resolve(given), given === void 0 ? [] : [given]);
|
|
361
|
+
const account = yield* accountOf(worker);
|
|
362
|
+
const found = yield* deployed(worker, account);
|
|
363
|
+
if (!found.deployed) return yield* failure("worker_not_deployed", `${printable(worker.name)} isn't deployed, or wrangler can't read it: ${found.why}`, {
|
|
364
|
+
says: "Deploy it with `wrangler deploy`, then make its keys",
|
|
365
|
+
run: [["keys", ...worker.argv]]
|
|
366
|
+
});
|
|
367
|
+
const mode = yield* CliModes;
|
|
368
|
+
const done = yield* putKeys(worker, account, mode.interactive);
|
|
369
|
+
if (mode.json) return yield* cliDocument(keysJson, keysDocument(done));
|
|
370
|
+
if (!mode.stdoutTerminal || !mode.interactive) yield* answer(done.accessKeyId);
|
|
371
|
+
const next = keysNext(done);
|
|
372
|
+
yield* receipt({
|
|
373
|
+
done: `Put R2's keys on ${printable(worker.name)}`,
|
|
374
|
+
fields: keysFields(done),
|
|
375
|
+
next
|
|
376
|
+
});
|
|
377
|
+
})).pipe(Command.withDescription("Put R2's keys on a deployed Worker, so its LFS links sign straight to the bucket; two runs at once can leave it a deleted key, which running keys again settles (experimental)"));
|
|
378
|
+
/**
|
|
379
|
+
* `keys` as `init` runs it: only for a person at a terminal who didn't pass `--no-keys`, and only on
|
|
380
|
+
* a Worker `wrangler secret list` reads as deployed and lacking one of `names`, so an unchanged
|
|
381
|
+
* re-run never rotates a key in use; with no prompt, since `init` asked its questions already.
|
|
382
|
+
* Anything short of a deployed Worker is `undefined`, and `init`'s next step names `keys`.
|
|
383
|
+
*/
|
|
384
|
+
const keysOnInit = /* @__PURE__ */ Effect.fnUntraced(function* (folder, names, asked) {
|
|
385
|
+
const mode = yield* CliModes;
|
|
386
|
+
if (!asked || !mode.interactive) return { kind: "notAsked" };
|
|
387
|
+
const found = yield* Effect.gen(function* () {
|
|
388
|
+
const worker = yield* workerIn(folder.path, folder.argv);
|
|
389
|
+
const account = yield* accountOf(worker);
|
|
390
|
+
const read = yield* deployed(worker, account);
|
|
391
|
+
return read.deployed && read.names !== void 0 ? {
|
|
392
|
+
worker,
|
|
393
|
+
account,
|
|
394
|
+
names: read.names
|
|
395
|
+
} : void 0;
|
|
396
|
+
}).pipe(Effect.orElseSucceed(() => void 0));
|
|
397
|
+
if (found === void 0) return void 0;
|
|
398
|
+
if (names.every((name) => found.names.includes(name))) return { kind: "present" };
|
|
399
|
+
yield* say(` Putting R2's keys on ${printable(found.worker.name)}...`);
|
|
400
|
+
return yield* putKeys(found.worker, found.account, false).pipe(Effect.match({
|
|
401
|
+
onSuccess: (put) => ({
|
|
402
|
+
kind: "put",
|
|
403
|
+
put
|
|
404
|
+
}),
|
|
405
|
+
onFailure: (failed) => ({
|
|
406
|
+
kind: "notPut",
|
|
407
|
+
why: failed.headline,
|
|
408
|
+
next: failed.next
|
|
409
|
+
})
|
|
410
|
+
}));
|
|
411
|
+
});
|
|
412
|
+
/** What `init`'s document says of the keys, when it looked at them. */
|
|
413
|
+
const initKeysDocument = (keys) => {
|
|
414
|
+
if (keys === void 0 || keys.kind === "notAsked") return void 0;
|
|
415
|
+
if (keys.kind === "put") return keysDocument(keys.put);
|
|
416
|
+
if (keys.kind === "present") return { present: true };
|
|
417
|
+
return { notPut: keys.why };
|
|
418
|
+
};
|
|
419
|
+
/** What `init`'s receipt says of the keys, when it looked at them. */
|
|
420
|
+
const initKeysFields = (keys) => {
|
|
421
|
+
if (keys === void 0 || keys.kind === "notAsked") return [];
|
|
422
|
+
if (keys.kind === "put") return keysFields(keys.put);
|
|
423
|
+
if (keys.kind === "present") return [["Keys", "on the Worker already: keys rotates them"]];
|
|
424
|
+
return [["Keys", `not put: ${keys.why}`]];
|
|
425
|
+
};
|
|
426
|
+
/** The step a run of `keys` from `init` leaves, as `keys` itself would: where it can't recover alone. */
|
|
427
|
+
const initKeysNext = (keys) => {
|
|
428
|
+
if (keys?.kind === "put") return keysNext(keys.put);
|
|
429
|
+
if (keys?.kind === "notPut") return keys.next;
|
|
430
|
+
};
|
|
431
|
+
export { NotMinted, accountOf, deployed, initKeysDocument, initKeysFields, initKeysNext, itemWrite, keysCommand, keysDocument, keysFields, keysNext, keysOnInit, olderThan, policyOf, putKeys, tokenName, workerIn };
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { signals } from "./credentials.mjs";
|
|
2
|
+
import { failureJson, helpJson } from "./documents.mjs";
|
|
3
|
+
import { CliFailure, cancelled, exitCodes, failure, leftovers, snakeCase, usageFailure } from "./failure.mjs";
|
|
4
|
+
import { node, written } from "./node.mjs";
|
|
5
|
+
import { CliModes, flagOn, modesOf, nextDocument, nextLines, printable, secrets } from "./output.mjs";
|
|
6
|
+
import { ref0Git } from "./commands.mjs";
|
|
7
|
+
import { runControl } from "./run-end.mjs";
|
|
8
|
+
import { layer } from "./runtime.mjs";
|
|
9
|
+
import { Tools } from "./tools.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";
|
|
23
|
+
// src/cli/main.ts
|
|
24
|
+
/**
|
|
25
|
+
* `ref0-git`'s run, as `npx ref0-git` starts it: its commands, and the one place a run ends, saying
|
|
26
|
+
* its failure and exiting 0, 1, 2 for usage, or 130; a defect's cause, which could hold a
|
|
27
|
+
* credential, isn't said. `tools` runs `cf` and `wrangler`: its bin gives the real ones, and the
|
|
28
|
+
* tests' bin their own.
|
|
29
|
+
*/
|
|
30
|
+
const { process } = node;
|
|
31
|
+
const formatter = CliOutput.defaultFormatter({ colors: false });
|
|
32
|
+
const args = process.argv.slice(2);
|
|
33
|
+
const json = flagOn(args, "json");
|
|
34
|
+
/** The lifecycle labels a description ends with, in parentheses. */
|
|
35
|
+
const labels = ["experimental", "beta"];
|
|
36
|
+
/** A description's lifecycle label, in its parentheses, and the words before it. */
|
|
37
|
+
const labelled = (description) => {
|
|
38
|
+
const label = labels.find((each) => description.endsWith(`(${each})`));
|
|
39
|
+
return label === void 0 ? {
|
|
40
|
+
description,
|
|
41
|
+
lifecycle: "stable"
|
|
42
|
+
} : {
|
|
43
|
+
description: description.slice(0, -`(${label})`.length).trimEnd(),
|
|
44
|
+
lifecycle: label
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
/** Help as `--help --json` prints it: the command, its arguments, flags and subcommands. */
|
|
48
|
+
const helpDocument = (help) => ({
|
|
49
|
+
command: (help.commandPath ?? []).join(" "),
|
|
50
|
+
...labelled(help.description),
|
|
51
|
+
usage: help.usage,
|
|
52
|
+
arguments: (help.args ?? []).map((arg) => ({
|
|
53
|
+
name: arg.name,
|
|
54
|
+
description: Option.getOrUndefined(arg.description),
|
|
55
|
+
required: arg.required
|
|
56
|
+
})),
|
|
57
|
+
flags: [...help.flags, ...help.globalFlags ?? []].map((flag) => ({
|
|
58
|
+
name: `--${flag.name}`,
|
|
59
|
+
description: Option.getOrUndefined(flag.description),
|
|
60
|
+
required: flag.required
|
|
61
|
+
})),
|
|
62
|
+
commands: (help.subcommands ?? []).flatMap((group) => group.commands).map((command) => ({
|
|
63
|
+
name: command.name,
|
|
64
|
+
...labelled(command.description)
|
|
65
|
+
}))
|
|
66
|
+
});
|
|
67
|
+
/** Help, as text or, with `--json`, as one document. */
|
|
68
|
+
const helpText = (help) => json ? helpJson(helpDocument(help)) : formatter.formatHelpDoc(help);
|
|
69
|
+
/** The help a parse showed with no request for it: printed only when nothing failed. */
|
|
70
|
+
let implicitHelp;
|
|
71
|
+
const printed = (text) => Effect.promise(() => written(process.stdout, `${text}\n`).catch(() => void 0));
|
|
72
|
+
/** Help asked for and the version go to stdout; help shown for a refusal waits for the run's end. */
|
|
73
|
+
const presenter = { present: Match.type().pipe(Match.tag("Help", (event) => event.reason === "Implicit" ? Effect.sync(() => {
|
|
74
|
+
implicitHelp = event.helpDoc;
|
|
75
|
+
}) : printed(helpText(event.helpDoc))), Match.tag("Version", (event) => printed(event.version)), Match.tag("InvalidInvocation", () => Effect.void), Match.exhaustive) };
|
|
76
|
+
const cliLayer = Layer.mergeAll(layer, CliConfig.layer({ builtIns: [GlobalFlag.Help, GlobalFlag.Version] }), CliOutput.layerPresenter(presenter));
|
|
77
|
+
/** A parse's refusal as the CLI's failure, naming the command's help. */
|
|
78
|
+
const usageOf = (error) => {
|
|
79
|
+
const [first] = error.errors;
|
|
80
|
+
const [, ...path] = error.commandPath;
|
|
81
|
+
return usageFailure(snakeCase(first?._tag ?? "missing_command"), first?.message ?? `${error.commandPath.join(" ")} needs a command`, {
|
|
82
|
+
says: "See its help",
|
|
83
|
+
run: [[...path, "--help"]]
|
|
84
|
+
});
|
|
85
|
+
};
|
|
86
|
+
/** A cancelled run's failure: what its command's clean-up says it may have left, if anything. */
|
|
87
|
+
const cancelledFailure = () => new CliFailure({
|
|
88
|
+
class: "cancelled",
|
|
89
|
+
reason: "canceled",
|
|
90
|
+
headline: cancelled.left?.headline ?? "Canceled",
|
|
91
|
+
next: cancelled.left?.next
|
|
92
|
+
});
|
|
93
|
+
/** What ended the run, as a failure to say, or `undefined` when it finished. */
|
|
94
|
+
const failureOf = (exit) => {
|
|
95
|
+
if (Exit.isSuccess(exit)) return void 0;
|
|
96
|
+
if (Cause.hasInterruptsOnly(exit.cause)) return cancelledFailure();
|
|
97
|
+
const error = Cause.squash(exit.cause);
|
|
98
|
+
if (error instanceof CliFailure) return error;
|
|
99
|
+
if (CliError.isCliError(error) && Predicate.isTagged(error, "ShowHelp")) return error.errors.length === 0 ? "help" : usageOf(error);
|
|
100
|
+
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");
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* A failure as its words on stderr, after `ref0-git: `, or with `--json` as one line: the
|
|
104
|
+
* `cli-design` skill's error document. Every part goes through `printable`, which also takes out
|
|
105
|
+
* each secret the run holds, since a hostile host's refusal could echo one.
|
|
106
|
+
*/
|
|
107
|
+
const failureLine = (failed) => {
|
|
108
|
+
const next = failed.next === void 0 ? void 0 : {
|
|
109
|
+
says: printable(failed.next.says),
|
|
110
|
+
run: failed.next.run
|
|
111
|
+
};
|
|
112
|
+
const document = {
|
|
113
|
+
status: failed.class === "usage" ? "action_required" : "error",
|
|
114
|
+
reason: failed.reason,
|
|
115
|
+
message: printable(failed.headline),
|
|
116
|
+
nextStep: next === void 0 ? void 0 : nextDocument(next),
|
|
117
|
+
data: failed.findings === void 0 ? failed.data : { findings: failed.findings }
|
|
118
|
+
};
|
|
119
|
+
const lines = [`ref0-git: ${document.message}`, ...next === void 0 || json ? [] : nextLines(next)];
|
|
120
|
+
return json ? `${secrets.scrub(failureJson(document))}\n` : `${lines.join("\n")}\n`;
|
|
121
|
+
};
|
|
122
|
+
const main = async (tools) => {
|
|
123
|
+
const fiber = Effect.runFork(Command.runWith(ref0Git, {
|
|
124
|
+
version: "0.0.0",
|
|
125
|
+
renderErrors: false
|
|
126
|
+
})(args).pipe(Effect.provide(cliLayer), Effect.provideService(CliModes, modesOf({
|
|
127
|
+
json,
|
|
128
|
+
nonInteractive: flagOn(args, "non-interactive")
|
|
129
|
+
})), Effect.provideService(Tools, tools)));
|
|
130
|
+
process.stdout.on("error", () => void 0);
|
|
131
|
+
process.stderr.on("error", () => void 0);
|
|
132
|
+
/** The run's signals and its end, as one state machine: `run-end.ts`' `runControl`. */
|
|
133
|
+
const control = runControl({
|
|
134
|
+
stderr: (text) => written(process.stderr, text),
|
|
135
|
+
exit: (code) => process.exit(code),
|
|
136
|
+
interrupt: () => Effect.runFork(Fiber.interrupt(fiber)),
|
|
137
|
+
leftovers: () => leftovers,
|
|
138
|
+
cancelledLine: () => failureLine(cancelledFailure())
|
|
139
|
+
});
|
|
140
|
+
for (const [signal, status] of signals) process.on(signal, () => control.signal(status));
|
|
141
|
+
const ended = failureOf(await Effect.runPromise(Fiber.await(fiber)));
|
|
142
|
+
if (ended === "help" && implicitHelp !== void 0) await written(process.stdout, `${helpText(implicitHelp)}\n`).catch(() => void 0);
|
|
143
|
+
await control.ended({
|
|
144
|
+
status: ended instanceof CliFailure ? exitCodes[ended.class] : 0,
|
|
145
|
+
failureLine: ended instanceof CliFailure ? failureLine(ended) : void 0
|
|
146
|
+
});
|
|
147
|
+
};
|
|
148
|
+
export { main };
|
package/dist/cli/prompt.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { field, stderrText } from "./output.mjs";
|
|
2
2
|
import * as Effect from "effect/Effect";
|
|
3
3
|
import * as Terminal from "effect/Terminal";
|
|
4
|
+
import * as Option from "effect/Option";
|
|
4
5
|
import * as Queue from "effect/Queue";
|
|
5
6
|
// src/cli/prompt.ts
|
|
6
7
|
/** The question and its options, `at` selected. */
|
|
@@ -32,4 +33,42 @@ const select = /* @__PURE__ */ Effect.fnUntraced(function* (row, question, optio
|
|
|
32
33
|
}
|
|
33
34
|
}));
|
|
34
35
|
});
|
|
35
|
-
|
|
36
|
+
/** What `input` does to `sofar`, at a hidden prompt. */
|
|
37
|
+
const typed = (input, sofar) => {
|
|
38
|
+
const { name, ctrl } = input.key;
|
|
39
|
+
if (ctrl && name === "c") return { kind: "cancel" };
|
|
40
|
+
if (name === "return" || name === "enter") return {
|
|
41
|
+
kind: "take",
|
|
42
|
+
line: sofar
|
|
43
|
+
};
|
|
44
|
+
if (name === "backspace") return {
|
|
45
|
+
kind: "typing",
|
|
46
|
+
sofar: sofar.slice(0, -1)
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
kind: "typing",
|
|
50
|
+
sofar: ctrl || Option.isNone(input.input) ? sofar : `${sofar}${input.input.value}`
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* One line asked on stderr whose answer is never drawn, as a secret is pasted: Enter takes it,
|
|
55
|
+
* Ctrl-C cancels the run. Only an interactive run calls it.
|
|
56
|
+
*/
|
|
57
|
+
const hidden = /* @__PURE__ */ Effect.fnUntraced(function* (question) {
|
|
58
|
+
const terminal = yield* Terminal.Terminal;
|
|
59
|
+
yield* stderrText(`? ${question} (hidden): `);
|
|
60
|
+
return yield* Effect.scoped(Effect.gen(function* () {
|
|
61
|
+
const keys = yield* terminal.readInput;
|
|
62
|
+
let sofar = "";
|
|
63
|
+
for (;;) {
|
|
64
|
+
const next = yield* Queue.take(keys).pipe(Effect.map((input) => typed(input, sofar)), Effect.orElseSucceed(() => ({ kind: "cancel" })));
|
|
65
|
+
if (next.kind === "cancel") return yield* Effect.interrupt;
|
|
66
|
+
if (next.kind === "take") {
|
|
67
|
+
yield* stderrText("\n");
|
|
68
|
+
return next.line.trim();
|
|
69
|
+
}
|
|
70
|
+
sofar = next.sofar;
|
|
71
|
+
}
|
|
72
|
+
}));
|
|
73
|
+
});
|
|
74
|
+
export { hidden, keyed, select, typed };
|