-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathserver.ts
More file actions
128 lines (122 loc) · 3.83 KB
/
server.ts
File metadata and controls
128 lines (122 loc) · 3.83 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
import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { OAuthServerInfo } from "../types.js";
import { logError, logWarn } from "../logger.js";
// Resolve path to oauth-success.html (one level up from auth/ subfolder)
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const SUCCESS_HTML_PATH = path.join(__dirname, "..", "oauth-success.html");
const FALLBACK_SUCCESS_HTML = `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Authorization Complete</title>
</head>
<body>
<h1>Authorization complete</h1>
<p>You can return to OpenCode.</p>
</body>
</html>`;
function loadSuccessHtml(): string {
try {
return fs.readFileSync(SUCCESS_HTML_PATH, "utf-8");
} catch (error) {
logWarn("oauth-success.html missing; using fallback success page", {
path: SUCCESS_HTML_PATH,
error: (error as Error)?.message ?? String(error),
});
return FALLBACK_SUCCESS_HTML;
}
}
const successHtml = loadSuccessHtml();
/**
* Start a small local HTTP server that waits for /auth/callback and returns the code
* @param options - OAuth state for validation
* @returns Promise that resolves to server info
*/
export function startLocalOAuthServer({ state }: { state: string }): Promise<OAuthServerInfo> {
let pollAborted = false;
const server = http.createServer((req, res) => {
try {
const url = new URL(req.url || "", "http://localhost");
if (url.pathname !== "/auth/callback") {
res.statusCode = 404;
res.end("Not found");
return;
}
if (url.searchParams.get("state") !== state) {
res.statusCode = 400;
res.end("State mismatch");
return;
}
const code = url.searchParams.get("code");
if (!code) {
res.statusCode = 400;
res.end("Missing authorization code");
return;
}
res.statusCode = 200;
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'none'");
res.end(successHtml);
const codeStore = server as http.Server & { _lastCode?: string; _lastState?: string };
codeStore._lastCode = code;
codeStore._lastState = state;
} catch (err) {
logError(`Request handler error: ${(err as Error)?.message ?? String(err)}`);
res.statusCode = 500;
res.end("Internal error");
}
});
server.unref();
return new Promise((resolve) => {
server
.listen(1455, "127.0.0.1", () => {
resolve({
port: 1455,
ready: true,
close: () => {
pollAborted = true;
server.close();
},
waitForCode: async (_expectedState: string) => {
const POLL_INTERVAL_MS = 100;
const TIMEOUT_MS = 5 * 60 * 1000;
const maxIterations = Math.floor(TIMEOUT_MS / POLL_INTERVAL_MS);
const poll = () => new Promise<void>((r) => setTimeout(r, POLL_INTERVAL_MS));
for (let i = 0; i < maxIterations; i++) {
if (pollAborted) return null;
const codeStore = server as http.Server & { _lastCode?: string; _lastState?: string };
const lastCode = codeStore._lastCode;
const lastState = codeStore._lastState;
if (lastCode && lastState === _expectedState) return { code: lastCode };
await poll();
}
logWarn("OAuth poll timeout after 5 minutes");
return null;
},
});
})
.on("error", (err: NodeJS.ErrnoException) => {
logError(
`Failed to bind http://127.0.0.1:1455 (${err?.code}). Falling back to manual paste.`,
);
resolve({
port: 1455,
ready: false,
close: () => {
pollAborted = true;
try {
server.close();
} catch (err) {
logError(`Failed to close OAuth server: ${(err as Error)?.message ?? String(err)}`);
}
},
waitForCode: () => Promise.resolve(null),
});
});
});
}