@xenosystem/agent-cli 0.5.115 → 0.5.116

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.
@@ -588,6 +588,578 @@ var WindowsHostRpc = class WindowsHostRpc2 {
588
588
  }
589
589
  };
590
590
 
591
+ // src/linux-host.ts
592
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
593
+ import { spawn as spawn2 } from "node:child_process";
594
+ import { createHash as createHash2, createPrivateKey, generateKeyPairSync, randomUUID as randomUUID2, sign } from "node:crypto";
595
+ import { closeSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs";
596
+ import { delimiter, isAbsolute, join as join2 } from "node:path";
597
+ import { hostname, tmpdir } from "node:os";
598
+ var VALUE_PREFIX = "xa1:";
599
+ var MAX_VALUE_BYTES = 2560;
600
+ var MAX_KEY_BYTES = 1024;
601
+ function refused2() {
602
+ return new AccountError({
603
+ code: "UNREACHABLE",
604
+ message: "Linux account host authority is unavailable",
605
+ retryable: false
606
+ });
607
+ }
608
+ __name(refused2, "refused");
609
+ async function createLinuxAccountHost(options) {
610
+ if (process.platform !== "linux") throw refused2();
611
+ const timeoutMs = options.timeoutMs ?? 15e3;
612
+ const tool = findSecretTool();
613
+ return openLinuxAccountHost(options, {
614
+ secretTool: tool ? secretToolRunner(tool, timeoutMs) : null,
615
+ lockDirectory: runtimeLockDirectory()
616
+ });
617
+ }
618
+ __name(createLinuxAccountHost, "createLinuxAccountHost");
619
+ async function openLinuxAccountHost(options, deps) {
620
+ const clientId = options.clientId, namespace = options.namespace ?? clientId;
621
+ const timeoutMs = options.timeoutMs ?? 15e3, waitMs = options.lockTimeoutMs ?? 5e3;
622
+ const transactionTimeoutMs = options.transactionTimeoutMs ?? timeoutMs;
623
+ if (typeof clientId !== "string" || typeof namespace !== "string" || !/^xeno-[a-z0-9][a-z0-9-]{0,63}$/.test(clientId) || !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(namespace) || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1e3 || timeoutMs > 12e4 || !Number.isSafeInteger(waitMs) || waitMs < 1 || waitMs > 1e4 || !Number.isSafeInteger(transactionTimeoutMs) || transactionTimeoutMs < 100 || transactionTimeoutMs > 12e4 || options.createKey !== void 0 && typeof options.createKey !== "boolean") throw refused2();
624
+ const identity = createHash2("sha256").update(`xeno/account/linux-host/1\0${namespace}\0${clientId}`).digest("hex");
625
+ const keyName = `Xeno.Account.${identity}`;
626
+ const refreshKey = `xeno.account/${clientId}/refresh`;
627
+ const keyring = deps.secretTool ? new Keyring(deps.secretTool, identity, clientId) : null;
628
+ let custody, privateKey, publicJwk;
629
+ let persistent;
630
+ const stored = keyring ? await keyring.read("dpop-key").catch(() => void 0) : void 0;
631
+ if (typeof stored === "string") {
632
+ ({ privateKey, publicJwk } = parsePrivateJwk(stored));
633
+ persistent = true;
634
+ custody = {
635
+ kind: "linux-secret-service+software-key",
636
+ hardwareBacked: false,
637
+ nonExportable: false,
638
+ persistent: true,
639
+ createdKey: false,
640
+ keyName
641
+ };
642
+ } else {
643
+ if (options.createKey !== true) throw refused2();
644
+ const generated = generateKeyPairSync("ec", {
645
+ namedCurve: "P-256"
646
+ });
647
+ const jwk = JSON.stringify(generated.privateKey.export({
648
+ format: "jwk"
649
+ }));
650
+ ({ privateKey, publicJwk } = parsePrivateJwk(jwk));
651
+ if (keyring && stored === null && await keyring.works()) {
652
+ if (await keyring.read("refresh") !== null || await keyring.read("pending") !== null) throw refused2();
653
+ await keyring.write("dpop-key", jwk);
654
+ persistent = true;
655
+ custody = {
656
+ kind: "linux-secret-service+software-key",
657
+ hardwareBacked: false,
658
+ nonExportable: false,
659
+ persistent: true,
660
+ createdKey: true,
661
+ keyName
662
+ };
663
+ } else {
664
+ persistent = false;
665
+ custody = {
666
+ kind: "linux-session-memory+software-key",
667
+ hardwareBacked: false,
668
+ nonExportable: false,
669
+ persistent: false,
670
+ createdKey: true,
671
+ keyName
672
+ };
673
+ }
674
+ }
675
+ const jkt = createHash2("sha256").update(JSON.stringify({
676
+ crv: publicJwk.crv,
677
+ kty: publicJwk.kty,
678
+ x: publicJwk.x,
679
+ y: publicJwk.y
680
+ })).digest("base64url");
681
+ const memory = /* @__PURE__ */ new Map();
682
+ const lock = persistent ? new ProcessLock(deps.lockDirectory, identity) : null;
683
+ const context = new AsyncLocalStorage2();
684
+ let tail = Promise.resolve(), locks = 0, closed = false, closing = false, failed = false;
685
+ const current = /* @__PURE__ */ __name(() => {
686
+ if (closed || closing || failed) throw refused2();
687
+ }, "current");
688
+ const itemOf = /* @__PURE__ */ __name((key) => {
689
+ current();
690
+ if (key === refreshKey) return "refresh";
691
+ if (key === `${refreshKey}/pending`) return "pending";
692
+ throw refused2();
693
+ }, "itemOf");
694
+ const exclusive = /* @__PURE__ */ __name(async (key, work) => {
695
+ itemOf(key);
696
+ if (context.getStore() || locks >= 64) throw refused2();
697
+ locks++;
698
+ const prior = tail;
699
+ let release;
700
+ tail = new Promise((resolve) => {
701
+ release = resolve;
702
+ });
703
+ await prior;
704
+ const lease = {
705
+ id: randomUUID2(),
706
+ active: true
707
+ };
708
+ let acquired = false;
709
+ try {
710
+ current();
711
+ if (lock) {
712
+ await lock.acquire(waitMs);
713
+ acquired = true;
714
+ }
715
+ let timer;
716
+ try {
717
+ return await Promise.race([
718
+ context.run(lease, work),
719
+ new Promise((_resolve, reject) => {
720
+ timer = setTimeout(() => {
721
+ lease.active = false;
722
+ failed = true;
723
+ reject(refused2());
724
+ }, transactionTimeoutMs);
725
+ })
726
+ ]);
727
+ } finally {
728
+ if (timer) clearTimeout(timer);
729
+ }
730
+ } finally {
731
+ lease.active = false;
732
+ try {
733
+ if (acquired && lock && !lock.release()) failed = true;
734
+ } finally {
735
+ locks--;
736
+ release();
737
+ }
738
+ }
739
+ }, "exclusive");
740
+ const storage = /* @__PURE__ */ __name(async (key, operation) => {
741
+ const item = itemOf(key);
742
+ const lease = context.getStore();
743
+ if (lease) {
744
+ if (!lease.active) throw refused2();
745
+ try {
746
+ return await operation(item);
747
+ } catch {
748
+ if (persistent) failed = true;
749
+ throw refused2();
750
+ }
751
+ }
752
+ return exclusive(refreshKey, () => storage(key, operation));
753
+ }, "storage");
754
+ const store = {
755
+ withExclusive: exclusive,
756
+ async get(key) {
757
+ return storage(key, async (item) => {
758
+ if (!keyring || !persistent) return memory.get(item) ?? null;
759
+ const value = await keyring.read(item);
760
+ if (value !== null && typeof value !== "string") throw refused2();
761
+ return value;
762
+ });
763
+ },
764
+ async set(key, text) {
765
+ if (typeof text !== "string" || Buffer.byteLength(text, "utf8") > MAX_VALUE_BYTES) throw refused2();
766
+ await storage(key, async (item) => {
767
+ if (!keyring || !persistent) {
768
+ memory.set(item, text);
769
+ return;
770
+ }
771
+ await keyring.write(item, text);
772
+ });
773
+ },
774
+ async delete(key) {
775
+ await storage(key, async (item) => {
776
+ if (!keyring || !persistent) {
777
+ memory.delete(item);
778
+ return;
779
+ }
780
+ await keyring.remove(item);
781
+ });
782
+ }
783
+ };
784
+ const dpopSigner = {
785
+ jkt,
786
+ async createProof(args) {
787
+ current();
788
+ if (!args || typeof args.method !== "string" || typeof args.url !== "string" || args.url.length > 8192 || args.accessToken !== void 0 && (typeof args.accessToken !== "string" || args.accessToken.length > 16384 || !/^[\x21-\x7e]+$/.test(args.accessToken)) || args.nonce !== void 0 && (typeof args.nonce !== "string" || args.nonce.length > 4096 || /[\r\n]/.test(args.nonce))) throw refused2();
789
+ const method = args.method.toUpperCase();
790
+ let url;
791
+ try {
792
+ url = new URL(args.url);
793
+ } catch {
794
+ throw refused2();
795
+ }
796
+ if (!/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)$/.test(method) || url.username || url.password || url.protocol !== "https:") throw refused2();
797
+ const header = {
798
+ alg: "ES256",
799
+ typ: "dpop+jwt",
800
+ jwk: publicJwk
801
+ };
802
+ const claims = {
803
+ jti: randomUUID2(),
804
+ htm: method,
805
+ htu: normalizeDpopHtu(args.url),
806
+ iat: Math.floor(Date.now() / 1e3),
807
+ ...args.accessToken ? {
808
+ ath: createHash2("sha256").update(args.accessToken).digest("base64url")
809
+ } : {},
810
+ ...args.nonce ? {
811
+ nonce: args.nonce
812
+ } : {}
813
+ };
814
+ const a = Buffer.from(JSON.stringify(header)).toString("base64url"), b = Buffer.from(JSON.stringify(claims)).toString("base64url");
815
+ const signature = sign("sha256", Buffer.from(`${a}.${b}`), {
816
+ key: privateKey,
817
+ dsaEncoding: "ieee-p1363"
818
+ });
819
+ if (signature.length !== 64) throw refused2();
820
+ return `${a}.${b}.${signature.toString("base64url")}`;
821
+ }
822
+ };
823
+ return {
824
+ store,
825
+ dpopSigner,
826
+ custody,
827
+ async close(input = {}) {
828
+ if (closed) return;
829
+ if (closing || locks || input.deleteCreatedKey && !custody.createdKey) throw refused2();
830
+ closing = true;
831
+ try {
832
+ if (input.deleteCreatedKey && keyring && persistent) await keyring.remove("dpop-key");
833
+ memory.clear();
834
+ closed = true;
835
+ } catch {
836
+ throw refused2();
837
+ } finally {
838
+ closing = false;
839
+ }
840
+ }
841
+ };
842
+ }
843
+ __name(openLinuxAccountHost, "openLinuxAccountHost");
844
+ function parsePrivateJwk(text) {
845
+ if (Buffer.byteLength(text, "utf8") > MAX_KEY_BYTES) throw refused2();
846
+ let jwk;
847
+ try {
848
+ jwk = JSON.parse(text);
849
+ } catch {
850
+ throw refused2();
851
+ }
852
+ if (jwk.kty !== "EC" || jwk.crv !== "P-256" || typeof jwk.x !== "string" || typeof jwk.y !== "string" || typeof jwk.d !== "string") throw refused2();
853
+ try {
854
+ const privateKey = createPrivateKey({
855
+ key: jwk,
856
+ format: "jwk"
857
+ });
858
+ return {
859
+ privateKey,
860
+ publicJwk: {
861
+ kty: "EC",
862
+ crv: "P-256",
863
+ x: jwk.x,
864
+ y: jwk.y
865
+ }
866
+ };
867
+ } catch {
868
+ throw refused2();
869
+ }
870
+ }
871
+ __name(parsePrivateJwk, "parsePrivateJwk");
872
+ var Keyring = class Keyring2 {
873
+ static {
874
+ __name(this, "Keyring");
875
+ }
876
+ run;
877
+ identity;
878
+ clientId;
879
+ constructor(run, identity, clientId) {
880
+ this.run = run;
881
+ this.identity = identity;
882
+ this.clientId = clientId;
883
+ }
884
+ attributes(item) {
885
+ return [
886
+ "xeno-account",
887
+ this.identity,
888
+ "item",
889
+ item
890
+ ];
891
+ }
892
+ /** `null` = no such item; throws when the keyring itself did not answer. */
893
+ async read(item) {
894
+ const result = await this.run([
895
+ "lookup",
896
+ ...this.attributes(item)
897
+ ]);
898
+ if (result.code === 1 && !result.stdout && !result.stderr.trim()) return null;
899
+ if (result.code !== 0) throw refused2();
900
+ const raw = result.stdout.replace(/\n$/, "");
901
+ if (!raw.startsWith(VALUE_PREFIX)) throw refused2();
902
+ const bytes = Buffer.from(raw.slice(VALUE_PREFIX.length), "base64");
903
+ try {
904
+ return new TextDecoder("utf-8", {
905
+ fatal: true
906
+ }).decode(bytes);
907
+ } catch {
908
+ throw refused2();
909
+ }
910
+ }
911
+ async write(item, value) {
912
+ const encoded = VALUE_PREFIX + Buffer.from(value, "utf8").toString("base64");
913
+ const result = await this.run([
914
+ "store",
915
+ `--label=XENO account ${this.clientId} (${item})`,
916
+ ...this.attributes(item)
917
+ ], encoded);
918
+ if (result.code !== 0 || await this.read(item) !== value) throw refused2();
919
+ }
920
+ async remove(item) {
921
+ await this.run([
922
+ "clear",
923
+ ...this.attributes(item)
924
+ ]);
925
+ if (await this.read(item) !== null) throw refused2();
926
+ }
927
+ /** Proves the keyring stores, returns and clears a value before anything is committed to it. */
928
+ async works() {
929
+ const probe = `probe-${randomUUID2()}`;
930
+ try {
931
+ await this.write("probe", probe);
932
+ await this.remove("probe");
933
+ return true;
934
+ } catch {
935
+ try {
936
+ await this.run([
937
+ "clear",
938
+ ...this.attributes("probe")
939
+ ]);
940
+ } catch {
941
+ }
942
+ return false;
943
+ }
944
+ }
945
+ };
946
+ function findSecretTool() {
947
+ for (const directory of (process.env.PATH ?? "").split(delimiter)) {
948
+ if (!directory || !isAbsolute(directory)) continue;
949
+ const candidate = join2(directory, "secret-tool");
950
+ try {
951
+ if (statSync(candidate).isFile()) return candidate;
952
+ } catch {
953
+ }
954
+ }
955
+ return null;
956
+ }
957
+ __name(findSecretTool, "findSecretTool");
958
+ function secretToolRunner(executable, timeoutMs) {
959
+ const allowed = [
960
+ "PATH",
961
+ "HOME",
962
+ "USER",
963
+ "LOGNAME",
964
+ "DBUS_SESSION_BUS_ADDRESS",
965
+ "XDG_RUNTIME_DIR",
966
+ "DISPLAY",
967
+ "WAYLAND_DISPLAY",
968
+ "XAUTHORITY"
969
+ ];
970
+ const env = {
971
+ LC_ALL: "C"
972
+ };
973
+ for (const name of allowed) {
974
+ const value = process.env[name];
975
+ if (value) env[name] = value;
976
+ }
977
+ return (args, input) => new Promise((resolve, reject) => {
978
+ const child = spawn2(executable, args, {
979
+ stdio: [
980
+ "pipe",
981
+ "pipe",
982
+ "pipe"
983
+ ],
984
+ env,
985
+ windowsHide: true
986
+ });
987
+ let stdout = "", stderr = "", settled = false;
988
+ const finish = /* @__PURE__ */ __name((fn) => {
989
+ if (!settled) {
990
+ settled = true;
991
+ clearTimeout(timer);
992
+ fn();
993
+ }
994
+ }, "finish");
995
+ const timer = setTimeout(() => {
996
+ child.kill("SIGKILL");
997
+ finish(() => reject(refused2()));
998
+ }, timeoutMs);
999
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
1000
+ stdout += chunk;
1001
+ if (stdout.length > 16384) {
1002
+ child.kill("SIGKILL");
1003
+ finish(() => reject(refused2()));
1004
+ }
1005
+ });
1006
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
1007
+ stderr += chunk;
1008
+ if (stderr.length > 16384) stderr = stderr.slice(-16384);
1009
+ });
1010
+ child.once("error", () => finish(() => reject(refused2())));
1011
+ child.once("close", (code) => finish(() => resolve({
1012
+ code,
1013
+ stdout,
1014
+ stderr
1015
+ })));
1016
+ child.stdin.on("error", () => {
1017
+ });
1018
+ child.stdin.end(input ?? "");
1019
+ });
1020
+ }
1021
+ __name(secretToolRunner, "secretToolRunner");
1022
+ function runtimeLockDirectory() {
1023
+ const uid = typeof process.getuid === "function" ? process.getuid() : -1;
1024
+ const runtime = process.env.XDG_RUNTIME_DIR;
1025
+ if (runtime && isAbsolute(runtime)) return join2(runtime, "xeno", "account");
1026
+ return join2(tmpdir(), `xeno-account-${uid}`);
1027
+ }
1028
+ __name(runtimeLockDirectory, "runtimeLockDirectory");
1029
+ function privateDirectory(path) {
1030
+ mkdirSync(path, {
1031
+ recursive: true,
1032
+ mode: 448
1033
+ });
1034
+ const stat = lstatSync(path);
1035
+ const uid = typeof process.getuid === "function" ? process.getuid() : void 0;
1036
+ if (!stat.isDirectory() || stat.isSymbolicLink() || uid !== void 0 && stat.uid !== uid || process.platform !== "win32" && (stat.mode & 63) !== 0) throw refused2();
1037
+ }
1038
+ __name(privateDirectory, "privateDirectory");
1039
+ function readBootId() {
1040
+ try {
1041
+ return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() || void 0;
1042
+ } catch {
1043
+ return void 0;
1044
+ }
1045
+ }
1046
+ __name(readBootId, "readBootId");
1047
+ function readStartTime(pid) {
1048
+ try {
1049
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
1050
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
1051
+ } catch {
1052
+ return void 0;
1053
+ }
1054
+ }
1055
+ __name(readStartTime, "readStartTime");
1056
+ var ProcessLock = class ProcessLock2 {
1057
+ static {
1058
+ __name(this, "ProcessLock");
1059
+ }
1060
+ directory;
1061
+ path;
1062
+ token = null;
1063
+ constructor(directory, identity) {
1064
+ this.directory = directory;
1065
+ this.path = join2(directory, `${identity}.lock`);
1066
+ }
1067
+ async acquire(waitMs) {
1068
+ if (this.token) throw refused2();
1069
+ privateDirectory(this.directory);
1070
+ const deadline = Date.now() + waitMs;
1071
+ const token = randomUUID2();
1072
+ const record = {
1073
+ v: 1,
1074
+ token,
1075
+ pid: process.pid,
1076
+ host: hostname(),
1077
+ boot: readBootId(),
1078
+ start: readStartTime(process.pid)
1079
+ };
1080
+ for (; ; ) {
1081
+ try {
1082
+ const fd = openSync(this.path, "wx", 384);
1083
+ try {
1084
+ writeSync(fd, JSON.stringify(record));
1085
+ fsyncSync(fd);
1086
+ } finally {
1087
+ closeSync(fd);
1088
+ }
1089
+ this.token = token;
1090
+ return;
1091
+ } catch (error) {
1092
+ if (error.code !== "EEXIST") throw refused2();
1093
+ }
1094
+ this.breakIfGone();
1095
+ if (Date.now() >= deadline) throw refused2();
1096
+ await new Promise((resolve) => setTimeout(resolve, 25));
1097
+ }
1098
+ }
1099
+ /** False when this process no longer held the lock it took, so its transaction was not exclusive. */
1100
+ release() {
1101
+ const token = this.token;
1102
+ this.token = null;
1103
+ if (!token) return false;
1104
+ const holder = this.readHolder(this.path);
1105
+ if (holder?.token !== token) return false;
1106
+ try {
1107
+ unlinkSync(this.path);
1108
+ return true;
1109
+ } catch {
1110
+ return false;
1111
+ }
1112
+ }
1113
+ readHolder(path) {
1114
+ try {
1115
+ const value = JSON.parse(readFileSync(path, "utf8"));
1116
+ return value && value.v === 1 && typeof value.token === "string" && Number.isSafeInteger(value.pid) && typeof value.host === "string" ? value : null;
1117
+ } catch (error) {
1118
+ return error.code === "ENOENT" ? void 0 : null;
1119
+ }
1120
+ }
1121
+ gone(holder) {
1122
+ if (holder === null) {
1123
+ try {
1124
+ return Date.now() - statSync(this.path).mtimeMs > 3e4;
1125
+ } catch {
1126
+ return false;
1127
+ }
1128
+ }
1129
+ if (holder.host !== hostname()) return false;
1130
+ const boot = readBootId();
1131
+ if (boot && holder.boot && boot !== holder.boot) return true;
1132
+ try {
1133
+ process.kill(holder.pid, 0);
1134
+ } catch (error) {
1135
+ return error.code === "ESRCH";
1136
+ }
1137
+ const start = readStartTime(holder.pid);
1138
+ return Boolean(start && holder.start && start !== holder.start);
1139
+ }
1140
+ breakIfGone() {
1141
+ const holder = this.readHolder(this.path);
1142
+ if (holder === void 0 || !this.gone(holder)) return;
1143
+ const moved = `${this.path}.stale-${randomUUID2()}`;
1144
+ try {
1145
+ renameSync(this.path, moved);
1146
+ } catch {
1147
+ return;
1148
+ }
1149
+ const removed = this.readHolder(moved);
1150
+ if (holder !== null && removed?.token !== holder.token) {
1151
+ try {
1152
+ linkSync(moved, this.path);
1153
+ } catch {
1154
+ }
1155
+ }
1156
+ try {
1157
+ unlinkSync(moved);
1158
+ } catch {
1159
+ }
1160
+ }
1161
+ };
1162
+
591
1163
  // src/node.ts
592
1164
  function createNodeDpopSigner(input) {
593
1165
  const parsed = typeof input === "string" ? JSON.parse(input) : input;
@@ -639,6 +1211,7 @@ function createNodeDpopSigner(input) {
639
1211
  }
640
1212
  __name(createNodeDpopSigner, "createNodeDpopSigner");
641
1213
  export {
1214
+ createLinuxAccountHost,
642
1215
  createNodeDpopSigner,
643
1216
  createWindowsAccountHost
644
1217
  };