koigrid 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/api.js +13 -0
  3. package/dist/args.js +28 -5
  4. package/dist/commands/ai.js +56 -0
  5. package/dist/commands/analytics.js +52 -0
  6. package/dist/commands/anomalies.js +38 -0
  7. package/dist/commands/apps.js +217 -13
  8. package/dist/commands/audit.js +45 -0
  9. package/dist/commands/bots.js +47 -0
  10. package/dist/commands/checks.js +87 -0
  11. package/dist/commands/config.js +52 -0
  12. package/dist/commands/connect.js +86 -0
  13. package/dist/commands/db.js +240 -0
  14. package/dist/commands/dns.js +79 -0
  15. package/dist/commands/email.js +16 -2
  16. package/dist/commands/errors.js +34 -0
  17. package/dist/commands/flags.js +85 -0
  18. package/dist/commands/heartbeats.js +51 -0
  19. package/dist/commands/images.js +31 -0
  20. package/dist/commands/logs.js +69 -0
  21. package/dist/commands/members.js +54 -0
  22. package/dist/commands/notifications.js +21 -0
  23. package/dist/commands/otel.js +35 -0
  24. package/dist/commands/projects.js +38 -0
  25. package/dist/commands/queues.js +90 -0
  26. package/dist/commands/redis.js +18 -0
  27. package/dist/commands/registry.js +31 -0
  28. package/dist/commands/rewards.js +57 -0
  29. package/dist/commands/sandboxes.js +46 -0
  30. package/dist/commands/speed.js +33 -0
  31. package/dist/commands/spend.js +33 -0
  32. package/dist/commands/status.js +81 -0
  33. package/dist/commands/storage.js +53 -0
  34. package/dist/commands/tokens.js +42 -0
  35. package/dist/commands/waf.js +57 -0
  36. package/dist/commands/webhooks.js +54 -0
  37. package/dist/commands/wordpress.js +153 -0
  38. package/dist/commands/workflows.js +95 -0
  39. package/dist/config.js +4 -2
  40. package/dist/manifest.js +35 -5
  41. package/dist/registry.js +31 -1
  42. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,29 @@
2
2
 
3
3
  All notable changes to the koigrid CLI are documented here. Format: [Keep a Changelog](https://keepachangelog.com). Versions follow [SemVer](https://semver.org).
4
4
 
5
+ ## [0.5.0] — 2026-07-24
6
+
7
+ Pone el CLI al día con la API (el publicado 0.4.0 era del 2026-07-05 → faltaban ~3 semanas de productos).
8
+ Los guards del repo (`cli-coverage`/`cli-methods`) garantizan que cada endpoint `/api/v1` tiene su comando.
9
+
10
+ ### Added
11
+ - **Imagen privada / registry** en `apps deploy`: `--registry <host>` con `--registry-user`/`--registry-password`
12
+ (GHCR/Docker Hub/GitLab) **o** `--registry-aws-region`/`--registry-aws-key`/`--registry-aws-secret` (AWS **ECR
13
+ nativo**: token fresco por deploy, como un execution role). Nuevo `apps registry <id>` para rotar/borrar (`--clear`)
14
+ las credenciales sin recrear la app.
15
+ - Comandos de todos los productos añadidos desde 0.4.0: `connect`, `spend`, `otel`, `dns`, `bots`, `log-drains`
16
+ (`logs`), `webhooks`, `anomalies`, `audit`, `notifications`, `status`, `protection` (en `apps`), `queues`,
17
+ `workflows`, `members`, `flags`, `config`, `heartbeats`, `analytics`, `speed`, `errors`, `sandboxes`, `waf`,
18
+ `images`, `ai`, `registry`, `rewards`, + subcomandos de `db` (branches, roles, rotation, data, query, rpc,
19
+ publications) y `apps` (previews, hooks, retention, volumes, rule-toggle, env por target).
20
+
21
+ ## [0.4.0] — 2026-07-05
22
+
23
+ ### Added
24
+ - **`--health-path`** on `apps deploy` (e.g. `--health-path /api/health`): koigrid probes that path after each
25
+ deploy. A 5xx / no-response means the container runs but the app is broken (e.g. can't reach its DB) — koigrid
26
+ emits `app.unhealthy` instead of calling it healthy. Closes the "running but broken" blind spot.
27
+
5
28
  ## [0.3.0] — 2026-07-05
6
29
 
7
30
  ### Added
package/dist/api.js CHANGED
@@ -23,6 +23,19 @@ export async function api(path, opts = {}) {
23
23
  signal: AbortSignal.timeout(30_000),
24
24
  }).catch((e) => { throw new ApiError(0, `network error: ${e?.message || e}`); });
25
25
  const text = await res.text();
26
+ // raw: devuelve el cuerpo sin parsear (p.ej. CSV del audit export). Solo intenta leer error JSON al fallar.
27
+ if (opts.raw) {
28
+ if (!res.ok) {
29
+ let j = null;
30
+ try {
31
+ j = JSON.parse(text);
32
+ }
33
+ catch { }
34
+ ;
35
+ throw new ApiError(res.status, j?.error || `HTTP ${res.status}`, j?.detail);
36
+ }
37
+ return text;
38
+ }
26
39
  let json = null;
27
40
  try {
28
41
  json = text ? JSON.parse(text) : null;
package/dist/args.js CHANGED
@@ -1,22 +1,45 @@
1
1
  /** `apps deploy web --image nginx --port 80 --json` → {cmd:apps, sub:deploy, positionals:[web], flags:{image,port,json}} */
2
2
  export function parseArgs(argv) {
3
+ // `--` = fin de opciones: lo que sigue es un comando a pasar tal cual (no se parsea).
4
+ let passthrough;
5
+ const dd = argv.indexOf('--');
6
+ if (dd >= 0) {
7
+ passthrough = argv.slice(dd + 1);
8
+ argv = argv.slice(0, dd);
9
+ }
3
10
  const positionals = [];
4
11
  const flags = {};
12
+ // Acumula un flag string repetido en un array (1ª vez = string, 2ª+ = array). Un boolean repetido sigue true.
13
+ const setFlag = (key, val) => {
14
+ const cur = flags[key];
15
+ if (cur === undefined || typeof val === 'boolean') {
16
+ if (cur === undefined)
17
+ flags[key] = val;
18
+ return;
19
+ }
20
+ if (Array.isArray(cur))
21
+ cur.push(val);
22
+ else if (typeof cur === 'string')
23
+ flags[key] = [cur, val];
24
+ else
25
+ flags[key] = val; // cur era boolean → lo reemplaza el valor
26
+ };
5
27
  for (let i = 0; i < argv.length; i++) {
6
28
  const a = argv[i];
7
29
  if (a.startsWith('--')) {
8
30
  const key = a.slice(2);
9
31
  const next = argv[i + 1];
10
- if (next !== undefined && !next.startsWith('-')) {
11
- flags[key] = next;
32
+ // Un valor puede empezar por '-' si es numérico (p.ej. `--offset -5`); un flag suelto no consume el siguiente flag.
33
+ if (next !== undefined && (!next.startsWith('-') || /^-\d/.test(next))) {
34
+ setFlag(key, next);
12
35
  i++;
13
36
  }
14
37
  else {
15
- flags[key] = true;
38
+ setFlag(key, true);
16
39
  }
17
40
  }
18
41
  else if (a.startsWith('-') && a.length === 2) {
19
- flags[a.slice(1)] = true;
42
+ setFlag(a.slice(1), true);
20
43
  }
21
44
  else {
22
45
  positionals.push(a);
@@ -24,5 +47,5 @@ export function parseArgs(argv) {
24
47
  }
25
48
  const cmd = positionals.shift();
26
49
  const sub = positionals.shift();
27
- return { cmd, sub, positionals, flags };
50
+ return { cmd, sub, positionals, flags, ...(passthrough ? { passthrough } : {}) };
28
51
  }
@@ -0,0 +1,56 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ // koigrid ai — AI Gateway (chat unificado a LLMs, BYO keys). Ver docs/AI-GATEWAY.md.
4
+ export async function ai(a) {
5
+ const json = !!a.flags.json;
6
+ const sub = a.sub || 'usage';
7
+ if (sub === 'chat') {
8
+ const model = a.positionals[0];
9
+ // prompt como posicional (koigrid ai chat <model> "hi") o vía --message/--prompt
10
+ const message = (a.positionals[1] || a.flags.message || a.flags.prompt);
11
+ if (!model || !message)
12
+ throw new Error('usage: koigrid ai chat <model> "your prompt" (or --message "…")');
13
+ const r = await api('/ai/chat', { method: 'POST', body: { model, messages: [{ role: 'user', content: message }] } });
14
+ if (json)
15
+ return console.log(JSON.stringify(r, null, 2));
16
+ console.log(r.content);
17
+ console.log(green(`\n— ${r.provider}/${r.model} · ${r.usage?.promptTokens}+${r.usage?.completionTokens} tok · ${r.runner}`));
18
+ return;
19
+ }
20
+ if (sub === 'providers' || sub === 'provider') {
21
+ const act = a.positionals[0];
22
+ if (!act || act === 'ls') {
23
+ const r = await api('/ai/providers');
24
+ const l = r.providers || [];
25
+ return output(l, json, { rows: l.map((x) => ({ name: x.name, configured: x.configuredAt ? 'yes' : '' })), columns: ['name', 'configured'] });
26
+ }
27
+ if (act === 'set') {
28
+ const name = a.positionals[1], key = a.positionals[2];
29
+ if (!name || !key)
30
+ throw new Error('usage: koigrid ai providers set <openai|anthropic> <API_KEY>');
31
+ await api('/ai/providers', { method: 'POST', body: { name, apiKey: key } });
32
+ return console.log(green(`✓ ${name} key saved (encrypted)`));
33
+ }
34
+ if (act === 'rm') {
35
+ const name = a.positionals[1];
36
+ if (!name)
37
+ throw new Error('need <name>');
38
+ await api(`/ai/providers/${encodeURIComponent(name)}`, { method: 'DELETE' });
39
+ return console.log(green(`✓ Removed ${name}`));
40
+ }
41
+ throw new Error('usage: koigrid ai providers ls | set <name> <key> | rm <name>');
42
+ }
43
+ // usage
44
+ const days = a.flags.days ? Number(a.flags.days) : 30;
45
+ const r = await api(`/ai/usage?days=${days}`);
46
+ if (json)
47
+ return console.log(JSON.stringify(r, null, 2));
48
+ const t = r.usage?.total || {};
49
+ console.log(`Requests: ${t.requests} Tokens: ${t.promptTokens}+${t.completionTokens} Cost: ${((t.costMicroCents || 0) / 1e6).toFixed(4)}¢ (last ${days}d)`);
50
+ const byModel = r.usage?.byModel || [];
51
+ if (byModel.length) {
52
+ console.log('\nBy model:');
53
+ for (const m of byModel)
54
+ console.log(` ${m.requests}\t${m.model}`);
55
+ }
56
+ }
@@ -0,0 +1,52 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ // koigrid analytics — web analytics privacy-first. Ver docs/ANALYTICS.md.
4
+ export async function analytics(a) {
5
+ const json = !!a.flags.json;
6
+ const sub = a.sub || 'sites';
7
+ if (sub === 'sites' || sub === 'ls' || sub === 'list') {
8
+ const r = await api('/analytics/sites');
9
+ const l = r.sites || [];
10
+ return output(l, json, {
11
+ rows: l.map((x) => ({ id: String(x.id).slice(0, 8), name: x.name, token: x.publicToken })),
12
+ columns: ['id', 'name', 'token'],
13
+ });
14
+ }
15
+ if (sub === 'create') {
16
+ const name = a.positionals[0];
17
+ if (!name)
18
+ throw new Error('usage: koigrid analytics create "<name>"');
19
+ const r = await api('/analytics/sites', { method: 'POST', body: { name } });
20
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Site created. Add this to your site:\n ${r.site?.snippet}`));
21
+ }
22
+ if (sub === 'stats') {
23
+ const id = a.positionals[0];
24
+ if (!id)
25
+ throw new Error('usage: koigrid analytics stats <siteId> [--days 30]');
26
+ const days = a.flags.days ? Number(a.flags.days) : 30;
27
+ const r = await api(`/analytics/sites/${encodeURIComponent(id)}/stats?days=${days}`);
28
+ if (json)
29
+ return console.log(JSON.stringify(r, null, 2));
30
+ const s = r.stats || {};
31
+ console.log(`Pageviews: ${s.pageviews} Visitors: ${s.visitors} (last ${days}d)`);
32
+ if (s.topPaths?.length) {
33
+ console.log('\nTop pages:');
34
+ for (const p of s.topPaths)
35
+ console.log(` ${p.count}\t${p.key}`);
36
+ }
37
+ if (s.topReferrers?.length) {
38
+ console.log('\nTop referrers:');
39
+ for (const p of s.topReferrers)
40
+ console.log(` ${p.count}\t${p.key}`);
41
+ }
42
+ return;
43
+ }
44
+ if (sub === 'rm' || sub === 'delete') {
45
+ const id = a.positionals[0];
46
+ if (!id)
47
+ throw new Error('usage: koigrid analytics rm <siteId>');
48
+ await api(`/analytics/sites/${encodeURIComponent(id)}`, { method: 'DELETE' });
49
+ return console.log(green(`✓ Deleted ${id}`));
50
+ }
51
+ throw new Error(`unknown: analytics ${sub}`);
52
+ }
@@ -0,0 +1,38 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ // koigrid anomalies — detección estadística de anomalías de consumo/coste (vs CloudWatch Anomaly Detection).
4
+ // koigrid anomalies ls
5
+ // koigrid anomalies create "cost spike" [--metric cost_cents] [--sigma 3] [--lookback 14] [--min-value 5]
6
+ // koigrid anomalies rm <id>
7
+ export async function anomalies(a) {
8
+ const json = !!a.flags.json, sub = a.sub || 'ls';
9
+ if (sub === 'ls' || sub === 'list') {
10
+ const r = await api('/anomalies');
11
+ const l = r.detectors || [];
12
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), name: x.name, metric: x.metric, sigma: x.sigma, state: x.state, lastValue: x.lastValue ?? '' })), columns: ['id', 'name', 'metric', 'sigma', 'state', 'lastValue'] });
13
+ }
14
+ if (sub === 'create') {
15
+ const name = a.positionals[0];
16
+ if (!name)
17
+ throw new Error('usage: koigrid anomalies create <name> [--metric cost_cents] [--sigma 3] [--lookback 14] [--min-value 0]');
18
+ const body = { name };
19
+ if (a.flags.metric)
20
+ body.metric = String(a.flags.metric);
21
+ if (a.flags.sigma !== undefined)
22
+ body.sigma = Number(a.flags.sigma);
23
+ if (a.flags.lookback !== undefined)
24
+ body.lookbackDays = Number(a.flags.lookback);
25
+ if (a.flags['min-value'] !== undefined)
26
+ body.minValue = Number(a.flags['min-value']);
27
+ const r = await api('/anomalies', { method: 'POST', body });
28
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Anomaly detector "${name}" created (${r.detector?.id})`));
29
+ }
30
+ if (sub === 'rm' || sub === 'delete') {
31
+ const id = a.positionals[0];
32
+ if (!id)
33
+ throw new Error('usage: koigrid anomalies rm <id>');
34
+ await api(`/anomalies/${encodeURIComponent(id)}`, { method: 'DELETE' });
35
+ return console.log(green(`✓ Deleted ${id}`));
36
+ }
37
+ throw new Error(`unknown: anomalies ${sub}`);
38
+ }
@@ -17,13 +17,37 @@ export async function apps(a) {
17
17
  const name = a.positionals[0], image = a.flags.image, repo = a.flags.repo;
18
18
  const dir = a.flags.dir; // deploy desde un directorio LOCAL (código privado, sin git/Docker)
19
19
  const repoToken = a.flags['repo-token']; // token/deploy-key para repos privados
20
+ // Registry PRIVADO (imagen inmutable de CI: build en CI → koigrid la corre): credenciales para el pull.
21
+ const registry = a.flags.registry;
22
+ const registryUsername = a.flags['registry-user'];
23
+ const registryPassword = a.flags['registry-password'];
24
+ const registryAwsRegion = a.flags['registry-aws-region']; // ECR: token fresco por deploy
25
+ const registryAwsAccessKeyId = a.flags['registry-aws-key'];
26
+ const registryAwsSecretKey = a.flags['registry-aws-secret'];
27
+ const reg = registry && registryUsername && registryPassword ? { registry, registryUsername, registryPassword }
28
+ : registry && registryAwsRegion && registryAwsAccessKeyId && registryAwsSecretKey ? { registry, registryAwsRegion, registryAwsAccessKeyId, registryAwsSecretKey }
29
+ : {};
30
+ const healthPath = a.flags['health-path']; // ruta de salud (/api/health) → koigrid detecta apps rotas
31
+ const hc = healthPath ? { healthCheckPath: healthPath } : {};
32
+ // Build settings (git/dir): overridean lo que detecta nixpacks. Un koigrid.json en el repo tiene prioridad.
33
+ const bs = {};
34
+ if (a.flags['build-cmd'])
35
+ bs.buildCommand = a.flags['build-cmd'];
36
+ if (a.flags['install-cmd'])
37
+ bs.installCommand = a.flags['install-cmd'];
38
+ if (a.flags['start-cmd'])
39
+ bs.startCommand = a.flags['start-cmd'];
40
+ if (a.flags['root-dir'])
41
+ bs.rootDirectory = a.flags['root-dir'];
42
+ if (a.flags['node-version'])
43
+ bs.nodeVersion = a.flags['node-version'];
20
44
  if (!name || (!image && !repo && !dir))
21
- throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--repo-token <t>] [--port N]');
45
+ throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--repo-token <t>] [--port N] [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V]');
22
46
  const port = a.flags.port ? Number(a.flags.port) : 3000;
23
47
  // deploy --dir: empaqueta el directorio (excluye lo pesado/irrelevante) → subida presignada a koigrid →
24
48
  // el runner lo construye igual que un repo. No requiere git ni Docker local.
25
49
  if (dir) {
26
- const app = await api('/apps', { method: 'POST', body: { name, port } });
50
+ const app = await api('/apps', { method: 'POST', body: { name, port, ...hc, ...bs } });
27
51
  const aid = app.app?.id || app.id;
28
52
  const up = await api(`/apps/${encodeURIComponent(aid)}/source-upload`, { method: 'POST', body: {} });
29
53
  const { uploadUrl, archiveKey } = up.upload;
@@ -32,13 +56,15 @@ export async function apps(a) {
32
56
  const put = await fetch(uploadUrl, { method: 'PUT', headers: { 'content-type': 'application/gzip' }, body: tar });
33
57
  if (!put.ok)
34
58
  throw new Error(`source upload failed (HTTP ${put.status})`);
35
- await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: { sourceType: 'archive', archiveKey } });
36
- return json ? console.log(JSON.stringify({ id: aid, status: 'queued', source: 'dir' }, null, 2)) : console.log(green(`✓ Deploying "${name}" from ${dir}…`));
59
+ const d = await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: { sourceType: 'archive', archiveKey } });
60
+ // Devuelve el ID del DEPLOYMENT (el que aparece en GET /apps/:id/deployments), NO el del app — evita la
61
+ // confusión "ids CLI≠API" del journey. appId aparte, etiquetado.
62
+ return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued', source: 'dir' }, null, 2)) : console.log(green(`✓ Deploying "${name}" from ${dir}… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
37
63
  }
38
- const app = await api('/apps', { method: 'POST', body: repo ? { name, sourceType: 'git', repo, port, ...(repoToken ? { repoToken } : {}) } : { name, sourceType: 'image', image, port } });
64
+ const app = await api('/apps', { method: 'POST', body: repo ? { name, sourceType: 'git', repo, port, ...(repoToken ? { repoToken } : {}), ...hc, ...bs } : { name, sourceType: 'image', image, port, ...hc, ...reg } });
39
65
  const aid = app.app?.id || app.id;
40
- await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: {} });
41
- return json ? console.log(JSON.stringify({ id: aid, status: 'queued' }, null, 2)) : console.log(green(`✓ Deploying "${name}"…`));
66
+ const d = await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: {} });
67
+ return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued' }, null, 2)) : console.log(green(`✓ Deploying "${name}"… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
42
68
  }
43
69
  case 'deployments':
44
70
  need('');
@@ -63,6 +89,26 @@ export async function apps(a) {
63
89
  await api(`/apps/${encodeURIComponent(id)}/rollback`, { method: 'POST', body: { deploymentId: d } });
64
90
  return console.log(green('✓ Rolling back…'));
65
91
  }
92
+ case 'restore': {
93
+ need('');
94
+ await api(`/apps/${encodeURIComponent(id)}/restore`, { method: 'POST' });
95
+ return console.log(green('✓ Restoring from trash…'));
96
+ }
97
+ case 'migrate': {
98
+ need(' [--server <serverId>]');
99
+ const t = a.flags.server;
100
+ const r = await api(`/apps/${encodeURIComponent(id)}/migrate`, { method: 'POST', body: t ? { targetServerId: t } : {} });
101
+ return json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(`✓ Migrated ${id} → runner ${String(r.toServerId || '').slice(0, 8)}`));
102
+ }
103
+ case 'registry': { // rota/actualiza (o borra --clear) las creds del registry privado sin recrear la app
104
+ need(' [--registry <host> --registry-user <u> --registry-password <p> | --registry-aws-region <r> --registry-aws-key <k> --registry-aws-secret <s> | --clear]');
105
+ const body = a.flags.clear ? { clear: true } : {
106
+ registry: a.flags.registry, registryUsername: a.flags['registry-user'], registryPassword: a.flags['registry-password'],
107
+ registryAwsRegion: a.flags['registry-aws-region'], registryAwsAccessKeyId: a.flags['registry-aws-key'], registryAwsSecretKey: a.flags['registry-aws-secret'],
108
+ };
109
+ const r = await api(`/apps/${encodeURIComponent(id)}/registry`, { method: 'PUT', body });
110
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ registry creds ${a.flags.clear ? 'cleared' : 'set'}`));
111
+ }
66
112
  case 'scale': {
67
113
  need(' [--replicas N]');
68
114
  if (a.flags.replicas === undefined) {
@@ -89,11 +135,14 @@ export async function apps(a) {
89
135
  return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Autoscale updated'));
90
136
  }
91
137
  case 'env': {
92
- need(' set KEY=VAL | rm KEY | ls');
138
+ need(' set KEY=VAL [--target production|preview|all] | rm KEY | ls');
93
139
  const act = a.positionals[1];
94
140
  if (!act || act === 'ls') {
95
141
  const r = await api(`/apps/${encodeURIComponent(id)}/env`);
96
- return console.log(json ? JSON.stringify(r, null, 2) : (r.env || r.keys || []).join('\n'));
142
+ if (json)
143
+ return console.log(JSON.stringify(r, null, 2));
144
+ const vs = r.vars || (r.keys || []).map((k) => ({ key: k, target: 'all' }));
145
+ return console.log(vs.map((v) => `${v.key}\t${v.target}`).join('\n'));
97
146
  }
98
147
  if (act === 'rm') {
99
148
  const k = a.positionals[2];
@@ -107,10 +156,11 @@ export async function apps(a) {
107
156
  if (!kv?.includes('='))
108
157
  throw new Error('need KEY=VALUE');
109
158
  const [k, ...v] = kv.split('=');
110
- await api(`/apps/${encodeURIComponent(id)}/env`, { method: 'POST', body: { env: { [k]: v.join('=') } } });
111
- return console.log(green(`✓ Set ${k} (redeploying)`));
159
+ const target = a.flags.target || 'all';
160
+ await api(`/apps/${encodeURIComponent(id)}/env`, { method: 'POST', body: { env: { [k]: v.join('=') }, target } });
161
+ return console.log(green(`✓ Set ${k} [${target}] (redeploying)`));
112
162
  }
113
- throw new Error('usage: koigrid apps env <id> set KEY=VAL | rm KEY | ls');
163
+ throw new Error('usage: koigrid apps env <id> set KEY=VAL [--target production|preview|all] | rm KEY | ls');
114
164
  }
115
165
  case 'domains': {
116
166
  need(' add <domain> | rm <domain> | ls | verify');
@@ -165,7 +215,33 @@ export async function apps(a) {
165
215
  await api(`/apps/${encodeURIComponent(id)}/volumes/${encodeURIComponent(v)}`, { method: 'DELETE' });
166
216
  return console.log(green(`✓ Removed ${v}`));
167
217
  }
168
- throw new Error('usage: koigrid apps volumes <id> add <name> --size N --mount /path | rm <volId> | ls');
218
+ // backups: koigrid apps volumes <id> backup <volId> · backups <volId> · restore <volId> <backupId> [--mount /path]
219
+ if (act === 'backup') {
220
+ const v = a.positionals[2];
221
+ if (!v)
222
+ throw new Error('need <volId>');
223
+ const r = await api(`/apps/${encodeURIComponent(id)}/volumes/${encodeURIComponent(v)}/backups`, { method: 'POST' });
224
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Backup started (${r.backup?.id})`));
225
+ }
226
+ if (act === 'backups') {
227
+ const v = a.positionals[2];
228
+ if (!v)
229
+ throw new Error('need <volId>');
230
+ const r = await api(`/apps/${encodeURIComponent(id)}/volumes/${encodeURIComponent(v)}/backups`);
231
+ const l = r.backups || [];
232
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), status: x.status, kind: x.kind, gb: String(x.sizeGb || ''), at: x.createdAt || '' })), columns: ['id', 'status', 'kind', 'gb', 'at'] });
233
+ }
234
+ if (act === 'restore') {
235
+ const v = a.positionals[2], b = a.positionals[3];
236
+ if (!v || !b)
237
+ throw new Error('need <volId> <backupId>');
238
+ const body = {};
239
+ if (a.flags.mount)
240
+ body.mountPath = a.flags.mount;
241
+ const r = await api(`/apps/${encodeURIComponent(id)}/volumes/${encodeURIComponent(v)}/backups/${encodeURIComponent(b)}/restore`, { method: 'POST', body });
242
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Restored to new volume ${r.volume?.id} at ${r.volume?.mountPath}`));
243
+ }
244
+ throw new Error('usage: koigrid apps volumes <id> add <name> --size N --mount /path | rm <volId> | ls | backup <volId> | backups <volId> | restore <volId> <backupId>');
169
245
  }
170
246
  case 'cdn': {
171
247
  need(' on|off');
@@ -177,6 +253,73 @@ export async function apps(a) {
177
253
  const r = await api(`/apps/${encodeURIComponent(id)}/cdn`, { method: 'PUT', body: { enabled: act === 'on' } });
178
254
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ CDN ${act}`));
179
255
  }
256
+ case 'retention': {
257
+ need(' [<keepLast> | off]');
258
+ const arg = a.positionals[1];
259
+ if (arg === undefined) {
260
+ const r = await api(`/apps/${encodeURIComponent(id)}/retention`);
261
+ return console.log(json ? JSON.stringify(r, null, 2) : `retention: ${r.retention?.keepLast ?? 'keep all'}`);
262
+ }
263
+ const keepLast = arg === 'off' || arg === 'all' ? null : Number(arg);
264
+ const r = await api(`/apps/${encodeURIComponent(id)}/retention`, { method: 'PUT', body: { keepLast } });
265
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Retention: keep last ${r.retention?.keepLast ?? 'all'}${r.pruned ? ` (pruned ${r.pruned})` : ''}`));
266
+ }
267
+ case 'protection': {
268
+ need(' [show|password|ips|off]');
269
+ const act = a.positionals[1] || 'show';
270
+ if (act === 'show') {
271
+ const r = await api(`/apps/${encodeURIComponent(id)}/protection`);
272
+ return console.log(json ? JSON.stringify(r, null, 2) : `protection: ${r.protection?.mode} (scope ${r.protection?.scope})`);
273
+ }
274
+ let body;
275
+ if (act === 'off')
276
+ body = { mode: 'none' };
277
+ else if (act === 'password') {
278
+ const pw = a.positionals[2] || a.flags.password;
279
+ if (!pw)
280
+ throw new Error('usage: koigrid apps protection <id> password <PASSWORD> [--scope preview|all]');
281
+ body = { mode: 'password', password: pw };
282
+ }
283
+ else if (act === 'ips') {
284
+ const list = (a.positionals.slice(2).join(',') || a.flags.ips || '').split(',').map((s) => s.trim()).filter(Boolean);
285
+ if (!list.length)
286
+ throw new Error('usage: koigrid apps protection <id> ips <CIDR,CIDR…> [--scope preview|all]');
287
+ body = { mode: 'trusted_ips', allowedIps: list };
288
+ }
289
+ else
290
+ throw new Error('usage: koigrid apps protection <id> [show|password <pw>|ips <cidrs>|off]');
291
+ if (a.flags.scope)
292
+ body.scope = a.flags.scope;
293
+ const r = await api(`/apps/${encodeURIComponent(id)}/protection`, { method: 'PUT', body });
294
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Protection: ${r.protection?.mode} (scope ${r.protection?.scope})`));
295
+ }
296
+ case 'hooks': {
297
+ need(' <ls|add|rm> …');
298
+ const act = a.positionals[1] || 'ls';
299
+ if (act === 'ls') {
300
+ const r = await api(`/apps/${encodeURIComponent(id)}/deploy-hooks`);
301
+ const l = r.hooks || [];
302
+ return output(l, json, { rows: l.map((h) => ({ id: String(h.id).slice(0, 8), name: h.name, url: h.url })), columns: ['id', 'name', 'url'] });
303
+ }
304
+ if (act === 'add') {
305
+ const name = a.positionals[2];
306
+ if (!name)
307
+ throw new Error('usage: koigrid apps hooks <id> add <name> [--ref <branch>]');
308
+ const body = { name };
309
+ if (a.flags.ref)
310
+ body.ref = String(a.flags.ref);
311
+ const r = await api(`/apps/${encodeURIComponent(id)}/deploy-hooks`, { method: 'POST', body });
312
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Deploy hook "${name}" → ${r.hook?.url}`));
313
+ }
314
+ if (act === 'rm') {
315
+ const hid = a.positionals[2];
316
+ if (!hid)
317
+ throw new Error('need <hook-id>');
318
+ await api(`/apps/${encodeURIComponent(id)}/deploy-hooks/${encodeURIComponent(hid)}`, { method: 'DELETE' });
319
+ return console.log(green(`✓ Deleted hook ${hid}`));
320
+ }
321
+ throw new Error('usage: koigrid apps hooks <id> ls|add <name>|rm <hook-id>');
322
+ }
180
323
  case 'github': {
181
324
  need(' <owner/repo> [--branch b] [--auto-deploy]');
182
325
  const repo = a.positionals[1];
@@ -206,6 +349,67 @@ export async function apps(a) {
206
349
  const r = await api(`/apps/${encodeURIComponent(id)}/resources`, { method: 'PUT', body });
207
350
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Resized → ${r.resources?.memoryMb}MB / ${r.resources?.cpus} vCPU${r.resources?.clamped ? ' (clamped to plan max)' : ''}`));
208
351
  }
352
+ case 'previews': {
353
+ need('');
354
+ const r = await api(`/apps/${encodeURIComponent(id)}/previews`);
355
+ const l = r.previews || [];
356
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), branch: x.branch, status: x.status, url: x.url })), columns: ['id', 'branch', 'status', 'url'] });
357
+ }
358
+ case 'preview': {
359
+ const branch = a.positionals[1];
360
+ if (!id || !branch)
361
+ throw new Error('usage: koigrid apps preview <appId> <branch> [--db-branch <dbBranchId>] [--db-env-key KEY]');
362
+ const body = { branch };
363
+ if (a.flags['db-branch'])
364
+ body.dbBranchId = String(a.flags['db-branch']); // branch-per-PR: cablea+borra un branch de BD con el preview
365
+ if (a.flags['db-env-key'])
366
+ body.dbEnvKey = String(a.flags['db-env-key']);
367
+ const r = await api(`/apps/${encodeURIComponent(id)}/previews`, { method: 'POST', body });
368
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Preview deploying → ${r.preview?.url}`));
369
+ }
370
+ case 'rules': {
371
+ need('');
372
+ const r = await api(`/apps/${encodeURIComponent(id)}/rules`);
373
+ const l = r.rules || [];
374
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), type: x.type, source: x.source, to: x.destination || (x.headerName ? `${x.headerName}: ${x.headerValue}` : ''), on: x.enabled ? 'yes' : '' })), columns: ['id', 'type', 'source', 'to', 'on'] });
375
+ }
376
+ case 'rule': {
377
+ const [, type, source, destination] = a.positionals;
378
+ if (!id || !type || !source)
379
+ throw new Error('usage: koigrid apps rule <appId> <redirect|rewrite|header> <source> [dest] [--status 301] [--header-name X --header-value Y]');
380
+ const body = { type, source };
381
+ if (destination)
382
+ body.destination = destination;
383
+ if (a.flags.status)
384
+ body.statusCode = Number(a.flags.status);
385
+ if (a.flags['header-name'])
386
+ body.headerName = String(a.flags['header-name']);
387
+ if (a.flags['header-value'] !== undefined)
388
+ body.headerValue = String(a.flags['header-value']);
389
+ const r = await api(`/apps/${encodeURIComponent(id)}/rules`, { method: 'POST', body });
390
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Rule ${r.rule?.type} ${r.rule?.source} (${String(r.rule?.id).slice(0, 8)})`));
391
+ }
392
+ case 'rule-rm': {
393
+ const rid = a.positionals[1];
394
+ if (!id || !rid)
395
+ throw new Error('usage: koigrid apps rule-rm <appId> <ruleId>');
396
+ await api(`/apps/${encodeURIComponent(id)}/rules/${encodeURIComponent(rid)}`, { method: 'DELETE' });
397
+ return console.log(green(`✓ Deleted rule ${rid}`));
398
+ }
399
+ case 'rule-toggle': {
400
+ const rid = a.positionals[1];
401
+ if (!id || !rid)
402
+ throw new Error('usage: koigrid apps rule-toggle <appId> <ruleId> [--off]');
403
+ const r = await api(`/apps/${encodeURIComponent(id)}/rules/${encodeURIComponent(rid)}`, { method: 'PATCH', body: { enabled: !a.flags.off } });
404
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Rule ${rid} ${a.flags.off ? 'disabled' : 'enabled'}`));
405
+ }
406
+ case 'rename': {
407
+ const name = a.positionals[1];
408
+ if (!id || !name)
409
+ throw new Error('usage: koigrid apps rename <appId> "<new name>"');
410
+ const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { name } });
411
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ App renamed to "${name}"`));
412
+ }
209
413
  default: throw new Error(`unknown: apps ${sub}`);
210
414
  }
211
415
  }
@@ -0,0 +1,45 @@
1
+ import { api } from '../api.js';
2
+ import { output } from '../output.js';
3
+ // koigrid audit — Audit Log (quién hizo qué, con IP y fecha). Sustituto de AWS CloudTrail. owner/admin only.
4
+ // Ver docs/AUDIT-LOG.md.
5
+ // koigrid audit ls [--category members,security] [--type token.created] [--actor-type agent] [--since 30] [--limit 100]
6
+ // koigrid audit export [mismos filtros] > audit.csv
7
+ export async function audit(a) {
8
+ const json = !!a.flags.json;
9
+ const sub = a.sub || 'ls';
10
+ function qs() {
11
+ const p = new URLSearchParams();
12
+ if (a.flags.category)
13
+ p.set('categories', String(a.flags.category));
14
+ if (a.flags.type)
15
+ p.set('types', String(a.flags.type));
16
+ if (a.flags['actor-type'])
17
+ p.set('actorType', String(a.flags['actor-type']));
18
+ if (a.flags.actor)
19
+ p.set('actorId', String(a.flags.actor));
20
+ if (a.flags.since)
21
+ p.set('sinceDays', String(a.flags.since));
22
+ if (a.flags.limit)
23
+ p.set('limit', String(a.flags.limit));
24
+ const s = p.toString();
25
+ return s ? `?${s}` : '';
26
+ }
27
+ if (sub === 'ls' || sub === 'list') {
28
+ const r = await api(`/audit${qs()}`);
29
+ const l = r.entries || [];
30
+ if (!json && !l.length)
31
+ return console.log('No audit entries for these filters yet.');
32
+ return output(l, json, {
33
+ rows: l.map((x) => ({
34
+ at: x.at, action: x.action, actor: `${x.actorType}:${x.actor}`, resource: x.resourceType || '', ip: x.ip || '',
35
+ })),
36
+ columns: ['at', 'action', 'actor', 'resource', 'ip'],
37
+ });
38
+ }
39
+ if (sub === 'export' || sub === 'csv') {
40
+ const csv = await api(`/audit/export${qs()}`, { raw: true });
41
+ process.stdout.write(csv);
42
+ return;
43
+ }
44
+ throw new Error(`unknown: audit ${sub}`);
45
+ }