Gate shares behind magic-link sessions, add comments and new-photo email digests
This commit is contained in:
@@ -0,0 +1,324 @@
|
||||
import crypto from 'crypto'
|
||||
import { Express, NextFunction, Request, Response } from 'express-serve-static-core'
|
||||
import {
|
||||
addNoStoreHeaders,
|
||||
Asset,
|
||||
asyncHandler,
|
||||
authHeaders,
|
||||
fetchSharedLink,
|
||||
isId,
|
||||
isKey,
|
||||
KeyType,
|
||||
log,
|
||||
renderPage,
|
||||
title,
|
||||
TtlLruCache
|
||||
} from '@ipp/core'
|
||||
import { h } from 'preact'
|
||||
import { assetFetchUrl } from '../immich'
|
||||
import { getStore, isFrequency, Recipient } from './store'
|
||||
import { inviteMail, mailConfigured, publicBaseUrl, sendMail } from './mailer'
|
||||
import { listShareAssets, runNotificationCycle, scanShare } from './digest'
|
||||
import { nowIso, readCookie, secureCookies } from './session'
|
||||
import { AdminDashboard, AdminLogin, AdminRecipient } from './views'
|
||||
|
||||
const ADMIN_COOKIE = 'imp_admin'
|
||||
const ADMIN_SESSION_MS = 30 * 24 * 60 * 60_000
|
||||
const MAX_LOGIN_FAILURES = 10
|
||||
const loginFailures = new TtlLruCache<number>({ ttlMs: 15 * 60_000, max: 1000 })
|
||||
|
||||
function adminPassword (): string {
|
||||
return process.env.ADMIN_PASSWORD || ''
|
||||
}
|
||||
|
||||
// Derived from the password, so changing ADMIN_PASSWORD signs every admin out
|
||||
function signingKey (): Buffer {
|
||||
return crypto.createHash('sha256').update('immich-magic-proxy admin\0' + adminPassword()).digest()
|
||||
}
|
||||
|
||||
function sign (expires: number): string {
|
||||
return expires + '.' + crypto.createHmac('sha256', signingKey()).update(String(expires)).digest('base64url')
|
||||
}
|
||||
|
||||
function safeEqual (a: string, b: string): boolean {
|
||||
const left = Buffer.from(a)
|
||||
const right = Buffer.from(b)
|
||||
return left.length === right.length && crypto.timingSafeEqual(left, right)
|
||||
}
|
||||
|
||||
function isAdmin (req: Request): boolean {
|
||||
const cookie = readCookie(req, ADMIN_COOKIE)
|
||||
if (!cookie || !adminPassword()) return false
|
||||
const expires = Number(cookie.split('.')[0])
|
||||
return Number.isFinite(expires) && expires > Date.now() && safeEqual(cookie, sign(expires))
|
||||
}
|
||||
|
||||
function requireAdmin (req: Request, res: Response, next: NextFunction) {
|
||||
if (isAdmin(req)) {
|
||||
next()
|
||||
} else if (req.method === 'GET') {
|
||||
res.redirect(303, '/admin')
|
||||
} else {
|
||||
res.status(403).send()
|
||||
}
|
||||
}
|
||||
|
||||
/** Absolute base for links an admin hands out. */
|
||||
function linkBase (req: Request): string {
|
||||
return publicBaseUrl() || (req.protocol + '://' + req.get('host'))
|
||||
}
|
||||
|
||||
function bodyString (req: Request, field: string, max = 300): string {
|
||||
const value = req.body?.[field]
|
||||
return typeof value === 'string' ? value.trim().slice(0, max) : ''
|
||||
}
|
||||
|
||||
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')
|
||||
}
|
||||
|
||||
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
/** Pull a share key or slug out of a pasted Immich / IPP link, or a bare key. */
|
||||
export function parseShareInput (input: string): { key: string, keyType: KeyType } | undefined {
|
||||
let path = input.trim()
|
||||
if (/^https?:\/\//i.test(path)) {
|
||||
try {
|
||||
path = new URL(path).pathname
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
const slug = path.match(/(?:^|\/)s\/([\w-]+)\/?$/)
|
||||
if (slug) return { key: slug[1], keyType: KeyType.slug }
|
||||
const shared = path.match(/(?:^|\/)share\/(?:(?:photo|video|meta)\/)?([\w-]+)/)
|
||||
if (shared) return { key: shared[1], keyType: KeyType.key }
|
||||
return isKey(path) ? { key: path, keyType: KeyType.key } : undefined
|
||||
}
|
||||
|
||||
type Message = { kind: 'ok' | 'error', text: string }
|
||||
|
||||
function renderDashboard (res: Response, message?: Message) {
|
||||
const store = getStore()
|
||||
const shares = store.listShares()
|
||||
res.send(renderPage(h(AdminDashboard, {
|
||||
shares: shares.map(share => ({ share, recipients: store.countShareRecipients(share.key), assets: store.countKnownAssets(share.key) })),
|
||||
recipients: store.listRecipients().map(recipient => ({
|
||||
recipient,
|
||||
shares: store.listRecipientShares(recipient.id),
|
||||
sessions: store.countSessions(recipient.id)
|
||||
})),
|
||||
comments: store.recentComments(50),
|
||||
emailEnabled: mailConfigured() && !!publicBaseUrl(),
|
||||
message
|
||||
})))
|
||||
}
|
||||
|
||||
function renderRecipient (res: Response, recipient: Recipient, extra: { newLink?: string, message?: Message } = {}) {
|
||||
const store = getStore()
|
||||
res.send(renderPage(h(AdminRecipient, {
|
||||
recipient,
|
||||
shares: store.listShares(),
|
||||
granted: store.listRecipientShares(recipient.id).map(share => share.key),
|
||||
sessions: store.countSessions(recipient.id),
|
||||
activeLinks: store.countMagicLinks(recipient.id, nowIso()),
|
||||
emailEnabled: mailConfigured() && !!publicBaseUrl(),
|
||||
...extra
|
||||
})))
|
||||
}
|
||||
|
||||
/** Create a non-expiring invitation link, and optionally email it. */
|
||||
async function issueInvite (req: Request, recipient: Recipient, send: boolean): Promise<{ link: string, message?: Message }> {
|
||||
const store = getStore()
|
||||
const token = store.createMagicLink(recipient.id, { purpose: 'invite', expiresAt: null }, nowIso())
|
||||
const link = linkBase(req) + '/m/' + token
|
||||
if (!send) return { link }
|
||||
try {
|
||||
await sendMail(inviteMail({
|
||||
to: recipient.email,
|
||||
name: recipient.name,
|
||||
link,
|
||||
albums: store.listRecipientShares(recipient.id).map(share => share.title)
|
||||
}))
|
||||
return { link, message: { kind: 'ok', text: 'Invitation emailed to ' + recipient.email + '.' } }
|
||||
} catch (e) {
|
||||
log.error('Invitation email failed: ' + (e instanceof Error ? e.message : String(e)))
|
||||
return { link, message: { kind: 'error', text: 'The email could not be sent; copy the link below instead.' } }
|
||||
}
|
||||
}
|
||||
|
||||
function recipientParam (req: Request, res: Response): Recipient | undefined {
|
||||
const recipient = /^\d+$/.test(req.params.id) ? getStore().getRecipient(Number(req.params.id)) : undefined
|
||||
if (!recipient) res.redirect(303, '/admin')
|
||||
return recipient
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin console at /admin. Off unless ADMIN_PASSWORD is set, in which case
|
||||
* /admin falls through to the visitor gate like any other path.
|
||||
*/
|
||||
export function registerAdminRoutes (app: Express) {
|
||||
if (!adminPassword()) return
|
||||
|
||||
app.use('/admin', (_req, res, next) => {
|
||||
addNoStoreHeaders(res)
|
||||
res.set('X-Frame-Options', 'DENY')
|
||||
next()
|
||||
})
|
||||
|
||||
app.get('/admin', (req, res) => {
|
||||
if (isAdmin(req)) renderDashboard(res)
|
||||
else res.send(renderPage(h(AdminLogin, {})))
|
||||
})
|
||||
|
||||
app.post('/admin/login', (req, res) => {
|
||||
const ip = req.ip || ''
|
||||
const failures = loginFailures.get(ip) || 0
|
||||
const password = bodyString(req, 'password', 1000)
|
||||
if (failures >= MAX_LOGIN_FAILURES || !safeEqual(password, adminPassword())) {
|
||||
loginFailures.set(ip, failures + 1)
|
||||
log.warn('Failed admin sign-in from ' + ip)
|
||||
res.status(401).send(renderPage(h(AdminLogin, { failed: true })))
|
||||
return
|
||||
}
|
||||
loginFailures.delete(ip)
|
||||
res.cookie(ADMIN_COOKIE, sign(Date.now() + ADMIN_SESSION_MS), {
|
||||
httpOnly: true, sameSite: 'strict', secure: secureCookies(), path: '/admin', maxAge: ADMIN_SESSION_MS
|
||||
})
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.post('/admin/logout', (_req, res) => {
|
||||
res.clearCookie(ADMIN_COOKIE, { path: '/admin' })
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.use('/admin', requireAdmin)
|
||||
|
||||
app.post('/admin/shares', asyncHandler(async (req, res) => {
|
||||
const parsed = parseShareInput(bodyString(req, 'link', 2000))
|
||||
const password = bodyString(req, 'password', 1000) || undefined
|
||||
if (!parsed) {
|
||||
renderDashboard(res, { kind: 'error', text: 'That doesn\'t look like an Immich share link.' })
|
||||
return
|
||||
}
|
||||
const result = await fetchSharedLink(parsed.key, parsed.keyType, password)
|
||||
if (result.passwordRequired) {
|
||||
renderDashboard(res, { kind: 'error', text: password ? 'Immich rejected that password.' : 'That share has a password: enter it too.' })
|
||||
return
|
||||
}
|
||||
if (!result.valid || !result.link) {
|
||||
renderDashboard(res, { kind: 'error', text: 'Immich didn\'t accept that link. Check it hasn\'t expired.' })
|
||||
return
|
||||
}
|
||||
const store = getStore()
|
||||
const share = store.upsertShare({
|
||||
key: result.link.key,
|
||||
slug: result.link.slug || null,
|
||||
title: title(result.link),
|
||||
password: password ?? null
|
||||
}, 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/delete', (req, res) => {
|
||||
getStore().deleteShare(req.params.key)
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.post('/admin/recipients', asyncHandler(async (req, res) => {
|
||||
const store = getStore()
|
||||
const name = bodyString(req, 'name', 100)
|
||||
const email = bodyString(req, 'email', 254)
|
||||
const frequency = bodyString(req, 'frequency')
|
||||
if (!name || !EMAIL_PATTERN.test(email) || !isFrequency(frequency)) {
|
||||
renderDashboard(res, { kind: 'error', text: 'Enter a name and a valid email address.' })
|
||||
return
|
||||
}
|
||||
if (store.getRecipientByEmail(email)) {
|
||||
renderDashboard(res, { kind: 'error', text: email + ' is already a recipient.' })
|
||||
return
|
||||
}
|
||||
const recipient = store.createRecipient({ name, email, frequency }, nowIso())
|
||||
store.setRecipientShares(recipient.id, bodyList(req, 'shares'), nowIso())
|
||||
const invite = await issueInvite(req, recipient, bodyString(req, 'sendInvite') === '1' && mailConfigured())
|
||||
renderRecipient(res, recipient, { newLink: invite.link, message: invite.message })
|
||||
}))
|
||||
|
||||
app.get('/admin/recipients/:id', (req, res) => {
|
||||
const recipient = recipientParam(req, res)
|
||||
if (recipient) renderRecipient(res, recipient)
|
||||
})
|
||||
|
||||
app.post('/admin/recipients/:id', (req, res) => {
|
||||
const store = getStore()
|
||||
const recipient = recipientParam(req, res)
|
||||
if (!recipient) return
|
||||
const name = bodyString(req, 'name', 100)
|
||||
const email = bodyString(req, 'email', 254)
|
||||
const frequency = bodyString(req, 'frequency')
|
||||
const existing = store.getRecipientByEmail(email)
|
||||
if (!name || !EMAIL_PATTERN.test(email) || !isFrequency(frequency) || (existing && existing.id !== recipient.id)) {
|
||||
renderRecipient(res, recipient, { message: { kind: 'error', text: 'Check the name and email (each email can only belong to one recipient).' } })
|
||||
return
|
||||
}
|
||||
store.updateRecipient(recipient.id, { name, email, disabled: bodyString(req, 'disabled') === '1' })
|
||||
store.setFrequency(recipient.id, frequency, nowIso())
|
||||
store.setRecipientShares(recipient.id, bodyList(req, 'shares'), nowIso())
|
||||
renderRecipient(res, store.getRecipient(recipient.id)!, { message: { kind: 'ok', text: 'Saved.' } })
|
||||
})
|
||||
|
||||
app.post('/admin/recipients/:id/link', asyncHandler(async (req, res) => {
|
||||
const recipient = recipientParam(req, res)
|
||||
if (!recipient) return
|
||||
const invite = await issueInvite(req, recipient, bodyString(req, 'send') === '1')
|
||||
renderRecipient(res, recipient, { newLink: invite.link, message: invite.message })
|
||||
}))
|
||||
|
||||
app.post('/admin/recipients/:id/revoke', (req, res) => {
|
||||
const recipient = recipientParam(req, res)
|
||||
if (!recipient) return
|
||||
getStore().revokeAccess(recipient.id)
|
||||
renderRecipient(res, recipient, { message: { kind: 'ok', text: 'Signed out everywhere; every link they had no longer works.' } })
|
||||
})
|
||||
|
||||
app.post('/admin/recipients/:id/delete', (req, res) => {
|
||||
const recipient = recipientParam(req, res)
|
||||
if (!recipient) return
|
||||
getStore().deleteRecipient(recipient.id)
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.post('/admin/comments/:id/delete', (req, res) => {
|
||||
if (/^\d+$/.test(req.params.id)) getStore().deleteComment(Number(req.params.id))
|
||||
res.redirect(303, '/admin')
|
||||
})
|
||||
|
||||
app.post('/admin/notify', asyncHandler(async (_req, res) => {
|
||||
await runNotificationCycle()
|
||||
renderDashboard(res, { kind: 'ok', text: 'Checked every album for new photos and sent any notification emails that were due.' })
|
||||
}))
|
||||
|
||||
// Thumbnail for the comment moderation list
|
||||
app.get('/admin/thumb/:key/:id', asyncHandler(async (req, res) => {
|
||||
const share = getStore().getShare(req.params.key)
|
||||
if (!share || !isId(req.params.id)) {
|
||||
res.status(404).send()
|
||||
return
|
||||
}
|
||||
const asset = { id: req.params.id, key: share.key, keyType: KeyType.key } as Asset
|
||||
const upstream = await fetch(assetFetchUrl(asset, '/thumbnail', 'thumbnail'), {
|
||||
headers: await authHeaders(KeyType.key, share.key, share.password ?? undefined)
|
||||
})
|
||||
if (!upstream.ok || !upstream.body) {
|
||||
res.status(404).send()
|
||||
return
|
||||
}
|
||||
res.set('Content-Type', upstream.headers.get('Content-Type') || 'image/jpeg')
|
||||
res.set('Cache-Control', 'private, max-age=3600')
|
||||
res.send(Buffer.from(await upstream.arrayBuffer()))
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import dayjs from 'dayjs'
|
||||
import { KeyType, log } from '@ipp/core'
|
||||
import { getShareByKey } from '../immich'
|
||||
import { Frequency, getStore, Recipient, ShareRecord, Store } from './store'
|
||||
import { digestMail, DigestSection, mailConfigured, MailSender, publicBaseUrl, sendMail } from './mailer'
|
||||
|
||||
/** Asset ids currently in a share, or null when Immich couldn't be read. */
|
||||
export type AssetLister = (share: ShareRecord) => Promise<string[] | null>
|
||||
|
||||
const DIGEST_LINK_DAYS = 30
|
||||
|
||||
export const listShareAssets: AssetLister = async (share) => {
|
||||
const result = await getShareByKey(share.key, share.password ?? undefined, KeyType.key)
|
||||
if (!result.valid || !result.link) return null
|
||||
return result.link.assets.map(asset => asset.id)
|
||||
}
|
||||
|
||||
/** Hour of day (server local time, set with TZ) that digests go out. */
|
||||
export function digestHour (): number {
|
||||
const hour = Number(process.env.DIGEST_HOUR ?? 8)
|
||||
return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : 8
|
||||
}
|
||||
|
||||
/**
|
||||
* When a recipient's next digest is due: the next daily / weekly / monthly
|
||||
* boundary after their window opened, at the digest hour. Anchoring to a
|
||||
* calendar day keeps the send time from drifting with the scan interval.
|
||||
*/
|
||||
export function nextDigestDue (frequency: Frequency, windowStart: string | null, hour = digestHour()): Date | undefined {
|
||||
if (frequency === 'off' || !windowStart) return undefined
|
||||
const day = dayjs(windowStart).startOf('day')
|
||||
const next = frequency === 'daily'
|
||||
? day.add(1, 'day')
|
||||
: frequency === 'weekly'
|
||||
? day.add(7, 'day')
|
||||
: day.add(1, 'month')
|
||||
return next.hour(hour).toDate()
|
||||
}
|
||||
|
||||
/**
|
||||
* Record each share's assets. The first scan of a share is its baseline:
|
||||
* those assets are dated to when the share was added, so nobody is told
|
||||
* about photos that were there before they were invited.
|
||||
*/
|
||||
export async function scanShares (store: Store, listAssets: AssetLister, now: string): Promise<Map<string, Set<string>>> {
|
||||
const current = new Map<string, Set<string>>()
|
||||
for (const share of store.listShares()) {
|
||||
const ids = await scanShare(store, share, listAssets, now)
|
||||
if (ids) current.set(share.key, ids)
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
/** Scan one share. Returns its current asset ids, or null if Immich couldn't be read. */
|
||||
export async function scanShare (store: Store, share: ShareRecord, listAssets: AssetLister, now: string): Promise<Set<string> | null> {
|
||||
let ids: string[] | null = null
|
||||
try {
|
||||
ids = await listAssets(share)
|
||||
} catch (e) {
|
||||
log.warn('Could not list assets of share ' + share.key + ': ' + (e instanceof Error ? e.message : String(e)))
|
||||
}
|
||||
if (!ids) {
|
||||
log.warn('Skipping notification scan for share "' + share.title + '": Immich did not return it')
|
||||
return null
|
||||
}
|
||||
const known = store.knownAssetIds(share.key)
|
||||
store.addAssets(share.key, ids.filter(id => !known.has(id)), share.lastScannedAt ? now : share.createdAt)
|
||||
store.setShareScanned(share.key, now)
|
||||
return new Set(ids)
|
||||
}
|
||||
|
||||
export interface DigestDeps {
|
||||
store: Store
|
||||
send: MailSender
|
||||
baseUrl: string
|
||||
now: Date
|
||||
hour?: number
|
||||
}
|
||||
|
||||
/** Send every digest that is due. Returns how many emails went out. */
|
||||
export async function sendDueDigests (deps: DigestDeps, current: Map<string, Set<string>>): Promise<number> {
|
||||
const { store, now } = deps
|
||||
const nowIso = now.toISOString()
|
||||
let sent = 0
|
||||
for (const recipient of store.listRecipients()) {
|
||||
if (recipient.disabled) continue
|
||||
const due = nextDigestDue(recipient.frequency, recipient.lastDigestAt, deps.hour)
|
||||
if (!due || now < due) continue
|
||||
try {
|
||||
if (await sendDigest(deps, recipient, current)) sent++
|
||||
store.setDigestAt(recipient.id, nowIso)
|
||||
} catch (e) {
|
||||
// The window stays open, so the next run retries with the same photos
|
||||
log.error('Digest to ' + recipient.email + ' failed: ' + (e instanceof Error ? e.message : String(e)))
|
||||
}
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
async function sendDigest (deps: DigestDeps, recipient: Recipient, current: Map<string, Set<string>>): Promise<boolean> {
|
||||
const { store, now } = deps
|
||||
const nowIso = now.toISOString()
|
||||
const pending: Array<{ share: ShareRecord, count: number }> = []
|
||||
for (const share of store.listRecipientShares(recipient.id)) {
|
||||
const present = current.get(share.key)
|
||||
// Nothing from before they had the album, and only photos still in it
|
||||
// when this run could check
|
||||
const after = share.grantedAt > recipient.lastDigestAt! ? share.grantedAt : recipient.lastDigestAt!
|
||||
const ids = store.assetsSeenBetween(share.key, after, nowIso)
|
||||
.filter(id => !present || present.has(id))
|
||||
if (ids.length) pending.push({ share, count: ids.length })
|
||||
}
|
||||
if (!pending.length) return false
|
||||
|
||||
// One sign-in link per email, so the links work on a device with no session
|
||||
const token = store.createMagicLink(recipient.id, {
|
||||
purpose: 'digest',
|
||||
expiresAt: dayjs(now).add(DIGEST_LINK_DAYS, 'day').toISOString()
|
||||
}, nowIso)
|
||||
const link = (path: string) => deps.baseUrl + '/m/' + token + '?next=' + encodeURIComponent(path)
|
||||
const sections: DigestSection[] = pending.map(({ share, count }) => ({
|
||||
title: share.title || 'Shared album',
|
||||
count,
|
||||
link: link('/share/' + share.key)
|
||||
}))
|
||||
await deps.send(digestMail({ to: recipient.email, name: recipient.name, sections, settingsLink: link('/me') }))
|
||||
return true
|
||||
}
|
||||
|
||||
let running = false
|
||||
let warnedNoMail = false
|
||||
|
||||
/** One scan-and-notify pass over every share and recipient. */
|
||||
export async function runNotificationCycle (now = new Date()) {
|
||||
if (running) return
|
||||
running = true
|
||||
try {
|
||||
const store = getStore()
|
||||
store.pruneExpiredLinks(now.toISOString())
|
||||
const current = await scanShares(store, listShareAssets, now.toISOString())
|
||||
const baseUrl = publicBaseUrl()
|
||||
if (!mailConfigured() || !baseUrl) {
|
||||
if (!warnedNoMail) {
|
||||
warnedNoMail = true
|
||||
log.warn('Photo notification emails are off: set SMTP_URL (or SMTP_HOST) and PUBLIC_BASE_URL to send them')
|
||||
}
|
||||
return
|
||||
}
|
||||
const sent = await sendDueDigests({ store, send: sendMail, baseUrl, now }, current)
|
||||
if (sent) log('Sent ' + sent + ' photo notification email' + (sent === 1 ? '' : 's'))
|
||||
} finally {
|
||||
running = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Scan for new photos every NOTIFY_INTERVAL_MINUTES (default 60), starting a minute after boot. */
|
||||
export function startNotificationScheduler () {
|
||||
const minutes = Math.max(1, Number(process.env.NOTIFY_INTERVAL_MINUTES) || 60)
|
||||
const tick = () => { runNotificationCycle().catch(e => log.error('Notification run failed: ' + e)) }
|
||||
setTimeout(tick, 60_000).unref()
|
||||
setInterval(tick, minutes * 60_000).unref()
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import nodemailer, { Transporter } from 'nodemailer'
|
||||
import { log } from '@ipp/core'
|
||||
|
||||
export interface Mail {
|
||||
to: string
|
||||
subject: string
|
||||
text: string
|
||||
html: string
|
||||
}
|
||||
|
||||
export type MailSender = (mail: Mail) => Promise<void>
|
||||
|
||||
/** True when SMTP_URL or SMTP_HOST is set. */
|
||||
export function mailConfigured (): boolean {
|
||||
return !!(process.env.SMTP_URL || process.env.SMTP_HOST)
|
||||
}
|
||||
|
||||
let transport: Transporter | undefined
|
||||
|
||||
function createTransport (): Transporter {
|
||||
if (process.env.SMTP_URL) return nodemailer.createTransport(process.env.SMTP_URL)
|
||||
const port = Number(process.env.SMTP_PORT) || 587
|
||||
return nodemailer.createTransport({
|
||||
host: process.env.SMTP_HOST,
|
||||
port,
|
||||
secure: process.env.SMTP_SECURE ? process.env.SMTP_SECURE === 'true' : port === 465,
|
||||
auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS || '' } : undefined
|
||||
})
|
||||
}
|
||||
|
||||
const smtpSender: MailSender = async (mail) => {
|
||||
if (!mailConfigured()) throw new Error('Email is not configured: set SMTP_URL or SMTP_HOST')
|
||||
transport ??= createTransport()
|
||||
await transport.sendMail({
|
||||
from: process.env.MAIL_FROM || process.env.SMTP_USER,
|
||||
to: mail.to,
|
||||
subject: mail.subject,
|
||||
text: mail.text,
|
||||
html: mail.html
|
||||
})
|
||||
log('Sent email "' + mail.subject + '" to ' + mail.to)
|
||||
}
|
||||
|
||||
let sender: MailSender = smtpSender
|
||||
|
||||
export function sendMail (mail: Mail): Promise<void> {
|
||||
return sender(mail)
|
||||
}
|
||||
|
||||
/** Replace how mail is sent, for tests. Pass undefined to restore SMTP. */
|
||||
export function setMailSender (next: MailSender | undefined) {
|
||||
sender = next ?? smtpSender
|
||||
}
|
||||
|
||||
export function siteName (): string {
|
||||
return process.env.SITE_NAME || 'Shared photos'
|
||||
}
|
||||
|
||||
/** The public origin for links in emails, from PUBLIC_BASE_URL. */
|
||||
export function publicBaseUrl (): string | undefined {
|
||||
const base = (process.env.PUBLIC_BASE_URL || '').trim().replace(/\/+$/, '')
|
||||
return /^https?:\/\//i.test(base) ? base : undefined
|
||||
}
|
||||
|
||||
function escapeHtml (value: string): string {
|
||||
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
}
|
||||
|
||||
function htmlDocument (body: string): string {
|
||||
return '<!DOCTYPE html><html><body style="font-family:-apple-system,Segoe UI,Roboto,sans-serif;line-height:1.5;color:#222;max-width:560px;margin:0 auto;padding:16px">' +
|
||||
body + '</body></html>'
|
||||
}
|
||||
|
||||
const button = (url: string, label: string) =>
|
||||
`<p><a href="${escapeHtml(url)}" style="display:inline-block;background:#4250af;color:#fff;padding:10px 18px;border-radius:6px;text-decoration:none">${escapeHtml(label)}</a></p>`
|
||||
|
||||
export function inviteMail (input: { to: string, name: string, link: string, albums: string[] }): Mail {
|
||||
const site = siteName()
|
||||
const albumList = input.albums.length ? input.albums : ['your albums']
|
||||
return {
|
||||
to: input.to,
|
||||
subject: `${site}: you've been invited to view photos`,
|
||||
text: `Hi ${input.name},\n\nYou've been given access to ${albumList.join(', ')}.\n\n` +
|
||||
`Open your personal link:\n${input.link}\n\n` +
|
||||
'After opening it once, you can bookmark the page; this browser stays signed in. ' +
|
||||
'Please don\'t forward this email: anyone with the link can see the photos.\n',
|
||||
html: htmlDocument(
|
||||
`<p>Hi ${escapeHtml(input.name)},</p>` +
|
||||
`<p>You've been given access to <strong>${albumList.map(escapeHtml).join(', ')}</strong>.</p>` +
|
||||
button(input.link, 'View photos') +
|
||||
'<p style="color:#666;font-size:14px">After opening it once, you can bookmark the page; this browser stays signed in. ' +
|
||||
'Please don\'t forward this email: anyone with the link can see the photos.</p>'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export function signInMail (input: { to: string, name: string, link: string }): Mail {
|
||||
const site = siteName()
|
||||
return {
|
||||
to: input.to,
|
||||
subject: `${site}: your sign-in link`,
|
||||
text: `Hi ${input.name},\n\nHere is your sign-in link:\n${input.link}\n\nIt works for 7 days. If you didn't ask for it, you can ignore this email.\n`,
|
||||
html: htmlDocument(
|
||||
`<p>Hi ${escapeHtml(input.name)},</p>` +
|
||||
button(input.link, 'Sign in') +
|
||||
'<p style="color:#666;font-size:14px">This link works for 7 days. If you didn\'t ask for it, you can ignore this email.</p>'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export interface DigestSection {
|
||||
title: string
|
||||
count: number
|
||||
link: string
|
||||
}
|
||||
|
||||
export function digestMail (input: { to: string, name: string, sections: DigestSection[], settingsLink: string }): Mail {
|
||||
const total = input.sections.reduce((sum, s) => sum + s.count, 0)
|
||||
const plural = (n: number) => n === 1 ? '1 new photo' : n + ' new photos'
|
||||
return {
|
||||
to: input.to,
|
||||
subject: `${siteName()}: ${plural(total)}`,
|
||||
text: `Hi ${input.name},\n\n` +
|
||||
input.sections.map(s => `${plural(s.count)} in ${s.title}:\n${s.link}`).join('\n\n') +
|
||||
`\n\nChange how often you get these emails: ${input.settingsLink}\n`,
|
||||
html: htmlDocument(
|
||||
`<p>Hi ${escapeHtml(input.name)},</p>` +
|
||||
input.sections.map(s =>
|
||||
`<p><strong>${escapeHtml(plural(s.count))}</strong> in ${escapeHtml(s.title)}</p>` + button(s.link, 'View ' + s.title)
|
||||
).join('') +
|
||||
`<p style="color:#666;font-size:14px"><a href="${escapeHtml(input.settingsLink)}">Change how often you get these emails</a></p>`
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { Express, Request, Response } from 'express-serve-static-core'
|
||||
import dayjs from 'dayjs'
|
||||
import { addNoStoreHeaders, asyncHandler, decodeCookie, KeyType, log, renderPage, respondToInvalidRequest, TtlLruCache } from '@ipp/core'
|
||||
import { h } from 'preact'
|
||||
import { resolveSharedAsset } from '../resolve'
|
||||
import { CommentRecord, getStore, isFrequency, Recipient } from './store'
|
||||
import { endSession, nowIso, requireShareAccess, startSession } from './session'
|
||||
import { isTokenShaped, safeNextPath } from './tokens'
|
||||
import { mailConfigured, publicBaseUrl, sendMail, signInMail } from './mailer'
|
||||
import { AccessDenied, LinkRequested, RecipientHome } from './views'
|
||||
import type { CommentView } from '../shared/types'
|
||||
|
||||
const SIGN_IN_LINK_DAYS = 7
|
||||
const LINK_REQUEST_INTERVAL_MS = 5 * 60_000
|
||||
const MAX_COMMENT_LENGTH = 2000
|
||||
const COMMENTS_PER_WINDOW = 30
|
||||
const linkRequestsByIp = new TtlLruCache<number>({ ttlMs: 60 * 60_000, max: 5000 })
|
||||
const commentsByRecipient = new TtlLruCache<number>({ ttlMs: 10 * 60_000, max: 5000 })
|
||||
|
||||
/** Routes anyone can reach: following a magic link, and asking for a new one. */
|
||||
export function registerSignInRoutes (app: Express) {
|
||||
app.get('/m/:token', (req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
// Keep the token out of any Referer sent by the page we redirect to
|
||||
res.set('Referrer-Policy', 'no-referrer')
|
||||
const store = getStore()
|
||||
const recipient = isTokenShaped(req.params.token) ? store.useMagicLink(req.params.token, nowIso()) : undefined
|
||||
if (!recipient) {
|
||||
log('Invalid or expired magic link')
|
||||
res.status(401).send(renderPage(h(AccessDenied, { signedIn: !!req.recipient, invalidLink: true })))
|
||||
return
|
||||
}
|
||||
// Reuse this browser's session when it already belongs to the recipient
|
||||
if (req.recipient?.id !== recipient.id) {
|
||||
if (req.recipient) endSession(req, res)
|
||||
startSession(res, recipient)
|
||||
}
|
||||
const shares = store.listRecipientShares(recipient.id)
|
||||
const next = safeNextPath(req.query.next) ?? (shares.length === 1 ? '/share/' + shares[0].key : '/me')
|
||||
res.redirect(303, next)
|
||||
})
|
||||
|
||||
app.post('/access', (req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
const email = typeof req.body?.email === 'string' ? req.body.email.trim().slice(0, 254) : ''
|
||||
const ip = req.ip || ''
|
||||
const requests = (linkRequestsByIp.get(ip) || 0) + 1
|
||||
linkRequestsByIp.set(ip, requests)
|
||||
// The same answer whether or not the address is known, and sent before
|
||||
// any email goes out, so neither content nor timing reveals who's invited
|
||||
res.send(renderPage(h(LinkRequested, {})))
|
||||
if (requests > 10 || !email) return
|
||||
emailSignInLink(email, req).catch(() => {})
|
||||
})
|
||||
}
|
||||
|
||||
async function emailSignInLink (email: string, req: Request) {
|
||||
const store = getStore()
|
||||
const recipient = store.getRecipientByEmail(email)
|
||||
if (!recipient || recipient.disabled || !mailConfigured()) return
|
||||
const now = new Date()
|
||||
if (!store.allowLinkRequest(recipient.email, now.toISOString(), new Date(now.getTime() - LINK_REQUEST_INTERVAL_MS).toISOString())) return
|
||||
const token = store.createMagicLink(recipient.id, {
|
||||
purpose: 'sign-in',
|
||||
expiresAt: dayjs(now).add(SIGN_IN_LINK_DAYS, 'day').toISOString()
|
||||
}, now.toISOString())
|
||||
const base = publicBaseUrl() || (req.protocol + '://' + req.get('host'))
|
||||
try {
|
||||
await sendMail(signInMail({ to: recipient.email, name: recipient.name, link: base + '/m/' + token }))
|
||||
} catch (e) {
|
||||
log.error('Sign-in email to ' + recipient.email + ' failed: ' + (e instanceof Error ? e.message : String(e)))
|
||||
}
|
||||
}
|
||||
|
||||
function commentView (comment: CommentRecord, viewer: Recipient): CommentView {
|
||||
return {
|
||||
id: comment.id,
|
||||
author: comment.authorName,
|
||||
body: comment.body,
|
||||
createdAt: comment.createdAt,
|
||||
mine: comment.recipientId === viewer.id
|
||||
}
|
||||
}
|
||||
|
||||
/** Routes behind the recipient gate. */
|
||||
export function registerRecipientRoutes (app: Express) {
|
||||
const renderHome = (req: Request, res: Response, saved = false) => {
|
||||
addNoStoreHeaders(res)
|
||||
const recipient = getStore().getRecipient(req.recipient!.id)!
|
||||
res.send(renderPage(h(RecipientHome, {
|
||||
recipient,
|
||||
shares: getStore().listRecipientShares(recipient.id),
|
||||
saved,
|
||||
emailEnabled: mailConfigured() && !!publicBaseUrl()
|
||||
})))
|
||||
}
|
||||
|
||||
app.get('/me', (req, res) => renderHome(req, res))
|
||||
|
||||
app.post('/me/notifications', (req, res) => {
|
||||
const frequency = req.body?.frequency
|
||||
if (isFrequency(frequency)) getStore().setFrequency(req.recipient!.id, frequency, nowIso())
|
||||
renderHome(req, res, true)
|
||||
})
|
||||
|
||||
app.post('/logout', (req, res) => {
|
||||
endSession(req, res)
|
||||
res.redirect(303, '/')
|
||||
})
|
||||
|
||||
// The bare root and /share land on the recipient's albums
|
||||
app.get(/^\/(|share)\/*$/, (_req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
res.redirect(303, '/me')
|
||||
})
|
||||
|
||||
// ----- comments ------------------------------------------------------------
|
||||
|
||||
const commentsPath = '/share/comments/:key/:id'
|
||||
|
||||
app.get(commentsPath, requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
|
||||
const resolved = await resolveSharedAsset(req, KeyType.key)
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
addNoStoreHeaders(res)
|
||||
res.json(getStore().listComments(resolved.link.key, resolved.asset.id).map(c => commentView(c, req.recipient!)))
|
||||
}))
|
||||
|
||||
app.post(commentsPath, requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
// JSON only: a cross-site HTML form can't send it
|
||||
if (!req.is('application/json')) {
|
||||
res.status(415).json({ error: 'Expected JSON' })
|
||||
return
|
||||
}
|
||||
const body = typeof req.body?.body === 'string' ? req.body.body.trim() : ''
|
||||
if (!body || body.length > MAX_COMMENT_LENGTH) {
|
||||
res.status(400).json({ error: 'A comment must be 1 to ' + MAX_COMMENT_LENGTH + ' characters.' })
|
||||
return
|
||||
}
|
||||
const recipient = req.recipient!
|
||||
const recent = (commentsByRecipient.get(String(recipient.id)) || 0) + 1
|
||||
if (recent > COMMENTS_PER_WINDOW) {
|
||||
res.status(429).json({ error: 'You\'re commenting too quickly. Try again in a few minutes.' })
|
||||
return
|
||||
}
|
||||
const resolved = await resolveSharedAsset(req, KeyType.key)
|
||||
if (!resolved.ok) {
|
||||
respondToInvalidRequest(res, resolved.status, resolved.reason)
|
||||
return
|
||||
}
|
||||
commentsByRecipient.set(String(recipient.id), recent)
|
||||
const comment = getStore().addComment({ shareKey: resolved.link.key, assetId: resolved.asset.id, recipient, body }, nowIso())
|
||||
res.status(201).json(commentView(comment, recipient))
|
||||
}))
|
||||
|
||||
app.delete(commentsPath + '/:commentId', requireShareAccess, (req, res) => {
|
||||
addNoStoreHeaders(res)
|
||||
const store = getStore()
|
||||
const comment = /^\d+$/.test(req.params.commentId) ? store.getComment(Number(req.params.commentId)) : undefined
|
||||
if (!comment || comment.shareKey !== req.grantedShare!.key || comment.assetId !== req.params.id || comment.recipientId !== req.recipient!.id) {
|
||||
res.status(404).send()
|
||||
return
|
||||
}
|
||||
store.deleteComment(comment.id)
|
||||
res.status(204).send()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { CookieOptions, NextFunction, Request, Response } from 'express-serve-static-core'
|
||||
import { addNoStoreHeaders, renderPage, respondToInvalidRequest } from '@ipp/core'
|
||||
import { h } from 'preact'
|
||||
import { getStore, Recipient, ShareRecord } from './store'
|
||||
import { AccessDenied } from './views'
|
||||
|
||||
declare module 'express-serve-static-core' {
|
||||
interface Request {
|
||||
recipient?: Recipient
|
||||
sessionToken?: string
|
||||
grantedShare?: ShareRecord
|
||||
}
|
||||
}
|
||||
|
||||
export const SESSION_COOKIE = 'imp_session'
|
||||
// Browsers cap cookie lifetimes at 400 days. The cookie is re-issued daily
|
||||
// while in use, so a bookmarked gallery keeps working indefinitely.
|
||||
const SESSION_MAX_AGE_MS = 400 * 24 * 60 * 60_000
|
||||
const SESSION_REFRESH_MS = 24 * 60 * 60_000
|
||||
|
||||
export const nowIso = () => new Date().toISOString()
|
||||
|
||||
export function readCookie (req: Request, name: string): string | undefined {
|
||||
for (const part of (req.headers.cookie || '').split(';')) {
|
||||
const index = part.indexOf('=')
|
||||
if (index > 0 && part.slice(0, index).trim() === name) {
|
||||
try {
|
||||
return decodeURIComponent(part.slice(index + 1).trim())
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Whether cookies should be `Secure`: true when the public URL is https. */
|
||||
export function secureCookies (): boolean {
|
||||
return (process.env.PUBLIC_BASE_URL || '').toLowerCase().startsWith('https://')
|
||||
}
|
||||
|
||||
function sessionCookieOptions (): CookieOptions {
|
||||
return { httpOnly: true, sameSite: 'lax', secure: secureCookies(), path: '/', maxAge: SESSION_MAX_AGE_MS }
|
||||
}
|
||||
|
||||
/** Sign a recipient in on this browser with a long-lived cookie. */
|
||||
export function startSession (res: Response, recipient: Recipient) {
|
||||
const token = getStore().createSession(recipient.id, nowIso())
|
||||
res.cookie(SESSION_COOKIE, token, sessionCookieOptions())
|
||||
}
|
||||
|
||||
export function endSession (req: Request, res: Response) {
|
||||
if (req.sessionToken) getStore().deleteSession(req.sessionToken)
|
||||
res.clearCookie(SESSION_COOKIE, { ...sessionCookieOptions(), maxAge: undefined })
|
||||
}
|
||||
|
||||
/** Attach `req.recipient` from the session cookie, if it is valid. Never blocks. */
|
||||
export function loadRecipient (req: Request, res: Response, next: NextFunction) {
|
||||
const token = readCookie(req, SESSION_COOKIE)
|
||||
if (token) {
|
||||
const store = getStore()
|
||||
const session = store.getSession(token)
|
||||
if (session && !session.recipient.disabled) {
|
||||
req.recipient = session.recipient
|
||||
req.sessionToken = token
|
||||
if (Date.now() - Date.parse(session.lastSeenAt) > SESSION_REFRESH_MS) {
|
||||
store.touchSession(token, nowIso())
|
||||
res.cookie(SESSION_COOKIE, token, sessionCookieOptions())
|
||||
}
|
||||
}
|
||||
}
|
||||
next()
|
||||
}
|
||||
|
||||
function wantsPage (req: Request): boolean {
|
||||
return req.method === 'GET' && (req.headers.accept || '').includes('text/html')
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse a request without revealing anything about what was asked for. A
|
||||
* browser navigation gets a page explaining how to get back in; anything else
|
||||
* (images, API calls) goes through IPP's invalid-request policy.
|
||||
*/
|
||||
export function deny (req: Request, res: Response, reason: string) {
|
||||
if (wantsPage(req)) {
|
||||
addNoStoreHeaders(res)
|
||||
res.status(req.recipient ? 404 : 401)
|
||||
res.send(renderPage(h(AccessDenied, { signedIn: !!req.recipient })))
|
||||
return
|
||||
}
|
||||
respondToInvalidRequest(res, 404, reason)
|
||||
}
|
||||
|
||||
/** Gate for everything except static files, healthchecks, sign-in and admin. */
|
||||
export function requireRecipient (req: Request, res: Response, next: NextFunction) {
|
||||
if (req.recipient) {
|
||||
next()
|
||||
} else {
|
||||
deny(req, res, 'No magic-link session for ' + req.path)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate for a share-scoped route: the signed-in recipient must have been given
|
||||
* this share (by key or slug) in `req.params.key`. Supplies the share's stored
|
||||
* password so recipients are never asked for it.
|
||||
*/
|
||||
export function requireShareAccess (req: Request, res: Response, next: NextFunction) {
|
||||
const share = req.recipient && typeof req.params.key === 'string'
|
||||
? getStore().grantedShare(req.recipient.id, req.params.key)
|
||||
: undefined
|
||||
if (!share) {
|
||||
deny(req, res, 'Recipient has no access to ' + req.params.key)
|
||||
return
|
||||
}
|
||||
req.grantedShare = share
|
||||
if (!req.password && share.password) req.password = share.password
|
||||
// Content behind a session must never land in a shared cache
|
||||
res.set('Vary', 'Cookie')
|
||||
next()
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
import { DatabaseSync, SQLInputValue } from 'node:sqlite'
|
||||
import { mkdirSync } from 'fs'
|
||||
import { dirname, resolve } from 'path'
|
||||
import { hashToken, newToken } from './tokens'
|
||||
|
||||
export type Frequency = 'off' | 'daily' | 'weekly' | 'monthly'
|
||||
export const FREQUENCIES: Frequency[] = ['off', 'daily', 'weekly', 'monthly']
|
||||
|
||||
export function isFrequency (value: unknown): value is Frequency {
|
||||
return typeof value === 'string' && (FREQUENCIES as string[]).includes(value)
|
||||
}
|
||||
|
||||
export interface Recipient {
|
||||
id: number
|
||||
name: string
|
||||
email: string
|
||||
frequency: Frequency
|
||||
/** Start of the window the next digest covers. */
|
||||
lastDigestAt: string | null
|
||||
createdAt: string
|
||||
disabled: boolean
|
||||
}
|
||||
|
||||
export interface ShareRecord {
|
||||
key: string
|
||||
slug: string | null
|
||||
title: string
|
||||
/** Lets recipients and the background scanner open a password-protected share. */
|
||||
password: string | null
|
||||
lastScannedAt: string | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface CommentRecord {
|
||||
id: number
|
||||
shareKey: string
|
||||
assetId: string
|
||||
recipientId: number | null
|
||||
authorName: string
|
||||
body: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS recipients (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
frequency TEXT NOT NULL DEFAULT 'off' CHECK (frequency IN ('off', 'daily', 'weekly', 'monthly')),
|
||||
last_digest_at TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
disabled INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS shares (
|
||||
key TEXT PRIMARY KEY,
|
||||
slug TEXT,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
password TEXT,
|
||||
last_scanned_at TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS recipient_shares (
|
||||
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
|
||||
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
|
||||
granted_at TEXT NOT NULL,
|
||||
PRIMARY KEY (recipient_id, share_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS magic_links (
|
||||
id INTEGER PRIMARY KEY,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
|
||||
purpose TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT,
|
||||
last_used_at TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
|
||||
created_at TEXT NOT NULL,
|
||||
last_seen_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS share_assets (
|
||||
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
|
||||
asset_id TEXT NOT NULL,
|
||||
first_seen_at TEXT NOT NULL,
|
||||
PRIMARY KEY (share_key, asset_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS comments (
|
||||
id INTEGER PRIMARY KEY,
|
||||
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
|
||||
asset_id TEXT NOT NULL,
|
||||
recipient_id INTEGER REFERENCES recipients(id) ON DELETE SET NULL,
|
||||
author_name TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS comments_by_asset ON comments (share_key, asset_id);
|
||||
CREATE TABLE IF NOT EXISTS link_requests (
|
||||
email TEXT PRIMARY KEY COLLATE NOCASE,
|
||||
last_at TEXT NOT NULL
|
||||
);
|
||||
`
|
||||
|
||||
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 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 toRecipient (row: Row | undefined): Recipient | undefined {
|
||||
if (!row) return undefined
|
||||
return { ...(row as unknown as Recipient), disabled: !!row.disabled }
|
||||
}
|
||||
|
||||
/**
|
||||
* All persistent state for magic-link access, notifications and comments.
|
||||
* Timestamps are ISO-8601 UTC strings, so they compare correctly as text.
|
||||
*/
|
||||
export class Store {
|
||||
readonly db: DatabaseSync
|
||||
|
||||
constructor (path: string) {
|
||||
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true })
|
||||
this.db = new DatabaseSync(path)
|
||||
this.db.exec('PRAGMA foreign_keys = ON')
|
||||
this.db.exec('PRAGMA busy_timeout = 5000')
|
||||
if (path !== ':memory:') this.db.exec('PRAGMA journal_mode = WAL')
|
||||
this.db.exec(SCHEMA)
|
||||
}
|
||||
|
||||
close () {
|
||||
this.db.close()
|
||||
}
|
||||
|
||||
private transaction (fn: () => void) {
|
||||
this.db.exec('BEGIN')
|
||||
try {
|
||||
fn()
|
||||
this.db.exec('COMMIT')
|
||||
} catch (e) {
|
||||
this.db.exec('ROLLBACK')
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// ----- recipients ----------------------------------------------------------
|
||||
|
||||
createRecipient (input: { name: string, email: string, frequency: Frequency }, now: string): Recipient {
|
||||
const result = this.db.prepare(`INSERT INTO recipients (name, email, frequency, last_digest_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)`).run(input.name, input.email, input.frequency, input.frequency === 'off' ? null : now, now)
|
||||
return this.getRecipient(Number(result.lastInsertRowid))!
|
||||
}
|
||||
|
||||
getRecipient (id: number): Recipient | undefined {
|
||||
return toRecipient(this.db.prepare(`SELECT ${RECIPIENT_COLUMNS} FROM recipients WHERE id = ?`).get(id))
|
||||
}
|
||||
|
||||
getRecipientByEmail (email: string): Recipient | undefined {
|
||||
return toRecipient(this.db.prepare(`SELECT ${RECIPIENT_COLUMNS} FROM recipients WHERE email = ?`).get(email))
|
||||
}
|
||||
|
||||
listRecipients (): Recipient[] {
|
||||
return this.db.prepare(`SELECT ${RECIPIENT_COLUMNS} FROM recipients ORDER BY name COLLATE NOCASE`).all()
|
||||
.map(row => toRecipient(row)!)
|
||||
}
|
||||
|
||||
updateRecipient (id: number, input: { name: string, email: string, disabled: boolean }) {
|
||||
this.db.prepare('UPDATE recipients SET name = ?, email = ?, disabled = ? WHERE id = ?')
|
||||
.run(input.name, input.email, input.disabled ? 1 : 0, id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Change how often a recipient hears about new photos. Turning digests on
|
||||
* starts the window now, so they are never told about photos that were
|
||||
* already there.
|
||||
*/
|
||||
setFrequency (id: number, frequency: Frequency, now: string) {
|
||||
const current = this.getRecipient(id)
|
||||
if (!current) return
|
||||
const startWindow = frequency !== 'off' && (current.frequency === 'off' || !current.lastDigestAt)
|
||||
this.db.prepare('UPDATE recipients SET frequency = ?, last_digest_at = ? WHERE id = ?')
|
||||
.run(frequency, startWindow ? now : current.lastDigestAt, id)
|
||||
}
|
||||
|
||||
setDigestAt (id: number, at: string) {
|
||||
this.db.prepare('UPDATE recipients SET last_digest_at = ? WHERE id = ?').run(at, id)
|
||||
}
|
||||
|
||||
deleteRecipient (id: number) {
|
||||
this.db.prepare('DELETE FROM recipients WHERE id = ?').run(id)
|
||||
}
|
||||
|
||||
// ----- 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)
|
||||
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
|
||||
}
|
||||
|
||||
listShares (): ShareRecord[] {
|
||||
return this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares ORDER BY title COLLATE NOCASE`).all() as unknown as ShareRecord[]
|
||||
}
|
||||
|
||||
deleteShare (key: string) {
|
||||
this.db.prepare('DELETE FROM shares WHERE key = ?').run(key)
|
||||
}
|
||||
|
||||
setShareScanned (key: string, at: string) {
|
||||
this.db.prepare('UPDATE shares SET last_scanned_at = ? WHERE key = ?').run(at, key)
|
||||
}
|
||||
|
||||
// ----- access grants -------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Set exactly which shares a recipient has. Shares they already had keep
|
||||
* their grant time, which bounds what their notifications count.
|
||||
*/
|
||||
setRecipientShares (recipientId: number, keys: string[], now: string) {
|
||||
const wanted = [...new Set(keys)]
|
||||
this.transaction(() => {
|
||||
const placeholders = wanted.map(() => '?').join(', ')
|
||||
this.db.prepare('DELETE FROM recipient_shares WHERE recipient_id = ?' +
|
||||
(wanted.length ? ` AND share_key NOT IN (${placeholders})` : '')).run(recipientId, ...wanted)
|
||||
const insert = this.db.prepare(`INSERT OR IGNORE INTO recipient_shares (recipient_id, share_key, granted_at)
|
||||
SELECT ?, key, ? FROM shares WHERE key = ?`)
|
||||
for (const key of wanted) insert.run(recipientId, now, key)
|
||||
})
|
||||
}
|
||||
|
||||
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 }>
|
||||
}
|
||||
|
||||
countShareRecipients (key: string): number {
|
||||
const row = this.db.prepare('SELECT COUNT(*) AS n FROM recipient_shares WHERE share_key = ?').get(key)
|
||||
return Number(row?.n ?? 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* The share a recipient may open by its key or slug, or undefined. This is
|
||||
* 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
|
||||
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
|
||||
}
|
||||
|
||||
// ----- magic links ---------------------------------------------------------
|
||||
|
||||
/** Returns the plaintext token; only its hash is stored. */
|
||||
createMagicLink (recipientId: number, options: { purpose: string, expiresAt: string | null }, now: string): string {
|
||||
const token = newToken()
|
||||
this.db.prepare(`INSERT INTO magic_links (token_hash, recipient_id, purpose, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?)`).run(hashToken(token), recipientId, options.purpose, now, options.expiresAt)
|
||||
return token
|
||||
}
|
||||
|
||||
/** The recipient a magic link signs in, if the link is live and the recipient enabled. */
|
||||
useMagicLink (token: string, now: string): Recipient | undefined {
|
||||
const hash = hashToken(token)
|
||||
const link = this.db.prepare('SELECT recipient_id AS recipientId, expires_at AS expiresAt FROM magic_links WHERE token_hash = ?')
|
||||
.get(hash) as { recipientId: number, expiresAt: string | null } | undefined
|
||||
if (!link || (link.expiresAt && link.expiresAt <= now)) return undefined
|
||||
const recipient = this.getRecipient(link.recipientId)
|
||||
if (!recipient || recipient.disabled) return undefined
|
||||
this.db.prepare('UPDATE magic_links SET last_used_at = ? WHERE token_hash = ?').run(now, hash)
|
||||
return recipient
|
||||
}
|
||||
|
||||
countMagicLinks (recipientId: number, now: string): number {
|
||||
const row = this.db.prepare('SELECT COUNT(*) AS n FROM magic_links WHERE recipient_id = ? AND (expires_at IS NULL OR expires_at > ?)')
|
||||
.get(recipientId, now)
|
||||
return Number(row?.n ?? 0)
|
||||
}
|
||||
|
||||
pruneExpiredLinks (now: string) {
|
||||
this.db.prepare('DELETE FROM magic_links WHERE expires_at IS NOT NULL AND expires_at <= ?').run(now)
|
||||
}
|
||||
|
||||
/** Allow at most one self-service link request per address per interval. */
|
||||
allowLinkRequest (email: string, now: string, notBefore: string): boolean {
|
||||
const row = this.db.prepare('SELECT last_at AS lastAt FROM link_requests WHERE email = ?').get(email) as { lastAt: string } | undefined
|
||||
if (row && row.lastAt > notBefore) return false
|
||||
this.db.prepare(`INSERT INTO link_requests (email, last_at) VALUES (?, ?)
|
||||
ON CONFLICT (email) DO UPDATE SET last_at = excluded.last_at`).run(email, now)
|
||||
return true
|
||||
}
|
||||
|
||||
// ----- sessions ------------------------------------------------------------
|
||||
|
||||
createSession (recipientId: number, now: string): string {
|
||||
const token = newToken()
|
||||
this.db.prepare('INSERT INTO sessions (token_hash, recipient_id, created_at, last_seen_at) VALUES (?, ?, ?, ?)')
|
||||
.run(hashToken(token), recipientId, now, now)
|
||||
return token
|
||||
}
|
||||
|
||||
getSession (token: string): { recipient: Recipient, lastSeenAt: string } | undefined {
|
||||
const row = this.db.prepare('SELECT recipient_id AS recipientId, last_seen_at AS lastSeenAt FROM sessions WHERE token_hash = ?')
|
||||
.get(hashToken(token)) as { recipientId: number, lastSeenAt: string } | undefined
|
||||
if (!row) return undefined
|
||||
const recipient = this.getRecipient(row.recipientId)
|
||||
return recipient ? { recipient, lastSeenAt: row.lastSeenAt } : undefined
|
||||
}
|
||||
|
||||
touchSession (token: string, now: string) {
|
||||
this.db.prepare('UPDATE sessions SET last_seen_at = ? WHERE token_hash = ?').run(now, hashToken(token))
|
||||
}
|
||||
|
||||
deleteSession (token: string) {
|
||||
this.db.prepare('DELETE FROM sessions WHERE token_hash = ?').run(hashToken(token))
|
||||
}
|
||||
|
||||
countSessions (recipientId: number): number {
|
||||
const row = this.db.prepare('SELECT COUNT(*) AS n FROM sessions WHERE recipient_id = ?').get(recipientId)
|
||||
return Number(row?.n ?? 0)
|
||||
}
|
||||
|
||||
/** Sign the recipient out everywhere and invalidate every link they were sent. */
|
||||
revokeAccess (recipientId: number) {
|
||||
this.transaction(() => {
|
||||
this.db.prepare('DELETE FROM sessions WHERE recipient_id = ?').run(recipientId)
|
||||
this.db.prepare('DELETE FROM magic_links WHERE recipient_id = ?').run(recipientId)
|
||||
})
|
||||
}
|
||||
|
||||
// ----- asset tracking (for notifications) ----------------------------------
|
||||
|
||||
knownAssetIds (shareKey: string): Set<string> {
|
||||
const rows = this.db.prepare('SELECT asset_id AS id FROM share_assets WHERE share_key = ?').all(shareKey)
|
||||
return new Set(rows.map(row => String(row.id)))
|
||||
}
|
||||
|
||||
addAssets (shareKey: string, ids: string[], firstSeenAt: string) {
|
||||
if (!ids.length) return
|
||||
this.transaction(() => {
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO share_assets (share_key, asset_id, first_seen_at) VALUES (?, ?, ?)')
|
||||
for (const id of ids) insert.run(shareKey, id, firstSeenAt)
|
||||
})
|
||||
}
|
||||
|
||||
/** Assets first seen in (after, upTo]. */
|
||||
assetsSeenBetween (shareKey: string, after: string, upTo: string): string[] {
|
||||
return this.db.prepare('SELECT asset_id AS id FROM share_assets WHERE share_key = ? AND first_seen_at > ? AND first_seen_at <= ?')
|
||||
.all(shareKey, after, upTo).map(row => String(row.id))
|
||||
}
|
||||
|
||||
countKnownAssets (shareKey: string): number {
|
||||
const row = this.db.prepare('SELECT COUNT(*) AS n FROM share_assets WHERE share_key = ?').get(shareKey)
|
||||
return Number(row?.n ?? 0)
|
||||
}
|
||||
|
||||
// ----- comments ------------------------------------------------------------
|
||||
|
||||
addComment (input: { shareKey: string, assetId: string, recipient: Recipient, body: string }, now: string): CommentRecord {
|
||||
const result = this.db.prepare(`INSERT INTO comments (share_key, asset_id, recipient_id, author_name, body, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`).run(input.shareKey, input.assetId, input.recipient.id, input.recipient.name, input.body, now)
|
||||
return this.getComment(Number(result.lastInsertRowid))!
|
||||
}
|
||||
|
||||
getComment (id: number): CommentRecord | undefined {
|
||||
return this.db.prepare(`SELECT ${COMMENT_COLUMNS} FROM comments WHERE id = ?`).get(id) as CommentRecord | undefined
|
||||
}
|
||||
|
||||
listComments (shareKey: string, assetId: string): CommentRecord[] {
|
||||
return this.db.prepare(`SELECT ${COMMENT_COLUMNS} FROM comments WHERE share_key = ? AND asset_id = ? ORDER BY id`)
|
||||
.all(shareKey, assetId) as unknown as CommentRecord[]
|
||||
}
|
||||
|
||||
countComments (shareKey: string): Record<string, number> {
|
||||
const rows = this.db.prepare('SELECT asset_id AS id, COUNT(*) AS n FROM comments WHERE share_key = ? GROUP BY asset_id').all(shareKey)
|
||||
return Object.fromEntries(rows.map(row => [String(row.id), Number(row.n)]))
|
||||
}
|
||||
|
||||
recentComments (limit: number): Array<CommentRecord & { shareTitle: string }> {
|
||||
return this.db.prepare(`SELECT c.id, c.share_key AS shareKey, c.asset_id AS assetId, c.recipient_id AS recipientId,
|
||||
c.author_name AS authorName, c.body, c.created_at AS createdAt, s.title AS shareTitle
|
||||
FROM comments c JOIN shares s ON s.key = c.share_key ORDER BY c.id DESC LIMIT ?`)
|
||||
.all(limit) as unknown as Array<CommentRecord & { shareTitle: string }>
|
||||
}
|
||||
|
||||
deleteComment (id: number) {
|
||||
this.db.prepare('DELETE FROM comments WHERE id = ?').run(id)
|
||||
}
|
||||
}
|
||||
|
||||
let store: Store | undefined
|
||||
|
||||
/** `<DATA_DIR>/magic.db`, where DATA_DIR defaults to `./data`. */
|
||||
export function defaultDbPath (): string {
|
||||
return resolve(process.env.DATA_DIR || 'data', 'magic.db')
|
||||
}
|
||||
|
||||
export function getStore (): Store {
|
||||
if (!store) store = new Store(defaultDbPath())
|
||||
return store
|
||||
}
|
||||
|
||||
/** Swap the store, for tests. */
|
||||
export function setStore (next: Store | undefined) {
|
||||
store = next
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
/** 256 bits of randomness, URL-safe. */
|
||||
export function newToken (): string {
|
||||
return crypto.randomBytes(32).toString('base64url')
|
||||
}
|
||||
|
||||
/** Tokens are stored hashed, so a leaked database does not leak working links or sessions. */
|
||||
export function hashToken (token: string): string {
|
||||
return crypto.createHash('sha256').update(token).digest('hex')
|
||||
}
|
||||
|
||||
export function isTokenShaped (value: unknown): value is string {
|
||||
return typeof value === 'string' && /^[\w-]{20,100}$/.test(value)
|
||||
}
|
||||
|
||||
/** A same-site path to send the visitor to after sign-in, or undefined (blocks open redirects). */
|
||||
export function safeNextPath (value: unknown): string | undefined {
|
||||
if (typeof value !== 'string') return undefined
|
||||
if (!/^\/(?![/\\])/.test(value)) return undefined
|
||||
if (/[\r\n]/.test(value)) return undefined
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
import { ComponentChildren } from 'preact'
|
||||
import { CommentRecord, Frequency, FREQUENCIES, Recipient, ShareRecord } from './store'
|
||||
|
||||
const FREQUENCY_LABELS: Record<Frequency, string> = {
|
||||
off: 'Never',
|
||||
daily: 'Daily',
|
||||
weekly: 'Weekly',
|
||||
monthly: 'Monthly'
|
||||
}
|
||||
|
||||
const STYLE = `
|
||||
main.container { max-width: 760px; padding-top: 2rem; padding-bottom: 3rem; }
|
||||
.muted { color: var(--pico-muted-color); }
|
||||
.notice { padding: .75rem 1rem; border-radius: var(--pico-border-radius); background: var(--pico-card-sectioning-background-color); margin-bottom: 1rem; }
|
||||
.notice.error { border-left: 4px solid var(--pico-del-color); }
|
||||
.notice.ok { border-left: 4px solid var(--pico-ins-color); }
|
||||
.link-box { word-break: break-all; font-family: var(--pico-font-family-monospace); font-size: .85rem; }
|
||||
.row-actions { display: flex; gap: .5rem; flex-wrap: wrap; align-items: center; }
|
||||
.row-actions form { margin: 0; }
|
||||
.row-actions button { margin: 0; padding: .35rem .75rem; font-size: .85rem; }
|
||||
table td, table th { vertical-align: top; font-size: .9rem; }
|
||||
fieldset.checks label { display: block; }
|
||||
.albums a { display: block; padding: .6rem .9rem; margin-bottom: .5rem; border-radius: var(--pico-border-radius); background: var(--pico-card-background-color); box-shadow: var(--pico-card-box-shadow); text-decoration: none; }
|
||||
`
|
||||
|
||||
// Forms with data-confirm ask before submitting
|
||||
const CONFIRM_SCRIPT = `document.addEventListener('submit', function (e) {
|
||||
var message = e.target.getAttribute('data-confirm')
|
||||
if (message && !confirm(message)) e.preventDefault()
|
||||
})`
|
||||
|
||||
function Layout ({ title, children }: { title: string, children: ComponentChildren }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<meta name="referrer" content="no-referrer"/>
|
||||
<meta name="robots" content="noindex, nofollow"/>
|
||||
<title>{title}</title>
|
||||
<link rel="icon" href="/share/static/favicon.ico" type="image/x-icon"/>
|
||||
<link type="text/css" rel="stylesheet" href="/share/static/pico.min.css"/>
|
||||
<style dangerouslySetInnerHTML={{ __html: STYLE }}/>
|
||||
</head>
|
||||
<body>
|
||||
<main class="container">{children}</main>
|
||||
<script dangerouslySetInnerHTML={{ __html: CONFIRM_SCRIPT }}/>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
|
||||
function Notice ({ kind, children }: { kind: 'ok' | 'error', children: ComponentChildren }) {
|
||||
return <div class={'notice ' + kind} role={kind === 'error' ? 'alert' : 'status'}>{children}</div>
|
||||
}
|
||||
|
||||
// ----- visitors --------------------------------------------------------------
|
||||
|
||||
/** Shown in place of anything gated. Reveals nothing about what was asked for. */
|
||||
export function AccessDenied ({ signedIn, invalidLink }: { signedIn: boolean, invalidLink?: boolean }) {
|
||||
return (
|
||||
<Layout title="Private photos">
|
||||
<h1>Private photos</h1>
|
||||
{invalidLink && <Notice kind="error">That link is no longer valid.</Notice>}
|
||||
{signedIn
|
||||
? <p>This page isn't available to you. <a href="/me">See the albums you can view</a>.</p>
|
||||
: <>
|
||||
<p>These photos are only visible through a personal invitation link. Open the link from your invitation email to continue.</p>
|
||||
<RequestLinkForm/>
|
||||
</>}
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
function RequestLinkForm () {
|
||||
return (
|
||||
<form method="post" action="/access">
|
||||
<label>
|
||||
Lost your link? Enter the email address you were invited with and we'll send a new one.
|
||||
<input type="email" name="email" required autocomplete="email" placeholder="you@example.com"/>
|
||||
</label>
|
||||
<button type="submit">Email me a link</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
export function LinkRequested () {
|
||||
return (
|
||||
<Layout title="Check your email">
|
||||
<h1>Check your email</h1>
|
||||
<p>If that address has been invited, a sign-in link is on its way. It works for 7 days.</p>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
export interface RecipientHomeProps {
|
||||
recipient: Recipient
|
||||
shares: ShareRecord[]
|
||||
saved?: boolean
|
||||
emailEnabled: boolean
|
||||
}
|
||||
|
||||
export function RecipientHome ({ recipient, shares, saved, emailEnabled }: RecipientHomeProps) {
|
||||
return (
|
||||
<Layout title="Your albums">
|
||||
<hgroup>
|
||||
<h1>Hi {recipient.name}</h1>
|
||||
<p class="muted">Bookmark this page to come back to your albums. This browser stays signed in.</p>
|
||||
</hgroup>
|
||||
<section class="albums">
|
||||
<h2>Albums</h2>
|
||||
{shares.length
|
||||
? shares.map(share => <a key={share.key} href={'/share/' + share.key}>{share.title || 'Shared album'}</a>)
|
||||
: <p class="muted">Nothing has been shared with you yet.</p>}
|
||||
</section>
|
||||
<section>
|
||||
<h2>Email notifications</h2>
|
||||
{saved && <Notice kind="ok">Saved.</Notice>}
|
||||
<form method="post" action="/me/notifications">
|
||||
<fieldset>
|
||||
<legend>Email me about new photos in these albums ({recipient.email}):</legend>
|
||||
{FREQUENCIES.map(frequency => (
|
||||
<label key={frequency}>
|
||||
<input type="radio" name="frequency" value={frequency} checked={recipient.frequency === frequency}/>
|
||||
{frequency === 'off' ? 'Never' : FREQUENCY_LABELS[frequency] + ' summary'}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
{!emailEnabled && <p class="muted"><small>Email isn't set up on this server yet, so nothing will be sent for now.</small></p>}
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
</section>
|
||||
<section>
|
||||
<form method="post" action="/logout">
|
||||
<button type="submit" class="secondary outline">Sign out of this browser</button>
|
||||
</form>
|
||||
</section>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
// ----- admin -----------------------------------------------------------------
|
||||
|
||||
export function AdminLogin ({ failed }: { failed?: boolean }) {
|
||||
return (
|
||||
<Layout title="Admin sign-in">
|
||||
<h1>Admin</h1>
|
||||
{failed && <Notice kind="error">Wrong password, or too many attempts. Try again in a few minutes.</Notice>}
|
||||
<form method="post" action="/admin/login">
|
||||
<input type="password" name="password" placeholder="Admin password" aria-label="Admin password" required autofocus/>
|
||||
<button type="submit">Sign in</button>
|
||||
</form>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
export interface AdminShareRow { share: ShareRecord, recipients: number, assets: number }
|
||||
export interface AdminRecipientRow { recipient: Recipient, shares: ShareRecord[], sessions: number }
|
||||
|
||||
export interface AdminDashboardProps {
|
||||
shares: AdminShareRow[]
|
||||
recipients: AdminRecipientRow[]
|
||||
comments: Array<CommentRecord & { shareTitle: string }>
|
||||
emailEnabled: boolean
|
||||
message?: { kind: 'ok' | 'error', text: string }
|
||||
}
|
||||
|
||||
export function AdminDashboard ({ shares, recipients, comments, emailEnabled, message }: AdminDashboardProps) {
|
||||
return (
|
||||
<Layout title="Admin">
|
||||
<nav>
|
||||
<ul><li><strong>Admin</strong></li></ul>
|
||||
<ul>
|
||||
<li>
|
||||
<form method="post" action="/admin/notify" style="margin:0">
|
||||
<button type="submit" class="secondary outline" style="margin:0">Check for new photos now</button>
|
||||
</form>
|
||||
</li>
|
||||
<li>
|
||||
<form method="post" action="/admin/logout" style="margin:0">
|
||||
<button type="submit" class="secondary outline" style="margin:0">Sign out</button>
|
||||
</form>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
{message && <Notice kind={message.kind}>{message.text}</Notice>}
|
||||
{!emailEnabled && <Notice kind="error">Email is not configured (SMTP_URL or SMTP_HOST, plus PUBLIC_BASE_URL), so invitations and notifications can't be sent. You can still copy links by hand.</Notice>}
|
||||
|
||||
<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>
|
||||
{shares.length > 0 && (
|
||||
<table>
|
||||
<thead><tr><th>Album</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>{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.'>
|
||||
<button type="submit" class="secondary outline" style="margin:0;padding:.3rem .6rem;font-size:.8rem">Remove</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
<details open={!shares.length}>
|
||||
<summary role="button" class="outline">Add an album</summary>
|
||||
<form method="post" action="/admin/shares">
|
||||
<label>
|
||||
Immich share link or key
|
||||
<input name="link" required placeholder="https://immich.example.com/share/AbC123… or /s/my-album"/>
|
||||
</label>
|
||||
<label>
|
||||
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>
|
||||
<button type="submit">Add album</button>
|
||||
</form>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Recipients</h2>
|
||||
{recipients.length > 0 && (
|
||||
<table>
|
||||
<thead><tr><th>Name</th><th>Albums</th><th>Emails</th><th>Signed-in browsers</th></tr></thead>
|
||||
<tbody>
|
||||
{recipients.map(({ recipient, shares: granted, sessions }) => (
|
||||
<tr key={recipient.id}>
|
||||
<td><a href={'/admin/recipients/' + recipient.id}>{recipient.name}</a>{recipient.disabled && <> <small>(disabled)</small></>}<br/><small class="muted">{recipient.email}</small></td>
|
||||
<td>{granted.map(s => s.title).join(', ') || <span class="muted">none</span>}</td>
|
||||
<td>{FREQUENCY_LABELS[recipient.frequency]}</td>
|
||||
<td>{sessions}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{shares.length
|
||||
? (
|
||||
<details open={!recipients.length}>
|
||||
<summary role="button" class="outline">Add a recipient</summary>
|
||||
<form method="post" action="/admin/recipients">
|
||||
<div class="grid">
|
||||
<label>Name<input name="name" required/></label>
|
||||
<label>Email<input type="email" name="email" required/></label>
|
||||
</div>
|
||||
<ShareChecks shares={shares.map(row => row.share)} selected={[]}/>
|
||||
<FrequencySelect value="weekly"/>
|
||||
<label><input type="checkbox" name="sendInvite" value="1" checked={emailEnabled} disabled={!emailEnabled}/> Email them their invitation link now</label>
|
||||
<button type="submit">Add recipient</button>
|
||||
</form>
|
||||
</details>
|
||||
)
|
||||
: <p class="muted">Add an album first.</p>}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Recent comments</h2>
|
||||
{comments.length
|
||||
? (
|
||||
<table>
|
||||
<tbody>
|
||||
{comments.map(comment => (
|
||||
<tr key={comment.id}>
|
||||
<td style="width:72px"><img src={'/admin/thumb/' + encodeURIComponent(comment.shareKey) + '/' + comment.assetId} alt="" width={64} height={64} style="object-fit:cover;border-radius:4px" loading="lazy"/></td>
|
||||
<td><strong>{comment.authorName}</strong> on {comment.shareTitle}<br/><small class="muted">{new Date(comment.createdAt).toLocaleString('en-GB')}</small></td>
|
||||
<td style="white-space:pre-wrap">{comment.body}</td>
|
||||
<td>
|
||||
<form method="post" action={'/admin/comments/' + comment.id + '/delete'}>
|
||||
<button type="submit" class="secondary outline" style="margin:0;padding:.3rem .6rem;font-size:.8rem">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
: <p class="muted">No comments yet.</p>}
|
||||
</section>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
|
||||
function ShareChecks ({ shares, selected }: { shares: ShareRecord[], selected: string[] }) {
|
||||
return (
|
||||
<fieldset class="checks">
|
||||
<legend>Albums they can see</legend>
|
||||
{shares.map(share => (
|
||||
<label key={share.key}>
|
||||
<input type="checkbox" name="shares" value={share.key} checked={selected.includes(share.key)}/>
|
||||
{share.title || 'Untitled'}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
|
||||
function FrequencySelect ({ value }: { value: Frequency }) {
|
||||
return (
|
||||
<label>
|
||||
New-photo emails
|
||||
<select name="frequency">
|
||||
{FREQUENCIES.map(frequency => <option key={frequency} value={frequency} selected={value === frequency}>{FREQUENCY_LABELS[frequency]}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
export interface AdminRecipientProps {
|
||||
recipient: Recipient
|
||||
shares: ShareRecord[]
|
||||
granted: string[]
|
||||
sessions: number
|
||||
activeLinks: number
|
||||
emailEnabled: boolean
|
||||
/** A link created by this request; shown once, never stored in plain text. */
|
||||
newLink?: string
|
||||
message?: { kind: 'ok' | 'error', text: string }
|
||||
}
|
||||
|
||||
export function AdminRecipient ({ recipient, shares, granted, sessions, activeLinks, emailEnabled, newLink, message }: AdminRecipientProps) {
|
||||
const base = '/admin/recipients/' + recipient.id
|
||||
return (
|
||||
<Layout title={recipient.name + ' · Admin'}>
|
||||
<p><a href="/admin">← Admin</a></p>
|
||||
<h1>{recipient.name}</h1>
|
||||
{message && <Notice kind={message.kind}>{message.text}</Notice>}
|
||||
{newLink && (
|
||||
<article>
|
||||
<header><strong>Personal link for {recipient.name}</strong></header>
|
||||
<p class="link-box">{newLink}</p>
|
||||
<footer><small class="muted">Shown once. Anyone with this link can see their albums. It doesn't expire; revoke access below to cancel it.</small></footer>
|
||||
</article>
|
||||
)}
|
||||
<form method="post" action={base}>
|
||||
<div class="grid">
|
||||
<label>Name<input name="name" required value={recipient.name}/></label>
|
||||
<label>Email<input type="email" name="email" required value={recipient.email}/></label>
|
||||
</div>
|
||||
<ShareChecks shares={shares} selected={granted}/>
|
||||
<FrequencySelect value={recipient.frequency}/>
|
||||
<label><input type="checkbox" name="disabled" value="1" checked={recipient.disabled}/> Disabled (blocks all their links and sessions)</label>
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
|
||||
<h2>Access</h2>
|
||||
<p>{sessions} signed-in browser{sessions === 1 ? '' : 's'} · {activeLinks} working link{activeLinks === 1 ? '' : 's'}</p>
|
||||
<div class="row-actions">
|
||||
<form method="post" action={base + '/link'}>
|
||||
<button type="submit">Create a new link</button>
|
||||
</form>
|
||||
<form method="post" action={base + '/link'}>
|
||||
<input type="hidden" name="send" value="1"/>
|
||||
<button type="submit" disabled={!emailEnabled}>Email them a new link</button>
|
||||
</form>
|
||||
<form method="post" action={base + '/revoke'} data-confirm='Sign them out everywhere and cancel all their links?'>
|
||||
<button type="submit" class="secondary">Revoke all access</button>
|
||||
</form>
|
||||
<form method="post" action={base + '/delete'} data-confirm='Delete this recipient? Their comments stay, unattributed to an account.'>
|
||||
<button type="submit" class="secondary outline">Delete recipient</button>
|
||||
</form>
|
||||
</div>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user