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