-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig-panel.js
More file actions
168 lines (149 loc) · 5.64 KB
/
Copy pathconfig-panel.js
File metadata and controls
168 lines (149 loc) · 5.64 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const ENV_PATH = path.join(__dirname, '.env');
const ENV_EXAMPLE_PATH = path.join(__dirname, '.env.example');
const COMMON_FIELDS = [
{ key: 'PORT', label: 'Web port', type: 'number', restart: true },
{ key: 'ADMIN_USERNAME', label: 'Admin username', type: 'text', restart: false },
{ key: 'DB_PATH', label: 'Database path', type: 'text', restart: true },
{ key: 'ALLOWED_ORIGINS', label: 'Allowed origins', type: 'text', restart: true },
];
const SECRET_FIELDS = ['JWT_SECRET', 'CONTROL_INTERNAL_TOKEN'];
function projectFields(projectName) {
if (projectName === 'mac-files') {
return [
...COMMON_FIELDS,
{ key: 'FINDER_ROOT', label: 'Finder root', type: 'text', restart: true },
];
}
return [
...COMMON_FIELDS,
{ key: 'MAC_CONTROLLER_HOST', label: 'Controller host', type: 'text', restart: true },
{ key: 'MAC_CONTROLLER_PORT', label: 'Controller port', type: 'number', restart: true },
{ key: 'CONTROL_AUTO_START', label: 'Auto-start controller', type: 'boolean', restart: true },
{ key: 'CONTROL_URL', label: 'Controller URL override', type: 'text', restart: true },
];
}
function readEnvFile(filePath) {
if (!fs.existsSync(filePath)) return {};
const env = {};
const raw = fs.readFileSync(filePath, 'utf8');
for (const line of raw.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const idx = trimmed.indexOf('=');
if (idx === -1) continue;
const key = trimmed.slice(0, idx).trim();
let value = trimmed.slice(idx + 1).trim();
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
env[key] = value;
}
return env;
}
function quoteEnvValue(value) {
const str = String(value ?? '');
if (!str || /[\s#"'\\]/.test(str)) {
return JSON.stringify(str);
}
return str;
}
function writeEnvFile(values) {
const orderedKeys = [
'PORT',
'JWT_SECRET',
'ADMIN_USERNAME',
'DB_PATH',
'ALLOWED_ORIGINS',
'FINDER_ROOT',
'MAC_CONTROLLER_HOST',
'MAC_CONTROLLER_PORT',
'CONTROL_AUTO_START',
'CONTROL_URL',
'CONTROL_INTERNAL_TOKEN',
];
const keys = [...orderedKeys.filter(k => Object.prototype.hasOwnProperty.call(values, k)), ...Object.keys(values).filter(k => !orderedKeys.includes(k)).sort()];
const lines = ['# Generated by the local configuration panel. Restart the app after changing restart-required settings.'];
for (const key of keys) {
lines.push(`${key}=${quoteEnvValue(values[key])}`);
}
fs.writeFileSync(ENV_PATH, `${lines.join('\n')}\n`, { mode: 0o600 });
}
function ensureEnvFile(projectName) {
if (fs.existsSync(ENV_PATH)) return false;
const values = readEnvFile(ENV_EXAMPLE_PATH);
values.JWT_SECRET = randomSecret();
if (projectName !== 'mac-files') {
values.CONTROL_INTERNAL_TOKEN = randomSecret();
}
writeEnvFile(values);
return true;
}
function randomSecret() {
return crypto.randomBytes(32).toString('hex');
}
function mergedEnv(projectName) {
return {
...projectDefaults(projectName),
...readEnvFile(ENV_EXAMPLE_PATH),
...readEnvFile(ENV_PATH),
};
}
function projectDefaults(projectName) {
if (projectName === 'mac-terminal') return { PORT: '3301', MAC_CONTROLLER_PORT: '5051' };
if (projectName === 'mac-files') return { PORT: '3302' };
if (projectName === 'mac-control') return { PORT: '3303', MAC_CONTROLLER_PORT: '5053' };
return {};
}
function getConfig(projectName) {
const values = mergedEnv(projectName);
const fields = projectFields(projectName).map(field => ({
...field,
value: Object.prototype.hasOwnProperty.call(values, field.key) ? values[field.key] : '',
}));
const secrets = SECRET_FIELDS
.filter(key => projectName !== 'mac-files' || key !== 'CONTROL_INTERNAL_TOKEN')
.map(key => ({ key, configured: Boolean(values[key]), masked: values[key] ? 'configured' : 'missing' }));
return {
fields,
secrets,
envPath: ENV_PATH,
envExists: fs.existsSync(ENV_PATH),
restartRequired: true,
};
}
function normalizeValue(field, value) {
if (field.type === 'boolean') return value === true || value === 'true' ? 'true' : 'false';
if (field.type === 'number') {
const n = Number(value);
if (!Number.isFinite(n) || n < 0 || n > 65535) throw new Error(`${field.key} must be a valid port or non-negative number`);
return String(Math.trunc(n));
}
return String(value ?? '').trim();
}
function saveConfig(projectName, payload = {}) {
const current = { ...readEnvFile(ENV_EXAMPLE_PATH), ...readEnvFile(ENV_PATH) };
const allowed = new Map(projectFields(projectName).map(field => [field.key, field]));
const input = payload.fields && typeof payload.fields === 'object' ? payload.fields : {};
for (const [key, value] of Object.entries(input)) {
const field = allowed.get(key);
if (!field) continue;
current[key] = normalizeValue(field, value);
}
const rotate = Array.isArray(payload.rotateSecrets) ? payload.rotateSecrets : [];
if (rotate.includes('JWT_SECRET')) current.JWT_SECRET = randomSecret();
if (projectName !== 'mac-files' && rotate.includes('CONTROL_INTERNAL_TOKEN')) {
current.CONTROL_INTERNAL_TOKEN = randomSecret();
}
if (!current.JWT_SECRET || current.JWT_SECRET === 'change-this-long-random-secret') {
current.JWT_SECRET = randomSecret();
}
if (projectName !== 'mac-files' && !current.CONTROL_INTERNAL_TOKEN) {
current.CONTROL_INTERNAL_TOKEN = randomSecret();
}
writeEnvFile(current);
return getConfig(projectName);
}
module.exports = { ensureEnvFile, getConfig, saveConfig };