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:
@@ -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
@@ -73,6 +73,11 @@ function bodyString (req: Request, field: string, max = 300): string {
|
||||
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[] {
|
||||
const value = req.body?.[field]
|
||||
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,
|
||||
slug: result.link.slug || null,
|
||||
title: title(result.link),
|
||||
password: password ?? null
|
||||
password: password ?? null,
|
||||
public: checkboxOn(req, 'public')
|
||||
}, nowIso())
|
||||
// Record what's there now, so recipients are only told about later photos
|
||||
await scanShare(store, share, listShareAssets, nowIso()).catch(() => false)
|
||||
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) => {
|
||||
getStore().deleteShare(req.params.key)
|
||||
res.redirect(303, '/admin')
|
||||
|
||||
+57
-12
@@ -27,6 +27,8 @@ export interface ShareRecord {
|
||||
title: string
|
||||
/** Lets recipients and the background scanner open a password-protected share. */
|
||||
password: string | null
|
||||
/** Anyone with the Immich link may view it, not only signed-in recipients. */
|
||||
public: boolean
|
||||
lastScannedAt: string | null
|
||||
createdAt: string
|
||||
}
|
||||
@@ -57,7 +59,8 @@ const SCHEMA = `
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
password 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 (
|
||||
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,
|
||||
created_at AS createdAt, disabled`
|
||||
const SHARE_COLUMNS = 'key, slug, title, password, 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 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.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,
|
||||
author_name AS authorName, body, created_at AS createdAt`
|
||||
|
||||
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 {
|
||||
if (!row) return undefined
|
||||
return { ...(row as unknown as Recipient), disabled: !!row.disabled }
|
||||
@@ -130,6 +139,14 @@ export class Store {
|
||||
this.db.exec('PRAGMA busy_timeout = 5000')
|
||||
if (path !== ':memory:') this.db.exec('PRAGMA journal_mode = WAL')
|
||||
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 () {
|
||||
@@ -196,19 +213,47 @@ export class Store {
|
||||
|
||||
// ----- 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 (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (key) DO UPDATE SET slug = excluded.slug, title = excluded.title, password = excluded.password`)
|
||||
.run(input.key, input.slug, input.title, input.password, now)
|
||||
/**
|
||||
* Add or update a share from the admin console. A new share requires sign-in
|
||||
* unless `public` says otherwise; an existing one keeps its setting unless
|
||||
* `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)!
|
||||
}
|
||||
|
||||
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[] {
|
||||
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) {
|
||||
@@ -240,7 +285,7 @@ export class Store {
|
||||
listRecipientShares (recipientId: number): Array<ShareRecord & { grantedAt: string }> {
|
||||
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`)
|
||||
.all(recipientId) as unknown as Array<ShareRecord & { grantedAt: string }>
|
||||
.all(recipientId).map(row => toShare<ShareRecord & { grantedAt: string }>(row)!)
|
||||
}
|
||||
|
||||
countShareRecipients (key: string): number {
|
||||
@@ -253,10 +298,10 @@ export class Store {
|
||||
* the one access check every share-scoped route goes through.
|
||||
*/
|
||||
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
|
||||
WHERE rs.recipient_id = ? AND (s.key = ? OR s.slug = ?)`)
|
||||
.get(recipientId, keyOrSlug, keyOrSlug) as ShareRecord | undefined
|
||||
.get(recipientId, keyOrSlug, keyOrSlug))
|
||||
}
|
||||
|
||||
// ----- magic links ---------------------------------------------------------
|
||||
|
||||
+22
-3
@@ -24,9 +24,13 @@ const STYLE = `
|
||||
`
|
||||
|
||||
// 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) {
|
||||
var message = e.target.getAttribute('data-confirm')
|
||||
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 }) {
|
||||
@@ -187,19 +191,30 @@ export function AdminDashboard ({ shares, recipients, comments, emailEnabled, me
|
||||
|
||||
<section>
|
||||
<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 && (
|
||||
<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>
|
||||
{shares.map(({ share, recipients: count, assets }) => (
|
||||
<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>
|
||||
<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>{assets}</td>
|
||||
<td>
|
||||
<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>
|
||||
</form>
|
||||
</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>
|
||||
<input type="password" name="password" autocomplete="off"/>
|
||||
</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>
|
||||
</form>
|
||||
</details>
|
||||
|
||||
Reference in New Issue
Block a user