joshlei-servercookies 1.0.0

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +76 -0
  3. package/index.js +97 -0
  4. package/package.json +27 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Josh Lei
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # JoshLei ServerCookies
2
+
3
+ Tiny helper to encrypt, decrypt, set, and remove HTTP cookies using AES-256-GCM. Designed to work with Express-style `res.cookie` or any Node.js response object that supports `setHeader`.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install joshlei-servercookies
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### With ES modules
14
+
15
+ ```js
16
+ import { setEncryptedCookie, getDecryptedCookie, removeCookie } from 'joshlei-servercookies';
17
+
18
+ const secret = process.env.COOKIE_SECRET;
19
+
20
+ // Set an encrypted cookie
21
+ setEncryptedCookie({
22
+ res, // Express response object
23
+ name: 'session',
24
+ data: { userId: '123' },
25
+ secret,
26
+ options: {
27
+ maxAge: 7 * 24 * 60 * 60 * 1000, // optional, defaults to 7 days
28
+ sameSite: 'none', // defaults to 'none'
29
+ secure: true, // defaults to true
30
+ httpOnly: true // defaults to true
31
+ }
32
+ });
33
+
34
+ // Read and decrypt
35
+ const session = getDecryptedCookie({ req, name: 'session', secret });
36
+
37
+ // Remove
38
+ removeCookie({ res, name: 'session', options: { sameSite: 'none', secure: true } });
39
+ ```
40
+
41
+ ### With CommonJS
42
+
43
+ ```js
44
+ const { setEncryptedCookie, getDecryptedCookie, removeCookie } = require('joshlei-servercookies');
45
+ ```
46
+
47
+ ## API
48
+
49
+ ### `setEncryptedCookie({ res, name, data, secret, options })`
50
+ - `res`: Express-like response. If `res.cookie` exists it is used; otherwise `Set-Cookie` header is written.
51
+ - `name`: Cookie name (required).
52
+ - `data`: Any JSON-serializable value (required).
53
+ - `secret`: String used to derive a 256-bit key (required).
54
+ - `options` (all optional):
55
+ - `maxAge` (ms) default 7 days
56
+ - `domain`, `path` default `/`
57
+ - `httpOnly` default `true`
58
+ - `secure` default `true`
59
+ - `sameSite` default `'none'`
60
+
61
+ ### `getDecryptedCookie({ req, name, secret })`
62
+ - `req.headers.cookie` is parsed to find `name`.
63
+ - Returns parsed JSON value or `null` when missing/invalid/decryption fails.
64
+
65
+ ### `removeCookie({ res, name, options })`
66
+ - Sets the cookie with `maxAge: 0` using the same option defaults as `setEncryptedCookie`.
67
+
68
+ ## Security notes
69
+ - Use a strong, random secret stored outside source control (env var).
70
+ - Cookies are authenticated and encrypted with AES-256-GCM; tampering returns `null` on read.
71
+ - Ensure `secure: true` and `sameSite` are configured for your deployment needs.
72
+
73
+ ## Release
74
+ 1. Update `version` in package.json if needed.
75
+ 2. `npm login` (once per machine).
76
+ 3. `npm publish --access public` from the project root.
package/index.js ADDED
@@ -0,0 +1,97 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
2
+
3
+ const deriveKey = (secret) => {
4
+ if (!secret || typeof secret !== 'string') {
5
+ throw new Error('Secret must be a non-empty string');
6
+ }
7
+ return createHash('sha256').update(secret, 'utf8').digest();
8
+ };
9
+
10
+ const encrypt = (plaintext, secret) => {
11
+ const key = deriveKey(secret);
12
+ const iv = randomBytes(12);
13
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
14
+ const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
15
+ const tag = cipher.getAuthTag();
16
+ return `${iv.toString('hex')}:${tag.toString('hex')}:${encrypted.toString('hex')}`;
17
+ };
18
+
19
+ const decrypt = (payload, secret) => {
20
+ const key = deriveKey(secret);
21
+ const [ivHex, tagHex, dataHex] = (payload || '').split(':');
22
+ if (!ivHex || !tagHex || !dataHex) throw new Error('Invalid encrypted payload format');
23
+ const iv = Buffer.from(ivHex, 'hex');
24
+ const tag = Buffer.from(tagHex, 'hex');
25
+ const encrypted = Buffer.from(dataHex, 'hex');
26
+ const decipher = createDecipheriv('aes-256-gcm', key, iv);
27
+ decipher.setAuthTag(tag);
28
+ const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
29
+ return decrypted.toString('utf8');
30
+ };
31
+
32
+ const serializeCookie = (name, value, options = {}) => {
33
+ const parts = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`];
34
+ if (options.maxAge) parts.push(`Max-Age=${Math.floor(options.maxAge / 1000)}`);
35
+ if (options.domain) parts.push(`Domain=${options.domain}`);
36
+ if (options.path) parts.push(`Path=${options.path}`);
37
+ if (options.httpOnly) parts.push('HttpOnly');
38
+ if (options.secure) parts.push('Secure');
39
+ if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);
40
+ return parts.join('; ');
41
+ };
42
+
43
+ export const setEncryptedCookie = ({ res, name, data, secret, options = {} }) => {
44
+ if (!res) throw new Error('Response object is required');
45
+ if (!name) throw new Error('Cookie name is required');
46
+ if (data === undefined || data === null) throw new Error('Cookie data cannot be null');
47
+ const payload = encrypt(JSON.stringify(data), secret);
48
+
49
+ const cookieOptions = {
50
+ httpOnly: options.httpOnly !== false,
51
+ secure: options.secure !== false,
52
+ sameSite: options.sameSite || 'none',
53
+ domain: options.domain,
54
+ path: options.path || '/',
55
+ maxAge: options.maxAge || 7 * 24 * 60 * 60 * 1000,
56
+ };
57
+
58
+ if (typeof res.cookie === 'function') {
59
+ res.cookie(name, payload, cookieOptions);
60
+ } else {
61
+ const serialized = serializeCookie(name, payload, cookieOptions);
62
+ res.setHeader('Set-Cookie', serialized);
63
+ }
64
+ };
65
+
66
+ export const getDecryptedCookie = ({ req, name, secret }) => {
67
+ if (!req || !req.headers) return null;
68
+ const raw = req.headers.cookie || '';
69
+ const pairs = raw.split(';').map(part => part.trim()).filter(Boolean);
70
+ const target = pairs.find(p => p.startsWith(`${encodeURIComponent(name)}=`));
71
+ if (!target) return null;
72
+ const value = decodeURIComponent(target.split('=').slice(1).join('='));
73
+ try {
74
+ const decrypted = decrypt(value, secret);
75
+ return JSON.parse(decrypted);
76
+ } catch (e) {
77
+ return null;
78
+ }
79
+ };
80
+
81
+ export const removeCookie = ({ res, name, options = {} }) => {
82
+ if (!res) throw new Error('Response object is required');
83
+ const cookieOptions = {
84
+ httpOnly: options.httpOnly !== false,
85
+ secure: options.secure !== false,
86
+ sameSite: options.sameSite || 'none',
87
+ domain: options.domain,
88
+ path: options.path || '/',
89
+ maxAge: 0,
90
+ };
91
+ if (typeof res.cookie === 'function') {
92
+ res.cookie(name, '', cookieOptions);
93
+ } else {
94
+ const serialized = serializeCookie(name, '', cookieOptions);
95
+ res.setHeader('Set-Cookie', serialized);
96
+ }
97
+ };
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "joshlei-servercookies",
3
+ "version": "1.0.0",
4
+ "description": "Tiny helper to encrypt, decrypt, set, and remove HTTP cookies with AES-256-GCM.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js"
9
+ },
10
+ "files": [
11
+ "index.js"
12
+ ],
13
+ "keywords": [
14
+ "cookie",
15
+ "cookies",
16
+ "http",
17
+ "express",
18
+ "encryption",
19
+ "aes",
20
+ "gcm"
21
+ ],
22
+ "engines": {
23
+ "node": ">=16"
24
+ },
25
+ "author": "Josh Lei",
26
+ "license": "MIT"
27
+ }