@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.
Files changed (74) hide show
  1. package/README.md +1 -1
  2. package/bridge/bridge.d.ts +39 -0
  3. package/bridge/bridge.js +210 -7
  4. package/bridge/config.js +5 -2
  5. package/bridge/gateway/gateway-config.d.ts +5 -0
  6. package/bridge/gateway/gateway-config.js +5 -2
  7. package/bridge/gateway/heartbeat-cron.js +3 -2
  8. package/bridge/heartbeat-runs.d.ts +6 -0
  9. package/bridge/heartbeat-runs.js +45 -4
  10. package/bridge/heartbeat-transcript.d.ts +2 -0
  11. package/bridge/heartbeat-transcript.js +45 -13
  12. package/bridge/index.js +31 -0
  13. package/bridge/providers/connector-update.js +22 -5
  14. package/bridge/providers/emergency-commands.js +2 -3
  15. package/bridge/providers/gateway.d.ts +6 -0
  16. package/bridge/providers/gateway.js +57 -27
  17. package/bridge/providers/onboarding-commands.d.ts +8 -7
  18. package/bridge/setup.js +12 -0
  19. package/bridge/shock-wake.d.ts +7 -0
  20. package/bridge/shock-wake.js +72 -9
  21. package/bridge/types.d.ts +17 -0
  22. package/bridge/utils/base-url.d.ts +26 -0
  23. package/bridge/utils/base-url.js +108 -0
  24. package/bridge/utils/operator-secret.d.ts +7 -0
  25. package/bridge/utils/operator-secret.js +59 -0
  26. package/bridge/utils/relay-host.d.ts +23 -0
  27. package/bridge/utils/relay-host.js +66 -0
  28. package/bridge/utils/untrusted-text.d.ts +9 -0
  29. package/bridge/utils/untrusted-text.js +51 -0
  30. package/bridge/utils/webapp-edge.d.ts +145 -0
  31. package/bridge/utils/webapp-edge.js +366 -0
  32. package/config/agent-config-client.js +18 -2
  33. package/config/agent-config-poller.d.ts +4 -0
  34. package/config/agent-config-poller.js +46 -6
  35. package/config/base-url.d.ts +16 -0
  36. package/config/base-url.js +87 -0
  37. package/config/operator-provenance.d.ts +19 -0
  38. package/config/operator-provenance.js +102 -25
  39. package/config/user-data-stream-config.d.ts +5 -1
  40. package/config/user-data-stream-config.js +7 -5
  41. package/connector-supervisor.d.ts +15 -0
  42. package/connector-supervisor.js +22 -1
  43. package/http/webapp-edge.d.ts +116 -0
  44. package/http/webapp-edge.js +313 -0
  45. package/index.js +36 -24
  46. package/ingest/position-decisions-client.js +51 -11
  47. package/ingest/readiness-reporter.d.ts +13 -0
  48. package/ingest/readiness-reporter.js +78 -8
  49. package/ingest/retry-after.d.ts +5 -0
  50. package/ingest/retry-after.js +21 -0
  51. package/ingest/trade-store-client.js +43 -7
  52. package/lifecycle/process-role.d.ts +4 -0
  53. package/lifecycle/process-role.js +1 -1
  54. package/openclaw.plugin.json +1 -1
  55. package/package.json +2 -2
  56. package/release-integrity.json +10 -0
  57. package/release-notes.json +3 -1
  58. package/risk/pre-trade-check.js +1 -1
  59. package/risk/stop-widening-guard.d.ts +35 -0
  60. package/risk/stop-widening-guard.js +98 -0
  61. package/skills/reefclaw/SKILL.md +2 -2
  62. package/tools/create-order.js +17 -12
  63. package/tools/get-bracket-config.d.ts +3 -1
  64. package/tools/get-bracket-config.js +3 -1
  65. package/tools/get-market-intel.d.ts +4 -0
  66. package/tools/get-market-intel.js +38 -4
  67. package/tools/modify-stop.d.ts +6 -0
  68. package/tools/modify-stop.js +110 -0
  69. package/tools/set-bracket-requirement.d.ts +7 -0
  70. package/tools/set-bracket-requirement.js +12 -0
  71. package/trading-params-bounds.d.ts +32 -0
  72. package/trading-params-bounds.js +113 -0
  73. package/trading-params-cache.d.ts +9 -1
  74. package/trading-params-cache.js +33 -2
package/bridge/types.d.ts CHANGED
@@ -141,10 +141,27 @@ export interface AgentStateData {
141
141
  * cron job's FailoverReason + the last recorded beat
142
142
  * (skill/src/model-health.ts). Absent until first derived. */
143
143
  modelHealth?: ModelHealthSummary;
144
+ /** Can this host reach ReefClaw's webapp, or is its IP being denied at
145
+ * the edge (Vercel DDoS mitigation)? Bridge ∪ plugin observation
146
+ * (skill/src/utils/webapp-edge.ts). Absent while never denied — the
147
+ * relay is the one channel that still works during the deny, so this
148
+ * is how the dashboard learns of it. */
149
+ webappApi?: WebappApiHealth;
144
150
  };
145
151
  };
146
152
  timestamp: string;
147
153
  }
154
+ /** See skill/src/utils/webapp-edge.ts (mirrored in webapp/src/types/agent.ts). */
155
+ export interface WebappApiHealth {
156
+ status: 'ok' | 'edge_denied';
157
+ since?: string;
158
+ lastDeniedAt?: string;
159
+ deniedCount: number;
160
+ source: 'bridge' | 'plugin' | 'both';
161
+ requestId?: string | null;
162
+ lastPath?: string | null;
163
+ recoveredAt?: string;
164
+ }
148
165
  /** Dashboard-facing summary of one heartbeat run (the full record lives in
149
166
  * the webapp's heartbeat_runs table). Token counts are RAW COUNTS — never
150
167
  * translated to a currency here or downstream. */
@@ -0,0 +1,26 @@
1
+ export declare const DEFAULT_WEBAPP_URL = "https://www.reefclaw.com";
2
+ /** True for hosts where cleartext never leaves the machine / private network. */
3
+ export declare function isPrivateHost(hostname: string): boolean;
4
+ export interface UrlCheck {
5
+ url: string;
6
+ /** Present when the configured value was rejected and `url` is the fallback. */
7
+ rejected?: {
8
+ value: string;
9
+ reason: string;
10
+ };
11
+ /** Present when cleartext was tolerated because the host is private. */
12
+ insecurePrivate?: boolean;
13
+ }
14
+ /** Validate an https base URL without side effects. */
15
+ export declare function checkBaseUrl(raw: unknown, fallback: string): UrlCheck;
16
+ /** Validate a wss relay URL without side effects. */
17
+ export declare function checkRelayUrl(raw: unknown, fallback: string): UrlCheck;
18
+ /** Validate + log an https base URL. Returns the URL the caller must use. */
19
+ export declare function sanitizeBaseUrl(raw: unknown, fallback: string, label: string): string;
20
+ /** Validate + log a wss relay URL. Returns the URL the caller must use. */
21
+ export declare function sanitizeRelayUrl(raw: unknown, fallback: string, label: string): string;
22
+ /** The webapp base URL every bridge call must use: an explicit override,
23
+ * else `REEFCLAW_API_URL`, else production — scheme-checked. `www` is
24
+ * load-bearing in the default: reefclaw.com 307-redirects and Node fetch
25
+ * strips the Authorization header on a cross-origin redirect. */
26
+ export declare function resolveWebappBaseUrl(override?: string): string;
@@ -0,0 +1,108 @@
1
+ // Outbound URL scheme check for the bridge's own service endpoints.
2
+ //
3
+ // Copy of plugin/src/config/base-url.ts (the bridge and the plugin are
4
+ // separately vendored packages; keep the two in sync like the redact.ts
5
+ // copies). The bridge sends the tenant's rc_ token as a Bearer header to the
6
+ // webapp (REEFCLAW_API_URL) and to intel (intelligenceUrl), and its relay
7
+ // socket carries the token in the auth query. Before this module a plain
8
+ // `http://` / `ws://` value from the environment or config was used verbatim
9
+ // (audit 2026-09-27 H4).
10
+ //
11
+ // Rule: `https:` / `wss:` required for any public host. Cleartext (`http:` /
12
+ // `ws:`) is tolerated ONLY for loopback and private-range hosts (localhost,
13
+ // RFC 1918, the 100.64/10 CGNAT block Tailscale uses, link-local, ULA) — the
14
+ // local-dev (`partykit dev`) / on-prem cases — with a warning. Anything else
15
+ // falls back to the production default. No env override on purpose.
16
+ import { logger } from '../logger.js';
17
+ const TAG = 'base-url';
18
+ export const DEFAULT_WEBAPP_URL = 'https://www.reefclaw.com';
19
+ /** True for hosts where cleartext never leaves the machine / private network. */
20
+ export function isPrivateHost(hostname) {
21
+ const h = hostname.toLowerCase().replace(/^\[|\]$/g, '');
22
+ if (h === 'localhost' || h.endsWith('.localhost') || h === '::1' || h === '0.0.0.0')
23
+ return true;
24
+ // Names that only resolve inside a private network: Docker's host alias,
25
+ // mDNS `.local`, `.internal` (RFC 6762 / 8375), Tailscale MagicDNS `.ts.net`.
26
+ // Review 2026-09-27 N2: a dev/staging box on one of these was classified
27
+ // public and silently fell back to the PRODUCTION URL with its token.
28
+ if (h === 'host.docker.internal' || h.endsWith('.internal') || h.endsWith('.local') || h.endsWith('.ts.net'))
29
+ return true;
30
+ const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
31
+ if (v4) {
32
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
33
+ if (a === 127)
34
+ return true; // loopback
35
+ if (a === 10)
36
+ return true; // RFC 1918
37
+ if (a === 172 && b >= 16 && b <= 31)
38
+ return true; // RFC 1918
39
+ if (a === 192 && b === 168)
40
+ return true; // RFC 1918
41
+ if (a === 100 && b >= 64 && b <= 127)
42
+ return true; // CGNAT / Tailscale
43
+ if (a === 169 && b === 254)
44
+ return true; // link-local
45
+ return false;
46
+ }
47
+ // IPv6 ULA (fc00::/7) and link-local (fe80::/10).
48
+ if (/^f[cd][0-9a-f]{2}:/.test(h) || /^fe[89ab][0-9a-f]:/.test(h))
49
+ return true;
50
+ return false;
51
+ }
52
+ function checkScheme(raw, fallback, secure, clear) {
53
+ if (typeof raw !== 'string' || raw.trim() === '')
54
+ return { url: fallback };
55
+ const value = raw.trim();
56
+ let parsed;
57
+ try {
58
+ parsed = new URL(value);
59
+ }
60
+ catch {
61
+ return { url: fallback, rejected: { value, reason: 'not a valid absolute URL' } };
62
+ }
63
+ const normalized = value.replace(/\/+$/, '');
64
+ if (parsed.protocol === secure)
65
+ return { url: normalized };
66
+ if (parsed.protocol === clear) {
67
+ if (isPrivateHost(parsed.hostname))
68
+ return { url: normalized, insecurePrivate: true };
69
+ return {
70
+ url: fallback,
71
+ rejected: { value, reason: `plain ${clear}// to a public host would send the connection token in cleartext` },
72
+ };
73
+ }
74
+ return { url: fallback, rejected: { value, reason: `unsupported scheme ${parsed.protocol}` } };
75
+ }
76
+ /** Validate an https base URL without side effects. */
77
+ export function checkBaseUrl(raw, fallback) {
78
+ return checkScheme(raw, fallback, 'https:', 'http:');
79
+ }
80
+ /** Validate a wss relay URL without side effects. */
81
+ export function checkRelayUrl(raw, fallback) {
82
+ return checkScheme(raw, fallback, 'wss:', 'ws:');
83
+ }
84
+ function report(check, fallback, label) {
85
+ if (check.rejected) {
86
+ logger.warn(TAG, `${label}=${JSON.stringify(check.rejected.value)} rejected (${check.rejected.reason}) — using ${fallback}`);
87
+ }
88
+ else if (check.insecurePrivate) {
89
+ logger.warn(TAG, `${label}=${check.url} uses a cleartext scheme to a private host — tolerated for local/on-prem use only`);
90
+ }
91
+ return check.url;
92
+ }
93
+ /** Validate + log an https base URL. Returns the URL the caller must use. */
94
+ export function sanitizeBaseUrl(raw, fallback, label) {
95
+ return report(checkBaseUrl(raw, fallback), fallback, label);
96
+ }
97
+ /** Validate + log a wss relay URL. Returns the URL the caller must use. */
98
+ export function sanitizeRelayUrl(raw, fallback, label) {
99
+ return report(checkRelayUrl(raw, fallback), fallback, label);
100
+ }
101
+ /** The webapp base URL every bridge call must use: an explicit override,
102
+ * else `REEFCLAW_API_URL`, else production — scheme-checked. `www` is
103
+ * load-bearing in the default: reefclaw.com 307-redirects and Node fetch
104
+ * strips the Authorization header on a cross-origin redirect. */
105
+ export function resolveWebappBaseUrl(override) {
106
+ const raw = override ?? process.env.REEFCLAW_API_URL;
107
+ return sanitizeBaseUrl(raw, DEFAULT_WEBAPP_URL, 'REEFCLAW_API_URL');
108
+ }
@@ -0,0 +1,7 @@
1
+ export declare const OPERATOR_SECRET_STDIN_MARKER = "REEFCLAW_OPERATOR_SECRET_STDIN";
2
+ /** Read one line from `fd` (default stdin) synchronously. Returns the line
3
+ * without its newline, or undefined on EOF / oversize / read error. */
4
+ export declare function readSecretLine(fd?: number): string | undefined;
5
+ /** The provenance secret for this process, or undefined when the plugin did
6
+ * not spawn us (no marker) or the line could not be read. */
7
+ export declare function readOperatorSecretFromStdin(env?: NodeJS.ProcessEnv, fd?: number): string | undefined;
@@ -0,0 +1,59 @@
1
+ // Operator-provenance secret handed to this bridge by the plugin that
2
+ // supervises it (plugin/src/connector-supervisor.ts, audit 2026-09-27 H1).
3
+ //
4
+ // The plugin mints a random per-boot value, spawns the bridge with stdin as a
5
+ // pipe, writes the secret as ONE line and closes the pipe. The bridge attaches
6
+ // it as `operator_token` on the operator-only tools (set_trading_mode,
7
+ // credential tools, set_bracket_requirement, …); the plugin accepts nothing
8
+ // else while a secret is issued. It never touches argv, the environment, or
9
+ // disk — the three places a same-user agent process can read.
10
+ //
11
+ // The environment carries only a non-secret MARKER (value '1') so a bridge
12
+ // started any other way (systemd unit, `node dist/index.js` by hand) does not
13
+ // block on a stdin that nobody will write to.
14
+ import { readSync } from 'node:fs';
15
+ export const OPERATOR_SECRET_STDIN_MARKER = 'REEFCLAW_OPERATOR_SECRET_STDIN';
16
+ /** A secret is 64 hex chars; anything past this is not ours. */
17
+ const MAX_LINE = 512;
18
+ /** EAGAIN retries before giving up (≈2 s at 5 ms). A non-blocking fd 0 with
19
+ * no writer must never spin the CPU forever (review 2026-09-27 N5). */
20
+ const MAX_EAGAIN_RETRIES = 400;
21
+ const EAGAIN_WAIT_MS = 5;
22
+ /** Read one line from `fd` (default stdin) synchronously. Returns the line
23
+ * without its newline, or undefined on EOF / oversize / read error. */
24
+ export function readSecretLine(fd = 0) {
25
+ const buf = Buffer.alloc(1);
26
+ let line = '';
27
+ let eagain = 0;
28
+ for (;;) {
29
+ let n;
30
+ try {
31
+ n = readSync(fd, buf, 0, 1, null);
32
+ }
33
+ catch (err) {
34
+ // EAGAIN on a non-blocking stdin: retry briefly (bounded); anything else = give up.
35
+ if (err.code === 'EAGAIN' && eagain++ < MAX_EAGAIN_RETRIES) {
36
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, EAGAIN_WAIT_MS);
37
+ continue;
38
+ }
39
+ return undefined;
40
+ }
41
+ if (n === 0)
42
+ return line.length > 0 ? line : undefined; // EOF
43
+ const ch = buf.toString('utf8');
44
+ if (ch === '\n')
45
+ return line;
46
+ if (ch !== '\r')
47
+ line += ch;
48
+ if (line.length > MAX_LINE)
49
+ return undefined;
50
+ }
51
+ }
52
+ /** The provenance secret for this process, or undefined when the plugin did
53
+ * not spawn us (no marker) or the line could not be read. */
54
+ export function readOperatorSecretFromStdin(env = process.env, fd = 0) {
55
+ if (env[OPERATOR_SECRET_STDIN_MARKER] !== '1')
56
+ return undefined;
57
+ const line = readSecretLine(fd)?.trim();
58
+ return line && /^[A-Za-z0-9._~+/=-]{16,}$/.test(line) ? line : undefined;
59
+ }
@@ -0,0 +1,23 @@
1
+ /** Hosts (exact, lowercase) or suffixes (leading dot) of ReefClaw relays. */
2
+ export declare const ALLOWED_RELAY_HOSTS: readonly string[];
3
+ export declare const ALLOW_CUSTOM_RELAY_ENV = "REEFCLAW_ALLOW_CUSTOM_RELAY";
4
+ export type RelayHostVerdict = {
5
+ ok: true;
6
+ host: string;
7
+ reason: 'allowlisted' | 'private_dev' | 'custom_opt_in';
8
+ } | {
9
+ ok: false;
10
+ host: string | null;
11
+ reason: 'unparseable' | 'not_allowlisted';
12
+ };
13
+ /**
14
+ * Decide whether the bridge may connect to `relayUrl`.
15
+ * - a ReefClaw host (exact or suffix match) → ok;
16
+ * - loopback / private hosts (partykit dev) → ok;
17
+ * - anything else → ok only when `allowCustom` (the env opt-out) is set.
18
+ */
19
+ export declare function checkRelayHost(relayUrl: string, allowCustom?: boolean): RelayHostVerdict;
20
+ /** Operator-facing explanation for a refused relay host. */
21
+ export declare function describeRelayRefusal(v: Extract<RelayHostVerdict, {
22
+ ok: false;
23
+ }>): string;
@@ -0,0 +1,66 @@
1
+ // Relay host allowlist for the connect bundle (audit 2026-09-27 M11).
2
+ //
3
+ // The onboarding "connect message" carries the rc_ token, the userId AND the
4
+ // relay URL. Before this module any `wss://` host in a pasted message was
5
+ // accepted: a phished or rewritten message pointed the bridge at an attacker
6
+ // relay, which then received the real token in the Authorization header,
7
+ // authenticated as the agent to the webapp and intel, and squatted the skill
8
+ // slot. Only ReefClaw relay hosts are accepted now; a self-hoster running
9
+ // their own relay opts out explicitly with REEFCLAW_ALLOW_CUSTOM_RELAY=1.
10
+ //
11
+ // The installer itself saves whatever wss:// host the connect message names
12
+ // (installer/src/bundle.ts); this module is the enforcement point — the bridge
13
+ // refuses to start against a host outside the list (skill/src/index.ts).
14
+ // (Review 2026-09-27: an earlier comment here claimed an installer-side copy
15
+ // that does not exist.)
16
+ /** Hosts (exact, lowercase) or suffixes (leading dot) of ReefClaw relays. */
17
+ export const ALLOWED_RELAY_HOSTS = [
18
+ 'reefclaw.radunlupsa.partykit.dev',
19
+ '.reefclaw.com',
20
+ '.reefclaw.partykit.dev',
21
+ ];
22
+ export const ALLOW_CUSTOM_RELAY_ENV = 'REEFCLAW_ALLOW_CUSTOM_RELAY';
23
+ function isPrivateHost(h) {
24
+ if (h === 'localhost' || h.endsWith('.localhost') || h === '::1' || h === '[::1]')
25
+ return true;
26
+ const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
27
+ if (!v4)
28
+ return false;
29
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
30
+ return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127);
31
+ }
32
+ /**
33
+ * Decide whether the bridge may connect to `relayUrl`.
34
+ * - a ReefClaw host (exact or suffix match) → ok;
35
+ * - loopback / private hosts (partykit dev) → ok;
36
+ * - anything else → ok only when `allowCustom` (the env opt-out) is set.
37
+ */
38
+ export function checkRelayHost(relayUrl, allowCustom = process.env[ALLOW_CUSTOM_RELAY_ENV] === '1') {
39
+ let host;
40
+ try {
41
+ host = new URL(relayUrl).hostname.toLowerCase();
42
+ }
43
+ catch {
44
+ return { ok: false, host: null, reason: 'unparseable' };
45
+ }
46
+ if (!host)
47
+ return { ok: false, host: null, reason: 'unparseable' };
48
+ for (const entry of ALLOWED_RELAY_HOSTS) {
49
+ if (entry.startsWith('.') ? host.endsWith(entry) || host === entry.slice(1) : host === entry) {
50
+ return { ok: true, host, reason: 'allowlisted' };
51
+ }
52
+ }
53
+ if (isPrivateHost(host))
54
+ return { ok: true, host, reason: 'private_dev' };
55
+ if (allowCustom)
56
+ return { ok: true, host, reason: 'custom_opt_in' };
57
+ return { ok: false, host, reason: 'not_allowlisted' };
58
+ }
59
+ /** Operator-facing explanation for a refused relay host. */
60
+ export function describeRelayRefusal(v) {
61
+ return v.reason === 'unparseable'
62
+ ? 'The relay URL in the connect message could not be parsed.'
63
+ : `The relay host "${v.host}" is not a ReefClaw relay. A connect message from reefclaw.com always points at ` +
64
+ `${ALLOWED_RELAY_HOSTS[0]} — a different host means the message was altered, and connecting would hand it your token. ` +
65
+ `Self-hosting your own relay? Set ${ALLOW_CUSTOM_RELAY_ENV}=1 in the connector's environment to allow it.`;
66
+ }
@@ -0,0 +1,9 @@
1
+ /** Strip hidden code points, fold every whitespace run (incl. newlines) to one
2
+ * space, trim, cap at `max` chars (with a visible marker when cut). */
3
+ export declare function fenceInlineText(raw: unknown, max?: number): string;
4
+ /** Accept only a label-shaped token (letters, digits, `_`, `-`, `/`, `:`, `.`);
5
+ * anything else — including an empty string — becomes `fallback`. For
6
+ * fields that are enum-like on the wire (symbol, regime, strategy, direction). */
7
+ export declare function labelOr(raw: unknown, fallback: string, max?: number): string;
8
+ /** A finite number, else `fallback`. JSON from a service can carry anything. */
9
+ export declare function finiteOr(raw: unknown, fallback: number): number;
@@ -0,0 +1,51 @@
1
+ // Untrusted-text hygiene for strings the bridge interpolates into AGENT TURNS
2
+ // (shock wakes, mission presentations). Those turns carry system authority in
3
+ // the agent's context, so an intel-supplied string that reaches them verbatim
4
+ // is a prompt-injection channel (audit 2026-09-27 M5). Mirror of the plugin's
5
+ // tools/get-market-intel.ts sanitizer (separately vendored package; keep in
6
+ // sync): strips control / zero-width / bidi-override code points that hide or
7
+ // spoof injected instructions, collapses line breaks (a newline inside a
8
+ // "label" would let it fake a new bullet or header of OUR message), and caps
9
+ // length.
10
+ const HIDDEN_CODEPOINT_RANGES = [
11
+ [0x00, 0x08], [0x0b, 0x1f], [0x7f, 0x9f], // C0 (keep TAB/LF for now — collapsed below), DEL + C1
12
+ [0x200b, 0x200f], // zero-width space/joiner + LRM/RLM
13
+ [0x202a, 0x202e], // bidi embeddings/overrides
14
+ [0x2066, 0x2069], // bidi isolates
15
+ [0xfeff, 0xfeff], // BOM
16
+ ];
17
+ function isHidden(cp) {
18
+ for (const [lo, hi] of HIDDEN_CODEPOINT_RANGES)
19
+ if (cp >= lo && cp <= hi)
20
+ return true;
21
+ return false;
22
+ }
23
+ /** Strip hidden code points, fold every whitespace run (incl. newlines) to one
24
+ * space, trim, cap at `max` chars (with a visible marker when cut). */
25
+ export function fenceInlineText(raw, max = 200) {
26
+ if (typeof raw !== 'string')
27
+ return '';
28
+ let out = '';
29
+ for (const ch of raw) {
30
+ const cp = ch.codePointAt(0);
31
+ if (cp !== undefined && !isHidden(cp))
32
+ out += ch;
33
+ }
34
+ out = out.replace(/\s+/g, ' ').trim();
35
+ return out.length > max ? `${out.slice(0, max)}…` : out;
36
+ }
37
+ /** Accept only a label-shaped token (letters, digits, `_`, `-`, `/`, `:`, `.`);
38
+ * anything else — including an empty string — becomes `fallback`. For
39
+ * fields that are enum-like on the wire (symbol, regime, strategy, direction). */
40
+ export function labelOr(raw, fallback, max = 32) {
41
+ if (typeof raw !== 'string')
42
+ return fallback;
43
+ const s = raw.trim();
44
+ if (s.length === 0 || s.length > max || !/^[A-Za-z0-9_\-/:.]+$/.test(s))
45
+ return fallback;
46
+ return s;
47
+ }
48
+ /** A finite number, else `fallback`. JSON from a service can carry anything. */
49
+ export function finiteOr(raw, fallback) {
50
+ return typeof raw === 'number' && Number.isFinite(raw) ? raw : fallback;
51
+ }
@@ -0,0 +1,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 {};