@dreamtree-org/harness-device 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,235 @@
1
+ // The OAuth 2.1 authorization server behind `harness-device serve`, for the
2
+ // MCP SDK's mcpAuthRouter: dynamic client registration, authorization code
3
+ // with PKCE (S256, checked by the SDK), rotating refresh tokens, revocation.
4
+ //
5
+ // The device owner approves each client on a consent page with the owner
6
+ // password (SERVE_OWNER_PASSWORD in secrets.env) and picks its scopes.
7
+ // Tokens are stored only as SHA-256 hashes in state/oauth.json (mode 600).
8
+
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { InvalidGrantError, InvalidTokenError, InvalidRequestError, AccessDeniedError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
13
+ import { SCOPES, known } from './scopes.js';
14
+
15
+ export const ACCESS_TTL = 3600; // s
16
+ export const REFRESH_TTL = 30 * 86400; // s
17
+ const CODE_TTL = 300; // s
18
+ const MAX_CLIENTS = 50;
19
+ const LOCK_AFTER = 5;
20
+ const LOCK_FOR = 15 * 60 * 1000;
21
+
22
+ const sha = (s) => crypto.createHash('sha256').update(String(s)).digest('hex');
23
+ const newToken = (kind) => `hd${kind}_${crypto.randomBytes(32).toString('base64url')}`;
24
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
25
+ const eqSecret = (a, b) => crypto.timingSafeEqual(Buffer.from(sha(a), 'hex'), Buffer.from(sha(b), 'hex'));
26
+
27
+ export class DeviceOAuth {
28
+ /**
29
+ * file: where clients and token hashes live.
30
+ * password(): the owner password now (read each time, so a rotation applies at once).
31
+ */
32
+ constructor({ file, password, device = 'device', now = () => Date.now() }) {
33
+ this.file = file;
34
+ this.password = password;
35
+ this.device = device;
36
+ this.now = now;
37
+ this.codes = new Map();
38
+ this.failures = [];
39
+ this.csrfKey = crypto.randomBytes(32);
40
+ this.db = this.load();
41
+ }
42
+
43
+ load() {
44
+ try {
45
+ const d = JSON.parse(fs.readFileSync(this.file, 'utf8'));
46
+ return { clients: d.clients || {}, access: d.access || {}, refresh: d.refresh || {} };
47
+ } catch {
48
+ return { clients: {}, access: {}, refresh: {} };
49
+ }
50
+ }
51
+
52
+ save() {
53
+ const t = this.now() / 1000;
54
+ for (const m of [this.db.access, this.db.refresh]) for (const [k, v] of Object.entries(m)) if (v.exp < t) delete m[k];
55
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
56
+ const tmp = `${this.file}.${process.pid}.tmp`;
57
+ fs.writeFileSync(tmp, JSON.stringify(this.db, null, 1), { mode: 0o600 });
58
+ fs.renameSync(tmp, this.file);
59
+ }
60
+
61
+ get clientsStore() {
62
+ return {
63
+ getClient: (id) => this.db.clients[id],
64
+ registerClient: (info) => {
65
+ this.pruneClients();
66
+ if (Object.keys(this.db.clients).length >= MAX_CLIENTS) throw new InvalidRequestError('Too many registered clients; revoke some with harness-device serve revoke');
67
+ const client = { ...info, client_id: crypto.randomUUID(), client_id_issued_at: Math.floor(this.now() / 1000) };
68
+ this.db.clients[client.client_id] = client;
69
+ this.save();
70
+ return client;
71
+ },
72
+ };
73
+ }
74
+
75
+ /** Registration is open (MCP clients register themselves): drop clients never approved within a day. */
76
+ pruneClients() {
77
+ const t = this.now() / 1000;
78
+ const used = new Set([...Object.values(this.db.access), ...Object.values(this.db.refresh)].map((x) => x.clientId));
79
+ for (const [id, c] of Object.entries(this.db.clients)) if (!used.has(id) && !c.approved && t - (c.client_id_issued_at || 0) > 86400) delete this.db.clients[id];
80
+ }
81
+
82
+ locked() {
83
+ const t = this.now();
84
+ this.failures = this.failures.filter((x) => t - x < LOCK_FOR);
85
+ return this.failures.length >= LOCK_AFTER;
86
+ }
87
+
88
+ csrf(clientId, challenge, ts = this.now()) {
89
+ return `${ts.toString(36)}.${crypto.createHmac('sha256', this.csrfKey).update(`${clientId}\n${challenge}\n${ts}`).digest('base64url')}`;
90
+ }
91
+
92
+ csrfOk(token, clientId, challenge) {
93
+ const [t36] = String(token || '').split('.');
94
+ const ts = parseInt(t36, 36);
95
+ if (!Number.isFinite(ts) || this.now() - ts > 15 * 60 * 1000) return false;
96
+ const want = this.csrf(clientId, challenge, ts);
97
+ return want.length === String(token).length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(String(token)));
98
+ }
99
+
100
+ /** GET: the consent page. POST (from that page): check the password, then redirect with a code. */
101
+ async authorize(client, params, res) {
102
+ const req = res.req;
103
+ const body = req.method === 'POST' ? req.body || {} : {};
104
+ const offered = known(params.scopes).length ? known(params.scopes) : Object.keys(SCOPES);
105
+ if (req.method === 'POST' && body.decision === 'deny') throw new AccessDeniedError('The device owner denied access');
106
+ if (req.method === 'POST' && body.decision === 'allow') {
107
+ if (!this.csrfOk(body.csrf, client.client_id, params.codeChallenge)) return this.page(res, client, params, offered, 'This page expired. Start again from the app.', 400);
108
+ if (this.locked()) return this.page(res, client, params, offered, 'Too many wrong passwords. Try again in 15 minutes.', 429);
109
+ const pw = this.password();
110
+ if (!pw || typeof body.password !== 'string' || !eqSecret(body.password, pw)) {
111
+ this.failures.push(this.now());
112
+ return this.page(res, client, params, offered, 'Wrong password.', 401);
113
+ }
114
+ this.failures = [];
115
+ const grant = known([].concat(body.grant || [])).filter((s) => offered.includes(s));
116
+ if (!grant.length) return this.page(res, client, params, offered, 'Choose at least one permission.', 400);
117
+ const code = crypto.randomBytes(24).toString('base64url');
118
+ this.codes.set(sha(code), { clientId: client.client_id, challenge: params.codeChallenge, redirectUri: params.redirectUri, scopes: grant, resource: params.resource?.href, exp: this.now() + CODE_TTL * 1000 });
119
+ this.db.clients[client.client_id] = { ...client, approved: true };
120
+ this.save();
121
+ const to = new URL(params.redirectUri);
122
+ to.searchParams.set('code', code);
123
+ if (params.state !== undefined) to.searchParams.set('state', params.state);
124
+ return res.redirect(302, to.href);
125
+ }
126
+ return this.page(res, client, params, offered);
127
+ }
128
+
129
+ page(res, client, params, offered, error = '', status = 200) {
130
+ const hidden = {
131
+ client_id: client.client_id, redirect_uri: params.redirectUri, response_type: 'code', code_challenge: params.codeChallenge,
132
+ code_challenge_method: 'S256', ...(params.state !== undefined ? { state: params.state } : {}), ...(params.resource ? { resource: params.resource.href } : {}),
133
+ ...(params.scopes?.length ? { scope: params.scopes.join(' ') } : {}), csrf: this.csrf(client.client_id, params.codeChallenge),
134
+ };
135
+ let host = '';
136
+ let target = '';
137
+ try {
138
+ const u = new URL(params.redirectUri);
139
+ host = u.host;
140
+ // The form posts here, then redirects to the app: the CSP must allow that hop (custom schemes too).
141
+ target = u.host ? `${u.protocol}//${u.host}` : u.protocol;
142
+ } catch { /* shown as is */ }
143
+ res.status(status).set({ 'Content-Type': 'text/html; charset=utf-8', 'X-Frame-Options': 'DENY', 'Content-Security-Policy': `default-src 'none'; style-src 'unsafe-inline'; form-action 'self' ${target}`.trim() }).send(`<!doctype html>
144
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Allow access to ${esc(this.device)}</title>
145
+ <style>
146
+ :root{color-scheme:light dark;--bg:#f7f7f5;--fg:#1d1d1b;--muted:#6b6b66;--card:#fff;--line:#deded8;--accent:#2f5d50;--err:#a33}
147
+ @media (prefers-color-scheme:dark){:root{--bg:#141413;--fg:#ececea;--muted:#a3a39c;--card:#1f1f1d;--line:#33332f;--accent:#7fb8a4;--err:#e88}}
148
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,sans-serif;display:flex;justify-content:center;padding:24px 16px}
149
+ main{max-width:440px;width:100%;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:24px}
150
+ h1{font-size:20px;margin:0 0 4px}p{margin:0 0 16px;color:var(--muted)}label{display:flex;gap:10px;align-items:flex-start;margin:0 0 12px}
151
+ label small{display:block;color:var(--muted)}input[type=password]{width:100%;box-sizing:border-box;padding:10px;border:1px solid var(--line);border-radius:8px;background:transparent;color:inherit;font:inherit;margin:4px 0 16px}
152
+ .row{display:flex;gap:8px}button{flex:1;padding:10px;border-radius:8px;border:1px solid var(--line);font:inherit;cursor:pointer;background:transparent;color:inherit}
153
+ button.ok{background:var(--accent);border-color:var(--accent);color:var(--card)}.err{color:var(--err);margin:0 0 12px}
154
+ </style></head><body><main>
155
+ <h1>Allow ${esc(client.client_name || 'an app')} to use ${esc(this.device)}?</h1>
156
+ <p>It will reach this device's harness-device tools and send you back to <b>${esc(host || params.redirectUri)}</b>. Only allow apps you just connected yourself.</p>
157
+ ${error ? `<p class="err" role="alert">${esc(error)}</p>` : ''}
158
+ <form method="post">
159
+ ${Object.entries(hidden).map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join('\n')}
160
+ ${offered.map((s) => `<label><input type="checkbox" name="grant" value="${esc(s)}"${s === 'device:read' ? ' checked' : ''}><span><b>${esc(s)}</b><small>${esc(SCOPES[s])}</small></span></label>`).join('\n')}
161
+ <label for="pw" style="display:block">Device owner password<input id="pw" type="password" name="password" autocomplete="current-password" required></label>
162
+ <div class="row"><button class="ok" name="decision" value="allow">Allow</button><button name="decision" value="deny" formnovalidate>Deny</button></div>
163
+ </form>
164
+ <p style="margin-top:16px;font-size:13px">The password is in the device's secrets (SERVE_OWNER_PASSWORD). On the device: <code>harness-device serve password</code>.</p>
165
+ </main></body></html>`);
166
+ }
167
+
168
+ async challengeForAuthorizationCode(client, code) {
169
+ const c = this.codes.get(sha(code));
170
+ if (!c || c.clientId !== client.client_id || c.exp < this.now()) throw new InvalidGrantError('Invalid or expired authorization code');
171
+ return c.challenge;
172
+ }
173
+
174
+ async exchangeAuthorizationCode(client, code, _verifier, redirectUri, resource) {
175
+ const key = sha(code);
176
+ const c = this.codes.get(key);
177
+ this.codes.delete(key); // one use, whatever happens next
178
+ if (!c || c.clientId !== client.client_id || c.exp < this.now()) throw new InvalidGrantError('Invalid or expired authorization code');
179
+ if (redirectUri && redirectUri !== c.redirectUri) throw new InvalidGrantError('redirect_uri does not match');
180
+ if (resource && c.resource && resource.href !== c.resource) throw new InvalidGrantError('resource does not match');
181
+ return this.mint(client.client_id, c.scopes, c.resource);
182
+ }
183
+
184
+ async exchangeRefreshToken(client, refreshToken, scopes, resource) {
185
+ const key = sha(refreshToken);
186
+ const r = this.db.refresh[key];
187
+ if (!r || r.clientId !== client.client_id || r.exp < this.now() / 1000) throw new InvalidGrantError('Invalid or expired refresh token');
188
+ delete this.db.refresh[key]; // rotation: each refresh token works once
189
+ const want = scopes && scopes.length ? known(scopes) : r.scopes;
190
+ if (want.some((s) => !r.scopes.includes(s))) throw new InvalidGrantError('Asked for more than was granted');
191
+ if (resource && r.resource && resource.href !== r.resource) throw new InvalidGrantError('resource does not match');
192
+ return this.mint(client.client_id, want, r.resource);
193
+ }
194
+
195
+ mint(clientId, scopes, resource) {
196
+ const t = Math.floor(this.now() / 1000);
197
+ const access = newToken('a');
198
+ const refresh = newToken('r');
199
+ this.db.access[sha(access)] = { clientId, scopes, resource, exp: t + ACCESS_TTL };
200
+ this.db.refresh[sha(refresh)] = { clientId, scopes, resource, exp: t + REFRESH_TTL };
201
+ this.save();
202
+ return { access_token: access, token_type: 'bearer', expires_in: ACCESS_TTL, refresh_token: refresh, scope: scopes.join(' ') };
203
+ }
204
+
205
+ async verifyAccessToken(token) {
206
+ const a = this.db.access[sha(token)];
207
+ if (!a || a.exp < this.now() / 1000 || !this.db.clients[a.clientId]) throw new InvalidTokenError('Invalid or expired token');
208
+ return { token, clientId: a.clientId, scopes: a.scopes, expiresAt: a.exp, ...(a.resource ? { resource: new URL(a.resource) } : {}) };
209
+ }
210
+
211
+ async revokeToken(client, { token }) {
212
+ const k = sha(token);
213
+ for (const m of [this.db.access, this.db.refresh]) if (m[k] && m[k].clientId === client.client_id) delete m[k];
214
+ this.save();
215
+ }
216
+
217
+ /** For `harness-device serve clients`. */
218
+ listClients() {
219
+ this.db = this.load();
220
+ const t = this.now() / 1000;
221
+ return Object.values(this.db.clients).map((c) => {
222
+ const live = Object.values(this.db.refresh).filter((r) => r.clientId === c.client_id && r.exp > t);
223
+ return { id: c.client_id, name: c.client_name || '', approved: !!c.approved, scopes: [...new Set(live.flatMap((r) => r.scopes))], registered: new Date((c.client_id_issued_at || 0) * 1000).toISOString(), redirect: (c.redirect_uris || [])[0] || '' };
224
+ });
225
+ }
226
+
227
+ /** Remove a client and every token it holds. */
228
+ revokeClient(id) {
229
+ this.db = this.load();
230
+ if (!this.db.clients[id]) throw new Error(`No client ${id}`);
231
+ delete this.db.clients[id];
232
+ for (const m of [this.db.access, this.db.refresh]) for (const [k, v] of Object.entries(m)) if (v.clientId === id) delete m[k];
233
+ this.save();
234
+ }
235
+ }
@@ -0,0 +1,37 @@
1
+ // OAuth scopes for `harness-device serve`: which device tools a token may see.
2
+ // Each scope includes the ones below it (admin ⊃ operate ⊃ read). A tool not
3
+ // listed here needs admin, so a new tool is never exposed by accident.
4
+
5
+ export const SCOPES = {
6
+ 'device:read': 'See the device: status, sessions, processes, logs, disk, resources, Docker, settings',
7
+ 'device:operate': 'Run things: register/stop processes, restart services and the browser, run tests, open/close ngrok URLs, free disk, limit containers',
8
+ 'device:admin': 'Change the device: upgrade it, restart it, change settings',
9
+ };
10
+
11
+ const ORDER = ['device:read', 'device:operate', 'device:admin'];
12
+
13
+ const TOOLS = {
14
+ 'device:read': ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs', 'resources', 'screenshot', 'docker_summary', 'ngrok_status', 'config_get'],
15
+ 'device:operate': ['proc_add', 'proc_remove', 'restart_service', 'browser_restart', 'run_tests_live', 'playwright_ui', 'ngrok_up', 'ngrok_down', 'disk_cleanup', 'docker_limit'],
16
+ };
17
+
18
+ /** Granted scopes with everything they include. */
19
+ export function expand(scopes = []) {
20
+ const top = Math.max(-1, ...scopes.map((s) => ORDER.indexOf(s)));
21
+ return ORDER.slice(0, top + 1);
22
+ }
23
+
24
+ /** The scope a tool needs. */
25
+ export function scopeFor(tool) {
26
+ for (const [scope, tools] of Object.entries(TOOLS)) if (tools.includes(tool)) return scope;
27
+ return 'device:admin';
28
+ }
29
+
30
+ /** A tool filter for buildServer({ allow }). */
31
+ export function allowFor(scopes) {
32
+ const have = new Set(expand(scopes));
33
+ return (tool) => have.has(scopeFor(tool));
34
+ }
35
+
36
+ /** Keep only known scopes, in order. */
37
+ export const known = (list) => ORDER.filter((s) => (list || []).includes(s));
package/src/state.js CHANGED
@@ -14,6 +14,7 @@ import path from 'node:path';
14
14
  import crypto from 'node:crypto';
15
15
  import { NAME_RE } from './config.js';
16
16
  import { capture, ok, run } from './util.js';
17
+ import { checkCap } from './limits.js';
17
18
 
18
19
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
19
20
 
@@ -96,6 +97,7 @@ export function newSlot(ctx, project, id = crypto.randomUUID()) {
96
97
  const dir = slotDir(ctx, project);
97
98
  fs.mkdirSync(dir, { recursive: true });
98
99
  // Exclusive create: two `session new` at once get different slots, never one shared.
100
+ checkCap(ctx, 'session', countSlots(ctx));
99
101
  const used = fs.readdirSync(dir).filter((f) => /^\d+$/.test(f)).map(Number);
100
102
  let slot = used.length ? Math.max(...used) + 1 : 1;
101
103
  for (;; slot++) {
@@ -135,12 +137,25 @@ export function removeSlot(ctx, project, slot) {
135
137
  return { id };
136
138
  }
137
139
 
140
+ /** Session slots across every project (conversation mode). */
141
+ function countSlots(ctx) {
142
+ const root = path.join(ctx.paths.state, 'sessions');
143
+ if (!fs.existsSync(root)) return 0;
144
+ return fs.readdirSync(root).reduce((a, p) => {
145
+ try { return a + fs.readdirSync(path.join(root, p)).filter((f) => /^\d+$/.test(f)).length; } catch { return a; }
146
+ }, 0);
147
+ }
148
+
138
149
  /** Register a process that must survive reboots (dev server, watcher, worker). */
139
150
  export function addProc(ctx, name, dir, command) {
140
151
  if (!NAME_RE.test(name)) throw new Error('Process name must be letters, digits, _ or -.');
141
152
  if (!path.isAbsolute(dir) || !fs.existsSync(dir)) throw new Error(`Not an existing absolute directory: ${dir}`);
142
153
  if (!command || /\n/.test(command)) throw new Error('Give the command as one line.');
143
154
  const d = path.join(ctx.paths.state, 'procs');
155
+ // Re-adding a name replaces it, so it doesn't count against the cap.
156
+ if (!fs.existsSync(path.join(d, `${name}.cmd`))) {
157
+ checkCap(ctx, 'proc', fs.existsSync(d) ? fs.readdirSync(d).filter((f) => f.endsWith('.cmd')).length : 0);
158
+ }
144
159
  fs.mkdirSync(d, { recursive: true });
145
160
  fs.writeFileSync(path.join(d, `${name}.cmd`), command + '\n');
146
161
  fs.writeFileSync(path.join(d, `${name}.dir`), dir + '\n');
@@ -12,6 +12,10 @@ RestartSec=3
12
12
  # Let Chromium flush cookies and the profile on stop.
13
13
  KillSignal=SIGTERM
14
14
  TimeoutStopSec=20
15
+ # Safe maximum (RES_BROWSER_MEM_MAX): reclaimed above High, stopped and
16
+ # restarted above Max instead of starving the rest of the machine.
17
+ MemoryHigh={{BROWSER_MEM_HIGH}}
18
+ MemoryMax={{BROWSER_MEM_MAX}}
15
19
 
16
20
  [Install]
17
21
  WantedBy=harness.target
@@ -0,0 +1,16 @@
1
+ [Unit]
2
+ Description=harness-device: MCP over HTTP with OAuth on {{SERVE_HOST}}:{{SERVE_PORT}} (harness-device serve)
3
+ After=network-online.target docker.service
4
+ PartOf=harness.target
5
+
6
+ [Service]
7
+ EnvironmentFile={{HD_HOME}}/runtime.env
8
+ ExecStart={{HD_HOME}}/bin/harness-device serve
9
+ Restart=always
10
+ RestartSec=5
11
+ # Small and fixed: it only answers requests; the work runs in the tools it calls.
12
+ MemoryHigh=200M
13
+ MemoryMax=256M
14
+
15
+ [Install]
16
+ WantedBy=harness.target
@@ -10,6 +10,10 @@ RemainAfterExit=yes
10
10
  EnvironmentFile={{HD_HOME}}/runtime.env
11
11
  ExecStart={{HD_HOME}}/bin/hd-tmux-layout
12
12
  ExecStop=-/usr/bin/env tmux kill-session -t ={{SESSION}}
13
+ # Sessions and anything they start (RES_HARNESS_MEM_MAX): above this the
14
+ # kernel reclaims their memory first, so the OS and Docker apps keep theirs.
15
+ # High throttles, it never kills; the watchdog does the stopping.
16
+ MemoryHigh={{HARNESS_MEM_HIGH}}
13
17
 
14
18
  [Install]
15
19
  WantedBy=harness.target