UNPKG

@light-auth/sveltekit

Version:

light auth framework for sveltekit, using arctic

248 lines (240 loc) 10.3 kB
/*! @light-auth/sveltekit v0.3.1 2025-06-13 */ 'use strict'; import { resolveBasePath, DEFAULT_BASE_PATH, createSignoutServerFunction, createSigninServerFunction, createSetUserServerFunction, createFetchUserServerFunction, createFetchSessionServerFunction, createHttpHandlerFunction, buildFullUrl, encryptJwt, buildSecret, getSessionExpirationMaxAge, DEFAULT_SESSION_NAME, decryptJwt } from '@light-auth/core'; import { redirect, json } from '@sveltejs/kit'; const createGetAuthSession = (config) => { const getSession = createFetchSessionServerFunction(config); return async (event) => await getSession({ event }); }; const createSetAuthSession = (config) => { const setSession = createFetchSessionServerFunction(config); return async (event, session) => await setSession({ event, session }); }; const createGetUser = (config) => { const getUser = createFetchUserServerFunction(config); return async (event, providerUserId) => await getUser({ providerUserId, event }); }; const createSetUser = (config) => { const setUser = createSetUserServerFunction(config); return async (event, user) => await setUser({ event, user }); }; function createSignin(config) { const signIn = createSigninServerFunction(config); return async (event, providerName, callbackUrl = "/") => await signIn({ providerName, callbackUrl, event }); } function createSignout(config) { const signOut = createSignoutServerFunction(config); return async (event, revokeToken = false, callbackUrl = "/") => await signOut({ revokeToken, callbackUrl, event }); } const createHandler = (config) => { const lightAuthHandler = createHttpHandlerFunction(config); return { GET: async (event) => { const response = await lightAuthHandler({ event }); return response; }, POST: async (event) => { const response = await lightAuthHandler({ event }); return response; }, }; }; function CreateLightAuth(config) { // check if we are on the server side const isServerSide = typeof window === "undefined"; if (!isServerSide) throw new Error("light-auth-nextjs: DO NOT use this function [CreateLightAuth] on the client side as you may expose sensitive data to the client."); if (!config.providers || config.providers.length === 0) throw new Error("At least one provider is required"); // dynamic imports to avoid error if we are on the client side if (!config.userAdapter && typeof window === "undefined") { import('@light-auth/core/adapters').then((module) => { config.userAdapter = module.createLightAuthUserAdapter({ base: "./users_db", isEncrypted: false }); }); } if (!config.sessionStore && typeof window === "undefined") { Promise.resolve().then(function () { return sveltekitLightAuthSessionStore$1; }).then((module) => { config.sessionStore = module.sveltekitLightAuthSessionStore; }); } if (!config.router && typeof window === "undefined") { Promise.resolve().then(function () { return sveltekitLightAuthRouter$1; }).then((module) => { config.router = module.sveltekitLightAuthRouter; }); } config.env = config.env || process.env; config.basePath = resolveBasePath(config.basePath, config.env); if (!config.env["LIGHT_AUTH_SECRET_VALUE"]) throw new Error("LIGHT_AUTH_SECRET_VALUE is required in environment variables"); return { providers: config.providers, handlers: createHandler(config), basePath: config.basePath || DEFAULT_BASE_PATH, // Default base path for the handlers getAuthSession: createGetAuthSession(config), setAuthSession: createSetAuthSession(config), getUser: createGetUser(config), setUser: createSetUser(config), signIn: createSignin(config), signOut: createSignout(config), }; } const sveltekitLightAuthRouter = { returnJson: function ({ data, init }) { return json(data, { ...(init ?? {}), status: init?.status ?? 200, }); }, getUrl: function ({ endpoint, event, args }) { const url = endpoint ?? event?.url?.toString(); if (!url) throw new Error("light-auth: No url provided and no RequestEvent object available in getUrl of sveltekitLightAuthRouter."); if (url.startsWith("http")) return url; const isServerSide = typeof window === "undefined"; if (!isServerSide) return url; if (!event) return url; const parsedUrl = buildFullUrl({ url, incomingHeaders: event.request.headers }); return parsedUrl.toString(); }, redirectTo: function ({ url, event }) { redirect(302, url); }, getHeaders: function ({ search, event }) { if (!event) return new Headers(); const incomingHeaders = event.request.headers; // Convert search to RegExp if it's a string const regex = typeof search === "string" ? new RegExp(search) : search; // Create a new Headers object to hold filtered headers const filteredHeaders = new Headers(); // Iterate and filter headers whose names match the regex for (const [key, value] of incomingHeaders.entries()) { if (!search || !regex) filteredHeaders.append(key, value); else if (regex.test(key)) { filteredHeaders.append(key, value); } } return filteredHeaders; }, setCookies: function ({ cookies, event, init, }) { if (!event) throw new Error("event is required in setCookies of sveltekitLightAuthRouter"); for (const cookie of cookies ?? []) { event.cookies.set(cookie.name, cookie.value, { httpOnly: cookie.httpOnly, secure: cookie.secure, sameSite: cookie.sameSite, maxAge: cookie.maxAge, path: cookie.path ?? "/", }); } if (init?.headers) { let headersObj = {}; if (init.headers instanceof Headers) { init.headers.forEach((value, key) => { headersObj[key] = value; }); } else if (Array.isArray(init.headers)) { for (const [key, value] of init.headers) { headersObj[key] = value; } } else { headersObj = { ...init.headers }; } event.setHeaders(headersObj); } }, getCookies: function ({ search, event }) { if (!event) throw new Error("RequestEvent is required in getCookies of sveltekitLightAuthRouter"); const cookies = []; const regex = typeof search === "string" ? new RegExp(search) : search; for (const { name, value } of event.cookies.getAll()) { if (!search || !regex || regex.test(name)) cookies.push({ name: name, value: value || "" }); } return cookies; }, getRequest: function ({ event }) { if (!event) throw new Error("RequestEvent is required in getRequest of sveltekitLightAuthRouter"); return event.request; }, }; var sveltekitLightAuthRouter$1 = /*#__PURE__*/Object.freeze({ __proto__: null, sveltekitLightAuthRouter: sveltekitLightAuthRouter }); /** * A concrete CookieStore implementation for Node.js server-side, * using the 'cookie' npm package and returning Response objects * with appropriate Set-Cookie headers. */ const sveltekitLightAuthSessionStore = { async getSession(args) { const { env, event } = args; if (!env) throw new Error("light-auth: Env is required in getSession of sveltekitLightAuthSessionStore"); if (!event) throw new Error("light-auth: Request is required in getSession of sveltekitLightAuthSessionStore"); const sessionCookie = event.cookies.get(DEFAULT_SESSION_NAME); if (!sessionCookie) return null; try { const decryptedSession = await decryptJwt(sessionCookie, buildSecret(env)); return decryptedSession; } catch (error) { console.error("Failed to decrypt session cookie:", error); return null; } }, async deleteSession(args) { const { event } = args; if (!event) throw new Error("light-auth: Request is required in deleteSession of sveltekitLightAuthSessionStore"); event.cookies.set(DEFAULT_SESSION_NAME, "", { maxAge: 0, path: "/", }); }, async setSession(args) { const { env, session, event } = args; if (!env) throw new Error("light-auth: Env is required in setSession of sveltekitLightAuthSessionStore"); if (!event) throw new Error("light-auth: Request is required in setSession of sveltekitLightAuthSessionStore"); const value = await encryptJwt(session, buildSecret(env)); // Check the size of the cookie value in bytes const encoder = new TextEncoder(); const valueBytes = encoder.encode(value); if (valueBytes.length > 4096) throw new Error("light-auth: Cookie value exceeds 4096 bytes, which may not be supported by your browser."); // get the cookie expiration time const maxAge = getSessionExpirationMaxAge(); // 30 days if no env var is set // maxAge: Specifies the number (in seconds) to be the value for the `Max-Age` event.cookies.set(DEFAULT_SESSION_NAME, value, { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: maxAge, }); return session; }, generateSessionId() { return Math.random().toString(36).slice(2); }, }; var sveltekitLightAuthSessionStore$1 = /*#__PURE__*/Object.freeze({ __proto__: null, sveltekitLightAuthSessionStore: sveltekitLightAuthSessionStore }); export { CreateLightAuth, sveltekitLightAuthRouter, sveltekitLightAuthSessionStore }; //# sourceMappingURL=index.mjs.map