@feltdb/feltkit 0.3.27 → 0.3.28

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/cli/main.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * The `feltkit` command.
3
3
  */
4
4
  import { spawn } from "node:child_process";
5
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { dirname, extname, join, relative, resolve } from "node:path";
7
7
  import { createHash, randomUUID } from "node:crypto";
8
8
  import { fileURLToPath } from "node:url";
@@ -97,6 +97,8 @@ ${c.bold("Commands")}
97
97
  inspect Show what the application is, where its state lives, and what it's doing
98
98
  deploy Deploy to AppBoundry, or build a verified deployment: one container, an app container + FeltDB, Vercel, Cloudflare, Fly.io
99
99
  status What AppBoundry says about the last deployment from this project
100
+ releases The application's releases on AppBoundry: lineage, rollbacks, which one serves
101
+ rollback Run an earlier release again on AppBoundry (--to <deploymentId>); refused if its schema cannot read today's data
100
102
  vercel <action> Set a Vercel project's environment from FeltDB's values, deploy, and sign you in
101
103
  cloudflare <action> Set a Cloudflare Worker's secrets from FeltDB's values, deploy, and sign you in
102
104
  fly <action> Create the Fly.io app (and volume), set its secrets, deploy, and sign you in
@@ -235,6 +237,10 @@ const COMMAND_HELP = {
235
237
  " FELTKIT_CREDENTIAL_VAULT=1 and FELTKIT_CREDENTIAL_VAULT_KEY are set. FELTKIT_CREDENTIAL_<ID> always wins.\n" +
236
238
  "feltkit credential status [credential-ref:<id>…] [--env development] [--json]\n" +
237
239
  " Every credential reference, what uses it, whether it is set, where, and its version. Never a value.\n" +
240
+ "feltkit credential set <credential-ref:<id>> --oauth\n" +
241
+ " Import an OAuth 2.0 grant: the provider's token response (JSON: access_token, refresh_token, expires_in, scope) at the prompt or on stdin.\n" +
242
+ "feltkit credential connect <integration> [--env development]\n" +
243
+ " Connect an integration's OAuth 2.0 grant (credential.oauth2): prints the provider's authorization address; FeltKit stores and renews the grant.\n" +
238
244
  "feltkit credential remove <credential-ref:<id>|provider> [--env development]\n" +
239
245
  " Erases a stored value (the reference then reports \"revoked\").",
240
246
  config: "feltkit config export [--env development] [--out <file>]\n" +
@@ -246,7 +252,11 @@ const COMMAND_HELP = {
246
252
  " created: attach each listed one in the target and set its FELTKIT_CREDENTIAL_<ID>. Schedules are not imported\n" +
247
253
  " (they run as their creator). Run it on the host, with the server stopped, for production. Exit code 1 on\n" +
248
254
  " conflicts or failures.",
249
- operator: "feltkit operator grant --id <id> --role <role>[,<role>] [--name <display name>] [--ttl <minutes>] [--env production] [--json]\n" +
255
+ operator: "feltkit operator signin [--grant <grant> | --id <id> --role <role>] [--url <server>] [--env production]\n" +
256
+ " Signs in to a running server as an operator. Production commands (inspect, readiness, session list|revoke,\n" +
257
+ " backup create, config set) then run online against it, authorized as that operator, with no stop.\n" +
258
+ "feltkit operator signout\n" +
259
+ "feltkit operator grant --id <id> --role <role>[,<role>] [--name <display name>] [--ttl <minutes>] [--env production] [--json]\n" +
250
260
  " Signs a one-time grant with this environment's operator key (FELTKIT_OPERATOR_KEY from the environment or, for a\n" +
251
261
  " deployment, .env.local; else .feltkit/<env>/operator-key). With a recorded deployment it prints a link that signs\n" +
252
262
  " in with it; otherwise paste it into Studio. It becomes an operator session holding exactly these declared roles.",
@@ -272,8 +282,18 @@ const COMMAND_HELP = {
272
282
  "feltkit session list [--env development]\n" +
273
283
  "feltkit session revoke <ref> [--env development]",
274
284
  };
285
+ function adminHeaders(record, token) {
286
+ if ("operator" in record) {
287
+ const session = record.operator;
288
+ return {
289
+ authorization: `Bearer ${session.token}`, origin: new URL(record.url).origin, "x-feltkit-environment": session.environment,
290
+ "x-feltkit-csrf": createHash("sha256").update(`feltkit-csrf:${session.token}`).digest("base64url").slice(0, 32),
291
+ };
292
+ }
293
+ return { "x-feltkit-admin": token };
294
+ }
275
295
  async function adminRequest(record, token, path, init = {}) {
276
- const response = await fetch(`${record.url}/_feltkit/api${path}`, { ...init, headers: { "x-feltkit-admin": token, "Content-Type": "application/json", ...(init.headers ?? {}) } });
296
+ const response = await fetch(`${record.url}/_feltkit/api${path}`, { ...init, headers: { ...adminHeaders(record, token), "Content-Type": "application/json", ...(init.headers ?? {}) }, ...(init.method && init.method !== "GET" && init.body === undefined ? { body: "{}" } : {}) });
277
297
  const body = (await response.json());
278
298
  if (!response.ok)
279
299
  throw new FeltKitError(body?.error?.code ?? "INTERNAL", body?.error?.message ?? `Admin API answered ${response.status}`);
@@ -281,7 +301,7 @@ async function adminRequest(record, token, path, init = {}) {
281
301
  }
282
302
  /** A running server's backup (POST /backup, NDJSON), passed line by line to `sink`. Returns its header. */
283
303
  async function adminBackup(record, token, sink) {
284
- const response = await fetch(`${record.url}/_feltkit/api/backup`, { method: "POST", headers: { "x-feltkit-admin": token, "Content-Type": "application/json" } });
304
+ const response = await fetch(`${record.url}/_feltkit/api/backup`, { method: "POST", headers: { ...adminHeaders(record, token), "Content-Type": "application/json" }, body: "{}" });
285
305
  if (!response.ok || !response.body) {
286
306
  const body = (await response.json().catch(() => null));
287
307
  throw new FeltKitError(body?.error?.code ?? "INTERNAL", body?.error?.message ?? `Admin API answered ${response.status}`);
@@ -307,10 +327,15 @@ async function adminBackup(record, token, sink) {
307
327
  async function withEnvironment(projectDir, envName, remote, local) {
308
328
  const runtimeDir = join(projectDir, ".feltkit", envName);
309
329
  const record = readRuntimeRecord(runtimeDir);
330
+ // An operator signed in to a running production server (`feltkit operator signin`): online, as that operator.
331
+ const session = envName === "production" ? readOperatorSession(projectDir) : null;
332
+ if (session) {
333
+ return { value: await remote({ url: session.url, operator: { token: session.token, environment: session.environment } }, ""), source: `running server (${session.url}), as operator ${session.operator}` };
334
+ }
310
335
  if (record) {
311
336
  if (envName === "production") {
312
337
  throw new FeltKitError("CONFIGURATION", `A production server is running (pid ${record.pid}). Its admin API answers verified operators only, not the admin token.`, {
313
- hint: "Sign in to Studio with `feltkit operator grant --id <you> --role <role>`, or stop the server to inspect its state directly.",
338
+ hint: "Sign in as an operator, online: `feltkit operator signin --id <you> --role <role> --url <server>`. Or stop the server to inspect its state directly.",
314
339
  });
315
340
  }
316
341
  const token = readAdminToken(runtimeDir);
@@ -334,6 +359,23 @@ async function withEnvironment(projectDir, envName, remote, local) {
334
359
  await runtime.close();
335
360
  }
336
361
  }
362
+ const operatorSessionPath = (projectDir) => join(projectDir, ".feltkit", "production", "operator-session.json");
363
+ function readOperatorSession(projectDir) {
364
+ const path = operatorSessionPath(projectDir);
365
+ if (!existsSync(path))
366
+ return null;
367
+ const session = JSON.parse(readFileSync(path, "utf8"));
368
+ if (session.expiresAt && Date.parse(session.expiresAt) <= Date.now()) {
369
+ rmSync(path, { force: true });
370
+ return null;
371
+ }
372
+ return session;
373
+ }
374
+ function writeOperatorSession(projectDir, session) {
375
+ mkdirSync(join(projectDir, ".feltkit", "production"), { recursive: true });
376
+ writeFileSync(operatorSessionPath(projectDir), JSON.stringify(session, null, 2) + "\n", { mode: 0o600 });
377
+ chmodSync(operatorSessionPath(projectDir), 0o600);
378
+ }
337
379
  function waitForShutdown(close) {
338
380
  return new Promise((done) => {
339
381
  let closing = false;
@@ -826,9 +868,15 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
826
868
  let source;
827
869
  const file = fileSink(partial);
828
870
  try {
829
- if (record) {
871
+ const session = envName === "production" ? readOperatorSession(projectDir) : null;
872
+ if (session) {
873
+ // Online, as the signed-in operator: the running server reads it with calls paused.
874
+ header = await adminBackup({ url: session.url, operator: { token: session.token, environment: session.environment } }, "", file.sink);
875
+ source = `running server (${session.url}; calls paused while it read), as operator ${session.operator}`;
876
+ }
877
+ else if (record) {
830
878
  if (envName === "production")
831
- throw new FeltKitError("CONFIGURATION", `A production server is running (pid ${record.pid}); its admin API answers verified operators only. Stop it to back up its state directly.`);
879
+ throw new FeltKitError("CONFIGURATION", `A production server is running (pid ${record.pid}); its admin API answers verified operators only.`, { hint: "Sign in as an operator to back it up online: `feltkit operator signin --url <server>`. Or stop it to back up its state directly." });
832
880
  const token = readAdminToken(runtimeDir);
833
881
  if (!token)
834
882
  throw new FeltKitError("CONFIGURATION", `A ${envName} server is running (pid ${record.pid}) but its admin token is missing.`);
@@ -975,11 +1023,57 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
975
1023
  line(` Evidence ${c.dim("none yet: AppBoundry reports Running only when the runtime itself names the module")}`);
976
1024
  if (d.failure)
977
1025
  line(` Failure ${d.failure.code}: ${d.failure.message}`);
978
- line(` Address ${d.address ?? c.dim(`none${d.routing?.reason ? `: ${d.routing.reason}` : ""}`)}`);
1026
+ // Running is the runtime; reachable is the route, verified by AppBoundry over HTTPS. Never one for the other.
1027
+ const routing = d.routing;
1028
+ if (routing && routing.status !== "unavailable") {
1029
+ const failure = routing.failure ? `${routing.failure.category} failure: ${routing.failure.code}: ${routing.failure.message}` : "";
1030
+ const state = routing.status === "active" ? c.green(`active, verified over HTTPS${routing.verifiedAt ? ` at ${routing.verifiedAt}` : ""}`) : routing.status === "failed" ? c.red(failure || "failed") : `${routing.status}${routing.reason ? `: ${routing.reason}` : ""}`;
1031
+ line(` Routing ${routing.hostname ? `${routing.hostname} ` : ""}${state}`);
1032
+ }
1033
+ line(` Address ${d.address ?? c.dim(`none${routing?.status === "unavailable" && routing.reason ? `: ${routing.reason}` : routing?.status && routing.status !== "active" ? ": not verified reachable" : ""}`)}`);
979
1034
  if (!s.verified && s.outcome === "pending")
980
1035
  line(c.dim(" Pending: AppBoundry has not observed a ready runtime for this build yet."));
981
1036
  return s.outcome === "failed" ? 1 : 0;
982
1037
  }
1038
+ case "releases": {
1039
+ const { appboundryReleases } = await import("./deploy-appboundry.js");
1040
+ const r = await appboundryReleases({ projectDir, ...(flags.portal ? { connection: { portal: String(flags.portal) } } : {}) });
1041
+ if (json) {
1042
+ line(JSON.stringify({ ok: true, ...r }, null, 2));
1043
+ return 0;
1044
+ }
1045
+ line(`${c.bold(r.applicationId)} on AppBoundry ${c.dim(r.portal)}`);
1046
+ if (!r.releases.length) {
1047
+ line(c.dim(" No deployments yet."));
1048
+ return 0;
1049
+ }
1050
+ for (const rel of r.releases) {
1051
+ const mark = rel.serving ? c.green("● serving") : rel.state === "Failed" ? c.red(rel.state) : rel.state;
1052
+ line(` ${rel.deploymentId} ${mark} artifact ${rel.artifactId.slice(0, 12)}… ${c.dim(rel.requestedAt ?? "")}`);
1053
+ const lineage = [rel.rollbackOf ? `rollback of ${rel.rollbackOf}` : "", rel.previousDeploymentId ? `replaced ${rel.previousDeploymentId}` : "", rel.trust ? `trusted (${rel.trust})` : "", rel.requestedBy ? `by ${rel.requestedBy}` : ""].filter(Boolean).join(" · ");
1054
+ if (lineage)
1055
+ line(c.dim(` ${lineage}`));
1056
+ if (rel.failure)
1057
+ line(c.dim(` ${rel.failure}`));
1058
+ }
1059
+ return 0;
1060
+ }
1061
+ case "rollback": {
1062
+ const { appboundryRollback } = await import("./deploy-appboundry.js");
1063
+ const r = await appboundryRollback({ projectDir, ...(flags.to ? { to: String(flags.to) } : {}), ...(flags.portal ? { connection: { portal: String(flags.portal) } } : {}), ...(json ? {} : { onProgress: (d) => line(` ${c.dim("→")} ${d}`) }) });
1064
+ if (json) {
1065
+ line(JSON.stringify({ ok: r.outcome === "rolled-back", ...r }, null, 2));
1066
+ return r.outcome === "rolled-back" ? 0 : 1;
1067
+ }
1068
+ if (r.outcome === "rolled-back")
1069
+ line(`${symbols.ok} Rolled back: ${r.deployment.deploymentId} runs artifact ${r.deployment.artifactId.slice(0, 16)}… with the runtime's evidence`);
1070
+ else if (r.outcome === "pending")
1071
+ line(`${symbols.info} Requested ${r.deployment.deploymentId}; AppBoundry has not observed it running yet (feltkit status).`);
1072
+ else
1073
+ line(`${symbols.fail} Refused: ${r.deployment.failure ? `${r.deployment.failure.code}: ${r.deployment.failure.message}` : r.deployment.state}. Nothing was rolled back.`);
1074
+ line(` Serving ${r.serving ? `${r.serving.deploymentId} (artifact ${r.serving.artifactId.slice(0, 12)}…)` : c.dim("nothing AppBoundry has verified")}`);
1075
+ return r.outcome === "rolled-back" ? 0 : 1;
1076
+ }
983
1077
  case "deploy": {
984
1078
  // How it will run: --target, else asked in a terminal, else one container.
985
1079
  let target = flags.target ? String(flags.target) : undefined;
@@ -1431,17 +1525,40 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
1431
1525
  if (looksLikeSecret(positional[1]))
1432
1526
  throw new FeltKitError("INVALID_ARGUMENT", "That argument looks like an API key, not a reference. Nothing was stored. Run `feltkit credential set <provider>` and enter the key at the prompt or on stdin.");
1433
1527
  const ref = toCredentialRef(positional[1]);
1434
- const value = await readSecret(`Value for ${ref} (input hidden): `);
1528
+ const oauth = flags.oauth === true || flags.oauth === "true";
1529
+ const value = await readSecret(oauth ? `OAuth 2.0 token response (JSON) for ${ref} (input hidden): ` : `Value for ${ref} (input hidden): `);
1435
1530
  if (!value)
1436
1531
  throw new FeltKitError("INVALID_ARGUMENT", "No value was entered; nothing was stored.");
1437
1532
  const provider = ref.slice("credential-ref:".length);
1438
- const { value: stored, source } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, "/credentials", { method: "POST", body: JSON.stringify({ ref, value, provider }) }).then((b) => b.stored), (runtime) => storeCredential(runtime, { ref, value, provider }, HOST_CUSTODY, "cli"));
1533
+ const kind = oauth ? { kind: "oauth2" } : {};
1534
+ const { value: stored, source } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, "/credentials", { method: "POST", body: JSON.stringify({ ref, value, provider, ...kind }) }).then((b) => b.stored), (runtime) => storeCredential(runtime, { ref, value, provider, ...kind }, HOST_CUSTODY, "cli"));
1439
1535
  if (json)
1440
1536
  line(JSON.stringify(stored, null, 2));
1441
1537
  else
1442
1538
  line(`${symbols.ok} ${envName}: ${stored.ref} set (${stored.location ?? "custody"}, version ${stored.version}) ${c.dim(`— ${source}`)}`);
1443
1539
  return 0;
1444
1540
  }
1541
+ if (action === "connect") {
1542
+ // An integration's OAuth 2.0 grant: the running server starts authorization code with PKCE and
1543
+ // receives the provider's callback; this prints the address to open. Nothing secret is shown.
1544
+ const name = positional[1];
1545
+ if (!name) {
1546
+ line(COMMAND_HELP.credential);
1547
+ return 1;
1548
+ }
1549
+ const { value, source } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, `/integrations/${encodeURIComponent(name)}/connect`, { method: "POST", body: JSON.stringify({}) }), async () => {
1550
+ throw new FeltKitError("FAILED_PRECONDITION", "Connecting needs the running server (it receives the provider's callback). Start it with `feltkit dev` (or sign in as an operator for production), then run this again.");
1551
+ });
1552
+ const v = value;
1553
+ if (json)
1554
+ line(JSON.stringify(v, null, 2));
1555
+ else {
1556
+ line(`${symbols.ok} ${envName}: open this address and approve access ${c.dim(`— ${source}`)}`);
1557
+ line(` ${v.url}`);
1558
+ line(c.dim(` The provider returns to ${v.redirectUri} (register it with the provider). Valid until ${v.expiresAt}, once.`));
1559
+ }
1560
+ return 0;
1561
+ }
1445
1562
  if (action === "remove") {
1446
1563
  if (!positional[1]) {
1447
1564
  line(COMMAND_HELP.credential);
@@ -1477,6 +1594,19 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
1477
1594
  }
1478
1595
  case "config": {
1479
1596
  const action = positional[0];
1597
+ if (action === "set") {
1598
+ // One variable, on the running server, as the signed-in operator (AppPort Services authorizes and records it).
1599
+ const [name, value] = [positional[1], positional[2]];
1600
+ if (!name || value === undefined)
1601
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit config set <NAME> <value> --env production (after `feltkit operator signin`)");
1602
+ const { source } = await withEnvironment(projectDir, envName, (record, token) => {
1603
+ if (!("operator" in record))
1604
+ throw new FeltKitError("FAILED_PRECONDITION", "`config set` changes a running production server as a signed-in operator; in development use Studio → Services → Configuration.");
1605
+ return adminRequest(record, token, `/configuration/${encodeURIComponent(name)}`, { method: "PUT", body: JSON.stringify({ value }) });
1606
+ }, async () => { throw new FeltKitError("FAILED_PRECONDITION", "No signed-in operator session: run `feltkit operator signin` first, or `feltkit config import` with the server stopped."); });
1607
+ line(`${symbols.ok} ${name} set ${c.dim(`— ${source}`)}`);
1608
+ return 0;
1609
+ }
1480
1610
  if (action === "export") {
1481
1611
  const { value, source } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, "/configuration/export"), (runtime) => runtime.services.exportConfiguration());
1482
1612
  const text = `${JSON.stringify(value, null, 2)}\n`;
@@ -1525,6 +1655,51 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
1525
1655
  return 1;
1526
1656
  }
1527
1657
  case "operator": {
1658
+ if (positional[0] === "signout") {
1659
+ const session = readOperatorSession(projectDir);
1660
+ if (session) {
1661
+ await adminRequest({ url: session.url, operator: { token: session.token, environment: session.environment } }, "", "/operator/signout", { method: "POST" }).catch(() => undefined);
1662
+ rmSync(operatorSessionPath(projectDir), { force: true });
1663
+ }
1664
+ line(`${symbols.ok} Signed out${session ? ` of ${session.url}` : ""}.`);
1665
+ return 0;
1666
+ }
1667
+ if (positional[0] === "signin") {
1668
+ // A grant (from --grant, or signed here with the deployment's operator key) becomes an operator session on the
1669
+ // running server. The session token is kept in .feltkit/production/operator-session.json (mode 0600), never printed.
1670
+ const env = String(flags.env ?? "production");
1671
+ let grant = flags.grant ? String(flags.grant) : "";
1672
+ let url = flags.url ? String(flags.url).replace(/\/+$/, "") : "";
1673
+ if (!grant) {
1674
+ if (!flags.id || !flags.role) {
1675
+ line(COMMAND_HELP.operator);
1676
+ return 1;
1677
+ }
1678
+ const link = await studioLink(projectDir, { id: String(flags.id), roles: String(flags.role) });
1679
+ grant = link.grant;
1680
+ if (!url && link.url)
1681
+ url = new URL(link.url).origin;
1682
+ }
1683
+ if (!url)
1684
+ url = readRuntimeRecord(join(projectDir, ".feltkit", env))?.url ?? "";
1685
+ if (!url)
1686
+ throw new FeltKitError("INVALID_ARGUMENT", "No running server to sign in to: pass --url <server URL>.");
1687
+ const response = await fetch(`${url}/_feltkit/api/operator/signin`, { method: "POST", headers: { "content-type": "application/json", origin: new URL(url).origin, "x-feltkit-environment": env }, body: JSON.stringify({ grant }) });
1688
+ const body = (await response.json().catch(() => ({})));
1689
+ if (!response.ok)
1690
+ throw new FeltKitError(body?.error?.code ?? "UNAUTHORIZED", body?.error?.message ?? `Sign-in answered ${response.status}`, {
1691
+ hint: "A production server serves its operator API only when started with FELTKIT_DASHBOARD=1; the grant must be signed with that deployment's operator key and used within its lifetime.",
1692
+ });
1693
+ const cookie = /feltkit_operator[^=]*=([^;]+)/.exec(response.headers.get("set-cookie") ?? "")?.[1];
1694
+ if (!cookie)
1695
+ throw new FeltKitError("INTERNAL", "The server signed the operator in but returned no session.");
1696
+ writeOperatorSession(projectDir, { url, environment: env, token: decodeURIComponent(cookie), operator: String(body.operator?.id ?? ""), expiresAt: String(body.expiresAt ?? "") });
1697
+ if (json)
1698
+ line(JSON.stringify({ ok: true, url, operator: body.operator, permissions: body.permissions, expiresAt: body.expiresAt }, null, 2));
1699
+ else
1700
+ line(`${symbols.ok} Signed in to ${url} as operator ${c.bold(String(body.operator?.id ?? ""))} until ${body.expiresAt}. Production commands now run online, as this operator.`);
1701
+ return 0;
1702
+ }
1528
1703
  if (positional[0] !== "grant" || !flags.id || !flags.role) {
1529
1704
  line(COMMAND_HELP.operator);
1530
1705
  return 1;