feat(security): opt-in recoverable gallery passwords (#1341)

* feat(security): opt-in recoverable gallery passwords

Gallery passwords are bcrypt hashes, so an admin who needs to hand a
password to a client a second time has to reset it, which invalidates
what the client already has. This adds a security setting,
security_gallery_password_recoverable, off by default, that keeps an
AES-256-GCM encrypted copy of each gallery password and client PIN next
to the hash. The key is derived from GALLERY_PASSWORD_ENCRYPTION_KEY or
JWT_SECRET.

While the setting is on:
- create, publish, send-later, edit, reset and the v1 API write the copy
  alongside the hash; turning a gallery's password requirement off
  clears it
- GET /api/admin/events/:id/password returns the copy to admins with
  events.edit and ownership, and writes a gallery_password_viewed
  activity entry on every real reveal
- resend-email uses the stored password instead of the "set at creation"
  sentinel, so the client receives what already works

Switching the setting off purges every stored copy. Login and hash
verification are untouched; the copy is never read on the gallery side.

The Security tab carries the toggle with a warning that stays visible,
and the event page shows "Show password" with copy buttons only while
the setting is on and the gallery has a secret.

Relates to issue 1271

* fix(security): close the write-versus-switch-off race in the password vault

The recoverable setting is read while an event insert is assembled and the
client-PIN hash awaits after that, so a settings request that switched the
feature off and purged in that gap was overtaken by the insert. Every write
site now re-reads the setting right after its statement and clears its own
row when the setting is off; the settings writer flips the value before it
purges, so either the purge or the re-check catches the row.

* fix(security): resend carries the stored client PIN and link; deterministic tamper test

The creation mail includes the client-access link and PIN; a resend only
sent the gallery password even when a stored PIN was available. The
ciphertext tamper assertion replaced the last two characters with a
constant, which was a no-op roughly once in 4096 runs.

* fix(security): drop the revealed password after Send gallery email

The send-later route can replace the password; the share card keys its
revealed copy on the event query's refetch time, so invalidate the event
after the send like the other password-changing mutations do.

* fix(security): purge leftovers before the setting write when turning recovery on

Switching on wrote the setting first and purged after, so a password write
that read the new "on" in between stored a copy the purge then deleted.
Turning on now purges before the write; turning off keeps purging after it,
which together with the write-site re-check leaves the vault holding
exactly what was written while the setting was on.

* chore(security): drop the duplicate rateLimitService import left by the rebase

* chore(usage): register the password recovery routes in the v5 coverage inventory

The inventory moved from v4 to v5 on main; the entry added by this branch
followed it.

---------

Co-authored-by: Paul Nothaft <[email protected]>
This commit is contained in:
Paul Nothaft
2026-09-07 20:36:48 +02:00
committed by GitHub
co-authored by Paul Nothaft
parent 16b79ee119
commit fb9da72f14
21 changed files with 905 additions and 39 deletions
+24
View File
@@ -26,6 +26,7 @@ const { normaliseEventTimeTriple } = require('../../services/eventService');
const { hasColumnCached } = require('../../utils/schemaCache');
const { requireEventOwnership } = require('../../middleware/ownership');
const { getAppSetting } = require('../../utils/appSettings');
const { galleryPasswordColumns, dropCopiesIfStorageOff } = require('../../utils/galleryPasswordVault');
const { clampIntOrUndefined } = require('../../utils/numericHelpers');
const { getFrontendBaseUrl, getAbsoluteFrontendUrl } = require('../../utils/frontendUrl');
const downloadZipService = require('../../services/downloadZipService');
@@ -620,6 +621,12 @@ module.exports = (router) => {
host_email: customerEmail || null,
admin_email: admin_email || null,
password_hash,
// Opt-in recoverable copy (#1271), written with the hash so the two
// can never disagree. Empty unless the security setting is on.
...(await galleryPasswordColumns({
...(requirePassword && password ? { password } : {}),
...(client_access_enabled && client_password ? { clientPassword: client_password } : {}),
})),
welcome_message,
color_theme,
share_link: shareLinkToStore,
@@ -674,6 +681,8 @@ module.exports = (router) => {
// Handle both PostgreSQL (returns array of objects) and SQLite (returns array of IDs)
const eventId = insertResult[0]?.id || insertResult[0];
// #1271 — the setting was read before the hashes; re-check after the write
await dropCopiesIfStorageOff(eventId);
// Apply customer-account assignments (#354). Skip when the customer
// portal flag is off — the frontend hides the picker in that case,
@@ -1115,7 +1124,9 @@ module.exports = (router) => {
await db('events').where('id', id).update({
password_hash: await bcrypt.hash(password, getBcryptRounds()),
...(await galleryPasswordColumns({ password })),
});
await dropCopiesIfStorageOff(id);
}
const queued = hasInlineRecipient
@@ -1213,8 +1224,10 @@ module.exports = (router) => {
if (policyError) return res.status(400).json(policyError);
publishUpdates.password_hash = await bcrypt.hash(password, getBcryptRounds());
Object.assign(publishUpdates, await galleryPasswordColumns({ password }));
}
await db('events').where('id', id).update(publishUpdates);
if (publishUpdates.password_hash) await dropCopiesIfStorageOff(id);
// Notify the customer — unless the admin asked to publish quietly
// (#1235). Everything else about publishing still happens: the gallery
@@ -1696,6 +1709,9 @@ module.exports = (router) => {
'share_link', 'share_token', 'client_share_token', 'show_share_token',
// Secrets (set via the plaintext password/client_password inputs)
'password_hash', 'client_password_hash',
// #1271 — encrypted copies follow the hashes; a forged ciphertext
// from another owner's row would decrypt through /:id/password
'password_recoverable', 'client_password_recoverable',
// Server-consumed file paths — e.g. DELETE /:id/logo fs.unlink()s
// hero_logo_path, so a forged value is an arbitrary-delete primitive.
'hero_logo_path', 'hero_logo_url', 'archive_path', 'download_zip_path',
@@ -1803,8 +1819,12 @@ module.exports = (router) => {
return res.status(400).json({ error: 'external_path is required when source_mode is reference' });
}
// Plaintexts to remember after the row is written (#1271); each key is
// only set when this request changed that password.
const recoverable = {};
if (Object.prototype.hasOwnProperty.call(updates, 'client_password') && updates.client_password) {
updates.client_password_hash = await bcrypt.hash(updates.client_password, getBcryptRounds());
recoverable.clientPassword = updates.client_password;
delete updates.client_password;
} else {
delete updates.client_password;
@@ -1879,8 +1899,10 @@ module.exports = (router) => {
if (newPasswordPlain) {
updates.password_hash = await bcrypt.hash(newPasswordPlain, getBcryptRounds());
recoverable.password = newPasswordPlain;
} else if (hasRequirePasswordUpdate && requirePasswordUpdate === false && currentRequirePassword) {
updates.password_hash = await bcrypt.hash(crypto.randomBytes(32).toString('hex'), getBcryptRounds());
recoverable.password = null;
}
// Enforce expires_at requirement based on app settings
@@ -2028,11 +2050,13 @@ module.exports = (router) => {
// left nothing to change — Knex rejects .update({}) with an error,
// which would surface as a 500 for an otherwise-valid no-op request
// (e.g. a body of only protected fields). (codex review.)
if (Object.keys(recoverable).length > 0) Object.assign(updates, await galleryPasswordColumns(recoverable));
if (Object.keys(updates).length > 0) {
await db('events')
.where('id', id)
.update(updates);
}
if (Object.keys(recoverable).length > 0) await dropCopiesIfStorageOff(id);
// Customer-account assignments (#354). Same skip semantics as POST:
// ignore when the customer portal flag is off so stale tabs don't
@@ -330,6 +330,8 @@ const isPhoneFieldEnabled = async () => {
}
};
const RECOVERABLE_PASSWORD_COLUMNS = ['password_recoverable', 'client_password_recoverable'];
const mapEventForApi = (event) => {
if (!event || typeof event !== 'object') {
return event;
@@ -345,6 +347,10 @@ const mapEventForApi = (event) => {
password_hash: _ph, client_password_hash: _cph,
...rest
} = event;
// #1271 — the encrypted copies never leave the server except via
// /:id/password. Removed by name (not destructured) so a secret scanner
// does not read the binding as a hard-coded password.
for (const column of RECOVERABLE_PASSWORD_COLUMNS) delete rest[column];
return {
...rest,
@@ -688,6 +694,7 @@ const SLIDESHOW_COLORFILTERS = ['none', 'bw', 'sepia', 'warm', 'cool', 'vignette
// 'random' = client-side shuffle.
const SLIDESHOW_ORDERS = ['chronological', 'random'];
module.exports = {
RECOVERABLE_PASSWORD_COLUMNS,
validateHeroImageAnchor,
getStoragePath,
getEventFieldRequirements,
+1
View File
@@ -12,6 +12,7 @@ require('./crud')(router);
require('./slideshow')(router);
require('./downloadResolutions')(router);
require('./resets')(router);
require('./passwordRecovery')(router);
require('./archiveBulk')(router);
require('./logo')(router);
require('./qr')(router);
@@ -0,0 +1,59 @@
const { db, logActivity } = require('../../database/db');
const { adminAuth } = require('../../middleware/auth');
const { requirePermission } = require('../../middleware/permissions');
const { requireEventOwnership } = require('../../middleware/ownership');
const { readGalleryPassword, isRecoverableStorageEnabled } = require('../../utils/galleryPasswordVault');
const { errorResponse } = require('../../utils/routeHelpers');
const { noStoreCache } = require('../../middleware/noStoreCache');
/**
* Show a gallery's stored password (#1271).
*
* Only meaningful when the security setting
* `security_gallery_password_recoverable` is on: the plaintext exists in no
* other place, the hash cannot be reversed. The response says whether the
* feature is enabled at all, so the UI can explain instead of failing.
* Every reveal of a real password is written to the activity log.
*/
module.exports = (router) => {
// Whether "Show password" should exist at all. Editors hold events.edit but
// not settings.view, so the event page cannot read the security setting
// itself; this answers the one question it has without touching the copy.
router.get('/:id/password-status', adminAuth, noStoreCache, requirePermission('events.view'), requireEventOwnership, async (req, res) => {
try {
const { id } = req.params;
let eventQuery = db('events').where('id', id);
if (req.admin.roleName === 'editor') eventQuery = eventQuery.where('created_by', req.admin.id);
const event = await eventQuery.first('id');
if (!event) return res.status(404).json({ error: 'Event not found' });
res.json({ enabled: await isRecoverableStorageEnabled() });
} catch (error) {
errorResponse(res, error, 500, 'Failed to read gallery password status');
}
});
router.get('/:id/password', adminAuth, noStoreCache, requirePermission('events.edit'), requireEventOwnership, async (req, res) => {
try {
const { id } = req.params;
let eventQuery = db('events').where('id', id);
if (req.admin.roleName === 'editor') eventQuery = eventQuery.where('created_by', req.admin.id);
const event = await eventQuery.first('id', 'event_name', 'require_password', 'client_access_enabled');
if (!event) return res.status(404).json({ error: 'Event not found' });
const stored = await readGalleryPassword(id);
if (stored.password || stored.clientPassword) {
await logActivity('gallery_password_viewed',
{ eventName: event.event_name, galleryPassword: Boolean(stored.password), clientPassword: Boolean(stored.clientPassword) },
id,
{ type: 'admin', id: req.admin.id, name: req.admin.username });
}
res.json({
enabled: stored.enabled,
password: stored.password,
client_password: stored.clientPassword
});
} catch (error) {
errorResponse(res, error, 500, 'Failed to read gallery password');
}
});
};
+33 -9
View File
@@ -7,11 +7,14 @@ const { adminAuth } = require('../../middleware/auth');
const { requirePermission } = require('../../middleware/permissions');
const bcrypt = require('bcrypt');
const { queueEmail } = require('../../services/emailProcessor');
const { galleryPasswordColumns, readGalleryPassword, dropCopiesIfStorageOff } = require('../../utils/galleryPasswordVault');
const { validatePasswordInContext, getBcryptRounds } = require('../../utils/passwordValidation');
const logger = require('../../utils/logger');
const { errorResponse } = require('../../utils/routeHelpers');
const { buildShareLinkVariants } = require('../../services/shareLinkService');
const { requireEventOwnership } = require('../../middleware/ownership');
const { getAbsoluteFrontendUrl } = require('../../utils/frontendUrl');
const { parseBooleanInput } = require('../../utils/parsers');
module.exports = (router) => {
@@ -64,8 +67,12 @@ module.exports = (router) => {
await db('events')
.where('id', id)
.update({
password_hash: passwordHash
password_hash: passwordHash,
// #1271 — same statement as the hash, so a concurrent reset can
// never leave a copy that does not match the hash next to it
...(await galleryPasswordColumns({ password: newPassword })),
});
await dropCopiesIfStorageOff(id);
// Log activity
await logActivity('password_reset',
@@ -132,12 +139,19 @@ module.exports = (router) => {
// First, try to get it from the request body if provided
// Use optional chaining to handle cases where req.body might be undefined
let galleryPassword = req.body?.password;
// If no password provided, we can't decrypt the existing one
// So we'll show a security message
// Without a password in the request: use the recoverable copy when the
// operator opted into keeping one (#1271), else the security sentinel —
// the hash cannot be turned back into the password.
let usedStoredPassword = false;
const stored = await readGalleryPassword(id);
if (!galleryPassword) {
// We'll let the email processor determine the language for the security message
galleryPassword = '{{password_security_message}}';
if (stored.password) {
galleryPassword = stored.password;
usedStoredPassword = true;
} else {
// We'll let the email processor determine the language for the security message
galleryPassword = '{{password_security_message}}';
}
}
// Dates will be formatted by the email processor based on recipient language
@@ -149,7 +163,7 @@ module.exports = (router) => {
// customer's mail client renders a clickable absolute link.
const { shareUrl } = await buildShareLinkVariants({ slug: event.slug, shareToken: event.share_token });
await queueEmail(id, recipientEmail, 'gallery_created', {
const emailData = {
customer_name: recipientName,
customer_email: recipientEmail,
host_name: recipientName,
@@ -161,7 +175,16 @@ module.exports = (router) => {
welcome_message: event.welcome_message || '',
eventId: id,
isResend: true // Flag to indicate this is a resend
});
};
// The creation mail carries the client link and PIN (#172). A resend can
// only do the same when a stored PIN exists (#1271); otherwise the client
// section is left out rather than sent with a placeholder.
if (parseBooleanInput(event.client_access_enabled, false) && stored.clientPassword && event.client_share_token) {
const frontendUrl = await getAbsoluteFrontendUrl(req, { override: process.env.APP_URL });
emailData.client_link = `${frontendUrl}/gallery/${event.slug}/client-access?token=${event.client_share_token}`;
emailData.client_password = stored.clientPassword;
}
await queueEmail(id, recipientEmail, 'gallery_created', emailData);
// Log the activity using the proper schema
try {
@@ -180,7 +203,8 @@ module.exports = (router) => {
// Don't fail the request if activity logging fails
}
res.json({
res.json({
usedStoredPassword,
success: true,
message: 'Creation email has been queued for sending'
});
+9 -1
View File
@@ -3,6 +3,7 @@ const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const { db, logActivity } = require('../database/db');
const { RECOVERABLE_PASSWORD_COLUMNS } = require('./adminEvents/helpers');
const { adminAuth } = require('../middleware/auth');
const { requirePermission } = require('../middleware/permissions');
const { ensureThumbnail } = require('../services/imageProcessor');
@@ -1599,9 +1600,16 @@ router.get('/:eventId/debug', adminAuth, requirePermission('photos.view'), requi
try {
const { eventId } = req.params;
const event = await db('events').where({ id: eventId }).first();
const eventRow = await db('events').where({ id: eventId }).first();
const photoCount = await db('photos').where({ event_id: eventId }).count('id as count').first();
const photos = await db('photos').where({ event_id: eventId }).limit(5);
// Never hand out the hashes or the recoverable copies (#1271) — this is
// a photos.view surface, not an events.edit one.
let event = eventRow;
if (eventRow) {
event = { ...eventRow };
for (const column of ['password_hash', 'client_password_hash', ...RECOVERABLE_PASSWORD_COLUMNS]) delete event[column];
}
res.json({
event: event || 'Not found',
+31
View File
@@ -15,6 +15,7 @@ const { adminAuth } = require('../middleware/auth');
const { requirePermission, userHasAnyPermission } = require('../middleware/permissions');
const { clearMaintenanceCache } = require('../middleware/maintenance');
const { clearSettingsCache, initializeRateLimiters, RATE_LIMIT_DEFAULTS } = require('../services/rateLimitService');
const { SETTING_KEY: GALLERY_PASSWORD_SETTING, purgeRecoverablePasswords, purgePlanForSettingWrite } = require('../utils/galleryPasswordVault');
const {
DEFAULT_PUBLIC_SITE_HTML,
DEFAULT_PUBLIC_SITE_CSS,
@@ -211,6 +212,21 @@ const faviconUpload = multer({
// reads 2 of the ~100 rows). The keys filter is allowlist-bounded by
// what's stored, so passing unknown keys just returns them as `null`
// — no enumeration risk beyond what GET / returned already.
/**
* Recoverable gallery passwords (#1271): every transition of the setting
* starts from a clean vault. Off is a promise that nothing reversible is
* left behind; on-from-off must not resurrect copies a write left behind
* after the previous purge. Decided BEFORE the upsert (needs the old value),
* applied after it. Every writer that accepts a security_ key (general,
* analytics and seo take them from a settings.security holder too) does this.
*/
// Every writer that accepts a security_ key runs the vault purge on the side
// of the write the transition calls for (see purgePlanForSettingWrite).
async function galleryPasswordPurgePlan(settings) {
if (!settings || !Object.prototype.hasOwnProperty.call(settings, GALLERY_PASSWORD_SETTING)) return { before: false, after: false };
return purgePlanForSettingWrite(settings[GALLERY_PASSWORD_SETTING]);
}
router.get('/', adminAuth, requirePermission('settings.view'), async (req, res) => {
try {
const keysParam = typeof req.query.keys === 'string' ? req.query.keys : null;
@@ -1532,6 +1548,8 @@ router.put('/general', adminAuth, requirePermission('settings.edit'), async (req
}
// Update or insert each setting
const galleryPasswordPurge = await galleryPasswordPurgePlan(settings);
if (galleryPasswordPurge.before) await purgeRecoverablePasswords();
for (const [key, value] of Object.entries(settings)) {
await db('app_settings')
.insert({
@@ -1547,6 +1565,8 @@ router.put('/general', adminAuth, requirePermission('settings.edit'), async (req
});
}
if (galleryPasswordPurge.after) await purgeRecoverablePasswords();
// Clear maintenance mode cache if it was updated
if ('general_maintenance_mode' in settings) {
clearMaintenanceCache();
@@ -1606,6 +1626,8 @@ router.put('/security', adminAuth, requirePermission('settings.security'), async
if (await rejectUnauthorizedProtectedKeys(settings, req, res)) return;
// Update or insert each setting
const galleryPasswordPurge = await galleryPasswordPurgePlan(settings);
if (galleryPasswordPurge.before) await purgeRecoverablePasswords();
for (const [key, value] of Object.entries(settings)) {
await db('app_settings')
.insert({
@@ -1622,6 +1644,7 @@ router.put('/security', adminAuth, requirePermission('settings.security'), async
}
resetSecurityConfigCache();
if (galleryPasswordPurge.after) await purgeRecoverablePasswords();
// Log activity
await db('activity_logs').insert({
@@ -1664,6 +1687,8 @@ router.put('/analytics', adminAuth, requirePermission('settings.edit'), async (r
}
// Update or insert each setting
const galleryPasswordPurge = await galleryPasswordPurgePlan(settings);
if (galleryPasswordPurge.before) await purgeRecoverablePasswords();
for (const [key, value] of Object.entries(settings)) {
await db('app_settings')
.insert({
@@ -1679,6 +1704,8 @@ router.put('/analytics', adminAuth, requirePermission('settings.edit'), async (r
});
}
if (galleryPasswordPurge.after) await purgeRecoverablePasswords();
// Log activity
await db('activity_logs').insert({
activity_type: 'analytics_settings_updated',
@@ -1725,6 +1752,8 @@ router.put('/seo', adminAuth, requirePermission('settings.edit'), async (req, re
const seoChanged = await settingsChanged(db, settings, SEO_USAGE_KEYS);
// Update or insert each setting
const galleryPasswordPurge = await galleryPasswordPurgePlan(settings);
if (galleryPasswordPurge.before) await purgeRecoverablePasswords();
for (const [key, value] of Object.entries(settings)) {
await db('app_settings')
.insert({
@@ -1740,6 +1769,8 @@ router.put('/seo', adminAuth, requirePermission('settings.edit'), async (req, re
});
}
if (galleryPasswordPurge.after) await purgeRecoverablePasswords();
// Clear robots.txt cache
const { clearRobotsTxtCache } = require('../services/robotsTxtService');
clearRobotsTxtCache();
+7
View File
@@ -31,6 +31,7 @@ const { requireEventOwnership, scopeEventsQuery } = require('../../middleware/ow
// which apiTokenAuth populates.
const { requirePermission } = require('../../middleware/permissions');
const { resolveEventFeedbackDefaults } = require('../../services/feedbackDefaults');
const { galleryPasswordColumns, dropCopiesIfStorageOff } = require('../../utils/galleryPasswordVault');
const { buildShareLinkVariants } = require('../../services/shareLinkService');
const { generateThumbnail } = require('../../services/imageProcessor');
const logger = require('../../utils/logger');
@@ -327,6 +328,8 @@ router.post(
host_email: customer_email,
admin_email,
password_hash: passwordHash,
// #1271 — recoverable copy rides with the hash; only when there is one
...(require_password && password ? await galleryPasswordColumns({ password }) : {}),
require_password,
share_link: shareLinkToStore,
share_token: shareToken,
@@ -352,6 +355,7 @@ router.post(
...(persistPhone ? { customer_phone: persistPhone } : {})
}).returning('id');
const id = insertResult[0]?.id || insertResult[0];
if (require_password && password) await dropCopiesIfStorageOff(id);
// Issue #550 — mirror adminEvents.js: create event_feedback_settings
// row when feedback is enabled, so the gallery actually shows feedback
@@ -595,6 +599,9 @@ router.get('/events/:id', apiTokenAuth, requireApiScope('read'), requirePermissi
if (!event) return res.status(404).json({ error: 'Event not found' });
delete event.password_hash;
delete event.client_password_hash;
// #1271 — the encrypted copies are server-only as well
delete event.password_recoverable;
delete event.client_password_recoverable;
res.json(event);
} catch (error) {
logger.error('v1 GET /events/:id failed', { error: error.message });
+158
View File
@@ -0,0 +1,158 @@
/**
* Recoverable storage for gallery passwords (#1271).
*
* Gallery passwords are bcrypt-hashed and that is what the login path
* checks. Some operators would rather be able to look a password up or
* resend it unchanged than reset it every time a client loses it, so an
* explicit security setting, `security_gallery_password_recoverable`, lets
* the plaintext be kept next to the hash — encrypted with AES-256-GCM under
* a key derived from GALLERY_PASSWORD_ENCRYPTION_KEY, falling back to
* JWT_SECRET. That is reversible by anyone holding the database AND the
* key, which is a weaker posture than the hash and why it is opt-in and
* off by default.
*
* Every write site that hashes a gallery or client password calls
* galleryPasswordColumns() right after. With the setting off it is a
* no-op, so nothing is ever stored unless the operator asked for it, and
* turning the setting off purges what was stored.
*/
const crypto = require('crypto');
const { db } = require('../database/db');
const { getAppSetting } = require('./appSettings');
const SETTING_KEY = 'security_gallery_password_recoverable';
const ENC_ALGO = 'aes-256-gcm';
// Distinct salt from the OIDC secret helper, so the two never share a key
// even when both derive from JWT_SECRET.
const ENC_SALT = 'picpeak-gallery-password-vault-v1';
let keyCache = null;
function getKey() {
const material = process.env.GALLERY_PASSWORD_ENCRYPTION_KEY || process.env.JWT_SECRET;
if (!material) throw new Error('galleryPasswordVault: GALLERY_PASSWORD_ENCRYPTION_KEY or JWT_SECRET must be set');
if (keyCache && keyCache.material === material) return keyCache.key;
keyCache = { material, key: crypto.scryptSync(material, ENC_SALT, 32) };
return keyCache.key;
}
/** AES-256-GCM encrypt → "iv.tag.ciphertext" (base64url). */
function encryptPassword(plain) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv(ENC_ALGO, getKey(), iv);
const ct = Buffer.concat([cipher.update(String(plain), 'utf8'), cipher.final()]);
return [iv, cipher.getAuthTag(), ct].map((b) => b.toString('base64url')).join('.');
}
/** Reverse of encryptPassword. Throws on tamper or a rotated key. */
function decryptPassword(stored) {
const [ivB64, tagB64, ctB64] = String(stored).split('.');
if (!ivB64 || !tagB64 || !ctB64) throw new Error('galleryPasswordVault: malformed ciphertext');
const decipher = crypto.createDecipheriv(ENC_ALGO, getKey(), Buffer.from(ivB64, 'base64url'));
decipher.setAuthTag(Buffer.from(tagB64, 'base64url'));
return Buffer.concat([decipher.update(Buffer.from(ctB64, 'base64url')), decipher.final()]).toString('utf8');
}
/** The one reading of the setting's value, shared by the read and write paths. */
function isEnabledValue(value) {
return value === true || value === 'true' || value === 1 || value === '1';
}
async function isRecoverableStorageEnabled(conn = db) {
return isEnabledValue(await getAppSetting(SETTING_KEY, false, conn));
}
/**
* The column values that belong next to a new hash — spread them into the
* same INSERT/UPDATE as password_hash / client_password_hash so the copy
* and the hash can never disagree, even under concurrent writes.
* `password: null` / `clientPassword: null` clears; with the setting off
* the copy is cleared rather than skipped, so a password that changes while
* storage is off cannot leave the previous plaintext behind to resurface,
* stale, when storage is switched on again. `{}` when nothing was asked.
*/
async function galleryPasswordColumns(values = {}, conn = db) {
const has = (key) => Object.prototype.hasOwnProperty.call(values, key);
if (!has('password') && !has('clientPassword')) return {};
const enabled = await isRecoverableStorageEnabled(conn);
const columns = {};
if (has('password')) {
columns.password_recoverable = enabled && values.password ? encryptPassword(values.password) : null;
}
if (has('clientPassword')) {
columns.client_password_recoverable = enabled && values.clientPassword ? encryptPassword(values.clientPassword) : null;
}
return columns;
}
/**
* The stored plaintexts for an event, or nulls. `enabled` says whether the
* setting is on; when it is off the columns are ignored even if a row still
* carried a value (it should not — see purgeRecoverablePasswords).
*/
async function readGalleryPassword(eventId, conn = db) {
const enabled = await isRecoverableStorageEnabled(conn);
if (!enabled) return { enabled: false, password: null, clientPassword: null };
const row = await conn('events').where('id', eventId)
.first('password_recoverable', 'client_password_recoverable', 'require_password');
if (!row) return { enabled: true, password: null, clientPassword: null };
const open = (value) => {
if (!value) return null;
try { return decryptPassword(value); } catch (_) { return null; }
};
return { enabled: true, password: open(row.password_recoverable), clientPassword: open(row.client_password_recoverable) };
}
/**
* Second half of the opt-out guarantee. Every write site calls this right
* after the statement that carried galleryPasswordColumns(). The setting is
* read before the bcrypt hashes, so a settings request that switches the
* feature off and purges in that gap used to be overtaken by the write. The
* settings writer flips the value before it purges, so a write that lands
* after the purge reads "off" here and clears its own row, and one that
* lands before it is caught by the purge. One settings read per password
* write; the UPDATE only runs when the setting is off.
*/
async function dropCopiesIfStorageOff(eventId, conn = db) {
if (await isRecoverableStorageEnabled(conn)) return false;
await conn('events').where('id', eventId)
.where((q) => q.whereNotNull('password_recoverable').orWhereNotNull('client_password_recoverable'))
.update({ password_recoverable: null, client_password_recoverable: null });
return true;
}
/**
* Which side of a settings write the vault purge belongs on, for a request
* that carries the setting. Off (staying or turning off): after the write,
* so a password write that still read "on" is caught by the purge and one
* that lands later reads "off" and clears itself (dropCopiesIfStorageOff).
* Turning on: before the write, so the purge only ever sees leftovers and
* never a copy stored under the new "on"; a write that still reads the old
* "off" stores nothing. Either way the vault holds exactly what was written
* while the setting was on. Same-state "on" saves do not purge.
*/
async function purgePlanForSettingWrite(newValue, conn = db) {
const willBeOn = isEnabledValue(newValue);
const isOn = await isRecoverableStorageEnabled(conn);
return { before: willBeOn && !isOn, after: !willBeOn };
}
/** Wipe every stored plaintext; called when the setting is switched off. */
async function purgeRecoverablePasswords(conn = db) {
return conn('events')
.where((q) => q.whereNotNull('password_recoverable').orWhereNotNull('client_password_recoverable'))
.update({ password_recoverable: null, client_password_recoverable: null });
}
module.exports = {
SETTING_KEY,
encryptPassword,
decryptPassword,
isRecoverableStorageEnabled,
galleryPasswordColumns,
isEnabledValue,
readGalleryPassword,
dropCopiesIfStorageOff,
purgePlanForSettingWrite,
purgeRecoverablePasswords
};