@gheima/cli 0.9.2 → 0.9.4

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,17 @@
1
1
  # @gheima/cli
2
2
 
3
+ ## 0.9.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 0b37d69: `gheima login --resume` finishes on a credential that appeared since `login --no-wait` (saved with `login --with-key`, or `GHEIMA_API_KEY`) instead of waiting on a device code nobody will approve. A credential that was already there when the sign-in started does not count, so signing in again as another account still waits for the code.
8
+
9
+ ## 0.9.3
10
+
11
+ ### Patch Changes
12
+
13
+ - 2910318: `gheima deploy` takes `--type WEB|WORKER|STATIC` for the service its first run creates, and a folder of plain HTML files (an `index.html` and nothing that builds or runs a server) now becomes a static site on its own. Plans count static sites apart from services, so on a Free plan whose one service is taken, a static site still deploys instead of hitting the service limit.
14
+
3
15
  ## 0.9.2
4
16
 
5
17
  ### Patch Changes
package/dist/cli.js CHANGED
@@ -4,6 +4,7 @@ import { readFileSync, createReadStream, createWriteStream, existsSync, statSync
4
4
  import { Readable } from 'node:stream';
5
5
  import { pipeline } from 'node:stream/promises';
6
6
  import { basename } from 'node:path';
7
+ import { createHash } from 'node:crypto';
7
8
  import { Command } from 'commander';
8
9
  import { GheimaError, GheimaClient, DEFAULT_API_URL } from '@gheima/sdk';
9
10
  import { makeClient, transportOptions, VERSION } from './client.js';
@@ -17,7 +18,7 @@ import { completionScript } from './completion.js';
17
18
  import { callOp, registerGenerated } from './generated.js';
18
19
  import { findLink, toDotenv, writeLink } from './link.js';
19
20
  import { listSourceFiles, packSource } from './pack.js';
20
- import { defaultServiceName, gitRemote, gitSubdir } from './git-remote.js';
21
+ import { defaultServiceName, detectServiceType, gitRemote, gitSubdir } from './git-remote.js';
21
22
  import { AGENTS_FILE, agentsSection, upsertAgentsMd } from './agents-md.js';
22
23
  import { clearPendingLogin, defaultClientName, loadPendingLogin, LoginEnded, LoginStillPending, openBrowser, pollForApproval, savePendingLogin, startDeviceLogin, } from './device-login.js';
23
24
  const program = new Command();
@@ -182,7 +183,15 @@ program
182
183
  async function startLoginOnly(baseUrl, profileName, urlOverride) {
183
184
  const started = await startDeviceLogin(baseUrl, defaultClientName());
184
185
  const expiresAt = Date.now() + started.expires_in * 1000;
185
- savePendingLogin({ start: started, expiresAt, baseUrl, profileName, urlOverride });
186
+ const prior = resolveAuth({ profile: profileName, url: urlOverride });
187
+ savePendingLogin({
188
+ start: started,
189
+ expiresAt,
190
+ baseUrl,
191
+ profileName,
192
+ urlOverride,
193
+ priorKeyHash: prior ? keyHash(prior.apiKey) : undefined,
194
+ });
186
195
  const result = {
187
196
  status: 'pending',
188
197
  userCode: started.user_code,
@@ -198,6 +207,10 @@ async function startLoginOnly(baseUrl, profileName, urlOverride) {
198
207
  info(`Open ${color.bold(started.verification_uri_complete)} and approve it.`);
199
208
  info('Then run `gheima login --resume` to finish signing in.');
200
209
  }
210
+ /** A short fingerprint of an API key, so a pending sign-in can tell keys apart without storing one. */
211
+ function keyHash(apiKey) {
212
+ return createHash('sha256').update(apiKey).digest('hex').slice(0, 16);
213
+ }
201
214
  /** `gheima login --resume`: finish the pending sign-in, or say it is still pending. */
202
215
  async function resumeLogin(timeout) {
203
216
  const seconds = timeout === undefined ? undefined : Number(timeout);
@@ -208,6 +221,31 @@ async function resumeLogin(timeout) {
208
221
  if (!pending) {
209
222
  throw new UsageError('No sign-in is waiting (none was started, or it expired). Run `gheima login --no-wait` first.');
210
223
  }
224
+ // Signed in another way meanwhile (`login --with-key`, GHEIMA_API_KEY): no approval is coming
225
+ // for this code, so finish on the credential that works instead of polling until it expires.
226
+ // Only a credential that appeared SINCE `--no-wait`: one already there is what a deliberate
227
+ // re-login (another account, a key about to be revoked) is replacing.
228
+ const resolved = resolveAuth({ profile: pending.profileName, url: pending.urlOverride });
229
+ const existing = resolved && keyHash(resolved.apiKey) !== pending.priorKeyHash ? resolved : null;
230
+ const account = existing
231
+ ? await new GheimaClient(transportOptions({ apiKey: existing.apiKey, url: existing.url })).account
232
+ .get()
233
+ .catch(() => null)
234
+ : null;
235
+ if (existing && account) {
236
+ clearPendingLogin();
237
+ const profile = existing.profile ?? pending.profileName;
238
+ if (isJsonMode()) {
239
+ return printJson({
240
+ status: 'signed_in',
241
+ account: { id: account.id, name: account.name, slug: account.slug },
242
+ profile,
243
+ source: existing.source,
244
+ });
245
+ }
246
+ success(`Already signed in as ${color.bold(account.name)} (${account.slug}), via ${existing.source}`);
247
+ return;
248
+ }
211
249
  const spin = spinner('Waiting for approval…');
212
250
  let result;
213
251
  try {
@@ -365,6 +403,32 @@ services
365
403
  fail(err);
366
404
  }
367
405
  });
406
+ services
407
+ .command('set-registry-auth <service>')
408
+ .description('Save the credential to pull an image service’s private image (token on stdin)')
409
+ .requiredOption('--username <name>', 'registry username')
410
+ .requiredOption('--password-stdin', 'read the token or password from stdin, e.g. `echo $GHCR_TOKEN | gheima services set-registry-auth web --username me --password-stdin`')
411
+ .action(async (ref, opts, cmd) => {
412
+ const g = globals(cmd);
413
+ const client = makeClient(g);
414
+ // Only from stdin: a token on argv lands in shell history and in `ps` for every user.
415
+ const password = (await readStdin()).replace(/\r?\n$/, '');
416
+ if (!password)
417
+ fail('No token on stdin. Pipe it in: echo $TOKEN | gheima services set-registry-auth …');
418
+ try {
419
+ const id = await resolveServiceId(client, ref);
420
+ const saved = await client.services.setRegistryAuth(id, {
421
+ username: opts.username,
422
+ password,
423
+ });
424
+ if (g.json)
425
+ return printJson(saved);
426
+ success(`Saved the credential for ${saved.host} as ${saved.username}. It applies from the next deploy.`);
427
+ }
428
+ catch (err) {
429
+ fail(err);
430
+ }
431
+ });
368
432
  services
369
433
  .command('get <service>')
370
434
  .description('Show service detail')
@@ -1152,6 +1216,7 @@ program
1152
1216
  .option('--timeout <minutes>', 'stop waiting after this long (exit 7)', '30')
1153
1217
  .option('--upload', 'upload this folder instead of building from the git remote')
1154
1218
  .option('--name <name>', 'name of the service the first deploy creates (default: the folder name)')
1219
+ .option('--type <type>', 'type of the service the first deploy creates: WEB | WORKER | STATIC (default: STATIC for a plain HTML folder, else WEB)')
1155
1220
  .option('-y, --yes', 'create the service without asking (needed without a terminal)')
1156
1221
  .action(async (ref, opts, cmd) => {
1157
1222
  const g = globals(cmd);
@@ -1202,9 +1267,14 @@ async function serviceToDeploy(client, ref, dir, opts) {
1202
1267
  return { id: await resolveServiceId(client, ref), created: false };
1203
1268
  const remote = opts.upload ? null : gitRemote(dir);
1204
1269
  const name = opts.name ?? defaultServiceName(dir);
1205
- await confirmDestructive(opts.yes, `create the service "${name}" ${remote ? `from ${remote.url} (${remote.branch})` : 'from the files in this folder'}`);
1270
+ const type = (opts.type?.toUpperCase() ?? detectServiceType(dir));
1271
+ if (!['WEB', 'WORKER', 'STATIC'].includes(type)) {
1272
+ throw new UsageError(`--type must be WEB, WORKER or STATIC, not ${opts.type}.`);
1273
+ }
1274
+ await confirmDestructive(opts.yes, `create the ${type === 'STATIC' ? 'static site' : 'service'} "${name}" ${remote ? `from ${remote.url} (${remote.branch})` : 'from the files in this folder'}`);
1206
1275
  const created = await client.services.create({
1207
1276
  name,
1277
+ type,
1208
1278
  ...(remote ? { repoUrl: remote.url, repoBranch: remote.branch } : {}),
1209
1279
  });
1210
1280
  // Run from a subfolder of a repository (a monorepo app): build that folder, not the root. An
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { readFileSync } from 'node:fs';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
3
  import { basename, join } from 'node:path';
4
4
  const git = (dir, ...args) => {
5
5
  const r = spawnSync('git', ['-C', dir, ...args], { encoding: 'utf8' });
@@ -65,3 +65,29 @@ export function defaultServiceName(dir) {
65
65
  export function gitSubdir(dir) {
66
66
  return git(dir, 'rev-parse', '--show-prefix').replace(/\/$/, '');
67
67
  }
68
+ /** Files that mean the folder is an app with a server or a build, not a bundle of static files. */
69
+ const APP_MARKERS = [
70
+ 'package.json',
71
+ 'requirements.txt',
72
+ 'pyproject.toml',
73
+ 'Pipfile',
74
+ 'go.mod',
75
+ 'Gemfile',
76
+ 'composer.json',
77
+ 'Cargo.toml',
78
+ 'pom.xml',
79
+ 'build.gradle',
80
+ 'mix.exs',
81
+ 'Dockerfile',
82
+ 'deno.json',
83
+ ];
84
+ /**
85
+ * The service type the first deploy of `dir` creates: STATIC for a plain site (an `index.html`
86
+ * at the root and nothing that builds or runs a server), WEB otherwise. A static site is served
87
+ * by nginx with no runtime, and plans count it apart from services (Free has one of each).
88
+ */
89
+ export function detectServiceType(dir) {
90
+ if (!existsSync(join(dir, 'index.html')))
91
+ return 'WEB';
92
+ return APP_MARKERS.some((f) => existsSync(join(dir, f))) ? 'WEB' : 'STATIC';
93
+ }
package/dist/pack.js CHANGED
@@ -15,6 +15,9 @@ import { gzipSync } from 'node:zlib';
15
15
  const WALK_SKIP = new Set(['.git', 'node_modules', '.gheima']);
16
16
  const SECRET_DIRS = new Set(['.ssh', '.aws', '.gnupg', '.kube', '.docker']);
17
17
  const SECRET_NAMES = new Set([
18
+ // direnv's per-folder environment: a shell script of `export KEY=value`, i.e. a `.env` by
19
+ // another name, and nothing a build reads.
20
+ '.envrc',
18
21
  '.npmrc',
19
22
  '.netrc',
20
23
  '.pgpass',
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.9.2';
2
+ export const VERSION = '0.9.4';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gheima/cli",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "description": "Command-line interface for the Gheima platform.",
5
5
  "license": "MIT",
6
6
  "repository": {