Public shares: any valid Immich link opens through the proxy and is recorded in /admin, with a per-share sign-in-only switch; comments stay recipient-only

This commit is contained in:
zyphlar
2026-11-07 22:34:44 -08:00
parent d4ce4444b8
commit 17bf59b218
9 changed files with 368 additions and 42 deletions
+16 -7
View File
@@ -1,11 +1,16 @@
# Immich Magic Proxy # Immich Magic Proxy
A fork of [Immich Public Proxy](https://github.com/alangrainger/immich-public-proxy) (4.1.1) where shares are A fork of [Immich Public Proxy](https://github.com/alangrainger/immich-public-proxy) (4.1.1) that adds invitations,
**private**: only people you invite can see them. comments and new-photo emails. Each share is either **public** (anyone with its Immich link can view it, as upstream)
or **sign-in only** (only people you invite).
- **Magic links.** You add an Immich shared link and the people allowed to see it. Each person gets a personal link. - **Public or sign-in only.** Any Immich shared link opened through the proxy is added to `/admin` automatically, as
Without a valid link, every page, photo, video, download and API route answers with a "private photos" page or a public. Untick "Public link works" there to make it sign-in only. Shares you add in `/admin` yourself are public
404, and never touches Immich. unless you untick the box when adding them. Shares added before this setting existed stay sign-in only. A key
Immich doesn't know is refused, and Immich is asked about it at most once every 10 minutes.
- **Magic links.** You add the people allowed to see a share. Each person gets a personal link. For a sign-in only
share, without a valid link every page, photo, video, download and API route answers with a "private photos"
page or a 404, and never touches Immich.
- **Bookmarkable.** Opening the link signs that browser in with an `HttpOnly` cookie that lasts 400 days (the - **Bookmarkable.** Opening the link signs that browser in with an `HttpOnly` cookie that lasts 400 days (the
browser maximum) and renews itself daily while in use. Sessions live in the database, so restarts don't sign browser maximum) and renews itself daily while in use. Sessions live in the database, so restarts don't sign
anyone out. Recipients can bookmark an album, or `/me` for all their albums. anyone out. Recipients can bookmark an album, or `/me` for all their albums.
@@ -13,7 +18,8 @@ A fork of [Immich Public Proxy](https://github.com/alangrainger/immich-public-pr
proxy checks every album for new photos and sends one summary email per period, with a sign-in link per album. proxy checks every album for new photos and sends one summary email per period, with a sign-in link per album.
Photos that were already there when someone got access are never reported as new. Photos that were already there when someone got access are never reported as new.
- **Comments.** Recipients can comment on any photo from the lightbox (comment button, or the info sidebar). They can - **Comments.** Recipients can comment on any photo from the lightbox (comment button, or the info sidebar). They can
delete their own; you can moderate all of them from the admin page. delete their own; you can moderate all of them from the admin page. Comments are only ever shown to recipients
given that share, never to other visitors of a public share.
- **Lost links.** A visitor with no session can ask for a new link by email. The reply is the same whether or not the - **Lost links.** A visitor with no session can ask for a new link by email. The reply is the same whether or not the
address was invited, and requests are rate-limited. address was invited, and requests are rate-limited.
- **Password-protected shares.** Store the share password when adding the album, and recipients are never asked - **Password-protected shares.** Store the share password when adding the album, and recipients are never asked
@@ -26,7 +32,8 @@ To run it in an LXC container (Proxmox, Incus, LXD) instead of Docker, see [`lxc
1. Set the environment (see `docker-compose.yml`) and start it with `docker compose up -d --build`. Mount a volume at 1. Set the environment (see `docker-compose.yml`) and start it with `docker compose up -d --build`. Mount a volume at
`/data`: it holds the SQLite database of recipients, sessions and comments. Back it up. `/data`: it holds the SQLite database of recipients, sessions and comments. Back it up.
2. Open `/admin` and sign in with `ADMIN_PASSWORD`. 2. Open `/admin` and sign in with `ADMIN_PASSWORD`.
3. Under **Albums**, paste an Immich shared link (`https://immich.example.com/share/...` or `/s/<slug>`). 3. Under **Albums**, paste an Immich shared link (`https://immich.example.com/share/...` or `/s/<slug>`), or just
open it through the proxy. Choose whether its public link works.
4. Under **Recipients**, add each person, tick their albums, and either email the invitation or copy the link. 4. Under **Recipients**, add each person, tick their albums, and either email the invitation or copy the link.
From a recipient's page you can send a new link, revoke every link and session they have, disable them, or delete From a recipient's page you can send a new link, revoke every link and session they have, disable them, or delete
@@ -57,6 +64,8 @@ them.
so don't route it unless you accept that anyone with a share key can upload. so don't route it unless you accept that anyone with a share key can upload.
- An Immich share link still works directly on Immich itself; this proxy only controls access through the proxy. - An Immich share link still works directly on Immich itself; this proxy only controls access through the proxy.
Keep Immich private, as upstream recommends. Keep Immich private, as upstream recommends.
- Removing a share in `/admin` doesn't block its link: if Immich still accepts it, opening it adds the share back as
public. To block a share, make it sign-in only, or delete the link in Immich.
The rest of this README is upstream's. The rest of this README is upstream's.
+3 -2
View File
@@ -45,9 +45,10 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
const motionPhotos = !!getConfigOption('ipp.motionPhotos', true) const motionPhotos = !!getConfigOption('ipp.motionPhotos', true)
const descriptionInCaption = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.caption', false) const descriptionInCaption = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.caption', false)
const descriptionInSidebar = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.sidebar', false) const descriptionInSidebar = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.sidebar', false)
// A signed-in recipient can comment, which lives in the sidebar too // A recipient given this share can comment, which lives in the sidebar too.
// Anyone else viewing a public share (signed in or not) never sees comments.
const viewer = res.req.recipient const viewer = res.req.recipient
const comments = viewer const comments = viewer && res.req.grantedShare?.key === share.key
? { base: '/share/comments/' + share.key, counts: getStore().countComments(share.key) } ? { base: '/share/comments/' + share.key, counts: getStore().countComments(share.key) }
: undefined : undefined
const sidebarHasContent = !!comments || const sidebarHasContent = !!comments ||
+112
View File
@@ -0,0 +1,112 @@
import { NextFunction, Request, Response } from 'express-serve-static-core'
import { fetchSharedLink, getKeyTypeFromShare, isKey, KeyType, log, slugLinksDisabled, title, TtlLruCache } from '@ipp/core'
import { getStore, ShareRecord } from './store'
import { listShareAssets, scanShare } from './digest'
import { deny, nowIso } from './session'
declare module 'express-serve-static-core' {
interface Request {
/** The share being viewed, whether by grant or because it is public. */
viewedShare?: ShareRecord
}
}
// Keys and slugs Immich said don't exist, so a scanner trying random keys
// can't make the proxy ask Immich about each one more than once in a while
const unknownToImmich = new TtlLruCache<true>({ ttlMs: 10 * 60_000, max: 5000 })
// One Immich lookup per new share, however many requests arrive at once
const discovering = new Map<string, Promise<ShareRecord | undefined>>()
const SLUG = /^[A-Za-z0-9_-]{1,200}$/
/**
* Look up a share this proxy hasn't seen in Immich, and record it if Immich
* knows it. New shares start public: their link already works in Immich
* itself, and the admin can switch any of them to sign-in only.
*/
async function discoverShare (keyOrSlug: string, keyType: KeyType): Promise<ShareRecord | undefined> {
if (keyType === KeyType.key ? !isKey(keyOrSlug) : (slugLinksDisabled(keyType) || !SLUG.test(keyOrSlug))) return undefined
const cacheKey = keyType + ':' + keyOrSlug
if (unknownToImmich.get(cacheKey)) return undefined
let pending = discovering.get(cacheKey)
if (!pending) {
pending = (async () => {
const result = await fetchSharedLink(keyOrSlug, keyType)
if (!result.valid) {
unknownToImmich.set(cacheKey, true)
return undefined
}
const store = getStore()
if (result.link) {
const share = store.addDiscoveredShare({ key: result.link.key, slug: result.link.slug || null, title: title(result.link) }, nowIso())
log('Added share "' + share.title + '", opened by its Immich link')
// Note what's there now, so recipients added later only hear about newer photos
scanShare(store, share, listShareAssets, nowIso()).catch(() => false)
return share
}
// Password-protected: Immich won't say more without the password. Record
// it by key so the visitor gets the password page; a slug can't be
// recorded, as only the key identifies the share.
if (keyType !== KeyType.key) return undefined
const share = store.addDiscoveredShare({ key: keyOrSlug, slug: null, title: 'Password-protected share' }, nowIso())
log('Added a password-protected share, opened by its Immich link')
return share
})().finally(() => discovering.delete(cacheKey))
discovering.set(cacheKey, pending)
}
return pending
}
/**
* Which share, if any, this visitor may view by `keyOrSlug`: one granted to
* the signed-in recipient, or any public one. Never asks Immich.
*/
function viewableShare (req: Request, keyOrSlug: string): { share?: ShareRecord, granted: boolean, known: boolean } {
const store = getStore()
const granted = req.recipient ? store.grantedShare(req.recipient.id, keyOrSlug) : undefined
if (granted) return { share: granted, granted: true, known: true }
const share = store.findShare(keyOrSlug)
return { share: share?.public ? share : undefined, granted: false, known: !!share }
}
function admit (req: Request, res: Response, share: ShareRecord, granted: boolean) {
req.viewedShare = share
if (granted) {
req.grantedShare = share
// Recipients are never asked for a password the admin stored. Anonymous
// visitors to a public share go through Immich's own password page.
if (!req.password && share.password) req.password = share.password
}
// What a visitor sees depends on who they are, so never share a cached copy
res.set('Vary', 'Cookie')
}
/**
* Gate for viewing a share (its gallery, photos, videos, downloads). Passes a
* recipient given the share, or anyone for a public one. A share key or slug
* this proxy hasn't seen is checked with Immich and, if real, recorded as a
* public share. Comments are behind `requireShareAccess` instead, so they
* stay recipient-only.
*/
export async function allowShareView (req: Request, res: Response, next: NextFunction) {
try {
const keyOrSlug = req.params.key
if (typeof keyOrSlug !== 'string') return deny(req, res, 'No share in ' + req.path)
let { share, granted, known } = viewableShare(req, keyOrSlug)
if (!share && !known) {
// Asset routes (/share/photo|video/...) only ever take keys
const keyType = req.params.shareType ? getKeyTypeFromShare(req.params.shareType) : KeyType.key
share = await discoverShare(keyOrSlug, keyType)
}
if (!share) return deny(req, res, 'No access to share ' + keyOrSlug)
admit(req, res, share, granted)
next()
} catch (e) {
next(e)
}
}
/** True if this visitor may view the share with this key; for the password unlock form. */
export function canViewShare (req: Request, key: string): boolean {
return !!viewableShare(req, key).share
}
+13 -1
View File
@@ -73,6 +73,11 @@ function bodyString (req: Request, field: string, max = 300): string {
return typeof value === 'string' ? value.trim().slice(0, max) : '' return typeof value === 'string' ? value.trim().slice(0, max) : ''
} }
/** A checkbox posting value "1"; a hidden "0" beside it may be sent too. */
function checkboxOn (req: Request, field: string): boolean {
return bodyList(req, field).includes('1')
}
function bodyList (req: Request, field: string): string[] { function bodyList (req: Request, field: string): string[] {
const value = req.body?.[field] const value = req.body?.[field]
return (Array.isArray(value) ? value : value === undefined ? [] : [value]).filter((v): v is string => typeof v === 'string') return (Array.isArray(value) ? value : value === undefined ? [] : [value]).filter((v): v is string => typeof v === 'string')
@@ -217,13 +222,20 @@ export function registerAdminRoutes (app: Express) {
key: result.link.key, key: result.link.key,
slug: result.link.slug || null, slug: result.link.slug || null,
title: title(result.link), title: title(result.link),
password: password ?? null password: password ?? null,
public: checkboxOn(req, 'public')
}, nowIso()) }, nowIso())
// Record what's there now, so recipients are only told about later photos // Record what's there now, so recipients are only told about later photos
await scanShare(store, share, listShareAssets, nowIso()).catch(() => false) await scanShare(store, share, listShareAssets, nowIso()).catch(() => false)
renderDashboard(res, { kind: 'ok', text: 'Added "' + share.title + '".' }) renderDashboard(res, { kind: 'ok', text: 'Added "' + share.title + '".' })
})) }))
app.post('/admin/shares/:key/access', (req, res) => {
const store = getStore()
if (store.getShare(req.params.key)) store.setSharePublic(req.params.key, checkboxOn(req, 'public'))
res.redirect(303, '/admin')
})
app.post('/admin/shares/:key/delete', (req, res) => { app.post('/admin/shares/:key/delete', (req, res) => {
getStore().deleteShare(req.params.key) getStore().deleteShare(req.params.key)
res.redirect(303, '/admin') res.redirect(303, '/admin')
+57 -12
View File
@@ -27,6 +27,8 @@ export interface ShareRecord {
title: string title: string
/** Lets recipients and the background scanner open a password-protected share. */ /** Lets recipients and the background scanner open a password-protected share. */
password: string | null password: string | null
/** Anyone with the Immich link may view it, not only signed-in recipients. */
public: boolean
lastScannedAt: string | null lastScannedAt: string | null
createdAt: string createdAt: string
} }
@@ -57,7 +59,8 @@ const SCHEMA = `
title TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '',
password TEXT, password TEXT,
last_scanned_at TEXT, last_scanned_at TEXT,
created_at TEXT NOT NULL created_at TEXT NOT NULL,
public INTEGER NOT NULL DEFAULT 0
); );
CREATE TABLE IF NOT EXISTS recipient_shares ( CREATE TABLE IF NOT EXISTS recipient_shares (
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE, recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
@@ -104,13 +107,19 @@ const SCHEMA = `
const RECIPIENT_COLUMNS = `id, name, email, frequency, last_digest_at AS lastDigestAt, const RECIPIENT_COLUMNS = `id, name, email, frequency, last_digest_at AS lastDigestAt,
created_at AS createdAt, disabled` created_at AS createdAt, disabled`
const SHARE_COLUMNS = 'key, slug, title, password, last_scanned_at AS lastScannedAt, created_at AS createdAt' const SHARE_COLUMNS = 'key, slug, title, password, public, last_scanned_at AS lastScannedAt, created_at AS createdAt'
const JOINED_SHARE_COLUMNS = 's.key, s.slug, s.title, s.password, s.last_scanned_at AS lastScannedAt, s.created_at AS createdAt' const JOINED_SHARE_COLUMNS = 's.key, s.slug, s.title, s.password, s.public, s.last_scanned_at AS lastScannedAt, s.created_at AS createdAt'
const COMMENT_COLUMNS = `id, share_key AS shareKey, asset_id AS assetId, recipient_id AS recipientId, const COMMENT_COLUMNS = `id, share_key AS shareKey, asset_id AS assetId, recipient_id AS recipientId,
author_name AS authorName, body, created_at AS createdAt` author_name AS authorName, body, created_at AS createdAt`
type Row = Record<string, SQLInputValue> type Row = Record<string, SQLInputValue>
function toShare<T extends ShareRecord> (row: unknown): T | undefined {
if (!row) return undefined
const share = row as Row
return { ...(share as unknown as T), public: !!share.public }
}
function toRecipient (row: Row | undefined): Recipient | undefined { function toRecipient (row: Row | undefined): Recipient | undefined {
if (!row) return undefined if (!row) return undefined
return { ...(row as unknown as Recipient), disabled: !!row.disabled } return { ...(row as unknown as Recipient), disabled: !!row.disabled }
@@ -130,6 +139,14 @@ export class Store {
this.db.exec('PRAGMA busy_timeout = 5000') this.db.exec('PRAGMA busy_timeout = 5000')
if (path !== ':memory:') this.db.exec('PRAGMA journal_mode = WAL') if (path !== ':memory:') this.db.exec('PRAGMA journal_mode = WAL')
this.db.exec(SCHEMA) this.db.exec(SCHEMA)
this.migrate()
}
/** Bring a database made by an earlier release up to the current schema. */
private migrate () {
const shareColumns = this.db.prepare('PRAGMA table_info(shares)').all().map(row => row.name)
// Shares added before this column existed keep requiring sign-in
if (!shareColumns.includes('public')) this.db.exec('ALTER TABLE shares ADD COLUMN public INTEGER NOT NULL DEFAULT 0')
} }
close () { close () {
@@ -196,19 +213,47 @@ export class Store {
// ----- shares -------------------------------------------------------------- // ----- shares --------------------------------------------------------------
upsertShare (input: { key: string, slug: string | null, title: string, password: string | null }, now: string): ShareRecord { /**
this.db.prepare(`INSERT INTO shares (key, slug, title, password, created_at) VALUES (?, ?, ?, ?, ?) * Add or update a share from the admin console. A new share requires sign-in
ON CONFLICT (key) DO UPDATE SET slug = excluded.slug, title = excluded.title, password = excluded.password`) * unless `public` says otherwise; an existing one keeps its setting unless
.run(input.key, input.slug, input.title, input.password, now) * `public` is given.
*/
upsertShare (input: { key: string, slug: string | null, title: string, password: string | null, public?: boolean }, now: string): ShareRecord {
const pub = input.public === undefined ? null : input.public ? 1 : 0
this.db.prepare(`INSERT INTO shares (key, slug, title, password, public, created_at) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (key) DO UPDATE SET slug = excluded.slug, title = excluded.title, password = excluded.password,
public = COALESCE(?, public)`)
.run(input.key, input.slug, input.title, input.password, pub ?? 0, now, pub)
return this.getShare(input.key)!
}
/**
* Record a share someone opened by its Immich link before it was added
* here. It starts public, since its link already worked in Immich. A share
* already on file (e.g. found again by its slug) is left exactly as it is.
*/
addDiscoveredShare (input: { key: string, slug: string | null, title: string }, now: string): ShareRecord {
this.db.prepare(`INSERT INTO shares (key, slug, title, password, public, created_at) VALUES (?, ?, ?, NULL, 1, ?)
ON CONFLICT (key) DO NOTHING`).run(input.key, input.slug, input.title, now)
return this.getShare(input.key)! return this.getShare(input.key)!
} }
getShare (key: string): ShareRecord | undefined { getShare (key: string): ShareRecord | undefined {
return this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares WHERE key = ?`).get(key) as ShareRecord | undefined return toShare(this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares WHERE key = ?`).get(key))
}
/** A share on file by its key or its slug, preferring a key match. */
findShare (keyOrSlug: string): ShareRecord | undefined {
return toShare(this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares WHERE key = ? OR slug = ?
ORDER BY key = ? DESC LIMIT 1`).get(keyOrSlug, keyOrSlug, keyOrSlug))
} }
listShares (): ShareRecord[] { listShares (): ShareRecord[] {
return this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares ORDER BY title COLLATE NOCASE`).all() as unknown as ShareRecord[] return this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares ORDER BY title COLLATE NOCASE`).all().map(row => toShare(row)!)
}
setSharePublic (key: string, isPublic: boolean) {
this.db.prepare('UPDATE shares SET public = ? WHERE key = ?').run(isPublic ? 1 : 0, key)
} }
deleteShare (key: string) { deleteShare (key: string) {
@@ -240,7 +285,7 @@ export class Store {
listRecipientShares (recipientId: number): Array<ShareRecord & { grantedAt: string }> { listRecipientShares (recipientId: number): Array<ShareRecord & { grantedAt: string }> {
return this.db.prepare(`SELECT ${JOINED_SHARE_COLUMNS}, rs.granted_at AS grantedAt FROM shares s return this.db.prepare(`SELECT ${JOINED_SHARE_COLUMNS}, rs.granted_at AS grantedAt FROM shares s
JOIN recipient_shares rs ON rs.share_key = s.key WHERE rs.recipient_id = ? ORDER BY s.title COLLATE NOCASE`) JOIN recipient_shares rs ON rs.share_key = s.key WHERE rs.recipient_id = ? ORDER BY s.title COLLATE NOCASE`)
.all(recipientId) as unknown as Array<ShareRecord & { grantedAt: string }> .all(recipientId).map(row => toShare<ShareRecord & { grantedAt: string }>(row)!)
} }
countShareRecipients (key: string): number { countShareRecipients (key: string): number {
@@ -253,10 +298,10 @@ export class Store {
* the one access check every share-scoped route goes through. * the one access check every share-scoped route goes through.
*/ */
grantedShare (recipientId: number, keyOrSlug: string): ShareRecord | undefined { grantedShare (recipientId: number, keyOrSlug: string): ShareRecord | undefined {
return this.db.prepare(`SELECT ${JOINED_SHARE_COLUMNS} FROM shares s return toShare(this.db.prepare(`SELECT ${JOINED_SHARE_COLUMNS} FROM shares s
JOIN recipient_shares rs ON rs.share_key = s.key JOIN recipient_shares rs ON rs.share_key = s.key
WHERE rs.recipient_id = ? AND (s.key = ? OR s.slug = ?)`) WHERE rs.recipient_id = ? AND (s.key = ? OR s.slug = ?)`)
.get(recipientId, keyOrSlug, keyOrSlug) as ShareRecord | undefined .get(recipientId, keyOrSlug, keyOrSlug))
} }
// ----- magic links --------------------------------------------------------- // ----- magic links ---------------------------------------------------------
+22 -3
View File
@@ -24,9 +24,13 @@ const STYLE = `
` `
// Forms with data-confirm ask before submitting // Forms with data-confirm ask before submitting
// and inputs with data-autosubmit submit their form as soon as they change
const CONFIRM_SCRIPT = `document.addEventListener('submit', function (e) { const CONFIRM_SCRIPT = `document.addEventListener('submit', function (e) {
var message = e.target.getAttribute('data-confirm') var message = e.target.getAttribute('data-confirm')
if (message && !confirm(message)) e.preventDefault() if (message && !confirm(message)) e.preventDefault()
})
document.addEventListener('change', function (e) {
if (e.target.hasAttribute('data-autosubmit')) e.target.form.submit()
})` })`
function Layout ({ title, children }: { title: string, children: ComponentChildren }) { function Layout ({ title, children }: { title: string, children: ComponentChildren }) {
@@ -187,19 +191,30 @@ export function AdminDashboard ({ shares, recipients, comments, emailEnabled, me
<section> <section>
<h2>Albums</h2> <h2>Albums</h2>
<p class="muted">Add an Immich shared link here, then give recipients access to it. Only recipients can open it through this proxy.</p> <p class="muted">Any Immich shared link opened through this proxy is added here automatically. A public album opens for anyone with its link; otherwise only signed-in recipients can open it. Comments and new-photo emails are for recipients only.</p>
{shares.length > 0 && ( {shares.length > 0 && (
<table> <table>
<thead><tr><th>Album</th><th>Recipients</th><th>Photos tracked</th><th></th></tr></thead> <thead><tr><th>Album</th><th>Public link works</th><th>Recipients</th><th>Photos tracked</th><th></th></tr></thead>
<tbody> <tbody>
{shares.map(({ share, recipients: count, assets }) => ( {shares.map(({ share, recipients: count, assets }) => (
<tr key={share.key}> <tr key={share.key}>
<td>{share.title || 'Untitled'}<br/><small class="muted">{share.slug ? 's/' + share.slug : share.key.slice(0, 12) + '…'}{share.password ? ' · password stored' : ''}</small></td> <td>{share.title || 'Untitled'}<br/><small class="muted">{share.slug ? 's/' + share.slug : share.key.slice(0, 12) + '…'}{share.password ? ' · password stored' : ''}</small></td>
<td>
<form method="post" action={'/admin/shares/' + encodeURIComponent(share.key) + '/access'} style="margin:0">
<input type="hidden" name="public" value="0"/>
<label style="margin:0">
<input type="checkbox" name="public" value="1" checked={share.public} data-autosubmit
aria-label={'Anyone with the link can view ' + (share.title || 'this album')}/>
{share.public ? 'Yes' : 'Sign-in only'}
</label>
<noscript><button type="submit" class="secondary outline" style="margin:0;padding:.2rem .5rem;font-size:.8rem">Save</button></noscript>
</form>
</td>
<td>{count}</td> <td>{count}</td>
<td>{assets}</td> <td>{assets}</td>
<td> <td>
<form method="post" action={'/admin/shares/' + encodeURIComponent(share.key) + '/delete'} <form method="post" action={'/admin/shares/' + encodeURIComponent(share.key) + '/delete'}
data-confirm='Remove this album? Recipients lose access and its comments are deleted.'> data-confirm='Remove this album? Recipients lose access and its comments are deleted. If its Immich link still works, opening it here adds it back as public: to block it, untick "Public link works" instead.'>
<button type="submit" class="secondary outline" style="margin:0;padding:.3rem .6rem;font-size:.8rem">Remove</button> <button type="submit" class="secondary outline" style="margin:0;padding:.3rem .6rem;font-size:.8rem">Remove</button>
</form> </form>
</td> </td>
@@ -219,6 +234,10 @@ export function AdminDashboard ({ shares, recipients, comments, emailEnabled, me
Share password <small class="muted">(only if the Immich link has one; stored so recipients aren't asked for it)</small> Share password <small class="muted">(only if the Immich link has one; stored so recipients aren't asked for it)</small>
<input type="password" name="password" autocomplete="off"/> <input type="password" name="password" autocomplete="off"/>
</label> </label>
<label>
<input type="checkbox" name="public" value="1" checked/>
Anyone with the link can view <small class="muted">(untick to allow only signed-in recipients)</small>
</label>
<button type="submit">Add album</button> <button type="submit">Add album</button>
</form> </form>
</details> </details>
+22 -16
View File
@@ -25,7 +25,8 @@ import { ImageSize } from './types'
import { canDownload, uploadHealthcheck } from './share' import { canDownload, uploadHealthcheck } from './share'
import { ASSET_VERSION } from './version' import { ASSET_VERSION } from './version'
import { resolveShare, resolveSharedAsset } from './resolve' import { resolveShare, resolveSharedAsset } from './resolve'
import { deny, loadRecipient, requireRecipient, requireShareAccess } from './magic/session' import { deny, loadRecipient, requireRecipient } from './magic/session'
import { allowShareView, canViewShare } from './magic/access'
import { registerRecipientRoutes, registerSignInRoutes } from './magic/routes' import { registerRecipientRoutes, registerSignInRoutes } from './magic/routes'
import { registerAdminRoutes } from './magic/admin' import { registerAdminRoutes } from './magic/admin'
import { getStore } from './magic/store' import { getStore } from './magic/store'
@@ -34,9 +35,12 @@ import { getStore } from './magic/store'
* Build the Express app. Call `loadConfig` first: routes read config as they * Build the Express app. Call `loadConfig` first: routes read config as they
* are registered. * are registered.
* *
* Every route that shows anything from Immich sits behind two gates: a * Every route that shows anything from Immich is gated. A share's gallery,
* magic-link session (`requireRecipient`), and that recipient having been * photos and downloads open for a recipient given that share, or for anyone
* given the specific share (`requireShareAccess`). * when the share is public (`allowShareView`); an Immich link not seen before
* is checked with Immich and recorded as a public share. Everything else,
* comments included, needs a magic-link session (`requireRecipient`) and,
* for comments, a grant of that share (`requireShareAccess`).
*/ */
export function createApp (): Express { export function createApp (): Express {
const app = express() const app = express()
@@ -89,14 +93,11 @@ export function createApp (): Express {
registerSignInRoutes(app) registerSignInRoutes(app)
registerAdminRoutes(app) registerAdminRoutes(app)
// ----- everything below needs a magic-link session -------------------------- // ----- shares: public ones for anyone, the rest for their recipients --------
app.use(requireRecipient)
registerRecipientRoutes(app)
/* /*
[ROUTE] The main URL a visitor opens from a shared link [ROUTE] The main URL a visitor opens from a shared link
*/ */
app.get('/:shareType(share|s)/:key/:mode(download)?', requireShareAccess, decodeCookie, asyncHandler(async (req, res) => { app.get('/:shareType(share|s)/:key/:mode(download)?', allowShareView, decodeCookie, asyncHandler(async (req, res) => {
const keyType = getKeyTypeFromShare(req.params.shareType) const keyType = getKeyTypeFromShare(req.params.shareType)
if (slugLinksDisabled(keyType)) { if (slugLinksDisabled(keyType)) {
@@ -113,13 +114,14 @@ export function createApp (): Express {
})) }))
/* /*
[ROUTE] Password unlock from the password page. Only reachable for a [ROUTE] Password unlock from the password page, for a visitor who may
share without a stored password, and only for a recipient of that share. view the share: a recipient of it (when no password is stored), or
anyone for a public share.
*/ */
app.post('/share/unlock', (req, res, next) => { app.post('/share/unlock', (req, res, next) => {
const key = req.body?.key const key = req.body?.key
if (typeof key !== 'string' || !isKey(key) || !getStore().grantedShare(req.recipient!.id, key)) { if (typeof key !== 'string' || !isKey(key) || !canViewShare(req, key)) {
deny(req, res, 'Unlock for a share the recipient was not given') deny(req, res, 'Unlock for a share this visitor may not view')
return return
} }
next() next()
@@ -131,7 +133,7 @@ export function createApp (): Express {
Validates each ID against share.assets so the request can't pull anything Validates each ID against share.assets so the request can't pull anything
outside the share. outside the share.
*/ */
app.post('/:shareType(share|s)/:key/download', requireShareAccess, decodeCookie, asyncHandler(async (req, res) => { app.post('/:shareType(share|s)/:key/download', allowShareView, decodeCookie, asyncHandler(async (req, res) => {
const keyType = getKeyTypeFromShare(req.params.shareType) const keyType = getKeyTypeFromShare(req.params.shareType)
let requestedIds: unknown let requestedIds: unknown
try { try {
@@ -177,7 +179,7 @@ export function createApp (): Express {
/* /*
[ROUTE] Direct link to a photo or video asset [ROUTE] Direct link to a photo or video asset
*/ */
app.get('/share/:type(photo|video)/:key/:id/:size?', requireShareAccess, decodeCookie, asyncHandler(async (req, res) => { app.get('/share/:type(photo|video)/:key/:id/:size?', allowShareView, decodeCookie, asyncHandler(async (req, res) => {
addResponseHeaders(res) addResponseHeaders(res)
if (req.params.size && !Object.values(ImageSize).includes(req.params.size as ImageSize)) { if (req.params.size && !Object.values(ImageSize).includes(req.params.size as ImageSize)) {
@@ -220,7 +222,7 @@ export function createApp (): Express {
validated against the share's asset set (defence in depth - Immich also validated against the share's asset set (defence in depth - Immich also
enforces this via the share key) before we fetch `GET /assets/:id`. enforces this via the share key) before we fetch `GET /assets/:id`.
*/ */
app.get('/:shareType(share|s)/meta/:key/:id', requireShareAccess, decodeCookie, asyncHandler(async (req, res) => { app.get('/:shareType(share|s)/meta/:key/:id', allowShareView, decodeCookie, asyncHandler(async (req, res) => {
addResponseHeaders(res) addResponseHeaders(res)
const resolved = await resolveSharedAsset(req, getKeyTypeFromShare(req.params.shareType)) const resolved = await resolveSharedAsset(req, getKeyTypeFromShare(req.params.shareType))
@@ -240,6 +242,10 @@ export function createApp (): Express {
res.json(buildAssetMetadata(detail, resolved.link)) res.json(buildAssetMetadata(detail, resolved.link))
})) }))
// ----- everything below needs a magic-link session --------------------------
app.use(requireRecipient)
registerRecipientRoutes(app)
/* /*
[ROUTE] Send a 404 for all other routes and methods. `all`, so a POST or DELETE to an [ROUTE] Send a 404 for all other routes and methods. `all`, so a POST or DELETE to an
unknown path gets the same policy instead of Express's own HTML error page. unknown path gets the same policy instead of Express's own HTML error page.
+71 -1
View File
@@ -18,6 +18,9 @@ const KEY_A = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
const KEY_B = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' const KEY_B = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
const KEY_C = 'ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' const KEY_C = 'ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc'
const KEY_P = 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp' const KEY_P = 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp'
// In Immich but never added to the proxy: opened by their Immich links
const KEY_D = 'ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'
const KEY_E = 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
const ASSET_1 = '11111111-1111-4111-8111-111111111111' const ASSET_1 = '11111111-1111-4111-8111-111111111111'
const ASSET_2 = '22222222-2222-4222-8222-222222222222' const ASSET_2 = '22222222-2222-4222-8222-222222222222'
const ASSET_B = '33333333-3333-4333-8333-333333333333' const ASSET_B = '33333333-3333-4333-8333-333333333333'
@@ -53,7 +56,9 @@ const links: Record<string, ReturnType<typeof link>> = {
[KEY_A]: link(KEY_A, 'Holiday', 'holiday', [ASSET_1, ASSET_2]), [KEY_A]: link(KEY_A, 'Holiday', 'holiday', [ASSET_1, ASSET_2]),
[KEY_B]: link(KEY_B, 'Wedding', null, [ASSET_B]), [KEY_B]: link(KEY_B, 'Wedding', null, [ASSET_B]),
[KEY_C]: link(KEY_C, 'Garden', null, [ASSET_1]), [KEY_C]: link(KEY_C, 'Garden', null, [ASSET_1]),
[KEY_P]: link(KEY_P, 'Private party', null, [ASSET_P]) [KEY_P]: link(KEY_P, 'Private party', null, [ASSET_P]),
[KEY_D]: link(KEY_D, 'Picnic', null, [ASSET_2]),
[KEY_E]: link(KEY_E, 'Beach', 'beach', [ASSET_1])
} }
const PASSWORD = 'party-pw' const PASSWORD = 'party-pw'
const IMMICH_TOKEN = 'immich-token-for-p' const IMMICH_TOKEN = 'immich-token-for-p'
@@ -459,3 +464,68 @@ describe('admin console', () => {
expect((await request(linkPath, { page: true })).res.status).toBe(401) expect((await request(linkPath, { page: true })).res.status).toBe(401)
}) })
}) })
describe('public shares', () => {
it('an Immich link not seen before opens for anyone, without comments, and is recorded as public', async () => {
const page = await request('/share/' + KEY_D, { page: true })
expect(page.res.status).toBe(200)
expect(page.text).toContain('Picnic')
expect(page.text).not.toContain('/share/comments/')
expect(page.res.headers.get('vary')).toContain('Cookie')
expect(store.getShare(KEY_D)).toMatchObject({ title: 'Picnic', public: true, password: null })
const photo = await request('/share/photo/' + KEY_D + '/' + ASSET_2 + '/thumbnail')
expect(photo.res.status).toBe(200)
expect(photo.text).toBe('JPEG:' + ASSET_2)
// Another share's photo can't be pulled through this one
expect((await request('/share/photo/' + KEY_D + '/' + ASSET_1 + '/thumbnail')).res.status).toBe(404)
// Comments stay recipient-only
expect((await request('/share/comments/' + KEY_D + '/' + ASSET_2)).res.status).toBe(404)
expect((await request('/share/comments/' + KEY_D + '/' + ASSET_2, { json: { body: 'hi' } })).res.status).toBe(404)
})
it('opens by slug too, recording the share under its key', async () => {
expect((await request('/s/beach', { page: true })).res.status).toBe(200)
expect(store.getShare(KEY_E)).toMatchObject({ slug: 'beach', public: true })
})
it('refuses a key Immich does not know, and asks Immich about it only once', async () => {
const unknown = 'z'.repeat(67)
const before = immichCalls
expect((await request('/share/' + unknown, { page: true })).res.status).toBe(401)
expect((await request('/share/' + unknown, { page: true })).res.status).toBe(401)
expect(immichCalls - before).toBe(1)
expect(store.getShare(unknown)).toBeUndefined()
})
it('a recipient not given the share can view it, but not comment', async () => {
const cookie = await signIn()
const page = await request('/share/' + KEY_D, { page: true, cookie })
expect(page.res.status).toBe(200)
expect(page.text).not.toContain('/share/comments/')
expect((await request('/share/comments/' + KEY_D + '/' + ASSET_2, { cookie, json: { body: 'hi' } })).res.status).toBe(404)
})
it('the admin can switch a share to sign-in only, and back', async () => {
const login = await request('/admin/login', { form: { password: 'admin-secret' } })
const admin = cookieFrom(login.res, 'imp_admin')!
const dashboard = await request('/admin', { page: true, cookie: admin })
expect(dashboard.text).toContain('Picnic')
expect(dashboard.text).toContain('Public link works')
await request('/admin/shares/' + KEY_D + '/access', { cookie: admin, form: { public: '0' } })
expect(store.getShare(KEY_D)?.public).toBe(false)
expect((await request('/share/' + KEY_D, { page: true })).res.status).toBe(401)
expect((await request('/share/photo/' + KEY_D + '/' + ASSET_2 + '/thumbnail')).res.status).toBe(404)
expect((await request('/share/' + KEY_D, { page: true, cookie: await signIn() })).res.status).toBe(404)
await request('/admin/shares/' + KEY_D + '/access', { cookie: admin, form: { public: ['0', '1'] } })
expect(store.getShare(KEY_D)?.public).toBe(true)
expect((await request('/share/' + KEY_D, { page: true })).res.status).toBe(200)
})
it('needs the admin session to change access', async () => {
await request('/admin/shares/' + KEY_D + '/access', { form: { public: '0' } })
expect(store.getShare(KEY_D)?.public).toBe(true)
})
})
+52
View File
@@ -1,3 +1,7 @@
import { mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { DatabaseSync } from 'node:sqlite'
import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { Store } from '../src/magic/store' import { Store } from '../src/magic/store'
import { hashToken, safeNextPath } from '../src/magic/tokens' import { hashToken, safeNextPath } from '../src/magic/tokens'
@@ -155,3 +159,51 @@ describe('safeNextPath', () => {
expect(safeNextPath(['/a'])).toBeUndefined() expect(safeNextPath(['/a'])).toBeUndefined()
}) })
}) })
describe('public shares', () => {
it('a share added by the admin requires sign-in unless marked public', () => {
expect(store.upsertShare({ key: 'k1', slug: null, title: 'A', password: null }, T0).public).toBe(false)
expect(store.upsertShare({ key: 'k2', slug: null, title: 'B', password: null, public: true }, T0).public).toBe(true)
})
it('saving a share again keeps its setting unless one is given', () => {
store.upsertShare({ key: 'k1', slug: null, title: 'A', password: null, public: true }, T0)
expect(store.upsertShare({ key: 'k1', slug: null, title: 'A2', password: null }, T1).public).toBe(true)
expect(store.upsertShare({ key: 'k1', slug: null, title: 'A2', password: null, public: false }, T1).public).toBe(false)
store.setSharePublic('k1', true)
expect(store.getShare('k1')?.public).toBe(true)
})
it('a discovered share starts public, and never overwrites one on file', () => {
expect(store.addDiscoveredShare({ key: 'k1', slug: 'one', title: 'Found' }, T0)).toMatchObject({ public: true, password: null })
store.upsertShare({ key: 'k2', slug: null, title: 'Mine', password: 'pw' }, T0)
expect(store.addDiscoveredShare({ key: 'k2', slug: null, title: 'Other' }, T1)).toMatchObject({ title: 'Mine', password: 'pw', public: false })
})
it('finds a share by key or slug, and lists the setting', () => {
store.addDiscoveredShare({ key: 'k1', slug: 'one', title: 'Found' }, T0)
expect(store.findShare('k1')?.key).toBe('k1')
expect(store.findShare('one')?.key).toBe('k1')
expect(store.findShare('nope')).toBeUndefined()
expect(store.listShares()[0].public).toBe(true)
})
it('upgrades a database from before the setting, keeping its shares sign-in only', () => {
const dir = mkdtempSync(join(tmpdir(), 'imp-store-'))
try {
const path = join(dir, 'magic.db')
const old = new DatabaseSync(path)
old.exec(`CREATE TABLE shares (key TEXT PRIMARY KEY, slug TEXT, title TEXT NOT NULL DEFAULT '', password TEXT,
last_scanned_at TEXT, created_at TEXT NOT NULL)`)
old.prepare('INSERT INTO shares (key, slug, title, password, created_at) VALUES (?, ?, ?, ?, ?)').run('old', null, 'Old', null, T0)
old.close()
const upgraded = new Store(path)
expect(upgraded.getShare('old')?.public).toBe(false)
upgraded.close()
// Opening it again doesn't try to add the column twice
new Store(path).close()
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
})