diff --git a/README.md b/README.md index 0986a12..74acad7 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ SvelteKitAuth also comes with first-class support for Typescript out of the box, SvelteKitAuth is very easy to setup! All you need to do is instantiate the `SvelteKitAuth` class, and configure it with some default providers, as well as a JWT secret key used to verify the cookies: -_**Warning**: env variables prefixed with `VITE_` can be exposed and leaked into client-side bundles if they are referenced in any client-side code. Make sure this is not the case, or consider using an alternative method such as loading them via dotenv directly instead._ +_**Warning**: env variables prefixed with `VITE_` can be exposed and leaked into client-side bundles if they are referenced in any client-side code. Make sure this is not the case, or consider using an alternative method such as loading them via dotenv directly instead.\_ ```ts export const appAuth = new SvelteKitAuth({ diff --git a/app/package.json b/app/package.json index 4659d25..f5c792f 100644 --- a/app/package.json +++ b/app/package.json @@ -5,7 +5,7 @@ "dev": "svelte-kit dev", "build": "svelte-kit build", "preview": "svelte-kit preview", - "lint": "prettier --check --plugin-search-dir=. . && eslint --ignore-path .gitignore .", + "lint": "prettier --check --plugin-search-dir=. . && eslint --ignore-path .gitignore --config .eslintrc.cjs .", "format": "prettier --write --plugin-search-dir=. ." }, "devDependencies": { diff --git a/app/yarn.lock b/app/yarn.lock index dfa041d..6665d82 100644 --- a/app/yarn.lock +++ b/app/yarn.lock @@ -3441,12 +3441,6 @@ simple-swizzle@^0.2.2: cookie "^0.4.1" jsonwebtoken "^8.5.1" -"sk-auth@file:../": - version "0.3.7" - dependencies: - cookie "^0.4.1" - jsonwebtoken "^8.5.1" - slash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" diff --git a/package.json b/package.json index d013fd1..4d981d9 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,7 @@ }, "devDependencies": { "@rollup/plugin-typescript": "^8.2.1", - "@sveltejs/kit": "^1.0.0-next.107", + "@sveltejs/kit": "^1.0.0-next.211", "@types/jsonwebtoken": "^8.5.1", "@typescript-eslint/eslint-plugin": "^4.23.0", "@typescript-eslint/parser": "^4.23.0", diff --git a/src/auth.ts b/src/auth.ts index 5cfc383..fe1fd58 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,6 +1,7 @@ import type { GetSession, RequestHandler } from "@sveltejs/kit"; -import type { EndpointOutput, ServerRequest } from "@sveltejs/kit/types/endpoint"; -import type { Headers } from "@sveltejs/kit/types/helper"; +import type { EndpointOutput } from "@sveltejs/kit/types/endpoint"; +import { RequestHeaders } from "@sveltejs/kit/types/helper"; +import { ServerRequest } from "@sveltejs/kit/types/hooks"; import cookie from "cookie"; import * as jsonwebtoken from "jsonwebtoken"; import type { JWT, Session } from "./interfaces"; @@ -43,7 +44,7 @@ export class Auth { return "svelte_auth_secret"; } - async getToken(headers: Headers) { + async getToken(headers: RequestHeaders) { if (!headers.cookie) { return null; } @@ -82,7 +83,7 @@ export class Auth { return new URL(pathname, this.getBaseUrl(host)).href; } - setToken(headers: Headers, newToken: JWT | any) { + setToken(headers: RequestHeaders, newToken: JWT | any) { const originalToken = this.getToken(headers); return { @@ -113,7 +114,7 @@ export class Auth { request: ServerRequest, provider: Provider, ): Promise { - const { headers, host } = request; + const { headers, url } = request; const [profile, redirectUrl] = await provider.callback(request, this); let token = (await this.getToken(headers)) ?? { user: {} }; @@ -124,7 +125,7 @@ export class Auth { } const jwt = this.signToken(token); - const redirect = await this.getRedirectUrl(host, redirectUrl ?? undefined); + const redirect = await this.getRedirectUrl(url.host, redirectUrl ?? undefined); return { status: 302, @@ -136,9 +137,9 @@ export class Auth { } async handleEndpoint(request: ServerRequest): Promise { - const { path, headers, method, host } = request; + const { headers, method, url } = request; - if (path === this.getPath("signout")) { + if (url.pathname === this.getPath("signout")) { const token = this.setToken(headers, {}); const jwt = this.signToken(token); @@ -153,7 +154,7 @@ export class Auth { }; } - const redirect = await this.getRedirectUrl(host); + const redirect = await this.getRedirectUrl(url.host); return { status: 302, @@ -165,7 +166,7 @@ export class Auth { } const regex = new RegExp(join([this.basePath, `(?signin|callback)/(?\\w+)`])); - const match = path.match(regex); + const match = url.pathname.match(regex); if (match && match.groups) { const provider = this.config?.providers?.find( @@ -187,11 +188,11 @@ export class Auth { } get: RequestHandler = async (request) => { - const { path } = request; + const { url } = request; - if (path === this.getPath("csrf")) { + if (url.pathname === this.getPath("csrf")) { return { body: "1234" }; // TODO: Generate real token - } else if (path === this.getPath("session")) { + } else if (url.pathname === this.getPath("session")) { const session = await this.getSession(request); return { body: { diff --git a/src/client/signIn.ts b/src/client/signIn.ts index 7cc3ba3..c6b372d 100644 --- a/src/client/signIn.ts +++ b/src/client/signIn.ts @@ -1,6 +1,6 @@ /* import { goto } from "@sveltejs/kit/assets/runtime/app/navigation"; import { page } from "@sveltejs/kit/assets/runtime/app/stores"; */ -import type { Page } from "@sveltejs/kit"; +import type { LoadInput } from "@sveltejs/kit"; interface SignInConfig { redirectUrl?: string; @@ -23,10 +23,10 @@ export async function signIn(provider: string, data?: any, config?: SignInConfig if (config?.redirectUrl) { redirectUrl = config.redirectUrl; } else { - let $val: Page | undefined; + let $val: LoadInput | undefined; /* page.subscribe(($) => ($val = $))(); */ if ($val) { - redirectUrl = `${$val.host}${$val.path}?${$val.query}`; + redirectUrl = `${$val.url.host}${$val.url.pathname}?${$val.url.searchParams}`; } } diff --git a/src/providers/base.ts b/src/providers/base.ts index ce83396..f678d36 100644 --- a/src/providers/base.ts +++ b/src/providers/base.ts @@ -1,5 +1,5 @@ import type { EndpointOutput } from "@sveltejs/kit"; -import type { ServerRequest } from "@sveltejs/kit/types/endpoint"; +import { ServerRequest } from "@sveltejs/kit/types/hooks"; import type { Auth } from "../auth"; import type { CallbackResult } from "../types"; diff --git a/src/providers/oauth2.base.ts b/src/providers/oauth2.base.ts index 303b077..5f94029 100644 --- a/src/providers/oauth2.base.ts +++ b/src/providers/oauth2.base.ts @@ -1,4 +1,5 @@ -import type { EndpointOutput, ServerRequest } from "@sveltejs/kit/types/endpoint"; +import type { EndpointOutput } from "@sveltejs/kit/types/endpoint"; +import { ServerRequest } from "@sveltejs/kit/types/hooks"; import type { Auth } from "../auth"; import type { CallbackResult } from "../types"; import { Provider, ProviderConfig } from "./base"; @@ -33,16 +34,18 @@ export abstract class OAuth2BaseProvider< abstract getUserProfile(tokens: any): ProfileType | Promise; async signin(request: ServerRequest, auth: Auth): Promise { - const { method, host, query } = request; - const state = [`redirect=${query.get("redirect") ?? this.getUri(auth, "/", host)}`].join(","); + const { method, url } = request; + const state = [ + `redirect=${url.searchParams.get("redirect") ?? this.getUri(auth, "/", url.host)}`, + ].join(","); const base64State = Buffer.from(state).toString("base64"); const nonce = Math.round(Math.random() * 1000).toString(); // TODO: Generate random based on user values - const url = await this.getAuthorizationUrl(request, auth, base64State, nonce); + const authUrl = await this.getAuthorizationUrl(request, auth, base64State, nonce); if (method === "POST") { return { body: { - redirect: url, + redirect: authUrl, }, }; } @@ -50,7 +53,7 @@ export abstract class OAuth2BaseProvider< return { status: 302, headers: { - Location: url, + Location: authUrl, }, }; } @@ -65,17 +68,17 @@ export abstract class OAuth2BaseProvider< } } - async callback({ query, host }: ServerRequest, auth: Auth): Promise { - const code = query.get("code"); - const redirect = this.getStateValue(query, "redirect"); + async callback({ url }: ServerRequest, auth: Auth): Promise { + const code = url.searchParams.get("code"); + const redirect = this.getStateValue(url.searchParams, "redirect"); - const tokens = await this.getTokens(code!, this.getCallbackUri(auth, host)); + const tokens = await this.getTokens(code!, this.getCallbackUri(auth, url.host)); let user = await this.getUserProfile(tokens); if (this.config.profile) { user = await this.config.profile(user, tokens); } - return [user, redirect ?? this.getUri(auth, "/", host)]; + return [user, redirect ?? this.getUri(auth, "/", url.host)]; } } diff --git a/src/providers/oauth2.ts b/src/providers/oauth2.ts index 391fb63..2ff400b 100644 --- a/src/providers/oauth2.ts +++ b/src/providers/oauth2.ts @@ -1,4 +1,4 @@ -import type { ServerRequest } from "@sveltejs/kit/types/endpoint"; +import { ServerRequest } from "@sveltejs/kit/types/hooks"; import type { Auth } from "../auth"; import { ucFirst } from "../helpers"; import { OAuth2BaseProvider, OAuth2BaseProviderConfig, OAuth2Tokens } from "./oauth2.base"; @@ -37,19 +37,19 @@ export class OAuth2Provider< }); } - getAuthorizationUrl({ host }: ServerRequest, auth: Auth, state: string, nonce: string) { + getAuthorizationUrl({ url }: ServerRequest, auth: Auth, state: string, nonce: string) { const data = { state, nonce, response_type: this.config.responseType, client_id: this.config.clientId, scope: Array.isArray(this.config.scope) ? this.config.scope.join(" ") : this.config.scope!, - redirect_uri: this.getCallbackUri(auth, host), + redirect_uri: this.getCallbackUri(auth, url.host), ...(this.config.authorizationParams ?? {}), }; - const url = `${this.config.authorizationUrl}?${new URLSearchParams(data)}`; - return url; + const authUrl = `${this.config.authorizationUrl}?${new URLSearchParams(data)}`; + return authUrl; } async getTokens(code: string, redirectUri: string): Promise { diff --git a/src/providers/twitter.ts b/src/providers/twitter.ts index b6a5696..9649e83 100644 --- a/src/providers/twitter.ts +++ b/src/providers/twitter.ts @@ -1,4 +1,4 @@ -import type { ServerRequest } from "@sveltejs/kit/types/endpoint"; +import { ServerRequest } from "@sveltejs/kit/types/hooks"; import type { Auth } from "../auth"; import type { CallbackResult } from "../types"; import { OAuth2BaseProvider, OAuth2BaseProviderConfig } from "./oauth2.base"; @@ -38,17 +38,17 @@ export class TwitterAuthProvider extends OAuth2BaseProvider { - const oauthToken = query.get("oauth_token"); - const oauthVerifier = query.get("oauth_verifier"); - const redirect = this.getStateValue(query, "redirect"); + async callback({ url }: ServerRequest, auth: Auth): Promise { + const oauthToken = url.searchParams.get("oauth_token"); + const oauthVerifier = url.searchParams.get("oauth_verifier"); + const redirect = this.getStateValue(url.searchParams, "redirect"); const tokens = await this.getTokens(oauthToken!, oauthVerifier!); let user = await this.getUserProfile(tokens); @@ -83,6 +83,6 @@ export class TwitterAuthProvider extends OAuth2BaseProvider