emailengine-app 2.87.0 → 2.87.2

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 (71) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +3 -4
  5. package/bin/emailengine.js +2 -4
  6. package/bin/healthcheck.js +20 -0
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +3 -7
  9. package/lib/account/auth-failure-backfill.js +3 -2
  10. package/lib/account/expected-identity.js +2 -2
  11. package/lib/account.js +9 -8
  12. package/lib/api-listener.js +40 -0
  13. package/lib/api-token-auth.js +406 -0
  14. package/lib/autodetect-imap-settings.js +36 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +23 -107
  21. package/lib/email-client/gmail-client.js +7 -4
  22. package/lib/email-client/imap/mailbox.js +89 -96
  23. package/lib/email-client/imap/sync-operations.js +13 -6
  24. package/lib/email-client/imap-client.js +28 -7
  25. package/lib/email-client/new-message-steps.js +162 -0
  26. package/lib/email-client/outlook-client.js +4 -2
  27. package/lib/env-setting-overrides.js +6 -2
  28. package/lib/export-worker.js +3 -2
  29. package/lib/export.js +43 -4
  30. package/lib/get-boolean.js +38 -0
  31. package/lib/health-probe.js +71 -0
  32. package/lib/imapproxy/imap-server.js +4 -55
  33. package/lib/net-tos-guard.js +42 -0
  34. package/lib/oauth2-apps.js +2 -1
  35. package/lib/privileged-settings.js +6 -0
  36. package/lib/read-env-value.js +19 -7
  37. package/lib/redis-keys.js +19 -0
  38. package/lib/redis-operations.js +7 -3
  39. package/lib/routes-ui.js +4 -1
  40. package/lib/schemas.js +8 -0
  41. package/lib/security-headers.js +18 -0
  42. package/lib/session-default.js +60 -0
  43. package/lib/settings.js +2 -1
  44. package/lib/stream-encrypt.js +71 -20
  45. package/lib/sub-script.js +8 -2
  46. package/lib/submit-lock.js +84 -0
  47. package/lib/submit-processor.js +283 -0
  48. package/lib/templates.js +6 -3
  49. package/lib/tls/context.js +2 -16
  50. package/lib/tools.js +8 -30
  51. package/lib/ui-routes/admin-config-routes.js +27 -5
  52. package/lib/ui-routes/auth-routes.js +4 -0
  53. package/lib/ui-routes/dbsc-routes.js +43 -0
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/worker-rpc-error.js +10 -5
  57. package/lib/worker-rpc.js +138 -0
  58. package/package.json +17 -19
  59. package/sbom.json +370 -1446
  60. package/server.js +6 -5
  61. package/static/css/flyonui.css +2 -2
  62. package/static/licenses.html +253 -1366
  63. package/translations/messages.pot +16 -16
  64. package/views/config/security.hbs +37 -0
  65. package/workers/api.js +61 -467
  66. package/workers/export.js +14 -55
  67. package/workers/imap-proxy.js +5 -18
  68. package/workers/imap.js +27 -49
  69. package/workers/smtp.js +7 -69
  70. package/workers/submit.js +21 -279
  71. package/workers/webhooks.js +7 -72
@@ -0,0 +1,292 @@
1
+ 'use strict';
2
+
3
+ // Device-bound admin sessions (DBSC, https://w3c.github.io/webappsec-dbsc/). An opt-in hardening of
4
+ // the admin session cookie: a browser that supports it creates a key pair it cannot export (the TPM
5
+ // on Windows, the Secure Enclave on macOS) and from then on proves possession of the key every few
6
+ // minutes to renew a short-lived second cookie. A session cookie copied off the machine stops
7
+ // working within BOUND_COOKIE_TTL, because nothing but the key can renew the second one.
8
+ //
9
+ // Opportunistic by design: a browser that does not support it never registers, and its session
10
+ // works exactly as before. Once a session HAS registered, the binding lives in Redis (store.js) and
11
+ // every request carrying that session's cookie must carry a valid bound cookie too - the session
12
+ // cookie says nothing about being bound, so it cannot be stripped of it.
13
+ //
14
+ // The pieces:
15
+ // offer() onPreResponse: asks an authenticated admin page's browser to register
16
+ // register() POST /admin/dbsc/start (lib/ui-routes/dbsc-routes.js)
17
+ // refresh() POST /admin/dbsc/refresh
18
+ // mustRefuse() onPostAuth: a bound session's request without the bound cookie is refused
19
+ // end() logout: marks the binding ended, which refuses the session cookie everywhere
20
+ //
21
+ // Verified end to end against Chrome 156 on macOS (Secure Enclave keys) on 2026-11-05. Chrome only
22
+ // registers on a trusted https origin: not on http, not on localhost, not with a certificate error.
23
+
24
+ const crypto = require('crypto');
25
+ const Boom = require('@hapi/boom');
26
+
27
+ const { ADMIN_SESSION_MAX_AGE } = require('../consts');
28
+ const { createDbscStore } = require('./store');
29
+ const { verifyRegistrationProof, verifyRefreshProof } = require('./jwt');
30
+ const {
31
+ BOUND_COOKIE,
32
+ BOUND_COOKIE_TTL,
33
+ readSfString,
34
+ registrationHeader,
35
+ challengeHeader,
36
+ registrationAnswer,
37
+ boundCookieValid,
38
+ boundCookieSpec
39
+ } = require('./protocol');
40
+
41
+ const RESPONSE_HEADER = 'secure-session-response';
42
+
43
+ // The admin session cookie's sid, which keys everything DBSC stores
44
+ const sidOf = request => (request.state && request.state.ee && request.state.ee.sid) || null;
45
+ const SESSION_ID_HEADER = 'sec-secure-session-id';
46
+ const SKIPPED_HEADER = 'secure-session-skipped';
47
+
48
+ /**
49
+ * @param {Object} deps
50
+ * @param {Object} deps.store - createDbscStore()
51
+ * @param {Object} deps.logger
52
+ * @param {string} deps.attributes - the bound cookie's attributes string (boundCookieSpec())
53
+ */
54
+ function createDbsc({ store, logger, attributes }) {
55
+ const issueBoundCookie = (h, sid, id) => h.state(BOUND_COOKIE, { sid, id, exp: Date.now() + BOUND_COOKIE_TTL });
56
+
57
+ // Seconds the admin session behind this cookie can still live, which bounds its binding
58
+ const sessionTtl = session => (Number(session.issuedAt) + ADMIN_SESSION_MAX_AGE - Date.now()) / 1000;
59
+
60
+ return {
61
+ async offer(request, h) {
62
+ const response = request.response;
63
+ if (!request.app.dbscEnabled || request.method !== 'get' || !request.auth.isAuthenticated || request.auth.strategy !== 'session') {
64
+ return h.continue;
65
+ }
66
+ if (response.isBoom || response.variety !== 'view' || response.statusCode !== 200) {
67
+ return h.continue;
68
+ }
69
+ const session = request.auth.artifacts || {};
70
+ if (!session.sid || session.requireTotp || boundCookieValid(request.state[BOUND_COOKIE], session.sid)) {
71
+ return h.continue;
72
+ }
73
+ try {
74
+ // The throttle first: on a browser that never binds, that is the only round trip
75
+ if (!(await store.claimOffer(session.sid)) || (!request.app.dbscUnbound && (await store.getBinding(session.sid)))) {
76
+ return h.continue;
77
+ }
78
+ response.header('Secure-Session-Registration', registrationHeader(await store.mintChallenge(session.sid, 'register')));
79
+ } catch (err) {
80
+ // An offer is an invitation, never a reason to fail the page
81
+ logger.warn({ msg: 'Failed to offer a device-bound session', err });
82
+ }
83
+ return h.continue;
84
+ },
85
+
86
+ async register(request, h) {
87
+ const session = request.auth.artifacts || {};
88
+ if (!request.app.dbscEnabled || !session.sid) {
89
+ return h.response().code(404);
90
+ }
91
+
92
+ const refuse = reason => {
93
+ logger.info({ msg: 'Refused a device-bound session registration', reason, remoteAddress: request.app.ip });
94
+ return h.response().code(400);
95
+ };
96
+
97
+ let proof;
98
+ try {
99
+ proof = verifyRegistrationProof(readSfString(request.headers[RESPONSE_HEADER]));
100
+ } catch (err) {
101
+ return refuse(err.message);
102
+ }
103
+ if (!(await store.consumeChallenge(proof.jti, session.sid, 'register'))) {
104
+ return refuse('unknown or spent challenge');
105
+ }
106
+
107
+ const id = crypto.randomBytes(16).toString('hex');
108
+ if (!(await store.bind(session.sid, { id, alg: proof.alg, jwk: proof.jwk }, sessionTtl(session)))) {
109
+ // Bound already. A second registration would let whoever holds the session cookie
110
+ // replace the key, which is the one thing the binding exists to prevent
111
+ return h.response().code(409);
112
+ }
113
+
114
+ logger.info({
115
+ msg: 'Admin session bound to a device key',
116
+ user: request.auth.credentials && request.auth.credentials.user,
117
+ alg: proof.alg,
118
+ remoteAddress: request.app.ip
119
+ });
120
+ issueBoundCookie(h, session.sid, id);
121
+ return h.response(registrationAnswer({ sessionId: id, attributes })).type('application/json');
122
+ },
123
+
124
+ async refresh(request, h) {
125
+ // A 4xx other than 403 ends the session in the browser, a 3xx is ignored by it, so the
126
+ // answers here are chosen by what the browser does with them
127
+ const stop = () => h.response({ continue: false }).type('application/json');
128
+
129
+ const session = request.auth.isAuthenticated ? request.auth.artifacts || {} : null;
130
+ if (!request.app.dbscEnabled || !session || !session.sid) {
131
+ return stop();
132
+ }
133
+ const binding = await store.getBinding(session.sid);
134
+ if (!binding || binding.ended || binding.id !== readSfString(request.headers[SESSION_ID_HEADER])) {
135
+ // A session the browser still holds from an earlier sign-in
136
+ return stop();
137
+ }
138
+
139
+ const challengeAgain = async () =>
140
+ h
141
+ .response()
142
+ .code(403)
143
+ .header('Secure-Session-Challenge', challengeHeader(await store.mintChallenge(session.sid, 'refresh'), binding.id));
144
+
145
+ const token = readSfString(request.headers[RESPONSE_HEADER]);
146
+ if (!token) {
147
+ return await challengeAgain();
148
+ }
149
+
150
+ let jti;
151
+ try {
152
+ ({ jti } = verifyRefreshProof(token, binding));
153
+ } catch (err) {
154
+ // counted as a failed proof below
155
+ }
156
+ // Chrome signs proactive refreshes over the challenge it has cached, which this server
157
+ // has already spent: that is answered with a fresh one, and the browser retries
158
+ if (!jti || !(await store.consumeChallenge(jti, session.sid, 'refresh'))) {
159
+ if (await store.recordRefreshFailure(session.sid)) {
160
+ return await challengeAgain();
161
+ }
162
+ logger.warn({ msg: 'Ended a device-bound session after repeated bad proofs', remoteAddress: request.app.ip });
163
+ return h.response().code(401);
164
+ }
165
+
166
+ await store.clearRefreshFailures(session.sid);
167
+ issueBoundCookie(h, session.sid, binding.id);
168
+ return h.response().code(200);
169
+ },
170
+
171
+ /**
172
+ * @returns {Promise<boolean>} true when the request carries a bound session without its
173
+ * bound cookie and has to be refused
174
+ */
175
+ async mustRefuse(request) {
176
+ // The refresh route opts out: it is where a missing bound cookie gets renewed
177
+ const routeOptions = request.route.settings.plugins.dbsc;
178
+ if (!request.app.dbscEnabled || (routeOptions && routeOptions.enforce === false)) {
179
+ return false;
180
+ }
181
+ // Both credentials the session cookie carries: the admin session, and the message
182
+ // browser's session token on /v1 (lib/api-token-auth.js), which reads the same cookie
183
+ const viaSession = request.auth.isAuthenticated && request.auth.strategy === 'session';
184
+ if (!viaSession && !request.app.sessionToken) {
185
+ return false;
186
+ }
187
+ const sid = sidOf(request);
188
+ if (!sid || boundCookieValid(request.state[BOUND_COOKIE], sid)) {
189
+ return false;
190
+ }
191
+ if (!(await store.getBinding(sid))) {
192
+ // Known unbound for the rest of this request, so the offer need not ask again
193
+ request.app.dbscUnbound = true;
194
+ return false;
195
+ }
196
+ // A binding and no valid bound cookie: the session cookie is being used without the device
197
+ // that holds the key. An ended binding (logout) is refused the same way; a bound cookie
198
+ // issued before the logout still passes until it runs out, which is the price of not
199
+ // reading Redis on every request that carries one
200
+
201
+ logger.warn({
202
+ msg: 'Refused a device-bound admin session without its bound credential',
203
+ path: request.path,
204
+ skipped: request.headers[SKIPPED_HEADER],
205
+ remoteAddress: request.app.ip
206
+ });
207
+ return true;
208
+ },
209
+
210
+ /**
211
+ * Whether the session making this request is bound to a device key, for the Security
212
+ * page's "this browser" line
213
+ * @returns {Promise<boolean>}
214
+ */
215
+ async isBound(request) {
216
+ const sid = sidOf(request);
217
+ if (!sid) {
218
+ return false;
219
+ }
220
+ const binding = await store.getBinding(sid);
221
+ return !!binding && !binding.ended;
222
+ },
223
+
224
+ async end(sid) {
225
+ await store.endBinding(sid);
226
+ }
227
+ };
228
+ }
229
+
230
+ /**
231
+ * Registers the bound cookie and publishes the DBSC instance on server.app, where the routes and
232
+ * the logout handlers find it. Called with the session strategy, from the same cookie settings
233
+ * @param {Object} server - hapi server
234
+ * @param {Object} opts
235
+ * @param {Object} opts.redis
236
+ * @param {Object} opts.logger
237
+ * @param {boolean} opts.secure - whether the admin cookies are Secure
238
+ * @param {string} opts.password - cookiePassword
239
+ */
240
+ function setupDbsc(server, { redis, logger, secure, password }) {
241
+ const spec = boundCookieSpec({ secure, password });
242
+ server.state(BOUND_COOKIE, spec.state);
243
+ server.app.dbsc = createDbsc({ store: createDbscStore(redis), logger, attributes: spec.attributes });
244
+ }
245
+
246
+ /**
247
+ * The offer (onPreResponse) and the enforcement (onPostAuth). Registered after the TOTP step, so a
248
+ * session still owing its second factor is sent there first, and after the error-page extension,
249
+ * so an offer is only ever attached to a page that is actually rendered
250
+ * @param {Object} server - hapi server, after setupDbsc()
251
+ */
252
+ function registerDbscExtensions(server) {
253
+ const dbsc = server.app.dbsc;
254
+
255
+ server.ext('onPostAuth', async (request, h) => {
256
+ if (!(await dbsc.mustRefuse(request))) {
257
+ return h.continue;
258
+ }
259
+ // The session is over on this browser. Its binding stays: deleting it would let the same
260
+ // session cookie, wherever it was copied to, pass as an unbound session
261
+ h.unstate('ee');
262
+ h.unstate(BOUND_COOKIE);
263
+ if (request.app.sessionToken) {
264
+ throw Boom.unauthorized('Session could not be confirmed on this device');
265
+ }
266
+ await request.flash({
267
+ type: 'warning',
268
+ message: 'You were signed out because this browser could not confirm it is the device you signed in on. Sign in again to continue.'
269
+ });
270
+ const next = request.method === 'get' ? `?next=${encodeURIComponent(request.url.pathname + request.url.search)}` : '';
271
+ return h.redirect(`/admin/login${next}`).takeover();
272
+ });
273
+
274
+ server.ext('onPreResponse', (request, h) => dbsc.offer(request, h));
275
+ }
276
+
277
+ /**
278
+ * Ends the binding of the session a logout ends. A no-op where DBSC was never set up
279
+ * @param {Object} request
280
+ * @param {Object} h
281
+ */
282
+ async function endDeviceBinding(request, h) {
283
+ const dbsc = request.server.app.dbsc;
284
+ const sid = sidOf(request);
285
+ if (!dbsc || !sid) {
286
+ return;
287
+ }
288
+ h.unstate(BOUND_COOKIE);
289
+ await dbsc.end(sid);
290
+ }
291
+
292
+ module.exports = { setupDbsc, registerDbscExtensions, endDeviceBinding };
@@ -0,0 +1,157 @@
1
+ 'use strict';
2
+
3
+ // Verifies the proofs a browser sends for a device-bound admin session (DBSC, see lib/dbsc/): a
4
+ // compact JWS with `typ: dbsc+jwt`, signed by the key pair the browser created for the session.
5
+ // Pure, and built on Node's own crypto only (no JOSE dependency, see "Pure JavaScript only").
6
+ //
7
+ // What Chrome sends, observed against Chrome 156 on 2026-11-05 and matching the spec's normative
8
+ // list (§9.10, which drops the `aud` and `iat` of one of its own examples):
9
+ // registration: header { alg, typ: 'dbsc+jwt', jwk }, payload { jti, authorization? }
10
+ // refresh: header { alg, typ: 'dbsc+jwt' }, payload { jti }
11
+ // `jti` is the challenge the server issued. Nothing else in the payload is relied on.
12
+
13
+ const crypto = require('crypto');
14
+
15
+ // RS256 and ES256 are what the spec lists besides `none`, which binds the session to nothing and
16
+ // is refused outright
17
+ const ALGORITHMS = Object.freeze(['ES256', 'RS256']);
18
+
19
+ // A proof is a few hundred bytes; anything far larger is not one, and is refused before parsing
20
+ const MAX_PROOF_LENGTH = 8 * 1024;
21
+
22
+ const MIN_RSA_BITS = 2048;
23
+
24
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
25
+
26
+ function proofError(message) {
27
+ const err = new Error(message);
28
+ err.code = 'DbscInvalidProof';
29
+ err.statusCode = 400;
30
+ return err;
31
+ }
32
+
33
+ function decodeSegment(segment, what) {
34
+ try {
35
+ const value = BASE64URL.test(segment) && JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
36
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
37
+ return value;
38
+ }
39
+ } catch (err) {
40
+ // reported below like any other malformed segment
41
+ }
42
+ throw proofError(`Malformed proof ${what}`);
43
+ }
44
+
45
+ /**
46
+ * Splits a compact JWS and decodes its header and payload, without checking the signature
47
+ * @param {string} token
48
+ * @returns {{ header: Object, payload: Object, signingInput: Buffer, signature: Buffer }}
49
+ */
50
+ function parseProof(token) {
51
+ if (typeof token !== 'string' || !token || token.length > MAX_PROOF_LENGTH) {
52
+ throw proofError('Missing or oversized proof');
53
+ }
54
+ const parts = token.split('.');
55
+ if (parts.length !== 3 || !BASE64URL.test(parts[2])) {
56
+ throw proofError('Malformed proof');
57
+ }
58
+ const header = decodeSegment(parts[0], 'header');
59
+ const payload = decodeSegment(parts[1], 'payload');
60
+
61
+ if (header.typ !== 'dbsc+jwt') {
62
+ throw proofError('Not a DBSC proof');
63
+ }
64
+ if (!ALGORITHMS.includes(header.alg)) {
65
+ throw proofError('Unsupported proof algorithm');
66
+ }
67
+ if (typeof payload.jti !== 'string' || !payload.jti) {
68
+ throw proofError('Proof carries no challenge');
69
+ }
70
+
71
+ return {
72
+ header,
73
+ payload,
74
+ signingInput: Buffer.from(`${parts[0]}.${parts[1]}`),
75
+ signature: Buffer.from(parts[2], 'base64url')
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Reduces a JWK to the public members of the type the algorithm needs, so a stored key can never
81
+ * carry a private member or an unrelated field from the browser
82
+ * @param {string} alg - ES256 or RS256
83
+ * @param {Object} jwk
84
+ * @returns {Object} the public JWK
85
+ */
86
+ function publicJwkFor(alg, jwk) {
87
+ if (!jwk || typeof jwk !== 'object' || Array.isArray(jwk)) {
88
+ throw proofError('Proof carries no key');
89
+ }
90
+ if (alg === 'ES256') {
91
+ if (jwk.kty !== 'EC' || jwk.crv !== 'P-256' || typeof jwk.x !== 'string' || typeof jwk.y !== 'string') {
92
+ throw proofError('Proof key does not match its algorithm');
93
+ }
94
+ return { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y };
95
+ }
96
+ if (jwk.kty !== 'RSA' || typeof jwk.n !== 'string' || typeof jwk.e !== 'string') {
97
+ throw proofError('Proof key does not match its algorithm');
98
+ }
99
+ return { kty: 'RSA', n: jwk.n, e: jwk.e };
100
+ }
101
+
102
+ function importKey(alg, jwk) {
103
+ let key;
104
+ try {
105
+ key = crypto.createPublicKey({ key: jwk, format: 'jwk' });
106
+ } catch (err) {
107
+ throw proofError('Proof key is not usable');
108
+ }
109
+ if (alg === 'RS256' && key.asymmetricKeyDetails.modulusLength < MIN_RSA_BITS) {
110
+ throw proofError('Proof key is too short');
111
+ }
112
+ return key;
113
+ }
114
+
115
+ function signatureValid(alg, key, signingInput, signature) {
116
+ if (alg === 'ES256') {
117
+ // JWS carries the raw r||s pair, 32 bytes each, not the DER form Node defaults to
118
+ return signature.length === 64 && crypto.verify('sha256', signingInput, { key, dsaEncoding: 'ieee-p1363' }, signature);
119
+ }
120
+ return crypto.verify('sha256', signingInput, { key, padding: crypto.constants.RSA_PKCS1_PADDING }, signature);
121
+ }
122
+
123
+ /**
124
+ * Verifies the proof a browser sends to register a session: signed by the key its own header
125
+ * carries, which becomes the session's key
126
+ * @param {string} token
127
+ * @returns {{ alg: string, jwk: Object, jti: string, authorization: string|undefined }}
128
+ */
129
+ function verifyRegistrationProof(token) {
130
+ const { header, payload, signingInput, signature } = parseProof(token);
131
+ const jwk = publicJwkFor(header.alg, header.jwk);
132
+ if (!signatureValid(header.alg, importKey(header.alg, jwk), signingInput, signature)) {
133
+ throw proofError('Proof signature does not verify');
134
+ }
135
+ return { alg: header.alg, jwk, jti: payload.jti, authorization: typeof payload.authorization === 'string' ? payload.authorization : undefined };
136
+ }
137
+
138
+ /**
139
+ * Verifies a refresh proof against the key stored when the session registered. A key in the
140
+ * proof's own header is ignored: the spec forbids one on refresh, and honouring it would let any
141
+ * key sign for the session
142
+ * @param {string} token
143
+ * @param {{ alg: string, jwk: Object }} binding - what registration stored
144
+ * @returns {{ jti: string }}
145
+ */
146
+ function verifyRefreshProof(token, binding) {
147
+ const { header, payload, signingInput, signature } = parseProof(token);
148
+ if (header.alg !== binding.alg) {
149
+ throw proofError('Proof algorithm does not match the session');
150
+ }
151
+ if (!signatureValid(binding.alg, importKey(binding.alg, publicJwkFor(binding.alg, binding.jwk)), signingInput, signature)) {
152
+ throw proofError('Proof signature does not verify');
153
+ }
154
+ return { jti: payload.jti };
155
+ }
156
+
157
+ module.exports = { verifyRegistrationProof, verifyRefreshProof, ALGORITHMS, MAX_PROOF_LENGTH };
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+
3
+ // The wire format of device-bound admin sessions (DBSC): the headers EmailEngine sends and reads,
4
+ // the short-lived cookie that carries the binding, and the registration answer. Pure.
5
+ //
6
+ // Chrome sends `Secure-Session-Response` and `Sec-Secure-Session-Id` as bare values although the
7
+ // spec declares them structured-field strings (quoted); both spellings are read. The challenge
8
+ // header carries the `id` parameter the spec requires, without which the browser does not cache
9
+ // the challenge and signs the next proof with a stale one.
10
+
11
+ const { ALGORITHMS } = require('./jwt');
12
+
13
+ // The paths the registration header and the registration answer name
14
+ const REGISTRATION_PATH = '/admin/dbsc/start';
15
+ const REFRESH_PATH = '/admin/dbsc/refresh';
16
+
17
+ // The cookie that proves a request came from the browser holding the session key. Short-lived on
18
+ // purpose: a stolen copy is useless once it runs out, and only the key can mint the next one
19
+ const BOUND_COOKIE = 'eeb';
20
+ const BOUND_COOKIE_TTL = 10 * 60 * 1000;
21
+
22
+ // Challenges are base64url, which is safe inside a structured-field string without escaping
23
+ const SF_TOKEN = /^[A-Za-z0-9_.~+/=-]+$/;
24
+
25
+ /**
26
+ * Reads a header the spec declares a structured-field string, accepting the bare form Chrome sends
27
+ * @param {string|undefined} value
28
+ * @returns {string|null} the string, or null when the header is absent or malformed
29
+ */
30
+ function readSfString(value) {
31
+ if (typeof value !== 'string') {
32
+ return null;
33
+ }
34
+ let text = value.trim();
35
+ if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) {
36
+ text = text.slice(1, -1);
37
+ }
38
+ return text && SF_TOKEN.test(text) ? text : null;
39
+ }
40
+
41
+ /**
42
+ * @param {string} challenge
43
+ * @returns {string} the Secure-Session-Registration value offering the algorithms jwt.js verifies
44
+ */
45
+ function registrationHeader(challenge) {
46
+ return `(${ALGORITHMS.join(' ')});path="${REGISTRATION_PATH}";challenge="${challenge}"`;
47
+ }
48
+
49
+ /**
50
+ * @param {string} challenge
51
+ * @param {string} sessionId - the session_identifier the browser registered under
52
+ * @returns {string} the Secure-Session-Challenge value
53
+ */
54
+ function challengeHeader(challenge, sessionId) {
55
+ return `"${challenge}";id="${sessionId}"`;
56
+ }
57
+
58
+ /**
59
+ * The bound cookie's settings, as hapi's server.state() takes them and as the attributes string the
60
+ * registration answer names. One source for both, because the browser compares the cookie it is
61
+ * sent against the attributes it registered (Domain, Path, Secure, HttpOnly, SameSite) and ignores
62
+ * a refresh that sets anything else
63
+ * @param {Object} opts
64
+ * @param {boolean} opts.secure - whether the admin cookies are marked Secure (an https serviceUrl)
65
+ * @param {string} opts.password - the iron sealing password (cookiePassword)
66
+ * @returns {{ state: Object, attributes: string }}
67
+ */
68
+ function boundCookieSpec({ secure, password }) {
69
+ return {
70
+ state: {
71
+ ttl: BOUND_COOKIE_TTL,
72
+ encoding: 'iron',
73
+ password,
74
+ path: '/',
75
+ isSecure: !!secure,
76
+ isHttpOnly: true,
77
+ isSameSite: 'Lax',
78
+ clearInvalid: true,
79
+ ignoreErrors: true
80
+ },
81
+ attributes: ['Path=/', 'HttpOnly', 'SameSite=Lax'].concat(secure ? ['Secure'] : []).join('; ')
82
+ };
83
+ }
84
+
85
+ /**
86
+ * The JSON answer to a registration. The scope names no origin, so it defaults to the origin the
87
+ * browser registered on: an operator reaching the admin UI on a name other than the Service URL's
88
+ * would otherwise be told about a different site and the browser would drop the session
89
+ * @param {Object} opts
90
+ * @param {string} opts.sessionId
91
+ * @param {string} opts.attributes - from boundCookieSpec()
92
+ * @returns {Object}
93
+ */
94
+ function registrationAnswer({ sessionId, attributes }) {
95
+ return {
96
+ session_identifier: sessionId,
97
+ refresh_url: REFRESH_PATH,
98
+ scope: {
99
+ include_site: false,
100
+ // Nothing under these carries the session, so there is nothing to refresh for
101
+ scope_specification: [
102
+ { type: 'exclude', domain: '*', path: '/static' },
103
+ { type: 'exclude', domain: '*', path: '/.well-known' }
104
+ ]
105
+ },
106
+ credentials: [{ type: 'cookie', name: BOUND_COOKIE, attributes }]
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Whether a decoded bound cookie vouches for this session right now
112
+ * @param {Object|undefined} cookie - request.state.eeb
113
+ * @param {string} sid - the admin session's sid
114
+ * @param {number} [now]
115
+ * @returns {boolean}
116
+ */
117
+ function boundCookieValid(cookie, sid, now = Date.now()) {
118
+ return !!(cookie && sid && cookie.sid === sid && Number(cookie.exp) > now);
119
+ }
120
+
121
+ module.exports = {
122
+ REGISTRATION_PATH,
123
+ REFRESH_PATH,
124
+ BOUND_COOKIE,
125
+ BOUND_COOKIE_TTL,
126
+ readSfString,
127
+ registrationHeader,
128
+ challengeHeader,
129
+ boundCookieSpec,
130
+ registrationAnswer,
131
+ boundCookieValid
132
+ };