@hostr/cli 0.1.4 → 0.2.1

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 (3) hide show
  1. package/README.md +5 -3
  2. package/dist/cli.js +329 -54
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -5,10 +5,12 @@ infrastructure: resumable upload → transcode → HLS delivery with signed
5
5
  playback URLs.
6
6
 
7
7
  ```bash
8
- npx @hostr/cli login # paste an API key from your hostr dashboard
9
- npx @hostr/cli init # write the integration guide + env template into your repo
8
+ npx @hostr/cli # setup status and the next command to run
9
+ npx @hostr/cli login # opens a browser for a human to approve — no key to paste, ever
10
+ npx @hostr/cli init # write the integration guide + env template into your repo
11
+ npx @hostr/cli keys create --name "app dev" --write-env .env.local
10
12
  npx @hostr/cli upload demo.mp4 --wait --json
11
- npx @hostr/cli webhooks set https://yourapp.example/hostr-webhook
13
+ npx @hostr/cli webhooks set https://yourapp.example/hostr-webhook --write-env .env.local
12
14
  npx @hostr/cli tail --follow
13
15
  ```
14
16
 
package/dist/cli.js CHANGED
@@ -3515,10 +3515,10 @@ var init_client = __esm({
3515
3515
  ApiError2 = class extends Error {
3516
3516
  status;
3517
3517
  code;
3518
- constructor(status, code) {
3519
- super(code ? `hostr api error ${status}: ${code}` : `hostr api error ${status}`);
3518
+ constructor(status2, code) {
3519
+ super(code ? `hostr api error ${status2}: ${code}` : `hostr api error ${status2}`);
3520
3520
  this.name = "ApiError";
3521
- this.status = status;
3521
+ this.status = status2;
3522
3522
  this.code = code;
3523
3523
  }
3524
3524
  };
@@ -3570,13 +3570,13 @@ __export(gui_exports, {
3570
3570
  });
3571
3571
  import { createServer } from "node:http";
3572
3572
  import { randomBytes } from "node:crypto";
3573
- import { spawn } from "node:child_process";
3573
+ import { spawn as spawn2 } from "node:child_process";
3574
3574
  async function uploadGui(ctx) {
3575
3575
  const secret = Array.from(randomBytes(16), (b) => b.toString(16).padStart(2, "0")).join("");
3576
3576
  const server = createServer(async (req2, res) => {
3577
3577
  const url = new URL(req2.url ?? "/", "http://localhost");
3578
- const send = (status, body, type = "application/json") => {
3579
- res.writeHead(status, { "content-type": type, "cache-control": "no-store" });
3578
+ const send = (status2, body, type = "application/json") => {
3579
+ res.writeHead(status2, { "content-type": type, "cache-control": "no-store" });
3580
3580
  res.end(body);
3581
3581
  };
3582
3582
  try {
@@ -3637,7 +3637,7 @@ async function uploadGui(ctx) {
3637
3637
  (drop a video in the browser; Ctrl+C here when done)
3638
3638
  `);
3639
3639
  const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
3640
- spawn(opener, [addr], { stdio: "ignore", detached: true }).unref();
3640
+ spawn2(opener, [addr], { stdio: "ignore", detached: true }).unref();
3641
3641
  await new Promise(() => {
3642
3642
  });
3643
3643
  }
@@ -3786,7 +3786,7 @@ async function go(file) {
3786
3786
  const t = await local('/api/playback/' + assetId, { method: 'POST' });
3787
3787
  const mediaHost = API.replace('api.', 'stream.');
3788
3788
  if (t.unavailable) {
3789
- st.innerHTML = 'ready \u2014 asset <span class="mono">' + assetId + '</span><br><span class="hint">key lacks full scope, so no preview token \u2014 mint one server-side to play</span>';
3789
+ st.innerHTML = 'ready \u2014 asset <span class="mono">' + assetId + '</span><br><span class="hint">key lacks playback scope, so no preview token \u2014 mint one server-side to play</span>';
3790
3790
  return;
3791
3791
  }
3792
3792
  const src = mediaHost + '/' + assetId + '.m3u8?token=' + encodeURIComponent(t.playback);
@@ -3834,6 +3834,7 @@ import { mkdir, readFile, writeFile, chmod } from "node:fs/promises";
3834
3834
  import { homedir } from "node:os";
3835
3835
  import { join } from "node:path";
3836
3836
  var DEFAULT_API_BASE = "https://api.hostr.sh";
3837
+ var CLI_VERSION = "0.2.0";
3837
3838
  var configDir = (env = process.env) => env.HOSTR_CONFIG_DIR ?? join(homedir(), ".config", "hostr");
3838
3839
  async function loadConfig(dir = configDir()) {
3839
3840
  try {
@@ -3866,10 +3867,10 @@ function resolveAuth(opts) {
3866
3867
  var ApiError = class extends Error {
3867
3868
  status;
3868
3869
  body;
3869
- constructor(status, body) {
3870
- const msg = body?.error ?? `http_${status}`;
3871
- super(`API error ${status}: ${msg}`);
3872
- this.status = status;
3870
+ constructor(status2, body) {
3871
+ const msg = body?.error ?? `http_${status2}`;
3872
+ super(`API error ${status2}: ${msg}`);
3873
+ this.status = status2;
3873
3874
  this.body = body;
3874
3875
  }
3875
3876
  };
@@ -3918,6 +3919,30 @@ function makeClient(opts) {
3918
3919
  webhookDelete: () => req2("DELETE", "/v1/webhooks")
3919
3920
  };
3920
3921
  }
3922
+ function makeDeviceClient(opts) {
3923
+ const doFetch = opts.fetchFn ?? fetch;
3924
+ const base = opts.apiBase.replace(/\/$/, "");
3925
+ const post = async (path, body) => {
3926
+ const res = await doFetch(`${base}${path}`, {
3927
+ method: "POST",
3928
+ headers: { "content-type": "application/json" },
3929
+ body: JSON.stringify(body)
3930
+ });
3931
+ return { status: res.status, body: await res.json().catch(() => ({})) };
3932
+ };
3933
+ return {
3934
+ async start(b) {
3935
+ const r = await post("/v1/device/code", b);
3936
+ if (r.status !== 201) throw new ApiError(r.status, r.body);
3937
+ return r.body;
3938
+ },
3939
+ async poll(deviceCode) {
3940
+ const r = await post("/v1/device/token", { deviceCode });
3941
+ if (r.status === 200) return { ok: true, value: r.body };
3942
+ return { ok: false, error: String(r.body.error ?? `http_${r.status}`) };
3943
+ }
3944
+ };
3945
+ }
3921
3946
 
3922
3947
  // src/context.ts
3923
3948
  var makeOut = (json) => ({
@@ -3947,7 +3972,7 @@ function fail(out, e) {
3947
3972
  }
3948
3973
 
3949
3974
  // src/commands-account.ts
3950
- import { createInterface } from "node:readline/promises";
3975
+ import { hostname } from "node:os";
3951
3976
 
3952
3977
  // ../control/src/fmt.ts
3953
3978
  function fmtBytes(n) {
@@ -3978,26 +4003,132 @@ function table(rows, cols) {
3978
4003
  ].join("\n");
3979
4004
  }
3980
4005
 
4006
+ // src/device.ts
4007
+ import { spawn } from "node:child_process";
4008
+ function pollAction(errorCode) {
4009
+ switch (errorCode) {
4010
+ case "authorization_pending":
4011
+ return { kind: "wait", addSec: 0 };
4012
+ case "slow_down":
4013
+ return { kind: "wait", addSec: 5 };
4014
+ case "access_denied":
4015
+ return { kind: "stop", error: "authorization was denied in the browser" };
4016
+ case "expired_token":
4017
+ return { kind: "stop", error: "the code expired \u2014 run `hostr login` again" };
4018
+ default:
4019
+ return { kind: "stop", error: `unexpected device-flow error: ${errorCode}` };
4020
+ }
4021
+ }
4022
+ async function awaitApproval(o) {
4023
+ const deadline = o.now() + o.expiresInSec * 1e3;
4024
+ let interval = o.intervalSec;
4025
+ for (; ; ) {
4026
+ const reply = await o.poll();
4027
+ if (reply.ok) return reply.value;
4028
+ const action = pollAction(reply.error);
4029
+ if (action.kind === "stop") throw new Error(action.error);
4030
+ interval += action.addSec;
4031
+ if (o.now() + interval * 1e3 > deadline)
4032
+ throw new Error("the code expired before it was approved \u2014 run `hostr login` again");
4033
+ await o.sleep(interval * 1e3);
4034
+ }
4035
+ }
4036
+ var openBrowser = (addr) => {
4037
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
4038
+ try {
4039
+ spawn(opener, [addr], { stdio: "ignore", detached: true }).unref();
4040
+ } catch {
4041
+ }
4042
+ };
4043
+
4044
+ // src/env-file.ts
4045
+ import { chmod as chmod2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
4046
+ import { basename } from "node:path";
4047
+ var readOrNull = (p) => readFile2(p, "utf8").catch(() => null);
4048
+ function upsertEnvLine(existing, name, value) {
4049
+ const line = `${name}=${value}`;
4050
+ if (existing === null || existing.trim() === "") return `${line}
4051
+ `;
4052
+ const eol = existing.includes("\r\n") ? "\r\n" : "\n";
4053
+ const lines = existing.split("\n");
4054
+ const i = lines.findIndex((l) => l.trimStart().startsWith(`${name}=`));
4055
+ if (i === -1) {
4056
+ const body = existing.replace(/[\r\n]*$/, "");
4057
+ return `${body}${eol}${line}${eol}`;
4058
+ }
4059
+ const hadCR = lines[i].endsWith("\r");
4060
+ lines[i] = hadCR ? `${line}\r` : line;
4061
+ return lines.join("\n");
4062
+ }
4063
+ var patternCovers = (pattern, candidates) => {
4064
+ const body = pattern.replace(/^\//, "");
4065
+ const re = new RegExp(
4066
+ "^" + body.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*") + "$"
4067
+ );
4068
+ return candidates.some((c) => re.test(c));
4069
+ };
4070
+ function gitignoreCovers(gitignore, file) {
4071
+ if (gitignore === null) return false;
4072
+ const candidates = [file.replace(/^\.\//, ""), basename(file)];
4073
+ return gitignore.split("\n").map((l) => l.trim()).filter((l) => l !== "" && !l.startsWith("#") && !l.startsWith("!")).some((l) => patternCovers(l, candidates));
4074
+ }
4075
+ async function isGitignored(file) {
4076
+ return gitignoreCovers(await readOrNull(".gitignore"), file);
4077
+ }
4078
+ async function writeEnvVar(file, name, value) {
4079
+ const next = upsertEnvLine(await readOrNull(file), name, value);
4080
+ await writeFile2(file, next, { mode: 384 });
4081
+ await chmod2(file, 384);
4082
+ return { gitignored: await isGitignored(file) };
4083
+ }
4084
+
3981
4085
  // src/commands-account.ts
3982
4086
  async function login(opts) {
3983
4087
  const out = makeOut(!!opts.json);
3984
- let key = opts.key ?? process.env.HOSTR_API_KEY;
3985
- if (!key) {
3986
- const rl = createInterface({ input: process.stdin, output: process.stderr });
3987
- key = (await rl.question("API key (from your hostr dashboard or `hostr keys create`): ")).trim();
3988
- rl.close();
3989
- }
3990
- if (!key) fail(out, new Error("an API key is required"));
3991
4088
  const cfg = await loadConfig(configDir());
3992
4089
  const apiBase = resolveAuth({ flagApi: opts.api, env: process.env, profile: activeProfile(cfg) }).apiBase;
3993
- const client = makeClient({ apiBase, key });
4090
+ const name = opts.profile ?? "default";
4091
+ const explicit = opts.key ?? process.env.HOSTR_API_KEY;
4092
+ if (explicit) {
4093
+ try {
4094
+ const acct = await makeClient({ apiBase, key: explicit }).account();
4095
+ await saveConfig(setProfile(cfg, name, { key: explicit, apiBase }), configDir());
4096
+ out.print(
4097
+ `logged in to ${acct.name} (plan: ${acct.plan}) as profile "${name}"`,
4098
+ { ok: true, accountId: acct.accountId, name: acct.name, plan: acct.plan, profile: name }
4099
+ );
4100
+ } catch (e) {
4101
+ fail(out, e);
4102
+ }
4103
+ return;
4104
+ }
4105
+ const dev = makeDeviceClient({ apiBase });
3994
4106
  try {
3995
- const acct = await client.account();
3996
- const name = opts.profile ?? "default";
3997
- await saveConfig(setProfile(cfg, name, { key, apiBase }), configDir());
4107
+ const start = await dev.start({ client: `hostr-cli/${CLI_VERSION}`, hostname: hostname() });
4108
+ process.stderr.write(
4109
+ `
4110
+ Your code: ${start.userCode}
4111
+ Approve at: ${start.verificationUriComplete}
4112
+
4113
+ Opening your browser\u2026 waiting for approval.
4114
+ (If you are an agent: hand this URL and code to your human. Do not
4115
+ ask them to paste an API key.)
4116
+
4117
+ `
4118
+ );
4119
+ openBrowser(start.verificationUriComplete);
4120
+ const res = await awaitApproval({
4121
+ poll: () => dev.poll(start.deviceCode),
4122
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
4123
+ intervalSec: start.interval,
4124
+ expiresInSec: start.expiresIn,
4125
+ now: () => Date.now()
4126
+ });
4127
+ await saveConfig(setProfile(cfg, name, { key: res.key, apiBase }), configDir());
3998
4128
  out.print(
3999
- `logged in to ${acct.name} (plan: ${acct.plan}) as profile "${name}"`,
4000
- { ok: true, accountId: acct.accountId, name: acct.name, plan: acct.plan, profile: name }
4129
+ `authorized \u2014 ${res.accountName} (plan: ${res.plan}) as profile "${name}"
4130
+ key stored in ${configDir()}/config.json; revoke it on the Keys page any time`,
4131
+ { ok: true, accountId: res.accountId, name: res.accountName, plan: res.plan, profile: name }
4001
4132
  );
4002
4133
  } catch (e) {
4003
4134
  fail(out, e);
@@ -4048,9 +4179,31 @@ async function keysList(ctx) {
4048
4179
  { items }
4049
4180
  );
4050
4181
  }
4182
+ var parseScopes = (csv) => {
4183
+ const parts = (csv ?? "").split(",").map((s) => s.trim()).filter(Boolean);
4184
+ return parts.length ? parts : ["playback"];
4185
+ };
4051
4186
  async function keysCreate(ctx, opts) {
4052
- const scopes = opts.scopes?.split(",").map((s) => s.trim());
4053
- const k = await ctx.client.keysCreate({ ...opts.name ? { name: opts.name } : {}, ...scopes ? { scopes } : {} });
4187
+ const scopes = parseScopes(opts.scopes);
4188
+ const k = await ctx.client.keysCreate({ ...opts.name ? { name: opts.name } : {}, scopes });
4189
+ if (opts.writeEnv) {
4190
+ let gitignored;
4191
+ try {
4192
+ ({ gitignored } = await writeEnvVar(opts.writeEnv, "HOSTR_API_KEY", k.key));
4193
+ } catch (e) {
4194
+ throw new Error(
4195
+ `key ${k.id} was created, but writing it to ${opts.writeEnv} failed: ${e?.message ?? e}. It is live with nobody holding it \u2014 run \`npx hostr keys list\` and \`npx hostr keys revoke ${k.id}\` to clean it up.`
4196
+ );
4197
+ }
4198
+ ctx.out.print(
4199
+ `wrote HOSTR_API_KEY to ${opts.writeEnv} (value not shown)
4200
+ id ${k.id}
4201
+ scopes ${k.scopes.join(",")}` + (gitignored ? "" : `
4202
+ WARNING: ${opts.writeEnv} does not look gitignored \u2014 do not commit it.`),
4203
+ { ok: true, wrote: "HOSTR_API_KEY", file: opts.writeEnv, id: k.id, scopes: k.scopes, gitignored }
4204
+ );
4205
+ return;
4206
+ }
4054
4207
  ctx.out.print(
4055
4208
  `key ${k.key}
4056
4209
  id ${k.id}
@@ -4071,6 +4224,33 @@ created ${fmtWhen(w.createdAt)}`, w);
4071
4224
  }
4072
4225
  async function webhooksSet(ctx, url, opts) {
4073
4226
  const w = await ctx.client.webhookSet({ url, ...opts.secret ? { secret: opts.secret } : {} });
4227
+ if (opts.writeEnv && w.secret) {
4228
+ let gitignored;
4229
+ try {
4230
+ ({ gitignored } = await writeEnvVar(opts.writeEnv, "HOSTR_WEBHOOK_SECRET", w.secret));
4231
+ } catch (e) {
4232
+ throw new Error(
4233
+ `webhook secret for ${w.url} was set, but writing it to ${opts.writeEnv} failed: ${e?.message ?? e}. Nobody has a copy \u2014 re-run \`npx hostr webhooks set ${url}\` to mint a fresh one, and confirm the write succeeds this time.`
4234
+ );
4235
+ }
4236
+ ctx.out.print(
4237
+ `url ${w.url}
4238
+ enabled ${w.enabled}
4239
+ wrote HOSTR_WEBHOOK_SECRET to ${opts.writeEnv} (value not shown)` + (gitignored ? "" : `
4240
+ WARNING: ${opts.writeEnv} does not look gitignored \u2014 do not commit it.`),
4241
+ { ok: true, url: w.url, enabled: w.enabled, wrote: "HOSTR_WEBHOOK_SECRET", file: opts.writeEnv, gitignored }
4242
+ );
4243
+ return;
4244
+ }
4245
+ if (opts.writeEnv && !w.secret) {
4246
+ ctx.out.print(
4247
+ `url ${w.url}
4248
+ enabled ${w.enabled}
4249
+ nothing written to ${opts.writeEnv} \u2014 you supplied --secret, so the server returned none.`,
4250
+ { ok: true, url: w.url, enabled: w.enabled, wrote: null, file: opts.writeEnv }
4251
+ );
4252
+ return;
4253
+ }
4074
4254
  ctx.out.print(
4075
4255
  `url ${w.url}
4076
4256
  enabled ${w.enabled}` + (w.secret ? `
@@ -4094,11 +4274,11 @@ async function webhooksTest(ctx) {
4094
4274
  }
4095
4275
 
4096
4276
  // src/commands-media.ts
4097
- import { basename } from "node:path";
4277
+ import { basename as basename2 } from "node:path";
4098
4278
  import { stat } from "node:fs/promises";
4099
4279
 
4100
4280
  // ../upload/src/node/index.ts
4101
- import { open, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, unlink } from "node:fs/promises";
4281
+ import { open, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile3, unlink } from "node:fs/promises";
4102
4282
  import { join as join2 } from "node:path";
4103
4283
  import { tmpdir } from "node:os";
4104
4284
 
@@ -4135,9 +4315,9 @@ function classifyPut(res, err) {
4135
4315
  if (err instanceof NetworkError) return "network";
4136
4316
  if (err != null) return "fatal";
4137
4317
  if (res === null) return "network";
4138
- const { status } = res;
4139
- if (status === 403) return "expired";
4140
- if (status === 429 || status >= 500 && status < 600) return "transient";
4318
+ const { status: status2 } = res;
4319
+ if (status2 === 403) return "expired";
4320
+ if (status2 === 429 || status2 >= 500 && status2 < 600) return "transient";
4141
4321
  return "fatal";
4142
4322
  }
4143
4323
  function classifyApi(err) {
@@ -5045,7 +5225,7 @@ function fileStateStore(dir) {
5045
5225
  return {
5046
5226
  async get(key) {
5047
5227
  try {
5048
- return await readFile2(fileFor(key), "utf8");
5228
+ return await readFile3(fileFor(key), "utf8");
5049
5229
  } catch (err) {
5050
5230
  if (err?.code === "ENOENT") return null;
5051
5231
  throw err;
@@ -5053,7 +5233,7 @@ function fileStateStore(dir) {
5053
5233
  },
5054
5234
  async set(key, value) {
5055
5235
  await mkdir2(dir, { recursive: true });
5056
- await writeFile2(fileFor(key), value, "utf8");
5236
+ await writeFile3(fileFor(key), value, "utf8");
5057
5237
  },
5058
5238
  async delete(key) {
5059
5239
  try {
@@ -5190,8 +5370,8 @@ async function subtitlesList(ctx, id) {
5190
5370
  );
5191
5371
  }
5192
5372
  async function subtitlesSet(ctx, id, file, opts) {
5193
- const { readFile: readFile4 } = await import("node:fs/promises");
5194
- const vtt = await readFile4(file, "utf8");
5373
+ const { readFile: readFile6 } = await import("node:fs/promises");
5374
+ const vtt = await readFile6(file, "utf8");
5195
5375
  const r = await ctx.client.subtitleSet(id, opts.lang, vtt, { name: opts.name, default: opts.default });
5196
5376
  ctx.out.print(`subtitle ${r.lang} ("${r.name}") attached to ${r.assetId}${r.default ? " as default" : ""}`, r);
5197
5377
  }
@@ -5222,7 +5402,7 @@ async function upload(ctx, file, opts) {
5222
5402
  const session = await createUploadSession({
5223
5403
  endpoint: ctx.apiBase,
5224
5404
  apiKey,
5225
- filename: basename(file),
5405
+ filename: basename2(file),
5226
5406
  contentType: opts.contentType ?? mimeOf(file),
5227
5407
  size
5228
5408
  });
@@ -5237,7 +5417,7 @@ async function upload(ctx, file, opts) {
5237
5417
  const isTty = process.stderr.isTTY;
5238
5418
  up.on("progress", (p) => {
5239
5419
  const pct = p.totalBytes ? Math.floor(p.bytesConfirmed / p.totalBytes * 100) : 0;
5240
- const line = `uploading ${basename(file)} ${pct}% (${p.partsDone}/${p.partsTotal} parts)`;
5420
+ const line = `uploading ${basename2(file)} ${pct}% (${p.partsDone}/${p.partsTotal} parts)`;
5241
5421
  if (isTty) process.stderr.write(`\r${line} `);
5242
5422
  });
5243
5423
  up.start();
@@ -5263,11 +5443,11 @@ size ${fmtBytes(size)}`,
5263
5443
  }
5264
5444
 
5265
5445
  // src/commands-init.ts
5266
- import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "node:fs/promises";
5446
+ import { mkdir as mkdir3, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
5267
5447
  import { join as join3 } from "node:path";
5268
5448
 
5269
5449
  // ../../docs/integrate.md
5270
- var integrate_default = '# hostr \u2014 integration guide\n\nhostr is self-hosted video infrastructure: resumable upload \u2192 transcode \u2192\nHLS delivery, with signed playback URLs. This document is the complete,\nself-contained integration reference. It is written to be executed by a\ncoding agent; every command has a `--json` mode and every flow is\nverifiable from the terminal.\n\n```\nAPI base https://api.hostr.sh (override: HOSTR_API_BASE)\nMedia host https://stream.hostr.sh (playback URLs are built on this)\nDocs GET {API base}/llms.txt \xB7 GET {API base}/llms-full.txt (this file)\n```\n\n## 0. TL;DR for an integrating agent\n\n```bash\nnpx @hostr/cli login --key $HOSTR_API_KEY # validate + save the key (or export HOSTR_API_KEY)\nnpx @hostr/cli init # write docs/hostr.md + AGENTS.md section + .env.example entries\nnpx @hostr/cli upload demo.mp4 --wait --json # -> { assetId, status: "ready", ... }\nnpx @hostr/cli upload # no file: opens a local drag-drop page in the browser\nnpx @hostr/cli webhooks set https://yourapp.example/hostr-webhook --json # -> { secret: "whsec_..." } ONCE\nnpx @hostr/cli tail --follow # watch the event log live\n```\n\nThen in your app: store `assetId`/`playbackId` per video, mint playback\ntokens server-side (\xA76), and hand players\n`{Media host}/{playbackId}.m3u8?token=\u2026`. Verify webhooks with the snippet\nin \xA75. That is the whole integration.\n\n## 1. Authentication\n\nEvery API call sends `Authorization: Bearer <credential>`. There are two\ncredential kinds an integrator sees:\n\n- **API key** \u2014 `hostr_sk_live_\u2026`, minted per account in the hostr\n dashboard or via `POST /v1/keys` / `npx @hostr/cli keys create`. Scoped:\n - `read` \u2014 GETs only (status, listing, usage, events)\n - `upload` \u2014 read + the upload lifecycle\n - `full` \u2014 everything, including playback-token minting and key management\n Keys are hashed at rest; the plaintext is shown exactly once at mint.\n Rotation = create new + revoke old (`DELETE /v1/keys/:id`); revocation\n takes effect within ~60 s. **Keep keys server-side.** Never ship one in a\n browser or mobile app.\n- **Upload token** \u2014 short-lived HMAC scoped to a single upload\n (`uploadToken` in the create-upload response). This is the only\n credential an untrusted client (browser/mobile) should ever hold: it can\n drive that one upload and nothing else.\n\nAuth errors: `401 {"error":"unauthorized"}` (bad/missing/revoked key, or a\nresource you don\'t own \u2014 hostr does not reveal which),\n`403 {"error":"insufficient_scope","need":"upload"}`,\n`403 {"error":"account_suspended"}`,\n`503 {"error":"control_plane_unavailable"}` (transient \u2014 retry with backoff;\nin-flight uploads with upload tokens are unaffected).\n\n## 2. Upload\n\nThree ways, strongest first:\n\n### 2a. CLI (recommended \u2014 resumable, integrity-checked)\n\n```bash\nnpx @hostr/cli upload path/to/video.mp4 --json # returns when bytes are verified in R2\nnpx @hostr/cli upload path/to/video.mp4 --wait --json # returns when transcode is ready/failed\n```\n\nOutput: `{ "assetId": "\u2026", "status": "queued"|"ready", "bytes": n, "etag": "\u2026", "sha256": "\u2026" }`.\nThe CLI wraps hostr\'s upload SDK: chunked multipart direct to storage,\nresume after crash/restart (server-authoritative \u2014 it asks storage which\nparts landed), retry with backoff, and three-layer integrity verification.\nExit code 1 + JSON on stderr on failure.\n\n### 2b. Raw HTTP (any language, no SDK)\n\n```\nPOST /v1/uploads {"filename":"a.mp4","size":<bytes>,"contentType":"video/mp4"}\n -> 201 { assetId, partSize, expectedParts, uploadToken, tokenExpiresAt, key, uploadId }\n (forward ONLY assetId/uploadToken/partSize/expectedParts/tokenExpiresAt to untrusted clients)\n\nPOST /v1/uploads/:id/parts {"partNumbers":[1,2,...]} (\u2264100 per call)\n -> { urls: [{partNumber, url}], expiresIn }\nPUT <each presigned url> body = that part\'s bytes; capture the ETag response header\n\nGET /v1/uploads/:id -> { status, uploadedParts, parts, bytesUploaded } (resume)\nPOST /v1/uploads/:id/complete {"sha256":"<hex of whole file>"} (sha256 optional)\n -> { assetId, status: "uploaded"|"queued", bytes, etag }\nDELETE /v1/uploads/:id abort\nPOST /v1/uploads/:id/token re-mint the upload token (API key with upload scope)\n```\n\nRules: every part is `partSize` bytes except the last; `size` must be\nexact \u2014 completion verifies both part count and total bytes against what\nactually landed and returns `409 incomplete_upload` (with the missing part\nnumbers) or `409 size_mismatch` otherwise. Completion is idempotent \u2014 a\ncrashed client retries it safely. Uploads are quota-gated:\n`403 {"error":"quota_uploads_daily"|"quota_assets"|"quota_storage","limit":n}`.\n\n### 2c. Browser/mobile clients\n\nCreate the upload server-side (2b), hand the client only\n`{assetId, uploadToken, partSize, expectedParts}`, and let it PUT parts\ndirectly to the presigned URLs \u2014 upload bytes never touch your servers.\n(A browser needs the storage bucket to allow your origin via CORS \u2014 if\npart PUTs stall at 0% with network-looking errors, that\'s the cause.)\n\n## 3. Asset lifecycle\n\n`uploading \u2192 uploaded \u2192 queued \u2192 processing \u2192 ready | failed` (plus\n`aborted`). Poll `GET /v1/assets/:id` (`read` scope) or \u2014 better \u2014 use\nwebhooks (\xA75). While `processing`, the asset carries live transcode\nprogress \u2014 `progress: { encodedSec, totalSec, speed }` (speed is the\nencode multiple of realtime; the field is null/absent outside\n`processing`) \u2014 so a UI can show a real percentage instead of a spinner. `GET /v1/assets?limit=&status=&cursor=` lists your assets\nnewest-first with keyset pagination (`nextCursor`).\n\nWhen `ready`, the asset record and the `video.ready` event both carry\n`playbackId` (equals `assetId` today \u2014 store it as its own field) and\n`durationSec`.\n\n## 4. Account, usage, keys\n\n```\nGET /v1/account -> { accountId, name, plan, limits, usage } (read)\nGET /v1/usage?from&to -> { days: [{day, uploads, bytesUploaded, encodedSeconds}] } (read)\nPOST /v1/keys {"name":"ci","scopes":["upload"]} -> { key: "hostr_sk_live_..." } ONCE (full)\nGET /v1/keys -> metadata only, never hashes (full)\nDELETE /v1/keys/:id -> { revoked: true } (full)\n```\n\n## 5. Webhooks + the event log\n\nConfigure one endpoint per account:\n\n```\nPUT /v1/webhooks {"url":"https://yourapp.example/hostr-webhook"} (full)\n -> { url, enabled, secret: "whsec_..." } # secret returned ONLY when generated, ONLY once\nGET /v1/webhooks -> { url, enabled, createdAt } # never the secret\nDELETE /v1/webhooks -> disables (delivery history retained)\n```\n\nEvents \u2014 body `{ id, type, createdAt, data }`; `id` is the durable event\nrow\'s id (dedupe on it):\n\n| type | fired when | data highlights |\n|------------------|----------------------------------------|------------------------------------------|\n| `upload.created` | multipart session opened | `assetId`, `filename`, `declaredSize` |\n| `video.uploaded` | bytes verified in storage, transcode queued | `assetId`, `bytes`, `etag`, `sha256?` |\n| `video.ready` | HLS renditions live | `assetId`, `playbackId`, `durationSec?` |\n| `video.errored` | transcode failed | `assetId`, `error` (always present) |\n| `video.deleted` | asset erased; playback over | `assetId` |\n| `video.input.non_standard` | the source needed a judgement call | `assetId`, `input`, `findings[]` |\n\n`video.input.non_standard` is advisory \u2014 the transcode proceeds normally and\na `video.ready` still follows. It fires at most once per asset, only when\nthere is something to say, and reports what the encoder had to assume:\n\n| finding code | meaning |\n|----------------------|-------------------------------------------------------------------------|\n| `hdr_tags_on_8bit` | source carries HLG/PQ tags but is 8-bit. HDR is a 10-bit format, so the tag is stale \u2014 treated as SDR, pixels untouched |\n| `hdr_source` | genuine 10-bit HDR. The ladder outputs 8-bit SDR; no tone mapping is applied |\n| `wide_gamut_tags` | BT.2020 primaries without an HDR transfer; output is BT.709, colour not converted |\n| `variable_frame_rate`| container rate and measured rate disagree; normalised to CFR |\n| `frame_rate_changed` | source rate was not a broadcast standard and was snapped to the nearest |\n\n`data.input` carries the full probe: `videoCodec`, `pixFmt`, `bitDepth`,\n`width`, `height`, `declaredFps`, `averageFps`, `targetFps`,\n`isVariableFrameRate`, `colorSpace`, `colorTransfer`, `colorPrimaries`. The\nsame block is on the asset record as `input`, so it can be read back at any\ntime without replaying events.\n\nEndpoint URLs: both `https` and `http` are accepted, including private\naddresses \u2014 hostr does not currently block internal ranges, so a local\nreceiver works in development exactly like production.\n\nEvery delivery carries `hostr-signature`, a comma-separated list currently\ncontaining `t=<unix-seconds>` and `v1=<hex>` where\n`v1 = HMAC-SHA256(secret, "<t>.<rawBody>")` \u2014 the Stripe scheme. Parse it\nas a list (future fields may be added); verify before trusting\n(constant-time compare, bounded timestamp):\n\n```js\nimport { createHmac, timingSafeEqual } from \'node:crypto\';\n\nexport function verifyHostrWebhook(secret, header, rawBody, toleranceSec = 300) {\n const m = /^t=(\\d+),v1=([0-9a-f]{64})$/.exec(header ?? \'\');\n if (!m) return false;\n if (Math.abs(Date.now() / 1000 - Number(m[1])) > toleranceSec) return false;\n const expected = createHmac(\'sha256\', secret).update(`${m[1]}.${rawBody}`).digest(\'hex\');\n return expected.length === m[2].length &&\n timingSafeEqual(Buffer.from(expected), Buffer.from(m[2]));\n}\n// Use the RAW request body bytes \u2014 parse JSON only after verification.\n```\n\nDelivery is at-least-once (3 attempts with backoff, each recorded). The\nwebhook is the wake-up signal; the **durable event log** is the ledger:\n\n```\nGET /v1/events?after=<cursor>&limit=&type= ascending; reuse nextCursor verbatim (read)\nGET /v1/events?order=desc&limit=1 newest first (e.g. the latest event) (read)\nPOST /v1/events/:id/redeliver replay any stored event (full)\n```\n\n`npx @hostr/cli tail --follow` polls this for you; `npx @hostr/cli webhooks test`\nredelivers the newest event to prove your endpoint end-to-end. Respond\n`2xx` fast (do the work async) \u2014 anything else is retried.\n\n## 6. Playback\n\nPlayback is token-gated. Mint per view, server-side, with a `full` key:\n\n```\nPOST /v1/assets/:id/tokens {"ttlSec":3600,"viewerId":"user-123"} (optional body)\n -> { playback, thumbnail, storyboard, expiresAt } (expiresAt in ms)\nnpx @hostr/cli assets token <assetId> --json (CLI equivalent)\n```\n\nMinting works any time after the asset exists (it 404s only for unknown\nassets); the stream itself returns 404 until the asset is `ready` \u2014 gate\nyour UI on `video.ready` / asset status, not on whether minting succeeds.\n\nBuild the URL and hand it to any HLS player:\n\n```\nhttps://stream.hostr.sh/{playbackId}.m3u8?token={playback}\n```\n\n- Use hls.js in browsers without native HLS; Safari/iOS play it natively.\n- The token is checked once at the master playlist; the stream then works\n for the whole viewing session (segment credentials are handled\n internally). Default TTL 1 h \u2014 it only needs to be valid when playback\n *starts*.\n- `viewerId` enables per-viewer concurrency observation.\n- **Non-browser user agents are rejected** (`403 blocked_user_agent`):\n curl/wget/ffmpeg/vlc UAs are blocked as a casual-ripping speed bump. For\n server-side smoke tests send a browser-like `User-Agent`.\n- Signed URLs are not DRM: they stop link-sharing and hotlinking, not an\n entitled viewer recording their screen.\n- `DELETE /v1/assets/:id` erases an asset for good: source and renditions\n are purged from storage, the storage quota is freed, and `video.deleted`\n is emitted. Deletion is idempotent (repeat calls return `deleted`\n again). New playback tokens stop minting immediately; tokens already\n issued can replay edge-cached segments for at most a few hours until\n they expire. There is no undelete.\n\nThe token bundle also covers the poster image and scrub previews \u2014 same\nhost, same query-token shape, each URL taking its matching token from the\nmint response:\n\n```\nhttps://stream.hostr.sh/{playbackId}/thumbnail.jpg?token={thumbnail}\nhttps://stream.hostr.sh/{playbackId}/storyboard.vtt?token={storyboard}\n```\n\nThe storyboard is a standard "thumbnails" WebVTT track (cues point into a\ntiled sprite with `#xywh=` fragments) \u2014 hand it to mux-player\'s\n`storyboard-src`, media-chrome\'s preview track, or any player that consumes\nthat convention; the sprite URLs inside the VTT are pre-signed for you.\nPlayers treat the track as optional: for assets encoded before storyboards\nexisted the URL 404s and scrubbing simply shows no preview.\n\n## 6b. Subtitles\n\nHuman-authored WebVTT tracks, attached any time after the asset is `ready`\n(409 `not_ready` before that \u2014 the playlist needs the duration):\n\n```\nPUT /v1/assets/:id/subtitles/:lang?name=English&default=true (body: raw WebVTT, upload scope)\nGET /v1/assets/:id/subtitles -> { tracks: [{ lang, name, default, rev }] }\nDELETE /v1/assets/:id/subtitles/:lang\nnpx @hostr/cli subtitles set <assetId> subs.vtt --lang en --name English --default\n```\n\n- `:lang` is a BCP 47 tag (`en`, `pt-BR`); one track per tag, PUT replaces.\n- Tracks appear in the master playlist automatically (`EXT-X-MEDIA`\n subtitles group) \u2014 the next master fetch after a PUT includes them, no\n re-encode, no new playback URL. Players show them in the captions menu.\n- `default=true` demotes any previous default.\n- Replacements propagate on the next playback session; a viewer mid-session\n keeps the track they started with.\n\n## 7. Error handling summary\n\n| status | error | meaning / action |\n|--------|------------------------------|------------------|\n| 401 | `unauthorized` | bad/revoked key, or not your resource \u2014 check key + assetId |\n| 403 | `insufficient_scope` | key scope too low; `need` names the required scope |\n| 403 | `quota_*` | account limit hit; `limit` is the ceiling |\n| 403 | `account_suspended` | contact the operator |\n| 409 | `incomplete_upload` | parts missing (`missing` lists them) \u2014 upload them, re-complete |\n| 409 | `size_mismatch` | declared size \u2260 bytes landed \u2014 abort and restart |\n| 409 | `not_uploading` | upload already finished/aborted |\n| 413 | `file_too_large` | raise `partSize` or split |\n| 503 | `control_plane_unavailable` | transient \u2014 retry with backoff |\n| 500 | `signing_not_configured` | operator-side: the playback signing key isn\'t loaded on this API deployment. Not your integration\'s fault and not retryable from the client \u2014 report it |\n\n## 8. Full route table\n\n| Method | Path | Scope | Purpose |\n|---|---|---|---|\n| POST | `/v1/uploads` | upload | create upload session |\n| GET | `/v1/uploads/:id` | upload* | status + landed parts (resume) |\n| POST | `/v1/uploads/:id/parts` | upload* | presigned part URLs |\n| POST | `/v1/uploads/:id/complete` | upload* | verify + finalize |\n| POST | `/v1/uploads/:id/token` | upload | re-mint upload token |\n| DELETE | `/v1/uploads/:id` | upload* | abort |\n| GET | `/v1/assets` | read | list own assets |\n| GET | `/v1/assets/:id` | read | asset record |\n| POST | `/v1/assets/:id/tokens` | full | playback credentials |\n| DELETE | `/v1/assets/:id` | full | erase asset: R2 purged, quota freed, `video.deleted` emitted |\n| PUT | `/v1/assets/:id/subtitles/:lang` | upload | attach/replace WebVTT track |\n| GET | `/v1/assets/:id/subtitles` | read | list subtitle tracks |\n| DELETE | `/v1/assets/:id/subtitles/:lang` | upload | remove subtitle track |\n| GET | `/v1/account` | read | whoami: plan, limits, usage |\n| GET | `/v1/usage` | read | daily usage rows |\n| GET | `/v1/events` | read | durable event log (ascending tail; `order=desc` for newest-first) |\n| POST | `/v1/events/:id/redeliver` | full | replay a webhook |\n| GET/PUT/DELETE | `/v1/webhooks` | full | endpoint config |\n| POST/GET | `/v1/keys` | full | mint / list keys |\n| DELETE | `/v1/keys/:id` | full | revoke key |\n\n\\* also accepted: that upload\'s own `uploadToken`.\n\n## 9. CLI reference\n\n`npx @hostr/cli <cmd>` \u2014 every command takes `--json` (one JSON document on\nstdout; NDJSON for `tail --follow`; errors as JSON on stderr, exit 1).\nCredentials: `--key` flag > `HOSTR_API_KEY` env > saved profile\n(`hostr login`). API base: `--api` > `HOSTR_API_BASE` > profile > default.\n\n```\nlogin \xB7 whoami \xB7 usage \xB7 init\nkeys create|list|revoke\nwebhooks get|set|delete|test\nassets list|get \xB7 assets token <id> [--ttl <sec>] \xB7 upload <file> [--wait] \xB7 tail [--follow]\n```\n';
5450
+ var integrate_default = '# hostr \u2014 integration guide\n\n<!-- GENERATED FILE \u2014 DO NOT EDIT.\n Source: apps/docs/src/content/docs/** (pages with `agentGuide: true`)\n packages/openapi/src/spec.ts (the route table)\n Regenerate: pnpm build:agent-guide \xB7 CI checks this with --check -->\n\nhostr is self-hosted video infrastructure: resumable upload \u2192 transcode \u2192\nHLS delivery, with signed playback URLs. This document is the complete,\nself-contained integration reference. It is written to be executed by a\ncoding agent; every command has a `--json` mode and every flow is\nverifiable from the terminal.\n\n```\nAPI base https://api.hostr.sh (override: HOSTR_API_BASE)\nMedia host https://stream.hostr.sh (playback URLs are built on this)\nDocs https://docs.hostr.sh \xB7 GET {API base}/llms-full.txt (this file)\n```\n\nRun `npx @hostr/cli` in your app\'s repo. With no arguments it reports what is\nconfigured and names the single next step \u2014 authorize, prepare the repo, mint\nan application key \u2014 and it is the intended entry point for a coding agent.\nThis document is the *reference*: consult it while implementing, section by\nsection, rather than reading it front to back.\n\n## Quickstart\n\nBases you will need:\n\n```\nAPI base https://api.hostr.sh (override with HOSTR_API_BASE)\nMedia host https://stream.hostr.sh (playback URLs are built on this)\n```\n\n### 1. Authorize\n\n```bash\nnpx @hostr/cli login\n```\n\nThis opens your browser and mints the CLI\'s own key once you approve it. Nothing\nis pasted, which matters when a coding agent is driving your terminal \u2014 a key\ntyped into an agent\'s session lands in its context and its transcript.\n\nThe key appears on the dashboard Keys page as `CLI \u2014 <hostname>` and is revocable\nlike any other. For CI, `--key <k>` or `HOSTR_API_KEY` skips the browser.\n\nConfirm it worked:\n\n```bash\nnpx @hostr/cli whoami --json\n```\n\n### 2. Upload\n\n```bash\nnpx @hostr/cli upload video.mp4 --wait --json\n```\n\n`--wait` blocks until the transcode reaches `ready` or `failed`. Without it the\ncommand returns as soon as the bytes are verified in storage.\n\n```json\n{ "assetId": "9f8c1e2a4b6d47f0a1b2c3d4e5f60718", "status": "ready", "bytes": 104857600 }\n```\n\nThe upload is resumable. Kill it mid-transfer and run it again \u2014 it asks storage\nwhich parts landed and continues from there.\n\n### 3. Play it\n\nMint a playback token, then build the URL:\n\n```bash\nnpx @hostr/cli assets token 9f8c1e2a4b6d47f0a1b2c3d4e5f60718 --json\n```\n\n```json\n{ "playback": "eyJhbGci...", "thumbnail": "...", "storyboard": "...", "expiresAt": 1756134000000 }\n```\n\n```\nhttps://stream.hostr.sh/{assetId}.m3u8?token={playback}\n```\n\nHand that to any HLS player. Safari and iOS play it natively; elsewhere use\nhls.js.\n\nThe token is checked once, when playback starts. It does not need to stay valid\nfor the whole viewing session, and the default one-hour lifetime is not a\none-hour viewing limit.\n\n### 4. Wire up events, not polling\n\n```bash\nnpx @hostr/cli webhooks set https://yourapp.example/hostr-webhook --write-env .env\n```\n\nThe signing secret is generated, written to `.env`, and never printed \u2014 only the\nvariable name is. Then verify signatures before trusting a delivery: see\n[Verifying webhooks](#verifying-webhook-signatures).\n\nProve your endpoint end to end without uploading anything else:\n\n```bash\nnpx @hostr/cli webhooks test\n```\n\n### No Node available?\n\nEvery flow here has a raw-HTTP equivalent. Start at\n[Upload from a server](#upload-from-a-server).\n\n## Authentication\n\nEvery call sends `Authorization: Bearer <credential>` over HTTPS. There are three\ncredential classes and **no shared master key**.\n\n### API keys\n\n`hostr_sk_live_\u2026`, minted per account. SHA-256-hashed at rest; the plaintext is\nshown exactly once, at mint. Verified in constant time and cached about 60 seconds\nin the edge Worker \u2014 so **revocation takes up to a minute** to take effect.\n\nScopes are a ladder, each rung including the ones below:\n\n| Scope | Grants |\n|---|---|\n| `read` | GETs only \u2014 asset status, listing, usage, events |\n| `upload` | read, plus the whole upload lifecycle |\n| `playback` | upload, plus minting playback tokens |\n| `full` | everything: deletion, key management, webhook config |\n\n**`playback` is what an application key should be.** It can ingest video and it\ncan let viewers watch, but it cannot delete assets or mint more keys. Reach for\n`full` only where you actually manage the account.\n\n**Keep keys server-side.** Never ship one in a browser or a mobile app.\n\nRotate by creating the new key and revoking the old one:\n\n```bash\nnpx @hostr/cli keys create --name ci --scopes upload --write-env .env\nnpx @hostr/cli keys revoke <old-id>\n```\n\nRevoking the key that makes the request is allowed \u2014 it is rotation\'s last step.\n\n### Upload tokens\n\nA stateless HMAC scoped to a single `assetId`, returned as `uploadToken` from\n`POST /v1/uploads`. **This is the only credential an untrusted client should ever\nhold.** It can drive that one upload and nothing else \u2014 it grants nothing on\nplayback, and nothing on any other asset.\n\nTokens expire. For uploads that outlive one, re-mint in place with\n`POST /v1/uploads/:id/token` (an API key with `upload` scope, not the expiring\ntoken itself) \u2014 no progress is lost. The SDK does this for you through its\n`onTokenExpired` hook.\n\n### Service key\n\nThe internal transcoder credential. Never issued to tenants; documented only so\nits one route is not mistaken for a public one.\n\n### Login without pasting a key\n\n```bash\nnpx @hostr/cli login\n```\n\nBrowser-authorized, using the RFC 8628 device flow. The CLI never accepts a\npasted key from a human or an agent, for the reason given in the\n[quickstart](#quickstart). `--key` and `HOSTR_API_KEY` remain the escape\nhatch for CI and other headless callers.\n\nCredential precedence everywhere: `--key` flag, then `HOSTR_API_KEY`, then the\nsaved profile.\n\n### Auth errors\n\n| Status | Error | Meaning |\n|---|---|---|\n| 401 | `unauthorized` | Bad, missing, or revoked credential \u2014 **or a resource you do not own.** hostr does not reveal which |\n| 403 | `insufficient_scope` | Scope too low; `need` names the rung required |\n| 403 | `account_suspended` | Contact the operator |\n| 503 | `control_plane_unavailable` | Transient. Retry with backoff |\n\nThat 401 conflation is deliberate: distinguishing "wrong key" from "not your\nasset" would let anyone with a valid key enumerate other accounts\' asset ids.\n\n**`control_plane_unavailable` fails closed for API keys only.** If the control\nplane is unreachable, key-authenticated calls 503 \u2014 but in-flight uploads using\nupload tokens keep working, and playback is untouched, because the media Worker\nnever queries it.\n\n## Assets and lifecycle\n\nAn asset is created when you open an upload and lives until you erase it.\n\n```\nuploading -> uploaded -> queued -> processing -> ready\n \\-> failed\n \\-> aborted (deleted, from anywhere)\n```\n\n| Status | Means |\n|---|---|\n| `uploading` | Multipart session open, parts landing |\n| `uploaded` | Bytes verified against storage; part count and total size both agree |\n| `queued` | Handed to the transcode queue |\n| `processing` | Encoding. Carries live `progress` |\n| `ready` | HLS renditions are live and playable |\n| `failed` | Transcode failed. `error` is always present |\n| `aborted` | Upload abandoned before completion |\n| `deleted` | Erased. Terminal and irreversible |\n\n### Reading progress\n\nWhile `processing`, the record carries\n`progress: { encodedSec, totalSec, speed }`, where `speed` is the encode rate as\na multiple of realtime. Outside `processing` it is null or absent \u2014 a terminal\nstatus never shows a stale bar.\n\nThat is enough for a real percentage instead of a spinner, which matters more\nthan it sounds: most "the transcode is slow" reports turn out to be missing\nprogress feedback rather than slow encoding.\n\n### Prefer events to polling\n\n`GET /v1/assets/:id` returns the authoritative record, and\n`GET /v1/assets?limit=&status=&cursor=` lists your assets newest-first with\nkeyset pagination. But polling is the fallback, not the design \u2014\n[webhooks](#webhooks-and-the-event-log) push the same transitions.\n\n### playbackId is its own field\n\nWhen an asset reaches `ready`, both the record and the `video.ready` event carry\n`playbackId` and `durationSec`.\n\n`playbackId` equals `assetId` today. **Store it as its own field anyway.** It is\nnamed separately so the two can diverge later without forcing a migration on\nevery consumer.\n\n### Deletion\n\n`DELETE /v1/assets/:id` purges the source and every rendition from storage, frees\nthe storage quota, and emits `video.deleted`. Idempotent \u2014 repeat calls report\n`deleted` again with `objectsDeleted: 0`.\n\nNew playback tokens stop minting immediately. Tokens already issued can replay\nedge-cached segments for at most a few hours until they expire. **There is no\nundelete.**\n\n## Quotas and limits\n\nAccounts carry three ceilings, visible any time:\n\n```bash\nnpx @hostr/cli whoami --json # or: GET /v1/account\n```\n\n```json\n{\n "limits": { "maxAssets": 10000, "maxSourceBytes": 5497558138880, "maxUploadsPerDay": 500 },\n "usage": { "assetCount": 1711, "storageBytes": 742381129728, "uploadsToday": 12 }\n}\n```\n\n| Limit | Counts |\n|---|---|\n| `maxAssets` | Assets held at once. Deletion frees this immediately |\n| `maxSourceBytes` | Total source bytes stored |\n| `maxUploadsPerDay` | Upload sessions created per UTC day |\n\n### Hitting one\n\nQuotas are checked when the upload is created, not when bytes arrive. A tripped\nquota is a `403` naming which one and its ceiling:\n\n```json\n{ "error": "quota_storage", "limit": 5497558138880 }\n```\n\nThe three codes are `quota_uploads_daily`, `quota_assets`, and `quota_storage`.\n\n**This means the account needs raising, not that the request was malformed.**\nDistinguish it from a `400` in your error handling \u2014 retrying a quota error\nwithout changing anything will fail identically forever.\n\n### Request-shaped limits\n\nThese are properties of the API rather than of your plan:\n\n| Limit | Value |\n|---|---|\n| Parts per presign request | 100 |\n| Parts per upload | 10,000 (a storage limit; raise `partSize` for very large files) |\n| Subtitle file size | 2,000,000 bytes |\n| Playback token lifetime | 60 s to 86,400 s, default 3,600 |\n| Event page size | 1 to 200, default 50 |\n\nExceeding the part ceiling for a given part size is `413 file_too_large`, and the\nresponse carries the maximum byte count that part size can address.\n\n### Usage over time\n\n```\nGET /v1/usage?from=2026-08-01&to=2026-08-25 (read)\n -> { from, to, days: [{ day, uploads, bytesUploaded, encodedSeconds }] }\n```\n\nDefaults to the last 30 days. Dates are UTC and must be `YYYY-MM-DD`; anything\nelse is `400 bad_date`.\n\n### Not your fault\n\nTwo failures look like integration bugs and are not:\n\n`503 control_plane_unavailable` is transient \u2014 retry with backoff. In-flight\nuploads holding upload tokens are unaffected, and playback is untouched.\n\n`500 signing_not_configured` means the playback signing key is not loaded on the\nAPI deployment. It is operator-side and not retryable from a client. Report it\nrather than working around it.\n\n## Upload from a server\n\nFour calls. Bytes go straight to storage via presigned URLs and never transit\nhostr\'s compute.\n\n```\nPOST /v1/uploads {"filename":"a.mp4","size":<bytes>,"contentType":"video/mp4"}\n -> 201 { assetId, partSize, expectedParts, uploadToken, tokenExpiresAt, key, uploadId }\n\nPOST /v1/uploads/:id/parts {"partNumbers":[1,2,3]} (at most 100 per call)\n -> { urls: [{ partNumber, url }], expiresIn }\n\nPUT <each presigned url> body = that part\'s bytes; capture the ETag response header\n\nPOST /v1/uploads/:id/complete {"sha256":"<hex of the whole file>"} (sha256 optional)\n -> { assetId, status: "uploaded"|"queued", bytes, etag }\n```\n\nPlus `GET /v1/uploads/:id` for resume and `DELETE /v1/uploads/:id` to abort.\n\n### The rules that bite\n\n**Every part is exactly `partSize` bytes except the last.** Use the `partSize`\nthe server returned, not one you picked.\n\n**`size` must be exact.** Completion verifies both the part count and the total\nbyte count against what actually landed. Mismatches are `409`:\n\n- `incomplete_upload` \u2014 `missing` lists the absent part numbers, first 50. Upload\n them and complete again.\n- `size_mismatch` \u2014 `declaredSize` and `receivedBytes` are both reported. Abort\n and restart; the file you declared is not the file you sent.\n\nPart count alone would accept N parts of the wrong sizes, which is why both are\nchecked.\n\n**Request presigned URLs only for the parts you are about to send.** They expire.\nMinting all of them up front for a large file wastes most of them.\n\n**Completion is idempotent.** A client that crashed after bytes landed but before\nit saw the response can safely retry and will get the stored result back rather\nthan a conflict.\n\n### Worked example\n\n```bash\nAPI=https://api.hostr.sh\nKEY=$HOSTR_API_KEY\nFILE=video.mp4\nSIZE=$(wc -c < "$FILE")\n\n# 1. Create the session.\nCREATE=$(curl -sS -X POST "$API/v1/uploads" \\\n -H "authorization: Bearer $KEY" -H \'content-type: application/json\' \\\n -d "{\\"filename\\":\\"$FILE\\",\\"contentType\\":\\"video/mp4\\",\\"size\\":$SIZE}")\n\nASSET=$(echo "$CREATE" | jq -r .assetId)\nPART_SIZE=$(echo "$CREATE" | jq -r .partSize)\nPARTS=$(echo "$CREATE" | jq -r .expectedParts)\n\n# 2. Split, presign, and PUT each part.\nsplit -b "$PART_SIZE" "$FILE" part-\ni=1\nfor p in part-*; do\n URL=$(curl -sS -X POST "$API/v1/uploads/$ASSET/parts" \\\n -H "authorization: Bearer $KEY" -H \'content-type: application/json\' \\\n -d "{\\"partNumbers\\":[$i]}" | jq -r \'.urls[0].url\')\n curl -sS -X PUT --data-binary "@$p" "$URL" -o /dev/null\n i=$((i + 1))\ndone\n\n# 3. Finalise.\ncurl -sS -X POST "$API/v1/uploads/$ASSET/complete" \\\n -H "authorization: Bearer $KEY" -H \'content-type: application/json\' \\\n -d "{\\"sha256\\":\\"$(shasum -a 256 "$FILE" | cut -d\' \' -f1)\\"}"\n```\n\nBatch the presign calls in real code \u2014 up to 100 part numbers per request.\n\n### Send the sha256\n\nThe `etag` completion returns is a *composite* multipart ETag: a hash of hashes,\nand dependent on the part size you used. It is not a content identity and cannot\nbe compared against a hash you computed locally.\n\nIf you want real integrity, send `sha256` \u2014 the lowercase hex SHA-256 of the\nwhole file. It is stored as object metadata and is what an independent\nverification would check against. A malformed value is ignored rather than\nrejected, since retrying the call cannot fix it.\n\n### Credentials\n\n`POST /v1/uploads` needs an API key with `upload` scope. The remaining upload\nroutes accept **either** that key or the `uploadToken` returned at creation.\n\nRe-minting a token (`POST /v1/uploads/:id/token`) requires the API key \u2014 not the\nexpiring token, which would otherwise be able to renew itself forever.\n\nUploading from a browser or mobile client? Do not ship the API key. See\n[Upload from a browser](#upload-from-a-browser).\n\n## Upload from a browser\n\nCreate the upload on your server, hand the client a narrow credential, and let it\nPUT parts directly. Upload bytes never touch your servers.\n\n### Forward only the client-safe fields\n\n`POST /v1/uploads` returns more than a client should see:\n\n```json\n{\n "assetId": "...", // safe\n "uploadToken": "...", // safe\n "tokenExpiresAt": 1756130400000, // safe\n "partSize": 8388608, // safe\n "expectedParts": 13, // safe\n\n "key": "acct_7Kd2/.../source.mp4", // storage internal \u2014 do NOT forward\n "uploadId": "2~aBcDeF..." // storage internal \u2014 do NOT forward\n}\n```\n\nForward exactly `assetId`, `uploadToken`, `tokenExpiresAt`, `partSize`, and\n`expectedParts`. Passing the whole body through leaks your storage layout to\nevery client.\n\nThe `uploadToken` is scoped to that one asset and grants nothing else \u2014 no other\nasset, and nothing on playback. That is why it is safe to hand out and an API key\nis not.\n\n### Bucket CORS is a hard prerequisite\n\nPart PUTs go **directly to object storage**, not through the API. The source\nbucket must allow `PUT` from every origin your uploading page runs on, and must\nexpose the `ETag` response header:\n\n```json\n{\n "AllowedOrigins": ["https://yourapp.example", "http://localhost:3000"],\n "AllowedMethods": ["PUT"],\n "AllowedHeaders": ["*"],\n "ExposeHeaders": ["ETag"]\n}\n```\n\n`ExposeHeaders: ["ETag"]` is not optional \u2014 the client verifies each part\'s ETag\nand cannot read it otherwise.\n\n### The failure mode, stated plainly\n\n**A missing origin is silent from the API\'s perspective.** The upload session\nexists, zero parts ever land, and the client cycles running/stalled as though the\nnetwork were flaky. A CORS-blocked PUT is indistinguishable from a network error\nto `XMLHttpRequest` \u2014 the browser deliberately withholds the detail.\n\n**First move when a browser upload stalls at 0%: check the preflight, not the\nWorker.** Open the network tab and look for the `OPTIONS` request.\n\nThis one cost real time on the first customer integration, which is why the SDK\nnow surfaces it itself. After three consecutive network-class part failures with\n**zero bytes ever confirmed** for the session, it emits:\n\n```js\nupload.on(\'diagnostic\', d => {\n // { code: \'systemic-transport-failure\', consecutiveNetworkFailures, bytesEverConfirmed, hint }\n console.warn(d.hint);\n});\n```\n\nZero-ever-confirmed is what separates this from ordinary mid-upload network loss.\nIt is **advisory, never terminal**: a client that is genuinely offline from byte\nzero looks identical, so the upload keeps retrying regardless. The event is the\nhook for telling the user to check their connection \u2014 or for telling *you* to\ncheck bucket CORS.\n\n### Token expiry mid-upload\n\nLong uploads outlive their token. Handle it on your server:\n\n```js\nconst upload = createUpload({\n file,\n assetId,\n uploadToken,\n onTokenExpired: async () => {\n const r = await fetch(\'/api/hostr/refresh-token\', {\n method: \'POST\',\n body: JSON.stringify({ assetId }),\n });\n return (await r.json()).uploadToken; // your server calls POST /v1/uploads/:id/token\n },\n});\n```\n\nThe SDK re-mints and retries in place. Nothing is lost even without this \u2014 a\nkilled client resumes from what storage reports on the next launch \u2014 but the hook\navoids the interruption.\n\nSee the [SDK reference](#sdk-reference) for the full option surface.\n\n## Resume and integrity\n\n### Resume asks storage, not the client\n\n```\nGET /v1/uploads/:id\n -> { status, partSize, expectedParts, uploadedParts, parts, bytesUploaded }\n```\n\n`uploadedParts` is part numbers only; `parts` is the richer form, each entry\ncarrying `partNumber`, `size`, and `etag`.\n\nThe API derives this by listing what is actually in storage, not by reading\nbookkeeping the client sent. That is the whole design: a crash, a refresh, a\ndropped connection, or a client that lied all converge on the same truth. Resume\nis simply "send the parts that are not in that list".\n\nParts are listed only while `uploading`. Once completed or aborted the list is\nempty, because there is nothing left to resume.\n\n### Three layers, three different claims\n\nEach layer proves something the others do not.\n\n**Per-part ETag.** Storage returns an ETag on every part PUT. The client compares\nit against the part it just sent, so a corrupted or truncated part is caught\nimmediately rather than at the end of a multi-gigabyte upload.\n\n**Part count and total size at completion.** Completion refuses to finalise\nunless the number of parts and the total byte count both match what was declared\nat creation. Count alone would accept N parts of the wrong sizes.\n\n**Whole-file SHA-256, if you send it.** This is the only one that proves content\nidentity.\n\n### Why the ETag is not enough\n\nThe ETag on a completed multipart object is a **hash of the part hashes**, then\nthe part count \u2014 `b8f1c0d9e2a34567-13`. Two consequences:\n\n- It cannot be compared against a hash you compute locally.\n- The same file uploaded with a different `partSize` produces a different ETag.\n\nSo it is a useful transfer check and a useless content identity. Send `sha256`\n(lowercase hex of the whole file) at completion if identity matters; it is stored\nas object metadata.\n\nIndependent verification, deriving both from the bytes actually in storage rather\nthan from anything the client claimed:\n\n```bash\npnpm verify:upload <assetId>\n```\n\n### Completion is idempotent\n\nA client that crashed after the bytes landed but before it saw the response\nretries and gets the stored `etag` and `bytes` back, not a `409`. Any genuinely\nunfinished status still conflicts with `not_uploading`.\n\nThis matters more than it sounds: the window between "storage has everything" and\n"the client knows" is exactly where flaky mobile connections die.\n\n### Aborting\n\n```\nDELETE /v1/uploads/:id\n```\n\nAn in-flight multipart session holds part storage that is invisible in normal\nlistings. Abandoning an upload without aborting leaks it. The SDK and CLI do this\nfor you; a hand-rolled client should too.\n\n## Webhooks and the event log\n\nhostr POSTs lifecycle events to one endpoint per account so you do not have to\npoll.\n\n```\nPUT /v1/webhooks {"url": "https://yourapp.example/hostr-webhook"} (full)\n -> { url, enabled, secret: "whsec_..." } # secret returned ONLY when generated, ONLY once\nGET /v1/webhooks -> { url, enabled, createdAt } # never the secret\nDELETE /v1/webhooks -> disables; delivery history is retained\n```\n\nOmit `secret` in the PUT to have one generated, or supply your own to bring an\nexisting one. Configuration is cached about 60 seconds in the Worker, the same\npropagation window as key revocation.\n\nA URL configured without a secret logs and skips: **unsigned events are never\nsent.**\n\n### The log is written first\n\nEvery event becomes a durable row **before** delivery is attempted. A consumer\noutage cannot lose one.\n\n```\nGET /v1/events?after=<cursor>&limit=&type= ascending tail; reuse nextCursor verbatim (read)\nGET /v1/events?order=desc&limit=1 newest first (read)\nPOST /v1/events/:id/redeliver replay any stored event (full)\n```\n\n**The webhook is the wake-up signal; the log is the ledger.** Delivery is\nat-least-once \u2014 three attempts with short backoff, each recorded and inspectable.\nA consumer that must not miss anything reconciles against `GET /v1/events` (or\n`GET /v1/assets/:id`) rather than trusting that every POST arrived.\n\n`npx @hostr/cli tail --follow` polls the log for you.\n\n### Building a consumer that behaves\n\n**Verify the signature before parsing.** See\n[Verifying webhooks](#verifying-webhook-signatures) \u2014 use the raw body bytes.\n\n**Dedupe on `id`.** It is the durable event row\'s id, and a redelivery reuses it\ndeliberately so your dedupe still works.\n\n**Respond `2xx` fast.** Do the real work asynchronously. Anything else is\nretried.\n\n**Expect at-least-once, and design for it.** `video.ready` and `video.errored`\nfire on the status *transition* only, so a transcoder re-posting a terminal state\ncannot duplicate them \u2014 but the network can still deliver the same event twice.\n\n### Testing locally\n\nBoth `https` and `http` endpoints are accepted, including private addresses.\nhostr does not block internal ranges, so a local receiver works in development\nexactly as production does.\n\n```bash\nnpx @hostr/cli webhooks test # redelivers the newest event to your endpoint\n```\n\nSee the [events reference](#event-reference) for every type and payload.\n\n## Verifying webhook signatures\n\nEvery delivery carries a `hostr-signature` header:\n\n```\nhostr-signature: t=1756130400,v1=3b1f2c9d8e7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f3a2b1c\n```\n\n`v1` is `HMAC-SHA256(secret, "<t>.<rawBody>")`, hex-encoded. `t` is a unix\ntimestamp in **seconds**. This is the Stripe scheme, and Mux\'s.\n\n### Implementation\n\n```js\nimport { createHmac, timingSafeEqual } from \'node:crypto\';\n\nexport function verifyHostrWebhook(secret, header, rawBody, toleranceSec = 300) {\n const m = /^t=(\\d+),v1=([0-9a-f]{64})$/.exec(header ?? \'\');\n if (!m) return false;\n if (Math.abs(Date.now() / 1000 - Number(m[1])) > toleranceSec) return false;\n const expected = createHmac(\'sha256\', secret).update(`${m[1]}.${rawBody}`).digest(\'hex\');\n return expected.length === m[2].length &&\n timingSafeEqual(Buffer.from(expected), Buffer.from(m[2]));\n}\n```\n\nWired into Express, where getting the raw body needs care:\n\n```js\nimport express from \'express\';\n\nconst app = express();\n\napp.post(\'/hostr-webhook\',\n express.raw({ type: \'application/json\' }), // NOT express.json()\n (req, res) => {\n const raw = req.body.toString(\'utf8\');\n if (!verifyHostrWebhook(process.env.HOSTR_WEBHOOK_SECRET, req.get(\'hostr-signature\'), raw)) {\n return res.status(400).end();\n }\n const event = JSON.parse(raw); // parse only after verifying\n res.status(200).end(); // ack fast\n queue.push(event); // then do the work\n });\n```\n\n### The three ways this goes wrong\n\n**Using the parsed body instead of the raw bytes.** `JSON.parse` followed by\n`JSON.stringify` does not reproduce the original bytes \u2014 key order, whitespace,\nand number formatting can all shift. The HMAC is over what was actually sent.\nRegister the raw body parser on this route specifically.\n\n**A plain `===` on the hex digest.** String comparison short-circuits on the\nfirst differing character, which leaks timing information. Use\n`timingSafeEqual`, and compare lengths first \u2014 it throws on mismatched lengths.\n\n**Ignoring `t`.** Without a bounded timestamp window a captured delivery can be\nreplayed at any time in the future. Five minutes is a reasonable tolerance.\n\n### Do not confuse the units\n\n`t` is unix **seconds**. Elsewhere in the API, `tokenExpiresAt` and `expiresAt`\nare epoch **milliseconds**. That is deliberate \u2014 each convention matches its home\n(Stripe\'s for signatures, Mux\'s for token bundles) rather than being made falsely\nuniform. Mixing them up produces a timestamp roughly 55,000 years out, which at\nleast fails loudly.\n\n### Getting the secret\n\n```bash\nnpx @hostr/cli webhooks set https://yourapp.example/hostr-webhook --write-env .env\n```\n\nWritten straight to the file at mode 0600; only the variable name is printed. The\nsecret is returned **once**, in the `PUT /v1/webhooks` response, and never again\n\u2014 `GET /v1/webhooks` deliberately does not include it. Lost it? Set a new one.\n\n### Proving it end to end\n\n```bash\nnpx @hostr/cli webhooks test\n```\n\nRedelivers the newest stored event to your endpoint, so you can confirm the whole\npath without uploading anything.\n\nIf your endpoint was down when an event fired, nothing was lost \u2014 see\n[Webhooks and the event log](#webhooks-and-the-event-log).\n\n## Playback\n\nPlayback is token-gated. Mint per view, server-side, with a `playback`-scoped\nkey.\n\n```\nPOST /v1/assets/:id/tokens {"ttlSec":3600,"viewerId":"user-123"} (body optional)\n -> { playback, thumbnail, storyboard, expiresAt }\n```\n\n```bash\nnpx @hostr/cli assets token <assetId> --json\n```\n\nField names mirror Mux\'s bundle, so a consumer migrating swaps its base URL and\nkeeps its client code.\n\n### Build the URL\n\n```\nhttps://stream.hostr.sh/{playbackId}.m3u8?token={playback}\n```\n\nHand it to any HLS player. Safari and iOS play HLS natively; elsewhere use\nhls.js.\n\n```html\n<video id="v" controls></video>\n<script type="module">\n import Hls from \'https://cdn.jsdelivr.net/npm/hls.js@1/+esm\';\n const src = `https://stream.hostr.sh/${playbackId}.m3u8?token=${token}`;\n const v = document.getElementById(\'v\');\n if (v.canPlayType(\'application/vnd.apple.mpegurl\')) v.src = src;\n else if (Hls.isSupported()) { const h = new Hls(); h.loadSource(src); h.attachMedia(v); }\n</script>\n```\n\n### Mint timing, and what to gate on\n\nMinting works any time after the asset exists \u2014 it 404s only for unknown or\ndeleted assets. **The stream itself 404s until the asset is `ready`.**\n\nSo gate your UI on `video.ready` or the asset\'s status, never on whether minting\nsucceeded. A successful mint for a still-encoding asset is expected behaviour,\nnot a green light.\n\n### The TTL is not a viewing limit\n\nThe token is checked **once**, at the master playlist. After that the session\ncarries its own internally-managed credentials, so a viewer who starts playback\nat minute 59 of a one-hour token watches the whole video.\n\n`ttlSec` accepts 60 to 86,400 and defaults to 3,600. It only needs to be valid\nwhen playback *starts*.\n\n### viewerId\n\nOptional, opaque, and carried inside the token. It enables per-viewer concurrency\nobservation. Concurrency is currently observed rather than enforced \u2014 see\n[Tokens and signed playback](https://docs.hostr.sh/concepts/playback/).\n\n### Things that will confuse you once\n\n**Non-browser user agents are rejected** with `403 blocked_user_agent` \u2014\ncurl, wget, yt-dlp, vlc, and ffmpeg UAs are blocked as a casual-ripping speed\nbump. A server-side smoke test must send a browser-like `User-Agent` or hit\n`/health`, which is exempt. Expect it; do not debug it.\n\n**Signed URLs are not DRM.** They stop link-sharing and hotlinking, not an\nentitled viewer recording their screen.\n\n**Deleted assets stop minting immediately**, but tokens already issued can replay\nedge-cached segments for a few hours until they expire.\n\n### Poster and scrub previews\n\nThe same mint response covers both, each URL taking its matching token:\n\n```\nhttps://stream.hostr.sh/{playbackId}/thumbnail.jpg?token={thumbnail}\nhttps://stream.hostr.sh/{playbackId}/storyboard.vtt?token={storyboard}\n```\n\nSee [Thumbnails and storyboards](#thumbnails-and-storyboards).\n\n## Thumbnails and storyboards\n\n`POST /v1/assets/:id/tokens` returns three tokens, not one. The `thumbnail` and\n`storyboard` values drive the poster image and the scrub preview.\n\n```\nhttps://stream.hostr.sh/{playbackId}/thumbnail.jpg?token={thumbnail}\nhttps://stream.hostr.sh/{playbackId}/storyboard.vtt?token={storyboard}\n```\n\nSame host, same query-token shape as the playlist. Each URL takes its **own**\ntoken \u2014 they are minted with different audiences and are not interchangeable.\n\n### Poster\n\nA single JPEG extracted during encoding. Use it as the `poster` attribute:\n\n```html\n<video poster="https://stream.hostr.sh/abc123/thumbnail.jpg?token=..." controls></video>\n```\n\n### Storyboard\n\nA standard "thumbnails" WebVTT track. Cues point into a tiled sprite using\n`#xywh=` fragments, and **the sprite URLs inside the VTT are pre-signed for you**\n\u2014 you do not mint anything extra.\n\nThat is the convention mux-player\'s `storyboard-src`, media-chrome\'s preview\ntrack, and most other players already consume:\n\n```html\n<mux-player\n storyboard-src="https://stream.hostr.sh/abc123/storyboard.vtt?token=..."\n></mux-player>\n```\n\n### Treat both as optional\n\nAssets encoded before storyboards existed 404 on that URL, and scrubbing simply\nshows no preview. Players handle this gracefully by design \u2014 do not add error\nhandling that turns a missing preview into a broken player.\n\n## Subtitles\n\nHuman-authored WebVTT tracks, attachable any time after the asset is `ready`.\n\n```\nPUT /v1/assets/:id/subtitles/:lang?name=English&default=true (body: raw WebVTT, upload scope)\nGET /v1/assets/:id/subtitles -> { assetId, tracks: [{ lang, name, default, rev }] }\nDELETE /v1/assets/:id/subtitles/:lang\n```\n\n```bash\nnpx @hostr/cli subtitles set <assetId> subs.vtt --lang en --name English --default\nnpx @hostr/cli subtitles list <assetId>\nnpx @hostr/cli subtitles rm <assetId> en\n```\n\nThe PUT body is **raw WebVTT, not JSON**. It must start with `WEBVTT`, and is\ncapped at 2,000,000 bytes.\n\n```bash\ncurl -X PUT "https://api.hostr.sh/v1/assets/$ASSET/subtitles/en?name=English&default=true" \\\n -H "authorization: Bearer $HOSTR_API_KEY" \\\n -H \'content-type: text/vtt\' \\\n --data-binary @subs.vtt\n```\n\n### Rules\n\n**`:lang` is a BCP 47 tag** \u2014 `en`, `pt-BR`. One track per tag; PUT replaces.\nAnything that is not a valid tag is `400 bad_language`.\n\n**The asset must be `ready`.** Before that it is `409 not_ready` \u2014 the track\nplaylist needs the encoded duration, which does not exist until the encode\nreports in.\n\n**`default=true` demotes any previous default.** At most one default per asset.\n\n**Write scope is `upload`, not `playback`.** Subtitles are content, not\nentitlement.\n\n### How they reach the player\n\nTracks are injected into the master playlist at serve time as an `EXT-X-MEDIA`\nsubtitles group. The next master fetch after a PUT includes them.\n\n**No re-encode. No new playback URL. No token change.** Players pick them up in\nthe captions menu automatically.\n\nTracks are stored under a content-hash revision, so replacing one is cache-safe\neven though segments are served with a one-year immutable cache. A viewer already\nmid-session keeps the track they started with; the replacement applies to the next\nplayback session.\n\n### Deleting\n\nRemoval delists the track first \u2014 that is what makes it invisible to players. The\nunderlying versioned objects become unreachable and are purged with the asset, so\nleftovers cost nothing.\n\n`404 subtitle_not_found` means no track for that tag; `404 asset_not_found` means\nno such asset. They are distinct codes.\n\n## Event reference\n\nDelivered body: `{ id, type, createdAt, data }`. `id` is the durable event row\'s\nid \u2014 **dedupe on it**, and note that a redelivery reuses it deliberately.\n\n| Type | Fired when | `data` highlights |\n|---|---|---|\n| `upload.created` | Multipart session opened | `assetId`, `filename`, `declaredSize` |\n| `video.uploaded` | Bytes verified in storage, transcode queued | `assetId`, `key`, `bytes`, `etag`, `sha256?` |\n| `video.ready` | HLS renditions live | `assetId`, `playbackId`, `durationSec?`, `renditions?` |\n| `video.errored` | Transcode failed | `assetId`, `error` (always present) |\n| `video.deleted` | Asset erased, playback over | `assetId` |\n| `video.input.non_standard` | The source needed a judgement call | `assetId`, `input`, `findings[]` |\n\n`video.ready` and `video.errored` fire on the status **transition** only, so a\ntranscoder re-posting a terminal state cannot duplicate them.\n\n`error` on `video.errored` is always present. An optional error field makes every\nconsumer invent its own generic message, which is worse than a bad message.\n\n### video.input.non_standard\n\nAdvisory. The transcode proceeds normally and a `video.ready` still follows. It\nfires **at most once per asset**, and only when there is something to say \u2014 a\nfile with nothing unusual about it generates no traffic.\n\n| Finding code | Meaning |\n|---|---|\n| `hdr_tags_on_8bit` | Source carries HLG/PQ tags but is 8-bit. HDR is a 10-bit format, so the tag is stale \u2014 treated as SDR, pixels untouched |\n| `hdr_source` | Genuine 10-bit HDR. The ladder outputs 8-bit SDR; no tone mapping is applied |\n| `wide_gamut_tags` | BT.2020 primaries without an HDR transfer; output is BT.709, colour not converted |\n| `variable_frame_rate` | Container rate and measured rate disagree; normalised to CFR |\n| `frame_rate_changed` | Source rate was not a broadcast standard and was snapped to the nearest |\n\n`data.input` carries the full probe \u2014 `container`, `videoCodec`, `pixFmt`,\n`bitDepth`, `width`, `height`, `declaredFps`, `averageFps`, `targetFps`,\n`isVariableFrameRate`, `colorSpace`, `colorTransfer`, `colorPrimaries`.\n\nThe same block is on the asset record as `input`, so it can be read back at any\ntime without replaying events.\n\n### Delivery\n\nThree attempts with short backoff, each recorded and inspectable. Every event is\nwritten to the durable log **before** the first attempt.\n\n```\nGET /v1/events?after=<cursor>&limit=&type= ascending tail; reuse nextCursor verbatim\nGET /v1/events?order=desc&limit=1 newest first\nPOST /v1/events/:id/redeliver replay to the current endpoint\n```\n\nSignature verification: [Verifying webhooks](#verifying-webhook-signatures).\n\n## Error reference\n\nEvery non-2xx body is `{ "error": "<code>", ... }`. **Switch on `error`, never on\nthe message** \u2014 codes are stable, prose is not.\n\n| Status | Error | Meaning and action |\n|---|---|---|\n| 400 | `size_required` | `size` missing or not positive on `POST /v1/uploads` |\n| 400 | `partNumbers_required` | Empty or non-array `partNumbers` |\n| 400 | `too_many_parts_per_request` | More than 100 part numbers; `max` names the cap |\n| 400 | `part_out_of_range` | A part number below 1 or above `expectedParts` |\n| 400 | `bad_language` | Not a BCP 47 tag |\n| 400 | `not_webvtt` | Subtitle body does not start with `WEBVTT` |\n| 400 | `bad_status` | Status outside the allowed set (internal route) |\n| 400 | `bad_scopes` | A scope outside `read`/`upload`/`playback`/`full` |\n| 400 | `bad_date` | A date parameter was not `YYYY-MM-DD` |\n| 400 | `authorization_pending` | Device login not yet approved \u2014 keep polling |\n| 400 | `slow_down` | Polling too fast \u2014 back off, keep polling |\n| 400 | `expired_token` | Device code expired. Start over |\n| 400 | `access_denied` | Device login was declined |\n| 401 | `unauthorized` | Bad, missing, or revoked credential \u2014 **or a resource you do not own.** hostr does not reveal which |\n| 403 | `insufficient_scope` | Scope too low; `need` names the rung required |\n| 403 | `quota_uploads_daily` | Daily upload cap; `limit` is the ceiling |\n| 403 | `quota_assets` | Asset count cap; `limit` is the ceiling |\n| 403 | `quota_storage` | Storage cap; `limit` is the ceiling |\n| 403 | `account_suspended` | Contact the operator |\n| 403 | `accountId_service_only` | Only the service key may name an owning account |\n| 403 | `blocked_user_agent` | Media host only \u2014 send a browser-like `User-Agent` |\n| 404 | `asset_not_found` | No such asset, or it has been deleted |\n| 404 | `subtitle_not_found` | No track for that language tag |\n| 404 | `event_not_found` | No such event for this account |\n| 404 | `key_not_found` | No such live key for this account |\n| 404 | `not_configured` | No webhook endpoint configured |\n| 404 | `account_not_found` | Key authenticated but its account row is gone |\n| 409 | `incomplete_upload` | Parts missing; `missing` lists them. Upload and re-complete |\n| 409 | `size_mismatch` | Declared size does not match bytes landed. Abort and restart |\n| 409 | `not_uploading` | Upload already finished or aborted |\n| 409 | `not_ready` | Asset is not `ready`, so its duration is unknown |\n| 409 | `no_webhook_endpoint` | Nothing configured or enabled to redeliver to |\n| 413 | `file_too_large` | Too many parts at this part size; raise `partSize` |\n| 413 | `subtitle_too_large` | Over 2,000,000 bytes |\n| 429 | `rate_limited` | `POST /v1/device/code` only. It is unauthenticated, so it is capped per IP. A real login makes one call \u2014 if you see this, something is looping |\n| 500 | `signing_not_configured` | Operator-side: the playback signing key is not loaded. Not your fault, not retryable. Report it |\n| 500 | `internal` | Unexpected. `message` carries truncated detail |\n| 503 | `control_plane_unavailable` | Transient. Retry with backoff |\n\n### Retry guidance\n\n**Retry with backoff:** `503 control_plane_unavailable`, `500 internal`,\n`400 authorization_pending`, `400 slow_down`.\n\n**Fix and retry:** the `409` upload conflicts \u2014 they tell you exactly what is\nwrong (`missing` part numbers, or both byte counts).\n\n**Do not retry unchanged:** every `400`, `401`, `403`, and `404`. A quota `403`\nin particular will fail identically forever until the account limit is raised.\n\n### The 401 conflation is deliberate\n\n`unauthorized` covers both "bad credential" and "not your asset". Distinguishing\nthem would let anyone holding a valid key enumerate other accounts\' asset ids by\nwatching which error came back.\n\n## CLI reference\n\n```bash\nnpx @hostr/cli <command>\n```\n\nA single-file, zero-dependency bundle published as `hostr`. **Every command takes\n`--json`** \u2014 one JSON document on stdout, NDJSON for `tail --follow`, errors as\nJSON on stderr with exit code 1. Nothing needs prose parsing.\n\nRun it with **no arguments** for setup status and the single next step. That is\nthe intended entry point, for humans and agents alike.\n\n### Credentials\n\nPrecedence, highest first: `--key <k>`, then `HOSTR_API_KEY`, then the saved\nprofile.\n\nAPI base, highest first: `--api <url>`, then `HOSTR_API_BASE`, then the profile,\nthen production.\n\nProfiles live in `~/.config/hostr/config.json`, cleartext at mode 0600 \u2014 the\n`gh` and `wrangler` precedent.\n\n### Authentication\n\n```bash\nhostr login # browser-authorized; nothing is pasted\nhostr login --profile staging # name the profile\nhostr login --key hostr_sk_live_... # escape hatch for CI; skips the browser\nhostr whoami # account, plan, limits, live usage\n```\n\n`login` with no key opens your browser and uses the device-authorization flow.\nThe code and URL are printed to **stderr**, so `--json` stdout stays a single\nparseable document.\n\n### Uploading\n\n```bash\nhostr upload video.mp4 # returns when bytes are verified in storage\nhostr upload video.mp4 --wait # blocks until transcode is ready or failed\nhostr upload video.mp4 --content-type video/quicktime\nhostr upload # no file: opens a local drag-drop page\n```\n\nWraps the SDK\'s Node adapter, so it carries the same resume and integrity\nguarantees. Kill it mid-transfer and re-run to continue.\n\n### Assets\n\n```bash\nhostr assets list --status ready --limit 20 --cursor <cursor>\nhostr assets get <id>\nhostr assets token <id> --ttl 3600 --viewer-id user-123 # playback scope\nhostr assets delete <id> # full scope\n```\n\n### Subtitles\n\n```bash\nhostr subtitles list <assetId>\nhostr subtitles set <assetId> subs.vtt --lang en --name English --default\nhostr subtitles rm <assetId> en\n```\n\n`--lang` is required and must be a BCP 47 tag. The asset must be `ready`.\n\n### Events\n\n```bash\nhostr tail # one page of the durable log\nhostr tail --follow # poll every 2s, NDJSON under --json\nhostr tail --type video.ready --limit 50 --after <cursor>\n```\n\n### Keys\n\n```bash\nhostr keys list\nhostr keys create --name ci --scopes upload --write-env .env\nhostr keys revoke <id>\n```\n\n`--scopes` takes a comma-separated list and **defaults to `playback`** \u2014 the\nright rung for an application key. `revoke` takes the `id` from `keys list`, not\nthe `keyId`.\n\n### Webhooks\n\n```bash\nhostr webhooks get\nhostr webhooks set https://app.example/hook --write-env .env\nhostr webhooks set https://app.example/hook --secret whsec_... # bring your own\nhostr webhooks delete\nhostr webhooks test # redeliver the newest event \u2014 proves your endpoint\n```\n\n### Repo setup\n\n```bash\nhostr init # docs/hostr.md + AGENTS.md section + .env.example\nhostr init --dir ../other-repo\n```\n\nIdempotent. Re-running replaces the content between the `AGENTS.md` markers\nrather than appending.\n\n### Usage\n\n```bash\nhostr usage --from 2026-08-01 --to 2026-08-25\n```\n\nDefaults to the last 30 days.\n\n### --write-env\n\n```bash\nhostr keys create --scopes upload --write-env .env\nhostr webhooks set https://app.example/hook --write-env .env\n```\n\nWrites the secret into that file at mode 0600 and prints **only the variable\nname** \u2014 in `--json` mode too. Nothing else in the CLI ever prints a credential.\n\nThe point is that an agent driving your terminal can orchestrate a credential\nwithout the value ever entering its context or its transcript.\n\n## SDK reference\n\n```bash\nnpm install @hostr/upload\n```\n\nFour entry points, each bundled independently:\n\n| Entry | Platform | What the adapter supplies |\n|---|---|---|\n| `@hostr/upload` | **Trusted backend only** | `createUploadSession`, `mintUploadToken` \u2014 needs your API key |\n| `@hostr/upload/browser` | Web | XHR transport (for progress events), `localStorage` session store |\n| `@hostr/upload/node` | Node, scripts | `fetch` transport, filesystem session store |\n| `@hostr/upload/react-native` | Expo / RN | Native staged-parts transport; survives backgrounding |\n\nThe engine, retry policy, and integrity checks are one shared core. Adapters only\nsupply platform I/O: read bytes, PUT bytes, persist a few KB of JSON.\n\n### Browser\n\n```js\nimport { createUpload } from \'@hostr/upload/browser\';\n\n// createUploadSession runs on YOUR SERVER \u2014 it holds the API key.\n// The browser receives only { endpoint, assetId, uploadToken }.\nconst upload = await createUpload({ endpoint, uploadToken, assetId, file });\n\nupload.on(\'progress\', p => {\n const pct = (p.bytesConfirmed / p.totalBytes * 100).toFixed(1);\n console.log(`${p.partsDone}/${p.partsTotal} parts, ${pct}%`);\n});\nupload.on(\'statechange\', s => console.log(s));\n// idle -> running -> (stalled <-> running)* -> completing -> complete\n\nupload.start();\nconst { etag, sha256 } = await upload.done;\n```\n\nSession state persists in `localStorage`, keyed by `name:size:lastModified`.\nReload the page, pick the same file, and `createUpload` resumes automatically \u2014\nthere is no explicit resume call.\n\n### Node\n\n```js\nimport { createUploadSession, createUpload } from \'@hostr/upload/node\';\n\nconst session = await createUploadSession({\n endpoint, apiKey, filename: \'video.mp4\', contentType: \'video/mp4\', size,\n});\n\nconst upload = await createUpload({\n endpoint, uploadToken: session.uploadToken, assetId: session.assetId,\n file: \'/path/to/video.mp4\', // a path, not an open handle\n stateDir: \'./upload-state\', // survives a process restart\n});\n\nupload.start();\nconst { etag, sha256 } = await upload.done;\n```\n\n### Take the endpoint from your backend\'s response\n\n**One rule for clients of a proxying backend:** take the hostr `endpoint` from\nyour backend\'s create-upload response, never from separate client config. Have\nyour backend include its own `HOSTR_API_BASE` in what it returns.\n\nAn upload token is only valid on the hostr instance that minted it. Endpoint\ndrift fails as a bare mid-flow `401` with nothing pointing at the cause;\nreturning the endpoint alongside the session makes the mistake structurally\nimpossible. Learned from the first consumer integration.\n\n### Events\n\n| Event | Payload |\n|---|---|\n| `progress` | `{ partsDone, partsTotal, bytesConfirmed, totalBytes, partStates }` |\n| `statechange` | `\'idle\' \\| \'running\' \\| \'stalled\' \\| \'completing\' \\| \'complete\'` |\n| `diagnostic` | `{ code, consecutiveNetworkFailures, bytesEverConfirmed, hint }` |\n\n`partStates` maps part number to `\'inflight\'` or `\'done\'` \u2014 enough for a per-part\nprogress grid.\n\nThe `diagnostic` event fires once per failure streak, on every adapter. Today its\nonly code is `systemic-transport-failure`, which almost always means bucket CORS\n\u2014 see [Upload from a browser](#upload-from-a-browser). It is **advisory, never\nterminal**: the upload keeps retrying regardless.\n\n### Token refresh\n\n```js\nconst upload = await createUpload({\n endpoint, assetId, uploadToken, file,\n onTokenExpired: async () => (await refreshFromYourServer(assetId)).uploadToken,\n});\n```\n\nYour server calls `POST /v1/uploads/:id/token`. The SDK retries in place; nothing\nis lost. Even without the hook a killed client resumes from what storage reports\non next launch.\n\n### Integrity\n\nThree layers, each proving something different \u2014 per-part ETag, part count and\ntotal size at completion, and an optional whole-file SHA-256. See\n[Resume and integrity](#resume-and-integrity) for what each one does and\ndoes not prove.\n\n### Import error classes from the entry you actually use\n\nEach entry is bundled independently, so `IntegrityError` from\n`@hostr/upload/node` is not the same class object as the one from\n`@hostr/upload/browser`. An `instanceof` check across entries fails. Import from\nthe entry your code uses.\n\n## Full route table\n\n| Method | Path | Scope | Purpose |\n|---|---|---|---|\n| GET | `/health` | \u2014 | Liveness check |\n| GET | `/llms.txt` | \u2014 | Agent documentation index |\n| GET | `/llms-full.txt` | \u2014 | Agent integration guide |\n| POST | `/v1/device/code` | \u2014 | Begin browser authorization |\n| POST | `/v1/device/token` | \u2014 | Exchange an approved device code for a key |\n| POST | `/v1/uploads` | upload | Create an asset and begin a multipart upload |\n| GET | `/v1/uploads/:id` | upload | Upload status and parts already stored |\n| DELETE | `/v1/uploads/:id` | upload | Abort an upload |\n| POST | `/v1/uploads/:id/parts` | upload | Get presigned PUT URLs for parts |\n| POST | `/v1/uploads/:id/complete` | upload | Finalise the upload and queue transcoding |\n| POST | `/v1/uploads/:id/token` | upload | Re-mint an upload token |\n| GET | `/v1/assets` | read | List your assets |\n| GET | `/v1/assets/:id` | read | Get one asset |\n| DELETE | `/v1/assets/:id` | full | Erase an asset |\n| POST | `/v1/assets/:id/tokens` | playback | Mint playback credentials |\n| POST | `/v1/assets/:id/status` | \u2014 | Report transcode status |\n| GET | `/v1/assets/:id/subtitles` | read | List subtitle tracks |\n| PUT | `/v1/assets/:id/subtitles/:lang` | upload | Attach or replace a subtitle track |\n| DELETE | `/v1/assets/:id/subtitles/:lang` | upload | Remove a subtitle track |\n| GET | `/v1/account` | read | Whoami |\n| GET | `/v1/usage` | read | Daily usage |\n| GET | `/v1/events` | read | Tail the durable event log |\n| POST | `/v1/events/:id/redeliver` | full | Replay a stored event |\n| GET | `/v1/webhooks` | full | Get the webhook endpoint |\n| PUT | `/v1/webhooks` | full | Configure the webhook endpoint |\n| DELETE | `/v1/webhooks` | full | Disable the webhook endpoint |\n| GET | `/v1/keys` | full | List key metadata |\n| POST | `/v1/keys` | full | Mint an API key |\n| DELETE | `/v1/keys/:id` | full | Revoke a key |\n\nGenerated from the same OpenAPI description the API is checked against.\nFull reference with schemas and examples: https://docs.hostr.sh/reference/api/\n';
5271
5451
 
5272
5452
  // src/init-content.ts
5273
5453
  var BEGIN = "<!-- hostr:begin -->";
@@ -5297,6 +5477,9 @@ function missingEnvLines(existing) {
5297
5477
  );
5298
5478
  return ENV_LINES.filter((l) => !have.has(l.split("=")[0]));
5299
5479
  }
5480
+ var guideStamp = (version) => `<!-- hostr guide \xB7 CLI ${version} -->`;
5481
+ var GUIDE_STAMP_RE = /^<!-- hostr guide · CLI ([0-9]+\.[0-9]+\.[0-9]+) -->/;
5482
+ var readGuideStamp = (doc) => GUIDE_STAMP_RE.exec(doc ?? "")?.[1] ?? null;
5300
5483
  var agentsSection = (apiBase) => `
5301
5484
  ## hostr (video hosting)
5302
5485
 
@@ -5317,7 +5500,7 @@ transcode, HLS playback with signed URLs.
5317
5500
  `;
5318
5501
 
5319
5502
  // src/commands-init.ts
5320
- var readOrNull = (p) => readFile3(p, "utf8").catch(() => null);
5503
+ var readOrNull2 = (p) => readFile4(p, "utf8").catch(() => null);
5321
5504
  async function init(opts) {
5322
5505
  const out = makeOut(!!opts.json);
5323
5506
  const dir = opts.dir ?? process.cwd();
@@ -5325,27 +5508,29 @@ async function init(opts) {
5325
5508
  const actions = {};
5326
5509
  await mkdir3(join3(dir, "docs"), { recursive: true });
5327
5510
  const docPath = join3(dir, "docs/hostr.md");
5328
- const prevDoc = await readOrNull(docPath);
5329
- if (prevDoc === integrate_default) actions["docs/hostr.md"] = "unchanged";
5511
+ const stamped = `${guideStamp(CLI_VERSION)}
5512
+ ${integrate_default}`;
5513
+ const prevDoc = await readOrNull2(docPath);
5514
+ if (prevDoc === stamped) actions["docs/hostr.md"] = "unchanged";
5330
5515
  else {
5331
- await writeFile3(docPath, integrate_default);
5516
+ await writeFile4(docPath, stamped);
5332
5517
  actions["docs/hostr.md"] = prevDoc === null ? "written" : "updated";
5333
5518
  }
5334
5519
  const agentsPath = join3(dir, "AGENTS.md");
5335
- const prevAgents = await readOrNull(agentsPath);
5520
+ const prevAgents = await readOrNull2(agentsPath);
5336
5521
  const nextAgents = spliceMarkers(prevAgents, agentsSection(apiBase));
5337
5522
  if (nextAgents === prevAgents) actions["AGENTS.md"] = "unchanged";
5338
5523
  else {
5339
- await writeFile3(agentsPath, nextAgents);
5524
+ await writeFile4(agentsPath, nextAgents);
5340
5525
  actions["AGENTS.md"] = prevAgents === null ? "written" : "updated";
5341
5526
  }
5342
5527
  const envPath = join3(dir, ".env.example");
5343
- const prevEnv = await readOrNull(envPath);
5528
+ const prevEnv = await readOrNull2(envPath);
5344
5529
  const missing = missingEnvLines(prevEnv);
5345
5530
  if (!missing.length) actions[".env.example"] = "unchanged";
5346
5531
  else {
5347
5532
  const base = prevEnv === null ? "" : prevEnv.replace(/\n*$/, "\n");
5348
- await writeFile3(envPath, `${base}${missing.join("\n")}
5533
+ await writeFile4(envPath, `${base}${missing.join("\n")}
5349
5534
  `);
5350
5535
  actions[".env.example"] = prevEnv === null ? "written" : "updated";
5351
5536
  }
@@ -5355,9 +5540,99 @@ async function init(opts) {
5355
5540
  );
5356
5541
  }
5357
5542
 
5543
+ // src/commands-status.ts
5544
+ import { readFile as readFile5 } from "node:fs/promises";
5545
+ import { join as join4 } from "node:path";
5546
+
5547
+ // src/status.ts
5548
+ var APP_KEY_CMD = 'npx hostr keys create --name "app dev" --write-env .env.local';
5549
+ function computeStatus(i) {
5550
+ const staleGuide = i.guideStampVersion !== null && i.guideStampVersion !== i.cliVersion;
5551
+ const authorized = !i.hasProfileKey ? { mark: "\u2717", label: "not authorized", detail: "" } : i.account ? { mark: "\u2713", label: "authorized", detail: `account "${i.account.name}" (plan: ${i.account.plan})` } : { mark: "?", label: "authorized", detail: "key saved; could not reach the API to confirm" };
5552
+ const prepared = i.guideStampVersion === null ? { mark: "\u2717", label: "repo not prepared", detail: "" } : {
5553
+ mark: "\u2713",
5554
+ label: "repo prepared",
5555
+ detail: staleGuide ? `docs/hostr.md written by CLI ${i.guideStampVersion}; you are running ${i.cliVersion} \u2014 re-run npx hostr init` : "docs/hostr.md, AGENTS.md, .env.example"
5556
+ };
5557
+ const appKey = i.envKeyFile === null ? { mark: "\u2717", label: "no app key", detail: "" } : { mark: "\u2713", label: "app key", detail: `HOSTR_API_KEY in ${i.envKeyFile}` };
5558
+ const rows = [authorized, prepared, appKey];
5559
+ let nextCommand = null;
5560
+ let nextNote = null;
5561
+ if (authorized.mark === "\u2717") {
5562
+ nextCommand = "npx hostr login";
5563
+ nextNote = "Opens a browser for your human to approve. Do NOT ask them to paste an\n API key, and do not put a key in your context.";
5564
+ } else if (prepared.mark === "\u2717") {
5565
+ nextCommand = "npx hostr init";
5566
+ nextNote = "Writes docs/hostr.md, an AGENTS.md section, and .env.example entries. No network.";
5567
+ } else if (appKey.mark === "\u2717") {
5568
+ nextCommand = APP_KEY_CMD;
5569
+ nextNote = "Writes the key straight to the file \u2014 the value is never printed.";
5570
+ }
5571
+ const activity = !i.online || !i.account ? "account: not checked (offline)" : `account: ${i.account.assetCount} assets \xB7 ${i.webhookUrl ? `webhook ${i.webhookUrl}` : "no webhook configured"}`;
5572
+ return { rows, nextCommand, nextNote, activity, staleGuide };
5573
+ }
5574
+ function renderStatus(r) {
5575
+ const body = r.rows.map((x) => ` ${x.mark} ${x.label.padEnd(18)}${x.detail}`.trimEnd()).join("\n");
5576
+ const next = r.nextCommand ? `
5577
+
5578
+ Next: ${r.nextCommand}${r.nextNote ? `
5579
+ ${r.nextNote}` : ""}` : "\n\nSetup complete. Implement from docs/hostr.md \u2014 \xA75 webhooks, \xA76 playback.\nRegister your webhook once the endpoint is deployed:\n npx hostr webhooks set <url> --write-env .env.local";
5580
+ return `hostr \u2014 video for this app.
5581
+
5582
+ ${body}${next}
5583
+
5584
+ ${r.activity}
5585
+ `;
5586
+ }
5587
+
5588
+ // src/commands-status.ts
5589
+ var readOrNull3 = (p) => readFile5(p, "utf8").catch(() => null);
5590
+ async function findEnvKey(dir) {
5591
+ for (const f of [".env.local", ".env"]) {
5592
+ const body = await readOrNull3(join4(dir, f));
5593
+ if (body && /^\s*HOSTR_API_KEY=\S/m.test(body)) return f;
5594
+ }
5595
+ return null;
5596
+ }
5597
+ async function status(opts) {
5598
+ const out = makeOut(!!opts.json);
5599
+ const dir = process.cwd();
5600
+ const cfg = await loadConfig(configDir());
5601
+ const { key, apiBase } = resolveAuth({
5602
+ flagKey: opts.key,
5603
+ flagApi: opts.api,
5604
+ env: process.env,
5605
+ profile: activeProfile(cfg)
5606
+ });
5607
+ const input = {
5608
+ hasProfileKey: !!key,
5609
+ guideStampVersion: readGuideStamp(await readOrNull3(join4(dir, "docs/hostr.md"))),
5610
+ cliVersion: CLI_VERSION,
5611
+ envKeyFile: await findEnvKey(dir),
5612
+ account: null,
5613
+ webhookUrl: null,
5614
+ online: false
5615
+ };
5616
+ if (key) {
5617
+ const client = makeClient({ apiBase, key });
5618
+ try {
5619
+ const a = await client.account();
5620
+ input.account = { name: a.name, plan: a.plan, assetCount: a.usage.assetCount };
5621
+ input.online = true;
5622
+ input.webhookUrl = await client.webhookGet().then((w) => w.url).catch(() => null);
5623
+ } catch {
5624
+ }
5625
+ }
5626
+ const report = computeStatus(input);
5627
+ out.print(renderStatus(report), { ...report, cliVersion: CLI_VERSION });
5628
+ }
5629
+
5358
5630
  // src/cli.ts
5359
- var program2 = new Command("hostr").description("hostr \u2014 self-hosted video infrastructure (upload, transcode, HLS delivery)").version("0.1.3").option("--key <key>", "API key (overrides HOSTR_API_KEY and the saved profile)").option("--api <url>", "API base URL (overrides HOSTR_API_BASE and the saved profile)").option("--json", "machine-readable output: one JSON document (NDJSON for tail --follow)");
5631
+ var program2 = new Command("hostr").description("hostr \u2014 self-hosted video infrastructure (upload, transcode, HLS delivery)\nRun `npx hostr` with no arguments for setup status and the next step.").version(CLI_VERSION).option("--key <key>", "API key (overrides HOSTR_API_KEY and the saved profile)").option("--api <url>", "API base URL (overrides HOSTR_API_BASE and the saved profile)").option("--json", "machine-readable output: one JSON document (NDJSON for tail --follow)");
5360
5632
  var globals = () => program2.opts();
5633
+ program2.action(async () => {
5634
+ await status(globals());
5635
+ });
5361
5636
  var run = (fn) => async (...args) => {
5362
5637
  const g = globals();
5363
5638
  const ctx = await makeCtx(g);
@@ -5367,7 +5642,7 @@ var run = (fn) => async (...args) => {
5367
5642
  fail(ctx.out, e);
5368
5643
  }
5369
5644
  };
5370
- program2.command("login").description("validate an API key and save it as a profile").option("--profile <name>", "profile name", "default").action(async (opts) => {
5645
+ program2.command("login").description("authorize in the browser and save the key as a profile").option("--profile <name>", "profile name", "default").action(async (opts) => {
5371
5646
  try {
5372
5647
  await login({ ...globals(), ...opts });
5373
5648
  } catch (e) {
@@ -5378,11 +5653,11 @@ program2.command("whoami").description("account, plan, limits, live usage").acti
5378
5653
  program2.command("usage").description("daily usage rows").option("--from <date>", "YYYY-MM-DD (default: 30 days ago)").option("--to <date>", "YYYY-MM-DD (default: today)").action(run(usage));
5379
5654
  var keys = program2.command("keys").description("API key management");
5380
5655
  keys.command("list").action(run(keysList));
5381
- keys.command("create").option("--name <name>").option("--scopes <scopes>", "comma-separated: read,upload,full").action(run(keysCreate));
5656
+ keys.command("create").option("--name <name>").option("--scopes <scopes>", "comma-separated: read,upload,playback,full (default: playback)").option("--write-env <file>", "write HOSTR_API_KEY into <file> instead of printing it").action(run(keysCreate));
5382
5657
  keys.command("revoke <id>").action(run(keysRevoke));
5383
5658
  var webhooks = program2.command("webhooks").description("webhook endpoint config");
5384
5659
  webhooks.command("get").action(run(webhooksGet));
5385
- webhooks.command("set <url>").option("--secret <secret>", "bring your own whsec (default: generated, shown once)").action(run((ctx, url, opts) => webhooksSet(ctx, url, opts)));
5660
+ webhooks.command("set <url>").option("--secret <secret>", "bring your own whsec (default: generated, shown once)").option("--write-env <file>", "write HOSTR_WEBHOOK_SECRET into <file> instead of printing it").action(run((ctx, url, opts) => webhooksSet(ctx, url, opts)));
5386
5661
  webhooks.command("delete").action(run(webhooksDelete));
5387
5662
  webhooks.command("test").description("redeliver the newest stored event to your endpoint").action(run(webhooksTest));
5388
5663
  var subtitles = program2.command("subtitles").description("subtitle tracks (WebVTT)");
@@ -5393,7 +5668,7 @@ var assets = program2.command("assets").description("asset listing and status");
5393
5668
  assets.command("list").option("--status <status>").option("--limit <n>").option("--cursor <cursor>").action(run(assetsList));
5394
5669
  assets.command("get <id>").action(run((ctx, id) => assetsGet(ctx, id)));
5395
5670
  assets.command("delete <id>").description("erase an asset: R2 objects purged, playback ends (requires full scope)").action(run((ctx, id) => assetsDelete(ctx, id)));
5396
- assets.command("token <id>").description("mint playback credentials (requires full scope)").option("--ttl <sec>").option("--viewer-id <id>").action(run((ctx, id, opts) => assetsToken(ctx, id, opts)));
5671
+ assets.command("token <id>").description("mint playback credentials (requires playback scope)").option("--ttl <sec>").option("--viewer-id <id>").action(run((ctx, id, opts) => assetsToken(ctx, id, opts)));
5397
5672
  program2.command("tail").description("event log (durable; ascending). One page by default.").option("-f, --follow", "poll every 2s").option("--type <type>", "filter: upload.created | video.uploaded | video.ready | video.errored").option("--limit <n>").option("--after <cursor>", "start after this event id").action(run(tail));
5398
5673
  program2.command("init").description("make this repo agent-ready: docs/hostr.md + AGENTS.md section + .env.example entries").option("--dir <dir>", "target directory (default: cwd)").action(async (opts) => {
5399
5674
  await init({ ...globals(), ...opts });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hostr/cli",
3
- "version": "0.1.4",
3
+ "version": "0.2.1",
4
4
  "description": "CLI for hostr \u2014 self-hosted video infrastructure (upload, transcode, HLS delivery)",
5
5
  "license": "MIT",
6
6
  "type": "module",