dsh-auth-remote 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/CHANGELOG.zh-CN.md +16 -0
  3. package/CONTRIBUTING.md +23 -0
  4. package/CONTRIBUTING.zh-CN.md +23 -0
  5. package/LICENSE +21 -0
  6. package/README.md +65 -0
  7. package/README.zh-CN.md +65 -0
  8. package/cordis.patch.yml +45 -0
  9. package/dist/cli.js +1858 -0
  10. package/dist/cli.js.map +7 -0
  11. package/dist/client.js +3076 -0
  12. package/dist/client.js.map +7 -0
  13. package/dist/index.js +2473 -0
  14. package/dist/index.js.map +7 -0
  15. package/dist/login.css +230 -0
  16. package/dist/login.css.map +7 -0
  17. package/dist/login.js +2865 -0
  18. package/dist/login.js.map +7 -0
  19. package/dist/types/adapters/dsh/browser-auth.d.ts +8 -0
  20. package/dist/types/adapters/dsh/browser-auth.d.ts.map +1 -0
  21. package/dist/types/adapters/dsh/browser-capability.d.ts +8 -0
  22. package/dist/types/adapters/dsh/browser-capability.d.ts.map +1 -0
  23. package/dist/types/adapters/dsh/compatibility.d.ts +7 -0
  24. package/dist/types/adapters/dsh/compatibility.d.ts.map +1 -0
  25. package/dist/types/adapters/dsh/readiness.d.ts +22 -0
  26. package/dist/types/adapters/dsh/readiness.d.ts.map +1 -0
  27. package/dist/types/adapters/dsh/startup-urls.d.ts +4 -0
  28. package/dist/types/adapters/dsh/startup-urls.d.ts.map +1 -0
  29. package/dist/types/adapters/dsh/webserver.d.ts +36 -0
  30. package/dist/types/adapters/dsh/webserver.d.ts.map +1 -0
  31. package/dist/types/auth/password.d.ts +12 -0
  32. package/dist/types/auth/password.d.ts.map +1 -0
  33. package/dist/types/auth/service.d.ts +90 -0
  34. package/dist/types/auth/service.d.ts.map +1 -0
  35. package/dist/types/auth/sessions.d.ts +8 -0
  36. package/dist/types/auth/sessions.d.ts.map +1 -0
  37. package/dist/types/auth/totp.d.ts +10 -0
  38. package/dist/types/auth/totp.d.ts.map +1 -0
  39. package/dist/types/cli/index.d.ts +3 -0
  40. package/dist/types/cli/index.d.ts.map +1 -0
  41. package/dist/types/cli/ipc-client.d.ts +18 -0
  42. package/dist/types/cli/ipc-client.d.ts.map +1 -0
  43. package/dist/types/cli/language.d.ts +14 -0
  44. package/dist/types/cli/language.d.ts.map +1 -0
  45. package/dist/types/cli/profile.d.ts +10 -0
  46. package/dist/types/cli/profile.d.ts.map +1 -0
  47. package/dist/types/cli/prompt.d.ts +20 -0
  48. package/dist/types/cli/prompt.d.ts.map +1 -0
  49. package/dist/types/config.d.ts +27 -0
  50. package/dist/types/config.d.ts.map +1 -0
  51. package/dist/types/http/admin-socket.d.ts +18 -0
  52. package/dist/types/http/admin-socket.d.ts.map +1 -0
  53. package/dist/types/http/connections.d.ts +21 -0
  54. package/dist/types/http/connections.d.ts.map +1 -0
  55. package/dist/types/http/gate.d.ts +24 -0
  56. package/dist/types/http/gate.d.ts.map +1 -0
  57. package/dist/types/http/origin-policy.d.ts +35 -0
  58. package/dist/types/http/origin-policy.d.ts.map +1 -0
  59. package/dist/types/http/origin.d.ts +5 -0
  60. package/dist/types/http/origin.d.ts.map +1 -0
  61. package/dist/types/http/request-context.d.ts +5 -0
  62. package/dist/types/http/request-context.d.ts.map +1 -0
  63. package/dist/types/http/routes.d.ts +15 -0
  64. package/dist/types/http/routes.d.ts.map +1 -0
  65. package/dist/types/index.d.ts +33 -0
  66. package/dist/types/index.d.ts.map +1 -0
  67. package/dist/types/shared/admin-contract.d.ts +40 -0
  68. package/dist/types/shared/admin-contract.d.ts.map +1 -0
  69. package/dist/types/shared/auth-contract.d.ts +33 -0
  70. package/dist/types/shared/auth-contract.d.ts.map +1 -0
  71. package/dist/types/shared/i18n.d.ts +323 -0
  72. package/dist/types/shared/i18n.d.ts.map +1 -0
  73. package/dist/types/shared/locales/en.d.ts +151 -0
  74. package/dist/types/shared/locales/en.d.ts.map +1 -0
  75. package/dist/types/shared/locales/zh.d.ts +150 -0
  76. package/dist/types/shared/locales/zh.d.ts.map +1 -0
  77. package/dist/types/storage/lock.d.ts +17 -0
  78. package/dist/types/storage/lock.d.ts.map +1 -0
  79. package/dist/types/storage/state.d.ts +34 -0
  80. package/dist/types/storage/state.d.ts.map +1 -0
  81. package/dist/types/storage/store.d.ts +30 -0
  82. package/dist/types/storage/store.d.ts.map +1 -0
  83. package/docs/deployment.md +89 -0
  84. package/docs/deployment.zh-CN.md +89 -0
  85. package/docs/development.md +43 -0
  86. package/docs/development.zh-CN.md +43 -0
  87. package/docs/releasing.md +44 -0
  88. package/docs/releasing.zh-CN.md +44 -0
  89. package/docs/reverse-proxy.md +27 -0
  90. package/docs/reverse-proxy.zh-CN.md +27 -0
  91. package/examples/nginx.conf +27 -0
  92. package/examples/traefik-dsh.yml +20 -0
  93. package/examples/web-profile-auth-remote.patch.yml +14 -0
  94. package/package.json +112 -0
package/dist/cli.js ADDED
@@ -0,0 +1,1858 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/index.ts
4
+ import { readFileSync } from "node:fs";
5
+
6
+ // src/auth/service.ts
7
+ import { randomBytes as randomBytes4 } from "node:crypto";
8
+
9
+ // src/storage/store.ts
10
+ import { randomUUID as randomUUID2 } from "node:crypto";
11
+ import { constants as constants2 } from "node:fs";
12
+ import { lstat as lstat2, open as open2, readFile as readFile2, rename, unlink as unlink2 } from "node:fs/promises";
13
+ import { join as join2 } from "node:path";
14
+
15
+ // src/storage/lock.ts
16
+ import { randomUUID } from "node:crypto";
17
+ import { constants } from "node:fs";
18
+ import { lstat, mkdir, open, readFile, rmdir, unlink } from "node:fs/promises";
19
+ import { join } from "node:path";
20
+ var STATE_DIR = "auth-remote";
21
+ var STATE_FILE = "auth-state.json";
22
+ var LOCK_FILE = "auth-state.lock";
23
+ function errno(error, code) {
24
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
25
+ }
26
+ async function processStartTicks(pid) {
27
+ let raw;
28
+ try {
29
+ raw = await readFile(`/proc/${pid}/stat`, "utf8");
30
+ } catch (error) {
31
+ if (errno(error, "ENOENT")) return null;
32
+ throw error;
33
+ }
34
+ const tail = raw.slice(raw.lastIndexOf(")") + 1).trim().split(/\s+/u);
35
+ const ticks = tail[19];
36
+ if (!ticks || !/^\d+$/u.test(ticks)) throw new Error("auth-remote: cannot verify lock owner");
37
+ return ticks;
38
+ }
39
+ async function localOwner() {
40
+ const [bootId, startTicks] = await Promise.all([
41
+ readFile("/proc/sys/kernel/random/boot_id", "utf8"),
42
+ processStartTicks(process.pid)
43
+ ]);
44
+ if (!startTicks) throw new Error("auth-remote: cannot verify own process identity");
45
+ return { pid: process.pid, bootId: bootId.trim(), startTicks, nonce: randomUUID() };
46
+ }
47
+ function parseOwner(raw) {
48
+ let value;
49
+ try {
50
+ value = JSON.parse(raw);
51
+ } catch {
52
+ throw new Error("auth-remote: lock owner is unreadable; manual recovery required");
53
+ }
54
+ if (typeof value !== "object" || value === null || Array.isArray(value))
55
+ throw new Error("auth-remote: lock owner is invalid; manual recovery required");
56
+ const owner = value;
57
+ if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0 || typeof owner.bootId !== "string" || !/^[0-9a-f-]{36}$/u.test(owner.bootId) || typeof owner.startTicks !== "string" || !/^\d+$/u.test(owner.startTicks) || typeof owner.nonce !== "string" || !/^[0-9a-f-]{36}$/u.test(owner.nonce))
58
+ throw new Error("auth-remote: lock owner is invalid; manual recovery required");
59
+ return owner;
60
+ }
61
+ async function isDead(owner, currentBootId) {
62
+ if (owner.bootId !== currentBootId) return true;
63
+ const ticks = await processStartTicks(owner.pid);
64
+ return ticks === null || ticks !== owner.startTicks;
65
+ }
66
+ async function assertPrivate(path, kind) {
67
+ const info = await lstat(path);
68
+ if ((kind === "directory" ? !info.isDirectory() : !info.isFile()) || info.uid !== process.getuid?.() || (info.mode & 511) !== (kind === "directory" ? 448 : 384))
69
+ throw new Error(`auth-remote: unsafe ${kind} permissions or owner: ${path}`);
70
+ }
71
+ async function ensureStateDirectory(profileDir) {
72
+ if (process.platform !== "linux") throw new Error("auth-remote: storage requires Linux /proc");
73
+ const dir = join(profileDir, STATE_DIR);
74
+ let created = false;
75
+ try {
76
+ await mkdir(dir, { mode: 448 });
77
+ created = true;
78
+ } catch (error) {
79
+ if (!errno(error, "EEXIST")) throw error;
80
+ }
81
+ await assertPrivate(dir, "directory");
82
+ if (created) {
83
+ const parent = await open(profileDir, constants.O_RDONLY | constants.O_DIRECTORY);
84
+ try {
85
+ await parent.sync();
86
+ } finally {
87
+ await parent.close();
88
+ }
89
+ }
90
+ return dir;
91
+ }
92
+ var StateLock = class _StateLock {
93
+ constructor(dir, path, owner) {
94
+ this.dir = dir;
95
+ this.path = path;
96
+ this.owner = owner;
97
+ }
98
+ dir;
99
+ path;
100
+ owner;
101
+ released = false;
102
+ static async acquire(profileDir) {
103
+ const dir = await ensureStateDirectory(profileDir);
104
+ const path = join(dir, LOCK_FILE);
105
+ const owner = await localOwner();
106
+ for (let attempt = 0; attempt < 2; attempt++) {
107
+ try {
108
+ const file = await open(
109
+ path,
110
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
111
+ 384
112
+ );
113
+ try {
114
+ await file.writeFile(JSON.stringify(owner));
115
+ await file.sync();
116
+ } catch (error) {
117
+ await file.close();
118
+ await unlink(path).catch(() => void 0);
119
+ throw error;
120
+ }
121
+ await file.close();
122
+ return new _StateLock(dir, path, owner);
123
+ } catch (error) {
124
+ if (!errno(error, "EEXIST")) throw error;
125
+ if (attempt === 1) throw new Error("auth-remote: state lock is held or contested");
126
+ await this.recoverStale(dir, path, owner.bootId);
127
+ }
128
+ }
129
+ throw new Error("auth-remote: state lock acquisition failed");
130
+ }
131
+ static async recoverStale(dir, path, currentBootId) {
132
+ const recovery = `${path}.recovery`;
133
+ try {
134
+ await mkdir(recovery, { mode: 448 });
135
+ } catch (error) {
136
+ if (errno(error, "EEXIST"))
137
+ throw new Error(
138
+ "auth-remote: lock recovery is already active or abandoned; manual review required"
139
+ );
140
+ throw error;
141
+ }
142
+ try {
143
+ let info;
144
+ try {
145
+ info = await lstat(path);
146
+ } catch (error) {
147
+ if (errno(error, "ENOENT")) return;
148
+ throw error;
149
+ }
150
+ await assertPrivate(path, "file");
151
+ const old = parseOwner(await readFile(path, "utf8"));
152
+ if (!await isDead(old, currentBootId))
153
+ throw new Error(`auth-remote: state lock held by live process ${old.pid}`);
154
+ const latest = await lstat(path);
155
+ if (latest.ino !== info.ino || latest.dev !== info.dev)
156
+ throw new Error("auth-remote: state lock changed during recovery");
157
+ await unlink(path);
158
+ const parent = await open(dir, constants.O_RDONLY | constants.O_DIRECTORY);
159
+ try {
160
+ await parent.sync();
161
+ } finally {
162
+ await parent.close();
163
+ }
164
+ } finally {
165
+ await rmdir(recovery);
166
+ }
167
+ }
168
+ async release() {
169
+ if (this.released) return;
170
+ const current = parseOwner(await readFile(this.path, "utf8"));
171
+ if (current.nonce !== this.owner.nonce)
172
+ throw new Error("auth-remote: state lock ownership changed before release");
173
+ await unlink(this.path);
174
+ this.released = true;
175
+ }
176
+ };
177
+ async function assertPrivateStateFile(path) {
178
+ await assertPrivate(path, "file");
179
+ }
180
+
181
+ // src/storage/state.ts
182
+ var STATE_SCHEMA_VERSION = 1;
183
+ function emptyState() {
184
+ return { schemaVersion: STATE_SCHEMA_VERSION, revision: 0, account: null, sessions: {} };
185
+ }
186
+ function record(value, keys, label) {
187
+ if (typeof value !== "object" || value === null || Array.isArray(value))
188
+ throw new Error(`auth-remote: invalid ${label}`);
189
+ const entries = Object.keys(value);
190
+ if (entries.length !== keys.length || entries.some((key) => !keys.includes(key)))
191
+ throw new Error(`auth-remote: invalid ${label} fields`);
192
+ return value;
193
+ }
194
+ function integer(value, label, min = 0) {
195
+ if (!Number.isSafeInteger(value) || value < min)
196
+ throw new Error(`auth-remote: invalid ${label}`);
197
+ return value;
198
+ }
199
+ function nonempty(value, label) {
200
+ if (typeof value !== "string" || value.length === 0)
201
+ throw new Error(`auth-remote: invalid ${label}`);
202
+ return value;
203
+ }
204
+ function hex(value, bytes, label) {
205
+ if (typeof value !== "string" || !new RegExp(`^[a-f0-9]{${bytes * 2}}$`, "u").test(value))
206
+ throw new Error(`auth-remote: invalid ${label}`);
207
+ return value;
208
+ }
209
+ function digest(value, label) {
210
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/u.test(value))
211
+ throw new Error(`auth-remote: invalid ${label}`);
212
+ return value;
213
+ }
214
+ function validateState(value) {
215
+ const state = record(value, ["schemaVersion", "revision", "account", "sessions"], "state");
216
+ if (state.schemaVersion !== STATE_SCHEMA_VERSION)
217
+ throw new Error(`auth-remote: unsupported state schema version ${String(state.schemaVersion)}`);
218
+ const revision = integer(state.revision, "revision");
219
+ let account = null;
220
+ if (state.account !== null) {
221
+ const entry = record(
222
+ state.account,
223
+ ["id", "username", "password", "totp", "securityVersion"],
224
+ "account"
225
+ );
226
+ const password = record(entry.password, ["salt", "hash"], "password record");
227
+ let totp = null;
228
+ if (entry.totp !== null) {
229
+ const factor = record(
230
+ entry.totp,
231
+ ["secret", "lastUsedStep", "backupCodeHashes"],
232
+ "TOTP record"
233
+ );
234
+ if (!Array.isArray(factor.backupCodeHashes) || factor.backupCodeHashes.length > 10)
235
+ throw new Error("auth-remote: invalid backup code hashes");
236
+ if (typeof factor.secret !== "string" || !/^[A-Z2-7]{32}$/u.test(factor.secret))
237
+ throw new Error("auth-remote: invalid TOTP secret");
238
+ totp = {
239
+ secret: factor.secret,
240
+ lastUsedStep: factor.lastUsedStep === null ? null : integer(factor.lastUsedStep, "TOTP step"),
241
+ backupCodeHashes: factor.backupCodeHashes.map((hash) => digest(hash, "backup code hash"))
242
+ };
243
+ if (new Set(totp.backupCodeHashes).size !== totp.backupCodeHashes.length)
244
+ throw new Error("auth-remote: duplicate backup code hash");
245
+ }
246
+ const username = nonempty(entry.username, "username");
247
+ if ([...username].length > 64 || /[\u0000-\u001f\u007f]/u.test(username))
248
+ throw new Error("auth-remote: invalid username");
249
+ account = {
250
+ id: hex(entry.id, 16, "account id"),
251
+ username,
252
+ password: {
253
+ salt: hex(password.salt, 32, "password salt"),
254
+ hash: hex(password.hash, 64, "password hash")
255
+ },
256
+ totp,
257
+ securityVersion: integer(entry.securityVersion, "security version", 1)
258
+ };
259
+ }
260
+ const sessions = state.sessions;
261
+ if (typeof sessions !== "object" || sessions === null || Array.isArray(sessions))
262
+ throw new Error("auth-remote: invalid sessions");
263
+ const validatedSessions = /* @__PURE__ */ Object.create(null);
264
+ for (const [hash, value2] of Object.entries(sessions)) {
265
+ digest(hash, "session token hash");
266
+ const session = record(
267
+ value2,
268
+ ["accountId", "securityVersion", "createdAt", "expiresAt"],
269
+ "session"
270
+ );
271
+ const createdAt = integer(session.createdAt, "session creation");
272
+ const expiresAt = integer(session.expiresAt, "session expiry");
273
+ if (!account || session.accountId !== account.id || expiresAt <= createdAt)
274
+ throw new Error("auth-remote: invalid session account or lifetime");
275
+ validatedSessions[hash] = {
276
+ accountId: account.id,
277
+ securityVersion: integer(session.securityVersion, "session security version", 1),
278
+ createdAt,
279
+ expiresAt
280
+ };
281
+ }
282
+ return { schemaVersion: STATE_SCHEMA_VERSION, revision, account, sessions: validatedSessions };
283
+ }
284
+
285
+ // src/storage/store.ts
286
+ function errno2(error, code) {
287
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
288
+ }
289
+ var AuthStateStore = class _AuthStateStore {
290
+ constructor(lock, state, options) {
291
+ this.lock = lock;
292
+ this.options = options;
293
+ this.path = join2(lock.dir, STATE_FILE);
294
+ this.state = state;
295
+ }
296
+ lock;
297
+ options;
298
+ path;
299
+ state;
300
+ queue = Promise.resolve();
301
+ unavailableReason = null;
302
+ closed = false;
303
+ listeners = /* @__PURE__ */ new Set();
304
+ static async open(profileDir, options = {}) {
305
+ const lock = await StateLock.acquire(profileDir);
306
+ try {
307
+ const path = join2(lock.dir, STATE_FILE);
308
+ let state = emptyState();
309
+ try {
310
+ await assertPrivateStateFile(path);
311
+ const info = await lstat2(path);
312
+ if (info.size > 16 * 1024 * 1024)
313
+ throw new Error("auth-remote: state file exceeds the supported size");
314
+ state = validateState(JSON.parse(await readFile2(path, "utf8")));
315
+ } catch (error) {
316
+ if (!errno2(error, "ENOENT")) throw error;
317
+ }
318
+ return new _AuthStateStore(lock, state, options);
319
+ } catch (error) {
320
+ await lock.release();
321
+ throw error;
322
+ }
323
+ }
324
+ healthy() {
325
+ return !this.closed && this.unavailableReason === null;
326
+ }
327
+ current() {
328
+ if (!this.healthy()) throw this.unavailableReason ?? new Error("auth-remote: store is closed");
329
+ return structuredClone(this.state);
330
+ }
331
+ /** Notifications finish before transact reports success; a failed listener closes admission. */
332
+ subscribe(listener) {
333
+ if (!this.healthy()) throw this.unavailableReason ?? new Error("auth-remote: store is closed");
334
+ this.listeners.add(listener);
335
+ return () => this.listeners.delete(listener);
336
+ }
337
+ async transact(mutate) {
338
+ const run = async () => {
339
+ if (!this.healthy()) throw this.unavailableReason ?? new Error("auth-remote: store is closed");
340
+ const draft = structuredClone(this.state);
341
+ const result = await mutate(draft);
342
+ if (this.state.revision >= Number.MAX_SAFE_INTEGER)
343
+ throw new Error("auth-remote: state revision exhausted");
344
+ draft.revision = this.state.revision + 1;
345
+ const next = validateState(draft);
346
+ await this.persist(next);
347
+ return result;
348
+ };
349
+ const operation = this.queue.then(run);
350
+ this.queue = operation.then(
351
+ () => void 0,
352
+ () => void 0
353
+ );
354
+ return operation;
355
+ }
356
+ async persist(next) {
357
+ const temp = `${this.path}.tmp-${process.pid}-${randomUUID2()}`;
358
+ const bytes = Buffer.from(`${JSON.stringify(next)}
359
+ `, "utf8");
360
+ if (bytes.length > 16 * 1024 * 1024)
361
+ throw new Error("auth-remote: state file exceeds the supported size");
362
+ let renamed = false;
363
+ let file;
364
+ try {
365
+ file = await open2(
366
+ temp,
367
+ constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY | constants2.O_NOFOLLOW,
368
+ 384
369
+ );
370
+ await file.writeFile(bytes);
371
+ await this.options.onStage?.("afterTempWrite");
372
+ await file.sync();
373
+ await this.options.onStage?.("afterFileSync");
374
+ await file.close();
375
+ file = void 0;
376
+ await this.options.onStage?.("beforeRename");
377
+ await rename(temp, this.path);
378
+ renamed = true;
379
+ await this.options.onStage?.("afterRename");
380
+ const parent = await open2(this.lock.dir, constants2.O_RDONLY | constants2.O_DIRECTORY);
381
+ try {
382
+ await parent.sync();
383
+ } finally {
384
+ await parent.close();
385
+ }
386
+ await this.options.onStage?.("afterDirSync");
387
+ const previous = this.state;
388
+ this.state = next;
389
+ await this.options.onCommitted?.(structuredClone(previous), structuredClone(next));
390
+ for (const listener of this.listeners)
391
+ await listener(structuredClone(previous), structuredClone(next));
392
+ await this.options.onStage?.("beforeSuccess");
393
+ } catch (error) {
394
+ if (renamed) {
395
+ this.unavailableReason = new Error("auth-remote: state commit outcome is uncertain", {
396
+ cause: error
397
+ });
398
+ this.options.onUnavailable?.(this.unavailableReason);
399
+ }
400
+ throw error;
401
+ } finally {
402
+ await file?.close().catch(() => void 0);
403
+ if (!renamed) await unlink2(temp).catch(() => void 0);
404
+ }
405
+ }
406
+ async close() {
407
+ if (this.closed) return;
408
+ this.closed = true;
409
+ await this.queue;
410
+ await this.lock.release();
411
+ }
412
+ };
413
+
414
+ // src/auth/password.ts
415
+ import { randomBytes, scrypt as scryptCallback, timingSafeEqual } from "node:crypto";
416
+ var PASSWORD_MIN_CHARACTERS = 12;
417
+ var PASSWORD_MAX_CHARACTERS = 256;
418
+ var PasswordValidationError = class extends Error {
419
+ constructor() {
420
+ super("auth-remote: password must contain 12\u2013256 Unicode characters");
421
+ }
422
+ };
423
+ function validatePassword(password) {
424
+ if (typeof password !== "string" || [...password].length < PASSWORD_MIN_CHARACTERS || [...password].length > PASSWORD_MAX_CHARACTERS)
425
+ throw new PasswordValidationError();
426
+ }
427
+ async function derive(password, salt) {
428
+ return new Promise((resolve2, reject) => {
429
+ scryptCallback(
430
+ password,
431
+ Buffer.from(salt, "hex"),
432
+ 64,
433
+ { N: 16384, r: 8, p: 1, maxmem: 32 * 1024 * 1024 },
434
+ (error, key) => error ? reject(error) : resolve2(key)
435
+ );
436
+ });
437
+ }
438
+ async function hashPassword(password) {
439
+ validatePassword(password);
440
+ const salt = randomBytes(32).toString("hex");
441
+ return { salt, hash: (await derive(password, salt)).toString("hex") };
442
+ }
443
+ async function verifyPassword(password, record2) {
444
+ const derived = await derive(password, record2.salt);
445
+ return timingSafeEqual(derived, Buffer.from(record2.hash, "hex"));
446
+ }
447
+ var DUMMY_PASSWORD_RECORD = {
448
+ salt: "0".repeat(64),
449
+ hash: "0".repeat(128)
450
+ };
451
+
452
+ // src/auth/sessions.ts
453
+ import { createHash, randomBytes as randomBytes2 } from "node:crypto";
454
+ function sessionHash(token) {
455
+ return createHash("sha256").update(token).digest("hex");
456
+ }
457
+ function issueSession(draft, now, sessionHours) {
458
+ const account = draft.account;
459
+ if (!account) throw new Error("auth-remote: cannot issue a session without an account");
460
+ const expiresAt = now + sessionHours * 36e5;
461
+ if (!Number.isSafeInteger(expiresAt)) throw new Error("auth-remote: session expiry overflow");
462
+ const token = randomBytes2(32).toString("base64url");
463
+ draft.sessions[sessionHash(token)] = {
464
+ accountId: account.id,
465
+ securityVersion: account.securityVersion,
466
+ createdAt: now,
467
+ expiresAt
468
+ };
469
+ return { token, expiresAt };
470
+ }
471
+ function sessionFor(state, token, now, requireTotp) {
472
+ if (typeof token !== "string" || !/^[A-Za-z0-9_-]{43}$/u.test(token)) return null;
473
+ const session = state.sessions[sessionHash(token)];
474
+ const account = state.account;
475
+ if (!session || !account || session.accountId !== account.id || session.securityVersion !== account.securityVersion || session.expiresAt <= now || requireTotp && !account.totp)
476
+ return null;
477
+ return session;
478
+ }
479
+
480
+ // src/auth/totp.ts
481
+ import { createHash as createHash2, createHmac, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
482
+ var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
483
+ var TOTP_PERIOD_MS = 3e4;
484
+ function base32(bytes) {
485
+ let bits = 0;
486
+ let value = 0;
487
+ let output2 = "";
488
+ for (const byte of bytes) {
489
+ value = value << 8 | byte;
490
+ bits += 8;
491
+ while (bits >= 5) {
492
+ output2 += alphabet[value >>> bits - 5 & 31];
493
+ bits -= 5;
494
+ }
495
+ }
496
+ if (bits > 0) output2 += alphabet[value << 5 - bits & 31];
497
+ return output2;
498
+ }
499
+ function fromBase32(value) {
500
+ let bits = 0;
501
+ let accum = 0;
502
+ const output2 = [];
503
+ for (const char of value) {
504
+ const digit = alphabet.indexOf(char);
505
+ if (digit < 0) throw new Error("auth-remote: invalid TOTP secret");
506
+ accum = accum << 5 | digit;
507
+ bits += 5;
508
+ if (bits >= 8) {
509
+ output2.push(accum >>> bits - 8 & 255);
510
+ bits -= 8;
511
+ }
512
+ }
513
+ return Buffer.from(output2);
514
+ }
515
+ function generateTotpSecret() {
516
+ return base32(randomBytes3(20));
517
+ }
518
+ function totpCode(secret, step) {
519
+ if (!Number.isSafeInteger(step) || step < 0) throw new Error("auth-remote: invalid TOTP step");
520
+ const counter = Buffer.alloc(8);
521
+ counter.writeBigUInt64BE(BigInt(step));
522
+ const mac = createHmac("sha1", fromBase32(secret)).update(counter).digest();
523
+ const offset = mac[mac.length - 1] & 15;
524
+ const value = (mac.readUInt32BE(offset) & 2147483647) % 1e6;
525
+ return String(value).padStart(6, "0");
526
+ }
527
+ function matchedTotpStep(secret, code, timestamp, lastUsedStep) {
528
+ if (typeof code !== "string" || !/^\d{6}$/u.test(code)) return null;
529
+ const current = Math.floor(timestamp / TOTP_PERIOD_MS);
530
+ for (const step of [current - 1, current, current + 1]) {
531
+ if (step < 0 || lastUsedStep !== null && step <= lastUsedStep) continue;
532
+ if (timingSafeEqual2(Buffer.from(totpCode(secret, step)), Buffer.from(code))) return step;
533
+ }
534
+ return null;
535
+ }
536
+ function backupCodeHash(code) {
537
+ if (typeof code !== "string") return null;
538
+ const canonical = code.replaceAll("-", "").toUpperCase();
539
+ if (!/^[A-Z2-7]{20}$/u.test(canonical)) return null;
540
+ return createHash2("sha256").update(`auth-remote-backup:${canonical}`).digest("hex");
541
+ }
542
+ function generateBackupCodes() {
543
+ const codes = Array.from(
544
+ { length: 10 },
545
+ () => base32(randomBytes3(12)).match(/.{1,5}/gu).join("-")
546
+ );
547
+ return { codes, hashes: codes.map((code) => backupCodeHash(code)) };
548
+ }
549
+
550
+ // src/auth/service.ts
551
+ var AuthError = class extends Error {
552
+ constructor(code, retryAfter) {
553
+ super(`auth-remote: ${code}`);
554
+ this.code = code;
555
+ this.retryAfter = retryAfter;
556
+ }
557
+ code;
558
+ retryAfter;
559
+ };
560
+ var LOGIN_CHALLENGE_MS = 5 * 6e4;
561
+ var BINDING_CHALLENGE_MS = 10 * 6e4;
562
+ var RATE_WINDOW_MS = 6e4;
563
+ var MAX_ATTEMPTS = 10;
564
+ var MAX_CHALLENGES = 32;
565
+ function validatePolicy(policy, now) {
566
+ if (typeof policy.requireTotp !== "boolean" || !Number.isSafeInteger(policy.sessionHours) || policy.sessionHours < 1 || !Number.isSafeInteger(now + policy.sessionHours * 36e5))
567
+ throw new AuthError("invalid_input");
568
+ }
569
+ function validUsername(username) {
570
+ return typeof username === "string" && username.length > 0 && [...username].length <= 64 && !/[\u0000-\u001f\u007f]/u.test(username);
571
+ }
572
+ var AuthService = class {
573
+ constructor(store, policy, options = {}) {
574
+ this.store = store;
575
+ this.policy = policy;
576
+ this.now = options.now ?? Date.now;
577
+ validatePolicy(policy, this.now());
578
+ this.unsubscribe = store.subscribe((previous, current) => {
579
+ if (previous.account?.securityVersion !== current.account?.securityVersion) {
580
+ this.challenges.clear();
581
+ return;
582
+ }
583
+ for (const [id, challenge] of this.challenges) {
584
+ if (challenge.kind === "binding" && challenge.originSessionHash && previous.sessions[challenge.originSessionHash] && !current.sessions[challenge.originSessionHash])
585
+ this.challenges.delete(id);
586
+ }
587
+ });
588
+ }
589
+ store;
590
+ policy;
591
+ now;
592
+ challenges = /* @__PURE__ */ new Map();
593
+ attempts = [];
594
+ activeDerivations = 0;
595
+ policyChanging = false;
596
+ unsubscribe;
597
+ dispose() {
598
+ this.unsubscribe();
599
+ this.challenges.clear();
600
+ }
601
+ status() {
602
+ const state = this.store.current();
603
+ return {
604
+ initialized: state.account !== null,
605
+ totpEnabled: state.account?.totp !== null && state.account?.totp !== void 0,
606
+ activeSessions: Object.values(state.sessions).filter(
607
+ (session) => state.account && session.accountId === state.account.id && session.securityVersion === state.account.securityVersion && session.expiresAt > this.now() && (!this.policy.requireTotp || state.account.totp)
608
+ ).length
609
+ };
610
+ }
611
+ session(token) {
612
+ return sessionFor(this.store.current(), token, this.now(), this.policy.requireTotp);
613
+ }
614
+ policySnapshot() {
615
+ return { ...this.policy };
616
+ }
617
+ me(token) {
618
+ const state = this.store.current();
619
+ const session = sessionFor(state, token, this.now(), this.policy.requireTotp);
620
+ if (!session || !state.account) throw new AuthError("unauthorized");
621
+ return {
622
+ username: state.account.username,
623
+ totpEnabled: state.account.totp !== null,
624
+ expiresAt: session.expiresAt
625
+ };
626
+ }
627
+ bindingDetails(id) {
628
+ const challenge = this.challenges.get(id);
629
+ if (!challenge || challenge.kind !== "binding") throw new AuthError("invalid_challenge");
630
+ if (challenge.expiresAt <= this.now()) {
631
+ this.challenges.delete(id);
632
+ throw new AuthError("challenge_expired");
633
+ }
634
+ const state = this.store.current();
635
+ this.sameAccount(state, challenge.accountId, challenge.securityVersion);
636
+ if (challenge.originSessionHash) {
637
+ const session = state.sessions[challenge.originSessionHash];
638
+ if (!session || session.expiresAt <= this.now()) throw new AuthError("unauthorized");
639
+ }
640
+ return { secret: challenge.secret, expiresAt: challenge.expiresAt };
641
+ }
642
+ pendingChallenges() {
643
+ this.expireChallenges();
644
+ return this.challenges.size;
645
+ }
646
+ occupyAttempt() {
647
+ const now = this.now();
648
+ while (this.attempts.length > 0 && this.attempts[0] <= now - RATE_WINDOW_MS)
649
+ this.attempts.shift();
650
+ if (this.attempts.length >= MAX_ATTEMPTS)
651
+ throw new AuthError(
652
+ "rate_limited",
653
+ Math.ceil((this.attempts[0] + RATE_WINDOW_MS - now) / 1e3)
654
+ );
655
+ this.attempts.push(now);
656
+ }
657
+ async derive(run) {
658
+ if (this.activeDerivations >= 2) throw new AuthError("busy");
659
+ this.activeDerivations++;
660
+ try {
661
+ return await run();
662
+ } finally {
663
+ this.activeDerivations--;
664
+ }
665
+ }
666
+ expireChallenges() {
667
+ const now = this.now();
668
+ for (const [id, challenge] of this.challenges)
669
+ if (challenge.expiresAt <= now) this.challenges.delete(id);
670
+ }
671
+ createChallenge(kind, account, originSessionHash = null) {
672
+ this.expireChallenges();
673
+ if (this.challenges.size >= MAX_CHALLENGES) throw new AuthError("busy");
674
+ const id = randomBytes4(32).toString("base64url");
675
+ const expiresAt = this.now() + (kind === "mfa" ? LOGIN_CHALLENGE_MS : BINDING_CHALLENGE_MS);
676
+ const base = {
677
+ id,
678
+ accountId: account.id,
679
+ securityVersion: account.securityVersion,
680
+ expiresAt,
681
+ failures: 0,
682
+ busy: false
683
+ };
684
+ if (kind === "mfa") {
685
+ this.challenges.set(id, { ...base, kind });
686
+ return { kind, challenge: id, expiresAt };
687
+ }
688
+ const secret = generateTotpSecret();
689
+ this.challenges.set(id, { ...base, kind, secret, originSessionHash });
690
+ return { kind, challenge: id, secret, expiresAt };
691
+ }
692
+ claim(id, kind) {
693
+ const challenge = this.challenges.get(id);
694
+ if (!challenge || challenge.kind !== kind) throw new AuthError("invalid_challenge");
695
+ if (challenge.expiresAt <= this.now()) {
696
+ this.challenges.delete(id);
697
+ throw new AuthError("challenge_expired");
698
+ }
699
+ if (challenge.busy || challenge.failures >= 5) throw new AuthError("invalid_challenge");
700
+ challenge.busy = true;
701
+ return challenge;
702
+ }
703
+ failedChallenge(challenge) {
704
+ challenge.failures++;
705
+ if (challenge.failures >= 5) this.challenges.delete(challenge.id);
706
+ }
707
+ sameAccount(state, accountId, securityVersion) {
708
+ const account = state.account;
709
+ if (!account || account.id !== accountId || account.securityVersion !== securityVersion)
710
+ throw new AuthError("conflict");
711
+ return account;
712
+ }
713
+ requireSession(state, token) {
714
+ if (!sessionFor(state, token, this.now(), this.policy.requireTotp))
715
+ throw new AuthError("unauthorized");
716
+ return state.account;
717
+ }
718
+ verifyFactor(account, code) {
719
+ const factor = account.totp;
720
+ if (!factor) return true;
721
+ if (!code) return false;
722
+ const step = matchedTotpStep(factor.secret, code, this.now(), factor.lastUsedStep);
723
+ if (step !== null) {
724
+ factor.lastUsedStep = step;
725
+ return true;
726
+ }
727
+ const hash = backupCodeHash(code);
728
+ if (!hash) return false;
729
+ const index = factor.backupCodeHashes.indexOf(hash);
730
+ if (index < 0) return false;
731
+ factor.backupCodeHashes.splice(index, 1);
732
+ return true;
733
+ }
734
+ async initialize(username, password) {
735
+ if (!validUsername(username)) throw new AuthError("invalid_input");
736
+ validatePassword(password);
737
+ if (this.store.current().account) throw new AuthError("already_initialized");
738
+ const record2 = await this.derive(() => hashPassword(password));
739
+ await this.store.transact((draft) => {
740
+ if (draft.account) throw new AuthError("already_initialized");
741
+ draft.account = {
742
+ id: randomBytes4(16).toString("hex"),
743
+ username,
744
+ password: record2,
745
+ totp: null,
746
+ securityVersion: 1
747
+ };
748
+ });
749
+ }
750
+ async login(username, password) {
751
+ this.occupyAttempt();
752
+ if (!validUsername(username) || typeof password !== "string" || password.length > 1024)
753
+ throw new AuthError("invalid_credentials");
754
+ const snapshot = this.store.current();
755
+ const account = snapshot.account;
756
+ if (!account) throw new AuthError("uninitialized");
757
+ const match = await this.derive(
758
+ () => verifyPassword(
759
+ password,
760
+ username === account.username ? account.password : DUMMY_PASSWORD_RECORD
761
+ )
762
+ );
763
+ if (!match || username !== account.username) throw new AuthError("invalid_credentials");
764
+ const current = this.store.current();
765
+ const latest = this.sameAccount(current, account.id, account.securityVersion);
766
+ if (latest.totp) return this.createChallenge("mfa", latest);
767
+ if (this.policy.requireTotp) return this.createChallenge("binding", latest);
768
+ const issued = await this.store.transact((draft) => {
769
+ this.sameAccount(draft, account.id, account.securityVersion);
770
+ if (draft.account.totp || this.policy.requireTotp) throw new AuthError("conflict");
771
+ return issueSession(draft, this.now(), this.policy.sessionHours);
772
+ });
773
+ return { kind: "session", ...issued };
774
+ }
775
+ async verifyMfa(id, code) {
776
+ this.occupyAttempt();
777
+ const challenge = this.claim(id, "mfa");
778
+ try {
779
+ const issued = await this.store.transact((draft) => {
780
+ if (challenge.expiresAt <= this.now()) throw new AuthError("challenge_expired");
781
+ const account = this.sameAccount(draft, challenge.accountId, challenge.securityVersion);
782
+ if (!account.totp || !this.verifyFactor(account, code))
783
+ throw new AuthError("invalid_factor");
784
+ return issueSession(draft, this.now(), this.policy.sessionHours);
785
+ });
786
+ this.challenges.delete(id);
787
+ return issued;
788
+ } catch (error) {
789
+ if (error instanceof AuthError && error.code === "invalid_factor")
790
+ this.failedChallenge(challenge);
791
+ throw error;
792
+ } finally {
793
+ challenge.busy = false;
794
+ }
795
+ }
796
+ async startBinding(token, password, currentCode) {
797
+ this.occupyAttempt();
798
+ const snapshot = this.store.current();
799
+ const account = this.requireSession(snapshot, token);
800
+ if (typeof password !== "string" || password.length > 1024)
801
+ throw new AuthError("invalid_credentials");
802
+ const match = await this.derive(() => verifyPassword(password, account.password));
803
+ if (!match) throw new AuthError("invalid_credentials");
804
+ if (account.totp) {
805
+ await this.store.transact((draft) => {
806
+ this.requireSession(draft, token);
807
+ this.sameAccount(draft, account.id, account.securityVersion);
808
+ if (!this.verifyFactor(draft.account, currentCode)) throw new AuthError("invalid_factor");
809
+ });
810
+ } else {
811
+ const latest = this.store.current();
812
+ this.requireSession(latest, token);
813
+ this.sameAccount(latest, account.id, account.securityVersion);
814
+ }
815
+ return this.createChallenge("binding", account, sessionHash(token));
816
+ }
817
+ async confirmBinding(id, code) {
818
+ this.occupyAttempt();
819
+ const challenge = this.claim(id, "binding");
820
+ try {
821
+ const step = matchedTotpStep(challenge.secret, code, this.now(), null);
822
+ if (step === null) {
823
+ this.failedChallenge(challenge);
824
+ throw new AuthError("invalid_factor");
825
+ }
826
+ const backups = generateBackupCodes();
827
+ await this.store.transact((draft) => {
828
+ if (challenge.expiresAt <= this.now()) throw new AuthError("challenge_expired");
829
+ const account = this.sameAccount(draft, challenge.accountId, challenge.securityVersion);
830
+ const originSession = challenge.originSessionHash ? draft.sessions[challenge.originSessionHash] : null;
831
+ if (challenge.originSessionHash && (!originSession || originSession.expiresAt <= this.now()))
832
+ throw new AuthError("unauthorized");
833
+ account.totp = {
834
+ secret: challenge.secret,
835
+ lastUsedStep: step,
836
+ backupCodeHashes: backups.hashes
837
+ };
838
+ account.securityVersion++;
839
+ draft.sessions = {};
840
+ });
841
+ this.challenges.clear();
842
+ return { backupCodes: backups.codes };
843
+ } finally {
844
+ challenge.busy = false;
845
+ }
846
+ }
847
+ async changePassword(token, currentPassword, currentCode, newPassword) {
848
+ this.occupyAttempt();
849
+ validatePassword(newPassword);
850
+ if (typeof currentPassword !== "string" || currentPassword.length > 1024)
851
+ throw new AuthError("invalid_credentials");
852
+ const snapshot = this.store.current();
853
+ const account = this.requireSession(snapshot, token);
854
+ const match = await this.derive(() => verifyPassword(currentPassword, account.password));
855
+ if (!match) throw new AuthError("invalid_credentials");
856
+ const replacement = await this.derive(() => hashPassword(newPassword));
857
+ await this.store.transact((draft) => {
858
+ this.requireSession(draft, token);
859
+ const current = this.sameAccount(draft, account.id, account.securityVersion);
860
+ if (!this.verifyFactor(current, currentCode)) throw new AuthError("invalid_factor");
861
+ current.password = replacement;
862
+ current.securityVersion++;
863
+ draft.sessions = {};
864
+ });
865
+ }
866
+ async disableTotp(token, password, currentCode) {
867
+ this.occupyAttempt();
868
+ if (this.policy.requireTotp) throw new AuthError("totp_required");
869
+ if (typeof password !== "string" || password.length > 1024)
870
+ throw new AuthError("invalid_credentials");
871
+ const snapshot = this.store.current();
872
+ const account = this.requireSession(snapshot, token);
873
+ const match = await this.derive(() => verifyPassword(password, account.password));
874
+ if (!match) throw new AuthError("invalid_credentials");
875
+ await this.store.transact((draft) => {
876
+ this.requireSession(draft, token);
877
+ const current = this.sameAccount(draft, account.id, account.securityVersion);
878
+ if (!current.totp || !this.verifyFactor(current, currentCode))
879
+ throw new AuthError("invalid_factor");
880
+ current.totp = null;
881
+ current.securityVersion++;
882
+ draft.sessions = {};
883
+ });
884
+ }
885
+ async revokeWithCredentials(token, password, currentCode) {
886
+ this.occupyAttempt();
887
+ if (typeof password !== "string" || password.length > 1024)
888
+ throw new AuthError("invalid_credentials");
889
+ const snapshot = this.store.current();
890
+ const account = this.requireSession(snapshot, token);
891
+ const match = await this.derive(() => verifyPassword(password, account.password));
892
+ if (!match) throw new AuthError("invalid_credentials");
893
+ await this.store.transact((draft) => {
894
+ this.requireSession(draft, token);
895
+ const current = this.sameAccount(draft, account.id, account.securityVersion);
896
+ if (!this.verifyFactor(current, currentCode)) throw new AuthError("invalid_factor");
897
+ current.securityVersion++;
898
+ draft.sessions = {};
899
+ });
900
+ }
901
+ async logout(token) {
902
+ if (typeof token !== "string" || !/^[A-Za-z0-9_-]{43}$/u.test(token)) return;
903
+ const hash = sessionHash(token);
904
+ if (!this.store.current().sessions[hash]) return;
905
+ await this.store.transact((draft) => {
906
+ delete draft.sessions[hash];
907
+ });
908
+ }
909
+ async resetPassword(newPassword) {
910
+ validatePassword(newPassword);
911
+ const replacement = await this.derive(() => hashPassword(newPassword));
912
+ await this.store.transact((draft) => {
913
+ if (!draft.account) throw new AuthError("uninitialized");
914
+ draft.account.password = replacement;
915
+ draft.account.securityVersion++;
916
+ draft.sessions = {};
917
+ });
918
+ }
919
+ async resetTotp() {
920
+ await this.store.transact((draft) => {
921
+ if (!draft.account) throw new AuthError("uninitialized");
922
+ draft.account.totp = null;
923
+ draft.account.securityVersion++;
924
+ draft.sessions = {};
925
+ });
926
+ }
927
+ async revokeAll() {
928
+ await this.store.transact((draft) => {
929
+ if (!draft.account) throw new AuthError("uninitialized");
930
+ draft.account.securityVersion++;
931
+ draft.sessions = {};
932
+ });
933
+ }
934
+ async applyPolicy(next) {
935
+ validatePolicy(next, this.now());
936
+ if (this.policyChanging) throw new AuthError("busy");
937
+ if (next.requireTotp === this.policy.requireTotp && next.sessionHours === this.policy.sessionHours)
938
+ return;
939
+ this.policyChanging = true;
940
+ const previous = this.policy;
941
+ this.policy = next;
942
+ try {
943
+ await this.store.transact((draft) => {
944
+ if (next.requireTotp && !previous.requireTotp && draft.account && !draft.account.totp) {
945
+ draft.account.securityVersion++;
946
+ draft.sessions = {};
947
+ }
948
+ if (next.sessionHours < previous.sessionHours) {
949
+ for (const session of Object.values(draft.sessions))
950
+ session.expiresAt = Math.min(
951
+ session.expiresAt,
952
+ session.createdAt + next.sessionHours * 36e5
953
+ );
954
+ }
955
+ });
956
+ this.challenges.clear();
957
+ } catch (error) {
958
+ if (this.store.healthy()) this.policy = previous;
959
+ throw error;
960
+ } finally {
961
+ this.policyChanging = false;
962
+ }
963
+ }
964
+ /** Startup/re-activation must persist tightening before the guarded listener opens. */
965
+ async enforceCurrentPolicy() {
966
+ const state = this.store.current();
967
+ const revokeUnbound = this.policy.requireTotp && !state.account?.totp && Object.keys(state.sessions).length > 0;
968
+ const shorten = Object.values(state.sessions).some(
969
+ (session) => session.expiresAt > session.createdAt + this.policy.sessionHours * 36e5
970
+ );
971
+ if (!revokeUnbound && !shorten) return;
972
+ await this.store.transact((draft) => {
973
+ if (this.policy.requireTotp && draft.account && !draft.account.totp) {
974
+ draft.account.securityVersion++;
975
+ draft.sessions = {};
976
+ }
977
+ for (const session of Object.values(draft.sessions))
978
+ session.expiresAt = Math.min(
979
+ session.expiresAt,
980
+ session.createdAt + this.policy.sessionHours * 36e5
981
+ );
982
+ });
983
+ }
984
+ };
985
+
986
+ // src/shared/admin-contract.ts
987
+ var ADMIN_PROTOCOL_VERSION = 1;
988
+ var ADMIN_MAX_BYTES = 16 * 1024;
989
+
990
+ // src/cli/ipc-client.ts
991
+ import { lstat as lstat3 } from "node:fs/promises";
992
+ import { connect } from "node:net";
993
+ import { dirname } from "node:path";
994
+
995
+ // src/shared/locales/en.ts
996
+ var en = {
997
+ brand: "DSH \xB7 Remote sign-in",
998
+ errorNetwork: "Connection failed. Check your network and try again.",
999
+ errorRateLimited: "Too many attempts. Try again in about {seconds} seconds.",
1000
+ errorUnauthorized: "Your session has expired. Sign in again.",
1001
+ errorServiceUnavailable: "The service is temporarily unavailable. Try again later.",
1002
+ errorGeneric: "The operation could not be completed. Try again.",
1003
+ loginInitialTitle: "Sign in to DSH",
1004
+ loginInitialLoading: "Checking sign-in status\u2026",
1005
+ loginLanguageLabel: "Language",
1006
+ loginSetupTitle: "Set up your account first",
1007
+ loginSetupDescription: "Run this command in a terminal on the server running DSH, then create a username and password when prompted. The web page cannot create the account.",
1008
+ loginSetupCopy: "Copy command",
1009
+ loginSetupRecheck: "I finished setup",
1010
+ loginSetupCopied: "Command copied.",
1011
+ loginSetupCopyFallback: "Select and copy the command manually.",
1012
+ loginSetupNotFound: "No account was found. Check that the command used this profile, then try again.",
1013
+ loginTitle: "Sign in to DSH",
1014
+ loginDescription: "Enter the single-user account created in the server terminal.",
1015
+ loginUsername: "Username",
1016
+ loginPassword: "Password",
1017
+ loginContinue: "Continue",
1018
+ loginMfaTitle: "Verify your second factor",
1019
+ loginMfaDescription: "Enter the six-digit code from your authenticator or a one-time backup code. This challenge expires in five minutes.",
1020
+ loginMfaCode: "Verification or backup code",
1021
+ loginMfaSubmit: "Verify and sign in",
1022
+ loginBackToPassword: "Back to password sign-in",
1023
+ loginMfaExhausted: "This challenge is exhausted. Enter your password again.",
1024
+ loginBindingTitle: "Connect an authenticator",
1025
+ loginBindingDescription: "Scan the QR code with your authenticator, or enter the secret below. After confirmation, ten one-time backup codes will appear and you will need to sign in again.",
1026
+ loginBindingQrAlt: "Authenticator setup QR code",
1027
+ loginBindingManualSecret: "Manual secret",
1028
+ loginBindingCode: "Six-digit code from the authenticator",
1029
+ loginBindingConfirm: "Confirm setup",
1030
+ loginBindingRestart: "Sign in again",
1031
+ loginBindingQrUnavailable: "The QR code is unavailable. Use the manual secret above.",
1032
+ loginBindingExhausted: "This setup challenge is exhausted. Enter your password again.",
1033
+ loginBackupTitle: "Save your backup codes",
1034
+ loginBackupDescription: "These codes are shown only once. Store them safely; each code can be used only once. Sign in again after saving them.",
1035
+ loginBackupSaved: "I saved them; sign in again",
1036
+ loginOptionalTitle: "Protect your account",
1037
+ loginOptionalDescription: "This profile lets you connect an authenticator later. Connecting one now adds protection; you can also do it in Security settings.",
1038
+ loginOptionalBindNow: "Connect TOTP now",
1039
+ loginOptionalSkip: "Skip and enter DSH",
1040
+ loginOptionalVerifyTitle: "Verify again before setup",
1041
+ loginOptionalVerifyDescription: "Enter your current password to protect your account.",
1042
+ loginOptionalCurrentPassword: "Current password",
1043
+ loginOptionalStart: "Start setup",
1044
+ loginOptionalSkipLater: "Connect later and enter DSH",
1045
+ loginReasonExpired: "Your session has expired. Sign in again.",
1046
+ loginReasonUpdated: "Security settings changed. Sign in again.",
1047
+ loginReasonSignedOut: "You signed out of this device.",
1048
+ loginUnavailableTitle: "Sign-in is temporarily unavailable",
1049
+ loginUnavailableDescription: "The service status is unavailable. Check the connection and retry.",
1050
+ loginRetry: "Check again",
1051
+ loginErrorInvalidCredentials: "The username or password is incorrect. Try again.",
1052
+ loginErrorInvalidFactor: "The verification or backup code is incorrect. After five failed attempts, you must enter your password again.",
1053
+ loginErrorChallenge: "This verification expired. Enter your username and password again.",
1054
+ loginErrorUninitialized: "The account is not set up. Run the setup command in the server terminal.",
1055
+ settingsSectionLabel: "Security",
1056
+ settingsSectionAria: "Security settings",
1057
+ settingsTitle: "Account security",
1058
+ settingsAccountSummary: "Account: {username} \xB7 TOTP: {totp}",
1059
+ settingsTotpEnabled: "Enabled",
1060
+ settingsTotpNotBound: "Not connected",
1061
+ settingsLoading: "Loading account status\u2026",
1062
+ settingsChangePassword: "Change password",
1063
+ settingsBindTotp: "Connect TOTP",
1064
+ settingsRebindTotp: "Reconnect TOTP",
1065
+ settingsSessions: "Session management",
1066
+ settingsPasswordMismatch: "The new passwords do not match.",
1067
+ settingsPasswordDescription: "After this change, every device must sign in again.",
1068
+ settingsCurrentPassword: "Current password",
1069
+ settingsCurrentCode: "Current verification or backup code",
1070
+ settingsNewPassword: "New password",
1071
+ settingsConfirmPassword: "Confirm new password",
1072
+ settingsSavePassword: "Save new password",
1073
+ settingsBindDescription: "Enter your current credentials. After connecting the new authenticator, every device must sign in again.",
1074
+ settingsStartBinding: "Start setup",
1075
+ settingsDisableTotp: "Turn off TOTP",
1076
+ settingsDisableDescription: "After turning off TOTP, every device must sign in again.",
1077
+ settingsScanQr: "Scan the QR code",
1078
+ settingsQrAlt: "Authenticator setup QR code",
1079
+ settingsQrUnavailable: "The QR code is unavailable. Use the manual secret below.",
1080
+ settingsQrLoading: "Generating the QR code; you can use the manual secret below.",
1081
+ settingsManualSecret: "Manual secret:",
1082
+ settingsNewCode: "Six-digit code from the new authenticator",
1083
+ settingsConfirmBinding: "Confirm setup",
1084
+ settingsRestartBinding: "Start over",
1085
+ settingsSignOutCurrent: "Sign out this device",
1086
+ settingsSignOutAll: "Sign out every device",
1087
+ settingsSignOutAllDescription: "Enter your current credentials. All signed-in devices and open connections will be revoked.",
1088
+ settingsBackupTitle: "Save your backup codes",
1089
+ settingsBackupDescription: "These codes are shown only once. Store them safely; each code can be used only once.",
1090
+ settingsBackupSaved: "I saved them; sign in again",
1091
+ settingsErrorInvalidCredentials: "The current password is incorrect.",
1092
+ settingsErrorInvalidFactor: "The current verification or backup code is incorrect.",
1093
+ settingsErrorInvalidInput: "The input is invalid. Passwords must meet the server length rules.",
1094
+ settingsErrorChallenge: "The setup challenge expired. Start setup again.",
1095
+ settingsErrorTotpRequired: "This profile requires TOTP, so it cannot be turned off.",
1096
+ cliHelp: `dsh-auth-remote {version}
1097
+
1098
+ Usage:
1099
+ dsh plugin --profile web exec dsh-auth-remote [--lang en|zh] COMMAND
1100
+
1101
+ Commands:
1102
+ init Create the single account interactively
1103
+ status [--json] Show non-sensitive authentication status
1104
+ reset-password Reset the password and revoke all sessions
1105
+ reset-totp Clear TOTP, backup codes and all sessions
1106
+ revoke-sessions Sign out every device
1107
+
1108
+ Options:
1109
+ --lang en|zh Choose the language for human-readable output
1110
+ --help, -h Show this help
1111
+ --version, -v Show the package version
1112
+
1113
+ The command uses the profile selected by dsh plugin exec and the caller's DSH_HOME.
1114
+ `,
1115
+ cliPromptUsername: "Username: ",
1116
+ cliPromptPassword: "Password: ",
1117
+ cliPromptPasswordAgain: "Enter password again: ",
1118
+ cliPromptNewPassword: "New password: ",
1119
+ cliPromptNewPasswordAgain: "Enter new password again: ",
1120
+ cliPromptConfirmTarget: "Enter {profile} to confirm {command}: ",
1121
+ cliTargetProfile: "Target profile: {profile}",
1122
+ cliDataFile: "State file: {path}",
1123
+ cliStatusProfile: "Profile: {profile}",
1124
+ cliStatusAccount: "Account: {state}",
1125
+ cliStatusTotp: "TOTP: {state}",
1126
+ cliStatusSessions: "Active sessions: {count}",
1127
+ cliStatusService: "Service: {state}",
1128
+ cliInitialized: "Initialized",
1129
+ cliNotInitialized: "Not initialized",
1130
+ cliTotpEnabled: "Enabled",
1131
+ cliTotpDisabled: "Disabled",
1132
+ cliOnlineReady: "Online and ready",
1133
+ cliOnlineNotReady: "Online but not ready",
1134
+ cliOffline: "Offline",
1135
+ cliCompleted: "{command} completed; the change is durable and effective.",
1136
+ cliErrorInvalidArguments: "Invalid command or arguments. Use --help.",
1137
+ cliErrorInvalidLanguage: "Invalid --lang value. Use en or zh.",
1138
+ cliErrorDuplicateLanguage: "Specify --lang only once.",
1139
+ cliErrorMissingLanguage: "Missing value for --lang. Use en or zh.",
1140
+ cliErrorPasswordsMismatch: "The passwords do not match.",
1141
+ cliErrorConfirmationMismatch: "The confirmation did not match the target profile.",
1142
+ cliErrorPasswordLength: "Password must contain 12\u2013256 Unicode characters.",
1143
+ cliErrorTerminalRequired: "An interactive terminal is required.",
1144
+ cliErrorTerminalClosed: "Terminal input closed.",
1145
+ cliErrorCancelled: "Cancelled.",
1146
+ cliErrorProfileDirectory: "The current directory is not the selected DSH profile under DSH_HOME.",
1147
+ cliErrorProfileManifest: "The profile package.json is missing.",
1148
+ cliErrorUnsafeManagementDirectory: "The management directory has unsafe permissions.",
1149
+ cliErrorUnsafeManagementSocket: "The management socket has unsafe permissions.",
1150
+ cliErrorManagementUnavailable: "The management socket is unavailable.",
1151
+ cliErrorOutcomeUnknown: "The management request disconnected or timed out. Its result is unknown; check status before trying again.",
1152
+ cliErrorOfflineLock: "The management socket is unavailable while the service holds the profile lock. Offline access was refused.",
1153
+ cliErrorInvalidCredentials: "The current credentials are incorrect.",
1154
+ cliErrorAlreadyInitialized: "The account is already initialized.",
1155
+ cliErrorInvalidInput: "The input is invalid.",
1156
+ cliErrorInvalidFactor: "The verification or backup code is incorrect.",
1157
+ cliErrorUninitialized: "The account is not initialized.",
1158
+ cliErrorTotpRequired: "This profile requires TOTP.",
1159
+ cliErrorConflict: "The account state changed. Check status and retry.",
1160
+ cliErrorBusy: "The service is busy. Try again later.",
1161
+ cliErrorUnknown: "The operation failed. Check status before trying again."
1162
+ };
1163
+
1164
+ // src/shared/locales/zh.ts
1165
+ var zh = {
1166
+ brand: "DSH \xB7 \u8FDC\u7A0B\u767B\u5F55",
1167
+ errorNetwork: "\u8FDE\u63A5\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5\u3002",
1168
+ errorRateLimited: "\u5C1D\u8BD5\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7EA6 {seconds} \u79D2\u540E\u91CD\u8BD5\u3002",
1169
+ errorUnauthorized: "\u4F1A\u8BDD\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002",
1170
+ errorServiceUnavailable: "\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
1171
+ errorGeneric: "\u64CD\u4F5C\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5\u3002",
1172
+ loginInitialTitle: "\u767B\u5F55 DSH",
1173
+ loginInitialLoading: "\u6B63\u5728\u68C0\u67E5\u767B\u5F55\u72B6\u6001\u2026",
1174
+ loginLanguageLabel: "\u8BED\u8A00",
1175
+ loginSetupTitle: "\u5148\u521D\u59CB\u5316\u8D26\u53F7",
1176
+ loginSetupDescription: "\u8BF7\u5728\u8FD0\u884C DSH \u7684\u670D\u52A1\u5668\u7EC8\u7AEF\u8F93\u5165\u4E0B\u5217\u547D\u4EE4\uFF0C\u7136\u540E\u6309\u63D0\u793A\u521B\u5EFA\u7528\u6237\u540D\u548C\u5BC6\u7801\u3002\u7F51\u9875\u4E0D\u4F1A\u521B\u5EFA\u8D26\u53F7\u3002",
1177
+ loginSetupCopy: "\u590D\u5236\u547D\u4EE4",
1178
+ loginSetupRecheck: "\u6211\u5DF2\u5B8C\u6210\u521D\u59CB\u5316",
1179
+ loginSetupCopied: "\u547D\u4EE4\u5DF2\u590D\u5236\u3002",
1180
+ loginSetupCopyFallback: "\u8BF7\u624B\u52A8\u9009\u62E9\u5E76\u590D\u5236\u547D\u4EE4\u3002",
1181
+ loginSetupNotFound: "\u5C1A\u672A\u68C0\u6D4B\u5230\u8D26\u53F7\u3002\u8BF7\u786E\u8BA4\u547D\u4EE4\u4F7F\u7528\u4E86\u5F53\u524D profile\uFF0C\u518D\u91CD\u65B0\u68C0\u67E5\u3002",
1182
+ loginTitle: "\u767B\u5F55 DSH",
1183
+ loginDescription: "\u8F93\u5165\u670D\u52A1\u5668\u7EC8\u7AEF\u521B\u5EFA\u7684\u5355\u7528\u6237\u8D26\u53F7\u3002",
1184
+ loginUsername: "\u7528\u6237\u540D",
1185
+ loginPassword: "\u5BC6\u7801",
1186
+ loginContinue: "\u7EE7\u7EED",
1187
+ loginMfaTitle: "\u9A8C\u8BC1\u7B2C\u4E8C\u56E0\u7D20",
1188
+ loginMfaDescription: "\u8F93\u5165\u8EAB\u4EFD\u9A8C\u8BC1\u5668\u4E2D\u7684 6 \u4F4D\u6570\u5B57\uFF0C\u6216\u8F93\u5165\u4E00\u6B21\u6027\u5907\u7528\u7801\u3002\u6311\u6218 5 \u5206\u949F\u540E\u5931\u6548\u3002",
1189
+ loginMfaCode: "\u9A8C\u8BC1\u7801\u6216\u5907\u7528\u7801",
1190
+ loginMfaSubmit: "\u9A8C\u8BC1\u5E76\u767B\u5F55",
1191
+ loginBackToPassword: "\u8FD4\u56DE\u5BC6\u7801\u767B\u5F55",
1192
+ loginMfaExhausted: "\u672C\u6B21\u6311\u6218\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165\u5BC6\u7801\u3002",
1193
+ loginBindingTitle: "\u7ED1\u5B9A\u8EAB\u4EFD\u9A8C\u8BC1\u5668",
1194
+ loginBindingDescription: "\u4F7F\u7528\u8EAB\u4EFD\u9A8C\u8BC1\u5668\u626B\u63CF\u4E8C\u7EF4\u7801\uFF0C\u6216\u624B\u52A8\u8F93\u5165\u4E0B\u65B9\u5BC6\u94A5\u3002\u786E\u8BA4\u6210\u529F\u540E\u5C06\u663E\u793A 10 \u4E2A\u4E00\u6B21\u6027\u5907\u7528\u7801\uFF0C\u5E76\u8981\u6C42\u91CD\u65B0\u767B\u5F55\u3002",
1195
+ loginBindingQrAlt: "\u8EAB\u4EFD\u9A8C\u8BC1\u5668\u7ED1\u5B9A\u4E8C\u7EF4\u7801",
1196
+ loginBindingManualSecret: "\u624B\u5DE5\u5BC6\u94A5",
1197
+ loginBindingCode: "\u8EAB\u4EFD\u9A8C\u8BC1\u5668\u4E2D\u7684 6 \u4F4D\u9A8C\u8BC1\u7801",
1198
+ loginBindingConfirm: "\u786E\u8BA4\u7ED1\u5B9A",
1199
+ loginBindingRestart: "\u91CD\u65B0\u767B\u5F55",
1200
+ loginBindingQrUnavailable: "\u4E8C\u7EF4\u7801\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u4F7F\u7528\u4E0A\u65B9\u624B\u5DE5\u5BC6\u94A5\u3002",
1201
+ loginBindingExhausted: "\u7ED1\u5B9A\u6311\u6218\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165\u5BC6\u7801\u3002",
1202
+ loginBackupTitle: "\u4FDD\u5B58\u5907\u7528\u7801",
1203
+ loginBackupDescription: "\u8FD9\u4E9B\u5907\u7528\u7801\u53EA\u4F1A\u663E\u793A\u8FD9\u4E00\u6B21\u3002\u8BF7\u5B58\u653E\u5728\u5B89\u5168\u7684\u4F4D\u7F6E\uFF0C\u6BCF\u4E2A\u5907\u7528\u7801\u53EA\u80FD\u4F7F\u7528\u4E00\u6B21\u3002\u4FDD\u5B58\u540E\u91CD\u65B0\u767B\u5F55\u3002",
1204
+ loginBackupSaved: "\u6211\u5DF2\u4FDD\u5B58\uFF0C\u91CD\u65B0\u767B\u5F55",
1205
+ loginOptionalTitle: "\u4FDD\u62A4\u4F60\u7684\u8D26\u53F7",
1206
+ loginOptionalDescription: "\u5F53\u524D profile \u5141\u8BB8\u7A0D\u540E\u7ED1\u5B9A\u8EAB\u4EFD\u9A8C\u8BC1\u5668\u3002\u73B0\u5728\u7ED1\u5B9A\u53EF\u4EE5\u589E\u52A0\u4FDD\u62A4\uFF1B\u8DF3\u8FC7\u540E\u4E5F\u53EF\u5728\u5B89\u5168\u8BBE\u7F6E\u4E2D\u7ED1\u5B9A\u3002",
1207
+ loginOptionalBindNow: "\u73B0\u5728\u7ED1\u5B9A TOTP",
1208
+ loginOptionalSkip: "\u8DF3\u8FC7\uFF0C\u8FDB\u5165 DSH",
1209
+ loginOptionalVerifyTitle: "\u518D\u6B21\u9A8C\u8BC1\u540E\u7ED1\u5B9A",
1210
+ loginOptionalVerifyDescription: "\u4E3A\u4FDD\u62A4\u8D26\u53F7\uFF0C\u8BF7\u518D\u6B21\u8F93\u5165\u5F53\u524D\u5BC6\u7801\u3002",
1211
+ loginOptionalCurrentPassword: "\u5F53\u524D\u5BC6\u7801",
1212
+ loginOptionalStart: "\u5F00\u59CB\u7ED1\u5B9A",
1213
+ loginOptionalSkipLater: "\u7A0D\u540E\u7ED1\u5B9A\uFF0C\u8FDB\u5165 DSH",
1214
+ loginReasonExpired: "\u4F1A\u8BDD\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002",
1215
+ loginReasonUpdated: "\u5B89\u5168\u8BBE\u7F6E\u5DF2\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002",
1216
+ loginReasonSignedOut: "\u5DF2\u9000\u51FA\u5F53\u524D\u8BBE\u5907\u3002",
1217
+ loginUnavailableTitle: "\u6682\u65F6\u65E0\u6CD5\u767B\u5F55",
1218
+ loginUnavailableDescription: "\u670D\u52A1\u72B6\u6001\u6682\u65F6\u65E0\u6CD5\u53D6\u5F97\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5\u5E76\u91CD\u8BD5\u3002",
1219
+ loginRetry: "\u91CD\u65B0\u68C0\u67E5",
1220
+ loginErrorInvalidCredentials: "\u7528\u6237\u540D\u6216\u5BC6\u7801\u4E0D\u6B63\u786E\uFF0C\u8BF7\u91CD\u8BD5\u3002",
1221
+ loginErrorInvalidFactor: "\u9A8C\u8BC1\u7801\u6216\u5907\u7528\u7801\u4E0D\u6B63\u786E\uFF1B\u8FDE\u7EED\u5931\u8D25 5 \u6B21\u540E\u9700\u91CD\u65B0\u8F93\u5165\u5BC6\u7801\u3002",
1222
+ loginErrorChallenge: "\u672C\u6B21\u9A8C\u8BC1\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165\u7528\u6237\u540D\u548C\u5BC6\u7801\u3002",
1223
+ loginErrorUninitialized: "\u8D26\u53F7\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u5728\u670D\u52A1\u5668\u7EC8\u7AEF\u8FD0\u884C\u521D\u59CB\u5316\u547D\u4EE4\u3002",
1224
+ settingsSectionLabel: "\u5B89\u5168",
1225
+ settingsSectionAria: "\u5B89\u5168\u8BBE\u7F6E",
1226
+ settingsTitle: "\u8D26\u53F7\u5B89\u5168",
1227
+ settingsAccountSummary: "\u8D26\u53F7\uFF1A{username} \xB7 TOTP\uFF1A{totp}",
1228
+ settingsTotpEnabled: "\u5DF2\u542F\u7528",
1229
+ settingsTotpNotBound: "\u672A\u7ED1\u5B9A",
1230
+ settingsLoading: "\u6B63\u5728\u8BFB\u53D6\u8D26\u53F7\u72B6\u6001\u2026",
1231
+ settingsChangePassword: "\u4FEE\u6539\u5BC6\u7801",
1232
+ settingsBindTotp: "\u7ED1\u5B9A TOTP",
1233
+ settingsRebindTotp: "\u91CD\u65B0\u7ED1\u5B9A TOTP",
1234
+ settingsSessions: "\u4F1A\u8BDD\u7BA1\u7406",
1235
+ settingsPasswordMismatch: "\u4E24\u6B21\u8F93\u5165\u7684\u65B0\u5BC6\u7801\u4E0D\u4E00\u81F4\u3002",
1236
+ settingsPasswordDescription: "\u5B8C\u6210\u540E\u6240\u6709\u8BBE\u5907\u90FD\u9700\u8981\u91CD\u65B0\u767B\u5F55\u3002",
1237
+ settingsCurrentPassword: "\u5F53\u524D\u5BC6\u7801",
1238
+ settingsCurrentCode: "\u5F53\u524D\u9A8C\u8BC1\u7801\u6216\u5907\u7528\u7801",
1239
+ settingsNewPassword: "\u65B0\u5BC6\u7801",
1240
+ settingsConfirmPassword: "\u518D\u6B21\u8F93\u5165\u65B0\u5BC6\u7801",
1241
+ settingsSavePassword: "\u4FDD\u5B58\u65B0\u5BC6\u7801",
1242
+ settingsBindDescription: "\u8BF7\u8F93\u5165\u5F53\u524D\u51ED\u8BC1\uFF1B\u65B0\u7ED1\u5B9A\u5B8C\u6210\u540E\u6240\u6709\u8BBE\u5907\u90FD\u9700\u8981\u91CD\u65B0\u767B\u5F55\u3002",
1243
+ settingsStartBinding: "\u5F00\u59CB\u7ED1\u5B9A",
1244
+ settingsDisableTotp: "\u5173\u95ED TOTP",
1245
+ settingsDisableDescription: "\u5173\u95ED\u540E\u6240\u6709\u8BBE\u5907\u90FD\u9700\u8981\u91CD\u65B0\u767B\u5F55\u3002",
1246
+ settingsScanQr: "\u626B\u63CF\u4E8C\u7EF4\u7801",
1247
+ settingsQrAlt: "\u8EAB\u4EFD\u9A8C\u8BC1\u5668\u7ED1\u5B9A\u4E8C\u7EF4\u7801",
1248
+ settingsQrUnavailable: "\u4E8C\u7EF4\u7801\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u4F7F\u7528\u4E0B\u65B9\u624B\u5DE5\u5BC6\u94A5\u3002",
1249
+ settingsQrLoading: "\u4E8C\u7EF4\u7801\u751F\u6210\u4E2D\uFF1B\u4E5F\u53EF\u4EE5\u4F7F\u7528\u4E0B\u65B9\u624B\u5DE5\u5BC6\u94A5\u3002",
1250
+ settingsManualSecret: "\u624B\u5DE5\u5BC6\u94A5\uFF1A",
1251
+ settingsNewCode: "\u65B0\u8EAB\u4EFD\u9A8C\u8BC1\u5668\u7684 6 \u4F4D\u9A8C\u8BC1\u7801",
1252
+ settingsConfirmBinding: "\u786E\u8BA4\u7ED1\u5B9A",
1253
+ settingsRestartBinding: "\u91CD\u65B0\u5F00\u59CB",
1254
+ settingsSignOutCurrent: "\u9000\u51FA\u5F53\u524D\u8BBE\u5907",
1255
+ settingsSignOutAll: "\u9000\u51FA\u5168\u90E8\u8BBE\u5907",
1256
+ settingsSignOutAllDescription: "\u8BF7\u8F93\u5165\u5F53\u524D\u51ED\u8BC1\uFF1B\u63D0\u4EA4\u540E\u6240\u6709\u5DF2\u767B\u5F55\u8BBE\u5907\u548C\u957F\u8FDE\u63A5\u90FD\u4F1A\u5931\u6548\u3002",
1257
+ settingsBackupTitle: "\u4FDD\u5B58\u5907\u7528\u7801",
1258
+ settingsBackupDescription: "\u8FD9\u4E9B\u5907\u7528\u7801\u53EA\u4F1A\u663E\u793A\u8FD9\u4E00\u6B21\u3002\u8BF7\u5B58\u653E\u5728\u5B89\u5168\u7684\u4F4D\u7F6E\uFF0C\u6BCF\u4E2A\u5907\u7528\u7801\u53EA\u80FD\u4F7F\u7528\u4E00\u6B21\u3002",
1259
+ settingsBackupSaved: "\u6211\u5DF2\u4FDD\u5B58\uFF0C\u91CD\u65B0\u767B\u5F55",
1260
+ settingsErrorInvalidCredentials: "\u5F53\u524D\u5BC6\u7801\u4E0D\u6B63\u786E\u3002",
1261
+ settingsErrorInvalidFactor: "\u5F53\u524D\u9A8C\u8BC1\u7801\u6216\u5907\u7528\u7801\u4E0D\u6B63\u786E\u3002",
1262
+ settingsErrorInvalidInput: "\u8F93\u5165\u4E0D\u7B26\u5408\u8981\u6C42\uFF1B\u5BC6\u7801\u9700\u7B26\u5408\u670D\u52A1\u7AEF\u957F\u5EA6\u89C4\u5219\u3002",
1263
+ settingsErrorChallenge: "\u7ED1\u5B9A\u6311\u6218\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u5F00\u59CB\u7ED1\u5B9A\u3002",
1264
+ settingsErrorTotpRequired: "\u5F53\u524D profile \u8981\u6C42 TOTP\uFF0C\u65E0\u6CD5\u5173\u95ED\u3002",
1265
+ cliHelp: `dsh-auth-remote {version}
1266
+
1267
+ \u7528\u6CD5\uFF1A
1268
+ dsh plugin --profile web exec dsh-auth-remote [--lang en|zh] COMMAND
1269
+
1270
+ \u547D\u4EE4\uFF1A
1271
+ init \u5728\u7EC8\u7AEF\u4EA4\u4E92\u521D\u59CB\u5316\u5355\u7528\u6237\u8D26\u53F7
1272
+ status [--json] \u67E5\u770B\u4E0D\u542B\u79D8\u5BC6\u7684\u8BA4\u8BC1\u72B6\u6001
1273
+ reset-password \u91CD\u7F6E\u5BC6\u7801\u5E76\u64A4\u9500\u5168\u90E8\u4F1A\u8BDD
1274
+ reset-totp \u6E05\u9664 TOTP\u3001\u5907\u7528\u7801\u53CA\u5168\u90E8\u4F1A\u8BDD
1275
+ revoke-sessions \u9000\u51FA\u6240\u6709\u8BBE\u5907
1276
+
1277
+ \u9009\u9879\uFF1A
1278
+ --lang en|zh \u9009\u62E9\u4EBA\u7C7B\u53EF\u8BFB\u8F93\u51FA\u7684\u8BED\u8A00
1279
+ --help, -h \u663E\u793A\u5E2E\u52A9
1280
+ --version, -v \u663E\u793A\u5305\u7248\u672C
1281
+
1282
+ \u547D\u4EE4\u4F7F\u7528 dsh plugin exec \u9009\u5B9A\u7684 profile \u548C\u8C03\u7528\u8005\u7684 DSH_HOME\u3002
1283
+ `,
1284
+ cliPromptUsername: "\u7528\u6237\u540D: ",
1285
+ cliPromptPassword: "\u5BC6\u7801: ",
1286
+ cliPromptPasswordAgain: "\u518D\u6B21\u8F93\u5165\u5BC6\u7801: ",
1287
+ cliPromptNewPassword: "\u65B0\u5BC6\u7801: ",
1288
+ cliPromptNewPasswordAgain: "\u518D\u6B21\u8F93\u5165\u65B0\u5BC6\u7801: ",
1289
+ cliPromptConfirmTarget: "\u8F93\u5165 {profile} \u4EE5\u786E\u8BA4 {command}: ",
1290
+ cliTargetProfile: "\u76EE\u6807 profile: {profile}",
1291
+ cliDataFile: "\u6570\u636E\u6587\u4EF6: {path}",
1292
+ cliStatusProfile: "profile: {profile}",
1293
+ cliStatusAccount: "\u8D26\u53F7: {state}",
1294
+ cliStatusTotp: "TOTP: {state}",
1295
+ cliStatusSessions: "\u6709\u6548\u4F1A\u8BDD: {count}",
1296
+ cliStatusService: "\u670D\u52A1: {state}",
1297
+ cliInitialized: "\u5DF2\u521D\u59CB\u5316",
1298
+ cliNotInitialized: "\u672A\u521D\u59CB\u5316",
1299
+ cliTotpEnabled: "\u5DF2\u542F\u7528",
1300
+ cliTotpDisabled: "\u672A\u542F\u7528",
1301
+ cliOnlineReady: "\u5728\u7EBF\u4E14\u5C31\u7EEA",
1302
+ cliOnlineNotReady: "\u5728\u7EBF\u4F46\u672A\u5C31\u7EEA",
1303
+ cliOffline: "\u79BB\u7EBF",
1304
+ cliCompleted: "{command} \u5DF2\u5B8C\u6210\uFF1B\u53D8\u66F4\u5DF2\u6301\u4E45\u5316\u5E76\u751F\u6548\u3002",
1305
+ cliErrorInvalidArguments: "\u547D\u4EE4\u6216\u53C2\u6570\u65E0\u6548\uFF0C\u8BF7\u4F7F\u7528 --help\u3002",
1306
+ cliErrorInvalidLanguage: "--lang \u7684\u503C\u65E0\u6548\uFF0C\u8BF7\u4F7F\u7528 en \u6216 zh\u3002",
1307
+ cliErrorDuplicateLanguage: "--lang \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\u3002",
1308
+ cliErrorMissingLanguage: "--lang \u7F3A\u5C11\u503C\uFF0C\u8BF7\u4F7F\u7528 en \u6216 zh\u3002",
1309
+ cliErrorPasswordsMismatch: "\u4E24\u6B21\u8F93\u5165\u7684\u5BC6\u7801\u4E0D\u4E00\u81F4\u3002",
1310
+ cliErrorConfirmationMismatch: "\u786E\u8BA4\u8F93\u5165\u4E0E\u76EE\u6807 profile \u4E0D\u4E00\u81F4\u3002",
1311
+ cliErrorPasswordLength: "\u5BC6\u7801\u987B\u5305\u542B 12\u2013256 \u4E2A Unicode \u5B57\u7B26\u3002",
1312
+ cliErrorTerminalRequired: "\u6B64\u64CD\u4F5C\u9700\u8981\u4EA4\u4E92\u7EC8\u7AEF\u3002",
1313
+ cliErrorTerminalClosed: "\u7EC8\u7AEF\u8F93\u5165\u5DF2\u5173\u95ED\u3002",
1314
+ cliErrorCancelled: "\u5DF2\u53D6\u6D88\u3002",
1315
+ cliErrorProfileDirectory: "\u5F53\u524D\u76EE\u5F55\u4E0D\u662F DSH_HOME \u4E0B\u9009\u5B9A\u7684 DSH profile\u3002",
1316
+ cliErrorProfileManifest: "\u7F3A\u5C11 profile \u7684 package.json\u3002",
1317
+ cliErrorUnsafeManagementDirectory: "\u7BA1\u7406\u76EE\u5F55\u6743\u9650\u4E0D\u5B89\u5168\u3002",
1318
+ cliErrorUnsafeManagementSocket: "\u7BA1\u7406 socket \u6743\u9650\u4E0D\u5B89\u5168\u3002",
1319
+ cliErrorManagementUnavailable: "\u7BA1\u7406 socket \u4E0D\u53EF\u7528\u3002",
1320
+ cliErrorOutcomeUnknown: "\u7BA1\u7406\u8BF7\u6C42\u5DF2\u65AD\u5F00\u6216\u8D85\u65F6\uFF0C\u7ED3\u679C\u672A\u77E5\uFF1B\u518D\u6B21\u64CD\u4F5C\u524D\u8BF7\u5148\u68C0\u67E5\u72B6\u6001\u3002",
1321
+ cliErrorOfflineLock: "\u670D\u52A1\u4ECD\u6301\u6709 profile \u9501\u4E14\u7BA1\u7406 socket \u4E0D\u53EF\u7528\uFF0C\u5DF2\u62D2\u7EDD\u79BB\u7EBF\u64CD\u4F5C\u3002",
1322
+ cliErrorInvalidCredentials: "\u5F53\u524D\u51ED\u8BC1\u4E0D\u6B63\u786E\u3002",
1323
+ cliErrorAlreadyInitialized: "\u8D26\u53F7\u5DF2\u521D\u59CB\u5316\u3002",
1324
+ cliErrorInvalidInput: "\u8F93\u5165\u65E0\u6548\u3002",
1325
+ cliErrorInvalidFactor: "\u9A8C\u8BC1\u7801\u6216\u5907\u7528\u7801\u4E0D\u6B63\u786E\u3002",
1326
+ cliErrorUninitialized: "\u8D26\u53F7\u5C1A\u672A\u521D\u59CB\u5316\u3002",
1327
+ cliErrorTotpRequired: "\u6B64 profile \u8981\u6C42 TOTP\u3002",
1328
+ cliErrorConflict: "\u8D26\u53F7\u72B6\u6001\u5DF2\u53D8\u5316\uFF0C\u8BF7\u68C0\u67E5\u72B6\u6001\u540E\u91CD\u8BD5\u3002",
1329
+ cliErrorBusy: "\u670D\u52A1\u6B63\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
1330
+ cliErrorUnknown: "\u64CD\u4F5C\u5931\u8D25\uFF1B\u518D\u6B21\u64CD\u4F5C\u524D\u8BF7\u5148\u68C0\u67E5\u72B6\u6001\u3002"
1331
+ };
1332
+
1333
+ // src/shared/i18n.ts
1334
+ var dictionaries = { en, zh };
1335
+ function parseExactLocale(value) {
1336
+ return value === "en" || value === "zh" ? value : null;
1337
+ }
1338
+ function localeFromLanguageTag(value) {
1339
+ return value && /^zh(?:[-_.@]|$)/iu.test(value.trim()) ? "zh" : "en";
1340
+ }
1341
+ function normalizeLocale(value) {
1342
+ return parseExactLocale(value) ?? "en";
1343
+ }
1344
+ function formatMessage(locale, key, ...args) {
1345
+ const template = dictionaries[normalizeLocale(locale)][key];
1346
+ const values = args[0] ?? {};
1347
+ return template.replace(/\{([A-Za-z][A-Za-z0-9]*)\}/gu, (_match, name) => {
1348
+ if (!Object.hasOwn(values, name)) throw new Error(`Missing i18n parameter ${name} for ${key}`);
1349
+ return String(values[name]);
1350
+ });
1351
+ }
1352
+
1353
+ // src/cli/language.ts
1354
+ var CliDiagnostic = class extends Error {
1355
+ constructor(key, englishMessage, locale) {
1356
+ super(englishMessage);
1357
+ this.key = key;
1358
+ this.locale = locale;
1359
+ }
1360
+ key;
1361
+ locale;
1362
+ };
1363
+ function environmentLocale(env) {
1364
+ const value = [env.LC_ALL, env.LC_MESSAGES, env.LANG].find(
1365
+ (candidate) => candidate !== void 0 && candidate.trim().length > 0
1366
+ );
1367
+ return localeFromLanguageTag(value);
1368
+ }
1369
+ function parseLanguage(input, env = process.env) {
1370
+ let locale = environmentLocale(env);
1371
+ let explicit = false;
1372
+ const args = [];
1373
+ for (let index = 0; index < input.length; index++) {
1374
+ const token = input[index];
1375
+ if (token !== "--lang" && !token.startsWith("--lang=")) {
1376
+ args.push(token);
1377
+ continue;
1378
+ }
1379
+ if (explicit)
1380
+ throw new CliDiagnostic(
1381
+ "cliErrorDuplicateLanguage",
1382
+ "dsh-auth-remote: --lang may be specified only once",
1383
+ locale
1384
+ );
1385
+ explicit = true;
1386
+ const value = token === "--lang" ? input[++index] : token.slice("--lang=".length);
1387
+ if (value === void 0 || value.length === 0 || value.startsWith("--"))
1388
+ throw new CliDiagnostic(
1389
+ "cliErrorMissingLanguage",
1390
+ "dsh-auth-remote: --lang requires en or zh",
1391
+ locale
1392
+ );
1393
+ if (value !== "en" && value !== "zh")
1394
+ throw new CliDiagnostic(
1395
+ "cliErrorInvalidLanguage",
1396
+ "dsh-auth-remote: invalid --lang value; use en or zh",
1397
+ locale
1398
+ );
1399
+ locale = value;
1400
+ }
1401
+ return { locale, args };
1402
+ }
1403
+ function cliText(locale, key, params = {}) {
1404
+ return formatMessage(locale, key, params);
1405
+ }
1406
+
1407
+ // src/cli/ipc-client.ts
1408
+ var AdminUnavailable = class extends Error {
1409
+ constructor() {
1410
+ super("dsh-auth-remote: management socket is unavailable");
1411
+ }
1412
+ };
1413
+ var AdminOutcomeUnknown = class extends Error {
1414
+ constructor() {
1415
+ super("dsh-auth-remote: management request disconnected or timed out; result is unknown");
1416
+ }
1417
+ };
1418
+ var AdminRejected = class extends Error {
1419
+ constructor(code) {
1420
+ super(`dsh-auth-remote: ${code}`);
1421
+ this.code = code;
1422
+ }
1423
+ code;
1424
+ };
1425
+ function errno3(error, code) {
1426
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
1427
+ }
1428
+ async function inspectSocket(path) {
1429
+ let directory;
1430
+ try {
1431
+ directory = await lstat3(dirname(path));
1432
+ } catch (error) {
1433
+ if (errno3(error, "ENOENT")) return false;
1434
+ throw error;
1435
+ }
1436
+ if (!directory.isDirectory() || directory.uid !== process.getuid?.() || (directory.mode & 511) !== 448)
1437
+ throw new CliDiagnostic(
1438
+ "cliErrorUnsafeManagementDirectory",
1439
+ "dsh-auth-remote: unsafe management directory"
1440
+ );
1441
+ let socket;
1442
+ try {
1443
+ socket = await lstat3(path);
1444
+ } catch (error) {
1445
+ if (errno3(error, "ENOENT")) return false;
1446
+ throw error;
1447
+ }
1448
+ if (!socket.isSocket() || socket.uid !== process.getuid?.() || (socket.mode & 511) !== 384)
1449
+ throw new CliDiagnostic(
1450
+ "cliErrorUnsafeManagementSocket",
1451
+ "dsh-auth-remote: unsafe management socket"
1452
+ );
1453
+ return true;
1454
+ }
1455
+ async function requestAdmin(path, request) {
1456
+ if (!await inspectSocket(path)) throw new AdminUnavailable();
1457
+ let socket;
1458
+ try {
1459
+ socket = await new Promise((resolve2, reject) => {
1460
+ const candidate = connect(path);
1461
+ candidate.setTimeout(2e3, () => {
1462
+ candidate.destroy();
1463
+ reject(new AdminUnavailable());
1464
+ });
1465
+ candidate.once("connect", () => {
1466
+ candidate.setTimeout(0);
1467
+ resolve2(candidate);
1468
+ });
1469
+ candidate.once("error", reject);
1470
+ });
1471
+ } catch (error) {
1472
+ if (errno3(error, "ENOENT") || errno3(error, "ECONNREFUSED")) throw new AdminUnavailable();
1473
+ throw error;
1474
+ }
1475
+ try {
1476
+ return await new Promise((resolve2, reject) => {
1477
+ let bytes = 0;
1478
+ const chunks = [];
1479
+ let settled = false;
1480
+ const fail = (error) => {
1481
+ if (settled) return;
1482
+ settled = true;
1483
+ reject(error);
1484
+ socket.destroy();
1485
+ };
1486
+ socket.setTimeout(3e4, () => fail(new AdminOutcomeUnknown()));
1487
+ socket.on("error", () => fail(new AdminOutcomeUnknown()));
1488
+ socket.on("end", () => {
1489
+ if (!settled) fail(new AdminOutcomeUnknown());
1490
+ });
1491
+ socket.on("data", (chunk) => {
1492
+ if (settled) return;
1493
+ bytes += chunk.length;
1494
+ if (bytes > ADMIN_MAX_BYTES) return fail(new AdminOutcomeUnknown());
1495
+ chunks.push(chunk);
1496
+ const data = Buffer.concat(chunks);
1497
+ const newline = data.indexOf(10);
1498
+ if (newline < 0) return;
1499
+ if (newline !== data.length - 1) return fail(new AdminOutcomeUnknown());
1500
+ let response;
1501
+ try {
1502
+ response = JSON.parse(data.subarray(0, newline).toString("utf8"));
1503
+ } catch {
1504
+ return fail(new AdminOutcomeUnknown());
1505
+ }
1506
+ if (typeof response !== "object" || response === null || !("version" in response) || response.version !== ADMIN_PROTOCOL_VERSION || !("ok" in response) || typeof response.ok !== "boolean")
1507
+ return fail(new AdminOutcomeUnknown());
1508
+ const reply = response;
1509
+ settled = true;
1510
+ socket.end();
1511
+ if (reply.ok) resolve2(reply.result);
1512
+ else reject(new AdminRejected(reply.error));
1513
+ });
1514
+ socket.write(`${JSON.stringify(request)}
1515
+ `);
1516
+ });
1517
+ } finally {
1518
+ socket.destroy();
1519
+ }
1520
+ }
1521
+
1522
+ // src/cli/profile.ts
1523
+ import { lstat as lstat4, realpath } from "node:fs/promises";
1524
+ import { homedir } from "node:os";
1525
+ import { basename, dirname as dirname2, join as join3, resolve } from "node:path";
1526
+ function dshHome(env) {
1527
+ const supplied = env.DSH_HOME;
1528
+ const candidate = supplied !== void 0 && supplied.trim().length > 0 ? supplied : join3(homedir(), ".dsh");
1529
+ const expanded = candidate === "~" ? homedir() : candidate.startsWith("~/") || candidate.startsWith("~\\") ? join3(homedir(), candidate.slice(2)) : candidate;
1530
+ return resolve(expanded);
1531
+ }
1532
+ async function resolveProfileTarget(cwd = process.cwd(), env = process.env) {
1533
+ const dir = await realpath(cwd);
1534
+ const home = await realpath(dshHome(env));
1535
+ const profiles = await realpath(join3(home, "profiles"));
1536
+ const name = basename(dir);
1537
+ const info = await lstat4(dir);
1538
+ if (!info.isDirectory() || info.uid !== process.getuid?.() || dirname2(dir) !== profiles || name === "node_modules" || name === "." || name === "..")
1539
+ throw new CliDiagnostic(
1540
+ "cliErrorProfileDirectory",
1541
+ "dsh-auth-remote: current directory is not the selected DSH profile under DSH_HOME"
1542
+ );
1543
+ let manifest2;
1544
+ try {
1545
+ manifest2 = await lstat4(join3(dir, "package.json"));
1546
+ } catch (error) {
1547
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
1548
+ throw new CliDiagnostic(
1549
+ "cliErrorProfileManifest",
1550
+ "dsh-auth-remote: profile package.json is missing"
1551
+ );
1552
+ throw error;
1553
+ }
1554
+ if (!manifest2.isFile())
1555
+ throw new CliDiagnostic(
1556
+ "cliErrorProfileManifest",
1557
+ "dsh-auth-remote: profile package.json is missing"
1558
+ );
1559
+ return {
1560
+ name,
1561
+ dir,
1562
+ home,
1563
+ statePath: join3(dir, "auth-remote", "auth-state.json"),
1564
+ socketPath: join3(dir, "auth-remote", "admin.sock")
1565
+ };
1566
+ }
1567
+
1568
+ // src/cli/prompt.ts
1569
+ var TerminalPrompt = class {
1570
+ constructor(input = process.stdin, output2 = process.stdout) {
1571
+ this.input = input;
1572
+ this.output = output2;
1573
+ if (!input.isTTY || !output2.isTTY || typeof input.setRawMode !== "function")
1574
+ throw new CliDiagnostic(
1575
+ "cliErrorTerminalRequired",
1576
+ "dsh-auth-remote: an interactive terminal is required"
1577
+ );
1578
+ this.previousRaw = input.isRaw;
1579
+ input.setRawMode(true);
1580
+ input.resume();
1581
+ input.on("data", this.onData);
1582
+ input.once("end", this.onEnd);
1583
+ }
1584
+ input;
1585
+ output;
1586
+ pending = [];
1587
+ wake;
1588
+ decoder = new TextDecoder();
1589
+ previousRaw;
1590
+ closed = false;
1591
+ ended = false;
1592
+ skipLf = false;
1593
+ onData = (chunk) => {
1594
+ for (const char of this.decoder.decode(chunk, { stream: true })) this.pending.push(char);
1595
+ this.wake?.();
1596
+ this.wake = void 0;
1597
+ };
1598
+ onEnd = () => {
1599
+ this.ended = true;
1600
+ this.wake?.();
1601
+ this.wake = void 0;
1602
+ };
1603
+ async take() {
1604
+ while (this.pending.length === 0) {
1605
+ if (this.closed || this.ended)
1606
+ throw new CliDiagnostic("cliErrorTerminalClosed", "dsh-auth-remote: terminal input closed");
1607
+ await new Promise((resolve2) => {
1608
+ this.wake = resolve2;
1609
+ });
1610
+ }
1611
+ const char = this.pending.shift();
1612
+ if (this.skipLf) {
1613
+ this.skipLf = false;
1614
+ if (char === "\n") return this.take();
1615
+ }
1616
+ return char;
1617
+ }
1618
+ async ask(label, secret = false, maxCharacters = 256) {
1619
+ if (this.closed)
1620
+ throw new CliDiagnostic("cliErrorTerminalClosed", "dsh-auth-remote: terminal input closed");
1621
+ this.output.write(label);
1622
+ const answer = [];
1623
+ let escape = false;
1624
+ for (; ; ) {
1625
+ const char = await this.take();
1626
+ if (escape) {
1627
+ if (/[A-Za-z~]/u.test(char)) escape = false;
1628
+ continue;
1629
+ }
1630
+ if (char === "\x1B") {
1631
+ escape = true;
1632
+ continue;
1633
+ }
1634
+ if (char === "")
1635
+ throw new CliDiagnostic("cliErrorCancelled", "dsh-auth-remote: cancelled");
1636
+ if (char === "")
1637
+ throw new CliDiagnostic("cliErrorTerminalClosed", "dsh-auth-remote: terminal input closed");
1638
+ if (char === "\r" || char === "\n") {
1639
+ if (char === "\r") this.skipLf = true;
1640
+ this.output.write("\n");
1641
+ return answer.join("");
1642
+ }
1643
+ if (char === "\x7F" || char === "\b") {
1644
+ if (answer.length > 0) {
1645
+ answer.pop();
1646
+ if (!secret) this.output.write("\b \b");
1647
+ }
1648
+ continue;
1649
+ }
1650
+ if (/[\u0000-\u001f\u007f]/u.test(char)) continue;
1651
+ if (answer.length >= maxCharacters) continue;
1652
+ answer.push(char);
1653
+ if (!secret) this.output.write(char);
1654
+ }
1655
+ }
1656
+ close() {
1657
+ if (this.closed) return;
1658
+ this.closed = true;
1659
+ this.input.off("data", this.onData);
1660
+ this.input.off("end", this.onEnd);
1661
+ this.input.setRawMode(this.previousRaw);
1662
+ this.input.pause();
1663
+ this.wake?.();
1664
+ this.wake = void 0;
1665
+ }
1666
+ };
1667
+
1668
+ // src/cli/index.ts
1669
+ var manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
1670
+ var currentLocale = environmentLocale(process.env);
1671
+ var output = (key, params = {}) => cliText(currentLocale, key, params);
1672
+ function authErrorKey(code) {
1673
+ switch (code) {
1674
+ case "already_initialized":
1675
+ return "cliErrorAlreadyInitialized";
1676
+ case "invalid_input":
1677
+ return "cliErrorInvalidInput";
1678
+ case "invalid_credentials":
1679
+ return "cliErrorInvalidCredentials";
1680
+ case "invalid_factor":
1681
+ return "cliErrorInvalidFactor";
1682
+ case "uninitialized":
1683
+ return "cliErrorUninitialized";
1684
+ case "totp_required":
1685
+ return "cliErrorTotpRequired";
1686
+ case "conflict":
1687
+ return "cliErrorConflict";
1688
+ case "busy":
1689
+ return "cliErrorBusy";
1690
+ default:
1691
+ return "cliErrorUnknown";
1692
+ }
1693
+ }
1694
+ function errorText(error, locale) {
1695
+ if (error instanceof CliDiagnostic) return cliText(error.locale ?? locale, error.key);
1696
+ if (error instanceof PasswordValidationError) return cliText(locale, "cliErrorPasswordLength");
1697
+ if (error instanceof AdminOutcomeUnknown) return cliText(locale, "cliErrorOutcomeUnknown");
1698
+ if (error instanceof AdminUnavailable) return cliText(locale, "cliErrorManagementUnavailable");
1699
+ if (error instanceof AdminRejected || error instanceof AuthError) {
1700
+ if (error.code === "rate_limited")
1701
+ return cliText(locale, "errorRateLimited", {
1702
+ seconds: error instanceof AuthError ? error.retryAfter ?? 1 : 1
1703
+ });
1704
+ return cliText(locale, authErrorKey(error.code));
1705
+ }
1706
+ return cliText(locale, "cliErrorUnknown");
1707
+ }
1708
+ async function offline(target, request) {
1709
+ let store;
1710
+ try {
1711
+ store = await AuthStateStore.open(target.dir);
1712
+ } catch (error) {
1713
+ if (error instanceof Error && /state lock held|state lock is held/u.test(error.message))
1714
+ throw new CliDiagnostic(
1715
+ "cliErrorOfflineLock",
1716
+ "dsh-auth-remote: management socket is unavailable while the service holds the profile lock; refusing offline access"
1717
+ );
1718
+ throw error;
1719
+ }
1720
+ const auth = new AuthService(store, { requireTotp: false, sessionHours: 168 });
1721
+ try {
1722
+ switch (request.command) {
1723
+ case "status":
1724
+ return { ...auth.status(), online: false, ready: false };
1725
+ case "init":
1726
+ await auth.initialize(request.username, request.password);
1727
+ return { ok: true };
1728
+ case "reset-password":
1729
+ await auth.resetPassword(request.password);
1730
+ return { ok: true };
1731
+ case "reset-totp":
1732
+ await auth.resetTotp();
1733
+ return { ok: true };
1734
+ case "revoke-sessions":
1735
+ await auth.revokeAll();
1736
+ return { ok: true };
1737
+ }
1738
+ } finally {
1739
+ auth.dispose();
1740
+ await store.close();
1741
+ }
1742
+ }
1743
+ async function execute(target, request) {
1744
+ try {
1745
+ return await requestAdmin(target.socketPath, request);
1746
+ } catch (error) {
1747
+ if (!(error instanceof AdminUnavailable)) throw error;
1748
+ return offline(target, request);
1749
+ }
1750
+ }
1751
+ async function interactiveRequest(target, command) {
1752
+ const prompt = new TerminalPrompt();
1753
+ try {
1754
+ if (command === "init") {
1755
+ const username = await prompt.ask(output("cliPromptUsername"), false, 64);
1756
+ const password = await prompt.ask(output("cliPromptPassword"), true, 256);
1757
+ const again = await prompt.ask(output("cliPromptPasswordAgain"), true, 256);
1758
+ if (password !== again)
1759
+ throw new CliDiagnostic(
1760
+ "cliErrorPasswordsMismatch",
1761
+ "dsh-auth-remote: passwords do not match"
1762
+ );
1763
+ validatePassword(password);
1764
+ return { version: ADMIN_PROTOCOL_VERSION, command, username, password };
1765
+ }
1766
+ const confirmation = await prompt.ask(
1767
+ output("cliPromptConfirmTarget", { profile: target.name, command }),
1768
+ false,
1769
+ 64
1770
+ );
1771
+ if (confirmation !== target.name)
1772
+ throw new CliDiagnostic(
1773
+ "cliErrorConfirmationMismatch",
1774
+ "dsh-auth-remote: confirmation did not match the target profile"
1775
+ );
1776
+ if (command === "reset-password") {
1777
+ const password = await prompt.ask(output("cliPromptNewPassword"), true, 256);
1778
+ const again = await prompt.ask(output("cliPromptNewPasswordAgain"), true, 256);
1779
+ if (password !== again)
1780
+ throw new CliDiagnostic(
1781
+ "cliErrorPasswordsMismatch",
1782
+ "dsh-auth-remote: passwords do not match"
1783
+ );
1784
+ validatePassword(password);
1785
+ return { version: ADMIN_PROTOCOL_VERSION, command, password };
1786
+ }
1787
+ return { version: ADMIN_PROTOCOL_VERSION, command };
1788
+ } finally {
1789
+ prompt.close();
1790
+ }
1791
+ }
1792
+ async function main() {
1793
+ const parsed = parseLanguage(process.argv.slice(2));
1794
+ currentLocale = parsed.locale;
1795
+ const args = parsed.args;
1796
+ if (args.length === 0 || args.length === 1 && ["--help", "-h"].includes(args[0])) {
1797
+ process.stdout.write(output("cliHelp", { version: manifest.version }));
1798
+ return;
1799
+ }
1800
+ if (args.length === 1 && ["--version", "-v"].includes(args[0])) {
1801
+ process.stdout.write(`${manifest.version}
1802
+ `);
1803
+ return;
1804
+ }
1805
+ const command = args[0];
1806
+ if (!["init", "status", "reset-password", "reset-totp", "revoke-sessions"].includes(
1807
+ command ?? ""
1808
+ ) || (command === "status" ? args.length > 2 || args.length === 2 && args[1] !== "--json" : args.length !== 1))
1809
+ throw new CliDiagnostic(
1810
+ "cliErrorInvalidArguments",
1811
+ "dsh-auth-remote: invalid command or arguments; use --help"
1812
+ );
1813
+ const target = await resolveProfileTarget();
1814
+ if (command !== "status")
1815
+ process.stdout.write(
1816
+ `${output("cliTargetProfile", { profile: target.name })}
1817
+ ${output("cliDataFile", { path: target.statePath })}
1818
+ `
1819
+ );
1820
+ const request = command === "status" ? { version: ADMIN_PROTOCOL_VERSION, command: "status" } : await interactiveRequest(target, command);
1821
+ const result = await execute(target, request);
1822
+ if (command === "status") {
1823
+ const status = result;
1824
+ if (args[1] === "--json")
1825
+ process.stdout.write(
1826
+ `${JSON.stringify({ profile: target.name, statePath: target.statePath, ...status })}
1827
+ `
1828
+ );
1829
+ else
1830
+ process.stdout.write(
1831
+ [
1832
+ output("cliStatusProfile", { profile: target.name }),
1833
+ output("cliDataFile", { path: target.statePath }),
1834
+ output("cliStatusAccount", {
1835
+ state: output(status.initialized ? "cliInitialized" : "cliNotInitialized")
1836
+ }),
1837
+ output("cliStatusTotp", {
1838
+ state: output(status.totpEnabled ? "cliTotpEnabled" : "cliTotpDisabled")
1839
+ }),
1840
+ output("cliStatusSessions", { count: status.activeSessions }),
1841
+ output("cliStatusService", {
1842
+ state: output(
1843
+ status.online ? status.ready ? "cliOnlineReady" : "cliOnlineNotReady" : "cliOffline"
1844
+ )
1845
+ })
1846
+ ].join("\n") + "\n"
1847
+ );
1848
+ return;
1849
+ }
1850
+ process.stdout.write(`${output("cliCompleted", { command })}
1851
+ `);
1852
+ }
1853
+ void main().catch((error) => {
1854
+ process.stderr.write(`${errorText(error, currentLocale)}
1855
+ `);
1856
+ process.exitCode = 1;
1857
+ });
1858
+ //# sourceMappingURL=cli.js.map