@chroxy/server 0.10.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/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { existsSync, statSync, openSync, readSync, closeSync } from 'fs'
|
|
2
|
+
import { metrics } from './metrics.js'
|
|
3
|
+
import { getLogPath } from './logger.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Build a diagnostics snapshot of the server's runtime state (#3732).
|
|
7
|
+
*
|
|
8
|
+
* Designed for triaging stuck sessions: when a session hangs and the user
|
|
9
|
+
* sees "Response timed out after 5 minutes", `/diagnostics` lets the operator
|
|
10
|
+
* pull the live values that determined the outcome — `_isBusy`,
|
|
11
|
+
* `_resultTimeoutPaused`, the pending-permission queue with timestamps, and
|
|
12
|
+
* the tail of the on-disk log (#3731).
|
|
13
|
+
*
|
|
14
|
+
* Tool inputs are NOT echoed in the snapshot. Permission entries surface
|
|
15
|
+
* `tool` + `description` only — never the raw `input` object — so that
|
|
16
|
+
* triaging a stuck Bash prompt doesn't leak the command. The full input is
|
|
17
|
+
* already in the on-disk log (which is auth-gated like every other endpoint
|
|
18
|
+
* in this server).
|
|
19
|
+
*
|
|
20
|
+
* @param {object} args
|
|
21
|
+
* @param {object} args.server - WsServer instance for global state.
|
|
22
|
+
* @param {string} args.serverVersion - Static version string from package.json.
|
|
23
|
+
* @param {number} [args.logTailBytes=8192] - Max bytes to read from the tail
|
|
24
|
+
* of the log file. Hard ceiling so a wedged session doesn't have us slurp
|
|
25
|
+
* a 5MB rotated file into JSON.
|
|
26
|
+
* @returns {object}
|
|
27
|
+
*/
|
|
28
|
+
export function buildDiagnosticsSnapshot({ server, serverVersion, logTailBytes = 8192 } = {}) {
|
|
29
|
+
const now = Date.now()
|
|
30
|
+
const mem = process.memoryUsage()
|
|
31
|
+
|
|
32
|
+
const sessions = []
|
|
33
|
+
const sm = server?.sessionManager
|
|
34
|
+
if (sm?._sessions instanceof Map) {
|
|
35
|
+
for (const [id, entry] of sm._sessions) {
|
|
36
|
+
const session = entry?.session
|
|
37
|
+
if (!session) continue
|
|
38
|
+
sessions.push({
|
|
39
|
+
id,
|
|
40
|
+
name: entry.name ?? null,
|
|
41
|
+
provider: entry.provider ?? null,
|
|
42
|
+
cwd: entry.cwd ?? null,
|
|
43
|
+
isBusy: !!session._isBusy,
|
|
44
|
+
permissionMode: session.permissionMode ?? null,
|
|
45
|
+
currentMessageId: session._currentMessageId ?? null,
|
|
46
|
+
// Inactivity-timer pause bookkeeping from #2831 — this is the
|
|
47
|
+
// signal that tells you "is the 5-min RESULT_TIMEOUT armed right
|
|
48
|
+
// now or not?" If paused with no permissions, you've found a leak.
|
|
49
|
+
resultTimeoutPaused: !!session._resultTimeoutPaused,
|
|
50
|
+
permissionPauseCount: session._permissionPauseCount ?? 0,
|
|
51
|
+
pendingPermissions: collectPendingPermissions(session),
|
|
52
|
+
// Last activity timestamp written by SessionManager in restoreState
|
|
53
|
+
// / serializeState — reading it from the same source the persistence
|
|
54
|
+
// layer trusts, rather than a fresh derivation.
|
|
55
|
+
lastActivityAt: entry.lastActivityAt ?? null,
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
server: {
|
|
62
|
+
version: serverVersion,
|
|
63
|
+
mode: server?.serverMode ?? null,
|
|
64
|
+
uptime: Math.round((now - (server?._startedAt || now)) / 1000),
|
|
65
|
+
pid: process.pid,
|
|
66
|
+
nodeVersion: process.version,
|
|
67
|
+
memory: { rss: mem.rss, heapUsed: mem.heapUsed, heapTotal: mem.heapTotal },
|
|
68
|
+
},
|
|
69
|
+
clients: {
|
|
70
|
+
connected: server?._clientManager?.clients?.size ?? 0,
|
|
71
|
+
authenticated: server?._clientManager?.authenticatedCount ?? 0,
|
|
72
|
+
},
|
|
73
|
+
counters: metrics.snapshot ? metrics.snapshot() : {},
|
|
74
|
+
rateLimiters: collectRateLimiters(server),
|
|
75
|
+
sessions,
|
|
76
|
+
logs: collectLogTail(logTailBytes),
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Snapshot eviction stats for every RateLimiter the server holds (#3996, #4005).
|
|
82
|
+
*
|
|
83
|
+
* Returns an array (not a keyed object) so the surface is uniform regardless
|
|
84
|
+
* of which limiters happen to exist on a given server build — operators
|
|
85
|
+
* scanning for trouble look for any entry with `evictionCount > 0` (cumulative)
|
|
86
|
+
* or `evictionsInWindow > 0` (live signal). Each entry already carries `name`
|
|
87
|
+
* from the limiter constructor.
|
|
88
|
+
*
|
|
89
|
+
* Resilient to partial server objects (tests may pass mocks without every
|
|
90
|
+
* limiter wired up): a missing or malformed limiter is silently skipped.
|
|
91
|
+
*
|
|
92
|
+
* @param {object} server - WsServer instance.
|
|
93
|
+
* @returns {Array<{ name: string, evictionCount: number, lastEvictionAt: number|null, mapSize: number, maxEntries: number, evictionsInWindow: number, evictionWindowMs: number, evictionWindowSaturated: boolean }>}
|
|
94
|
+
*/
|
|
95
|
+
function collectRateLimiters(server) {
|
|
96
|
+
const out = []
|
|
97
|
+
const candidates = [
|
|
98
|
+
server?._rateLimiter,
|
|
99
|
+
server?._permissionRateLimiter,
|
|
100
|
+
server?._diagnosticsRateLimiter,
|
|
101
|
+
// The HTTP-permission limiter lives inside the permission handler
|
|
102
|
+
// closure and is re-exported on the handler object for this purpose.
|
|
103
|
+
server?._permissions?._httpPermissionLimiter,
|
|
104
|
+
]
|
|
105
|
+
for (const limiter of candidates) {
|
|
106
|
+
if (limiter && typeof limiter.getEvictionStats === 'function') {
|
|
107
|
+
try {
|
|
108
|
+
out.push(limiter.getEvictionStats())
|
|
109
|
+
} catch {
|
|
110
|
+
// Defensive — never let a misbehaving limiter crash /diagnostics.
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return out
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Collect pending permission requests for a session, with sensitive fields
|
|
119
|
+
* stripped. Returns the empty array when the session has no permission
|
|
120
|
+
* manager (CLI-mode sessions route via the HTTP hook path instead).
|
|
121
|
+
*/
|
|
122
|
+
function collectPendingPermissions(session) {
|
|
123
|
+
const out = []
|
|
124
|
+
const pendingMap = session?._pendingPermissions
|
|
125
|
+
if (!(pendingMap instanceof Map) || pendingMap.size === 0) return out
|
|
126
|
+
const lastData = session?._lastPermissionData
|
|
127
|
+
for (const [requestId] of pendingMap) {
|
|
128
|
+
const meta = (lastData instanceof Map) ? lastData.get(requestId) : null
|
|
129
|
+
out.push({
|
|
130
|
+
requestId,
|
|
131
|
+
tool: meta?.tool ?? null,
|
|
132
|
+
// Description only — `input` is intentionally omitted to avoid
|
|
133
|
+
// leaking command strings into the diagnostics surface. The full
|
|
134
|
+
// input lives in the on-disk log already.
|
|
135
|
+
description: typeof meta?.description === 'string'
|
|
136
|
+
? meta.description.slice(0, 200)
|
|
137
|
+
: null,
|
|
138
|
+
createdAt: meta?.createdAt ?? null,
|
|
139
|
+
ageMs: typeof meta?.createdAt === 'number'
|
|
140
|
+
? Math.max(0, Date.now() - meta.createdAt)
|
|
141
|
+
: null,
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
return out
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Read up to `maxBytes` from the tail of the on-disk log, if file logging
|
|
149
|
+
* is enabled. Returns metadata even when no log is configured so callers
|
|
150
|
+
* can tell the difference between "no logging" and "logging on, no content".
|
|
151
|
+
*/
|
|
152
|
+
function collectLogTail(maxBytes) {
|
|
153
|
+
const path = getLogPath()
|
|
154
|
+
if (!path) {
|
|
155
|
+
return { source: 'disabled', path: null, lines: [] }
|
|
156
|
+
}
|
|
157
|
+
if (!existsSync(path)) {
|
|
158
|
+
return { source: 'file', path, lines: [], note: 'log file not yet written' }
|
|
159
|
+
}
|
|
160
|
+
let fd
|
|
161
|
+
try {
|
|
162
|
+
const stats = statSync(path)
|
|
163
|
+
const start = Math.max(0, stats.size - maxBytes)
|
|
164
|
+
const length = stats.size - start
|
|
165
|
+
fd = openSync(path, 'r')
|
|
166
|
+
// #3734 review (Copilot): Buffer.alloc (zero-filled) + respect
|
|
167
|
+
// bytesRead. The earlier Buffer.allocUnsafe + ignoring readSync's
|
|
168
|
+
// return value would have disclosed uninitialized heap memory if
|
|
169
|
+
// the log file shrank between statSync and readSync — rare but
|
|
170
|
+
// possible during log rotation. Slicing on bytesRead also covers
|
|
171
|
+
// partial reads on slow filesystems.
|
|
172
|
+
const buf = Buffer.alloc(length)
|
|
173
|
+
const bytesRead = readSync(fd, buf, 0, length, start)
|
|
174
|
+
const text = buf.toString('utf8', 0, bytesRead)
|
|
175
|
+
// Drop the first line if we sliced into the middle of one — preserves
|
|
176
|
+
// the JSON-line guarantee in JSON-mode logs.
|
|
177
|
+
const lines = text.split('\n').filter(Boolean)
|
|
178
|
+
if (start > 0 && lines.length > 0) lines.shift()
|
|
179
|
+
return { source: 'file', path, lines }
|
|
180
|
+
} catch (err) {
|
|
181
|
+
return { source: 'file', path, lines: [], error: err?.message || String(err) }
|
|
182
|
+
} finally {
|
|
183
|
+
if (fd !== undefined) {
|
|
184
|
+
try { closeSync(fd) } catch {}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse unified diff output from `git diff` into structured data.
|
|
3
|
+
*
|
|
4
|
+
* Handles:
|
|
5
|
+
* - File headers (diff --git a/... b/...)
|
|
6
|
+
* - Hunk headers (@@ -start,count +start,count @@)
|
|
7
|
+
* - Context lines (space prefix), additions (+), deletions (-)
|
|
8
|
+
* - New files (status: 'added'), deleted files (status: 'deleted')
|
|
9
|
+
* - Renamed files (status: 'renamed')
|
|
10
|
+
* - Binary files (skipped with note)
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @typedef {Object} DiffLine
|
|
15
|
+
* @property {'context'|'addition'|'deletion'} type
|
|
16
|
+
* @property {string} content
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {Object} DiffHunk
|
|
21
|
+
* @property {string} header
|
|
22
|
+
* @property {DiffLine[]} lines
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @typedef {Object} DiffFile
|
|
27
|
+
* @property {string} path
|
|
28
|
+
* @property {'modified'|'added'|'deleted'|'renamed'|'untracked'} status
|
|
29
|
+
* @property {number} additions
|
|
30
|
+
* @property {number} deletions
|
|
31
|
+
* @property {DiffHunk[]} hunks
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Parse unified diff output into structured file data.
|
|
36
|
+
* @param {string} diffOutput - Raw output from `git diff`
|
|
37
|
+
* @returns {DiffFile[]}
|
|
38
|
+
*/
|
|
39
|
+
export function parseDiff(diffOutput) {
|
|
40
|
+
if (!diffOutput || typeof diffOutput !== 'string') return []
|
|
41
|
+
|
|
42
|
+
const lines = diffOutput.split('\n')
|
|
43
|
+
const files = []
|
|
44
|
+
let currentFile = null
|
|
45
|
+
let currentHunk = null
|
|
46
|
+
|
|
47
|
+
for (let i = 0; i < lines.length; i++) {
|
|
48
|
+
const line = lines[i]
|
|
49
|
+
|
|
50
|
+
// File header: diff --git a/path b/path
|
|
51
|
+
if (line.startsWith('diff --git ')) {
|
|
52
|
+
// Finalize previous file
|
|
53
|
+
if (currentFile) {
|
|
54
|
+
if (currentHunk) currentFile.hunks.push(currentHunk)
|
|
55
|
+
files.push(currentFile)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Extract path from "diff --git a/path b/path"
|
|
59
|
+
const match = line.match(/^diff --git a\/(.+) b\/(.+)$/)
|
|
60
|
+
const path = match ? match[2] : 'unknown'
|
|
61
|
+
|
|
62
|
+
currentFile = {
|
|
63
|
+
path,
|
|
64
|
+
status: 'modified',
|
|
65
|
+
additions: 0,
|
|
66
|
+
deletions: 0,
|
|
67
|
+
hunks: [],
|
|
68
|
+
}
|
|
69
|
+
currentHunk = null
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (!currentFile) continue
|
|
74
|
+
|
|
75
|
+
// Detect new file
|
|
76
|
+
if (line.startsWith('new file mode')) {
|
|
77
|
+
currentFile.status = 'added'
|
|
78
|
+
continue
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Detect deleted file
|
|
82
|
+
if (line.startsWith('deleted file mode')) {
|
|
83
|
+
currentFile.status = 'deleted'
|
|
84
|
+
continue
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Detect renamed file
|
|
88
|
+
if (line.startsWith('rename from ') || line.startsWith('rename to ')) {
|
|
89
|
+
currentFile.status = 'renamed'
|
|
90
|
+
continue
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Detect similarity index (rename marker)
|
|
94
|
+
if (line.startsWith('similarity index ')) {
|
|
95
|
+
currentFile.status = 'renamed'
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Binary file marker
|
|
100
|
+
if (line.startsWith('Binary files ')) {
|
|
101
|
+
currentFile.status = currentFile.status || 'modified'
|
|
102
|
+
// Add a note hunk for binary files
|
|
103
|
+
currentFile.hunks.push({
|
|
104
|
+
header: 'Binary file',
|
|
105
|
+
lines: [{ type: 'context', content: line }],
|
|
106
|
+
})
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Skip --- and +++ file markers
|
|
111
|
+
if (line.startsWith('--- ') || line.startsWith('+++ ')) {
|
|
112
|
+
// Detect /dev/null for added/deleted files
|
|
113
|
+
if (line === '--- /dev/null') {
|
|
114
|
+
currentFile.status = 'added'
|
|
115
|
+
} else if (line === '+++ /dev/null') {
|
|
116
|
+
currentFile.status = 'deleted'
|
|
117
|
+
}
|
|
118
|
+
continue
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Skip index lines (index abc..def 100644)
|
|
122
|
+
if (line.startsWith('index ')) continue
|
|
123
|
+
|
|
124
|
+
// Hunk header: @@ -start,count +start,count @@ optional context
|
|
125
|
+
if (line.startsWith('@@ ')) {
|
|
126
|
+
if (currentHunk) currentFile.hunks.push(currentHunk)
|
|
127
|
+
currentHunk = {
|
|
128
|
+
header: line,
|
|
129
|
+
lines: [],
|
|
130
|
+
}
|
|
131
|
+
continue
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (!currentHunk) continue
|
|
135
|
+
|
|
136
|
+
// Diff content lines
|
|
137
|
+
if (line.startsWith('+')) {
|
|
138
|
+
currentHunk.lines.push({ type: 'addition', content: line.slice(1) })
|
|
139
|
+
currentFile.additions++
|
|
140
|
+
} else if (line.startsWith('-')) {
|
|
141
|
+
currentHunk.lines.push({ type: 'deletion', content: line.slice(1) })
|
|
142
|
+
currentFile.deletions++
|
|
143
|
+
} else if (line.startsWith(' ') || line === '') {
|
|
144
|
+
// Context line (space prefix) or empty line at end of hunk
|
|
145
|
+
currentHunk.lines.push({ type: 'context', content: line.startsWith(' ') ? line.slice(1) : line })
|
|
146
|
+
}
|
|
147
|
+
// Skip "" and other backslash lines
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Finalize last file
|
|
151
|
+
if (currentFile) {
|
|
152
|
+
if (currentHunk) currentFile.hunks.push(currentHunk)
|
|
153
|
+
files.push(currentFile)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return files
|
|
157
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential sourcing for the Discord webhook notification sink (#5413
|
|
3
|
+
* Phase 2).
|
|
4
|
+
*
|
|
5
|
+
* A Discord webhook URL IS a secret: anyone holding it can post arbitrary
|
|
6
|
+
* messages to (and delete the sink's messages from) the target channel. It
|
|
7
|
+
* is therefore sourced exactly like the provider API keys — mirrors
|
|
8
|
+
* byok-credentials.js / deepseek-credentials.js: priority order, 0600 mode
|
|
9
|
+
* enforcement, lazy path resolution, masking helper. Kept as a separate
|
|
10
|
+
* module so a credentials.json carrying API keys AND the webhook URL routes
|
|
11
|
+
* each secret to its consumer without either path knowing about the other.
|
|
12
|
+
*
|
|
13
|
+
* Priority order:
|
|
14
|
+
* 1. process.env.CHROXY_DISCORD_WEBHOOK_URL
|
|
15
|
+
* 2. ~/.chroxy/credentials.json — { discordWebhookUrl: "https://discord.com/api/webhooks/..." }
|
|
16
|
+
* File MUST be mode 0600. We refuse to read it otherwise (security
|
|
17
|
+
* boundary: secrets must not be world-readable).
|
|
18
|
+
* 3. OS keychain — service `chroxy-discord-webhook`, account `webhook-url`
|
|
19
|
+
* (#5493). The launchd cutover stores it here; a Tauri-app-spawned server
|
|
20
|
+
* has no wrapper to export the env var, so the server reads the keychain
|
|
21
|
+
* directly (mirrors how the API token self-resolves).
|
|
22
|
+
*
|
|
23
|
+
* The URL is deliberately NOT a config.json key — config.json is not
|
|
24
|
+
* permission-restricted and gets echoed in verbose/diagnostic output.
|
|
25
|
+
* validateConfig warns if someone puts a webhookUrl in the
|
|
26
|
+
* notifications.discord block.
|
|
27
|
+
*
|
|
28
|
+
* Never logged. The redactor at logger.js scrubs discord.com/api/webhooks
|
|
29
|
+
* URLs (token part is the secret); masking at the use site via
|
|
30
|
+
* maskWebhookUrl is the second layer.
|
|
31
|
+
*/
|
|
32
|
+
import { join } from 'path'
|
|
33
|
+
import { homedir } from 'os'
|
|
34
|
+
import { cachedResolveCredentialFile } from './auth-probes.js'
|
|
35
|
+
import { readStoredField } from './credential-store.js'
|
|
36
|
+
import { getToken } from './keychain.js'
|
|
37
|
+
|
|
38
|
+
// #5493: the launchd cutover (#5439) stores the webhook in the OS keychain under
|
|
39
|
+
// this service/account and relies on ~/.chroxy/service-wrapper.sh to export it as
|
|
40
|
+
// the env var. A Tauri-app-spawned server has no wrapper, so env+file both miss —
|
|
41
|
+
// read the keychain directly as a third source (mirrors the API token, which the
|
|
42
|
+
// server self-resolves from the keychain too).
|
|
43
|
+
const DISCORD_WEBHOOK_KEYCHAIN_SERVICE = 'chroxy-discord-webhook'
|
|
44
|
+
const DISCORD_WEBHOOK_KEYCHAIN_ACCOUNT = 'webhook-url'
|
|
45
|
+
|
|
46
|
+
// Lazy-resolved per call so tests that mutate process.env.HOME between
|
|
47
|
+
// cases pick up the new home (same rationale as byok-credentials.js).
|
|
48
|
+
function credentialsFilePath() {
|
|
49
|
+
return join(homedir(), '.chroxy', 'credentials.json')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Accepted webhook URL shapes. discordapp.com is the legacy domain Discord
|
|
53
|
+
// still serves; ptb/canary are Discord's test builds. The path may carry an
|
|
54
|
+
// API version segment (`/api/v10/webhooks/...`).
|
|
55
|
+
const WEBHOOK_URL_RE = /^https:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/(\d+)\/([A-Za-z0-9_-]+)(?:[/?#]|$)/
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Whether a string looks like a real Discord webhook URL.
|
|
59
|
+
* @param {string} url
|
|
60
|
+
* @returns {boolean}
|
|
61
|
+
*/
|
|
62
|
+
export function isValidDiscordWebhookUrl(url) {
|
|
63
|
+
return typeof url === 'string' && WEBHOOK_URL_RE.test(url)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Extract the `<id>/<token>` pair from a webhook URL (used to build the
|
|
68
|
+
* per-message endpoints: `/webhooks/<id>/<token>/messages/<messageId>`).
|
|
69
|
+
* Strips query params / fragments / trailing slashes.
|
|
70
|
+
*
|
|
71
|
+
* @param {string} url
|
|
72
|
+
* @returns {{ id: string, token: string } | null}
|
|
73
|
+
*/
|
|
74
|
+
export function extractWebhookIdToken(url) {
|
|
75
|
+
if (typeof url !== 'string') return null
|
|
76
|
+
const m = WEBHOOK_URL_RE.exec(url)
|
|
77
|
+
if (!m) return null
|
|
78
|
+
return { id: m[1], token: m[2] }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Resolve the Discord webhook URL for the notification sink.
|
|
83
|
+
*
|
|
84
|
+
* @param {object} [opts]
|
|
85
|
+
* @param {(service: string, account: string) => string|null} [opts.keychainGet]
|
|
86
|
+
* OS-keychain reader (source 3); injectable for tests. Defaults to
|
|
87
|
+
* keychain.getToken, which itself returns null when no keychain is available.
|
|
88
|
+
* @returns {{ url: string, source: 'env' | 'file' | 'keychain' } | { url: null, source: 'none', reason: string }}
|
|
89
|
+
*/
|
|
90
|
+
export function resolveDiscordWebhookUrl({ keychainGet = getToken } = {}) {
|
|
91
|
+
const envUrl = process.env.CHROXY_DISCORD_WEBHOOK_URL
|
|
92
|
+
if (typeof envUrl === 'string' && envUrl.length > 0) {
|
|
93
|
+
return { url: envUrl, source: 'env' }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const CREDENTIALS_FILE = credentialsFilePath()
|
|
97
|
+
// The file source's failure reason is captured rather than returned eagerly so
|
|
98
|
+
// a missing/empty/unreadable file falls through to the keychain (#5493) before
|
|
99
|
+
// we report `source: 'none'` with the most informative reason.
|
|
100
|
+
let fileReason = null
|
|
101
|
+
|
|
102
|
+
// #5490: route the file read through credential-store's cipher-aware reader.
|
|
103
|
+
// The webhook URL lives in the SAME credentials.json the BYOK/API-key
|
|
104
|
+
// resolvers read, and the #5154 at-rest migration rewrites that file into an
|
|
105
|
+
// encrypted envelope on first daemon start. A plain JSON.parse here finds no
|
|
106
|
+
// `discordWebhookUrl` key in the envelope, so the sink silently goes
|
|
107
|
+
// unconfigured. `readStoredField` applies the same 0600 mode enforcement,
|
|
108
|
+
// envelope decryption, and keychain-unavailable handling as the other
|
|
109
|
+
// resolvers — plaintext (not-yet-encrypted) files still pass through. Never
|
|
110
|
+
// throws (readStore catches fs/JSON/decrypt errors); never logs or returns
|
|
111
|
+
// the URL in a reason string.
|
|
112
|
+
let read
|
|
113
|
+
try {
|
|
114
|
+
read = readStoredField('discordWebhookUrl')
|
|
115
|
+
} catch (err) {
|
|
116
|
+
// Defensive: readStoredField is non-throwing by contract, but if it ever
|
|
117
|
+
// does, record the reason and fall through to the keychain.
|
|
118
|
+
read = null
|
|
119
|
+
fileReason = `unable to read ${CREDENTIALS_FILE}: ${err.message}`
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (read) {
|
|
123
|
+
// A read error covers bad mode, malformed JSON, an encrypted envelope whose
|
|
124
|
+
// keychain data key is unavailable, a corrupt/undecryptable envelope, AND a
|
|
125
|
+
// non-ENOENT stat failure (EACCES/EPERM). readStore() reports those stat
|
|
126
|
+
// failures with `fileExists:false` but a populated `error`, so this MUST be
|
|
127
|
+
// checked before the `!fileExists` "does not exist" branch below — otherwise a
|
|
128
|
+
// permission error would be misreported as a missing file, hiding the real
|
|
129
|
+
// cause from an operator debugging a 0600/ownership problem. The reason is
|
|
130
|
+
// value-free (built by credential-store from the path/cause).
|
|
131
|
+
if (read.error) {
|
|
132
|
+
fileReason = read.error
|
|
133
|
+
} else if (!read.fileExists) {
|
|
134
|
+
fileReason = `CHROXY_DISCORD_WEBHOOK_URL not set and ${CREDENTIALS_FILE} does not exist`
|
|
135
|
+
} else if (read.value === null) {
|
|
136
|
+
fileReason = `${CREDENTIALS_FILE} missing or empty "discordWebhookUrl" field`
|
|
137
|
+
} else {
|
|
138
|
+
return { url: read.value, source: 'file' }
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Source 3 (#5493): the OS keychain. getToken short-circuits to null when the
|
|
143
|
+
// keychain is unavailable/disabled, so this is a no-op on platforms/tests
|
|
144
|
+
// without one. Returned raw (like env/file) — the sink applies the same
|
|
145
|
+
// isValidDiscordWebhookUrl + maskWebhookUrl rules to every source.
|
|
146
|
+
const keychainUrl = keychainGet(DISCORD_WEBHOOK_KEYCHAIN_SERVICE, DISCORD_WEBHOOK_KEYCHAIN_ACCOUNT)
|
|
147
|
+
if (typeof keychainUrl === 'string' && keychainUrl.length > 0) {
|
|
148
|
+
return { url: keychainUrl, source: 'keychain' }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return {
|
|
152
|
+
url: null,
|
|
153
|
+
source: 'none',
|
|
154
|
+
reason: fileReason
|
|
155
|
+
? `${fileReason}; no webhook in the keychain either`
|
|
156
|
+
: `CHROXY_DISCORD_WEBHOOK_URL not set and no webhook in ${CREDENTIALS_FILE} or the keychain`,
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Mask a webhook URL for display in logs / UI / errors. The webhook ID is
|
|
162
|
+
* not secret (it's a channel-ish identifier); the token after it is. Never
|
|
163
|
+
* returns the token — even for malformed inputs the whole string is
|
|
164
|
+
* replaced with a fixed marker rather than echoed.
|
|
165
|
+
*
|
|
166
|
+
* @param {string} url
|
|
167
|
+
* @returns {string}
|
|
168
|
+
*/
|
|
169
|
+
export function maskWebhookUrl(url) {
|
|
170
|
+
const parts = extractWebhookIdToken(url)
|
|
171
|
+
if (!parts) return '<invalid webhook url>'
|
|
172
|
+
return `https://discord.com/api/webhooks/${parts.id}/[REDACTED]`
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Cached resolver — same result as resolveDiscordWebhookUrl, but routed
|
|
177
|
+
* through auth-probes' mtime+size+mode-keyed credentials.json cache
|
|
178
|
+
* (#5427 review): the sink's isConfigured() is probed by the registry on
|
|
179
|
+
* every notification (and again inside send()/heartbeat), and the raw
|
|
180
|
+
* resolver statSync+readFileSync+JSON.parses the file each time. The
|
|
181
|
+
* cache repeats the parsed result until the env var or the file actually
|
|
182
|
+
* changes. Tests that need isolation call auth-probes'
|
|
183
|
+
* resetCachesForTest() (the suites already do, via the providers tests'
|
|
184
|
+
* shared setup) or inject their own resolveWebhookUrl.
|
|
185
|
+
*/
|
|
186
|
+
export function cachedResolveDiscordWebhookUrl() {
|
|
187
|
+
return cachedResolveCredentialFile('discord', process.env.CHROXY_DISCORD_WEBHOOK_URL, resolveDiscordWebhookUrl)
|
|
188
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Discord pairing-link delivery (#5513, epic #5509).
|
|
3
|
+
*
|
|
4
|
+
* A ONE-OFF webhook POST of an approval-gated chroxy:// pairing link to the
|
|
5
|
+
* configured private channel. Deliberately NOT the per-project status embed
|
|
6
|
+
* (discord-webhook-sink.js): no message-id tracking, no PATCH/DELETE lifecycle,
|
|
7
|
+
* no state machine — a single `webhook execute` POST and done. The two share
|
|
8
|
+
* only credential resolution (env > 0600 credentials.json) and the id/token
|
|
9
|
+
* extraction, which is the seam the issue calls for.
|
|
10
|
+
*
|
|
11
|
+
* Security:
|
|
12
|
+
* - The link carries an APPROVAL-GATED id (PairingManager
|
|
13
|
+
* .createApprovalGatedPairingId). Redeeming it never mints a token on its
|
|
14
|
+
* own — the host must approve. So possession of the channel grants nothing.
|
|
15
|
+
* - No token material beyond the ephemeral gated id is posted.
|
|
16
|
+
* - The webhook URL is a SECRET. It is resolved here but NEVER logged and
|
|
17
|
+
* NEVER returned in a result / reason string (a thrown fetch error may
|
|
18
|
+
* embed the URL; we discard the error text and return a fixed reason).
|
|
19
|
+
*
|
|
20
|
+
* Host-triggered only (CLI `chroxy pair-discord`, dashboard button) — never
|
|
21
|
+
* automatic. Each trigger generates a fresh gated id upstream and calls this.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import {
|
|
25
|
+
cachedResolveDiscordWebhookUrl,
|
|
26
|
+
isValidDiscordWebhookUrl,
|
|
27
|
+
extractWebhookIdToken,
|
|
28
|
+
} from './discord-credentials.js'
|
|
29
|
+
|
|
30
|
+
const FETCH_TIMEOUT_MS = 10_000
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Build the minimal Discord message for a pairing link. Plain `content` (no
|
|
34
|
+
* embeds, no state-machine fields). The only ephemeral material is the gated
|
|
35
|
+
* id already embedded in `url`.
|
|
36
|
+
*
|
|
37
|
+
* @param {{ url: string, expiresInSeconds?: number }} args
|
|
38
|
+
* @returns {{ content: string }}
|
|
39
|
+
*/
|
|
40
|
+
export function buildPairLinkMessage({ url, expiresInSeconds } = {}) {
|
|
41
|
+
const ttl = Number.isFinite(expiresInSeconds) ? Math.max(0, Math.round(expiresInSeconds)) : 60
|
|
42
|
+
// Minimal, masked-friendly: the link + the two facts a recipient needs.
|
|
43
|
+
// Approval is required on the host, so a leaked channel grants nothing.
|
|
44
|
+
const content = [
|
|
45
|
+
'Chroxy pairing link:',
|
|
46
|
+
url,
|
|
47
|
+
`Expires in ${ttl}s · approval required on the host.`,
|
|
48
|
+
].join('\n')
|
|
49
|
+
return { content }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* POST a pairing link to the configured Discord webhook. Resolves a plain
|
|
54
|
+
* result object; never throws, never logs or returns the webhook URL/token.
|
|
55
|
+
*
|
|
56
|
+
* @param {{ url: string, expiresInSeconds?: number }} link
|
|
57
|
+
* @param {object} [deps]
|
|
58
|
+
* @param {Function} [deps.resolveWebhookUrl] - injection seam; defaults to the
|
|
59
|
+
* cached env > 0600-credentials resolver.
|
|
60
|
+
* @param {Function} [deps.fetchFn] - injection seam; defaults to global fetch.
|
|
61
|
+
* @returns {Promise<{ posted: true, expiresInSeconds: number }
|
|
62
|
+
* | { posted: false, reason: 'not_configured'|'invalid'|'post_failed' }>}
|
|
63
|
+
*/
|
|
64
|
+
export async function postPairLinkToDiscord(link, deps = {}) {
|
|
65
|
+
const resolveWebhookUrl = deps.resolveWebhookUrl || cachedResolveDiscordWebhookUrl
|
|
66
|
+
const fetchFn = deps.fetchFn || globalThis.fetch
|
|
67
|
+
|
|
68
|
+
const url = link?.url
|
|
69
|
+
if (typeof url !== 'string' || url.length === 0) {
|
|
70
|
+
return { posted: false, reason: 'invalid' }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
let resolved
|
|
74
|
+
try {
|
|
75
|
+
resolved = resolveWebhookUrl()
|
|
76
|
+
} catch {
|
|
77
|
+
return { posted: false, reason: 'not_configured' }
|
|
78
|
+
}
|
|
79
|
+
const webhookUrl = resolved?.url
|
|
80
|
+
if (typeof webhookUrl !== 'string' || !isValidDiscordWebhookUrl(webhookUrl)) {
|
|
81
|
+
return { posted: false, reason: 'not_configured' }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const parts = extractWebhookIdToken(webhookUrl)
|
|
85
|
+
if (!parts) return { posted: false, reason: 'not_configured' }
|
|
86
|
+
const endpoint = `https://discord.com/api/webhooks/${parts.id}/${parts.token}`
|
|
87
|
+
|
|
88
|
+
const message = buildPairLinkMessage(link)
|
|
89
|
+
const expiresInSeconds = Number.isFinite(link?.expiresInSeconds)
|
|
90
|
+
? Math.max(0, Math.round(link.expiresInSeconds))
|
|
91
|
+
: 60
|
|
92
|
+
|
|
93
|
+
const controller = new AbortController()
|
|
94
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
|
|
95
|
+
try {
|
|
96
|
+
const res = await fetchFn(endpoint, {
|
|
97
|
+
method: 'POST',
|
|
98
|
+
headers: { 'Content-Type': 'application/json' },
|
|
99
|
+
body: JSON.stringify(message),
|
|
100
|
+
signal: controller.signal,
|
|
101
|
+
})
|
|
102
|
+
if (!res || !res.ok) {
|
|
103
|
+
return { posted: false, reason: 'post_failed' }
|
|
104
|
+
}
|
|
105
|
+
return { posted: true, expiresInSeconds }
|
|
106
|
+
} catch {
|
|
107
|
+
// The thrown error text may embed the secret webhook URL — discard it and
|
|
108
|
+
// return a fixed reason. NEVER surface err.message.
|
|
109
|
+
return { posted: false, reason: 'post_failed' }
|
|
110
|
+
} finally {
|
|
111
|
+
clearTimeout(timer)
|
|
112
|
+
}
|
|
113
|
+
}
|