Files
BetterDesk/web-nodejs/lib/agentTemplates.js
T
UNITRONIX 790b65fd32 fix(enrollment): keep stock clients and Support Agents able to enroll (C1 follow-up)
Hardening device registration must not lock out the clients the product is built
for. Stock RustDesk clients and Support Agents cannot produce an Ed25519
signature, so `POST /api/bd/register` now accepts three equivalent proofs of
admission instead of demanding a signature:

1. an `approved` row in `pending_registrations` for this exact device id
   (operator clicked Approve in the Registrations tab),
2. a single-use enrollment token issued by `POST /api/bd/enroll`,
3. an Ed25519 proof of possession of the key being bound.

Banned and soft-deleted ids are still refused before any write, and an existing
device's key/uuid can only be rotated by the key it already has — admission
proves identity, not ownership of an established identity. The refusal is a
single neutral error (`403 enrollment_proof_required`) so a caller cannot probe
which admission method is missing.

Verified end to end on the test host: register before approval -> 403
enrollment_proof_required; register-request -> pending; operator approval;
register with no signature -> 200; template + enroll -> 200; register with the
token -> 200; a second device reusing the same token -> 403.

Also fixed, because it silently broke this same model:

- `POST /api/bd/enroll` and the agent-template tab called `db.get()` /
  `db.query()`, which the database facade never exposed, so every enrollment
  token answered 401. Added `listAgentTemplates` / `getAgentTemplateByToken` /
  `createAgentTemplate` to both adapters and `lib/agentTemplates.js`.
- PostgreSQL installs had no `agent_templates` table (it only existed in SQLite
  auth.db). It is now created by the adapter schema on both backends with
  `enrolled_device_id` / `enrolled_at`, so a token is single-use and bound to one
  device.

Tests: `tests/bd-register.enrollment.test.js` (8 cases covering approval,
pending, rejected, token, token reuse, no-admission, later heartbeats and
removed devices) plus the existing hardening suite (11 cases).

Thanks: INSOLVE (Honorary); Marco Jakobs (@jacotec); MyNameisStitch (@MyNameisStitch); Redspin (@playerumpknow); muopc (@muopc)
2026-11-13 21:45:07 +01:00

99 lines
3.4 KiB
JavaScript

'use strict';
/**
* Agent template (enrollment token) store.
*
* Templates hold the single-use enrollment token an operator hands to a Support
* Agent. Backend-agnostic: SQLite keeps them in `auth.db` beside users/groups,
* PostgreSQL keeps them in the single console database. Both schemas are created
* by the adapter, so this module only queries.
*
* History (2026-11-13): the routes called `db.get()` / `db.query()`, which the
* database facade never exposed, so `POST /api/bd/enroll` could never find a
* token and always answered 401 — and the template tab returned nothing on
* PostgreSQL, which had no `agent_templates` table at all.
*/
const crypto = require('crypto');
const TABLE = 'agent_templates';
/** True when the adapter talks to PostgreSQL. */
function isPostgres(adapter) {
return Boolean(adapter && String(adapter.type || '').toLowerCase() === 'postgres');
}
/**
* Run one query through whichever raw accessor the adapter exposes.
* Both adapters implement the domain methods below, so this is only a fallback.
*/
async function queryOne(adapter, sql, params) {
if (typeof adapter.getAgentTemplateByToken === 'function') {
return adapter.getAgentTemplateByToken(params[0]);
}
return null;
}
/**
* @param {object} adapter database adapter
* @param {string} token
* @returns {Promise<{ id:number, name:string, config_json:string,
* enrolled_device_id:string|null }|null>}
*/
async function findByEnrollmentToken(adapter, token) {
const clean = String(token || '').trim();
if (!clean || clean.length > 64) return null;
if (!adapter || typeof adapter.getAgentTemplateByToken !== 'function') return null;
try {
return await adapter.getAgentTemplateByToken(clean);
} catch (err) {
console.warn('[agentTemplates] lookup failed:', err.message);
return null;
}
}
/**
* Bind a token to the device redeeming it. A token is single-use: once bound it
* only admits the same device again, so a leaked token cannot enrol a second
* machine.
*
* @returns {Promise<{ ok: boolean, boundTo: string }>}
*/
async function redeemEnrollmentToken(adapter, token, deviceId) {
const clean = String(token || '').trim();
const device = String(deviceId || '').trim();
if (!clean || !device || !adapter) return { ok: false, boundTo: '' };
const row = await findByEnrollmentToken(adapter, clean);
if (!row) return { ok: false, boundTo: '' };
const boundTo = String(row.enrolled_device_id || '').trim();
if (boundTo) return { ok: boundTo === device, boundTo };
if (typeof adapter.bindAgentTemplateDevice !== 'function') {
// Older adapter: admit without single-use binding rather than lock the
// agent out, but leave a trace so the gap is visible in the log.
console.warn('[agentTemplates] adapter cannot bind tokens; single-use enforcement skipped');
return { ok: true, boundTo: '' };
}
try {
await adapter.bindAgentTemplateDevice(clean, device);
return { ok: true, boundTo: device };
} catch (err) {
console.warn('[agentTemplates] bind failed:', err.message);
return { ok: false, boundTo: '' };
}
}
function generateEnrollmentToken() {
return crypto.randomBytes(24).toString('hex');
}
module.exports = {
TABLE,
isPostgres,
findByEnrollmentToken,
redeemEnrollmentToken,
generateEnrollmentToken,
};