@reefclaw/openclaw-plugin 0.1.45 → 0.1.48
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.d.ts +39 -0
- package/bridge/bridge.js +210 -7
- 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/gateway/heartbeat-cron.js +3 -2
- package/bridge/heartbeat-runs.d.ts +6 -0
- package/bridge/heartbeat-runs.js +45 -4
- package/bridge/heartbeat-transcript.d.ts +2 -0
- package/bridge/heartbeat-transcript.js +45 -13
- package/bridge/index.js +31 -0
- package/bridge/providers/connector-update.js +22 -5
- package/bridge/providers/emergency-commands.js +2 -3
- package/bridge/providers/gateway.d.ts +6 -0
- package/bridge/providers/gateway.js +57 -27
- 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 +72 -9
- package/bridge/types.d.ts +17 -0
- 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/bridge/utils/webapp-edge.d.ts +145 -0
- package/bridge/utils/webapp-edge.js +366 -0
- package/config/agent-config-client.js +18 -2
- package/config/agent-config-poller.d.ts +4 -0
- package/config/agent-config-poller.js +46 -6
- 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/http/webapp-edge.d.ts +116 -0
- package/http/webapp-edge.js +313 -0
- package/index.js +36 -24
- package/ingest/position-decisions-client.js +51 -11
- package/ingest/readiness-reporter.d.ts +13 -0
- package/ingest/readiness-reporter.js +78 -8
- package/ingest/retry-after.d.ts +5 -0
- package/ingest/retry-after.js +21 -0
- package/ingest/trade-store-client.js +43 -7
- 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 +10 -0
- package/release-notes.json +3 -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 +4 -0
- package/tools/get-market-intel.js +38 -4
- 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
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// Edge-deny detection + backoff for the plugin's webapp (reefclaw.com) calls.
|
|
2
|
+
//
|
|
3
|
+
// Why (2026-09-28): Vercel's automatic DDoS mitigation ("System Mitigations",
|
|
4
|
+
// nothing the operator configured) put a rolling 30-minute Deny on the IP of a
|
|
5
|
+
// host running four OpenClaw boxes. Every plugin→webapp call answered
|
|
6
|
+
// `403 Forbidden` (plain text, `x-vercel-mitigated: deny`) while the relay kept
|
|
7
|
+
// working — so the dashboard showed Connected and all-green while the SKILL.md
|
|
8
|
+
// pull, central config, readiness, the position journal and the heartbeat
|
|
9
|
+
// recorder were all dead, and every client kept polling at full cadence
|
|
10
|
+
// through the ban. Worse, the clients read the 403 as "Pro subscription
|
|
11
|
+
// required" / "connect the account first": a firewall verdict reported as an
|
|
12
|
+
// account problem.
|
|
13
|
+
//
|
|
14
|
+
// This module gives every webapp client one shared verdict and one shared
|
|
15
|
+
// brake:
|
|
16
|
+
// • classifyEdgeDeny() — is this 403 the edge (Vercel) or the app? The app's
|
|
17
|
+
// own denials are JSON (`{error: …}`); the edge answers plain text with an
|
|
18
|
+
// `x-vercel-mitigated` header. Only the edge shape counts.
|
|
19
|
+
// • WebappEdgeGate — process-wide backoff (5 → 10 → 20 → 30 min, the
|
|
20
|
+
// 30-min cap matching Vercel's persistent-action window). Periodic callers
|
|
21
|
+
// skip their call while blocked; the gate reopens on its own and the next
|
|
22
|
+
// successful call resets it. Same shape as the Binance ban gate.
|
|
23
|
+
// • a state file (~/.reefclaw/webapp-edge-state.json) so the connector — the
|
|
24
|
+
// process that still reaches the dashboard over the relay — can surface
|
|
25
|
+
// the episode (agent_state health.webappApi) even though every HTTP path
|
|
26
|
+
// to the webapp is the thing being denied.
|
|
27
|
+
// • webappHeaders() — one place for the Bearer header + a real
|
|
28
|
+
// User-Agent (`reefclaw-plugin/<release>`), so our traffic is nameable in
|
|
29
|
+
// the edge's traffic view instead of showing up as "node".
|
|
30
|
+
//
|
|
31
|
+
// Everything here fails open: a missing state dir, an unreadable header, a
|
|
32
|
+
// classifier miss — nothing throws into a caller, and the gate never blocks
|
|
33
|
+
// anything but the plugin's OWN optional webapp traffic (never trading, never
|
|
34
|
+
// the safety floor, never the exchange).
|
|
35
|
+
import { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
|
|
36
|
+
import { dirname, join } from 'node:path';
|
|
37
|
+
import { homedir } from 'node:os';
|
|
38
|
+
import { logger, formatError } from '../logger.js';
|
|
39
|
+
const TAG = 'webapp-edge';
|
|
40
|
+
/**
|
|
41
|
+
* Decide whether a 403 came from the edge rather than the webapp. Pure.
|
|
42
|
+
*
|
|
43
|
+
* The webapp's own 403s (entitlement walls, verifyProAccess) are JSON with an
|
|
44
|
+
* `error` field; authInternalRequest answers 401 JSON. The Vercel edge answers
|
|
45
|
+
* `403` with `content-type: text/plain`, a body that starts with "Forbidden"
|
|
46
|
+
* and the `x-vercel-mitigated` header. Anything else → null (not an edge deny).
|
|
47
|
+
*/
|
|
48
|
+
export function classifyEdgeDeny(status, headers, bodyText) {
|
|
49
|
+
if (status !== 403)
|
|
50
|
+
return null;
|
|
51
|
+
const get = (name) => {
|
|
52
|
+
try {
|
|
53
|
+
return headers?.get(name) ?? null;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
const mitigated = get('x-vercel-mitigated');
|
|
60
|
+
const requestId = get('x-vercel-id');
|
|
61
|
+
if (mitigated) {
|
|
62
|
+
return { kind: 'vercel_mitigated', action: mitigated.trim().toLowerCase() || null, requestId };
|
|
63
|
+
}
|
|
64
|
+
const contentType = (get('content-type') ?? '').toLowerCase();
|
|
65
|
+
const body = (bodyText ?? '').trimStart();
|
|
66
|
+
if (contentType.startsWith('text/plain') && /^forbidden\b/i.test(body)) {
|
|
67
|
+
return { kind: 'plain_forbidden', action: null, requestId };
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
/** Kill-switch (repo convention: every new mechanism ships with one).
|
|
72
|
+
* `RC_WEBAPP_EDGE_GATE=off` disables the BRAKE only — no call is ever skipped
|
|
73
|
+
* or deferred — while detection, logging, the state file and the relay-borne
|
|
74
|
+
* health signal stay on. Read at call time; logged once. */
|
|
75
|
+
export function webappEdgeGateDisabled() {
|
|
76
|
+
return (process.env.RC_WEBAPP_EDGE_GATE ?? 'on').trim().toLowerCase() === 'off';
|
|
77
|
+
}
|
|
78
|
+
let loggedDisabled = false;
|
|
79
|
+
function noteGateDisabled() {
|
|
80
|
+
if (loggedDisabled)
|
|
81
|
+
return;
|
|
82
|
+
loggedDisabled = true;
|
|
83
|
+
logger.info(TAG, 'backoff gate disabled by RC_WEBAPP_EDGE_GATE=off — edge denies are still detected and reported, but no call is skipped');
|
|
84
|
+
}
|
|
85
|
+
function stripQuery(path) {
|
|
86
|
+
const i = path.indexOf('?');
|
|
87
|
+
return i >= 0 ? path.slice(0, i) : path;
|
|
88
|
+
}
|
|
89
|
+
/** 5 → 10 → 20 → 30 min. The cap equals Vercel's persistent-action window: a
|
|
90
|
+
* host that stops knocking for a full window gives the block a chance to
|
|
91
|
+
* expire instead of feeding the pattern that armed it. */
|
|
92
|
+
export const DEFAULT_EDGE_BACKOFF_LADDER_MS = [
|
|
93
|
+
5 * 60_000,
|
|
94
|
+
10 * 60_000,
|
|
95
|
+
20 * 60_000,
|
|
96
|
+
30 * 60_000,
|
|
97
|
+
];
|
|
98
|
+
export class WebappEdgeGate {
|
|
99
|
+
now;
|
|
100
|
+
ladder;
|
|
101
|
+
onChange;
|
|
102
|
+
blockedUntil = null;
|
|
103
|
+
firstDeniedAt = null;
|
|
104
|
+
lastDeniedAt = null;
|
|
105
|
+
deniedCount = 0;
|
|
106
|
+
step = 0;
|
|
107
|
+
lastPath = null;
|
|
108
|
+
lastRequestId = null;
|
|
109
|
+
lastAction = null;
|
|
110
|
+
lastSuccessAt = null;
|
|
111
|
+
constructor(opts = {}) {
|
|
112
|
+
this.now = opts.now ?? (() => Date.now());
|
|
113
|
+
this.ladder = opts.backoffLadderMs && opts.backoffLadderMs.length > 0
|
|
114
|
+
? opts.backoffLadderMs
|
|
115
|
+
: DEFAULT_EDGE_BACKOFF_LADDER_MS;
|
|
116
|
+
this.onChange = opts.onChange;
|
|
117
|
+
}
|
|
118
|
+
/** True while periodic webapp calls should be skipped. Always false under
|
|
119
|
+
* the kill-switch (the episode itself is still tracked). */
|
|
120
|
+
isBlocked() {
|
|
121
|
+
const blocked = this.blockedUntil !== null && this.now() < this.blockedUntil;
|
|
122
|
+
if (blocked && webappEdgeGateDisabled()) {
|
|
123
|
+
noteGateDisabled();
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
return blocked;
|
|
127
|
+
}
|
|
128
|
+
/** ms until the gate reopens (0 when open). */
|
|
129
|
+
msUntilOpen() {
|
|
130
|
+
if (this.blockedUntil === null)
|
|
131
|
+
return 0;
|
|
132
|
+
return Math.max(0, this.blockedUntil - this.now());
|
|
133
|
+
}
|
|
134
|
+
/** Record an edge deny for `path`. Extends the block along the ladder and
|
|
135
|
+
* logs ONCE per episode at warn (every further deny is debug). */
|
|
136
|
+
noteDeny(rawPath, match) {
|
|
137
|
+
const now = this.now();
|
|
138
|
+
const path = stripQuery(rawPath);
|
|
139
|
+
const wasBlocked = this.isBlocked();
|
|
140
|
+
const backoff = this.ladder[Math.min(this.step, this.ladder.length - 1)];
|
|
141
|
+
// Only an UNBLOCKED deny climbs the ladder: four 403s arriving together
|
|
142
|
+
// at the start of a ban (config, readiness, journal, intel) are one event,
|
|
143
|
+
// not four — otherwise the first episode would jump straight to 30 min.
|
|
144
|
+
if (!wasBlocked) {
|
|
145
|
+
this.step += 1;
|
|
146
|
+
this.blockedUntil = now + backoff;
|
|
147
|
+
}
|
|
148
|
+
this.lastDeniedAt = now;
|
|
149
|
+
this.deniedCount += 1;
|
|
150
|
+
this.lastPath = path;
|
|
151
|
+
this.lastRequestId = match.requestId;
|
|
152
|
+
this.lastAction = match.action;
|
|
153
|
+
if (this.firstDeniedAt === null) {
|
|
154
|
+
this.firstDeniedAt = now;
|
|
155
|
+
logger.warn(TAG, edgeDenyMessage(match, path, backoff));
|
|
156
|
+
}
|
|
157
|
+
else if (!wasBlocked) {
|
|
158
|
+
logger.warn(TAG, `still denied by the webapp's edge firewall on ${path} (${this.deniedCount} denials since ` +
|
|
159
|
+
`${new Date(this.firstDeniedAt).toISOString()}) — pausing webapp calls for ${Math.round(backoff / 60_000)} min`);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
logger.debug(TAG, `edge deny on ${path} (${this.deniedCount} in episode)`);
|
|
163
|
+
}
|
|
164
|
+
this.emitChange();
|
|
165
|
+
}
|
|
166
|
+
/** Record a successful webapp call. Ends the episode (logged once). */
|
|
167
|
+
noteSuccess(startedAt) {
|
|
168
|
+
const now = this.now();
|
|
169
|
+
// A response that was already in flight when the ban started proves
|
|
170
|
+
// nothing about the ban: a success older than the last deny is ignored.
|
|
171
|
+
if (startedAt !== undefined && this.lastDeniedAt !== null && startedAt < this.lastDeniedAt) {
|
|
172
|
+
logger.debug(TAG, 'ignoring a success that started before the last edge deny');
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const hadEpisode = this.firstDeniedAt !== null;
|
|
176
|
+
const firstSuccess = this.lastSuccessAt === null;
|
|
177
|
+
this.lastSuccessAt = now;
|
|
178
|
+
if (!hadEpisode && this.blockedUntil === null) {
|
|
179
|
+
// First success of this process: rewrite the state file, so an episode
|
|
180
|
+
// left on disk by a previous gateway process cannot outlive it.
|
|
181
|
+
if (firstSuccess)
|
|
182
|
+
this.emitChange();
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (hadEpisode) {
|
|
186
|
+
logger.info(TAG, `webapp reachable again after ${this.deniedCount} edge denials ` +
|
|
187
|
+
`(episode ${new Date(this.firstDeniedAt).toISOString()} → now) — resuming normal cadence`);
|
|
188
|
+
}
|
|
189
|
+
this.blockedUntil = null;
|
|
190
|
+
this.firstDeniedAt = null;
|
|
191
|
+
this.lastDeniedAt = null;
|
|
192
|
+
this.deniedCount = 0;
|
|
193
|
+
this.step = 0;
|
|
194
|
+
this.lastPath = null;
|
|
195
|
+
this.lastRequestId = null;
|
|
196
|
+
this.lastAction = null;
|
|
197
|
+
this.emitChange();
|
|
198
|
+
}
|
|
199
|
+
snapshot() {
|
|
200
|
+
return {
|
|
201
|
+
blocked: this.isBlocked(),
|
|
202
|
+
blockedUntil: this.blockedUntil,
|
|
203
|
+
firstDeniedAt: this.firstDeniedAt,
|
|
204
|
+
lastDeniedAt: this.lastDeniedAt,
|
|
205
|
+
deniedCount: this.deniedCount,
|
|
206
|
+
lastPath: this.lastPath,
|
|
207
|
+
lastRequestId: this.lastRequestId,
|
|
208
|
+
lastAction: this.lastAction,
|
|
209
|
+
lastSuccessAt: this.lastSuccessAt,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
emitChange() {
|
|
213
|
+
if (!this.onChange)
|
|
214
|
+
return;
|
|
215
|
+
try {
|
|
216
|
+
this.onChange(this.snapshot());
|
|
217
|
+
}
|
|
218
|
+
catch (err) {
|
|
219
|
+
logger.debug(TAG, `onChange threw: ${formatError(err)}`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/** The one sentence every client logs when the edge denies it — names the
|
|
224
|
+
* actual cause so nobody goes hunting for a token or subscription problem. */
|
|
225
|
+
export function edgeDenyMessage(match, path, backoffMs) {
|
|
226
|
+
const who = match.kind === 'vercel_mitigated' ? "ReefClaw's edge firewall" : 'a firewall in front of ReefClaw';
|
|
227
|
+
const via = match.kind === 'vercel_mitigated'
|
|
228
|
+
? `Vercel edge mitigation '${match.action ?? 'deny'}'`
|
|
229
|
+
: 'plain-text Forbidden with no Vercel header — possibly a proxy on your side';
|
|
230
|
+
const rid = match.requestId ? `, request ${match.requestId}` : '';
|
|
231
|
+
return (`${path} denied by ${who} (${via}${rid}) — an IP-level block on this host, ` +
|
|
232
|
+
`NOT your account or token. Journal, central config and instruction updates pause until it lifts ` +
|
|
233
|
+
`(pausing webapp calls for ${Math.round(backoffMs / 60_000)} min); trading and the safety floor are unaffected. ` +
|
|
234
|
+
`If it persists, tell support@reefclaw.com the time and your hosting provider.`);
|
|
235
|
+
}
|
|
236
|
+
// ---- state file (read by the connector for the relay-borne health field) ----
|
|
237
|
+
export const WEBAPP_EDGE_STATE_FILENAME = 'webapp-edge-state.json';
|
|
238
|
+
export function defaultWebappEdgeStatePath() {
|
|
239
|
+
return join(homedir(), '.reefclaw', WEBAPP_EDGE_STATE_FILENAME);
|
|
240
|
+
}
|
|
241
|
+
/** Atomic write (tmp + rename, 0o600 — the plugin-config-io convention). Never
|
|
242
|
+
* throws: persistence is an observability aid, not a correctness requirement. */
|
|
243
|
+
export function writeWebappEdgeState(snapshot, path = defaultWebappEdgeStatePath()) {
|
|
244
|
+
try {
|
|
245
|
+
const dir = dirname(path);
|
|
246
|
+
if (!existsSync(dir))
|
|
247
|
+
mkdirSync(dir, { recursive: true });
|
|
248
|
+
const file = { schemaVersion: 1, updatedAt: Date.now(), source: 'plugin', ...snapshot };
|
|
249
|
+
const tmp = `${path}.${process.pid}.tmp`; // per-process: several runtimes may share the file
|
|
250
|
+
writeFileSync(tmp, JSON.stringify(file) + '\n', { encoding: 'utf-8', mode: 0o600 });
|
|
251
|
+
renameSync(tmp, path);
|
|
252
|
+
}
|
|
253
|
+
catch (err) {
|
|
254
|
+
logger.debug(TAG, `state file write failed: ${formatError(err)}`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
// ---- process-wide singleton ---------------------------------------------------
|
|
258
|
+
let statePath = defaultWebappEdgeStatePath();
|
|
259
|
+
let gate = new WebappEdgeGate({ onChange: (s) => writeWebappEdgeState(s, statePath) });
|
|
260
|
+
/** The process-wide gate every webapp client consults. */
|
|
261
|
+
export function webappEdgeGate() {
|
|
262
|
+
return gate;
|
|
263
|
+
}
|
|
264
|
+
/** Test-only: fresh gate, optional custom state path / clock. */
|
|
265
|
+
export function __resetWebappEdgeGateForTests(opts = {}) {
|
|
266
|
+
statePath = opts.statePath ?? defaultWebappEdgeStatePath();
|
|
267
|
+
gate = new WebappEdgeGate({
|
|
268
|
+
...opts,
|
|
269
|
+
onChange: opts.onChange ?? ((s) => writeWebappEdgeState(s, statePath)),
|
|
270
|
+
});
|
|
271
|
+
return gate;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Inspect a webapp response on the shared gate. Success → episode over;
|
|
275
|
+
* 403 → classified (using `bodyText` when the caller already read it). Returns
|
|
276
|
+
* the match so the caller can word its own log line. Never throws.
|
|
277
|
+
*/
|
|
278
|
+
export function noteWebappResponse(res, path, bodyText,
|
|
279
|
+
/** Epoch ms taken BEFORE the request was sent — lets the gate ignore a
|
|
280
|
+
* success that was already in flight when the ban started. */
|
|
281
|
+
startedAt) {
|
|
282
|
+
try {
|
|
283
|
+
if (res.ok) {
|
|
284
|
+
gate.noteSuccess(startedAt);
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
const match = classifyEdgeDeny(res.status, res.headers, bodyText);
|
|
288
|
+
if (match)
|
|
289
|
+
gate.noteDeny(path, match);
|
|
290
|
+
return match;
|
|
291
|
+
}
|
|
292
|
+
catch (err) {
|
|
293
|
+
logger.debug(TAG, `noteWebappResponse failed: ${formatError(err)}`);
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// ---- headers / user agent ------------------------------------------------------
|
|
298
|
+
let clientVersion = null;
|
|
299
|
+
/** Set once at boot from the shipped manifest (plugin-version.ts). */
|
|
300
|
+
export function setWebappClientVersion(version) {
|
|
301
|
+
clientVersion = version && /^[0-9A-Za-z.+-]{1,40}$/.test(version) ? version : null;
|
|
302
|
+
}
|
|
303
|
+
export function webappUserAgent() {
|
|
304
|
+
return `reefclaw-plugin/${clientVersion ?? 'unknown'} (openclaw-plugin)`;
|
|
305
|
+
}
|
|
306
|
+
/** Bearer + User-Agent for a webapp call. `extra` wins on key collision. */
|
|
307
|
+
export function webappHeaders(token, extra = {}) {
|
|
308
|
+
return {
|
|
309
|
+
authorization: `Bearer ${token}`,
|
|
310
|
+
'user-agent': webappUserAgent(),
|
|
311
|
+
...extra,
|
|
312
|
+
};
|
|
313
|
+
}
|
package/index.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// Paper mode: simulated execution, no API keys needed.
|
|
5
5
|
//
|
|
6
6
|
// CRITICAL: register() MUST be synchronous — OpenClaw silently ignores async registration.
|
|
7
|
-
// CRITICAL: Agent needs "group:plugins" in tools.sandbox.tools.
|
|
7
|
+
// CRITICAL: Agent needs "group:plugins" in tools.sandbox.tools.alsoAllow in openclaw.json (never an explicit allow list — audit M6).
|
|
8
8
|
// See memory/connection.md for full deployment guide.
|
|
9
9
|
import { readFileSync, existsSync } from 'node:fs';
|
|
10
10
|
import { homedir } from 'node:os';
|
|
@@ -25,6 +25,7 @@ import { createLiveAdapter, fillExchangeId, isLiveVenueSupported, parseVenue, ve
|
|
|
25
25
|
import { resolvePluginSymbol } from './venues/symbols.js';
|
|
26
26
|
import { HyperliquidPublicApi } from './venues/hyperliquid/hl-public.js';
|
|
27
27
|
import { bracketsEnabled, loadBracketMode } from './config/brackets-config.js';
|
|
28
|
+
import { sanitizeBaseUrl } from './config/base-url.js';
|
|
28
29
|
import { loadUserDataStreamMode, loadUserDataStreamTunables, loadUserDataStreamDbWrite, getUserDataStreamIngestBaseUrl, resolveIngestToken, resolveReefclawUserId, } from './config/user-data-stream-config.js';
|
|
29
30
|
import { TradeStoreClient } from './ingest/trade-store-client.js';
|
|
30
31
|
import { ProposalManager } from './live/proposal-manager.js';
|
|
@@ -39,6 +40,7 @@ import { onStopWatcherClose } from './ingest/position-auto-capture.js';
|
|
|
39
40
|
import { ReentryTracker } from './portfolio/reentry-tracker.js';
|
|
40
41
|
import { startReadinessReporter } from './ingest/readiness-reporter.js';
|
|
41
42
|
import { resolvePluginInstallFacts } from './plugin-version.js';
|
|
43
|
+
import { setWebappClientVersion } from './http/webapp-edge.js';
|
|
42
44
|
import { processRuntime, resolveProcessRole } from './lifecycle/process-role.js';
|
|
43
45
|
import { computePluginIntegrity, describePluginIntegrity } from './plugin-integrity.js';
|
|
44
46
|
import { IntelMicrostructureAssembler } from './live/microstructure-assembler.js';
|
|
@@ -53,7 +55,7 @@ import { loadPositionReviewMode } from './config/position-review-config.js';
|
|
|
53
55
|
import { installSignalHandlers } from './lifecycle/install-signal-handlers.js';
|
|
54
56
|
import { SerialTradingOperationLock } from './lifecycle/trading-operation-lock.js';
|
|
55
57
|
import { readPluginConfig, readOpenClawConnection, loadMicroLiveConfig, loadStopWatcherIntervalMs } from './config/plugin-config-io.js';
|
|
56
|
-
import { verifyOperatorProvenance } from './config/operator-provenance.js';
|
|
58
|
+
import { verifyOperatorProvenance, issueOperatorSecret, provenanceRefusal } from './config/operator-provenance.js';
|
|
57
59
|
import { startConnectorSupervisor, hasBundledBridge } from './connector-supervisor.js';
|
|
58
60
|
import { ToolGate } from './config/tool-gate.js';
|
|
59
61
|
import { gateStore } from './config/gate-store.js';
|
|
@@ -242,7 +244,7 @@ const TOOL_PARAMS = {
|
|
|
242
244
|
type: 'object',
|
|
243
245
|
properties: {
|
|
244
246
|
symbol: { type: 'string', description: 'Symbol of the open live position' },
|
|
245
|
-
new_stop_price: { type: 'number', description: 'New stop-loss price (must be on the protective side of entry)' },
|
|
247
|
+
new_stop_price: { type: 'number', description: 'New stop-loss price (must be on the protective side of entry). Widening is refused while the position is under water; a widening in profit must keep the loss-at-stop from entry within the per-trade loss cap. Tightening is always allowed.' },
|
|
246
248
|
},
|
|
247
249
|
required: ['symbol', 'new_stop_price'],
|
|
248
250
|
},
|
|
@@ -805,7 +807,7 @@ const TOOL_PARAMS = {
|
|
|
805
807
|
set_exchange_credentials: {
|
|
806
808
|
type: 'object',
|
|
807
809
|
properties: {
|
|
808
|
-
operator_token: { type: 'string', description: 'Operator provenance —
|
|
810
|
+
operator_token: { type: 'string', description: 'Operator provenance — a per-boot secret that exists only inside the ReefClaw connector process and is attached by the dashboard path. It is not available to the agent; agent-initiated calls are refused.' },
|
|
809
811
|
venue: { type: 'string', enum: ['binance', 'hyperliquid'], description: "Trading venue the credentials are for (default 'binance')" },
|
|
810
812
|
apiKey: { type: 'string', description: 'Binance API key (venue=binance)' },
|
|
811
813
|
secret: { type: 'string', description: 'Binance API secret (venue=binance)' },
|
|
@@ -819,7 +821,7 @@ const TOOL_PARAMS = {
|
|
|
819
821
|
set_trading_mode: {
|
|
820
822
|
type: 'object',
|
|
821
823
|
properties: {
|
|
822
|
-
operator_token: { type: 'string', description: 'Operator provenance —
|
|
824
|
+
operator_token: { type: 'string', description: 'Operator provenance — a per-boot secret that exists only inside the ReefClaw connector process and is attached by the dashboard path. It is not available to the agent; agent-initiated calls are refused.' },
|
|
823
825
|
mode: { type: 'string', enum: ['PAPER', 'MICRO_LIVE', 'LIVE'], description: 'Target trading mode' },
|
|
824
826
|
acknowledged: { type: 'boolean', description: 'Required when moving to LIVE — explicit operator acknowledgment' },
|
|
825
827
|
},
|
|
@@ -828,7 +830,7 @@ const TOOL_PARAMS = {
|
|
|
828
830
|
test_exchange_credentials: {
|
|
829
831
|
type: 'object',
|
|
830
832
|
properties: {
|
|
831
|
-
operator_token: { type: 'string', description: 'Operator provenance —
|
|
833
|
+
operator_token: { type: 'string', description: 'Operator provenance — a per-boot secret that exists only inside the ReefClaw connector process and is attached by the dashboard path. It is not available to the agent; agent-initiated calls are refused.' },
|
|
832
834
|
venue: { type: 'string', enum: ['binance', 'hyperliquid'], description: "Trading venue to verify against (default 'binance')" },
|
|
833
835
|
apiKey: { type: 'string', description: 'Binance API key to verify (venue=binance; not persisted)' },
|
|
834
836
|
secret: { type: 'string', description: 'Binance API secret to verify (venue=binance; not persisted)' },
|
|
@@ -841,7 +843,7 @@ const TOOL_PARAMS = {
|
|
|
841
843
|
hl_provision_agent_wallet: {
|
|
842
844
|
type: 'object',
|
|
843
845
|
properties: {
|
|
844
|
-
operator_token: { type: 'string', description: 'Operator provenance —
|
|
846
|
+
operator_token: { type: 'string', description: 'Operator provenance — a per-boot secret that exists only inside the ReefClaw connector process and is attached by the dashboard path. It is not available to the agent; agent-initiated calls are refused.' },
|
|
845
847
|
walletAddress: { type: 'string', description: 'Hyperliquid MASTER account address 0x… the agent wallet will trade for (public; never a private key)' },
|
|
846
848
|
testnet: { type: 'boolean', description: 'Provision for the Hyperliquid testnet (default: false)' },
|
|
847
849
|
regenerate: { type: 'boolean', description: 'Replace an existing agent wallet with a fresh key (PAPER mode only; the old approval is orphaned)' },
|
|
@@ -851,14 +853,14 @@ const TOOL_PARAMS = {
|
|
|
851
853
|
hl_agent_wallet_status: {
|
|
852
854
|
type: 'object',
|
|
853
855
|
properties: {
|
|
854
|
-
operator_token: { type: 'string', description: 'Operator provenance —
|
|
856
|
+
operator_token: { type: 'string', description: 'Operator provenance — a per-boot secret that exists only inside the ReefClaw connector process and is attached by the dashboard path. It is not available to the agent; agent-initiated calls are refused.' },
|
|
855
857
|
probe: { type: 'boolean', description: 'Tool-discovery probe — returns immediately without config or network access' },
|
|
856
858
|
},
|
|
857
859
|
},
|
|
858
860
|
hl_submit_agent_approval: {
|
|
859
861
|
type: 'object',
|
|
860
862
|
properties: {
|
|
861
|
-
operator_token: { type: 'string', description: 'Operator provenance —
|
|
863
|
+
operator_token: { type: 'string', description: 'Operator provenance — a per-boot secret that exists only inside the ReefClaw connector process and is attached by the dashboard path. It is not available to the agent; agent-initiated calls are refused.' },
|
|
862
864
|
action: { type: 'object', description: "The wallet-signed approveAgent action, verbatim. Only type='approveAgent' is accepted." },
|
|
863
865
|
nonce: { type: 'number', description: 'Outer nonce — must equal action.nonce (user-signed actions carry one nonce)' },
|
|
864
866
|
signature: { type: 'object', description: 'Wallet signature { r, s, v } over the approveAgent typed data' },
|
|
@@ -868,7 +870,7 @@ const TOOL_PARAMS = {
|
|
|
868
870
|
clear_exchange_credentials: {
|
|
869
871
|
type: 'object',
|
|
870
872
|
properties: {
|
|
871
|
-
operator_token: { type: 'string', description: 'Operator provenance —
|
|
873
|
+
operator_token: { type: 'string', description: 'Operator provenance — a per-boot secret that exists only inside the ReefClaw connector process and is attached by the dashboard path. It is not available to the agent; agent-initiated calls are refused.' },
|
|
872
874
|
confirm: { type: 'boolean', description: 'Must be true — safety gate against accidental probe wipes' },
|
|
873
875
|
},
|
|
874
876
|
required: ['confirm'],
|
|
@@ -880,7 +882,7 @@ const TOOL_PARAMS = {
|
|
|
880
882
|
set_bracket_requirement: {
|
|
881
883
|
type: 'object',
|
|
882
884
|
properties: {
|
|
883
|
-
operator_token: { type: 'string', description: 'Operator provenance —
|
|
885
|
+
operator_token: { type: 'string', description: 'Operator provenance — a per-boot secret that exists only inside the ReefClaw connector process and is attached by the dashboard path. It is not available to the agent; agent-initiated calls are refused.' },
|
|
884
886
|
flag: { type: 'string', enum: ['requireStopLoss', 'requireTakeProfit'], description: 'Which requirement to flip' },
|
|
885
887
|
value: { type: 'boolean', description: 'New value. False disables the requirement and returns a warning banner copy.' },
|
|
886
888
|
},
|
|
@@ -1130,8 +1132,11 @@ const paperTradingPlugin = {
|
|
|
1130
1132
|
const rcRaw = readFileSync(rcConfigPath, 'utf-8');
|
|
1131
1133
|
const rcConfig = JSON.parse(rcRaw);
|
|
1132
1134
|
connectionToken = rcConfig?.connectionToken ?? '';
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
+
// Both carry the rc_ token as a Bearer header: https required for a
|
|
1136
|
+
// public host, plain http only to a private/loopback host (dev,
|
|
1137
|
+
// on-prem); anything else → production default + warning (H4).
|
|
1138
|
+
apiBaseUrl = sanitizeBaseUrl(rcConfig?.apiBaseUrl, apiBaseUrl, 'apiBaseUrl');
|
|
1139
|
+
intelligenceUrl = sanitizeBaseUrl(rcConfig?.intelligenceUrl, intelligenceUrl, 'intelligenceUrl');
|
|
1135
1140
|
const ev = rcConfig?.signals?.evaluator;
|
|
1136
1141
|
if (ev === 'shadow' || ev === 'enforce')
|
|
1137
1142
|
signalsEvaluator = ev;
|
|
@@ -2418,7 +2423,7 @@ const paperTradingPlugin = {
|
|
|
2418
2423
|
{
|
|
2419
2424
|
name: 'modify_stop',
|
|
2420
2425
|
label: 'Modify Stop',
|
|
2421
|
-
description: 'Move the exchange-side stop-loss on an open live position. Atomic cancel-then-resubmit with automatic rollback. Live mode only; requires brackets.mode enabled.',
|
|
2426
|
+
description: 'Move the exchange-side stop-loss on an open live position. Atomic cancel-then-resubmit with automatic rollback. Live mode only; requires brackets.mode enabled. Safety floor: a wider stop is refused while the position is under water, and a widening in profit is capped at the per-trade loss limit.',
|
|
2422
2427
|
parameters: TOOL_PARAMS.modify_stop,
|
|
2423
2428
|
execute: async (_id, params) => jsonResult(await modifyStopTool(params, {
|
|
2424
2429
|
...adapterDeps,
|
|
@@ -2848,7 +2853,7 @@ const paperTradingPlugin = {
|
|
|
2848
2853
|
execute: async (_id, params) => {
|
|
2849
2854
|
const prov = verifyOperatorProvenance(params.operator_token);
|
|
2850
2855
|
if (!prov.ok)
|
|
2851
|
-
return jsonResult(
|
|
2856
|
+
return jsonResult(provenanceRefusal(prov));
|
|
2852
2857
|
return jsonResult(await setExchangeCredentialsTool(params, { runtime, adapterDeps, bootVenue: venue }));
|
|
2853
2858
|
},
|
|
2854
2859
|
},
|
|
@@ -2860,7 +2865,7 @@ const paperTradingPlugin = {
|
|
|
2860
2865
|
execute: async (_id, params) => {
|
|
2861
2866
|
const prov = verifyOperatorProvenance(params.operator_token);
|
|
2862
2867
|
if (!prov.ok)
|
|
2863
|
-
return jsonResult(
|
|
2868
|
+
return jsonResult(provenanceRefusal(prov));
|
|
2864
2869
|
return jsonResult(await setTradingModeTool(params, { runtime, adapterDeps, bootVenue: venue }));
|
|
2865
2870
|
},
|
|
2866
2871
|
},
|
|
@@ -2875,7 +2880,7 @@ const paperTradingPlugin = {
|
|
|
2875
2880
|
execute: async (_id, params) => {
|
|
2876
2881
|
const prov = verifyOperatorProvenance(params.operator_token);
|
|
2877
2882
|
if (!prov.ok)
|
|
2878
|
-
return jsonResult(
|
|
2883
|
+
return jsonResult(provenanceRefusal(prov));
|
|
2879
2884
|
return jsonResult(await testExchangeCredentialsTool(params));
|
|
2880
2885
|
},
|
|
2881
2886
|
},
|
|
@@ -2887,7 +2892,7 @@ const paperTradingPlugin = {
|
|
|
2887
2892
|
execute: async (_id, params) => {
|
|
2888
2893
|
const prov = verifyOperatorProvenance(params.operator_token);
|
|
2889
2894
|
if (!prov.ok)
|
|
2890
|
-
return jsonResult(
|
|
2895
|
+
return jsonResult(provenanceRefusal(prov));
|
|
2891
2896
|
return jsonResult(await clearExchangeCredentialsTool(params, { runtime, adapterDeps }));
|
|
2892
2897
|
},
|
|
2893
2898
|
},
|
|
@@ -2899,7 +2904,7 @@ const paperTradingPlugin = {
|
|
|
2899
2904
|
execute: async (_id, params) => {
|
|
2900
2905
|
const prov = verifyOperatorProvenance(params.operator_token);
|
|
2901
2906
|
if (!prov.ok)
|
|
2902
|
-
return jsonResult(
|
|
2907
|
+
return jsonResult(provenanceRefusal(prov));
|
|
2903
2908
|
return jsonResult(await hlProvisionAgentWalletTool(params, { runtime, bootVenue: venue }));
|
|
2904
2909
|
},
|
|
2905
2910
|
},
|
|
@@ -2913,7 +2918,7 @@ const paperTradingPlugin = {
|
|
|
2913
2918
|
return jsonResult(await hlSubmitAgentApprovalTool(params));
|
|
2914
2919
|
const prov = verifyOperatorProvenance(params.operator_token);
|
|
2915
2920
|
if (!prov.ok)
|
|
2916
|
-
return jsonResult(
|
|
2921
|
+
return jsonResult(provenanceRefusal(prov));
|
|
2917
2922
|
return jsonResult(await hlSubmitAgentApprovalTool(params));
|
|
2918
2923
|
},
|
|
2919
2924
|
},
|
|
@@ -2930,7 +2935,7 @@ const paperTradingPlugin = {
|
|
|
2930
2935
|
return jsonResult(await hlAgentWalletStatusTool(params, {}));
|
|
2931
2936
|
const prov = verifyOperatorProvenance(params.operator_token);
|
|
2932
2937
|
if (!prov.ok)
|
|
2933
|
-
return jsonResult(
|
|
2938
|
+
return jsonResult(provenanceRefusal(prov));
|
|
2934
2939
|
return jsonResult(await hlAgentWalletStatusTool(params, { bootVenue: venue }));
|
|
2935
2940
|
},
|
|
2936
2941
|
},
|
|
@@ -2951,8 +2956,10 @@ const paperTradingPlugin = {
|
|
|
2951
2956
|
execute: async (_id, params) => {
|
|
2952
2957
|
const prov = verifyOperatorProvenance(params.operator_token);
|
|
2953
2958
|
if (!prov.ok)
|
|
2954
|
-
return jsonResult(
|
|
2955
|
-
|
|
2959
|
+
return jsonResult(provenanceRefusal(prov));
|
|
2960
|
+
// Adapter read at execute time: the protective-stop floor is not
|
|
2961
|
+
// waivable while trading is live (audit 2026-09-27 H1/H4).
|
|
2962
|
+
return jsonResult(setBracketRequirementTool(params, { isLive: runtime.adapter.isLive }));
|
|
2956
2963
|
},
|
|
2957
2964
|
},
|
|
2958
2965
|
];
|
|
@@ -3059,6 +3066,8 @@ const paperTradingPlugin = {
|
|
|
3059
3066
|
});
|
|
3060
3067
|
logger.info(TAG, `Plugin release ${installFacts.version ?? 'unknown (no stamped manifest)'} via ${installFacts.channel}`);
|
|
3061
3068
|
processRecord.release = installFacts.version ?? null;
|
|
3069
|
+
// Name our traffic at the webapp's edge (User-Agent reefclaw-plugin/<release>).
|
|
3070
|
+
setWebappClientVersion(installFacts.version ?? null);
|
|
3062
3071
|
// What THIS process actually loaded — install-location CLASS (never the
|
|
3063
3072
|
// path), process start, SHA-256 of the plugin's own order-path files —
|
|
3064
3073
|
// captured once here at boot and carried on every readiness post. The
|
|
@@ -3120,7 +3129,10 @@ function maybeStartConnectorSupervisor() {
|
|
|
3120
3129
|
// is self-contained by design). Prod's linked plugin dir has no bundled
|
|
3121
3130
|
// bridge and no flag → stays off; systemd keeps owning prod's bridge.
|
|
3122
3131
|
if (supervisorMode === 'on' || hasBundledBridge()) {
|
|
3123
|
-
|
|
3132
|
+
// The supervised connector receives a per-boot provenance secret over
|
|
3133
|
+
// stdin; from then on the operator-only tools accept ONLY that secret
|
|
3134
|
+
// (config/operator-provenance.ts, audit 2026-09-27 H1).
|
|
3135
|
+
startConnectorSupervisor({ issueOperatorSecret });
|
|
3124
3136
|
}
|
|
3125
3137
|
}
|
|
3126
3138
|
catch (err) {
|