Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): keep live listeners off-limits; reject unpersistable port edits

[._.]/ Adam Eivy79936cb03b05
diff --git a/server/routes/apps.js b/server/routes/apps.js
index e82cdcc4d1..2fa0cb2326 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -392,30 +392,41 @@ router.put('/:id', asyncHandler(async (req, res, next) => {
// Count current values so a value-keyed rewrite never fires on a number
// shared by another port field (e.g. uiPort derived from apiPort, both
// 6000) — that would rewrite every occurrence and clobber the field the
- // user didn't touch.
+ // user didn't touch. Such a change is unpersistable by value alone.
const valueCounts = new Map();
for (const key of PORT_KEYS) {
const v = existing[key];
if (Number.isInteger(v)) valueCounts.set(v, (valueCounts.get(v) || 0) + 1);
}
+ // A port the user actually changed (valid new value, differs from current).
+ const changedKeys = PORT_KEYS.filter(key => Number.isInteger(data[key]) && data[key] !== existing[key]);
const remap = [];
- for (const key of PORT_KEYS) {
+ const unpersistable = [];
+ for (const key of changedKeys) {
const oldPort = existing[key];
- const newPort = data[key];
- if (!Number.isInteger(oldPort) || !Number.isInteger(newPort) || oldPort === newPort) continue;
- if (valueCounts.get(oldPort) > 1) {
- console.warn(`⚠️ Skipped ecosystem rewrite of ${key} for ${existing.name}: ${oldPort} is shared by another port — can't disambiguate by value`);
+ // No old literal to find (derived/absent), or value shared with another
+ // field (can't disambiguate by value) → can't write it to the config.
+ if (!Number.isInteger(oldPort) || valueCounts.get(oldPort) > 1) {
+ unpersistable.push(key);
continue;
}
- remap.push([oldPort, newPort]);
+ remap.push([oldPort, data[key]]);
}
- if (remap.length > 0) {
- const result = await writeEcosystemPorts(existing.repoPath, remap);
- if (result?.changed) {
- console.log(`🔧 Updated ${result.file} ports for ${existing.name}: ${remap.map(([o, n]) => `${o}→${n}`).join(', ')} (restart the app to apply)`);
- } else {
- console.warn(`⚠️ Port edit for ${existing.name} found no matching literal in ecosystem config — registry updated, but restart/refresh won't pick up the new port`);
- }
+
+ const result = remap.length > 0 ? await writeEcosystemPorts(existing.repoPath, remap) : { changed: false };
+ if (result.changed) {
+ console.log(`🔧 Updated ${result.file} ports for ${existing.name}: ${remap.map(([o, n]) => `${o}→${n}`).join(', ')} (restart the app to apply)`);
+ }
+
+ // Honesty gate: if the user changed a port we could NOT write to the
+ // source-of-truth config, reject the whole update rather than persist a
+ // registry value PM2 will contradict (and the next refresh will revert).
+ // `!result.changed` catches remap pairs whose literal wasn't found.
+ if (changedKeys.length > 0 && (unpersistable.length > 0 || (remap.length > 0 && !result.changed))) {
+ throw new ServerError(
+ `Could not persist port change to ${existing.name}'s ecosystem config — the port is shared with another field, derived from process config, or not a literal value. Edit the ecosystem.config.cjs directly to change this port.`,
+ { status: 422, code: 'PORT_NOT_PERSISTABLE' }
+ );
}
}
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index a9b19a0cc8..2b36d02bd3 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -285,17 +285,29 @@ describe('Apps Routes', () => {
expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();
});
- it('skips the rewrite when the changed port shares its value with another port field', async () => {
- // uiPort derived from apiPort — both 6000. Changing only uiPort must NOT
- // value-rewrite every 6000 (which would clobber the unchanged apiPort).
+ it('rejects (422) a port change that cannot be written to the config, leaving the registry untouched', async () => {
+ // uiPort derived from apiPort — both 6000. Changing only uiPort can't be
+ // value-rewritten without clobbering apiPort, so the request must fail
+ // rather than persist a registry value PM2 will contradict.
const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000 };
appsService.getAppById.mockResolvedValue(mockApp);
- appsService.updateApp.mockResolvedValue({ ...mockApp, uiPort: 7000 });
const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });
- expect(response.status).toBe(200);
+ expect(response.status).toBe(422);
expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();
+ expect(appsService.updateApp).not.toHaveBeenCalled();
+ });
+
+ it('rejects (422) when the port literal is not found in the config (changed:false)', async () => {
+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ streamingDetect.writeEcosystemPorts.mockResolvedValueOnce({ file: 'ecosystem.config.cjs', changed: false });
+
+ const response = await request(app).put('/api/apps/app-001').send({ apiPort: 6000 });
+
+ expect(response.status).toBe(422);
+ expect(appsService.updateApp).not.toHaveBeenCalled();
});
it('fails the request (and does not update the registry) when the config write throws', async () => {
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index 87e72f3ef3..f07260f90e 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -136,10 +136,16 @@ async function gatherTakenPorts(excludePorts = []) {
getReservedPorts().catch(() => []),
getListeningPorts().catch(() => []),
]);
+ // Exempt the app's own ports ONLY from the reserved-app registry — so
+ // re-standardizing keeps them. Do NOT exempt them from `listening`: if the
+ // app is stopped and another process now holds one of its old ports, that
+ // port is genuinely occupied and must stay off-limits regardless of which app
+ // recorded it. (Vite defaults are likewise never exempted — moving off them
+ // is the point.)
const own = new Set(excludePorts.filter(Number.isInteger));
- return Array.from(new Set([...reserved, ...listening, ...VITE_DEFAULT_PORTS]))
+ const reservedMinusOwn = reserved.filter((p) => !own.has(p));
+ return Array.from(new Set([...reservedMinusOwn, ...listening, ...VITE_DEFAULT_PORTS]))
.filter(Number.isInteger)
- .filter((p) => !own.has(p))
.sort((a, b) => a - b);
}