Consolidate app files

This commit is contained in:
Alan Grainger
2024-11-02 22:18:04 +01:00
parent 12064d740f
commit 69d88fa849
32 changed files with 15 additions and 13 deletions
+38
View File
@@ -0,0 +1,38 @@
import crypto from 'crypto'
interface Payload {
iv: string;
cr: string; // Encrypted data
}
// Generate a random 256-bit key on startup
const key = crypto.randomBytes(32)
const algorithm = 'aes-256-cbc'
export function encrypt (text: string): Payload {
try {
const ivBuf = crypto.randomBytes(16)
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), ivBuf)
let encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex')
return {
iv: ivBuf.toString('hex'),
cr: encrypted
}
} catch (e) { }
return {
cr: '',
iv: ''
}
}
export function decrypt (payload: Payload) {
try {
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), Buffer.from(payload.iv, 'hex'))
let decrypted = decipher.update(payload.cr, 'hex', 'utf8')
decrypted += decipher.final('utf8')
return decrypted
} catch (e) { }
return ''
}
+222
View File
@@ -0,0 +1,222 @@
import { Asset, AssetType, ImageSize, IncomingShareRequest, SharedLink, SharedLinkResult } from './types'
import dayjs from 'dayjs'
import { log } from './index'
import render from './render'
import { Response } from 'express-serve-static-core'
import { encrypt } from './encrypt'
class Immich {
/**
* Make a request to Immich API. We're not using the SDK to limit
* the possible attack surface of this app.
*/
async request (endpoint: string) {
const res = await fetch(process.env.IMMICH_URL + '/api' + endpoint)
if (res.status === 200) {
const contentType = res.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) {
return res.json()
} else {
return res
}
} else {
log('Immich API status ' + res.status)
console.log(await res.text())
}
}
/**
* Handle an incoming request for a shared link `key`. This is the main function which
* communicates with Immich and returns the output back to the visitor.
*
* Possible HTTP responses are:
*
* 200 - either a photo gallery or the unlock page.
* 401 - the visitor provided a password but it was invalid.
* 404 - any other failed request. Check console.log for details.
*/
async handleShareRequest (request: IncomingShareRequest, res: Response) {
res.set('Cache-Control', 'public, max-age=' + process.env.CACHE_AGE)
if (!immich.isKey(request.key)) {
// This is not a valid key format
log('Invalid share key ' + request.key)
res.status(404).send()
} else {
// Get information about the shared link via Immich API
const sharedLinkRes = await immich.getShareByKey(request.key, request.password)
if (!sharedLinkRes.valid) {
// This isn't a valid request - check the console for more information
res.status(404).send()
} else if (sharedLinkRes.passwordRequired && request.password) {
// A password is required, but the visitor-provided one doesn't match
log('Invalid password for key ' + request.key)
res.status(401).send()
} else if (sharedLinkRes.passwordRequired) {
// Password required - show the visitor the password page
// `req.params.key` should already be sanitised at this point, but it never hurts to be explicit
const key = request.key.replace(/[^\w-]/g, '')
res.render('password', { key, lgConfig: render.lgConfig })
} else if (sharedLinkRes.link) {
// Valid shared link
const link = sharedLinkRes.link
if (!link.assets.length) {
log('No assets for key ' + request.key)
res.status(404).send()
} else if (link.assets.length === 1) {
// This is an individual item (not a gallery)
log('Serving link ' + request.key)
const asset = link.assets[0]
if (asset.type === AssetType.image) {
// For photos, output the image directly
await render.assetBuffer(res, link.assets[0], request.size)
} else if (asset.type === AssetType.video) {
// For videos, show the video as a web player
await render.gallery(res, link, 1)
}
} else {
// Multiple images - render as a gallery
log('Serving link ' + request.key)
await render.gallery(res, link)
}
} else {
log('Unknown error with key ' + request.key)
res.status(404).send()
}
}
}
/**
* Query Immich for the SharedLink metadata for a given key.
* The key is what is returned in the URL when you create a share in Immich.
*/
async getShareByKey (key: string, password?: string): Promise<SharedLinkResult> {
let link
const url = this.buildUrl(process.env.IMMICH_URL + '/api/shared-links/me', {
key,
password
})
const res = await fetch(url)
const contentType = res.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) {
const jsonBody = await res.json()
if (jsonBody) {
if (res.status === 200) {
// Normal response - get the shared assets
link = jsonBody as SharedLink
if (link.expiresAt && dayjs(link.expiresAt) < dayjs()) {
// This link has expired
log('Expired link ' + key)
} else {
// Filter assets to exclude trashed assets
link.assets = link.assets.filter(asset => !asset.isTrashed)
// Populate the shared assets with the public key/password
link.assets.forEach(asset => {
asset.key = key
asset.password = password
})
return {
valid: true,
link
}
}
} else if (res.status === 401 && jsonBody?.message === 'Invalid password') {
// Password authentication required
return {
valid: true,
passwordRequired: true
}
}
}
}
// Otherwise return failure
log('Immich response ' + res.status + ' for key ' + key)
return {
valid: false
}
}
/**
* Stream asset buffer data from Immich.
*
* For photos, you can request 'thumbnail' or 'original' size.
* For videos, it is Immich's streaming quality, not the original quality.
*/
async getAssetBuffer (asset: Asset, size?: ImageSize) {
switch (asset.type) {
case AssetType.image:
size = size === ImageSize.thumbnail ? ImageSize.thumbnail : ImageSize.original
return this.request(this.buildUrl('/assets/' + encodeURIComponent(asset.id) + '/' + size, {
key: asset.key,
password: asset.password
}))
case AssetType.video:
return this.request(this.buildUrl('/assets/' + encodeURIComponent(asset.id) + '/video/playback', {
key: asset.key,
password: asset.password
}))
}
}
/**
* Get the content-type of an Immich asset
*/
async getContentType (asset: Asset) {
const assetBuffer = await this.getAssetBuffer(asset)
return assetBuffer.headers.get('Content-Type')
}
/**
* Build safely-encoded URL string
*/
buildUrl (baseUrl: string, params: { [key: string]: string | undefined } = {}) {
// Remove empty properties
params = Object.fromEntries(Object.entries(params).filter(([_, value]) => !!value))
let query = ''
// Safely encode query parameters
if (Object.entries(params).length) {
query = '?' + (new URLSearchParams(params as {
[key: string]: string
})).toString()
}
return baseUrl + query
}
/**
* Return the image data URL for a photo
*/
photoUrl (key: string, id: string, size?: ImageSize, password?: string) {
const params = { key, size }
if (password) {
Object.assign(params, encrypt(password))
}
return this.buildUrl(`/photo/${key}/${id}`, params)
}
/**
* Return the video data URL for a video
*/
videoUrl (key: string, id: string, password?: string) {
const params = password ? encrypt(password) : {}
return this.buildUrl(`/video/${key}/${id}`, params)
}
/**
* Check if a provided ID matches the Immich ID format
*/
isId (id: string) {
return !!id.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)
}
/**
* Check if a provided key matches the Immich shared-link key format.
* It appears that the key is always 67 chars long, but since I don't know that this
* will always be the case, I've left it open-ended.
*/
isKey (key: string) {
return !!key.match(/^[\w-]+$/)
}
}
const immich = new Immich()
export default immich
+94
View File
@@ -0,0 +1,94 @@
import express from 'express'
import immich from './immich'
import render from './render'
import dayjs from 'dayjs'
import { AssetType, ImageSize } from './types'
import { Request } from 'express-serve-static-core'
import { decrypt } from './encrypt'
require('dotenv').config()
const app = express()
// Add the EJS view engine, to render the gallery page
app.set('view engine', 'ejs')
// Serve static assets from the /public folder
app.use(express.static('public'))
// For parsing the password unlock form
app.use(express.json())
// An incoming request for a shared link
app.get('/share/:key', async (req, res) => {
await immich.handleShareRequest({
key: req.params.key,
size: getSize(req)
}, res)
})
// Receive an unlock request from the password page
app.post('/unlock', async (req, res) => {
await immich.handleShareRequest({
key: toString(req.body.key),
password: toString(req.body.password)
}, res)
})
// Output the buffer data for a photo or video
app.get('/:type(photo|video)/:key/:id', async (req, res) => {
res.set('Cache-Control', 'public, max-age=' + process.env.CACHE_AGE)
// Check for valid key and ID
if (immich.isKey(req.params.key) && immich.isId(req.params.id)) {
// Decrypt the password, if one was provided
let password
if (req.query?.cr && req.query?.iv) {
password = decrypt({
iv: toString(req.query.iv),
cr: toString(req.query.cr)
})
}
// Check if the key is a valid share link
const sharedLink = (await immich.getShareByKey(req.params.key, password))?.link
if (sharedLink?.assets.length) {
// Check that the requested asset exists in this share
const asset = sharedLink.assets.find(x => x.id === req.params.id)
if (asset) {
asset.type = req.params.type === 'video' ? AssetType.video : AssetType.image
render.assetBuffer(res, asset, getSize(req)).then()
return
}
}
}
log('No asset found for ' + req.path)
res.status(404).send()
})
// Healthcheck
app.get('/healthcheck', (_req, res) => {
res.send('ok')
})
// Send a 404 for all other routes
app.get('*', (req, res) => {
log('Invalid route ' + req.path)
res.status(404).send()
})
/**
* Output a console.log message with timestamp
*/
export const log = (message: string) => console.log(dayjs().format() + ' ' + message)
/**
* Sanitise the data for an incoming query string `size` parameter
* e.g. https://example.com/share/abc...xyz?size=thumbnail
*/
const getSize = (req: Request) => {
return req.query?.size === 'thumbnail' ? ImageSize.thumbnail : ImageSize.original
}
const toString = (value: unknown) => {
return typeof value === 'string' ? value : ''
}
app.listen(3000, () => {
console.log(dayjs().format() + ' Server started')
})
+78
View File
@@ -0,0 +1,78 @@
import immich from './immich'
import { Response } from 'express-serve-static-core'
import { Asset, AssetType, ImageSize, SharedLink } from './types'
class Render {
lgConfig = {}
constructor () {
try {
// Import user-provided lightGallery config (if exists)
const config = require('../config.json')
if (typeof config === 'object' && config.lightGallery) this.lgConfig = config.lightGallery
} catch (e) { }
}
async assetBuffer (res: Response, asset: Asset, size?: ImageSize) {
const data = await immich.getAssetBuffer(asset, size)
if (data) {
for (const header of ['content-type', 'content-length']) {
res.set(header, data.headers[header])
}
res.send(Buffer.from(await data.arrayBuffer()))
} else {
res.status(404).send()
}
}
/**
* Render a gallery page for a given SharedLink, using EJS and lightGallery.
*
* @param res - ExpressJS Response
* @param share - Immich `shared-link` containing the assets to show in the gallery
* @param [openItem] - Immediately open a lightbox to the Nth item when the gallery loads
*/
async gallery (res: Response, share: SharedLink, openItem?: number) {
const items = []
for (const asset of share.assets) {
let video
if (asset.type === AssetType.video) {
// Populate the data-video property
video = JSON.stringify({
source: [
{
src: immich.videoUrl(share.key, asset.id, asset.password),
type: await immich.getContentType(asset)
}
],
attributes: {
preload: false,
controls: true
}
})
}
items.push({
originalUrl: immich.photoUrl(share.key, asset.id, undefined, asset.password),
thumbnailUrl: immich.photoUrl(share.key, asset.id, ImageSize.thumbnail, asset.password),
video
})
}
res.render('gallery', {
items,
openItem,
title: this.title(share),
lgConfig: this.lgConfig
})
}
/**
* Attempt to get a title from the link description or the album title
*/
title (share: SharedLink) {
return share.description || share?.album?.albumName || ''
}
}
const render = new Render()
export default render
+42
View File
@@ -0,0 +1,42 @@
export enum AssetType {
image = 'IMAGE',
video = 'VIDEO'
}
export interface Asset {
id: string;
key: string;
password?: string;
type: AssetType;
isTrashed: boolean;
}
export interface SharedLink {
key: string;
type: string;
description?: string;
assets: Asset[];
album?: {
id: string;
albumName?: string;
}
expiresAt: string | null;
}
export interface SharedLinkResult {
valid: boolean;
key?: string;
passwordRequired?: boolean;
link?: SharedLink;
}
export enum ImageSize {
thumbnail = 'thumbnail',
original = 'original'
}
export interface IncomingShareRequest {
key: string;
password?: string;
size?: ImageSize;
}