tacticremote 1.6.5 → 1.7.0
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/lib/authChallengeManager.js +1 -134
- package/lib/claudeSessionManager.js +1 -0
- package/lib/claudeTransport.js +1 -0
- package/lib/errorCodes.js +1 -127
- package/lib/execSafe.js +1 -218
- package/lib/fileService.js +1 -177
- package/lib/hookInstaller.js +21 -7
- package/lib/outputParser.js +1 -106
- package/lib/pushClient.js +1 -0
- package/lib/rateLimiter.js +1 -111
- package/lib/serverIdentity.js +1 -0
- package/lib/streamJsonParser.js +1 -0
- package/lib/tmuxManager.js +1 -671
- package/lib/uploadService.js +1 -366
- package/lib/validators.js +1 -350
- package/package.json +2 -1
- package/routes/httpHandler.js +3 -1
- package/routes/wsHandler.js +418 -364
- package/server.js +67 -152
- package/shared/server-core/authChallengeManager.js +108 -0
- package/shared/server-core/claudeSessionManager.js +222 -0
- package/shared/server-core/claudeTransport.js +176 -0
- package/shared/server-core/errorCodes.js +91 -0
- package/shared/server-core/execSafe.js +185 -0
- package/shared/server-core/fileService.js +155 -0
- package/shared/server-core/outputParser.js +174 -0
- package/shared/server-core/protocol-manifest.json +59 -0
- package/shared/server-core/protocol-manifest.schema.json +90 -0
- package/shared/server-core/protocolManifest.js +42 -0
- package/shared/server-core/pushClient.js +198 -0
- package/shared/server-core/rateLimiter.js +98 -0
- package/shared/server-core/serverConnectionLifecycle.js +118 -0
- package/shared/server-core/serverHandshake.js +72 -0
- package/shared/server-core/serverIdentity.js +102 -0
- package/shared/server-core/streamJsonParser.js +321 -0
- package/shared/server-core/tmuxManager.js +596 -0
- package/shared/server-core/unixProcessLifecycle.js +96 -0
- package/shared/server-core/unixServerHooks.js +148 -0
- package/shared/server-core/unixWsRuntime.js +412 -0
- package/shared/server-core/uploadService.js +321 -0
- package/shared/server-core/validators.js +274 -0
- package/shared/server-core/windowsServerHooks.js +174 -0
- package/shared/server-core/windowsWsRuntime.js +413 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Output parser for Claude Code terminal output
|
|
3
|
+
* Preserves ANSI codes for client-side rendering.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Parse and clean Claude Code output.
|
|
8
|
+
* @param {string} rawOutput - Raw terminal output with ANSI codes
|
|
9
|
+
* @param {Object} options - Parser options
|
|
10
|
+
* @param {boolean} options.preserveANSI - Whether to keep ANSI codes (default: true)
|
|
11
|
+
* @param {number} options.maxLines - Maximum lines to return (default: 5000)
|
|
12
|
+
* @returns {Object} Parsed output with display text
|
|
13
|
+
*/
|
|
14
|
+
function parseClaudeOutput(rawOutput, options = {}) {
|
|
15
|
+
const { preserveANSI = true, maxLines = 5000 } = options;
|
|
16
|
+
|
|
17
|
+
let cleaned = rawOutput;
|
|
18
|
+
|
|
19
|
+
cleaned = cleaned
|
|
20
|
+
.replace(/\x1b\].*?\x07/g, '')
|
|
21
|
+
.replace(/\x1b\[\?[0-9;]*[a-z]/g, '')
|
|
22
|
+
.replace(/\x1b\[[0-9;]*[ABCDEFGJKST]/g, '')
|
|
23
|
+
.replace(/\r/g, '');
|
|
24
|
+
|
|
25
|
+
if (!preserveANSI) {
|
|
26
|
+
cleaned = cleaned
|
|
27
|
+
.replace(/\x1b\[[0-9;]*m/g, '')
|
|
28
|
+
.replace(/[╭╮╰╯│─┬┴┼├┤┌┐└┘║═╔╗╚╝╠╣╦╩╬]/g, ' ');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
cleaned = cleaned.replace(/\n{4,}/g, '\n\n\n');
|
|
32
|
+
|
|
33
|
+
const lines = cleaned.split('\n');
|
|
34
|
+
const displayLines = lines.slice(-maxLines);
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
display: displayLines.join('\n'),
|
|
38
|
+
raw: rawOutput,
|
|
39
|
+
lineCount: displayLines.length,
|
|
40
|
+
hasANSI: /\x1b\[/.test(rawOutput)
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Strip terminal escape sequences so text-based matching is not fooled by
|
|
46
|
+
* color codes sitting between adjacent glyphs (Amp's "Esc[color] to cancel").
|
|
47
|
+
*/
|
|
48
|
+
function stripAnsi(s) {
|
|
49
|
+
return String(s)
|
|
50
|
+
.replace(/\x1b\].*?(?:\x07|\x1b\\)/g, '')
|
|
51
|
+
.replace(/\x1b\[[\d;?]*[a-zA-Z]/g, '')
|
|
52
|
+
.replace(/\x1b[>=]/g, '');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Agent-busy markers. If any appears in the tail, the agent is mid-turn and
|
|
57
|
+
* must not be treated as idle — even if the input box is still on-screen
|
|
58
|
+
* (Amp keeps its input box visible during a turn).
|
|
59
|
+
*/
|
|
60
|
+
const BUSY_MARKERS = [
|
|
61
|
+
/Esc to cancel/i, // Amp: "Waiting for response" / "Streaming response"
|
|
62
|
+
/esc to interrupt/i // Claude: "✻ Doing … (esc to interrupt)"
|
|
63
|
+
];
|
|
64
|
+
|
|
65
|
+
function hasBusyMarker(output) {
|
|
66
|
+
const tail = stripAnsi(output).split('\n').slice(-15).join('\n');
|
|
67
|
+
return BUSY_MARKERS.some((re) => re.test(tail));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Check if the agent is sitting at the idle input prompt.
|
|
72
|
+
* A visible idle box is necessary but not sufficient — busy markers win.
|
|
73
|
+
*/
|
|
74
|
+
function isWaitingForInput(output) {
|
|
75
|
+
if (hasBusyMarker(output)) return false;
|
|
76
|
+
return hasClaudeIdleUI(output);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Strict idle-UI detection — the TUI input box must be visible.
|
|
81
|
+
* Matches both Claude and Amp (both use ╭─/╰─ box and "? for shortcuts").
|
|
82
|
+
* ANSI codes are stripped first so color escapes between adjacent glyphs
|
|
83
|
+
* don't prevent matches like "? for shortcuts".
|
|
84
|
+
*/
|
|
85
|
+
function hasClaudeIdleUI(output) {
|
|
86
|
+
const lines = stripAnsi(output).split('\n').slice(-20).join('\n');
|
|
87
|
+
|
|
88
|
+
if (lines.includes('? for shortcuts')) return true;
|
|
89
|
+
if (lines.includes('╭─') && lines.includes('╰─')) return true;
|
|
90
|
+
|
|
91
|
+
let score = 0;
|
|
92
|
+
if (lines.includes('╭─')) score++;
|
|
93
|
+
if (lines.includes('╰─')) score++;
|
|
94
|
+
if (/│\s*>/.test(lines)) score++;
|
|
95
|
+
if (/claude/i.test(lines) && lines.includes('│')) score++;
|
|
96
|
+
|
|
97
|
+
return score >= 2;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Spinner glyphs used by various CLIs — braille dots, bullets, dashes, tildes.
|
|
102
|
+
* Normalized to '*' when comparing frames for stability so that a tick of the
|
|
103
|
+
* spinner does not look like new content.
|
|
104
|
+
*/
|
|
105
|
+
// All Unicode braille patterns (U+2800–U+28FF) + common CLI spinner glyphs.
|
|
106
|
+
const SPINNER_RE = /[\u2800-\u28FF●○◐◑◒◓◔◕≈≋✻✢✳✽]/g;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Signature of the terminal state used for "has the agent settled" polling.
|
|
110
|
+
*
|
|
111
|
+
* Returns a normalized string derived from the bottom `lineCount` visible
|
|
112
|
+
* lines, stripped of ANSI escape codes and with spinner glyphs collapsed to a
|
|
113
|
+
* placeholder. The goal: two polls should compare equal whenever the input
|
|
114
|
+
* box and status region are unchanged, even if a startup logo is animating
|
|
115
|
+
* higher up on the screen or a spinner is ticking in place.
|
|
116
|
+
*
|
|
117
|
+
* This is NOT meant for display or parsing — only for frame-to-frame equality.
|
|
118
|
+
*/
|
|
119
|
+
function stabilitySignature(output, lineCount = 12) {
|
|
120
|
+
if (typeof output !== 'string') return '';
|
|
121
|
+
const tail = output.split('\n').slice(-lineCount).join('\n');
|
|
122
|
+
return stripAnsi(tail)
|
|
123
|
+
.replace(/[\r\b]/g, '') // CR / backspace
|
|
124
|
+
.replace(SPINNER_RE, '*'); // spinner → placeholder
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Permissive "is Claude alive" check. Accepts the '●' spinner too, so that
|
|
129
|
+
* attachSession / session-list reconnect doesn't wrongly report a busy Claude
|
|
130
|
+
* as stopped just because the idle box is scrolled off-screen.
|
|
131
|
+
*/
|
|
132
|
+
function hasClaudeUI(output) {
|
|
133
|
+
if (hasClaudeIdleUI(output)) return true;
|
|
134
|
+
const lines = output.split('\n').slice(-20).join('\n');
|
|
135
|
+
if (lines.includes('●')) return true;
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Check if Claude is currently running.
|
|
141
|
+
* @param {string} output - Terminal output to check
|
|
142
|
+
* @returns {boolean} Whether Claude is running
|
|
143
|
+
*/
|
|
144
|
+
function isClaudeRunning(output) {
|
|
145
|
+
if (output.includes('Goodbye!') || output.includes('Session ended')) {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const lastLines = output.split('\n').slice(-10).join('\n');
|
|
150
|
+
if (lastLines.includes('error: An unknown error occurred')) {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const shellTail = output.split('\n').slice(-5).join('\n');
|
|
155
|
+
if (shellTail.match(/\$\s*$/) && !shellTail.includes('Claude')) {
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
if (shellTail.match(/^[A-Z]:\\[^]*>\s*$/m) && !shellTail.includes('Claude')) {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
if (shellTail.match(/PS [A-Z]:\\[^]*>\s*$/m) && !shellTail.includes('Claude')) {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return hasClaudeUI(output);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
module.exports = {
|
|
169
|
+
parseClaudeOutput,
|
|
170
|
+
isWaitingForInput,
|
|
171
|
+
isClaudeRunning,
|
|
172
|
+
hasBusyMarker,
|
|
173
|
+
stabilitySignature
|
|
174
|
+
};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "./protocol-manifest.schema.json",
|
|
3
|
+
"protocolVersion": 1,
|
|
4
|
+
"minimumSupportedClientProtocolVersion": 1,
|
|
5
|
+
"minimumSupportedServerProtocolVersion": 1,
|
|
6
|
+
"capabilities": {
|
|
7
|
+
"structured_json": {
|
|
8
|
+
"description": "Server can run Claude in stream-json mode via the `claude` CLI",
|
|
9
|
+
"runtimeCondition": "claude CLI detected at server startup",
|
|
10
|
+
"consumedBy": [
|
|
11
|
+
"iOS ServerConnection.swift `supportsStructuredMode`",
|
|
12
|
+
"start_claude_structured / send_structured / steer_structured / respond_approval methods"
|
|
13
|
+
]
|
|
14
|
+
},
|
|
15
|
+
"tmux": {
|
|
16
|
+
"description": "Server can run Claude in terminal mode via tmux",
|
|
17
|
+
"runtimeCondition": "tmux binary detected at server startup",
|
|
18
|
+
"consumedBy": [
|
|
19
|
+
"iOS terminal-mode UI",
|
|
20
|
+
"send_to_claude / start_claude / send_key / capture_pane methods"
|
|
21
|
+
]
|
|
22
|
+
},
|
|
23
|
+
"client_state": {
|
|
24
|
+
"description": "Server honors `client_state` messages and uses them for push notification routing decisions",
|
|
25
|
+
"runtimeCondition": "always (since v1.6.0)",
|
|
26
|
+
"consumedBy": [
|
|
27
|
+
"shared/server-core/unixServerHooks.js: selects new vs legacy push path based on ws.clientState.supportsClientState"
|
|
28
|
+
]
|
|
29
|
+
},
|
|
30
|
+
"register_push": {
|
|
31
|
+
"description": "Server can relay device registration to the APNs push service",
|
|
32
|
+
"runtimeCondition": "PUSH_SERVICE_URL env var set and serverIdentity provisioned",
|
|
33
|
+
"consumedBy": [
|
|
34
|
+
"iOS PushTokenManager: register_push method"
|
|
35
|
+
]
|
|
36
|
+
},
|
|
37
|
+
"worktree": {
|
|
38
|
+
"description": "Server exposes `list_worktrees` RPC and augments `git_info` responses with `worktree_path` / `is_worktree`",
|
|
39
|
+
"runtimeCondition": "git binary detected at runtime (same availability as git_info)",
|
|
40
|
+
"consumedBy": [
|
|
41
|
+
"iOS PathPickerView: show worktree selection sheet when picking a repo path",
|
|
42
|
+
"iOS ServerConnection.listWorktrees(at:)"
|
|
43
|
+
]
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"deprecations": [],
|
|
47
|
+
"history": [
|
|
48
|
+
{
|
|
49
|
+
"protocolVersion": 1,
|
|
50
|
+
"addedIn": "v1.6.7",
|
|
51
|
+
"note": "Initial manifest. Prior versions (v1.0–v1.6.6) did not advertise protocolVersion; treated as v0 on the client side with fallback to capability sniffing."
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"protocolVersion": 1,
|
|
55
|
+
"addedIn": "v1.6.8",
|
|
56
|
+
"note": "Added `worktree` capability and `list_worktrees` RPC; extended `git_info` with worktree_path / is_worktree fields. Backwards-compatible — old clients ignore the new fields."
|
|
57
|
+
}
|
|
58
|
+
]
|
|
59
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
|
+
"title": "Tactic Remote Protocol Manifest",
|
|
4
|
+
"description": "Single source of truth for WebSocket protocol compatibility between iOS/iPad clients and all server variants. See shared/server-core/protocol-manifest.json.",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"required": [
|
|
7
|
+
"protocolVersion",
|
|
8
|
+
"minimumSupportedClientProtocolVersion",
|
|
9
|
+
"minimumSupportedServerProtocolVersion",
|
|
10
|
+
"capabilities"
|
|
11
|
+
],
|
|
12
|
+
"properties": {
|
|
13
|
+
"$schema": { "type": "string" },
|
|
14
|
+
"protocolVersion": {
|
|
15
|
+
"type": "integer",
|
|
16
|
+
"minimum": 1,
|
|
17
|
+
"description": "Current wire protocol version. Bump ONLY on breaking changes (removed message type, renamed field, changed semantics). Additive changes do NOT bump."
|
|
18
|
+
},
|
|
19
|
+
"minimumSupportedClientProtocolVersion": {
|
|
20
|
+
"type": "integer",
|
|
21
|
+
"minimum": 1,
|
|
22
|
+
"description": "Servers reject client_hello with protocolVersion < this value. Rarely advanced; raising this is a breaking change for stale iOS users."
|
|
23
|
+
},
|
|
24
|
+
"minimumSupportedServerProtocolVersion": {
|
|
25
|
+
"type": "integer",
|
|
26
|
+
"minimum": 1,
|
|
27
|
+
"description": "Clients show a hard-fail banner if server.protocolVersion < this value. Used only for truly unsafe old servers."
|
|
28
|
+
},
|
|
29
|
+
"capabilities": {
|
|
30
|
+
"type": "object",
|
|
31
|
+
"description": "Named capabilities that servers may advertise in the `connected` handshake. iOS decides UI based on these, not on protocolVersion.",
|
|
32
|
+
"patternProperties": {
|
|
33
|
+
"^[a-z][a-z0-9_]*$": {
|
|
34
|
+
"type": "object",
|
|
35
|
+
"required": ["description"],
|
|
36
|
+
"properties": {
|
|
37
|
+
"description": { "type": "string" },
|
|
38
|
+
"runtimeCondition": {
|
|
39
|
+
"type": "string",
|
|
40
|
+
"description": "When at runtime this capability is advertised by a server. 'always' means unconditional."
|
|
41
|
+
},
|
|
42
|
+
"consumedBy": {
|
|
43
|
+
"type": "array",
|
|
44
|
+
"items": { "type": "string" },
|
|
45
|
+
"description": "Where this capability is read in the codebase. Useful for verifying a capability is not orphaned."
|
|
46
|
+
},
|
|
47
|
+
"deprecatedIn": {
|
|
48
|
+
"type": "integer",
|
|
49
|
+
"description": "If set, the protocolVersion in which this capability was deprecated. Still advertised, but clients should migrate."
|
|
50
|
+
},
|
|
51
|
+
"removedIn": {
|
|
52
|
+
"type": "integer",
|
|
53
|
+
"description": "If set, the protocolVersion in which this capability was removed. Must be > deprecatedIn."
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
"additionalProperties": false
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
"additionalProperties": false
|
|
60
|
+
},
|
|
61
|
+
"deprecations": {
|
|
62
|
+
"type": "array",
|
|
63
|
+
"description": "History of removed/renamed capabilities. Append-only.",
|
|
64
|
+
"items": {
|
|
65
|
+
"type": "object",
|
|
66
|
+
"required": ["capability", "removedInProtocolVersion"],
|
|
67
|
+
"properties": {
|
|
68
|
+
"capability": { "type": "string" },
|
|
69
|
+
"removedInProtocolVersion": { "type": "integer" },
|
|
70
|
+
"replacedBy": { "type": "string" },
|
|
71
|
+
"note": { "type": "string" }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
"history": {
|
|
76
|
+
"type": "array",
|
|
77
|
+
"description": "Human-readable changelog of protocol version bumps. Append-only.",
|
|
78
|
+
"items": {
|
|
79
|
+
"type": "object",
|
|
80
|
+
"required": ["protocolVersion", "addedIn"],
|
|
81
|
+
"properties": {
|
|
82
|
+
"protocolVersion": { "type": "integer" },
|
|
83
|
+
"addedIn": { "type": "string", "description": "App version (SemVer) in which this protocol version shipped" },
|
|
84
|
+
"note": { "type": "string" }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"additionalProperties": false
|
|
90
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loader for the protocol manifest — the single source of truth for
|
|
3
|
+
* WebSocket wire-level compatibility between iOS clients and all server
|
|
4
|
+
* variants.
|
|
5
|
+
*
|
|
6
|
+
* Servers import this to learn:
|
|
7
|
+
* - PROTOCOL_VERSION: current wire version, included in handshake
|
|
8
|
+
* - MINIMUM_SUPPORTED_CLIENT_PROTOCOL_VERSION: reject older clients
|
|
9
|
+
* - KNOWN_CAPABILITIES: list of capability names the manifest declares
|
|
10
|
+
*
|
|
11
|
+
* The manifest JSON travels with `shared/server-core/` into every shipping
|
|
12
|
+
* unit via `iOS/scripts/sync-server-bundle.sh`, so every server (MacServer,
|
|
13
|
+
* LinuxServer, Windows, iOS ServerBundle, tactic-remote-server npm) reads
|
|
14
|
+
* the same values.
|
|
15
|
+
*
|
|
16
|
+
* @see shared/server-core/protocol-manifest.json
|
|
17
|
+
* @see shared/server-core/protocol-manifest.schema.json
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const manifest = require('./protocol-manifest.json');
|
|
21
|
+
|
|
22
|
+
const PROTOCOL_VERSION = manifest.protocolVersion;
|
|
23
|
+
const MINIMUM_SUPPORTED_CLIENT_PROTOCOL_VERSION =
|
|
24
|
+
manifest.minimumSupportedClientProtocolVersion;
|
|
25
|
+
const MINIMUM_SUPPORTED_SERVER_PROTOCOL_VERSION =
|
|
26
|
+
manifest.minimumSupportedServerProtocolVersion;
|
|
27
|
+
|
|
28
|
+
const KNOWN_CAPABILITIES = Object.freeze(Object.keys(manifest.capabilities));
|
|
29
|
+
|
|
30
|
+
function isKnownCapability(name) {
|
|
31
|
+
return Object.prototype.hasOwnProperty.call(manifest.capabilities, name);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
module.exports = {
|
|
35
|
+
PROTOCOL_VERSION,
|
|
36
|
+
MINIMUM_SUPPORTED_CLIENT_PROTOCOL_VERSION,
|
|
37
|
+
MINIMUM_SUPPORTED_SERVER_PROTOCOL_VERSION,
|
|
38
|
+
KNOWN_CAPABILITIES,
|
|
39
|
+
isKnownCapability,
|
|
40
|
+
// Expose the raw manifest for tests / tooling that need the full shape.
|
|
41
|
+
_manifest: Object.freeze(manifest)
|
|
42
|
+
};
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Push notification client for the cloud push service.
|
|
3
|
+
* Makes HTTP requests to the cloud push service to register devices
|
|
4
|
+
* and send push notifications.
|
|
5
|
+
*
|
|
6
|
+
* All network errors are caught and logged — never crashes the server.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const http = require('http');
|
|
10
|
+
const https = require('https');
|
|
11
|
+
|
|
12
|
+
let pushServiceUrl = null;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Configure the push client with the cloud push service URL.
|
|
16
|
+
* @param {string} url - The base URL of the push service (e.g. https://push.example.com)
|
|
17
|
+
*/
|
|
18
|
+
function configure(url) {
|
|
19
|
+
if (!url || typeof url !== 'string') {
|
|
20
|
+
pushServiceUrl = null;
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
// Remove trailing slash
|
|
24
|
+
pushServiceUrl = url.replace(/\/+$/, '');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Check if push client is configured and ready to make requests.
|
|
29
|
+
* @returns {boolean}
|
|
30
|
+
*/
|
|
31
|
+
function isConfigured() {
|
|
32
|
+
return pushServiceUrl !== null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Make a single HTTP POST attempt to the push service.
|
|
37
|
+
*/
|
|
38
|
+
function postRequestOnce(path, body) {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
if (!pushServiceUrl) {
|
|
41
|
+
resolve({ ok: false, error: 'Push client not configured', retryable: false });
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
const fullUrl = new URL(path, pushServiceUrl);
|
|
47
|
+
const isHttps = fullUrl.protocol === 'https:';
|
|
48
|
+
const transport = isHttps ? https : http;
|
|
49
|
+
const payload = JSON.stringify(body);
|
|
50
|
+
|
|
51
|
+
const options = {
|
|
52
|
+
hostname: fullUrl.hostname,
|
|
53
|
+
port: fullUrl.port || (isHttps ? 443 : 80),
|
|
54
|
+
path: fullUrl.pathname,
|
|
55
|
+
method: 'POST',
|
|
56
|
+
headers: {
|
|
57
|
+
'Content-Type': 'application/json',
|
|
58
|
+
'Content-Length': Buffer.byteLength(payload)
|
|
59
|
+
},
|
|
60
|
+
timeout: 10000
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const req = transport.request(options, (res) => {
|
|
64
|
+
const chunks = [];
|
|
65
|
+
res.on('data', (chunk) => chunks.push(chunk));
|
|
66
|
+
res.on('end', () => {
|
|
67
|
+
try {
|
|
68
|
+
const responseBody = Buffer.concat(chunks).toString('utf8');
|
|
69
|
+
const data = JSON.parse(responseBody);
|
|
70
|
+
resolve({ ok: res.statusCode >= 200 && res.statusCode < 300, status: res.statusCode, data, retryable: false });
|
|
71
|
+
} catch (_err) {
|
|
72
|
+
resolve({ ok: false, status: res.statusCode, error: 'Invalid JSON response', retryable: false });
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
req.on('error', (err) => {
|
|
78
|
+
resolve({ ok: false, error: err.message, retryable: true });
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
req.on('timeout', () => {
|
|
82
|
+
req.destroy();
|
|
83
|
+
resolve({ ok: false, error: 'Request timed out', retryable: true });
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
req.write(payload);
|
|
87
|
+
req.end();
|
|
88
|
+
} catch (err) {
|
|
89
|
+
resolve({ ok: false, error: err.message, retryable: false });
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Make an HTTP POST request to the push service with retry on network errors.
|
|
96
|
+
* @param {string} path - URL path (e.g. /v1/push/register-device)
|
|
97
|
+
* @param {Object} body - JSON body
|
|
98
|
+
* @returns {Promise<{ok: boolean, status?: number, data?: Object, error?: string}>}
|
|
99
|
+
*/
|
|
100
|
+
async function postRequest(path, body) {
|
|
101
|
+
const maxAttempts = 3;
|
|
102
|
+
const backoffMs = [500, 1500];
|
|
103
|
+
let lastResult = null;
|
|
104
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
105
|
+
const result = await postRequestOnce(path, body);
|
|
106
|
+
lastResult = result;
|
|
107
|
+
if (result.ok || !result.retryable) {
|
|
108
|
+
if (attempt > 1) {
|
|
109
|
+
console.log(`[push] ${path} succeeded on attempt ${attempt}`);
|
|
110
|
+
}
|
|
111
|
+
return result;
|
|
112
|
+
}
|
|
113
|
+
if (attempt < maxAttempts) {
|
|
114
|
+
console.warn(`[push] ${path} attempt ${attempt} failed: ${result.error} — retrying in ${backoffMs[attempt - 1]}ms`);
|
|
115
|
+
await new Promise(r => setTimeout(r, backoffMs[attempt - 1]));
|
|
116
|
+
} else {
|
|
117
|
+
console.error(`[push] ${path} failed after ${maxAttempts} attempts: ${result.error}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return lastResult;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Register a device token with the push service.
|
|
125
|
+
* @param {string} serverId - Server identity UUID
|
|
126
|
+
* @param {string} serverSecret - Server secret (64 hex chars)
|
|
127
|
+
* @param {string} deviceToken - APNs device token
|
|
128
|
+
* @param {boolean} alertsEnabled - Whether push alerts are enabled
|
|
129
|
+
* @param {string} apnsEnvironment - "sandbox" or "production"
|
|
130
|
+
* @returns {Promise<{ok: boolean, error?: string}>}
|
|
131
|
+
*/
|
|
132
|
+
async function register(serverId, serverSecret, deviceToken, alertsEnabled, apnsEnvironment) {
|
|
133
|
+
const result = await postRequest('/v1/push/register-device', {
|
|
134
|
+
serverId,
|
|
135
|
+
serverSecret,
|
|
136
|
+
deviceToken,
|
|
137
|
+
alertsEnabled: alertsEnabled !== false,
|
|
138
|
+
apnsEnvironment: apnsEnvironment || 'production'
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
if (!result.ok) {
|
|
142
|
+
console.error(`[push] register failed: ${result.error || `HTTP ${result.status}`}`);
|
|
143
|
+
}
|
|
144
|
+
return result;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Notify the push service that a task has completed.
|
|
149
|
+
* @param {string} serverId - Server identity UUID
|
|
150
|
+
* @param {string} serverSecret - Server secret (64 hex chars)
|
|
151
|
+
* @param {string} title - Notification title
|
|
152
|
+
* @param {string} body - Notification body
|
|
153
|
+
* @param {string} project - Project name
|
|
154
|
+
* @param {string} event - Event type (Stop, Notification, Error)
|
|
155
|
+
* @param {string} [session] - tmux session name
|
|
156
|
+
* @returns {Promise<{ok: boolean, error?: string}>}
|
|
157
|
+
*/
|
|
158
|
+
async function notifyCompletion(serverId, serverSecret, title, body, project, event, session) {
|
|
159
|
+
const payload = { serverId, serverSecret, title, body, project, event };
|
|
160
|
+
if (session) payload.session = session;
|
|
161
|
+
const result = await postRequest('/v1/push/notify-completion', payload);
|
|
162
|
+
|
|
163
|
+
if (!result.ok) {
|
|
164
|
+
console.error(`[push] notifyCompletion failed: ${result.error || `HTTP ${result.status}`}`);
|
|
165
|
+
}
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Unregister a device token from the push service.
|
|
171
|
+
* @param {string} serverId - Server identity UUID
|
|
172
|
+
* @param {string} serverSecret - Server secret (64 hex chars)
|
|
173
|
+
* @param {string} deviceToken - APNs device token to unregister
|
|
174
|
+
* @returns {Promise<{ok: boolean, error?: string}>}
|
|
175
|
+
*/
|
|
176
|
+
async function unregister(serverId, serverSecret, deviceToken) {
|
|
177
|
+
const result = await postRequest('/v1/push/unregister-device', {
|
|
178
|
+
serverId,
|
|
179
|
+
serverSecret,
|
|
180
|
+
deviceToken
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
if (!result.ok) {
|
|
184
|
+
console.error(`[push] unregister failed: ${result.error || `HTTP ${result.status}`}`);
|
|
185
|
+
}
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
module.exports = {
|
|
190
|
+
configure,
|
|
191
|
+
isConfigured,
|
|
192
|
+
register,
|
|
193
|
+
notifyCompletion,
|
|
194
|
+
unregister,
|
|
195
|
+
// Exposed for testing
|
|
196
|
+
_postRequest: postRequest,
|
|
197
|
+
_getUrl: () => pushServiceUrl
|
|
198
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate limiter module
|
|
3
|
+
* Simple in-memory rate limiting for authentication attempts.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
class RateLimiter {
|
|
7
|
+
constructor(options = {}) {
|
|
8
|
+
this.windowMs = options.windowMs || 60 * 1000;
|
|
9
|
+
this.maxAttempts = options.maxAttempts || 30;
|
|
10
|
+
this.records = new Map();
|
|
11
|
+
this.cleanupInterval = null;
|
|
12
|
+
this.startCleanup();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
startCleanup() {
|
|
16
|
+
if (this.cleanupInterval) {
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const cleanupMs = Math.min(this.windowMs, 60 * 1000);
|
|
20
|
+
this.cleanupInterval = setInterval(() => {
|
|
21
|
+
this.cleanup();
|
|
22
|
+
}, cleanupMs);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
ensureRunning() {
|
|
26
|
+
this.startCleanup();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
isAllowed(ip) {
|
|
30
|
+
const now = Date.now();
|
|
31
|
+
const record = this.records.get(ip);
|
|
32
|
+
|
|
33
|
+
if (!record) {
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (now > record.resetTime) {
|
|
38
|
+
this.records.delete(ip);
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return record.count < this.maxAttempts;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
recordFailure(ip) {
|
|
46
|
+
const now = Date.now();
|
|
47
|
+
let record = this.records.get(ip);
|
|
48
|
+
|
|
49
|
+
if (!record || now > record.resetTime) {
|
|
50
|
+
record = {
|
|
51
|
+
count: 0,
|
|
52
|
+
resetTime: now + this.windowMs
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
record.count++;
|
|
57
|
+
this.records.set(ip, record);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
getRemainingAttempts(ip) {
|
|
61
|
+
const record = this.records.get(ip);
|
|
62
|
+
if (!record || Date.now() > record.resetTime) {
|
|
63
|
+
return this.maxAttempts;
|
|
64
|
+
}
|
|
65
|
+
return Math.max(0, this.maxAttempts - record.count);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
getResetTime(ip) {
|
|
69
|
+
const record = this.records.get(ip);
|
|
70
|
+
if (!record) {
|
|
71
|
+
return 0;
|
|
72
|
+
}
|
|
73
|
+
const remaining = record.resetTime - Date.now();
|
|
74
|
+
return remaining > 0 ? Math.ceil(remaining / 1000) : 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
cleanup() {
|
|
78
|
+
const now = Date.now();
|
|
79
|
+
for (const [ip, record] of this.records.entries()) {
|
|
80
|
+
if (now > record.resetTime) {
|
|
81
|
+
this.records.delete(ip);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
clear() {
|
|
87
|
+
this.records.clear();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
destroy() {
|
|
91
|
+
if (this.cleanupInterval) {
|
|
92
|
+
clearInterval(this.cleanupInterval);
|
|
93
|
+
this.cleanupInterval = null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
module.exports = { RateLimiter };
|