@reefclaw/openclaw-plugin 0.1.45 → 0.1.47
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 +1 -1
- package/bridge/bridge.js +3 -3
- package/bridge/config.js +5 -2
- package/bridge/gateway/gateway-config.d.ts +5 -0
- package/bridge/gateway/gateway-config.js +5 -2
- package/bridge/heartbeat-runs.js +2 -3
- package/bridge/heartbeat-transcript.d.ts +2 -0
- package/bridge/heartbeat-transcript.js +45 -13
- package/bridge/index.js +28 -0
- package/bridge/providers/connector-update.js +2 -3
- package/bridge/providers/emergency-commands.js +2 -3
- package/bridge/providers/gateway.d.ts +6 -0
- package/bridge/providers/gateway.js +40 -25
- package/bridge/providers/onboarding-commands.d.ts +8 -7
- package/bridge/setup.js +12 -0
- package/bridge/shock-wake.d.ts +7 -0
- package/bridge/shock-wake.js +60 -7
- package/bridge/utils/base-url.d.ts +26 -0
- package/bridge/utils/base-url.js +108 -0
- package/bridge/utils/operator-secret.d.ts +7 -0
- package/bridge/utils/operator-secret.js +59 -0
- package/bridge/utils/relay-host.d.ts +23 -0
- package/bridge/utils/relay-host.js +66 -0
- package/bridge/utils/untrusted-text.d.ts +9 -0
- package/bridge/utils/untrusted-text.js +51 -0
- package/config/base-url.d.ts +16 -0
- package/config/base-url.js +87 -0
- package/config/operator-provenance.d.ts +19 -0
- package/config/operator-provenance.js +102 -25
- package/config/user-data-stream-config.d.ts +5 -1
- package/config/user-data-stream-config.js +7 -5
- package/connector-supervisor.d.ts +15 -0
- package/connector-supervisor.js +22 -1
- package/index.js +33 -24
- package/ingest/position-decisions-client.js +23 -4
- package/ingest/retry-after.d.ts +5 -0
- package/ingest/retry-after.js +21 -0
- package/ingest/trade-store-client.js +18 -3
- package/lifecycle/process-role.d.ts +4 -0
- package/lifecycle/process-role.js +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +2 -2
- package/release-integrity.json +5 -0
- package/release-notes.json +2 -1
- package/risk/pre-trade-check.js +1 -1
- package/risk/stop-widening-guard.d.ts +35 -0
- package/risk/stop-widening-guard.js +98 -0
- package/skills/reefclaw/SKILL.md +2 -2
- package/tools/create-order.js +17 -12
- package/tools/get-bracket-config.d.ts +3 -1
- package/tools/get-bracket-config.js +3 -1
- package/tools/get-market-intel.d.ts +1 -0
- package/tools/get-market-intel.js +14 -3
- package/tools/modify-stop.d.ts +6 -0
- package/tools/modify-stop.js +110 -0
- package/tools/set-bracket-requirement.d.ts +7 -0
- package/tools/set-bracket-requirement.js +12 -0
- package/trading-params-bounds.d.ts +32 -0
- package/trading-params-bounds.js +113 -0
- package/trading-params-cache.d.ts +9 -1
- package/trading-params-cache.js +33 -2
package/bridge/shock-wake.js
CHANGED
|
@@ -41,7 +41,57 @@
|
|
|
41
41
|
// Env overrides: RC_SHOCK_WAKE_POLL_MS (60s), RC_SHOCK_WAKE_GATE_POLL_MS
|
|
42
42
|
// (5 min), RC_SHOCK_WAKE_COOLDOWN_MS (30 min), RC_SHOCK_WAKE_DAILY_CAP (8).
|
|
43
43
|
import { logger, formatError } from './logger.js';
|
|
44
|
+
import { labelOr, finiteOr } from './utils/untrusted-text.js';
|
|
45
|
+
import { resolveWebappBaseUrl } from './utils/base-url.js';
|
|
44
46
|
const TAG = 'shock-wake';
|
|
47
|
+
/** Coerce one intel row into a ShockEntry, or null when it is not one.
|
|
48
|
+
* The wake message interpolates `symbol` and `regime` into a
|
|
49
|
+
* system-authority agent turn, so they must be label-shaped tokens, never
|
|
50
|
+
* free text; numbers must be finite; flags must be strings
|
|
51
|
+
* (audit 2026-09-27 M5). A row that fails is dropped, not repaired. */
|
|
52
|
+
export function sanitizeShockEntry(raw) {
|
|
53
|
+
if (!raw || typeof raw !== 'object')
|
|
54
|
+
return null;
|
|
55
|
+
const r = raw;
|
|
56
|
+
const symbol = labelOr(r.symbol, '');
|
|
57
|
+
const time = typeof r.time === 'string' && r.time.length <= 40 ? r.time : '';
|
|
58
|
+
if (!symbol || !time)
|
|
59
|
+
return null;
|
|
60
|
+
const flags = Array.isArray(r.flags)
|
|
61
|
+
? r.flags.filter((f) => typeof f === 'string' && /^[a-z_]{1,32}$/.test(f))
|
|
62
|
+
: [];
|
|
63
|
+
const nums = ['shock30mAtr', 'range30mAtr', 'return1hPct', 'return4hPct', 'tape4hAtr'];
|
|
64
|
+
const n = {
|
|
65
|
+
shock30mAtr: 0, range30mAtr: 0, return1hPct: 0, return4hPct: 0, tape4hAtr: 0,
|
|
66
|
+
};
|
|
67
|
+
for (const k of nums) {
|
|
68
|
+
const v = finiteOr(r[k], Number.NaN);
|
|
69
|
+
if (!Number.isFinite(v))
|
|
70
|
+
return null;
|
|
71
|
+
n[k] = v;
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
symbol,
|
|
75
|
+
time,
|
|
76
|
+
flags,
|
|
77
|
+
...n,
|
|
78
|
+
regime: labelOr(r.regime, 'UNKNOWN'),
|
|
79
|
+
// `summary` is intel free text; the message never prints it.
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
export function sanitizeShockEntries(raw) {
|
|
83
|
+
if (!Array.isArray(raw))
|
|
84
|
+
return [];
|
|
85
|
+
const out = [];
|
|
86
|
+
for (const row of raw) {
|
|
87
|
+
const e = sanitizeShockEntry(row);
|
|
88
|
+
if (e)
|
|
89
|
+
out.push(e);
|
|
90
|
+
if (out.length >= 200)
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
45
95
|
/** Leaders whose lone shock is wake-worthy, as base coins (venue-stripped). */
|
|
46
96
|
const LEADER_COINS = new Set(['BTC', 'ETH']);
|
|
47
97
|
/** Majors (the platform's liquidation-pulse majors group): their participation
|
|
@@ -98,14 +148,16 @@ export function buildWakeMessage(a) {
|
|
|
98
148
|
const seen = new Set();
|
|
99
149
|
const lines = [];
|
|
100
150
|
for (const s of a.shocked) {
|
|
101
|
-
|
|
102
|
-
|
|
151
|
+
// Defence in depth: the poller sanitizes rows before assessment, but
|
|
152
|
+
// this function is exported — never let a raw string into the turn.
|
|
153
|
+
const coin = labelOr(coinOf(s.symbol), '');
|
|
154
|
+
if (!coin || seen.has(coin))
|
|
103
155
|
continue;
|
|
104
156
|
seen.add(coin);
|
|
105
157
|
const sign = (v) => (v >= 0 ? '+' : '');
|
|
106
|
-
lines.push(`- ${coin}: 30m ${Math.max(s.shock30mAtr, s.range30mAtr).toFixed(1)}×ATR, ` +
|
|
107
|
-
`1h ${sign(s.return1hPct)}${s.return1hPct}%, 4h ${sign(s.return4hPct)}${s.return4hPct}% ` +
|
|
108
|
-
`(regime label: ${s.regime})`);
|
|
158
|
+
lines.push(`- ${coin}: 30m ${Math.max(finiteOr(s.shock30mAtr, 0), finiteOr(s.range30mAtr, 0)).toFixed(1)}×ATR, ` +
|
|
159
|
+
`1h ${sign(finiteOr(s.return1hPct, 0))}${finiteOr(s.return1hPct, 0)}%, 4h ${sign(finiteOr(s.return4hPct, 0))}${finiteOr(s.return4hPct, 0)}% ` +
|
|
160
|
+
`(regime label: ${labelOr(s.regime, 'UNKNOWN')})`);
|
|
109
161
|
if (lines.length >= 6)
|
|
110
162
|
break;
|
|
111
163
|
}
|
|
@@ -199,7 +251,7 @@ export class ShockWakePoller {
|
|
|
199
251
|
this.awaitingSinceMs = null;
|
|
200
252
|
}
|
|
201
253
|
async refreshGate() {
|
|
202
|
-
const base = (this.opts.webappUrl
|
|
254
|
+
const base = resolveWebappBaseUrl(this.opts.webappUrl);
|
|
203
255
|
try {
|
|
204
256
|
const doFetch = this.opts.fetchImpl ?? fetch;
|
|
205
257
|
const res = await doFetch(`${base}/api/internal/config`, {
|
|
@@ -238,7 +290,8 @@ export class ShockWakePoller {
|
|
|
238
290
|
const body = (await res.json());
|
|
239
291
|
if (!Array.isArray(body?.shocks))
|
|
240
292
|
return;
|
|
241
|
-
|
|
293
|
+
// Only label-shaped, finite rows can reach the agent turn (M5).
|
|
294
|
+
const a = assessWakeWorthiness(sanitizeShockEntries(body.shocks), nowMs, this.minBroad);
|
|
242
295
|
if (!a.wake)
|
|
243
296
|
return;
|
|
244
297
|
// Rate limits — checked only for wake-worthy ticks so quiet markets
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare const DEFAULT_WEBAPP_URL = "https://www.reefclaw.com";
|
|
2
|
+
/** True for hosts where cleartext never leaves the machine / private network. */
|
|
3
|
+
export declare function isPrivateHost(hostname: string): boolean;
|
|
4
|
+
export interface UrlCheck {
|
|
5
|
+
url: string;
|
|
6
|
+
/** Present when the configured value was rejected and `url` is the fallback. */
|
|
7
|
+
rejected?: {
|
|
8
|
+
value: string;
|
|
9
|
+
reason: string;
|
|
10
|
+
};
|
|
11
|
+
/** Present when cleartext was tolerated because the host is private. */
|
|
12
|
+
insecurePrivate?: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** Validate an https base URL without side effects. */
|
|
15
|
+
export declare function checkBaseUrl(raw: unknown, fallback: string): UrlCheck;
|
|
16
|
+
/** Validate a wss relay URL without side effects. */
|
|
17
|
+
export declare function checkRelayUrl(raw: unknown, fallback: string): UrlCheck;
|
|
18
|
+
/** Validate + log an https base URL. Returns the URL the caller must use. */
|
|
19
|
+
export declare function sanitizeBaseUrl(raw: unknown, fallback: string, label: string): string;
|
|
20
|
+
/** Validate + log a wss relay URL. Returns the URL the caller must use. */
|
|
21
|
+
export declare function sanitizeRelayUrl(raw: unknown, fallback: string, label: string): string;
|
|
22
|
+
/** The webapp base URL every bridge call must use: an explicit override,
|
|
23
|
+
* else `REEFCLAW_API_URL`, else production — scheme-checked. `www` is
|
|
24
|
+
* load-bearing in the default: reefclaw.com 307-redirects and Node fetch
|
|
25
|
+
* strips the Authorization header on a cross-origin redirect. */
|
|
26
|
+
export declare function resolveWebappBaseUrl(override?: string): string;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Outbound URL scheme check for the bridge's own service endpoints.
|
|
2
|
+
//
|
|
3
|
+
// Copy of plugin/src/config/base-url.ts (the bridge and the plugin are
|
|
4
|
+
// separately vendored packages; keep the two in sync like the redact.ts
|
|
5
|
+
// copies). The bridge sends the tenant's rc_ token as a Bearer header to the
|
|
6
|
+
// webapp (REEFCLAW_API_URL) and to intel (intelligenceUrl), and its relay
|
|
7
|
+
// socket carries the token in the auth query. Before this module a plain
|
|
8
|
+
// `http://` / `ws://` value from the environment or config was used verbatim
|
|
9
|
+
// (audit 2026-09-27 H4).
|
|
10
|
+
//
|
|
11
|
+
// Rule: `https:` / `wss:` required for any public host. Cleartext (`http:` /
|
|
12
|
+
// `ws:`) is tolerated ONLY for loopback and private-range hosts (localhost,
|
|
13
|
+
// RFC 1918, the 100.64/10 CGNAT block Tailscale uses, link-local, ULA) — the
|
|
14
|
+
// local-dev (`partykit dev`) / on-prem cases — with a warning. Anything else
|
|
15
|
+
// falls back to the production default. No env override on purpose.
|
|
16
|
+
import { logger } from '../logger.js';
|
|
17
|
+
const TAG = 'base-url';
|
|
18
|
+
export const DEFAULT_WEBAPP_URL = 'https://www.reefclaw.com';
|
|
19
|
+
/** True for hosts where cleartext never leaves the machine / private network. */
|
|
20
|
+
export function isPrivateHost(hostname) {
|
|
21
|
+
const h = hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
22
|
+
if (h === 'localhost' || h.endsWith('.localhost') || h === '::1' || h === '0.0.0.0')
|
|
23
|
+
return true;
|
|
24
|
+
// Names that only resolve inside a private network: Docker's host alias,
|
|
25
|
+
// mDNS `.local`, `.internal` (RFC 6762 / 8375), Tailscale MagicDNS `.ts.net`.
|
|
26
|
+
// Review 2026-09-27 N2: a dev/staging box on one of these was classified
|
|
27
|
+
// public and silently fell back to the PRODUCTION URL with its token.
|
|
28
|
+
if (h === 'host.docker.internal' || h.endsWith('.internal') || h.endsWith('.local') || h.endsWith('.ts.net'))
|
|
29
|
+
return true;
|
|
30
|
+
const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
31
|
+
if (v4) {
|
|
32
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
33
|
+
if (a === 127)
|
|
34
|
+
return true; // loopback
|
|
35
|
+
if (a === 10)
|
|
36
|
+
return true; // RFC 1918
|
|
37
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
38
|
+
return true; // RFC 1918
|
|
39
|
+
if (a === 192 && b === 168)
|
|
40
|
+
return true; // RFC 1918
|
|
41
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
42
|
+
return true; // CGNAT / Tailscale
|
|
43
|
+
if (a === 169 && b === 254)
|
|
44
|
+
return true; // link-local
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
// IPv6 ULA (fc00::/7) and link-local (fe80::/10).
|
|
48
|
+
if (/^f[cd][0-9a-f]{2}:/.test(h) || /^fe[89ab][0-9a-f]:/.test(h))
|
|
49
|
+
return true;
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
function checkScheme(raw, fallback, secure, clear) {
|
|
53
|
+
if (typeof raw !== 'string' || raw.trim() === '')
|
|
54
|
+
return { url: fallback };
|
|
55
|
+
const value = raw.trim();
|
|
56
|
+
let parsed;
|
|
57
|
+
try {
|
|
58
|
+
parsed = new URL(value);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return { url: fallback, rejected: { value, reason: 'not a valid absolute URL' } };
|
|
62
|
+
}
|
|
63
|
+
const normalized = value.replace(/\/+$/, '');
|
|
64
|
+
if (parsed.protocol === secure)
|
|
65
|
+
return { url: normalized };
|
|
66
|
+
if (parsed.protocol === clear) {
|
|
67
|
+
if (isPrivateHost(parsed.hostname))
|
|
68
|
+
return { url: normalized, insecurePrivate: true };
|
|
69
|
+
return {
|
|
70
|
+
url: fallback,
|
|
71
|
+
rejected: { value, reason: `plain ${clear}// to a public host would send the connection token in cleartext` },
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return { url: fallback, rejected: { value, reason: `unsupported scheme ${parsed.protocol}` } };
|
|
75
|
+
}
|
|
76
|
+
/** Validate an https base URL without side effects. */
|
|
77
|
+
export function checkBaseUrl(raw, fallback) {
|
|
78
|
+
return checkScheme(raw, fallback, 'https:', 'http:');
|
|
79
|
+
}
|
|
80
|
+
/** Validate a wss relay URL without side effects. */
|
|
81
|
+
export function checkRelayUrl(raw, fallback) {
|
|
82
|
+
return checkScheme(raw, fallback, 'wss:', 'ws:');
|
|
83
|
+
}
|
|
84
|
+
function report(check, fallback, label) {
|
|
85
|
+
if (check.rejected) {
|
|
86
|
+
logger.warn(TAG, `${label}=${JSON.stringify(check.rejected.value)} rejected (${check.rejected.reason}) — using ${fallback}`);
|
|
87
|
+
}
|
|
88
|
+
else if (check.insecurePrivate) {
|
|
89
|
+
logger.warn(TAG, `${label}=${check.url} uses a cleartext scheme to a private host — tolerated for local/on-prem use only`);
|
|
90
|
+
}
|
|
91
|
+
return check.url;
|
|
92
|
+
}
|
|
93
|
+
/** Validate + log an https base URL. Returns the URL the caller must use. */
|
|
94
|
+
export function sanitizeBaseUrl(raw, fallback, label) {
|
|
95
|
+
return report(checkBaseUrl(raw, fallback), fallback, label);
|
|
96
|
+
}
|
|
97
|
+
/** Validate + log a wss relay URL. Returns the URL the caller must use. */
|
|
98
|
+
export function sanitizeRelayUrl(raw, fallback, label) {
|
|
99
|
+
return report(checkRelayUrl(raw, fallback), fallback, label);
|
|
100
|
+
}
|
|
101
|
+
/** The webapp base URL every bridge call must use: an explicit override,
|
|
102
|
+
* else `REEFCLAW_API_URL`, else production — scheme-checked. `www` is
|
|
103
|
+
* load-bearing in the default: reefclaw.com 307-redirects and Node fetch
|
|
104
|
+
* strips the Authorization header on a cross-origin redirect. */
|
|
105
|
+
export function resolveWebappBaseUrl(override) {
|
|
106
|
+
const raw = override ?? process.env.REEFCLAW_API_URL;
|
|
107
|
+
return sanitizeBaseUrl(raw, DEFAULT_WEBAPP_URL, 'REEFCLAW_API_URL');
|
|
108
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const OPERATOR_SECRET_STDIN_MARKER = "REEFCLAW_OPERATOR_SECRET_STDIN";
|
|
2
|
+
/** Read one line from `fd` (default stdin) synchronously. Returns the line
|
|
3
|
+
* without its newline, or undefined on EOF / oversize / read error. */
|
|
4
|
+
export declare function readSecretLine(fd?: number): string | undefined;
|
|
5
|
+
/** The provenance secret for this process, or undefined when the plugin did
|
|
6
|
+
* not spawn us (no marker) or the line could not be read. */
|
|
7
|
+
export declare function readOperatorSecretFromStdin(env?: NodeJS.ProcessEnv, fd?: number): string | undefined;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Operator-provenance secret handed to this bridge by the plugin that
|
|
2
|
+
// supervises it (plugin/src/connector-supervisor.ts, audit 2026-09-27 H1).
|
|
3
|
+
//
|
|
4
|
+
// The plugin mints a random per-boot value, spawns the bridge with stdin as a
|
|
5
|
+
// pipe, writes the secret as ONE line and closes the pipe. The bridge attaches
|
|
6
|
+
// it as `operator_token` on the operator-only tools (set_trading_mode,
|
|
7
|
+
// credential tools, set_bracket_requirement, …); the plugin accepts nothing
|
|
8
|
+
// else while a secret is issued. It never touches argv, the environment, or
|
|
9
|
+
// disk — the three places a same-user agent process can read.
|
|
10
|
+
//
|
|
11
|
+
// The environment carries only a non-secret MARKER (value '1') so a bridge
|
|
12
|
+
// started any other way (systemd unit, `node dist/index.js` by hand) does not
|
|
13
|
+
// block on a stdin that nobody will write to.
|
|
14
|
+
import { readSync } from 'node:fs';
|
|
15
|
+
export const OPERATOR_SECRET_STDIN_MARKER = 'REEFCLAW_OPERATOR_SECRET_STDIN';
|
|
16
|
+
/** A secret is 64 hex chars; anything past this is not ours. */
|
|
17
|
+
const MAX_LINE = 512;
|
|
18
|
+
/** EAGAIN retries before giving up (≈2 s at 5 ms). A non-blocking fd 0 with
|
|
19
|
+
* no writer must never spin the CPU forever (review 2026-09-27 N5). */
|
|
20
|
+
const MAX_EAGAIN_RETRIES = 400;
|
|
21
|
+
const EAGAIN_WAIT_MS = 5;
|
|
22
|
+
/** Read one line from `fd` (default stdin) synchronously. Returns the line
|
|
23
|
+
* without its newline, or undefined on EOF / oversize / read error. */
|
|
24
|
+
export function readSecretLine(fd = 0) {
|
|
25
|
+
const buf = Buffer.alloc(1);
|
|
26
|
+
let line = '';
|
|
27
|
+
let eagain = 0;
|
|
28
|
+
for (;;) {
|
|
29
|
+
let n;
|
|
30
|
+
try {
|
|
31
|
+
n = readSync(fd, buf, 0, 1, null);
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
// EAGAIN on a non-blocking stdin: retry briefly (bounded); anything else = give up.
|
|
35
|
+
if (err.code === 'EAGAIN' && eagain++ < MAX_EAGAIN_RETRIES) {
|
|
36
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, EAGAIN_WAIT_MS);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
if (n === 0)
|
|
42
|
+
return line.length > 0 ? line : undefined; // EOF
|
|
43
|
+
const ch = buf.toString('utf8');
|
|
44
|
+
if (ch === '\n')
|
|
45
|
+
return line;
|
|
46
|
+
if (ch !== '\r')
|
|
47
|
+
line += ch;
|
|
48
|
+
if (line.length > MAX_LINE)
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** The provenance secret for this process, or undefined when the plugin did
|
|
53
|
+
* not spawn us (no marker) or the line could not be read. */
|
|
54
|
+
export function readOperatorSecretFromStdin(env = process.env, fd = 0) {
|
|
55
|
+
if (env[OPERATOR_SECRET_STDIN_MARKER] !== '1')
|
|
56
|
+
return undefined;
|
|
57
|
+
const line = readSecretLine(fd)?.trim();
|
|
58
|
+
return line && /^[A-Za-z0-9._~+/=-]{16,}$/.test(line) ? line : undefined;
|
|
59
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Hosts (exact, lowercase) or suffixes (leading dot) of ReefClaw relays. */
|
|
2
|
+
export declare const ALLOWED_RELAY_HOSTS: readonly string[];
|
|
3
|
+
export declare const ALLOW_CUSTOM_RELAY_ENV = "REEFCLAW_ALLOW_CUSTOM_RELAY";
|
|
4
|
+
export type RelayHostVerdict = {
|
|
5
|
+
ok: true;
|
|
6
|
+
host: string;
|
|
7
|
+
reason: 'allowlisted' | 'private_dev' | 'custom_opt_in';
|
|
8
|
+
} | {
|
|
9
|
+
ok: false;
|
|
10
|
+
host: string | null;
|
|
11
|
+
reason: 'unparseable' | 'not_allowlisted';
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Decide whether the bridge may connect to `relayUrl`.
|
|
15
|
+
* - a ReefClaw host (exact or suffix match) → ok;
|
|
16
|
+
* - loopback / private hosts (partykit dev) → ok;
|
|
17
|
+
* - anything else → ok only when `allowCustom` (the env opt-out) is set.
|
|
18
|
+
*/
|
|
19
|
+
export declare function checkRelayHost(relayUrl: string, allowCustom?: boolean): RelayHostVerdict;
|
|
20
|
+
/** Operator-facing explanation for a refused relay host. */
|
|
21
|
+
export declare function describeRelayRefusal(v: Extract<RelayHostVerdict, {
|
|
22
|
+
ok: false;
|
|
23
|
+
}>): string;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Relay host allowlist for the connect bundle (audit 2026-09-27 M11).
|
|
2
|
+
//
|
|
3
|
+
// The onboarding "connect message" carries the rc_ token, the userId AND the
|
|
4
|
+
// relay URL. Before this module any `wss://` host in a pasted message was
|
|
5
|
+
// accepted: a phished or rewritten message pointed the bridge at an attacker
|
|
6
|
+
// relay, which then received the real token in the Authorization header,
|
|
7
|
+
// authenticated as the agent to the webapp and intel, and squatted the skill
|
|
8
|
+
// slot. Only ReefClaw relay hosts are accepted now; a self-hoster running
|
|
9
|
+
// their own relay opts out explicitly with REEFCLAW_ALLOW_CUSTOM_RELAY=1.
|
|
10
|
+
//
|
|
11
|
+
// The installer itself saves whatever wss:// host the connect message names
|
|
12
|
+
// (installer/src/bundle.ts); this module is the enforcement point — the bridge
|
|
13
|
+
// refuses to start against a host outside the list (skill/src/index.ts).
|
|
14
|
+
// (Review 2026-09-27: an earlier comment here claimed an installer-side copy
|
|
15
|
+
// that does not exist.)
|
|
16
|
+
/** Hosts (exact, lowercase) or suffixes (leading dot) of ReefClaw relays. */
|
|
17
|
+
export const ALLOWED_RELAY_HOSTS = [
|
|
18
|
+
'reefclaw.radunlupsa.partykit.dev',
|
|
19
|
+
'.reefclaw.com',
|
|
20
|
+
'.reefclaw.partykit.dev',
|
|
21
|
+
];
|
|
22
|
+
export const ALLOW_CUSTOM_RELAY_ENV = 'REEFCLAW_ALLOW_CUSTOM_RELAY';
|
|
23
|
+
function isPrivateHost(h) {
|
|
24
|
+
if (h === 'localhost' || h.endsWith('.localhost') || h === '::1' || h === '[::1]')
|
|
25
|
+
return true;
|
|
26
|
+
const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
27
|
+
if (!v4)
|
|
28
|
+
return false;
|
|
29
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
30
|
+
return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Decide whether the bridge may connect to `relayUrl`.
|
|
34
|
+
* - a ReefClaw host (exact or suffix match) → ok;
|
|
35
|
+
* - loopback / private hosts (partykit dev) → ok;
|
|
36
|
+
* - anything else → ok only when `allowCustom` (the env opt-out) is set.
|
|
37
|
+
*/
|
|
38
|
+
export function checkRelayHost(relayUrl, allowCustom = process.env[ALLOW_CUSTOM_RELAY_ENV] === '1') {
|
|
39
|
+
let host;
|
|
40
|
+
try {
|
|
41
|
+
host = new URL(relayUrl).hostname.toLowerCase();
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return { ok: false, host: null, reason: 'unparseable' };
|
|
45
|
+
}
|
|
46
|
+
if (!host)
|
|
47
|
+
return { ok: false, host: null, reason: 'unparseable' };
|
|
48
|
+
for (const entry of ALLOWED_RELAY_HOSTS) {
|
|
49
|
+
if (entry.startsWith('.') ? host.endsWith(entry) || host === entry.slice(1) : host === entry) {
|
|
50
|
+
return { ok: true, host, reason: 'allowlisted' };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (isPrivateHost(host))
|
|
54
|
+
return { ok: true, host, reason: 'private_dev' };
|
|
55
|
+
if (allowCustom)
|
|
56
|
+
return { ok: true, host, reason: 'custom_opt_in' };
|
|
57
|
+
return { ok: false, host, reason: 'not_allowlisted' };
|
|
58
|
+
}
|
|
59
|
+
/** Operator-facing explanation for a refused relay host. */
|
|
60
|
+
export function describeRelayRefusal(v) {
|
|
61
|
+
return v.reason === 'unparseable'
|
|
62
|
+
? 'The relay URL in the connect message could not be parsed.'
|
|
63
|
+
: `The relay host "${v.host}" is not a ReefClaw relay. A connect message from reefclaw.com always points at ` +
|
|
64
|
+
`${ALLOWED_RELAY_HOSTS[0]} — a different host means the message was altered, and connecting would hand it your token. ` +
|
|
65
|
+
`Self-hosting your own relay? Set ${ALLOW_CUSTOM_RELAY_ENV}=1 in the connector's environment to allow it.`;
|
|
66
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Strip hidden code points, fold every whitespace run (incl. newlines) to one
|
|
2
|
+
* space, trim, cap at `max` chars (with a visible marker when cut). */
|
|
3
|
+
export declare function fenceInlineText(raw: unknown, max?: number): string;
|
|
4
|
+
/** Accept only a label-shaped token (letters, digits, `_`, `-`, `/`, `:`, `.`);
|
|
5
|
+
* anything else — including an empty string — becomes `fallback`. For
|
|
6
|
+
* fields that are enum-like on the wire (symbol, regime, strategy, direction). */
|
|
7
|
+
export declare function labelOr(raw: unknown, fallback: string, max?: number): string;
|
|
8
|
+
/** A finite number, else `fallback`. JSON from a service can carry anything. */
|
|
9
|
+
export declare function finiteOr(raw: unknown, fallback: number): number;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Untrusted-text hygiene for strings the bridge interpolates into AGENT TURNS
|
|
2
|
+
// (shock wakes, mission presentations). Those turns carry system authority in
|
|
3
|
+
// the agent's context, so an intel-supplied string that reaches them verbatim
|
|
4
|
+
// is a prompt-injection channel (audit 2026-09-27 M5). Mirror of the plugin's
|
|
5
|
+
// tools/get-market-intel.ts sanitizer (separately vendored package; keep in
|
|
6
|
+
// sync): strips control / zero-width / bidi-override code points that hide or
|
|
7
|
+
// spoof injected instructions, collapses line breaks (a newline inside a
|
|
8
|
+
// "label" would let it fake a new bullet or header of OUR message), and caps
|
|
9
|
+
// length.
|
|
10
|
+
const HIDDEN_CODEPOINT_RANGES = [
|
|
11
|
+
[0x00, 0x08], [0x0b, 0x1f], [0x7f, 0x9f], // C0 (keep TAB/LF for now — collapsed below), DEL + C1
|
|
12
|
+
[0x200b, 0x200f], // zero-width space/joiner + LRM/RLM
|
|
13
|
+
[0x202a, 0x202e], // bidi embeddings/overrides
|
|
14
|
+
[0x2066, 0x2069], // bidi isolates
|
|
15
|
+
[0xfeff, 0xfeff], // BOM
|
|
16
|
+
];
|
|
17
|
+
function isHidden(cp) {
|
|
18
|
+
for (const [lo, hi] of HIDDEN_CODEPOINT_RANGES)
|
|
19
|
+
if (cp >= lo && cp <= hi)
|
|
20
|
+
return true;
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
/** Strip hidden code points, fold every whitespace run (incl. newlines) to one
|
|
24
|
+
* space, trim, cap at `max` chars (with a visible marker when cut). */
|
|
25
|
+
export function fenceInlineText(raw, max = 200) {
|
|
26
|
+
if (typeof raw !== 'string')
|
|
27
|
+
return '';
|
|
28
|
+
let out = '';
|
|
29
|
+
for (const ch of raw) {
|
|
30
|
+
const cp = ch.codePointAt(0);
|
|
31
|
+
if (cp !== undefined && !isHidden(cp))
|
|
32
|
+
out += ch;
|
|
33
|
+
}
|
|
34
|
+
out = out.replace(/\s+/g, ' ').trim();
|
|
35
|
+
return out.length > max ? `${out.slice(0, max)}…` : out;
|
|
36
|
+
}
|
|
37
|
+
/** Accept only a label-shaped token (letters, digits, `_`, `-`, `/`, `:`, `.`);
|
|
38
|
+
* anything else — including an empty string — becomes `fallback`. For
|
|
39
|
+
* fields that are enum-like on the wire (symbol, regime, strategy, direction). */
|
|
40
|
+
export function labelOr(raw, fallback, max = 32) {
|
|
41
|
+
if (typeof raw !== 'string')
|
|
42
|
+
return fallback;
|
|
43
|
+
const s = raw.trim();
|
|
44
|
+
if (s.length === 0 || s.length > max || !/^[A-Za-z0-9_\-/:.]+$/.test(s))
|
|
45
|
+
return fallback;
|
|
46
|
+
return s;
|
|
47
|
+
}
|
|
48
|
+
/** A finite number, else `fallback`. JSON from a service can carry anything. */
|
|
49
|
+
export function finiteOr(raw, fallback) {
|
|
50
|
+
return typeof raw === 'number' && Number.isFinite(raw) ? raw : fallback;
|
|
51
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** True for hosts where cleartext never leaves the machine / private network. */
|
|
2
|
+
export declare function isPrivateHost(hostname: string): boolean;
|
|
3
|
+
export interface BaseUrlCheck {
|
|
4
|
+
url: string;
|
|
5
|
+
/** Present when the configured value was rejected and `url` is the fallback. */
|
|
6
|
+
rejected?: {
|
|
7
|
+
value: string;
|
|
8
|
+
reason: string;
|
|
9
|
+
};
|
|
10
|
+
/** Present when cleartext was tolerated because the host is private. */
|
|
11
|
+
insecurePrivate?: boolean;
|
|
12
|
+
}
|
|
13
|
+
/** Validate a configured base URL without side effects. */
|
|
14
|
+
export declare function checkBaseUrl(raw: unknown, fallback: string): BaseUrlCheck;
|
|
15
|
+
/** Validate + log. Returns the URL the caller must use. */
|
|
16
|
+
export declare function sanitizeBaseUrl(raw: unknown, fallback: string, label: string): string;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Outbound base-URL scheme check for the plugin's own service endpoints.
|
|
2
|
+
//
|
|
3
|
+
// The plugin sends the tenant's rc_ token as a Bearer header to the webapp
|
|
4
|
+
// (apiBaseUrl / ingestBaseUrl) and to the intel service (intelligenceUrl), and
|
|
5
|
+
// takes the trading-parameter policy back from intel. Before this module a
|
|
6
|
+
// plain `http://` value in plugin-config.json was accepted verbatim, so one
|
|
7
|
+
// local edit put the token and every telemetry payload on the wire in
|
|
8
|
+
// cleartext and let an on-path party answer as "intel" (audit 2026-09-27 H4).
|
|
9
|
+
//
|
|
10
|
+
// Rule: `https:` is required for any public host. `http:` is tolerated ONLY
|
|
11
|
+
// for loopback and private-range hosts (localhost, RFC 1918, the 100.64/10
|
|
12
|
+
// CGNAT block Tailscale uses, link-local, ULA) — the local-dev / on-prem
|
|
13
|
+
// cases — with a warning. Anything else falls back to the production default
|
|
14
|
+
// and logs why. No env override on purpose: an environment switch that
|
|
15
|
+
// downgrades transport security is the class of knob CLAUDE.md says must not
|
|
16
|
+
// exist (M14).
|
|
17
|
+
import { logger } from '../logger.js';
|
|
18
|
+
const TAG = 'base-url';
|
|
19
|
+
/** True for hosts where cleartext never leaves the machine / private network. */
|
|
20
|
+
export function isPrivateHost(hostname) {
|
|
21
|
+
const h = hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
22
|
+
if (h === 'localhost' || h.endsWith('.localhost') || h === '::1' || h === '0.0.0.0')
|
|
23
|
+
return true;
|
|
24
|
+
// Names that only resolve inside a private network: Docker's host alias,
|
|
25
|
+
// mDNS `.local`, `.internal` (RFC 6762 / 8375), Tailscale MagicDNS `.ts.net`.
|
|
26
|
+
// Review 2026-09-27 N2: a dev/staging box on one of these was classified
|
|
27
|
+
// public and silently fell back to the PRODUCTION URL with its token.
|
|
28
|
+
if (h === 'host.docker.internal' || h.endsWith('.internal') || h.endsWith('.local') || h.endsWith('.ts.net'))
|
|
29
|
+
return true;
|
|
30
|
+
const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
31
|
+
if (v4) {
|
|
32
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
33
|
+
if (a === 127)
|
|
34
|
+
return true; // loopback
|
|
35
|
+
if (a === 10)
|
|
36
|
+
return true; // RFC 1918
|
|
37
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
38
|
+
return true; // RFC 1918
|
|
39
|
+
if (a === 192 && b === 168)
|
|
40
|
+
return true; // RFC 1918
|
|
41
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
42
|
+
return true; // CGNAT / Tailscale
|
|
43
|
+
if (a === 169 && b === 254)
|
|
44
|
+
return true; // link-local
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
// IPv6 ULA (fc00::/7) and link-local (fe80::/10).
|
|
48
|
+
if (/^f[cd][0-9a-f]{2}:/.test(h) || /^fe[89ab][0-9a-f]:/.test(h))
|
|
49
|
+
return true;
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
/** Validate a configured base URL without side effects. */
|
|
53
|
+
export function checkBaseUrl(raw, fallback) {
|
|
54
|
+
if (typeof raw !== 'string' || raw.trim() === '')
|
|
55
|
+
return { url: fallback };
|
|
56
|
+
const value = raw.trim();
|
|
57
|
+
let parsed;
|
|
58
|
+
try {
|
|
59
|
+
parsed = new URL(value);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return { url: fallback, rejected: { value, reason: 'not a valid absolute URL' } };
|
|
63
|
+
}
|
|
64
|
+
const normalized = value.replace(/\/+$/, '');
|
|
65
|
+
if (parsed.protocol === 'https:')
|
|
66
|
+
return { url: normalized };
|
|
67
|
+
if (parsed.protocol === 'http:') {
|
|
68
|
+
if (isPrivateHost(parsed.hostname))
|
|
69
|
+
return { url: normalized, insecurePrivate: true };
|
|
70
|
+
return {
|
|
71
|
+
url: fallback,
|
|
72
|
+
rejected: { value, reason: 'plain http:// to a public host would send the connection token in cleartext' },
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
return { url: fallback, rejected: { value, reason: `unsupported scheme ${parsed.protocol}` } };
|
|
76
|
+
}
|
|
77
|
+
/** Validate + log. Returns the URL the caller must use. */
|
|
78
|
+
export function sanitizeBaseUrl(raw, fallback, label) {
|
|
79
|
+
const check = checkBaseUrl(raw, fallback);
|
|
80
|
+
if (check.rejected) {
|
|
81
|
+
logger.warn(TAG, `${label}=${JSON.stringify(check.rejected.value)} rejected (${check.rejected.reason}) — using ${fallback}`);
|
|
82
|
+
}
|
|
83
|
+
else if (check.insecurePrivate) {
|
|
84
|
+
logger.warn(TAG, `${label}=${check.url} uses plain http to a private host — cleartext tolerated for local/on-prem use only`);
|
|
85
|
+
}
|
|
86
|
+
return check.url;
|
|
87
|
+
}
|
|
@@ -3,4 +3,23 @@ export interface ProvenanceVerdict {
|
|
|
3
3
|
/** Agent-legible refusal — returned verbatim as the tool error. */
|
|
4
4
|
error?: string;
|
|
5
5
|
}
|
|
6
|
+
/** Mint (once per process) the per-boot secret the supervised bridge will
|
|
7
|
+
* present as `operator_token`. Idempotent: repeat calls return the same
|
|
8
|
+
* value so every module instance of this plugin agrees. */
|
|
9
|
+
export declare function issueOperatorSecret(): string;
|
|
10
|
+
/** The issued secret, or null when this process never spawned a bridge. */
|
|
11
|
+
export declare function currentOperatorSecret(): string | null;
|
|
6
12
|
export declare function verifyOperatorProvenance(provided: unknown, configPath?: string): ProvenanceVerdict;
|
|
13
|
+
/** Tool-result envelope for a refusal. Carries BOTH `error` (what every
|
|
14
|
+
* plugin tool returns and the agent reads) and `ok:false` + `message` (what
|
|
15
|
+
* the bridge's execute* wrappers pass through and the dashboard's
|
|
16
|
+
* TradingModeControl / ExchangeConnection render). Review 2026-09-27 B2: a
|
|
17
|
+
* bare `{error}` reached the dashboard as an EMPTY red box, so the stale-
|
|
18
|
+
* connector window this scheme creates was silent to the operator. */
|
|
19
|
+
export declare function provenanceRefusal(v: ProvenanceVerdict): {
|
|
20
|
+
ok: false;
|
|
21
|
+
error: string;
|
|
22
|
+
message: string;
|
|
23
|
+
};
|
|
24
|
+
/** Test-only: forget the issued secret and the one-time warning. */
|
|
25
|
+
export declare function resetOperatorProvenanceForTest(): void;
|