|
| 1 | +import * as crypto from "crypto"; |
| 2 | +import * as vscode from "vscode"; |
| 3 | +import {getClient} from "../api/api"; |
| 4 | +import {getSession, newSession} from "../auth/auth"; |
| 5 | +import {getGitHubApiUri} from "../configuration/configuration"; |
| 6 | +import {log, logDebug, logError} from "../log"; |
| 7 | +import {parseJobUrl} from "./jobUrl"; |
| 8 | +import {validateTunnelUrl} from "./tunnelUrl"; |
| 9 | +import {WebSocketDapAdapter} from "./webSocketDapAdapter"; |
| 10 | + |
| 11 | +export const DEBUG_TYPE = "github-actions-job"; |
| 12 | + |
| 13 | +/** |
| 14 | + * Extension-private token store keyed by one-time nonce. Tokens are never |
| 15 | + * placed in DebugConfiguration (readable by other extensions). |
| 16 | + */ |
| 17 | +const pendingTokens = new Map<string, string>(); |
| 18 | + |
| 19 | +export function registerDebugger(context: vscode.ExtensionContext): void { |
| 20 | + context.subscriptions.push( |
| 21 | + vscode.debug.registerDebugAdapterDescriptorFactory(DEBUG_TYPE, new ActionsDebugAdapterFactory()) |
| 22 | + ); |
| 23 | + |
| 24 | + context.subscriptions.push( |
| 25 | + vscode.debug.registerDebugAdapterTrackerFactory(DEBUG_TYPE, new ActionsDebugTrackerFactory()) |
| 26 | + ); |
| 27 | + |
| 28 | + context.subscriptions.push( |
| 29 | + vscode.commands.registerCommand("github-actions.debugger.connect", () => connectToDebugger()) |
| 30 | + ); |
| 31 | +} |
| 32 | + |
| 33 | +async function connectToDebugger(): Promise<void> { |
| 34 | + const rawUrl = await vscode.window.showInputBox({ |
| 35 | + title: "Connect to Actions Job Debugger", |
| 36 | + prompt: "Paste the URL of the Actions job to debug", |
| 37 | + placeHolder: "https://github.com/owner/repo/actions/runs/123/job/456", |
| 38 | + ignoreFocusOut: true, |
| 39 | + validateInput: input => { |
| 40 | + if (!input) { |
| 41 | + return "A job URL is required"; |
| 42 | + } |
| 43 | + const result = parseJobUrl(input, getGitHubApiUri()); |
| 44 | + return result.valid ? null : result.reason; |
| 45 | + } |
| 46 | + }); |
| 47 | + |
| 48 | + if (!rawUrl) { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + const parsed = parseJobUrl(rawUrl, getGitHubApiUri()); |
| 53 | + if (!parsed.valid) { |
| 54 | + void vscode.window.showErrorMessage(`Invalid job URL: ${parsed.reason}`); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + // Try silently first; fall back to prompting for sign-in if needed. |
| 59 | + let session = await getSession(); |
| 60 | + if (!session) { |
| 61 | + try { |
| 62 | + session = await newSession("Sign in to GitHub to connect to the Actions job debugger."); |
| 63 | + } catch { |
| 64 | + void vscode.window.showErrorMessage( |
| 65 | + "GitHub authentication is required to connect to the Actions job debugger. Please sign in and try again." |
| 66 | + ); |
| 67 | + return; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + const token = session.accessToken; |
| 72 | + let debuggerUrl: string; |
| 73 | + try { |
| 74 | + debuggerUrl = await vscode.window.withProgress( |
| 75 | + {location: vscode.ProgressLocation.Notification, title: "Connecting to Actions job debugger…"}, |
| 76 | + async () => { |
| 77 | + const octokit = getClient(token); |
| 78 | + const response = await octokit.request("GET /repos/{owner}/{repo}/actions/jobs/{job_id}/debugger", { |
| 79 | + owner: parsed.owner, |
| 80 | + repo: parsed.repo, |
| 81 | + job_id: parsed.jobId |
| 82 | + }); |
| 83 | + return (response.data as {debugger_url: string}).debugger_url; |
| 84 | + } |
| 85 | + ); |
| 86 | + } catch (e) { |
| 87 | + const status = (e as {status?: number}).status; |
| 88 | + if (status === 404) { |
| 89 | + void vscode.window.showErrorMessage( |
| 90 | + "Debugger is not available for this job. Make sure the job is running with debugging enabled." |
| 91 | + ); |
| 92 | + } else if (status === 403) { |
| 93 | + void vscode.window.showErrorMessage( |
| 94 | + "Permission denied. You may need to re-authenticate or check your access to this repository." |
| 95 | + ); |
| 96 | + } else { |
| 97 | + const msg = (e as Error).message || "Unknown error"; |
| 98 | + void vscode.window.showErrorMessage(`Failed to fetch debugger URL: ${msg}`); |
| 99 | + } |
| 100 | + return; |
| 101 | + } |
| 102 | + |
| 103 | + const validation = validateTunnelUrl(debuggerUrl); |
| 104 | + if (!validation.valid) { |
| 105 | + void vscode.window.showErrorMessage(`Invalid debugger URL returned by API: ${validation.reason}`); |
| 106 | + return; |
| 107 | + } |
| 108 | + |
| 109 | + // Store token in extension-private memory (not in the config) to avoid |
| 110 | + // exposing it to other extensions. |
| 111 | + const nonce = crypto.randomBytes(16).toString("hex"); |
| 112 | + pendingTokens.set(nonce, token); |
| 113 | + |
| 114 | + const config: vscode.DebugConfiguration = { |
| 115 | + type: DEBUG_TYPE, |
| 116 | + name: "Actions Job Debugger", |
| 117 | + request: "attach", |
| 118 | + tunnelUrl: validation.url, |
| 119 | + __tokenNonce: nonce |
| 120 | + }; |
| 121 | + |
| 122 | + log(`Starting debug session for ${validation.url}`); |
| 123 | + |
| 124 | + try { |
| 125 | + const started = await vscode.debug.startDebugging(undefined, config); |
| 126 | + if (!started) { |
| 127 | + void vscode.window.showErrorMessage( |
| 128 | + "Failed to start the debug session. Check the GitHub Actions output for details." |
| 129 | + ); |
| 130 | + } |
| 131 | + } finally { |
| 132 | + // Clean up if the factory hasn't consumed the token yet |
| 133 | + pendingTokens.delete(nonce); |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +class ActionsDebugAdapterFactory implements vscode.DebugAdapterDescriptorFactory { |
| 138 | + async createDebugAdapterDescriptor(session: vscode.DebugSession): Promise<vscode.DebugAdapterDescriptor> { |
| 139 | + const tunnelUrl = session.configuration.tunnelUrl as string | undefined; |
| 140 | + const nonce = session.configuration.__tokenNonce as string | undefined; |
| 141 | + const token = nonce ? pendingTokens.get(nonce) : undefined; |
| 142 | + |
| 143 | + // Consume immediately so it cannot be replayed. |
| 144 | + if (nonce) { |
| 145 | + pendingTokens.delete(nonce); |
| 146 | + } |
| 147 | + |
| 148 | + if (!tunnelUrl || !token) { |
| 149 | + throw new Error( |
| 150 | + "Missing tunnel URL or authentication token. Use the 'Connect to Actions Job Debugger' command to start a session." |
| 151 | + ); |
| 152 | + } |
| 153 | + |
| 154 | + const revalidation = validateTunnelUrl(tunnelUrl); |
| 155 | + if (!revalidation.valid) { |
| 156 | + throw new Error(`Invalid debugger tunnel URL: ${revalidation.reason}`); |
| 157 | + } |
| 158 | + |
| 159 | + const adapter = new WebSocketDapAdapter(tunnelUrl, token); |
| 160 | + |
| 161 | + try { |
| 162 | + await adapter.connect(); |
| 163 | + } catch (e) { |
| 164 | + adapter.dispose(); |
| 165 | + const msg = (e as Error).message; |
| 166 | + logError(e as Error, "Failed to connect debugger adapter"); |
| 167 | + throw new Error(`Could not connect to the debugger tunnel: ${msg}`); |
| 168 | + } |
| 169 | + |
| 170 | + return new vscode.DebugAdapterInlineImplementation(adapter); |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +class ActionsDebugTrackerFactory implements vscode.DebugAdapterTrackerFactory { |
| 175 | + createDebugAdapterTracker(): vscode.DebugAdapterTracker { |
| 176 | + return { |
| 177 | + onWillReceiveMessage(message: unknown) { |
| 178 | + const m = message as Record<string, unknown>; |
| 179 | + logDebug( |
| 180 | + `[tracker] VS Code → DA: ${String(m.type)}${m.command ? `:${String(m.command)}` : ""} (seq ${String(m.seq)})` |
| 181 | + ); |
| 182 | + }, |
| 183 | + onDidSendMessage(message: unknown) { |
| 184 | + const m = message as Record<string, unknown>; |
| 185 | + const body = m.body as Record<string, unknown> | undefined; |
| 186 | + let detail = String(m.type); |
| 187 | + if (m.command) { |
| 188 | + detail += `:${String(m.command)}`; |
| 189 | + } |
| 190 | + if (m.event) { |
| 191 | + detail += `:${String(m.event)}`; |
| 192 | + } |
| 193 | + if (m.event === "stopped" && body) { |
| 194 | + detail += ` threadId=${String(body.threadId)} allThreadsStopped=${String(body.allThreadsStopped)}`; |
| 195 | + } |
| 196 | + logDebug(`[tracker] DA → VS Code: ${detail} (seq ${String(m.seq)})`); |
| 197 | + }, |
| 198 | + onError(error: Error) { |
| 199 | + logError(error, "[tracker] DAP error"); |
| 200 | + }, |
| 201 | + onExit(code: number | undefined, signal: string | undefined) { |
| 202 | + log(`[tracker] DAP session exited: code=${String(code)} signal=${String(signal)}`); |
| 203 | + } |
| 204 | + }; |
| 205 | + } |
| 206 | +} |
0 commit comments