Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New shell login setup #364

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"postpack": "rm -f oclif.manifest.json",
"prepack": "yarn build && oclif manifest",
"pretest": "yarn fixlint",
"local": "export $(cat .env | xargs); node bin/run",
"local-test": "export $(cat .env | xargs); c8 -r text mocha --forbid-only \"test/**/*.test.{js,ts}\"",
"test": "export $(cat .env.test | xargs); c8 -r html mocha --forbid-only \"test/**/*.test.{js,ts}\"",
"lint": "eslint .",
Expand Down
66 changes: 66 additions & 0 deletions src/commands/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { Command } from "@oclif/core";
import OAuthServer from "../lib/auth/oauth-client";

type AccessToken = {
access_token: string;
token_type: string;
ttl: string;
state: string;
};

export default class LoginCommand extends Command {
static description = "Log in to a Fauna account.";
mwilde345 marked this conversation as resolved.
Show resolved Hide resolved
static examples = ["$ fauna login"];
static flags = {};

async run() {
await this.execute();
}

async getSession(access_token: string) {
mwilde345 marked this conversation as resolved.
Show resolved Hide resolved
const myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${access_token}`);

const requestOptions = {
method: "POST",
headers: myHeaders,
};
const response = await fetch(
"http://localhost:8000/api/v1/session",
requestOptions
);
if (response.status >= 400) {
throw new Error(`Error creating session: ${response.statusText}`);
}
const session = await response.json();
return session;
}

async execute() {
await this.parse();
mwilde345 marked this conversation as resolved.
Show resolved Hide resolved

const oAuth = new OAuthServer();
await oAuth.start();
const dashboardOAuthURL = (await fetch(oAuth.getRequestUrl())).url;
const error = new URL(dashboardOAuthURL).searchParams.get("error");
if (error) {
throw new Error(`Error during login: ${error}`);
}
this.log(`To login, open your browser to:\n ${dashboardOAuthURL}`);
oAuth.server.on("auth_code_received", async () => {
try {
const tokenResponse = await oAuth.getToken();
const token: AccessToken = await tokenResponse.json();
this.log("Authentication successful!");
const { state, access_token } = token;
if (state !== oAuth.state) {
throw new Error("Error during login: invalid state.");
}
const session = await this.getSession(access_token);
this.log("Session created:", session);
} catch (err) {
console.error(err);
}
});
}
}
161 changes: 161 additions & 0 deletions src/lib/auth/oauth-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import http, { IncomingMessage, ServerResponse } from "http";
const { randomBytes, createHash } = require("node:crypto");
import url from "url";
import net, { AddressInfo } from "net";

const accountURL = process.env.FAUNA_ACCOUNT_URL ?? "https://account.fauna.com";

// Default to prod client id and secret
const clientId = process.env.FAUNA_CLIENT_ID ?? "Aq4_G0mOtm_F1fK3PuzE0k-i9F0";
// Native public clients are not confidential. The client secret is not used beyond
// client identification. https://datatracker.ietf.org/doc/html/rfc8252#section-8.5
const clientSecret =
process.env.FAUNA_CLIENT_SECRET ??
"2W9eZYlyN5XwnpvaP3AwOfclrtAjTXncH6k-bdFq1ZV0hZMFPzRIfg";
mwilde345 marked this conversation as resolved.
Show resolved Hide resolved
const REDIRECT_URI = `http://127.0.0.1`;

class OAuthClient {
public server: http.Server;
public port: number;
private code_verifier: string;
private code_challenge: string;
private auth_code: string;
public state: string;

constructor() {
this.server = http.createServer(this._handleRequest.bind(this));
this.code_verifier = Buffer.from(randomBytes(20)).toString("base64url");
this.code_challenge = createHash("sha256")
.update(this.code_verifier)
.digest("base64url");
this.port = 0;
this.auth_code = "";
this.state = this._generateCSRFToken();
}

public getRequestUrl() {
const params = {
client_id: clientId,
redirect_uri: `${REDIRECT_URI}:${this.port}`,
code_challenge: this.code_challenge,
code_challenge_method: "S256",
response_type: "code",
scope: "create_session",
state: this.state,
};
return `${accountURL}/api/v1/oauth/authorize?${new URLSearchParams(
params
)}`;
}

public getToken() {
const now = new Date();
// Short expiry for access token as it's only used to create a session
now.setUTCMinutes(now.getUTCMinutes() + 5);
mwilde345 marked this conversation as resolved.
Show resolved Hide resolved
const params = {
grant_type: "authorization_code",
client_id: clientId,
client_secret: clientSecret,
code: this.auth_code,
redirect_uri: `${REDIRECT_URI}:${this.port}`,
code_verifier: this.code_verifier,
ttl: now.toISOString(),
};
return fetch(`${accountURL}/api/v1/oauth/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams(params),
});
}

private _generateCSRFToken(): string {
return Buffer.from(randomBytes(20)).toString("base64url");
}

private _handleRequest(req: IncomingMessage, res: ServerResponse) {
const allowedOrigins = [
"http://localhost:3005",
"http://127.0.0.1:3005",
"http://dashboard.fauna.com",
"http://dashboard.fauna-dev.com",
"http://dashboard.fauna-preview.com",
];
const origin = req.headers.origin || "";

if (allowedOrigins.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Methods", "GET");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
}

let errorMessage = "";

if (req.method === "GET") {
const parsedUrl = url.parse(req.url || "", true);
if (parsedUrl.pathname !== "/") {
errorMessage = "Invalid redirect uri";
this.closeServer();
}
const query = parsedUrl.query;
if (query.error) {
errorMessage = query.error.toString();
mwilde345 marked this conversation as resolved.
Show resolved Hide resolved
this.closeServer();
}
if (query.code) {
const authCode = query.code;
if (!authCode || typeof authCode !== "string") {
errorMessage = "Invalid authorization code received";
this.server.close();
} else {
this.auth_code = authCode;
if (query.state !== this.state) {
errorMessage = "Invalid state received";
this.closeServer();
}
// TODO: Send them to a nice page that shows auth is complete and they can close the window.
res.writeHead(200, { "Content-Type": "text/html" });
res.end();
this.server.emit("auth_code_received");
this.closeServer();
}
}
} else {
errorMessage = "Invalid request method";
this.closeServer();
}
if (errorMessage) {
console.error("Error during authentication:", errorMessage);
}
}

private _getFreePort(): Promise<number> {
return new Promise((res, rej) => {
const srv = net.createServer();
srv.listen(0, () => {
const port = srv.address() as AddressInfo;
srv.close((err) => {
if (err) rej(err);
res(port.port);
});
});
});
}

public async start() {
try {
this.port = await this._getFreePort();
this.server.listen(this.port);
} catch (e: any) {
console.error("Error starting loopback server:", e.message);
}
}
mwilde345 marked this conversation as resolved.
Show resolved Hide resolved

public closeServer() {
this.server.closeAllConnections();
this.server.close();
}
}

export default OAuthClient;