securenow 8.2.0 → 8.3.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.
package/NPM_README.md CHANGED
@@ -259,6 +259,23 @@ npx securenow notifications read-all
259
259
 
260
260
  ### Alerting
261
261
 
262
+ ### Revoke / kill sessions (new in 8.3)
263
+
264
+ ```js
265
+ const securenow = require('securenow/sessions');
266
+ app.use(securenow.guard()); // auto-detects NextAuth/connect.sid/JWT sessions; rejects revoked ones (401)
267
+ // ...or check manually:
268
+ if (securenow.isRevoked({ sessionId, userId })) return res.status(401).send('re-auth');
269
+ ```
270
+
271
+ Revoke from the CLI (the SDK enforces within ~seconds, outbound-only, fail-open):
272
+
273
+ ```bash
274
+ npx securenow revoke session <session-id> --reason "impossible travel"
275
+ npx securenow revoke user <user-id> --duration 7d # kill all of a user's sessions
276
+ npx securenow revoke list
277
+ ```
278
+
262
279
  ### Emit custom security events (new in 8.2)
263
280
 
264
281
  ```js
package/cli/security.js CHANGED
@@ -583,6 +583,88 @@ async function blocklistList(args, flags) {
583
583
  }
584
584
  }
585
585
 
586
+ async function revokeRoute(args, flags) {
587
+ const sub = args[0];
588
+ if (sub === 'list') return revokeList(args.slice(1), flags);
589
+ if (sub === 'restore') return revokeRestore(args.slice(1), flags);
590
+ if (sub === 'session' || sub === 'user') return revokeAdd(sub, args.slice(1), flags);
591
+ ui.error('Usage: securenow revoke <session <id> | user <id> | list | restore <id>> [--reason "..."] [--duration 24h] [--app <key>] [--env <env>]');
592
+ process.exit(1);
593
+ }
594
+
595
+ async function revokeAdd(type, args, flags) {
596
+ requireAuth();
597
+ const value = args[0];
598
+ if (!value) {
599
+ ui.error(`Usage: securenow revoke ${type} <${type === 'session' ? 'session-id' : 'user-id'}> [--reason "..."] [--duration 24h] [--app <key>] [--env <env>]`);
600
+ process.exit(1);
601
+ }
602
+ const body = { type, value, source: 'cli' };
603
+ if (flags.reason) body.reason = flags.reason;
604
+ if (flags.duration) body.duration = flags.duration;
605
+ if (flags.app || flags.apps) body.applicationKey = flags.app || flags.apps;
606
+ if (flags.env || flags.environment) body.environment = flags.env || flags.environment;
607
+
608
+ const s = ui.spinner(`Revoking ${type} ${value}`);
609
+ try {
610
+ const data = await api.post('/revocations', body);
611
+ s.stop(`Revoked ${type} ${ui.truncate(value, 24)}`);
612
+ if (flags.json) { ui.json(data); return; }
613
+ const r = data.revocation || data;
614
+ ui.keyValue([
615
+ ['ID', r._id || r.id || '-'],
616
+ ['Type', r.type || type],
617
+ ['Value', r.value || value],
618
+ ['Scope', r.applicationKey || 'all apps'],
619
+ ['Expires', r.expiresAt ? new Date(r.expiresAt).toISOString() : 'never'],
620
+ ]);
621
+ } catch (err) {
622
+ s.fail('Failed to revoke');
623
+ throw err;
624
+ }
625
+ }
626
+
627
+ async function revokeList(args, flags) {
628
+ requireAuth();
629
+ const s = ui.spinner('Fetching revocations');
630
+ try {
631
+ const query = {};
632
+ if (flags.type) query.type = flags.type;
633
+ if (flags.status) query.status = flags.status;
634
+ const data = await api.get('/revocations', { query });
635
+ const entries = data.revocations || [];
636
+ s.stop(`Found ${entries.length} revocation${entries.length !== 1 ? 's' : ''}`);
637
+ if (flags.json) { ui.json(entries); return; }
638
+ console.log('');
639
+ ui.table(['ID', 'Type', 'Value', 'Scope', 'Expires'], entries.map((r) => [
640
+ ui.c.dim(ui.truncate(r._id || r.id, 12)),
641
+ r.type,
642
+ ui.truncate(r.value, 28),
643
+ r.applicationKey || ui.c.dim('all'),
644
+ r.expiresAt ? new Date(r.expiresAt).toISOString().slice(0, 16) : ui.c.dim('never'),
645
+ ]));
646
+ console.log('');
647
+ } catch (err) {
648
+ s.fail('Failed to list revocations');
649
+ throw err;
650
+ }
651
+ }
652
+
653
+ async function revokeRestore(args, flags) {
654
+ requireAuth();
655
+ const id = args[0];
656
+ if (!id) { ui.error('Usage: securenow revoke restore <id> [--reason "..."]'); process.exit(1); }
657
+ const s = ui.spinner('Restoring');
658
+ try {
659
+ const data = await api.post(`/revocations/${id}/restore`, { reason: flags.reason || '' });
660
+ s.stop('Revocation lifted');
661
+ if (flags.json) ui.json(data);
662
+ } catch (err) {
663
+ s.fail('Failed to restore');
664
+ throw err;
665
+ }
666
+ }
667
+
586
668
  async function blocklistAdd(args, flags) {
587
669
  requireAuth();
588
670
  let ip = args[0];
@@ -1337,6 +1419,7 @@ module.exports = {
1337
1419
  blocklistAdd,
1338
1420
  blocklistRemove,
1339
1421
  blocklistStats,
1422
+ revokeRoute,
1340
1423
  allowlistList,
1341
1424
  allowlistAdd,
1342
1425
  allowlistRemove,
package/cli.js CHANGED
@@ -437,6 +437,18 @@ const COMMANDS = {
437
437
  },
438
438
  defaultSub: 'list',
439
439
  },
440
+ revoke: {
441
+ desc: 'Revoke sessions/users (kill stolen sessions; the SDK enforces via securenow/sessions)',
442
+ usage: 'securenow revoke <session <id> | user <id> | list | restore <id>> [options]',
443
+ flags: { reason: 'Audit reason', duration: 'Expiry, e.g. 24h or 7d (default 7d)', app: 'Scope to app key', env: 'Scope to environment', environment: 'Alias for --env', type: 'List filter: session or user', status: 'List filter: active or restored', json: 'Output as JSON' },
444
+ sub: {
445
+ session: { desc: 'Revoke a session id', usage: 'securenow revoke session <session-id> [--reason <r>] [--duration 24h] [--app <key>]', run: (a, f) => require('./cli/security').revokeRoute(['session', ...a], f) },
446
+ user: { desc: 'Revoke all sessions of a user id', usage: 'securenow revoke user <user-id> [--reason <r>] [--duration 24h] [--app <key>]', run: (a, f) => require('./cli/security').revokeRoute(['user', ...a], f) },
447
+ list: { desc: 'List active revocations', run: (a, f) => require('./cli/security').revokeRoute(['list', ...a], f) },
448
+ restore: { desc: 'Lift a revocation', usage: 'securenow revoke restore <id> [--reason <r>]', run: (a, f) => require('./cli/security').revokeRoute(['restore', ...a], f) },
449
+ },
450
+ defaultSub: 'list',
451
+ },
440
452
  allowlist: {
441
453
  desc: 'Manage IP allowlist (only allow listed IPs)',
442
454
  usage: 'securenow allowlist <subcommand> [options]',
@@ -710,7 +722,7 @@ function showHelp(commandName) {
710
722
  'Detect & Respond': ['human', 'notifications', 'alerts', 'fp'],
711
723
  'Investigate': ['ip', 'forensics'],
712
724
  'Firewall': ['firewall'],
713
- 'Remediation': ['automation', 'ratelimit', 'blocklist', 'allowlist', 'trusted'],
725
+ 'Remediation': ['automation', 'ratelimit', 'blocklist', 'revoke', 'allowlist', 'trusted'],
714
726
  'Telemetry': ['log', 'event', 'test-span'],
715
727
  'Utilities': ['redact', 'cidr', 'doctor', 'env', 'mcp'],
716
728
  'Settings': ['instances', 'config', 'version'],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "securenow",
3
- "version": "8.2.0",
3
+ "version": "8.3.0",
4
4
  "description": "OpenTelemetry instrumentation for Node.js, Next.js, and Nuxt - Send traces and logs to any OTLP-compatible backend",
5
5
  "type": "commonjs",
6
6
  "main": "register.js",
@@ -54,6 +54,10 @@
54
54
  "types": "./events.d.ts",
55
55
  "default": "./events.js"
56
56
  },
57
+ "./sessions": {
58
+ "types": "./sessions.d.ts",
59
+ "default": "./sessions.js"
60
+ },
57
61
  "./console-instrumentation": {
58
62
  "default": "./console-instrumentation.js"
59
63
  },
@@ -118,6 +122,8 @@
118
122
  "tracing.d.ts",
119
123
  "events.js",
120
124
  "events.d.ts",
125
+ "sessions.js",
126
+ "sessions.d.ts",
121
127
  "console-instrumentation.js",
122
128
  "nextjs.js",
123
129
  "nextjs.d.ts",
package/sessions.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { IncomingMessage, ServerResponse } from "http";
2
+
3
+ export interface GuardOptions {
4
+ /** Extract the session id from a request. Defaults to NextAuth/connect.sid cookie or hashed Bearer token. */
5
+ getSessionId?: (req: IncomingMessage) => string | null | undefined;
6
+ /** Extract the user id from a request. Defaults to the JWT `sub` claim. */
7
+ getUserId?: (req: IncomingMessage) => string | null | undefined;
8
+ /** Custom rejection handler. Default: 401 + clears known session cookies. */
9
+ onRevoked?: (req: any, res: any, next: any, ctx: { sessionId: string | null; userId: string | null }) => void;
10
+ /** Background sync interval in ms (default 30000). */
11
+ syncIntervalMs?: number;
12
+ }
13
+
14
+ /** Start background revocation sync (called automatically by guard()). */
15
+ export function start(options?: GuardOptions): void;
16
+
17
+ /** Force one sync now. Best-effort; never throws. */
18
+ export function syncOnce(): Promise<boolean>;
19
+
20
+ /** Is this session/user currently revoked? */
21
+ export function isRevoked(input: { sessionId?: string | null; userId?: string | null }): boolean;
22
+
23
+ /** Express-style middleware that rejects revoked sessions/users. Fail-open. */
24
+ export function guard(options?: GuardOptions): (req: any, res: any, next: any) => void;
25
+
26
+ /** SHA-256 helper (used to hash raw session tokens consistently). */
27
+ export function sha256(value: string): string;
package/sessions.js ADDED
@@ -0,0 +1,238 @@
1
+ 'use strict';
2
+
3
+ // SecureNow session/user revocation enforcement (the "kill the stolen session"
4
+ // half of account-takeover response).
5
+ //
6
+ // const securenow = require('securenow/sessions');
7
+ // app.use(securenow.guard()); // auto-detects NextAuth/connect.sid/JWT sessions
8
+ // // ...or check manually in your auth middleware:
9
+ // if (securenow.isRevoked({ sessionId, userId })) return res.status(401)...
10
+ //
11
+ // The SDK pulls active revocations from SecureNow (outbound, ETag-cached) and
12
+ // checks each request locally — no inbound webhook, works behind NAT, portable
13
+ // to any language. Fail-open: a SecureNow/network outage never blocks traffic.
14
+
15
+ const crypto = require('crypto');
16
+ const appConfig = require('./app-config');
17
+
18
+ let _entries = new Map(); // "type:value" -> expiryMs (0 = never)
19
+ let _etag = null;
20
+ let _started = false;
21
+ let _timer = null;
22
+ let _syncIntervalMs = 30000;
23
+
24
+ function sha256(value) {
25
+ return crypto.createHash('sha256').update(String(value)).digest('hex');
26
+ }
27
+
28
+ function resolveSyncTarget() {
29
+ try {
30
+ const fw = appConfig.resolveFirewallOptions();
31
+ const apiUrl = String((fw && fw.apiUrl) || '').replace(/\/$/, '');
32
+ const apiKey = fw && fw.apiKey;
33
+ const resolvedApp = appConfig.resolveAll();
34
+ const appKey = resolvedApp && resolvedApp.appKey;
35
+ let env = 'production';
36
+ try { env = appConfig.resolveDeploymentEnvironment() || 'production'; } catch {}
37
+ if (!apiUrl || !apiKey || !appKey) return null;
38
+ const url = `${apiUrl}/api/v1/revocations/sync?app=${encodeURIComponent(appKey)}&env=${encodeURIComponent(env)}`;
39
+ return { url, apiKey, appKey };
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ function applyEntries(list) {
46
+ const next = new Map();
47
+ for (const e of list || []) {
48
+ if (!e || !e.type || !e.value) continue;
49
+ const exp = e.expiresAt ? Date.parse(e.expiresAt) : 0;
50
+ next.set(`${e.type}:${e.value}`, Number.isFinite(exp) ? exp : 0);
51
+ }
52
+ _entries = next;
53
+ }
54
+
55
+ function syncOnce() {
56
+ return new Promise((resolve) => {
57
+ const t = resolveSyncTarget();
58
+ if (!t) return resolve(false);
59
+ let parsed;
60
+ let lib;
61
+ try {
62
+ parsed = new (require('url').URL)(t.url);
63
+ lib = parsed.protocol === 'https:' ? require('https') : require('http');
64
+ } catch {
65
+ return resolve(false);
66
+ }
67
+ const headers = { Authorization: `Bearer ${t.apiKey}`, 'x-securenow-app-key': t.appKey };
68
+ if (_etag) headers['if-none-match'] = _etag;
69
+ const req = lib.request(
70
+ {
71
+ method: 'GET',
72
+ hostname: parsed.hostname,
73
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
74
+ path: parsed.pathname + parsed.search,
75
+ headers,
76
+ timeout: 5000,
77
+ },
78
+ (res) => {
79
+ if (res.statusCode === 304) {
80
+ res.resume();
81
+ return resolve(true);
82
+ }
83
+ const etag = res.headers.etag;
84
+ const chunks = [];
85
+ res.on('data', (c) => chunks.push(c));
86
+ res.on('end', () => {
87
+ if (res.statusCode >= 200 && res.statusCode < 300) {
88
+ try {
89
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
90
+ applyEntries(body && body.revocations && body.revocations.entries);
91
+ if (etag) _etag = etag;
92
+ } catch {}
93
+ return resolve(true);
94
+ }
95
+ return resolve(false);
96
+ });
97
+ }
98
+ );
99
+ req.on('error', () => resolve(false));
100
+ req.on('timeout', () => {
101
+ try { req.destroy(); } catch {}
102
+ resolve(false);
103
+ });
104
+ req.end();
105
+ });
106
+ }
107
+
108
+ function isExpired(exp) {
109
+ return exp && Date.now() > exp;
110
+ }
111
+
112
+ /**
113
+ * Is this session/user currently revoked? Pass whatever you have.
114
+ * @param {{sessionId?: string, userId?: string}} input
115
+ */
116
+ function isRevoked(input) {
117
+ if (!input) return false;
118
+ const sid = input.sessionId != null ? String(input.sessionId) : null;
119
+ const uid = input.userId != null ? String(input.userId) : null;
120
+ if (sid) {
121
+ const e = _entries.get(`session:${sid}`);
122
+ if (e !== undefined && !isExpired(e)) return true;
123
+ }
124
+ if (uid) {
125
+ const e = _entries.get(`user:${uid}`);
126
+ if (e !== undefined && !isExpired(e)) return true;
127
+ }
128
+ return false;
129
+ }
130
+
131
+ function start(options = {}) {
132
+ if (options.syncIntervalMs) _syncIntervalMs = options.syncIntervalMs;
133
+ if (_started) return;
134
+ _started = true;
135
+ syncOnce();
136
+ _timer = setInterval(syncOnce, _syncIntervalMs);
137
+ if (_timer && typeof _timer.unref === 'function') _timer.unref();
138
+ }
139
+
140
+ // --- Tier-0 auto session detection (zero app code) -------------------------
141
+ const SESSION_COOKIES = [
142
+ '__Secure-next-auth.session-token',
143
+ '__Host-next-auth.session-token',
144
+ 'next-auth.session-token',
145
+ 'connect.sid',
146
+ 'session',
147
+ 'sid',
148
+ ];
149
+
150
+ function parseCookies(header) {
151
+ const out = {};
152
+ if (!header) return out;
153
+ for (const part of String(header).split(';')) {
154
+ const i = part.indexOf('=');
155
+ if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim();
156
+ }
157
+ return out;
158
+ }
159
+
160
+ // Mirrors how an auto-adapter emits session.id/enduser.id: hash the raw
161
+ // cookie/token; read the JWT `sub` for the user id.
162
+ function defaultExtract(req) {
163
+ let sessionId = null;
164
+ let userId = null;
165
+ const headers = req.headers || {};
166
+ const auth = headers.authorization || headers.Authorization;
167
+ if (auth && /^Bearer\s+/i.test(auth)) {
168
+ const token = auth.replace(/^Bearer\s+/i, '').trim();
169
+ if (token) {
170
+ sessionId = sha256(token);
171
+ try {
172
+ const seg = token.split('.')[1] || '';
173
+ const payload = JSON.parse(Buffer.from(seg, 'base64').toString('utf8'));
174
+ if (payload && payload.sub) userId = String(payload.sub);
175
+ } catch {}
176
+ }
177
+ }
178
+ if (!sessionId && headers.cookie) {
179
+ const cookies = parseCookies(headers.cookie);
180
+ for (const name of SESSION_COOKIES) {
181
+ if (cookies[name]) {
182
+ sessionId = sha256(cookies[name]);
183
+ break;
184
+ }
185
+ }
186
+ }
187
+ return { sessionId, userId };
188
+ }
189
+
190
+ function defaultOnRevoked(req, res) {
191
+ try {
192
+ const clears = SESSION_COOKIES.map((n) => `${n}=; Path=/; Max-Age=0; HttpOnly`);
193
+ if (typeof res.setHeader === 'function') res.setHeader('Set-Cookie', clears);
194
+ } catch {}
195
+ if (typeof res.status === 'function' && typeof res.json === 'function') {
196
+ return res.status(401).json({ error: 'Session revoked. Please sign in again.', code: 'session_revoked' });
197
+ }
198
+ res.statusCode = 401;
199
+ try { res.end('Session revoked'); } catch {}
200
+ }
201
+
202
+ /**
203
+ * Express-style middleware that rejects requests whose session/user is revoked.
204
+ * Starts background sync on first use. Fail-open and never throws.
205
+ *
206
+ * @param {object} [options]
207
+ * @param {(req)=>string} [options.getSessionId] Custom session id extractor.
208
+ * @param {(req)=>string} [options.getUserId] Custom user id extractor.
209
+ * @param {(req,res,next,ctx)=>void} [options.onRevoked] Custom rejection handler.
210
+ * @param {number} [options.syncIntervalMs]
211
+ */
212
+ function guard(options = {}) {
213
+ start(options);
214
+ const { getSessionId, getUserId } = options;
215
+ const onRevoked = options.onRevoked || defaultOnRevoked;
216
+ return function securenowSessionGuard(req, res, next) {
217
+ try {
218
+ let sessionId = null;
219
+ let userId = null;
220
+ if (getSessionId || getUserId) {
221
+ if (getSessionId) sessionId = getSessionId(req);
222
+ if (getUserId) userId = getUserId(req);
223
+ } else {
224
+ const d = defaultExtract(req);
225
+ sessionId = d.sessionId;
226
+ userId = d.userId;
227
+ }
228
+ if (isRevoked({ sessionId, userId })) {
229
+ return onRevoked(req, res, next, { sessionId, userId });
230
+ }
231
+ } catch {
232
+ /* fail-open */
233
+ }
234
+ return next();
235
+ };
236
+ }
237
+
238
+ module.exports = { start, syncOnce, isRevoked, guard, sha256 };