@openupstream/cli 0.4.0 → 0.6.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,6 +6,10 @@
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>
@@ -20,6 +24,10 @@
20
24
  * oup job stop <name> <run>
21
25
  * oup job logs <name> [<run>] [--tail <n>] [-f] [--timestamps] the newest run by default
22
26
  * oup secret list | set <NAME> | delete <NAME> a value is read from stdin
27
+ * oup key list | create <name> | show <name> | rotate <name> | delete <name> | restore <name>
28
+ * oup key grant <name> (--service <name> | --job <name>) --access encrypt|decrypt|both
29
+ * oup key revoke <name> (--service <name> | --job <name>)
30
+ * oup key log <name> [--limit <n>] [--json] who encrypted and decrypted, kept 30 days
23
31
  * oup bucket list | create <name> | show <name> | show-access-key <name> | export-env <name> [--file <path>] | delete <name>
24
32
  * oup domain list | add <hostname> | verify <hostname> | delete <hostname>
25
33
  * oup route list | add <address> --bucket <name> [--spa] | add <address> --service <name> | delete <address>
@@ -27,10 +35,10 @@
27
35
  * oup site deploy <dir> --bucket <name> [--keep] [--force]
28
36
  * oup version
29
37
  *
30
- * Database, service, job, secret, bucket, domain, route and usage commands act on the linked Project; `--project`
38
+ * Database, service, job, secret, key, bucket, domain, route and usage commands act on the linked Project; `--project`
31
39
  * or `OUP_PROJECT` names another.
32
40
  *
33
- * `OUP_API_KEY` (a madAuth API key) replaces `oup login`, e.g. in CI, with
41
+ * `OUP_API_KEY` (a madAuth API key or an Account token) replaces `oup login`, e.g. in CI, with
34
42
  * `OUP_API_URL` for another API than https://console.openupstream.com/api.
35
43
  */
36
44
  import { spawn } from 'node:child_process';
@@ -40,12 +48,14 @@ import { createServer } from 'node:net';
40
48
  import { resolve } from 'node:path';
41
49
  import { parseArgs } from 'node:util';
42
50
  import { S3Client } from '@aws-sdk/client-s3';
43
- import { COMPUTE_SITES, DEFAULT_API_URL, OpenUpstreamClient, SDK_VERSION, cliLogin, } from '@openupstream/sdk';
51
+ import { SITE_ID, DEFAULT_API_URL, OpenUpstreamClient, SDK_VERSION, cliLogin, } from '@openupstream/sdk';
44
52
  import { bucketEnv, bucketIn, mergeEnv, s3Endpoint } from './buckets.js';
45
53
  import { credentialsPath, readCredentials, removeCredentials, writeCredentials } from './credentials.js';
46
54
  import { deploy } from './deploy.js';
47
55
  import { discover, emailOf, startDeviceSignIn, waitForApproval } from './oidc.js';
48
56
  import { accountFor, findLink, formatProjects, projectFor, resolveProject, writeLink } from './project.js';
57
+ import { LAST_OWNER_HINT, formatMembers, memberByEmail, parseGrantAccess, parseRole } from './members.js';
58
+ import { formatTokens, parseExpiry, parseTokenRole, tokenByName } from './tokens.js';
49
59
  import { JOB_FLAGS, formatJobs, formatRuns, isFinished, outcomeOf, parseEnv, planJobDeploy, splitAtDashes, strayFlag, } from './jobs.js';
50
60
  import { formatLogEntry, parseTail } from './logs.js';
51
61
  import { DATABASE_DEFAULTS, formatDatabases, growthOf, growthSettings, planRestore } from './databases.js';
@@ -53,9 +63,13 @@ import { formatServices, planServiceDeploy, waitUntilRunning } from './services.
53
63
  import { LISTEN_HOST, connectionUrl, listen, parseAccess, parsePort, portFree, prepareRole, serveTunnel } from './proxy.js';
54
64
  import { dnsRecords, domainNamed, formatDomains, formatRoutes, hostnameOf, hostnameProblem, ingressOf, parseAddress, routeInput, routeRefusal } from './routes.js';
55
65
  import { apiAccess } from './session.js';
66
+ import { deletionNotice, formatKey, formatKeyCalls, formatKeys, grantHolder, parseCallLimit, parseKeyAccess } from './keys.js';
56
67
  import { readSecretValue } from './stdin.js';
68
+ import { ENVIRONMENT_FLAGS, ENVIRONMENT_OPTIONS, desiredEnvironment, removedNames } from './environment.js';
69
+ import { formatSecrets, secretSetMessage } from './secrets.js';
57
70
  import { waitUntil } from './wait.js';
58
71
  import { formatUsage } from './usage.js';
72
+ import { formatSites } from './sites.js';
59
73
  import { CLI_VERSION } from './version.js';
60
74
  const USAGE = `usage:
61
75
  oup login [--api <url>] [--no-browser]
@@ -63,9 +77,22 @@ const USAGE = `usage:
63
77
  oup project list
64
78
  oup project create <name> [--account <name|id>] [--link]
65
79
  oup link <project>
80
+ oup member list [--account <name|id>]
81
+ oup member role <email> owner|developer|none [--account <name|id>]
82
+ oup member grant <email> read|write|owner --database <name> [--project <name|id>]
83
+ oup member revoke <email> --database <name> [--project <name|id>]
84
+ oup member remove <email> [--account <name|id>]
85
+ oup member leave [--account <name|id>]
86
+ oup token list [--account <name|id>]
87
+ oup token create <name> --expires <days|date> [--developer] [--account <name|id>] (prints the secret once)
88
+ oup token role <name> developer|none [--account <name|id>]
89
+ oup token grant <name> read|write|owner --database <name> [--project <name|id>]
90
+ oup token revoke <name> --database <name> [--project <name|id>]
91
+ oup token roll <name> --expires <days|date> [--account <name|id>] (a new secret; the old one works 24 hours more)
92
+ oup token delete <name> [--account <name|id>]
66
93
  oup pg list
67
94
  oup pg show <name>
68
- oup pg create <name> [--memory <MB>] [--storage <GB>] [--site hetzner-fsn1|ovh-lim] [--max-storage <GB> | --no-auto-grow] [--no-wait]
95
+ oup pg create <name> [--memory <MB>] [--storage <GB>] [--site <site>] [--max-storage <GB> | --no-auto-grow] [--no-wait]
69
96
  oup pg restore <source> <name> [--time <RFC 3339>] [--memory <MB>] [--storage <GB>] [--site …] [--max-storage <GB> | --no-auto-grow] [--no-wait]
70
97
  oup pg resize <name> [--memory <MB>] [--storage <GB>] [--max-storage <GB> | --no-max-storage] [--auto-grow | --no-auto-grow] [--no-wait]
71
98
  oup pg delete <name>
@@ -73,14 +100,21 @@ const USAGE = `usage:
73
100
  oup service list
74
101
  oup service show <name>
75
102
  oup service deploy <name> --image <ref> [--port <n> | --no-port] [--replicas <n>] [--memory <MB>] [--cpu <millicores>]
76
- [--site hetzner-fsn1|ovh-lim] [--registry-user <user> --registry-password-stdin] [--no-wait]
103
+ [--site <site>] [--registry-user <user> --registry-password-stdin] [--no-wait]
104
+ [--secret <NAME>]… [--env <NAME>=<value>]… [--env-file <path>]… [--no-secrets] [--no-env]
105
+ [--add-secret <NAME>]… [--remove-secret <NAME>]… [--set-env <NAME>=<value>]… [--unset-env <NAME>]…
106
+ [--database <name>[:owner]]… [--no-databases] [--add-database <name>[:owner]]… [--remove-database <name>]…
107
+ [--pre-deploy <job> | --no-pre-deploy]
77
108
  oup service logs <name> [--tail <n>] [-f | --follow] [--timestamps]
78
109
  oup service delete <name>
79
110
  oup job list
80
111
  oup job show <name>
81
112
  oup job deploy <name> --image <ref> [--schedule <cron> | --no-schedule] [--time-zone <IANA name>]
82
- [--timeout <seconds>] [--memory <MB>] [--cpu <millicores>] [--site hetzner-fsn1|ovh-lim]
113
+ [--timeout <seconds>] [--memory <MB>] [--cpu <millicores>] [--site <site>]
83
114
  [--registry-user <user> --registry-password-stdin] [--no-wait] [--no-command | -- <command> <arg>…]
115
+ [--secret <NAME>]… [--env <NAME>=<value>]… [--env-file <path>]… [--no-secrets] [--no-env]
116
+ [--add-secret <NAME>]… [--remove-secret <NAME>]… [--set-env <NAME>=<value>]… [--unset-env <NAME>]…
117
+ [--database <name>[:owner]]… [--no-databases] [--add-database <name>[:owner]]… [--remove-database <name>]…
84
118
  oup job run <name> [--env NAME=value]… [--no-wait] [-- <arg>…]
85
119
  oup job runs <name>
86
120
  oup job stop <name> <run>
@@ -89,6 +123,15 @@ const USAGE = `usage:
89
123
  oup secret list
90
124
  oup secret set <NAME> (the value from stdin)
91
125
  oup secret delete <NAME>
126
+ oup key list
127
+ oup key create <name>
128
+ oup key show <name>
129
+ oup key rotate <name> (a new version; what older ones encrypted still decrypts)
130
+ oup key delete <name> (pending deletion for 7 days, then erased for good)
131
+ oup key restore <name> (while it is pending deletion)
132
+ oup key grant <name> (--service <name> | --job <name>) --access encrypt|decrypt|both
133
+ oup key revoke <name> (--service <name> | --job <name>)
134
+ oup key log <name> [--limit <n>] [--json] (its calls, newest first, kept 30 days)
92
135
  oup bucket list
93
136
  oup bucket create <name>
94
137
  oup bucket show <name>
@@ -105,10 +148,11 @@ const USAGE = `usage:
105
148
  oup route delete <address>
106
149
  <address> is <hostname>/<path>, or /<path> alone for the Project's default Domain
107
150
  oup usage [--instances] [--json]
151
+ oup sites (the compute Sites, for --site)
108
152
  oup site deploy <dir> --bucket <name> [--keep] [--force]
109
153
  oup version
110
154
 
111
- Database, service, job, secret, bucket, domain, route and usage commands take --project <name|id>; without
155
+ Database, service, job, secret, key, bucket, domain, route and usage commands take --project <name|id>; without
112
156
  it, the Project linked to this directory (oup link) or OUP_PROJECT.
113
157
 
114
158
  pg create gives a Database 256 MB and 1 GB unless told otherwise. pg restore
@@ -127,6 +171,50 @@ every table, write also changes rows, owner acts as app, the role the
127
171
  Project's Services use, so migrations work; owner connections go to the
128
172
  primary, so migration tools' locks work, at most 5 at once.
129
173
 
174
+ A Service or Job gets the Secrets its deploy names and no others: --secret
175
+ NAME (the Secret must exist: oup secret set), and plain settings as
176
+ Variables: --env NAME=value or --env-file with one NAME=value per line.
177
+ These state the whole list: given for a Service that exists, they replace
178
+ what it has, and oup prints the names that go; --no-secrets and --no-env
179
+ empty one. To change one entry and keep the rest: --add-secret,
180
+ --remove-secret, --set-env, --unset-env. Without any of them a deploy
181
+ leaves both lists as they are. A Variable is shown to everyone who may read
182
+ the Project: credentials belong in a Secret.
183
+
184
+ A Service or Job reaches the Databases its deploy names and no others:
185
+ --database main gives it DATABASE_URL as a Postgres role of its own
186
+ (svc_<name> or job_<name>), which can connect and nothing else until the
187
+ Database's owner grants it rights in SQL, e.g. GRANT oup_write TO svc_api.
188
+ --database main:owner gives it the owner's connection, for the Job that
189
+ changes the schema and runs those grants. Without --database it gets no
190
+ DATABASE_URL. The flags work like --secret: --database states the whole
191
+ list, --no-databases empties it, --add-database and --remove-database
192
+ change one entry.
193
+
194
+ --pre-deploy <job> names a Job of the Project that is run, and waited for,
195
+ before each rollout of the Service: a migration, for example. Deploy the
196
+ Job first, so it runs the new image. When its run fails, nothing is rolled
197
+ out, the Service runs what it ran before, and oup service deploy exits 1
198
+ and says where the run's output is. --no-pre-deploy takes it off.
199
+
200
+ member acts on your only Account, or on --account. An owner may do
201
+ everything, the Account's Members included; a developer every Project and
202
+ everything in it; a Member with role none only what their grants give. A
203
+ grant lets a Member use one Database of the linked Project (or --project)
204
+ at a level or below: see it and open pg proxy, nothing else of the Project.
205
+ Only owners change roles and grants and remove Members; anyone may leave.
206
+ An Account always keeps an owner. Postgres roles a Member may no longer use
207
+ are dropped. These commands need oup login: an API key cannot change who
208
+ is in an Account.
209
+
210
+ token manages Account tokens: secrets of the Account, not of a person, for
211
+ CI, BI tools and scripts. A token has the developer role (--developer) or
212
+ only the grants given to it, never owner, and expires after at most a year
213
+ (--expires 90d or a date). create and roll print the secret alone on
214
+ stdout, once; pipe it into where it is kept, e.g. | gh secret set
215
+ OUP_API_KEY. oup and the SDK use it as OUP_API_KEY. Owners manage tokens
216
+ with oup login; developers list them. delete revokes a token at once.
217
+
130
218
  logs prints the last lines (100 by default) of every replica or of a run,
131
219
  with -f also new ones as they are written, for up to an hour. Nothing is
132
220
  kept: what a pod wrote before it was replaced is gone.`;
@@ -277,7 +365,8 @@ const count = (flag, value) => {
277
365
  const n = Number(value);
278
366
  return Number.isInteger(n) && n > 0 ? n : fail(`--${flag} must be a positive whole number, not ${value}`);
279
367
  };
280
- const isSite = (value) => COMPUTE_SITES.includes(value);
368
+ /** A Site id's form; whether the Site exists, the API says (oup sites lists them). */
369
+ const isSite = (value) => SITE_ID.test(value);
281
370
  /** A Database's flags of one verb that another verb does not take. */
282
371
  const PG_FLAGS = {
283
372
  list: [],
@@ -321,7 +410,7 @@ async function pg(args) {
321
410
  return fail(USAGE);
322
411
  }
323
412
  if (values.site !== undefined && !isSite(values.site)) {
324
- return fail(`--site is one of ${COMPUTE_SITES.join(', ')}`);
413
+ return fail('--site takes a Site id, as oup sites lists them');
325
414
  }
326
415
  const memoryMb = count('memory', values.memory);
327
416
  const storageGb = count('storage', values.storage);
@@ -474,6 +563,9 @@ async function service(args) {
474
563
  image: { type: 'string' },
475
564
  port: { type: 'string' },
476
565
  'no-port': { type: 'boolean' },
566
+ ...ENVIRONMENT_OPTIONS,
567
+ 'pre-deploy': { type: 'string' },
568
+ 'no-pre-deploy': { type: 'boolean' },
477
569
  replicas: { type: 'string' },
478
570
  memory: { type: 'string' },
479
571
  cpu: { type: 'string' },
@@ -494,6 +586,10 @@ async function service(args) {
494
586
  if (verb !== 'logs' && logFlag !== undefined) {
495
587
  return fail(`oup service ${verb} does not take --${logFlag}`);
496
588
  }
589
+ const environmentFlag = [...ENVIRONMENT_FLAGS, 'pre-deploy', 'no-pre-deploy'].find((flag) => values[flag] !== undefined);
590
+ if (verb !== 'deploy' && environmentFlag !== undefined) {
591
+ return fail(`oup service ${verb} does not take --${environmentFlag}`);
592
+ }
497
593
  const { client, project } = await inProject(values.project);
498
594
  const services = await client.listServices(project.id);
499
595
  if (!services.ok) {
@@ -537,12 +633,27 @@ async function serviceDeploy(client, project, existing, flags) {
537
633
  return fail('oup service deploy needs --image');
538
634
  }
539
635
  if (flags.site !== undefined && !isSite(flags.site)) {
540
- return fail(`--site is one of ${COMPUTE_SITES.join(', ')}`);
636
+ return fail('--site takes a Site id, as oup sites lists them');
541
637
  }
542
638
  if (flags.port !== undefined && flags['no-port'] === true) {
543
639
  return fail('--port and --no-port exclude each other');
544
640
  }
641
+ if (flags['pre-deploy'] !== undefined && flags['no-pre-deploy'] === true) {
642
+ return fail('--pre-deploy and --no-pre-deploy exclude each other');
643
+ }
644
+ // The Job that is run, and waited for, before each rollout (decision 173): named by the flag, else as it is.
645
+ const jobs = flags['pre-deploy'] !== undefined || existing?.preDeployJobId != null ? await client.listJobs(project.id) : undefined;
646
+ if (jobs !== undefined && !jobs.ok) {
647
+ return fail(jobs.error.message);
648
+ }
649
+ const namedJob = flags['pre-deploy'] === undefined ? undefined : jobs?.value.find((job) => job.name === flags['pre-deploy']);
650
+ if (flags['pre-deploy'] !== undefined && namedJob === undefined) {
651
+ return fail(`no Job ${flags['pre-deploy']} in ${project.name}; deploy it first (oup job deploy)`);
652
+ }
653
+ const preDeployJobId = flags['no-pre-deploy'] === true ? null : namedJob?.id;
654
+ const preDeployJob = preDeployJobId === null ? undefined : (namedJob ?? jobs?.value.find((job) => job.id === existing?.preDeployJobId));
545
655
  const registryAuth = await registryAuthFrom(flags);
656
+ const environment = await environmentFrom(existing, flags);
546
657
  const port = flags['no-port'] === true ? null : count('port', flags.port);
547
658
  const replicas = count('replicas', flags.replicas);
548
659
  const memoryMb = count('memory', flags.memory);
@@ -556,6 +667,8 @@ async function serviceDeploy(client, project, existing, flags) {
556
667
  ...(cpuMillicores === undefined ? {} : { cpuMillicores }),
557
668
  ...(flags.site === undefined || !isSite(flags.site) ? {} : { homeSite: flags.site }),
558
669
  ...(registryAuth === undefined ? {} : { registryAuth }),
670
+ environment,
671
+ ...(preDeployJobId === undefined ? {} : { preDeployJobId }),
559
672
  };
560
673
  const plan = planServiceDeploy(existing, desired);
561
674
  const deployed = plan.kind === 'invalid'
@@ -568,17 +681,28 @@ async function serviceDeploy(client, project, existing, flags) {
568
681
  if (!deployed.ok) {
569
682
  return fail(deployed.error.message);
570
683
  }
684
+ if (plan.kind === 'update') {
685
+ reportRemoved(flags.name, existing, plan.patch);
686
+ }
571
687
  const verb = plan.kind === 'create' ? 'Created' : plan.kind === 'update' ? 'Changed' : 'Deployed';
572
688
  console.log(`${verb} ${flags.name}: ${deployed.value.image} at ${deployed.value.imageDigest}`);
573
689
  if (flags['no-wait'] === true) {
574
690
  return;
575
691
  }
692
+ if (preDeployJob !== undefined) {
693
+ console.log(` runs the Job ${preDeployJob.name} first and rolls out once it has succeeded`);
694
+ }
576
695
  const running = await waitUntilRunning(() => client.getService(project.id, deployed.value.id), {
577
- timeoutMs: 5 * 60_000,
696
+ // The pre-deploy run may take as long as its Job's timeout, before the rollout's own five minutes.
697
+ timeoutMs: 5 * 60_000 + (preDeployJob?.timeoutSeconds ?? 0) * 1000,
578
698
  intervalMs: 3_000,
579
699
  report: (state) => console.log(` ${state}`),
580
700
  });
581
- return running.ok ? undefined : fail(`${flags.name} is not running: ${running.error}`);
701
+ if (running.ok) {
702
+ return;
703
+ }
704
+ const log = 'preDeployRun' in running && running.preDeployRun != null && preDeployJob !== undefined ? `; its output: oup job logs ${preDeployJob.name} ${running.preDeployRun}` : '';
705
+ return fail(`${flags.name} is not running: ${running.error}${log}`);
582
706
  }
583
707
  const logQuery = (tail, follow) => ({
584
708
  ...(tail === undefined ? {} : { tail }),
@@ -593,6 +717,35 @@ async function printLogs(opened, options) {
593
717
  console.log(formatLogEntry(entry, options));
594
718
  }
595
719
  }
720
+ /**
721
+ * The Secrets and Variables the flags ask for (environment.ts), with the
722
+ * `--env-file`s read here.
723
+ */
724
+ async function environmentFrom(existing, flags) {
725
+ const files = [];
726
+ for (const path of flags['env-file'] ?? []) {
727
+ const text = await readFile(path, 'utf8').then((content) => ({ ok: true, content }), (error) => ({ ok: false, error }));
728
+ if (!text.ok) {
729
+ return fail(`cannot read ${path}: ${text.error instanceof Error ? text.error.message : String(text.error)}`);
730
+ }
731
+ files.push({ path, text: text.content });
732
+ }
733
+ const desired = desiredEnvironment(existing, flags, files);
734
+ return desired.ok ? desired.value : fail(desired.error);
735
+ }
736
+ /** Says which names a change takes away: stating a whole list drops what is not repeated. */
737
+ function reportRemoved(name, existing, change) {
738
+ const removed = removedNames(existing, change);
739
+ if (removed.secrets.length > 0) {
740
+ console.log(`${name} no longer names the ${removed.secrets.length === 1 ? 'Secret' : 'Secrets'} ${removed.secrets.join(', ')}`);
741
+ }
742
+ if (removed.variables.length > 0) {
743
+ console.log(`${name} loses the ${removed.variables.length === 1 ? 'Variable' : 'Variables'} ${removed.variables.join(', ')}`);
744
+ }
745
+ if (removed.databases.length > 0) {
746
+ console.log(`${name} no longer reaches the ${removed.databases.length === 1 ? 'Database' : 'Databases'} ${removed.databases.join(', ')}`);
747
+ }
748
+ }
596
749
  /** Registry credentials from `--registry-user` and the password on stdin; undefined without them. */
597
750
  async function registryAuthFrom(flags) {
598
751
  const username = flags['registry-user'];
@@ -623,7 +776,7 @@ async function job(args) {
623
776
  cpu: { type: 'string' },
624
777
  site: { type: 'string' },
625
778
  'no-command': { type: 'boolean' },
626
- env: { type: 'string', multiple: true },
779
+ ...ENVIRONMENT_OPTIONS,
627
780
  'registry-user': { type: 'string' },
628
781
  'registry-password-stdin': { type: 'boolean' },
629
782
  'no-wait': { type: 'boolean' },
@@ -711,12 +864,13 @@ async function jobDeploy(client, project, existing, flags) {
711
864
  return fail('--schedule and --no-schedule exclude each other');
712
865
  }
713
866
  if (flags.site !== undefined && !isSite(flags.site)) {
714
- return fail(`--site is one of ${COMPUTE_SITES.join(', ')}`);
867
+ return fail('--site takes a Site id, as oup sites lists them');
715
868
  }
716
869
  if (flags.command !== undefined && flags.command.length === 0) {
717
870
  return fail('nothing after --; leave it out to keep the command');
718
871
  }
719
872
  const registryAuth = await registryAuthFrom(flags);
873
+ const environment = await environmentFrom(existing, flags);
720
874
  const timeoutSeconds = count('timeout', flags.timeout);
721
875
  const memoryMb = count('memory', flags.memory);
722
876
  const cpuMillicores = count('cpu', flags.cpu);
@@ -732,6 +886,7 @@ async function jobDeploy(client, project, existing, flags) {
732
886
  ...(flags['time-zone'] === undefined ? {} : { timeZone: flags['time-zone'] }),
733
887
  ...(flags.site === undefined || !isSite(flags.site) ? {} : { homeSite: flags.site }),
734
888
  ...(registryAuth === undefined ? {} : { registryAuth }),
889
+ environment,
735
890
  };
736
891
  const plan = planJobDeploy(existing, desired);
737
892
  const deployed = plan.kind === 'create'
@@ -742,6 +897,9 @@ async function jobDeploy(client, project, existing, flags) {
742
897
  if (!deployed.ok) {
743
898
  return fail(deployed.error.message);
744
899
  }
900
+ if (plan.kind === 'update') {
901
+ reportRemoved(flags.name, existing, plan.patch);
902
+ }
745
903
  const verb = plan.kind === 'create' ? 'Created' : plan.kind === 'update' ? 'Changed' : 'Deployed';
746
904
  const when = deployed.value.schedule === null ? 'on demand' : `on ${deployed.value.schedule} (${deployed.value.timeZone ?? 'UTC'})`;
747
905
  console.log(`${verb} ${flags.name}, ${when}: ${deployed.value.image} at ${deployed.value.imageDigest}`);
@@ -784,6 +942,99 @@ async function jobRun(client, project, target, options) {
784
942
  const outcome = outcomeOf(finished.value);
785
943
  return finished.value.state === 'succeeded' ? console.log(outcome) : fail(`${started.value.id} ${outcome}`);
786
944
  }
945
+ /** `oup key`: a Project's Keys (decision 167). No verb shows or takes key material: it never leaves the platform. */
946
+ async function key(args) {
947
+ const [verb, ...rest] = args;
948
+ const { values, positionals } = parseArgs({
949
+ args: rest,
950
+ allowPositionals: true,
951
+ options: { project: { type: 'string' }, service: { type: 'string' }, job: { type: 'string' }, access: { type: 'string' }, limit: { type: 'string' }, json: { type: 'boolean' } },
952
+ });
953
+ const [name] = positionals;
954
+ if (verb === undefined || (verb !== 'list' && name === undefined)) {
955
+ return fail(USAGE);
956
+ }
957
+ const { client, project } = await inProject(values.project);
958
+ /** The Service or Job a grant is for, by its name in the Project. */
959
+ const holder = async () => {
960
+ const wanted = grantHolder(values.service, values.job);
961
+ if (!wanted.ok) {
962
+ return fail(wanted.error);
963
+ }
964
+ const listed = wanted.value.holder === 'service' ? await client.listServices(project.id) : await client.listJobs(project.id);
965
+ if (!listed.ok) {
966
+ return fail(listed.error.message);
967
+ }
968
+ const what = `the ${wanted.value.holder === 'service' ? 'Service' : 'Job'} ${wanted.value.name}`;
969
+ const found = listed.value.find((candidate) => candidate.name === wanted.value.name);
970
+ return found === undefined ? fail(`no ${what.slice(4)} in ${project.name}`) : { id: found.id, what };
971
+ };
972
+ const list = async () => {
973
+ const keys = await client.listKeys(project.id);
974
+ return keys.ok ? keys.value : fail(keys.error.message);
975
+ };
976
+ /** The Key `name` of the Project, for the verbs that act on one. */
977
+ const named = async () => (await list()).find((candidate) => candidate.name === name) ?? fail(`no Key ${name} in ${project.name}`);
978
+ switch (verb) {
979
+ case 'list': {
980
+ const keys = await list();
981
+ return console.log(keys.length === 0 ? `No Keys in ${project.name}.` : formatKeys(keys).join('\n'));
982
+ }
983
+ case 'create': {
984
+ const created = await client.createKey(project.id, { name: name });
985
+ return created.ok ? console.log(`Created the Key ${created.value.name} in ${project.name}.`) : fail(created.error.message);
986
+ }
987
+ case 'show':
988
+ return console.log(formatKey(await named()).join('\n'));
989
+ case 'rotate': {
990
+ const rotated = await client.rotateKey(project.id, (await named()).id);
991
+ return rotated.ok
992
+ ? console.log(`${rotated.value.name} is at version ${rotated.value.version}; what older versions encrypted still decrypts.`)
993
+ : fail(rotated.error.message);
994
+ }
995
+ case 'delete': {
996
+ const deleted = await client.deleteKey(project.id, (await named()).id);
997
+ return deleted.ok ? console.log(deletionNotice(deleted.value, project.name)) : fail(deleted.error.message);
998
+ }
999
+ case 'restore': {
1000
+ const restored = await client.restoreKey(project.id, (await named()).id);
1001
+ return restored.ok ? console.log(`Restored ${restored.value.name} in ${project.name}; it is active again.`) : fail(restored.error.message);
1002
+ }
1003
+ case 'grant': {
1004
+ const access = parseKeyAccess(values.access);
1005
+ if (!access.ok) {
1006
+ return fail(access.error);
1007
+ }
1008
+ const { id, what } = await holder();
1009
+ const granted = await client.putKeyGrant(project.id, (await named()).id, id, { access: access.value });
1010
+ return granted.ok
1011
+ ? console.log(`${what[0]?.toUpperCase()}${what.slice(1)} may ${access.value === 'both' ? 'encrypt and decrypt' : access.value} with ${name}.` +
1012
+ (values.service === undefined ? '' : ' Its first grant on any Key restarts the Service once, to give its pods their token.'))
1013
+ : fail(granted.error.message);
1014
+ }
1015
+ case 'log': {
1016
+ const limit = parseCallLimit(values.limit);
1017
+ if (!limit.ok) {
1018
+ return fail(limit.error);
1019
+ }
1020
+ const calls = await client.listKeyCalls(project.id, (await named()).id, { limit: limit.value });
1021
+ if (!calls.ok) {
1022
+ return fail(calls.error.message);
1023
+ }
1024
+ if (values.json === true) {
1025
+ return console.log(JSON.stringify(calls.value, null, 2));
1026
+ }
1027
+ return console.log(calls.value.length === 0 ? `No calls of ${name} in the last 30 days.` : formatKeyCalls(calls.value).join('\n'));
1028
+ }
1029
+ case 'revoke': {
1030
+ const { id, what } = await holder();
1031
+ const revoked = await client.deleteKeyGrant(project.id, (await named()).id, id);
1032
+ return revoked.ok ? console.log(`Took the grant on ${name} from ${what}; its next call is refused.`) : fail(revoked.error.message);
1033
+ }
1034
+ default:
1035
+ return fail(USAGE);
1036
+ }
1037
+ }
787
1038
  async function secret(args) {
788
1039
  const [verb, ...rest] = args;
789
1040
  const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { project: { type: 'string' } } });
@@ -798,7 +1049,7 @@ async function secret(args) {
798
1049
  if (!secrets.ok) {
799
1050
  return fail(secrets.error.message);
800
1051
  }
801
- console.log(secrets.value.length === 0 ? `No Secrets in ${project.name}.` : secrets.value.map((s) => `${s.name.padEnd(32)} ${s.updatedAt}`).join('\n'));
1052
+ console.log(secrets.value.length === 0 ? `No Secrets in ${project.name}.` : formatSecrets(secrets.value).join('\n'));
802
1053
  return;
803
1054
  }
804
1055
  case 'set': {
@@ -811,7 +1062,7 @@ async function secret(args) {
811
1062
  return fail(`no value for ${name} on stdin; pipe it in, e.g. printf %s "$VALUE" | oup secret set ${name}`);
812
1063
  }
813
1064
  const stored = await client.putSecret(project.id, { name: name, value });
814
- return stored.ok ? console.log(`Set ${name} in ${project.name}; its Services restart with it.`) : fail(stored.error.message);
1065
+ return stored.ok ? console.log(secretSetMessage(stored.value, project.name)) : fail(stored.error.message);
815
1066
  }
816
1067
  case 'delete': {
817
1068
  const deleted = await client.deleteSecret(project.id, name);
@@ -1011,6 +1262,231 @@ async function route(args) {
1011
1262
  return deleted.ok ? console.log(`Deleted the Route ${where}; what it went to stays.`) : fail(deleted.error.message);
1012
1263
  }
1013
1264
  /** `oup usage`: what the linked Project's Resources use now of what they were given (decision 124); not what is billed. */
1265
+ /** `oup member`: the Account's Members, their roles and grants, removing one, leaving. */
1266
+ async function member(args) {
1267
+ const [verb, ...rest] = args;
1268
+ const { values, positionals } = parseArgs({
1269
+ args: rest,
1270
+ allowPositionals: true,
1271
+ options: { account: { type: 'string' }, database: { type: 'string' }, project: { type: 'string' } },
1272
+ });
1273
+ const [email, word, ...extra] = positionals;
1274
+ const arity = { list: 0, leave: 0, remove: 1, role: 2, grant: 2, revoke: 1 }[verb ?? ''];
1275
+ if (arity === undefined || positionals.length !== arity || extra.length > 0) {
1276
+ return fail(USAGE);
1277
+ }
1278
+ const onDatabase = verb === 'grant' || verb === 'revoke';
1279
+ if (onDatabase && values.database === undefined) {
1280
+ return fail(`oup member ${verb} needs --database <name>`);
1281
+ }
1282
+ if (onDatabase ? values.account !== undefined : values.database !== undefined || values.project !== undefined) {
1283
+ return fail(onDatabase ? `oup member ${verb} acts in the Database's Account; it takes no --account` : `oup member ${verb} takes no --database or --project`);
1284
+ }
1285
+ if (onDatabase) {
1286
+ return memberGrant(verb, email ?? '', word, values.database ?? '', values.project);
1287
+ }
1288
+ const client = await apiClient();
1289
+ const account = accountFor(await listAccounts(client), values.account);
1290
+ if (!account.ok) {
1291
+ return fail(account.error);
1292
+ }
1293
+ const refusal = (error) => fail(error.status === 409 ? `${error.message}\n ${LAST_OWNER_HINT}` : error.message);
1294
+ if (verb === 'leave') {
1295
+ const left = await client.removeMember(account.value.id, 'me');
1296
+ return left.ok ? console.log(`You left the Account ${account.value.name}.`) : refusal(left.error);
1297
+ }
1298
+ const members = await client.listMembers(account.value.id);
1299
+ if (!members.ok) {
1300
+ return fail(members.error.message);
1301
+ }
1302
+ if (verb === 'list') {
1303
+ return console.log(formatMembers(members.value).join('\n'));
1304
+ }
1305
+ const target = memberByEmail(members.value, email ?? '');
1306
+ if (!target.ok) {
1307
+ return fail(target.error);
1308
+ }
1309
+ if (verb === 'remove') {
1310
+ const removed = await client.removeMember(account.value.id, target.value.id);
1311
+ return removed.ok
1312
+ ? console.log(`Removed ${target.value.email} from ${account.value.name}; their Postgres roles in its Databases are dropped.`)
1313
+ : refusal(removed.error);
1314
+ }
1315
+ const parsed = parseRole(word);
1316
+ if (!parsed.ok) {
1317
+ return fail(parsed.error);
1318
+ }
1319
+ const changed = await client.updateMember(account.value.id, target.value.id, { role: parsed.value });
1320
+ if (!changed.ok) {
1321
+ return refusal(changed.error);
1322
+ }
1323
+ return console.log(changed.value.role === null
1324
+ ? `${changed.value.email} now has no role in ${account.value.name}, only their grants; their Postgres roles beyond those are dropped.`
1325
+ : `${changed.value.email} is now ${changed.value.role} of ${account.value.name}.`);
1326
+ }
1327
+ /** `oup token`: the Account's tokens (decision 144); create and roll print the secret alone on stdout. */
1328
+ async function token(args) {
1329
+ const [verb, ...rest] = args;
1330
+ const { values, positionals } = parseArgs({
1331
+ args: rest,
1332
+ allowPositionals: true,
1333
+ options: {
1334
+ account: { type: 'string' },
1335
+ database: { type: 'string' },
1336
+ project: { type: 'string' },
1337
+ expires: { type: 'string' },
1338
+ developer: { type: 'boolean' },
1339
+ },
1340
+ });
1341
+ const [name, word, ...extra] = positionals;
1342
+ const arity = { list: 0, create: 1, role: 2, grant: 2, revoke: 1, roll: 1, delete: 1 }[verb ?? ''];
1343
+ if (arity === undefined || positionals.length !== arity || extra.length > 0) {
1344
+ return fail(USAGE);
1345
+ }
1346
+ const onDatabase = verb === 'grant' || verb === 'revoke';
1347
+ if (onDatabase && values.database === undefined) {
1348
+ return fail(`oup token ${verb} needs --database <name>${verb === 'revoke' ? `; oup token delete ${name ?? '<name>'} revokes the token itself` : ''}`);
1349
+ }
1350
+ if (onDatabase ? values.account !== undefined : values.database !== undefined || values.project !== undefined) {
1351
+ return fail(onDatabase ? `oup token ${verb} acts in the Database's Account; it takes no --account` : `oup token ${verb} takes no --database or --project`);
1352
+ }
1353
+ if (values.expires !== undefined && verb !== 'create' && verb !== 'roll') {
1354
+ return fail(`oup token ${verb} takes no --expires`);
1355
+ }
1356
+ if (values.developer !== undefined && verb !== 'create') {
1357
+ return fail(`oup token ${verb} takes no --developer; oup token role <name> developer gives it the role`);
1358
+ }
1359
+ const now = new Date();
1360
+ const expiry = verb === 'create' || verb === 'roll' ? parseExpiry(values.expires, now) : undefined;
1361
+ if (expiry !== undefined && !expiry.ok) {
1362
+ return fail(expiry.error);
1363
+ }
1364
+ const role = verb === 'role' ? parseTokenRole(word) : undefined;
1365
+ if (role !== undefined && !role.ok) {
1366
+ return fail(role.error);
1367
+ }
1368
+ const access = verb === 'grant' ? parseGrantAccess(word) : undefined;
1369
+ if (access !== undefined && !access.ok) {
1370
+ return fail(access.error);
1371
+ }
1372
+ if (onDatabase) {
1373
+ return tokenGrant(name ?? '', access?.value, values.database ?? '', values.project);
1374
+ }
1375
+ const client = await apiClient();
1376
+ const account = accountFor(await listAccounts(client), values.account);
1377
+ if (!account.ok) {
1378
+ return fail(account.error);
1379
+ }
1380
+ if (verb === 'create') {
1381
+ const input = { name: name ?? '', role: values.developer === true ? 'developer' : null, expiresAt: expiry?.ok === true ? expiry.value.toISOString() : '' };
1382
+ const created = await client.createAccountToken(account.value.id, input);
1383
+ if (!created.ok) {
1384
+ return fail(created.error.message);
1385
+ }
1386
+ const rights = created.value.role === null ? `no rights yet: oup token grant ${created.value.name} read --database <name> gives some` : 'the developer role';
1387
+ console.error(`Created the Account token ${created.value.name} in ${account.value.name}, with ${rights}, until ${created.value.expiresAt.slice(0, 10)}.`);
1388
+ console.error('Its secret follows, shown only now; use it as OUP_API_KEY:');
1389
+ return console.log(created.value.secret);
1390
+ }
1391
+ const tokens = await client.listAccountTokens(account.value.id);
1392
+ if (!tokens.ok) {
1393
+ return fail(tokens.error.message);
1394
+ }
1395
+ if (verb === 'list') {
1396
+ const lines = formatTokens(tokens.value, now);
1397
+ return console.log(lines.length === 0 ? 'No Account tokens; oup token create <name> --expires 90d makes one.' : lines.join('\n'));
1398
+ }
1399
+ const target = tokenByName(tokens.value, name ?? '');
1400
+ if (!target.ok) {
1401
+ return fail(target.error);
1402
+ }
1403
+ if (verb === 'delete') {
1404
+ const deleted = await client.deleteAccountToken(account.value.id, target.value.id);
1405
+ return deleted.ok
1406
+ ? console.log(`Revoked the Account token ${target.value.name}; it stops working now, and its Postgres roles are dropped.`)
1407
+ : fail(deleted.error.message);
1408
+ }
1409
+ if (verb === 'roll') {
1410
+ const rolled = await client.rollAccountToken(account.value.id, target.value.id, { expiresAt: expiry?.ok === true ? expiry.value.toISOString() : '' });
1411
+ if (!rolled.ok) {
1412
+ return fail(rolled.error.message);
1413
+ }
1414
+ const previous = rolled.value.previousSecretValidUntil;
1415
+ console.error(`Rolled the Account token ${rolled.value.name}, now valid until ${rolled.value.expiresAt.slice(0, 10)}.`);
1416
+ console.error(previous === undefined ? 'The previous secret had expired.' : `The previous secret works until ${previous}.`);
1417
+ console.error('The new secret follows, shown only now:');
1418
+ return console.log(rolled.value.secret);
1419
+ }
1420
+ const changed = await client.updateAccountToken(account.value.id, target.value.id, { role: role?.ok === true ? role.value : null });
1421
+ if (!changed.ok) {
1422
+ return fail(changed.error.message);
1423
+ }
1424
+ return console.log(changed.value.role === null
1425
+ ? `The Account token ${changed.value.name} now has no role, only its grants; its Postgres roles beyond those are dropped.`
1426
+ : `The Account token ${changed.value.name} now has the role ${changed.value.role}.`);
1427
+ }
1428
+ /** `oup token grant` and `revoke`: a token's access to one Database of the linked Project (decision 139). */
1429
+ async function tokenGrant(name, access, databaseName, projectFlag) {
1430
+ const { client, project } = await inProject(projectFlag);
1431
+ const databases = await client.listDatabases(project.id);
1432
+ if (!databases.ok) {
1433
+ return fail(databases.error.message);
1434
+ }
1435
+ const database = databases.value.find((candidate) => candidate.name === databaseName) ?? fail(`no Database ${databaseName} in ${project.name}`);
1436
+ const tokens = await client.listAccountTokens(project.accountId);
1437
+ if (!tokens.ok) {
1438
+ return fail(tokens.error.message);
1439
+ }
1440
+ const target = tokenByName(tokens.value, name);
1441
+ if (!target.ok) {
1442
+ return fail(target.error);
1443
+ }
1444
+ const where = `${project.name}/${database.name}`;
1445
+ if (access === undefined) {
1446
+ const removed = await client.removeAccountTokenGrant(project.accountId, target.value.id, database.id);
1447
+ return removed.ok
1448
+ ? console.log(`The Account token ${name} has no grant on ${where} any more.${target.value.role === null ? ' Its Postgres roles there are dropped.' : ''}`)
1449
+ : fail(removed.error.status === 404 ? `the Account token ${name} has no grant on ${where}` : removed.error.message);
1450
+ }
1451
+ const granted = await client.setAccountTokenGrant(project.accountId, target.value.id, database.id, { access });
1452
+ const note = target.value.role === null ? '' : ` It counts only once the token has no role (it is ${target.value.role}).`;
1453
+ return granted.ok
1454
+ ? 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}`)
1455
+ : fail(granted.error.message);
1456
+ }
1457
+ /** `oup member grant` and `revoke`: a Member's access to one Database of the linked Project (decision 139). */
1458
+ async function memberGrant(verb, email, level, name, projectFlag) {
1459
+ const access = verb === 'grant' ? parseGrantAccess(level) : undefined;
1460
+ if (access !== undefined && !access.ok) {
1461
+ return fail(access.error);
1462
+ }
1463
+ const { client, project } = await inProject(projectFlag);
1464
+ const databases = await client.listDatabases(project.id);
1465
+ if (!databases.ok) {
1466
+ return fail(databases.error.message);
1467
+ }
1468
+ const database = databases.value.find((candidate) => candidate.name === name) ?? fail(`no Database ${name} in ${project.name}`);
1469
+ const members = await client.listMembers(project.accountId);
1470
+ if (!members.ok) {
1471
+ return fail(members.error.message);
1472
+ }
1473
+ const target = memberByEmail(members.value, email);
1474
+ if (!target.ok) {
1475
+ return fail(target.error);
1476
+ }
1477
+ const where = `${project.name}/${database.name}`;
1478
+ const note = target.value.role === null ? '' : ` It counts only once they have no role (they are ${target.value.role}).`;
1479
+ if (access === undefined) {
1480
+ const removed = await client.removeGrant(project.accountId, target.value.id, database.id);
1481
+ return removed.ok
1482
+ ? console.log(`${target.value.email} has no grant on ${where} any more.${target.value.role === null ? ' Their Postgres roles there are dropped.' : ''}`)
1483
+ : fail(removed.error.status === 404 ? `${target.value.email} has no grant on ${where}` : removed.error.message);
1484
+ }
1485
+ const granted = await client.setGrant(project.accountId, target.value.id, database.id, { access: access.value });
1486
+ return granted.ok
1487
+ ? console.log(`${target.value.email} may use ${where} at ${granted.value.access}: oup pg proxy ${database.name} --access ${granted.value.access} or lower.${note}`)
1488
+ : fail(granted.error.message);
1489
+ }
1014
1490
  async function usage(args) {
1015
1491
  const { values, positionals } = parseArgs({
1016
1492
  args,
@@ -1027,6 +1503,16 @@ async function usage(args) {
1027
1503
  }
1028
1504
  console.log(values.json === true ? JSON.stringify(read.value, null, 2) : formatUsage(read.value, project.name, { instances: values.instances ?? false }).join('\n'));
1029
1505
  }
1506
+ async function sites(args) {
1507
+ if (args.length > 0) {
1508
+ return fail(USAGE);
1509
+ }
1510
+ const read = await (await apiClient()).listSites();
1511
+ if (!read.ok) {
1512
+ return fail(read.error.message);
1513
+ }
1514
+ console.log(formatSites(read.value).join('\n'));
1515
+ }
1030
1516
  async function siteDeploy(args) {
1031
1517
  const { values, positionals } = parseArgs({
1032
1518
  args,
@@ -1078,6 +1564,10 @@ const run = async () => {
1078
1564
  return project(rest);
1079
1565
  case 'link':
1080
1566
  return link(rest);
1567
+ case 'token':
1568
+ return token(rest);
1569
+ case 'member':
1570
+ return member(rest);
1081
1571
  case 'pg':
1082
1572
  return pg(rest);
1083
1573
  case 'service':
@@ -1086,6 +1576,8 @@ const run = async () => {
1086
1576
  return job(rest);
1087
1577
  case 'secret':
1088
1578
  return secret(rest);
1579
+ case 'key':
1580
+ return key(rest);
1089
1581
  case 'bucket':
1090
1582
  return bucket(rest);
1091
1583
  case 'domain':
@@ -1094,6 +1586,8 @@ const run = async () => {
1094
1586
  return route(rest);
1095
1587
  case 'usage':
1096
1588
  return usage(rest);
1589
+ case 'sites':
1590
+ return sites(rest);
1097
1591
  case 'site':
1098
1592
  return rest[0] === 'deploy' ? siteDeploy(rest.slice(1)) : fail(USAGE);
1099
1593
  case 'version':