memorio 4.7.3 → 4.9.5

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.
@@ -1,323 +0,0 @@
1
- # Memorio Security Documentation
2
-
3
- > Last Updated: v3.0.2
4
-
5
- This document describes the security measures implemented in Memorio to protect against common vulnerabilities and ensure safe operation across different platforms.
6
-
7
- ---
8
-
9
- ## Security Overview
10
-
11
- Memorio implements multiple layers of security to protect user data and prevent common attack vectors:
12
-
13
- | Security Feature | Status | Description |
14
- |------------------|--------|-------------|
15
- | Cryptographically Secure IDs | ✅ Enabled | Session/Context IDs use crypto.randomUUID |
16
- | Input Validation | ✅ Enabled | Key length limits + character filtering |
17
- | Session Isolation | ✅ Enabled | Unique namespaces per session |
18
- | Context Isolation | ✅ Enabled | Separate storage per tenant |
19
- | No Code Injection | ✅ Enabled | No eval() or dynamic code execution |
20
- | XSS Prevention | ✅ Enabled | No innerHTML or document.write |
21
-
22
- ---
23
-
24
- ## 1. Cryptographically Secure Random Generation
25
-
26
- ### Implementation
27
-
28
- Session and context IDs are generated using cryptographically secure random values:
29
-
30
- ```typescript
31
- // config/platform.ts
32
- function generateSessionId(): string {
33
- // Priority 1: crypto.randomUUID (most secure)
34
- if (typeof crypto !== 'undefined' && crypto.randomUUID) {
35
- return crypto.randomUUID()
36
- }
37
-
38
- // Priority 2: crypto.getRandomValues (secure fallback)
39
- if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
40
- const array = new Uint8Array(16)
41
- crypto.getRandomValues(array)
42
- return Array.from(array, b => b.toString(16).padStart(2, '0')).join('')
43
- }
44
-
45
- // Priority 3: Math.random (last resort - less secure)
46
- return `session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`
47
- }
48
- ```
49
-
50
- ### Random Source Priority
51
-
52
- | Priority | Method | Security Level |
53
- |----------|--------|----------------|
54
- | 1 | `crypto.randomUUID()` | 🔒 FIPS 140-2 compliant |
55
- | 2 | `crypto.getRandomValues()` | 🔒 Cryptographically secure |
56
- | 3 | `Math.random()` | ⚠️ Not for security purposes |
57
-
58
- ---
59
-
60
- ## 2. Input Validation & Key Sanitization
61
-
62
- All storage keys are validated before use to prevent injection attacks:
63
-
64
- ### Validation Rules
65
-
66
- | Rule | Limit | Action on Violation |
67
- |------|-------|---------------------|
68
- | Key Length | Max 512 chars | Reject with debug message |
69
- | Character Set | `[a-zA-Z0-9_.-]` | Reject with debug message |
70
- | Type Check | Must be string | Return empty/null |
71
-
72
- ### Implementation
73
-
74
- ```typescript
75
- function _prefixKey(name: string): string {
76
- // Validate key
77
- if (!name || typeof name !== 'string') return ''
78
- if (name.length > 512) {
79
- console.debug('Key too long (max 512 characters)')
80
- return ''
81
- }
82
- // Sanitize: only allow alphanumeric, underscore, dash, dot
83
- if (!/^[a-zA-Z0-9_.-]+$/.test(name)) {
84
- console.debug('Key contains invalid characters')
85
- return ''
86
- }
87
- return _sessionPrefix + name
88
- }
89
- ```
90
-
91
- ### Allowed Characters Table
92
-
93
- | Character Type | Allowed | Example |
94
- |----------------|---------|---------|
95
- | Lowercase | ✅ | `username`, `user_data` |
96
- | Uppercase | ✅ | `USER`, `UserName` |
97
- | Numbers | ✅ | `user123`, `data_2024` |
98
- | Underscore | ✅ | `user_name`, `_private` |
99
- | Dash | ✅ | `user-id`, `data-set` |
100
- | Dot | ✅ | `user.profile`, `data.json` |
101
- | Special Chars | ❌ | `<script>`, `../../../etc` |
102
-
103
- ---
104
-
105
- ## 3. Session Isolation
106
-
107
- Each session gets a unique namespace to prevent data leakage:
108
-
109
- ### Isolation Mechanism
110
-
111
- | Component | Without Context | With Context |
112
- |-----------|-----------------|--------------|
113
- | Session ID | `crypto.randomUUID()` | Context name |
114
- | Store Keys | `memorio_store_[uuid]-keyname` | `[contextName]-keyname` |
115
- | Session Keys | `memorio_session_[uuid]-keyname` | `[contextName]-keyname` |
116
- | State | In-memory (per-instance) | In-memory (per-instance) |
117
-
118
- ### Key Prefix Format
119
-
120
- ```
121
- // Without context:
122
- memorio_store-[session-uuid]-username
123
- memorio_session-[session-uuid]-auth-token
124
-
125
- // With context (createContext('user-123')):
126
- user-123-username
127
- user-123-auth-token
128
- ```
129
-
130
- ### Cross-Session Protection
131
-
132
- | Scenario | Protection |
133
- |----------|------------|
134
- | Browser Tabs | Each tab has unique session ID |
135
- | Server Requests | Each request can use separate context |
136
- | Multi-Tenant | `memorio.createContext()` isolates tenants |
137
-
138
- ---
139
-
140
- ## 4. Context Isolation (Multi-Tenant)
141
-
142
- For server-side applications, contexts provide complete data isolation:
143
-
144
- ```typescript
145
- // Create isolated context per tenant
146
- const tenantA = memorio.isolate('tenant-A')
147
- const tenantB = memorio.isolate('tenant-B')
148
-
149
- // Each context has completely separate storage
150
- tenantA.state.secret = 'Tenant A data' // Isolated
151
- tenantB.state.secret = 'Tenant B data' // Isolated
152
- ```
153
-
154
- ### Context Security
155
-
156
- | Feature | Description |
157
- |---------|-------------|
158
- | Unique ID | Each context gets unique identifier |
159
- | Separate Storage | State, Store, Session, Cache all isolated |
160
- | No Cross-Context Access | Impossible to read other contexts |
161
- | Cleanup | `deleteContext()` removes all data |
162
-
163
- ---
164
-
165
- ## 5. Data Serialization Security
166
-
167
- ### Safe Operations
168
-
169
- | Operation | Security Measure |
170
- |-----------|-----------------|
171
- | `store.set()` | JSON.stringify only allowed types |
172
- | `store.get()` | JSON.parse with try-catch |
173
- | Functions | Blocked with debug message |
174
- | Objects | Deep-cloned on read |
175
-
176
- ### Blocked Types
177
-
178
- ```typescript
179
- // These are blocked and logged:
180
- store.set('myFunc', () => {}) // "It's not secure to store functions."
181
- store.set('mySymbol', Symbol('test')) // Would fail serialization
182
- ```
183
-
184
- ---
185
-
186
- ## 6. Platform-Specific Security
187
-
188
- ### Browser Environment
189
-
190
- | Feature | Security |
191
- |---------|----------|
192
- | localStorage | Same-origin policy applies |
193
- | sessionStorage | Tab isolation |
194
- | IndexedDB | Same-origin policy |
195
- | HTTPS Required | Recommended for production |
196
-
197
- ### Server Environment (Node.js/Deno)
198
-
199
- | Feature | Security |
200
- |---------|----------|
201
- | In-Memory Storage | Process-scoped only |
202
- | Context Isolation | Per-request isolation recommended |
203
- | No Persistence | Data lost on restart (by design) |
204
-
205
- ---
206
-
207
- ## 7. Security Best Practices
208
-
209
- ### For Developers
210
-
211
- 1. **Use Contexts in Server Apps**
212
- ```typescript
213
- // Express middleware
214
- app.use((req, res, next) => {
215
- req.memorio = memorio.createContext(`req-${req.id}`)
216
- next()
217
- })
218
- ```
219
-
220
- 2. **Validate Keys**
221
- ```typescript
222
- // Don't use user input directly as keys
223
- const safeKey = sanitize(userInput) // Input validation
224
- store.set(safeKey, value)
225
- ```
226
-
227
- 3. **Check Persistence**
228
- ```typescript
229
- if (!store.isPersistent) {
230
- console.warn('Data not persisted!')
231
- }
232
- ```
233
-
234
- 4. **Clear Sensitive Data**
235
- ```typescript
236
- // On logout
237
- session.removeAll()
238
- state.removeAll()
239
- ```
240
-
241
- ### For Security Audits
242
-
243
- | Check | Location |
244
- |-------|----------|
245
- | Random Generation | `config/platform.ts:44` |
246
- | Key Validation | `functions/store/index.ts:31` |
247
- | Session Isolation | `functions/session/index.ts:27` |
248
- | Context System | `config/platform.ts:301` |
249
-
250
- ---
251
-
252
- ## 8. Vulnerability Prevention
253
-
254
- ### Prevention Matrix
255
-
256
- | Vulnerability | Prevention | Status |
257
- |---------------|------------|--------|
258
- | XSS | No innerHTML/document.write | ✅ |
259
- | Code Injection | No eval/Function | ✅ |
260
- | Key Injection | Character whitelist | ✅ |
261
- | DoS | 512 char key limit | ✅ |
262
- | Session Hijacking | Unique session IDs | ✅ |
263
- | Data Leakage | Namespace isolation | ✅ |
264
- | CSRF | Browser Same-Origin | ✅ |
265
-
266
- ---
267
-
268
- ## 9. Compliance
269
-
270
- ### Standards Alignment
271
-
272
- | Standard | Compliance |
273
- |----------|------------|
274
- | NIST SP 800-53 | ✅ Cryptographic standards |
275
- | OWASP Top 10 | ✅ Key injection prevention |
276
- | CWE | ✅ Common weaknesses addressed |
277
- | FIPS 140-2 | ✅ crypto.randomUUID |
278
-
279
- ---
280
-
281
- ## 10. Reporting Security Issues
282
-
283
- If you discover a security vulnerability in Memorio:
284
-
285
- 1. **Do NOT** open a public GitHub issue
286
- 2. **Email**: security@example.com (replace with actual contact)
287
- 3. **Include**: Vulnerability details, steps to reproduce, potential impact
288
-
289
- ### Response Timeline
290
-
291
- | Phase | Timeline |
292
- |-------|----------|
293
- | Acknowledgment | 48 hours |
294
- | Initial Assessment | 7 days |
295
- | Fix Released | Based on severity |
296
-
297
- ---
298
-
299
- ## Security Changelog
300
-
301
- ### v3.0.2 (Current)
302
-
303
- - ✅ Removed esbuild-sass-plugin / esbuild-scss-modules-plugin (SCSS attack vector eliminated)
304
- - ✅ `store.set()` now blocks function values instead of silently continuing
305
- - ✅ All `PRIVATE License` headers in `functions/idb/` replaced with `MIT`
306
- - ✅ `buildPathTracker` dead code removed from state
307
- - ✅ `Object.freeze(observer)` call removed (undeclared variable, caused `ReferenceError`)
308
- - ✅ `confirm()` removed from `idb.db.delete()` (no blocking UI calls in libraries)
309
- - ✅ Fully generated changelog for v3.0.2 across all github docs
310
-
311
- ---
312
-
313
- ### v2.7.0 - Previous
314
-
315
- - ✅ Added `crypto.getRandomValues()` fallback
316
- - ✅ Added key length validation (512 chars)
317
- - ✅ Added character whitelist validation
318
- - ✅ Improved session isolation
319
- - ✅ Context isolation for multi-tenancy
320
-
321
- ---
322
-
323
- *This document was last updated for Memorio v3.0.2*
@@ -1,154 +0,0 @@
1
- # Session - Memorio
2
-
3
- > 🖥️ **Browser & Edge**: Uses sessionStorage for persistence
4
- > ⚙️ **Node.js/Deno**: Falls back to in-memory storage (not persistent)
5
-
6
- Session provides temporary storage using browser sessionStorage. Data persists until the tab or window is closed.
7
-
8
- ## Installation
9
-
10
- ```bash
11
- npm install memorio
12
- ```
13
-
14
- ```javascript
15
- import 'memorio';
16
- ```
17
-
18
- ---
19
-
20
- ## Quick Examples
21
-
22
- ### Example 1: Basic Usage
23
-
24
- ```javascript
25
- // Save session data
26
- session.set('token', 'abc123');
27
- session.set('userId', 42);
28
-
29
- // Read session data
30
- console.debug(session.get('token')); // "abc123"
31
-
32
- // Check persistence
33
- console.debug(session.isPersistent); // true in browser, false in Node.js/Deno
34
- ```
35
-
36
- ### Example 2: Intermediate
37
-
38
- ```javascript
39
- // Store objects
40
- session.set('user', { name: 'Mario', role: 'admin' });
41
-
42
- // Remove specific item
43
- session.remove('token');
44
-
45
- // Clear all session data
46
- session.removeAll();
47
- ```
48
-
49
- ### Example 3: Advanced
50
-
51
- ```javascript
52
- // Check if session has data
53
- if (session.get('authToken')) {
54
- // User is logged in
55
- }
56
-
57
- // Get storage quota (returns Promise<[usage, quota]> in KB)
58
- const [used, total] = await session.quota();
59
- console.debug(`Using ${used} out of ${total} KB`);
60
-
61
- // Get total size in characters
62
- const size = session.size();
63
- console.debug(`${size} bytes`);
64
-
65
- // Handle session expiry
66
- window.addEventListener('storage', (e) => {
67
- if (e.key === 'session' && !e.newValue) {
68
- // Session cleared
69
- redirectToLogin();
70
- }
71
- });
72
- ```
73
-
74
- ---
75
-
76
- ## API Reference
77
-
78
- ### Methods
79
-
80
- | Method | Parameters | Returns | Description |
81
- |--------|------------|---------|-------------|
82
- | `session.get(name)` | `name: string` | `any` | Get value from session |
83
- | `session.set(name, value)` | `name: string, value: any` | `void` | Save value to session |
84
- | `session.remove(name)` | `name: string` | `boolean` | Remove single item |
85
- | `session.delete(name)` | `name: string` | `boolean` | Alias for remove |
86
- | `session.removeAll()` | `none` | `boolean` | Clear all session data |
87
- | `session.clearAll()` | `none` | `boolean` | Alias for removeAll |
88
- | `session.size()` | `none` | `number` | Get total size in characters |
89
- | `session.quota()` | `none` | `Promise<[number, number]>` | Get storage usage/quota in KB |
90
-
91
- ### Properties
92
-
93
- | Property | Type | Description |
94
- |----------|------|-------------|
95
- | `session.isPersistent` | `boolean` | `true` if using real sessionStorage, `false` if in-memory fallback |
96
-
97
- ---
98
-
99
- ## Store vs Session
100
-
101
- | Feature | Store | Session |
102
- |---------|-------|---------|
103
- | Storage | localStorage | sessionStorage |
104
- | Lifetime | Forever | Until tab closes |
105
- | Use case | User preferences | Temporary auth |
106
- | Shared across tabs | Yes | No |
107
- | Platform | Browser/Edge | Browser/Edge |
108
- | Persistence | ✅ Always | ✅ Browser only |
109
-
110
- ---
111
-
112
- ## Platform Notes
113
-
114
- | Platform | Behavior |
115
- |----------|----------|
116
- | Browser | Uses real sessionStorage - data persists until tab closes |
117
- | Edge Worker | Uses real sessionStorage |
118
- | Node.js | In-memory fallback - data lost on process restart |
119
- | Deno | In-memory fallback - data lost on process restart |
120
-
121
- ---
122
-
123
- ## Best Practices
124
-
125
- 1. Use for auth tokens: `session.set('token', jwt)`
126
- 2. Clear on logout: `session.removeAll()`
127
- 3. Don't use for persistent data
128
- 4. Check for null: `session.get('key') || defaultValue`
129
-
130
- ---
131
-
132
- ## Common Use Cases
133
-
134
- ### Authentication
135
-
136
- ```javascript
137
- // Login
138
- session.set('authToken', response.token);
139
- session.set('user', response.user);
140
-
141
- // Logout
142
- session.removeAll();
143
- router.push('/login');
144
- ```
145
-
146
- ### Form Progress
147
-
148
- ```javascript
149
- // Save form draft
150
- session.set('formDraft', formData);
151
-
152
- // Restore on page refresh
153
- const draft = session.get('formDraft');
154
- if (draft) restoreForm(draft);
package/markdown/STATE.md DELETED
@@ -1,153 +0,0 @@
1
- # State - Memorio
2
-
3
- > ✅ **Universal**: Works in Browser, Node.js, Deno, and Edge Workers
4
-
5
- State is a reactive global state manager using JavaScript Proxies. It's simple, powerful, and requires no setup. Data persists only in memory during the session.
6
-
7
- ## Installation
8
-
9
- ```bash
10
- npm install memorio
11
- ```
12
-
13
- ```javascript
14
- import 'memorio';
15
- ```
16
-
17
- That's it. `state` is now global.
18
-
19
- > **Classic `import`**: `state` is also a named export.
20
- > `import { state } from 'memorio'` returns the exact same proxy as `globalThis.state`.
21
-
22
- ---
23
-
24
- ## Quick Examples
25
-
26
- ### Example 1: Basic Usage
27
-
28
- ```javascript
29
- // Set a value
30
- state.name = 'Mario';
31
- state.age = 25;
32
-
33
- // Get a value
34
- console.debug(state.name); // "Mario"
35
-
36
- // Simple object
37
- state.user = { name: 'Luigi', level: 1 };
38
- ```
39
-
40
- ### Example 2: Intermediate
41
-
42
- ```javascript
43
- // Array operations
44
- state.items = [1, 2, 3];
45
- state.items.push(4);
46
- console.debug(state.items); // [1, 2, 3, 4]
47
-
48
- // Nested objects
49
- state.config = { theme: 'dark', lang: 'en' };
50
- state.config.theme = 'light';
51
-
52
- // List all states
53
- console.debug(state.list);
54
- ```
55
-
56
- ### Example 3: Advanced
57
-
58
- ```javascript
59
- // Lock state to prevent modifications
60
- state.frozenConfig = { maxUsers: 100 };
61
- state.frozenConfig.lock();
62
- // Now state.frozenConfig cannot be modified
63
-
64
- // Path tracking
65
- const path = state.user.path;
66
- console.debug(path.name); // "user"
67
- console.debug(path.profile.name); // "user.profile"
68
-
69
- // Get full path as string
70
- console.debug(state.user.__path); // "state.user"
71
-
72
- // Protected keys (internal use)
73
- console.debug(protect); // Array of protected keys
74
- ```
75
-
76
- ---
77
-
78
- ## API Reference
79
-
80
- ### Properties
81
-
82
- | Property | Type | Description |
83
- |----------|------|-------------|
84
- | `state.list` | Array | Get all current state keys (deep copy) |
85
- | `state.path` | Object | Get path tracker for current location |
86
- | `state.__path` | string | Get full path as string |
87
-
88
- ### Methods
89
-
90
- | Method | Parameters | Description |
91
- |--------|------------|-------------|
92
- | `state.remove(key)` | `key: string` | Remove a specific state |
93
- | `state.removeAll()` | none | Clear all states |
94
-
95
- ### Lock
96
-
97
- ```javascript
98
- // Lock an object or array
99
- state.myArray = [1, 2, 3];
100
- state.myArray.lock();
101
-
102
- // Now any modification will fail
103
- state.myArray.push(4); // Error: state 'myArray' is locked
104
- ```
105
-
106
- ---
107
-
108
- ## How It Works
109
-
110
- Memorio uses JavaScript `Proxy` to intercept get/set operations on the global `state` object. This allows:
111
-
112
- 1. **Reactivity** - Any change can trigger observers
113
- 2. **Nested objects** - Deep path tracking
114
- 3. **Type safety** - Full TypeScript support
115
-
116
- ---
117
-
118
- ## Platform Notes
119
-
120
- | Platform | Support | Notes |
121
- |----------|---------|-------|
122
- | Browser | ✅ Full | In-memory, lost on refresh |
123
- | Node.js | ✅ Full | In-memory, lost on restart |
124
- | Deno | ✅ Full | In-memory, lost on restart |
125
- | Edge Workers | ✅ Full | In-memory, lost on function cold start |
126
-
127
- **Note**: In server environments (Node.js/Deno), use `memorio.createContext()` for request isolation.
128
-
129
- ---
130
-
131
- ## Best Practices
132
-
133
- 1. Use descriptive keys: `state.userProfile` not `state.up`
134
- 2. Group related data: `state.cart.items` not `state.cartItems`
135
- 3. Lock static config: `state.appConfig.lock()`
136
- 4. Clean up on logout: `state.removeAll()`
137
- 5. Use path tracking for debugging: `state.myData.__path`
138
-
139
- ---
140
-
141
- ## Common Errors
142
-
143
- ```javascript
144
- // Error: protected key
145
- state._internal = 'value';
146
- // Output: "key _internal is protected"
147
-
148
- // Error: locked state
149
- state.locked = { x: 1 };
150
- state.locked.lock();
151
- state.locked.x = 2;
152
- // Output: "Error: state 'locked' is locked"
153
- ```