@openupstream/cli 0.2.2 → 0.4.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/README.md CHANGED
@@ -65,6 +65,21 @@ oup site deploy dist --bucket my-site
65
65
  growth settings alone takes effect at once.
66
66
  - `oup pg list` (with each Database's growth: `auto`, `auto ≤ 40 GB` or
67
67
  `manual`), `oup pg show <name>` (JSON), `oup pg delete <name>`.
68
+ - `oup pg proxy <name> [--access read|write|owner] [--port <n>]`: the
69
+ Database on this machine while it runs (decision 126). It listens on
70
+ `127.0.0.1:5432`, or `--port`, and prints the URL to give `psql`, a
71
+ database GUI or a migration tool. You log in with a Postgres role of
72
+ your own, created the first time (the first start waits a minute or two
73
+ for it): `--access read`, the default, reads every table; `write` also
74
+ inserts, updates and deletes rows; `owner` acts as `app`, the role the
75
+ Project's Services use, so migrations work and what they create belongs
76
+ to `app`. `read` and `write` go through the Pooler like a Service;
77
+ `owner` goes to the primary, so migration tools' locks work, with at most
78
+ 5 connections at once, which end when the primary restarts. The same role
79
+ and password every time, on any machine. Connections travel through a
80
+ WebSocket on port 443; nothing else needs installing or opening. With
81
+ `OUP_API_KEY` (which needs `openupstream:write`), the key gets roles of
82
+ its own.
68
83
  - `oup service deploy <name> --image <ref> [--port <n> | --no-port] [--replicas <n>]
69
84
  [--memory <MB>] [--cpu <millicores>] [--site hetzner-fsn1|ovh-lim]
70
85
  [--registry-user <user> --registry-password-stdin] [--no-wait]`: brings
@@ -117,6 +132,45 @@ oup site deploy dist --bucket my-site
117
132
  shells keep in their history: piped (one trailing line break is dropped,
118
133
  as `echo` adds it) or typed at the prompt, which does not echo it. The
119
134
  Project's Services restart with the new value.
135
+ - `oup bucket list`, `oup bucket create <name>`, `oup bucket show <name>`
136
+ (S3 endpoint, region and access key id), `oup bucket delete <name>` (and
137
+ every object in it; refused while a Route serves it). A Bucket's name is
138
+ part of its hostname, so no other Bucket of anyone has it.
139
+ - `oup bucket show-access-key <name>` prints the Bucket's access key id
140
+ and its secret access key: the only command that prints a secret.
141
+ - `oup bucket export-env <name> [--file <path>]` writes what an S3 client
142
+ reads into an env file, `.env` by default, without showing the secret:
143
+ `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`,
144
+ `AWS_DEFAULT_REGION`, `AWS_ENDPOINT_URL_S3` and `BUCKET_NAME`. Lines that
145
+ set them already are replaced and the rest of the file stays; a new file
146
+ can be read by you alone. Keep it out of git. A file holds one Bucket's
147
+ variables: for a second Bucket, name another file with `--file`. Recent AWS SDKs read all
148
+ but `BUCKET_NAME` by themselves; the AWS CLI also needs
149
+ `aws configure set default.s3.addressing_style virtual`, since a Bucket
150
+ is reached at its own hostname only.
151
+ - `oup domain list`, `oup domain add <hostname>`, `oup domain verify
152
+ <hostname>`, `oup domain delete <hostname>` (and its Routes). Every
153
+ Project has its default Domain. `add` claims a hostname of your own and
154
+ prints the two DNS records to publish: a TXT record that proves it is
155
+ yours, and a CNAME that brings its traffic here. `verify` looks the TXT
156
+ record up now. Publish the CNAME before the first Route: the Domain's
157
+ certificate is requested then, and a failed attempt is tried again only
158
+ after an hour.
159
+ - `oup route list`, `oup route add <address> --bucket <name> [--spa]`,
160
+ `oup route add <address> --service <name>`, `oup route delete <address>`.
161
+ A Route sends everything below a path of a Domain to a Bucket or to a
162
+ Service that has a port. The address is the hostname with the path, as in
163
+ `www.example.com/docs` (`www.example.com` alone is its `/`), or the path
164
+ alone, as in `/docs`, on the Project's default Domain. A Bucket gets the
165
+ path without the prefix, and with `--spa` a path without an object
166
+ serves `index.html`; a Service gets the path as it came. Deleting a Route
167
+ leaves what it went to.
168
+ - `oup usage [--instances] [--json]`: what the Project's Resources use
169
+ now of what they were given: CPU (the last two minutes' average), memory
170
+ and storage per Database, Service, Job and Bucket. `--instances` adds
171
+ every running copy below its Resource, with its Site, its state and its
172
+ restarts; `--json` prints what the API answers. This is the use right
173
+ now, not what is billed.
120
174
  - `oup site deploy <dir> --bucket <name> [--keep] [--force]`: makes the
121
175
  Bucket mirror the directory (decision 88): changed files only, `index.html`
122
176
  files last, then deletes what the directory no longer has, unless
@@ -131,7 +185,7 @@ In CI, set `OUP_API_KEY` to a madAuth API key instead of signing in, and
131
185
  <!-- docs:end -->
132
186
 
133
187
  `src/oidc.ts` is the device grant and refresh, `src/session.ts` the token
134
- for each call, `src/deploy.ts` the site deploy (`planDeploy` is pure),
188
+ for each call, `src/proxy.ts` the database proxy, `src/deploy.ts` the site deploy (`planDeploy` is pure),
135
189
  `src/project.ts` the linked Project, `src/services.ts` the Service deploy
136
190
  (`planServiceDeploy` is pure), `src/jobs.ts` the Job deploy and runs
137
191
  (`planJobDeploy` is pure), `src/wait.ts` the polling both wait with and
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `oup bucket`: what an S3 client needs to reach a Bucket, as environment
3
+ * variables, and a `.env` file that holds them next to whatever else is in
4
+ * it. Pure, so it is tested without an API or a file.
5
+ */
6
+ import type { BucketDetails } from '@openupstream/sdk';
7
+ import { type Result } from './result.js';
8
+ /** A variable of an env file. */
9
+ export interface EnvEntry {
10
+ readonly name: string;
11
+ readonly value: string;
12
+ }
13
+ /**
14
+ * The variables S3 clients read (the AWS CLI and SDKs take all but
15
+ * `BUCKET_NAME` by themselves). The endpoint is the one above the Bucket's
16
+ * own hostname: clients put the Bucket's name in front (virtual-hosted
17
+ * style, the only one served). An error for a key that may not read the
18
+ * secret.
19
+ */
20
+ export declare const bucketEnv: (bucket: Pick<BucketDetails, "name" | "access">) => Result<readonly EnvEntry[], string>;
21
+ /** `https://<bucket>.s3.<domain>` as `https://s3.<domain>`: what a client is given, which adds the Bucket's name itself. */
22
+ export declare const s3Endpoint: (name: string, endpoint: string) => string;
23
+ /**
24
+ * The env file's text with the entries in it: a line that sets one of them
25
+ * is replaced where it is (once; further ones go), the others are added at
26
+ * the end, and every other line stays as it is.
27
+ */
28
+ export declare const mergeEnv: (text: string, entries: readonly EnvEntry[]) => string;
29
+ /** The Bucket a file's variables are for, when it has them: the value of its `BUCKET_NAME` line. */
30
+ export declare const bucketIn: (text: string) => string | undefined;
@@ -0,0 +1,54 @@
1
+ import { err, ok } from './result.js';
2
+ /**
3
+ * The variables S3 clients read (the AWS CLI and SDKs take all but
4
+ * `BUCKET_NAME` by themselves). The endpoint is the one above the Bucket's
5
+ * own hostname: clients put the Bucket's name in front (virtual-hosted
6
+ * style, the only one served). An error for a key that may not read the
7
+ * secret.
8
+ */
9
+ export const bucketEnv = (bucket) => {
10
+ const { endpoint, region, accessKeyId, secretAccessKey } = bucket.access;
11
+ return secretAccessKey === undefined
12
+ ? err("this API key may not read the Bucket's key; it needs openupstream:write")
13
+ : ok([
14
+ { name: 'AWS_ACCESS_KEY_ID', value: accessKeyId },
15
+ { name: 'AWS_SECRET_ACCESS_KEY', value: secretAccessKey },
16
+ { name: 'AWS_REGION', value: region },
17
+ { name: 'AWS_DEFAULT_REGION', value: region },
18
+ { name: 'AWS_ENDPOINT_URL_S3', value: s3Endpoint(bucket.name, endpoint) },
19
+ { name: 'BUCKET_NAME', value: bucket.name },
20
+ ]);
21
+ };
22
+ /** `https://<bucket>.s3.<domain>` as `https://s3.<domain>`: what a client is given, which adds the Bucket's name itself. */
23
+ export const s3Endpoint = (name, endpoint) => endpoint.replace(`//${name}.`, '//');
24
+ /** A value as an env file holds it: as it is when it has only plain characters, in single quotes otherwise. */
25
+ const quoted = (value) => (/^[A-Za-z0-9_./:@%+=-]*$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`);
26
+ const assigns = (line, name) => new RegExp(`^\\s*(export\\s+)?${name}\\s*=`).test(line);
27
+ /**
28
+ * The env file's text with the entries in it: a line that sets one of them
29
+ * is replaced where it is (once; further ones go), the others are added at
30
+ * the end, and every other line stays as it is.
31
+ */
32
+ export const mergeEnv = (text, entries) => {
33
+ // The file's own line ending, for the lines it gets too.
34
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
35
+ const lines = text === '' ? [] : text.replace(/\r?\n$/, '').split(/\r?\n/);
36
+ const kept = lines.flatMap((line, index) => {
37
+ const entry = entries.find(({ name }) => assigns(line, name));
38
+ return entry === undefined
39
+ ? [line]
40
+ : lines.findIndex((other) => assigns(other, entry.name)) === index
41
+ ? [`${entry.name}=${quoted(entry.value)}`]
42
+ : [];
43
+ });
44
+ const added = entries.filter(({ name }) => !lines.some((line) => assigns(line, name))).map(({ name, value }) => `${name}=${quoted(value)}`);
45
+ return `${[...kept, ...added].join(eol)}${eol}`;
46
+ };
47
+ /** The Bucket a file's variables are for, when it has them: the value of its `BUCKET_NAME` line. */
48
+ export const bucketIn = (text) => text
49
+ .split(/\r?\n/)
50
+ .find((line) => assigns(line, 'BUCKET_NAME'))
51
+ ?.replace(/^[^=]*=\s*/, '')
52
+ .replace(/^(['"])(.*)\1$/, '$2')
53
+ .trim();
54
+ //# sourceMappingURL=buckets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buckets.js","sourceRoot":"","sources":["../src/buckets.ts"],"names":[],"mappings":"AAMA,OAAO,EAAe,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAQnD;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,MAA8C,EAAuC,EAAE;IAC7G,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,eAAe,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC;IACzE,OAAO,eAAe,KAAK,SAAS;QAChC,CAAC,CAAC,GAAG,CAAC,yEAAyE,CAAC;QAChF,CAAC,CAAC,EAAE,CAAC;YACC,EAAE,IAAI,EAAE,mBAAmB,EAAE,KAAK,EAAE,WAAW,EAAE;YACjD,EAAE,IAAI,EAAE,uBAAuB,EAAE,KAAK,EAAE,eAAe,EAAE;YACzD,EAAE,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,EAAE;YACrC,EAAE,IAAI,EAAE,oBAAoB,EAAE,KAAK,EAAE,MAAM,EAAE;YAC7C,EAA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AgB,EAAE,IAAI,CAAC;KAC/B,IAAI,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * oup pg create <name> [--memory <MB>] [--storage <GB>] [--site …] waits until ready
11
11
  * oup pg restore <source> <name> [--time <RFC 3339>] … a new Database as a copy of <source>
12
12
  * oup pg resize <name> [--memory <MB>] [--storage <GB>] storage only grows
13
+ * oup pg proxy <name> [--access read|write|owner] [--port <n>] the Database on this machine
13
14
  * oup service list | show <name> | delete <name>
14
15
  * oup service deploy <name> --image <ref> [--port … | --no-port] …
15
16
  * oup service logs <name> [--tail <n>] [-f] [--timestamps]
@@ -19,21 +20,28 @@
19
20
  * oup job stop <name> <run>
20
21
  * oup job logs <name> [<run>] [--tail <n>] [-f] [--timestamps] the newest run by default
21
22
  * oup secret list | set <NAME> | delete <NAME> a value is read from stdin
23
+ * oup bucket list | create <name> | show <name> | show-access-key <name> | export-env <name> [--file <path>] | delete <name>
24
+ * oup domain list | add <hostname> | verify <hostname> | delete <hostname>
25
+ * oup route list | add <address> --bucket <name> [--spa] | add <address> --service <name> | delete <address>
26
+ * oup usage [--instances] [--json] what the Project's Resources use now
22
27
  * oup site deploy <dir> --bucket <name> [--keep] [--force]
23
28
  * oup version
24
29
  *
25
- * Database, service, job and secret commands act on the linked Project; `--project`
30
+ * Database, service, job, secret, bucket, domain, route and usage commands act on the linked Project; `--project`
26
31
  * or `OUP_PROJECT` names another.
27
32
  *
28
- * Planned (ARCHITECTURE.md build order): oup bucket, oup routes, oup usage.
29
- *
30
33
  * `OUP_API_KEY` (a madAuth API key) replaces `oup login`, e.g. in CI, with
31
34
  * `OUP_API_URL` for another API than https://console.openupstream.com/api.
32
35
  */
33
36
  import { spawn } from 'node:child_process';
37
+ import { once } from 'node:events';
38
+ import { readFile, writeFile } from 'node:fs/promises';
39
+ import { createServer } from 'node:net';
40
+ import { resolve } from 'node:path';
34
41
  import { parseArgs } from 'node:util';
35
42
  import { S3Client } from '@aws-sdk/client-s3';
36
43
  import { COMPUTE_SITES, DEFAULT_API_URL, OpenUpstreamClient, SDK_VERSION, cliLogin, } from '@openupstream/sdk';
44
+ import { bucketEnv, bucketIn, mergeEnv, s3Endpoint } from './buckets.js';
37
45
  import { credentialsPath, readCredentials, removeCredentials, writeCredentials } from './credentials.js';
38
46
  import { deploy } from './deploy.js';
39
47
  import { discover, emailOf, startDeviceSignIn, waitForApproval } from './oidc.js';
@@ -42,9 +50,12 @@ import { JOB_FLAGS, formatJobs, formatRuns, isFinished, outcomeOf, parseEnv, pla
42
50
  import { formatLogEntry, parseTail } from './logs.js';
43
51
  import { DATABASE_DEFAULTS, formatDatabases, growthOf, growthSettings, planRestore } from './databases.js';
44
52
  import { formatServices, planServiceDeploy, waitUntilRunning } from './services.js';
53
+ import { LISTEN_HOST, connectionUrl, listen, parseAccess, parsePort, portFree, prepareRole, serveTunnel } from './proxy.js';
54
+ import { dnsRecords, domainNamed, formatDomains, formatRoutes, hostnameOf, hostnameProblem, ingressOf, parseAddress, routeInput, routeRefusal } from './routes.js';
45
55
  import { apiAccess } from './session.js';
46
56
  import { readSecretValue } from './stdin.js';
47
57
  import { waitUntil } from './wait.js';
58
+ import { formatUsage } from './usage.js';
48
59
  import { CLI_VERSION } from './version.js';
49
60
  const USAGE = `usage:
50
61
  oup login [--api <url>] [--no-browser]
@@ -58,6 +69,7 @@ const USAGE = `usage:
58
69
  oup pg restore <source> <name> [--time <RFC 3339>] [--memory <MB>] [--storage <GB>] [--site …] [--max-storage <GB> | --no-auto-grow] [--no-wait]
59
70
  oup pg resize <name> [--memory <MB>] [--storage <GB>] [--max-storage <GB> | --no-max-storage] [--auto-grow | --no-auto-grow] [--no-wait]
60
71
  oup pg delete <name>
72
+ oup pg proxy <name> [--access read|write|owner] [--port <n>]
61
73
  oup service list
62
74
  oup service show <name>
63
75
  oup service deploy <name> --image <ref> [--port <n> | --no-port] [--replicas <n>] [--memory <MB>] [--cpu <millicores>]
@@ -77,10 +89,26 @@ const USAGE = `usage:
77
89
  oup secret list
78
90
  oup secret set <NAME> (the value from stdin)
79
91
  oup secret delete <NAME>
92
+ oup bucket list
93
+ oup bucket create <name>
94
+ oup bucket show <name>
95
+ oup bucket show-access-key <name> (prints the Bucket's secret access key)
96
+ oup bucket export-env <name> [--file <path>] (writes it into an env file, default .env)
97
+ oup bucket delete <name>
98
+ oup domain list
99
+ oup domain add <hostname> (a custom domain; prints the DNS records to publish)
100
+ oup domain verify <hostname>
101
+ oup domain delete <hostname> (and its Routes)
102
+ oup route list
103
+ oup route add <address> --bucket <name> [--spa]
104
+ oup route add <address> --service <name>
105
+ oup route delete <address>
106
+ <address> is <hostname>/<path>, or /<path> alone for the Project's default Domain
107
+ oup usage [--instances] [--json]
80
108
  oup site deploy <dir> --bucket <name> [--keep] [--force]
81
109
  oup version
82
110
 
83
- Database, service, job and secret commands take --project <name|id>; without
111
+ Database, service, job, secret, bucket, domain, route and usage commands take --project <name|id>; without
84
112
  it, the Project linked to this directory (oup link) or OUP_PROJECT.
85
113
 
86
114
  pg create gives a Database 256 MB and 1 GB unless told otherwise. pg restore
@@ -92,6 +120,12 @@ Storage grows by itself by half once 90% full, without a limit unless
92
120
  --max-storage sets one; --no-auto-grow leaves it to pg resize.
93
121
  pg resize grows the storage online; a new memory size restarts the
94
122
  instances one after the other (writes pause for seconds).
123
+ pg proxy reaches the Database from this machine while it runs: it listens on
124
+ 127.0.0.1:5432 (--port for another) and prints the URL to connect with. You
125
+ log in with a Postgres role of your own: --access read (the default) reads
126
+ every table, write also changes rows, owner acts as app, the role the
127
+ Project's Services use, so migrations work; owner connections go to the
128
+ primary, so migration tools' locks work, at most 5 at once.
95
129
 
96
130
  logs prints the last lines (100 by default) of every replica or of a run,
97
131
  with -f also new ones as they are written, for up to an hour. Nothing is
@@ -252,6 +286,7 @@ const PG_FLAGS = {
252
286
  create: ['memory', 'storage', 'site', 'no-wait', 'max-storage', 'no-auto-grow'],
253
287
  restore: ['memory', 'storage', 'site', 'no-wait', 'time', 'max-storage', 'no-auto-grow'],
254
288
  resize: ['memory', 'storage', 'no-wait', 'max-storage', 'no-max-storage', 'auto-grow', 'no-auto-grow'],
289
+ proxy: ['access', 'port'],
255
290
  };
256
291
  async function pg(args) {
257
292
  const [verb, ...rest] = args;
@@ -269,6 +304,8 @@ async function pg(args) {
269
304
  'no-max-storage': { type: 'boolean' },
270
305
  'auto-grow': { type: 'boolean' },
271
306
  'no-auto-grow': { type: 'boolean' },
307
+ access: { type: 'string' },
308
+ port: { type: 'string' },
272
309
  },
273
310
  });
274
311
  if (verb === undefined || !Object.hasOwn(PG_FLAGS, verb)) {
@@ -313,6 +350,8 @@ async function pg(args) {
313
350
  ? console.log(`Deleted ${name}. Its backups are kept for the retention window; until then\n oup pg restore ${database.id} <name> --storage ${database.storageGb}\nbrings it back as a new Database.`)
314
351
  : fail(deleted.error.message);
315
352
  }
353
+ case 'proxy':
354
+ return pgProxy(client, project, found(), values.access, values.port);
316
355
  case 'resize': {
317
356
  const database = found();
318
357
  if (memoryMb === undefined && storageGb === undefined && Object.keys(growth.settings).length === 0) {
@@ -371,6 +410,50 @@ async function pg(args) {
371
410
  return fail(USAGE);
372
411
  }
373
412
  }
413
+ /**
414
+ * `oup pg proxy`: the caller's own role, a first login through the tunnel
415
+ * (which waits for the role and, at owner, makes it act as app), then the
416
+ * local port, until Ctrl-C.
417
+ */
418
+ async function pgProxy(client, project, database, accessFlag, portFlag) {
419
+ const access = parseAccess(accessFlag);
420
+ const port = parsePort(portFlag);
421
+ if (!access.ok || !port.ok) {
422
+ return fail(!access.ok ? access.error : !port.ok ? port.error : '');
423
+ }
424
+ // A taken port is said before any waiting.
425
+ const free = await portFree(port.value);
426
+ if (!free.ok) {
427
+ return fail(free.error);
428
+ }
429
+ const proxy = await client.openDatabaseProxy(project.id, database.id, { access: access.value });
430
+ if (!proxy.ok) {
431
+ return fail(proxy.error.message);
432
+ }
433
+ const token = async () => {
434
+ const fresh = await apiAccess(credentialsPath());
435
+ return fresh.ok ? { ok: true, value: fresh.value.token } : fresh;
436
+ };
437
+ const tunnel = { url: proxy.value.tunnelUrl, token, warn: (message) => console.error(`oup: ${message}`) };
438
+ const prepared = await prepareRole({ ...tunnel, proxy: proxy.value, report: (message) => console.log(message) });
439
+ if (!prepared.ok) {
440
+ return fail(prepared.error);
441
+ }
442
+ const server = createServer();
443
+ serveTunnel(server, tunnel);
444
+ const listening = await listen(server, port.value);
445
+ if (!listening.ok) {
446
+ return fail(listening.error);
447
+ }
448
+ // Once listening, an error of the server (too many open files) is said, and the proxy goes on.
449
+ server.on('error', (error) => console.error(`oup: ${error.message}`));
450
+ console.log(`${database.name} (${access.value}) on ${LISTEN_HOST}:${port.value}. Connect with:`);
451
+ console.log(` ${connectionUrl(proxy.value, port.value)}`);
452
+ console.log('Press Ctrl-C to stop.');
453
+ await once(process, 'SIGINT');
454
+ server.close();
455
+ process.exit(0);
456
+ }
374
457
  /** Until the Database is ready; every state it passes through is reported once. */
375
458
  async function waitReady(client, projectId, databaseId, name) {
376
459
  // A restore first fetches the base backup and replays WAL; a new memory size restarts both instances.
@@ -738,6 +821,212 @@ async function secret(args) {
738
821
  return fail(USAGE);
739
822
  }
740
823
  }
824
+ /**
825
+ * `oup bucket`: the linked Project's Buckets. Only `show-access-key` prints
826
+ * the Bucket's secret, and `export-env` writes it into a file without
827
+ * showing it (decision 133).
828
+ */
829
+ async function bucket(args) {
830
+ const [verb, ...rest] = args;
831
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { project: { type: 'string' }, file: { type: 'string' } } });
832
+ const [name] = positionals;
833
+ if (verb === undefined || (verb !== 'list' && name === undefined) || (values.file !== undefined && verb !== 'export-env')) {
834
+ return fail(USAGE);
835
+ }
836
+ const { client, project } = await inProject(values.project);
837
+ const list = async () => {
838
+ const buckets = await client.listBuckets(project.id);
839
+ return buckets.ok ? buckets.value : fail(buckets.error.message);
840
+ };
841
+ /** The Bucket `name` of the Project, for the verbs that act on one. */
842
+ const named = async () => (await list()).find((candidate) => candidate.name === name) ?? fail(`no Bucket ${name} in ${project.name}`);
843
+ /** The same with its access. */
844
+ const details = async () => {
845
+ const read = await client.getBucket(project.id, (await named()).id);
846
+ return read.ok ? read.value : fail(read.error.message);
847
+ };
848
+ switch (verb) {
849
+ case 'list': {
850
+ const buckets = await list();
851
+ console.log(buckets.length === 0 ? `No Buckets in ${project.name}.` : buckets.map((b) => `${b.name.padEnd(32)} ${b.createdAt}`).join('\n'));
852
+ return;
853
+ }
854
+ case 'create': {
855
+ const created = await client.createBucket(project.id, { name: name });
856
+ return created.ok
857
+ ? console.log(`Created ${created.value.name} in ${project.name}: S3 endpoint ${s3Endpoint(created.value.name, created.value.access.endpoint)}`)
858
+ : fail(created.error.message);
859
+ }
860
+ case 'show': {
861
+ const { access, createdAt } = await details();
862
+ console.log([
863
+ `Name: ${name}`,
864
+ `S3 endpoint: ${s3Endpoint(name, access.endpoint)} (virtual-hosted style: https://${new URL(access.endpoint).host})`,
865
+ `Region: ${access.region}`,
866
+ `Access key id: ${access.accessKeyId}`,
867
+ `Created: ${createdAt}`,
868
+ ].join('\n'));
869
+ return;
870
+ }
871
+ case 'show-access-key': {
872
+ const { access } = await details();
873
+ if (access.secretAccessKey === undefined) {
874
+ return fail("this API key may not read the Bucket's key; it needs openupstream:write");
875
+ }
876
+ console.log(`Access key id: ${access.accessKeyId}\nSecret access key: ${access.secretAccessKey}`);
877
+ return;
878
+ }
879
+ case 'export-env': {
880
+ const entries = bucketEnv(await details());
881
+ if (!entries.ok) {
882
+ return fail(entries.error);
883
+ }
884
+ const path = resolve(values.file ?? '.env');
885
+ // Only a file that is not there reads as empty: one that cannot be read is not written over.
886
+ const before = await readFile(path, 'utf8').catch((error) => error instanceof Error && 'code' in error && error.code === 'ENOENT' ? '' : fail(`cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`));
887
+ // A file holds one Bucket's variables: their names are the same for every Bucket.
888
+ const other = bucketIn(before);
889
+ const written = await writeFile(path, mergeEnv(before, entries.value), { mode: 0o600 }).then(() => undefined, (error) => (error instanceof Error ? error.message : String(error)));
890
+ if (written !== undefined) {
891
+ return fail(`cannot write ${path}: ${written}`);
892
+ }
893
+ console.log(`Wrote ${entries.value.map((entry) => entry.name).join(', ')} to ${path}. It holds the Bucket's secret: keep it out of git.`);
894
+ if (other !== undefined && other !== name) {
895
+ console.log(`They replace those of the Bucket ${other}, which the file held: use --file for a file per Bucket.`);
896
+ }
897
+ return;
898
+ }
899
+ case 'delete': {
900
+ const deleted = await client.deleteBucket(project.id, (await named()).id);
901
+ return deleted.ok ? console.log(`Deleted ${name} and every object in it.`) : fail(deleted.error.message);
902
+ }
903
+ default:
904
+ return fail(USAGE);
905
+ }
906
+ }
907
+ /** `oup domain`: the linked Project's Domains; a custom one is claimed, proven with a DNS record, and deleted (decision 135). */
908
+ async function domain(args) {
909
+ const [verb, ...rest] = args;
910
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { project: { type: 'string' } } });
911
+ const [typed] = positionals;
912
+ if (verb === undefined || !['list', 'add', 'verify', 'delete'].includes(verb) || (verb !== 'list' && typed === undefined)) {
913
+ return fail(USAGE);
914
+ }
915
+ const { client, project } = await inProject(values.project);
916
+ const listed = await client.listDomains(project.id);
917
+ const domains = listed.ok ? listed.value : fail(listed.error.message);
918
+ if (verb === 'list') {
919
+ console.log(formatDomains(domains).join('\n'));
920
+ return;
921
+ }
922
+ const hostname = hostnameOf(typed);
923
+ const records = (claimed) => dnsRecords(claimed, ingressOf(domains)).join('\n');
924
+ if (verb === 'add') {
925
+ const problem = hostnameProblem(hostname);
926
+ if (problem !== undefined) {
927
+ return fail(problem);
928
+ }
929
+ const created = await client.createDomain(project.id, { hostname });
930
+ if (!created.ok) {
931
+ return fail(created.error.message);
932
+ }
933
+ console.log(`Added ${hostname} to ${project.name}. Publish these DNS records, then run: oup domain verify ${hostname}\n${records(created.value)}`);
934
+ console.log('The TXT record proves the domain is yours; the CNAME brings its traffic here. Publish the CNAME before the first Route: the certificate is requested then.');
935
+ return;
936
+ }
937
+ const found = domainNamed(domains, hostname, project.name);
938
+ if (!found.ok) {
939
+ return fail(found.error);
940
+ }
941
+ if (verb === 'verify') {
942
+ if (found.value.kind === 'default' || found.value.verification.state === 'verified') {
943
+ console.log(`${hostname} is ${found.value.kind === 'default' ? "the Project's default Domain and needs no proof" : 'verified already'}.`);
944
+ return;
945
+ }
946
+ const verified = await client.verifyDomain(project.id, found.value.id);
947
+ return verified.ok ? console.log(`${hostname} is verified: its Routes are served.`) : fail(`${verified.error.message}\n${records(found.value)}`);
948
+ }
949
+ const deleted = await client.deleteDomain(project.id, found.value.id);
950
+ return deleted.ok ? console.log(`Deleted ${hostname} and its Routes from ${project.name}.`) : fail(deleted.error.message);
951
+ }
952
+ /** `oup route`: what is served where. A Route is named by its address, `<hostname>/<path>`, or `/<path>` on the default Domain. */
953
+ async function route(args) {
954
+ const [verb, ...rest] = args;
955
+ const { values, positionals } = parseArgs({
956
+ args: rest,
957
+ allowPositionals: true,
958
+ options: { project: { type: 'string' }, bucket: { type: 'string' }, service: { type: 'string' }, spa: { type: 'boolean' } },
959
+ });
960
+ const [address] = positionals;
961
+ const target = values.bucket !== undefined || values.service !== undefined || values.spa !== undefined;
962
+ if (verb === undefined || !['list', 'add', 'delete'].includes(verb) || (verb !== 'list' && address === undefined) || (verb !== 'add' && target)) {
963
+ return fail(USAGE);
964
+ }
965
+ const { client, project } = await inProject(values.project);
966
+ const listed = await client.listDomains(project.id);
967
+ const domains = listed.ok ? listed.value : fail(listed.error.message);
968
+ const routesOf = async (domainId) => {
969
+ const routes = await client.listRoutes(project.id, domainId);
970
+ return routes.ok ? routes.value : fail(routes.error.message);
971
+ };
972
+ const buckets = async () => {
973
+ const all = await client.listBuckets(project.id);
974
+ return all.ok ? all.value : fail(all.error.message);
975
+ };
976
+ const services = async () => {
977
+ const all = await client.listServices(project.id);
978
+ return all.ok ? all.value : fail(all.error.message);
979
+ };
980
+ if (verb === 'list') {
981
+ const [routes, allBuckets, allServices] = await Promise.all([Promise.all(domains.map((each) => routesOf(each.id))), buckets(), services()]);
982
+ const lines = formatRoutes(domains, Object.fromEntries(domains.map((each, index) => [each.id, routes[index] ?? []])), allBuckets, allServices);
983
+ console.log(lines.length === 0 ? `No Routes in ${project.name}: every path answers 404.` : lines.join('\n'));
984
+ return;
985
+ }
986
+ const named = parseAddress(address, domains, project.name);
987
+ if (!named.ok) {
988
+ return fail(named.error);
989
+ }
990
+ const { domain: at, pathPrefix } = named.value;
991
+ const where = `${at.hostname}${pathPrefix}`;
992
+ if (verb === 'add') {
993
+ // Only the list the Route's target is in.
994
+ const input = routeInput(pathPrefix, values, values.bucket === undefined ? [] : await buckets(), values.service === undefined ? [] : await services(), project.name);
995
+ if (!input.ok) {
996
+ return fail(input.error);
997
+ }
998
+ const created = await client.createRoute(project.id, at.id, input.value);
999
+ if (!created.ok) {
1000
+ return fail(routeRefusal(created.error.message, values));
1001
+ }
1002
+ const pending = at.kind === 'custom' && at.verification.state === 'pending';
1003
+ console.log(pending ? `Added the Route ${where}. It is served once the Domain is verified: oup domain verify ${at.hostname}` : `Added the Route: https://${where} is served within a minute.`);
1004
+ return;
1005
+ }
1006
+ const existing = (await routesOf(at.id)).find((candidate) => candidate.pathPrefix === pathPrefix);
1007
+ if (existing === undefined) {
1008
+ return fail(`no Route ${where} in ${project.name}; oup route list shows them`);
1009
+ }
1010
+ const deleted = await client.deleteRoute(project.id, at.id, existing.id);
1011
+ return deleted.ok ? console.log(`Deleted the Route ${where}; what it went to stays.`) : fail(deleted.error.message);
1012
+ }
1013
+ /** `oup usage`: what the linked Project's Resources use now of what they were given (decision 124); not what is billed. */
1014
+ async function usage(args) {
1015
+ const { values, positionals } = parseArgs({
1016
+ args,
1017
+ allowPositionals: true,
1018
+ options: { project: { type: 'string' }, instances: { type: 'boolean' }, json: { type: 'boolean' } },
1019
+ });
1020
+ if (positionals.length > 0) {
1021
+ return fail(USAGE);
1022
+ }
1023
+ const { client, project } = await inProject(values.project);
1024
+ const read = await client.getUsage(project.id);
1025
+ if (!read.ok) {
1026
+ return fail(read.error.message);
1027
+ }
1028
+ console.log(values.json === true ? JSON.stringify(read.value, null, 2) : formatUsage(read.value, project.name, { instances: values.instances ?? false }).join('\n'));
1029
+ }
741
1030
  async function siteDeploy(args) {
742
1031
  const { values, positionals } = parseArgs({
743
1032
  args,
@@ -797,6 +1086,14 @@ const run = async () => {
797
1086
  return job(rest);
798
1087
  case 'secret':
799
1088
  return secret(rest);
1089
+ case 'bucket':
1090
+ return bucket(rest);
1091
+ case 'domain':
1092
+ return domain(rest);
1093
+ case 'route':
1094
+ return route(rest);
1095
+ case 'usage':
1096
+ return usage(rest);
800
1097
  case 'site':
801
1098
  return rest[0] === 'deploy' ? siteDeploy(rest.slice(1)) : fail(USAGE);
802
1099
  case 'version':