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

Add createJWTSessionStorage #196

Open
wants to merge 7 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
8 changes: 4 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- name: Use Node LTS
uses: actions/setup-node@v2
with:
node-version: "lts/*"
node-version: "20"

- name: Install dependencies
uses: bahmutov/npm-install@v1
Expand All @@ -31,7 +31,7 @@ jobs:
- name: Use Node LTS
uses: actions/setup-node@v2
with:
node-version: "lts/*"
node-version: "20"

- name: Install dependencies
uses: bahmutov/npm-install@v1
Expand All @@ -49,7 +49,7 @@ jobs:
- name: Use Node LTS
uses: actions/setup-node@v2
with:
node-version: "lts/*"
node-version: "20"

- name: Install dependencies
uses: bahmutov/npm-install@v1
Expand All @@ -67,7 +67,7 @@ jobs:
- name: Use Node LTS
uses: actions/setup-node@v2
with:
node-version: "lts/*"
node-version: "20"

- name: Install dependencies
uses: bahmutov/npm-install@v1
Expand Down
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"dependencies": {
"intl-parse-accept-language": "^1.0.0",
"is-ip": "^3.1.0",
"jose": "^4.14.4",
"schema-dts": "^1.1.0",
"type-fest": "^2.5.2",
"uuid": "^8.3.2"
Expand Down
3 changes: 2 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
export * from "./server/cors";
export * from "./server/create-jwt-session-storage";
export * from "./server/csrf";
export * from "./server/event-stream";
export * from "./server/get-client-ip-address";
export * from "./server/get-client-locales";
export * from "./server/is-prefetch";
export * from "./server/json-hash";
export * from "./server/named-action";
export * from "./server/preload-route-assets";
export * from "./server/json-hash";
export * from "./server/responses";
export * from "./server/rolling-cookie";
export * from "./server/safe-redirect";
Expand Down
160 changes: 160 additions & 0 deletions src/server/create-jwt-session-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import type {
Session,
SessionStorage,
CookieOptions,
SessionData,
} from "@remix-run/server-runtime";
import { createSession } from "@remix-run/server-runtime";
import { EncryptJWT, jwtDecrypt, jwtVerify, SignJWT, UnsecuredJWT } from "jose";
import { parse, serialize } from "cookie";

interface JWTSessionStorageOptions {
cookie: CookieOptions & { name: string };
encrypt?: boolean;
sign?: boolean;
}

interface JWTSessionStorage extends SessionStorage {
getJWT(
cookieHeader?: string | null,
options?: CookieOptions
): Promise<string | null>;
}

export function createJWTSessionStorage({
cookie,
encrypt,
sign,
}: JWTSessionStorageOptions): JWTSessionStorage {
let secret = cookie.secrets?.[0];

async function encodeJWT(data: SessionData, expires?: Date) {
let encoded;

if (encrypt && secret) {
encoded = new EncryptJWT({ data })
.setProtectedHeader({ alg: "PBES2-HS512+A256KW", enc: "A256GCM" })
.setIssuedAt();

if (expires) {
encoded.setExpirationTime(expires.getTime());
}

encoded = encoded.encrypt(new TextEncoder().encode(secret));
} else if (sign && secret) {
encoded = new SignJWT({ data })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt();

if (expires) {
encoded.setExpirationTime(expires.getTime());
}

encoded = encoded.sign(new TextEncoder().encode(secret));
} else {
encoded = new UnsecuredJWT({ data }).setIssuedAt().encode();
}

return encoded as string;
}

async function decodeJWT(jwt: string) {
if (encrypt && secret) {
try {
let { payload: unsignedValue } = await jwtDecrypt(
jwt,
new TextEncoder().encode(secret)
);
return unsignedValue.data as SessionData;
} catch {}

return null;
} else if (sign && secret) {
try {
let { payload: unsignedValue } = await jwtVerify(
jwt,
new TextEncoder().encode(secret)
);

return unsignedValue.data as SessionData;
} catch {}

return null;
}

return UnsecuredJWT.decode(jwt).payload.data as SessionData;
}

return {
async getSession(
cookieHeader?: string | null,
options?: CookieOptions
): Promise<Session> {
let cookies =
cookieHeader && parse(cookieHeader, { ...options, ...cookie });
let jwt = cookies && cookies[cookie.name] ? cookies[cookie.name] : "";
let data: SessionData | null = {};
let id = "";

try {
data = await decodeJWT(jwt);
id = jwt.split(".").slice(-1)[0] + "";
} catch {
data = {};
id = "";
}

return createSession(data || {}, id);
},

async getJWT(
cookieHeader?: string | null,
options?: CookieOptions
): Promise<string | null> {
let cookies =
cookieHeader && parse(cookieHeader, { ...options, ...cookie });
let jwt = cookies && cookies[cookie.name] ? cookies[cookie.name] : "";

try {
await decodeJWT(jwt);

return jwt;
} catch {
return null;
}
},

async commitSession(
session: Session,
options?: CookieOptions
): Promise<string> {
let jwt = await encodeJWT(
session.data,
options?.expires || new Date(Date.now() + (cookie.maxAge || 0) * 1000)
);

let serializedCookie = serialize(cookie.name, jwt, {
...options,
...cookie,
});

if (serializedCookie.length > 4096) {
throw new Error(
"Cookie length will exceed browser maximum. Length: " +
serializedCookie.length
);
}

return serializedCookie;
},

destroySession(_: Session, options?: CookieOptions): Promise<string> {
return Promise.resolve(
serialize(cookie.name, "", {
...(options || cookie),
expires: new Date(0),
})
);
},
};
}
67 changes: 67 additions & 0 deletions test/server/create-jwt-session-storage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { createJWTSessionStorage } from "../../src";

describe(createJWTSessionStorage.name, () => {
let sessionStorage = createJWTSessionStorage({
cookie: { name: "session", secrets: ["secret"] },
encrypt: true,
sign: false,
});

test("gets an empty session", async () => {
let session = await sessionStorage.getSession();
expect(session.data).toEqual({});
});

test("commits a session", async () => {
let session = await sessionStorage.getSession();
session.set("foo", "bar");

// expect sessionStorage.commitSession(session) to resolves to any string
await expect(sessionStorage.commitSession(session)).resolves.toEqual(
expect.any(String)
);
});

test("reads session back from cookie", async () => {
let session = await sessionStorage.getSession();

session.set("foo", "bar");

let cookie = await sessionStorage.commitSession(session);

let session2 = await sessionStorage.getSession(cookie);

expect(session2.data).toEqual(session.data);
});

test("destroys returns an empty cookie", async () => {
let session = await sessionStorage.getSession();

session.set("foo", "bar");

let cookie = await sessionStorage.commitSession(session);

let session2 = await sessionStorage.getSession(cookie);

expect(session2.data).toEqual(session.data);

await sessionStorage.destroySession(session2);

let session3 = await sessionStorage.getSession();

expect(session3.data).toEqual({});
});

test("gets JWT from cookie", async () => {
await expect(
sessionStorage
.getSession()
.then((session) => {
session.set("foo", "bar");
return session;
})
.then(sessionStorage.commitSession)
.then(sessionStorage.getJWT)
).resolves.toEqual(expect.any(String));
});
});