@openupstream/cli 0.3.0 → 0.5.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/dist/index.js CHANGED
@@ -6,10 +6,15 @@
6
6
  * oup logout
7
7
  * oup project list | create <name> [--account <name|id>] [--link]
8
8
  * oup link <project> this directory's Project (.openupstream.json)
9
+ * oup member list | role <email> owner|developer|none | remove <email> | leave [--account <name|id>]
10
+ * oup member grant <email> read|write|owner --database <name> | revoke <email> --database <name> [--project <name|id>]
11
+ * oup token list | create <name> --expires <days|date> [--developer] | role <name> developer|none | roll <name> --expires … | delete <name>
12
+ * oup token grant <name> read|write|owner --database <name> | revoke <name> --database <name> [--project <name|id>]
9
13
  * oup pg list | show <name> | delete <name>
10
14
  * oup pg create <name> [--memory <MB>] [--storage <GB>] [--site …] waits until ready
11
15
  * oup pg restore <source> <name> [--time <RFC 3339>] … a new Database as a copy of <source>
12
16
  * oup pg resize <name> [--memory <MB>] [--storage <GB>] storage only grows
17
+ * oup pg proxy <name> [--access read|write|owner] [--port <n>] the Database on this machine
13
18
  * oup service list | show <name> | delete <name>
14
19
  * oup service deploy <name> --image <ref> [--port … | --no-port] …
15
20
  * oup service logs <name> [--tail <n>] [-f] [--timestamps]
@@ -20,35 +25,44 @@
20
25
  * oup job logs <name> [<run>] [--tail <n>] [-f] [--timestamps] the newest run by default
21
26
  * oup secret list | set <NAME> | delete <NAME> a value is read from stdin
22
27
  * oup bucket list | create <name> | show <name> | show-access-key <name> | export-env <name> [--file <path>] | delete <name>
28
+ * oup domain list | add <hostname> | verify <hostname> | delete <hostname>
29
+ * oup route list | add <address> --bucket <name> [--spa] | add <address> --service <name> | delete <address>
30
+ * oup usage [--instances] [--json] what the Project's Resources use now
23
31
  * oup site deploy <dir> --bucket <name> [--keep] [--force]
24
32
  * oup version
25
33
  *
26
- * Database, service, job, secret and bucket commands act on the linked Project; `--project`
34
+ * Database, service, job, secret, bucket, domain, route and usage commands act on the linked Project; `--project`
27
35
  * or `OUP_PROJECT` names another.
28
36
  *
29
- * Planned (ARCHITECTURE.md build order): oup routes, oup usage.
30
- *
31
- * `OUP_API_KEY` (a madAuth API key) replaces `oup login`, e.g. in CI, with
37
+ * `OUP_API_KEY` (a madAuth API key or an Account token) replaces `oup login`, e.g. in CI, with
32
38
  * `OUP_API_URL` for another API than https://console.openupstream.com/api.
33
39
  */
34
40
  import { spawn } from 'node:child_process';
41
+ import { once } from 'node:events';
35
42
  import { readFile, writeFile } from 'node:fs/promises';
43
+ import { createServer } from 'node:net';
36
44
  import { resolve } from 'node:path';
37
45
  import { parseArgs } from 'node:util';
38
46
  import { S3Client } from '@aws-sdk/client-s3';
39
- import { COMPUTE_SITES, DEFAULT_API_URL, OpenUpstreamClient, SDK_VERSION, cliLogin, } from '@openupstream/sdk';
47
+ import { SITE_ID, DEFAULT_API_URL, OpenUpstreamClient, SDK_VERSION, cliLogin, } from '@openupstream/sdk';
40
48
  import { bucketEnv, bucketIn, mergeEnv, s3Endpoint } from './buckets.js';
41
49
  import { credentialsPath, readCredentials, removeCredentials, writeCredentials } from './credentials.js';
42
50
  import { deploy } from './deploy.js';
43
51
  import { discover, emailOf, startDeviceSignIn, waitForApproval } from './oidc.js';
44
52
  import { accountFor, findLink, formatProjects, projectFor, resolveProject, writeLink } from './project.js';
53
+ import { LAST_OWNER_HINT, formatMembers, memberByEmail, parseGrantAccess, parseRole } from './members.js';
54
+ import { formatTokens, parseExpiry, parseTokenRole, tokenByName } from './tokens.js';
45
55
  import { JOB_FLAGS, formatJobs, formatRuns, isFinished, outcomeOf, parseEnv, planJobDeploy, splitAtDashes, strayFlag, } from './jobs.js';
46
56
  import { formatLogEntry, parseTail } from './logs.js';
47
57
  import { DATABASE_DEFAULTS, formatDatabases, growthOf, growthSettings, planRestore } from './databases.js';
48
58
  import { formatServices, planServiceDeploy, waitUntilRunning } from './services.js';
59
+ import { LISTEN_HOST, connectionUrl, listen, parseAccess, parsePort, portFree, prepareRole, serveTunnel } from './proxy.js';
60
+ import { dnsRecords, domainNamed, formatDomains, formatRoutes, hostnameOf, hostnameProblem, ingressOf, parseAddress, routeInput, routeRefusal } from './routes.js';
49
61
  import { apiAccess } from './session.js';
50
62
  import { readSecretValue } from './stdin.js';
51
63
  import { waitUntil } from './wait.js';
64
+ import { formatUsage } from './usage.js';
65
+ import { formatSites } from './sites.js';
52
66
  import { CLI_VERSION } from './version.js';
53
67
  const USAGE = `usage:
54
68
  oup login [--api <url>] [--no-browser]
@@ -56,22 +70,36 @@ const USAGE = `usage:
56
70
  oup project list
57
71
  oup project create <name> [--account <name|id>] [--link]
58
72
  oup link <project>
73
+ oup member list [--account <name|id>]
74
+ oup member role <email> owner|developer|none [--account <name|id>]
75
+ oup member grant <email> read|write|owner --database <name> [--project <name|id>]
76
+ oup member revoke <email> --database <name> [--project <name|id>]
77
+ oup member remove <email> [--account <name|id>]
78
+ oup member leave [--account <name|id>]
79
+ oup token list [--account <name|id>]
80
+ oup token create <name> --expires <days|date> [--developer] [--account <name|id>] (prints the secret once)
81
+ oup token role <name> developer|none [--account <name|id>]
82
+ oup token grant <name> read|write|owner --database <name> [--project <name|id>]
83
+ oup token revoke <name> --database <name> [--project <name|id>]
84
+ oup token roll <name> --expires <days|date> [--account <name|id>] (a new secret; the old one works 24 hours more)
85
+ oup token delete <name> [--account <name|id>]
59
86
  oup pg list
60
87
  oup pg show <name>
61
- oup pg create <name> [--memory <MB>] [--storage <GB>] [--site hetzner-fsn1|ovh-lim] [--max-storage <GB> | --no-auto-grow] [--no-wait]
88
+ oup pg create <name> [--memory <MB>] [--storage <GB>] [--site <site>] [--max-storage <GB> | --no-auto-grow] [--no-wait]
62
89
  oup pg restore <source> <name> [--time <RFC 3339>] [--memory <MB>] [--storage <GB>] [--site …] [--max-storage <GB> | --no-auto-grow] [--no-wait]
63
90
  oup pg resize <name> [--memory <MB>] [--storage <GB>] [--max-storage <GB> | --no-max-storage] [--auto-grow | --no-auto-grow] [--no-wait]
64
91
  oup pg delete <name>
92
+ oup pg proxy <name> [--access read|write|owner] [--port <n>]
65
93
  oup service list
66
94
  oup service show <name>
67
95
  oup service deploy <name> --image <ref> [--port <n> | --no-port] [--replicas <n>] [--memory <MB>] [--cpu <millicores>]
68
- [--site hetzner-fsn1|ovh-lim] [--registry-user <user> --registry-password-stdin] [--no-wait]
96
+ [--site <site>] [--registry-user <user> --registry-password-stdin] [--no-wait]
69
97
  oup service logs <name> [--tail <n>] [-f | --follow] [--timestamps]
70
98
  oup service delete <name>
71
99
  oup job list
72
100
  oup job show <name>
73
101
  oup job deploy <name> --image <ref> [--schedule <cron> | --no-schedule] [--time-zone <IANA name>]
74
- [--timeout <seconds>] [--memory <MB>] [--cpu <millicores>] [--site hetzner-fsn1|ovh-lim]
102
+ [--timeout <seconds>] [--memory <MB>] [--cpu <millicores>] [--site <site>]
75
103
  [--registry-user <user> --registry-password-stdin] [--no-wait] [--no-command | -- <command> <arg>…]
76
104
  oup job run <name> [--env NAME=value]… [--no-wait] [-- <arg>…]
77
105
  oup job runs <name>
@@ -87,10 +115,21 @@ const USAGE = `usage:
87
115
  oup bucket show-access-key <name> (prints the Bucket's secret access key)
88
116
  oup bucket export-env <name> [--file <path>] (writes it into an env file, default .env)
89
117
  oup bucket delete <name>
118
+ oup domain list
119
+ oup domain add <hostname> (a custom domain; prints the DNS records to publish)
120
+ oup domain verify <hostname>
121
+ oup domain delete <hostname> (and its Routes)
122
+ oup route list
123
+ oup route add <address> --bucket <name> [--spa]
124
+ oup route add <address> --service <name>
125
+ oup route delete <address>
126
+ <address> is <hostname>/<path>, or /<path> alone for the Project's default Domain
127
+ oup usage [--instances] [--json]
128
+ oup sites (the compute Sites, for --site)
90
129
  oup site deploy <dir> --bucket <name> [--keep] [--force]
91
130
  oup version
92
131
 
93
- Database, service, job, secret and bucket commands take --project <name|id>; without
132
+ Database, service, job, secret, bucket, domain, route and usage commands take --project <name|id>; without
94
133
  it, the Project linked to this directory (oup link) or OUP_PROJECT.
95
134
 
96
135
  pg create gives a Database 256 MB and 1 GB unless told otherwise. pg restore
@@ -102,6 +141,30 @@ Storage grows by itself by half once 90% full, without a limit unless
102
141
  --max-storage sets one; --no-auto-grow leaves it to pg resize.
103
142
  pg resize grows the storage online; a new memory size restarts the
104
143
  instances one after the other (writes pause for seconds).
144
+ pg proxy reaches the Database from this machine while it runs: it listens on
145
+ 127.0.0.1:5432 (--port for another) and prints the URL to connect with. You
146
+ log in with a Postgres role of your own: --access read (the default) reads
147
+ every table, write also changes rows, owner acts as app, the role the
148
+ Project's Services use, so migrations work; owner connections go to the
149
+ primary, so migration tools' locks work, at most 5 at once.
150
+
151
+ member acts on your only Account, or on --account. An owner may do
152
+ everything, the Account's Members included; a developer every Project and
153
+ everything in it; a Member with role none only what their grants give. A
154
+ grant lets a Member use one Database of the linked Project (or --project)
155
+ at a level or below: see it and open pg proxy, nothing else of the Project.
156
+ Only owners change roles and grants and remove Members; anyone may leave.
157
+ An Account always keeps an owner. Postgres roles a Member may no longer use
158
+ are dropped. These commands need oup login: an API key cannot change who
159
+ is in an Account.
160
+
161
+ token manages Account tokens: secrets of the Account, not of a person, for
162
+ CI, BI tools and scripts. A token has the developer role (--developer) or
163
+ only the grants given to it, never owner, and expires after at most a year
164
+ (--expires 90d or a date). create and roll print the secret alone on
165
+ stdout, once; pipe it into where it is kept, e.g. | gh secret set
166
+ OUP_API_KEY. oup and the SDK use it as OUP_API_KEY. Owners manage tokens
167
+ with oup login; developers list them. delete revokes a token at once.
105
168
 
106
169
  logs prints the last lines (100 by default) of every replica or of a run,
107
170
  with -f also new ones as they are written, for up to an hour. Nothing is
@@ -253,7 +316,8 @@ const count = (flag, value) => {
253
316
  const n = Number(value);
254
317
  return Number.isInteger(n) && n > 0 ? n : fail(`--${flag} must be a positive whole number, not ${value}`);
255
318
  };
256
- const isSite = (value) => COMPUTE_SITES.includes(value);
319
+ /** A Site id's form; whether the Site exists, the API says (oup sites lists them). */
320
+ const isSite = (value) => SITE_ID.test(value);
257
321
  /** A Database's flags of one verb that another verb does not take. */
258
322
  const PG_FLAGS = {
259
323
  list: [],
@@ -262,6 +326,7 @@ const PG_FLAGS = {
262
326
  create: ['memory', 'storage', 'site', 'no-wait', 'max-storage', 'no-auto-grow'],
263
327
  restore: ['memory', 'storage', 'site', 'no-wait', 'time', 'max-storage', 'no-auto-grow'],
264
328
  resize: ['memory', 'storage', 'no-wait', 'max-storage', 'no-max-storage', 'auto-grow', 'no-auto-grow'],
329
+ proxy: ['access', 'port'],
265
330
  };
266
331
  async function pg(args) {
267
332
  const [verb, ...rest] = args;
@@ -279,6 +344,8 @@ async function pg(args) {
279
344
  'no-max-storage': { type: 'boolean' },
280
345
  'auto-grow': { type: 'boolean' },
281
346
  'no-auto-grow': { type: 'boolean' },
347
+ access: { type: 'string' },
348
+ port: { type: 'string' },
282
349
  },
283
350
  });
284
351
  if (verb === undefined || !Object.hasOwn(PG_FLAGS, verb)) {
@@ -294,7 +361,7 @@ async function pg(args) {
294
361
  return fail(USAGE);
295
362
  }
296
363
  if (values.site !== undefined && !isSite(values.site)) {
297
- return fail(`--site is one of ${COMPUTE_SITES.join(', ')}`);
364
+ return fail('--site takes a Site id, as oup sites lists them');
298
365
  }
299
366
  const memoryMb = count('memory', values.memory);
300
367
  const storageGb = count('storage', values.storage);
@@ -323,6 +390,8 @@ async function pg(args) {
323
390
  ? 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.`)
324
391
  : fail(deleted.error.message);
325
392
  }
393
+ case 'proxy':
394
+ return pgProxy(client, project, found(), values.access, values.port);
326
395
  case 'resize': {
327
396
  const database = found();
328
397
  if (memoryMb === undefined && storageGb === undefined && Object.keys(growth.settings).length === 0) {
@@ -381,6 +450,50 @@ async function pg(args) {
381
450
  return fail(USAGE);
382
451
  }
383
452
  }
453
+ /**
454
+ * `oup pg proxy`: the caller's own role, a first login through the tunnel
455
+ * (which waits for the role and, at owner, makes it act as app), then the
456
+ * local port, until Ctrl-C.
457
+ */
458
+ async function pgProxy(client, project, database, accessFlag, portFlag) {
459
+ const access = parseAccess(accessFlag);
460
+ const port = parsePort(portFlag);
461
+ if (!access.ok || !port.ok) {
462
+ return fail(!access.ok ? access.error : !port.ok ? port.error : '');
463
+ }
464
+ // A taken port is said before any waiting.
465
+ const free = await portFree(port.value);
466
+ if (!free.ok) {
467
+ return fail(free.error);
468
+ }
469
+ const proxy = await client.openDatabaseProxy(project.id, database.id, { access: access.value });
470
+ if (!proxy.ok) {
471
+ return fail(proxy.error.message);
472
+ }
473
+ const token = async () => {
474
+ const fresh = await apiAccess(credentialsPath());
475
+ return fresh.ok ? { ok: true, value: fresh.value.token } : fresh;
476
+ };
477
+ const tunnel = { url: proxy.value.tunnelUrl, token, warn: (message) => console.error(`oup: ${message}`) };
478
+ const prepared = await prepareRole({ ...tunnel, proxy: proxy.value, report: (message) => console.log(message) });
479
+ if (!prepared.ok) {
480
+ return fail(prepared.error);
481
+ }
482
+ const server = createServer();
483
+ serveTunnel(server, tunnel);
484
+ const listening = await listen(server, port.value);
485
+ if (!listening.ok) {
486
+ return fail(listening.error);
487
+ }
488
+ // Once listening, an error of the server (too many open files) is said, and the proxy goes on.
489
+ server.on('error', (error) => console.error(`oup: ${error.message}`));
490
+ console.log(`${database.name} (${access.value}) on ${LISTEN_HOST}:${port.value}. Connect with:`);
491
+ console.log(` ${connectionUrl(proxy.value, port.value)}`);
492
+ console.log('Press Ctrl-C to stop.');
493
+ await once(process, 'SIGINT');
494
+ server.close();
495
+ process.exit(0);
496
+ }
384
497
  /** Until the Database is ready; every state it passes through is reported once. */
385
498
  async function waitReady(client, projectId, databaseId, name) {
386
499
  // A restore first fetches the base backup and replays WAL; a new memory size restarts both instances.
@@ -464,7 +577,7 @@ async function serviceDeploy(client, project, existing, flags) {
464
577
  return fail('oup service deploy needs --image');
465
578
  }
466
579
  if (flags.site !== undefined && !isSite(flags.site)) {
467
- return fail(`--site is one of ${COMPUTE_SITES.join(', ')}`);
580
+ return fail('--site takes a Site id, as oup sites lists them');
468
581
  }
469
582
  if (flags.port !== undefined && flags['no-port'] === true) {
470
583
  return fail('--port and --no-port exclude each other');
@@ -638,7 +751,7 @@ async function jobDeploy(client, project, existing, flags) {
638
751
  return fail('--schedule and --no-schedule exclude each other');
639
752
  }
640
753
  if (flags.site !== undefined && !isSite(flags.site)) {
641
- return fail(`--site is one of ${COMPUTE_SITES.join(', ')}`);
754
+ return fail('--site takes a Site id, as oup sites lists them');
642
755
  }
643
756
  if (flags.command !== undefined && flags.command.length === 0) {
644
757
  return fail('nothing after --; leave it out to keep the command');
@@ -831,6 +944,364 @@ async function bucket(args) {
831
944
  return fail(USAGE);
832
945
  }
833
946
  }
947
+ /** `oup domain`: the linked Project's Domains; a custom one is claimed, proven with a DNS record, and deleted (decision 135). */
948
+ async function domain(args) {
949
+ const [verb, ...rest] = args;
950
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { project: { type: 'string' } } });
951
+ const [typed] = positionals;
952
+ if (verb === undefined || !['list', 'add', 'verify', 'delete'].includes(verb) || (verb !== 'list' && typed === undefined)) {
953
+ return fail(USAGE);
954
+ }
955
+ const { client, project } = await inProject(values.project);
956
+ const listed = await client.listDomains(project.id);
957
+ const domains = listed.ok ? listed.value : fail(listed.error.message);
958
+ if (verb === 'list') {
959
+ console.log(formatDomains(domains).join('\n'));
960
+ return;
961
+ }
962
+ const hostname = hostnameOf(typed);
963
+ const records = (claimed) => dnsRecords(claimed, ingressOf(domains)).join('\n');
964
+ if (verb === 'add') {
965
+ const problem = hostnameProblem(hostname);
966
+ if (problem !== undefined) {
967
+ return fail(problem);
968
+ }
969
+ const created = await client.createDomain(project.id, { hostname });
970
+ if (!created.ok) {
971
+ return fail(created.error.message);
972
+ }
973
+ console.log(`Added ${hostname} to ${project.name}. Publish these DNS records, then run: oup domain verify ${hostname}\n${records(created.value)}`);
974
+ 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.');
975
+ return;
976
+ }
977
+ const found = domainNamed(domains, hostname, project.name);
978
+ if (!found.ok) {
979
+ return fail(found.error);
980
+ }
981
+ if (verb === 'verify') {
982
+ if (found.value.kind === 'default' || found.value.verification.state === 'verified') {
983
+ console.log(`${hostname} is ${found.value.kind === 'default' ? "the Project's default Domain and needs no proof" : 'verified already'}.`);
984
+ return;
985
+ }
986
+ const verified = await client.verifyDomain(project.id, found.value.id);
987
+ return verified.ok ? console.log(`${hostname} is verified: its Routes are served.`) : fail(`${verified.error.message}\n${records(found.value)}`);
988
+ }
989
+ const deleted = await client.deleteDomain(project.id, found.value.id);
990
+ return deleted.ok ? console.log(`Deleted ${hostname} and its Routes from ${project.name}.`) : fail(deleted.error.message);
991
+ }
992
+ /** `oup route`: what is served where. A Route is named by its address, `<hostname>/<path>`, or `/<path>` on the default Domain. */
993
+ async function route(args) {
994
+ const [verb, ...rest] = args;
995
+ const { values, positionals } = parseArgs({
996
+ args: rest,
997
+ allowPositionals: true,
998
+ options: { project: { type: 'string' }, bucket: { type: 'string' }, service: { type: 'string' }, spa: { type: 'boolean' } },
999
+ });
1000
+ const [address] = positionals;
1001
+ const target = values.bucket !== undefined || values.service !== undefined || values.spa !== undefined;
1002
+ if (verb === undefined || !['list', 'add', 'delete'].includes(verb) || (verb !== 'list' && address === undefined) || (verb !== 'add' && target)) {
1003
+ return fail(USAGE);
1004
+ }
1005
+ const { client, project } = await inProject(values.project);
1006
+ const listed = await client.listDomains(project.id);
1007
+ const domains = listed.ok ? listed.value : fail(listed.error.message);
1008
+ const routesOf = async (domainId) => {
1009
+ const routes = await client.listRoutes(project.id, domainId);
1010
+ return routes.ok ? routes.value : fail(routes.error.message);
1011
+ };
1012
+ const buckets = async () => {
1013
+ const all = await client.listBuckets(project.id);
1014
+ return all.ok ? all.value : fail(all.error.message);
1015
+ };
1016
+ const services = async () => {
1017
+ const all = await client.listServices(project.id);
1018
+ return all.ok ? all.value : fail(all.error.message);
1019
+ };
1020
+ if (verb === 'list') {
1021
+ const [routes, allBuckets, allServices] = await Promise.all([Promise.all(domains.map((each) => routesOf(each.id))), buckets(), services()]);
1022
+ const lines = formatRoutes(domains, Object.fromEntries(domains.map((each, index) => [each.id, routes[index] ?? []])), allBuckets, allServices);
1023
+ console.log(lines.length === 0 ? `No Routes in ${project.name}: every path answers 404.` : lines.join('\n'));
1024
+ return;
1025
+ }
1026
+ const named = parseAddress(address, domains, project.name);
1027
+ if (!named.ok) {
1028
+ return fail(named.error);
1029
+ }
1030
+ const { domain: at, pathPrefix } = named.value;
1031
+ const where = `${at.hostname}${pathPrefix}`;
1032
+ if (verb === 'add') {
1033
+ // Only the list the Route's target is in.
1034
+ const input = routeInput(pathPrefix, values, values.bucket === undefined ? [] : await buckets(), values.service === undefined ? [] : await services(), project.name);
1035
+ if (!input.ok) {
1036
+ return fail(input.error);
1037
+ }
1038
+ const created = await client.createRoute(project.id, at.id, input.value);
1039
+ if (!created.ok) {
1040
+ return fail(routeRefusal(created.error.message, values));
1041
+ }
1042
+ const pending = at.kind === 'custom' && at.verification.state === 'pending';
1043
+ 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.`);
1044
+ return;
1045
+ }
1046
+ const existing = (await routesOf(at.id)).find((candidate) => candidate.pathPrefix === pathPrefix);
1047
+ if (existing === undefined) {
1048
+ return fail(`no Route ${where} in ${project.name}; oup route list shows them`);
1049
+ }
1050
+ const deleted = await client.deleteRoute(project.id, at.id, existing.id);
1051
+ return deleted.ok ? console.log(`Deleted the Route ${where}; what it went to stays.`) : fail(deleted.error.message);
1052
+ }
1053
+ /** `oup usage`: what the linked Project's Resources use now of what they were given (decision 124); not what is billed. */
1054
+ /** `oup member`: the Account's Members, their roles and grants, removing one, leaving. */
1055
+ async function member(args) {
1056
+ const [verb, ...rest] = args;
1057
+ const { values, positionals } = parseArgs({
1058
+ args: rest,
1059
+ allowPositionals: true,
1060
+ options: { account: { type: 'string' }, database: { type: 'string' }, project: { type: 'string' } },
1061
+ });
1062
+ const [email, word, ...extra] = positionals;
1063
+ const arity = { list: 0, leave: 0, remove: 1, role: 2, grant: 2, revoke: 1 }[verb ?? ''];
1064
+ if (arity === undefined || positionals.length !== arity || extra.length > 0) {
1065
+ return fail(USAGE);
1066
+ }
1067
+ const onDatabase = verb === 'grant' || verb === 'revoke';
1068
+ if (onDatabase && values.database === undefined) {
1069
+ return fail(`oup member ${verb} needs --database <name>`);
1070
+ }
1071
+ if (onDatabase ? values.account !== undefined : values.database !== undefined || values.project !== undefined) {
1072
+ return fail(onDatabase ? `oup member ${verb} acts in the Database's Account; it takes no --account` : `oup member ${verb} takes no --database or --project`);
1073
+ }
1074
+ if (onDatabase) {
1075
+ return memberGrant(verb, email ?? '', word, values.database ?? '', values.project);
1076
+ }
1077
+ const client = await apiClient();
1078
+ const account = accountFor(await listAccounts(client), values.account);
1079
+ if (!account.ok) {
1080
+ return fail(account.error);
1081
+ }
1082
+ const refusal = (error) => fail(error.status === 409 ? `${error.message}\n ${LAST_OWNER_HINT}` : error.message);
1083
+ if (verb === 'leave') {
1084
+ const left = await client.removeMember(account.value.id, 'me');
1085
+ return left.ok ? console.log(`You left the Account ${account.value.name}.`) : refusal(left.error);
1086
+ }
1087
+ const members = await client.listMembers(account.value.id);
1088
+ if (!members.ok) {
1089
+ return fail(members.error.message);
1090
+ }
1091
+ if (verb === 'list') {
1092
+ return console.log(formatMembers(members.value).join('\n'));
1093
+ }
1094
+ const target = memberByEmail(members.value, email ?? '');
1095
+ if (!target.ok) {
1096
+ return fail(target.error);
1097
+ }
1098
+ if (verb === 'remove') {
1099
+ const removed = await client.removeMember(account.value.id, target.value.id);
1100
+ return removed.ok
1101
+ ? console.log(`Removed ${target.value.email} from ${account.value.name}; their Postgres roles in its Databases are dropped.`)
1102
+ : refusal(removed.error);
1103
+ }
1104
+ const parsed = parseRole(word);
1105
+ if (!parsed.ok) {
1106
+ return fail(parsed.error);
1107
+ }
1108
+ const changed = await client.updateMember(account.value.id, target.value.id, { role: parsed.value });
1109
+ if (!changed.ok) {
1110
+ return refusal(changed.error);
1111
+ }
1112
+ return console.log(changed.value.role === null
1113
+ ? `${changed.value.email} now has no role in ${account.value.name}, only their grants; their Postgres roles beyond those are dropped.`
1114
+ : `${changed.value.email} is now ${changed.value.role} of ${account.value.name}.`);
1115
+ }
1116
+ /** `oup token`: the Account's tokens (decision 144); create and roll print the secret alone on stdout. */
1117
+ async function token(args) {
1118
+ const [verb, ...rest] = args;
1119
+ const { values, positionals } = parseArgs({
1120
+ args: rest,
1121
+ allowPositionals: true,
1122
+ options: {
1123
+ account: { type: 'string' },
1124
+ database: { type: 'string' },
1125
+ project: { type: 'string' },
1126
+ expires: { type: 'string' },
1127
+ developer: { type: 'boolean' },
1128
+ },
1129
+ });
1130
+ const [name, word, ...extra] = positionals;
1131
+ const arity = { list: 0, create: 1, role: 2, grant: 2, revoke: 1, roll: 1, delete: 1 }[verb ?? ''];
1132
+ if (arity === undefined || positionals.length !== arity || extra.length > 0) {
1133
+ return fail(USAGE);
1134
+ }
1135
+ const onDatabase = verb === 'grant' || verb === 'revoke';
1136
+ if (onDatabase && values.database === undefined) {
1137
+ return fail(`oup token ${verb} needs --database <name>${verb === 'revoke' ? `; oup token delete ${name ?? '<name>'} revokes the token itself` : ''}`);
1138
+ }
1139
+ if (onDatabase ? values.account !== undefined : values.database !== undefined || values.project !== undefined) {
1140
+ return fail(onDatabase ? `oup token ${verb} acts in the Database's Account; it takes no --account` : `oup token ${verb} takes no --database or --project`);
1141
+ }
1142
+ if (values.expires !== undefined && verb !== 'create' && verb !== 'roll') {
1143
+ return fail(`oup token ${verb} takes no --expires`);
1144
+ }
1145
+ if (values.developer !== undefined && verb !== 'create') {
1146
+ return fail(`oup token ${verb} takes no --developer; oup token role <name> developer gives it the role`);
1147
+ }
1148
+ const now = new Date();
1149
+ const expiry = verb === 'create' || verb === 'roll' ? parseExpiry(values.expires, now) : undefined;
1150
+ if (expiry !== undefined && !expiry.ok) {
1151
+ return fail(expiry.error);
1152
+ }
1153
+ const role = verb === 'role' ? parseTokenRole(word) : undefined;
1154
+ if (role !== undefined && !role.ok) {
1155
+ return fail(role.error);
1156
+ }
1157
+ const access = verb === 'grant' ? parseGrantAccess(word) : undefined;
1158
+ if (access !== undefined && !access.ok) {
1159
+ return fail(access.error);
1160
+ }
1161
+ if (onDatabase) {
1162
+ return tokenGrant(name ?? '', access?.value, values.database ?? '', values.project);
1163
+ }
1164
+ const client = await apiClient();
1165
+ const account = accountFor(await listAccounts(client), values.account);
1166
+ if (!account.ok) {
1167
+ return fail(account.error);
1168
+ }
1169
+ if (verb === 'create') {
1170
+ const input = { name: name ?? '', role: values.developer === true ? 'developer' : null, expiresAt: expiry?.ok === true ? expiry.value.toISOString() : '' };
1171
+ const created = await client.createAccountToken(account.value.id, input);
1172
+ if (!created.ok) {
1173
+ return fail(created.error.message);
1174
+ }
1175
+ const rights = created.value.role === null ? `no rights yet: oup token grant ${created.value.name} read --database <name> gives some` : 'the developer role';
1176
+ console.error(`Created the Account token ${created.value.name} in ${account.value.name}, with ${rights}, until ${created.value.expiresAt.slice(0, 10)}.`);
1177
+ console.error('Its secret follows, shown only now; use it as OUP_API_KEY:');
1178
+ return console.log(created.value.secret);
1179
+ }
1180
+ const tokens = await client.listAccountTokens(account.value.id);
1181
+ if (!tokens.ok) {
1182
+ return fail(tokens.error.message);
1183
+ }
1184
+ if (verb === 'list') {
1185
+ const lines = formatTokens(tokens.value, now);
1186
+ return console.log(lines.length === 0 ? 'No Account tokens; oup token create <name> --expires 90d makes one.' : lines.join('\n'));
1187
+ }
1188
+ const target = tokenByName(tokens.value, name ?? '');
1189
+ if (!target.ok) {
1190
+ return fail(target.error);
1191
+ }
1192
+ if (verb === 'delete') {
1193
+ const deleted = await client.deleteAccountToken(account.value.id, target.value.id);
1194
+ return deleted.ok
1195
+ ? console.log(`Revoked the Account token ${target.value.name}; it stops working now, and its Postgres roles are dropped.`)
1196
+ : fail(deleted.error.message);
1197
+ }
1198
+ if (verb === 'roll') {
1199
+ const rolled = await client.rollAccountToken(account.value.id, target.value.id, { expiresAt: expiry?.ok === true ? expiry.value.toISOString() : '' });
1200
+ if (!rolled.ok) {
1201
+ return fail(rolled.error.message);
1202
+ }
1203
+ const previous = rolled.value.previousSecretValidUntil;
1204
+ console.error(`Rolled the Account token ${rolled.value.name}, now valid until ${rolled.value.expiresAt.slice(0, 10)}.`);
1205
+ console.error(previous === undefined ? 'The previous secret had expired.' : `The previous secret works until ${previous}.`);
1206
+ console.error('The new secret follows, shown only now:');
1207
+ return console.log(rolled.value.secret);
1208
+ }
1209
+ const changed = await client.updateAccountToken(account.value.id, target.value.id, { role: role?.ok === true ? role.value : null });
1210
+ if (!changed.ok) {
1211
+ return fail(changed.error.message);
1212
+ }
1213
+ return console.log(changed.value.role === null
1214
+ ? `The Account token ${changed.value.name} now has no role, only its grants; its Postgres roles beyond those are dropped.`
1215
+ : `The Account token ${changed.value.name} now has the role ${changed.value.role}.`);
1216
+ }
1217
+ /** `oup token grant` and `revoke`: a token's access to one Database of the linked Project (decision 139). */
1218
+ async function tokenGrant(name, access, databaseName, projectFlag) {
1219
+ const { client, project } = await inProject(projectFlag);
1220
+ const databases = await client.listDatabases(project.id);
1221
+ if (!databases.ok) {
1222
+ return fail(databases.error.message);
1223
+ }
1224
+ const database = databases.value.find((candidate) => candidate.name === databaseName) ?? fail(`no Database ${databaseName} in ${project.name}`);
1225
+ const tokens = await client.listAccountTokens(project.accountId);
1226
+ if (!tokens.ok) {
1227
+ return fail(tokens.error.message);
1228
+ }
1229
+ const target = tokenByName(tokens.value, name);
1230
+ if (!target.ok) {
1231
+ return fail(target.error);
1232
+ }
1233
+ const where = `${project.name}/${database.name}`;
1234
+ if (access === undefined) {
1235
+ const removed = await client.removeAccountTokenGrant(project.accountId, target.value.id, database.id);
1236
+ return removed.ok
1237
+ ? console.log(`The Account token ${name} has no grant on ${where} any more.${target.value.role === null ? ' Its Postgres roles there are dropped.' : ''}`)
1238
+ : fail(removed.error.status === 404 ? `the Account token ${name} has no grant on ${where}` : removed.error.message);
1239
+ }
1240
+ const granted = await client.setAccountTokenGrant(project.accountId, target.value.id, database.id, { access });
1241
+ const note = target.value.role === null ? '' : ` It counts only once the token has no role (it is ${target.value.role}).`;
1242
+ return granted.ok
1243
+ ? console.log(`The Account token ${name} may use ${where} at ${granted.value.access}: oup pg proxy ${database.name} --access ${granted.value.access} or lower.${note}`)
1244
+ : fail(granted.error.message);
1245
+ }
1246
+ /** `oup member grant` and `revoke`: a Member's access to one Database of the linked Project (decision 139). */
1247
+ async function memberGrant(verb, email, level, name, projectFlag) {
1248
+ const access = verb === 'grant' ? parseGrantAccess(level) : undefined;
1249
+ if (access !== undefined && !access.ok) {
1250
+ return fail(access.error);
1251
+ }
1252
+ const { client, project } = await inProject(projectFlag);
1253
+ const databases = await client.listDatabases(project.id);
1254
+ if (!databases.ok) {
1255
+ return fail(databases.error.message);
1256
+ }
1257
+ const database = databases.value.find((candidate) => candidate.name === name) ?? fail(`no Database ${name} in ${project.name}`);
1258
+ const members = await client.listMembers(project.accountId);
1259
+ if (!members.ok) {
1260
+ return fail(members.error.message);
1261
+ }
1262
+ const target = memberByEmail(members.value, email);
1263
+ if (!target.ok) {
1264
+ return fail(target.error);
1265
+ }
1266
+ const where = `${project.name}/${database.name}`;
1267
+ const note = target.value.role === null ? '' : ` It counts only once they have no role (they are ${target.value.role}).`;
1268
+ if (access === undefined) {
1269
+ const removed = await client.removeGrant(project.accountId, target.value.id, database.id);
1270
+ return removed.ok
1271
+ ? console.log(`${target.value.email} has no grant on ${where} any more.${target.value.role === null ? ' Their Postgres roles there are dropped.' : ''}`)
1272
+ : fail(removed.error.status === 404 ? `${target.value.email} has no grant on ${where}` : removed.error.message);
1273
+ }
1274
+ const granted = await client.setGrant(project.accountId, target.value.id, database.id, { access: access.value });
1275
+ return granted.ok
1276
+ ? console.log(`${target.value.email} may use ${where} at ${granted.value.access}: oup pg proxy ${database.name} --access ${granted.value.access} or lower.${note}`)
1277
+ : fail(granted.error.message);
1278
+ }
1279
+ async function usage(args) {
1280
+ const { values, positionals } = parseArgs({
1281
+ args,
1282
+ allowPositionals: true,
1283
+ options: { project: { type: 'string' }, instances: { type: 'boolean' }, json: { type: 'boolean' } },
1284
+ });
1285
+ if (positionals.length > 0) {
1286
+ return fail(USAGE);
1287
+ }
1288
+ const { client, project } = await inProject(values.project);
1289
+ const read = await client.getUsage(project.id);
1290
+ if (!read.ok) {
1291
+ return fail(read.error.message);
1292
+ }
1293
+ console.log(values.json === true ? JSON.stringify(read.value, null, 2) : formatUsage(read.value, project.name, { instances: values.instances ?? false }).join('\n'));
1294
+ }
1295
+ async function sites(args) {
1296
+ if (args.length > 0) {
1297
+ return fail(USAGE);
1298
+ }
1299
+ const read = await (await apiClient()).listSites();
1300
+ if (!read.ok) {
1301
+ return fail(read.error.message);
1302
+ }
1303
+ console.log(formatSites(read.value).join('\n'));
1304
+ }
834
1305
  async function siteDeploy(args) {
835
1306
  const { values, positionals } = parseArgs({
836
1307
  args,
@@ -882,6 +1353,10 @@ const run = async () => {
882
1353
  return project(rest);
883
1354
  case 'link':
884
1355
  return link(rest);
1356
+ case 'token':
1357
+ return token(rest);
1358
+ case 'member':
1359
+ return member(rest);
885
1360
  case 'pg':
886
1361
  return pg(rest);
887
1362
  case 'service':
@@ -892,6 +1367,14 @@ const run = async () => {
892
1367
  return secret(rest);
893
1368
  case 'bucket':
894
1369
  return bucket(rest);
1370
+ case 'domain':
1371
+ return domain(rest);
1372
+ case 'route':
1373
+ return route(rest);
1374
+ case 'usage':
1375
+ return usage(rest);
1376
+ case 'sites':
1377
+ return sites(rest);
895
1378
  case 'site':
896
1379
  return rest[0] === 'deploy' ? siteDeploy(rest.slice(1)) : fail(USAGE);
897
1380
  case 'version':