Repository navigation
Expand file tree
/
Copy pathaccounts.ts
More file actions
117 lines (104 loc) · 4.17 KB
/
Copy pathaccounts.ts
File metadata and controls
117 lines (104 loc) · 4.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import fs from 'fs';
import type { Stats } from 'fs';
import path from 'path';
import { homedir } from 'os';
import { ParsedKey, utils } from 'ssh2';
export type AccountConfig = {
keys: ParsedKey[];
// Connection ids / aliases this account may access. '*' grants all.
// The root account always has access and is not listed here.
servers: string[];
};
// ~/.ssh/accounts.json format:
// {
// "alice": { "keys": ["ssh-ed25519 AAAA... comment"], "servers": ["web01", "client-id"] }
// }
// root is implicit: its keys come from authorized_keys (plus any "root" entry here).
export class AccountsStore {
private accounts = new Map<string, AccountConfig>();
private reloadTimer: NodeJS.Timeout | null = null;
private watching = false;
constructor(
public readonly filePath: string,
private readonly watchInterval = 500,
) { }
keysOf(username: string): ParsedKey[] {
return this.accounts.get(username)?.keys ?? [];
}
canAccess(username: string, connectionId: string, alias: string): boolean {
if (username === 'root') return true;
const servers = this.accounts.get(username)?.servers ?? [];
return servers.includes('*')
|| servers.includes(connectionId)
|| (!!alias && servers.includes(alias));
}
reload(initial = false) {
let raw = '';
try {
raw = fs.readFileSync(this.filePath, 'utf-8');
} catch (e: any) {
if (e?.code !== 'ENOENT') {
console.error(`[!] Failed to reload accounts from ${this.filePath}: ${e.message}`);
return;
}
}
const next = new Map<string, AccountConfig>();
let invalidCount = 0;
try {
const obj = raw ? JSON.parse(raw) : {};
for (const [name, cfg] of Object.entries(obj as Record<string, any>)) {
if (!name || !cfg || typeof cfg !== 'object' || name === 'guest') continue;
const keys: ParsedKey[] = [];
for (const keyText of Array.isArray(cfg.keys) ? cfg.keys : []) {
if (typeof keyText !== 'string') { invalidCount++; continue; }
const parsed = utils.parseKey(keyText.trim());
if (parsed instanceof Error) { invalidCount++; continue; }
keys.push(parsed);
}
const servers = Array.isArray(cfg.servers)
? cfg.servers.filter((s: unknown): s is string => typeof s === 'string' && !!s)
: [];
next.set(name, { keys, servers });
}
} catch (e: any) {
console.error(`[!] Failed to parse ${this.filePath}: ${e.message}`);
return;
}
this.accounts = next;
const action = initial ? 'Loaded' : 'Reloaded';
console.log(`[*] ${action} ${next.size} account(s) from ${this.filePath}`);
if (invalidCount > 0) {
console.error(`[!] Ignored ${invalidCount} invalid key line(s) in ${this.filePath}`);
}
}
startWatching() {
if (this.watching) return;
this.watching = true;
this.reload(true);
fs.watchFile(this.filePath, { interval: this.watchInterval }, this.handleFileChange);
}
stopWatching() {
if (!this.watching) return;
this.watching = false;
if (this.reloadTimer) {
clearTimeout(this.reloadTimer);
this.reloadTimer = null;
}
fs.unwatchFile(this.filePath, this.handleFileChange);
}
private handleFileChange = (current: Stats, previous: Stats) => {
const changed = current.mtimeMs !== previous.mtimeMs
|| current.ctimeMs !== previous.ctimeMs
|| current.size !== previous.size
|| current.ino !== previous.ino
|| current.nlink !== previous.nlink;
if (!changed) return;
if (this.reloadTimer) clearTimeout(this.reloadTimer);
this.reloadTimer = setTimeout(() => {
this.reloadTimer = null;
this.reload();
}, 100);
};
}
export const accounts = new AccountsStore(path.join(homedir(), '.ssh', 'accounts.json'));
accounts.startWatching();