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:
@@ -45,9 +45,10 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
|
||||
const motionPhotos = !!getConfigOption('ipp.motionPhotos', true)
|
||||
const descriptionInCaption = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.caption', 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 comments = viewer
|
||||
const comments = viewer && res.req.grantedShare?.key === share.key
|
||||
? { base: '/share/comments/' + share.key, counts: getStore().countComments(share.key) }
|
||||
: undefined
|
||||
const sidebarHasContent = !!comments ||
|
||||
|
||||
@@ -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>
|
||||
|
||||
+22
-16
@@ -25,7 +25,8 @@ import { ImageSize } from './types'
|
||||
import { canDownload, uploadHealthcheck } from './share'
|
||||
import { ASSET_VERSION } from './version'
|
||||
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 { registerAdminRoutes } from './magic/admin'
|
||||
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
|
||||
* are registered.
|
||||
*
|
||||
* Every route that shows anything from Immich sits behind two gates: a
|
||||
* magic-link session (`requireRecipient`), and that recipient having been
|
||||
* given the specific share (`requireShareAccess`).
|
||||
* Every route that shows anything from Immich is gated. A share's gallery,
|
||||
* photos and downloads open for a recipient given that share, or for anyone
|
||||
* 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 {
|
||||
const app = express()
|
||||
@@ -89,14 +93,11 @@ export function createApp (): Express {
|
||||
registerSignInRoutes(app)
|
||||
registerAdminRoutes(app)
|
||||
|
||||
// ----- everything below needs a magic-link session --------------------------
|
||||
app.use(requireRecipient)
|
||||
registerRecipientRoutes(app)
|
||||
|
||||
// ----- shares: public ones for anyone, the rest for their recipients --------
|
||||
/*
|
||||
[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)
|
||||
|
||||
if (slugLinksDisabled(keyType)) {
|
||||
@@ -113,13 +114,14 @@ export function createApp (): Express {
|
||||
}))
|
||||
|
||||
/*
|
||||
[ROUTE] Password unlock from the password page. Only reachable for a
|
||||
share without a stored password, and only for a recipient of that share.
|
||||
[ROUTE] Password unlock from the password page, for a visitor who may
|
||||
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) => {
|
||||
const key = req.body?.key
|
||||
if (typeof key !== 'string' || !isKey(key) || !getStore().grantedShare(req.recipient!.id, key)) {
|
||||
deny(req, res, 'Unlock for a share the recipient was not given')
|
||||
if (typeof key !== 'string' || !isKey(key) || !canViewShare(req, key)) {
|
||||
deny(req, res, 'Unlock for a share this visitor may not view')
|
||||
return
|
||||
}
|
||||
next()
|
||||
@@ -131,7 +133,7 @@ export function createApp (): Express {
|
||||
Validates each ID against share.assets so the request can't pull anything
|
||||
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)
|
||||
let requestedIds: unknown
|
||||
try {
|
||||
@@ -177,7 +179,7 @@ export function createApp (): Express {
|
||||
/*
|
||||
[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)
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
const resolved = await resolveSharedAsset(req, getKeyTypeFromShare(req.params.shareType))
|
||||
@@ -240,6 +242,10 @@ export function createApp (): Express {
|
||||
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
|
||||
unknown path gets the same policy instead of Express's own HTML error page.
|
||||
|
||||
@@ -18,6 +18,9 @@ const KEY_A = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
const KEY_B = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
|
||||
const KEY_C = 'ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc'
|
||||
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_2 = '22222222-2222-4222-8222-222222222222'
|
||||
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_B]: link(KEY_B, 'Wedding', null, [ASSET_B]),
|
||||
[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 IMMICH_TOKEN = 'immich-token-for-p'
|
||||
@@ -459,3 +464,68 @@ describe('admin console', () => {
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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 { Store } from '../src/magic/store'
|
||||
import { hashToken, safeNextPath } from '../src/magic/tokens'
|
||||
@@ -155,3 +159,51 @@ describe('safeNextPath', () => {
|
||||
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 })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user