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

Support Cloudflare Workers #78

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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"private": false,
"dependencies": {
"cookie": "^0.4.1",
"jsonwebtoken": "^8.5.1"
"jose": "^4.6.0"
},
"devDependencies": {
"@rollup/plugin-typescript": "^8.2.1",
Expand Down
38 changes: 20 additions & 18 deletions src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import type { GetSession, RequestHandler } from "@sveltejs/kit";
import type { EndpointOutput } from "@sveltejs/kit/types/endpoint";
import { RequestEvent } from "@sveltejs/kit/types/hooks";
import cookie from "cookie";
import * as jsonwebtoken from "jsonwebtoken";
import { JWTPayload, jwtVerify, KeyLike, SignJWT } from "jose";
import { base64Encode } from "./helpers";
import type { JWT, Session } from "./interfaces";
import { join } from "./path";
import type { Provider } from "./providers";
Expand Down Expand Up @@ -31,17 +32,19 @@ export class Auth {
return this.config?.basePath ?? "/api/auth";
}

getJwtSecret() {
getJwtSecret(): Uint8Array | KeyLike {
const encoder = new TextEncoder();

if (this.config?.jwtSecret) {
return this.config?.jwtSecret;
return encoder.encode(this.config?.jwtSecret);
}

if (this.config?.providers?.length) {
const provs = this.config?.providers?.map((provider) => provider.id).join("+");
return Buffer.from(provs).toString("base64");
return encoder.encode(base64Encode(provs));
}

return "svelte_auth_secret";
return encoder.encode("svelte_auth_secret");
}

async getToken(headers: any) {
Expand All @@ -55,10 +58,11 @@ export class Auth {
return null;
}

let token: JWT;
let token: JWTPayload & JWT;
try {
token = (jsonwebtoken.verify(cookies.svelteauthjwt, this.getJwtSecret()) || {}) as JWT;
} catch {
token = ((await jwtVerify(cookies.svelteauthjwt, this.getJwtSecret())) || {})
.payload as JWTPayload & JWT;
} catch (e) {
return null;
}

Expand Down Expand Up @@ -94,14 +98,12 @@ export class Auth {
};
}

signToken(token: JWT) {
const opts = !token.exp
? {
expiresIn: this.config?.jwtExpiresIn ?? "30d",
}
: {};
const jwt = jsonwebtoken.sign(token, this.getJwtSecret(), opts);
return jwt;
async signToken(token: JWT) {
const jwt = new SignJWT(token).setProtectedHeader({ alg: "HS256", typ: "JWT" });
if (!token.exp) {
jwt.setExpirationTime(this.config?.jwtExpiresIn ?? "30d");
}
return jwt.sign(this.getJwtSecret());
}

async getRedirectUrl(host: string, redirectUrl?: string) {
Expand All @@ -124,7 +126,7 @@ export class Auth {
token = this.setToken(headers, { user: profile });
}

const jwt = this.signToken(token);
const jwt = await this.signToken(token);
const redirect = await this.getRedirectUrl(url.host, redirectUrl ?? undefined);

return {
Expand All @@ -142,7 +144,7 @@ export class Auth {

if (url.pathname === this.getPath("signout")) {
const token = this.setToken(event.request.headers, {});
const jwt = this.signToken(token);
const jwt = await this.signToken(token);

if (method === "POST") {
return {
Expand Down
14 changes: 14 additions & 0 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
export function ucFirst(val: string) {
return val.charAt(0).toUpperCase() + val.slice(1);
}

export function base64Encode(str: string): string {
if (typeof btoa === 'undefined') {
return Buffer.from(str).toString('base64');
}
return btoa(str);
}

export function base64Decode(str: string): string {
if (typeof atob === 'undefined') {
return Buffer.from(str, 'base64').toString();
}
return atob(str);
}
5 changes: 3 additions & 2 deletions src/providers/oauth2.base.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { EndpointOutput } from "@sveltejs/kit/types/endpoint";
import { RequestEvent } from "@sveltejs/kit/types/hooks";
import { base64Encode, base64Decode } from "../helpers";
import type { Auth } from "../auth";
import type { CallbackResult } from "../types";
import { Provider, ProviderConfig } from "./base";
Expand Down Expand Up @@ -39,7 +40,7 @@ export abstract class OAuth2BaseProvider<
const state = [
`redirect=${url.searchParams.get("redirect") ?? this.getUri(auth, "/", url.host)}`,
].join(",");
const base64State = Buffer.from(state).toString("base64");
const base64State = base64Encode(state);
const nonce = Math.round(Math.random() * 1000).toString(); // TODO: Generate random based on user values
const authUrl = await this.getAuthorizationUrl(event, auth, base64State, nonce);

Expand All @@ -61,7 +62,7 @@ export abstract class OAuth2BaseProvider<

getStateValue(query: URLSearchParams, name: string) {
if (query.get("state")) {
const state = Buffer.from(query.get("state")!, "base64").toString();
const state = base64Decode(query.get("state")!);
return state
.split(",")
.find((state) => state.startsWith(`${name}=`))
Expand Down
3 changes: 2 additions & 1 deletion src/providers/reddit.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { base64Encode } from "../helpers";
import { OAuth2Provider, OAuth2ProviderConfig } from "./oauth2";

export interface RedditProfile {
Expand Down Expand Up @@ -228,7 +229,7 @@ export class RedditOAuth2Provider extends OAuth2Provider<
headers: {
...config.headers,
Authorization:
"Basic " + Buffer.from(`${config.apiKey}:${config.apiSecret}`).toString("base64"),
"Basic " + base64Encode(`${config.apiKey}:${config.apiSecret}`),
},
authorizationParams: {
...config.authorizationParams,
Expand Down
95 changes: 5 additions & 90 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1357,11 +1357,6 @@ browserslist@^4.17.5, browserslist@^4.19.1:
node-releases "^2.0.2"
picocolors "^1.0.0"

[email protected]:
version "1.0.1"
resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819"
integrity sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=

buffer-from@^1.0.0:
version "1.1.2"
resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5"
Expand Down Expand Up @@ -1528,13 +1523,6 @@ doctrine@^3.0.0:
dependencies:
esutils "^2.0.2"

[email protected]:
version "1.0.11"
resolved "https://registry.yarnpkg.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz#ae0f0fa2d85045ef14a817daa3ce9acd0489e5bf"
integrity sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==
dependencies:
safe-buffer "^5.0.1"

electron-to-chromium@^1.4.71:
version "1.4.71"
resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.71.tgz#17056914465da0890ce00351a3b946fd4cd51ff6"
Expand Down Expand Up @@ -2102,6 +2090,11 @@ isobject@^3.0.1:
resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df"
integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8=

jose@^4.6.0:
version "4.6.0"
resolved "https://registry.yarnpkg.com/jose/-/jose-4.6.0.tgz#f3ff007ddcbce462c091d3d41b7af2e35dec348c"
integrity sha512-0hNAkhMBNi4soKSAX4zYOFV+aqJlEz/4j4fregvasJzEVtjDChvWqRjPvHwLqr5hx28Ayr6bsOs1Kuj87V0O8w==

joycon@^3.0.1:
version "3.1.1"
resolved "https://registry.yarnpkg.com/joycon/-/joycon-3.1.1.tgz#bce8596d6ae808f8b68168f5fc69280996894f03"
Expand Down Expand Up @@ -2157,39 +2150,6 @@ jsonc-parser@^3.0.0:
resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.0.0.tgz#abdd785701c7e7eaca8a9ec8cf070ca51a745a22"
integrity sha512-fQzRfAbIBnR0IQvftw9FJveWiHp72Fg20giDrHz6TdfB12UH/uue0D3hm57UB5KgAVuniLMCaS8P1IMj9NR7cA==

jsonwebtoken@^8.5.1:
version "8.5.1"
resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz#00e71e0b8df54c2121a1f26137df2280673bcc0d"
integrity sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==
dependencies:
jws "^3.2.2"
lodash.includes "^4.3.0"
lodash.isboolean "^3.0.3"
lodash.isinteger "^4.0.4"
lodash.isnumber "^3.0.3"
lodash.isplainobject "^4.0.6"
lodash.isstring "^4.0.1"
lodash.once "^4.0.0"
ms "^2.1.1"
semver "^5.6.0"

jwa@^1.4.1:
version "1.4.1"
resolved "https://registry.yarnpkg.com/jwa/-/jwa-1.4.1.tgz#743c32985cb9e98655530d53641b66c8645b039a"
integrity sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==
dependencies:
buffer-equal-constant-time "1.0.1"
ecdsa-sig-formatter "1.0.11"
safe-buffer "^5.0.1"

jws@^3.2.2:
version "3.2.2"
resolved "https://registry.yarnpkg.com/jws/-/jws-3.2.2.tgz#001099f3639468c9414000e99995fa52fb478304"
integrity sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==
dependencies:
jwa "^1.4.1"
safe-buffer "^5.0.1"

kind-of@^6.0.2:
version "6.0.3"
resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd"
Expand Down Expand Up @@ -2221,46 +2181,11 @@ lodash.debounce@^4.0.8:
resolved "https://registry.yarnpkg.com/lodash.debounce/-/lodash.debounce-4.0.8.tgz#82d79bff30a67c4005ffd5e2515300ad9ca4d7af"
integrity sha1-gteb/zCmfEAF/9XiUVMArZyk168=

lodash.includes@^4.3.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/lodash.includes/-/lodash.includes-4.3.0.tgz#60bb98a87cb923c68ca1e51325483314849f553f"
integrity sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=

lodash.isboolean@^3.0.3:
version "3.0.3"
resolved "https://registry.yarnpkg.com/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz#6c2e171db2a257cd96802fd43b01b20d5f5870f6"
integrity sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=

lodash.isinteger@^4.0.4:
version "4.0.4"
resolved "https://registry.yarnpkg.com/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz#619c0af3d03f8b04c31f5882840b77b11cd68343"
integrity sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=

lodash.isnumber@^3.0.3:
version "3.0.3"
resolved "https://registry.yarnpkg.com/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz#3ce76810c5928d03352301ac287317f11c0b1ffc"
integrity sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=

lodash.isplainobject@^4.0.6:
version "4.0.6"
resolved "https://registry.yarnpkg.com/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz#7c526a52d89b45c45cc690b88163be0497f550cb"
integrity sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=

lodash.isstring@^4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/lodash.isstring/-/lodash.isstring-4.0.1.tgz#d527dfb5456eca7cc9bb95d5daeaf88ba54a5451"
integrity sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=

lodash.merge@^4.6.2:
version "4.6.2"
resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a"
integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==

lodash.once@^4.0.0:
version "4.1.1"
resolved "https://registry.yarnpkg.com/lodash.once/-/lodash.once-4.1.1.tgz#0dd3971213c7c56df880977d504c88fb471a97ac"
integrity sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=

lodash.truncate@^4.4.2:
version "4.4.2"
resolved "https://registry.yarnpkg.com/lodash.truncate/-/lodash.truncate-4.4.2.tgz#5a350da0b1113b837ecfffd5812cbe58d6eae193"
Expand Down Expand Up @@ -2335,11 +2260,6 @@ [email protected]:
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==

ms@^2.1.1:
version "2.1.3"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2"
integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==

nanoid@^3.2.0:
version "3.3.1"
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.1.tgz#6347a18cac88af88f58af0b3594b723d5e99bb35"
Expand Down Expand Up @@ -2661,11 +2581,6 @@ sade@^1.7.4:
dependencies:
mri "^1.1.0"

safe-buffer@^5.0.1:
version "5.2.1"
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6"
integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==

safe-buffer@~5.1.1:
version "5.1.2"
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"
Expand Down