@ours.network/install 1.2.1-nightly.6 → 1.2.1-nightly.60
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/GATEWAY_SETUP.md +178 -0
- package/README.md +573 -9
- package/ROOTLESS_PODMAN_VALIDATION.md +210 -0
- package/assets/Dockerfile +15 -12
- package/assets/Dockerfile.gateway +5 -0
- package/assets/docker-compose.yaml +8 -1
- package/assets/fleet-settings.example.json +48 -0
- package/assets/gateway-entrypoint.sh +37 -0
- package/assets/release-lock.json +1222 -4517
- package/assets/release.json +37 -19
- package/assets/scripts/build/build-common.mjs +10 -1
- package/assets/scripts/build/build-sdk.mjs +6 -1
- package/assets/scripts/maintenance/build-context.mjs +1 -1
- package/assets/scripts/maintenance/daemon-owner.mjs +15 -0
- package/assets/scripts/maintenance/docker-layout-conversion.mjs +22 -7
- package/assets/scripts/maintenance/recover-notifications.mjs +36 -0
- package/assets/scripts/maintenance/release-graph.mjs +18 -1
- package/assets/scripts/maintenance/state-operation.mjs +76 -8
- package/assets/scripts/runtime/README.md +7 -0
- package/assets/scripts/runtime/client-setup.mjs +105 -20
- package/assets/scripts/runtime/daemon-client-prefix.mjs +115 -0
- package/assets/scripts/runtime/dependency-ready.mjs +13 -0
- package/assets/scripts/runtime/diagnostics.mjs +72 -0
- package/assets/scripts/runtime/entrypoint.sh +5 -1
- package/assets/scripts/runtime/health-messenger.mjs +7 -6
- package/assets/scripts/runtime/healthcheck.mjs +49 -15
- package/assets/scripts/runtime/notifications-gateway.mjs +90 -0
- package/assets/scripts/runtime/recover.mjs +202 -0
- package/assets/scripts/runtime/start-cowork.sh +5 -0
- package/assets/scripts/runtime/start-messenger.sh +29 -4
- package/assets/scripts/runtime/start-telegram.sh +5 -0
- package/assets/scripts/runtime/supervise.mjs +35 -0
- package/assets/sources.json +54 -28
- package/install.mjs +7 -2
- package/lib/boot-readiness.mjs +96 -0
- package/lib/build-transition.mjs +16 -0
- package/lib/client-cli.mjs +127 -0
- package/lib/container-engine.mjs +127 -0
- package/lib/diagnostics.mjs +1 -0
- package/lib/docker-conversion-runtime.mjs +7 -4
- package/lib/docker-layout-installation.mjs +2 -1
- package/lib/docker-recovery.mjs +60 -0
- package/lib/docker-runtime-repair.mjs +49 -14
- package/lib/effects.mjs +482 -140
- package/lib/gateway-transition.mjs +87 -0
- package/lib/gateway.mjs +227 -0
- package/lib/legacy-migration.mjs +13 -2
- package/lib/orchestrate-uninstall.mjs +23 -6
- package/lib/orchestrate.mjs +335 -44
- package/lib/ownership.mjs +63 -0
- package/lib/plan.mjs +37 -11
- package/lib/podman-preflight.mjs +40 -0
- package/lib/product.mjs +69 -0
- package/lib/removal-plan.mjs +437 -0
- package/lib/removal.mjs +749 -0
- package/lib/server-onboarding.mjs +182 -16
- package/lib/server-ports.mjs +17 -0
- package/lib/setup-options.mjs +119 -29
- package/lib/setup.mjs +93 -22
- package/lib/target.mjs +24 -8
- package/lib/uninstall.mjs +2 -2
- package/lib/usage.mjs +35 -9
- package/lib/welcome.mjs +219 -0
- package/lib/workspace-setup.mjs +154 -0
- package/package.json +4 -2
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
import { readBuildRecords, initializeBuildMarker } from '../maintenance/build-context.mjs';
|
|
2
|
+
import { redactDiagnostic } from './diagnostics.mjs';
|
|
2
3
|
import { spawnSync } from 'node:child_process';
|
|
3
|
-
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import { generateKeyPairSync, randomBytes } from 'node:crypto';
|
|
4
5
|
import {
|
|
5
|
-
closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync,
|
|
6
|
+
existsSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync,
|
|
6
7
|
realpathSync, renameSync, unlinkSync, writeFileSync, readdirSync, chmodSync, chownSync,
|
|
7
8
|
} from 'node:fs';
|
|
8
9
|
|
|
9
|
-
const DELIVERY_FILES = [
|
|
10
|
-
'/credentials/telegram/daemon-token',
|
|
11
|
-
'/credentials/cowork/daemon-token',
|
|
12
|
-
'/credentials/messenger/daemon-token',
|
|
13
|
-
];
|
|
14
10
|
const fail = (message) => { throw new Error(message); };
|
|
11
|
+
/** Applications of this installation; plugin-only installations have only the daemon. */
|
|
12
|
+
const APPLICATIONS = (() => {
|
|
13
|
+
const all = ['daemon', 'telegram', 'cowork', 'messenger'];
|
|
14
|
+
const raw = process.env.OURS_SERVER_APPLICATIONS;
|
|
15
|
+
if (raw === undefined || raw === '') return all;
|
|
16
|
+
const selected = raw.split(',');
|
|
17
|
+
if (selected[0] !== 'daemon' || new Set(selected).size !== selected.length || selected.some(name => !all.includes(name))) fail('Invalid OURS_SERVER_APPLICATIONS selection');
|
|
18
|
+
return selected;
|
|
19
|
+
})();
|
|
20
|
+
const CONSUMERS = APPLICATIONS.filter(name => name !== 'daemon');
|
|
21
|
+
const DELIVERY_FILES = CONSUMERS.map(name => `/credentials/${name}/daemon-token`);
|
|
22
|
+
let diagnosticStage = 'validation';
|
|
15
23
|
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
16
24
|
|
|
17
25
|
function privatePath(path, directory, exact = directory ? 0o700 : 0o600) {
|
|
@@ -67,7 +75,7 @@ function validateCommon(idName = 'OURS_DAEMON_ID') {
|
|
|
67
75
|
|
|
68
76
|
function composeConfig(domain) {
|
|
69
77
|
if (domain === 'daemon') {
|
|
70
|
-
const value = { stateDir: '/var/lib/ours', port: 3050, apiVisibility: 'owner'
|
|
78
|
+
const value = { stateDir: '/var/lib/ours', port: 3050, apiVisibility: 'owner' };
|
|
71
79
|
if (process.env.OURS_BROKER_URL) value.brokerUrl = process.env.OURS_BROKER_URL;
|
|
72
80
|
return value;
|
|
73
81
|
}
|
|
@@ -79,6 +87,61 @@ function composeConfig(domain) {
|
|
|
79
87
|
return null;
|
|
80
88
|
}
|
|
81
89
|
|
|
90
|
+
const NOTIFICATIONS_PORT = 49677;
|
|
91
|
+
const NOTIFICATION_FILES = {
|
|
92
|
+
config: '/storage/state/notifications/config.json',
|
|
93
|
+
messenger: '/storage/state/credentials/messenger/notifications-producer',
|
|
94
|
+
// Read through the Messenger service by local client setup.
|
|
95
|
+
fleet: '/storage/state/notifications/fleet-producer',
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
function privateText(path, value) {
|
|
99
|
+
if (existingPrivate(path, false) && readFileSync(path, 'utf8') === value) return;
|
|
100
|
+
const temp = `${path}.setup-${randomBytes(8).toString('hex')}`;
|
|
101
|
+
try { writeFileSync(temp, value, { encoding: 'utf8', mode: 0o600, flag: 'wx' }); renameSync(temp, path); }
|
|
102
|
+
finally { try { unlinkSync(temp); } catch (error) { if (error.code !== 'ENOENT') throw error; } }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function notificationConfig() {
|
|
106
|
+
const token = () => randomBytes(32).toString('base64url');
|
|
107
|
+
const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
|
|
108
|
+
const pub = publicKey.export({ format: 'jwk' }), key = privateKey.export({ format: 'jwk' });
|
|
109
|
+
const raw = Buffer.concat([Buffer.from([4]), Buffer.from(pub.x, 'base64url'), Buffer.from(pub.y, 'base64url')]);
|
|
110
|
+
return {
|
|
111
|
+
host: '0.0.0.0', port: NOTIFICATIONS_PORT, stateFile: '/var/lib/ours-notifications/state.json',
|
|
112
|
+
users: [{ userId: 'owner', token: token() }],
|
|
113
|
+
producers: [{ userId: 'owner', source: 'fleet', token: token() }, { userId: 'owner', source: 'messenger', token: token() }],
|
|
114
|
+
vapid: { subject: 'https://ours.network', publicKey: raw.toString('base64url'), privateKey: key.d },
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Exact retained shape; any other content is operator state the installer will not rewrite. */
|
|
119
|
+
function validNotificationConfig(config) {
|
|
120
|
+
const tokens = [...(config.users ?? []), ...(config.producers ?? [])].map(entry => entry?.token);
|
|
121
|
+
return config.host === '0.0.0.0' && config.port === NOTIFICATIONS_PORT && config.stateFile === '/var/lib/ours-notifications/state.json'
|
|
122
|
+
&& Array.isArray(config.users) && config.users.length === 1 && config.users[0].userId === 'owner'
|
|
123
|
+
&& Array.isArray(config.producers) && config.producers.length === 2
|
|
124
|
+
&& ['fleet', 'messenger'].every(source => config.producers.some(p => p?.source === source && p.userId === 'owner'))
|
|
125
|
+
&& tokens.every(t => typeof t === 'string' && t.length >= 32) && new Set(tokens).size === tokens.length
|
|
126
|
+
&& typeof config.vapid?.subject === 'string' && /^[A-Za-z0-9_-]{87}$/.test(config.vapid.publicKey ?? '') && /^[A-Za-z0-9_-]{43}$/.test(config.vapid.privateKey ?? '');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Notification secrets are created once and then only validated: rotating the
|
|
131
|
+
* owner token or VAPID keys would orphan every browser subscription. Producer
|
|
132
|
+
* delivery files are derived from the retained configuration on every run.
|
|
133
|
+
*/
|
|
134
|
+
function prepareNotifications() {
|
|
135
|
+
// Messenger mounts this directory whether or not this runtime ships the service.
|
|
136
|
+
ensureDirectory('/storage/state/notifications');
|
|
137
|
+
if (!existsSync('/opt/ours/node_modules/@ours.network/notifications/package.json')) return;
|
|
138
|
+
initializeBuildMarker('/storage/state/notifications/.ours-provenance', readBuildRecords('/opt/ours'));
|
|
139
|
+
if (!existingPrivate(NOTIFICATION_FILES.config, false)) atomicJson(NOTIFICATION_FILES.config, notificationConfig());
|
|
140
|
+
const config = jsonObject(NOTIFICATION_FILES.config);
|
|
141
|
+
if (!validNotificationConfig(config)) fail('Existing notification configuration differs; use the supported maintenance workflow');
|
|
142
|
+
for (const source of ['messenger', 'fleet']) privateText(NOTIFICATION_FILES[source], config.producers.find(p => p.source === source).token);
|
|
143
|
+
}
|
|
144
|
+
|
|
82
145
|
function prepare() {
|
|
83
146
|
const uid = Number(process.env.OURS_UID), gid = Number(process.env.OURS_GID);
|
|
84
147
|
if (![uid, gid].every((n) => Number.isSafeInteger(n) && n > 0)) fail('Configure non-root numeric OURS_UID and OURS_GID');
|
|
@@ -96,11 +159,11 @@ function prepare() {
|
|
|
96
159
|
process.umask(0o077);
|
|
97
160
|
validateCommon();
|
|
98
161
|
for (const path of ['/storage/state', '/storage/state/mcp', '/storage/state/credentials',
|
|
99
|
-
...
|
|
162
|
+
...CONSUMERS.map(name => `/storage/state/credentials/${name}`),
|
|
100
163
|
'/storage/backups', '/storage/.maintenance']) ensureDirectory(path);
|
|
101
164
|
const coworkPort = Number(process.env.OURS_COWORK_REST_PORT);
|
|
102
165
|
if (!Number.isSafeInteger(coworkPort) || coworkPort < 1 || coworkPort > 65535) fail('Configure a valid cowork REST port');
|
|
103
|
-
for (const domain of
|
|
166
|
+
for (const domain of APPLICATIONS) {
|
|
104
167
|
const data = `/storage/state/${domain}`;
|
|
105
168
|
ensureDirectory(data);
|
|
106
169
|
// access-init owns the fresh-state check; no installer files enter daemon
|
|
@@ -116,22 +179,28 @@ function prepare() {
|
|
|
116
179
|
fail('Existing daemon configuration differs; use the supported maintenance workflow');
|
|
117
180
|
}
|
|
118
181
|
} else atomicJson(path, expected);
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
182
|
+
if (APPLICATIONS.includes('cowork')) {
|
|
183
|
+
const coworkPath = '/storage/state/cowork/config.json';
|
|
184
|
+
const cowork = composeConfig('cowork');
|
|
185
|
+
if (!existingPrivate(coworkPath, false)) atomicJson(coworkPath, cowork);
|
|
186
|
+
else {
|
|
187
|
+
const config = jsonObject(coworkPath);
|
|
188
|
+
if (config.version !== 1 || config.stateDir !== cowork.stateDir || config.rest?.enabled !== true || config.rest?.host !== '0.0.0.0') fail('Existing cowork configuration conflicts with Compose');
|
|
189
|
+
}
|
|
125
190
|
}
|
|
191
|
+
if (APPLICATIONS.includes('messenger')) prepareNotifications();
|
|
126
192
|
console.log('OURS persistent volumes are ready');
|
|
127
193
|
}
|
|
128
194
|
|
|
129
195
|
function finishDaemonSetup() {
|
|
130
196
|
const state = '/var/lib/ours';
|
|
197
|
+
diagnosticStage = 'daemon-provenance';
|
|
131
198
|
initializeBuildMarker(`${state}/.ours-provenance`, readBuildRecords('/opt/ours'));
|
|
199
|
+
diagnosticStage = 'mcp-directory';
|
|
132
200
|
privatePath('/var/lib/ours-mcp', true);
|
|
133
201
|
const mcpProfile = { endpoint: 'http://127.0.0.1:3050', expectedInstanceId: process.env.OURS_DAEMON_ID, credentialPath: `${state}/daemon-token` };
|
|
134
202
|
const mcpPath = '/var/lib/ours-mcp/profile.json';
|
|
203
|
+
diagnosticStage = 'mcp-profile';
|
|
135
204
|
if (!existingPrivate(mcpPath, false)) atomicJson(mcpPath, mcpProfile);
|
|
136
205
|
else if (JSON.stringify(jsonObject(mcpPath)) !== JSON.stringify(mcpProfile)) fail('Existing MCP profile differs from the selected daemon');
|
|
137
206
|
}
|
|
@@ -155,10 +224,19 @@ async function telegramInput() {
|
|
|
155
224
|
}
|
|
156
225
|
|
|
157
226
|
function cliJson(args) {
|
|
158
|
-
|
|
227
|
+
diagnosticStage = 'official-cli';
|
|
228
|
+
const result = spawnSync(process.execPath, [existsSync('/opt/ours/node_modules/@ours.network/daemon/dist/cli.js') ? '/opt/ours/node_modules/@ours.network/daemon/dist/cli.js' : '/opt/ours/node_modules/@ours.network/cli/dist/cli.js', ...args], {
|
|
159
229
|
encoding: 'utf8', timeout: 60_000, maxBuffer: 1024 * 1024,
|
|
160
230
|
});
|
|
161
|
-
if (result.status !== 0)
|
|
231
|
+
if (result.error || result.status !== 0) {
|
|
232
|
+
// --json writes failures on stderr. Successful credential stdout is never
|
|
233
|
+
// forwarded, even if a later operation exits unsuccessfully.
|
|
234
|
+
let reason = 'CLI supplied no structured error reason';
|
|
235
|
+
for (const line of String(result.stderr ?? '').split('\n').reverse()) {
|
|
236
|
+
try { const value = JSON.parse(line); if (typeof value?.error?.message === 'string') { reason = value.error.message; break; } } catch {}
|
|
237
|
+
}
|
|
238
|
+
fail(`Official OURS CLI operation failed (${args[1]}; exit=${result.status ?? 'none'}; signal=${result.signal ?? 'none'}; system=${result.error?.code ?? 'none'}): ${reason}`);
|
|
239
|
+
}
|
|
162
240
|
try { return JSON.parse(result.stdout); }
|
|
163
241
|
catch { fail('Official OURS CLI returned malformed JSON'); }
|
|
164
242
|
}
|
|
@@ -188,10 +266,17 @@ function exactKeys(value, allowed, label) {
|
|
|
188
266
|
try {
|
|
189
267
|
const operation = process.argv[2];
|
|
190
268
|
if (operation === 'prepare') prepare();
|
|
191
|
-
else if (operation === 'telegram-input') {
|
|
269
|
+
else if (operation === 'telegram-input') {
|
|
270
|
+
if (!APPLICATIONS.includes('telegram')) fail('This installation has no Telegram connector');
|
|
271
|
+
prepare(); await telegramInput();
|
|
272
|
+
}
|
|
192
273
|
else if (['access-init', 'access-issue', 'access-replace'].includes(operation)) access(operation, process.argv[3]);
|
|
193
274
|
else fail('usage: client-setup.mjs prepare | telegram-input | access-init | access-issue [OUTPUT] | access-replace');
|
|
194
275
|
} catch (error) {
|
|
195
|
-
|
|
276
|
+
// Structured stderr retains the failing stage across sensitive Compose
|
|
277
|
+
// capture. The installer redacts secrets before exposing this envelope.
|
|
278
|
+
const message = redactDiagnostic(error.message);
|
|
279
|
+
console.error(JSON.stringify({ oursInstallerError: { stage: diagnosticStage, message } }));
|
|
280
|
+
console.error(`OURS client setup refused: ${message}`);
|
|
196
281
|
process.exit(1);
|
|
197
282
|
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createServer, request } from 'node:http';
|
|
3
|
+
import { connect } from 'node:net';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Plugin-only installations run no gateway container. Current client releases
|
|
8
|
+
* still address the daemon as <serverUrl>/daemon, so the daemon container itself
|
|
9
|
+
* serves that one prefix. Requests and responses pass through unchanged, including
|
|
10
|
+
* the client's own credential and instance checks; nothing is added or injected.
|
|
11
|
+
* Any other path, method form or host-absolute target is refused.
|
|
12
|
+
*/
|
|
13
|
+
export const PREFIX = '/daemon';
|
|
14
|
+
export const CAPABILITY = 'ours.daemon-prefix-v1';
|
|
15
|
+
const HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'te', 'trailer', 'upgrade'];
|
|
16
|
+
|
|
17
|
+
/** Only origin-form targets under the prefix; the remainder is the daemon path. */
|
|
18
|
+
export function daemonPath(target) {
|
|
19
|
+
if (typeof target !== 'string' || !target.startsWith(PREFIX + '/') || /[\s\\]/.test(target)) return null;
|
|
20
|
+
const rest = target.slice(PREFIX.length);
|
|
21
|
+
// A dot segment could step out of the prefix once normalized by the daemon.
|
|
22
|
+
for (const segment of rest.split('?')[0].split('/')) {
|
|
23
|
+
let decoded;
|
|
24
|
+
try { decoded = decodeURIComponent(segment); } catch { return null; }
|
|
25
|
+
if (decoded === '.' || decoded === '..' || decoded.includes('/')) return null;
|
|
26
|
+
}
|
|
27
|
+
return rest;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function discovery(instanceId) {
|
|
31
|
+
return { schema: 1, instanceId, services: { daemon: PREFIX }, capabilities: [CAPABILITY] };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Headers as received, minus hop-by-hop ones; repeated headers keep every value. */
|
|
35
|
+
function headersFor(raw) {
|
|
36
|
+
const headers = {};
|
|
37
|
+
for (let i = 0; i < raw.length; i += 2) {
|
|
38
|
+
const name = raw[i].toLowerCase();
|
|
39
|
+
if (HOP.includes(name)) continue;
|
|
40
|
+
if (!Object.hasOwn(headers, name)) headers[name] = raw[i + 1];
|
|
41
|
+
else if (name === 'set-cookie') headers[name] = [].concat(headers[name], raw[i + 1]);
|
|
42
|
+
else headers[name] = `${headers[name]}, ${raw[i + 1]}`;
|
|
43
|
+
}
|
|
44
|
+
return headers;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createPrefixServer({ upstreamPort = 3050, upstreamHost = '127.0.0.1', instanceId }) {
|
|
48
|
+
const reply = (res, status, body) => {
|
|
49
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
50
|
+
res.end(JSON.stringify(body));
|
|
51
|
+
};
|
|
52
|
+
const server = createServer((req, res) => {
|
|
53
|
+
if (req.url === '/.well-known/ours' && req.method === 'GET') return reply(res, 200, discovery(instanceId));
|
|
54
|
+
if (req.url === PREFIX) { res.writeHead(308, { location: PREFIX + '/' }); res.end(); return; }
|
|
55
|
+
const path = daemonPath(req.url);
|
|
56
|
+
if (path === null) return reply(res, 404, { error: 'not found' });
|
|
57
|
+
const upstream = request({ host: upstreamHost, port: upstreamPort, method: req.method, path, headers: headersFor(req.rawHeaders) }, response => {
|
|
58
|
+
res.writeHead(response.statusCode ?? 502, headersFor(response.rawHeaders));
|
|
59
|
+
response.pipe(res);
|
|
60
|
+
response.on('error', () => res.destroy());
|
|
61
|
+
});
|
|
62
|
+
upstream.on('error', () => { if (!res.headersSent) reply(res, 502, { error: 'daemon unavailable' }); else res.destroy(); });
|
|
63
|
+
// A client that goes away cancels its long poll or stream at the daemon too.
|
|
64
|
+
res.on('close', () => { if (!res.writableFinished) upstream.destroy(); });
|
|
65
|
+
req.pipe(upstream);
|
|
66
|
+
});
|
|
67
|
+
server.on('upgrade', (req, socket, head) => {
|
|
68
|
+
const path = daemonPath(req.url);
|
|
69
|
+
if (path === null) { socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'); return; }
|
|
70
|
+
const upstream = connect(upstreamPort, upstreamHost, () => {
|
|
71
|
+
const lines = [`${req.method} ${path} HTTP/1.1`];
|
|
72
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) lines.push(`${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}`);
|
|
73
|
+
upstream.write(lines.join('\r\n') + '\r\n\r\n');
|
|
74
|
+
if (head?.length) upstream.write(head);
|
|
75
|
+
upstream.pipe(socket); socket.pipe(upstream);
|
|
76
|
+
});
|
|
77
|
+
const close = () => { upstream.destroy(); socket.destroy(); };
|
|
78
|
+
upstream.on('error', close); socket.on('error', close);
|
|
79
|
+
upstream.on('close', () => socket.destroy()); socket.on('close', () => upstream.destroy());
|
|
80
|
+
});
|
|
81
|
+
// Absolute-form ("GET http://host/...") and CONNECT never reach the daemon.
|
|
82
|
+
server.on('connect', (req, socket) => socket.end('HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'));
|
|
83
|
+
return server;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Run the daemon's own locked, recovering entrypoint as the single child and
|
|
88
|
+
* serve the prefix beside it. Either one ending stops the other, so the
|
|
89
|
+
* container exits and its restart policy recovers both together.
|
|
90
|
+
*/
|
|
91
|
+
async function main() {
|
|
92
|
+
const port = Number(process.env.OURS_DAEMON_CLIENT_PREFIX_PORT);
|
|
93
|
+
const instanceId = process.env.OURS_DAEMON_ID ?? '';
|
|
94
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535 || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(instanceId)) {
|
|
95
|
+
console.error('OURS daemon client prefix requires a port and the daemon UUID'); process.exit(2);
|
|
96
|
+
}
|
|
97
|
+
const runtime = process.env.OURS_RUNTIME_ROOT ?? '/opt/ours';
|
|
98
|
+
const child = spawn('/bin/sh', ['-e', `${runtime}/docker/entrypoint.sh`], { stdio: 'inherit' });
|
|
99
|
+
const server = createPrefixServer({ instanceId });
|
|
100
|
+
let stopping = false;
|
|
101
|
+
const stop = (signal, code) => {
|
|
102
|
+
if (stopping) return;
|
|
103
|
+
stopping = true;
|
|
104
|
+
server.close();
|
|
105
|
+
if (child.exitCode === null && child.signalCode === null) child.kill(signal);
|
|
106
|
+
else process.exit(code);
|
|
107
|
+
};
|
|
108
|
+
child.on('exit', (code, signal) => { server.close(); process.exit(code ?? (signal ? 1 : 0)); });
|
|
109
|
+
child.on('error', () => { server.close(); process.exit(1); });
|
|
110
|
+
server.on('error', error => { console.error(`OURS daemon client prefix stopped: ${error.code ?? error.message}`); stop('SIGTERM', 1); });
|
|
111
|
+
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => stop(signal, 0));
|
|
112
|
+
server.listen(port, '0.0.0.0', () => console.error(`OURS daemon client prefix ready on ${PREFIX}`));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main();
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { attachOursClient } from '@ours.network/sdk/client';
|
|
2
|
+
let client;
|
|
3
|
+
try {
|
|
4
|
+
const service = process.argv[2];
|
|
5
|
+
if (!['telegram', 'cowork', 'messenger'].includes(service)) throw new Error('Unknown dependency');
|
|
6
|
+
client = await attachOursClient({ endpoint: 'http://daemon:3050',
|
|
7
|
+
expectedInstanceId: process.env[service === 'telegram' ? 'OURS_TG_DAEMON_ID' : 'OURS_DAEMON_ID'],
|
|
8
|
+
credentialPath: `/credentials/${service}/daemon-token`,
|
|
9
|
+
requiredCapabilities: ['external-sessions-v1'], sessionMode: 'external',
|
|
10
|
+
leaseToken: `container-dependency-${service}`, env: {} });
|
|
11
|
+
await client.listIdentities();
|
|
12
|
+
} catch { process.exitCode = 1; }
|
|
13
|
+
finally { await client?.close(); }
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Retain actionable failure details without emitting credential output. */
|
|
2
|
+
export function redactDiagnostic(value, env = process.env) {
|
|
3
|
+
let text = String(value ?? '').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
|
4
|
+
for (const [key, secret] of Object.entries(env)) {
|
|
5
|
+
if (/(?:token|password|secret|api.?key|private.?key|invitation|enrollment|authorization|credential|access.?token|refresh.?token)/i.test(key) && typeof secret === 'string' && secret)
|
|
6
|
+
text = text.split(secret).join('[redacted]');
|
|
7
|
+
}
|
|
8
|
+
return text
|
|
9
|
+
.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, '[redacted private key]')
|
|
10
|
+
.replace(/(Bearer\s+)[^\s"',;]+/gi, '$1[redacted]')
|
|
11
|
+
.replace(/((?:["']?(?:api[-_]?token|token|password|secret|api[-_]?key|private[-_]?key|invitation|enrollment|authorization|credential|access.?token|refresh.?token)["']?)\s*[:=]\s*)(?:"[^"\n]*"|'[^'\n]*'|[^\s,;}]+)/gi, '$1[redacted]')
|
|
12
|
+
.replace(/(--(?:setup-workspace|password|token|secret|api-key|private-key|invitation|enrollment)(?:=|\s+))\S+/gi, '$1[redacted]')
|
|
13
|
+
.replace(/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/g, '$1[redacted]@')
|
|
14
|
+
.replace(/\b[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, '[redacted credential]')
|
|
15
|
+
.replace(/[A-Za-z0-9_+/=-]{43,}/g, '[redacted opaque value]');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const bounded = text => text.length <= 65536 ? text : text.slice(0, 65536) + '\n[Diagnostic output exceeds 64 KiB; remainder omitted.]';
|
|
19
|
+
function credentialFailure(stderr) {
|
|
20
|
+
// Credential stdout can be a successful issuance followed by failure: never
|
|
21
|
+
// include it. Only a structured error envelope or shipped helper refusal is
|
|
22
|
+
// accepted from stderr; arbitrary lines/warnings remain private.
|
|
23
|
+
const lines = String(stderr ?? '').split('\n').reverse();
|
|
24
|
+
for (const line of lines) {
|
|
25
|
+
try {
|
|
26
|
+
const value = JSON.parse(line);
|
|
27
|
+
if (typeof value?.oursInstallerError?.message === 'string') {
|
|
28
|
+
const detail = value.oursInstallerError;
|
|
29
|
+
const stage = /^[a-z][a-z-]{0,40}$/.test(detail.stage ?? '') ? detail.stage : 'credential-operation';
|
|
30
|
+
return `Stage: ${stage}\nReason: ${detail.message}`;
|
|
31
|
+
}
|
|
32
|
+
if (typeof value?.error?.message === 'string') return `Reason: ${value.error.message}`;
|
|
33
|
+
} catch {}
|
|
34
|
+
}
|
|
35
|
+
const prefix = 'OURS client setup refused: ';
|
|
36
|
+
const legacy = lines.find(line => line.startsWith(prefix));
|
|
37
|
+
if (legacy) return `Reason: ${legacy.slice(prefix.length)}`;
|
|
38
|
+
return 'The credential operation provided no structured reason. Its raw output was withheld because it can contain credentials.';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function commandFailure(command, args, result, { sensitive = false, cwd, env = process.env } = {}) {
|
|
42
|
+
const visibleArgs = [...args];
|
|
43
|
+
if (sensitive) {
|
|
44
|
+
for (let i = 0; i < visibleArgs.length - 1; i++) if (['-e', '--eval'].includes(visibleArgs[i])) visibleArgs[i + 1] = '[captured installer helper]';
|
|
45
|
+
}
|
|
46
|
+
const details = [`Command: ${command} ${visibleArgs.join(' ')}${result.status != null ? ` exited ${result.status}` : ''}`];
|
|
47
|
+
if (cwd) details.push(`Working directory: ${cwd}`);
|
|
48
|
+
if (result.status !== null && result.status !== undefined) details.push(`Exit code: ${result.status}`);
|
|
49
|
+
if (result.signal) details.push(`Signal: ${result.signal}`);
|
|
50
|
+
if (result.error?.code) details.push(`System error: ${result.error.code}`);
|
|
51
|
+
if (result.error?.code === 'ETIMEDOUT') details.push('Reason: command timed out.');
|
|
52
|
+
if (sensitive) details.push(credentialFailure(result.stderr));
|
|
53
|
+
else {
|
|
54
|
+
const stderr = String(result.stderr ?? '').trim(), stdout = String(result.stdout ?? '').trim();
|
|
55
|
+
if (stderr) details.push(`Standard error:\n${stderr}`);
|
|
56
|
+
if (stdout) details.push(`Standard output:\n${stdout}`);
|
|
57
|
+
if (!stderr && !stdout) details.push('No captured command output. Streaming commands print their output above.');
|
|
58
|
+
}
|
|
59
|
+
details.push('Keep installation data intact. Include this error and the preceding installation stage when requesting help.');
|
|
60
|
+
return new Error(bounded(redactDiagnostic(details.join('\n'), env)), result.error ? { cause: result.error } : undefined);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function installerFailure(error, env = process.env) {
|
|
64
|
+
const details = []; const seen = new Set();
|
|
65
|
+
for (let cause = error; cause && !seen.has(cause) && seen.size < 8; cause = cause.cause) {
|
|
66
|
+
seen.add(cause);
|
|
67
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
68
|
+
if (!details.includes(message)) details.push(message);
|
|
69
|
+
if (typeof cause.code === 'string' && /^[A-Z_0-9]+$/.test(cause.code)) details.push(`System error: ${cause.code}`);
|
|
70
|
+
}
|
|
71
|
+
return bounded(redactDiagnostic(details.join('\nCaused by: '), env));
|
|
72
|
+
}
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
|
+
# Re-enter this entrypoint for every recovery, including its locks and checks.
|
|
3
|
+
if [ "${OURS_RECOVERY_CHILD:-}" != 1 ]; then
|
|
4
|
+
exec node "${OURS_RUNTIME_ROOT:-/opt/ours}/docker/recover.mjs" daemon
|
|
5
|
+
fi
|
|
2
6
|
set -eu
|
|
3
7
|
umask 077
|
|
4
8
|
exec 3</var/lib/ours
|
|
@@ -10,4 +14,4 @@ else
|
|
|
10
14
|
exit "$status"
|
|
11
15
|
fi
|
|
12
16
|
node /opt/ours/docker/check-start.mjs
|
|
13
|
-
exec node /opt/ours/node_modules/@ours.network/
|
|
17
|
+
exec node /opt/ours/node_modules/@ours.network/daemon/dist/cli.js serve
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
});
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
const healthy = async url => {
|
|
4
|
+
try { return (await fetch(url, { signal: AbortSignal.timeout(3000), redirect: 'error' })).ok; } catch { return false; }
|
|
5
|
+
};
|
|
6
|
+
const notifications = process.env.OURS_NOTIFICATIONS_CONFIG && existsSync('/opt/ours/node_modules/@ours.network/notifications/package.json') && existsSync(process.env.OURS_NOTIFICATIONS_CONFIG);
|
|
7
|
+
process.exitCode = await healthy('http://127.0.0.1:8420/api/healthz') && (!notifications || await healthy('http://127.0.0.1:49677/healthz')) ? 0 : 1;
|
|
@@ -1,17 +1,51 @@
|
|
|
1
1
|
import { attachOursClient } from '@ours.network/sdk/client';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
leaseToken: 'container-readiness',
|
|
11
|
-
env: {},
|
|
12
|
-
});
|
|
13
|
-
await client.listIdentities();
|
|
14
|
-
} catch {
|
|
15
|
-
console.error('Daemon API is not ready');
|
|
2
|
+
|
|
3
|
+
// Liveness: the anonymous selection route answers without authentication or
|
|
4
|
+
// state, so a failure here means the daemon is down or its event loop is stalled.
|
|
5
|
+
// Readiness: an authenticated external session can list identities.
|
|
6
|
+
// Only a fixed classification is printed; error text may carry private detail.
|
|
7
|
+
const report = (stage, reason) => {
|
|
8
|
+
console.log(`OURS_PROBE ${stage}:${reason}`);
|
|
9
|
+
console.error(`Daemon API is not ready (${stage}: ${reason})`);
|
|
16
10
|
process.exitCode = 1;
|
|
17
|
-
}
|
|
11
|
+
};
|
|
12
|
+
const LIVENESS_TIMEOUT_MS = 3_000;
|
|
13
|
+
const READINESS_TIMEOUT_MS = 10_000;
|
|
14
|
+
|
|
15
|
+
let live = false;
|
|
16
|
+
try {
|
|
17
|
+
const response = await fetch('http://127.0.0.1:3050/selection', { signal: AbortSignal.timeout(LIVENESS_TIMEOUT_MS), redirect: 'error' });
|
|
18
|
+
await response.body?.cancel();
|
|
19
|
+
if (response.ok) live = true;
|
|
20
|
+
else report('liveness', 'http');
|
|
21
|
+
} catch (error) {
|
|
22
|
+
report('liveness', error?.name === 'TimeoutError' ? 'timeout' : 'unreachable');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (live) {
|
|
26
|
+
let client, timer;
|
|
27
|
+
const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(Object.assign(new Error(), { name: 'TimeoutError' })), READINESS_TIMEOUT_MS); });
|
|
28
|
+
try {
|
|
29
|
+
await Promise.race([deadline, (async () => {
|
|
30
|
+
client = await attachOursClient({
|
|
31
|
+
endpoint: 'http://127.0.0.1:3050',
|
|
32
|
+
expectedInstanceId: process.env.OURS_DAEMON_ID,
|
|
33
|
+
credentialPath: '/var/lib/ours/daemon-token',
|
|
34
|
+
requiredCapabilities: ['external-sessions-v1'],
|
|
35
|
+
sessionMode: 'external',
|
|
36
|
+
leaseToken: 'container-readiness',
|
|
37
|
+
env: {},
|
|
38
|
+
});
|
|
39
|
+
await client.listIdentities();
|
|
40
|
+
})()]);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
const text = String(error?.message ?? '');
|
|
43
|
+
report('readiness', error?.name === 'TimeoutError' ? 'timeout'
|
|
44
|
+
: /instance selection metadata|expected daemon instance/i.test(text) ? 'instance'
|
|
45
|
+
: /required capabilities/i.test(text) ? 'capability'
|
|
46
|
+
: /\b401\b|unauthori[sz]ed|credential|token/i.test(text) ? 'auth' : 'error');
|
|
47
|
+
} finally {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
await client?.close().catch(() => {});
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { createServer, request } from 'node:http';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
4
|
+
|
|
5
|
+
/** Browser context has no authority at the notification service. */
|
|
6
|
+
const BROWSER = ['cookie', 'origin', 'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest', 'sec-fetch-user'];
|
|
7
|
+
const SERVER_CREDENTIAL = 'x-ours-api-token', PRODUCER = 'x-ours-notifications-producer';
|
|
8
|
+
|
|
9
|
+
/** true: accepted; false: explicitly denied; null: the daemon could not decide. */
|
|
10
|
+
export function daemonCredentialCheck(daemonUrl) {
|
|
11
|
+
return token => new Promise(resolve => {
|
|
12
|
+
const req = request(new URL('/identities', daemonUrl), { method: 'GET', headers: { [SERVER_CREDENTIAL]: token }, timeout: 5000 }, res => {
|
|
13
|
+
res.resume(); resolve(res.statusCode >= 200 && res.statusCode < 300 ? true : [401,403].includes(res.statusCode) ? false : null);
|
|
14
|
+
});
|
|
15
|
+
req.on('timeout', () => req.destroy());
|
|
16
|
+
req.on('error', () => resolve(null));
|
|
17
|
+
req.end();
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Front the notification service with the server's own authentication.
|
|
23
|
+
* A request carrying a server API credential is checked with the daemon; only then
|
|
24
|
+
* does it act as this installation's owner (or, for producer lifecycle routes, as the named
|
|
25
|
+
* producer). A request without one keeps its own Authorization, which the service
|
|
26
|
+
* checks against its scoped tokens. Nothing is injected for an unauthenticated caller.
|
|
27
|
+
*/
|
|
28
|
+
export function createNotificationsAdapter({ service, userToken, verifyServerCredential }) {
|
|
29
|
+
const authorize = async (req) => {
|
|
30
|
+
for (const name of BROWSER) delete req.headers[name];
|
|
31
|
+
const credential = req.headers[SERVER_CREDENTIAL], producer = req.headers[PRODUCER];
|
|
32
|
+
delete req.headers[SERVER_CREDENTIAL]; delete req.headers[PRODUCER];
|
|
33
|
+
if (credential === undefined) return producer === undefined ? 200 : 401;
|
|
34
|
+
if (typeof credential !== 'string' || !credential) return 401;
|
|
35
|
+
let verified;
|
|
36
|
+
try { verified = await verifyServerCredential(credential); } catch { return 503; }
|
|
37
|
+
if (verified !== true) return verified === false ? 401 : 503;
|
|
38
|
+
const path = new URL(req.url ?? '/', 'http://localhost').pathname;
|
|
39
|
+
if (producer !== undefined && !(req.method === 'POST' && ['/api/v1/send', '/api/v1/delete-target'].includes(path))) return 401;
|
|
40
|
+
req.headers.authorization = `Bearer ${producer ?? userToken}`;
|
|
41
|
+
return 200;
|
|
42
|
+
};
|
|
43
|
+
const server = createServer(async (req, res) => {
|
|
44
|
+
if (req.url === '/healthz' && req.method === 'GET') { res.writeHead(200, { 'content-type': 'application/json' }); res.end('{"ok":true}'); return; }
|
|
45
|
+
const status = await authorize(req);
|
|
46
|
+
if (status !== 200) {
|
|
47
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...(status === 503 ? { 'retry-after': '1' } : {}) });
|
|
48
|
+
res.end(status === 503 ? '{"error":{"code":"authentication_unavailable","message":"Server authentication is temporarily unavailable"}}' : '{"error":"authentication required"}'); return;
|
|
49
|
+
}
|
|
50
|
+
service.server.emit('request', req, res);
|
|
51
|
+
});
|
|
52
|
+
// Upgraded connections leave the HTTP server's connection tracking, so shutdown ends them itself.
|
|
53
|
+
const upgraded = new Set();
|
|
54
|
+
server.on('upgrade', async (req, socket, head) => {
|
|
55
|
+
upgraded.add(socket); socket.once('close', () => upgraded.delete(socket));
|
|
56
|
+
const status = await authorize(req);
|
|
57
|
+
if (status !== 200) { socket.end(`HTTP/1.1 ${status} ${status === 503 ? 'Service Unavailable' : 'Unauthorized'}\r\nConnection: close\r\n${status === 503 ? 'Retry-After: 1\r\n' : ''}Content-Length: 0\r\n\r\n`); return; }
|
|
58
|
+
service.server.emit('upgrade', req, socket, head);
|
|
59
|
+
});
|
|
60
|
+
return { server, async close() {
|
|
61
|
+
// Stop accepting first; the service then ends its presence sockets and saves state.
|
|
62
|
+
const listening = new Promise(resolve => server.close(() => resolve()));
|
|
63
|
+
server.closeAllConnections();
|
|
64
|
+
await service.close();
|
|
65
|
+
for (const socket of upgraded) socket.destroy();
|
|
66
|
+
await listening;
|
|
67
|
+
} };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The installer-generated private configuration also names the owner token this adapter injects. */
|
|
71
|
+
export function readPrivateConfig(path) {
|
|
72
|
+
const stat = statSync(path);
|
|
73
|
+
if (!stat.isFile() || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid()) throw new Error('Notification configuration must be a private owner file');
|
|
74
|
+
const config = JSON.parse(readFileSync(path, 'utf8'));
|
|
75
|
+
if (!Array.isArray(config.users) || config.users.length !== 1 || typeof config.users[0]?.token !== 'string') throw new Error('Notification configuration must select one owner');
|
|
76
|
+
return config;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
|
|
80
|
+
const config = readPrivateConfig(process.env.OURS_NOTIFICATIONS_CONFIG ?? '/var/lib/ours-notifications/config.json');
|
|
81
|
+
const { createNotificationService } = await import('/opt/ours/node_modules/@ours.network/notifications/dist/server.js');
|
|
82
|
+
const adapter = createNotificationsAdapter({
|
|
83
|
+
service: createNotificationService(config),
|
|
84
|
+
userToken: config.users[0].token,
|
|
85
|
+
verifyServerCredential: daemonCredentialCheck(process.env.OURS_DAEMON_URL ?? 'http://daemon:3050'),
|
|
86
|
+
});
|
|
87
|
+
await new Promise((resolve, reject) => { adapter.server.once('error', reject); adapter.server.listen(config.port, config.host, resolve); });
|
|
88
|
+
console.log('Notification service ready');
|
|
89
|
+
for (const signal of ['SIGTERM', 'SIGINT']) process.once(signal, async () => { await adapter.close(); process.exit(0); });
|
|
90
|
+
}
|