@astratra/security 1.9.1 → 1.11.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/README.md +267 -0
- package/package.json +1 -1
- package/src/index.d.ts +387 -0
- package/src/index.js +5 -1
- package/src/loginDevices.js +298 -0
- package/src/privateFileLinks.js +327 -0
- package/src/refreshTokens.js +214 -0
- package/src/trustedDevices.js +390 -0
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Knowing when an account is used from somewhere new, and saying so.
|
|
3
|
+
*
|
|
4
|
+
* Two alerts, one purpose: the person whose account is being taken over must
|
|
5
|
+
* hear about it while there is still time to act.
|
|
6
|
+
*
|
|
7
|
+
* A NEW SIGN-IN DEVICE. "Device" is the user agent plus the network FAMILY of
|
|
8
|
+
* the address — /16 in IPv4, /48 in IPv6. A finer family (/24) changed every
|
|
9
|
+
* time a mobile carrier switched antenna: a parent got an alert a day for
|
|
10
|
+
* their own phone, and an alert that rings every day is no longer read.
|
|
11
|
+
* Nothing is kept in the clear, only an HMAC fingerprint, and a bounded number
|
|
12
|
+
* per account (the least recently seen leave first).
|
|
13
|
+
*
|
|
14
|
+
* No alert on an account's very first sign-in: there is nothing to compare
|
|
15
|
+
* with, and the person is the one who just created it.
|
|
16
|
+
*
|
|
17
|
+
* A SENSITIVE CHANGE — password, e-mail, sign-in factors. A code was sent to
|
|
18
|
+
* AUTHORISE a change, but nothing confirmed it had happened; the victim learnt
|
|
19
|
+
* it the day they could no longer sign in. The confirmation afterwards is the
|
|
20
|
+
* one that protects. Two rules carry it:
|
|
21
|
+
*
|
|
22
|
+
* 1. An e-mail change is announced to the PREVIOUS address. The new one is
|
|
23
|
+
* already in the hands of whoever made the change: writing there warns
|
|
24
|
+
* nobody.
|
|
25
|
+
* 2. A failed send NEVER fails the change. The password is already changed
|
|
26
|
+
* when we get here; an error would make the person believe otherwise, and
|
|
27
|
+
* they would retry with the old one.
|
|
28
|
+
*
|
|
29
|
+
* NO WORDS HERE. This module decides WHEN to warn and WHOM; the caller turns a
|
|
30
|
+
* catalogue key and the account's locale into text, in its own language files.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
const crypto = require('crypto');
|
|
34
|
+
|
|
35
|
+
const DEFAULT_MAX_DEVICES = 8;
|
|
36
|
+
const MAX_USER_AGENT = 512;
|
|
37
|
+
|
|
38
|
+
/* ─────────────────────────── Address families ─────────────────────────── */
|
|
39
|
+
|
|
40
|
+
/** Expand an IPv6 literal to its eight groups, or null. */
|
|
41
|
+
function ipv6Groups(value) {
|
|
42
|
+
let text = value.split('%')[0];
|
|
43
|
+
/* An embedded IPv4 tail (::1.2.3.4) counts as two groups. */
|
|
44
|
+
const v4 = text.match(/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
45
|
+
if (v4) {
|
|
46
|
+
const [a, b, c, d] = v4.slice(1).map(Number);
|
|
47
|
+
text = text.slice(0, -v4[0].length) + `${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;
|
|
48
|
+
}
|
|
49
|
+
const halves = text.split('::');
|
|
50
|
+
if (halves.length > 2) return null;
|
|
51
|
+
const head = halves[0] ? halves[0].split(':') : [];
|
|
52
|
+
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
|
|
53
|
+
const missing = 8 - head.length - tail.length;
|
|
54
|
+
if (halves.length === 1 ? missing !== 0 : missing < 1) return null;
|
|
55
|
+
const groups = [...head, ...Array(halves.length === 2 ? missing : 0).fill('0'), ...tail];
|
|
56
|
+
if (!groups.every((group) => /^[0-9a-f]{1,4}$/i.test(group))) return null;
|
|
57
|
+
return groups.map((group) => parseInt(group, 16).toString(16));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The network family an address belongs to.
|
|
62
|
+
*
|
|
63
|
+
* IPv6 is EXPANDED before cutting. Splitting the literal on ':' gave
|
|
64
|
+
* "2001:db8::5" and "2001:db8:0:1::5" two different families for the same
|
|
65
|
+
* /48, so the same phone raised a "new device" alert depending on how its
|
|
66
|
+
* address happened to be written.
|
|
67
|
+
*/
|
|
68
|
+
function ipFamily(ip) {
|
|
69
|
+
const value = String(ip || '').trim().toLowerCase().replace(/^::ffff:(?=\d)/, '');
|
|
70
|
+
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(value)) {
|
|
71
|
+
const parts = value.split('.').map(Number);
|
|
72
|
+
if (parts.some((part) => part > 255)) return 'unknown';
|
|
73
|
+
return `${parts[0]}.${parts[1]}.0.0/16`;
|
|
74
|
+
}
|
|
75
|
+
if (value.includes(':')) {
|
|
76
|
+
const groups = ipv6Groups(value);
|
|
77
|
+
if (!groups) return 'unknown';
|
|
78
|
+
return `${groups.slice(0, 3).join(':')}::/48`;
|
|
79
|
+
}
|
|
80
|
+
return 'unknown';
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/* ─────────────────────────── Sign-in devices ─────────────────────────── */
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* In-memory store. Dev and tests only.
|
|
87
|
+
* Contract: upsert() must be ATOMIC — two simultaneous sign-ins from the same
|
|
88
|
+
* device must yield exactly one `inserted: true`, or the person gets two alerts.
|
|
89
|
+
* With MongoDB: updateOne({ accountId, fingerprint }, { $set, $setOnInsert },
|
|
90
|
+
* { upsert: true }) and `inserted = upsertedCount === 1`, plus a unique index.
|
|
91
|
+
*/
|
|
92
|
+
function createMemoryLoginDeviceStore() {
|
|
93
|
+
const rows = new Map();
|
|
94
|
+
const key = (accountId, fingerprint) => `${accountId}\u0000${fingerprint}`;
|
|
95
|
+
return {
|
|
96
|
+
async upsert(accountId, fingerprint, at) {
|
|
97
|
+
const existing = rows.get(key(accountId, fingerprint));
|
|
98
|
+
if (existing) {
|
|
99
|
+
existing.lastSeenAt = at;
|
|
100
|
+
return { inserted: false };
|
|
101
|
+
}
|
|
102
|
+
rows.set(key(accountId, fingerprint), { accountId, fingerprint, firstSeenAt: at, lastSeenAt: at });
|
|
103
|
+
return { inserted: true };
|
|
104
|
+
},
|
|
105
|
+
async count(accountId) {
|
|
106
|
+
return [...rows.values()].filter((row) => row.accountId === accountId).length;
|
|
107
|
+
},
|
|
108
|
+
async keepMostRecent(accountId, keep) {
|
|
109
|
+
const mine = [...rows.values()].filter((row) => row.accountId === accountId)
|
|
110
|
+
.sort((a, b) => b.lastSeenAt - a.lastSeenAt);
|
|
111
|
+
for (const row of mine.slice(keep)) rows.delete(key(row.accountId, row.fingerprint));
|
|
112
|
+
},
|
|
113
|
+
async all() {
|
|
114
|
+
return [...rows.values()].map((row) => ({ ...row }));
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* @param {object} options
|
|
121
|
+
* @param {object} options.store upsert/count/keepMostRecent.
|
|
122
|
+
* @param {string} options.secret HMAC key for fingerprints — dedicated, not the
|
|
123
|
+
* session secret.
|
|
124
|
+
* @param {(account: object, event: {type: 'new-login-device', at: number}) => Promise<void>} options.notify
|
|
125
|
+
* Tell the account holder. You pick the catalogue key and the locale.
|
|
126
|
+
* @param {number} [options.maxDevices=8]
|
|
127
|
+
* @param {(error: Error) => void} [options.onError]
|
|
128
|
+
* @param {() => number} [options.now]
|
|
129
|
+
*/
|
|
130
|
+
function createLoginDeviceTracker(options = {}) {
|
|
131
|
+
const { store, secret, notify } = options;
|
|
132
|
+
if (!store || typeof store.upsert !== 'function' || typeof store.count !== 'function') {
|
|
133
|
+
throw new Error('createLoginDeviceTracker requires options.store.');
|
|
134
|
+
}
|
|
135
|
+
if (typeof secret !== 'string' || secret.length < 16) {
|
|
136
|
+
throw new Error('createLoginDeviceTracker requires options.secret.');
|
|
137
|
+
}
|
|
138
|
+
if (typeof notify !== 'function') throw new Error('createLoginDeviceTracker requires options.notify.');
|
|
139
|
+
const maxDevices = options.maxDevices || DEFAULT_MAX_DEVICES;
|
|
140
|
+
const onError = options.onError || (() => {});
|
|
141
|
+
const now = options.now || Date.now;
|
|
142
|
+
|
|
143
|
+
function fingerprint({ ip, userAgent } = {}) {
|
|
144
|
+
const source = `${ipFamily(ip)}|${String(userAgent || 'unknown').slice(0, MAX_USER_AGENT)}`;
|
|
145
|
+
return crypto.createHmac('sha256', secret).update(source).digest('hex');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Call AFTER the session is granted. Never throws: the sign-in already
|
|
150
|
+
* succeeded, and a tracking failure must not turn it into an error.
|
|
151
|
+
*
|
|
152
|
+
* @param {{id: *}} account what `notify` receives back.
|
|
153
|
+
* @returns {Promise<{isNew: boolean, firstDevice: boolean, notified: boolean, error?: true}>}
|
|
154
|
+
*/
|
|
155
|
+
async function record(account, context = {}) {
|
|
156
|
+
try {
|
|
157
|
+
const accountId = String(account?.id ?? account?._id ?? '');
|
|
158
|
+
if (!accountId) throw new Error('record requires account.id.');
|
|
159
|
+
const at = now();
|
|
160
|
+
const { inserted } = await store.upsert(accountId, fingerprint(context), at);
|
|
161
|
+
if (!inserted) return { isNew: false, firstDevice: false, notified: false };
|
|
162
|
+
|
|
163
|
+
const total = await store.count(accountId);
|
|
164
|
+
if (total > maxDevices && typeof store.keepMostRecent === 'function') {
|
|
165
|
+
await store.keepMostRecent(accountId, maxDevices);
|
|
166
|
+
}
|
|
167
|
+
if (total <= 1) return { isNew: true, firstDevice: true, notified: false };
|
|
168
|
+
|
|
169
|
+
await notify(account, { type: 'new-login-device', at });
|
|
170
|
+
return { isNew: true, firstDevice: false, notified: true };
|
|
171
|
+
} catch (error) {
|
|
172
|
+
onError(error);
|
|
173
|
+
return { isNew: false, firstDevice: false, notified: false, error: true };
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return { record, fingerprint };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/* ─────────────────────────── Change alerts ─────────────────────────── */
|
|
181
|
+
|
|
182
|
+
const CHANGE_TYPES = Object.freeze([
|
|
183
|
+
'password',
|
|
184
|
+
'email',
|
|
185
|
+
'factor-added',
|
|
186
|
+
'factor-removed',
|
|
187
|
+
'recovery-codes',
|
|
188
|
+
'trusted-device'
|
|
189
|
+
]);
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* @param {object} options
|
|
193
|
+
* @param {(message: {to: string, key: string, locale?: string, change: string, detail?: string, account: object}) => Promise<unknown>} options.send
|
|
194
|
+
* Delivers the alert. `key` is `${keyPrefix}.${change}` — render subject and
|
|
195
|
+
* body from YOUR catalogue, in `locale`. Do not put an action link in it: a
|
|
196
|
+
* security alert must not teach people to click links received by e-mail.
|
|
197
|
+
* @param {string} [options.keyPrefix='security.change']
|
|
198
|
+
* @param {(account: object) => string|undefined} [options.localeOf] default account.locale.
|
|
199
|
+
* @param {(error: Error, change: string) => void} [options.onError]
|
|
200
|
+
*/
|
|
201
|
+
function createChangeAlerts(options = {}) {
|
|
202
|
+
const send = options.send;
|
|
203
|
+
if (typeof send !== 'function') throw new Error('createChangeAlerts requires options.send.');
|
|
204
|
+
const keyPrefix = options.keyPrefix || 'security.change';
|
|
205
|
+
const localeOf = options.localeOf || ((account) => account?.locale);
|
|
206
|
+
const onError = options.onError || (() => {});
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* @param {object} account the account that changed.
|
|
210
|
+
* @param {string} change one of CHANGE_TYPES.
|
|
211
|
+
* @param {object} [input]
|
|
212
|
+
* @param {string} [input.to] where to warn — the account address. For
|
|
213
|
+
* 'email', ignored: use previousEmail.
|
|
214
|
+
* @param {string} [input.previousEmail] 'email' only: the address BEFORE.
|
|
215
|
+
* @param {string} [input.newEmail] 'email' only: shown so the owner can
|
|
216
|
+
* recognise — or not — the address that replaced theirs.
|
|
217
|
+
* @param {string} [input.detail] e.g. the new device's name.
|
|
218
|
+
* @returns {Promise<boolean>} whether the alert was handed over. Never throws.
|
|
219
|
+
*/
|
|
220
|
+
async function alert(account, change, input = {}) {
|
|
221
|
+
if (!CHANGE_TYPES.includes(change)) throw new Error(`Unknown change type: ${change}`);
|
|
222
|
+
|
|
223
|
+
let to = input.to;
|
|
224
|
+
let detail = input.detail;
|
|
225
|
+
if (change === 'email') {
|
|
226
|
+
/* A FIRST address has no predecessor to warn, and belongs to the person
|
|
227
|
+
who just set it. */
|
|
228
|
+
to = input.previousEmail;
|
|
229
|
+
detail = input.newEmail;
|
|
230
|
+
if (to && input.newEmail && String(to).toLowerCase() === String(input.newEmail).toLowerCase()) return false;
|
|
231
|
+
}
|
|
232
|
+
if (!to) return false;
|
|
233
|
+
|
|
234
|
+
try {
|
|
235
|
+
await send({ to: String(to), key: `${keyPrefix}.${change}`, locale: localeOf(account), change, detail, account });
|
|
236
|
+
return true;
|
|
237
|
+
} catch (error) {
|
|
238
|
+
onError(error, change);
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return { alert, CHANGE_TYPES };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/* ─────────────────────────── Operator alerts ─────────────────────────── */
|
|
247
|
+
|
|
248
|
+
const ALERT_LEVELS = Object.freeze(['INFO', 'WARN', 'ERROR', 'FATAL']);
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Fan an operator alert (not a user-facing one) out to every channel you
|
|
252
|
+
* configured — webhook, dedicated mailbox, pager. One channel down must not
|
|
253
|
+
* silence the others, and an alert failure must never break the request that
|
|
254
|
+
* raised it.
|
|
255
|
+
*
|
|
256
|
+
* Send these to a DEDICATED mailbox, never the founder's personal one: an
|
|
257
|
+
* automated flow into a main inbox ends up ignored, and exposes the admin
|
|
258
|
+
* account in automated mail headers.
|
|
259
|
+
*
|
|
260
|
+
* @param {object} options
|
|
261
|
+
* @param {Array<(alert: object) => Promise<unknown>>} options.channels
|
|
262
|
+
* @param {(line: string, alert: object) => void} [options.log]
|
|
263
|
+
* @param {() => number} [options.now]
|
|
264
|
+
*/
|
|
265
|
+
function createSecurityAlerter(options = {}) {
|
|
266
|
+
const channels = Array.isArray(options.channels) ? options.channels.filter((fn) => typeof fn === 'function') : [];
|
|
267
|
+
const log = options.log || (() => {});
|
|
268
|
+
const now = options.now || Date.now;
|
|
269
|
+
|
|
270
|
+
/** @returns {Promise<boolean>} true when at least one channel delivered. */
|
|
271
|
+
async function send({ level = 'WARN', type = 'security', subject, message, meta = {} } = {}) {
|
|
272
|
+
const alertEvent = {
|
|
273
|
+
level: ALERT_LEVELS.includes(level) ? level : 'WARN',
|
|
274
|
+
type: String(type),
|
|
275
|
+
subject: subject || type,
|
|
276
|
+
message,
|
|
277
|
+
meta,
|
|
278
|
+
timestamp: new Date(now()).toISOString()
|
|
279
|
+
};
|
|
280
|
+
log(`[${alertEvent.level}] ${alertEvent.type}`, alertEvent);
|
|
281
|
+
if (channels.length === 0) return false;
|
|
282
|
+
const results = await Promise.allSettled(channels.map((channel) => Promise.resolve().then(() => channel(alertEvent))));
|
|
283
|
+
return results.some((result) => result.status === 'fulfilled' && result.value !== false);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return { send };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
module.exports = {
|
|
290
|
+
ipFamily,
|
|
291
|
+
createMemoryLoginDeviceStore,
|
|
292
|
+
createLoginDeviceTracker,
|
|
293
|
+
createChangeAlerts,
|
|
294
|
+
createSecurityAlerter,
|
|
295
|
+
CHANGE_TYPES,
|
|
296
|
+
ALERT_LEVELS,
|
|
297
|
+
DEFAULT_MAX_LOGIN_DEVICES: DEFAULT_MAX_DEVICES
|
|
298
|
+
};
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Private files behind short-lived links — one link per READER, never shared.
|
|
3
|
+
*
|
|
4
|
+
* An <img> tag or an audio player sends no Authorization header, so a private
|
|
5
|
+
* file cannot be protected by the session alone: the address itself has to
|
|
6
|
+
* carry a pass. That pass is where the real defects were.
|
|
7
|
+
*
|
|
8
|
+
* THE DEFECT THIS MODULE EXISTS FOR. A chat message with an attachment was
|
|
9
|
+
* broadcast in real time with its link already signed — signed for the
|
|
10
|
+
* SENDER, because the sender's request is the one that produced the message.
|
|
11
|
+
* The recipient opened the file by borrowing the sender's identity, and the
|
|
12
|
+
* pass expired a quarter of an hour later inside a conversation left open.
|
|
13
|
+
* The rule that follows: a broadcast carries the PATH only; each reader asks
|
|
14
|
+
* for their own link at the moment they display the file, and the server
|
|
15
|
+
* re-checks the right to read on that request.
|
|
16
|
+
*
|
|
17
|
+
* A LINK IS STABLE WITHIN A STEP. Signed "now", a link differed on every
|
|
18
|
+
* response for the same file. A thread polled every five seconds therefore
|
|
19
|
+
* produced a new address every time: no image cache recognised it, and an
|
|
20
|
+
* audio player whose source changed restarted mid-playback — a voice note
|
|
21
|
+
* never finished (measured: 202 requests in one minute, 79 MB served for five
|
|
22
|
+
* files weighing 600 KB). The pass is aligned on a time step: identical within
|
|
23
|
+
* a step, valid for two, so a link obtained just before a change still lives
|
|
24
|
+
* one full step.
|
|
25
|
+
*
|
|
26
|
+
* THE PASS IS HEX, END TO END. A JWT is base64url, which contains '-'. About
|
|
27
|
+
* one pass in a hundred carried a '--', which a WAF reads as an SQL comment in
|
|
28
|
+
* the query string: that file answered 403 to that person for the whole step,
|
|
29
|
+
* and nobody could reproduce it. Same lesson as the refresh tokens.
|
|
30
|
+
*
|
|
31
|
+
* THE PASS NAMES THE ACCOUNT AND ITS SESSION VERSION. Revoking sessions (a
|
|
32
|
+
* password change, "sign out everywhere") must also kill the passes already
|
|
33
|
+
* handed out; `accountVersion` is re-read at verification for that reason.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
const crypto = require('crypto');
|
|
37
|
+
const path = require('path');
|
|
38
|
+
|
|
39
|
+
const DEFAULT_STEP_SECONDS = 15 * 60;
|
|
40
|
+
const MIN_SECRET_LENGTH = 32;
|
|
41
|
+
const PURPOSE = 'private-file';
|
|
42
|
+
/* Kinds and ids end up in a URL path: anything outside these alphabets is a
|
|
43
|
+
path segment an attacker chose. */
|
|
44
|
+
const KIND_PATTERN = /^[A-Za-z0-9_-]{1,40}$/;
|
|
45
|
+
const FILE_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
46
|
+
const TICKET_PATTERN = /^[a-f0-9]+\.[a-f0-9]{64}$/;
|
|
47
|
+
const INLINE_MIME = /^(image\/(jpeg|png|gif|webp)|audio\/[a-z0-9.+-]+|video\/[a-z0-9.+-]+)$/;
|
|
48
|
+
|
|
49
|
+
const idOf = (value) => String(value?._id ?? value?.id ?? value ?? '');
|
|
50
|
+
|
|
51
|
+
function sameText(a, b) {
|
|
52
|
+
const left = Buffer.from(String(a || ''), 'utf8');
|
|
53
|
+
const right = Buffer.from(String(b || ''), 'utf8');
|
|
54
|
+
return left.length === right.length && crypto.timingSafeEqual(left, right);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @param {object} options
|
|
59
|
+
* @param {string} options.secret DEDICATED to file links, at least 32 chars.
|
|
60
|
+
* Reusing the session-signing secret means one leak forges both.
|
|
61
|
+
* @param {number} [options.stepSeconds=900]
|
|
62
|
+
* @param {string} [options.basePath='/files'] where the file route is mounted.
|
|
63
|
+
* @param {string} [options.ticketParam='ticket']
|
|
64
|
+
* @param {(accountId: string) => Promise<number|null|undefined>} [options.accountVersion]
|
|
65
|
+
* Current session version of an account, null when it no longer exists.
|
|
66
|
+
* Without it a pass survives a "sign out everywhere" until it expires.
|
|
67
|
+
* @param {() => number} [options.now]
|
|
68
|
+
*/
|
|
69
|
+
function createPrivateFileLinks(options = {}) {
|
|
70
|
+
const secret = options.secret;
|
|
71
|
+
if (typeof secret !== 'string' || secret.length < MIN_SECRET_LENGTH) {
|
|
72
|
+
throw new Error(`createPrivateFileLinks requires options.secret (at least ${MIN_SECRET_LENGTH} characters).`);
|
|
73
|
+
}
|
|
74
|
+
const stepSeconds = options.stepSeconds || DEFAULT_STEP_SECONDS;
|
|
75
|
+
const basePath = String(options.basePath || '/files').replace(/\/+$/, '');
|
|
76
|
+
const ticketParam = options.ticketParam || 'ticket';
|
|
77
|
+
const accountVersion = options.accountVersion;
|
|
78
|
+
const now = options.now || Date.now;
|
|
79
|
+
|
|
80
|
+
const digest = (payloadHex) => crypto.createHmac('sha256', secret).update(`${PURPOSE}:${payloadHex}`).digest('hex');
|
|
81
|
+
|
|
82
|
+
function assertTarget(kind, fileId) {
|
|
83
|
+
if (!KIND_PATTERN.test(String(kind))) throw new Error(`Invalid private file kind: ${kind}`);
|
|
84
|
+
if (!FILE_ID_PATTERN.test(String(fileId))) throw new Error('Invalid private file id.');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The address with no pass — the only form a broadcast may carry. */
|
|
88
|
+
function pathFor(kind, fileId) {
|
|
89
|
+
const id = idOf(fileId);
|
|
90
|
+
assertTarget(kind, id);
|
|
91
|
+
return `${basePath}/${kind}/${id}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Sign a pass for ONE reader and ONE file.
|
|
96
|
+
* @param {{kind: string, fileId: *, accountId: *, version?: number}} input
|
|
97
|
+
* @returns {{ticket: string, url: string, issuedAt: number, expiresAt: number}}
|
|
98
|
+
*/
|
|
99
|
+
function sign({ kind, fileId, accountId, version = 0 } = {}) {
|
|
100
|
+
const id = idOf(fileId);
|
|
101
|
+
const account = idOf(accountId);
|
|
102
|
+
assertTarget(kind, id);
|
|
103
|
+
if (!account) throw new Error('sign requires the reader accountId.');
|
|
104
|
+
|
|
105
|
+
const step = Math.floor(now() / 1000 / stepSeconds) * stepSeconds;
|
|
106
|
+
/* Array, not object: a fixed field order is what keeps the pass
|
|
107
|
+
byte-identical within a step. */
|
|
108
|
+
const payload = JSON.stringify([PURPOSE, kind, id, account, Number(version) || 0, step, step + 2 * stepSeconds]);
|
|
109
|
+
const payloadHex = Buffer.from(payload, 'utf8').toString('hex');
|
|
110
|
+
const ticket = `${payloadHex}.${digest(payloadHex)}`;
|
|
111
|
+
return {
|
|
112
|
+
ticket,
|
|
113
|
+
url: `${basePath}/${kind}/${id}?${ticketParam}=${ticket}`,
|
|
114
|
+
issuedAt: step * 1000,
|
|
115
|
+
expiresAt: (step + 2 * stepSeconds) * 1000
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Shorthand for the reader's own link: `linkFor(kind, file, { id, version })`. */
|
|
120
|
+
function linkFor(kind, fileId, reader) {
|
|
121
|
+
if (!reader) return null;
|
|
122
|
+
return sign({ kind, fileId, accountId: reader.id ?? reader._id, version: reader.version ?? reader.tokenVersion ?? 0 }).url;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Check a pass against the file actually requested.
|
|
127
|
+
*
|
|
128
|
+
* @returns {Promise<{valid: true, accountId: string, version: number, expiresAt: number}
|
|
129
|
+
* | {valid: false, reason: 'missing'|'malformed'|'bad-signature'|'expired'|'wrong-file'|'unknown-account'|'revoked'}>}
|
|
130
|
+
*/
|
|
131
|
+
async function verify(ticket, { kind, fileId } = {}) {
|
|
132
|
+
if (!ticket || typeof ticket !== 'string') return { valid: false, reason: 'missing' };
|
|
133
|
+
if (!TICKET_PATTERN.test(ticket)) return { valid: false, reason: 'malformed' };
|
|
134
|
+
|
|
135
|
+
const [payloadHex, signature] = ticket.split('.');
|
|
136
|
+
/* Signature FIRST, parse second: parsing an unverified payload runs the
|
|
137
|
+
JSON parser on whatever an attacker sent. */
|
|
138
|
+
if (!sameText(digest(payloadHex), signature)) return { valid: false, reason: 'bad-signature' };
|
|
139
|
+
|
|
140
|
+
let claims;
|
|
141
|
+
try {
|
|
142
|
+
claims = JSON.parse(Buffer.from(payloadHex, 'hex').toString('utf8'));
|
|
143
|
+
} catch {
|
|
144
|
+
return { valid: false, reason: 'malformed' };
|
|
145
|
+
}
|
|
146
|
+
if (!Array.isArray(claims) || claims.length !== 7 || claims[0] !== PURPOSE) return { valid: false, reason: 'malformed' };
|
|
147
|
+
|
|
148
|
+
const [, signedKind, signedId, account, version, issuedAt, expiresAt] = claims;
|
|
149
|
+
const nowSeconds = now() / 1000;
|
|
150
|
+
/* A pass from the future is a forged clock or a skewed server: refused. */
|
|
151
|
+
if (!(issuedAt <= nowSeconds && nowSeconds < expiresAt)) return { valid: false, reason: 'expired' };
|
|
152
|
+
|
|
153
|
+
/* A pass is for ONE file. Without this, a pass to any file the person may
|
|
154
|
+
read opens every other file id put in the path. */
|
|
155
|
+
if (signedKind !== String(kind) || signedId !== idOf(fileId)) return { valid: false, reason: 'wrong-file' };
|
|
156
|
+
|
|
157
|
+
if (typeof accountVersion === 'function') {
|
|
158
|
+
const current = await accountVersion(account);
|
|
159
|
+
if (current === null || current === undefined) return { valid: false, reason: 'unknown-account' };
|
|
160
|
+
if ((Number(current) || 0) !== version) return { valid: false, reason: 'revoked' };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return { valid: true, accountId: account, version, expiresAt: expiresAt * 1000 };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return { sign, linkFor, pathFor, verify, stepSeconds, ticketParam };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/* ─────────────────────── Serialising what goes out ─────────────────────── */
|
|
170
|
+
|
|
171
|
+
function walk(value, visit) {
|
|
172
|
+
if (value === null || typeof value !== 'object' || value instanceof Date || Buffer.isBuffer(value)) return value;
|
|
173
|
+
if (Array.isArray(value)) return value.map((entry) => walk(entry, visit));
|
|
174
|
+
/* ObjectId and friends: a value object with its own toString, not a record. */
|
|
175
|
+
if (typeof value.toHexString === 'function') return value;
|
|
176
|
+
const plain = typeof value.toObject === 'function' ? value.toObject() : value;
|
|
177
|
+
const result = {};
|
|
178
|
+
for (const [key, entry] of Object.entries(plain)) result[key] = walk(entry, visit);
|
|
179
|
+
return visit(plain, result);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function fileFieldsRewriter({ field = 'fileUrl', idField = '_id', deletedField = 'deletedAt', clearWhenDeleted = [], kind, toAddress }) {
|
|
183
|
+
return (plain, result) => {
|
|
184
|
+
if (!Object.prototype.hasOwnProperty.call(plain, field)) return result;
|
|
185
|
+
const deleted = Boolean(plain[deletedField]);
|
|
186
|
+
const resolvedKind = typeof kind === 'function' ? kind(plain) : kind;
|
|
187
|
+
result[field] = plain[field] && plain[idField] && !deleted ? toAddress(resolvedKind, plain[idField]) : null;
|
|
188
|
+
/* Cutting the address of a deleted item while leaving its preview (a
|
|
189
|
+
thumbnail, a quoted text) in place deletes nothing at all. Applied at
|
|
190
|
+
EVERY depth: a quoted message carries the same risk as the message. */
|
|
191
|
+
if (deleted) for (const extra of clearWhenDeleted) if (extra in result) result[extra] = null;
|
|
192
|
+
return result;
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* For a response to ONE reader: every file address becomes that reader's own
|
|
198
|
+
* link. Never use it for a broadcast — see serializeForBroadcast.
|
|
199
|
+
*/
|
|
200
|
+
function serializeForReader(value, { links, reader, kind, ...fields } = {}) {
|
|
201
|
+
if (!links) throw new Error('serializeForReader requires options.links.');
|
|
202
|
+
return walk(value, fileFieldsRewriter({ ...fields, kind, toAddress: (k, id) => links.linkFor(k, id, reader) }));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* For anything sent to several people (a socket room, a push, a webhook): the
|
|
207
|
+
* PATH only. Each recipient then asks for their own link.
|
|
208
|
+
*/
|
|
209
|
+
function serializeForBroadcast(value, { links, kind, ...fields } = {}) {
|
|
210
|
+
if (!links) throw new Error('serializeForBroadcast requires options.links.');
|
|
211
|
+
return walk(value, fileFieldsRewriter({ ...fields, kind, toAddress: (k, id) => links.pathFor(k, id) }));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/* ─────────────────────────── Serving the bytes ─────────────────────────── */
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Resolve a stored file name under its root, or null.
|
|
218
|
+
*
|
|
219
|
+
* Two checks, each doing its own job. A bare name only — no separator, no NUL
|
|
220
|
+
* — so a stored name can never reach into a sub-directory. Then the resolved
|
|
221
|
+
* path must sit strictly INSIDE the root, which is what refuses '.', '..' and
|
|
222
|
+
* any form of traversal nobody thought to list.
|
|
223
|
+
*/
|
|
224
|
+
function resolveStoredFile(root, name) {
|
|
225
|
+
if (!root || typeof name !== 'string' || !name) return null;
|
|
226
|
+
if (name.includes('/') || name.includes('\\') || name.includes('\0')) return null;
|
|
227
|
+
const base = path.resolve(root);
|
|
228
|
+
const full = path.resolve(base, name);
|
|
229
|
+
const relative = path.relative(base, full);
|
|
230
|
+
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
|
|
231
|
+
return full;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Headers for serving a private file. Inline only for media a browser renders
|
|
236
|
+
* without running anything; everything else downloads. The sandbox CSP and
|
|
237
|
+
* nosniff stop an uploaded HTML or SVG from executing as your origin.
|
|
238
|
+
*/
|
|
239
|
+
function privateFileHeaders({ mime, fileName } = {}) {
|
|
240
|
+
const type = String(mime || 'application/octet-stream').toLowerCase();
|
|
241
|
+
const inline = INLINE_MIME.test(type);
|
|
242
|
+
return {
|
|
243
|
+
'Content-Type': type,
|
|
244
|
+
'Content-Disposition': `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(fileName || 'file')}`,
|
|
245
|
+
'Cache-Control': 'private, no-store',
|
|
246
|
+
'X-Content-Type-Options': 'nosniff',
|
|
247
|
+
'Referrer-Policy': 'no-referrer',
|
|
248
|
+
'Content-Security-Policy': "default-src 'none'; sandbox"
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* The route, with its three doors in the right order.
|
|
254
|
+
*
|
|
255
|
+
* GET {base}/:kind/:id?ticket=… the pass alone identifies the reader;
|
|
256
|
+
* GET {base}/:kind/:id?link=1 SESSION required: answers the reader's own link;
|
|
257
|
+
* GET {base}/:kind/:id SESSION required: serves the bytes.
|
|
258
|
+
*
|
|
259
|
+
* A pass never mints another pass: `link=1` with a ticket goes through the
|
|
260
|
+
* session door, otherwise a leaked pass could be renewed forever.
|
|
261
|
+
* Every refusal answers the same 404 (401 for a bad pass), so the route never
|
|
262
|
+
* says whether a file exists. Bodies carry a code, never text: the words
|
|
263
|
+
* belong to the caller's catalogue.
|
|
264
|
+
*
|
|
265
|
+
* @param {object} options
|
|
266
|
+
* @param {object} options.links createPrivateFileLinks()
|
|
267
|
+
* @param {Function} options.authenticate (req, res, next) — your session middleware; sets req.user.
|
|
268
|
+
* @param {(kind: string, id: string) => Promise<object|null>} options.loadFile
|
|
269
|
+
* @param {(reader: object, kind: string, file: object) => Promise<boolean>} options.canRead
|
|
270
|
+
* @param {(accountId: string) => Promise<object|null>} options.loadReader reader for a valid pass.
|
|
271
|
+
* @param {(file: object, req: object, res: object) => Promise<void>} options.send streams the bytes.
|
|
272
|
+
*/
|
|
273
|
+
function createPrivateFileHandler(options = {}) {
|
|
274
|
+
const { links, authenticate, loadFile, canRead, loadReader, send } = options;
|
|
275
|
+
for (const [name, fn] of Object.entries({ authenticate, loadFile, canRead, loadReader, send })) {
|
|
276
|
+
if (typeof fn !== 'function') throw new Error(`createPrivateFileHandler requires options.${name}.`);
|
|
277
|
+
}
|
|
278
|
+
if (!links || typeof links.verify !== 'function') throw new Error('createPrivateFileHandler requires options.links.');
|
|
279
|
+
|
|
280
|
+
const refuse = (res, status = 404) => res.status(status).json({ success: false, code: status === 401 ? 'FILE_LINK_INVALID' : 'FILE_UNAVAILABLE' });
|
|
281
|
+
|
|
282
|
+
return async function privateFileHandler(req, res, next) {
|
|
283
|
+
const kind = String(req.params?.kind || '');
|
|
284
|
+
const id = String(req.params?.id || '');
|
|
285
|
+
if (!KIND_PATTERN.test(kind) || !FILE_ID_PATTERN.test(id)) return refuse(res);
|
|
286
|
+
|
|
287
|
+
const wantsLink = req.query?.link === '1';
|
|
288
|
+
const ticket = req.query?.[links.ticketParam || 'ticket'];
|
|
289
|
+
|
|
290
|
+
const handle = async () => {
|
|
291
|
+
try {
|
|
292
|
+
const file = await loadFile(kind, id);
|
|
293
|
+
if (!file || !req.user || !(await canRead(req.user, kind, file))) return refuse(res);
|
|
294
|
+
if (res.setHeader) res.setHeader('Cache-Control', 'private, no-store');
|
|
295
|
+
if (wantsLink) return res.status(200).json({ success: true, data: { fileUrl: links.linkFor(kind, id, req.user) } });
|
|
296
|
+
return await send(file, req, res);
|
|
297
|
+
} catch (error) {
|
|
298
|
+
return next(error);
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
if (ticket && !wantsLink) {
|
|
303
|
+
try {
|
|
304
|
+
const check = await links.verify(String(ticket), { kind, fileId: id });
|
|
305
|
+
if (!check.valid) return refuse(res, 401);
|
|
306
|
+
const reader = await loadReader(check.accountId);
|
|
307
|
+
if (!reader) return refuse(res, 401);
|
|
308
|
+
req.user = reader;
|
|
309
|
+
} catch (_error) {
|
|
310
|
+
return refuse(res, 401);
|
|
311
|
+
}
|
|
312
|
+
return handle();
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
return authenticate(req, res, handle);
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
module.exports = {
|
|
320
|
+
createPrivateFileLinks,
|
|
321
|
+
serializeForReader,
|
|
322
|
+
serializeForBroadcast,
|
|
323
|
+
resolveStoredFile,
|
|
324
|
+
privateFileHeaders,
|
|
325
|
+
createPrivateFileHandler,
|
|
326
|
+
PRIVATE_FILE_STEP_SECONDS: DEFAULT_STEP_SECONDS
|
|
327
|
+
};
|