From f598200e24c84034b1ae4a652c076137d17cf141 Mon Sep 17 00:00:00 2001 From: zyphlar Date: Mon, 19 Oct 2026 15:10:57 -0700 Subject: [PATCH] Gate shares behind magic-link sessions, add comments and new-photo email digests --- .dockerignore | 2 + .gitignore | 2 + Dockerfile | 6 +- README.md | 62 +++++ app/config.json | 7 +- app/package.json | 2 + app/public/style.css | 111 ++++++++ app/src/client/comments.ts | 205 +++++++++++++++ app/src/client/icons.ts | 1 + app/src/client/init.ts | 1 + app/src/client/lightbox.ts | 23 +- app/src/client/sidebar.ts | 72 +++++- app/src/client/state.ts | 6 +- app/src/gallery/builder.ts | 24 +- app/src/index.ts | 309 +---------------------- app/src/magic/admin.ts | 324 ++++++++++++++++++++++++ app/src/magic/digest.ts | 162 ++++++++++++ app/src/magic/mailer.ts | 134 ++++++++++ app/src/magic/routes.ts | 170 +++++++++++++ app/src/magic/session.ts | 121 +++++++++ app/src/magic/store.ts | 416 ++++++++++++++++++++++++++++++ app/src/magic/tokens.ts | 23 ++ app/src/magic/views.tsx | 371 +++++++++++++++++++++++++++ app/src/resolve.ts | 66 +++++ app/src/server.ts | 253 +++++++++++++++++++ app/src/shared/types.ts | 18 ++ app/src/view/gallery.tsx | 22 +- app/tests/magicAccess.test.ts | 461 ++++++++++++++++++++++++++++++++++ app/tests/magicDigest.test.ts | 147 +++++++++++ app/tests/magicStore.test.ts | 157 ++++++++++++ docker-compose.yml | 43 ++-- docs/config/gallery.md | 4 +- docs/config/ipp-options.md | 16 +- package-lock.json | 21 ++ 34 files changed, 3387 insertions(+), 375 deletions(-) create mode 100644 app/src/client/comments.ts create mode 100644 app/src/magic/admin.ts create mode 100644 app/src/magic/digest.ts create mode 100644 app/src/magic/mailer.ts create mode 100644 app/src/magic/routes.ts create mode 100644 app/src/magic/session.ts create mode 100644 app/src/magic/store.ts create mode 100644 app/src/magic/tokens.ts create mode 100644 app/src/magic/views.tsx create mode 100644 app/src/resolve.ts create mode 100644 app/src/server.ts create mode 100644 app/tests/magicAccess.test.ts create mode 100644 app/tests/magicDigest.test.ts create mode 100644 app/tests/magicStore.test.ts diff --git a/.dockerignore b/.dockerignore index f49ee86..f549885 100644 --- a/.dockerignore +++ b/.dockerignore @@ -9,3 +9,5 @@ /upload-app/dist/ /upload-app/public/js/ /upload-app/.env +/data/ +/app/data/ diff --git a/.gitignore b/.gitignore index 7aee33b..3bf3cb0 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ app/public/js/ .npm-cache/ *.tsbuildinfo upload-app/public/js/ +/data/ +/app/data/ diff --git a/Dockerfile b/Dockerfile index d37039b..a9d13a7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -47,13 +47,17 @@ COPY --from=builder --chown=root:root /ipp/app/public ./public COPY --from=builder --chown=root:root /ipp/app/config.json ./ # The code is root-owned and the app runs as node, so a compromised process -# cannot rewrite it; nothing writes to disk at runtime. The explicit --chown +# cannot rewrite it. The only runtime writes are the SQLite database of +# recipients, sessions and comments, in the /data volume. The explicit --chown # is for buildah, which keeps the builder's owner on COPY --from. +RUN mkdir /data && chown node:node /data +VOLUME /data USER node ARG PACKAGE_VERSION ENV APP_VERSION=${PACKAGE_VERSION} ENV NODE_ENV=production +ENV DATA_DIR=/data # tini as PID 1 reaps orphaned healthcheck processes, which node does not (GitHub #66). # -s keeps reaping, without a warning, when PID 1 is already an init (compose `init: true`). diff --git a/README.md b/README.md index 276100f..bb98bd4 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,65 @@ +# Immich Magic Proxy + +A fork of [Immich Public Proxy](https://github.com/alangrainger/immich-public-proxy) (4.1.1) where shares are +**private**: only people you invite can see them. + +- **Magic links.** You add an Immich shared link and the people allowed to see it. Each person gets a personal link. + Without a valid link, every page, photo, video, download and API route answers with a "private photos" page or a + 404, and never touches Immich. +- **Bookmarkable.** Opening the link signs that browser in with an `HttpOnly` cookie that lasts 400 days (the + browser maximum) and renews itself daily while in use. Sessions live in the database, so restarts don't sign + anyone out. Recipients can bookmark an album, or `/me` for all their albums. +- **New-photo emails.** Each recipient chooses daily, weekly, monthly or never (you set their starting choice). The + proxy checks every album for new photos and sends one summary email per period, with a sign-in link per album. + Photos that were already there when someone got access are never reported as new. +- **Comments.** Recipients can comment on any photo from the lightbox (comment button, or the info sidebar). They can + delete their own; you can moderate all of them from the admin page. +- **Lost links.** A visitor with no session can ask for a new link by email. The reply is the same whether or not the + address was invited, and requests are rate-limited. +- **Password-protected shares.** Store the share password when adding the album, and recipients are never asked + for it. + +## Setup + +1. Set the environment (see `docker-compose.yml`) and start it with `docker compose up -d --build`. Mount a volume at + `/data`: it holds the SQLite database of recipients, sessions and comments. Back it up. +2. Open `/admin` and sign in with `ADMIN_PASSWORD`. +3. Under **Albums**, paste an Immich shared link (`https://immich.example.com/share/...` or `/s/`). +4. Under **Recipients**, add each person, tick their albums, and either email the invitation or copy the link. + +From a recipient's page you can send a new link, revoke every link and session they have, disable them, or delete +them. + +| Variable | | +| --- | --- | +| `IMMICH_URL` | Immich's internal URL, as upstream | +| `PUBLIC_BASE_URL` | This proxy's public URL. Needed for links in emails, and `https://` makes cookies `Secure` | +| `ADMIN_PASSWORD` | Turns on `/admin`. Without it there is no admin console | +| `SMTP_URL` or `SMTP_HOST` / `SMTP_PORT` / `SMTP_USER` / `SMTP_PASS` / `SMTP_SECURE` | Outgoing mail. Without it, no emails are sent; you copy links by hand | +| `MAIL_FROM` | Sender address, e.g. `Our photos ` | +| `SITE_NAME` | Name used in email subjects. Default `Shared photos` | +| `DIGEST_HOUR` | Hour (0-23) that notification emails go out. Default `8` | +| `TZ` | Timezone for `DIGEST_HOUR`. Default UTC | +| `NOTIFY_INTERVAL_MINUTES` | How often albums are checked for new photos. Default `60` | +| `DATA_DIR` | Database directory. `/data` in the image, `./data` otherwise | +| `TRUST_PROXY` | Express `trust proxy` setting. Default trusts private-network proxies | + +## Differences from upstream + +- Responses are cached `private` only, with no CORS header, so a CDN can't hand a photo to someone without a session. + If you set `ipp.responseHeaders` yourself, keep `Cache-Control` private. +- The gallery page is `private, no-cache`; `ipp.gallery.cacheTime` and `ipp.showHomePage` are no longer used. `/` + goes to the recipient's albums. +- `ipp.gallery.singleImage` defaults to `true`, so a one-photo share opens in the gallery where it can be commented on. +- `ipp.uploadUrl` defaults to off. The separate upload service (`upload-app/`) does not check magic-link sessions, + so don't route it unless you accept that anyone with a share key can upload. +- An Immich share link still works directly on Immich itself; this proxy only controls access through the proxy. + Keep Immich private, as upstream recommends. + +The rest of this README is upstream's. + +--- + # Immich Public Proxy

diff --git a/app/config.json b/app/config.json index 7ff9393..989eb46 100644 --- a/app/config.json +++ b/app/config.json @@ -7,7 +7,7 @@ "motionPhotos": true, "showHomePage": true, "allowSlugLinks": true, - "uploadUrl": "/upload", + "uploadUrl": "", "shareCacheTime": 120, "showMetadata": { "description": { @@ -44,7 +44,7 @@ "expiryDateLocale": "", "showDownloadZip": true, "groupByDate": false, - "singleImage": false, + "singleImage": true, "singleVideo": true, "singleItemAutoOpen": true, "cacheTime": 300 @@ -58,8 +58,7 @@ }, "customInvalidResponse": false, "responseHeaders": { - "Cache-Control": "public, max-age=2592000", - "Access-Control-Allow-Origin": "*" + "Cache-Control": "private, max-age=2592000" } } } diff --git a/app/package.json b/app/package.json index 8a9572a..0a8557a 100644 --- a/app/package.json +++ b/app/package.json @@ -28,6 +28,7 @@ "dayjs": "^1.11.13", "dotenv": "^16.4.5", "express": "^4.21.1", + "nodemailer": "^10.1.7", "preact": "^10.29.2", "tslib": "^2.8.1" }, @@ -36,6 +37,7 @@ "@types/cookie-session": "^2.0.49", "@types/express": "^4.17.21", "@types/node": "^22", + "@types/nodemailer": "^8.0.2", "@typescript-eslint/eslint-plugin": "^7", "@typescript-eslint/parser": "^7", "concurrently": "^10.0.3", diff --git a/app/public/style.css b/app/public/style.css index dabb922..33661ed 100644 --- a/app/public/style.css +++ b/app/public/style.css @@ -450,3 +450,114 @@ html.ipp-sidebar-open .ipp-sidebar { opacity: 0.6; text-align: center; } + +/* ============================================================================ + Comments, the last section of the sidebar + ============================================================================ */ + +.ipp-sidebar-comments { + border-top: 1px solid var(--color-gray); + margin-top: 8px; +} +.ipp-sidebar-comments-only { + border-top: none; + margin-top: 0; +} +.ipp-comments-list .ipp-sidebar-empty { + padding: 8px 0; + text-align: left; +} +.ipp-comment { + padding: 10px 0; + border-bottom: 1px solid rgba(127, 127, 127, 0.2); +} +.ipp-comment header { + display: flex; + align-items: baseline; + gap: 8px; + flex-wrap: wrap; +} +.ipp-comment time { + font-size: 12px; + opacity: 0.6; +} +.ipp-comment p { + margin: 4px 0 0; + white-space: pre-wrap; + word-break: break-word; +} +.ipp-comment-delete { + border: none; + background: none; + color: var(--color-fg); + opacity: 0.6; + font-size: 12px; + padding: 4px 0 0; + cursor: pointer; +} +.ipp-comment-delete:hover { + opacity: 1; + text-decoration: underline; +} +.ipp-comment-form { + display: flex; + flex-direction: column; + gap: 8px; + padding-top: 12px; +} +.ipp-comment-input { + width: 100%; + box-sizing: border-box; + resize: vertical; + min-height: 64px; + font: inherit; + color: var(--color-fg); + background: var(--color-bg); + border: 1px solid var(--color-gray); + border-radius: 8px; + padding: 8px 10px; +} +.ipp-comment-input:focus { + outline: 2px solid var(--color-primary); + outline-offset: -1px; +} +.ipp-comment-submit { + align-self: flex-end; + border: none; + border-radius: 999px; + padding: 6px 18px; + background: var(--color-primary); + color: var(--color-bg); + font: inherit; + font-weight: 500; + cursor: pointer; +} +.ipp-comment-submit:disabled { + opacity: 0.5; + cursor: default; +} +.ipp-comment-error { + margin: 0; + color: var(--color-danger); + font-size: 13px; +} + +/* Count badge on the lightbox's comments button */ +.pswp__button--comments-toggle { + position: relative; +} +.ipp-comment-badge { + position: absolute; + top: 8px; + right: 6px; + min-width: 16px; + height: 16px; + padding: 0 4px; + box-sizing: border-box; + border-radius: 8px; + background: var(--color-primary); + color: #fff; + font: 600 10px/16px var(--font-sans); + text-align: center; + pointer-events: none; +} diff --git a/app/src/client/comments.ts b/app/src/client/comments.ts new file mode 100644 index 0000000..c105aa2 --- /dev/null +++ b/app/src/client/comments.ts @@ -0,0 +1,205 @@ +// Comments thread for the current lightbox slide, rendered as a section of +// the info sidebar. Comment text is always set with textContent, never HTML. + +import { state } from './state.js' +import type { CommentView, GalleryItem } from '../shared/types.js' + +const MAX_LENGTH = 2000 + +// Comments already fetched, by asset id, so paging back and forth is instant +const loaded = new Map() +// Unsent text by asset id: the sidebar re-renders on slide change and when +// lazy metadata arrives, and that must not throw away what someone typed +const drafts = new Map() + +export function commentCount (assetId: string): number { + return state.comments?.counts[assetId] || 0 +} + +function setCount (assetId: string, count: number) { + if (state.comments) state.comments.counts[assetId] = count +} + +function url (assetId: string, commentId?: number): string { + return state.comments!.base + '/' + encodeURIComponent(assetId) + (commentId != null ? '/' + commentId : '') +} + +export function isTyping (target: EventTarget | null): boolean { + const el = target as HTMLElement | null + return !!el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable) +} + +const DATE_FORMAT: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeStyle: 'short' } + +function formatWhen (iso: string): string { + const date = new Date(iso) + return isNaN(date.getTime()) ? '' : date.toLocaleString(undefined, DATE_FORMAT) +} + +/** + * Build the comments section for a slide. `onCountChange` runs after a + * comment is added or removed, so the toolbar badge can follow. + */ +export function renderCommentsSection (item: GalleryItem, onCountChange: () => void, withHeading: boolean): HTMLElement { + const section = document.createElement('section') + section.className = 'ipp-sidebar-section ipp-sidebar-comments' + + if (withHeading) { + const heading = document.createElement('h3') + heading.className = 'ipp-sidebar-heading' + heading.textContent = 'Comments' + section.appendChild(heading) + } else { + section.classList.add('ipp-sidebar-comments-only') + } + + const list = document.createElement('div') + list.className = 'ipp-comments-list' + list.setAttribute('aria-live', 'polite') + section.appendChild(list) + + const form = document.createElement('form') + form.className = 'ipp-comment-form' + const input = document.createElement('textarea') + input.className = 'ipp-comment-input' + input.rows = 3 + input.maxLength = MAX_LENGTH + input.placeholder = 'Write a comment…' + input.setAttribute('aria-label', 'Write a comment') + input.value = drafts.get(item.id) || '' + const error = document.createElement('p') + error.className = 'ipp-comment-error' + error.hidden = true + const submit = document.createElement('button') + submit.type = 'submit' + submit.className = 'ipp-comment-submit' + submit.textContent = 'Post' + form.append(input, error, submit) + section.appendChild(form) + + input.addEventListener('input', () => { + if (input.value) drafts.set(item.id, input.value) + else drafts.delete(item.id) + }) + input.addEventListener('keydown', (e) => { + if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { + e.preventDefault() + form.requestSubmit() + } + }) + + const showError = (message: string) => { + error.textContent = message + error.hidden = false + } + + const renderList = (comments: CommentView[]) => { + list.replaceChildren() + if (!comments.length) { + const empty = document.createElement('p') + empty.className = 'ipp-sidebar-empty' + empty.textContent = 'No comments yet.' + list.appendChild(empty) + return + } + for (const comment of comments) list.appendChild(renderComment(comment)) + } + + const renderComment = (comment: CommentView): HTMLElement => { + const el = document.createElement('article') + el.className = 'ipp-comment' + const meta = document.createElement('header') + const author = document.createElement('strong') + author.textContent = comment.author + const when = document.createElement('time') + when.dateTime = comment.createdAt + when.textContent = formatWhen(comment.createdAt) + meta.append(author, when) + const body = document.createElement('p') + body.textContent = comment.body + el.append(meta, body) + if (comment.mine) { + const remove = document.createElement('button') + remove.type = 'button' + remove.className = 'ipp-comment-delete' + remove.textContent = 'Delete' + remove.addEventListener('click', async () => { + if (!confirm('Delete your comment?')) return + remove.disabled = true + const res = await fetch(url(item.id, comment.id), { method: 'DELETE' }).catch(() => null) + if (!res || (res.status !== 204 && res.status !== 404)) { + remove.disabled = false + showError('Couldn\'t delete the comment. Try again.') + return + } + const remaining = (loaded.get(item.id) || []).filter(c => c.id !== comment.id) + loaded.set(item.id, remaining) + setCount(item.id, remaining.length) + renderList(remaining) + onCountChange() + }) + el.appendChild(remove) + } + return el + } + + form.addEventListener('submit', async (e) => { + e.preventDefault() + const text = input.value.trim() + if (!text) return + submit.disabled = true + error.hidden = true + try { + const res = await fetch(url(item.id), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ body: text }) + }) + const data = await res.json().catch(() => ({})) + if (res.status !== 201) { + showError(data?.error || 'Couldn\'t post the comment. Try again.') + return + } + const comments = [...(loaded.get(item.id) || []), data as CommentView] + loaded.set(item.id, comments) + setCount(item.id, comments.length) + drafts.delete(item.id) + input.value = '' + renderList(comments) + onCountChange() + } catch { + showError('Couldn\'t post the comment. Check your connection.') + } finally { + submit.disabled = false + } + }) + + const cached = loaded.get(item.id) + if (cached) { + renderList(cached) + } else if (!commentCount(item.id) && !state.sidebarOpen) { + // Nothing when the page loaded, and nobody's looking: skip the request + renderList([]) + } else { + const loading = document.createElement('p') + loading.className = 'ipp-sidebar-empty' + loading.textContent = 'Loading comments…' + list.appendChild(loading) + fetch(url(item.id), { cache: 'no-store' }) + .then(res => res.ok ? res.json() : Promise.reject(new Error(String(res.status)))) + .then((comments: CommentView[]) => { + loaded.set(item.id, comments) + if (commentCount(item.id) !== comments.length) { + setCount(item.id, comments.length) + onCountChange() + } + renderList(comments) + }) + .catch(() => { + list.replaceChildren() + showError('Couldn\'t load comments.') + }) + } + + return section +} diff --git a/app/src/client/icons.ts b/app/src/client/icons.ts index 3abb272..3f596c0 100644 --- a/app/src/client/icons.ts +++ b/app/src/client/icons.ts @@ -18,6 +18,7 @@ export const ICON_INFO = ' ({ - ...basePadding, - right: state.sidebarOpen && window.innerWidth >= MOBILE_BREAKPOINT - ? SIDEBAR_WIDTH + basePadding.right - : basePadding.right - }), + // slide viewport: from the right when docked, and from the bottom when it + // is a bottom sheet on a narrow viewport, so the photo stays in view above + // the comments. + paddingFn: () => { + const narrow = window.innerWidth < MOBILE_BREAKPOINT + return { + ...basePadding, + right: state.sidebarOpen && !narrow ? SIDEBAR_WIDTH + basePadding.right : basePadding.right, + bottom: state.sidebarOpen && narrow + ? Math.round(window.innerHeight * SIDEBAR_SHEET_FRACTION) + basePadding.bottom + : basePadding.bottom + } + }, dataSource: buildDataSource(), // @ts-expect-error - runtime URL resolved by Express static pswpModule: () => import('/share/static/photoswipe/photoswipe.esm.js') // eslint-disable-line import/no-absolute-path diff --git a/app/src/client/sidebar.ts b/app/src/client/sidebar.ts index 7eb1b66..36a94ef 100644 --- a/app/src/client/sidebar.ts +++ b/app/src/client/sidebar.ts @@ -5,9 +5,15 @@ // by the toolbar info button or the `i` key, persisted via localStorage. import { state, SIDEBAR_STORAGE_KEY } from './state.js' -import { ICON_INFO, ICON_CLOSE, ICON_IMAGE, ICON_CALENDAR, ICON_CAMERA, ICON_IRIS, ICON_MAP } from './icons.js' +import { ICON_INFO, ICON_CLOSE, ICON_COMMENT, ICON_IMAGE, ICON_CALENDAR, ICON_CAMERA, ICON_IRIS, ICON_MAP } from './icons.js' +import { commentCount, isTyping, renderCommentsSection } from './comments.js' import type { GalleryItem, GalleryExif } from '../shared/types.js' +// Re-renders the sidebar for the current slide; set while the lightbox is open +let rerender: (() => void) | undefined +// Updates the comment-count badge on the toolbar button +let updateCommentBadge: (() => void) | undefined + // eslint-disable-next-line @typescript-eslint/no-explicit-any type LightboxInstance = any // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -37,19 +43,57 @@ export function registerSidebar (lightbox: LightboxInstance) { appendTo: 'root', onInit: (el: HTMLElement, pswp: PswpInstance) => { el.classList.add('ipp-sidebar') - el.setAttribute('aria-label', 'Photo information') + el.setAttribute('aria-label', state.comments ? 'Photo information and comments' : 'Photo information') const renderSidebar = () => renderContents(el, state.items[pswp.currIndex]) + rerender = renderSidebar renderSidebar() pswp.on('change', renderSidebar) // Re-render when a lazy album item's detail arrives after open. state.slideRefreshers.push(renderSidebar) pswp.on('destroy', () => { document.documentElement.classList.remove('ipp-sidebar-open') + rerender = undefined + updateCommentBadge = undefined + }) + // Typing a comment must not page through slides or close the lightbox + pswp.on('keydown', (e: { originalEvent: KeyboardEvent, preventDefault: () => void }) => { + if (isTyping(e.originalEvent.target)) e.preventDefault() }) applyOpenState(pswp) } } as PswpUiElementConfig) + if (state.comments) { + lightbox.pswp.ui.registerElement({ + name: 'comments-toggle', + order: 8, + isButton: true, + ariaLabel: 'Comments', + html: ICON_COMMENT + '', + onInit: (el: HTMLElement, pswp: PswpInstance) => { + const badge = el.querySelector('.ipp-comment-badge') as HTMLElement + const update = () => { + const count = commentCount(state.items[pswp.currIndex]?.id || '') + badge.textContent = count > 99 ? '99+' : String(count) + badge.hidden = count === 0 + el.setAttribute('aria-label', count ? 'Comments (' + count + ')' : 'Comments') + } + updateCommentBadge = update + update() + pswp.on('change', update) + el.addEventListener('click', () => { + setSidebarOpen(pswp, true) + const section = document.querySelector('.ipp-sidebar-comments') + section?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }) + // On touch screens focusing would throw the keyboard up over the photo + if (window.matchMedia('(pointer: fine)').matches) { + (section?.querySelector('.ipp-comment-input') as HTMLTextAreaElement | null)?.focus({ preventScroll: true }) + } + }) + } + } as PswpUiElementConfig) + } + lightbox.pswp.ui.registerElement({ name: 'sidebar-toggle', order: 7, @@ -72,11 +116,9 @@ export function registerSidebar (lightbox: LightboxInstance) { // keypress hook for arbitrary keys. window.addEventListener('keydown', (e) => { if (!state.lightbox || !state.lightbox.pswp) return + // Leave keys alone while someone types a comment + if (isTyping(e.target)) return if (e.key === 'i' || e.key === 'I') { - // Don't steal `i` from text inputs (none exist in the lightbox today, - // but better safe). - const target = e.target as HTMLElement | null - if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return e.preventDefault() toggleSidebar(state.lightbox.pswp) } else if (e.key === 'Escape' && state.sidebarOpen) { @@ -96,6 +138,8 @@ function setSidebarOpen (pswp: PswpInstance, open: boolean) { state.sidebarOpen = open writePersistedState(open) applyOpenState(pswp) + // Opening fetches the comments, which are skipped while it's closed + if (open && state.comments) rerender?.() } function applyOpenState (pswp: PswpInstance) { @@ -133,9 +177,10 @@ function renderContents (root: HTMLElement, item: GalleryItem | undefined) { root.replaceChildren() if (!item) return - root.appendChild(renderHeader()) - const showDescription = state.metadataConfig.descriptionInSidebar && !!item.description + const metadataShown = showDescription || !!(item.exif && (hasAnyExifField(item.exif) || hasAnyLocationField(item.exif))) + root.appendChild(renderHeader(state.comments && !metadataShown ? 'Comments' : 'Info')) + if (showDescription && item.description) { root.appendChild(renderSection('description', renderDescription(item.description))) } @@ -149,8 +194,9 @@ function renderContents (root: HTMLElement, item: GalleryItem | undefined) { root.appendChild(renderSection('location', renderLocation(exif))) } - const noExifShown = !exif || (!hasAnyExifField(exif) && !hasAnyLocationField(exif)) - if (!showDescription && noExifShown) { + if (state.comments) { + root.appendChild(renderCommentsSection(item, () => updateCommentBadge?.(), metadataShown)) + } else if (!metadataShown) { const empty = document.createElement('p') empty.className = 'ipp-sidebar-empty' empty.textContent = 'No metadata available' @@ -158,13 +204,13 @@ function renderContents (root: HTMLElement, item: GalleryItem | undefined) { } } -function renderHeader (): HTMLElement { +function renderHeader (titleText: string): HTMLElement { const header = document.createElement('header') header.className = 'ipp-sidebar-header' const close = document.createElement('button') close.type = 'button' close.className = 'ipp-sidebar-close' - close.setAttribute('aria-label', 'Close info') + close.setAttribute('aria-label', 'Close ' + titleText.toLowerCase()) close.innerHTML = ICON_CLOSE close.addEventListener('click', () => { if (state.lightbox && state.lightbox.pswp) setSidebarOpen(state.lightbox.pswp, false) @@ -172,7 +218,7 @@ function renderHeader (): HTMLElement { header.appendChild(close) const title = document.createElement('span') title.className = 'ipp-sidebar-title' - title.textContent = 'Info' + title.textContent = titleText header.appendChild(title) return header } diff --git a/app/src/client/state.ts b/app/src/client/state.ts index 2feac04..3494b02 100644 --- a/app/src/client/state.ts +++ b/app/src/client/state.ts @@ -3,7 +3,7 @@ // top-level `let`s. Layout / scroll-tuning constants live here too because // they are read by multiple modules. SVG icon strings live in `icons.ts`. -import type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types.js' +import type { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types.js' // ----- layout / scroll tuning ---------------------------------------------- @@ -28,6 +28,8 @@ export const LONG_PRESS_MS = 500 export const SIDEBAR_STORAGE_KEY = 'ipp-sidebar-open' // Width of the sidebar when docked (must match the CSS rule) export const SIDEBAR_WIDTH = 360 +// Height of the sidebar as a bottom sheet, as a fraction of the viewport (must match the CSS 60vh) +export const SIDEBAR_SHEET_FRACTION = 0.6 // ----- mutable state ------------------------------------------------------- @@ -95,6 +97,8 @@ export const state = { sidebarOpen: false, // Base URL (`/share/meta/`) for the on-demand per-asset metadata route. metaBase: '', + // Comments API and per-photo counts; null when commenting isn't available + comments: null as CommentsConfig | null, // Re-render callbacks registered by lightbox UI elements (sidebar, caption, // download button). Each re-renders for the current slide. Invoked after a // lazy item's detail arrives so the just-opened slide reflects it. diff --git a/app/src/gallery/builder.ts b/app/src/gallery/builder.ts index 51674cc..5270f36 100644 --- a/app/src/gallery/builder.ts +++ b/app/src/gallery/builder.ts @@ -1,4 +1,4 @@ -import { AssetType, getConfigOption, getNumericConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core' +import { AssetType, getConfigOption, renderPage, SharedLink, title, toString } from '@ipp/core' import { getVideoContentType, photoUrl, @@ -13,6 +13,7 @@ import { downloadFilename, positionInShare } from './filename' import { groupByDateMode } from './order' import { requiresOriginal } from './sizing' import { displayDimensions, metadataGroupActive, pickExif } from './exif' +import { getStore } from '../magic/store' /** * Render a gallery page for a given SharedLink. @@ -44,7 +45,13 @@ 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) - const sidebarHasContent = shareMetadataAllowed && (descriptionInSidebar || metadataGroupActive('exif') || metadataGroupActive('location')) + // A signed-in recipient can comment, which lives in the sidebar too + const viewer = res.req.recipient + const comments = viewer + ? { base: '/share/comments/' + share.key, counts: getStore().countComments(share.key) } + : undefined + const sidebarHasContent = !!comments || + (shareMetadataAllowed && (descriptionInSidebar || metadataGroupActive('exif') || metadataGroupActive('location'))) const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset, index): Promise => { let videoData: string | undefined @@ -152,14 +159,17 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb groupByDate, metaBase, uploadLink: uploadLink(share), - uploadHealthcheck: uploadHealthcheck() + uploadHealthcheck: uploadHealthcheck(), + comments, + accountLink: viewer ? '/me' : undefined } - // HTML gallery page cache time. A password-protected gallery keeps the - // no-store that handleShareRequest set. + // The page is per-viewer (comment counts, account link) and behind a + // session, so it must never sit in a shared cache, and the browser should + // recheck it so new photos and comments show up. A password-protected + // gallery keeps the no-store that handleShareRequest set. if (!share.password) { - const cacheTime = Math.max(0, getNumericConfigOption('ipp.gallery.cacheTime', 300)) - res.header('Cache-Control', 'public, max-age=' + cacheTime) + res.header('Cache-Control', 'private, no-cache') } res.send(renderPage(h(Gallery, props))) } diff --git a/app/src/index.ts b/app/src/index.ts index 45fd500..12f4cf5 100644 --- a/app/src/index.ts +++ b/app/src/index.ts @@ -1,46 +1,13 @@ #!/usr/bin/env node import 'dotenv/config' -import express from 'express' import { resolve } from 'path' -import { - addNoStoreHeaders, - addResponseHeaders, - Asset, - AssetType, - asyncHandler, - CORE_PUBLIC_DIR, - decodeCookie, - enforceMinimumImmichVersion, - errorHandler, - getConfigOption, - getKeyTypeFromShare, - healthcheck, - isId, - isKey, - KeyType, - loadConfig, - renderPage, - respondToInvalidRequest, - sessionMiddleware, - setInvalidRequestHandler, - SharedLink, - slugLinksDisabled, - unlockHandler -} from '@ipp/core' -import { fetchAssetDetail, getShareByKey, handleShareRequest } from './immich' -import { buildAssetMetadata } from './gallery/metadata' -import { removedMetadataSwitches } from './gallery/exif' -import { assetBuffer } from './stream/asset' -import { downloadAssets } from './stream/download' import dayjs from 'dayjs' -import { Request } from 'express-serve-static-core' -import { ImageSize } from './types' -import { canDownload, findMotionPhotoStill, uploadHealthcheck } from './share' +import { enforceMinimumImmichVersion, loadConfig, log, setInvalidRequestHandler } from '@ipp/core' +import { removedMetadataSwitches } from './gallery/exif' import { respondToInvalidRequest as ippInvalidRequestHandler } from './invalidRequestHandler' -import { ASSET_VERSION } from './version' -import { h } from 'preact' -import { Home } from './view/home' +import { createApp } from './server' +import { startNotificationScheduler } from './magic/digest' /* Must run before any code that calls getConfigOption. The bundled @@ -64,271 +31,7 @@ if (removedSwitches.length) { */ setInvalidRequestHandler(ippInvalidRequestHandler) -const app = express() -app.use(sessionMiddleware({ name: 'session' })) -// For parsing the password unlock form and POSTed JSON payloads -app.use(express.json()) -// For parsing the selective-download form POST (form-encoded body) -app.use(express.urlencoded({ extended: false, limit: '1mb' })) - -/** Serve IPP's own `public` folder, then core's, at `path`. */ -function serveStatic (path: string, options: Parameters[1] = {}) { - for (const dir of ['public', CORE_PUBLIC_DIR]) { - app.use(path, express.static(dir, { ...options, setHeaders: addResponseHeaders })) - } -} - -// Cache-busted, immutable static assets under a per-release version segment. -const inProduction = process.env.NODE_ENV === 'production' -serveStatic('/share/static/' + ASSET_VERSION, { immutable: inProduction, maxAge: inProduction ? '365d' : 0 }) -serveStatic('/share/static') -// The same assets on /, to allow for /robots.txt and /favicon.ico -serveStatic('/') -app.disable('x-powered-by') - -/* - Shared route guards. Several routes need the same "resolve a share, reject - invalid / password-protected ones, optionally find the requested asset" - preamble. These return a discriminated result so each route keeps control of - its own response (e.g. the photo route redirects on password where the meta - and download routes return 401), while the validation order and the - `valid`/`link`/`passwordRequired` checks live in one place. -*/ -type ShareResolution = - | { ok: true, link: SharedLink } - | { ok: false, status: number, reason: string, passwordRequired?: boolean } - -type SharedAssetResolution = - | { ok: true, link: SharedLink, asset: Asset } - | { ok: false, status: number, reason: string, passwordRequired?: boolean } - -async function resolveShare (req: Request, keyType: KeyType): Promise { - if (slugLinksDisabled(keyType)) { - return { ok: false, status: 404, reason: 'Slug links are disabled in config.json' } - } - if (!isKey(req.params.key)) { - return { ok: false, status: 404, reason: 'Invalid key for ' + req.path } - } - // The password is provided from the encrypted session cookie (if set) by - // decodeCookie. Validating the share here prevents direct URL access from - // bypassing password protection. - const share = await getShareByKey(req.params.key, req.password, keyType) - if (!share?.valid || !share.link) { - return { ok: false, status: 404, reason: 'Invalid share link' } - } - if (share.passwordRequired) { - return { ok: false, status: 401, reason: 'Password required', passwordRequired: true } - } - return { ok: true, link: share.link } -} - -async function resolveSharedAsset (req: Request, keyType: KeyType, allowMotion = false): Promise { - if (!isId(req.params.id)) { - return { ok: false, status: 404, reason: 'Invalid ID for ' + req.path } - } - const resolved = await resolveShare(req, keyType) - if (!resolved.ok) return resolved - // Confirm the asset belongs to this share (defence in depth - Immich also - // enforces this via the share key). - const asset = resolved.link.assets.find(a => a.id === req.params.id) - if (asset) return { ok: true, link: resolved.link, asset } - // A motion photo's clip is a hidden asset outside the share's asset list. - // Serve it on the video route only, and only if a shared still points at it. - if (allowMotion) { - const parent = findMotionPhotoStill(resolved.link, req.params.id) - if (parent) { - return { - ok: true, - link: resolved.link, - // Streams inline, so the still's filename / mime must not carry over. - asset: { ...parent, id: req.params.id, type: AssetType.video, originalFileName: undefined, originalMimeType: undefined } - } - } - } - return { ok: false, status: 404, reason: 'Asset not found in share' } -} - -/* - [ROUTE] Healthcheck, on /share/healthcheck and the legacy /healthcheck -*/ -app.get(/^(|\/share)\/healthcheck$/, asyncHandler(healthcheck)) - -/* - [ROUTE] The upload service's healthcheck path, when the service is assumed - to be at a path on this hostname. The gallery page probes it before showing - the "Add photos" button. With the upload service routed in front of IPP the - probe never gets here; without it, this answers "nothing here" as a 204 - rather than a 404, so the probe is neither a console error in the browser - nor a hit on the 404 policy. -*/ -const uploadProbe = uploadHealthcheck() -if (uploadProbe) { - app.get(uploadProbe, (_req, res) => { - addNoStoreHeaders(res) - res.status(204).end() - }) -} - -/* - [ROUTE] The main URL a visitor opens from a shared link -*/ -app.get('/:shareType(share|s)/:key/:mode(download)?', decodeCookie, asyncHandler(async (req, res) => { - const keyType = getKeyTypeFromShare(req.params.shareType) - - if (slugLinksDisabled(keyType)) { - respondToInvalidRequest(res, 404, 'Slug links are disabled in config.json') - } else { - await handleShareRequest({ - req, - key: req.params.key, - keyType, - mode: req.params.mode, - password: req.password - }, res) - } -})) - -/* - [ROUTE] Password unlock from the password page -*/ -app.post('/share/unlock', unlockHandler) - -/* - [ROUTE] Selective download - POST a list of asset IDs, get a zip of just those. - The list arrives as a single "assets" form field containing a JSON array. - Validates each ID against share.assets so the request can't pull anything - outside the share. -*/ -app.post('/:shareType(share|s)/:key/download', decodeCookie, asyncHandler(async (req, res) => { - const keyType = getKeyTypeFromShare(req.params.shareType) - let requestedIds: unknown - try { - requestedIds = JSON.parse(String(req.body?.assets ?? '[]')) - } catch (e) { - respondToInvalidRequest(res, 400, 'Malformed assets list') - return - } - if (!Array.isArray(requestedIds) || requestedIds.length === 0) { - respondToInvalidRequest(res, 400, 'No assets selected') - return - } - - const resolved = await resolveShare(req, keyType) - if (!resolved.ok) { - respondToInvalidRequest(res, resolved.status, resolved.reason) - return - } - if (!canDownload(resolved.link)) { - respondToInvalidRequest(res, 403, 'Downloads disabled for this share') - return - } - - const requested = new Set(requestedIds.map(String)) - const validAssets = resolved.link.assets.filter(a => requested.has(a.id)) - if (validAssets.length === 0) { - respondToInvalidRequest(res, 400, 'No valid assets in selection') - return - } - - await downloadAssets(res, resolved.link, validAssets) -})) - -/* - [ROUTE] Catch accidental POST requests to share URLs (e.g. from browser history - state issues) and force a clean GET redirect. - See https://github.com/alangrainger/immich-public-proxy/pull/205 -*/ -app.post('/:shareType(share|s)/:key/:mode(download)?', (req, res) => { - res.redirect(303, req.originalUrl) -}) - -/* - [ROUTE] Direct link to a photo or video asset -*/ -app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, asyncHandler(async (req, res) => { - addResponseHeaders(res) - - if (req.params.size && !Object.values(ImageSize).includes(req.params.size as ImageSize)) { - respondToInvalidRequest(res, 404, 'Invalid size parameter ' + req.path) - return - } - - // Always key auth: this route has no slug form - const resolved = await resolveSharedAsset(req, KeyType.key, req.params.type === 'video') - if (!resolved.ok) { - // Password-protected: redirect to the share page so the visitor gets the - // unlock prompt, rather than returning an error. - if (resolved.passwordRequired) { - res.redirect('/share/' + req.params.key) - return - } - respondToInvalidRequest(res, resolved.status, resolved.reason) - return - } - if (resolved.link.password) addNoStoreHeaders(res) - const asset: Asset = { - ...resolved.asset, - type: req.params.type === 'video' ? AssetType.video : resolved.asset.type - } - - const request = { - req, - key: req.params.key, - range: req.headers.range || '' - } - await assetBuffer(request, res, asset, req.params.size, resolved.link, req.params.type === 'video') -})) - -/* - [ROUTE] On-demand per-asset metadata for lazy album items. - - Album shares enumerate their assets from the timeline API, which yields - grid-only data (no exif / filename / description). When such an item opens - in the lightbox, the client fetches its detail from here. The id is - 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', decodeCookie, asyncHandler(async (req, res) => { - addResponseHeaders(res) - - const resolved = await resolveSharedAsset(req, getKeyTypeFromShare(req.params.shareType)) - if (!resolved.ok) { - respondToInvalidRequest(res, resolved.status, resolved.reason) - return - } - - if (resolved.link.password) addNoStoreHeaders(res) - - const detail = await fetchAssetDetail(resolved.asset) - if (!detail) { - respondToInvalidRequest(res, 404, 'Asset detail unavailable for ' + req.params.id) - return - } - - res.json(buildAssetMetadata(detail, resolved.link)) -})) - -/* - [ROUTE] Home page, so the root shows *something*, as requested in - https://github.com/alangrainger/immich-public-proxy/discussions/19. - Turned off by https://docs.ipp.nz/config/ipp-options#showhomepage -*/ -if (getConfigOption('ipp.showHomePage', true)) { - app.get(/^\/(|share)\/*$/, (_req, res) => { - addResponseHeaders(res) - res.send(renderPage(h(Home, {}))) - }) -} - -/* - [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. -*/ -app.all('*', (req, res) => { - respondToInvalidRequest(res, 404, 'Invalid route ' + req.path) -}) - -app.use(errorHandler) +const app = createApp() // Exit non-zero on an uncaught exception, so Docker restarts the container process.on('uncaughtException', (err) => { @@ -353,5 +56,7 @@ process.on('SIGTERM', () => { const port = Number(process.env.IPP_PORT) || 3000 const server = app.listen(port, () => { console.log(dayjs().format() + ' Server started on port ' + port) + if (!process.env.ADMIN_PASSWORD) log.warn('ADMIN_PASSWORD is not set, so the /admin console is off') enforceMinimumImmichVersion().catch(e => console.error('Immich version check failed:', e)) + startNotificationScheduler() }) diff --git a/app/src/magic/admin.ts b/app/src/magic/admin.ts new file mode 100644 index 0000000..82600c5 --- /dev/null +++ b/app/src/magic/admin.ts @@ -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({ 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())) + })) +} diff --git a/app/src/magic/digest.ts b/app/src/magic/digest.ts new file mode 100644 index 0000000..08f0d85 --- /dev/null +++ b/app/src/magic/digest.ts @@ -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 + +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>> { + const current = new Map>() + 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 | 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>): Promise { + 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>): Promise { + 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() +} diff --git a/app/src/magic/mailer.ts b/app/src/magic/mailer.ts new file mode 100644 index 0000000..b34117b --- /dev/null +++ b/app/src/magic/mailer.ts @@ -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 + +/** 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 { + 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, '"') +} + +function htmlDocument (body: string): string { + return '' + + body + '' +} + +const button = (url: string, label: string) => + `

${escapeHtml(label)}

` + +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( + `

Hi ${escapeHtml(input.name)},

` + + `

You've been given access to ${albumList.map(escapeHtml).join(', ')}.

` + + button(input.link, 'View photos') + + '

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.

' + ) + } +} + +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( + `

Hi ${escapeHtml(input.name)},

` + + button(input.link, 'Sign in') + + '

This link works for 7 days. If you didn\'t ask for it, you can ignore this email.

' + ) + } +} + +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( + `

Hi ${escapeHtml(input.name)},

` + + input.sections.map(s => + `

${escapeHtml(plural(s.count))} in ${escapeHtml(s.title)}

` + button(s.link, 'View ' + s.title) + ).join('') + + `

Change how often you get these emails

` + ) + } +} diff --git a/app/src/magic/routes.ts b/app/src/magic/routes.ts new file mode 100644 index 0000000..de8a938 --- /dev/null +++ b/app/src/magic/routes.ts @@ -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({ ttlMs: 60 * 60_000, max: 5000 }) +const commentsByRecipient = new TtlLruCache({ 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() + }) +} diff --git a/app/src/magic/session.ts b/app/src/magic/session.ts new file mode 100644 index 0000000..798042c --- /dev/null +++ b/app/src/magic/session.ts @@ -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() +} diff --git a/app/src/magic/store.ts b/app/src/magic/store.ts new file mode 100644 index 0000000..dd188b5 --- /dev/null +++ b/app/src/magic/store.ts @@ -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 + +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 { + 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 + } + + 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 { + 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 { + 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 { + 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 + } + + deleteComment (id: number) { + this.db.prepare('DELETE FROM comments WHERE id = ?').run(id) + } +} + +let store: Store | undefined + +/** `/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 +} diff --git a/app/src/magic/tokens.ts b/app/src/magic/tokens.ts new file mode 100644 index 0000000..1a544e3 --- /dev/null +++ b/app/src/magic/tokens.ts @@ -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 +} diff --git a/app/src/magic/views.tsx b/app/src/magic/views.tsx new file mode 100644 index 0000000..8e49920 --- /dev/null +++ b/app/src/magic/views.tsx @@ -0,0 +1,371 @@ +import { ComponentChildren } from 'preact' +import { CommentRecord, Frequency, FREQUENCIES, Recipient, ShareRecord } from './store' + +const FREQUENCY_LABELS: Record = { + 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 ( + + + + + + {title} + + +