@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
|
@@ -1,50 +1,127 @@
|
|
|
1
1
|
// Operator-provenance gate for the state-mutating operator tools
|
|
2
|
-
// (audit 2026-07-26 F12).
|
|
2
|
+
// (audit 2026-07-26 F12; redesigned audit 2026-09-27 H1).
|
|
3
3
|
//
|
|
4
4
|
// "Operator-only. Never called by the agent." was PROSE in four tool
|
|
5
5
|
// descriptions — nothing enforced it, and `acknowledged:true` is
|
|
6
6
|
// caller-supplied, so a tool-capable agent could walk the PAPER→LIVE ladder,
|
|
7
7
|
// clear the exchange credentials, or disable the stop-loss requirement with
|
|
8
|
-
// one impulsive call. The dashboard path (browser → relay →
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
// its own copy. The chat redaction guards keep rc_* tokens OUT of the
|
|
12
|
-
// agent's context, so the agent cannot produce one conversationally.
|
|
8
|
+
// one impulsive call. The dashboard path (browser → relay → bridge → gateway
|
|
9
|
+
// `/tools/invoke`) proves provenance by attaching a secret the agent does not
|
|
10
|
+
// have.
|
|
13
11
|
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
12
|
+
// ★ WHAT THE SECRET IS (2026-09-27): a random per-boot value the plugin MINTS
|
|
13
|
+
// in memory and hands to the bridge it supervises over the child's STDIN at
|
|
14
|
+
// spawn — never argv (visible in `ps`), never the environment (readable from
|
|
15
|
+
// /proc/<pid>/environ by any same-user process, i.e. the agent's `exec`),
|
|
16
|
+
// never a file. The previous scheme used the rc_ connection token, which the
|
|
17
|
+
// onboarding flow tells the agent to write into its own config and which the
|
|
18
|
+
// tool schema advertised by name; an injected agent could `read` the file
|
|
19
|
+
// and forge provenance in two calls.
|
|
18
20
|
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
21
|
+
// Fallback: a bridge NOT spawned by this plugin (an unsupervised systemd unit)
|
|
22
|
+
// has no stdin channel, so no secret is issued and the plugin accepts the rc_
|
|
23
|
+
// connection token exactly as before — with a one-time warning that the box
|
|
24
|
+
// is on the weaker scheme. Supervised is the default on every npx / ClawHub
|
|
25
|
+
// install (the bridge ships inside the plugin package).
|
|
26
|
+
//
|
|
27
|
+
// Fail direction: OPEN only when the box has no connection token configured
|
|
28
|
+
// AT ALL (a pure-local dev box has no dashboard to inject provenance);
|
|
29
|
+
// CLOSED on a missing/mismatched value, and CLOSED when the config cannot be
|
|
30
|
+
// read (a corrupt or garbled plugin-config.json used to fail OPEN — the one
|
|
31
|
+
// file the agent could scribble on to disarm the gate).
|
|
23
32
|
// Read per call (no restart needed after a token rotation — F10 philosophy).
|
|
24
|
-
|
|
33
|
+
//
|
|
34
|
+
// THREAT-MODEL HONESTY: the agent runs on the operator's own box as the same
|
|
35
|
+
// user as this plugin. The gate defends against one-call LLM impulsivity and
|
|
36
|
+
// against an agent READING a static proof (the realistic failure modes) — not
|
|
37
|
+
// against a deliberately adversarial agent, which owns the box: it could
|
|
38
|
+
// overwrite the bridge entrypoint the supervisor spawns and collect the secret
|
|
39
|
+
// on the next restart, or edit plugin-config.json directly. User-facing prose
|
|
40
|
+
// must therefore say the agent cannot supply provenance conversationally or
|
|
41
|
+
// read it back — never that the setting "cannot be changed by anyone".
|
|
42
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
25
43
|
import { readPluginConfig } from './plugin-config-io.js';
|
|
26
44
|
import { resolveIngestToken } from './user-data-stream-config.js';
|
|
45
|
+
import { processRuntime } from '../lifecycle/process-role.js';
|
|
46
|
+
import { logger } from '../logger.js';
|
|
47
|
+
const TAG = 'operator-provenance';
|
|
27
48
|
const REFUSAL = 'operator_only: this tool changes safety-critical operator settings and accepts requests ' +
|
|
28
|
-
'ONLY from the ReefClaw dashboard (operator provenance
|
|
29
|
-
'retry and do not attempt to obtain the
|
|
30
|
-
'makes it from the
|
|
49
|
+
'ONLY from the ReefClaw dashboard (operator provenance missing or invalid). Do not ' +
|
|
50
|
+
'retry and do not attempt to obtain the provenance secret — it exists only inside the ' +
|
|
51
|
+
'ReefClaw connector process. If this change is wanted, the OPERATOR makes it from the ' +
|
|
52
|
+
'dashboard Settings panel.';
|
|
53
|
+
/** The presented value is an rc_ connection token while a per-boot secret is
|
|
54
|
+
* issued: that is a CONNECTOR on the older scheme (pre-dates this plugin
|
|
55
|
+
* version, or was not started by it), not an agent — say so, and say what
|
|
56
|
+
* fixes it (review 2026-09-27 N3). */
|
|
57
|
+
const REFUSAL_STALE_CONNECTOR = 'operator_only: this request presented the rc_ connection token as provenance, but this plugin ' +
|
|
58
|
+
'issues a per-boot secret to the connector it supervises and accepts only that. The connector that ' +
|
|
59
|
+
'sent this is on the older scheme — it predates this plugin version or was not started by it. ' +
|
|
60
|
+
'OPERATOR: update the connector (dashboard → Update, or re-run the installer) and restart the ' +
|
|
61
|
+
'gateway so plugin and connector match. Agent: do not retry.';
|
|
62
|
+
const REFUSAL_CONFIG_UNREADABLE = 'operator_only: the plugin config could not be read, so operator provenance cannot be ' +
|
|
63
|
+
'verified — refusing (fail closed). The operator should check ~/.reefclaw/plugin-config.json.';
|
|
64
|
+
/** Mint (once per process) the per-boot secret the supervised bridge will
|
|
65
|
+
* present as `operator_token`. Idempotent: repeat calls return the same
|
|
66
|
+
* value so every module instance of this plugin agrees. */
|
|
67
|
+
export function issueOperatorSecret() {
|
|
68
|
+
const rec = processRuntime();
|
|
69
|
+
if (!rec.operatorSecret)
|
|
70
|
+
rec.operatorSecret = randomBytes(32).toString('hex');
|
|
71
|
+
return rec.operatorSecret;
|
|
72
|
+
}
|
|
73
|
+
/** The issued secret, or null when this process never spawned a bridge. */
|
|
74
|
+
export function currentOperatorSecret() {
|
|
75
|
+
return processRuntime().operatorSecret ?? null;
|
|
76
|
+
}
|
|
77
|
+
let warnedLegacyScheme = false;
|
|
78
|
+
function constantTimeEqual(given, expected) {
|
|
79
|
+
const a = Buffer.from(given, 'utf8');
|
|
80
|
+
const b = Buffer.from(expected, 'utf8');
|
|
81
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
82
|
+
}
|
|
31
83
|
export function verifyOperatorProvenance(provided, configPath) {
|
|
84
|
+
const given = typeof provided === 'string' ? provided.trim() : '';
|
|
85
|
+
// Strong scheme: the process minted a secret for the bridge it supervises.
|
|
86
|
+
// Nothing else — not even the rc_ connection token — is accepted then.
|
|
87
|
+
const secret = currentOperatorSecret();
|
|
88
|
+
if (secret) {
|
|
89
|
+
if (given.length > 0 && constantTimeEqual(given, secret))
|
|
90
|
+
return { ok: true };
|
|
91
|
+
return { ok: false, error: /^rc_/.test(given) ? REFUSAL_STALE_CONNECTOR : REFUSAL };
|
|
92
|
+
}
|
|
93
|
+
// Legacy scheme (unsupervised bridge): the rc_ connection token.
|
|
32
94
|
let expected;
|
|
33
95
|
try {
|
|
34
96
|
expected = resolveIngestToken(readPluginConfig(configPath))?.trim() || undefined;
|
|
35
97
|
}
|
|
36
98
|
catch {
|
|
37
|
-
|
|
99
|
+
return { ok: false, error: REFUSAL_CONFIG_UNREADABLE };
|
|
38
100
|
}
|
|
39
101
|
if (!expected)
|
|
40
102
|
return { ok: true }; // unconfigured box — nothing to prove against
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (
|
|
103
|
+
if (!warnedLegacyScheme) {
|
|
104
|
+
warnedLegacyScheme = true;
|
|
105
|
+
logger.warn(TAG, 'operator provenance is using the rc_ connection token (no supervised connector in this process). ' +
|
|
106
|
+
'A connector spawned by the plugin gets a per-boot secret instead — prefer that deployment shape.');
|
|
107
|
+
}
|
|
108
|
+
if (given.length === 0 || !constantTimeEqual(given, expected)) {
|
|
47
109
|
return { ok: false, error: REFUSAL };
|
|
48
110
|
}
|
|
49
111
|
return { ok: true };
|
|
50
112
|
}
|
|
113
|
+
/** Tool-result envelope for a refusal. Carries BOTH `error` (what every
|
|
114
|
+
* plugin tool returns and the agent reads) and `ok:false` + `message` (what
|
|
115
|
+
* the bridge's execute* wrappers pass through and the dashboard's
|
|
116
|
+
* TradingModeControl / ExchangeConnection render). Review 2026-09-27 B2: a
|
|
117
|
+
* bare `{error}` reached the dashboard as an EMPTY red box, so the stale-
|
|
118
|
+
* connector window this scheme creates was silent to the operator. */
|
|
119
|
+
export function provenanceRefusal(v) {
|
|
120
|
+
const text = v.error ?? REFUSAL;
|
|
121
|
+
return { ok: false, error: text, message: text };
|
|
122
|
+
}
|
|
123
|
+
/** Test-only: forget the issued secret and the one-time warning. */
|
|
124
|
+
export function resetOperatorProvenanceForTest() {
|
|
125
|
+
processRuntime().operatorSecret = null;
|
|
126
|
+
warnedLegacyScheme = false;
|
|
127
|
+
}
|
|
@@ -52,7 +52,11 @@ export type UserDataStreamDbWrite = 'off' | 'on';
|
|
|
52
52
|
* Both must be enabled together for WS rows to land in `trades`. */
|
|
53
53
|
export declare function getUserDataStreamDbWrite(config?: PluginConfigFile): UserDataStreamDbWrite;
|
|
54
54
|
export declare function loadUserDataStreamDbWrite(): UserDataStreamDbWrite;
|
|
55
|
-
/** Webapp ingest base URL (POST target). Defaults to production reefclaw.com.
|
|
55
|
+
/** Webapp ingest base URL (POST target). Defaults to production reefclaw.com.
|
|
56
|
+
* `https:` required for a public host; plain `http:` only to a private /
|
|
57
|
+
* loopback host (local dev, on-prem) — anything else falls back to the
|
|
58
|
+
* default with a warning, so the rc_ token never goes out in cleartext
|
|
59
|
+
* (audit 2026-09-27 H4). */
|
|
56
60
|
export declare function getUserDataStreamIngestBaseUrl(config?: PluginConfigFile): string;
|
|
57
61
|
/** Resolve the webapp-ingest credential (the per-user `rc_*` token).
|
|
58
62
|
*
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
// Reverse transitions to any earlier stage (including 'shadow' and 'off') are
|
|
22
22
|
// always permitted as a safety-net rollback.
|
|
23
23
|
import { readPluginConfig, readOpenClawConnection } from './plugin-config-io.js';
|
|
24
|
+
import { sanitizeBaseUrl } from './base-url.js';
|
|
24
25
|
const VALID = new Set(['off', 'shadow', 'observe', 'enforce']);
|
|
25
26
|
/** Allowed forward transitions. Reverse transitions are always permitted so
|
|
26
27
|
* the operator can fall back to REST if WS misbehaves.
|
|
@@ -118,12 +119,13 @@ export function loadUserDataStreamDbWrite() {
|
|
|
118
119
|
return 'off';
|
|
119
120
|
}
|
|
120
121
|
}
|
|
121
|
-
/** Webapp ingest base URL (POST target). Defaults to production reefclaw.com.
|
|
122
|
+
/** Webapp ingest base URL (POST target). Defaults to production reefclaw.com.
|
|
123
|
+
* `https:` required for a public host; plain `http:` only to a private /
|
|
124
|
+
* loopback host (local dev, on-prem) — anything else falls back to the
|
|
125
|
+
* default with a warning, so the rc_ token never goes out in cleartext
|
|
126
|
+
* (audit 2026-09-27 H4). */
|
|
122
127
|
export function getUserDataStreamIngestBaseUrl(config) {
|
|
123
|
-
|
|
124
|
-
if (typeof raw === 'string' && /^https?:\/\//.test(raw))
|
|
125
|
-
return raw;
|
|
126
|
-
return 'https://www.reefclaw.com';
|
|
128
|
+
return sanitizeBaseUrl(config?.userDataStream?.ingestBaseUrl, 'https://www.reefclaw.com', 'userDataStream.ingestBaseUrl');
|
|
127
129
|
}
|
|
128
130
|
/** Resolve the webapp-ingest credential (the per-user `rc_*` token).
|
|
129
131
|
*
|
|
@@ -20,7 +20,22 @@ export interface ConnectorSupervisorOptions {
|
|
|
20
20
|
bridgeDir?: string;
|
|
21
21
|
/** Injectable spawn for tests. */
|
|
22
22
|
spawnFn?: typeof spawn;
|
|
23
|
+
/** Per-boot operator-provenance secret (config/operator-provenance.ts).
|
|
24
|
+
* Delivered to the child over STDIN as one line, then stdin is closed —
|
|
25
|
+
* never argv, never the environment (both readable by the agent's `exec`
|
|
26
|
+
* as the same user). The env only carries a non-secret MARKER telling the
|
|
27
|
+
* bridge to read the line. Absent → nothing is written and the bridge
|
|
28
|
+
* falls back to the rc_ token scheme. */
|
|
29
|
+
operatorSecret?: string;
|
|
30
|
+
/** Lazy form of `operatorSecret`: called only once a bridge is actually
|
|
31
|
+
* found and about to be launched, so a box with no connector on disk never
|
|
32
|
+
* mints a secret that would (correctly) lock out the rc_ token fallback of
|
|
33
|
+
* a bridge run some other way. Takes precedence over `operatorSecret`. */
|
|
34
|
+
issueOperatorSecret?: () => string;
|
|
23
35
|
}
|
|
36
|
+
/** Env marker (value is not secret): the spawned bridge reads one line of
|
|
37
|
+
* stdin for the provenance secret when this is '1'. */
|
|
38
|
+
export declare const OPERATOR_SECRET_STDIN_MARKER = "REEFCLAW_OPERATOR_SECRET_STDIN";
|
|
24
39
|
export interface ConnectorSupervisorHandle {
|
|
25
40
|
stop(): void;
|
|
26
41
|
/** Test/debug introspection. */
|
package/connector-supervisor.js
CHANGED
|
@@ -51,6 +51,9 @@ const MIN_BACKOFF_MS = 5_000;
|
|
|
51
51
|
const MAX_BACKOFF_MS = 60_000;
|
|
52
52
|
/** A child that survives this long resets the backoff (it was healthy). */
|
|
53
53
|
const STABLE_RESET_MS = 5 * 60_000;
|
|
54
|
+
/** Env marker (value is not secret): the spawned bridge reads one line of
|
|
55
|
+
* stdin for the provenance secret when this is '1'. */
|
|
56
|
+
export const OPERATOR_SECRET_STDIN_MARKER = 'REEFCLAW_OPERATOR_SECRET_STDIN';
|
|
54
57
|
// Process-wide, not module-scoped: OpenClaw 2026.9.5+ can load the plugin as
|
|
55
58
|
// two module instances in one gateway, and a per-module singleton let each
|
|
56
59
|
// start its own connector — two bridges sharing one relay-instance-id, which
|
|
@@ -81,6 +84,8 @@ export function startConnectorSupervisor(opts = {}) {
|
|
|
81
84
|
return null;
|
|
82
85
|
}
|
|
83
86
|
const spawnFn = opts.spawnFn ?? spawn;
|
|
87
|
+
// A bridge WILL be launched from here on — only now mint the secret.
|
|
88
|
+
const operatorSecret = opts.issueOperatorSecret ? opts.issueOperatorSecret() : opts.operatorSecret;
|
|
84
89
|
let child = null;
|
|
85
90
|
let stopped = false;
|
|
86
91
|
let backoffMs = MIN_BACKOFF_MS;
|
|
@@ -91,11 +96,27 @@ export function startConnectorSupervisor(opts = {}) {
|
|
|
91
96
|
const startedAt = Date.now();
|
|
92
97
|
// NOT detached: the connector must die with the gateway (a gateway
|
|
93
98
|
// restart resurrects both, and an orphan bridge can never linger).
|
|
99
|
+
const withSecret = typeof operatorSecret === 'string' && operatorSecret.length > 0;
|
|
94
100
|
child = spawnFn(process.execPath, [indexJs, '--provider', 'gateway', '--log-level', 'info'], {
|
|
95
101
|
cwd: bridgeDir,
|
|
96
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
102
|
+
stdio: [withSecret ? 'pipe' : 'ignore', 'pipe', 'pipe'],
|
|
103
|
+
env: withSecret ? { ...process.env, [OPERATOR_SECRET_STDIN_MARKER]: '1' } : process.env,
|
|
97
104
|
});
|
|
98
105
|
logger.info(TAG, `connector started (pid ${child.pid})`);
|
|
106
|
+
if (withSecret) {
|
|
107
|
+
// One line, then EOF: the bridge's reader stops at the newline and the
|
|
108
|
+
// pipe never carries anything else. Errors here (EPIPE if the child
|
|
109
|
+
// died at once) are logged, not thrown — the restart loop handles it.
|
|
110
|
+
try {
|
|
111
|
+
child.stdin?.on('error', (err) => logger.warn(TAG, `connector stdin: ${err.message}`));
|
|
112
|
+
// One call: write + EOF together, so a throwing write can never leave
|
|
113
|
+
// the pipe open with the bridge blocked in readSync (review N6).
|
|
114
|
+
child.stdin?.end(`${operatorSecret}\n`);
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
logger.warn(TAG, `could not hand the provenance secret to the connector: ${err instanceof Error ? err.message : String(err)}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
99
120
|
const forward = (stream, level) => {
|
|
100
121
|
stream?.on('data', (chunk) => {
|
|
101
122
|
for (const line of chunk.toString().split('\n')) {
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
export interface HeadersLike {
|
|
2
|
+
get(name: string): string | null;
|
|
3
|
+
}
|
|
4
|
+
export interface EdgeDenyMatch {
|
|
5
|
+
/** `vercel_mitigated` = the `x-vercel-mitigated` header was present (the
|
|
6
|
+
* definitive signal); `plain_forbidden` = a text/plain "Forbidden" body
|
|
7
|
+
* without the header (older/other edge shapes — still not our app). */
|
|
8
|
+
kind: 'vercel_mitigated' | 'plain_forbidden';
|
|
9
|
+
/** The mitigation action the edge reported (`deny`, `challenge`, …). */
|
|
10
|
+
action: string | null;
|
|
11
|
+
/** `x-vercel-id` — the request id Vercel support can look up. */
|
|
12
|
+
requestId: string | null;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Decide whether a 403 came from the edge rather than the webapp. Pure.
|
|
16
|
+
*
|
|
17
|
+
* The webapp's own 403s (entitlement walls, verifyProAccess) are JSON with an
|
|
18
|
+
* `error` field; authInternalRequest answers 401 JSON. The Vercel edge answers
|
|
19
|
+
* `403` with `content-type: text/plain`, a body that starts with "Forbidden"
|
|
20
|
+
* and the `x-vercel-mitigated` header. Anything else → null (not an edge deny).
|
|
21
|
+
*/
|
|
22
|
+
export declare function classifyEdgeDeny(status: number, headers: HeadersLike | null | undefined, bodyText?: string | null): EdgeDenyMatch | null;
|
|
23
|
+
/** Kill-switch (repo convention: every new mechanism ships with one).
|
|
24
|
+
* `RC_WEBAPP_EDGE_GATE=off` disables the BRAKE only — no call is ever skipped
|
|
25
|
+
* or deferred — while detection, logging, the state file and the relay-borne
|
|
26
|
+
* health signal stay on. Read at call time; logged once. */
|
|
27
|
+
export declare function webappEdgeGateDisabled(): boolean;
|
|
28
|
+
export interface EdgeGateSnapshot {
|
|
29
|
+
blocked: boolean;
|
|
30
|
+
/** Epoch ms the gate reopens; null when open. */
|
|
31
|
+
blockedUntil: number | null;
|
|
32
|
+
/** First deny of the CURRENT episode (null once a success resets it). */
|
|
33
|
+
firstDeniedAt: number | null;
|
|
34
|
+
lastDeniedAt: number | null;
|
|
35
|
+
/** Denies in the current episode. */
|
|
36
|
+
deniedCount: number;
|
|
37
|
+
lastPath: string | null;
|
|
38
|
+
lastRequestId: string | null;
|
|
39
|
+
lastAction: string | null;
|
|
40
|
+
lastSuccessAt: number | null;
|
|
41
|
+
}
|
|
42
|
+
/** 5 → 10 → 20 → 30 min. The cap equals Vercel's persistent-action window: a
|
|
43
|
+
* host that stops knocking for a full window gives the block a chance to
|
|
44
|
+
* expire instead of feeding the pattern that armed it. */
|
|
45
|
+
export declare const DEFAULT_EDGE_BACKOFF_LADDER_MS: readonly number[];
|
|
46
|
+
export interface WebappEdgeGateOptions {
|
|
47
|
+
now?: () => number;
|
|
48
|
+
backoffLadderMs?: readonly number[];
|
|
49
|
+
/** Called on every state change (deny, success-after-deny). Used to persist
|
|
50
|
+
* the state file; errors inside are swallowed. */
|
|
51
|
+
onChange?: (snapshot: EdgeGateSnapshot) => void;
|
|
52
|
+
}
|
|
53
|
+
export declare class WebappEdgeGate {
|
|
54
|
+
private readonly now;
|
|
55
|
+
private readonly ladder;
|
|
56
|
+
private readonly onChange?;
|
|
57
|
+
private blockedUntil;
|
|
58
|
+
private firstDeniedAt;
|
|
59
|
+
private lastDeniedAt;
|
|
60
|
+
private deniedCount;
|
|
61
|
+
private step;
|
|
62
|
+
private lastPath;
|
|
63
|
+
private lastRequestId;
|
|
64
|
+
private lastAction;
|
|
65
|
+
private lastSuccessAt;
|
|
66
|
+
constructor(opts?: WebappEdgeGateOptions);
|
|
67
|
+
/** True while periodic webapp calls should be skipped. Always false under
|
|
68
|
+
* the kill-switch (the episode itself is still tracked). */
|
|
69
|
+
isBlocked(): boolean;
|
|
70
|
+
/** ms until the gate reopens (0 when open). */
|
|
71
|
+
msUntilOpen(): number;
|
|
72
|
+
/** Record an edge deny for `path`. Extends the block along the ladder and
|
|
73
|
+
* logs ONCE per episode at warn (every further deny is debug). */
|
|
74
|
+
noteDeny(rawPath: string, match: EdgeDenyMatch): void;
|
|
75
|
+
/** Record a successful webapp call. Ends the episode (logged once). */
|
|
76
|
+
noteSuccess(startedAt?: number): void;
|
|
77
|
+
snapshot(): EdgeGateSnapshot;
|
|
78
|
+
private emitChange;
|
|
79
|
+
}
|
|
80
|
+
/** The one sentence every client logs when the edge denies it — names the
|
|
81
|
+
* actual cause so nobody goes hunting for a token or subscription problem. */
|
|
82
|
+
export declare function edgeDenyMessage(match: EdgeDenyMatch, path: string, backoffMs: number): string;
|
|
83
|
+
export declare const WEBAPP_EDGE_STATE_FILENAME = "webapp-edge-state.json";
|
|
84
|
+
export declare function defaultWebappEdgeStatePath(): string;
|
|
85
|
+
export interface WebappEdgeStateFile extends EdgeGateSnapshot {
|
|
86
|
+
schemaVersion: 1;
|
|
87
|
+
updatedAt: number;
|
|
88
|
+
source: 'plugin';
|
|
89
|
+
}
|
|
90
|
+
/** Atomic write (tmp + rename, 0o600 — the plugin-config-io convention). Never
|
|
91
|
+
* throws: persistence is an observability aid, not a correctness requirement. */
|
|
92
|
+
export declare function writeWebappEdgeState(snapshot: EdgeGateSnapshot, path?: string): void;
|
|
93
|
+
/** The process-wide gate every webapp client consults. */
|
|
94
|
+
export declare function webappEdgeGate(): WebappEdgeGate;
|
|
95
|
+
/** Test-only: fresh gate, optional custom state path / clock. */
|
|
96
|
+
export declare function __resetWebappEdgeGateForTests(opts?: WebappEdgeGateOptions & {
|
|
97
|
+
statePath?: string;
|
|
98
|
+
}): WebappEdgeGate;
|
|
99
|
+
/**
|
|
100
|
+
* Inspect a webapp response on the shared gate. Success → episode over;
|
|
101
|
+
* 403 → classified (using `bodyText` when the caller already read it). Returns
|
|
102
|
+
* the match so the caller can word its own log line. Never throws.
|
|
103
|
+
*/
|
|
104
|
+
export declare function noteWebappResponse(res: {
|
|
105
|
+
ok: boolean;
|
|
106
|
+
status: number;
|
|
107
|
+
headers: HeadersLike;
|
|
108
|
+
}, path: string, bodyText?: string | null,
|
|
109
|
+
/** Epoch ms taken BEFORE the request was sent — lets the gate ignore a
|
|
110
|
+
* success that was already in flight when the ban started. */
|
|
111
|
+
startedAt?: number): EdgeDenyMatch | null;
|
|
112
|
+
/** Set once at boot from the shipped manifest (plugin-version.ts). */
|
|
113
|
+
export declare function setWebappClientVersion(version: string | null | undefined): void;
|
|
114
|
+
export declare function webappUserAgent(): string;
|
|
115
|
+
/** Bearer + User-Agent for a webapp call. `extra` wins on key collision. */
|
|
116
|
+
export declare function webappHeaders(token: string, extra?: Record<string, string>): Record<string, string>;
|