hono-sessions 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/package.json +1 -1
  2. package/esm/src/Crypto.d.ts +0 -16
  3. package/esm/src/Crypto.js +0 -21
  4. package/esm/src/Middleware.d.ts +0 -14
  5. package/esm/src/Middleware.js +0 -117
  6. package/esm/src/Session.d.ts +0 -31
  7. package/esm/src/Session.js +0 -67
  8. package/esm/src/store/CookieStore.d.ts +0 -21
  9. package/esm/src/store/CookieStore.js +0 -66
  10. package/esm/src/store/MemoryStore.d.ts +0 -14
  11. package/esm/src/store/MemoryStore.js +0 -27
  12. package/esm/src/store/Store.d.ts +0 -10
  13. package/esm/src/store/Store.js +0 -1
  14. package/esm/src/store/bun/BunSqliteStore.d.ts +0 -11
  15. package/esm/src/store/bun/BunSqliteStore.js +0 -42
  16. package/esm/src/store/cloudflare/CloudflareD1Store.d.ts +0 -11
  17. package/esm/src/store/cloudflare/CloudflareD1Store.js +0 -37
  18. package/script/src/Crypto.d.ts +0 -16
  19. package/script/src/Crypto.js +0 -26
  20. package/script/src/Middleware.d.ts +0 -14
  21. package/script/src/Middleware.js +0 -124
  22. package/script/src/Session.d.ts +0 -31
  23. package/script/src/Session.js +0 -71
  24. package/script/src/store/CookieStore.d.ts +0 -21
  25. package/script/src/store/CookieStore.js +0 -68
  26. package/script/src/store/MemoryStore.d.ts +0 -14
  27. package/script/src/store/MemoryStore.js +0 -29
  28. package/script/src/store/Store.d.ts +0 -10
  29. package/script/src/store/Store.js +0 -2
  30. package/script/src/store/bun/BunSqliteStore.d.ts +0 -11
  31. package/script/src/store/bun/BunSqliteStore.js +0 -46
  32. package/script/src/store/cloudflare/CloudflareD1Store.d.ts +0 -11
  33. package/script/src/store/cloudflare/CloudflareD1Store.js +0 -41
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "module": "./esm/mod.js",
3
3
  "main": "./script/mod.js",
4
4
  "name": "hono-sessions",
5
- "version": "0.5.2",
5
+ "version": "0.5.4",
6
6
  "description": "Cookie-based sessions for Hono web framework",
7
7
  "license": "MIT",
8
8
  "repository": {
@@ -1,16 +0,0 @@
1
- /**
2
- * Encrypt a string or object value
3
- *
4
- * @param password Random string at least 32 characters long
5
- * @param payload String or object to encrypt
6
- * @returns A promise of the encrypted string
7
- */
8
- export declare function encrypt(password: string, payload: object | string): Promise<string>;
9
- /**
10
- * Decrypt an encrypted payload
11
- *
12
- * @param password Random string at least 32 characters long
13
- * @param encrypted Encrypted string
14
- * @returns Promise of the unencrypted value (string or object in most cases)
15
- */
16
- export declare function decrypt(password: string, encrypted: string): Promise<unknown>;
package/esm/src/Crypto.js DELETED
@@ -1,21 +0,0 @@
1
- import { Iron } from '../deps.js';
2
- /**
3
- * Encrypt a string or object value
4
- *
5
- * @param password Random string at least 32 characters long
6
- * @param payload String or object to encrypt
7
- * @returns A promise of the encrypted string
8
- */
9
- export async function encrypt(password, payload) {
10
- return await Iron.seal(globalThis.crypto, payload, password, Iron.defaults);
11
- }
12
- /**
13
- * Decrypt an encrypted payload
14
- *
15
- * @param password Random string at least 32 characters long
16
- * @param encrypted Encrypted string
17
- * @returns Promise of the unencrypted value (string or object in most cases)
18
- */
19
- export async function decrypt(password, encrypted) {
20
- return await Iron.unseal(globalThis.crypto, encrypted, { default: password }, Iron.defaults);
21
- }
@@ -1,14 +0,0 @@
1
- import { MiddlewareHandler } from '../deps.js';
2
- import Store from './store/Store.js';
3
- import CookieStore from './store/CookieStore.js';
4
- import { CookieOptions } from '../deps.js';
5
- interface SessionOptions {
6
- store: Store | CookieStore;
7
- encryptionKey?: string;
8
- expireAfterSeconds?: number;
9
- cookieOptions?: CookieOptions;
10
- sessionCookieName?: string;
11
- }
12
- /** Function that returns a Hono-compatible session middleware */
13
- export declare function sessionMiddleware(options: SessionOptions): MiddlewareHandler;
14
- export {};
@@ -1,117 +0,0 @@
1
- import { getCookie, setCookie, createMiddleware } from '../deps.js';
2
- import CookieStore from './store/CookieStore.js';
3
- import { Session, encrypt, decrypt } from '../mod.js';
4
- /** Function that returns a Hono-compatible session middleware */
5
- export function sessionMiddleware(options) {
6
- const store = options.store;
7
- const encryptionKey = options.encryptionKey;
8
- const expireAfterSeconds = options.expireAfterSeconds;
9
- const cookieOptions = options.cookieOptions;
10
- const sessionCookieName = options.sessionCookieName || 'session';
11
- if (store instanceof CookieStore) {
12
- store.sessionCookieName = sessionCookieName;
13
- if (encryptionKey) {
14
- store.encryptionKey = encryptionKey;
15
- }
16
- else {
17
- throw new Error('encryptionKey is required while using CookieStore. encryptionKey must be at least 32 characters long.');
18
- }
19
- if (cookieOptions) {
20
- store.cookieOptions = cookieOptions;
21
- }
22
- }
23
- const middleware = createMiddleware(async (c, next) => {
24
- const session = new Session;
25
- let sid = '';
26
- let session_data;
27
- let createNewSession = false;
28
- const sessionCookie = getCookie(c, sessionCookieName);
29
- if (sessionCookie) { // If there is a session cookie present...
30
- if (store instanceof CookieStore) {
31
- session_data = await store.getSession(c);
32
- }
33
- else {
34
- try {
35
- sid = (encryptionKey ? await decrypt(encryptionKey, sessionCookie) : sessionCookie);
36
- session_data = await store.getSessionById(sid);
37
- }
38
- catch {
39
- createNewSession = true;
40
- }
41
- }
42
- if (session_data) {
43
- session.setCache(session_data);
44
- if (session.sessionValid()) {
45
- session.reupSession(expireAfterSeconds);
46
- }
47
- else {
48
- store instanceof CookieStore ? await store.deleteSession(c) : await store.deleteSession(sid);
49
- createNewSession = true;
50
- }
51
- }
52
- else {
53
- createNewSession = true;
54
- }
55
- }
56
- else {
57
- createNewSession = true;
58
- }
59
- if (createNewSession) {
60
- const defaultData = {
61
- _data: {},
62
- _expire: null,
63
- _delete: false,
64
- _accessed: null,
65
- };
66
- if (store instanceof CookieStore) {
67
- await store.createSession(c, defaultData);
68
- }
69
- else {
70
- sid = globalThis.crypto.randomUUID();
71
- await store.createSession(sid, defaultData);
72
- }
73
- session.setCache(defaultData);
74
- }
75
- if (!(store instanceof CookieStore)) {
76
- setCookie(c, sessionCookieName, encryptionKey ? await encrypt(encryptionKey, sid) : sid, cookieOptions);
77
- }
78
- session.updateAccess();
79
- c.set('session', session);
80
- await next();
81
- const shouldDelete = session.getCache()._delete;
82
- const shouldRotateSessionKey = c.get("session_key_rotation") === true;
83
- const storeIsCookieStore = store instanceof CookieStore;
84
- if (shouldDelete) {
85
- store instanceof CookieStore
86
- ? await store.deleteSession(c)
87
- : await store.deleteSession(sid);
88
- }
89
- /*
90
- * Only update session data if we didn't just delete it.
91
- * If session key rotation is enabled and the store is not a CookieStore,
92
- * we need to roate the session key by deleting the old session and creating a new one.
93
- */
94
- const shouldRecreateSessionForNonCookieStore = !shouldDelete &&
95
- !storeIsCookieStore &&
96
- shouldRotateSessionKey;
97
- if (shouldRecreateSessionForNonCookieStore) {
98
- await store.deleteSession(sid);
99
- sid = globalThis.crypto.randomUUID();
100
- await store.createSession(sid, session.getCache());
101
- setCookie(c, sessionCookieName, encryptionKey ? await encrypt(encryptionKey, sid) : sid, cookieOptions);
102
- }
103
- /*
104
- * We skip session data persistence if it was just deleted.
105
- * Only persist if we didn't just rotate the session key,
106
- * or the store is a CookieStore (which does not have its session key rotated)
107
- */
108
- const shouldPersistSession = !shouldDelete &&
109
- (!shouldRotateSessionKey || storeIsCookieStore);
110
- if (shouldPersistSession) {
111
- store instanceof CookieStore
112
- ? await store.persistSessionData(c, session.getCache())
113
- : await store.persistSessionData(sid, session.getCache());
114
- }
115
- });
116
- return middleware;
117
- }
@@ -1,31 +0,0 @@
1
- interface SessionDataEntry {
2
- value: unknown;
3
- flash: boolean;
4
- }
5
- /**
6
- * Interface for specifying the necessary data for a session entry
7
- */
8
- export interface SessionData {
9
- _data: Record<string, SessionDataEntry>;
10
- _expire: string | null;
11
- _delete: boolean;
12
- _accessed: string | null;
13
- }
14
- /**
15
- * Session class with methods for interacting with the session
16
- */
17
- export declare class Session {
18
- private cache;
19
- constructor();
20
- setCache(cache_data: SessionData): void;
21
- getCache(): SessionData;
22
- setExpiration(expiration: string): void;
23
- reupSession(expiration: number | null | undefined): void;
24
- deleteSession(): void;
25
- sessionValid(): boolean;
26
- updateAccess(): void;
27
- get(key: string): unknown;
28
- set(key: string, value: unknown): void;
29
- flash(key: string, value: unknown): void;
30
- }
31
- export {};
@@ -1,67 +0,0 @@
1
- /**
2
- * Session class with methods for interacting with the session
3
- */
4
- export class Session {
5
- constructor() {
6
- Object.defineProperty(this, "cache", {
7
- enumerable: true,
8
- configurable: true,
9
- writable: true,
10
- value: void 0
11
- });
12
- this.cache = {
13
- _data: {},
14
- _expire: null,
15
- _delete: false,
16
- _accessed: null,
17
- };
18
- }
19
- setCache(cache_data) {
20
- this.cache = cache_data;
21
- }
22
- getCache() {
23
- return this.cache;
24
- }
25
- setExpiration(expiration) {
26
- this.cache._expire = expiration;
27
- }
28
- reupSession(expiration) {
29
- if (expiration) {
30
- this.setExpiration(new Date(Date.now() + expiration * 1000).toISOString());
31
- }
32
- }
33
- deleteSession() {
34
- this.cache._delete = true;
35
- }
36
- sessionValid() {
37
- return this.cache._expire == null || Date.now() < new Date(this.cache._expire).getTime();
38
- }
39
- updateAccess() {
40
- this.cache._accessed = new Date().toISOString();
41
- }
42
- get(key) {
43
- const entry = this.cache._data[key];
44
- if (entry) {
45
- const value = entry.value;
46
- if (entry.flash) {
47
- delete this.cache._data[key];
48
- }
49
- return value;
50
- }
51
- else {
52
- return null;
53
- }
54
- }
55
- set(key, value) {
56
- this.cache._data[key] = {
57
- value,
58
- flash: false
59
- };
60
- }
61
- flash(key, value) {
62
- this.cache._data[key] = {
63
- value,
64
- flash: true
65
- };
66
- }
67
- }
@@ -1,21 +0,0 @@
1
- import { Context, CookieOptions } from '../../deps.js';
2
- import { SessionData } from '../../mod.js';
3
- interface CookieStoreOptions {
4
- encryptionKey?: string | null;
5
- cookieOptions?: CookieOptions;
6
- sessionCookieName: string;
7
- }
8
- /**
9
- * Cookie storage driver class
10
- */
11
- declare class CookieStore {
12
- encryptionKey: string | null | undefined;
13
- cookieOptions: CookieOptions | undefined;
14
- sessionCookieName: string;
15
- constructor(options?: CookieStoreOptions);
16
- getSession(c: Context): Promise<SessionData | null>;
17
- createSession(c: Context, initial_data: SessionData): Promise<void>;
18
- deleteSession(c: Context): Promise<void>;
19
- persistSessionData(c: Context, session_data: SessionData): Promise<void>;
20
- }
21
- export default CookieStore;
@@ -1,66 +0,0 @@
1
- import { getCookie, setCookie } from '../../deps.js';
2
- import { encrypt, decrypt } from '../../mod.js';
3
- /**
4
- * Cookie storage driver class
5
- */
6
- class CookieStore {
7
- constructor(options) {
8
- Object.defineProperty(this, "encryptionKey", {
9
- enumerable: true,
10
- configurable: true,
11
- writable: true,
12
- value: void 0
13
- });
14
- Object.defineProperty(this, "cookieOptions", {
15
- enumerable: true,
16
- configurable: true,
17
- writable: true,
18
- value: void 0
19
- });
20
- Object.defineProperty(this, "sessionCookieName", {
21
- enumerable: true,
22
- configurable: true,
23
- writable: true,
24
- value: void 0
25
- });
26
- this.encryptionKey = options?.encryptionKey;
27
- this.cookieOptions = options?.cookieOptions;
28
- this.sessionCookieName = options?.sessionCookieName || 'session';
29
- }
30
- async getSession(c) {
31
- let session_data_raw;
32
- const sessionCookie = getCookie(c, this.sessionCookieName);
33
- if (this.encryptionKey && sessionCookie) {
34
- // Decrypt cookie string. If decryption fails, return null
35
- try {
36
- session_data_raw = (await decrypt(this.encryptionKey, sessionCookie));
37
- }
38
- catch {
39
- return null;
40
- }
41
- // Parse session object from cookie string and return result. If fails, return null
42
- try {
43
- const session_data = JSON.parse(session_data_raw);
44
- return session_data;
45
- }
46
- catch {
47
- return null;
48
- }
49
- }
50
- else {
51
- return null;
52
- }
53
- }
54
- async createSession(c, initial_data) {
55
- const stringified_data = JSON.stringify(initial_data);
56
- setCookie(c, this.sessionCookieName, this.encryptionKey ? await encrypt(this.encryptionKey, stringified_data) : stringified_data, this.cookieOptions);
57
- }
58
- async deleteSession(c) {
59
- setCookie(c, this.sessionCookieName, this.encryptionKey ? await encrypt(this.encryptionKey, '') : '', this.cookieOptions);
60
- }
61
- async persistSessionData(c, session_data) {
62
- const stringified_data = JSON.stringify(session_data);
63
- setCookie(c, this.sessionCookieName, this.encryptionKey ? await encrypt(this.encryptionKey, stringified_data) : stringified_data, this.cookieOptions);
64
- }
65
- }
66
- export default CookieStore;
@@ -1,14 +0,0 @@
1
- import Store from './Store.js';
2
- import { SessionData } from '../../mod.js';
3
- /**
4
- * Memory storage driver class
5
- */
6
- declare class MemoryStore implements Store {
7
- private data;
8
- constructor();
9
- getSessionById(sid: string): SessionData | null | undefined;
10
- createSession(sid: string, initial_data: SessionData): void;
11
- deleteSession(sid: string): void;
12
- persistSessionData(sid: string, session_data: SessionData): void;
13
- }
14
- export default MemoryStore;
@@ -1,27 +0,0 @@
1
- /**
2
- * Memory storage driver class
3
- */
4
- class MemoryStore {
5
- constructor() {
6
- Object.defineProperty(this, "data", {
7
- enumerable: true,
8
- configurable: true,
9
- writable: true,
10
- value: void 0
11
- });
12
- this.data = new Map;
13
- }
14
- getSessionById(sid) {
15
- return this.data.has(sid) ? this.data.get(sid) : null;
16
- }
17
- createSession(sid, initial_data) {
18
- this.data.set(sid, initial_data);
19
- }
20
- deleteSession(sid) {
21
- this.data.delete(sid);
22
- }
23
- persistSessionData(sid, session_data) {
24
- this.data.set(sid, session_data);
25
- }
26
- }
27
- export default MemoryStore;
@@ -1,10 +0,0 @@
1
- import { SessionData } from "../../mod.js";
2
- /**
3
- * Interface for required methods in session storage drivers
4
- */
5
- export default interface Store {
6
- getSessionById(sessionId?: string): SessionData | null | undefined | Promise<SessionData | null | undefined>;
7
- createSession(sessionId: string, initialData: SessionData): Promise<void> | void;
8
- persistSessionData(sessionId: string, sessionData: SessionData): Promise<void> | void;
9
- deleteSession(sessionId: string): Promise<void> | void;
10
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,11 +0,0 @@
1
- import Store from '../Store.js';
2
- import { SessionData } from '../../Session.js';
3
- export declare class BunSqliteStore implements Store {
4
- db: any;
5
- tableName: string;
6
- constructor(db: any, tableName?: string);
7
- getSessionById(sessionId: string): any;
8
- createSession(sessionId: string, initialData: SessionData): void;
9
- deleteSession(sessionId: string): void;
10
- persistSessionData(sessionId: string, sessionData: SessionData): void;
11
- }
@@ -1,42 +0,0 @@
1
- export class BunSqliteStore {
2
- constructor(db, tableName = 'sessions') {
3
- Object.defineProperty(this, "db", {
4
- enumerable: true,
5
- configurable: true,
6
- writable: true,
7
- value: void 0
8
- });
9
- Object.defineProperty(this, "tableName", {
10
- enumerable: true,
11
- configurable: true,
12
- writable: true,
13
- value: void 0
14
- });
15
- this.db = db;
16
- this.tableName = tableName;
17
- const query = db.query(`CREATE TABLE IF NOT EXISTS ${tableName} (id TEXT PRIMARY KEY, data TEXT)`);
18
- query.run();
19
- }
20
- getSessionById(sessionId) {
21
- const query = this.db.query(`SELECT data FROM ${this.tableName} WHERE id = $id`);
22
- const result = query.get({ $id: sessionId });
23
- if (result) {
24
- return JSON.parse(result.data);
25
- }
26
- else {
27
- return null;
28
- }
29
- }
30
- createSession(sessionId, initialData) {
31
- const query = this.db.query(`INSERT INTO ${this.tableName} (id, data) VALUES ($id, $data)`);
32
- query.run({ $id: sessionId, $data: JSON.stringify(initialData) });
33
- }
34
- deleteSession(sessionId) {
35
- const query = this.db.query(`DELETE FROM ${this.tableName} WHERE id = $id`);
36
- query.run({ $id: sessionId });
37
- }
38
- persistSessionData(sessionId, sessionData) {
39
- const query = this.db.query(`UPDATE ${this.tableName} SET data = $data WHERE id = $id`);
40
- query.run({ $id: sessionId, $data: JSON.stringify(sessionData) });
41
- }
42
- }
@@ -1,11 +0,0 @@
1
- import Store from '../Store.js';
2
- import { SessionData } from '../../Session.js';
3
- export declare class CloudflareD1Store implements Store {
4
- db: any;
5
- tableName: string;
6
- constructor(tableName?: string);
7
- getSessionById(sessionId?: string | undefined): Promise<any>;
8
- createSession(sessionId: string, initialData: SessionData): Promise<void>;
9
- deleteSession(sessionId: string): Promise<void>;
10
- persistSessionData(sessionId: string, sessionData: SessionData): Promise<void>;
11
- }
@@ -1,37 +0,0 @@
1
- export class CloudflareD1Store {
2
- constructor(tableName = 'sessions') {
3
- Object.defineProperty(this, "db", {
4
- enumerable: true,
5
- configurable: true,
6
- writable: true,
7
- value: void 0
8
- });
9
- Object.defineProperty(this, "tableName", {
10
- enumerable: true,
11
- configurable: true,
12
- writable: true,
13
- value: void 0
14
- });
15
- this.tableName = tableName;
16
- }
17
- async getSessionById(sessionId) {
18
- const session = await this.db.prepare(`SELECT data FROM ${this.tableName} WHERE id = ?`)
19
- .bind(sessionId)
20
- .first('data');
21
- if (session) {
22
- return JSON.parse(session);
23
- }
24
- else {
25
- return null;
26
- }
27
- }
28
- async createSession(sessionId, initialData) {
29
- await this.db.prepare(`INSERT INTO ${this.tableName} (id, data) VALUES (?, ?)`).bind(sessionId, JSON.stringify(initialData)).run();
30
- }
31
- async deleteSession(sessionId) {
32
- await this.db.prepare(`DELETE FROM ${this.tableName} WHERE id = ?`).bind(sessionId).run();
33
- }
34
- async persistSessionData(sessionId, sessionData) {
35
- await this.db.prepare(`UPDATE ${this.tableName} SET data = ? WHERE id = ?`).bind(JSON.stringify(sessionData), sessionId).run();
36
- }
37
- }
@@ -1,16 +0,0 @@
1
- /**
2
- * Encrypt a string or object value
3
- *
4
- * @param password Random string at least 32 characters long
5
- * @param payload String or object to encrypt
6
- * @returns A promise of the encrypted string
7
- */
8
- export declare function encrypt(password: string, payload: object | string): Promise<string>;
9
- /**
10
- * Decrypt an encrypted payload
11
- *
12
- * @param password Random string at least 32 characters long
13
- * @param encrypted Encrypted string
14
- * @returns Promise of the unencrypted value (string or object in most cases)
15
- */
16
- export declare function decrypt(password: string, encrypted: string): Promise<unknown>;
@@ -1,26 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decrypt = exports.encrypt = void 0;
4
- const deps_js_1 = require("../deps.js");
5
- /**
6
- * Encrypt a string or object value
7
- *
8
- * @param password Random string at least 32 characters long
9
- * @param payload String or object to encrypt
10
- * @returns A promise of the encrypted string
11
- */
12
- async function encrypt(password, payload) {
13
- return await deps_js_1.Iron.seal(globalThis.crypto, payload, password, deps_js_1.Iron.defaults);
14
- }
15
- exports.encrypt = encrypt;
16
- /**
17
- * Decrypt an encrypted payload
18
- *
19
- * @param password Random string at least 32 characters long
20
- * @param encrypted Encrypted string
21
- * @returns Promise of the unencrypted value (string or object in most cases)
22
- */
23
- async function decrypt(password, encrypted) {
24
- return await deps_js_1.Iron.unseal(globalThis.crypto, encrypted, { default: password }, deps_js_1.Iron.defaults);
25
- }
26
- exports.decrypt = decrypt;
@@ -1,14 +0,0 @@
1
- import { MiddlewareHandler } from '../deps.js';
2
- import Store from './store/Store.js';
3
- import CookieStore from './store/CookieStore.js';
4
- import { CookieOptions } from '../deps.js';
5
- interface SessionOptions {
6
- store: Store | CookieStore;
7
- encryptionKey?: string;
8
- expireAfterSeconds?: number;
9
- cookieOptions?: CookieOptions;
10
- sessionCookieName?: string;
11
- }
12
- /** Function that returns a Hono-compatible session middleware */
13
- export declare function sessionMiddleware(options: SessionOptions): MiddlewareHandler;
14
- export {};
@@ -1,124 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.sessionMiddleware = void 0;
7
- const deps_js_1 = require("../deps.js");
8
- const CookieStore_js_1 = __importDefault(require("./store/CookieStore.js"));
9
- const mod_js_1 = require("../mod.js");
10
- /** Function that returns a Hono-compatible session middleware */
11
- function sessionMiddleware(options) {
12
- const store = options.store;
13
- const encryptionKey = options.encryptionKey;
14
- const expireAfterSeconds = options.expireAfterSeconds;
15
- const cookieOptions = options.cookieOptions;
16
- const sessionCookieName = options.sessionCookieName || 'session';
17
- if (store instanceof CookieStore_js_1.default) {
18
- store.sessionCookieName = sessionCookieName;
19
- if (encryptionKey) {
20
- store.encryptionKey = encryptionKey;
21
- }
22
- else {
23
- throw new Error('encryptionKey is required while using CookieStore. encryptionKey must be at least 32 characters long.');
24
- }
25
- if (cookieOptions) {
26
- store.cookieOptions = cookieOptions;
27
- }
28
- }
29
- const middleware = (0, deps_js_1.createMiddleware)(async (c, next) => {
30
- const session = new mod_js_1.Session;
31
- let sid = '';
32
- let session_data;
33
- let createNewSession = false;
34
- const sessionCookie = (0, deps_js_1.getCookie)(c, sessionCookieName);
35
- if (sessionCookie) { // If there is a session cookie present...
36
- if (store instanceof CookieStore_js_1.default) {
37
- session_data = await store.getSession(c);
38
- }
39
- else {
40
- try {
41
- sid = (encryptionKey ? await (0, mod_js_1.decrypt)(encryptionKey, sessionCookie) : sessionCookie);
42
- session_data = await store.getSessionById(sid);
43
- }
44
- catch {
45
- createNewSession = true;
46
- }
47
- }
48
- if (session_data) {
49
- session.setCache(session_data);
50
- if (session.sessionValid()) {
51
- session.reupSession(expireAfterSeconds);
52
- }
53
- else {
54
- store instanceof CookieStore_js_1.default ? await store.deleteSession(c) : await store.deleteSession(sid);
55
- createNewSession = true;
56
- }
57
- }
58
- else {
59
- createNewSession = true;
60
- }
61
- }
62
- else {
63
- createNewSession = true;
64
- }
65
- if (createNewSession) {
66
- const defaultData = {
67
- _data: {},
68
- _expire: null,
69
- _delete: false,
70
- _accessed: null,
71
- };
72
- if (store instanceof CookieStore_js_1.default) {
73
- await store.createSession(c, defaultData);
74
- }
75
- else {
76
- sid = globalThis.crypto.randomUUID();
77
- await store.createSession(sid, defaultData);
78
- }
79
- session.setCache(defaultData);
80
- }
81
- if (!(store instanceof CookieStore_js_1.default)) {
82
- (0, deps_js_1.setCookie)(c, sessionCookieName, encryptionKey ? await (0, mod_js_1.encrypt)(encryptionKey, sid) : sid, cookieOptions);
83
- }
84
- session.updateAccess();
85
- c.set('session', session);
86
- await next();
87
- const shouldDelete = session.getCache()._delete;
88
- const shouldRotateSessionKey = c.get("session_key_rotation") === true;
89
- const storeIsCookieStore = store instanceof CookieStore_js_1.default;
90
- if (shouldDelete) {
91
- store instanceof CookieStore_js_1.default
92
- ? await store.deleteSession(c)
93
- : await store.deleteSession(sid);
94
- }
95
- /*
96
- * Only update session data if we didn't just delete it.
97
- * If session key rotation is enabled and the store is not a CookieStore,
98
- * we need to roate the session key by deleting the old session and creating a new one.
99
- */
100
- const shouldRecreateSessionForNonCookieStore = !shouldDelete &&
101
- !storeIsCookieStore &&
102
- shouldRotateSessionKey;
103
- if (shouldRecreateSessionForNonCookieStore) {
104
- await store.deleteSession(sid);
105
- sid = globalThis.crypto.randomUUID();
106
- await store.createSession(sid, session.getCache());
107
- (0, deps_js_1.setCookie)(c, sessionCookieName, encryptionKey ? await (0, mod_js_1.encrypt)(encryptionKey, sid) : sid, cookieOptions);
108
- }
109
- /*
110
- * We skip session data persistence if it was just deleted.
111
- * Only persist if we didn't just rotate the session key,
112
- * or the store is a CookieStore (which does not have its session key rotated)
113
- */
114
- const shouldPersistSession = !shouldDelete &&
115
- (!shouldRotateSessionKey || storeIsCookieStore);
116
- if (shouldPersistSession) {
117
- store instanceof CookieStore_js_1.default
118
- ? await store.persistSessionData(c, session.getCache())
119
- : await store.persistSessionData(sid, session.getCache());
120
- }
121
- });
122
- return middleware;
123
- }
124
- exports.sessionMiddleware = sessionMiddleware;
@@ -1,31 +0,0 @@
1
- interface SessionDataEntry {
2
- value: unknown;
3
- flash: boolean;
4
- }
5
- /**
6
- * Interface for specifying the necessary data for a session entry
7
- */
8
- export interface SessionData {
9
- _data: Record<string, SessionDataEntry>;
10
- _expire: string | null;
11
- _delete: boolean;
12
- _accessed: string | null;
13
- }
14
- /**
15
- * Session class with methods for interacting with the session
16
- */
17
- export declare class Session {
18
- private cache;
19
- constructor();
20
- setCache(cache_data: SessionData): void;
21
- getCache(): SessionData;
22
- setExpiration(expiration: string): void;
23
- reupSession(expiration: number | null | undefined): void;
24
- deleteSession(): void;
25
- sessionValid(): boolean;
26
- updateAccess(): void;
27
- get(key: string): unknown;
28
- set(key: string, value: unknown): void;
29
- flash(key: string, value: unknown): void;
30
- }
31
- export {};
@@ -1,71 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Session = void 0;
4
- /**
5
- * Session class with methods for interacting with the session
6
- */
7
- class Session {
8
- constructor() {
9
- Object.defineProperty(this, "cache", {
10
- enumerable: true,
11
- configurable: true,
12
- writable: true,
13
- value: void 0
14
- });
15
- this.cache = {
16
- _data: {},
17
- _expire: null,
18
- _delete: false,
19
- _accessed: null,
20
- };
21
- }
22
- setCache(cache_data) {
23
- this.cache = cache_data;
24
- }
25
- getCache() {
26
- return this.cache;
27
- }
28
- setExpiration(expiration) {
29
- this.cache._expire = expiration;
30
- }
31
- reupSession(expiration) {
32
- if (expiration) {
33
- this.setExpiration(new Date(Date.now() + expiration * 1000).toISOString());
34
- }
35
- }
36
- deleteSession() {
37
- this.cache._delete = true;
38
- }
39
- sessionValid() {
40
- return this.cache._expire == null || Date.now() < new Date(this.cache._expire).getTime();
41
- }
42
- updateAccess() {
43
- this.cache._accessed = new Date().toISOString();
44
- }
45
- get(key) {
46
- const entry = this.cache._data[key];
47
- if (entry) {
48
- const value = entry.value;
49
- if (entry.flash) {
50
- delete this.cache._data[key];
51
- }
52
- return value;
53
- }
54
- else {
55
- return null;
56
- }
57
- }
58
- set(key, value) {
59
- this.cache._data[key] = {
60
- value,
61
- flash: false
62
- };
63
- }
64
- flash(key, value) {
65
- this.cache._data[key] = {
66
- value,
67
- flash: true
68
- };
69
- }
70
- }
71
- exports.Session = Session;
@@ -1,21 +0,0 @@
1
- import { Context, CookieOptions } from '../../deps.js';
2
- import { SessionData } from '../../mod.js';
3
- interface CookieStoreOptions {
4
- encryptionKey?: string | null;
5
- cookieOptions?: CookieOptions;
6
- sessionCookieName: string;
7
- }
8
- /**
9
- * Cookie storage driver class
10
- */
11
- declare class CookieStore {
12
- encryptionKey: string | null | undefined;
13
- cookieOptions: CookieOptions | undefined;
14
- sessionCookieName: string;
15
- constructor(options?: CookieStoreOptions);
16
- getSession(c: Context): Promise<SessionData | null>;
17
- createSession(c: Context, initial_data: SessionData): Promise<void>;
18
- deleteSession(c: Context): Promise<void>;
19
- persistSessionData(c: Context, session_data: SessionData): Promise<void>;
20
- }
21
- export default CookieStore;
@@ -1,68 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const deps_js_1 = require("../../deps.js");
4
- const mod_js_1 = require("../../mod.js");
5
- /**
6
- * Cookie storage driver class
7
- */
8
- class CookieStore {
9
- constructor(options) {
10
- Object.defineProperty(this, "encryptionKey", {
11
- enumerable: true,
12
- configurable: true,
13
- writable: true,
14
- value: void 0
15
- });
16
- Object.defineProperty(this, "cookieOptions", {
17
- enumerable: true,
18
- configurable: true,
19
- writable: true,
20
- value: void 0
21
- });
22
- Object.defineProperty(this, "sessionCookieName", {
23
- enumerable: true,
24
- configurable: true,
25
- writable: true,
26
- value: void 0
27
- });
28
- this.encryptionKey = options?.encryptionKey;
29
- this.cookieOptions = options?.cookieOptions;
30
- this.sessionCookieName = options?.sessionCookieName || 'session';
31
- }
32
- async getSession(c) {
33
- let session_data_raw;
34
- const sessionCookie = (0, deps_js_1.getCookie)(c, this.sessionCookieName);
35
- if (this.encryptionKey && sessionCookie) {
36
- // Decrypt cookie string. If decryption fails, return null
37
- try {
38
- session_data_raw = (await (0, mod_js_1.decrypt)(this.encryptionKey, sessionCookie));
39
- }
40
- catch {
41
- return null;
42
- }
43
- // Parse session object from cookie string and return result. If fails, return null
44
- try {
45
- const session_data = JSON.parse(session_data_raw);
46
- return session_data;
47
- }
48
- catch {
49
- return null;
50
- }
51
- }
52
- else {
53
- return null;
54
- }
55
- }
56
- async createSession(c, initial_data) {
57
- const stringified_data = JSON.stringify(initial_data);
58
- (0, deps_js_1.setCookie)(c, this.sessionCookieName, this.encryptionKey ? await (0, mod_js_1.encrypt)(this.encryptionKey, stringified_data) : stringified_data, this.cookieOptions);
59
- }
60
- async deleteSession(c) {
61
- (0, deps_js_1.setCookie)(c, this.sessionCookieName, this.encryptionKey ? await (0, mod_js_1.encrypt)(this.encryptionKey, '') : '', this.cookieOptions);
62
- }
63
- async persistSessionData(c, session_data) {
64
- const stringified_data = JSON.stringify(session_data);
65
- (0, deps_js_1.setCookie)(c, this.sessionCookieName, this.encryptionKey ? await (0, mod_js_1.encrypt)(this.encryptionKey, stringified_data) : stringified_data, this.cookieOptions);
66
- }
67
- }
68
- exports.default = CookieStore;
@@ -1,14 +0,0 @@
1
- import Store from './Store.js';
2
- import { SessionData } from '../../mod.js';
3
- /**
4
- * Memory storage driver class
5
- */
6
- declare class MemoryStore implements Store {
7
- private data;
8
- constructor();
9
- getSessionById(sid: string): SessionData | null | undefined;
10
- createSession(sid: string, initial_data: SessionData): void;
11
- deleteSession(sid: string): void;
12
- persistSessionData(sid: string, session_data: SessionData): void;
13
- }
14
- export default MemoryStore;
@@ -1,29 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- /**
4
- * Memory storage driver class
5
- */
6
- class MemoryStore {
7
- constructor() {
8
- Object.defineProperty(this, "data", {
9
- enumerable: true,
10
- configurable: true,
11
- writable: true,
12
- value: void 0
13
- });
14
- this.data = new Map;
15
- }
16
- getSessionById(sid) {
17
- return this.data.has(sid) ? this.data.get(sid) : null;
18
- }
19
- createSession(sid, initial_data) {
20
- this.data.set(sid, initial_data);
21
- }
22
- deleteSession(sid) {
23
- this.data.delete(sid);
24
- }
25
- persistSessionData(sid, session_data) {
26
- this.data.set(sid, session_data);
27
- }
28
- }
29
- exports.default = MemoryStore;
@@ -1,10 +0,0 @@
1
- import { SessionData } from "../../mod.js";
2
- /**
3
- * Interface for required methods in session storage drivers
4
- */
5
- export default interface Store {
6
- getSessionById(sessionId?: string): SessionData | null | undefined | Promise<SessionData | null | undefined>;
7
- createSession(sessionId: string, initialData: SessionData): Promise<void> | void;
8
- persistSessionData(sessionId: string, sessionData: SessionData): Promise<void> | void;
9
- deleteSession(sessionId: string): Promise<void> | void;
10
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,11 +0,0 @@
1
- import Store from '../Store.js';
2
- import { SessionData } from '../../Session.js';
3
- export declare class BunSqliteStore implements Store {
4
- db: any;
5
- tableName: string;
6
- constructor(db: any, tableName?: string);
7
- getSessionById(sessionId: string): any;
8
- createSession(sessionId: string, initialData: SessionData): void;
9
- deleteSession(sessionId: string): void;
10
- persistSessionData(sessionId: string, sessionData: SessionData): void;
11
- }
@@ -1,46 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BunSqliteStore = void 0;
4
- class BunSqliteStore {
5
- constructor(db, tableName = 'sessions') {
6
- Object.defineProperty(this, "db", {
7
- enumerable: true,
8
- configurable: true,
9
- writable: true,
10
- value: void 0
11
- });
12
- Object.defineProperty(this, "tableName", {
13
- enumerable: true,
14
- configurable: true,
15
- writable: true,
16
- value: void 0
17
- });
18
- this.db = db;
19
- this.tableName = tableName;
20
- const query = db.query(`CREATE TABLE IF NOT EXISTS ${tableName} (id TEXT PRIMARY KEY, data TEXT)`);
21
- query.run();
22
- }
23
- getSessionById(sessionId) {
24
- const query = this.db.query(`SELECT data FROM ${this.tableName} WHERE id = $id`);
25
- const result = query.get({ $id: sessionId });
26
- if (result) {
27
- return JSON.parse(result.data);
28
- }
29
- else {
30
- return null;
31
- }
32
- }
33
- createSession(sessionId, initialData) {
34
- const query = this.db.query(`INSERT INTO ${this.tableName} (id, data) VALUES ($id, $data)`);
35
- query.run({ $id: sessionId, $data: JSON.stringify(initialData) });
36
- }
37
- deleteSession(sessionId) {
38
- const query = this.db.query(`DELETE FROM ${this.tableName} WHERE id = $id`);
39
- query.run({ $id: sessionId });
40
- }
41
- persistSessionData(sessionId, sessionData) {
42
- const query = this.db.query(`UPDATE ${this.tableName} SET data = $data WHERE id = $id`);
43
- query.run({ $id: sessionId, $data: JSON.stringify(sessionData) });
44
- }
45
- }
46
- exports.BunSqliteStore = BunSqliteStore;
@@ -1,11 +0,0 @@
1
- import Store from '../Store.js';
2
- import { SessionData } from '../../Session.js';
3
- export declare class CloudflareD1Store implements Store {
4
- db: any;
5
- tableName: string;
6
- constructor(tableName?: string);
7
- getSessionById(sessionId?: string | undefined): Promise<any>;
8
- createSession(sessionId: string, initialData: SessionData): Promise<void>;
9
- deleteSession(sessionId: string): Promise<void>;
10
- persistSessionData(sessionId: string, sessionData: SessionData): Promise<void>;
11
- }
@@ -1,41 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CloudflareD1Store = void 0;
4
- class CloudflareD1Store {
5
- constructor(tableName = 'sessions') {
6
- Object.defineProperty(this, "db", {
7
- enumerable: true,
8
- configurable: true,
9
- writable: true,
10
- value: void 0
11
- });
12
- Object.defineProperty(this, "tableName", {
13
- enumerable: true,
14
- configurable: true,
15
- writable: true,
16
- value: void 0
17
- });
18
- this.tableName = tableName;
19
- }
20
- async getSessionById(sessionId) {
21
- const session = await this.db.prepare(`SELECT data FROM ${this.tableName} WHERE id = ?`)
22
- .bind(sessionId)
23
- .first('data');
24
- if (session) {
25
- return JSON.parse(session);
26
- }
27
- else {
28
- return null;
29
- }
30
- }
31
- async createSession(sessionId, initialData) {
32
- await this.db.prepare(`INSERT INTO ${this.tableName} (id, data) VALUES (?, ?)`).bind(sessionId, JSON.stringify(initialData)).run();
33
- }
34
- async deleteSession(sessionId) {
35
- await this.db.prepare(`DELETE FROM ${this.tableName} WHERE id = ?`).bind(sessionId).run();
36
- }
37
- async persistSessionData(sessionId, sessionData) {
38
- await this.db.prepare(`UPDATE ${this.tableName} SET data = ? WHERE id = ?`).bind(JSON.stringify(sessionData), sessionId).run();
39
- }
40
- }
41
- exports.CloudflareD1Store = CloudflareD1Store;