|
| 1 | +import http, { IncomingMessage, ServerResponse } from "http"; |
| 2 | +import { randomBytes, createHash } from "crypto"; |
| 3 | +import url from "url"; |
| 4 | + |
| 5 | +export const ACCOUNT_URL = |
| 6 | + process.env.FAUNA_ACCOUNT_URL ?? "https://account.fauna.com/api/v1"; |
| 7 | + |
| 8 | +// Default to prod client id and secret |
| 9 | +const clientId = process.env.FAUNA_CLIENT_ID ?? "Aq4_G0mOtm_F1fK3PuzE0k-i9F0"; |
| 10 | +// Native public clients are not confidential. The client secret is not used beyond |
| 11 | +// client identification. https://datatracker.ietf.org/doc/html/rfc8252#section-8.5 |
| 12 | +const clientSecret = |
| 13 | + process.env.FAUNA_CLIENT_SECRET ?? |
| 14 | + "2W9eZYlyN5XwnpvaP3AwOfclrtAjTXncH6k-bdFq1ZV0hZMFPzRIfg"; |
| 15 | +const REDIRECT_URI = `http://127.0.0.1`; |
| 16 | + |
| 17 | +class OAuthClient { |
| 18 | + server; //: http.Server; |
| 19 | + port; //: number; |
| 20 | + code_verifier; //: string; |
| 21 | + code_challenge; //: string; |
| 22 | + auth_code; //: string; |
| 23 | + state; //: string; |
| 24 | + |
| 25 | + constructor() { |
| 26 | + this.server = http.createServer(this._handleRequest.bind(this)); |
| 27 | + this.code_verifier = Buffer.from(randomBytes(20)).toString("base64url"); |
| 28 | + this.code_challenge = createHash("sha256") |
| 29 | + .update(this.code_verifier) |
| 30 | + .digest("base64url"); |
| 31 | + this.port = 0; |
| 32 | + this.auth_code = ""; |
| 33 | + this.state = this._generateCSRFToken(); |
| 34 | + } |
| 35 | + |
| 36 | + getRequestUrl() { |
| 37 | + const params = { |
| 38 | + client_id: clientId, |
| 39 | + redirect_uri: `${REDIRECT_URI}:${this.port}`, |
| 40 | + code_challenge: this.code_challenge, |
| 41 | + code_challenge_method: "S256", |
| 42 | + response_type: "code", |
| 43 | + scope: "create_session", |
| 44 | + state: this.state, |
| 45 | + }; |
| 46 | + return `${ACCOUNT_URL}/api/v1/oauth/authorize?${new URLSearchParams( |
| 47 | + params |
| 48 | + )}`; |
| 49 | + } |
| 50 | + |
| 51 | + getToken() { |
| 52 | + const params = { |
| 53 | + grant_type: "authorization_code", |
| 54 | + client_id: clientId, |
| 55 | + client_secret: clientSecret, |
| 56 | + code: this.auth_code, |
| 57 | + redirect_uri: `${REDIRECT_URI}:${this.port}`, |
| 58 | + code_verifier: this.code_verifier, |
| 59 | + }; |
| 60 | + return fetch(`${ACCOUNT_URL}/api/v1/oauth/token`, { |
| 61 | + method: "POST", |
| 62 | + headers: { |
| 63 | + "Content-Type": "application/x-www-form-urlencoded", |
| 64 | + }, |
| 65 | + body: new URLSearchParams(params), |
| 66 | + }); |
| 67 | + } |
| 68 | + |
| 69 | + _generateCSRFToken() { |
| 70 | + return Buffer.from(randomBytes(20)).toString("base64url"); |
| 71 | + } |
| 72 | + |
| 73 | + // req: IncomingMessage, res: ServerResponse |
| 74 | + _handleRequest(req, res) { |
| 75 | + const allowedOrigins = [ |
| 76 | + "http://localhost:3005", |
| 77 | + "http://127.0.0.1:3005", |
| 78 | + "http://dashboard.fauna.com", |
| 79 | + "http://dashboard.fauna-dev.com", |
| 80 | + "http://dashboard.fauna-preview.com", |
| 81 | + ]; |
| 82 | + const origin = req.headers.origin || ""; |
| 83 | + |
| 84 | + if (allowedOrigins.includes(origin)) { |
| 85 | + res.setHeader("Access-Control-Allow-Origin", origin); |
| 86 | + res.setHeader("Access-Control-Allow-Methods", "GET"); |
| 87 | + res.setHeader("Access-Control-Allow-Headers", "Content-Type"); |
| 88 | + } |
| 89 | + |
| 90 | + let errorMessage = ""; |
| 91 | + |
| 92 | + if (req.method === "GET") { |
| 93 | + const parsedUrl = url.parse(req.url || "", true); |
| 94 | + if (parsedUrl.pathname === "/success") { |
| 95 | + console.log("Received success response"); |
| 96 | + res.write(` |
| 97 | + <body> |
| 98 | + <h1>Success</h1> |
| 99 | + <p>Authentication successful. You can close this window and return to the terminal.</p> |
| 100 | + </body> |
| 101 | + `); |
| 102 | + res.end(); |
| 103 | + this.closeServer(); |
| 104 | + } else if (parsedUrl.pathname !== "/") { |
| 105 | + errorMessage = "Invalid redirect uri"; |
| 106 | + this.closeServer(); |
| 107 | + } |
| 108 | + const query = parsedUrl.query; |
| 109 | + if (query.error) { |
| 110 | + errorMessage = `${query.error.toString()} - ${query.error_description}`; |
| 111 | + this.closeServer(); |
| 112 | + } |
| 113 | + if (query.code) { |
| 114 | + const authCode = query.code; |
| 115 | + if (!authCode || typeof authCode !== "string") { |
| 116 | + errorMessage = "Invalid authorization code received"; |
| 117 | + this.server.close(); |
| 118 | + } else { |
| 119 | + this.auth_code = authCode; |
| 120 | + if (query.state !== this.state) { |
| 121 | + errorMessage = "Invalid state received"; |
| 122 | + this.closeServer(); |
| 123 | + } |
| 124 | + res.writeHead(302, { Location: "/success" }); |
| 125 | + res.end(); |
| 126 | + this.server.emit("auth_code_received"); |
| 127 | + } |
| 128 | + } |
| 129 | + } else { |
| 130 | + errorMessage = "Invalid request method"; |
| 131 | + this.closeServer(); |
| 132 | + } |
| 133 | + if (errorMessage) { |
| 134 | + console.error("Error during authentication:", errorMessage); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + async start() { |
| 139 | + try { |
| 140 | + this.server.on("listening", () => { |
| 141 | + this.port = (this.server.address()).port; |
| 142 | + this.server.emit("ready"); |
| 143 | + }); |
| 144 | + this.server.listen(0); |
| 145 | + } catch (e) { |
| 146 | + console.error("Error starting loopback server:", e.message); |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + closeServer() { |
| 151 | + this.server.closeAllConnections(); |
| 152 | + this.server.close(); |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +export default OAuthClient; |
0 commit comments