Code Monkey home page Code Monkey logo

lucia's Introduction

Lucia

Lucia is an auth library written in TypeScript that abstracts away the complexity of handling sessions. It works alongside your database to provide an API that's easy to use, understand, and extend.

  • No more endless configuration and callbacks
  • Fully typed
  • Works in any runtime - Node.js, Bun, Deno, Cloudflare Workers
  • Extensive database support out of the box
import { Lucia } from "lucia";

const lucia = new Lucia(new Adapter(db));

const session = await lucia.createSession(userId, {});
await lucia.validateSession(session.id);

Lucia is an open source library released under the MIT license, with the help of 100+ contributors!

Resources

Documentation

Join the Discord server!

Examples

Changelog

Installation

npm i lucia
pnpm add lucia
yarn add lucia

lucia's People

Contributors

adriangonz97 avatar blastose avatar brilliantdeviation7 avatar danawoodman avatar dawidmachon avatar dmitryscaletta avatar faeyumbrea avatar ffss92 avatar fredtreg avatar gtim avatar gustavocadev avatar jings avatar josefaidt avatar jouandeag avatar kazuumin avatar lucythecat avatar machina20 avatar moshetanzer avatar ollema avatar oscartbeaumont avatar pilcrowonpaper avatar rhenaldkarrel avatar schweden1997 avatar simonsarris avatar skepticmystic avatar sooditk avatar stewartside avatar tazorde avatar v-rogg avatar xanderbarkhatov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lucia's Issues

[BUG] Example application exposing app secret to client

Bug report

Report for: https://github.com/pilcrowOnPaper/lucia-sveltekit/blob/main/test-apps/username-password/src/lib/server/lucia.ts

Currently, the example documentation suggests that we should prefix the LUCIA_SECRET with VITE_. This prefix effectively lets Sveltekit to leak the secret to the client as explained in the vite documentation here: https://vitejs.dev/guide/env-and-mode.html#env-files

Current behavior

LUCIA_SECRET is leaking to the client codde

Expected behavior

We should simply remove the VITE_ prefix in the example documentation to help newcomers and unsuspecting developers.

Additional info

I am willing to open a simple PR, simply give me the go ahead.

Version

main branch

Mongodb adapter: E11000 duplicate key error collection: refresh_tokens index: id_1 dup key: { id: null }

Hey :)

Everything was working fine yesterday, but now when I try to login to an existing account, I get this error:

 E11000 duplicate key error collection: tmqsk.refresh_tokens index: id_1 dup key: { id: null }

Singing up a new user works, siging in with the wrong password gives the correct error.
But signing in with the right password does not work.

The error arises when the adapter runs setRefreshToken

setRefreshToken: async (refreshToken, userId) => {
            try {
                const refreshTokenDoc = new RefreshToken({
                    refresh_token: refreshToken,
                    user_id: userId,
                });
                await refreshTokenDoc.save();
            }
            catch (e) {
                console.error(e);
                throw new Error("DATABASE_UPDATE_FAILED");
            }
        },

The error is saying there is a duplicate key error, and the key it is trying to set is null, meaning either the refreshToken value is null, or userId is.
I'm not quite sure what to do, I've not changed how I log in

TypeError when building

Description

When building a pretty bare-bones app using adapter-auto, set up exactly according to the docs, the build fails with the below stacktrace. Building with adapter-node succeeds, but every page gives the same error 500.

Running in development mode works flawlessly. Building locally and running in preview mode also works.

Stacktrace

✓ 87 modules transformed.
.svelte-kit/output/server/vite-manifest.json                                 4.79 KiB
.svelte-kit/output/server/index.js                                           60.08 KiB
.svelte-kit/output/server/entries/endpoints/admin/dashboard/api/_server.js   4.24 KiB
.svelte-kit/output/server/entries/pages/_layout.svelte.js                    5.89 KiB
.svelte-kit/output/server/entries/pages/_layout.server.js                    0.31 KiB
.svelte-kit/output/server/entries/fallbacks/error.svelte.js                  0.60 KiB
.svelte-kit/output/server/entries/pages/admin/_layout.svelte.js              0.23 KiB
.svelte-kit/output/server/entries/pages/_page.svelte.js                      4.16 KiB
.svelte-kit/output/server/entries/pages/_page.js                             0.36 KiB
.svelte-kit/output/server/entries/pages/_page.server.js                      1.33 KiB
.svelte-kit/output/server/entries/pages/admin/dashboard/_page.svelte.js      16.78 KiB
.svelte-kit/output/server/entries/pages/admin/dashboard/_page.js             1.31 KiB
.svelte-kit/output/server/entries/pages/admin/login/_page.svelte.js          1.19 KiB
.svelte-kit/output/server/entries/pages/admin/login/_page.server.js          1.31 KiB
.svelte-kit/output/server/entries/pages/admin/register/_page.svelte.js       1.93 KiB
.svelte-kit/output/server/entries/pages/admin/register/_page.server.js       0.93 KiB
.svelte-kit/output/server/chunks/env-private.js                              0.12 KiB
.svelte-kit/output/server/chunks/env-public.js                               0.12 KiB
.svelte-kit/output/server/chunks/index.js                                    4.23 KiB
.svelte-kit/output/server/chunks/index2.js                                   0.73 KiB
.svelte-kit/output/server/chunks/index3.js                                   1.29 KiB
.svelte-kit/output/server/chunks/supabase.js                                 0.24 KiB
.svelte-kit/output/server/chunks/utils.js                                    0.22 KiB
.svelte-kit/output/server/chunks/lucia.js                                    24.95 KiB
.svelte-kit/output/server/chunks/errors.js                                   0.09 KiB
.svelte-kit/output/server/chunks/stores.js                                   1.00 KiB
.svelte-kit/output/server/chunks/hooks.js                                    0.28 KiB
undefined
TypeError [ERR_INVALID_ARG_TYPE]: The "password" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined
    at check (node:internal/crypto/scrypt:89:14)
    at Object.scryptSync (node:internal/crypto/scrypt:70:13)
    at new Encrypter (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:25:23)
    at new EncryptedRefreshToken (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:163:22)
    at handleTokens (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:333:35)
    at handleTokens (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:685:46)
    at apply_handle (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:54:14)
    at file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:51:12
    at Object.handleAuth [as handle] (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:696:61)
    at respond (file:///home/x/x/asclepius/.svelte-kit/output/server/index.js:1611:42)
TypeError [ERR_INVALID_ARG_TYPE]: The "password" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined
    at check (node:internal/crypto/scrypt:89:14)
    at Object.scryptSync (node:internal/crypto/scrypt:70:13)
    at new Encrypter (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:25:23)
    at new EncryptedRefreshToken (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:163:22)
    at handleTokens (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:333:35)
    at handleTokens (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:685:46)
    at apply_handle (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:54:14)
    at file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:51:12
    at Object.handleAuth [as handle] (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:696:61)
    at respond (file:///home/x/x/asclepius/.svelte-kit/output/server/index.js:1611:42)
TypeError [ERR_INVALID_ARG_TYPE]: The "password" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined
    at check (node:internal/crypto/scrypt:89:14)
    at Object.scryptSync (node:internal/crypto/scrypt:70:13)
    at new Encrypter (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:25:23)
    at new EncryptedRefreshToken (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:163:22)
    at handleTokens (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:333:35)
    at handleTokens (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:685:46)
    at apply_handle (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:54:14)
    at file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:51:12
    at Object.handleAuth [as handle] (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:696:61)
    at respond (file:///home/x/x/asclepius/.svelte-kit/output/server/index.js:1611:42)
TypeError [ERR_INVALID_ARG_TYPE]: The "password" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined
    at check (node:internal/crypto/scrypt:89:14)
    at Object.scryptSync (node:internal/crypto/scrypt:70:13)
    at new Encrypter (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:25:23)
    at new EncryptedRefreshToken (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:163:22)
    at handleTokens (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:333:35)
    at handleTokens (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:685:46)
    at apply_handle (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:54:14)
    at file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:51:12
    at Object.handleAuth [as handle] (file:///home/x/x/asclepius/.svelte-kit/output/server/chunks/lucia.js:696:61)
    at respond (file:///home/x/x/asclepius/.svelte-kit/output/server/index.js:1611:42)
file:///home/x/x/asclepius/node_modules/@sveltejs/kit/src/core/prerender/prerender.js:48
				throw new Error(format_error(details, config));
				      ^

Error: 500 /
at file:///home/x/x/asclepius/node_modules/@sveltejs/kit/src/core/prerender/prerender.js:48:11
at save (file:///home/x/x/asclepius/node_modules/@sveltejs/kit/src/core/prerender/prerender.js:336:4)
at visit (file:///home/x/x/asclepius/node_modules/@sveltejs/kit/src/core/prerender/prerender.js:223:3)

Page error

500
The "password" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined
TypeError [ERR_INVALID_ARG_TYPE]: The "password" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined

Platform

  • OS: Fails on Arch and Ubuntu
  • Node: 18.7.0
  • lucia-sveltekit: 0.7.1
  • svelte: 3.49.0
  • vite: 3.0.9
  • lucia-sveltekit/adapter-supabase: 0.3.1
  • sveltejs/kit: 1.0.0-next.442

[Feature]: How to get current session from server endpoint

Hello this might be a stupid question but I don't see how to do this in the docs.

I don't mean how to use the handleServerLoad function but instead how to get the current session when in an api endpoint as in for example inside a post function inside a "+server.js/ts" file.
Is it possible? If so how?

Thanks

[Feature]: Add links to types in docs

Feature request

Feature Request for: documentation

For type ref:

const f: (i: Input) => Output

It would be nice if Input and Output are links to their reference page

Use case

Easier to use the docs

Additional notes

none.

AUTH_INVALID_ACCESS_TOKEN in page endpoints using Prisma adapter

Hi,

I'm unsure how to fix this error when accessing data in load function/page endpoint.
The docs say:

The access token should be send as a bearer token in the authorization header. Lucia does not rely on http-only cookies to verify the user in endpoints to prevent CSRF attacks.

How would this work with the a page endpoint that calls e.g.

export const GET: RequestHandler = async ({ request }) => {
	try {
		await auth.validateRequest(request);
		...

Thanks for your help!

Documentation - Hook configuration

In the documentation, the suggested code to be added to the hooks file is invalid.

Currently it is:

export handle = auth.authHandle
export getSession = auth.getAuthSession

however I believe it should be

import { auth } from '$lib/lucia';

export const handle = auth.handleAuth;
export const getSession = auth.getAuthSession;

You are missing the const for the variables, and also the auth handler is handleAuth rather than authHandle.

[Feature]: Get session outside of wrapper component

Feature request

Feature Request for: Lucia

Getting session store using getSession cannot be done outside of Lucia.svelte wrapper. While this makes sense, it makes it impossible to get the store in the layout component that wrapper is located in. It would be nice to be able to get the session without having a dependency on the wrapper.

Use case

General

Additional notes

None

AUTH_INVALID_ACCESS_TOKEN on sign out

I'm using Lucia with the prisma adapter, and working the OAuth example (using the Amazon Cognito hosted UI). I have sign in working, but I'm not sure how to get the sign out to work. When I call signOut(access_token), I get a 500 from /api/auth/logout with an AUTH_INVALID_ACCESS_TOKEN.

`
import { getSession, signOut } from "lucia-sveltekit/client";
const lucia = getSession();

async function signOutUser() {
await signOut($lucia.access_token);
// this function calls the cognito signout
const response = await logout();
};
`
Is there something I need to do because I'm using OAuth? I'm not totally sure how the flow should work. Thanks!

[BUG] pageDataFunctionRegex not capturing hydrate.data

Bug report

Report for: 0.9.0

Regex in auth/hooks.js does not always capture <script type="module" data-sveltekit-hydrate="">

Current behavior

On my homepage, window._lucia_page_data is present. However, on some other pages, it is undefined. This is causing $session to be empty, breaking other features such as signOut.

Expected behavior

window._lucia_page_data is defined regardless of what other page data is used in sveltekit

Possible cause

const pageDataFunctionRegex = new RegExp(/(<script type="module" data-sveltekit-hydrate=".*?">)[\s\S]*start\(\s*\{[\s\S]*?hydrate:[\s\S]*?data:\s*\(\s*(function\([\s\S]*?\)\s*{\s*return[\s\S]*)\),\s*form:[\s\S]*?\}\);\s*<\/script>/gm);

Specifically: \s*return

My homepage data is of the form: data: (function(a,b,c,d){return [{type:"data",data:{_lucia:... and matches
Other pages have data like this: data: (function(a,b,c,d,e,f,g){d._id=f;d.email="[...];return [{type... and don't match

Possible solution

use .*return instead of \s*return

autoRefreshTokens not working

It seems like there's 2 errors causing it:

  1. unsubscribe() returned by autoRefreshTokens is being called on component initialization regardless of if it's inside onDestroy() or not.
  2. window is undefined

As for the solutions,

2 can be solved by changing window.atob to Buffer.from(). 1, I'm not sure.

Supabase adapter: Using the existing auth.users table

I’m wondering how much effort it would be to reuse the auth.users table in the Auth module of Supabase, instead of creating a new public.user table.

It seems like this library set a user_id of 8 random chars, but the Supabase Auth module is using UUID instead.

Also, not using the Auth module, we’re losing the ability to send mails or propose different social auth to users.

What to you think about that? Would Lucia be too much tight to Supabase or it would be too much work to make them work together?

jsdom dependency preventing from using Vercel's edge network

When deploying to Vercel's edge, Vercel throws the following error:

Error: Dynamic require of "path" is not supported
    at worker.js:48:23171
    at ../../node_modules/.pnpm/[email protected]/node_modules/jsdom/lib/api.js (worker.js:2320:23425)
    at worker.js:48:23334
    at .svelte-kit/output/server/entries/endpoints/api/docs/_...doc_.ts.js (worker.js:2320:28592)
    at worker.js:48:23279
    at worker.js:2336:2086
    at async resolve (worker.js:48:18073)
    at async _c (worker.js:48:17397)
    at async fetch (worker.js:48:8178)
    at async ss (worker.js:93:63)

[BUG] Cookie types incompatible

Bug report

Report for: Types

When using setCookie(cookies, ...user.cookies) in a SvelteKit Form Action, the cookies types are incompatible between SvelteKit Cookie interface and Lucia Cookie interface.

Current behavior

Argument of type 'import("@sveltejs/kit/types/index").Cookies' is not assignable to parameter of type 'import("lucia-sveltekit/kit").Cookies'.
The types returned by 'get(...)' are incompatible between these types.
Type 'string | void' is not assignable to type 'string | undefined'.
Type 'void' is not assignable to type 'string | undefined'.

Expected behavior

Type should be as below in kit.d.ts:
image

Possible cause

SvelteKit commited this change on 14/09/2022:
image

Additional info

Not sure if I reported this correctly, first time reporting a bug on GitHub.

Version

[email protected]
sveltejs/[email protected]

[BUG] Failed to resolve import "#ansi-styles"

Bug report

Report for: lucia-sveltekit

Node doesn't recognize something in import statement

Current behavior

Failed to resolve import "#ansi-styles" from "node_modules/.pnpm/[email protected]/node_modules/chalk/source/index.js?v=e4b116c2". Does the file exist?

Possible cause

It looks like the depedency used [email protected] is using ESM, check this for more info

Additional info

Version

[email protected]

Additional notes

My suggestion is to used version 4 of chalk dependency

[BUG] Failed to resolve import "#ansi-styles"

Bug report

Report for: lucia-sveltekit

Node doesn't recognize something in import statement

Current behavior

Failed to resolve import "#ansi-styles" from "node_modules/.pnpm/[email protected]/node_modules/chalk/source/index.js?v=e4b116c2". Does the file exist?

Possible cause

It looks like the depedency used [email protected] is using ESM, check this for more info

Additional info

Version

[email protected]

Additional notes

My suggestion is to used version 4 of chalk dependency

[BUG] Error caused by `EncryptedRefreshToken.decrypt()` causes the server to crash

Bug report

Report for: Lucia

EncryptedRefreshToken.decrypt() can throw the error Error: IV not found but it can't be caught, causing the server to crash.

Current behavior

Error should be caught if inside a try-catch block.

Expected behavior

Crashes server with an error message of Error: IV not found

Possible cause

not sure

Additional info

none

Version

v.0.9.1

Reproduction

none

Additional notes

none

[BUG] Decode cookie value in `setCookie()`

Bug report

Report for: Lucia

The value of the cookie string passed onto setCookie() should be decoded before being set. Not sure what exactly should be used to decode.

Current behavior

 const cookieValue = valueEntry[1]

Expected behavior

 const cookieValue = decode(valueEntry[1])

Possible cause

above

Additional info

Version

v0.8.4

Reproduction

.

Additional notes

.

[BUG] type issues with handleHooks and handleServerLoad

Bug report

Report for: lucia-sveltekit 0.8.5

I'm following the docs on migrating, but having TypeScript troubles.
There are three problems I'm having

  1. The auth.handleHooks function complains that setHeaders is the incorrect type.
  2. It also expects _lucia: Session to exist on ServerLoadEvent, which it doesn't at that point
  3. using the auth.handleServerLoad function as a wrapper like the docs show
    a) doesn't keep the types of any locals set in hooks
    b) breaks all downstream load function types

Everything is a pretty local TS problem except for 3b
To fix that, I'm just passing in the ServerLoadEvent to handleServerLoad separately, extracting _lucia and returning it with other data.
Doing it this way has the same missing _lucia: Session and setHeaders type issues as the auth.handleHooks function

Current behavior

This works: export const handle = auth.handleHooks()
This does not work: export const handle = sequence(auth.handleHooks(), ...handles)

export const load = auth.handleServerLoad(handleSession(), async (e) => { breaks all load types downstream

Expected behavior

Load the warning/route handling hooks and pass in _lucia to the main server load without breaking SK type safety. Declaring _lucia on App.Locals shouldn't be necessary because it doesn't actually exist there

Possible cause

The setHeaders issue seems to be because SK has it as Record<string, string> and in Lucia it's Record<string, string | number | string[] | null>
Changing this fixes the hooks issue, but the wrapper is still breaking things for me

Version

lucia-sveltekit 0.8.5 and kit next.484

Reproduction

repro

[BUG] `refresh_token` cookie should be `encrypt_refresh_token`

The issue: auth.handleServerLoad is not recognizing the session.

Please note that the getSession function inside handleLoad from "lucia-sveltekit/load" works fine.

I'm not very familiar with this codebase but after some debugging I this the issue is this line

That lines makes it so that the getSession function inside auth.handleServerLoad returns null. However, the session exists.

This other line seems to be correct.

[BUG] Comments in docs not highlighted correctly

Bug report

Report for: Documentation

Comments within objects within function parameters are not correctly highlighted.

Current behavior

Ignore the single /

/ comment

Expected behavior

// comment

Possible cause

Likely a bug with highlight.js

Additional info

Version

none.

Reproduction

none.

Additional notes

none.

FR: Change password

Doing a search through the docs, I don't see the ability to change a password.
Is that something that could already relatively easily be done manually?

[BUG] Github actions throwing error when publishing adapters

Bug report

Report for: Github actions

Trying to publish adapters with Github actions terminates with an error.

Current behavior

> @lucia-sveltekit/adapter-mongoose@0.2.1 build /home/runner/work/lucia-sveltekit/lucia-sveltekit/packages/adapter-mongoose
[108](https://github.com/pilcrowOnPaper/lucia-sveltekit/actions/runs/3247591817/jobs/5327758730#step:4:109)
> tsc && cp ./package.json ./dist && cp ./README.md ./dist && cp .npmignore dist
[109](https://github.com/pilcrowOnPaper/lucia-sveltekit/actions/runs/3247591817/jobs/5327758730#step:4:110)

[110](https://github.com/pilcrowOnPaper/lucia-sveltekit/actions/runs/3247591817/jobs/5327758730#step:4:111)ERR_PNPM_CANNOT_RESOLVE_WORKSPACE_PROTOCOLCannot resolve workspace protocol of dependency "lucia-sveltekit" because this dependency is not installed. Try running "pnpm install".

Expected behavior

(successful publish)

Possible cause

PNPM?

Additional info

Version

all

Reproduction

none

Additional notes

none

Calling `auth.validateRequest` fails with `AUTH_INVALID_ACCESS_TOKEN` when using Prisma adapter

Summary

In a basic reproduction, following the Prisma Adapter setup guide and following the email and password guide leads to auth.validateRequest failing with AUTH_INVALID_ACCESS_TOKEN.

I'm not sure if this is related to #8. I'm also fairly new to using SvelteKit so it's possible I've messed something up elsewhere, but I believe I've followed the lucia guides to a tee.

Reproduction

For the reproduction I setup a simple repository with a detailed README for instructions on how to setup + reproduce the issue.

https://github.com/gabewomble/lucia-sveltekit-with-prisma

[BUG] import app.postcss failed in +layout.svelte

Bug report

Report for:
lucia-sveltekit

Current behavior

failed to import app.css

Expected behavior

should import app.postcss

Possible cause

Additional info

Version

Reproduction

Additional notes

Access tokens in page data not updated after token refresh

Bug report

Tokens in pageData (await parent()) is not updated after token refresh.

Current behavior

After refreshing the access token:

const lucia = await parent()
console.log(lucia.access_token) // logs old access token

Expected behavior

console.log(lucia.access_token) // logs new access token

Possible cause

Unimplemented

Additional info

Version

0.7.0 and over

Reproduction

none

Additional notes

none

Handling refresh tokens in SSR

So currently, the refresh token is sent with every request because of the path: "/" property. This is a vulnerability and refresh token should only be sent (via http-only cookie or the authorization headers) to the refresh endpoint. An easy fix would be to set the cookie property to path: "/api/auth/refresh". But that would make the refresh token inaccessible in normal paths and the access token can't be refreshed on server-side navigation.

Failed to serialize session data: Cannot stringify arbitrary non-POJOs

I get this error every now and then, and I'm not sure why...
I assume it is to do with lucia's getSession?

I will post more info as I learn more.

  Error: Failed to serialize session data: Cannot stringify arbitrary non-POJOs
    at ./.svelte-kit/runtime/server/index.js:1482:11
    at try_serialize (./.svelte-kit/runtime/server/index.js:1645:13)
    at render_response (./.svelte-kit/runtime/server/index.js:1481:15)
    at async respond_with_error (./.svelte-kit/runtime/server/index.js:2856:10)
    at async respond$1 (./.svelte-kit/runtime/server/index.js:3112:4)
    at async resolve (./.svelte-kit/runtime/server/index.js:3453:11)
    at async handleEndpoints (./node_modules/lucia-sveltekit/dist/auth/hooks.js:84:16)
    at async handleTokens (./node_modules/lucia-sveltekit/dist/auth/hooks.js:55:30)
    at async respond (./.svelte-kit/runtime/server/index.js:3389:20)
    at async ./node_modules/@sveltejs/kit/dist/vite.js:1665:22

[BUG] validateRequestByCookie parameter - incorrect type reported

Bug report

When trying to use the following on +page.server.ts to check authentication:

export const load: PageServerLoad = async (request) => {
	try {
		const session = await auth.validateRequestByCookie(request);
		console.log(session);
		if (session) {
			const data = await db.employee.findMany();
			const employees = JSON.stringify(data);
			return { employees };
		}
	} catch {
		throw redirect(302, '/login');
	}
};

I'm getting the following error on request parameter of the validateRequestByCookie function:

(parameter) request: ServerLoadEvent<RouteParams, {
    _lucia: Session;
}>
Argument of type 'ServerLoadEvent<RouteParams, { _lucia: Session; }>' is not assignable to parameter of type 'Request'.
  Type 'ServerLoadEvent<RouteParams, { _lucia: Session; }>' is missing the following properties from type 'Request': cache, credentials, destination, headers, and 16 more.ts(2345)

Version

lucia-sveltekit: 0.8.6
sveltejs/kit: 1.0.0-next.491

[RFC] Revamping session store

Right now, tokens are read using server load function and passed on to subsequent load functions. This value is then read in Lucia.svelte component and set as the value of $session (returned by getSession()). This however leads to a few issues:

  • #63
  • #66
  • Load function cannot run in parallel as it needs to use await parent() to retrieve user's session

With some hacks, I think some or all these issues can be addressed.

Load functions

I'm thinking of creating a load function that handles sessions for you, one for setting the session and one for load functions:

// +layout.server.ts
export const load: ServerLoad = sessionHandler()
// +page.ts
export const load: Load = loadHandler()

These handlers can take a callback function that can runs as a normal load function. Except, it allows you to use session:

loadHandler((session, url) => {
    const user = session.user
    return {
        message: "hello" // acts as a normal load function
    }
})

As for server load functions, since we have access to cookies, we can just use read the cookie and call validateAccessToken().

If the load function is running in the browser, it can access global state safely and it'll be possible to get the latest session. This fixes #63. This also means that load functions running in the browser does not depend on parent load functions and can be ran in parallel. However, it might be possible to get the same behavior in the server, maybe. I'm still not sure, but since functions can be included in the object returned by load functions, this may allow for some magic to happen in the background. I think you can still get type safety as long as TS knows what loadHandler is returning.

Client

With some new knowledge of Svelte, I think we can get rid of the wrapper:

const session = getSession() // automatically sets the session store
listenForTokenExpiration() 

I'm open to feedback, and I hope any changes (this one or not) will streamline the experience!

handleSilentRefresh does not start the checkAccessToken loop

Hi,

I also posted about this in discord. handleSilentRefresh never gets the ball rolling on checkAccessToken.

Here is the diff that solved my problem:

diff --git a/node_modules/lucia-sveltekit/client.js b/node_modules/lucia-sveltekit/client.js
index cecee87..5c5d82b 100644
--- a/node_modules/lucia-sveltekit/client.js
+++ b/node_modules/lucia-sveltekit/client.js
@@ -94,6 +94,8 @@ export const handleSilentRefresh = (errorHandler = () => { }) => {
             }
         }, 5000);
     };
+    checkAccessToken();
+
     const refresh = async (session) => {
         if (!session)
             return;

This issue body was partially generated by patch-package.

Prisma Client Import error

When first importing the library and trying to run it, SvelteKit gave the following error in the browser.

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/***/node_modules/@prisma/client/runtime' is not supported resolving ES modules imported from /***/node_modules/@lucia-sveltekit/adapter-prisma/dist/index.js Did you mean to import @prisma/client/runtime/index.js? at new NodeError (node:internal/errors:387:5) at finalizeResolution (node:internal/modules/esm/resolve:400:17) at moduleResolve (node:internal/modules/esm/resolve:965:10) at defaultResolve (node:internal/modules/esm/resolve:1173:11) at nextResolve (node:internal/modules/esm/loader:173:28) at ESMLoader.resolve (node:internal/modules/esm/loader:852:30) at ESMLoader.getModuleJob (node:internal/modules/esm/loader:439:18) at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40) at link (node:internal/modules/esm/module_job:75:36)

I ended up trying a few items, and found a solution was to modify the file dist/index.js , and replace the following:

import { PrismaClientKnownRequestError } from "@prisma/client/runtime";

with

import pkg from '@prisma/client';
const { PrismaClientKnownRequestError } = pkg;

I also tried moving sveltekit-lucia and @lucia-sveltekit/adapter-prisma to dev dependencies (the documentation is unclear on this), but it didn't help.

My sveltekit version is "next", vite v3.0.3 and node v18.6.0

[BUG] `getSession` in server load function is calling the database to get the current user

Bug report

Report for: Lucia

getSession() in handleServerLoad is calling the database to get the user even when it has an access token.

Current behavior

const user = await context.auth.getUserFromAccessToken(
    accessToken,
    fingerprintToken
);

Expected behavior

const user = accessToken.user(fingerprintToken)

Possible cause

above.

Additional info

Version

0.8.4

Reproduction

none.

Additional notes

none.

[Q] Postgres identity sql

Hi, few questions.
In docs for supabase there is table for example user database https://lucia-sveltekit.vercel.app/adapters/supabase.
Could somone idicate me more, what command should be used for ID?

id bigint generated always as identity primary key
or use UUID there ? Its not clear what means in table unique and identity on 'true'.

How Im supposed to structure table?

Better errors

Errors right now are super simple, only consisting with a short message. This should be updated to include details and possibly how to fix the problem.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.