instar 1.2.33 → 1.2.35

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,201 @@
1
+ /**
2
+ * CloudflareQuickProvider — Tier-1 zero-config Cloudflare quick tunnel.
3
+ *
4
+ * Extracted from the original `TunnelManager.startQuickTunnel()` so the
5
+ * manager can drive multiple providers through the common
6
+ * `TunnelProvider` interface. Behavior preserved verbatim where it
7
+ * doesn't conflict with the spec's single-owner mandate:
8
+ *
9
+ * - Owns: spawning `cloudflared` with --config-isolation; resolving
10
+ * when the quick-tunnel URL emits; tearing down on stop().
11
+ * - Does NOT own: retry/backoff, reconnect-on-disconnect, failure
12
+ * notification, episode/consent state. Those are the manager's
13
+ * responsibility now (per
14
+ * specs/dev-infrastructure/tunnel-failure-resilience.md Part 1's
15
+ * "single-owner mandate" that retires the old in-provider reconnect
16
+ * loop).
17
+ *
18
+ * Failure-mode classification is surfaced via the rejection Error's
19
+ * `message`; the manager parses to `ProviderFailureReason`. This module
20
+ * uses fixed substrings the manager recognizes:
21
+ * - "rate-limited" (Cloudflare 429 / 1015 detected from cloudflared stderr)
22
+ * - "binary-missing" (the bundled cloudflared binary path doesn't exist)
23
+ * - "timeout" (URL didn't emit within the start budget)
24
+ * - "process-exit code N" (child exited before URL emit)
25
+ */
26
+ import fs from 'node:fs';
27
+ import path from 'node:path';
28
+ import { bin, install, Tunnel } from 'cloudflared';
29
+ export class CloudflareQuickProvider {
30
+ name = 'cloudflare-quick';
31
+ tier = 1;
32
+ port;
33
+ stateDir;
34
+ startTimeoutMs;
35
+ constructor(opts) {
36
+ this.port = opts.port;
37
+ this.stateDir = opts.stateDir;
38
+ this.startTimeoutMs = opts.startTimeoutMs ?? 30_000;
39
+ }
40
+ async isAvailable() {
41
+ // The cloudflared npm package installs the binary on-demand via
42
+ // install(bin). availability == we can install or already have it.
43
+ // We don't actually do the install here; we just confirm the path
44
+ // is resolvable. Install happens during start().
45
+ return typeof bin === 'string' && bin.length > 0;
46
+ }
47
+ start(localPort) {
48
+ // localPort overrides constructor-time port for flexibility, but we
49
+ // default to the constructor value.
50
+ const port = localPort || this.port;
51
+ return new Promise((resolve, reject) => {
52
+ void this.startInner(port, resolve, reject);
53
+ });
54
+ }
55
+ async startInner(port, resolve, reject) {
56
+ try {
57
+ if (!fs.existsSync(bin)) {
58
+ try {
59
+ await install(bin);
60
+ }
61
+ catch (installErr) {
62
+ reject(new Error(`binary-missing: cloudflared install failed: ${installErr.message}`));
63
+ return;
64
+ }
65
+ }
66
+ }
67
+ catch {
68
+ reject(new Error('binary-missing: cloudflared binary path unresolvable'));
69
+ return;
70
+ }
71
+ const localUrl = `http://127.0.0.1:${port}`;
72
+ let tunnel;
73
+ try {
74
+ // Empty config to prevent cloudflared from reading
75
+ // ~/.cloudflared/config.yml, whose named-tunnel ingress rules
76
+ // would override the quick-tunnel's --url proxy. Preserved from
77
+ // the original implementation.
78
+ const emptyConfig = path.join(this.stateDir, 'cloudflared-quick.yml');
79
+ const dir = path.dirname(emptyConfig);
80
+ if (!fs.existsSync(dir)) {
81
+ fs.mkdirSync(dir, { recursive: true });
82
+ }
83
+ fs.writeFileSync(emptyConfig, '# Quick tunnel — no ingress rules\n');
84
+ tunnel = Tunnel.quick(localUrl, { '--config': emptyConfig });
85
+ }
86
+ catch (err) {
87
+ reject(new Error(`process-exit: failed to spawn cloudflared: ${err.message}`));
88
+ return;
89
+ }
90
+ let resolved = false;
91
+ let urlEmitted = null;
92
+ let stderrTail = '';
93
+ const timeout = setTimeout(() => {
94
+ if (!resolved) {
95
+ resolved = true;
96
+ try {
97
+ tunnel.stop();
98
+ }
99
+ catch { /* may already be dead */ }
100
+ reject(new Error('timeout: cloudflared quick tunnel did not emit a URL within the start budget'));
101
+ }
102
+ }, this.startTimeoutMs);
103
+ tunnel.once('url', (url) => {
104
+ if (resolved)
105
+ return;
106
+ resolved = true;
107
+ clearTimeout(timeout);
108
+ urlEmitted = url;
109
+ resolve({
110
+ url,
111
+ stop: () => this.stopHandle(tunnel),
112
+ });
113
+ });
114
+ tunnel.on('error', (err) => {
115
+ // Capture stderr-ish context. The cloudflared npm wrapper emits
116
+ // 'error' for child exit failures; we use the message as is.
117
+ stderrTail = (stderrTail + ' ' + (err?.message ?? '')).slice(-500);
118
+ if (!resolved) {
119
+ resolved = true;
120
+ clearTimeout(timeout);
121
+ reject(this.classifyError(err?.message ?? '', stderrTail));
122
+ }
123
+ // After resolution, we do NOT auto-reconnect. The manager owns
124
+ // disconnect handling per the single-owner mandate.
125
+ });
126
+ tunnel.on('exit', (code) => {
127
+ if (!resolved) {
128
+ resolved = true;
129
+ clearTimeout(timeout);
130
+ const msg = code === 0
131
+ ? 'process-exit: cloudflared exited cleanly before URL emission'
132
+ : `process-exit code ${code}: ${stderrTail || 'no stderr captured'}`;
133
+ reject(this.classifyError(msg, stderrTail));
134
+ }
135
+ // Post-resolution exits are surfaced to the manager via the
136
+ // handle's lifecycle. (The handle itself doesn't reconnect.)
137
+ });
138
+ // urlEmitted is referenced only inside the closure above; this
139
+ // suppresses an unused-variable lint while documenting intent.
140
+ void urlEmitted;
141
+ }
142
+ classifyError(msg, stderr) {
143
+ const haystack = `${msg} ${stderr}`.toLowerCase();
144
+ // Cloudflare's quick-tunnel rate-limit surfaces as 429 / error 1015.
145
+ // Both substrings appear in cloudflared's stderr on rate-limit.
146
+ if (haystack.includes('429') || haystack.includes('1015') || haystack.includes('rate limit') || haystack.includes('too many requests')) {
147
+ return new Error(`rate-limited: cloudflared quick-tunnel rate-limited (${msg})`);
148
+ }
149
+ if (haystack.includes('enoent') || haystack.includes('not found') || haystack.includes('binary-missing')) {
150
+ return new Error(`binary-missing: ${msg}`);
151
+ }
152
+ if (haystack.includes('dns') || haystack.includes('eai_again') || haystack.includes('econnrefused') || haystack.includes('network')) {
153
+ return new Error(`network: ${msg}`);
154
+ }
155
+ // Preserve as-is so the manager's classifier sees the original prefix.
156
+ return new Error(msg);
157
+ }
158
+ async stopHandle(tunnel) {
159
+ // Force-stop with PID escalation, mirroring TunnelManager.forceStop's
160
+ // SIGINT → SIGKILL pattern. This is security-load-bearing per spec
161
+ // Part 5 (relay teardown must guarantee the child process dies).
162
+ const proc = tunnel.process;
163
+ const pid = proc?.pid;
164
+ try {
165
+ tunnel.stop();
166
+ }
167
+ catch { /* may already be dead */ }
168
+ if (!pid)
169
+ return;
170
+ // Poll for exit; escalate to SIGKILL after 5s.
171
+ const timeoutMs = 5_000;
172
+ const exited = await new Promise((resolve) => {
173
+ const timer = setTimeout(() => resolve(false), timeoutMs);
174
+ try {
175
+ process.kill(pid, 0);
176
+ }
177
+ catch {
178
+ clearTimeout(timer);
179
+ resolve(true);
180
+ return;
181
+ }
182
+ const poll = setInterval(() => {
183
+ try {
184
+ process.kill(pid, 0);
185
+ }
186
+ catch {
187
+ clearInterval(poll);
188
+ clearTimeout(timer);
189
+ resolve(true);
190
+ }
191
+ }, 200);
192
+ });
193
+ if (!exited) {
194
+ try {
195
+ process.kill(pid, 'SIGKILL');
196
+ }
197
+ catch { /* already dead */ }
198
+ }
199
+ }
200
+ }
201
+ //# sourceMappingURL=CloudflareQuickProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CloudflareQuickProvider.js","sourceRoot":"","sources":["../../src/tunnel/CloudflareQuickProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAiBnD,MAAM,OAAO,uBAAuB;IACzB,IAAI,GAAiB,kBAAkB,CAAC;IACxC,IAAI,GAAiB,CAAC,CAAC;IAEf,IAAI,CAAS;IACb,QAAQ,CAAS;IACjB,cAAc,CAAS;IAExC,YAAY,IAAoC;QAC9C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,I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AC,MAAM,CAAC,IAAI,EAAE,CAAC;QAAC,CAAC;QAAC,MAAM,CAAC,CAAC,yBAAyB,CAAC,CAAC;QAC1D,IAAI,CAAC,GAAG;YAAE,OAAO;QAEjB,+CAA+C;QAC/C,MAAM,SAAS,GAAG,KAAK,CAAC;QACxB,MAAM,MAAM,GAAG,MAAM,IAAI,OAAO,CAAU,CAAC,OAAO,EAAE,EAAE;YACpD,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,SAAS,CAAC,CAAC;YAC1D,IAAI,CAAC;gBACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;YACvB,CAAC;YAAC,MAAM,CAAC;gBACP,YAAY,CAAC,KAAK,CAAC,CAAC;gBACpB,OAAO,CAAC,IAAI,CAAC,CAAC;gBACd,OAAO;YACT,CAAC;YACD,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,EAAE;gBAC5B,IAAI,CAAC;oBACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;gBACvB,CAAC;gBAAC,MAAM,CAAC;oBACP,aAAa,CAAC,IAAI,CAAC,CAAC;oBACpB,YAAY,CAAC,KAAK,CAAC,CAAC;oBACpB,OAAO,CAAC,IAAI,CAAC,CAAC;gBAChB,CAAC;YACH,CAAC,EAAE,GAAG,CAAC,CAAC;QACV,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,IAAI,CAAC;gBAAC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;YAAC,CAAC;YAAC,MAAM,CAAC,CAAC,kBAAkB,CAAC,CAAC;QACpE,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,190 @@
1
+ /**
2
+ * TunnelLifecycle — single-owner state machine for the tunnel layer.
3
+ *
4
+ * Per spec specs/dev-infrastructure/tunnel-failure-resilience.md Part 2.
5
+ *
6
+ * This module owns the detect → attempt → fall-back → notify → self-heal
7
+ * lifecycle. The existing server.ts startup-retry ladder, background-
8
+ * retry ladder, and Lifeline failure message are retired in favor of
9
+ * routing all retry through here.
10
+ *
11
+ * Design properties:
12
+ * - Single-writer transitions: every state change goes through
13
+ * `transition(expectedFrom, to)`, a compare-and-swap that REJECTS
14
+ * any transition whose expectedFrom doesn't match the current
15
+ * state. This prevents the error+exit double-handler race that the
16
+ * concurrency reviewer surfaced.
17
+ * - Monotonic epoch: each guarded transition carries a `transition.id`
18
+ * for downstream notification dedup. Notifications are emitted ONLY
19
+ * from inside the guarded mutation, tagged with the epoch.
20
+ * - Episode model: each contiguous failure→recovery cycle is an
21
+ * `episode` with its own id and one-time consent nonce. All consent
22
+ * state binds to (episodeId, provider, ownerId, chatId, messageId,
23
+ * issuedAt).
24
+ *
25
+ * This module is provider-agnostic and notification-channel-agnostic.
26
+ * Providers are injected as a pool; the notifier is injected as a sink.
27
+ * Both responsibilities live OUTSIDE this module per the spec's
28
+ * separation of concerns.
29
+ */
30
+ import { EventEmitter } from 'node:events';
31
+ import type { ProviderFailureReason, ProviderName } from './TunnelProvider.js';
32
+ export type TunnelLifecycleState =
33
+ /** No tunnel running and not currently trying. */
34
+ 'idle'
35
+ /** A start attempt is in flight on some provider. */
36
+ | 'starting'
37
+ /** A provider is up; URL is being served. */
38
+ | 'active'
39
+ /** A Tier-1 provider failed and we are backing off / trying the next one. */
40
+ | 'retrying'
41
+ /** All Tier-1 providers exhausted; awaiting owner consent for a Tier-2 relay. */
42
+ | 'awaiting-consent'
43
+ /** A Tier-2 relay provider is up; URL being served via the relay. */
44
+ | 'relay-active'
45
+ /** Cloudflare recovery probe verifying Tier-1 is back; switch-back imminent. */
46
+ | 'self-healing'
47
+ /** All providers exhausted (or consent declined); background self-heal is the only retry mechanism. */
48
+ | 'exhausted';
49
+ export interface Episode {
50
+ /** Stable per-failure-cycle id. Resets each time the manager enters `starting` from `idle`/`active`. */
51
+ episodeId: string;
52
+ /** When this episode began (ISO timestamp). */
53
+ startedAt: string;
54
+ /** Number of Tier-1 providers attempted in this episode. */
55
+ tier1Attempts: number;
56
+ /** Last classified failure reason (the most recent provider failure). */
57
+ lastFailureReason: ProviderFailureReason | null;
58
+ /** Which provider names have been attempted in this episode (in order). */
59
+ attemptedProviders: ProviderName[];
60
+ }
61
+ export interface ConsentRecord {
62
+ /** Tied to the episode that issued the prompt. */
63
+ episodeId: string;
64
+ /** Which Tier-2 provider the consent authorizes. Single-use, per-provider. */
65
+ provider: 'localtunnel' | 'bore';
66
+ /** Owner principal id (Telegram user id). Non-owner clicks are rejected. */
67
+ ownerId: string;
68
+ /** Telegram chat the consent was issued in (DM chat id). */
69
+ chatId: string;
70
+ /** Telegram message id of the inline-button prompt. */
71
+ messageId: string;
72
+ /** 128-bit CSPRNG nonce carried in callback_data. Atomic compare-and-delete on use. */
73
+ nonce: string;
74
+ /** Issued-at (ms epoch). Combined with consentTimeoutMs to expire. */
75
+ issuedAt: number;
76
+ }
77
+ export interface ConsentCooldownState {
78
+ /** Count of consecutive declines/timeouts feeding the exponential backoff. */
79
+ consecutiveRefusals: number;
80
+ /** When the cooldown was last extended (ms epoch). */
81
+ lastExtendedAt: number;
82
+ /** Until when the cooldown is active (ms epoch). 0 = no cooldown. */
83
+ activeUntil: number;
84
+ }
85
+ export interface PersistedTunnelState {
86
+ /** Schema version for safe future migrations. */
87
+ version: 1;
88
+ /** Last observed state. Used by the boot-recovery path. */
89
+ lastState: TunnelLifecycleState;
90
+ /** Last active URL (if any) — for diagnostic only; never trusted as live. */
91
+ lastUrl: string | null;
92
+ /** Name of the provider that was active when state was persisted. */
93
+ activeProvider: ProviderName | null;
94
+ /**
95
+ * Set to true the moment a Tier-2 relay-active state is entered. Cleared
96
+ * only after `authToken`/PIN rotation succeeds. If the agent crashes
97
+ * mid-relay-episode, this flag tells the boot-recovery path "rotate
98
+ * BEFORE accepting any API traffic on the new boot" — per spec Part 6.
99
+ */
100
+ rotationPending: boolean;
101
+ /** Cross-episode consent cooldown counter. */
102
+ consentCooldown: ConsentCooldownState;
103
+ /** Current episode, if any. */
104
+ episode: Episode | null;
105
+ /** Saved-at timestamp (ISO). */
106
+ savedAt: string;
107
+ }
108
+ export interface TransitionEvent {
109
+ /** Monotonic per-manager-instance epoch — never reset. Used by notifiers for dedup. */
110
+ epoch: number;
111
+ /** State BEFORE this transition. */
112
+ from: TunnelLifecycleState;
113
+ /** State AFTER this transition. */
114
+ to: TunnelLifecycleState;
115
+ /** Episode in effect at the time of the transition. */
116
+ episode: Episode | null;
117
+ /** Last classified failure (when relevant). */
118
+ lastFailureReason: ProviderFailureReason | null;
119
+ /** When (ms epoch). */
120
+ at: number;
121
+ }
122
+ export type TunnelLifecycleEvents = {
123
+ /** Fires on every successful guarded transition. */
124
+ transition: (e: TransitionEvent) => void;
125
+ };
126
+ /** Classify a provider failure based on the Error's `message`. */
127
+ export declare function classifyFailure(err: unknown): ProviderFailureReason;
128
+ /** Generate a fresh 128-bit CSPRNG nonce as hex (32 chars). */
129
+ export declare function generateNonce(): string;
130
+ /** Generate a fresh episode id (16-byte hex, no PII). */
131
+ export declare function generateEpisodeId(): string;
132
+ export declare function isValidTransition(from: TunnelLifecycleState, to: TunnelLifecycleState): boolean;
133
+ export declare class TunnelLifecycle extends EventEmitter {
134
+ private _state;
135
+ private _epoch;
136
+ private _episode;
137
+ private _lastFailureReason;
138
+ private _activeProvider;
139
+ private _consentCooldown;
140
+ private _rotationPending;
141
+ get state(): TunnelLifecycleState;
142
+ get epoch(): number;
143
+ get episode(): Episode | null;
144
+ get activeProvider(): ProviderName | null;
145
+ get rotationPending(): boolean;
146
+ get consentCooldown(): ConsentCooldownState;
147
+ get lastFailureReason(): ProviderFailureReason | null;
148
+ /**
149
+ * Compare-and-swap transition. Returns true if the transition was
150
+ * accepted; false if the current state didn't match `expectedFrom`
151
+ * (caller MUST treat false as a race — the lifecycle moved
152
+ * underneath them — and re-read state).
153
+ *
154
+ * `to` must be reachable from `expectedFrom` per VALID_TRANSITIONS;
155
+ * an invalid pair throws (programming error, not a runtime race).
156
+ */
157
+ transition(expectedFrom: TunnelLifecycleState, to: TunnelLifecycleState, ctx?: {
158
+ episode?: Episode | null;
159
+ activeProvider?: ProviderName | null;
160
+ lastFailureReason?: ProviderFailureReason | null;
161
+ rotationPending?: boolean;
162
+ }): boolean;
163
+ /** Begin a new failure-recovery episode. Called when entering `starting` from `idle` or `active`. */
164
+ startEpisode(): Episode;
165
+ /** Close out the current episode (called when returning to `active` or `idle`). */
166
+ endEpisode(): void;
167
+ /** Record a Tier-1 provider failure attempt against the current episode. */
168
+ recordAttempt(provider: ProviderName, reason: ProviderFailureReason): void;
169
+ /** Apply an exponential consent cooldown after a decline / timeout. */
170
+ recordConsentRefusal(): ConsentCooldownState;
171
+ /** Clear cooldown — called on explicit owner opt-in or fresh post-cooldown episode. */
172
+ clearConsentCooldown(): void;
173
+ /** True if the consent prompt is currently suppressed by the cooldown. */
174
+ isConsentSuppressed(now?: number): boolean;
175
+ /** Snapshot current state for persistence to tunnel.json. */
176
+ snapshot(): PersistedTunnelState;
177
+ /**
178
+ * Restore from a persisted snapshot. Called at boot ONLY for the
179
+ * cooldown counter + rotationPending flag — the state itself is NOT
180
+ * resumed (every boot starts at `idle` and re-enters `starting` from
181
+ * scratch). The rotationPending flag triggers a rotation-before-
182
+ * traffic in the boot-recovery path; rotation clears the flag.
183
+ */
184
+ restoreFrom(snapshot: PersistedTunnelState): void;
185
+ /** Set the rotation-pending flag (entered on `relay-active`; cleared after rotation). */
186
+ setRotationPending(value: boolean): void;
187
+ /** Used by callers (manager) that need to validate a consent-reply against the active state. */
188
+ isAwaitingConsent(): boolean;
189
+ }
190
+ //# sourceMappingURL=TunnelLifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TunnelLifecycle.d.ts","sourceRoot":"","sources":["../../src/tunnel/TunnelLifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;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yF;IACzF,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;IAIxC,gGAAgG;IAChG,iBAAiB,IAAI,OAAO;CAG7B"}
@@ -0,0 +1,222 @@
1
+ /**
2
+ * TunnelLifecycle — single-owner state machine for the tunnel layer.
3
+ *
4
+ * Per spec specs/dev-infrastructure/tunnel-failure-resilience.md Part 2.
5
+ *
6
+ * This module owns the detect → attempt → fall-back → notify → self-heal
7
+ * lifecycle. The existing server.ts startup-retry ladder, background-
8
+ * retry ladder, and Lifeline failure message are retired in favor of
9
+ * routing all retry through here.
10
+ *
11
+ * Design properties:
12
+ * - Single-writer transitions: every state change goes through
13
+ * `transition(expectedFrom, to)`, a compare-and-swap that REJECTS
14
+ * any transition whose expectedFrom doesn't match the current
15
+ * state. This prevents the error+exit double-handler race that the
16
+ * concurrency reviewer surfaced.
17
+ * - Monotonic epoch: each guarded transition carries a `transition.id`
18
+ * for downstream notification dedup. Notifications are emitted ONLY
19
+ * from inside the guarded mutation, tagged with the epoch.
20
+ * - Episode model: each contiguous failure→recovery cycle is an
21
+ * `episode` with its own id and one-time consent nonce. All consent
22
+ * state binds to (episodeId, provider, ownerId, chatId, messageId,
23
+ * issuedAt).
24
+ *
25
+ * This module is provider-agnostic and notification-channel-agnostic.
26
+ * Providers are injected as a pool; the notifier is injected as a sink.
27
+ * Both responsibilities live OUTSIDE this module per the spec's
28
+ * separation of concerns.
29
+ */
30
+ import crypto from 'node:crypto';
31
+ import { EventEmitter } from 'node:events';
32
+ // ── Helpers ──────────────────────────────────────────────────────────
33
+ /** Classify a provider failure based on the Error's `message`. */
34
+ export function classifyFailure(err) {
35
+ const msg = (err instanceof Error ? err.message : String(err ?? '')).toLowerCase();
36
+ if (msg.startsWith('rate-limited') || msg.includes('rate limit') || msg.includes('429') || msg.includes('1015')) {
37
+ return 'rate-limited';
38
+ }
39
+ if (msg.startsWith('binary-missing') || msg.includes('not installed') || msg.includes('enoent')) {
40
+ return 'binary-missing';
41
+ }
42
+ if (msg.startsWith('network') || msg.includes('dns') || msg.includes('econnrefused') || msg.includes('eai_again')) {
43
+ return 'network';
44
+ }
45
+ if (msg.startsWith('timeout') || msg.includes('timed out')) {
46
+ return 'timeout';
47
+ }
48
+ if (msg.startsWith('reachability-failed')) {
49
+ return 'reachability-failed';
50
+ }
51
+ if (msg.includes('process-exit') || msg.includes('exited')) {
52
+ return 'process-exit';
53
+ }
54
+ return 'unknown';
55
+ }
56
+ /** Generate a fresh 128-bit CSPRNG nonce as hex (32 chars). */
57
+ export function generateNonce() {
58
+ return crypto.randomBytes(16).toString('hex');
59
+ }
60
+ /** Generate a fresh episode id (16-byte hex, no PII). */
61
+ export function generateEpisodeId() {
62
+ return crypto.randomBytes(8).toString('hex');
63
+ }
64
+ // ── Single-writer state machine ─────────────────────────────────────
65
+ /** Valid transitions per the spec's state machine. */
66
+ const VALID_TRANSITIONS = new Map([
67
+ ['idle', new Set(['starting'])],
68
+ ['starting', new Set(['active', 'retrying', 'awaiting-consent', 'exhausted', 'idle'])],
69
+ ['active', new Set(['retrying', 'idle'])],
70
+ ['retrying', new Set(['active', 'starting', 'awaiting-consent', 'exhausted', 'idle'])],
71
+ ['awaiting-consent', new Set(['relay-active', 'starting', 'active', 'exhausted', 'idle'])],
72
+ ['relay-active', new Set(['self-healing', 'idle', 'exhausted'])],
73
+ ['self-healing', new Set(['active', 'relay-active', 'exhausted', 'idle'])],
74
+ ['exhausted', new Set(['self-healing', 'starting', 'idle'])],
75
+ ]);
76
+ export function isValidTransition(from, to) {
77
+ if (from === to)
78
+ return false;
79
+ const allowed = VALID_TRANSITIONS.get(from);
80
+ return !!allowed && allowed.has(to);
81
+ }
82
+ export class TunnelLifecycle extends EventEmitter {
83
+ _state = 'idle';
84
+ _epoch = 0;
85
+ _episode = null;
86
+ _lastFailureReason = null;
87
+ _activeProvider = null;
88
+ _consentCooldown = {
89
+ consecutiveRefusals: 0,
90
+ lastExtendedAt: 0,
91
+ activeUntil: 0,
92
+ };
93
+ _rotationPending = false;
94
+ get state() { return this._state; }
95
+ get epoch() { return this._epoch; }
96
+ get episode() { return this._episode; }
97
+ get activeProvider() { return this._activeProvider; }
98
+ get rotationPending() { return this._rotationPending; }
99
+ get consentCooldown() { return { ...this._consentCooldown }; }
100
+ get lastFailureReason() { return this._lastFailureReason; }
101
+ /**
102
+ * Compare-and-swap transition. Returns true if the transition was
103
+ * accepted; false if the current state didn't match `expectedFrom`
104
+ * (caller MUST treat false as a race — the lifecycle moved
105
+ * underneath them — and re-read state).
106
+ *
107
+ * `to` must be reachable from `expectedFrom` per VALID_TRANSITIONS;
108
+ * an invalid pair throws (programming error, not a runtime race).
109
+ */
110
+ transition(expectedFrom, to, ctx) {
111
+ if (this._state !== expectedFrom) {
112
+ return false; // CAS lost
113
+ }
114
+ if (!isValidTransition(expectedFrom, to)) {
115
+ throw new Error(`invalid transition ${expectedFrom} → ${to}`);
116
+ }
117
+ // Apply mutation atomically (Node is single-threaded; this synchronous
118
+ // block IS the critical section).
119
+ this._state = to;
120
+ this._epoch += 1;
121
+ if (ctx?.episode !== undefined)
122
+ this._episode = ctx.episode;
123
+ if (ctx?.activeProvider !== undefined)
124
+ this._activeProvider = ctx.activeProvider;
125
+ if (ctx?.lastFailureReason !== undefined)
126
+ this._lastFailureReason = ctx.lastFailureReason;
127
+ if (ctx?.rotationPending !== undefined)
128
+ this._rotationPending = ctx.rotationPending;
129
+ const event = {
130
+ epoch: this._epoch,
131
+ from: expectedFrom,
132
+ to,
133
+ episode: this._episode,
134
+ lastFailureReason: this._lastFailureReason,
135
+ at: Date.now(),
136
+ };
137
+ this.emit('transition', event);
138
+ return true;
139
+ }
140
+ /** Begin a new failure-recovery episode. Called when entering `starting` from `idle` or `active`. */
141
+ startEpisode() {
142
+ const ep = {
143
+ episodeId: generateEpisodeId(),
144
+ startedAt: new Date().toISOString(),
145
+ tier1Attempts: 0,
146
+ lastFailureReason: null,
147
+ attemptedProviders: [],
148
+ };
149
+ this._episode = ep;
150
+ return ep;
151
+ }
152
+ /** Close out the current episode (called when returning to `active` or `idle`). */
153
+ endEpisode() {
154
+ this._episode = null;
155
+ }
156
+ /** Record a Tier-1 provider failure attempt against the current episode. */
157
+ recordAttempt(provider, reason) {
158
+ if (!this._episode)
159
+ return;
160
+ this._episode.tier1Attempts += 1;
161
+ this._episode.lastFailureReason = reason;
162
+ this._episode.attemptedProviders.push(provider);
163
+ this._lastFailureReason = reason;
164
+ }
165
+ /** Apply an exponential consent cooldown after a decline / timeout. */
166
+ recordConsentRefusal() {
167
+ this._consentCooldown.consecutiveRefusals += 1;
168
+ const n = this._consentCooldown.consecutiveRefusals;
169
+ // 1h → 4h → 24h, then 24h forever
170
+ const COOLDOWNS_MS = [60 * 60_000, 4 * 60 * 60_000, 24 * 60 * 60_000];
171
+ const idx = Math.min(n - 1, COOLDOWNS_MS.length - 1);
172
+ const ms = COOLDOWNS_MS[idx] ?? COOLDOWNS_MS[COOLDOWNS_MS.length - 1];
173
+ if (ms === undefined)
174
+ throw new Error('unreachable: cooldown table empty');
175
+ this._consentCooldown.lastExtendedAt = Date.now();
176
+ this._consentCooldown.activeUntil = Date.now() + ms;
177
+ return this.consentCooldown;
178
+ }
179
+ /** Clear cooldown — called on explicit owner opt-in or fresh post-cooldown episode. */
180
+ clearConsentCooldown() {
181
+ this._consentCooldown = { consecutiveRefusals: 0, lastExtendedAt: 0, activeUntil: 0 };
182
+ }
183
+ /** True if the consent prompt is currently suppressed by the cooldown. */
184
+ isConsentSuppressed(now = Date.now()) {
185
+ return this._consentCooldown.activeUntil > now;
186
+ }
187
+ /** Snapshot current state for persistence to tunnel.json. */
188
+ snapshot() {
189
+ return {
190
+ version: 1,
191
+ lastState: this._state,
192
+ lastUrl: null, // populated by the manager that knows the URL
193
+ activeProvider: this._activeProvider,
194
+ rotationPending: this._rotationPending,
195
+ consentCooldown: this.consentCooldown,
196
+ episode: this._episode ? { ...this._episode, attemptedProviders: [...this._episode.attemptedProviders] } : null,
197
+ savedAt: new Date().toISOString(),
198
+ };
199
+ }
200
+ /**
201
+ * Restore from a persisted snapshot. Called at boot ONLY for the
202
+ * cooldown counter + rotationPending flag — the state itself is NOT
203
+ * resumed (every boot starts at `idle` and re-enters `starting` from
204
+ * scratch). The rotationPending flag triggers a rotation-before-
205
+ * traffic in the boot-recovery path; rotation clears the flag.
206
+ */
207
+ restoreFrom(snapshot) {
208
+ this._consentCooldown = { ...snapshot.consentCooldown };
209
+ this._rotationPending = snapshot.rotationPending;
210
+ // _state stays 'idle' by design — boot recovery rotation runs before
211
+ // the new lifecycle starts.
212
+ }
213
+ /** Set the rotation-pending flag (entered on `relay-active`; cleared after rotation). */
214
+ setRotationPending(value) {
215
+ this._rotationPending = value;
216
+ }
217
+ /** Used by callers (manager) that need to validate a consent-reply against the active state. */
218
+ isAwaitingConsent() {
219
+ return this._state === 'awaiting-consent';
220
+ }
221
+ }
222
+ //# sourceMappingURL=TunnelLifecycle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TunnelLifecycle.js","sourceRoot":"","sources":["../../src/tunnel/TunnelLifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA4G3C,wEAAwE;AAExE,kEAAkE;AAClE,MAAM,UAAU,eAAe,CAAC,GAAY;IAC1C,MAAM,GAAG,GAAG,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;IACnF,IAAI,GAAG,CAAC,UAAU,CAAC,cAAc,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAA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