@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,366 @@
|
|
|
1
|
+
// Edge-deny detection for the connector's webapp (reefclaw.com) calls, a
|
|
2
|
+
// bridge-side backoff gate, and the relay-borne health signal that survives
|
|
3
|
+
// the deny.
|
|
4
|
+
//
|
|
5
|
+
// Why (2026-09-28): Vercel's automatic DDoS mitigation denied a host's IP for
|
|
6
|
+
// rolling 30-minute windows. Every HTTP path to the webapp answered a
|
|
7
|
+
// plain-text `403 Forbidden` with `x-vercel-mitigated: deny` — the SKILL.md
|
|
8
|
+
// pull ("not authorized — connect the account first"), the heartbeat recorder
|
|
9
|
+
// ("rejected"), the plugin's config/readiness/journal calls — while the relay
|
|
10
|
+
// kept working, so the dashboard stayed green. The relay is therefore the one
|
|
11
|
+
// channel that can carry the episode to the operator: this tracker feeds
|
|
12
|
+
// `agent_state.health.webappApi` and a one-shot `webapp_edge_denied` /
|
|
13
|
+
// `webapp_edge_recovered` event (the relay audits both as `skill.<event>`,
|
|
14
|
+
// which is what the fleet alarm keys on).
|
|
15
|
+
//
|
|
16
|
+
// The bridge also backs off (5 → 10 → 20 → 30 min, like the plugin's gate) so
|
|
17
|
+
// the recorder, the shock-wake gate poll and the bootstrap heal stop feeding
|
|
18
|
+
// a ban from this IP; the gate reopens on its own and the next call re-probes.
|
|
19
|
+
//
|
|
20
|
+
// The plugin sees the deny far more often than the bridge (its config poll is
|
|
21
|
+
// every 60 s; the bridge only posts after each beat), so it records its own
|
|
22
|
+
// gate in ~/.reefclaw/webapp-edge-state.json (plugin/src/http/webapp-edge.ts)
|
|
23
|
+
// and the bridge merges that file here. The classifier is deliberately a
|
|
24
|
+
// small duplicate of the plugin's: npx boxes vendor @reefclaw/shared twice
|
|
25
|
+
// and a new shared export would crash an older bridge on a missing symbol.
|
|
26
|
+
//
|
|
27
|
+
// Fails open everywhere: a missing file, a bad header, a classifier miss —
|
|
28
|
+
// the tracker stays silent and the payload stays byte-identical to today's.
|
|
29
|
+
// The gate only ever pauses the bridge's OWN optional webapp traffic; it
|
|
30
|
+
// never touches the relay, the gateway, emergency commands or trading.
|
|
31
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
32
|
+
import { dirname, join } from 'node:path';
|
|
33
|
+
import { homedir } from 'node:os';
|
|
34
|
+
import { logger } from '../logger.js';
|
|
35
|
+
const TAG = 'webapp-edge';
|
|
36
|
+
/** Is this 403 the edge (Vercel) rather than the webapp? Pure. The app's own
|
|
37
|
+
* denials are JSON; the edge answers text/plain "Forbidden" + `x-vercel-mitigated`. */
|
|
38
|
+
export function classifyEdgeDeny(status, headers, bodyText) {
|
|
39
|
+
if (status !== 403)
|
|
40
|
+
return null;
|
|
41
|
+
const get = (name) => {
|
|
42
|
+
try {
|
|
43
|
+
return headers?.get(name) ?? null;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const mitigated = get('x-vercel-mitigated');
|
|
50
|
+
const requestId = get('x-vercel-id');
|
|
51
|
+
if (mitigated) {
|
|
52
|
+
return { kind: 'vercel_mitigated', action: mitigated.trim().toLowerCase() || null, requestId };
|
|
53
|
+
}
|
|
54
|
+
const contentType = (get('content-type') ?? '').toLowerCase();
|
|
55
|
+
const body = (bodyText ?? '').trimStart();
|
|
56
|
+
if (contentType.startsWith('text/plain') && /^forbidden\b/i.test(body)) {
|
|
57
|
+
return { kind: 'plain_forbidden', action: null, requestId };
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
/** Kill-switch (repo convention: every new mechanism ships with one).
|
|
62
|
+
* `RC_WEBAPP_EDGE_GATE=off` disables the BRAKE only — no call is ever skipped
|
|
63
|
+
* or deferred — while detection, logging, the state file and the relay-borne
|
|
64
|
+
* health signal stay on. Read at call time; logged once. */
|
|
65
|
+
export function webappEdgeGateDisabled() {
|
|
66
|
+
return (process.env.RC_WEBAPP_EDGE_GATE ?? 'on').trim().toLowerCase() === 'off';
|
|
67
|
+
}
|
|
68
|
+
let loggedDisabled = false;
|
|
69
|
+
function noteGateDisabled() {
|
|
70
|
+
if (loggedDisabled)
|
|
71
|
+
return;
|
|
72
|
+
loggedDisabled = true;
|
|
73
|
+
logger.info(TAG, 'backoff gate disabled by RC_WEBAPP_EDGE_GATE=off — edge denies are still detected and reported, but no call is skipped');
|
|
74
|
+
}
|
|
75
|
+
function stripQuery(path) {
|
|
76
|
+
const i = path.indexOf('?');
|
|
77
|
+
return i >= 0 ? path.slice(0, i) : path;
|
|
78
|
+
}
|
|
79
|
+
export function defaultPluginEdgeStatePath() {
|
|
80
|
+
return join(homedir(), '.reefclaw', 'webapp-edge-state.json');
|
|
81
|
+
}
|
|
82
|
+
/** A plugin file older than this is ignored outright (corrupt clock, dead
|
|
83
|
+
* gateway that never wrote again). */
|
|
84
|
+
const PLUGIN_STATE_MAX_AGE_MS = 2 * 60 * 60_000;
|
|
85
|
+
/** A plugin EPISODE counts as live only while its last deny is this recent
|
|
86
|
+
* (or its block is still open): a gateway that died mid-episode must not
|
|
87
|
+
* haunt the dashboard until the 2 h file rule drops it. 45 min covers the
|
|
88
|
+
* plugin gate's longest backoff (30 min) plus its re-probe. */
|
|
89
|
+
const PLUGIN_EPISODE_MAX_AGE_MS = 45 * 60_000;
|
|
90
|
+
/** The file is re-read at most this often from health() (called on every
|
|
91
|
+
* agent-state build). */
|
|
92
|
+
const PLUGIN_STATE_READ_TTL_MS = 10_000;
|
|
93
|
+
/** Read + validate the plugin's gate file. Missing/corrupt/stale → null. */
|
|
94
|
+
export function readPluginEdgeState(path = defaultPluginEdgeStatePath(), now = Date.now()) {
|
|
95
|
+
try {
|
|
96
|
+
if (!existsSync(path))
|
|
97
|
+
return null;
|
|
98
|
+
const raw = JSON.parse(readFileSync(path, 'utf-8'));
|
|
99
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
100
|
+
return null;
|
|
101
|
+
const f = raw;
|
|
102
|
+
if (typeof f.updatedAt !== 'number' || now - f.updatedAt > PLUGIN_STATE_MAX_AGE_MS)
|
|
103
|
+
return null;
|
|
104
|
+
return f;
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Is the plugin file describing an episode that is still live? */
|
|
111
|
+
export function pluginEpisodeActive(f, now) {
|
|
112
|
+
if (!f)
|
|
113
|
+
return false;
|
|
114
|
+
if (typeof f.firstDeniedAt !== 'number' || !((f.deniedCount ?? 0) > 0))
|
|
115
|
+
return false;
|
|
116
|
+
const recentDeny = typeof f.lastDeniedAt === 'number' && now - f.lastDeniedAt <= PLUGIN_EPISODE_MAX_AGE_MS;
|
|
117
|
+
const openBlock = typeof f.blockedUntil === 'number' && f.blockedUntil > now - 5 * 60_000;
|
|
118
|
+
return recentDeny || openBlock;
|
|
119
|
+
}
|
|
120
|
+
/** 5 → 10 → 20 → 30 min — the plugin gate's ladder (30 = Vercel's window). */
|
|
121
|
+
export const DEFAULT_EDGE_BACKOFF_LADDER_MS = [
|
|
122
|
+
5 * 60_000,
|
|
123
|
+
10 * 60_000,
|
|
124
|
+
20 * 60_000,
|
|
125
|
+
30 * 60_000,
|
|
126
|
+
];
|
|
127
|
+
/**
|
|
128
|
+
* Merges the bridge's own observations with the plugin's file into one
|
|
129
|
+
* health verdict, runs the bridge-side backoff gate, and queues one event per
|
|
130
|
+
* transition for the bridge to emit.
|
|
131
|
+
*/
|
|
132
|
+
export class WebappEdgeTracker {
|
|
133
|
+
now;
|
|
134
|
+
pluginStatePath;
|
|
135
|
+
ladder;
|
|
136
|
+
// Bridge-observed episode + gate.
|
|
137
|
+
firstDeniedAt = null;
|
|
138
|
+
lastDeniedAt = null;
|
|
139
|
+
deniedCount = 0;
|
|
140
|
+
lastPath = null;
|
|
141
|
+
lastRequestId = null;
|
|
142
|
+
blockedUntil = null;
|
|
143
|
+
step = 0;
|
|
144
|
+
// Last emitted verdict (for transition detection) + queued events.
|
|
145
|
+
emittedDenied = false;
|
|
146
|
+
emittedSince = null;
|
|
147
|
+
recoveredAt = null;
|
|
148
|
+
lastSource = 'bridge';
|
|
149
|
+
pending = [];
|
|
150
|
+
// Plugin file cache.
|
|
151
|
+
pluginCache = null;
|
|
152
|
+
constructor(opts = {}) {
|
|
153
|
+
this.now = opts.now ?? (() => Date.now());
|
|
154
|
+
this.pluginStatePath = opts.pluginStatePath === undefined ? defaultPluginEdgeStatePath() : opts.pluginStatePath;
|
|
155
|
+
this.ladder = opts.backoffLadderMs && opts.backoffLadderMs.length > 0 ? opts.backoffLadderMs : DEFAULT_EDGE_BACKOFF_LADDER_MS;
|
|
156
|
+
}
|
|
157
|
+
/** The bridge itself observed a deny that no success has cleared yet. */
|
|
158
|
+
hasOwnEpisode() {
|
|
159
|
+
return this.firstDeniedAt !== null;
|
|
160
|
+
}
|
|
161
|
+
/** True while the bridge's own periodic webapp calls should be skipped.
|
|
162
|
+
* Always false under the kill-switch (the episode itself is still tracked). */
|
|
163
|
+
isBlocked() {
|
|
164
|
+
const blocked = this.blockedUntil !== null && this.now() < this.blockedUntil;
|
|
165
|
+
if (blocked && webappEdgeGateDisabled()) {
|
|
166
|
+
noteGateDisabled();
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
return blocked;
|
|
170
|
+
}
|
|
171
|
+
/** ms until the bridge gate reopens (0 when open). */
|
|
172
|
+
msUntilOpen() {
|
|
173
|
+
if (this.blockedUntil === null)
|
|
174
|
+
return 0;
|
|
175
|
+
return Math.max(0, this.blockedUntil - this.now());
|
|
176
|
+
}
|
|
177
|
+
/** The connector's own webapp call was denied by the edge. Only an
|
|
178
|
+
* UNBLOCKED deny climbs the ladder (several 403s at the start of a ban are
|
|
179
|
+
* one event, not four). */
|
|
180
|
+
noteDeny(rawPath, match) {
|
|
181
|
+
const now = this.now();
|
|
182
|
+
const path = stripQuery(rawPath);
|
|
183
|
+
const wasBlocked = this.isBlocked();
|
|
184
|
+
if (!wasBlocked) {
|
|
185
|
+
const backoff = this.ladder[Math.min(this.step, this.ladder.length - 1)];
|
|
186
|
+
this.step += 1;
|
|
187
|
+
this.blockedUntil = now + backoff;
|
|
188
|
+
}
|
|
189
|
+
if (this.firstDeniedAt === null) {
|
|
190
|
+
this.firstDeniedAt = now;
|
|
191
|
+
const who = match.kind === 'vercel_mitigated' ? "ReefClaw's edge firewall" : 'a firewall in front of ReefClaw';
|
|
192
|
+
const how = match.kind === 'vercel_mitigated' ? `Vercel mitigation '${match.action ?? 'deny'}'` : 'plain-text Forbidden, no Vercel header';
|
|
193
|
+
logger.warn(TAG, `${path} denied by ${who} (${how}${match.requestId ? `, request ${match.requestId}` : ''}) — an IP-level block on this host, NOT the account or token. ` +
|
|
194
|
+
`Instruction pulls and heartbeat records wait for it to lift (pausing webapp calls for ${Math.round(this.msUntilOpen() / 60_000)} min); trading and the safety floor are unaffected.`);
|
|
195
|
+
}
|
|
196
|
+
this.lastDeniedAt = now;
|
|
197
|
+
this.deniedCount += 1;
|
|
198
|
+
this.lastPath = path;
|
|
199
|
+
this.lastRequestId = match.requestId;
|
|
200
|
+
this.refresh();
|
|
201
|
+
}
|
|
202
|
+
/** The connector's own webapp call succeeded. A response that was already
|
|
203
|
+
* in flight when the ban started proves nothing: pass `startedAt` and a
|
|
204
|
+
* success older than the last deny is ignored. */
|
|
205
|
+
noteSuccess(startedAt) {
|
|
206
|
+
if (startedAt !== undefined && this.lastDeniedAt !== null && startedAt < this.lastDeniedAt) {
|
|
207
|
+
logger.debug(TAG, 'ignoring a success that started before the last edge deny');
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (this.firstDeniedAt !== null) {
|
|
211
|
+
logger.info(TAG, `webapp reachable again after ${this.deniedCount} edge denials`);
|
|
212
|
+
}
|
|
213
|
+
this.firstDeniedAt = null;
|
|
214
|
+
this.lastDeniedAt = null;
|
|
215
|
+
this.deniedCount = 0;
|
|
216
|
+
this.lastPath = null;
|
|
217
|
+
this.lastRequestId = null;
|
|
218
|
+
this.blockedUntil = null;
|
|
219
|
+
this.step = 0;
|
|
220
|
+
this.refresh();
|
|
221
|
+
}
|
|
222
|
+
/** Current verdict (bridge ∪ plugin file). Undefined while nothing was ever
|
|
223
|
+
* denied — the caller omits the field. Re-reads the plugin file (cached
|
|
224
|
+
* 10 s), so a plugin-only episode is picked up on every state build. */
|
|
225
|
+
health() {
|
|
226
|
+
const now = this.now();
|
|
227
|
+
const plugin = this.pluginState(now);
|
|
228
|
+
const bridgeActive = this.firstDeniedAt !== null;
|
|
229
|
+
const pluginActive = pluginEpisodeActive(plugin, now);
|
|
230
|
+
if (bridgeActive || pluginActive) {
|
|
231
|
+
const since = Math.min(bridgeActive ? this.firstDeniedAt : Number.POSITIVE_INFINITY, pluginActive ? plugin?.firstDeniedAt : Number.POSITIVE_INFINITY);
|
|
232
|
+
const last = Math.max(this.lastDeniedAt ?? 0, pluginActive && typeof plugin?.lastDeniedAt === 'number' ? plugin.lastDeniedAt : 0);
|
|
233
|
+
const source = bridgeActive && pluginActive ? 'both' : bridgeActive ? 'bridge' : 'plugin';
|
|
234
|
+
this.lastSource = source;
|
|
235
|
+
const requestId = this.lastRequestId ?? (pluginActive ? (plugin?.lastRequestId ?? null) : null);
|
|
236
|
+
const lastPath = this.lastPath ?? (pluginActive ? stripQuery(plugin?.lastPath ?? '') || null : null);
|
|
237
|
+
return {
|
|
238
|
+
status: 'edge_denied',
|
|
239
|
+
since: new Date(Number.isFinite(since) ? since : now).toISOString(),
|
|
240
|
+
...(last > 0 ? { lastDeniedAt: new Date(last).toISOString() } : {}),
|
|
241
|
+
deniedCount: this.deniedCount + (pluginActive ? (plugin?.deniedCount ?? 0) : 0),
|
|
242
|
+
source,
|
|
243
|
+
requestId,
|
|
244
|
+
lastPath,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
if (this.recoveredAt !== null) {
|
|
248
|
+
return { status: 'ok', deniedCount: 0, source: this.lastSource, recoveredAt: new Date(this.recoveredAt).toISOString() };
|
|
249
|
+
}
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
/** Drain the queued transition events (called by the bridge's emitter). Also
|
|
253
|
+
* refreshes against the plugin file so a plugin-only transition is noticed
|
|
254
|
+
* even when the bridge made no webapp call of its own. */
|
|
255
|
+
takeEvents() {
|
|
256
|
+
this.refresh();
|
|
257
|
+
const out = this.pending;
|
|
258
|
+
this.pending = [];
|
|
259
|
+
return out;
|
|
260
|
+
}
|
|
261
|
+
pluginState(now) {
|
|
262
|
+
if (!this.pluginStatePath)
|
|
263
|
+
return null;
|
|
264
|
+
if (this.pluginCache && now - this.pluginCache.at < PLUGIN_STATE_READ_TTL_MS && now >= this.pluginCache.at) {
|
|
265
|
+
return this.pluginCache.value;
|
|
266
|
+
}
|
|
267
|
+
const value = readPluginEdgeState(this.pluginStatePath, now);
|
|
268
|
+
this.pluginCache = { at: now, value };
|
|
269
|
+
return value;
|
|
270
|
+
}
|
|
271
|
+
/** Compare the current verdict with the last emitted one; queue on change. */
|
|
272
|
+
refresh() {
|
|
273
|
+
// Force a fresh file read on a transition check so a plugin-side change
|
|
274
|
+
// is never masked by the 10 s cache.
|
|
275
|
+
this.pluginCache = null;
|
|
276
|
+
const h = this.health();
|
|
277
|
+
const denied = h?.status === 'edge_denied';
|
|
278
|
+
const now = this.now();
|
|
279
|
+
if (denied && !this.emittedDenied) {
|
|
280
|
+
this.emittedDenied = true;
|
|
281
|
+
this.emittedSince = h?.since ? Date.parse(h.since) : now;
|
|
282
|
+
this.recoveredAt = null;
|
|
283
|
+
this.pending.push({
|
|
284
|
+
event: 'webapp_edge_denied',
|
|
285
|
+
since: h?.since ?? new Date(now).toISOString(),
|
|
286
|
+
deniedCount: h?.deniedCount ?? 0,
|
|
287
|
+
source: h?.source ?? 'bridge',
|
|
288
|
+
requestId: h?.requestId ?? null,
|
|
289
|
+
lastPath: h?.lastPath ?? null,
|
|
290
|
+
timestamp: new Date(now).toISOString(),
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
else if (!denied && this.emittedDenied) {
|
|
294
|
+
this.emittedDenied = false;
|
|
295
|
+
this.recoveredAt = now;
|
|
296
|
+
this.pending.push({
|
|
297
|
+
event: 'webapp_edge_recovered',
|
|
298
|
+
since: new Date(this.emittedSince ?? now).toISOString(),
|
|
299
|
+
recoveredAt: new Date(now).toISOString(),
|
|
300
|
+
deniedCount: 0,
|
|
301
|
+
timestamp: new Date(now).toISOString(),
|
|
302
|
+
});
|
|
303
|
+
this.emittedSince = null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
// ---- process-wide singleton (the connector is single-tenant) ---------------------
|
|
308
|
+
let tracker = new WebappEdgeTracker();
|
|
309
|
+
export function webappEdgeTracker() {
|
|
310
|
+
return tracker;
|
|
311
|
+
}
|
|
312
|
+
/** Test-only: fresh tracker with injected clock / plugin file path. */
|
|
313
|
+
export function __resetWebappEdgeTrackerForTests(opts = {}) {
|
|
314
|
+
tracker = new WebappEdgeTracker(opts);
|
|
315
|
+
return tracker;
|
|
316
|
+
}
|
|
317
|
+
/** Inspect a webapp response on the shared tracker. Never throws. Returns the
|
|
318
|
+
* edge match (if any) so the caller can word its own log line. Pass
|
|
319
|
+
* `startedAt` (epoch ms before the request) so an in-flight success cannot
|
|
320
|
+
* end an episode that began after it was sent. */
|
|
321
|
+
export function noteWebappResponse(res, path, bodyText, startedAt) {
|
|
322
|
+
try {
|
|
323
|
+
if (res.ok) {
|
|
324
|
+
tracker.noteSuccess(startedAt);
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
const match = classifyEdgeDeny(res.status, res.headers, bodyText);
|
|
328
|
+
if (match)
|
|
329
|
+
tracker.noteDeny(path, match);
|
|
330
|
+
return match;
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
// ---- user agent ---------------------------------------------------------------------
|
|
337
|
+
let clientVersion = null;
|
|
338
|
+
/** Set once at boot from the installed bridge's package.json (index.ts). */
|
|
339
|
+
export function setWebappClientVersion(version) {
|
|
340
|
+
clientVersion = version && /^[0-9A-Za-z.+-]{1,40}$/.test(version) ? version : null;
|
|
341
|
+
}
|
|
342
|
+
export function webappUserAgent() {
|
|
343
|
+
return `reefclaw-connect/${clientVersion ?? 'unknown'} (openclaw-bridge)`;
|
|
344
|
+
}
|
|
345
|
+
/** Bearer + User-Agent for a webapp call. `extra` wins on key collision.
|
|
346
|
+
* Capitalised `Authorization` on purpose: the skill-pull test pins that key. */
|
|
347
|
+
export function webappHeaders(token, extra = {}) {
|
|
348
|
+
return {
|
|
349
|
+
Authorization: `Bearer ${token}`,
|
|
350
|
+
'user-agent': webappUserAgent(),
|
|
351
|
+
...extra,
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
/** Best-effort: the version stamped in the package.json beside the running
|
|
355
|
+
* entry (the installed bridge dir). Unknown → null; never throws. */
|
|
356
|
+
export function resolveBridgeVersion(entryPath = process.argv[1]) {
|
|
357
|
+
if (!entryPath)
|
|
358
|
+
return null;
|
|
359
|
+
try {
|
|
360
|
+
const raw = JSON.parse(readFileSync(join(dirname(entryPath), 'package.json'), 'utf-8'));
|
|
361
|
+
return typeof raw.version === 'string' && raw.version !== '0.1.0' ? raw.version : null;
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
@@ -18,6 +18,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from '
|
|
|
18
18
|
import { dirname, join } from 'node:path';
|
|
19
19
|
import { homedir } from 'node:os';
|
|
20
20
|
import { logger, formatError } from '../logger.js';
|
|
21
|
+
import { noteWebappResponse, webappHeaders } from '../http/webapp-edge.js';
|
|
21
22
|
const TAG = 'agent-config';
|
|
22
23
|
/** Shared four-stage ladder for the gates migrated so far. Kept as one set
|
|
23
24
|
* because exitGate + positionReviewMode use identical values; a future gate
|
|
@@ -147,14 +148,29 @@ export async function fetchAgentConfig(opts) {
|
|
|
147
148
|
const { apiBaseUrl, token, fetchImpl = fetch, timeoutMs = 10_000 } = opts;
|
|
148
149
|
const url = `${apiBaseUrl.replace(/\/+$/, '')}/api/internal/config`;
|
|
149
150
|
try {
|
|
151
|
+
const startedAt = Date.now();
|
|
150
152
|
const res = await fetchImpl(url, {
|
|
151
|
-
headers:
|
|
153
|
+
headers: webappHeaders(token),
|
|
152
154
|
signal: AbortSignal.timeout(timeoutMs),
|
|
153
155
|
});
|
|
154
156
|
if (!res.ok) {
|
|
155
|
-
|
|
157
|
+
// A 403 is classified on the shared edge gate: the edge firewall's
|
|
158
|
+
// plain-text Forbidden (IP-level block) vs the app's JSON denial. The
|
|
159
|
+
// gate logs the episode once; here we only tag the debug line.
|
|
160
|
+
let bodyText = null;
|
|
161
|
+
if (res.status === 403) {
|
|
162
|
+
try {
|
|
163
|
+
bodyText = (await res.text()).slice(0, 200);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
/* body unreadable — classify on headers alone */
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const edge = noteWebappResponse(res, '/api/internal/config', bodyText);
|
|
170
|
+
logger.debug(TAG, `config fetch non-200: ${res.status}${edge ? ' (edge firewall deny)' : ''}`);
|
|
156
171
|
return null;
|
|
157
172
|
}
|
|
173
|
+
noteWebappResponse(res, '/api/internal/config', undefined, startedAt);
|
|
158
174
|
const body = (await res.json());
|
|
159
175
|
const validated = validateAgentConfig(body);
|
|
160
176
|
if (!validated)
|
|
@@ -21,6 +21,10 @@ export interface AgentConfigPollerOptions {
|
|
|
21
21
|
fetchImpl?: typeof fetch;
|
|
22
22
|
intervalMs?: number;
|
|
23
23
|
cachePath?: string;
|
|
24
|
+
/** Fraction of the interval each tick may fire early (0 → exact cadence). */
|
|
25
|
+
jitter?: number;
|
|
26
|
+
/** Injectable RNG for deterministic tests. */
|
|
27
|
+
random?: () => number;
|
|
24
28
|
}
|
|
25
29
|
export interface AgentConfigPollerHandle {
|
|
26
30
|
stop(): void;
|
|
@@ -15,9 +15,17 @@
|
|
|
15
15
|
// multiple times per process and we must never spawn a second timer.
|
|
16
16
|
import { defaultAgentConfig, fetchAgentConfig, isAcceptableVersion, readCachedConfig, writeCachedConfig, } from './agent-config-client.js';
|
|
17
17
|
import { logger } from '../logger.js';
|
|
18
|
+
import { webappEdgeGate } from '../http/webapp-edge.js';
|
|
18
19
|
const TAG = 'agent-config';
|
|
19
20
|
const DEFAULT_POLL_MS = 60_000;
|
|
20
21
|
const MIN_POLL_MS = 5_000;
|
|
22
|
+
/** Each tick fires up to this fraction EARLY (never late): several boxes behind
|
|
23
|
+
* one IP restarted together must not knock on the webapp in lockstep every
|
|
24
|
+
* 60 s — that synchronized pattern is what Vercel's DDoS heuristics read as
|
|
25
|
+
* an attack (2026-09-28). Early-only keeps the configured interval the
|
|
26
|
+
* maximum gap, so tests and operators can still reason about "at least one
|
|
27
|
+
* poll per interval". */
|
|
28
|
+
const DEFAULT_JITTER = 0.2;
|
|
21
29
|
export function resolvePollIntervalMs() {
|
|
22
30
|
const raw = Number(process.env.RC_AGENT_CONFIG_POLL_MS);
|
|
23
31
|
if (!Number.isFinite(raw) || raw <= 0)
|
|
@@ -44,8 +52,11 @@ export function startAgentConfigPoller(opts) {
|
|
|
44
52
|
}
|
|
45
53
|
pollerStarted = true;
|
|
46
54
|
const intervalMs = opts.intervalMs ?? resolvePollIntervalMs();
|
|
55
|
+
const jitter = Math.min(0.5, Math.max(0, opts.jitter ?? DEFAULT_JITTER));
|
|
56
|
+
const random = opts.random ?? Math.random;
|
|
47
57
|
let current = defaultAgentConfig();
|
|
48
58
|
let loggedFetchFailure = false;
|
|
59
|
+
let loggedEdgeSkip = false;
|
|
49
60
|
const applyIfAcceptable = (fetched, source) => {
|
|
50
61
|
if (!isAcceptableVersion(fetched, current)) {
|
|
51
62
|
logger.warn(TAG, `rejected ${source} config v${fetched.version} < applied v${current.version} (rollback guard)`);
|
|
@@ -58,6 +69,17 @@ export function startAgentConfigPoller(opts) {
|
|
|
58
69
|
return true;
|
|
59
70
|
};
|
|
60
71
|
const poll = async (isBoot) => {
|
|
72
|
+
// The edge firewall is denying this host: every poll would be another
|
|
73
|
+
// 403 feeding the block. Keep last-known-good and wait the gate out; the
|
|
74
|
+
// boot poll still runs (it is the one that seeds the cache fallback).
|
|
75
|
+
if (!isBoot && webappEdgeGate().isBlocked()) {
|
|
76
|
+
if (!loggedEdgeSkip) {
|
|
77
|
+
loggedEdgeSkip = true;
|
|
78
|
+
logger.info(TAG, `config polls paused — webapp edge-denied (${Math.ceil(webappEdgeGate().msUntilOpen() / 60_000)} min); keeping v${current.version}`);
|
|
79
|
+
}
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
loggedEdgeSkip = false;
|
|
61
83
|
const fetched = await fetchAgentConfig({
|
|
62
84
|
apiBaseUrl: opts.apiBaseUrl,
|
|
63
85
|
token: opts.token,
|
|
@@ -93,13 +115,31 @@ export function startAgentConfigPoller(opts) {
|
|
|
93
115
|
}
|
|
94
116
|
};
|
|
95
117
|
void poll(true);
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
118
|
+
// Self-scheduling timeout (not setInterval) so each gap can be jittered
|
|
119
|
+
// early; the delay never exceeds intervalMs.
|
|
120
|
+
let timer = null;
|
|
121
|
+
let stopped = false;
|
|
122
|
+
const schedule = (elapsedMs = 0) => {
|
|
123
|
+
if (stopped)
|
|
124
|
+
return;
|
|
125
|
+
const early = intervalMs * jitter * Math.min(1, Math.max(0, random()));
|
|
126
|
+
// Measured from the START of the previous tick, so a slow fetch cannot
|
|
127
|
+
// push the next poll past the configured interval.
|
|
128
|
+
const delay = Math.max(1_000, Math.round(intervalMs - early - elapsedMs));
|
|
129
|
+
timer = setTimeout(() => {
|
|
130
|
+
const tickStart = Date.now();
|
|
131
|
+
void poll(false).finally(() => schedule(Date.now() - tickStart));
|
|
132
|
+
}, delay);
|
|
133
|
+
timer.unref();
|
|
134
|
+
};
|
|
135
|
+
schedule();
|
|
136
|
+
logger.info(TAG, `poller started (interval ${Math.round(intervalMs / 1000)}s, jitter ${Math.round(jitter * 100)}% early)`);
|
|
101
137
|
return {
|
|
102
|
-
stop: () =>
|
|
138
|
+
stop: () => {
|
|
139
|
+
stopped = true;
|
|
140
|
+
if (timer)
|
|
141
|
+
clearTimeout(timer);
|
|
142
|
+
},
|
|
103
143
|
getCurrent: () => current,
|
|
104
144
|
};
|
|
105
145
|
}
|
|
@@ -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;
|