@keyboxed/cli 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/keybox.js CHANGED
@@ -1,6 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
8
  var __esm = (fn, res, err) => function __init() {
5
9
  if (err) throw err[0];
6
10
  try {
@@ -9,10 +13,33 @@ var __esm = (fn, res, err) => function __init() {
9
13
  throw err = [e], e;
10
14
  }
11
15
  };
16
+ var __commonJS = (cb, mod) => function __require() {
17
+ try {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ } catch (e) {
20
+ throw mod = 0, e;
21
+ }
22
+ };
12
23
  var __export = (target, all) => {
13
24
  for (var name in all)
14
25
  __defProp(target, name, { get: all[name], enumerable: true });
15
26
  };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
36
+ // If the importer is in node compatibility mode or this is not an ESM
37
+ // file that has been converted to a CommonJS file using a Babel-
38
+ // compatible transform (i.e. "__esModule" has not been set), then set
39
+ // "default" to the CommonJS "module.exports" for node compatibility.
40
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
41
+ mod
42
+ ));
16
43
 
17
44
  // src/config.ts
18
45
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
@@ -188,7 +215,7 @@ var init_providers = __esm({
188
215
  admin: "^sk_live_",
189
216
  adminHint: "This is a full live secret key. Prefer a restricted key (rk_live_)."
190
217
  },
191
- { id: "cloudflare", label: "Cloudflare", hosts: ["api.cloudflare.com"], header: "authorization", format: "bearer", prefixes: ["CLOUDFLARE_", "CF_"] },
218
+ { id: "cloudflare", label: "Cloudflare", hosts: ["api.cloudflare.com"], header: "authorization", format: "bearer", prefixes: ["CLOUDFLARE_", "CF_"], pattern: "^cf[a-z]t_" },
192
219
  { id: "gemini", label: "Google Gemini", hosts: ["generativelanguage.googleapis.com"], header: "x-goog-api-key", format: "raw", prefixes: ["GEMINI_", "GOOGLE_AI_", "GOOGLE_GENERATIVE_AI_", "GOOGLE_API_"], pattern: "^AIza[0-9A-Za-z_-]{35}$" },
193
220
  { id: "groq", label: "Groq", hosts: ["api.groq.com"], header: "authorization", format: "bearer", prefixes: ["GROQ_"], pattern: "^gsk_" },
194
221
  { id: "mistral", label: "Mistral", hosts: ["api.mistral.ai"], header: "authorization", format: "bearer", prefixes: ["MISTRAL_"] },
@@ -216,6 +243,11 @@ var init_providers = __esm({
216
243
  { id: "vercel", label: "Vercel", hosts: ["api.vercel.com"], header: "authorization", format: "bearer", prefixes: ["VERCEL_"] },
217
244
  { id: "netlify", label: "Netlify", hosts: ["api.netlify.com"], header: "authorization", format: "bearer", prefixes: ["NETLIFY_"] },
218
245
  { id: "digitalocean", label: "DigitalOcean", hosts: ["api.digitalocean.com"], header: "authorization", format: "bearer", prefixes: ["DIGITALOCEAN_", "DO_"], pattern: "^dop_v1_" },
246
+ { id: "workos", label: "WorkOS", hosts: ["api.workos.com"], header: "authorization", format: "bearer", prefixes: ["WORKOS_"] },
247
+ { id: "retell", label: "Retell AI", hosts: ["api.retellai.com"], header: "authorization", format: "bearer", prefixes: ["RETELL_"] },
248
+ { id: "nvidia", label: "NVIDIA NIM", hosts: ["integrate.api.nvidia.com"], header: "authorization", format: "bearer", prefixes: ["NVIDIA_", "NVAPI", "NIM_"], pattern: "^nvapi-" },
249
+ { id: "plane", label: "Plane", hosts: ["api.plane.so"], header: "x-api-key", format: "raw", prefixes: ["PLANE_"], pattern: "^plane_api_" },
250
+ { id: "crates", label: "crates.io", hosts: ["crates.io"], header: "authorization", format: "raw", prefixes: ["CRATES_IO_", "CARGO_REGISTRY_TOKEN"], pattern: "^cio[A-Za-z0-9]{30,}$" },
219
251
  { id: "sentry", label: "Sentry", hosts: ["sentry.io"], header: "authorization", format: "bearer", prefixes: ["SENTRY_"], pattern: "^sntry[us]_" }
220
252
  ];
221
253
  UNSUPPORTED = [
@@ -557,8 +589,8 @@ function list(question, options, o) {
557
589
  let cur = Math.min(o.def, options.length - 1);
558
590
  let top = 0;
559
591
  let drawn = 0;
560
- const cols = () => Math.max(24, (out2.columns ?? 80) - 1);
561
- const rows = () => Math.max(3, Math.min(12, (out2.rows ?? 24) - 6, options.length));
592
+ const cols = () => Math.max(24, (out2.columns || 80) - 1);
593
+ const rows = () => Math.max(3, Math.min(12, (out2.rows || 24) - 6, options.length));
562
594
  const help2 = () => {
563
595
  const pos = shown.length > rows() ? `${cur + 1}/${shown.length} \xB7 ` : "";
564
596
  if (o.multi) return `${pos}\u2191\u2193 move \xB7 space pick \xB7 a all \xB7 n none \xB7 enter done \xB7 ${checked.size} picked`;
@@ -673,17 +705,17 @@ function list(question, options, o) {
673
705
  });
674
706
  }
675
707
  async function choose(question, options, def = 0) {
676
- if (!process.stdin.isTTY || !color) return options[def].value;
708
+ if (!canList()) return options[def].value;
677
709
  const [k] = await list(question, options, { multi: false, def, checked: /* @__PURE__ */ new Set() });
678
710
  return options[k].value;
679
711
  }
680
712
  async function checklist(question, options, preselected) {
681
713
  const checked = new Set(options.flatMap((opt, k) => preselected(opt.value) ? [k] : []));
682
- if (!process.stdin.isTTY || !color || !options.length) return [...checked].map((k) => options[k].value);
714
+ if (!canList() || !options.length) return [...checked].map((k) => options[k].value);
683
715
  const picked = await list(question, options, { multi: true, def: 0, checked });
684
716
  return picked.map((k) => options[k].value);
685
717
  }
686
- var GLYPHS, MAX_DOTS, clip;
718
+ var GLYPHS, MAX_DOTS, clip, canList;
687
719
  var init_prompt = __esm({
688
720
  "src/prompt.ts"() {
689
721
  "use strict";
@@ -693,12 +725,15 @@ var init_prompt = __esm({
693
725
  GLYPHS = "\u2591\u2592\u2593\u2588#%&@$";
694
726
  MAX_DOTS = 32;
695
727
  clip = (s, n) => n <= 0 ? "" : s.length <= n ? s : n === 1 ? "\u2026" : `${s.slice(0, n - 1)}\u2026`;
728
+ canList = () => Boolean(process.stdin.isTTY && process.stderr.isTTY) && process.env.TERM !== "dumb";
696
729
  }
697
730
  });
698
731
 
699
732
  // src/migrate.ts
700
733
  import { spawn, spawnSync } from "node:child_process";
701
734
  import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "node:fs";
735
+ import { homedir as homedir2 } from "node:os";
736
+ import { join as join2 } from "node:path";
702
737
  function has(bin2) {
703
738
  return spawnSync(process.platform === "win32" ? "where" : "which", [bin2], { stdio: "ignore" }).status === 0;
704
739
  }
@@ -735,6 +770,150 @@ function pickField(fields) {
735
770
  const named = fields.find((f) => /^(credential|api[ _-]?key|token|secret|password|key)$/i.test(f.label ?? f.name ?? f.id ?? "") && f.value);
736
771
  return (named ?? fields.find((f) => (f.type === "CONCEALED" || f.type === 1) && f.value))?.value;
737
772
  }
773
+ function infisicalBase() {
774
+ const fromEnv = process.env.INFISICAL_DOMAIN?.replace(/\/+$/, "");
775
+ if (fromEnv) return /\/api$/.test(fromEnv) ? fromEnv : `${fromEnv}/api`;
776
+ try {
777
+ const cfg = JSON.parse(readFileSync2(join2(homedir2(), ".infisical", "infisical-config.json"), "utf8"));
778
+ const p = cfg.profiles?.find((x) => x.name === cfg.activeProfile) ?? cfg.profiles?.[0];
779
+ if (p?.domain) return p.domain.replace(/\/+$/, "");
780
+ } catch {
781
+ }
782
+ return "https://app.infisical.com/api";
783
+ }
784
+ async function fetchInfisical(_arg, o) {
785
+ let token2 = process.env.INFISICAL_TOKEN?.trim() ?? "";
786
+ if (!token2) {
787
+ try {
788
+ token2 = (await capture("infisical", ["user", "get", "token", "--plain", "--silent"])).trim();
789
+ } catch {
790
+ throw new UserError("Sign in to Infisical first: infisical login");
791
+ }
792
+ }
793
+ const base = infisicalBase();
794
+ const get = async (path2) => {
795
+ let r;
796
+ try {
797
+ r = await fetch(base + path2, { headers: { authorization: `Bearer ${token2}` } });
798
+ } catch {
799
+ throw new UserError(`Cannot reach Infisical at ${base}.`);
800
+ }
801
+ if (r.status === 401 || r.status === 403) throw new UserError("Infisical refused the session. Run infisical login and try again.");
802
+ if (!r.ok) throw new UserError(`Infisical returned HTTP ${r.status} for ${path2.split("?")[0]}.`);
803
+ return await r.json();
804
+ };
805
+ const wanted = (list2) => list2?.split(",").map((x) => x.trim().toLowerCase()).filter(Boolean);
806
+ const onlyProjects = wanted(o.project);
807
+ const onlyEnvs = wanted(o.env);
808
+ const { workspaces = [] } = await get("/v1/workspace");
809
+ const projects = workspaces.filter(
810
+ (p) => p.environments?.length && (!p.type || p.type === "secret-manager") && (!onlyProjects || onlyProjects.includes(p.id.toLowerCase()) || onlyProjects.includes(p.name.toLowerCase()))
811
+ );
812
+ if (!projects.length) throw new UserError(onlyProjects ? `No Infisical project named ${o.project}.` : "This Infisical login has no secret projects.");
813
+ const path = o.path ?? "/";
814
+ const parts2 = projects.flatMap(
815
+ (p) => p.environments.filter((e) => !onlyEnvs || onlyEnvs.includes(e.slug.toLowerCase())).map((e) => ({ project: p, env: e, secrets: [] }))
816
+ );
817
+ await Promise.all(
818
+ parts2.map(async (part) => {
819
+ const q = new URLSearchParams({
820
+ workspaceId: part.project.id,
821
+ environment: part.env.slug,
822
+ secretPath: path,
823
+ recursive: "true",
824
+ include_imports: "true",
825
+ expandSecretReferences: "true"
826
+ });
827
+ const r = await get(`/v3/secrets/raw?${q}`);
828
+ const own = [...r.secrets ?? []].sort((a, b) => Number(b.type === "personal") - Number(a.type === "personal"));
829
+ const imported = (r.imports ?? []).flatMap((i) => (i.secrets ?? []).map((x) => ({ ...x, secretPath: x.secretPath ?? i.secretPath ?? "/" })));
830
+ const seen = /* @__PURE__ */ new Set();
831
+ for (const x of [...own, ...imported]) {
832
+ const id = `${x.secretPath ?? "/"}
833
+ ${x.secretKey}`;
834
+ if (seen.has(id)) continue;
835
+ seen.add(id);
836
+ part.secrets.push(x);
837
+ }
838
+ })
839
+ );
840
+ const full = parts2.filter((x) => x.secrets.length);
841
+ const many = projects.length > 1;
842
+ const label2 = (x) => `${many ? `${x.project.name} \xB7 ` : ""}${x.env.name}`;
843
+ let chosen = full;
844
+ if (o.interactive && full.length > 1) {
845
+ const folders = (x) => new Set(x.secrets.map((s) => s.secretPath ?? "/").filter((f) => f !== "/")).size;
846
+ const keep = new Set(
847
+ await checklist(
848
+ "Read which projects and environments?",
849
+ full.map((x, i) => ({
850
+ value: i,
851
+ label: label2(x),
852
+ hint: `${x.secrets.length} entr${x.secrets.length === 1 ? "y" : "ies"}${folders(x) ? `, ${folders(x)} folder${folders(x) === 1 ? "" : "s"}` : ""}`
853
+ })),
854
+ () => true
855
+ )
856
+ );
857
+ chosen = full.filter((_, i) => keep.has(i));
858
+ }
859
+ const empty = parts2.filter((x) => !x.secrets.length);
860
+ if (empty.length) note(`Empty: ${empty.map(label2).join(", ")}`);
861
+ return chosen.flatMap(
862
+ (x) => x.secrets.map((sec) => {
863
+ const folder = (sec.secretPath ?? "/").replace(/^\/+|\/+$/g, "");
864
+ return {
865
+ name: sec.secretKey,
866
+ value: sec.secretValue ?? "",
867
+ origin: `infisical:${x.project.name}/${x.env.slug}${folder ? `/${folder}` : ""}/${sec.secretKey}`,
868
+ scope: [
869
+ ...folder ? [{ part: folder.split("/").at(-1), at: "prefix" }] : [],
870
+ ...many ? [{ part: x.project.name, at: "prefix" }] : [],
871
+ { part: x.env.slug, at: "suffix" }
872
+ ]
873
+ };
874
+ })
875
+ );
876
+ }
877
+ function disambiguate(found) {
878
+ const norm = (n) => /^[A-Z][A-Z0-9_]{0,63}$/.test(n) ? n : toSecretName(n);
879
+ const taken = /* @__PURE__ */ new Map();
880
+ const out2 = [];
881
+ let merged = 0;
882
+ for (const f of found) {
883
+ const base = norm(f.name);
884
+ const holder = taken.get(base);
885
+ if (!holder) {
886
+ taken.set(base, f);
887
+ out2.push(f);
888
+ continue;
889
+ }
890
+ if (holder.value === f.value) {
891
+ merged++;
892
+ continue;
893
+ }
894
+ const theirs = new Set((holder.scope ?? []).map((q) => toSecretName(q.part)));
895
+ let name = base;
896
+ for (const q of f.scope ?? []) {
897
+ const part = toSecretName(q.part).replace(/^KEY_/, "");
898
+ if (theirs.has(part) || name.startsWith(`${part}_`) || name.endsWith(`_${part}`)) continue;
899
+ name = toSecretName(q.at === "prefix" ? `${part}_${name}` : `${name}_${part}`);
900
+ if (!taken.has(name) || taken.get(name).value === f.value) break;
901
+ }
902
+ if (taken.get(name)?.value === f.value) {
903
+ merged++;
904
+ continue;
905
+ }
906
+ if (taken.has(name)) {
907
+ let i = 2;
908
+ while (taken.has(`${name}_${i}`)) i++;
909
+ name = `${name}_${i}`;
910
+ }
911
+ const renamed = { ...f, name };
912
+ taken.set(name, renamed);
913
+ out2.push(renamed);
914
+ }
915
+ return { found: out2, merged };
916
+ }
738
917
  async function readRef(ref) {
739
918
  const m = /^([a-z0-9-]+):\/\/(.+)$/.exec(ref);
740
919
  if (!m) throw new UserError(`Not a reference: ${ref}. Try op://vault/item/field, vault://path#field, env://NAME \u2026`);
@@ -791,69 +970,90 @@ function classify(found, existing, opts = {}) {
791
970
  const unknown = [];
792
971
  const seen = /* @__PURE__ */ new Set();
793
972
  for (const f of found) {
794
- if (opts.only?.length && !opts.only.includes(f.name)) continue;
795
- if (seen.has(f.name)) continue;
796
- seen.add(f.name);
797
- const unsupported = UNSUPPORTED.find((u) => u.match.test(f.name));
798
- const d = detect(f.name, f.value);
799
- const looksLikeKey = f.explicit || CREDENTIAL_NAME.test(f.name) || d.via === "value";
800
- if (!looksLikeKey || PUBLIC_NAME.test(f.name)) {
801
- if (d.provider || unsupported) skipped.push({ name: f.name, why: "not a credential" });
973
+ const name = /^[A-Z][A-Z0-9_]{0,63}$/.test(f.name) ? f.name : toSecretName(f.name);
974
+ if (opts.only?.length && !opts.only.includes(f.name) && !opts.only.includes(name)) continue;
975
+ if (seen.has(name)) continue;
976
+ seen.add(name);
977
+ const renamed = name !== f.name ? `stored as ${name}` : "";
978
+ const item = { ...f, name };
979
+ const v = f.value.trim();
980
+ if (!v) {
981
+ skipped.push({ name: f.name, why: "empty value" });
802
982
  continue;
803
983
  }
804
- if (unsupported) {
805
- skipped.push({ name: f.name, why: unsupported.why });
984
+ if (PLACEHOLDER.test(v)) {
985
+ skipped.push({ name: f.name, why: "placeholder value" });
806
986
  continue;
807
987
  }
808
- if (f.value.trim().length < 8 || /^(x+|changeme|todo|your[-_].*|<.*>|\.\.\.)$/i.test(f.value.trim())) {
809
- skipped.push({ name: f.name, why: "empty or placeholder" });
988
+ const unsupported = UNSUPPORTED.find((u) => u.match.test(name));
989
+ if (unsupported) {
990
+ skipped.push({ name: f.name, why: unsupported.why });
810
991
  continue;
811
992
  }
812
- if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(f.name)) {
813
- skipped.push({ name: f.name, why: "name must be UPPER_SNAKE_CASE" });
993
+ const d = detect(name, f.value);
994
+ const looksLikeKey = f.explicit || CREDENTIAL_NAME.test(name) || d.via === "value";
995
+ const isPublic = PUBLIC_NAME.test(name);
996
+ if (d.provider && d.mismatch) {
997
+ unknown.push({ ...item, why: [`name says ${d.mismatch.label}, value looks like ${d.provider.label}`, renamed].filter(Boolean).join(" \xB7 "), guess: d.mismatch });
814
998
  continue;
815
999
  }
816
- if (!d.provider) {
817
- unknown.push(f);
1000
+ if (d.provider && looksLikeKey && !isPublic && v.length >= 8) {
1001
+ const flags = [];
1002
+ if (renamed) flags.push(renamed);
1003
+ if (d.adminHint) flags.push("admin-grade");
1004
+ if (d.via === "name") flags.push("guessed from name");
1005
+ plans.push({ ...item, provider: d.provider, hosts: d.provider.hosts, header: d.provider.header, format: d.provider.format, flags, replaces: existing.has(name) });
818
1006
  continue;
819
1007
  }
820
- const flags = [];
821
- if (d.adminHint) flags.push("admin-grade");
822
- if (d.mismatch) flags.push(`name says ${d.mismatch.label}`);
823
- if (d.via === "name") flags.push("guessed from name");
824
- plans.push({ ...f, provider: d.provider, hosts: d.provider.hosts, header: d.provider.header, format: d.provider.format, flags, replaces: existing.has(f.name) });
1008
+ const why = [
1009
+ isPublic ? "looks like a public value" : !looksLikeKey ? "name doesn't look like a key" : v.length < 8 ? "very short" : "no preset",
1010
+ renamed
1011
+ ].filter(Boolean).join(" \xB7 ");
1012
+ unknown.push({ ...item, why, guess: d.provider });
825
1013
  }
1014
+ const rank = (o) => o.why?.startsWith("name says") ? 0 : o.why?.startsWith("no preset") ? 1 : o.why?.startsWith("very short") ? 2 : 3;
1015
+ unknown.sort((a, b) => rank(a) - rank(b));
826
1016
  return { plans, skipped, unknown };
827
1017
  }
828
1018
  function printSkipped(skipped) {
829
1019
  const byWhy = /* @__PURE__ */ new Map();
830
- for (const s of skipped) byWhy.set(s.why, [...byWhy.get(s.why) ?? [], s.name]);
1020
+ for (const s of skipped) {
1021
+ const why = s.why.replace(/ · stored as [A-Z0-9_]+/, "");
1022
+ byWhy.set(why, [...byWhy.get(why) ?? [], s.name]);
1023
+ }
831
1024
  for (const [why, names] of byWhy) {
832
1025
  const list2 = names.length > 6 ? `${names.slice(0, 6).join(", ")} +${names.length - 6} more` : names.join(", ");
833
1026
  process.stderr.write(` ${c.dim(`${why}: ${list2}`)}
834
1027
  `);
835
1028
  }
836
1029
  }
837
- async function placeUnknown(f, progress, replaces) {
838
- const pick = await choose(`${c.dim(progress)} Where may ${c.bold(f.name)} be sent?`, [
1030
+ async function pickDestination(name, o) {
1031
+ const pick = await choose(`${o.progress ? c.dim(o.progress) + " " : ""}Where may ${c.bold(name)} be sent?`, [
1032
+ ...o.guess ? [{ value: o.guess.id, label: o.guess.label, hint: `${o.guess.hosts[0]} \xB7 guessed from the name` }] : [],
839
1033
  { value: "_custom", label: "A host I will type", hint: "e.g. api.example.com" },
840
- { value: "_skip", label: "Skip this one" },
841
- ...PROVIDERS.map((p) => ({ value: p.id, label: p.label, hint: p.hosts[0] }))
1034
+ ...o.park ? [
1035
+ { value: "_park", label: "Not sure yet: park it", hint: "stored, unusable until you give it a host" },
1036
+ { value: "_park_rest", label: "Park this and all the rest", hint: "decide later with keybox secrets bind" }
1037
+ ] : [],
1038
+ { value: "_skip", label: o.skipLabel ?? "Skip this one" },
1039
+ ...PROVIDERS.filter((p) => p !== o.guess).map((p) => ({ value: p.id, label: p.label, hint: p.hosts[0] }))
842
1040
  ]);
843
- if (pick === "_skip") return null;
1041
+ if (pick === "_skip") return "skip";
1042
+ if (pick === "_park") return PARKED;
1043
+ if (pick === "_park_rest") return "park-rest";
844
1044
  if (pick !== "_custom") {
845
1045
  const p = byId(pick);
846
- return { ...f, provider: p, hosts: p.hosts, header: p.header, format: p.format, flags: ["chosen by you"], replaces };
1046
+ return { hosts: p.hosts, header: p.header, format: p.format, provider: p, flag: "chosen by you" };
847
1047
  }
848
1048
  let host = "";
849
1049
  for (let tries = 0; tries < 3 && !host; tries++) {
850
1050
  const raw = (await ask("Hostname it may be sent to (empty to skip):")).trim().toLowerCase();
851
- if (!raw) return null;
1051
+ if (!raw) return "skip";
852
1052
  const h = raw.replace(/^[a-z]+:\/\//, "").replace(/[/?#].*$/, "").replace(/:\d+$/, "");
853
1053
  if (/^[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,63}$/.test(h)) host = h;
854
1054
  else warn(`${raw} is not a hostname. Example: api.example.com`);
855
1055
  }
856
- if (!host) return null;
1056
+ if (!host) return "skip";
857
1057
  const how = await choose(`How does ${host} expect the key?`, [
858
1058
  { value: "bearer", label: "Authorization: Bearer <key>", hint: "most APIs" },
859
1059
  { value: "x-api-key", label: "x-api-key: <key>" },
@@ -862,7 +1062,45 @@ async function placeUnknown(f, progress, replaces) {
862
1062
  ]);
863
1063
  const header = how === "x-api-key" ? "x-api-key" : how === "header" ? (await ask("Header name:", "x-api-key")).toLowerCase() : "authorization";
864
1064
  const format = how === "bearer" ? "bearer" : how === "basic" ? "basic" : "raw";
865
- return { ...f, hosts: [host], header, format, flags: ["custom host"], replaces };
1065
+ return { hosts: [host], header, format, flag: "custom host" };
1066
+ }
1067
+ function prefixes(name) {
1068
+ const parts2 = name.split("_");
1069
+ const out2 = [];
1070
+ for (let n = Math.min(parts2.length - 1, 3); n >= 1; n--) if (parts2.slice(0, n).join("_").length >= 3) out2.push(parts2.slice(0, n).join("_") + "_");
1071
+ return out2;
1072
+ }
1073
+ async function placeMany(items, o) {
1074
+ const out2 = /* @__PURE__ */ new Map();
1075
+ const queue = [...items];
1076
+ let n = 0;
1077
+ while (queue.length) {
1078
+ const item = queue.shift();
1079
+ n++;
1080
+ const a = await pickDestination(item.name, { guess: item.guess, progress: `(${n}/${n + queue.length})`, park: o.park, skipLabel: o.skipLabel });
1081
+ if (a === "park-rest") {
1082
+ for (const x of [item, ...queue]) out2.set(x.name, PARKED);
1083
+ break;
1084
+ }
1085
+ const dest = a === "skip" ? null : a;
1086
+ out2.set(item.name, dest);
1087
+ if (!dest) continue;
1088
+ const family = prefixes(item.name).map((p) => queue.filter((x) => x.name.startsWith(p))).find((xs) => xs.length);
1089
+ if (!family?.length) continue;
1090
+ const where = dest.hosts.length ? `to ${dest.hosts.join(", ")}` : "parked as well";
1091
+ const same = new Set(
1092
+ await checklist(
1093
+ `Send ${family.length === 1 ? "this one" : `these ${family.length}`} ${where} too?`,
1094
+ family.map((x) => ({ value: x.name, label: x.name })),
1095
+ () => true
1096
+ )
1097
+ );
1098
+ for (const x of family.filter((x2) => same.has(x2.name))) {
1099
+ out2.set(x.name, dest);
1100
+ queue.splice(queue.indexOf(x), 1);
1101
+ }
1102
+ }
1103
+ return out2;
866
1104
  }
867
1105
  function dotenvFiles() {
868
1106
  try {
@@ -892,26 +1130,39 @@ async function migrate(opts) {
892
1130
  const source = SOURCES.find((s) => s.id === id) ?? (existsSync2(from) ? SOURCES[0] : void 0);
893
1131
  if (!source) throw new UserError(`Unknown source ${id}. Sources: ${SOURCES.map((s) => s.id).join(", ")}.`);
894
1132
  const fileArg = source === SOURCES[0] && !arg ? from : arg;
895
- const stop = spin(`Reading from ${source.label}`);
1133
+ const interactive = Boolean(process.stdin.isTTY) && !opts.yes && !opts.dryRun;
896
1134
  let found;
897
1135
  let existing;
898
- try {
899
- [found, existing] = await Promise.all([
900
- source.fetch(fileArg, opts),
901
- api("GET", "/secrets").then((r) => new Set(r.map((x) => x.name)))
902
- ]);
903
- } catch (err) {
904
- stop();
905
- throw err;
1136
+ {
1137
+ const existingP = api("GET", "/secrets").then((r) => new Set(r.map((x) => x.name)));
1138
+ existingP.catch(() => {
1139
+ });
1140
+ const raw = await source.fetch(fileArg, { ...opts, interactive: !!process.stdin.isTTY && !opts.yes });
1141
+ const stop = spin(`Reading from ${source.label}`);
1142
+ try {
1143
+ existing = await existingP;
1144
+ } catch (err) {
1145
+ stop();
1146
+ throw err;
1147
+ }
1148
+ const d = disambiguate(raw);
1149
+ found = d.found;
1150
+ const kept = new Set(found);
1151
+ for (const f of raw) if (!kept.has(f)) f.value = "";
1152
+ stop(
1153
+ `${c.accent("\u25A0")} Read ${found.length} entr${found.length === 1 ? "y" : "ies"} from ${source.label}${d.merged ? c.dim(` (${d.merged} duplicate${d.merged === 1 ? "" : "s"} with the same value merged)`) : ""} ${c.dim("\xB7 names only; values are never shown")}`
1154
+ );
906
1155
  }
907
- stop(`${c.accent("\u25A0")} Read ${found.length} entr${found.length === 1 ? "y" : "ies"} from ${source.label} ${c.dim("(names only below; values are never shown)")}`);
908
1156
  const { plans: matched, skipped, unknown } = classify(found, existing, { only: opts.only });
909
- const interactive = Boolean(process.stdin.isTTY) && !opts.yes && !opts.dryRun;
910
1157
  const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
911
1158
  const tally = [
912
1159
  [matched.length, "recognised", "known provider, destination filled in"],
913
- [unknown.length, "no preset", interactive ? "you pick which to keep and where each may go" : "skipped; add with keybox secrets add NAME --host"],
914
- [skipped.length, "skipped", "not credentials, placeholders or unsupported"]
1160
+ [
1161
+ unknown.length,
1162
+ "to pick",
1163
+ interactive ? "no preset: you pick which to store, then a host or park them" : opts.park ? "no preset: stored parked (no host yet)" : "not stored; add --park to store them without a host"
1164
+ ],
1165
+ [skipped.length, "skipped", "empty, placeholders, or not usable as an API header (reasons below)"]
915
1166
  ];
916
1167
  for (const [n, label2, why] of tally) if (n) process.stderr.write(` ${c.bold(String(n).padStart(3))} ${label2.padEnd(11)}${c.dim(why)}
917
1168
  `);
@@ -929,20 +1180,42 @@ async function migrate(opts) {
929
1180
  plans = matched.filter((p) => keep.has(p.name));
930
1181
  }
931
1182
  const later = [];
932
- if (unknown.length && !interactive) for (const f of unknown) later.push({ name: f.name, why: "no preset; add it with --host" });
1183
+ const asPlan = (f, d) => ({
1184
+ ...f,
1185
+ provider: d.provider,
1186
+ hosts: d.hosts,
1187
+ header: d.header,
1188
+ format: d.format,
1189
+ flags: [d.flag],
1190
+ replaces: existing.has(f.name)
1191
+ });
1192
+ if (unknown.length && !interactive) {
1193
+ for (const f of unknown) {
1194
+ if (opts.park) plans.push(asPlan(f, PARKED));
1195
+ else later.push({ name: f.name, why: `not stored (${f.why})` });
1196
+ }
1197
+ }
933
1198
  if (unknown.length && interactive) {
934
1199
  const pick = new Set(
935
1200
  await checklist(
936
- `${count(unknown.length, "key has", "keys have")} no preset. Pick the ones to set up now (the rest are skipped):`,
937
- unknown.map((f) => ({ value: f.name, label: f.name, hint: f.origin })),
938
- () => false
1201
+ `${count(unknown.length, "more entry", "more entries")} have no preset. Which should Keybox hold? (space toggles, a = all)`,
1202
+ unknown.map((f) => ({ value: f.name, label: f.name, hint: f.why ?? f.origin })),
1203
+ (n) => /^(no preset|name says)/.test(unknown.find((f) => f.name === n)?.why ?? "")
939
1204
  )
940
1205
  );
941
1206
  const chosen = unknown.filter((f) => pick.has(f.name));
942
1207
  for (const f of unknown) if (!pick.has(f.name)) later.push({ name: f.name, why: "not picked" });
943
- for (const [n, f] of chosen.entries()) {
944
- const plan = await placeUnknown(f, `(${n + 1}/${chosen.length})`, existing.has(f.name));
945
- if (plan) plans.push(plan);
1208
+ let how = chosen.length > 1 ? "" : "each";
1209
+ if (chosen.length > 1) {
1210
+ how = await choose(`Where may these ${chosen.length} go?`, [
1211
+ { value: "each", label: "Choose now", hint: "keys that share a prefix share the answer" },
1212
+ { value: "park", label: "Park them all, decide later", hint: "stored encrypted; no agent can use one until you run keybox secrets bind" }
1213
+ ]);
1214
+ }
1215
+ const placed = how === "park" ? new Map(chosen.map((f) => [f.name, PARKED])) : await placeMany(chosen, { park: true });
1216
+ for (const f of chosen) {
1217
+ const d = placed.get(f.name);
1218
+ if (d) plans.push(asPlan(f, d));
946
1219
  else later.push({ name: f.name, why: "skipped by you" });
947
1220
  }
948
1221
  }
@@ -950,11 +1223,17 @@ async function migrate(opts) {
950
1223
  process.stdout.write(
951
1224
  headed([
952
1225
  ["NAME", "PROVIDER", "ONLY SENT TO", ""],
953
- ...plans.map((p) => [p.name, p.provider?.label ?? "Custom", p.hosts.join(","), [p.replaces ? "replaces existing" : "new", ...p.flags].join(", ")])
1226
+ ...plans.map((p) => [
1227
+ p.name,
1228
+ p.hosts.length ? p.provider?.label ?? "Custom" : "Parked",
1229
+ p.hosts.join(",") || c.dim("nowhere yet"),
1230
+ [p.replaces ? "replaces existing" : "new", ...p.flags.filter((x) => x !== "parked")].join(", ")
1231
+ ])
954
1232
  ])
955
1233
  );
956
1234
  }
957
1235
  if (!interactive) printSkipped(later);
1236
+ if (!interactive && later.length) note("To keep those too: re-run with --park (stored, no host yet), or run keybox migrate at a terminal to pick hosts.");
958
1237
  for (const p of plans.filter((p2) => p2.flags.includes("admin-grade"))) {
959
1238
  warn(`${p.name} is an admin-grade key. ${p.provider?.adminHint ?? ""} Keybox blocks key-minting calls either way.`);
960
1239
  }
@@ -964,19 +1243,27 @@ async function migrate(opts) {
964
1243
  throw new UserError("Cancelled. Re-run with --yes to skip the prompt.");
965
1244
  }
966
1245
  let stored = 0;
1246
+ let oldWorker = false;
967
1247
  for (const p of plans) {
1248
+ if (oldWorker && !p.hosts.length) continue;
968
1249
  try {
969
1250
  const r = await api("PUT", `/secrets/${p.name}`, { hosts: p.hosts, header: p.header, format: p.format, value: p.value });
970
- ok(`${p.name} ${c.dim(`\u2192 ${p.hosts.join(", ")}${r.fingerprint ? ` \xB7 fp ${r.fingerprint}` : ""}`)}`);
1251
+ ok(`${p.name} ${c.dim(`\u2192 ${p.hosts.join(", ") || "parked"}${r.fingerprint ? ` \xB7 fp ${r.fingerprint}` : ""}`)}`);
971
1252
  stored++;
972
1253
  } catch (err) {
973
- warn(`${p.name}: ${err.message}`);
1254
+ const msg = err.message;
1255
+ if (!p.hosts.length && /hosts must list 1-16/.test(msg)) {
1256
+ oldWorker = true;
1257
+ warn("Your Worker is older than 0.2.3 and cannot hold parked keys. Run keybox update, then migrate again for those.");
1258
+ } else warn(`${p.name}: ${msg}`);
974
1259
  }
975
1260
  p.value = "";
976
1261
  }
977
1262
  found.forEach((f) => f.value = "");
978
1263
  process.stderr.write("\n");
1264
+ const parked = plans.filter((p) => !p.hosts.length).length;
979
1265
  step(`Stored ${stored}.`);
1266
+ if (parked && !oldWorker) note(`${parked} parked. Give them hosts when you know: keybox secrets bind (or Set host in keybox ui)`);
980
1267
  if (opts.quietNext) return;
981
1268
  if (source.id === "dotenv" || source.id === "env") {
982
1269
  note(`${fileArg ?? "Your shell"} still holds the original values. Once Keybox works, delete them there and rotate`);
@@ -986,7 +1273,7 @@ async function migrate(opts) {
986
1273
  }
987
1274
  note('Next: keybox agents create NAME --allow "METHOD host/path" then keybox run NAME -- your command');
988
1275
  }
989
- var json, SOURCES, NOT_READABLE;
1276
+ var json, SOURCES, NOT_READABLE, PLACEHOLDER, PARKED;
990
1277
  var init_migrate = __esm({
991
1278
  "src/migrate.ts"() {
992
1279
  "use strict";
@@ -1086,14 +1373,8 @@ var init_migrate = __esm({
1086
1373
  id: "infisical",
1087
1374
  label: "Infisical",
1088
1375
  bin: "infisical",
1089
- usage: "keybox migrate --from infisical [--env dev --path /]",
1090
- async fetch(_arg, o) {
1091
- const args = ["export", "--format", "json"];
1092
- if (o.env) args.push("--env", o.env);
1093
- if (o.path) args.push("--path", o.path);
1094
- if (o.project) args.push("--projectId", o.project);
1095
- return json(await capture("infisical", args)).map((s) => ({ name: s.key, value: s.value, origin: `infisical:${s.key}` }));
1096
- }
1376
+ usage: "keybox migrate --from infisical [--project NAME,\u2026] [--env dev,prod] [--path /]",
1377
+ fetch: fetchInfisical
1097
1378
  },
1098
1379
  {
1099
1380
  id: "vault",
@@ -1182,6 +1463,8 @@ var init_migrate = __esm({
1182
1463
  lastpass: "Use `lpass show --password ITEM | keybox secrets add NAME` for each key.",
1183
1464
  keepass: "Export is a plaintext file. Prefer `keepassxc-cli show -sa password DB ENTRY | keybox secrets add NAME` per key."
1184
1465
  };
1466
+ PLACEHOLDER = /^(x+|changeme|todo|tbd|none|null|your[-_ ].*|<.*>|\.\.\.|\*+)$/i;
1467
+ PARKED = { hosts: [], header: "authorization", format: "bearer", flag: "parked" };
1185
1468
  }
1186
1469
  });
1187
1470
 
@@ -1225,6 +1508,7 @@ __export(commands_exports, {
1225
1508
  buildGrants: () => buildGrants2,
1226
1509
  run: () => run,
1227
1510
  secretsAdd: () => secretsAdd,
1511
+ secretsBind: () => secretsBind,
1228
1512
  secretsImport: () => secretsImport,
1229
1513
  secretsList: () => secretsList,
1230
1514
  secretsRm: () => secretsRm,
@@ -1272,9 +1556,55 @@ async function secretsList() {
1272
1556
  process.stdout.write(
1273
1557
  headed([
1274
1558
  ["NAME", "HOSTS", "HEADER", "FINGERPRINT", "LAST USED"],
1275
- ...rows.map((s) => [s.name, s.hosts.join(","), `${s.header} (${s.format})`, s.fingerprint ?? "-", ago(s.last_used ?? null)])
1559
+ ...rows.map((s) => [s.name, s.hosts.join(",") || c.warn("parked"), `${s.header} (${s.format})`, s.fingerprint ?? "-", ago(s.last_used ?? null)])
1276
1560
  ])
1277
1561
  );
1562
+ const parked = rows.filter((s) => !s.hosts.length).length;
1563
+ if (parked) note(`${parked} parked: stored, but no agent can use ${parked === 1 ? "it" : "them"} until bound to a host. Run keybox secrets bind.`);
1564
+ }
1565
+ async function secretsBind(name, opts) {
1566
+ const rows = await api("GET", "/secrets");
1567
+ const bind = async (n2, d) => {
1568
+ const r = await api("PATCH", `/secrets/${n2}`, { hosts: d.hosts, header: d.header, format: d.format });
1569
+ ok(`${n2} ${c.dim(`\u2192 ${r.hosts.join(", ") || "parked"} \xB7 ${r.header} (${r.format})${r.fingerprint ? ` \xB7 fp ${r.fingerprint}` : ""}`)}`);
1570
+ };
1571
+ if (name) {
1572
+ const row = rows.find((s) => s.name === name);
1573
+ if (!row) throw new UserError(`No secret named ${name}. See keybox secrets list.`);
1574
+ if (opts.host?.length || opts.preset) {
1575
+ const p = opts.preset ? PRESETS[opts.preset] : void 0;
1576
+ if (opts.preset && !p) throw new UserError(`Unknown preset ${opts.preset}. Known: ${Object.keys(PRESETS).join(", ")}.`);
1577
+ return bind(name, {
1578
+ hosts: opts.host?.length ? opts.host.map((h) => h.toLowerCase()) : p.hosts,
1579
+ header: opts.header ?? p?.header ?? row.header,
1580
+ format: opts.format ?? p?.format ?? row.format,
1581
+ flag: "bound"
1582
+ });
1583
+ }
1584
+ if (!process.stdin.isTTY) throw new UserError(`Say where: keybox secrets bind ${name} --host HOST (or --preset NAME).`);
1585
+ const placed2 = await placeMany([{ name, guess: detect(name, "").provider }], { park: false, skipLabel: "Leave it as it is" });
1586
+ const d = placed2.get(name);
1587
+ return d ? bind(name, d) : note(`${name} unchanged.`);
1588
+ }
1589
+ const parked = rows.filter((s) => !s.hosts.length);
1590
+ if (!parked.length) return note("No parked keys. To move one: keybox secrets bind NAME --host HOST");
1591
+ if (!process.stdin.isTTY) throw new UserError(`${parked.length} parked: ${parked.map((s) => s.name).join(", ")}. Bind each with keybox secrets bind NAME --host HOST.`);
1592
+ step(`${parked.length} parked key${parked.length === 1 ? "" : "s"}. Pick a host for each, or leave it parked.`);
1593
+ const placed = await placeMany(
1594
+ parked.map((s) => ({ name: s.name, guess: detect(s.name, "").provider })),
1595
+ { park: false, skipLabel: "Leave it parked" }
1596
+ );
1597
+ let n = 0;
1598
+ for (const [k, d] of placed) {
1599
+ if (!d) continue;
1600
+ try {
1601
+ await bind(k, d);
1602
+ n++;
1603
+ } catch (err) {
1604
+ warn(`${k}: ${err.message}`);
1605
+ }
1606
+ }
1607
+ note(n ? `Bound ${n}. Grant them to an agent: keybox agents create NAME --allow "GET host/**"` : "Nothing changed.");
1278
1608
  }
1279
1609
  async function secretsRm(name) {
1280
1610
  const r = await api("DELETE", `/secrets/${name}`);
@@ -1422,11 +1752,11 @@ var init_commands = __esm({
1422
1752
  import { spawn as spawn3 } from "node:child_process";
1423
1753
  import { readFileSync as readFileSync3 } from "node:fs";
1424
1754
  import { createRequire } from "node:module";
1425
- import { dirname, join as join2 } from "node:path";
1755
+ import { dirname, join as join3 } from "node:path";
1426
1756
  function bin() {
1427
1757
  const pkgPath = createRequire(import.meta.url).resolve("wrangler/package.json");
1428
1758
  const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
1429
- return join2(dirname(pkgPath), pkg.bin.wrangler);
1759
+ return join3(dirname(pkgPath), pkg.bin.wrangler);
1430
1760
  }
1431
1761
  function useAccount(id) {
1432
1762
  accountId = id;
@@ -1511,13 +1841,30 @@ async function cf(path, account = currentAccount()) {
1511
1841
  }
1512
1842
  return body.result;
1513
1843
  }
1514
- async function findWorker(name, accounts) {
1844
+ function workersDevSubdomain(url) {
1845
+ try {
1846
+ const m = /^[^.]+\.([^.]+)\.workers\.dev$/.exec(new URL(url).hostname);
1847
+ return m ? m[1] : null;
1848
+ } catch {
1849
+ return null;
1850
+ }
1851
+ }
1852
+ async function accountSubdomain(accountId2) {
1853
+ try {
1854
+ return (await cf("/workers/subdomain", accountId2)).subdomain ?? null;
1855
+ } catch {
1856
+ return null;
1857
+ }
1858
+ }
1859
+ async function findWorker(name, accounts, url) {
1860
+ const want = url ? workersDevSubdomain(url) : null;
1515
1861
  for (const a of accounts) {
1516
1862
  try {
1517
1863
  await cf(`/workers/scripts/${name}/settings`, a.id);
1518
- return a;
1519
1864
  } catch {
1865
+ continue;
1520
1866
  }
1867
+ if (!want || await accountSubdomain(a.id) === want) return a;
1521
1868
  }
1522
1869
  return null;
1523
1870
  }
@@ -1543,7 +1890,7 @@ var VERSION;
1543
1890
  var init_version = __esm({
1544
1891
  "src/version.ts"() {
1545
1892
  "use strict";
1546
- VERSION = true ? "0.2.1" : "0.0.0-dev";
1893
+ VERSION = true ? "0.2.3" : "0.0.0-dev";
1547
1894
  }
1548
1895
  });
1549
1896
 
@@ -1554,6 +1901,7 @@ __export(verify_exports, {
1554
1901
  printChecks: () => printChecks,
1555
1902
  resolveAccount: () => resolveAccount,
1556
1903
  shippedWorkerHash: () => shippedWorkerHash,
1904
+ shippedWorkerVersion: () => shippedWorkerVersion,
1557
1905
  verify: () => verify
1558
1906
  });
1559
1907
  import { createHash } from "node:crypto";
@@ -1584,8 +1932,8 @@ async function resolveAccount(cfg) {
1584
1932
  }
1585
1933
  const me = await whoami();
1586
1934
  if (!me) throw new UserError("Log in to Cloudflare first: npx wrangler login");
1587
- const found = await findWorker(cfg.name, me.accounts);
1588
- if (!found) throw new UserError(`No Worker named "${cfg.name}" in the Cloudflare accounts you are logged in to (${me.accounts.map((a) => a.name).join(", ")}).`);
1935
+ const found = await findWorker(cfg.name, me.accounts, cfg.url);
1936
+ if (!found) throw new UserError(`No Worker named "${cfg.name}" serving ${cfg.url} in the Cloudflare accounts you are logged in to (${me.accounts.map((a) => a.name).join(", ")}).`);
1589
1937
  useAccount(found.id);
1590
1938
  if (cfg.d1Id) saveConfig({ ...cfg, accountId: found.id });
1591
1939
  return found.id;
@@ -1593,6 +1941,16 @@ async function resolveAccount(cfg) {
1593
1941
  async function checks(cfg) {
1594
1942
  const out2 = [];
1595
1943
  const name = cfg.name;
1944
+ const sub = workersDevSubdomain(cfg.url);
1945
+ const acct = currentAccount();
1946
+ if (sub && acct) {
1947
+ const has2 = await accountSubdomain(acct);
1948
+ if (has2 !== sub) {
1949
+ throw new UserError(
1950
+ `${cfg.url} is not served from Cloudflare account ${acct} (its workers.dev subdomain is ${has2 ?? "unknown"}, not ${sub}). Log in to the account that runs this Keybox (npx wrangler login), or set KEYBOX_ACCOUNT_ID, and run this again.`
1951
+ );
1952
+ }
1953
+ }
1596
1954
  const r = await cfRaw(`/workers/scripts/${name}/content/v2`);
1597
1955
  if (!r.ok) throw new UserError(`Could not read the deployed Worker "${name}" (HTTP ${r.status}).`);
1598
1956
  const modules = parts(new Uint8Array(await r.arrayBuffer()), r.headers.get("content-type") ?? "");
@@ -1628,7 +1986,7 @@ async function checks(cfg) {
1628
1986
  try {
1629
1987
  const h = await (await fetch(`${cfg.url}/_keybox/health`)).json();
1630
1988
  out2.push(
1631
- h.configured ? { ok: h.version === VERSION ? true : "warn", label: "Live", detail: `answering as v${h.version}${h.version === VERSION ? "" : ` (this CLI is v${VERSION})`}` } : { ok: false, label: "Live", detail: "answering, but missing its encryption key or admin token" }
1989
+ h.configured ? h.version === shippedWorkerVersion() ? { ok: true, label: "Live", detail: `answering as v${h.version}` } : { ok: out2[0]?.ok === true ? false : "warn", label: "Live", detail: `answering as v${h.version}, this CLI ships Worker v${shippedWorkerVersion()}${out2[0]?.ok === true ? ": the URL is served by a different Worker than the one checked above" : ""}` } : { ok: false, label: "Live", detail: "answering, but missing its encryption key or admin token" }
1632
1990
  );
1633
1991
  } catch {
1634
1992
  out2.push({ ok: false, label: "Live", detail: `not reachable at ${cfg.url}` });
@@ -1666,7 +2024,7 @@ async function verify(opts) {
1666
2024
  note("If nobody you trust deployed it, assume the stored keys are exposed: rotate them at each provider,");
1667
2025
  note("secure your Cloudflare account (hardware key, review members and API tokens), then run `keybox deploy`.");
1668
2026
  }
1669
- var EXPECTED_BINDINGS, shaHex, shippedWorkerHash;
2027
+ var EXPECTED_BINDINGS, shaHex, shippedWorkerHash, shippedWorkerVersion;
1670
2028
  var init_verify = __esm({
1671
2029
  "src/verify.ts"() {
1672
2030
  "use strict";
@@ -1678,6 +2036,7 @@ var init_verify = __esm({
1678
2036
  EXPECTED_BINDINGS = /* @__PURE__ */ new Set(["DB", "KEYBOX_KEK", "KEYBOX_ADMIN_TOKEN_HASH", "KEYBOX_SCRIPT_NAME", "KEYBOX_D1_ID"]);
1679
2037
  shaHex = (b) => createHash("sha256").update(b).digest("hex");
1680
2038
  shippedWorkerHash = () => shaHex(readFileSync4(new URL("../assets/worker.js", import.meta.url)));
2039
+ shippedWorkerVersion = () => /VERSION = "([^"]+)"/.exec(readFileSync4(new URL("../assets/worker.js", import.meta.url), "utf8"))?.[1] ?? VERSION;
1681
2040
  }
1682
2041
  });
1683
2042
 
@@ -1691,7 +2050,7 @@ __export(deploy_exports, {
1691
2050
  import { spawn as spawn4 } from "node:child_process";
1692
2051
  import { createHash as createHash2, randomBytes } from "node:crypto";
1693
2052
  import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
1694
- import { join as join3 } from "node:path";
2053
+ import { join as join4 } from "node:path";
1695
2054
  async function deployWorker(cfg) {
1696
2055
  for (let attempt = 1; ; attempt++) {
1697
2056
  try {
@@ -1705,10 +2064,10 @@ async function deployWorker(cfg) {
1705
2064
  }
1706
2065
  function writeDeployFiles(name, d1Id, accountId2) {
1707
2066
  const dir = deployDir();
1708
- mkdirSync2(join3(dir, "worker"), { recursive: true, mode: 448 });
1709
- copyFileSync(asset("worker.js"), join3(dir, "worker", "worker.js"));
1710
- copyFileSync(asset("schema.sql"), join3(dir, "schema.sql"));
1711
- const cfg = join3(dir, "wrangler.json");
2067
+ mkdirSync2(join4(dir, "worker"), { recursive: true, mode: 448 });
2068
+ copyFileSync(asset("worker.js"), join4(dir, "worker", "worker.js"));
2069
+ copyFileSync(asset("schema.sql"), join4(dir, "schema.sql"));
2070
+ const cfg = join4(dir, "wrangler.json");
1712
2071
  writeFileSync2(
1713
2072
  cfg,
1714
2073
  JSON.stringify(
@@ -1816,7 +2175,7 @@ async function init(opts) {
1816
2175
  const cfgPath = writeDeployFiles(name, d1Id, account.id);
1817
2176
  await task(
1818
2177
  "Schema",
1819
- () => wrangler(["d1", "execute", name, "--remote", "--yes", "--file", join3(deployDir(), "schema.sql"), "--config", cfgPath], { capture: true, quiet: true }),
2178
+ () => wrangler(["d1", "execute", name, "--remote", "--yes", "--file", join4(deployDir(), "schema.sql"), "--config", cfgPath], { capture: true, quiet: true }),
1820
2179
  () => "applied"
1821
2180
  );
1822
2181
  const url = await task(
@@ -1895,7 +2254,7 @@ async function deploy(opts) {
1895
2254
  if (!cfg.d1Id) throw new UserError("`keybox deploy` needs the config written by `keybox init`.");
1896
2255
  await resolveAccount(cfg);
1897
2256
  const dir = deployDir();
1898
- const current = existsSync3(join3(dir, "worker", "worker.js")) ? sha(join3(dir, "worker", "worker.js")) : null;
2257
+ const current = existsSync3(join4(dir, "worker", "worker.js")) ? sha(join4(dir, "worker", "worker.js")) : null;
1899
2258
  const next = shippedWorkerHash();
1900
2259
  if (current === next && !opts.force) {
1901
2260
  ok("The deployed Worker already matches this CLI version. Run `keybox verify` to check what Cloudflare is serving.");
@@ -1913,7 +2272,7 @@ ${c.accent("\u25A0")} This replaces the Worker that holds your keys.
1913
2272
  const wranglerCfg = writeDeployFiles(fresh.name, fresh.d1Id, fresh.accountId);
1914
2273
  await task(
1915
2274
  "Schema",
1916
- () => wrangler(["d1", "execute", fresh.name, "--remote", "--yes", "--file", join3(dir, "schema.sql"), "--config", wranglerCfg], { capture: true, quiet: true }),
2275
+ () => wrangler(["d1", "execute", fresh.name, "--remote", "--yes", "--file", join4(dir, "schema.sql"), "--config", wranglerCfg], { capture: true, quiet: true }),
1917
2276
  () => "applied"
1918
2277
  );
1919
2278
  await task("Worker", () => deployWorker(wranglerCfg), () => "deployed");
@@ -1927,7 +2286,7 @@ async function status() {
1927
2286
  const row = (k, v) => `${c.dim(k.padEnd(11))} ${v}
1928
2287
  `;
1929
2288
  process.stdout.write(
1930
- row("url", cfg.url) + row("dashboard", `${cfg.url.replace(/\/$/, "")}/_keybox/ui ${c.dim("(open with keybox ui)")}`) + (cfg.accountId ? row("account", cfg.accountId) : "") + row("worker", `v${health.version}${health.version === VERSION ? "" : c.warn(` (this CLI is v${VERSION}; run keybox update)`)}`) + row("configured", health.configured) + row("secrets", secrets.length) + row("agents", agents.length)
2289
+ row("url", cfg.url) + row("dashboard", `${cfg.url.replace(/\/$/, "")}/_keybox/ui ${c.dim("(open with keybox ui)")}`) + (cfg.accountId ? row("account", cfg.accountId) : "") + row("worker", `v${health.version}${health.version === shippedWorkerVersion() ? "" : c.warn(` (this CLI ships v${shippedWorkerVersion()}; run keybox update)`)}`) + row("configured", health.configured) + row("secrets", secrets.length) + row("agents", agents.length)
1931
2290
  );
1932
2291
  if (process.stdout.isTTY) step(`Run ${c.bold("keybox verify")} to check the deployed code against this CLI.`);
1933
2292
  }
@@ -1958,6 +2317,1814 @@ var init_deploy = __esm({
1958
2317
  }
1959
2318
  });
1960
2319
 
2320
+ // ../node_modules/qrcode/lib/core/utils.js
2321
+ var require_utils = __commonJS({
2322
+ "../node_modules/qrcode/lib/core/utils.js"(exports) {
2323
+ var toSJISFunction;
2324
+ var CODEWORDS_COUNT = [
2325
+ 0,
2326
+ // Not used
2327
+ 26,
2328
+ 44,
2329
+ 70,
2330
+ 100,
2331
+ 134,
2332
+ 172,
2333
+ 196,
2334
+ 242,
2335
+ 292,
2336
+ 346,
2337
+ 404,
2338
+ 466,
2339
+ 532,
2340
+ 581,
2341
+ 655,
2342
+ 733,
2343
+ 815,
2344
+ 901,
2345
+ 991,
2346
+ 1085,
2347
+ 1156,
2348
+ 1258,
2349
+ 1364,
2350
+ 1474,
2351
+ 1588,
2352
+ 1706,
2353
+ 1828,
2354
+ 1921,
2355
+ 2051,
2356
+ 2185,
2357
+ 2323,
2358
+ 2465,
2359
+ 2611,
2360
+ 2761,
2361
+ 2876,
2362
+ 3034,
2363
+ 3196,
2364
+ 3362,
2365
+ 3532,
2366
+ 3706
2367
+ ];
2368
+ exports.getSymbolSize = function getSymbolSize(version) {
2369
+ if (!version) throw new Error('"version" cannot be null or undefined');
2370
+ if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40');
2371
+ return version * 4 + 17;
2372
+ };
2373
+ exports.getSymbolTotalCodewords = function getSymbolTotalCodewords(version) {
2374
+ return CODEWORDS_COUNT[version];
2375
+ };
2376
+ exports.getBCHDigit = function(data) {
2377
+ let digit = 0;
2378
+ while (data !== 0) {
2379
+ digit++;
2380
+ data >>>= 1;
2381
+ }
2382
+ return digit;
2383
+ };
2384
+ exports.setToSJISFunction = function setToSJISFunction(f) {
2385
+ if (typeof f !== "function") {
2386
+ throw new Error('"toSJISFunc" is not a valid function.');
2387
+ }
2388
+ toSJISFunction = f;
2389
+ };
2390
+ exports.isKanjiModeEnabled = function() {
2391
+ return typeof toSJISFunction !== "undefined";
2392
+ };
2393
+ exports.toSJIS = function toSJIS(kanji) {
2394
+ return toSJISFunction(kanji);
2395
+ };
2396
+ }
2397
+ });
2398
+
2399
+ // ../node_modules/qrcode/lib/core/error-correction-level.js
2400
+ var require_error_correction_level = __commonJS({
2401
+ "../node_modules/qrcode/lib/core/error-correction-level.js"(exports) {
2402
+ exports.L = { bit: 1 };
2403
+ exports.M = { bit: 0 };
2404
+ exports.Q = { bit: 3 };
2405
+ exports.H = { bit: 2 };
2406
+ function fromString(string) {
2407
+ if (typeof string !== "string") {
2408
+ throw new Error("Param is not a string");
2409
+ }
2410
+ const lcStr = string.toLowerCase();
2411
+ switch (lcStr) {
2412
+ case "l":
2413
+ case "low":
2414
+ return exports.L;
2415
+ case "m":
2416
+ case "medium":
2417
+ return exports.M;
2418
+ case "q":
2419
+ case "quartile":
2420
+ return exports.Q;
2421
+ case "h":
2422
+ case "high":
2423
+ return exports.H;
2424
+ default:
2425
+ throw new Error("Unknown EC Level: " + string);
2426
+ }
2427
+ }
2428
+ exports.isValid = function isValid(level) {
2429
+ return level && typeof level.bit !== "undefined" && level.bit >= 0 && level.bit < 4;
2430
+ };
2431
+ exports.from = function from(value, defaultValue) {
2432
+ if (exports.isValid(value)) {
2433
+ return value;
2434
+ }
2435
+ try {
2436
+ return fromString(value);
2437
+ } catch (e) {
2438
+ return defaultValue;
2439
+ }
2440
+ };
2441
+ }
2442
+ });
2443
+
2444
+ // ../node_modules/qrcode/lib/core/bit-buffer.js
2445
+ var require_bit_buffer = __commonJS({
2446
+ "../node_modules/qrcode/lib/core/bit-buffer.js"(exports, module) {
2447
+ function BitBuffer() {
2448
+ this.buffer = [];
2449
+ this.length = 0;
2450
+ }
2451
+ BitBuffer.prototype = {
2452
+ get: function(index) {
2453
+ const bufIndex = Math.floor(index / 8);
2454
+ return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) === 1;
2455
+ },
2456
+ put: function(num, length) {
2457
+ for (let i = 0; i < length; i++) {
2458
+ this.putBit((num >>> length - i - 1 & 1) === 1);
2459
+ }
2460
+ },
2461
+ getLengthInBits: function() {
2462
+ return this.length;
2463
+ },
2464
+ putBit: function(bit) {
2465
+ const bufIndex = Math.floor(this.length / 8);
2466
+ if (this.buffer.length <= bufIndex) {
2467
+ this.buffer.push(0);
2468
+ }
2469
+ if (bit) {
2470
+ this.buffer[bufIndex] |= 128 >>> this.length % 8;
2471
+ }
2472
+ this.length++;
2473
+ }
2474
+ };
2475
+ module.exports = BitBuffer;
2476
+ }
2477
+ });
2478
+
2479
+ // ../node_modules/qrcode/lib/core/bit-matrix.js
2480
+ var require_bit_matrix = __commonJS({
2481
+ "../node_modules/qrcode/lib/core/bit-matrix.js"(exports, module) {
2482
+ function BitMatrix(size) {
2483
+ if (!size || size < 1) {
2484
+ throw new Error("BitMatrix size must be defined and greater than 0");
2485
+ }
2486
+ this.size = size;
2487
+ this.data = new Uint8Array(size * size);
2488
+ this.reservedBit = new Uint8Array(size * size);
2489
+ }
2490
+ BitMatrix.prototype.set = function(row, col, value, reserved) {
2491
+ const index = row * this.size + col;
2492
+ this.data[index] = value;
2493
+ if (reserved) this.reservedBit[index] = true;
2494
+ };
2495
+ BitMatrix.prototype.get = function(row, col) {
2496
+ return this.data[row * this.size + col];
2497
+ };
2498
+ BitMatrix.prototype.xor = function(row, col, value) {
2499
+ this.data[row * this.size + col] ^= value;
2500
+ };
2501
+ BitMatrix.prototype.isReserved = function(row, col) {
2502
+ return this.reservedBit[row * this.size + col];
2503
+ };
2504
+ module.exports = BitMatrix;
2505
+ }
2506
+ });
2507
+
2508
+ // ../node_modules/qrcode/lib/core/alignment-pattern.js
2509
+ var require_alignment_pattern = __commonJS({
2510
+ "../node_modules/qrcode/lib/core/alignment-pattern.js"(exports) {
2511
+ var getSymbolSize = require_utils().getSymbolSize;
2512
+ exports.getRowColCoords = function getRowColCoords(version) {
2513
+ if (version === 1) return [];
2514
+ const posCount = Math.floor(version / 7) + 2;
2515
+ const size = getSymbolSize(version);
2516
+ const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2;
2517
+ const positions = [size - 7];
2518
+ for (let i = 1; i < posCount - 1; i++) {
2519
+ positions[i] = positions[i - 1] - intervals;
2520
+ }
2521
+ positions.push(6);
2522
+ return positions.reverse();
2523
+ };
2524
+ exports.getPositions = function getPositions(version) {
2525
+ const coords = [];
2526
+ const pos = exports.getRowColCoords(version);
2527
+ const posLength = pos.length;
2528
+ for (let i = 0; i < posLength; i++) {
2529
+ for (let j = 0; j < posLength; j++) {
2530
+ if (i === 0 && j === 0 || // top-left
2531
+ i === 0 && j === posLength - 1 || // bottom-left
2532
+ i === posLength - 1 && j === 0) {
2533
+ continue;
2534
+ }
2535
+ coords.push([pos[i], pos[j]]);
2536
+ }
2537
+ }
2538
+ return coords;
2539
+ };
2540
+ }
2541
+ });
2542
+
2543
+ // ../node_modules/qrcode/lib/core/finder-pattern.js
2544
+ var require_finder_pattern = __commonJS({
2545
+ "../node_modules/qrcode/lib/core/finder-pattern.js"(exports) {
2546
+ var getSymbolSize = require_utils().getSymbolSize;
2547
+ var FINDER_PATTERN_SIZE = 7;
2548
+ exports.getPositions = function getPositions(version) {
2549
+ const size = getSymbolSize(version);
2550
+ return [
2551
+ // top-left
2552
+ [0, 0],
2553
+ // top-right
2554
+ [size - FINDER_PATTERN_SIZE, 0],
2555
+ // bottom-left
2556
+ [0, size - FINDER_PATTERN_SIZE]
2557
+ ];
2558
+ };
2559
+ }
2560
+ });
2561
+
2562
+ // ../node_modules/qrcode/lib/core/mask-pattern.js
2563
+ var require_mask_pattern = __commonJS({
2564
+ "../node_modules/qrcode/lib/core/mask-pattern.js"(exports) {
2565
+ exports.Patterns = {
2566
+ PATTERN000: 0,
2567
+ PATTERN001: 1,
2568
+ PATTERN010: 2,
2569
+ PATTERN011: 3,
2570
+ PATTERN100: 4,
2571
+ PATTERN101: 5,
2572
+ PATTERN110: 6,
2573
+ PATTERN111: 7
2574
+ };
2575
+ var PenaltyScores = {
2576
+ N1: 3,
2577
+ N2: 3,
2578
+ N3: 40,
2579
+ N4: 10
2580
+ };
2581
+ exports.isValid = function isValid(mask) {
2582
+ return mask != null && mask !== "" && !isNaN(mask) && mask >= 0 && mask <= 7;
2583
+ };
2584
+ exports.from = function from(value) {
2585
+ return exports.isValid(value) ? parseInt(value, 10) : void 0;
2586
+ };
2587
+ exports.getPenaltyN1 = function getPenaltyN1(data) {
2588
+ const size = data.size;
2589
+ let points = 0;
2590
+ let sameCountCol = 0;
2591
+ let sameCountRow = 0;
2592
+ let lastCol = null;
2593
+ let lastRow = null;
2594
+ for (let row = 0; row < size; row++) {
2595
+ sameCountCol = sameCountRow = 0;
2596
+ lastCol = lastRow = null;
2597
+ for (let col = 0; col < size; col++) {
2598
+ let module2 = data.get(row, col);
2599
+ if (module2 === lastCol) {
2600
+ sameCountCol++;
2601
+ } else {
2602
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
2603
+ lastCol = module2;
2604
+ sameCountCol = 1;
2605
+ }
2606
+ module2 = data.get(col, row);
2607
+ if (module2 === lastRow) {
2608
+ sameCountRow++;
2609
+ } else {
2610
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
2611
+ lastRow = module2;
2612
+ sameCountRow = 1;
2613
+ }
2614
+ }
2615
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
2616
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
2617
+ }
2618
+ return points;
2619
+ };
2620
+ exports.getPenaltyN2 = function getPenaltyN2(data) {
2621
+ const size = data.size;
2622
+ let points = 0;
2623
+ for (let row = 0; row < size - 1; row++) {
2624
+ for (let col = 0; col < size - 1; col++) {
2625
+ const last = data.get(row, col) + data.get(row, col + 1) + data.get(row + 1, col) + data.get(row + 1, col + 1);
2626
+ if (last === 4 || last === 0) points++;
2627
+ }
2628
+ }
2629
+ return points * PenaltyScores.N2;
2630
+ };
2631
+ exports.getPenaltyN3 = function getPenaltyN3(data) {
2632
+ const size = data.size;
2633
+ let points = 0;
2634
+ let bitsCol = 0;
2635
+ let bitsRow = 0;
2636
+ for (let row = 0; row < size; row++) {
2637
+ bitsCol = bitsRow = 0;
2638
+ for (let col = 0; col < size; col++) {
2639
+ bitsCol = bitsCol << 1 & 2047 | data.get(row, col);
2640
+ if (col >= 10 && (bitsCol === 1488 || bitsCol === 93)) points++;
2641
+ bitsRow = bitsRow << 1 & 2047 | data.get(col, row);
2642
+ if (col >= 10 && (bitsRow === 1488 || bitsRow === 93)) points++;
2643
+ }
2644
+ }
2645
+ return points * PenaltyScores.N3;
2646
+ };
2647
+ exports.getPenaltyN4 = function getPenaltyN4(data) {
2648
+ let darkCount = 0;
2649
+ const modulesCount = data.data.length;
2650
+ for (let i = 0; i < modulesCount; i++) darkCount += data.data[i];
2651
+ const k = Math.abs(Math.ceil(darkCount * 100 / modulesCount / 5) - 10);
2652
+ return k * PenaltyScores.N4;
2653
+ };
2654
+ function getMaskAt(maskPattern, i, j) {
2655
+ switch (maskPattern) {
2656
+ case exports.Patterns.PATTERN000:
2657
+ return (i + j) % 2 === 0;
2658
+ case exports.Patterns.PATTERN001:
2659
+ return i % 2 === 0;
2660
+ case exports.Patterns.PATTERN010:
2661
+ return j % 3 === 0;
2662
+ case exports.Patterns.PATTERN011:
2663
+ return (i + j) % 3 === 0;
2664
+ case exports.Patterns.PATTERN100:
2665
+ return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0;
2666
+ case exports.Patterns.PATTERN101:
2667
+ return i * j % 2 + i * j % 3 === 0;
2668
+ case exports.Patterns.PATTERN110:
2669
+ return (i * j % 2 + i * j % 3) % 2 === 0;
2670
+ case exports.Patterns.PATTERN111:
2671
+ return (i * j % 3 + (i + j) % 2) % 2 === 0;
2672
+ default:
2673
+ throw new Error("bad maskPattern:" + maskPattern);
2674
+ }
2675
+ }
2676
+ exports.applyMask = function applyMask(pattern, data) {
2677
+ const size = data.size;
2678
+ for (let col = 0; col < size; col++) {
2679
+ for (let row = 0; row < size; row++) {
2680
+ if (data.isReserved(row, col)) continue;
2681
+ data.xor(row, col, getMaskAt(pattern, row, col));
2682
+ }
2683
+ }
2684
+ };
2685
+ exports.getBestMask = function getBestMask(data, setupFormatFunc) {
2686
+ const numPatterns = Object.keys(exports.Patterns).length;
2687
+ let bestPattern = 0;
2688
+ let lowerPenalty = Infinity;
2689
+ for (let p = 0; p < numPatterns; p++) {
2690
+ setupFormatFunc(p);
2691
+ exports.applyMask(p, data);
2692
+ const penalty = exports.getPenaltyN1(data) + exports.getPenaltyN2(data) + exports.getPenaltyN3(data) + exports.getPenaltyN4(data);
2693
+ exports.applyMask(p, data);
2694
+ if (penalty < lowerPenalty) {
2695
+ lowerPenalty = penalty;
2696
+ bestPattern = p;
2697
+ }
2698
+ }
2699
+ return bestPattern;
2700
+ };
2701
+ }
2702
+ });
2703
+
2704
+ // ../node_modules/qrcode/lib/core/error-correction-code.js
2705
+ var require_error_correction_code = __commonJS({
2706
+ "../node_modules/qrcode/lib/core/error-correction-code.js"(exports) {
2707
+ var ECLevel = require_error_correction_level();
2708
+ var EC_BLOCKS_TABLE = [
2709
+ // L M Q H
2710
+ 1,
2711
+ 1,
2712
+ 1,
2713
+ 1,
2714
+ 1,
2715
+ 1,
2716
+ 1,
2717
+ 1,
2718
+ 1,
2719
+ 1,
2720
+ 2,
2721
+ 2,
2722
+ 1,
2723
+ 2,
2724
+ 2,
2725
+ 4,
2726
+ 1,
2727
+ 2,
2728
+ 4,
2729
+ 4,
2730
+ 2,
2731
+ 4,
2732
+ 4,
2733
+ 4,
2734
+ 2,
2735
+ 4,
2736
+ 6,
2737
+ 5,
2738
+ 2,
2739
+ 4,
2740
+ 6,
2741
+ 6,
2742
+ 2,
2743
+ 5,
2744
+ 8,
2745
+ 8,
2746
+ 4,
2747
+ 5,
2748
+ 8,
2749
+ 8,
2750
+ 4,
2751
+ 5,
2752
+ 8,
2753
+ 11,
2754
+ 4,
2755
+ 8,
2756
+ 10,
2757
+ 11,
2758
+ 4,
2759
+ 9,
2760
+ 12,
2761
+ 16,
2762
+ 4,
2763
+ 9,
2764
+ 16,
2765
+ 16,
2766
+ 6,
2767
+ 10,
2768
+ 12,
2769
+ 18,
2770
+ 6,
2771
+ 10,
2772
+ 17,
2773
+ 16,
2774
+ 6,
2775
+ 11,
2776
+ 16,
2777
+ 19,
2778
+ 6,
2779
+ 13,
2780
+ 18,
2781
+ 21,
2782
+ 7,
2783
+ 14,
2784
+ 21,
2785
+ 25,
2786
+ 8,
2787
+ 16,
2788
+ 20,
2789
+ 25,
2790
+ 8,
2791
+ 17,
2792
+ 23,
2793
+ 25,
2794
+ 9,
2795
+ 17,
2796
+ 23,
2797
+ 34,
2798
+ 9,
2799
+ 18,
2800
+ 25,
2801
+ 30,
2802
+ 10,
2803
+ 20,
2804
+ 27,
2805
+ 32,
2806
+ 12,
2807
+ 21,
2808
+ 29,
2809
+ 35,
2810
+ 12,
2811
+ 23,
2812
+ 34,
2813
+ 37,
2814
+ 12,
2815
+ 25,
2816
+ 34,
2817
+ 40,
2818
+ 13,
2819
+ 26,
2820
+ 35,
2821
+ 42,
2822
+ 14,
2823
+ 28,
2824
+ 38,
2825
+ 45,
2826
+ 15,
2827
+ 29,
2828
+ 40,
2829
+ 48,
2830
+ 16,
2831
+ 31,
2832
+ 43,
2833
+ 51,
2834
+ 17,
2835
+ 33,
2836
+ 45,
2837
+ 54,
2838
+ 18,
2839
+ 35,
2840
+ 48,
2841
+ 57,
2842
+ 19,
2843
+ 37,
2844
+ 51,
2845
+ 60,
2846
+ 19,
2847
+ 38,
2848
+ 53,
2849
+ 63,
2850
+ 20,
2851
+ 40,
2852
+ 56,
2853
+ 66,
2854
+ 21,
2855
+ 43,
2856
+ 59,
2857
+ 70,
2858
+ 22,
2859
+ 45,
2860
+ 62,
2861
+ 74,
2862
+ 24,
2863
+ 47,
2864
+ 65,
2865
+ 77,
2866
+ 25,
2867
+ 49,
2868
+ 68,
2869
+ 81
2870
+ ];
2871
+ var EC_CODEWORDS_TABLE = [
2872
+ // L M Q H
2873
+ 7,
2874
+ 10,
2875
+ 13,
2876
+ 17,
2877
+ 10,
2878
+ 16,
2879
+ 22,
2880
+ 28,
2881
+ 15,
2882
+ 26,
2883
+ 36,
2884
+ 44,
2885
+ 20,
2886
+ 36,
2887
+ 52,
2888
+ 64,
2889
+ 26,
2890
+ 48,
2891
+ 72,
2892
+ 88,
2893
+ 36,
2894
+ 64,
2895
+ 96,
2896
+ 112,
2897
+ 40,
2898
+ 72,
2899
+ 108,
2900
+ 130,
2901
+ 48,
2902
+ 88,
2903
+ 132,
2904
+ 156,
2905
+ 60,
2906
+ 110,
2907
+ 160,
2908
+ 192,
2909
+ 72,
2910
+ 130,
2911
+ 192,
2912
+ 224,
2913
+ 80,
2914
+ 150,
2915
+ 224,
2916
+ 264,
2917
+ 96,
2918
+ 176,
2919
+ 260,
2920
+ 308,
2921
+ 104,
2922
+ 198,
2923
+ 288,
2924
+ 352,
2925
+ 120,
2926
+ 216,
2927
+ 320,
2928
+ 384,
2929
+ 132,
2930
+ 240,
2931
+ 360,
2932
+ 432,
2933
+ 144,
2934
+ 280,
2935
+ 408,
2936
+ 480,
2937
+ 168,
2938
+ 308,
2939
+ 448,
2940
+ 532,
2941
+ 180,
2942
+ 338,
2943
+ 504,
2944
+ 588,
2945
+ 196,
2946
+ 364,
2947
+ 546,
2948
+ 650,
2949
+ 224,
2950
+ 416,
2951
+ 600,
2952
+ 700,
2953
+ 224,
2954
+ 442,
2955
+ 644,
2956
+ 750,
2957
+ 252,
2958
+ 476,
2959
+ 690,
2960
+ 816,
2961
+ 270,
2962
+ 504,
2963
+ 750,
2964
+ 900,
2965
+ 300,
2966
+ 560,
2967
+ 810,
2968
+ 960,
2969
+ 312,
2970
+ 588,
2971
+ 870,
2972
+ 1050,
2973
+ 336,
2974
+ 644,
2975
+ 952,
2976
+ 1110,
2977
+ 360,
2978
+ 700,
2979
+ 1020,
2980
+ 1200,
2981
+ 390,
2982
+ 728,
2983
+ 1050,
2984
+ 1260,
2985
+ 420,
2986
+ 784,
2987
+ 1140,
2988
+ 1350,
2989
+ 450,
2990
+ 812,
2991
+ 1200,
2992
+ 1440,
2993
+ 480,
2994
+ 868,
2995
+ 1290,
2996
+ 1530,
2997
+ 510,
2998
+ 924,
2999
+ 1350,
3000
+ 1620,
3001
+ 540,
3002
+ 980,
3003
+ 1440,
3004
+ 1710,
3005
+ 570,
3006
+ 1036,
3007
+ 1530,
3008
+ 1800,
3009
+ 570,
3010
+ 1064,
3011
+ 1590,
3012
+ 1890,
3013
+ 600,
3014
+ 1120,
3015
+ 1680,
3016
+ 1980,
3017
+ 630,
3018
+ 1204,
3019
+ 1770,
3020
+ 2100,
3021
+ 660,
3022
+ 1260,
3023
+ 1860,
3024
+ 2220,
3025
+ 720,
3026
+ 1316,
3027
+ 1950,
3028
+ 2310,
3029
+ 750,
3030
+ 1372,
3031
+ 2040,
3032
+ 2430
3033
+ ];
3034
+ exports.getBlocksCount = function getBlocksCount(version, errorCorrectionLevel) {
3035
+ switch (errorCorrectionLevel) {
3036
+ case ECLevel.L:
3037
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 0];
3038
+ case ECLevel.M:
3039
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 1];
3040
+ case ECLevel.Q:
3041
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 2];
3042
+ case ECLevel.H:
3043
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 3];
3044
+ default:
3045
+ return void 0;
3046
+ }
3047
+ };
3048
+ exports.getTotalCodewordsCount = function getTotalCodewordsCount(version, errorCorrectionLevel) {
3049
+ switch (errorCorrectionLevel) {
3050
+ case ECLevel.L:
3051
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0];
3052
+ case ECLevel.M:
3053
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1];
3054
+ case ECLevel.Q:
3055
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2];
3056
+ case ECLevel.H:
3057
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3];
3058
+ default:
3059
+ return void 0;
3060
+ }
3061
+ };
3062
+ }
3063
+ });
3064
+
3065
+ // ../node_modules/qrcode/lib/core/galois-field.js
3066
+ var require_galois_field = __commonJS({
3067
+ "../node_modules/qrcode/lib/core/galois-field.js"(exports) {
3068
+ var EXP_TABLE = new Uint8Array(512);
3069
+ var LOG_TABLE = new Uint8Array(256);
3070
+ (function initTables() {
3071
+ let x = 1;
3072
+ for (let i = 0; i < 255; i++) {
3073
+ EXP_TABLE[i] = x;
3074
+ LOG_TABLE[x] = i;
3075
+ x <<= 1;
3076
+ if (x & 256) {
3077
+ x ^= 285;
3078
+ }
3079
+ }
3080
+ for (let i = 255; i < 512; i++) {
3081
+ EXP_TABLE[i] = EXP_TABLE[i - 255];
3082
+ }
3083
+ })();
3084
+ exports.log = function log(n) {
3085
+ if (n < 1) throw new Error("log(" + n + ")");
3086
+ return LOG_TABLE[n];
3087
+ };
3088
+ exports.exp = function exp(n) {
3089
+ return EXP_TABLE[n];
3090
+ };
3091
+ exports.mul = function mul(x, y) {
3092
+ if (x === 0 || y === 0) return 0;
3093
+ return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]];
3094
+ };
3095
+ }
3096
+ });
3097
+
3098
+ // ../node_modules/qrcode/lib/core/polynomial.js
3099
+ var require_polynomial = __commonJS({
3100
+ "../node_modules/qrcode/lib/core/polynomial.js"(exports) {
3101
+ var GF = require_galois_field();
3102
+ exports.mul = function mul(p1, p2) {
3103
+ const coeff = new Uint8Array(p1.length + p2.length - 1);
3104
+ for (let i = 0; i < p1.length; i++) {
3105
+ for (let j = 0; j < p2.length; j++) {
3106
+ coeff[i + j] ^= GF.mul(p1[i], p2[j]);
3107
+ }
3108
+ }
3109
+ return coeff;
3110
+ };
3111
+ exports.mod = function mod(divident, divisor) {
3112
+ let result = new Uint8Array(divident);
3113
+ while (result.length - divisor.length >= 0) {
3114
+ const coeff = result[0];
3115
+ for (let i = 0; i < divisor.length; i++) {
3116
+ result[i] ^= GF.mul(divisor[i], coeff);
3117
+ }
3118
+ let offset = 0;
3119
+ while (offset < result.length && result[offset] === 0) offset++;
3120
+ result = result.slice(offset);
3121
+ }
3122
+ return result;
3123
+ };
3124
+ exports.generateECPolynomial = function generateECPolynomial(degree) {
3125
+ let poly = new Uint8Array([1]);
3126
+ for (let i = 0; i < degree; i++) {
3127
+ poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]));
3128
+ }
3129
+ return poly;
3130
+ };
3131
+ }
3132
+ });
3133
+
3134
+ // ../node_modules/qrcode/lib/core/reed-solomon-encoder.js
3135
+ var require_reed_solomon_encoder = __commonJS({
3136
+ "../node_modules/qrcode/lib/core/reed-solomon-encoder.js"(exports, module) {
3137
+ var Polynomial = require_polynomial();
3138
+ function ReedSolomonEncoder(degree) {
3139
+ this.genPoly = void 0;
3140
+ this.degree = degree;
3141
+ if (this.degree) this.initialize(this.degree);
3142
+ }
3143
+ ReedSolomonEncoder.prototype.initialize = function initialize(degree) {
3144
+ this.degree = degree;
3145
+ this.genPoly = Polynomial.generateECPolynomial(this.degree);
3146
+ };
3147
+ ReedSolomonEncoder.prototype.encode = function encode(data) {
3148
+ if (!this.genPoly) {
3149
+ throw new Error("Encoder not initialized");
3150
+ }
3151
+ const paddedData = new Uint8Array(data.length + this.degree);
3152
+ paddedData.set(data);
3153
+ const remainder = Polynomial.mod(paddedData, this.genPoly);
3154
+ const start = this.degree - remainder.length;
3155
+ if (start > 0) {
3156
+ const buff = new Uint8Array(this.degree);
3157
+ buff.set(remainder, start);
3158
+ return buff;
3159
+ }
3160
+ return remainder;
3161
+ };
3162
+ module.exports = ReedSolomonEncoder;
3163
+ }
3164
+ });
3165
+
3166
+ // ../node_modules/qrcode/lib/core/version-check.js
3167
+ var require_version_check = __commonJS({
3168
+ "../node_modules/qrcode/lib/core/version-check.js"(exports) {
3169
+ exports.isValid = function isValid(version) {
3170
+ return !isNaN(version) && version >= 1 && version <= 40;
3171
+ };
3172
+ }
3173
+ });
3174
+
3175
+ // ../node_modules/qrcode/lib/core/regex.js
3176
+ var require_regex = __commonJS({
3177
+ "../node_modules/qrcode/lib/core/regex.js"(exports) {
3178
+ var numeric = "[0-9]+";
3179
+ var alphanumeric = "[A-Z $%*+\\-./:]+";
3180
+ var kanji = "(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";
3181
+ kanji = kanji.replace(/u/g, "\\u");
3182
+ var byte = "(?:(?![A-Z0-9 $%*+\\-./:]|" + kanji + ")(?:.|[\r\n]))+";
3183
+ exports.KANJI = new RegExp(kanji, "g");
3184
+ exports.BYTE_KANJI = new RegExp("[^A-Z0-9 $%*+\\-./:]+", "g");
3185
+ exports.BYTE = new RegExp(byte, "g");
3186
+ exports.NUMERIC = new RegExp(numeric, "g");
3187
+ exports.ALPHANUMERIC = new RegExp(alphanumeric, "g");
3188
+ var TEST_KANJI = new RegExp("^" + kanji + "$");
3189
+ var TEST_NUMERIC = new RegExp("^" + numeric + "$");
3190
+ var TEST_ALPHANUMERIC = new RegExp("^[A-Z0-9 $%*+\\-./:]+$");
3191
+ exports.testKanji = function testKanji(str) {
3192
+ return TEST_KANJI.test(str);
3193
+ };
3194
+ exports.testNumeric = function testNumeric(str) {
3195
+ return TEST_NUMERIC.test(str);
3196
+ };
3197
+ exports.testAlphanumeric = function testAlphanumeric(str) {
3198
+ return TEST_ALPHANUMERIC.test(str);
3199
+ };
3200
+ }
3201
+ });
3202
+
3203
+ // ../node_modules/qrcode/lib/core/mode.js
3204
+ var require_mode = __commonJS({
3205
+ "../node_modules/qrcode/lib/core/mode.js"(exports) {
3206
+ var VersionCheck = require_version_check();
3207
+ var Regex = require_regex();
3208
+ exports.NUMERIC = {
3209
+ id: "Numeric",
3210
+ bit: 1 << 0,
3211
+ ccBits: [10, 12, 14]
3212
+ };
3213
+ exports.ALPHANUMERIC = {
3214
+ id: "Alphanumeric",
3215
+ bit: 1 << 1,
3216
+ ccBits: [9, 11, 13]
3217
+ };
3218
+ exports.BYTE = {
3219
+ id: "Byte",
3220
+ bit: 1 << 2,
3221
+ ccBits: [8, 16, 16]
3222
+ };
3223
+ exports.KANJI = {
3224
+ id: "Kanji",
3225
+ bit: 1 << 3,
3226
+ ccBits: [8, 10, 12]
3227
+ };
3228
+ exports.MIXED = {
3229
+ bit: -1
3230
+ };
3231
+ exports.getCharCountIndicator = function getCharCountIndicator(mode, version) {
3232
+ if (!mode.ccBits) throw new Error("Invalid mode: " + mode);
3233
+ if (!VersionCheck.isValid(version)) {
3234
+ throw new Error("Invalid version: " + version);
3235
+ }
3236
+ if (version >= 1 && version < 10) return mode.ccBits[0];
3237
+ else if (version < 27) return mode.ccBits[1];
3238
+ return mode.ccBits[2];
3239
+ };
3240
+ exports.getBestModeForData = function getBestModeForData(dataStr) {
3241
+ if (Regex.testNumeric(dataStr)) return exports.NUMERIC;
3242
+ else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC;
3243
+ else if (Regex.testKanji(dataStr)) return exports.KANJI;
3244
+ else return exports.BYTE;
3245
+ };
3246
+ exports.toString = function toString(mode) {
3247
+ if (mode && mode.id) return mode.id;
3248
+ throw new Error("Invalid mode");
3249
+ };
3250
+ exports.isValid = function isValid(mode) {
3251
+ return mode && mode.bit && mode.ccBits;
3252
+ };
3253
+ function fromString(string) {
3254
+ if (typeof string !== "string") {
3255
+ throw new Error("Param is not a string");
3256
+ }
3257
+ const lcStr = string.toLowerCase();
3258
+ switch (lcStr) {
3259
+ case "numeric":
3260
+ return exports.NUMERIC;
3261
+ case "alphanumeric":
3262
+ return exports.ALPHANUMERIC;
3263
+ case "kanji":
3264
+ return exports.KANJI;
3265
+ case "byte":
3266
+ return exports.BYTE;
3267
+ default:
3268
+ throw new Error("Unknown mode: " + string);
3269
+ }
3270
+ }
3271
+ exports.from = function from(value, defaultValue) {
3272
+ if (exports.isValid(value)) {
3273
+ return value;
3274
+ }
3275
+ try {
3276
+ return fromString(value);
3277
+ } catch (e) {
3278
+ return defaultValue;
3279
+ }
3280
+ };
3281
+ }
3282
+ });
3283
+
3284
+ // ../node_modules/qrcode/lib/core/version.js
3285
+ var require_version = __commonJS({
3286
+ "../node_modules/qrcode/lib/core/version.js"(exports) {
3287
+ var Utils = require_utils();
3288
+ var ECCode = require_error_correction_code();
3289
+ var ECLevel = require_error_correction_level();
3290
+ var Mode = require_mode();
3291
+ var VersionCheck = require_version_check();
3292
+ var G18 = 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0;
3293
+ var G18_BCH = Utils.getBCHDigit(G18);
3294
+ function getBestVersionForDataLength(mode, length, errorCorrectionLevel) {
3295
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
3296
+ if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
3297
+ return currentVersion;
3298
+ }
3299
+ }
3300
+ return void 0;
3301
+ }
3302
+ function getReservedBitsCount(mode, version) {
3303
+ return Mode.getCharCountIndicator(mode, version) + 4;
3304
+ }
3305
+ function getTotalBitsFromDataArray(segments, version) {
3306
+ let totalBits = 0;
3307
+ segments.forEach(function(data) {
3308
+ const reservedBits = getReservedBitsCount(data.mode, version);
3309
+ totalBits += reservedBits + data.getBitsLength();
3310
+ });
3311
+ return totalBits;
3312
+ }
3313
+ function getBestVersionForMixedData(segments, errorCorrectionLevel) {
3314
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
3315
+ const length = getTotalBitsFromDataArray(segments, currentVersion);
3316
+ if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
3317
+ return currentVersion;
3318
+ }
3319
+ }
3320
+ return void 0;
3321
+ }
3322
+ exports.from = function from(value, defaultValue) {
3323
+ if (VersionCheck.isValid(value)) {
3324
+ return parseInt(value, 10);
3325
+ }
3326
+ return defaultValue;
3327
+ };
3328
+ exports.getCapacity = function getCapacity(version, errorCorrectionLevel, mode) {
3329
+ if (!VersionCheck.isValid(version)) {
3330
+ throw new Error("Invalid QR Code version");
3331
+ }
3332
+ if (typeof mode === "undefined") mode = Mode.BYTE;
3333
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
3334
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
3335
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
3336
+ if (mode === Mode.MIXED) return dataTotalCodewordsBits;
3337
+ const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version);
3338
+ switch (mode) {
3339
+ case Mode.NUMERIC:
3340
+ return Math.floor(usableBits / 10 * 3);
3341
+ case Mode.ALPHANUMERIC:
3342
+ return Math.floor(usableBits / 11 * 2);
3343
+ case Mode.KANJI:
3344
+ return Math.floor(usableBits / 13);
3345
+ case Mode.BYTE:
3346
+ default:
3347
+ return Math.floor(usableBits / 8);
3348
+ }
3349
+ };
3350
+ exports.getBestVersionForData = function getBestVersionForData(data, errorCorrectionLevel) {
3351
+ let seg;
3352
+ const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M);
3353
+ if (Array.isArray(data)) {
3354
+ if (data.length > 1) {
3355
+ return getBestVersionForMixedData(data, ecl);
3356
+ }
3357
+ if (data.length === 0) {
3358
+ return 1;
3359
+ }
3360
+ seg = data[0];
3361
+ } else {
3362
+ seg = data;
3363
+ }
3364
+ return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl);
3365
+ };
3366
+ exports.getEncodedBits = function getEncodedBits(version) {
3367
+ if (!VersionCheck.isValid(version) || version < 7) {
3368
+ throw new Error("Invalid QR Code version");
3369
+ }
3370
+ let d = version << 12;
3371
+ while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
3372
+ d ^= G18 << Utils.getBCHDigit(d) - G18_BCH;
3373
+ }
3374
+ return version << 12 | d;
3375
+ };
3376
+ }
3377
+ });
3378
+
3379
+ // ../node_modules/qrcode/lib/core/format-info.js
3380
+ var require_format_info = __commonJS({
3381
+ "../node_modules/qrcode/lib/core/format-info.js"(exports) {
3382
+ var Utils = require_utils();
3383
+ var G15 = 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0;
3384
+ var G15_MASK = 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1;
3385
+ var G15_BCH = Utils.getBCHDigit(G15);
3386
+ exports.getEncodedBits = function getEncodedBits(errorCorrectionLevel, mask) {
3387
+ const data = errorCorrectionLevel.bit << 3 | mask;
3388
+ let d = data << 10;
3389
+ while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
3390
+ d ^= G15 << Utils.getBCHDigit(d) - G15_BCH;
3391
+ }
3392
+ return (data << 10 | d) ^ G15_MASK;
3393
+ };
3394
+ }
3395
+ });
3396
+
3397
+ // ../node_modules/qrcode/lib/core/numeric-data.js
3398
+ var require_numeric_data = __commonJS({
3399
+ "../node_modules/qrcode/lib/core/numeric-data.js"(exports, module) {
3400
+ var Mode = require_mode();
3401
+ function NumericData(data) {
3402
+ this.mode = Mode.NUMERIC;
3403
+ this.data = data.toString();
3404
+ }
3405
+ NumericData.getBitsLength = function getBitsLength(length) {
3406
+ return 10 * Math.floor(length / 3) + (length % 3 ? length % 3 * 3 + 1 : 0);
3407
+ };
3408
+ NumericData.prototype.getLength = function getLength() {
3409
+ return this.data.length;
3410
+ };
3411
+ NumericData.prototype.getBitsLength = function getBitsLength() {
3412
+ return NumericData.getBitsLength(this.data.length);
3413
+ };
3414
+ NumericData.prototype.write = function write(bitBuffer) {
3415
+ let i, group, value;
3416
+ for (i = 0; i + 3 <= this.data.length; i += 3) {
3417
+ group = this.data.substr(i, 3);
3418
+ value = parseInt(group, 10);
3419
+ bitBuffer.put(value, 10);
3420
+ }
3421
+ const remainingNum = this.data.length - i;
3422
+ if (remainingNum > 0) {
3423
+ group = this.data.substr(i);
3424
+ value = parseInt(group, 10);
3425
+ bitBuffer.put(value, remainingNum * 3 + 1);
3426
+ }
3427
+ };
3428
+ module.exports = NumericData;
3429
+ }
3430
+ });
3431
+
3432
+ // ../node_modules/qrcode/lib/core/alphanumeric-data.js
3433
+ var require_alphanumeric_data = __commonJS({
3434
+ "../node_modules/qrcode/lib/core/alphanumeric-data.js"(exports, module) {
3435
+ var Mode = require_mode();
3436
+ var ALPHA_NUM_CHARS = [
3437
+ "0",
3438
+ "1",
3439
+ "2",
3440
+ "3",
3441
+ "4",
3442
+ "5",
3443
+ "6",
3444
+ "7",
3445
+ "8",
3446
+ "9",
3447
+ "A",
3448
+ "B",
3449
+ "C",
3450
+ "D",
3451
+ "E",
3452
+ "F",
3453
+ "G",
3454
+ "H",
3455
+ "I",
3456
+ "J",
3457
+ "K",
3458
+ "L",
3459
+ "M",
3460
+ "N",
3461
+ "O",
3462
+ "P",
3463
+ "Q",
3464
+ "R",
3465
+ "S",
3466
+ "T",
3467
+ "U",
3468
+ "V",
3469
+ "W",
3470
+ "X",
3471
+ "Y",
3472
+ "Z",
3473
+ " ",
3474
+ "$",
3475
+ "%",
3476
+ "*",
3477
+ "+",
3478
+ "-",
3479
+ ".",
3480
+ "/",
3481
+ ":"
3482
+ ];
3483
+ function AlphanumericData(data) {
3484
+ this.mode = Mode.ALPHANUMERIC;
3485
+ this.data = data;
3486
+ }
3487
+ AlphanumericData.getBitsLength = function getBitsLength(length) {
3488
+ return 11 * Math.floor(length / 2) + 6 * (length % 2);
3489
+ };
3490
+ AlphanumericData.prototype.getLength = function getLength() {
3491
+ return this.data.length;
3492
+ };
3493
+ AlphanumericData.prototype.getBitsLength = function getBitsLength() {
3494
+ return AlphanumericData.getBitsLength(this.data.length);
3495
+ };
3496
+ AlphanumericData.prototype.write = function write(bitBuffer) {
3497
+ let i;
3498
+ for (i = 0; i + 2 <= this.data.length; i += 2) {
3499
+ let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45;
3500
+ value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]);
3501
+ bitBuffer.put(value, 11);
3502
+ }
3503
+ if (this.data.length % 2) {
3504
+ bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6);
3505
+ }
3506
+ };
3507
+ module.exports = AlphanumericData;
3508
+ }
3509
+ });
3510
+
3511
+ // ../node_modules/qrcode/lib/core/byte-data.js
3512
+ var require_byte_data = __commonJS({
3513
+ "../node_modules/qrcode/lib/core/byte-data.js"(exports, module) {
3514
+ var Mode = require_mode();
3515
+ function ByteData(data) {
3516
+ this.mode = Mode.BYTE;
3517
+ if (typeof data === "string") {
3518
+ this.data = new TextEncoder().encode(data);
3519
+ } else {
3520
+ this.data = new Uint8Array(data);
3521
+ }
3522
+ }
3523
+ ByteData.getBitsLength = function getBitsLength(length) {
3524
+ return length * 8;
3525
+ };
3526
+ ByteData.prototype.getLength = function getLength() {
3527
+ return this.data.length;
3528
+ };
3529
+ ByteData.prototype.getBitsLength = function getBitsLength() {
3530
+ return ByteData.getBitsLength(this.data.length);
3531
+ };
3532
+ ByteData.prototype.write = function(bitBuffer) {
3533
+ for (let i = 0, l = this.data.length; i < l; i++) {
3534
+ bitBuffer.put(this.data[i], 8);
3535
+ }
3536
+ };
3537
+ module.exports = ByteData;
3538
+ }
3539
+ });
3540
+
3541
+ // ../node_modules/qrcode/lib/core/kanji-data.js
3542
+ var require_kanji_data = __commonJS({
3543
+ "../node_modules/qrcode/lib/core/kanji-data.js"(exports, module) {
3544
+ var Mode = require_mode();
3545
+ var Utils = require_utils();
3546
+ function KanjiData(data) {
3547
+ this.mode = Mode.KANJI;
3548
+ this.data = data;
3549
+ }
3550
+ KanjiData.getBitsLength = function getBitsLength(length) {
3551
+ return length * 13;
3552
+ };
3553
+ KanjiData.prototype.getLength = function getLength() {
3554
+ return this.data.length;
3555
+ };
3556
+ KanjiData.prototype.getBitsLength = function getBitsLength() {
3557
+ return KanjiData.getBitsLength(this.data.length);
3558
+ };
3559
+ KanjiData.prototype.write = function(bitBuffer) {
3560
+ let i;
3561
+ for (i = 0; i < this.data.length; i++) {
3562
+ let value = Utils.toSJIS(this.data[i]);
3563
+ if (value >= 33088 && value <= 40956) {
3564
+ value -= 33088;
3565
+ } else if (value >= 57408 && value <= 60351) {
3566
+ value -= 49472;
3567
+ } else {
3568
+ throw new Error(
3569
+ "Invalid SJIS character: " + this.data[i] + "\nMake sure your charset is UTF-8"
3570
+ );
3571
+ }
3572
+ value = (value >>> 8 & 255) * 192 + (value & 255);
3573
+ bitBuffer.put(value, 13);
3574
+ }
3575
+ };
3576
+ module.exports = KanjiData;
3577
+ }
3578
+ });
3579
+
3580
+ // ../node_modules/dijkstrajs/dijkstra.js
3581
+ var require_dijkstra = __commonJS({
3582
+ "../node_modules/dijkstrajs/dijkstra.js"(exports, module) {
3583
+ "use strict";
3584
+ var dijkstra = {
3585
+ single_source_shortest_paths: function(graph, s, d) {
3586
+ var predecessors = {};
3587
+ var costs = {};
3588
+ costs[s] = 0;
3589
+ var open = dijkstra.PriorityQueue.make();
3590
+ open.push(s, 0);
3591
+ var closest, u, v, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit;
3592
+ while (!open.empty()) {
3593
+ closest = open.pop();
3594
+ u = closest.value;
3595
+ cost_of_s_to_u = closest.cost;
3596
+ adjacent_nodes = graph[u] || {};
3597
+ for (v in adjacent_nodes) {
3598
+ if (adjacent_nodes.hasOwnProperty(v)) {
3599
+ cost_of_e = adjacent_nodes[v];
3600
+ cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
3601
+ cost_of_s_to_v = costs[v];
3602
+ first_visit = typeof costs[v] === "undefined";
3603
+ if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
3604
+ costs[v] = cost_of_s_to_u_plus_cost_of_e;
3605
+ open.push(v, cost_of_s_to_u_plus_cost_of_e);
3606
+ predecessors[v] = u;
3607
+ }
3608
+ }
3609
+ }
3610
+ }
3611
+ if (typeof d !== "undefined" && typeof costs[d] === "undefined") {
3612
+ var msg = ["Could not find a path from ", s, " to ", d, "."].join("");
3613
+ throw new Error(msg);
3614
+ }
3615
+ return predecessors;
3616
+ },
3617
+ extract_shortest_path_from_predecessor_list: function(predecessors, d) {
3618
+ var nodes = [];
3619
+ var u = d;
3620
+ var predecessor;
3621
+ while (u) {
3622
+ nodes.push(u);
3623
+ predecessor = predecessors[u];
3624
+ u = predecessors[u];
3625
+ }
3626
+ nodes.reverse();
3627
+ return nodes;
3628
+ },
3629
+ find_path: function(graph, s, d) {
3630
+ var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
3631
+ return dijkstra.extract_shortest_path_from_predecessor_list(
3632
+ predecessors,
3633
+ d
3634
+ );
3635
+ },
3636
+ /**
3637
+ * A very naive priority queue implementation.
3638
+ */
3639
+ PriorityQueue: {
3640
+ make: function(opts) {
3641
+ var T = dijkstra.PriorityQueue, t = {}, key;
3642
+ opts = opts || {};
3643
+ for (key in T) {
3644
+ if (T.hasOwnProperty(key)) {
3645
+ t[key] = T[key];
3646
+ }
3647
+ }
3648
+ t.queue = [];
3649
+ t.sorter = opts.sorter || T.default_sorter;
3650
+ return t;
3651
+ },
3652
+ default_sorter: function(a, b) {
3653
+ return a.cost - b.cost;
3654
+ },
3655
+ /**
3656
+ * Add a new item to the queue and ensure the highest priority element
3657
+ * is at the front of the queue.
3658
+ */
3659
+ push: function(value, cost) {
3660
+ var item = { value, cost };
3661
+ this.queue.push(item);
3662
+ this.queue.sort(this.sorter);
3663
+ },
3664
+ /**
3665
+ * Return the highest priority element in the queue.
3666
+ */
3667
+ pop: function() {
3668
+ return this.queue.shift();
3669
+ },
3670
+ empty: function() {
3671
+ return this.queue.length === 0;
3672
+ }
3673
+ }
3674
+ };
3675
+ if (typeof module !== "undefined") {
3676
+ module.exports = dijkstra;
3677
+ }
3678
+ }
3679
+ });
3680
+
3681
+ // ../node_modules/qrcode/lib/core/segments.js
3682
+ var require_segments = __commonJS({
3683
+ "../node_modules/qrcode/lib/core/segments.js"(exports) {
3684
+ var Mode = require_mode();
3685
+ var NumericData = require_numeric_data();
3686
+ var AlphanumericData = require_alphanumeric_data();
3687
+ var ByteData = require_byte_data();
3688
+ var KanjiData = require_kanji_data();
3689
+ var Regex = require_regex();
3690
+ var Utils = require_utils();
3691
+ var dijkstra = require_dijkstra();
3692
+ function getStringByteLength(str) {
3693
+ return unescape(encodeURIComponent(str)).length;
3694
+ }
3695
+ function getSegments(regex, mode, str) {
3696
+ const segments = [];
3697
+ let result;
3698
+ while ((result = regex.exec(str)) !== null) {
3699
+ segments.push({
3700
+ data: result[0],
3701
+ index: result.index,
3702
+ mode,
3703
+ length: result[0].length
3704
+ });
3705
+ }
3706
+ return segments;
3707
+ }
3708
+ function getSegmentsFromString(dataStr) {
3709
+ const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr);
3710
+ const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr);
3711
+ let byteSegs;
3712
+ let kanjiSegs;
3713
+ if (Utils.isKanjiModeEnabled()) {
3714
+ byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr);
3715
+ kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr);
3716
+ } else {
3717
+ byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr);
3718
+ kanjiSegs = [];
3719
+ }
3720
+ const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs);
3721
+ return segs.sort(function(s1, s2) {
3722
+ return s1.index - s2.index;
3723
+ }).map(function(obj) {
3724
+ return {
3725
+ data: obj.data,
3726
+ mode: obj.mode,
3727
+ length: obj.length
3728
+ };
3729
+ });
3730
+ }
3731
+ function getSegmentBitsLength(length, mode) {
3732
+ switch (mode) {
3733
+ case Mode.NUMERIC:
3734
+ return NumericData.getBitsLength(length);
3735
+ case Mode.ALPHANUMERIC:
3736
+ return AlphanumericData.getBitsLength(length);
3737
+ case Mode.KANJI:
3738
+ return KanjiData.getBitsLength(length);
3739
+ case Mode.BYTE:
3740
+ return ByteData.getBitsLength(length);
3741
+ }
3742
+ }
3743
+ function mergeSegments(segs) {
3744
+ return segs.reduce(function(acc, curr) {
3745
+ const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null;
3746
+ if (prevSeg && prevSeg.mode === curr.mode) {
3747
+ acc[acc.length - 1].data += curr.data;
3748
+ return acc;
3749
+ }
3750
+ acc.push(curr);
3751
+ return acc;
3752
+ }, []);
3753
+ }
3754
+ function buildNodes(segs) {
3755
+ const nodes = [];
3756
+ for (let i = 0; i < segs.length; i++) {
3757
+ const seg = segs[i];
3758
+ switch (seg.mode) {
3759
+ case Mode.NUMERIC:
3760
+ nodes.push([
3761
+ seg,
3762
+ { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
3763
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
3764
+ ]);
3765
+ break;
3766
+ case Mode.ALPHANUMERIC:
3767
+ nodes.push([
3768
+ seg,
3769
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
3770
+ ]);
3771
+ break;
3772
+ case Mode.KANJI:
3773
+ nodes.push([
3774
+ seg,
3775
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
3776
+ ]);
3777
+ break;
3778
+ case Mode.BYTE:
3779
+ nodes.push([
3780
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
3781
+ ]);
3782
+ }
3783
+ }
3784
+ return nodes;
3785
+ }
3786
+ function buildGraph(nodes, version) {
3787
+ const table2 = {};
3788
+ const graph = { start: {} };
3789
+ let prevNodeIds = ["start"];
3790
+ for (let i = 0; i < nodes.length; i++) {
3791
+ const nodeGroup = nodes[i];
3792
+ const currentNodeIds = [];
3793
+ for (let j = 0; j < nodeGroup.length; j++) {
3794
+ const node = nodeGroup[j];
3795
+ const key = "" + i + j;
3796
+ currentNodeIds.push(key);
3797
+ table2[key] = { node, lastCount: 0 };
3798
+ graph[key] = {};
3799
+ for (let n = 0; n < prevNodeIds.length; n++) {
3800
+ const prevNodeId = prevNodeIds[n];
3801
+ if (table2[prevNodeId] && table2[prevNodeId].node.mode === node.mode) {
3802
+ graph[prevNodeId][key] = getSegmentBitsLength(table2[prevNodeId].lastCount + node.length, node.mode) - getSegmentBitsLength(table2[prevNodeId].lastCount, node.mode);
3803
+ table2[prevNodeId].lastCount += node.length;
3804
+ } else {
3805
+ if (table2[prevNodeId]) table2[prevNodeId].lastCount = node.length;
3806
+ graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) + 4 + Mode.getCharCountIndicator(node.mode, version);
3807
+ }
3808
+ }
3809
+ }
3810
+ prevNodeIds = currentNodeIds;
3811
+ }
3812
+ for (let n = 0; n < prevNodeIds.length; n++) {
3813
+ graph[prevNodeIds[n]].end = 0;
3814
+ }
3815
+ return { map: graph, table: table2 };
3816
+ }
3817
+ function buildSingleSegment(data, modesHint) {
3818
+ let mode;
3819
+ const bestMode = Mode.getBestModeForData(data);
3820
+ mode = Mode.from(modesHint, bestMode);
3821
+ if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
3822
+ throw new Error('"' + data + '" cannot be encoded with mode ' + Mode.toString(mode) + ".\n Suggested mode is: " + Mode.toString(bestMode));
3823
+ }
3824
+ if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
3825
+ mode = Mode.BYTE;
3826
+ }
3827
+ switch (mode) {
3828
+ case Mode.NUMERIC:
3829
+ return new NumericData(data);
3830
+ case Mode.ALPHANUMERIC:
3831
+ return new AlphanumericData(data);
3832
+ case Mode.KANJI:
3833
+ return new KanjiData(data);
3834
+ case Mode.BYTE:
3835
+ return new ByteData(data);
3836
+ }
3837
+ }
3838
+ exports.fromArray = function fromArray(array) {
3839
+ return array.reduce(function(acc, seg) {
3840
+ if (typeof seg === "string") {
3841
+ acc.push(buildSingleSegment(seg, null));
3842
+ } else if (seg.data) {
3843
+ acc.push(buildSingleSegment(seg.data, seg.mode));
3844
+ }
3845
+ return acc;
3846
+ }, []);
3847
+ };
3848
+ exports.fromString = function fromString(data, version) {
3849
+ const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled());
3850
+ const nodes = buildNodes(segs);
3851
+ const graph = buildGraph(nodes, version);
3852
+ const path = dijkstra.find_path(graph.map, "start", "end");
3853
+ const optimizedSegs = [];
3854
+ for (let i = 1; i < path.length - 1; i++) {
3855
+ optimizedSegs.push(graph.table[path[i]].node);
3856
+ }
3857
+ return exports.fromArray(mergeSegments(optimizedSegs));
3858
+ };
3859
+ exports.rawSplit = function rawSplit(data) {
3860
+ return exports.fromArray(
3861
+ getSegmentsFromString(data, Utils.isKanjiModeEnabled())
3862
+ );
3863
+ };
3864
+ }
3865
+ });
3866
+
3867
+ // ../node_modules/qrcode/lib/core/qrcode.js
3868
+ var require_qrcode = __commonJS({
3869
+ "../node_modules/qrcode/lib/core/qrcode.js"(exports) {
3870
+ var Utils = require_utils();
3871
+ var ECLevel = require_error_correction_level();
3872
+ var BitBuffer = require_bit_buffer();
3873
+ var BitMatrix = require_bit_matrix();
3874
+ var AlignmentPattern = require_alignment_pattern();
3875
+ var FinderPattern = require_finder_pattern();
3876
+ var MaskPattern = require_mask_pattern();
3877
+ var ECCode = require_error_correction_code();
3878
+ var ReedSolomonEncoder = require_reed_solomon_encoder();
3879
+ var Version = require_version();
3880
+ var FormatInfo = require_format_info();
3881
+ var Mode = require_mode();
3882
+ var Segments = require_segments();
3883
+ function setupFinderPattern(matrix, version) {
3884
+ const size = matrix.size;
3885
+ const pos = FinderPattern.getPositions(version);
3886
+ for (let i = 0; i < pos.length; i++) {
3887
+ const row = pos[i][0];
3888
+ const col = pos[i][1];
3889
+ for (let r = -1; r <= 7; r++) {
3890
+ if (row + r <= -1 || size <= row + r) continue;
3891
+ for (let c2 = -1; c2 <= 7; c2++) {
3892
+ if (col + c2 <= -1 || size <= col + c2) continue;
3893
+ if (r >= 0 && r <= 6 && (c2 === 0 || c2 === 6) || c2 >= 0 && c2 <= 6 && (r === 0 || r === 6) || r >= 2 && r <= 4 && c2 >= 2 && c2 <= 4) {
3894
+ matrix.set(row + r, col + c2, true, true);
3895
+ } else {
3896
+ matrix.set(row + r, col + c2, false, true);
3897
+ }
3898
+ }
3899
+ }
3900
+ }
3901
+ }
3902
+ function setupTimingPattern(matrix) {
3903
+ const size = matrix.size;
3904
+ for (let r = 8; r < size - 8; r++) {
3905
+ const value = r % 2 === 0;
3906
+ matrix.set(r, 6, value, true);
3907
+ matrix.set(6, r, value, true);
3908
+ }
3909
+ }
3910
+ function setupAlignmentPattern(matrix, version) {
3911
+ const pos = AlignmentPattern.getPositions(version);
3912
+ for (let i = 0; i < pos.length; i++) {
3913
+ const row = pos[i][0];
3914
+ const col = pos[i][1];
3915
+ for (let r = -2; r <= 2; r++) {
3916
+ for (let c2 = -2; c2 <= 2; c2++) {
3917
+ if (r === -2 || r === 2 || c2 === -2 || c2 === 2 || r === 0 && c2 === 0) {
3918
+ matrix.set(row + r, col + c2, true, true);
3919
+ } else {
3920
+ matrix.set(row + r, col + c2, false, true);
3921
+ }
3922
+ }
3923
+ }
3924
+ }
3925
+ }
3926
+ function setupVersionInfo(matrix, version) {
3927
+ const size = matrix.size;
3928
+ const bits = Version.getEncodedBits(version);
3929
+ let row, col, mod;
3930
+ for (let i = 0; i < 18; i++) {
3931
+ row = Math.floor(i / 3);
3932
+ col = i % 3 + size - 8 - 3;
3933
+ mod = (bits >> i & 1) === 1;
3934
+ matrix.set(row, col, mod, true);
3935
+ matrix.set(col, row, mod, true);
3936
+ }
3937
+ }
3938
+ function setupFormatInfo(matrix, errorCorrectionLevel, maskPattern) {
3939
+ const size = matrix.size;
3940
+ const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern);
3941
+ let i, mod;
3942
+ for (i = 0; i < 15; i++) {
3943
+ mod = (bits >> i & 1) === 1;
3944
+ if (i < 6) {
3945
+ matrix.set(i, 8, mod, true);
3946
+ } else if (i < 8) {
3947
+ matrix.set(i + 1, 8, mod, true);
3948
+ } else {
3949
+ matrix.set(size - 15 + i, 8, mod, true);
3950
+ }
3951
+ if (i < 8) {
3952
+ matrix.set(8, size - i - 1, mod, true);
3953
+ } else if (i < 9) {
3954
+ matrix.set(8, 15 - i - 1 + 1, mod, true);
3955
+ } else {
3956
+ matrix.set(8, 15 - i - 1, mod, true);
3957
+ }
3958
+ }
3959
+ matrix.set(size - 8, 8, 1, true);
3960
+ }
3961
+ function setupData(matrix, data) {
3962
+ const size = matrix.size;
3963
+ let inc = -1;
3964
+ let row = size - 1;
3965
+ let bitIndex = 7;
3966
+ let byteIndex = 0;
3967
+ for (let col = size - 1; col > 0; col -= 2) {
3968
+ if (col === 6) col--;
3969
+ while (true) {
3970
+ for (let c2 = 0; c2 < 2; c2++) {
3971
+ if (!matrix.isReserved(row, col - c2)) {
3972
+ let dark = false;
3973
+ if (byteIndex < data.length) {
3974
+ dark = (data[byteIndex] >>> bitIndex & 1) === 1;
3975
+ }
3976
+ matrix.set(row, col - c2, dark);
3977
+ bitIndex--;
3978
+ if (bitIndex === -1) {
3979
+ byteIndex++;
3980
+ bitIndex = 7;
3981
+ }
3982
+ }
3983
+ }
3984
+ row += inc;
3985
+ if (row < 0 || size <= row) {
3986
+ row -= inc;
3987
+ inc = -inc;
3988
+ break;
3989
+ }
3990
+ }
3991
+ }
3992
+ }
3993
+ function createData(version, errorCorrectionLevel, segments) {
3994
+ const buffer = new BitBuffer();
3995
+ segments.forEach(function(data) {
3996
+ buffer.put(data.mode.bit, 4);
3997
+ buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version));
3998
+ data.write(buffer);
3999
+ });
4000
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
4001
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
4002
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
4003
+ if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
4004
+ buffer.put(0, 4);
4005
+ }
4006
+ while (buffer.getLengthInBits() % 8 !== 0) {
4007
+ buffer.putBit(0);
4008
+ }
4009
+ const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8;
4010
+ for (let i = 0; i < remainingByte; i++) {
4011
+ buffer.put(i % 2 ? 17 : 236, 8);
4012
+ }
4013
+ return createCodewords(buffer, version, errorCorrectionLevel);
4014
+ }
4015
+ function createCodewords(bitBuffer, version, errorCorrectionLevel) {
4016
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
4017
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
4018
+ const dataTotalCodewords = totalCodewords - ecTotalCodewords;
4019
+ const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel);
4020
+ const blocksInGroup2 = totalCodewords % ecTotalBlocks;
4021
+ const blocksInGroup1 = ecTotalBlocks - blocksInGroup2;
4022
+ const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks);
4023
+ const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks);
4024
+ const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1;
4025
+ const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1;
4026
+ const rs = new ReedSolomonEncoder(ecCount);
4027
+ let offset = 0;
4028
+ const dcData = new Array(ecTotalBlocks);
4029
+ const ecData = new Array(ecTotalBlocks);
4030
+ let maxDataSize = 0;
4031
+ const buffer = new Uint8Array(bitBuffer.buffer);
4032
+ for (let b = 0; b < ecTotalBlocks; b++) {
4033
+ const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2;
4034
+ dcData[b] = buffer.slice(offset, offset + dataSize);
4035
+ ecData[b] = rs.encode(dcData[b]);
4036
+ offset += dataSize;
4037
+ maxDataSize = Math.max(maxDataSize, dataSize);
4038
+ }
4039
+ const data = new Uint8Array(totalCodewords);
4040
+ let index = 0;
4041
+ let i, r;
4042
+ for (i = 0; i < maxDataSize; i++) {
4043
+ for (r = 0; r < ecTotalBlocks; r++) {
4044
+ if (i < dcData[r].length) {
4045
+ data[index++] = dcData[r][i];
4046
+ }
4047
+ }
4048
+ }
4049
+ for (i = 0; i < ecCount; i++) {
4050
+ for (r = 0; r < ecTotalBlocks; r++) {
4051
+ data[index++] = ecData[r][i];
4052
+ }
4053
+ }
4054
+ return data;
4055
+ }
4056
+ function createSymbol(data, version, errorCorrectionLevel, maskPattern) {
4057
+ let segments;
4058
+ if (Array.isArray(data)) {
4059
+ segments = Segments.fromArray(data);
4060
+ } else if (typeof data === "string") {
4061
+ let estimatedVersion = version;
4062
+ if (!estimatedVersion) {
4063
+ const rawSegments = Segments.rawSplit(data);
4064
+ estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel);
4065
+ }
4066
+ segments = Segments.fromString(data, estimatedVersion || 40);
4067
+ } else {
4068
+ throw new Error("Invalid data");
4069
+ }
4070
+ const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel);
4071
+ if (!bestVersion) {
4072
+ throw new Error("The amount of data is too big to be stored in a QR Code");
4073
+ }
4074
+ if (!version) {
4075
+ version = bestVersion;
4076
+ } else if (version < bestVersion) {
4077
+ throw new Error(
4078
+ "\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: " + bestVersion + ".\n"
4079
+ );
4080
+ }
4081
+ const dataBits = createData(version, errorCorrectionLevel, segments);
4082
+ const moduleCount = Utils.getSymbolSize(version);
4083
+ const modules = new BitMatrix(moduleCount);
4084
+ setupFinderPattern(modules, version);
4085
+ setupTimingPattern(modules);
4086
+ setupAlignmentPattern(modules, version);
4087
+ setupFormatInfo(modules, errorCorrectionLevel, 0);
4088
+ if (version >= 7) {
4089
+ setupVersionInfo(modules, version);
4090
+ }
4091
+ setupData(modules, dataBits);
4092
+ if (isNaN(maskPattern)) {
4093
+ maskPattern = MaskPattern.getBestMask(
4094
+ modules,
4095
+ setupFormatInfo.bind(null, modules, errorCorrectionLevel)
4096
+ );
4097
+ }
4098
+ MaskPattern.applyMask(maskPattern, modules);
4099
+ setupFormatInfo(modules, errorCorrectionLevel, maskPattern);
4100
+ return {
4101
+ modules,
4102
+ version,
4103
+ errorCorrectionLevel,
4104
+ maskPattern,
4105
+ segments
4106
+ };
4107
+ }
4108
+ exports.create = function create(data, options) {
4109
+ if (typeof data === "undefined" || data === "") {
4110
+ throw new Error("No input text");
4111
+ }
4112
+ let errorCorrectionLevel = ECLevel.M;
4113
+ let version;
4114
+ let mask;
4115
+ if (typeof options !== "undefined") {
4116
+ errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M);
4117
+ version = Version.from(options.version);
4118
+ mask = MaskPattern.from(options.maskPattern);
4119
+ if (options.toSJISFunc) {
4120
+ Utils.setToSJISFunction(options.toSJISFunc);
4121
+ }
4122
+ }
4123
+ return createSymbol(data, version, errorCorrectionLevel, mask);
4124
+ };
4125
+ }
4126
+ });
4127
+
1961
4128
  // src/extra.ts
1962
4129
  var extra_exports = {};
1963
4130
  __export(extra_exports, {
@@ -1965,13 +4132,15 @@ __export(extra_exports, {
1965
4132
  accessCloudflare: () => accessCloudflare,
1966
4133
  accessSet: () => accessSet,
1967
4134
  accessShow: () => accessShow,
4135
+ pair: () => pair,
4136
+ qrBlocks: () => qrBlocks,
1968
4137
  skill: () => skill,
1969
4138
  ui: () => ui
1970
4139
  });
1971
4140
  import { spawn as spawn5 } from "node:child_process";
1972
4141
  import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "node:fs";
1973
- import { homedir as homedir2 } from "node:os";
1974
- import { dirname as dirname2, join as join4 } from "node:path";
4142
+ import { homedir as homedir3 } from "node:os";
4143
+ import { dirname as dirname2, join as join5 } from "node:path";
1975
4144
  function openBrowser(url) {
1976
4145
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1977
4146
  const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
@@ -1996,6 +4165,35 @@ async function ui(opts) {
1996
4165
  }
1997
4166
  ok(`Opened the dashboard for ${cfg.url} ${c.dim("(one-time link, valid 2 minutes)")}`);
1998
4167
  }
4168
+ function qrBlocks(text) {
4169
+ const qr = (0, import_qrcode.create)(text, { errorCorrectionLevel: "M" });
4170
+ const n = qr.modules.size;
4171
+ const q = 2;
4172
+ const dark = (x, y) => x >= 0 && y >= 0 && x < n && y < n && Boolean(qr.modules.get(y, x));
4173
+ const out2 = [];
4174
+ for (let y = -q; y < n + q; y += 2) {
4175
+ let row = "";
4176
+ for (let x = -q; x < n + q; x++) {
4177
+ const top = dark(x, y);
4178
+ const bottom = dark(x, y + 1);
4179
+ row += top && bottom ? "\u2588" : top ? "\u2580" : bottom ? "\u2584" : " ";
4180
+ }
4181
+ out2.push(` \x1B[30;107m${row}\x1B[0m`);
4182
+ }
4183
+ return out2.join("\n") + "\n";
4184
+ }
4185
+ async function pair() {
4186
+ if (!process.stderr.isTTY) {
4187
+ throw new UserError("keybox pair draws a QR code for your phone; run it yourself in a terminal. (For a browser, use `keybox ui`.)");
4188
+ }
4189
+ const cfg = requireConfig();
4190
+ const { code } = await api("POST", "/ui/link");
4191
+ const url = `${cfg.url.replace(/\/$/, "")}/_keybox/ui#code=${code}`;
4192
+ step(`Scan this with the Keybox app ${c.dim("(Pair \u203A Scan QR code)")}`);
4193
+ process.stderr.write("\n" + qrBlocks(url) + "\n");
4194
+ note("Works once, for 2 minutes. The app gets a 12-hour session; your admin token stays on this machine.");
4195
+ note("To end every dashboard and app session: Access \u203A Sign out every dashboard session.");
4196
+ }
1999
4197
  async function accessShow() {
2000
4198
  const [p, me] = await Promise.all([api("GET", "/policy"), api("GET", "/whoami")]);
2001
4199
  process.stdout.write(
@@ -2070,11 +4268,11 @@ async function accessCloudflare(opts) {
2070
4268
  async function skill(opts) {
2071
4269
  const text = readFileSync6(skillAsset(), "utf8");
2072
4270
  if (opts.print) return void process.stdout.write(text);
2073
- const base = opts.project ? process.cwd() : homedir2();
4271
+ const base = opts.project ? process.cwd() : homedir3();
2074
4272
  const targets = {
2075
- claude: join4(base, ".claude", "skills", "keybox", "SKILL.md"),
2076
- codex: join4(opts.project ? join4(base, ".codex") : join4(homedir2(), ".codex"), "skills", "keybox", "SKILL.md"),
2077
- agents: join4(base, ".agents", "skills", "keybox", "SKILL.md")
4273
+ claude: join5(base, ".claude", "skills", "keybox", "SKILL.md"),
4274
+ codex: join5(opts.project ? join5(base, ".codex") : join5(homedir3(), ".codex"), "skills", "keybox", "SKILL.md"),
4275
+ agents: join5(base, ".agents", "skills", "keybox", "SKILL.md")
2078
4276
  };
2079
4277
  const pick = opts.target === "all" ? Object.keys(targets) : opts.target.split(",");
2080
4278
  for (const t of pick) {
@@ -2088,10 +4286,11 @@ async function skill(opts) {
2088
4286
  step("Agents that load skills now know how to set up Keybox, migrate keys and write narrow rules safely.");
2089
4287
  note('Ask yours: "set up keybox for this project".');
2090
4288
  }
2091
- var describe, skillAsset;
4289
+ var import_qrcode, describe, skillAsset;
2092
4290
  var init_extra = __esm({
2093
4291
  "src/extra.ts"() {
2094
4292
  "use strict";
4293
+ import_qrcode = __toESM(require_qrcode(), 1);
2095
4294
  init_api();
2096
4295
  init_config();
2097
4296
  init_prompt();
@@ -2123,7 +4322,7 @@ init_dove();
2123
4322
  init_ui();
2124
4323
  import { spawn as spawn6 } from "node:child_process";
2125
4324
  import { existsSync as existsSync5 } from "node:fs";
2126
- import { delimiter, join as join5 } from "node:path";
4325
+ import { delimiter, join as join6 } from "node:path";
2127
4326
  var TABS = ["Activity", "Secrets", "Agents"];
2128
4327
  var out = process.stdout;
2129
4328
  var ago2 = (ms) => {
@@ -2152,7 +4351,7 @@ function nativeTui() {
2152
4351
  if (explicit && existsSync5(explicit)) return explicit;
2153
4352
  for (const dir of (process.env.PATH ?? "").split(delimiter)) {
2154
4353
  for (const name of process.platform === "win32" ? ["keybox-tui.exe"] : ["keybox-tui"]) {
2155
- const p = join5(dir, name);
4354
+ const p = join6(dir, name);
2156
4355
  if (dir && existsSync5(p)) return p;
2157
4356
  }
2158
4357
  }
@@ -2351,14 +4550,14 @@ init_verify();
2351
4550
  init_version();
2352
4551
  import { spawn as spawn7, spawnSync as spawnSync2 } from "node:child_process";
2353
4552
  import { existsSync as existsSync6, realpathSync } from "node:fs";
2354
- import { dirname as dirname3, join as join6 } from "node:path";
4553
+ import { dirname as dirname3, join as join7 } from "node:path";
2355
4554
  import { fileURLToPath } from "node:url";
2356
4555
  function howInstalled() {
2357
4556
  const self = realpathSync(fileURLToPath(import.meta.url));
2358
- if (self.includes(`${join6("_npx", "")}`) || self.includes("/_npx/")) return { kind: "npx" };
4557
+ if (self.includes(`${join7("_npx", "")}`) || self.includes("/_npx/")) return { kind: "npx" };
2359
4558
  const root = dirname3(dirname3(dirname3(self)));
2360
- if (existsSync6(join6(root, ".git")) && existsSync6(join6(root, "cli", "package.json"))) return { kind: "checkout", root };
2361
- if (self.includes(join6("node_modules", "@keyboxed", "cli"))) return { kind: "npm-global" };
4559
+ if (existsSync6(join7(root, ".git")) && existsSync6(join7(root, "cli", "package.json"))) return { kind: "checkout", root };
4560
+ if (self.includes(join7("node_modules", "@keyboxed", "cli"))) return { kind: "npm-global" };
2362
4561
  return { kind: "unknown", path: self };
2363
4562
  }
2364
4563
  function newer(a, b) {
@@ -2410,14 +4609,21 @@ async function update(opts) {
2410
4609
  else if (install.kind === "npx") note(`You run Keybox through npx. Use npx @keyboxed/cli@${v} \u2026 from now on.`);
2411
4610
  else if (install.kind === "unknown") note(`Installed somewhere unusual (${install.path}). Install ${v} the way you installed this one.`);
2412
4611
  else if (opts.yes || await confirm(`Install @keyboxed/cli ${v}?`, true)) {
2413
- if (await run2("npm", ["install", "-g", `@keyboxed/cli@${v}`]) !== 0) throw new UserError("npm install failed. You may need to fix npm permissions, or use npx.");
4612
+ const args = ["install", "-g", "--prefer-online", `@keyboxed/cli@${v}`];
4613
+ let code = await run2("npm", args);
4614
+ if (code !== 0) {
4615
+ note("Retrying in 20 seconds in case the release has not reached every npm mirror yet\u2026");
4616
+ await new Promise((r) => setTimeout(r, 2e4));
4617
+ code = await run2("npm", args);
4618
+ }
4619
+ if (code !== 0) throw new UserError("npm install failed. You may need to fix npm permissions, or use npx.");
2414
4620
  cliUpdated = true;
2415
4621
  }
2416
4622
  } else if (v) ok(`${"CLI".padEnd(16)}${c.dim("up to date")}`);
2417
4623
  }
2418
4624
  if (cliUpdated) {
2419
4625
  ok("CLI updated. Continuing with the new version.");
2420
- const bin2 = install.kind === "checkout" ? [process.execPath, join6(install.root, "cli", "dist", "keybox.js")] : ["keybox"];
4626
+ const bin2 = install.kind === "checkout" ? [process.execPath, join7(install.root, "cli", "dist", "keybox.js")] : ["keybox"];
2421
4627
  const code = await run2(bin2[0], [...bin2.slice(1), "update", "--worker-only", ...opts.yes ? ["--yes"] : []]);
2422
4628
  process.exitCode = code;
2423
4629
  return;
@@ -2435,7 +4641,7 @@ async function updateWorker(opts) {
2435
4641
  const { deploy: deploy2 } = await Promise.resolve().then(() => (init_deploy(), deploy_exports));
2436
4642
  const { checks: checks2, printChecks: printChecks2, resolveAccount: resolveAccount2 } = await Promise.resolve().then(() => (init_verify(), verify_exports));
2437
4643
  await resolveAccount2(cfg);
2438
- const list2 = await task("Worker", () => checks2(cfg), () => `v${deployedVersion} deployed, this CLI ships v${VERSION}`);
4644
+ const list2 = await task("Worker", () => checks2(cfg), () => `v${deployedVersion} deployed, this CLI ships v${shippedWorkerVersion()}`);
2439
4645
  const code = list2.find((x) => x.label === "Code");
2440
4646
  if (code?.ok === true) {
2441
4647
  if (!list2.every((x) => x.ok === true)) printChecks2(list2);
@@ -2456,16 +4662,19 @@ var HELP_BODY = `Setup
2456
4662
  keybox deploy [--yes] Replace the deployed Worker with this CLI's version
2457
4663
  keybox status
2458
4664
  keybox ui [--print] Open the web dashboard (one-time login link)
4665
+ keybox pair Pair the Keybox phone app (one-time QR code)
2459
4666
  keybox tui [--basic] Live console (uses keybox-tui, the Rust console, when installed)
2460
4667
 
2461
4668
  Moving keys in (values are never printed, logged or put on a command line)
2462
- keybox migrate [--from SOURCE] [--dry-run] [--yes] [--only A,B]
4669
+ keybox migrate [--from SOURCE] [--dry-run] [--yes] [--park] [--only A,B]
2463
4670
  SOURCE: dotenv:FILE | env | 1password [--vault V] | bitwarden | bws [--project ID]
2464
- doppler [--project P --config C] | infisical [--env E --path P]
4671
+ doppler [--project P --config C] | infisical [--project A,B --env dev,prod --path P]
2465
4672
  vault:PATH | sops:FILE | aws:SECRET_ID | gcp [--project P]
2466
4673
  pass --item PATH | keychain --item SERVICE
2467
4674
  keybox secrets add NAME [--from op://vault/item/field | vault://path#field | env://VAR \u2026]
2468
4675
  [--preset openai|anthropic|github|\u2026] [--host HOST \u2026 --header H --format bearer|raw|basic]
4676
+ keybox secrets bind [NAME] [--preset P | --host HOST \u2026 --header H --format F]
4677
+ Give a parked key a host, or change where a key may go, without re-sending it
2469
4678
  keybox secrets list | rm NAME
2470
4679
 
2471
4680
  Agents
@@ -2509,6 +4718,7 @@ async function main(argv) {
2509
4718
  url: { type: "string" },
2510
4719
  yes: { type: "boolean", short: "y", default: false },
2511
4720
  "dry-run": { type: "boolean", default: false },
4721
+ park: { type: "boolean", default: false },
2512
4722
  force: { type: "boolean", default: false },
2513
4723
  preset: { type: "string" },
2514
4724
  host: { type: "string", multiple: true },
@@ -2570,6 +4780,8 @@ async function main(argv) {
2570
4780
  return status();
2571
4781
  case "ui":
2572
4782
  return ui({ print: o.print });
4783
+ case "pair":
4784
+ return pair();
2573
4785
  case "tui":
2574
4786
  return tui({ basic: o.basic });
2575
4787
  case "migrate":
@@ -2583,12 +4795,15 @@ async function main(argv) {
2583
4795
  config: o.config,
2584
4796
  env: o.env,
2585
4797
  path: o.path,
2586
- item: o.item
4798
+ item: o.item,
4799
+ park: o.park
2587
4800
  });
2588
4801
  case "secrets add":
2589
4802
  return secretsAdd(need(arg, "secret name"), { preset: o.preset, host: o.host, header: o.header, format: o.format, from: o.from });
2590
4803
  case "secrets import":
2591
4804
  return secretsImport(need(arg, "file"), { dryRun: o["dry-run"], yes: o.yes });
4805
+ case "secrets bind":
4806
+ return secretsBind(arg, { preset: o.preset, host: o.host, header: o.header, format: o.format });
2592
4807
  case "secrets list":
2593
4808
  return secretsList();
2594
4809
  case "secrets rm":