@reefclaw/openclaw-plugin 0.1.47 → 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.
@@ -0,0 +1,145 @@
1
+ export interface HeadersLike {
2
+ get(name: string): string | null;
3
+ }
4
+ export interface EdgeDenyMatch {
5
+ kind: 'vercel_mitigated' | 'plain_forbidden';
6
+ action: string | null;
7
+ requestId: string | null;
8
+ }
9
+ /** Is this 403 the edge (Vercel) rather than the webapp? Pure. The app's own
10
+ * denials are JSON; the edge answers text/plain "Forbidden" + `x-vercel-mitigated`. */
11
+ export declare function classifyEdgeDeny(status: number, headers: HeadersLike | null | undefined, bodyText?: string | null): EdgeDenyMatch | null;
12
+ /** Kill-switch (repo convention: every new mechanism ships with one).
13
+ * `RC_WEBAPP_EDGE_GATE=off` disables the BRAKE only — no call is ever skipped
14
+ * or deferred — while detection, logging, the state file and the relay-borne
15
+ * health signal stay on. Read at call time; logged once. */
16
+ export declare function webappEdgeGateDisabled(): boolean;
17
+ /** The health field carried on agent_state (webapp/src/types/agent.ts
18
+ * AgentHealth.webappApi). Absent from the payload while nothing was ever
19
+ * denied, so older dashboards see a byte-identical shape. */
20
+ export interface WebappApiHealth {
21
+ status: 'ok' | 'edge_denied';
22
+ /** ISO — first deny of the current episode. */
23
+ since?: string;
24
+ lastDeniedAt?: string;
25
+ deniedCount: number;
26
+ /** Who observed it: the connector's own calls, the plugin's gate file, or both. */
27
+ source: 'bridge' | 'plugin' | 'both';
28
+ requestId?: string | null;
29
+ lastPath?: string | null;
30
+ /** ISO — when the last episode ended (status 'ok' only). */
31
+ recoveredAt?: string;
32
+ }
33
+ export type WebappEdgeEvent = {
34
+ event: 'webapp_edge_denied';
35
+ since: string;
36
+ deniedCount: number;
37
+ source: WebappApiHealth['source'];
38
+ requestId: string | null;
39
+ lastPath: string | null;
40
+ timestamp: string;
41
+ } | {
42
+ event: 'webapp_edge_recovered';
43
+ since: string;
44
+ recoveredAt: string;
45
+ deniedCount: number;
46
+ timestamp: string;
47
+ };
48
+ /** Shape of the plugin's state file (plugin/src/http/webapp-edge.ts). Only the
49
+ * fields read here are typed; unknown fields are ignored. */
50
+ interface PluginEdgeStateFile {
51
+ schemaVersion?: number;
52
+ updatedAt?: number;
53
+ blocked?: boolean;
54
+ blockedUntil?: number | null;
55
+ firstDeniedAt?: number | null;
56
+ lastDeniedAt?: number | null;
57
+ deniedCount?: number;
58
+ lastPath?: string | null;
59
+ lastRequestId?: string | null;
60
+ }
61
+ export declare function defaultPluginEdgeStatePath(): string;
62
+ /** Read + validate the plugin's gate file. Missing/corrupt/stale → null. */
63
+ export declare function readPluginEdgeState(path?: string, now?: number): PluginEdgeStateFile | null;
64
+ /** Is the plugin file describing an episode that is still live? */
65
+ export declare function pluginEpisodeActive(f: PluginEdgeStateFile | null, now: number): boolean;
66
+ /** 5 → 10 → 20 → 30 min — the plugin gate's ladder (30 = Vercel's window). */
67
+ export declare const DEFAULT_EDGE_BACKOFF_LADDER_MS: readonly number[];
68
+ export interface WebappEdgeTrackerOptions {
69
+ now?: () => number;
70
+ /** Where the plugin writes its gate file; null disables the merge. */
71
+ pluginStatePath?: string | null;
72
+ backoffLadderMs?: readonly number[];
73
+ }
74
+ /**
75
+ * Merges the bridge's own observations with the plugin's file into one
76
+ * health verdict, runs the bridge-side backoff gate, and queues one event per
77
+ * transition for the bridge to emit.
78
+ */
79
+ export declare class WebappEdgeTracker {
80
+ private readonly now;
81
+ private readonly pluginStatePath;
82
+ private readonly ladder;
83
+ private firstDeniedAt;
84
+ private lastDeniedAt;
85
+ private deniedCount;
86
+ private lastPath;
87
+ private lastRequestId;
88
+ private blockedUntil;
89
+ private step;
90
+ private emittedDenied;
91
+ private emittedSince;
92
+ private recoveredAt;
93
+ private lastSource;
94
+ private pending;
95
+ private pluginCache;
96
+ constructor(opts?: WebappEdgeTrackerOptions);
97
+ /** The bridge itself observed a deny that no success has cleared yet. */
98
+ hasOwnEpisode(): boolean;
99
+ /** True while the bridge's own periodic webapp calls should be skipped.
100
+ * Always false under the kill-switch (the episode itself is still tracked). */
101
+ isBlocked(): boolean;
102
+ /** ms until the bridge gate reopens (0 when open). */
103
+ msUntilOpen(): number;
104
+ /** The connector's own webapp call was denied by the edge. Only an
105
+ * UNBLOCKED deny climbs the ladder (several 403s at the start of a ban are
106
+ * one event, not four). */
107
+ noteDeny(rawPath: string, match: EdgeDenyMatch): void;
108
+ /** The connector's own webapp call succeeded. A response that was already
109
+ * in flight when the ban started proves nothing: pass `startedAt` and a
110
+ * success older than the last deny is ignored. */
111
+ noteSuccess(startedAt?: number): void;
112
+ /** Current verdict (bridge ∪ plugin file). Undefined while nothing was ever
113
+ * denied — the caller omits the field. Re-reads the plugin file (cached
114
+ * 10 s), so a plugin-only episode is picked up on every state build. */
115
+ health(): WebappApiHealth | undefined;
116
+ /** Drain the queued transition events (called by the bridge's emitter). Also
117
+ * refreshes against the plugin file so a plugin-only transition is noticed
118
+ * even when the bridge made no webapp call of its own. */
119
+ takeEvents(): WebappEdgeEvent[];
120
+ private pluginState;
121
+ /** Compare the current verdict with the last emitted one; queue on change. */
122
+ private refresh;
123
+ }
124
+ export declare function webappEdgeTracker(): WebappEdgeTracker;
125
+ /** Test-only: fresh tracker with injected clock / plugin file path. */
126
+ export declare function __resetWebappEdgeTrackerForTests(opts?: WebappEdgeTrackerOptions): WebappEdgeTracker;
127
+ /** Inspect a webapp response on the shared tracker. Never throws. Returns the
128
+ * edge match (if any) so the caller can word its own log line. Pass
129
+ * `startedAt` (epoch ms before the request) so an in-flight success cannot
130
+ * end an episode that began after it was sent. */
131
+ export declare function noteWebappResponse(res: {
132
+ ok: boolean;
133
+ status: number;
134
+ headers: HeadersLike;
135
+ }, path: string, bodyText?: string | null, startedAt?: number): EdgeDenyMatch | null;
136
+ /** Set once at boot from the installed bridge's package.json (index.ts). */
137
+ export declare function setWebappClientVersion(version: string | null | undefined): void;
138
+ export declare function webappUserAgent(): string;
139
+ /** Bearer + User-Agent for a webapp call. `extra` wins on key collision.
140
+ * Capitalised `Authorization` on purpose: the skill-pull test pins that key. */
141
+ export declare function webappHeaders(token: string, extra?: Record<string, string>): Record<string, string>;
142
+ /** Best-effort: the version stamped in the package.json beside the running
143
+ * entry (the installed bridge dir). Unknown → null; never throws. */
144
+ export declare function resolveBridgeVersion(entryPath?: string | undefined): string | null;
145
+ export {};
@@ -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: { authorization: `Bearer ${token}` },
153
+ headers: webappHeaders(token),
152
154
  signal: AbortSignal.timeout(timeoutMs),
153
155
  });
154
156
  if (!res.ok) {
155
- logger.debug(TAG, `config fetch non-200: ${res.status}`);
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
- const timer = setInterval(() => {
97
- void poll(false);
98
- }, intervalMs);
99
- timer.unref();
100
- logger.info(TAG, `poller started (interval ${Math.round(intervalMs / 1000)}s)`);
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: () => clearInterval(timer),
138
+ stop: () => {
139
+ stopped = true;
140
+ if (timer)
141
+ clearTimeout(timer);
142
+ },
103
143
  getCurrent: () => current,
104
144
  };
105
145
  }