@dreamtree-org/harness-device 0.1.7 → 0.2.0
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.
- package/README.md +53 -0
- package/package.json +2 -1
- package/sh/bin/hd-proc-loop +10 -1
- package/sh/bin/hd-serve-claude +3 -0
- package/sh/bin/hd-tmux-layout +3 -0
- package/sh/bin/hd-watchdog +13 -0
- package/src/capabilities.js +34 -1
- package/src/cleanup.js +195 -0
- package/src/cli.js +88 -11
- package/src/config.js +60 -1
- package/src/container.js +26 -0
- package/src/context.js +4 -1
- package/src/device.js +21 -1
- package/src/doctor.js +10 -0
- package/src/limits.js +248 -0
- package/src/mcp/interact.js +130 -0
- package/src/mcp/server.js +79 -45
- package/src/platform/darwin.js +3 -1
- package/src/platform/linux.js +2 -0
- package/src/pool/join.js +82 -0
- package/src/pool/link.js +169 -0
- package/src/pool/sync.js +84 -0
- package/src/providers/claude.js +6 -1
- package/src/resources.js +3 -2
- package/src/serve/cli.js +129 -0
- package/src/serve/http.js +120 -0
- package/src/serve/oauth.js +235 -0
- package/src/serve/scopes.js +37 -0
- package/src/state.js +15 -0
- package/templates/systemd/harness-chromium.service +4 -0
- package/templates/systemd/harness-pool.service +16 -0
- package/templates/systemd/harness-serve.service +16 -0
- package/templates/systemd/harness-tmux.service +4 -0
package/src/resources.js
CHANGED
|
@@ -94,7 +94,8 @@ export async function sample(ctx, { quick = false, sampleMs = 400 } = {}) {
|
|
|
94
94
|
const memPct = m.total ? Math.round((100 * m.available) / m.total) : 100;
|
|
95
95
|
const memLevel = memPct <= t.memCritical ? 'critical' : memPct <= t.memHigh ? 'high' : 'ok';
|
|
96
96
|
|
|
97
|
-
|
|
97
|
+
// In a container the host's disk is mounted read-only at HD_HOST_ROOT.
|
|
98
|
+
const d = disks(ctx.env && ctx.env.HD_HOST_ROOT ? [ctx.env.HD_HOST_ROOT] : [ctx.paths.home, ...(ctx.projects || []).map((p) => p.dir)]);
|
|
98
99
|
for (const x of d) {
|
|
99
100
|
x.level = x.freePct <= t.diskCritical || x.free < 1 * GiB ? 'critical' : x.freePct <= t.diskHigh || x.free < 5 * GiB ? 'high' : 'ok';
|
|
100
101
|
}
|
|
@@ -155,7 +156,7 @@ export async function gate(ctx, { force = false, waitSeconds, what = 'this', qui
|
|
|
155
156
|
const LIGHT = [
|
|
156
157
|
/^(ps|top|htop|free|df|du|uptime|vm_stat|sysctl|iostat|vmstat|nproc|kill|pkill|killall|ls|pwd|cat|head|tail|less|wc|grep|rg|find|echo|printf|which|type|stat|date|env|id|whoami|rm|true)\b/,
|
|
157
158
|
/^git (status|log|diff|show|branch|remote|stash list)\b/,
|
|
158
|
-
/^harness-device (status|logs|events|resources|gate|doctor|proc (list|rm)|session list|ngrok (status|down)|config get|tunnel)\b/,
|
|
159
|
+
/^harness-device (status|logs|events|resources|limits|cleanup|gate|doctor|proc (list|rm)|session list|ngrok (status|down)|config get|tunnel)\b/,
|
|
159
160
|
/^docker (ps|stop|kill|rm|rmi|logs|stats|system (df|prune)|image (ls|prune)|container (ls|prune)|volume (ls|prune)|builder prune)\b/,
|
|
160
161
|
/^tmux (ls|list-\w+|kill-window|display-message|capture-pane|has-session)\b/,
|
|
161
162
|
/^(npm|pnpm|yarn) cache (clean|verify)\b/,
|
package/src/serve/cli.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// `harness-device serve …` on the machine: run the server, manage the owner
|
|
2
|
+
// password, list/revoke connected apps, and route a domain to it in Dokploy.
|
|
3
|
+
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { readSecrets } from '../context.js';
|
|
8
|
+
import { loadConfig, saveConfig, setSecret, validateConfig } from '../config.js';
|
|
9
|
+
import { capture, log, color, which } from '../util.js';
|
|
10
|
+
import { DeviceOAuth } from './oauth.js';
|
|
11
|
+
|
|
12
|
+
const DOKPLOY_DYNAMIC = '/etc/dokploy/traefik/dynamic';
|
|
13
|
+
|
|
14
|
+
export function ensurePassword(ctx, { rotate = false } = {}) {
|
|
15
|
+
if (ctx.env.SERVE_OWNER_PASSWORD && !rotate) return { password: ctx.env.SERVE_OWNER_PASSWORD, created: false };
|
|
16
|
+
const cur = readSecrets(ctx.paths.secrets).SERVE_OWNER_PASSWORD;
|
|
17
|
+
if (cur && !rotate) return { password: cur, created: false };
|
|
18
|
+
const pw = crypto.randomBytes(18).toString('base64url');
|
|
19
|
+
setSecret(ctx.paths.secrets, 'SERVE_OWNER_PASSWORD', pw);
|
|
20
|
+
return { password: pw, created: true };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const oauth = (ctx) => new DeviceOAuth({ file: path.join(ctx.paths.state, 'oauth.json'), password: () => '', device: ctx.cfg.DEVICE });
|
|
24
|
+
|
|
25
|
+
/** The IP Dokploy's Traefik reaches this host on: the gateway of its Docker network. */
|
|
26
|
+
export function traefikGateway(env) {
|
|
27
|
+
if (!which('docker', env)) return '';
|
|
28
|
+
const names = capture('docker', ['ps', '--format', '{{.Names}}', '--filter', 'name=traefik'], { env }).split('\n').filter(Boolean);
|
|
29
|
+
for (const n of names) {
|
|
30
|
+
const gw = capture('docker', ['inspect', n, '--format', '{{range .NetworkSettings.Networks}}{{.Gateway}} {{end}}'], { env }).split(/\s+/).find((x) => /^\d+\.\d+\.\d+\.\d+$/.test(x));
|
|
31
|
+
if (gw) return gw;
|
|
32
|
+
}
|
|
33
|
+
return '';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function traefikConfig(domain, upstream) {
|
|
37
|
+
return `# harness-device serve: https://${domain} → ${upstream} (written by harness-device serve expose)
|
|
38
|
+
http:
|
|
39
|
+
routers:
|
|
40
|
+
harness-device-mcp:
|
|
41
|
+
rule: Host(\`${domain}\`)
|
|
42
|
+
entryPoints: [websecure]
|
|
43
|
+
service: harness-device-mcp
|
|
44
|
+
tls:
|
|
45
|
+
certResolver: letsencrypt
|
|
46
|
+
harness-device-mcp-http:
|
|
47
|
+
rule: Host(\`${domain}\`)
|
|
48
|
+
entryPoints: [web]
|
|
49
|
+
middlewares: [harness-device-https]
|
|
50
|
+
service: harness-device-mcp
|
|
51
|
+
middlewares:
|
|
52
|
+
harness-device-https:
|
|
53
|
+
redirectScheme:
|
|
54
|
+
scheme: https
|
|
55
|
+
permanent: true
|
|
56
|
+
services:
|
|
57
|
+
harness-device-mcp:
|
|
58
|
+
loadBalancer:
|
|
59
|
+
servers:
|
|
60
|
+
- url: "${upstream}"
|
|
61
|
+
`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function run(ctx, sub, rest, f) {
|
|
65
|
+
switch (sub) {
|
|
66
|
+
case undefined:
|
|
67
|
+
case 'start': {
|
|
68
|
+
const { created } = ensurePassword(ctx);
|
|
69
|
+
if (created) log.info(`Created the owner password (SERVE_OWNER_PASSWORD in ${ctx.paths.secrets}); see it with: harness-device serve password`);
|
|
70
|
+
const { startServe } = await import('./http.js');
|
|
71
|
+
const s = await startServe(ctx.env, { host: f.host, port: f.port });
|
|
72
|
+
log.ok(`serving ${ctx.cfg.DEVICE}'s tools: MCP ${s.mcpUrl} (OAuth; approve apps with the owner password)`);
|
|
73
|
+
const stop = async () => { await s.close(); process.exit(0); };
|
|
74
|
+
process.on('SIGTERM', stop);
|
|
75
|
+
process.on('SIGINT', stop);
|
|
76
|
+
return new Promise(() => {}); // runs until stopped
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
case 'password': {
|
|
80
|
+
const { password, created } = ensurePassword(ctx, { rotate: !!f.rotate });
|
|
81
|
+
if (created) log.ok(`${f.rotate ? 'New' : 'Created the'} owner password (stored as SERVE_OWNER_PASSWORD in ${ctx.paths.secrets}). Apps already approved keep their tokens; revoke them with harness-device serve revoke.`);
|
|
82
|
+
return console.log(password);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
case 'clients': {
|
|
86
|
+
const list = oauth(ctx).listClients();
|
|
87
|
+
if (f.json) return console.log(JSON.stringify(list, null, 2));
|
|
88
|
+
if (!list.length) return console.log('(no apps have connected)');
|
|
89
|
+
for (const c of list) console.log(`${c.id} ${c.name || '(unnamed)'} ${c.approved ? color.green(c.scopes.join(' ') || 'approved, no live token') : color.dim('never approved')} ${color.dim(c.redirect)}`);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
case 'revoke': {
|
|
94
|
+
if (!rest[0]) throw new Error('usage: harness-device serve revoke <client id> (ids: harness-device serve clients)');
|
|
95
|
+
oauth(ctx).revokeClient(rest[0]);
|
|
96
|
+
return log.ok(`revoked ${rest[0]} and all its tokens`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
case 'expose': {
|
|
100
|
+
const domain = f.domain;
|
|
101
|
+
if (!domain || !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i.test(domain)) throw new Error('usage: harness-device serve expose --domain mcp.example.com');
|
|
102
|
+
const gw = f.host || traefikGateway(ctx.env) || '172.17.0.1';
|
|
103
|
+
const port = ctx.cfg.SERVE_PORT || '7700';
|
|
104
|
+
const { cfg } = loadConfig(ctx.env);
|
|
105
|
+
const next = { ...cfg, SERVE_HOST: gw, SERVE_PUBLIC_URL: `https://${domain}` };
|
|
106
|
+
const errs = validateConfig(next, ctx.env);
|
|
107
|
+
if (errs.length) throw new Error(errs.join(' '));
|
|
108
|
+
saveConfig(next, ctx.env);
|
|
109
|
+
const yml = traefikConfig(domain, `http://${gw}:${port}`);
|
|
110
|
+
const file = path.join(DOKPLOY_DYNAMIC, 'harness-device-mcp.yml');
|
|
111
|
+
let wrote = false;
|
|
112
|
+
try { fs.writeFileSync(file, yml); wrote = true; } catch { /* not writable without root */ }
|
|
113
|
+
log.ok(`SERVE_HOST=${gw} (Traefik's Docker gateway: reachable by Dokploy's Traefik, not from the internet) and SERVE_PUBLIC_URL=https://${domain} saved.`);
|
|
114
|
+
if (wrote) log.ok(`Traefik route written: ${file}`);
|
|
115
|
+
else {
|
|
116
|
+
console.log(`\nSave this as ${file} on the Dokploy server (needs root, e.g. sudo tee ${file}):\n`);
|
|
117
|
+
console.log(yml);
|
|
118
|
+
}
|
|
119
|
+
console.log(`Then:
|
|
120
|
+
1. DNS: an A record ${domain} → this server's public IP.
|
|
121
|
+
2. Add "serve" to CAPABILITIES (harness-device init --capabilities …) or keep it, and run: harness-device install
|
|
122
|
+
3. In the MCP client, add the server ${color.bold(`https://${domain}/mcp`)}; approve it with: harness-device serve password`);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
default:
|
|
127
|
+
throw new Error(`Unknown: serve ${sub}. Use serve, serve password, serve clients, serve revoke <id>, serve expose --domain D`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// `harness-device serve`: the device's MCP tools over Streamable HTTP, behind
|
|
2
|
+
// OAuth, for any MCP client (claude.ai connectors, other agents, scripts),
|
|
3
|
+
// not only the Remote Control sessions on this machine.
|
|
4
|
+
//
|
|
5
|
+
// /mcp MCP (Bearer token; tools filtered by its scopes)
|
|
6
|
+
// /authorize /token /register /revoke OAuth 2.1 (MCP SDK router + DeviceOAuth)
|
|
7
|
+
// /.well-known/oauth-* discovery metadata
|
|
8
|
+
// /healthz liveness, no auth
|
|
9
|
+
//
|
|
10
|
+
// It binds SERVE_HOST:SERVE_PORT (127.0.0.1:7700). The public URL
|
|
11
|
+
// (SERVE_PUBLIC_URL, https) is where Traefik/Dokploy or ngrok routes to it.
|
|
12
|
+
|
|
13
|
+
import crypto from 'node:crypto';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js';
|
|
16
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
17
|
+
import { mcpAuthRouter, getOAuthProtectedResourceMetadataUrl } from '@modelcontextprotocol/sdk/server/auth/router.js';
|
|
18
|
+
import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';
|
|
19
|
+
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
20
|
+
import { loadContext, readSecrets } from '../context.js';
|
|
21
|
+
import { buildServer } from '../mcp/server.js';
|
|
22
|
+
import { PKG } from '../util.js';
|
|
23
|
+
import { DeviceOAuth } from './oauth.js';
|
|
24
|
+
import { SCOPES, allowFor } from './scopes.js';
|
|
25
|
+
import { isContainer, CONTAINER_TOOLS } from '../container.js';
|
|
26
|
+
|
|
27
|
+
const IDLE_MS = 60 * 60 * 1000;
|
|
28
|
+
|
|
29
|
+
/** Where clients reach the server, from config (or the bind address). */
|
|
30
|
+
export function publicUrl(cfg, host, port) {
|
|
31
|
+
if (cfg.SERVE_PUBLIC_URL) return new URL(cfg.SERVE_PUBLIC_URL.replace(/\/+$/, '') + '/');
|
|
32
|
+
const h = ['0.0.0.0', '::'].includes(host) ? '127.0.0.1' : host;
|
|
33
|
+
return new URL(`http://${h.includes(':') ? `[${h}]` : h}:${port}/`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Start the server. Returns { url, close }. opts.host / opts.port override
|
|
38
|
+
* config; opts.password overrides the secret (tests).
|
|
39
|
+
*/
|
|
40
|
+
export async function startServe(env = process.env, opts = {}) {
|
|
41
|
+
const ctx = loadContext(env);
|
|
42
|
+
const host = opts.host || ctx.cfg.SERVE_HOST || '127.0.0.1';
|
|
43
|
+
const port = Number(opts.port ?? ctx.cfg.SERVE_PORT ?? 7700);
|
|
44
|
+
const base = opts.publicUrl ? new URL(opts.publicUrl) : publicUrl(ctx.cfg, host, port);
|
|
45
|
+
const mcpUrl = new URL('mcp', base);
|
|
46
|
+
// A container gets it from its environment (a Dokploy secret); a host from secrets.env.
|
|
47
|
+
const password = opts.password ? () => opts.password : () => env.SERVE_OWNER_PASSWORD || readSecrets(ctx.paths.secrets).SERVE_OWNER_PASSWORD;
|
|
48
|
+
const inContainer = isContainer(env);
|
|
49
|
+
if (!password()) throw new Error('No owner password yet: run harness-device serve password (it creates one) and start again.');
|
|
50
|
+
|
|
51
|
+
const provider = new DeviceOAuth({ file: path.join(ctx.paths.state, 'oauth.json'), password, device: ctx.cfg.DEVICE });
|
|
52
|
+
const app = createMcpExpressApp({ host, allowedHosts: [...new Set([base.hostname, 'localhost', '127.0.0.1', host])] });
|
|
53
|
+
// Behind Traefik (a Docker network) or the ngrok agent (loopback): rate limits see the real client.
|
|
54
|
+
app.set('trust proxy', 'loopback, uniquelocal');
|
|
55
|
+
app.disable('x-powered-by');
|
|
56
|
+
|
|
57
|
+
app.get('/healthz', (_req, res) => res.json({ ok: true, device: ctx.cfg.DEVICE, version: PKG.version }));
|
|
58
|
+
app.use(mcpAuthRouter({
|
|
59
|
+
provider,
|
|
60
|
+
issuerUrl: base,
|
|
61
|
+
resourceServerUrl: mcpUrl,
|
|
62
|
+
scopesSupported: Object.keys(SCOPES),
|
|
63
|
+
resourceName: `harness-device ${ctx.cfg.DEVICE}`,
|
|
64
|
+
}));
|
|
65
|
+
|
|
66
|
+
const sessions = new Map(); // mcp-session-id → { transport, clientId, last }
|
|
67
|
+
const auth = requireBearerAuth({ verifier: provider, resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpUrl) });
|
|
68
|
+
const rpcError = (res, status, message) => res.status(status).json({ jsonrpc: '2.0', error: { code: -32000, message }, id: null });
|
|
69
|
+
|
|
70
|
+
app.all('/mcp', auth, async (req, res) => {
|
|
71
|
+
try {
|
|
72
|
+
const sid = req.headers['mcp-session-id'];
|
|
73
|
+
if (sid) {
|
|
74
|
+
const s = sessions.get(sid);
|
|
75
|
+
if (!s) return rpcError(res, 404, 'Unknown or expired session; initialize again');
|
|
76
|
+
// A session belongs to the client (and scopes) that opened it.
|
|
77
|
+
if (s.clientId !== req.auth.clientId) return rpcError(res, 403, 'This session belongs to another client');
|
|
78
|
+
s.last = Date.now();
|
|
79
|
+
return await s.transport.handleRequest(req, res, req.body);
|
|
80
|
+
}
|
|
81
|
+
if (req.method !== 'POST' || !isInitializeRequest(req.body)) return rpcError(res, 400, 'Send initialize first (no mcp-session-id)');
|
|
82
|
+
const scopes = req.auth.scopes;
|
|
83
|
+
const transport = new StreamableHTTPServerTransport({
|
|
84
|
+
sessionIdGenerator: () => crypto.randomUUID(),
|
|
85
|
+
onsessioninitialized: (id) => sessions.set(id, { transport, clientId: req.auth.clientId, last: Date.now() }),
|
|
86
|
+
});
|
|
87
|
+
transport.onclose = () => { if (transport.sessionId) sessions.delete(transport.sessionId); };
|
|
88
|
+
const byScope = allowFor(scopes);
|
|
89
|
+
const allow = inContainer ? (name) => CONTAINER_TOOLS.includes(name) && byScope(name) : byScope;
|
|
90
|
+
const server = buildServer(env, { transport: 'http', allow });
|
|
91
|
+
await server.connect(transport);
|
|
92
|
+
await transport.handleRequest(req, res, req.body);
|
|
93
|
+
} catch (e) {
|
|
94
|
+
console.error(`serve: ${e && e.stack ? e.stack : e}`);
|
|
95
|
+
if (!res.headersSent) rpcError(res, 500, 'Internal error');
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const sweep = setInterval(() => {
|
|
100
|
+
for (const [id, s] of sessions) if (Date.now() - s.last > IDLE_MS) { sessions.delete(id); s.transport.close().catch(() => {}); }
|
|
101
|
+
}, 60000);
|
|
102
|
+
sweep.unref();
|
|
103
|
+
|
|
104
|
+
const srv = await new Promise((resolve, reject) => {
|
|
105
|
+
const s = app.listen(port, host, () => resolve(s));
|
|
106
|
+
s.on('error', reject);
|
|
107
|
+
});
|
|
108
|
+
const actual = srv.address().port;
|
|
109
|
+
return {
|
|
110
|
+
url: opts.publicUrl || ctx.cfg.SERVE_PUBLIC_URL ? base.href : `http://${base.hostname}:${actual}/`,
|
|
111
|
+
port: actual,
|
|
112
|
+
mcpUrl: opts.publicUrl || ctx.cfg.SERVE_PUBLIC_URL ? mcpUrl.href : `http://${base.hostname}:${actual}/mcp`,
|
|
113
|
+
provider,
|
|
114
|
+
close: async () => {
|
|
115
|
+
clearInterval(sweep);
|
|
116
|
+
for (const s of sessions.values()) await s.transport.close().catch(() => {});
|
|
117
|
+
await new Promise((r) => srv.close(r));
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
@@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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', 'session_new', '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: link to the HarnessPro pool hub (outbound only)
|
|
3
|
+
After=network-online.target harness-tmux.service
|
|
4
|
+
Wants=network-online.target
|
|
5
|
+
PartOf=harness.target
|
|
6
|
+
|
|
7
|
+
[Service]
|
|
8
|
+
EnvironmentFile={{HD_HOME}}/runtime.env
|
|
9
|
+
ExecStart={{HD_HOME}}/bin/harness-device pool link
|
|
10
|
+
Restart=always
|
|
11
|
+
RestartSec=10
|
|
12
|
+
MemoryHigh=200M
|
|
13
|
+
MemoryMax=256M
|
|
14
|
+
|
|
15
|
+
[Install]
|
|
16
|
+
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
|