diff --git a/app/package-lock.json b/app/package-lock.json index 58db352..3acca73 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -10,6 +10,7 @@ "license": "AGPL-3.0", "dependencies": { "archiver": "^7.0.1", + "cookie-session": "^2.1.0", "dayjs": "^1.11.13", "dotenv": "^16.4.5", "ejs": "^3.1.10", @@ -22,6 +23,7 @@ }, "devDependencies": { "@types/archiver": "^6.0.3", + "@types/cookie-session": "^2.0.49", "@types/express": "^4.17.21", "@types/node": "^16.18.111", "@typescript-eslint/eslint-plugin": "5.29.0", @@ -332,6 +334,17 @@ "@types/node": "*" } }, + "node_modules/@types/cookie-session": { + "version": "2.0.49", + "resolved": "https://registry.npmjs.org/@types/cookie-session/-/cookie-session-2.0.49.tgz", + "integrity": "sha512-4E/bBjlqLhU5l4iGPR+NkVJH593hpNsT4dC3DJDr+ODm6Qpe13kZQVkezRIb+TYDXaBMemS3yLQ+0leba3jlkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/express": "*", + "@types/keygrip": "*" + } + }, "node_modules/@types/express": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", @@ -380,6 +393,13 @@ "license": "MIT", "peer": true }, + "node_modules/@types/keygrip": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/keygrip/-/keygrip-1.0.6.tgz", + "integrity": "sha512-lZuNAY9xeJt7Bx4t4dx0rYCDqGPW8RXhQZK1td7d4H6E9zYbLoOtjBvfwdTKpsyxQI/2jv+armjX/RW+ZNpXOQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/mime": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", @@ -1240,12 +1260,49 @@ "node": ">= 0.6" } }, + "node_modules/cookie-session": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cookie-session/-/cookie-session-2.1.0.tgz", + "integrity": "sha512-u73BDmR8QLGcs+Lprs0cfbcAPKl2HnPcjpwRXT41sEV4DRJ2+W0vJEEZkG31ofkx+HZflA70siRIjiTdIodmOQ==", + "license": "MIT", + "dependencies": { + "cookies": "0.9.1", + "debug": "3.2.7", + "on-headers": "~1.0.2", + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cookie-session/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, "node_modules/cookie-signature": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", "license": "MIT" }, + "node_modules/cookies": { + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/cookies/-/cookies-0.9.1.tgz", + "integrity": "sha512-TG2hpqe4ELx54QER/S3HQ9SRVnQnGBtKUz5bLQWtYAQ+o6GpgMs6sYUvaiJjVxb+UXwhRhAEP3m7LbsIZ77Hmw==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "keygrip": "~1.1.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", @@ -3486,6 +3543,18 @@ "json5": "lib/cli.js" } }, + "node_modules/keygrip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "license": "MIT", + "dependencies": { + "tsscmp": "1.0.6" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/keyv": { "version": "4.5.4", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", @@ -3857,6 +3926,15 @@ "node": ">= 0.8" } }, + "node_modules/on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -4947,6 +5025,15 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/tsscmp": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", + "license": "MIT", + "engines": { + "node": ">=0.6.x" + } + }, "node_modules/tsutils": { "version": "3.21.0", "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", diff --git a/app/package.json b/app/package.json index e2d7b53..b2ad001 100644 --- a/app/package.json +++ b/app/package.json @@ -18,6 +18,7 @@ "bin": "dist/index.js", "dependencies": { "archiver": "^7.0.1", + "cookie-session": "^2.1.0", "dayjs": "^1.11.13", "dotenv": "^16.4.5", "ejs": "^3.1.10", @@ -27,6 +28,7 @@ }, "devDependencies": { "@types/archiver": "^6.0.3", + "@types/cookie-session": "^2.0.49", "@types/express": "^4.17.21", "@types/node": "^16.18.111", "@typescript-eslint/eslint-plugin": "5.29.0", diff --git a/app/src/immich.ts b/app/src/immich.ts index f70b7c7..4a03a0e 100644 --- a/app/src/immich.ts +++ b/app/src/immich.ts @@ -3,7 +3,6 @@ import dayjs from 'dayjs' import { addResponseHeaders, getConfigOption, log } from './functions' import render from './render' import { Response } from 'express-serve-static-core' -import { encrypt } from './encrypt' class Immich { /** @@ -65,8 +64,9 @@ class Immich { // A password is required, but the visitor-provided one doesn't match if (sharedLinkRes.passwordRequired && request.password) { log('Invalid password for key ' + request.key) - res.status(401).send() - return + res.status(401) + // Delete the cookie-session data, so that it doesn't keep saying "Invalid password" + if (request.req?.session) delete request.req.session[request.key] } // Password required - show the visitor the password page @@ -75,7 +75,8 @@ class Immich { const key = request.key.replace(/[^\w-]/g, '') res.render('password', { key, - lgConfig: render.lgConfig + lgConfig: render.lgConfig, + notifyInvalidPassword: !!request.password }) return } @@ -222,16 +223,14 @@ class Immich { photoUrl (key: string, id: string, size?: ImageSize, password?: string) { const path = ['photo', key, id] if (size) path.push(size) - const params = password ? this.encryptPassword(password) : {} - return this.buildUrl('/share/' + path.join('/'), params) + return this.buildUrl('/share/' + path.join('/')) } /** * Return the video data URL for a video */ videoUrl (key: string, id: string, password?: string) { - const params = password ? this.encryptPassword(password) : {} - return this.buildUrl(`/share/video/${key}/${id}`, params) + return this.buildUrl(`/share/video/${key}/${id}`) } /** @@ -250,20 +249,6 @@ class Immich { return !!key.match(/^[\w-]+$/) } - /** - * When loading assets from a password-protected link, make the decryption key valid for a - * short time. If the visitor loads the share link again, it will renew that expiry time. - * Even though the recipient already knows the password, this is just in case - for example - * to protect against the password-protected link being revoked, but the asset links still - * being valid. - */ - encryptPassword (password: string) { - return encrypt(JSON.stringify({ - password, - expires: dayjs().add(1, 'hour').format() - })) - } - async accessible () { return !!(await immich.request('/server/ping')) } diff --git a/app/src/index.ts b/app/src/index.ts index ca4d53e..7b81d11 100644 --- a/app/src/index.ts +++ b/app/src/index.ts @@ -1,13 +1,15 @@ #!/usr/bin/env node import express from 'express' +import cookieSession from 'cookie-session' import immich from './immich' +import crypto from 'crypto' import render from './render' import dayjs from 'dayjs' import { Request, Response, NextFunction } from 'express-serve-static-core' import { AssetType, ImageSize } from './types' -import { decrypt } from './encrypt' import { log, toString, addResponseHeaders, getConfigOption } from './functions' +import { decrypt, encrypt } from './encrypt' // Extend the Request type with a `password` property declare module 'express-serve-static-core' { @@ -19,6 +21,12 @@ declare module 'express-serve-static-core' { require('dotenv').config() const app = express() +app.use(cookieSession({ + name: 'session', + httpOnly: true, + sameSite: 'strict', + secret: crypto.randomBytes(32).toString('base64url') +})) // Add the EJS view engine, to render the gallery page app.set('view engine', 'ejs') // For parsing the password unlock form @@ -29,14 +37,16 @@ app.use('/share/static', express.static('public', { setHeaders: addResponseHeade app.use(express.static('public', { setHeaders: addResponseHeaders })) /** - * Middleware to decode an encrypted password sent from the frontend (if provided) + * Middleware to decode the encrypted data stored in the session cookie */ -const checkPassword = (req: Request, res: Response, next: NextFunction) => { - if (req.query?.cr && req.query?.iv) { +const decodeCookie = (req: Request, _res: Response, next: NextFunction) => { + const shareKey = req.params.key + const session = req.session?.[shareKey] + if (shareKey && session?.iv && session?.cr) { try { const payload = JSON.parse(decrypt({ - iv: toString(req.query.iv), - cr: toString(req.query.cr) + iv: toString(session.iv), + cr: toString(session.cr) })) if (payload?.expires && dayjs(payload.expires) > dayjs()) { req.password = payload.password @@ -61,8 +71,9 @@ app.get(/^(|\/share)\/healthcheck$/, async (_req, res) => { /* * [ROUTE] This is the main URL that someone would visit if they are opening a shared link */ -app.get('/share/:key/:mode(download)?', checkPassword, async (req, res) => { +app.get('/share/:key/:mode(download)?', decodeCookie, async (req, res) => { await immich.handleShareRequest({ + req, key: req.params.key, mode: req.params.mode, password: req.password @@ -71,16 +82,23 @@ app.get('/share/:key/:mode(download)?', checkPassword, async (req, res) => { /* * [ROUTE] Receive an unlock request from the password page - * Returns an encrypted unlock key which lasts for 1 hour + * Stores a cookie with an encrypted payload which expires in 1 hour. + * After that time, the visitor will need to provide the password again. */ app.post('/share/unlock', async (req, res) => { - res.send(immich.encryptPassword(req.body.password)) + if (req.session && req.body.key) { + req.session[req.body.key] = encrypt(JSON.stringify({ + password: req.body.password, + expires: dayjs().add(1, 'hour').format() + })) + } + res.send() }) /* * [ROUTE] This is the direct link to a photo or video asset */ -app.get('/share/:type(photo|video)/:key/:id/:size?', checkPassword, async (req, res) => { +app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, res) => { // Add the headers configured in config.json (most likely `cache-control`) addResponseHeaders(res) @@ -102,6 +120,7 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', checkPassword, async (req, // is allowed by this shared link. const sharedLink = (await immich.getShareByKey(req.params.key, req.password))?.link const request = { + req, key: req.params.key, range: req.headers.range || '' } diff --git a/app/src/render.ts b/app/src/render.ts index 556f9f3..a7a0cdd 100644 --- a/app/src/render.ts +++ b/app/src/render.ts @@ -121,7 +121,6 @@ class Render { title: this.title(share), path: '/share/' + share.key, showDownload: getConfigOption('ipp.allowDownloadAll', false), - password: share.password ? immich.encryptPassword(share.password) : {}, showTitle: getConfigOption('ipp.showGalleryTitle', false), lgConfig: getConfigOption('lightGallery', {}) }) diff --git a/app/src/types.ts b/app/src/types.ts index 127ec55..2097ef5 100644 --- a/app/src/types.ts +++ b/app/src/types.ts @@ -1,3 +1,5 @@ +import { Request } from 'express-serve-static-core' + export enum AssetType { image = 'IMAGE', video = 'VIDEO' @@ -41,6 +43,7 @@ export enum ImageSize { } export interface IncomingShareRequest { + req: Request; key: string; password?: string; mode?: string; diff --git a/app/views/password.ejs b/app/views/password.ejs index 8d32c04..bdc86d2 100644 --- a/app/views/password.ejs +++ b/app/views/password.ejs @@ -20,7 +20,11 @@ placeholder="Password" aria-label="Password" required + autofocus /> + <% if (notifyInvalidPassword) { %> + Invalid password + <% } %>