@gheima/cli 0.8.0 → 0.9.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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @gheima/cli
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 83f3918: `gheima login --no-wait` starts a browser sign-in, prints the code and the URL (as one JSON document with `--json`) and exits, so a script or a coding agent can hand the link to a person without keeping a blocking command alive. `gheima login --resume` then waits for the approval and saves the key; with `--timeout <seconds>` it exits 7 (`login_pending`) while the sign-in is still waiting, and can be run again. A missing credential now reports the error code `unauthenticated` under `--json` instead of the generic `error`.
8
+ - 65610dc: `gheima deploy` in a folder with no service yet does the whole job: it creates the service (from the git remote when there is one, on the current branch, with any credential in the remote URL removed), links the folder, deploys, waits and prints the live URL. With no git remote it uploads the folder instead (git's own file list inside a work tree; `.env` files, `node_modules` and `.gheima/` are always left out). `--yes` confirms the creation without a terminal, `--name` names the service, and `--upload` uploads even when there is a remote. Under `--json` the result now carries `url`, `serviceId`, `created` and `source`.
9
+ - 8609489: `github.installation` (`GET /github/installation?repoUrl=…`, `gheima github installation`) says whether the Gheima GitHub App is installed on a repository's owner, by the same rule a build uses, and returns the one link a person opens to install it (it signs them in first). `gheima github wait` prints that link and returns once the app is installed (exit 7 on `--timeout`).
10
+
11
+ ### Patch Changes
12
+
13
+ - 35cce08: `services.createUpload` (`POST /services/{id}/upload-url`; MCP `gheima_services_create_upload`; CLI `gheima services upload-url <id>`) mints a single-use, 15-minute upload URL for one service and returns a ready `tar … | curl` command. Running it in a project folder deploys the folder exactly like `deploySource`, so an MCP client can deploy local files with no Git repository. The credential is sent in the `authorization` header, never in the URL.
14
+ - Updated dependencies [8609489]
15
+ - Updated dependencies [31c349f]
16
+ - Updated dependencies [35cce08]
17
+ - Updated dependencies [40afd02]
18
+ - @gheima/contracts@0.3.0
19
+ - @gheima/sdk@0.6.0
20
+
3
21
  ## 0.8.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -28,6 +28,8 @@ dashboard, and waits while you approve it — nothing is pasted.
28
28
  gheima login # browser sign-in; the key is stored in ~/.config/gheima/config.json (0600)
29
29
  gheima login --no-browser # print the URL instead of opening one (SSH, CI, headless)
30
30
  gheima login --with-key # paste an existing API key instead
31
+ gheima login --no-wait --json # print the code + URL and exit (scripts, coding agents)
32
+ gheima login --resume # then wait for that sign-in to be approved
31
33
  gheima login --profile work # named profile
32
34
  gheima whoami
33
35
  gheima logout
@@ -82,7 +84,7 @@ This bites anyone who set a custom npm prefix to avoid `sudo` without also exten
82
84
  | `gheima services create --name <name> [--type WEB\|WORKER\|STATIC] [--repo <url>] [--project <id>]` | Create a service. Names are unique per **account**; omitting `--project` leaves the service ungrouped |
83
85
  | `gheima services delete <service> [-y]` | Delete a service |
84
86
  | `gheima link <service>` | Link the current directory to a service: commands run anywhere inside it then default to that service. Writes `.gheima/project.json` and adds `.gheima/` to `.gitignore` |
85
- | `gheima deploy [service] [--no-wait] [--timeout <min>]` | Deploy, stream the build, and exit 0 once it is live, or 8 if it fails. `--no-wait` only queues it |
87
+ | `gheima deploy [service] [--yes] [--upload] [--name <n>] [--no-wait] [--timeout <min>]` | Deploy this folder, stream the build, print the live URL; exit 0 once live, 8 if it fails. The first time in a folder it creates and links a service: from the git remote, or by uploading the files when there is none (`.env` files and `node_modules` left out). `--yes` confirms that without a terminal |
86
88
  | `gheima logs [service] [-f] [-b] [-s <text>]` | Show or tail runtime (`-b` → build) logs |
87
89
  | `gheima run <service> [--timeout <s>] [--no-wait] -- <cmd>` | Run a one-off command (a migration, a seed) in a fresh container from the service's live image and environment, print its log, and exit with its exit code. The words after `--` are joined and run by the remote `/bin/sh -c`, so quote the whole command when an argument holds spaces: `gheima run web -- 'psql -c "select 1"'`. Admins only; 10 runs an hour per service |
88
90
  | `gheima templates [list]` | List marketplace templates |
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ import { basename } from 'node:path';
7
7
  import { Command } from 'commander';
8
8
  import { GheimaError, GheimaClient, DEFAULT_API_URL } from '@gheima/sdk';
9
9
  import { makeClient, transportOptions, VERSION } from './client.js';
10
- import { EXIT, UsageError, exitCodeFor } from './exit.js';
10
+ import { EXIT, NotAuthenticatedError, UsageError, exitCodeFor } from './exit.js';
11
11
  import { useProxyFromEnv } from './proxy.js';
12
12
  import { REFRESH_ARG, refreshUpdateCache, shouldCheck, updateNotice } from './update-check.js';
13
13
  import { resolveAuth, setProfile, removeProfile, loadConfig } from './config.js';
@@ -16,8 +16,10 @@ import { table, printJson, printJsonLine, spinner, success, info, color, isInter
16
16
  import { completionScript } from './completion.js';
17
17
  import { callOp, registerGenerated } from './generated.js';
18
18
  import { findLink, toDotenv, writeLink } from './link.js';
19
+ import { listSourceFiles, packSource } from './pack.js';
20
+ import { defaultServiceName, gitRemote, gitSubdir } from './git-remote.js';
19
21
  import { AGENTS_FILE, agentsSection, upsertAgentsMd } from './agents-md.js';
20
- import { defaultClientName, openBrowser, pollForApproval, startDeviceLogin, } from './device-login.js';
22
+ import { clearPendingLogin, defaultClientName, loadPendingLogin, LoginStillPending, openBrowser, pollForApproval, savePendingLogin, startDeviceLogin, } from './device-login.js';
21
23
  const program = new Command();
22
24
  program
23
25
  .name('gheima')
@@ -75,6 +77,16 @@ async function readStdin() {
75
77
  chunks.push(chunk);
76
78
  return Buffer.concat(chunks).toString('utf8');
77
79
  }
80
+ /** The `code` a failure the CLI raised itself carries under --json: stable, like the API's. */
81
+ function localErrorCode(err) {
82
+ if (err instanceof UsageError)
83
+ return 'usage';
84
+ if (err instanceof NotAuthenticatedError)
85
+ return 'unauthenticated';
86
+ if (err instanceof LoginStillPending)
87
+ return 'login_pending';
88
+ return 'error';
89
+ }
78
90
  /**
79
91
  * Report a failure and exit with its code (see exit.ts). The API's code and request id are
80
92
  * always shown, because the request id is what support needs to find the request.
@@ -85,7 +97,7 @@ function fail(err) {
85
97
  if (isJsonMode()) {
86
98
  process.stderr.write(JSON.stringify({
87
99
  error: {
88
- code: api?.code ?? (err instanceof UsageError ? 'usage' : 'error'),
100
+ code: api?.code ?? localErrorCode(err),
89
101
  message,
90
102
  ...(api ? { status: api.status, requestId: api.requestId ?? null } : {}),
91
103
  },
@@ -110,16 +122,31 @@ program
110
122
  .description('Sign in through the browser, or with an existing API key')
111
123
  .option('--no-browser', 'print the URL instead of opening a browser')
112
124
  .option('--with-key', 'paste an existing API key instead of using the browser')
125
+ .option('--no-wait', 'print the sign-in code and URL and exit; finish with `gheima login --resume` (for agents and scripts)')
126
+ .option('--resume', 'wait for the sign-in started with `--no-wait` to be approved')
127
+ .option('--timeout <seconds>', 'with --resume: stop waiting after this long (exit 7, still pending)')
113
128
  .action(async (opts, cmd) => {
114
129
  const g = globals(cmd);
115
130
  const profileName = g.profile || 'default';
116
131
  const baseUrl = g.url || process.env.GHEIMA_URL || DEFAULT_API_URL;
132
+ if (opts.resume) {
133
+ try {
134
+ await resumeLogin(opts.timeout);
135
+ }
136
+ catch (err) {
137
+ fail(err);
138
+ }
139
+ return;
140
+ }
117
141
  // `--key` on the program means the caller already has a credential and is not asking to
118
142
  // be sent through a browser at all.
119
143
  const pasteInstead = opts.withKey || Boolean(g.key);
120
144
  if (!pasteInstead) {
121
145
  try {
122
- await browserLogin(baseUrl, profileName, opts.browser !== false, g.url);
146
+ if (!opts.wait)
147
+ await startLoginOnly(baseUrl, profileName, g.url);
148
+ else
149
+ await browserLogin(baseUrl, profileName, opts.browser !== false, g.url);
123
150
  return;
124
151
  }
125
152
  catch (err) {
@@ -146,6 +173,74 @@ program
146
173
  fail(err);
147
174
  }
148
175
  });
176
+ /**
177
+ * `gheima login --no-wait`: start the device flow, keep it for `--resume`, and say what the
178
+ * person has to do. Under --json that is the whole result, so an agent can relay it verbatim.
179
+ */
180
+ async function startLoginOnly(baseUrl, profileName, urlOverride) {
181
+ const started = await startDeviceLogin(baseUrl, defaultClientName());
182
+ const expiresAt = Date.now() + started.expires_in * 1000;
183
+ savePendingLogin({ start: started, expiresAt, baseUrl, profileName, urlOverride });
184
+ const result = {
185
+ status: 'pending',
186
+ userCode: started.user_code,
187
+ verificationUrl: started.verification_uri_complete,
188
+ expiresAt: new Date(expiresAt).toISOString(),
189
+ instructions: `Open ${started.verification_uri_complete} and approve the code ${started.user_code}. ` +
190
+ 'Sign in or create an account there first if needed.',
191
+ next: 'gheima login --resume',
192
+ };
193
+ if (isJsonMode())
194
+ return printJson(result);
195
+ info(`Your code is ${color.bold(started.user_code)}`);
196
+ info(`Open ${color.bold(started.verification_uri_complete)} and approve it.`);
197
+ info('Then run `gheima login --resume` to finish signing in.');
198
+ }
199
+ /** `gheima login --resume`: finish the pending sign-in, or say it is still pending. */
200
+ async function resumeLogin(timeout) {
201
+ const seconds = timeout === undefined ? undefined : Number(timeout);
202
+ if (seconds !== undefined && !(seconds > 0)) {
203
+ throw new UsageError(`--timeout must be a positive number of seconds, not ${timeout}.`);
204
+ }
205
+ const pending = loadPendingLogin();
206
+ if (!pending) {
207
+ throw new UsageError('No sign-in is waiting (none was started, or it expired). Run `gheima login --no-wait` first.');
208
+ }
209
+ const spin = spinner('Waiting for approval…');
210
+ let result;
211
+ try {
212
+ result = await pollForApproval(pending.baseUrl, pending.start, {
213
+ expiresAt: pending.expiresAt,
214
+ restartCommand: 'gheima login --no-wait',
215
+ giveUpAt: seconds === undefined ? undefined : Date.now() + seconds * 1000,
216
+ });
217
+ }
218
+ catch (err) {
219
+ // Kept on every failure: a dropped connection must not lose a sign-in the person may be
220
+ // approving right now, and a dead code is dropped by loadPendingLogin once it expires.
221
+ spin.stop();
222
+ throw err;
223
+ }
224
+ spin.stop();
225
+ clearPendingLogin();
226
+ await finishLogin(result.apiKey, result.keyName, pending.profileName, pending.urlOverride);
227
+ }
228
+ /** Save the key a device login minted, and say who it signed in as. */
229
+ async function finishLogin(apiKey, keyName, profileName, urlOverride) {
230
+ setProfile(profileName, { apiKey, url: urlOverride });
231
+ const client = new GheimaClient(transportOptions({ apiKey, url: urlOverride }));
232
+ const account = await client.account.get();
233
+ if (isJsonMode()) {
234
+ return printJson({
235
+ status: 'signed_in',
236
+ account: { id: account.id, name: account.name, slug: account.slug },
237
+ profile: profileName,
238
+ keyName,
239
+ });
240
+ }
241
+ success(`Signed in as ${color.bold(account.name)} (${account.slug}), saved as profile "${profileName}"`);
242
+ info(`Key "${keyName}" created. Revoke it any time in Settings > API keys.`);
243
+ }
149
244
  /**
150
245
  * Browser half of `gheima login`.
151
246
  *
@@ -161,21 +256,18 @@ async function browserLogin(baseUrl, profileName, wantBrowser, urlOverride) {
161
256
  info('Could not open a browser. Open the URL above yourself.');
162
257
  }
163
258
  const spin = spinner('Waiting for approval…');
259
+ let result;
164
260
  try {
165
- const result = await pollForApproval(baseUrl, started, {
261
+ result = await pollForApproval(baseUrl, started, {
166
262
  onSlowDown: (seconds) => info(`The server asked for slower polling. Checking every ${seconds}s now.`),
167
263
  });
168
- spin.stop();
169
- setProfile(profileName, { apiKey: result.apiKey, url: urlOverride });
170
- const client = new GheimaClient(transportOptions({ apiKey: result.apiKey, url: urlOverride }));
171
- const account = await client.account.get();
172
- success(`Signed in as ${color.bold(account.name)} (${account.slug}), saved as profile "${profileName}"`);
173
- info(`Key "${result.keyName}" created. Revoke it any time in Settings > API keys.`);
174
264
  }
175
265
  catch (err) {
176
266
  spin.stop();
177
267
  throw err;
178
268
  }
269
+ spin.stop();
270
+ await finishLogin(result.apiKey, result.keyName, profileName, urlOverride);
179
271
  }
180
272
  program
181
273
  .command('logout')
@@ -973,6 +1065,55 @@ program
973
1065
  fail(err);
974
1066
  }
975
1067
  });
1068
+ program
1069
+ .command('github')
1070
+ .description('The Gheima GitHub App on your repositories')
1071
+ .command('wait')
1072
+ .description("Wait until the Gheima GitHub App is installed on this repository's owner (its git remote, or --repo), " +
1073
+ 'printing the install link for a person to open meanwhile')
1074
+ .option('--repo <url>', "the repository (default: this folder's git remote)")
1075
+ .option('--timeout <minutes>', 'stop waiting after this long (exit 7)', '10')
1076
+ .action(async (opts, cmd) => {
1077
+ const g = globals(cmd);
1078
+ try {
1079
+ const repoUrl = opts.repo ?? gitRemote(process.cwd())?.url;
1080
+ if (!repoUrl) {
1081
+ throw new UsageError('This folder has no git remote: pass the repository with --repo <url>.');
1082
+ }
1083
+ const minutes = Number(opts.timeout);
1084
+ if (!(minutes > 0))
1085
+ throw new UsageError(`--timeout must be a positive number of minutes.`);
1086
+ const deadline = Date.now() + minutes * 60_000;
1087
+ let told = false;
1088
+ for (;;) {
1089
+ const r = (await callOp('github.installation', { repoUrl }, g));
1090
+ if (r.installed) {
1091
+ if (g.json)
1092
+ return printJson(r);
1093
+ return success(`The Gheima GitHub App is installed on ${r.owner}.`);
1094
+ }
1095
+ if (!told) {
1096
+ // Prose on stderr even under --json, so an agent can relay it while this waits.
1097
+ info(`Open ${color.bold(r.installUrl)} and install the Gheima GitHub App on ${r.owner}.`);
1098
+ info('Waiting for the install…');
1099
+ told = true;
1100
+ }
1101
+ if (Date.now() >= deadline) {
1102
+ throw new GheimaError({
1103
+ status: 0,
1104
+ code: 'timeout',
1105
+ message: `The app is still not installed on ${r.owner}. Run \`gheima github wait\` again once it is.`,
1106
+ });
1107
+ }
1108
+ await new Promise((res) => setTimeout(res, GITHUB_POLL_MS));
1109
+ }
1110
+ }
1111
+ catch (err) {
1112
+ fail(err);
1113
+ }
1114
+ });
1115
+ /** How often `github wait` asks. Tests shorten it. */
1116
+ const GITHUB_POLL_MS = Number(process.env.GHEIMA_GITHUB_POLL_MS) || 5000;
976
1117
  program
977
1118
  .command('agents')
978
1119
  .description(`Print the Gheima section for ${AGENTS_FILE}, so coding agents know how this project deploys`)
@@ -1003,9 +1144,13 @@ program
1003
1144
  });
1004
1145
  program
1005
1146
  .command('deploy [service]')
1006
- .description('Deploy, stream the build, and exit with the outcome (the linked service by default)')
1147
+ .description('Deploy this folder and print its URL. The first time, it creates a service and links the ' +
1148
+ 'folder: built from the git remote, or uploaded when there is none')
1007
1149
  .option('--no-wait', 'queue the deployment and exit without waiting for it')
1008
1150
  .option('--timeout <minutes>', 'stop waiting after this long (exit 7)', '30')
1151
+ .option('--upload', 'upload this folder instead of building from the git remote')
1152
+ .option('--name <name>', 'name of the service the first deploy creates (default: the folder name)')
1153
+ .option('-y, --yes', 'create the service without asking (needed without a terminal)')
1009
1154
  .action(async (ref, opts, cmd) => {
1010
1155
  const g = globals(cmd);
1011
1156
  try {
@@ -1015,30 +1160,104 @@ program
1015
1160
  if (opts.wait && !(timeout > 0)) {
1016
1161
  throw new UsageError(`--timeout must be a positive number of minutes, not ${opts.timeout}.`);
1017
1162
  }
1018
- const id = await resolveServiceId(client, ref);
1019
- const { deploymentId } = await client.services.deploy(id);
1163
+ const dir = process.cwd();
1164
+ const target = await serviceToDeploy(client, ref, dir, opts);
1165
+ const source = await sourceFor(client, target.id, opts.upload);
1166
+ const { deploymentId } = source === 'upload'
1167
+ ? await uploadAndDeploy(client, target.id, dir)
1168
+ : await client.services.deploy(target.id);
1169
+ const base = { serviceId: target.id, created: target.created, source, deploymentId };
1020
1170
  if (!opts.wait) {
1021
1171
  if (g.json)
1022
- return printJson({ deploymentId, status: 'QUEUED' });
1172
+ return printJson({ ...base, status: 'QUEUED' });
1023
1173
  return success(`Deployment queued: ${color.bold(deploymentId)}`);
1024
1174
  }
1025
1175
  info(`Deployment ${deploymentId} queued. Streaming the build…`);
1026
- const final = await waitForDeployment(client, id, deploymentId, timeout * 60_000);
1176
+ const final = await waitForDeployment(client, target.id, deploymentId, timeout * 60_000);
1177
+ const url = final.status === 'LIVE' ? (await client.services.get(target.id)).url : null;
1027
1178
  if (g.json)
1028
- printJson(final);
1179
+ printJson({ ...base, ...final, url });
1029
1180
  if (final.status === 'LIVE') {
1030
1181
  if (!g.json)
1031
- success(`Live: ${deploymentId}`);
1182
+ success(url ? `Live: ${color.bold(url)}` : `Live: ${deploymentId}`);
1032
1183
  return;
1033
1184
  }
1034
1185
  process.stderr.write(`${color.red('Deployment')} ${deploymentId} ended ${final.status}` +
1035
- `${final.errorMessage ? `: ${final.errorMessage}` : ''}\n`);
1186
+ `${final.errorMessage ? `: ${final.errorMessage}` : ''}\n` +
1187
+ `Read the build log: gheima logs --build${ref ? ` ${ref}` : ''}\n`);
1036
1188
  process.exit(EXIT.deployFailed);
1037
1189
  }
1038
1190
  catch (err) {
1039
1191
  fail(err);
1040
1192
  }
1041
1193
  });
1194
+ /**
1195
+ * The service `deploy` acts on: the one named, else the linked one, else (the first deploy in
1196
+ * this folder) a new one, created from the git remote or for uploads, and linked.
1197
+ */
1198
+ async function serviceToDeploy(client, ref, dir, opts) {
1199
+ if (ref || findLink(dir))
1200
+ return { id: await resolveServiceId(client, ref), created: false };
1201
+ const remote = opts.upload ? null : gitRemote(dir);
1202
+ const name = opts.name ?? defaultServiceName(dir);
1203
+ await confirmDestructive(opts.yes, `create the service "${name}" ${remote ? `from ${remote.url} (${remote.branch})` : 'from the files in this folder'}`);
1204
+ const created = await client.services.create({
1205
+ name,
1206
+ ...(remote ? { repoUrl: remote.url, repoBranch: remote.branch } : {}),
1207
+ });
1208
+ // Run from a subfolder of a repository (a monorepo app): build that folder, not the root. An
1209
+ // upload packs the whole repository too (pack.ts), so the same holds without a remote.
1210
+ const subdir = remote?.subdir ?? gitSubdir(dir);
1211
+ if (subdir)
1212
+ await client.services.update(created.id, { rootDirectory: subdir });
1213
+ const ignored = writeLink(dir, { serviceId: created.id, serviceName: name });
1214
+ info(`Created ${color.bold(name)} and linked it to ${dir}.`);
1215
+ if (ignored)
1216
+ info('Added .gheima/ to .gitignore.');
1217
+ return { id: created.id, created: true };
1218
+ }
1219
+ /**
1220
+ * Whether `deploy` uploads this folder or asks the service to rebuild (its repository) or
1221
+ * redeploy (its image). A template or image service has no repository either, so "no repo" is
1222
+ * not enough: an upload is right only for a service whose latest deployment was an upload, or
1223
+ * that has never been deployed and has no image.
1224
+ */
1225
+ async function sourceFor(client, serviceId, forceUpload) {
1226
+ if (forceUpload)
1227
+ return 'upload';
1228
+ const service = await client.services.get(serviceId);
1229
+ if (service.repoUrl)
1230
+ return 'git';
1231
+ const [latest] = await client.services.deployments(serviceId);
1232
+ if (!latest)
1233
+ return service.dockerImage ? 'image' : 'upload';
1234
+ return latest.sourceKind === 'UPLOAD' ? 'upload' : 'image';
1235
+ }
1236
+ /** Pack this folder and deploy it as an upload (no git remote involved). */
1237
+ async function uploadAndDeploy(client, serviceId, dir) {
1238
+ const { rootDirectory } = await client.services.get(serviceId);
1239
+ const { root, files } = listSourceFiles(dir, { fromTop: Boolean(rootDirectory) });
1240
+ if (files.length === 0)
1241
+ throw new UsageError(`There are no files to deploy in ${dir}.`);
1242
+ const { tarball, files: count } = packSource(root, files);
1243
+ const mb = (tarball.length / 1024 / 1024).toFixed(1);
1244
+ info(`Uploading ${count} files (${mb} MB compressed; .env files and node_modules left out)…`);
1245
+ try {
1246
+ return await client.services.deploySource(serviceId, tarball);
1247
+ }
1248
+ catch (err) {
1249
+ // The edge answers an oversized body itself, before the API's own message can.
1250
+ if (err instanceof GheimaError && err.status === 413) {
1251
+ throw new GheimaError({
1252
+ status: 413,
1253
+ code: 'payload_too_large',
1254
+ message: `The upload (${mb} MB) is larger than the API accepts. Leave out build output and ` +
1255
+ 'large assets: add them to .gitignore.',
1256
+ });
1257
+ }
1258
+ throw err;
1259
+ }
1260
+ }
1042
1261
  /**
1043
1262
  * Wait for a deployment to finish, streaming its build output meanwhile. The stream is for
1044
1263
  * people; the OUTCOME comes from polling the deployment by id, because the stream follows the
@@ -1,6 +1,9 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
3
  import { hostname, userInfo } from 'node:os';
4
+ import { join } from 'node:path';
3
5
  import { apiBaseUrl } from '@gheima/sdk';
6
+ import { configDir } from './config.js';
4
7
  /** A name the approver will recognise as their own machine — or not, if it is not theirs. */
5
8
  export function defaultClientName() {
6
9
  let who = 'cli';
@@ -28,13 +31,22 @@ export function defaultClientName() {
28
31
  * interleave with the CLI's own output or hold the process open.
29
32
  */
30
33
  export function openBrowser(url) {
31
- const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
34
+ // The URL comes from the server's response, so it is data, not a command line. It used to go
35
+ // through `start` with shell:true on Windows, where cmd.exe would run anything after a `&` in
36
+ // it. Only an http(s) URL is opened, and always as one argv entry with no shell: rundll32 on
37
+ // Windows, as `gheima open` does.
38
+ let parsed;
32
39
  try {
33
- const child = spawn(cmd, [url], {
34
- stdio: 'ignore',
35
- detached: true,
36
- shell: process.platform === 'win32',
37
- });
40
+ parsed = new URL(url);
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
46
+ return false;
47
+ const [cmd, args] = openerFor(process.platform, parsed.href);
48
+ try {
49
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
38
50
  child.on('error', () => undefined); // a missing xdg-open must not crash the login
39
51
  child.unref();
40
52
  return true;
@@ -43,6 +55,14 @@ export function openBrowser(url) {
43
55
  return false;
44
56
  }
45
57
  }
58
+ /** The OS opener and its argv for a URL. Exported for the test. */
59
+ export function openerFor(platform, url) {
60
+ if (platform === 'darwin')
61
+ return ['open', [url]];
62
+ if (platform === 'win32')
63
+ return ['rundll32', ['url.dll,FileProtocolHandler', url]];
64
+ return ['xdg-open', [url]];
65
+ }
46
66
  async function postJson(url, body, signal) {
47
67
  return fetch(url, {
48
68
  method: 'POST',
@@ -59,6 +79,14 @@ export async function startDeviceLogin(baseUrl, clientName) {
59
79
  }
60
80
  return (await res.json());
61
81
  }
82
+ /** `--resume --timeout` ran out while the sign-in is still waiting for the person. */
83
+ export class LoginStillPending extends Error {
84
+ name = 'LoginStillPending';
85
+ constructor() {
86
+ super('Still waiting for the sign-in to be approved in the browser. ' +
87
+ 'Run `gheima login --resume` again to keep waiting.');
88
+ }
89
+ }
62
90
  const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
63
91
  /**
64
92
  * Poll until the login is approved, denied or expires.
@@ -70,12 +98,15 @@ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
70
98
  export async function pollForApproval(baseUrl, start, opts = {}) {
71
99
  const sleep = opts.sleep ?? defaultSleep;
72
100
  const now = opts.now ?? (() => Date.now());
73
- const deadline = now() + start.expires_in * 1000;
101
+ const deadline = opts.expiresAt ?? now() + start.expires_in * 1000;
102
+ const restart = `Run \`${opts.restartCommand ?? 'gheima login'}\` again.`;
74
103
  let intervalMs = Math.max(1, start.interval) * 1000;
75
104
  for (;;) {
76
105
  if (now() >= deadline) {
77
- throw new Error('This sign-in expired before it was approved. Run `gheima login` again.');
106
+ throw new Error(`This sign-in expired before it was approved. ${restart}`);
78
107
  }
108
+ if (opts.giveUpAt !== undefined && now() >= opts.giveUpAt)
109
+ throw new LoginStillPending();
79
110
  await sleep(intervalMs);
80
111
  const res = await postJson(`${apiBaseUrl(baseUrl)}/device/token`, {
81
112
  device_code: start.device_code,
@@ -93,11 +124,32 @@ export async function pollForApproval(baseUrl, start, opts = {}) {
93
124
  opts.onSlowDown?.(Math.round(intervalMs / 1000));
94
125
  break;
95
126
  case 'access_denied':
96
- throw new Error('The sign-in was denied in the dashboard.');
127
+ throw new Error(`The sign-in was denied in the dashboard. ${restart}`);
97
128
  case 'expired_token':
98
- throw new Error('This sign-in expired or was already used. Run `gheima login` again.');
129
+ throw new Error(`This sign-in expired or was already used. ${restart}`);
99
130
  default:
100
- throw new Error(body.error?.message ?? `Sign-in failed (HTTP ${res.status}). Run \`gheima login\` again.`);
131
+ throw new Error(body.error?.message ?? `Sign-in failed (HTTP ${res.status}). ${restart}`);
101
132
  }
102
133
  }
103
134
  }
135
+ function pendingPath() {
136
+ return join(configDir(), 'pending-login.json');
137
+ }
138
+ export function savePendingLogin(p) {
139
+ mkdirSync(configDir(), { recursive: true, mode: 0o700 });
140
+ writeFileSync(pendingPath(), JSON.stringify(p) + '\n', { encoding: 'utf8', mode: 0o600 });
141
+ chmodSync(pendingPath(), 0o600);
142
+ }
143
+ /** The pending sign-in, or null when there is none or it has expired. */
144
+ export function loadPendingLogin(now = Date.now()) {
145
+ try {
146
+ const p = JSON.parse(readFileSync(pendingPath(), 'utf8'));
147
+ return p.expiresAt > now ? p : null;
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ }
153
+ export function clearPendingLogin() {
154
+ rmSync(pendingPath(), { force: true });
155
+ }
package/dist/exit.js CHANGED
@@ -27,6 +27,9 @@ export function exitCodeFor(err) {
27
27
  return EXIT.usage;
28
28
  if (err instanceof NotAuthenticatedError)
29
29
  return EXIT.auth;
30
+ // `login --resume --timeout` ran out: a timeout, and nothing is wrong yet.
31
+ if (err instanceof Error && err.name === 'LoginStillPending')
32
+ return EXIT.network;
30
33
  if (!(err instanceof GheimaError))
31
34
  return EXIT.error;
32
35
  // status 0 is the SDK's "no response at all": a dropped connection or a timeout.
@@ -36,7 +39,8 @@ export function exitCodeFor(err) {
36
39
  return EXIT.auth;
37
40
  if (err.status === 404)
38
41
  return EXIT.notFound;
39
- if ([400, 409, 412, 422, 428].includes(err.status))
42
+ // 413: the upload is over a size cap, which the caller fixes like any validation error.
43
+ if ([400, 409, 412, 413, 422, 428].includes(err.status))
40
44
  return EXIT.conflict;
41
45
  if (err.status === 429)
42
46
  return EXIT.rateLimited;
@@ -0,0 +1,67 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { basename, join } from 'node:path';
4
+ const git = (dir, ...args) => {
5
+ const r = spawnSync('git', ['-C', dir, ...args], { encoding: 'utf8' });
6
+ return r.status === 0 ? r.stdout.trim() : '';
7
+ };
8
+ /**
9
+ * A git remote URL as the API takes it: https, with any credential removed. A remote such as
10
+ * `https://x-access-token:<token>@github.com/o/r.git` must never reach the API (it refuses one
11
+ * anyway), and an ssh remote (`git@github.com:o/r.git`) is the same repository over https.
12
+ * Null for anything that is not a recognisable remote.
13
+ */
14
+ export function httpsRemote(raw) {
15
+ const scp = /^[\w.-]+@([\w.-]+):(.+)$/.exec(raw);
16
+ if (scp)
17
+ return `https://${scp[1]}/${scp[2].replace(/^\/+/, '')}`;
18
+ let u;
19
+ try {
20
+ u = new URL(raw);
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ if (!['https:', 'http:', 'ssh:', 'git:'].includes(u.protocol) || !u.hostname)
26
+ return null;
27
+ // An ssh remote's port is SSH's; an http(s) one's is the web server's and must stay.
28
+ const host = u.protocol === 'https:' || u.protocol === 'http:' ? u.host : u.hostname;
29
+ return `https://${host}${u.pathname}`;
30
+ }
31
+ /**
32
+ * The folder's `origin` (or its only remote), current branch, and where the folder sits in the
33
+ * repository (`apps/web`, or '' at the root), or null with no remote.
34
+ */
35
+ export function gitRemote(dir) {
36
+ const names = git(dir, 'remote').split('\n').filter(Boolean);
37
+ const name = names.includes('origin') ? 'origin' : names.length === 1 ? names[0] : null;
38
+ if (!name)
39
+ return null;
40
+ const url = httpsRemote(git(dir, 'remote', 'get-url', name));
41
+ if (!url)
42
+ return null;
43
+ // symbolic-ref, not rev-parse: it answers in a repository that has no commit yet.
44
+ const branch = git(dir, 'symbolic-ref', '--short', '-q', 'HEAD');
45
+ return { url, branch: branch || 'main', subdir: gitSubdir(dir) };
46
+ }
47
+ /** A service name for the first deploy: package.json's name (unscoped), else the folder's. */
48
+ export function defaultServiceName(dir) {
49
+ let name = '';
50
+ try {
51
+ name =
52
+ JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name ?? '';
53
+ }
54
+ catch {
55
+ // no package.json, or not JSON: the folder name will do
56
+ }
57
+ name = name.replace(/^@[^/]+\//, '') || basename(dir);
58
+ return (name
59
+ .toLowerCase()
60
+ .replace(/[^a-z0-9-]+/g, '-')
61
+ .replace(/^-+|-+$/g, '')
62
+ .slice(0, 60) || 'app');
63
+ }
64
+ /** Where `dir` sits in its git repository (`apps/web`), or '' at the root or outside git. */
65
+ export function gitSubdir(dir) {
66
+ return git(dir, 'rev-parse', '--show-prefix').replace(/\/$/, '');
67
+ }
package/dist/pack.js ADDED
@@ -0,0 +1,170 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { lstatSync, readFileSync, readdirSync, readlinkSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, relative, resolve, sep } from 'node:path';
5
+ import { gzipSync } from 'node:zlib';
6
+ /**
7
+ * Pack a project folder for `gheima deploy` with no git remote (ADR 0002, decision 9).
8
+ *
9
+ * Inside a git work tree the file list is git's own (`.gitignore` holds); elsewhere it is a walk
10
+ * that skips `.git`, `node_modules` and `.gheima`. Both skip `.env` and `.env.*` (except
11
+ * `.env.example`): a secrets file must not be uploaded into a build because an agent forgot it
12
+ * was there. The tarball is written here, as plain ustar, so it is the same on every OS (the
13
+ * system `tar` on macOS adds AppleDouble files and extended attributes).
14
+ */
15
+ const WALK_SKIP = new Set(['.git', 'node_modules', '.gheima']);
16
+ const SECRET_DIRS = new Set(['.ssh', '.aws', '.gnupg', '.kube', '.docker']);
17
+ const SECRET_NAMES = new Set([
18
+ '.npmrc',
19
+ '.netrc',
20
+ '.pgpass',
21
+ '.git-credentials',
22
+ 'credentials.json',
23
+ ]);
24
+ const SECRET_EXT = /\.(pem|key|p12|pfx|jks|keystore)$/;
25
+ /**
26
+ * A secrets file, never uploaded: `.env` files (but `.env.example` and friends are
27
+ * documentation, so they go), private keys and certificates, and the credential files and
28
+ * folders a home directory holds.
29
+ */
30
+ export function isSecretsFile(path) {
31
+ const parts = path.split('/');
32
+ const name = parts.at(-1) ?? '';
33
+ if (parts.slice(0, -1).some((p) => SECRET_DIRS.has(p)))
34
+ return true;
35
+ if (SECRET_NAMES.has(name) || SECRET_EXT.test(name) || /^id_(rsa|dsa|ecdsa|ed25519)/.test(name)) {
36
+ return true;
37
+ }
38
+ if (name !== '.env' && !name.startsWith('.env.'))
39
+ return false;
40
+ return !/\.(example|sample|template)$/.test(name);
41
+ }
42
+ /** The most `gheima deploy` reads into memory to pack: the largest plan's compressed cap. */
43
+ export const MAX_PACK_BYTES = 100 * 1024 * 1024;
44
+ function gitFiles(dir) {
45
+ const inside = spawnSync('git', ['-C', dir, 'rev-parse', '--is-inside-work-tree'], {
46
+ encoding: 'utf8',
47
+ });
48
+ if (inside.status !== 0 || inside.stdout.trim() !== 'true')
49
+ return null;
50
+ const ls = spawnSync('git', ['-C', dir, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
51
+ if (ls.status !== 0)
52
+ return null;
53
+ return ls.stdout.split('\0').filter(Boolean);
54
+ }
55
+ function walk(dir, root = dir, out = [], budget = { bytes: 0 }) {
56
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
57
+ if (WALK_SKIP.has(entry.name) || SECRET_DIRS.has(entry.name))
58
+ continue;
59
+ const full = join(dir, entry.name);
60
+ if (entry.isDirectory())
61
+ walk(full, root, out, budget);
62
+ else {
63
+ // Stop early: a folder that is not a project (a downloads folder) must not be read whole.
64
+ budget.bytes += lstatSync(full).size;
65
+ if (budget.bytes > MAX_PACK_BYTES)
66
+ throw tooBig();
67
+ out.push(relative(root, full).split(sep).join('/'));
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+ const tooBig = () => new Error(`This folder holds more than ${MAX_PACK_BYTES / 1024 / 1024} MB of files to upload. Run gheima ` +
73
+ 'deploy in the project folder, and leave build output and large assets out with .gitignore.');
74
+ /**
75
+ * What `gheima deploy` would upload from `dir`: the folder to pack from and its files, as
76
+ * `/`-separated paths relative to it. Inside a git work tree, for a service with a
77
+ * `rootDirectory`, that is the repository's top level, so `rootDirectory` means the same for an
78
+ * upload as for a git build.
79
+ */
80
+ export function listSourceFiles(dir, { fromTop = true } = {}) {
81
+ const top = gitTopLevel(dir);
82
+ // From the top only when the service builds a subdirectory of it (`rootDirectory`); a service
83
+ // with none builds exactly the folder the person is in.
84
+ const root = fromTop && top ? top : dir;
85
+ if (resolve(root) === resolve(homedir())) {
86
+ throw new Error('Refusing to upload your home directory. Run gheima deploy in the project folder.');
87
+ }
88
+ const files = (top ? gitFiles(root) : null) ?? walk(root);
89
+ return {
90
+ root,
91
+ files: files
92
+ .filter((f) => !isSecretsFile(f) && !f.split('/').some((s) => s === '.gheima'))
93
+ .sort(),
94
+ };
95
+ }
96
+ function gitTopLevel(dir) {
97
+ const r = spawnSync('git', ['-C', dir, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' });
98
+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null;
99
+ }
100
+ /** One 512-byte ustar header. Throws on a path ustar cannot hold (over 255 bytes). */
101
+ function header(path, { size, mode, type, link }) {
102
+ const h = Buffer.alloc(512);
103
+ let name = path;
104
+ let prefix = '';
105
+ if (Buffer.byteLength(name) > 100) {
106
+ const cut = path.lastIndexOf('/', 155);
107
+ prefix = cut > 0 ? path.slice(0, cut) : '';
108
+ name = cut > 0 ? path.slice(cut + 1) : path;
109
+ if (!prefix || Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) {
110
+ throw new Error(`The path "${path}" is too long to upload (over 255 bytes).`);
111
+ }
112
+ }
113
+ if (link && Buffer.byteLength(link) > 100) {
114
+ throw new Error(`The symlink "${path}" points at a target too long to upload.`);
115
+ }
116
+ const octal = (n, width) => n.toString(8).padStart(width - 1, '0') + '\0';
117
+ h.write(name, 0, 100);
118
+ h.write(octal(mode, 8), 100);
119
+ h.write(octal(0, 8), 108); // uid
120
+ h.write(octal(0, 8), 116); // gid
121
+ h.write(octal(size, 12), 124);
122
+ h.write(octal(0, 12), 136); // mtime: fixed, so the same tree packs to the same bytes
123
+ h.write(' ', 148); // checksum placeholder
124
+ h.write(type, 156);
125
+ if (link)
126
+ h.write(link, 157, 100);
127
+ h.write('ustar\0', 257);
128
+ h.write('00', 263);
129
+ h.write(prefix, 345, 155);
130
+ let sum = 0;
131
+ for (const b of h)
132
+ sum += b;
133
+ h.write(sum.toString(8).padStart(6, '0') + '\0 ', 148);
134
+ return h;
135
+ }
136
+ /** A gzipped ustar tarball of `files` (relative to `dir`). Missing files are skipped. */
137
+ export function packSource(dir, files) {
138
+ const parts = [];
139
+ let count = 0;
140
+ let bytes = 0;
141
+ for (const file of files) {
142
+ const full = join(dir, file);
143
+ let st;
144
+ try {
145
+ st = lstatSync(full);
146
+ }
147
+ catch {
148
+ continue; // tracked by git but deleted in the work tree
149
+ }
150
+ bytes += st.size;
151
+ if (bytes > MAX_PACK_BYTES)
152
+ throw tooBig();
153
+ if (st.isSymbolicLink()) {
154
+ parts.push(header(file, { size: 0, mode: 0o777, type: '2', link: readlinkSync(full) }));
155
+ }
156
+ else if (st.isFile()) {
157
+ const body = readFileSync(full);
158
+ parts.push(header(file, { size: body.length, mode: st.mode & 0o755, type: '0' }), body);
159
+ const pad = (512 - (body.length % 512)) % 512;
160
+ if (pad)
161
+ parts.push(Buffer.alloc(pad));
162
+ }
163
+ else {
164
+ continue; // a submodule's directory, a socket: nothing a build can use
165
+ }
166
+ count++;
167
+ }
168
+ parts.push(Buffer.alloc(1024)); // end-of-archive: two zero blocks
169
+ return { tarball: gzipSync(Buffer.concat(parts)), files: count };
170
+ }
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // GENERATED by scripts/write-version.mjs from package.json. Do not edit.
2
- export const VERSION = '0.8.0';
2
+ export const VERSION = '0.9.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gheima/cli",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Command-line interface for the Gheima platform.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -35,8 +35,8 @@
35
35
  "commander": "^12.1.0",
36
36
  "undici": "^7.29.0",
37
37
  "zod": "^4.4.3",
38
- "@gheima/contracts": "0.2.1",
39
- "@gheima/sdk": "0.5.0"
38
+ "@gheima/contracts": "0.3.0",
39
+ "@gheima/sdk": "0.6.0"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@arethetypeswrong/cli": "^0.18.5",