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

auth: Use webcrypto & Uint8Array instead of NodeJS crypto & Buffer #77

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ const client = new Client(authClient);
### Generating an Authentication URL

```typescript
const authUrl = authClient.generateAuthURL({
const authUrl = await authClient.generateAuthURL({
code_challenge_method: "s256",
});
```
Expand Down
2 changes: 1 addition & 1 deletion examples/oauth2-callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ app.get("/callback", async function (req, res) {
});

app.get("/login", async function (req, res) {
const authUrl = authClient.generateAuthURL({
const authUrl = await authClient.generateAuthURL({
state: STATE,
code_challenge_method: "s256",
});
Expand Down
2 changes: 1 addition & 1 deletion examples/oauth2-callback_pkce_plain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ app.get("/callback", async function (req, res) {
});

app.get("/login", async function (req, res) {
const authUrl = authClient.generateAuthURL({
const authUrl = await authClient.generateAuthURL({
state: STATE,
code_challenge_method: "plain",
code_challenge: "test",
Expand Down
2 changes: 1 addition & 1 deletion examples/oauth2-callback_pkce_s256.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ app.get("/callback", async function (req, res) {
});

app.get("/login", async function (req, res) {
const authUrl = authClient.generateAuthURL({
const authUrl = await authClient.generateAuthURL({
state: STATE,
code_challenge_method: "s256",
});
Expand Down
2 changes: 1 addition & 1 deletion examples/oauth2-public-callback_pkce_s256.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ app.get("/callback", async function (req, res) {
});

app.get("/login", async function (req, res) {
const authUrl = authClient.generateAuthURL({
const authUrl = await authClient.generateAuthURL({
state: STATE,
code_challenge_method: "s256",
});
Expand Down
18 changes: 8 additions & 10 deletions src/OAuth2User.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// Copyright 2021 Twitter, Inc.
// SPDX-License-Identifier: Apache-2.0

import crypto from "crypto";
import { buildQueryString, basicAuthHeader } from "./utils";
import { buildQueryString, basicAuthHeader, base64Encode } from "./utils";
import { AuthClient, AuthHeader } from "./types";
import { RequestOptions, rest } from "./request";

Expand Down Expand Up @@ -63,13 +62,12 @@ export interface RevokeAccessTokenParams {
client_id: string;
}

function sha256(buffer: string) {
return crypto.createHash("sha256").update(buffer).digest();
async function sha256(buffer: string): Promise<Uint8Array> {
return new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(buffer)));
}

function base64URLEncode(str: Buffer) {
return str
.toString("base64")
function base64URLEncode(str: Uint8Array) {
return base64Encode(str)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
Expand Down Expand Up @@ -242,14 +240,14 @@ export class OAuth2User implements AuthClient {
});
}

generateAuthURL(options: GenerateAuthUrlOptions): string {
async generateAuthURL(options: GenerateAuthUrlOptions): Promise<string> {
const { client_id, callback, scopes } = this.#options;
if (!callback) throw new Error("callback required");
if (!scopes) throw new Error("scopes required");
if (options.code_challenge_method === "s256") {
const code_verifier = base64URLEncode(crypto.randomBytes(32));
const code_verifier = base64URLEncode(crypto.getRandomValues(new Uint8Array(32)));
this.#code_verifier = code_verifier;
this.#code_challenge = base64URLEncode(sha256(code_verifier));
this.#code_challenge = base64URLEncode(await sha256(code_verifier));
} else {
this.#code_challenge = options.code_challenge;
this.#code_verifier = options.code_challenge;
Expand Down
8 changes: 5 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ export function buildQueryString(query: Record<string, any>): string {
.join("&");
}

export function base64Encode(byteValues: Uint8Array): string {
return btoa([...byteValues].map(byteValue => String.fromCharCode(byteValue)).join(''))
}

export function basicAuthHeader(client_id: string, client_secret: string) {
return `Basic ${Buffer.from(`${client_id}:${client_secret}`).toString(
"base64"
)}`;
return `Basic ${base64Encode(new TextEncoder().encode(`${client_id}:${client_secret}`))}`
}
15 changes: 15 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright 2021 Twitter, Inc.
// SPDX-License-Identifier: Apache-2.0

import { base64Encode } from "../src/utils";

describe("test utils", () => {

test("base64Encode is equivalent to Buffer.toString('base64')", () => {
for (let i = 0; i < 64; i++) { // go through all 64 symbols
const byteValues = new Uint8Array([i << 2]);
expect(base64Encode(byteValues)).toEqual(Buffer.from(Buffer.from(byteValues)).toString("base64"));
}
});

});