Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions packages/installer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,28 @@ npx @fleetbase/installer --directory ./fleetbase --environment production --host
| `--app-name <name>` | Application name (default: Fleetbase) |
| `--non-interactive` | Skip every prompt; flags and safe defaults only |

## Socket authentication

The installer writes the realtime socket authentication settings to the project-root `.env`, next to
`docker-compose.yml`. Compose passes them to the application, queue, scheduler and socket containers;
setting them only in `api/.env` has no effect. Every value already in `.env` is kept on re-runs, and
other lines are left untouched (the file is written with mode 600).

| Variable | Default | Meaning |
| --- | --- | --- |
| `SOCKETCLUSTER_AUTH_KEY` | 64 random hex characters | Shared secret between the API and the socket server. A key of 32+ characters is kept, since changing it invalidates socket tokens already issued |
| `SOCKETCLUSTER_AUTH_ENABLED` | `false` | Turns socket authentication on for the API (socket token routes, the authorize endpoint, signed HTTP publishing) and the socket server. While it is off nothing is authenticated, the token routes answer 404, and the API publishes over the legacy websocket path, so clients that don't fetch socket tokens yet keep working |
| `SOCKETCLUSTER_AUTH_MODE` | `log` | `off`, `log` or `enforce`; takes effect once the switch is on. `enforce` needs `SOCKETCLUSTER_AUTH_ENABLED=true`, since an enforcing socket server refuses the legacy publish path |
| `SOCKETCLUSTER_ORIGIN` | the console origin (`http://localhost:4200` on localhost, `<scheme>://<host>` otherwise) | The `Origin` the API sends when it publishes over the websocket. Without it the socket server refuses every broadcast with `Invalid origin: *` |

These match the fleetbase repo's `scripts/docker-install.sh`. To turn authentication on:

1. Ship clients that fall back to an anonymous connection when the token route answers 404.
2. Set `SOCKETCLUSTER_AUTH_ENABLED=true` with `SOCKETCLUSTER_AUTH_MODE=log`.
3. Switch to `enforce` once the socket server's deny log only shows traffic you expect to lose.

Restart the containers after editing `.env`. The socket's allowed origins (`SOCKETCLUSTER_OPTIONS`) are still written to
`docker-compose.override.yml`.

This was `flb install-fleetbase` in `@fleetbase/cli` up to 0.0.7. The CLI now only covers
the extensions registry; `flb install-fleetbase` prints a pointer here.
100 changes: 99 additions & 1 deletion packages/installer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,96 @@ async function ensureApiEnvFile(directory) {
console.log('✔ api/.env created');
}

/**
* Write the realtime socket auth settings to the project-root .env file.
* docker-compose.yml reads SOCKETCLUSTER_AUTH_KEY, SOCKETCLUSTER_AUTH_ENABLED, SOCKETCLUSTER_AUTH_MODE
* and SOCKETCLUSTER_ORIGIN from this file (Compose loads it automatically) and hands them to the
* application, queue, scheduler and socket containers; setting them in api/.env has no effect.
*
* Fresh installs get the switch off (SOCKETCLUSTER_AUTH_ENABLED=false) and mode `log`, the same as
* the fleetbase repo's scripts/docker-install.sh: the key is provisioned, but clients that don't
* fetch socket tokens yet (released mobile apps, integrations) keep working until the switch is
* turned on. While it is off the API publishes over the legacy websocket path, so `enforce` needs
* the switch on.
*
* An existing key of at least 32 characters is kept across re-runs, because changing it would
* invalidate every socket token already handed out. An existing switch value, mode and origin are
* kept too, and other lines in the file are left untouched.
*
* SOCKETCLUSTER_ORIGIN is the Origin header the API's websocket publisher sends. Without it the
* socket server sees `*` and, with restricted SOCKETCLUSTER_OPTIONS origins, refuses every
* broadcast with "Invalid origin: *". It defaults to `defaultOrigin`, which must be one of the
* origins written to SOCKETCLUSTER_OPTIONS.
*
* @param {string} directory resolved installation directory
* @param {string} defaultOrigin console origin allowed by SOCKETCLUSTER_OPTIONS
* @returns {Promise<{ envPath: string, enabled: string, mode: string, origin: string, summary: string, generated: boolean }>}
*/
async function ensureSocketAuthEnv(directory, defaultOrigin = '') {
const crypto = require('crypto');
const envPath = path.join(directory, '.env');

let lines = [];
if (await fs.pathExists(envPath)) {
const stat = await fs.stat(envPath);
if (stat.isDirectory()) {
throw new Error(`${envPath} is a directory; remove it and re-run the installer.`);
}
lines = (await fs.readFile(envPath, 'utf8')).split(/\r?\n/);
if (lines.length && lines[lines.length - 1] === '') lines.pop();
}

// Last KEY=value in the file wins (as in Compose), with surrounding quotes stripped.
const readValue = (key) => {
const pattern = new RegExp(`^\\s*${key}=(.*)$`);
let value = '';
for (const line of lines) {
const match = line.match(pattern);
if (match) value = match[1].trim().replace(/^(['"])(.*)\1$/, '$2');
}
return value;
};

let authKey = readValue('SOCKETCLUSTER_AUTH_KEY');
let generated = false;
if (authKey.length >= 32) {
console.log('✔ Keeping the existing socket auth key from .env');
} else {
if (authKey) {
console.warn(' ⚠ The socket auth key in .env is shorter than 32 characters; generating a new one.');
}
authKey = crypto.randomBytes(32).toString('hex'); // 64 hex characters
generated = true;
console.log('✔ Socket auth key generated');
}
const enabled = readValue('SOCKETCLUSTER_AUTH_ENABLED') || 'false';
const mode = readValue('SOCKETCLUSTER_AUTH_MODE') || 'log';
const origin = readValue('SOCKETCLUSTER_ORIGIN') || defaultOrigin;
const switchedOn = /^(true|1|yes|on)$/i.test(enabled);

const managed = /^\s*SOCKETCLUSTER_(AUTH_KEY|AUTH_ENABLED|AUTH_MODE|ORIGIN)=/;
const output = lines.filter((line) => !managed.test(line));
output.push(
`SOCKETCLUSTER_AUTH_KEY=${authKey}`,
`SOCKETCLUSTER_AUTH_ENABLED=${enabled}`,
`SOCKETCLUSTER_AUTH_MODE=${mode}`,
...(origin ? [`SOCKETCLUSTER_ORIGIN=${origin}`] : []),
''
);

await fs.writeFile(envPath, output.join('\n'), { mode: 0o600 });
try {
await fs.chmod(envPath, 0o600);
} catch {
// best effort, e.g. on Windows
}
const summary = switchedOn ? `on, mode: ${mode}` : 'off until SOCKETCLUSTER_AUTH_ENABLED=true';
console.log(`✔ Socket auth written to .env (${summary})`);
if (origin) console.log(`✔ API publisher origin: ${origin}`);

return { envPath, enabled, mode, origin, summary, generated };
}

// Command to install Fleetbase via Docker
async function installFleetbaseCommand(options) {
const crypto = require('crypto');
Expand Down Expand Up @@ -367,6 +457,9 @@ async function installFleetbaseCommand(options) {
? 'http://localhost:*,https://localhost:*,ws://localhost:*,wss://localhost:*'
: `${schemeConsole}://${host}:*,wss://${host}:*`;
const socketClusterOptions = JSON.stringify({ origins: socketOrigins });
// Origin the API publisher sends; the socket server matches hostname + port
// against the entries above (e.g. "localhost:*"), so it must fall inside them.
const socketPublisherOrigin = isLocalhost ? 'http://localhost:4200' : `${schemeConsole}://${host}`;
console.log(`✔ SESSION_DOMAIN set to: ${sessionDomain}`);
console.log(`✔ WebSocket origins restricted to: ${socketOrigins}`);

Expand Down Expand Up @@ -408,6 +501,10 @@ async function installFleetbaseCommand(options) {
const appKey = 'base64:' + crypto.randomBytes(32).toString('base64');
console.log('✔ APP_KEY generated');

// ── Step 8b: Socket authentication key (project-root .env) ───────────
console.log('\n⏳ Configuring socket authentication...');
const socketAuth = await ensureSocketAuthEnv(directory, socketPublisherOrigin);

// ── Step 9: Write docker-compose.override.yml ─────────────────────────
console.log('⏳ Writing docker-compose.override.yml...');

Expand Down Expand Up @@ -600,6 +697,7 @@ ${buildEnvBlock(dbEnvVars)}
mailSetup.configure ? `Mail (${mailConfig.mailMailer})` : null,
storageChoice.driver !== 'public' ? `Storage (${storageChoice.driver.toUpperCase()})` : null,
'WebSocket security (origins restricted)',
`Socket authentication (${socketAuth.summary}; key in .env)`,
thirdPartySetup.configure ? 'Third-party APIs' : null,
].filter(Boolean);

Expand Down Expand Up @@ -658,4 +756,4 @@ if (require.main === module) {
program.parse(process.argv);
}

module.exports = { installFleetbaseCommand, buildEnvBlock, isPortAvailable };
module.exports = { installFleetbaseCommand, buildEnvBlock, isPortAvailable, ensureSocketAuthEnv };
84 changes: 83 additions & 1 deletion packages/installer/test/installer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ const assert = require('node:assert');
const { execFileSync } = require('node:child_process');
const path = require('node:path');
const test = require('node:test');
const { buildEnvBlock } = require('..');
const fs = require('node:fs');
const os = require('node:os');
const { buildEnvBlock, ensureSocketAuthEnv } = require('..');

const bin = path.join(__dirname, '..', 'index.js');

Expand All @@ -21,3 +23,83 @@ test('--version prints the package version', () => {
test('buildEnvBlock drops empty values and quotes the rest', () => {
assert.strictEqual(buildEnvBlock({ A: 'x', B: '', C: null, D: 3 }, 2), ' A: "x"\n D: "3"');
});

function tempDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'fleetbase-installer-'));
}

// The installer logs progress; keep it out of the test runner's stdout.
function quiet(t) {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
}

function readEnv(dir) {
return fs.readFileSync(path.join(dir, '.env'), 'utf8');
}

test('ensureSocketAuthEnv writes a new key with auth switched off', async (t) => {
quiet(t);
const dir = tempDir();
const result = await ensureSocketAuthEnv(dir, 'http://localhost:4200');
const env = readEnv(dir);

assert.match(env, /^SOCKETCLUSTER_AUTH_KEY=[0-9a-f]{64}$/m);
assert.match(env, /^SOCKETCLUSTER_AUTH_ENABLED=false$/m);
assert.match(env, /^SOCKETCLUSTER_AUTH_MODE=log$/m);
assert.match(env, /^SOCKETCLUSTER_ORIGIN=http:\/\/localhost:4200$/m);
assert.strictEqual(result.generated, true);
assert.strictEqual(result.summary, 'off until SOCKETCLUSTER_AUTH_ENABLED=true');
if (process.platform !== 'win32') {
assert.strictEqual(fs.statSync(path.join(dir, '.env')).mode & 0o777, 0o600);
}
});

test('ensureSocketAuthEnv keeps an existing key, switch, mode, origin and other lines', async (t) => {
quiet(t);
const dir = tempDir();
const key = 'a'.repeat(40);
fs.writeFileSync(path.join(dir, '.env'), [
'OTHER=1',
'SOCKETCLUSTER_AUTH_KEY=short',
`SOCKETCLUSTER_AUTH_KEY="${key}"`,
'SOCKETCLUSTER_AUTH_ENABLED=true',
'SOCKETCLUSTER_AUTH_MODE=enforce',
'SOCKETCLUSTER_ORIGIN=https://fleet.example.com',
'',
].join('\n'));

const result = await ensureSocketAuthEnv(dir, 'http://localhost:4200');
const env = readEnv(dir);

assert.strictEqual(result.generated, false);
assert.strictEqual(result.summary, 'on, mode: enforce');
assert.strictEqual(env, [
'OTHER=1',
`SOCKETCLUSTER_AUTH_KEY=${key}`,
'SOCKETCLUSTER_AUTH_ENABLED=true',
'SOCKETCLUSTER_AUTH_MODE=enforce',
'SOCKETCLUSTER_ORIGIN=https://fleet.example.com',
'',
].join('\n'));
});

test('ensureSocketAuthEnv replaces a key shorter than 32 characters', async (t) => {
quiet(t);
const dir = tempDir();
fs.writeFileSync(path.join(dir, '.env'), 'SOCKETCLUSTER_AUTH_KEY=tooshort\n');

const result = await ensureSocketAuthEnv(dir);

assert.strictEqual(result.generated, true);
assert.match(readEnv(dir), /^SOCKETCLUSTER_AUTH_KEY=[0-9a-f]{64}$/m);
assert.doesNotMatch(readEnv(dir), /SOCKETCLUSTER_ORIGIN/);
});

test('ensureSocketAuthEnv refuses a .env directory', async (t) => {
quiet(t);
const dir = tempDir();
fs.mkdirSync(path.join(dir, '.env'));

await assert.rejects(ensureSocketAuthEnv(dir), /is a directory/);
});
Loading