MCPcopy Create free account
hub / github.com/code-with-antonio/nightcode / fetch

Function fetch

packages/cli/src/lib/oauth.ts:54–128  ·  view source on GitHub ↗
(req)

Source from the content-addressed store, hash-verified

52 const server = Bun.serve({
53 port: 0,
54 async fetch(req) {
55 const url = new URL(req.url);
56
57 if (url.pathname !== "/callback") {
58 return new Response("Not found", { status: 404 });
59 }
60
61 const error = url.searchParams.get("error");
62
63 if (error) {
64 const msg = url.searchParams.get("error_description") ?? error;
65 settled = true;
66 reject(new Error(msg));
67 setTimeout(() => server.stop(), 500);
68 return new Response(`Authentication failed: ${msg}`, { status: 400 });
69 }
70
71 const code = url.searchParams.get("code");
72 const state = url.searchParams.get("state");
73
74 if (!code || !state) {
75 settled = true;
76 reject(new Error("Missing code or state"));
77 setTimeout(() => server.stop(), 500);
78 return new Response("Bad request", { status: 400 });
79 }
80
81 // Verify nonce from state
82 try {
83 const payload = decodeState(state);
84
85 if (payload.nonce !== nonce) throw new Error("State mismatch");
86 } catch (err) {
87 settled = true;
88 reject(err);
89 setTimeout(() => server.stop(), 500);
90 return new Response("Invalid state", { status: 400 });
91 }
92
93 try {
94 // Exchange authorization code for Clerk tokens
95 const redirectUri = `${apiUrl}/auth/callback`;
96
97 const tokenRes = await fetch(`${clerkFrontendApi}/oauth/token`, {
98 method: "POST",
99 headers: { "Content-Type": "application/x-www-form-urlencoded" },
100 body: new URLSearchParams({
101 grant_type: "authorization_code",
102 code,
103 redirect_uri: redirectUri,
104 client_id: clientId,
105 code_verifier: codeVerifier,
106 }),
107 });
108
109 if (!tokenRes.ok) {
110 const details = await tokenRes.text();
111 throw new Error(details || "Failed to exchange authorization code");

Callers 1

api-client.tsFile · 0.85

Calls 3

saveAuthFunction · 0.90
decodeStateFunction · 0.85
getErrorMessageFunction · 0.70

Tested by

no test coverage detected