Move password payload to cookie
Improve invalid password message
This commit is contained in:
Alan Grainger
2025-02-02 21:03:13 +08:00
parent f4a2cd17b7
commit 5f19270df7
7 changed files with 133 additions and 35 deletions
+87
View File
@@ -10,6 +10,7 @@
"license": "AGPL-3.0", "license": "AGPL-3.0",
"dependencies": { "dependencies": {
"archiver": "^7.0.1", "archiver": "^7.0.1",
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"ejs": "^3.1.10", "ejs": "^3.1.10",
@@ -22,6 +23,7 @@
}, },
"devDependencies": { "devDependencies": {
"@types/archiver": "^6.0.3", "@types/archiver": "^6.0.3",
"@types/cookie-session": "^2.0.49",
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/node": "^16.18.111", "@types/node": "^16.18.111",
"@typescript-eslint/eslint-plugin": "5.29.0", "@typescript-eslint/eslint-plugin": "5.29.0",
@@ -332,6 +334,17 @@
"@types/node": "*" "@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": { "node_modules/@types/express": {
"version": "4.17.21", "version": "4.17.21",
"resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz",
@@ -380,6 +393,13 @@
"license": "MIT", "license": "MIT",
"peer": true "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": { "node_modules/@types/mime": {
"version": "1.3.5", "version": "1.3.5",
"resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz",
@@ -1240,12 +1260,49 @@
"node": ">= 0.6" "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": { "node_modules/cookie-signature": {
"version": "1.0.6", "version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==",
"license": "MIT" "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": { "node_modules/core-util-is": {
"version": "1.0.3", "version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
@@ -3486,6 +3543,18 @@
"json5": "lib/cli.js" "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": { "node_modules/keyv": {
"version": "4.5.4", "version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -3857,6 +3926,15 @@
"node": ">= 0.8" "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": { "node_modules/once": {
"version": "1.4.0", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
@@ -4947,6 +5025,15 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD" "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": { "node_modules/tsutils": {
"version": "3.21.0", "version": "3.21.0",
"resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz",
+2
View File
@@ -18,6 +18,7 @@
"bin": "dist/index.js", "bin": "dist/index.js",
"dependencies": { "dependencies": {
"archiver": "^7.0.1", "archiver": "^7.0.1",
"cookie-session": "^2.1.0",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"ejs": "^3.1.10", "ejs": "^3.1.10",
@@ -27,6 +28,7 @@
}, },
"devDependencies": { "devDependencies": {
"@types/archiver": "^6.0.3", "@types/archiver": "^6.0.3",
"@types/cookie-session": "^2.0.49",
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/node": "^16.18.111", "@types/node": "^16.18.111",
"@typescript-eslint/eslint-plugin": "5.29.0", "@typescript-eslint/eslint-plugin": "5.29.0",
+7 -22
View File
@@ -3,7 +3,6 @@ import dayjs from 'dayjs'
import { addResponseHeaders, getConfigOption, log } from './functions' import { addResponseHeaders, getConfigOption, log } from './functions'
import render from './render' import render from './render'
import { Response } from 'express-serve-static-core' import { Response } from 'express-serve-static-core'
import { encrypt } from './encrypt'
class Immich { class Immich {
/** /**
@@ -65,8 +64,9 @@ class Immich {
// A password is required, but the visitor-provided one doesn't match // A password is required, but the visitor-provided one doesn't match
if (sharedLinkRes.passwordRequired && request.password) { if (sharedLinkRes.passwordRequired && request.password) {
log('Invalid password for key ' + request.key) log('Invalid password for key ' + request.key)
res.status(401).send() res.status(401)
return // 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 // Password required - show the visitor the password page
@@ -75,7 +75,8 @@ class Immich {
const key = request.key.replace(/[^\w-]/g, '') const key = request.key.replace(/[^\w-]/g, '')
res.render('password', { res.render('password', {
key, key,
lgConfig: render.lgConfig lgConfig: render.lgConfig,
notifyInvalidPassword: !!request.password
}) })
return return
} }
@@ -222,16 +223,14 @@ class Immich {
photoUrl (key: string, id: string, size?: ImageSize, password?: string) { photoUrl (key: string, id: string, size?: ImageSize, password?: string) {
const path = ['photo', key, id] const path = ['photo', key, id]
if (size) path.push(size) if (size) path.push(size)
const params = password ? this.encryptPassword(password) : {} return this.buildUrl('/share/' + path.join('/'))
return this.buildUrl('/share/' + path.join('/'), params)
} }
/** /**
* Return the video data URL for a video * Return the video data URL for a video
*/ */
videoUrl (key: string, id: string, password?: string) { videoUrl (key: string, id: string, password?: string) {
const params = password ? this.encryptPassword(password) : {} return this.buildUrl(`/share/video/${key}/${id}`)
return this.buildUrl(`/share/video/${key}/${id}`, params)
} }
/** /**
@@ -250,20 +249,6 @@ class Immich {
return !!key.match(/^[\w-]+$/) 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 () { async accessible () {
return !!(await immich.request('/server/ping')) return !!(await immich.request('/server/ping'))
} }
+29 -10
View File
@@ -1,13 +1,15 @@
#!/usr/bin/env node #!/usr/bin/env node
import express from 'express' import express from 'express'
import cookieSession from 'cookie-session'
import immich from './immich' import immich from './immich'
import crypto from 'crypto'
import render from './render' import render from './render'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { Request, Response, NextFunction } from 'express-serve-static-core' import { Request, Response, NextFunction } from 'express-serve-static-core'
import { AssetType, ImageSize } from './types' import { AssetType, ImageSize } from './types'
import { decrypt } from './encrypt'
import { log, toString, addResponseHeaders, getConfigOption } from './functions' import { log, toString, addResponseHeaders, getConfigOption } from './functions'
import { decrypt, encrypt } from './encrypt'
// Extend the Request type with a `password` property // Extend the Request type with a `password` property
declare module 'express-serve-static-core' { declare module 'express-serve-static-core' {
@@ -19,6 +21,12 @@ declare module 'express-serve-static-core' {
require('dotenv').config() require('dotenv').config()
const app = express() 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 // Add the EJS view engine, to render the gallery page
app.set('view engine', 'ejs') app.set('view engine', 'ejs')
// For parsing the password unlock form // 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 })) 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) => { const decodeCookie = (req: Request, _res: Response, next: NextFunction) => {
if (req.query?.cr && req.query?.iv) { const shareKey = req.params.key
const session = req.session?.[shareKey]
if (shareKey && session?.iv && session?.cr) {
try { try {
const payload = JSON.parse(decrypt({ const payload = JSON.parse(decrypt({
iv: toString(req.query.iv), iv: toString(session.iv),
cr: toString(req.query.cr) cr: toString(session.cr)
})) }))
if (payload?.expires && dayjs(payload.expires) > dayjs()) { if (payload?.expires && dayjs(payload.expires) > dayjs()) {
req.password = payload.password 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 * [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({ await immich.handleShareRequest({
req,
key: req.params.key, key: req.params.key,
mode: req.params.mode, mode: req.params.mode,
password: req.password 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 * [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) => { 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 * [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`) // Add the headers configured in config.json (most likely `cache-control`)
addResponseHeaders(res) addResponseHeaders(res)
@@ -102,6 +120,7 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', checkPassword, async (req,
// is allowed by this shared link. // is allowed by this shared link.
const sharedLink = (await immich.getShareByKey(req.params.key, req.password))?.link const sharedLink = (await immich.getShareByKey(req.params.key, req.password))?.link
const request = { const request = {
req,
key: req.params.key, key: req.params.key,
range: req.headers.range || '' range: req.headers.range || ''
} }
-1
View File
@@ -121,7 +121,6 @@ class Render {
title: this.title(share), title: this.title(share),
path: '/share/' + share.key, path: '/share/' + share.key,
showDownload: getConfigOption('ipp.allowDownloadAll', false), showDownload: getConfigOption('ipp.allowDownloadAll', false),
password: share.password ? immich.encryptPassword(share.password) : {},
showTitle: getConfigOption('ipp.showGalleryTitle', false), showTitle: getConfigOption('ipp.showGalleryTitle', false),
lgConfig: getConfigOption('lightGallery', {}) lgConfig: getConfigOption('lightGallery', {})
}) })
+3
View File
@@ -1,3 +1,5 @@
import { Request } from 'express-serve-static-core'
export enum AssetType { export enum AssetType {
image = 'IMAGE', image = 'IMAGE',
video = 'VIDEO' video = 'VIDEO'
@@ -41,6 +43,7 @@ export enum ImageSize {
} }
export interface IncomingShareRequest { export interface IncomingShareRequest {
req: Request;
key: string; key: string;
password?: string; password?: string;
mode?: string; mode?: string;
+5 -2
View File
@@ -20,7 +20,11 @@
placeholder="Password" placeholder="Password"
aria-label="Password" aria-label="Password"
required required
autofocus
/> />
<% if (notifyInvalidPassword) { %>
<small>Invalid password</small>
<% } %>
<input <input
type="hidden" type="hidden"
name="key" name="key"
@@ -53,8 +57,7 @@
}) })
if (res.status === 200) { if (res.status === 200) {
// Valid password - redirect to the gallery // Valid password - redirect to the gallery
const params = await res.json() window.location.reload()
window.location = window.location.href.split('?')[0] + '?' + new URLSearchParams(params).toString()
} }
} catch (e) { } } catch (e) { }
} }