Gate shares behind magic-link sessions, add comments and new-photo email digests

This commit is contained in:
zyphlar
2026-10-19 15:10:57 -07:00
parent c8d8dc9dbc
commit f598200e24
34 changed files with 3387 additions and 375 deletions
+2
View File
@@ -9,3 +9,5 @@
/upload-app/dist/ /upload-app/dist/
/upload-app/public/js/ /upload-app/public/js/
/upload-app/.env /upload-app/.env
/data/
/app/data/
+2
View File
@@ -8,3 +8,5 @@ app/public/js/
.npm-cache/ .npm-cache/
*.tsbuildinfo *.tsbuildinfo
upload-app/public/js/ upload-app/public/js/
/data/
/app/data/
+5 -1
View File
@@ -47,13 +47,17 @@ COPY --from=builder --chown=root:root /ipp/app/public ./public
COPY --from=builder --chown=root:root /ipp/app/config.json ./ 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 # 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. # is for buildah, which keeps the builder's owner on COPY --from.
RUN mkdir /data && chown node:node /data
VOLUME /data
USER node USER node
ARG PACKAGE_VERSION ARG PACKAGE_VERSION
ENV APP_VERSION=${PACKAGE_VERSION} ENV APP_VERSION=${PACKAGE_VERSION}
ENV NODE_ENV=production ENV NODE_ENV=production
ENV DATA_DIR=/data
# tini as PID 1 reaps orphaned healthcheck processes, which node does not (GitHub #66). # 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`). # -s keeps reaping, without a warning, when PID 1 is already an init (compose `init: true`).
+62
View File
@@ -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/<slug>`).
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 <photos@example.com>` |
| `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 # Immich Public Proxy
<p align="center" width="100%"> <p align="center" width="100%">
+3 -4
View File
@@ -7,7 +7,7 @@
"motionPhotos": true, "motionPhotos": true,
"showHomePage": true, "showHomePage": true,
"allowSlugLinks": true, "allowSlugLinks": true,
"uploadUrl": "/upload", "uploadUrl": "",
"shareCacheTime": 120, "shareCacheTime": 120,
"showMetadata": { "showMetadata": {
"description": { "description": {
@@ -44,7 +44,7 @@
"expiryDateLocale": "", "expiryDateLocale": "",
"showDownloadZip": true, "showDownloadZip": true,
"groupByDate": false, "groupByDate": false,
"singleImage": false, "singleImage": true,
"singleVideo": true, "singleVideo": true,
"singleItemAutoOpen": true, "singleItemAutoOpen": true,
"cacheTime": 300 "cacheTime": 300
@@ -58,8 +58,7 @@
}, },
"customInvalidResponse": false, "customInvalidResponse": false,
"responseHeaders": { "responseHeaders": {
"Cache-Control": "public, max-age=2592000", "Cache-Control": "private, max-age=2592000"
"Access-Control-Allow-Origin": "*"
} }
} }
} }
+2
View File
@@ -28,6 +28,7 @@
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.21.1", "express": "^4.21.1",
"nodemailer": "^10.1.7",
"preact": "^10.29.2", "preact": "^10.29.2",
"tslib": "^2.8.1" "tslib": "^2.8.1"
}, },
@@ -36,6 +37,7 @@
"@types/cookie-session": "^2.0.49", "@types/cookie-session": "^2.0.49",
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/node": "^22", "@types/node": "^22",
"@types/nodemailer": "^8.0.2",
"@typescript-eslint/eslint-plugin": "^7", "@typescript-eslint/eslint-plugin": "^7",
"@typescript-eslint/parser": "^7", "@typescript-eslint/parser": "^7",
"concurrently": "^10.0.3", "concurrently": "^10.0.3",
+111
View File
@@ -450,3 +450,114 @@ html.ipp-sidebar-open .ipp-sidebar {
opacity: 0.6; opacity: 0.6;
text-align: center; 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;
}
+205
View File
@@ -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<string, CommentView[]>()
// 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<string, string>()
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
}
+1
View File
@@ -18,6 +18,7 @@ export const ICON_INFO = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden
export const ICON_BACK = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z"/></svg>' export const ICON_BACK = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z"/></svg>'
// Motion photo (Live Photo) toggle, off / on. Same pair as Immich's viewer. // Motion photo (Live Photo) toggle, off / on. Same pair as Immich's viewer.
export const ICON_MOTION_PLAY = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M10 16.5L16 12L10 7.5M22 12C22 6.46 17.54 2 12 2C10.83 2 9.7 2.19 8.62 2.56L9.32 4.5C10.17 4.16 11.06 3.97 12 3.97C16.41 3.97 20.03 7.59 20.03 12C20.03 16.41 16.41 20.03 12 20.03C7.59 20.03 3.97 16.41 3.97 12C3.97 11.06 4.16 10.12 4.5 9.28L2.56 8.62C2.19 9.7 2 10.83 2 12C2 17.54 6.46 22 12 22C17.54 22 22 17.54 22 12M5.47 3.97C6.32 3.97 7 4.68 7 5.47C7 6.32 6.32 7 5.47 7C4.68 7 3.97 6.32 3.97 5.47C3.97 4.68 4.68 3.97 5.47 3.97Z"/></svg>' export const ICON_MOTION_PLAY = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M10 16.5L16 12L10 7.5M22 12C22 6.46 17.54 2 12 2C10.83 2 9.7 2.19 8.62 2.56L9.32 4.5C10.17 4.16 11.06 3.97 12 3.97C16.41 3.97 20.03 7.59 20.03 12C20.03 16.41 16.41 20.03 12 20.03C7.59 20.03 3.97 16.41 3.97 12C3.97 11.06 4.16 10.12 4.5 9.28L2.56 8.62C2.19 9.7 2 10.83 2 12C2 17.54 6.46 22 12 22C17.54 22 22 17.54 22 12M5.47 3.97C6.32 3.97 7 4.68 7 5.47C7 6.32 6.32 7 5.47 7C4.68 7 3.97 6.32 3.97 5.47C3.97 4.68 4.68 3.97 5.47 3.97Z"/></svg>'
export const ICON_COMMENT = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M9,22A1,1 0 0,1 8,21V18H4A2,2 0 0,1 2,16V4C2,2.89 2.9,2 4,2H20A2,2 0 0,1 22,4V16A2,2 0 0,1 20,18H13.9L10.2,21.71C10,21.9 9.75,22 9.5,22H9M10,16V19.08L13.08,16H20V4H4V16H10Z"/></svg>'
export const ICON_MOTION_PAUSE = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M22 12C22 6.46 17.54 2 12 2C10.83 2 9.7 2.19 8.62 2.56L9.32 4.5C10.17 4.16 11.06 3.97 12 3.97C16.41 3.97 20.03 7.59 20.03 12C20.03 16.41 16.41 20.03 12 20.03C7.59 20.03 3.97 16.41 3.97 12C3.97 11.06 4.16 10.12 4.5 9.28L2.56 8.62C2.19 9.7 2 10.83 2 12C2 17.54 6.46 22 12 22C17.54 22 22 17.54 22 12M5.47 7C4.68 7 3.97 6.32 3.97 5.47C3.97 4.68 4.68 3.97 5.47 3.97C6.32 3.97 7 4.68 7 5.47C7 6.32 6.32 7 5.47 7M9 9H11V15H9M13 9H15V15H13"/></svg>' export const ICON_MOTION_PAUSE = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M22 12C22 6.46 17.54 2 12 2C10.83 2 9.7 2.19 8.62 2.56L9.32 4.5C10.17 4.16 11.06 3.97 12 3.97C16.41 3.97 20.03 7.59 20.03 12C20.03 16.41 16.41 20.03 12 20.03C7.59 20.03 3.97 16.41 3.97 12C3.97 11.06 4.16 10.12 4.5 9.28L2.56 8.62C2.19 9.7 2 10.83 2 12C2 17.54 6.46 22 12 22C17.54 22 22 17.54 22 12M5.47 7C4.68 7 3.97 6.32 3.97 5.47C3.97 4.68 4.68 3.97 5.47 3.97C6.32 3.97 7 4.68 7 5.47C7 6.32 6.32 7 5.47 7M9 9H11V15H9M13 9H15V15H13"/></svg>'
export const ICON_CLOSE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"/></svg>' export const ICON_CLOSE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"/></svg>'
+1
View File
@@ -48,6 +48,7 @@ function init () {
if (params.metadataConfig) state.metadataConfig = params.metadataConfig if (params.metadataConfig) state.metadataConfig = params.metadataConfig
state.groupByDate = params.groupByDate || false state.groupByDate = params.groupByDate || false
state.metaBase = params.metaBase || '' state.metaBase = params.metaBase || ''
state.comments = params.comments || null
state.container = document.getElementById('gallery') state.container = document.getElementById('gallery')
if (!state.container) return if (!state.container) return
+13 -8
View File
@@ -7,7 +7,7 @@
import PhotoSwipeLightbox from '/share/static/photoswipe/photoswipe-lightbox.esm.js' // eslint-disable-line import/no-absolute-path import PhotoSwipeLightbox from '/share/static/photoswipe/photoswipe-lightbox.esm.js' // eslint-disable-line import/no-absolute-path
import type { PhotoSwipeOptions } from 'photoswipe' import type { PhotoSwipeOptions } from 'photoswipe'
import { state, SIDEBAR_WIDTH, MOBILE_BREAKPOINT } from './state.js' import { state, SIDEBAR_WIDTH, SIDEBAR_SHEET_FRACTION, MOBILE_BREAKPOINT } from './state.js'
import type { GalleryItem } from '../shared/types.js' import type { GalleryItem } from '../shared/types.js'
import { import {
registerBackButton, registerBackButton,
@@ -211,14 +211,19 @@ export function initLightbox () {
// precedence over `padding`, and spreading it last neutralises any `padding` // precedence over `padding`, and spreading it last neutralises any `padding`
// or (mistyped) `paddingFn` an operator put in config. Their static `padding` // or (mistyped) `paddingFn` an operator put in config. Their static `padding`
// is still honoured above via basePadding. It lets the sidebar shrink the // is still honoured above via basePadding. It lets the sidebar shrink the
// slide viewport when docked; on a narrow viewport the sidebar overlays // slide viewport: from the right when docked, and from the bottom when it
// instead, so we leave padding alone there. // is a bottom sheet on a narrow viewport, so the photo stays in view above
paddingFn: () => ({ // the comments.
paddingFn: () => {
const narrow = window.innerWidth < MOBILE_BREAKPOINT
return {
...basePadding, ...basePadding,
right: state.sidebarOpen && window.innerWidth >= MOBILE_BREAKPOINT right: state.sidebarOpen && !narrow ? SIDEBAR_WIDTH + basePadding.right : basePadding.right,
? SIDEBAR_WIDTH + basePadding.right bottom: state.sidebarOpen && narrow
: basePadding.right ? Math.round(window.innerHeight * SIDEBAR_SHEET_FRACTION) + basePadding.bottom
}), : basePadding.bottom
}
},
dataSource: buildDataSource(), dataSource: buildDataSource(),
// @ts-expect-error - runtime URL resolved by Express static // @ts-expect-error - runtime URL resolved by Express static
pswpModule: () => import('/share/static/photoswipe/photoswipe.esm.js') // eslint-disable-line import/no-absolute-path pswpModule: () => import('/share/static/photoswipe/photoswipe.esm.js') // eslint-disable-line import/no-absolute-path
+59 -13
View File
@@ -5,9 +5,15 @@
// by the toolbar info button or the `i` key, persisted via localStorage. // by the toolbar info button or the `i` key, persisted via localStorage.
import { state, SIDEBAR_STORAGE_KEY } from './state.js' 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' 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 // eslint-disable-next-line @typescript-eslint/no-explicit-any
type LightboxInstance = any type LightboxInstance = any
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -37,19 +43,57 @@ export function registerSidebar (lightbox: LightboxInstance) {
appendTo: 'root', appendTo: 'root',
onInit: (el: HTMLElement, pswp: PswpInstance) => { onInit: (el: HTMLElement, pswp: PswpInstance) => {
el.classList.add('ipp-sidebar') 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]) const renderSidebar = () => renderContents(el, state.items[pswp.currIndex])
rerender = renderSidebar
renderSidebar() renderSidebar()
pswp.on('change', renderSidebar) pswp.on('change', renderSidebar)
// Re-render when a lazy album item's detail arrives after open. // Re-render when a lazy album item's detail arrives after open.
state.slideRefreshers.push(renderSidebar) state.slideRefreshers.push(renderSidebar)
pswp.on('destroy', () => { pswp.on('destroy', () => {
document.documentElement.classList.remove('ipp-sidebar-open') 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) applyOpenState(pswp)
} }
} as PswpUiElementConfig) } as PswpUiElementConfig)
if (state.comments) {
lightbox.pswp.ui.registerElement({
name: 'comments-toggle',
order: 8,
isButton: true,
ariaLabel: 'Comments',
html: ICON_COMMENT + '<span class="ipp-comment-badge" hidden></span>',
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({ lightbox.pswp.ui.registerElement({
name: 'sidebar-toggle', name: 'sidebar-toggle',
order: 7, order: 7,
@@ -72,11 +116,9 @@ export function registerSidebar (lightbox: LightboxInstance) {
// keypress hook for arbitrary keys. // keypress hook for arbitrary keys.
window.addEventListener('keydown', (e) => { window.addEventListener('keydown', (e) => {
if (!state.lightbox || !state.lightbox.pswp) return 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') { 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() e.preventDefault()
toggleSidebar(state.lightbox.pswp) toggleSidebar(state.lightbox.pswp)
} else if (e.key === 'Escape' && state.sidebarOpen) { } else if (e.key === 'Escape' && state.sidebarOpen) {
@@ -96,6 +138,8 @@ function setSidebarOpen (pswp: PswpInstance, open: boolean) {
state.sidebarOpen = open state.sidebarOpen = open
writePersistedState(open) writePersistedState(open)
applyOpenState(pswp) applyOpenState(pswp)
// Opening fetches the comments, which are skipped while it's closed
if (open && state.comments) rerender?.()
} }
function applyOpenState (pswp: PswpInstance) { function applyOpenState (pswp: PswpInstance) {
@@ -133,9 +177,10 @@ function renderContents (root: HTMLElement, item: GalleryItem | undefined) {
root.replaceChildren() root.replaceChildren()
if (!item) return if (!item) return
root.appendChild(renderHeader())
const showDescription = state.metadataConfig.descriptionInSidebar && !!item.description 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) { if (showDescription && item.description) {
root.appendChild(renderSection('description', renderDescription(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))) root.appendChild(renderSection('location', renderLocation(exif)))
} }
const noExifShown = !exif || (!hasAnyExifField(exif) && !hasAnyLocationField(exif)) if (state.comments) {
if (!showDescription && noExifShown) { root.appendChild(renderCommentsSection(item, () => updateCommentBadge?.(), metadataShown))
} else if (!metadataShown) {
const empty = document.createElement('p') const empty = document.createElement('p')
empty.className = 'ipp-sidebar-empty' empty.className = 'ipp-sidebar-empty'
empty.textContent = 'No metadata available' 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') const header = document.createElement('header')
header.className = 'ipp-sidebar-header' header.className = 'ipp-sidebar-header'
const close = document.createElement('button') const close = document.createElement('button')
close.type = 'button' close.type = 'button'
close.className = 'ipp-sidebar-close' close.className = 'ipp-sidebar-close'
close.setAttribute('aria-label', 'Close info') close.setAttribute('aria-label', 'Close ' + titleText.toLowerCase())
close.innerHTML = ICON_CLOSE close.innerHTML = ICON_CLOSE
close.addEventListener('click', () => { close.addEventListener('click', () => {
if (state.lightbox && state.lightbox.pswp) setSidebarOpen(state.lightbox.pswp, false) if (state.lightbox && state.lightbox.pswp) setSidebarOpen(state.lightbox.pswp, false)
@@ -172,7 +218,7 @@ function renderHeader (): HTMLElement {
header.appendChild(close) header.appendChild(close)
const title = document.createElement('span') const title = document.createElement('span')
title.className = 'ipp-sidebar-title' title.className = 'ipp-sidebar-title'
title.textContent = 'Info' title.textContent = titleText
header.appendChild(title) header.appendChild(title)
return header return header
} }
+5 -1
View File
@@ -3,7 +3,7 @@
// top-level `let`s. Layout / scroll-tuning constants live here too because // 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`. // 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 ---------------------------------------------- // ----- layout / scroll tuning ----------------------------------------------
@@ -28,6 +28,8 @@ export const LONG_PRESS_MS = 500
export const SIDEBAR_STORAGE_KEY = 'ipp-sidebar-open' export const SIDEBAR_STORAGE_KEY = 'ipp-sidebar-open'
// Width of the sidebar when docked (must match the CSS rule) // Width of the sidebar when docked (must match the CSS rule)
export const SIDEBAR_WIDTH = 360 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 ------------------------------------------------------- // ----- mutable state -------------------------------------------------------
@@ -95,6 +97,8 @@ export const state = {
sidebarOpen: false, sidebarOpen: false,
// Base URL (`/share/meta/<key>`) for the on-demand per-asset metadata route. // Base URL (`/share/meta/<key>`) for the on-demand per-asset metadata route.
metaBase: '', 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, // Re-render callbacks registered by lightbox UI elements (sidebar, caption,
// download button). Each re-renders for the current slide. Invoked after a // download button). Each re-renders for the current slide. Invoked after a
// lazy item's detail arrives so the just-opened slide reflects it. // lazy item's detail arrives so the just-opened slide reflects it.
+17 -7
View File
@@ -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 { import {
getVideoContentType, getVideoContentType,
photoUrl, photoUrl,
@@ -13,6 +13,7 @@ import { downloadFilename, positionInShare } from './filename'
import { groupByDateMode } from './order' import { groupByDateMode } from './order'
import { requiresOriginal } from './sizing' import { requiresOriginal } from './sizing'
import { displayDimensions, metadataGroupActive, pickExif } from './exif' import { displayDimensions, metadataGroupActive, pickExif } from './exif'
import { getStore } from '../magic/store'
/** /**
* Render a gallery page for a given SharedLink. * 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 motionPhotos = !!getConfigOption('ipp.motionPhotos', true)
const descriptionInCaption = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.caption', false) const descriptionInCaption = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.caption', false)
const descriptionInSidebar = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.sidebar', false) const descriptionInSidebar = shareMetadataAllowed && !!getConfigOption('ipp.showMetadata.description.sidebar', false)
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<GalleryItem> => { const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset, index): Promise<GalleryItem> => {
let videoData: string | undefined let videoData: string | undefined
@@ -152,14 +159,17 @@ export async function gallery (res: Response, share: SharedLink, openItem?: numb
groupByDate, groupByDate,
metaBase, metaBase,
uploadLink: uploadLink(share), uploadLink: uploadLink(share),
uploadHealthcheck: uploadHealthcheck() uploadHealthcheck: uploadHealthcheck(),
comments,
accountLink: viewer ? '/me' : undefined
} }
// HTML gallery page cache time. A password-protected gallery keeps the // The page is per-viewer (comment counts, account link) and behind a
// no-store that handleShareRequest set. // 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) { if (!share.password) {
const cacheTime = Math.max(0, getNumericConfigOption('ipp.gallery.cacheTime', 300)) res.header('Cache-Control', 'private, no-cache')
res.header('Cache-Control', 'public, max-age=' + cacheTime)
} }
res.send(renderPage(h(Gallery, props))) res.send(renderPage(h(Gallery, props)))
} }
+7 -302
View File
@@ -1,46 +1,13 @@
#!/usr/bin/env node #!/usr/bin/env node
import 'dotenv/config' import 'dotenv/config'
import express from 'express'
import { resolve } from 'path' 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 dayjs from 'dayjs'
import { Request } from 'express-serve-static-core' import { enforceMinimumImmichVersion, loadConfig, log, setInvalidRequestHandler } from '@ipp/core'
import { ImageSize } from './types' import { removedMetadataSwitches } from './gallery/exif'
import { canDownload, findMotionPhotoStill, uploadHealthcheck } from './share'
import { respondToInvalidRequest as ippInvalidRequestHandler } from './invalidRequestHandler' import { respondToInvalidRequest as ippInvalidRequestHandler } from './invalidRequestHandler'
import { ASSET_VERSION } from './version' import { createApp } from './server'
import { h } from 'preact' import { startNotificationScheduler } from './magic/digest'
import { Home } from './view/home'
/* /*
Must run before any code that calls getConfigOption. The bundled Must run before any code that calls getConfigOption. The bundled
@@ -64,271 +31,7 @@ if (removedSwitches.length) {
*/ */
setInvalidRequestHandler(ippInvalidRequestHandler) setInvalidRequestHandler(ippInvalidRequestHandler)
const app = express() const app = createApp()
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<typeof express.static>[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<ShareResolution> {
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<SharedAssetResolution> {
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)
// Exit non-zero on an uncaught exception, so Docker restarts the container // Exit non-zero on an uncaught exception, so Docker restarts the container
process.on('uncaughtException', (err) => { process.on('uncaughtException', (err) => {
@@ -353,5 +56,7 @@ process.on('SIGTERM', () => {
const port = Number(process.env.IPP_PORT) || 3000 const port = Number(process.env.IPP_PORT) || 3000
const server = app.listen(port, () => { const server = app.listen(port, () => {
console.log(dayjs().format() + ' Server started on port ' + 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)) enforceMinimumImmichVersion().catch(e => console.error('Immich version check failed:', e))
startNotificationScheduler()
}) })
+324
View File
@@ -0,0 +1,324 @@
import crypto from 'crypto'
import { Express, NextFunction, Request, Response } from 'express-serve-static-core'
import {
addNoStoreHeaders,
Asset,
asyncHandler,
authHeaders,
fetchSharedLink,
isId,
isKey,
KeyType,
log,
renderPage,
title,
TtlLruCache
} from '@ipp/core'
import { h } from 'preact'
import { assetFetchUrl } from '../immich'
import { getStore, isFrequency, Recipient } from './store'
import { inviteMail, mailConfigured, publicBaseUrl, sendMail } from './mailer'
import { listShareAssets, runNotificationCycle, scanShare } from './digest'
import { nowIso, readCookie, secureCookies } from './session'
import { AdminDashboard, AdminLogin, AdminRecipient } from './views'
const ADMIN_COOKIE = 'imp_admin'
const ADMIN_SESSION_MS = 30 * 24 * 60 * 60_000
const MAX_LOGIN_FAILURES = 10
const loginFailures = new TtlLruCache<number>({ ttlMs: 15 * 60_000, max: 1000 })
function adminPassword (): string {
return process.env.ADMIN_PASSWORD || ''
}
// Derived from the password, so changing ADMIN_PASSWORD signs every admin out
function signingKey (): Buffer {
return crypto.createHash('sha256').update('immich-magic-proxy admin\0' + adminPassword()).digest()
}
function sign (expires: number): string {
return expires + '.' + crypto.createHmac('sha256', signingKey()).update(String(expires)).digest('base64url')
}
function safeEqual (a: string, b: string): boolean {
const left = Buffer.from(a)
const right = Buffer.from(b)
return left.length === right.length && crypto.timingSafeEqual(left, right)
}
function isAdmin (req: Request): boolean {
const cookie = readCookie(req, ADMIN_COOKIE)
if (!cookie || !adminPassword()) return false
const expires = Number(cookie.split('.')[0])
return Number.isFinite(expires) && expires > Date.now() && safeEqual(cookie, sign(expires))
}
function requireAdmin (req: Request, res: Response, next: NextFunction) {
if (isAdmin(req)) {
next()
} else if (req.method === 'GET') {
res.redirect(303, '/admin')
} else {
res.status(403).send()
}
}
/** Absolute base for links an admin hands out. */
function linkBase (req: Request): string {
return publicBaseUrl() || (req.protocol + '://' + req.get('host'))
}
function bodyString (req: Request, field: string, max = 300): string {
const value = req.body?.[field]
return typeof value === 'string' ? value.trim().slice(0, max) : ''
}
function bodyList (req: Request, field: string): string[] {
const value = req.body?.[field]
return (Array.isArray(value) ? value : value === undefined ? [] : [value]).filter((v): v is string => typeof v === 'string')
}
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
/** Pull a share key or slug out of a pasted Immich / IPP link, or a bare key. */
export function parseShareInput (input: string): { key: string, keyType: KeyType } | undefined {
let path = input.trim()
if (/^https?:\/\//i.test(path)) {
try {
path = new URL(path).pathname
} catch {
return undefined
}
}
const slug = path.match(/(?:^|\/)s\/([\w-]+)\/?$/)
if (slug) return { key: slug[1], keyType: KeyType.slug }
const shared = path.match(/(?:^|\/)share\/(?:(?:photo|video|meta)\/)?([\w-]+)/)
if (shared) return { key: shared[1], keyType: KeyType.key }
return isKey(path) ? { key: path, keyType: KeyType.key } : undefined
}
type Message = { kind: 'ok' | 'error', text: string }
function renderDashboard (res: Response, message?: Message) {
const store = getStore()
const shares = store.listShares()
res.send(renderPage(h(AdminDashboard, {
shares: shares.map(share => ({ share, recipients: store.countShareRecipients(share.key), assets: store.countKnownAssets(share.key) })),
recipients: store.listRecipients().map(recipient => ({
recipient,
shares: store.listRecipientShares(recipient.id),
sessions: store.countSessions(recipient.id)
})),
comments: store.recentComments(50),
emailEnabled: mailConfigured() && !!publicBaseUrl(),
message
})))
}
function renderRecipient (res: Response, recipient: Recipient, extra: { newLink?: string, message?: Message } = {}) {
const store = getStore()
res.send(renderPage(h(AdminRecipient, {
recipient,
shares: store.listShares(),
granted: store.listRecipientShares(recipient.id).map(share => share.key),
sessions: store.countSessions(recipient.id),
activeLinks: store.countMagicLinks(recipient.id, nowIso()),
emailEnabled: mailConfigured() && !!publicBaseUrl(),
...extra
})))
}
/** Create a non-expiring invitation link, and optionally email it. */
async function issueInvite (req: Request, recipient: Recipient, send: boolean): Promise<{ link: string, message?: Message }> {
const store = getStore()
const token = store.createMagicLink(recipient.id, { purpose: 'invite', expiresAt: null }, nowIso())
const link = linkBase(req) + '/m/' + token
if (!send) return { link }
try {
await sendMail(inviteMail({
to: recipient.email,
name: recipient.name,
link,
albums: store.listRecipientShares(recipient.id).map(share => share.title)
}))
return { link, message: { kind: 'ok', text: 'Invitation emailed to ' + recipient.email + '.' } }
} catch (e) {
log.error('Invitation email failed: ' + (e instanceof Error ? e.message : String(e)))
return { link, message: { kind: 'error', text: 'The email could not be sent; copy the link below instead.' } }
}
}
function recipientParam (req: Request, res: Response): Recipient | undefined {
const recipient = /^\d+$/.test(req.params.id) ? getStore().getRecipient(Number(req.params.id)) : undefined
if (!recipient) res.redirect(303, '/admin')
return recipient
}
/**
* The admin console at /admin. Off unless ADMIN_PASSWORD is set, in which case
* /admin falls through to the visitor gate like any other path.
*/
export function registerAdminRoutes (app: Express) {
if (!adminPassword()) return
app.use('/admin', (_req, res, next) => {
addNoStoreHeaders(res)
res.set('X-Frame-Options', 'DENY')
next()
})
app.get('/admin', (req, res) => {
if (isAdmin(req)) renderDashboard(res)
else res.send(renderPage(h(AdminLogin, {})))
})
app.post('/admin/login', (req, res) => {
const ip = req.ip || ''
const failures = loginFailures.get(ip) || 0
const password = bodyString(req, 'password', 1000)
if (failures >= MAX_LOGIN_FAILURES || !safeEqual(password, adminPassword())) {
loginFailures.set(ip, failures + 1)
log.warn('Failed admin sign-in from ' + ip)
res.status(401).send(renderPage(h(AdminLogin, { failed: true })))
return
}
loginFailures.delete(ip)
res.cookie(ADMIN_COOKIE, sign(Date.now() + ADMIN_SESSION_MS), {
httpOnly: true, sameSite: 'strict', secure: secureCookies(), path: '/admin', maxAge: ADMIN_SESSION_MS
})
res.redirect(303, '/admin')
})
app.post('/admin/logout', (_req, res) => {
res.clearCookie(ADMIN_COOKIE, { path: '/admin' })
res.redirect(303, '/admin')
})
app.use('/admin', requireAdmin)
app.post('/admin/shares', asyncHandler(async (req, res) => {
const parsed = parseShareInput(bodyString(req, 'link', 2000))
const password = bodyString(req, 'password', 1000) || undefined
if (!parsed) {
renderDashboard(res, { kind: 'error', text: 'That doesn\'t look like an Immich share link.' })
return
}
const result = await fetchSharedLink(parsed.key, parsed.keyType, password)
if (result.passwordRequired) {
renderDashboard(res, { kind: 'error', text: password ? 'Immich rejected that password.' : 'That share has a password: enter it too.' })
return
}
if (!result.valid || !result.link) {
renderDashboard(res, { kind: 'error', text: 'Immich didn\'t accept that link. Check it hasn\'t expired.' })
return
}
const store = getStore()
const share = store.upsertShare({
key: result.link.key,
slug: result.link.slug || null,
title: title(result.link),
password: password ?? null
}, nowIso())
// Record what's there now, so recipients are only told about later photos
await scanShare(store, share, listShareAssets, nowIso()).catch(() => false)
renderDashboard(res, { kind: 'ok', text: 'Added "' + share.title + '".' })
}))
app.post('/admin/shares/:key/delete', (req, res) => {
getStore().deleteShare(req.params.key)
res.redirect(303, '/admin')
})
app.post('/admin/recipients', asyncHandler(async (req, res) => {
const store = getStore()
const name = bodyString(req, 'name', 100)
const email = bodyString(req, 'email', 254)
const frequency = bodyString(req, 'frequency')
if (!name || !EMAIL_PATTERN.test(email) || !isFrequency(frequency)) {
renderDashboard(res, { kind: 'error', text: 'Enter a name and a valid email address.' })
return
}
if (store.getRecipientByEmail(email)) {
renderDashboard(res, { kind: 'error', text: email + ' is already a recipient.' })
return
}
const recipient = store.createRecipient({ name, email, frequency }, nowIso())
store.setRecipientShares(recipient.id, bodyList(req, 'shares'), nowIso())
const invite = await issueInvite(req, recipient, bodyString(req, 'sendInvite') === '1' && mailConfigured())
renderRecipient(res, recipient, { newLink: invite.link, message: invite.message })
}))
app.get('/admin/recipients/:id', (req, res) => {
const recipient = recipientParam(req, res)
if (recipient) renderRecipient(res, recipient)
})
app.post('/admin/recipients/:id', (req, res) => {
const store = getStore()
const recipient = recipientParam(req, res)
if (!recipient) return
const name = bodyString(req, 'name', 100)
const email = bodyString(req, 'email', 254)
const frequency = bodyString(req, 'frequency')
const existing = store.getRecipientByEmail(email)
if (!name || !EMAIL_PATTERN.test(email) || !isFrequency(frequency) || (existing && existing.id !== recipient.id)) {
renderRecipient(res, recipient, { message: { kind: 'error', text: 'Check the name and email (each email can only belong to one recipient).' } })
return
}
store.updateRecipient(recipient.id, { name, email, disabled: bodyString(req, 'disabled') === '1' })
store.setFrequency(recipient.id, frequency, nowIso())
store.setRecipientShares(recipient.id, bodyList(req, 'shares'), nowIso())
renderRecipient(res, store.getRecipient(recipient.id)!, { message: { kind: 'ok', text: 'Saved.' } })
})
app.post('/admin/recipients/:id/link', asyncHandler(async (req, res) => {
const recipient = recipientParam(req, res)
if (!recipient) return
const invite = await issueInvite(req, recipient, bodyString(req, 'send') === '1')
renderRecipient(res, recipient, { newLink: invite.link, message: invite.message })
}))
app.post('/admin/recipients/:id/revoke', (req, res) => {
const recipient = recipientParam(req, res)
if (!recipient) return
getStore().revokeAccess(recipient.id)
renderRecipient(res, recipient, { message: { kind: 'ok', text: 'Signed out everywhere; every link they had no longer works.' } })
})
app.post('/admin/recipients/:id/delete', (req, res) => {
const recipient = recipientParam(req, res)
if (!recipient) return
getStore().deleteRecipient(recipient.id)
res.redirect(303, '/admin')
})
app.post('/admin/comments/:id/delete', (req, res) => {
if (/^\d+$/.test(req.params.id)) getStore().deleteComment(Number(req.params.id))
res.redirect(303, '/admin')
})
app.post('/admin/notify', asyncHandler(async (_req, res) => {
await runNotificationCycle()
renderDashboard(res, { kind: 'ok', text: 'Checked every album for new photos and sent any notification emails that were due.' })
}))
// Thumbnail for the comment moderation list
app.get('/admin/thumb/:key/:id', asyncHandler(async (req, res) => {
const share = getStore().getShare(req.params.key)
if (!share || !isId(req.params.id)) {
res.status(404).send()
return
}
const asset = { id: req.params.id, key: share.key, keyType: KeyType.key } as Asset
const upstream = await fetch(assetFetchUrl(asset, '/thumbnail', 'thumbnail'), {
headers: await authHeaders(KeyType.key, share.key, share.password ?? undefined)
})
if (!upstream.ok || !upstream.body) {
res.status(404).send()
return
}
res.set('Content-Type', upstream.headers.get('Content-Type') || 'image/jpeg')
res.set('Cache-Control', 'private, max-age=3600')
res.send(Buffer.from(await upstream.arrayBuffer()))
}))
}
+162
View File
@@ -0,0 +1,162 @@
import dayjs from 'dayjs'
import { KeyType, log } from '@ipp/core'
import { getShareByKey } from '../immich'
import { Frequency, getStore, Recipient, ShareRecord, Store } from './store'
import { digestMail, DigestSection, mailConfigured, MailSender, publicBaseUrl, sendMail } from './mailer'
/** Asset ids currently in a share, or null when Immich couldn't be read. */
export type AssetLister = (share: ShareRecord) => Promise<string[] | null>
const DIGEST_LINK_DAYS = 30
export const listShareAssets: AssetLister = async (share) => {
const result = await getShareByKey(share.key, share.password ?? undefined, KeyType.key)
if (!result.valid || !result.link) return null
return result.link.assets.map(asset => asset.id)
}
/** Hour of day (server local time, set with TZ) that digests go out. */
export function digestHour (): number {
const hour = Number(process.env.DIGEST_HOUR ?? 8)
return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : 8
}
/**
* When a recipient's next digest is due: the next daily / weekly / monthly
* boundary after their window opened, at the digest hour. Anchoring to a
* calendar day keeps the send time from drifting with the scan interval.
*/
export function nextDigestDue (frequency: Frequency, windowStart: string | null, hour = digestHour()): Date | undefined {
if (frequency === 'off' || !windowStart) return undefined
const day = dayjs(windowStart).startOf('day')
const next = frequency === 'daily'
? day.add(1, 'day')
: frequency === 'weekly'
? day.add(7, 'day')
: day.add(1, 'month')
return next.hour(hour).toDate()
}
/**
* Record each share's assets. The first scan of a share is its baseline:
* those assets are dated to when the share was added, so nobody is told
* about photos that were there before they were invited.
*/
export async function scanShares (store: Store, listAssets: AssetLister, now: string): Promise<Map<string, Set<string>>> {
const current = new Map<string, Set<string>>()
for (const share of store.listShares()) {
const ids = await scanShare(store, share, listAssets, now)
if (ids) current.set(share.key, ids)
}
return current
}
/** Scan one share. Returns its current asset ids, or null if Immich couldn't be read. */
export async function scanShare (store: Store, share: ShareRecord, listAssets: AssetLister, now: string): Promise<Set<string> | null> {
let ids: string[] | null = null
try {
ids = await listAssets(share)
} catch (e) {
log.warn('Could not list assets of share ' + share.key + ': ' + (e instanceof Error ? e.message : String(e)))
}
if (!ids) {
log.warn('Skipping notification scan for share "' + share.title + '": Immich did not return it')
return null
}
const known = store.knownAssetIds(share.key)
store.addAssets(share.key, ids.filter(id => !known.has(id)), share.lastScannedAt ? now : share.createdAt)
store.setShareScanned(share.key, now)
return new Set(ids)
}
export interface DigestDeps {
store: Store
send: MailSender
baseUrl: string
now: Date
hour?: number
}
/** Send every digest that is due. Returns how many emails went out. */
export async function sendDueDigests (deps: DigestDeps, current: Map<string, Set<string>>): Promise<number> {
const { store, now } = deps
const nowIso = now.toISOString()
let sent = 0
for (const recipient of store.listRecipients()) {
if (recipient.disabled) continue
const due = nextDigestDue(recipient.frequency, recipient.lastDigestAt, deps.hour)
if (!due || now < due) continue
try {
if (await sendDigest(deps, recipient, current)) sent++
store.setDigestAt(recipient.id, nowIso)
} catch (e) {
// The window stays open, so the next run retries with the same photos
log.error('Digest to ' + recipient.email + ' failed: ' + (e instanceof Error ? e.message : String(e)))
}
}
return sent
}
async function sendDigest (deps: DigestDeps, recipient: Recipient, current: Map<string, Set<string>>): Promise<boolean> {
const { store, now } = deps
const nowIso = now.toISOString()
const pending: Array<{ share: ShareRecord, count: number }> = []
for (const share of store.listRecipientShares(recipient.id)) {
const present = current.get(share.key)
// Nothing from before they had the album, and only photos still in it
// when this run could check
const after = share.grantedAt > recipient.lastDigestAt! ? share.grantedAt : recipient.lastDigestAt!
const ids = store.assetsSeenBetween(share.key, after, nowIso)
.filter(id => !present || present.has(id))
if (ids.length) pending.push({ share, count: ids.length })
}
if (!pending.length) return false
// One sign-in link per email, so the links work on a device with no session
const token = store.createMagicLink(recipient.id, {
purpose: 'digest',
expiresAt: dayjs(now).add(DIGEST_LINK_DAYS, 'day').toISOString()
}, nowIso)
const link = (path: string) => deps.baseUrl + '/m/' + token + '?next=' + encodeURIComponent(path)
const sections: DigestSection[] = pending.map(({ share, count }) => ({
title: share.title || 'Shared album',
count,
link: link('/share/' + share.key)
}))
await deps.send(digestMail({ to: recipient.email, name: recipient.name, sections, settingsLink: link('/me') }))
return true
}
let running = false
let warnedNoMail = false
/** One scan-and-notify pass over every share and recipient. */
export async function runNotificationCycle (now = new Date()) {
if (running) return
running = true
try {
const store = getStore()
store.pruneExpiredLinks(now.toISOString())
const current = await scanShares(store, listShareAssets, now.toISOString())
const baseUrl = publicBaseUrl()
if (!mailConfigured() || !baseUrl) {
if (!warnedNoMail) {
warnedNoMail = true
log.warn('Photo notification emails are off: set SMTP_URL (or SMTP_HOST) and PUBLIC_BASE_URL to send them')
}
return
}
const sent = await sendDueDigests({ store, send: sendMail, baseUrl, now }, current)
if (sent) log('Sent ' + sent + ' photo notification email' + (sent === 1 ? '' : 's'))
} finally {
running = false
}
}
/** Scan for new photos every NOTIFY_INTERVAL_MINUTES (default 60), starting a minute after boot. */
export function startNotificationScheduler () {
const minutes = Math.max(1, Number(process.env.NOTIFY_INTERVAL_MINUTES) || 60)
const tick = () => { runNotificationCycle().catch(e => log.error('Notification run failed: ' + e)) }
setTimeout(tick, 60_000).unref()
setInterval(tick, minutes * 60_000).unref()
}
+134
View File
@@ -0,0 +1,134 @@
import nodemailer, { Transporter } from 'nodemailer'
import { log } from '@ipp/core'
export interface Mail {
to: string
subject: string
text: string
html: string
}
export type MailSender = (mail: Mail) => Promise<void>
/** True when SMTP_URL or SMTP_HOST is set. */
export function mailConfigured (): boolean {
return !!(process.env.SMTP_URL || process.env.SMTP_HOST)
}
let transport: Transporter | undefined
function createTransport (): Transporter {
if (process.env.SMTP_URL) return nodemailer.createTransport(process.env.SMTP_URL)
const port = Number(process.env.SMTP_PORT) || 587
return nodemailer.createTransport({
host: process.env.SMTP_HOST,
port,
secure: process.env.SMTP_SECURE ? process.env.SMTP_SECURE === 'true' : port === 465,
auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS || '' } : undefined
})
}
const smtpSender: MailSender = async (mail) => {
if (!mailConfigured()) throw new Error('Email is not configured: set SMTP_URL or SMTP_HOST')
transport ??= createTransport()
await transport.sendMail({
from: process.env.MAIL_FROM || process.env.SMTP_USER,
to: mail.to,
subject: mail.subject,
text: mail.text,
html: mail.html
})
log('Sent email "' + mail.subject + '" to ' + mail.to)
}
let sender: MailSender = smtpSender
export function sendMail (mail: Mail): Promise<void> {
return sender(mail)
}
/** Replace how mail is sent, for tests. Pass undefined to restore SMTP. */
export function setMailSender (next: MailSender | undefined) {
sender = next ?? smtpSender
}
export function siteName (): string {
return process.env.SITE_NAME || 'Shared photos'
}
/** The public origin for links in emails, from PUBLIC_BASE_URL. */
export function publicBaseUrl (): string | undefined {
const base = (process.env.PUBLIC_BASE_URL || '').trim().replace(/\/+$/, '')
return /^https?:\/\//i.test(base) ? base : undefined
}
function escapeHtml (value: string): string {
return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
function htmlDocument (body: string): string {
return '<!DOCTYPE html><html><body style="font-family:-apple-system,Segoe UI,Roboto,sans-serif;line-height:1.5;color:#222;max-width:560px;margin:0 auto;padding:16px">' +
body + '</body></html>'
}
const button = (url: string, label: string) =>
`<p><a href="${escapeHtml(url)}" style="display:inline-block;background:#4250af;color:#fff;padding:10px 18px;border-radius:6px;text-decoration:none">${escapeHtml(label)}</a></p>`
export function inviteMail (input: { to: string, name: string, link: string, albums: string[] }): Mail {
const site = siteName()
const albumList = input.albums.length ? input.albums : ['your albums']
return {
to: input.to,
subject: `${site}: you've been invited to view photos`,
text: `Hi ${input.name},\n\nYou've been given access to ${albumList.join(', ')}.\n\n` +
`Open your personal link:\n${input.link}\n\n` +
'After opening it once, you can bookmark the page; this browser stays signed in. ' +
'Please don\'t forward this email: anyone with the link can see the photos.\n',
html: htmlDocument(
`<p>Hi ${escapeHtml(input.name)},</p>` +
`<p>You've been given access to <strong>${albumList.map(escapeHtml).join(', ')}</strong>.</p>` +
button(input.link, 'View photos') +
'<p style="color:#666;font-size:14px">After opening it once, you can bookmark the page; this browser stays signed in. ' +
'Please don\'t forward this email: anyone with the link can see the photos.</p>'
)
}
}
export function signInMail (input: { to: string, name: string, link: string }): Mail {
const site = siteName()
return {
to: input.to,
subject: `${site}: your sign-in link`,
text: `Hi ${input.name},\n\nHere is your sign-in link:\n${input.link}\n\nIt works for 7 days. If you didn't ask for it, you can ignore this email.\n`,
html: htmlDocument(
`<p>Hi ${escapeHtml(input.name)},</p>` +
button(input.link, 'Sign in') +
'<p style="color:#666;font-size:14px">This link works for 7 days. If you didn\'t ask for it, you can ignore this email.</p>'
)
}
}
export interface DigestSection {
title: string
count: number
link: string
}
export function digestMail (input: { to: string, name: string, sections: DigestSection[], settingsLink: string }): Mail {
const total = input.sections.reduce((sum, s) => sum + s.count, 0)
const plural = (n: number) => n === 1 ? '1 new photo' : n + ' new photos'
return {
to: input.to,
subject: `${siteName()}: ${plural(total)}`,
text: `Hi ${input.name},\n\n` +
input.sections.map(s => `${plural(s.count)} in ${s.title}:\n${s.link}`).join('\n\n') +
`\n\nChange how often you get these emails: ${input.settingsLink}\n`,
html: htmlDocument(
`<p>Hi ${escapeHtml(input.name)},</p>` +
input.sections.map(s =>
`<p><strong>${escapeHtml(plural(s.count))}</strong> in ${escapeHtml(s.title)}</p>` + button(s.link, 'View ' + s.title)
).join('') +
`<p style="color:#666;font-size:14px"><a href="${escapeHtml(input.settingsLink)}">Change how often you get these emails</a></p>`
)
}
}
+170
View File
@@ -0,0 +1,170 @@
import { Express, Request, Response } from 'express-serve-static-core'
import dayjs from 'dayjs'
import { addNoStoreHeaders, asyncHandler, decodeCookie, KeyType, log, renderPage, respondToInvalidRequest, TtlLruCache } from '@ipp/core'
import { h } from 'preact'
import { resolveSharedAsset } from '../resolve'
import { CommentRecord, getStore, isFrequency, Recipient } from './store'
import { endSession, nowIso, requireShareAccess, startSession } from './session'
import { isTokenShaped, safeNextPath } from './tokens'
import { mailConfigured, publicBaseUrl, sendMail, signInMail } from './mailer'
import { AccessDenied, LinkRequested, RecipientHome } from './views'
import type { CommentView } from '../shared/types'
const SIGN_IN_LINK_DAYS = 7
const LINK_REQUEST_INTERVAL_MS = 5 * 60_000
const MAX_COMMENT_LENGTH = 2000
const COMMENTS_PER_WINDOW = 30
const linkRequestsByIp = new TtlLruCache<number>({ ttlMs: 60 * 60_000, max: 5000 })
const commentsByRecipient = new TtlLruCache<number>({ ttlMs: 10 * 60_000, max: 5000 })
/** Routes anyone can reach: following a magic link, and asking for a new one. */
export function registerSignInRoutes (app: Express) {
app.get('/m/:token', (req, res) => {
addNoStoreHeaders(res)
// Keep the token out of any Referer sent by the page we redirect to
res.set('Referrer-Policy', 'no-referrer')
const store = getStore()
const recipient = isTokenShaped(req.params.token) ? store.useMagicLink(req.params.token, nowIso()) : undefined
if (!recipient) {
log('Invalid or expired magic link')
res.status(401).send(renderPage(h(AccessDenied, { signedIn: !!req.recipient, invalidLink: true })))
return
}
// Reuse this browser's session when it already belongs to the recipient
if (req.recipient?.id !== recipient.id) {
if (req.recipient) endSession(req, res)
startSession(res, recipient)
}
const shares = store.listRecipientShares(recipient.id)
const next = safeNextPath(req.query.next) ?? (shares.length === 1 ? '/share/' + shares[0].key : '/me')
res.redirect(303, next)
})
app.post('/access', (req, res) => {
addNoStoreHeaders(res)
const email = typeof req.body?.email === 'string' ? req.body.email.trim().slice(0, 254) : ''
const ip = req.ip || ''
const requests = (linkRequestsByIp.get(ip) || 0) + 1
linkRequestsByIp.set(ip, requests)
// The same answer whether or not the address is known, and sent before
// any email goes out, so neither content nor timing reveals who's invited
res.send(renderPage(h(LinkRequested, {})))
if (requests > 10 || !email) return
emailSignInLink(email, req).catch(() => {})
})
}
async function emailSignInLink (email: string, req: Request) {
const store = getStore()
const recipient = store.getRecipientByEmail(email)
if (!recipient || recipient.disabled || !mailConfigured()) return
const now = new Date()
if (!store.allowLinkRequest(recipient.email, now.toISOString(), new Date(now.getTime() - LINK_REQUEST_INTERVAL_MS).toISOString())) return
const token = store.createMagicLink(recipient.id, {
purpose: 'sign-in',
expiresAt: dayjs(now).add(SIGN_IN_LINK_DAYS, 'day').toISOString()
}, now.toISOString())
const base = publicBaseUrl() || (req.protocol + '://' + req.get('host'))
try {
await sendMail(signInMail({ to: recipient.email, name: recipient.name, link: base + '/m/' + token }))
} catch (e) {
log.error('Sign-in email to ' + recipient.email + ' failed: ' + (e instanceof Error ? e.message : String(e)))
}
}
function commentView (comment: CommentRecord, viewer: Recipient): CommentView {
return {
id: comment.id,
author: comment.authorName,
body: comment.body,
createdAt: comment.createdAt,
mine: comment.recipientId === viewer.id
}
}
/** Routes behind the recipient gate. */
export function registerRecipientRoutes (app: Express) {
const renderHome = (req: Request, res: Response, saved = false) => {
addNoStoreHeaders(res)
const recipient = getStore().getRecipient(req.recipient!.id)!
res.send(renderPage(h(RecipientHome, {
recipient,
shares: getStore().listRecipientShares(recipient.id),
saved,
emailEnabled: mailConfigured() && !!publicBaseUrl()
})))
}
app.get('/me', (req, res) => renderHome(req, res))
app.post('/me/notifications', (req, res) => {
const frequency = req.body?.frequency
if (isFrequency(frequency)) getStore().setFrequency(req.recipient!.id, frequency, nowIso())
renderHome(req, res, true)
})
app.post('/logout', (req, res) => {
endSession(req, res)
res.redirect(303, '/')
})
// The bare root and /share land on the recipient's albums
app.get(/^\/(|share)\/*$/, (_req, res) => {
addNoStoreHeaders(res)
res.redirect(303, '/me')
})
// ----- comments ------------------------------------------------------------
const commentsPath = '/share/comments/:key/:id'
app.get(commentsPath, requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
const resolved = await resolveSharedAsset(req, KeyType.key)
if (!resolved.ok) {
respondToInvalidRequest(res, resolved.status, resolved.reason)
return
}
addNoStoreHeaders(res)
res.json(getStore().listComments(resolved.link.key, resolved.asset.id).map(c => commentView(c, req.recipient!)))
}))
app.post(commentsPath, requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
addNoStoreHeaders(res)
// JSON only: a cross-site HTML form can't send it
if (!req.is('application/json')) {
res.status(415).json({ error: 'Expected JSON' })
return
}
const body = typeof req.body?.body === 'string' ? req.body.body.trim() : ''
if (!body || body.length > MAX_COMMENT_LENGTH) {
res.status(400).json({ error: 'A comment must be 1 to ' + MAX_COMMENT_LENGTH + ' characters.' })
return
}
const recipient = req.recipient!
const recent = (commentsByRecipient.get(String(recipient.id)) || 0) + 1
if (recent > COMMENTS_PER_WINDOW) {
res.status(429).json({ error: 'You\'re commenting too quickly. Try again in a few minutes.' })
return
}
const resolved = await resolveSharedAsset(req, KeyType.key)
if (!resolved.ok) {
respondToInvalidRequest(res, resolved.status, resolved.reason)
return
}
commentsByRecipient.set(String(recipient.id), recent)
const comment = getStore().addComment({ shareKey: resolved.link.key, assetId: resolved.asset.id, recipient, body }, nowIso())
res.status(201).json(commentView(comment, recipient))
}))
app.delete(commentsPath + '/:commentId', requireShareAccess, (req, res) => {
addNoStoreHeaders(res)
const store = getStore()
const comment = /^\d+$/.test(req.params.commentId) ? store.getComment(Number(req.params.commentId)) : undefined
if (!comment || comment.shareKey !== req.grantedShare!.key || comment.assetId !== req.params.id || comment.recipientId !== req.recipient!.id) {
res.status(404).send()
return
}
store.deleteComment(comment.id)
res.status(204).send()
})
}
+121
View File
@@ -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()
}
+416
View File
@@ -0,0 +1,416 @@
import { DatabaseSync, SQLInputValue } from 'node:sqlite'
import { mkdirSync } from 'fs'
import { dirname, resolve } from 'path'
import { hashToken, newToken } from './tokens'
export type Frequency = 'off' | 'daily' | 'weekly' | 'monthly'
export const FREQUENCIES: Frequency[] = ['off', 'daily', 'weekly', 'monthly']
export function isFrequency (value: unknown): value is Frequency {
return typeof value === 'string' && (FREQUENCIES as string[]).includes(value)
}
export interface Recipient {
id: number
name: string
email: string
frequency: Frequency
/** Start of the window the next digest covers. */
lastDigestAt: string | null
createdAt: string
disabled: boolean
}
export interface ShareRecord {
key: string
slug: string | null
title: string
/** Lets recipients and the background scanner open a password-protected share. */
password: string | null
lastScannedAt: string | null
createdAt: string
}
export interface CommentRecord {
id: number
shareKey: string
assetId: string
recipientId: number | null
authorName: string
body: string
createdAt: string
}
const SCHEMA = `
CREATE TABLE IF NOT EXISTS recipients (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
frequency TEXT NOT NULL DEFAULT 'off' CHECK (frequency IN ('off', 'daily', 'weekly', 'monthly')),
last_digest_at TEXT,
created_at TEXT NOT NULL,
disabled INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS shares (
key TEXT PRIMARY KEY,
slug TEXT,
title TEXT NOT NULL DEFAULT '',
password TEXT,
last_scanned_at TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS recipient_shares (
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
granted_at TEXT NOT NULL,
PRIMARY KEY (recipient_id, share_key)
);
CREATE TABLE IF NOT EXISTS magic_links (
id INTEGER PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
purpose TEXT NOT NULL,
created_at TEXT NOT NULL,
expires_at TEXT,
last_used_at TEXT
);
CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY,
recipient_id INTEGER NOT NULL REFERENCES recipients(id) ON DELETE CASCADE,
created_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS share_assets (
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
asset_id TEXT NOT NULL,
first_seen_at TEXT NOT NULL,
PRIMARY KEY (share_key, asset_id)
);
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY,
share_key TEXT NOT NULL REFERENCES shares(key) ON DELETE CASCADE,
asset_id TEXT NOT NULL,
recipient_id INTEGER REFERENCES recipients(id) ON DELETE SET NULL,
author_name TEXT NOT NULL,
body TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS comments_by_asset ON comments (share_key, asset_id);
CREATE TABLE IF NOT EXISTS link_requests (
email TEXT PRIMARY KEY COLLATE NOCASE,
last_at TEXT NOT NULL
);
`
const RECIPIENT_COLUMNS = `id, name, email, frequency, last_digest_at AS lastDigestAt,
created_at AS createdAt, disabled`
const SHARE_COLUMNS = 'key, slug, title, password, last_scanned_at AS lastScannedAt, created_at AS createdAt'
const JOINED_SHARE_COLUMNS = 's.key, s.slug, s.title, s.password, s.last_scanned_at AS lastScannedAt, s.created_at AS createdAt'
const COMMENT_COLUMNS = `id, share_key AS shareKey, asset_id AS assetId, recipient_id AS recipientId,
author_name AS authorName, body, created_at AS createdAt`
type Row = Record<string, SQLInputValue>
function toRecipient (row: Row | undefined): Recipient | undefined {
if (!row) return undefined
return { ...(row as unknown as Recipient), disabled: !!row.disabled }
}
/**
* All persistent state for magic-link access, notifications and comments.
* Timestamps are ISO-8601 UTC strings, so they compare correctly as text.
*/
export class Store {
readonly db: DatabaseSync
constructor (path: string) {
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true })
this.db = new DatabaseSync(path)
this.db.exec('PRAGMA foreign_keys = ON')
this.db.exec('PRAGMA busy_timeout = 5000')
if (path !== ':memory:') this.db.exec('PRAGMA journal_mode = WAL')
this.db.exec(SCHEMA)
}
close () {
this.db.close()
}
private transaction (fn: () => void) {
this.db.exec('BEGIN')
try {
fn()
this.db.exec('COMMIT')
} catch (e) {
this.db.exec('ROLLBACK')
throw e
}
}
// ----- recipients ----------------------------------------------------------
createRecipient (input: { name: string, email: string, frequency: Frequency }, now: string): Recipient {
const result = this.db.prepare(`INSERT INTO recipients (name, email, frequency, last_digest_at, created_at)
VALUES (?, ?, ?, ?, ?)`).run(input.name, input.email, input.frequency, input.frequency === 'off' ? null : now, now)
return this.getRecipient(Number(result.lastInsertRowid))!
}
getRecipient (id: number): Recipient | undefined {
return toRecipient(this.db.prepare(`SELECT ${RECIPIENT_COLUMNS} FROM recipients WHERE id = ?`).get(id))
}
getRecipientByEmail (email: string): Recipient | undefined {
return toRecipient(this.db.prepare(`SELECT ${RECIPIENT_COLUMNS} FROM recipients WHERE email = ?`).get(email))
}
listRecipients (): Recipient[] {
return this.db.prepare(`SELECT ${RECIPIENT_COLUMNS} FROM recipients ORDER BY name COLLATE NOCASE`).all()
.map(row => toRecipient(row)!)
}
updateRecipient (id: number, input: { name: string, email: string, disabled: boolean }) {
this.db.prepare('UPDATE recipients SET name = ?, email = ?, disabled = ? WHERE id = ?')
.run(input.name, input.email, input.disabled ? 1 : 0, id)
}
/**
* Change how often a recipient hears about new photos. Turning digests on
* starts the window now, so they are never told about photos that were
* already there.
*/
setFrequency (id: number, frequency: Frequency, now: string) {
const current = this.getRecipient(id)
if (!current) return
const startWindow = frequency !== 'off' && (current.frequency === 'off' || !current.lastDigestAt)
this.db.prepare('UPDATE recipients SET frequency = ?, last_digest_at = ? WHERE id = ?')
.run(frequency, startWindow ? now : current.lastDigestAt, id)
}
setDigestAt (id: number, at: string) {
this.db.prepare('UPDATE recipients SET last_digest_at = ? WHERE id = ?').run(at, id)
}
deleteRecipient (id: number) {
this.db.prepare('DELETE FROM recipients WHERE id = ?').run(id)
}
// ----- shares --------------------------------------------------------------
upsertShare (input: { key: string, slug: string | null, title: string, password: string | null }, now: string): ShareRecord {
this.db.prepare(`INSERT INTO shares (key, slug, title, password, created_at) VALUES (?, ?, ?, ?, ?)
ON CONFLICT (key) DO UPDATE SET slug = excluded.slug, title = excluded.title, password = excluded.password`)
.run(input.key, input.slug, input.title, input.password, now)
return this.getShare(input.key)!
}
getShare (key: string): ShareRecord | undefined {
return this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares WHERE key = ?`).get(key) as ShareRecord | undefined
}
listShares (): ShareRecord[] {
return this.db.prepare(`SELECT ${SHARE_COLUMNS} FROM shares ORDER BY title COLLATE NOCASE`).all() as unknown as ShareRecord[]
}
deleteShare (key: string) {
this.db.prepare('DELETE FROM shares WHERE key = ?').run(key)
}
setShareScanned (key: string, at: string) {
this.db.prepare('UPDATE shares SET last_scanned_at = ? WHERE key = ?').run(at, key)
}
// ----- access grants -------------------------------------------------------
/**
* Set exactly which shares a recipient has. Shares they already had keep
* their grant time, which bounds what their notifications count.
*/
setRecipientShares (recipientId: number, keys: string[], now: string) {
const wanted = [...new Set(keys)]
this.transaction(() => {
const placeholders = wanted.map(() => '?').join(', ')
this.db.prepare('DELETE FROM recipient_shares WHERE recipient_id = ?' +
(wanted.length ? ` AND share_key NOT IN (${placeholders})` : '')).run(recipientId, ...wanted)
const insert = this.db.prepare(`INSERT OR IGNORE INTO recipient_shares (recipient_id, share_key, granted_at)
SELECT ?, key, ? FROM shares WHERE key = ?`)
for (const key of wanted) insert.run(recipientId, now, key)
})
}
listRecipientShares (recipientId: number): Array<ShareRecord & { grantedAt: string }> {
return this.db.prepare(`SELECT ${JOINED_SHARE_COLUMNS}, rs.granted_at AS grantedAt FROM shares s
JOIN recipient_shares rs ON rs.share_key = s.key WHERE rs.recipient_id = ? ORDER BY s.title COLLATE NOCASE`)
.all(recipientId) as unknown as Array<ShareRecord & { grantedAt: string }>
}
countShareRecipients (key: string): number {
const row = this.db.prepare('SELECT COUNT(*) AS n FROM recipient_shares WHERE share_key = ?').get(key)
return Number(row?.n ?? 0)
}
/**
* The share a recipient may open by its key or slug, or undefined. This is
* the one access check every share-scoped route goes through.
*/
grantedShare (recipientId: number, keyOrSlug: string): ShareRecord | undefined {
return this.db.prepare(`SELECT ${JOINED_SHARE_COLUMNS} FROM shares s
JOIN recipient_shares rs ON rs.share_key = s.key
WHERE rs.recipient_id = ? AND (s.key = ? OR s.slug = ?)`)
.get(recipientId, keyOrSlug, keyOrSlug) as ShareRecord | undefined
}
// ----- magic links ---------------------------------------------------------
/** Returns the plaintext token; only its hash is stored. */
createMagicLink (recipientId: number, options: { purpose: string, expiresAt: string | null }, now: string): string {
const token = newToken()
this.db.prepare(`INSERT INTO magic_links (token_hash, recipient_id, purpose, created_at, expires_at)
VALUES (?, ?, ?, ?, ?)`).run(hashToken(token), recipientId, options.purpose, now, options.expiresAt)
return token
}
/** The recipient a magic link signs in, if the link is live and the recipient enabled. */
useMagicLink (token: string, now: string): Recipient | undefined {
const hash = hashToken(token)
const link = this.db.prepare('SELECT recipient_id AS recipientId, expires_at AS expiresAt FROM magic_links WHERE token_hash = ?')
.get(hash) as { recipientId: number, expiresAt: string | null } | undefined
if (!link || (link.expiresAt && link.expiresAt <= now)) return undefined
const recipient = this.getRecipient(link.recipientId)
if (!recipient || recipient.disabled) return undefined
this.db.prepare('UPDATE magic_links SET last_used_at = ? WHERE token_hash = ?').run(now, hash)
return recipient
}
countMagicLinks (recipientId: number, now: string): number {
const row = this.db.prepare('SELECT COUNT(*) AS n FROM magic_links WHERE recipient_id = ? AND (expires_at IS NULL OR expires_at > ?)')
.get(recipientId, now)
return Number(row?.n ?? 0)
}
pruneExpiredLinks (now: string) {
this.db.prepare('DELETE FROM magic_links WHERE expires_at IS NOT NULL AND expires_at <= ?').run(now)
}
/** Allow at most one self-service link request per address per interval. */
allowLinkRequest (email: string, now: string, notBefore: string): boolean {
const row = this.db.prepare('SELECT last_at AS lastAt FROM link_requests WHERE email = ?').get(email) as { lastAt: string } | undefined
if (row && row.lastAt > notBefore) return false
this.db.prepare(`INSERT INTO link_requests (email, last_at) VALUES (?, ?)
ON CONFLICT (email) DO UPDATE SET last_at = excluded.last_at`).run(email, now)
return true
}
// ----- sessions ------------------------------------------------------------
createSession (recipientId: number, now: string): string {
const token = newToken()
this.db.prepare('INSERT INTO sessions (token_hash, recipient_id, created_at, last_seen_at) VALUES (?, ?, ?, ?)')
.run(hashToken(token), recipientId, now, now)
return token
}
getSession (token: string): { recipient: Recipient, lastSeenAt: string } | undefined {
const row = this.db.prepare('SELECT recipient_id AS recipientId, last_seen_at AS lastSeenAt FROM sessions WHERE token_hash = ?')
.get(hashToken(token)) as { recipientId: number, lastSeenAt: string } | undefined
if (!row) return undefined
const recipient = this.getRecipient(row.recipientId)
return recipient ? { recipient, lastSeenAt: row.lastSeenAt } : undefined
}
touchSession (token: string, now: string) {
this.db.prepare('UPDATE sessions SET last_seen_at = ? WHERE token_hash = ?').run(now, hashToken(token))
}
deleteSession (token: string) {
this.db.prepare('DELETE FROM sessions WHERE token_hash = ?').run(hashToken(token))
}
countSessions (recipientId: number): number {
const row = this.db.prepare('SELECT COUNT(*) AS n FROM sessions WHERE recipient_id = ?').get(recipientId)
return Number(row?.n ?? 0)
}
/** Sign the recipient out everywhere and invalidate every link they were sent. */
revokeAccess (recipientId: number) {
this.transaction(() => {
this.db.prepare('DELETE FROM sessions WHERE recipient_id = ?').run(recipientId)
this.db.prepare('DELETE FROM magic_links WHERE recipient_id = ?').run(recipientId)
})
}
// ----- asset tracking (for notifications) ----------------------------------
knownAssetIds (shareKey: string): Set<string> {
const rows = this.db.prepare('SELECT asset_id AS id FROM share_assets WHERE share_key = ?').all(shareKey)
return new Set(rows.map(row => String(row.id)))
}
addAssets (shareKey: string, ids: string[], firstSeenAt: string) {
if (!ids.length) return
this.transaction(() => {
const insert = this.db.prepare('INSERT OR IGNORE INTO share_assets (share_key, asset_id, first_seen_at) VALUES (?, ?, ?)')
for (const id of ids) insert.run(shareKey, id, firstSeenAt)
})
}
/** Assets first seen in (after, upTo]. */
assetsSeenBetween (shareKey: string, after: string, upTo: string): string[] {
return this.db.prepare('SELECT asset_id AS id FROM share_assets WHERE share_key = ? AND first_seen_at > ? AND first_seen_at <= ?')
.all(shareKey, after, upTo).map(row => String(row.id))
}
countKnownAssets (shareKey: string): number {
const row = this.db.prepare('SELECT COUNT(*) AS n FROM share_assets WHERE share_key = ?').get(shareKey)
return Number(row?.n ?? 0)
}
// ----- comments ------------------------------------------------------------
addComment (input: { shareKey: string, assetId: string, recipient: Recipient, body: string }, now: string): CommentRecord {
const result = this.db.prepare(`INSERT INTO comments (share_key, asset_id, recipient_id, author_name, body, created_at)
VALUES (?, ?, ?, ?, ?, ?)`).run(input.shareKey, input.assetId, input.recipient.id, input.recipient.name, input.body, now)
return this.getComment(Number(result.lastInsertRowid))!
}
getComment (id: number): CommentRecord | undefined {
return this.db.prepare(`SELECT ${COMMENT_COLUMNS} FROM comments WHERE id = ?`).get(id) as CommentRecord | undefined
}
listComments (shareKey: string, assetId: string): CommentRecord[] {
return this.db.prepare(`SELECT ${COMMENT_COLUMNS} FROM comments WHERE share_key = ? AND asset_id = ? ORDER BY id`)
.all(shareKey, assetId) as unknown as CommentRecord[]
}
countComments (shareKey: string): Record<string, number> {
const rows = this.db.prepare('SELECT asset_id AS id, COUNT(*) AS n FROM comments WHERE share_key = ? GROUP BY asset_id').all(shareKey)
return Object.fromEntries(rows.map(row => [String(row.id), Number(row.n)]))
}
recentComments (limit: number): Array<CommentRecord & { shareTitle: string }> {
return this.db.prepare(`SELECT c.id, c.share_key AS shareKey, c.asset_id AS assetId, c.recipient_id AS recipientId,
c.author_name AS authorName, c.body, c.created_at AS createdAt, s.title AS shareTitle
FROM comments c JOIN shares s ON s.key = c.share_key ORDER BY c.id DESC LIMIT ?`)
.all(limit) as unknown as Array<CommentRecord & { shareTitle: string }>
}
deleteComment (id: number) {
this.db.prepare('DELETE FROM comments WHERE id = ?').run(id)
}
}
let store: Store | undefined
/** `<DATA_DIR>/magic.db`, where DATA_DIR defaults to `./data`. */
export function defaultDbPath (): string {
return resolve(process.env.DATA_DIR || 'data', 'magic.db')
}
export function getStore (): Store {
if (!store) store = new Store(defaultDbPath())
return store
}
/** Swap the store, for tests. */
export function setStore (next: Store | undefined) {
store = next
}
+23
View File
@@ -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
}
+371
View File
@@ -0,0 +1,371 @@
import { ComponentChildren } from 'preact'
import { CommentRecord, Frequency, FREQUENCIES, Recipient, ShareRecord } from './store'
const FREQUENCY_LABELS: Record<Frequency, string> = {
off: 'Never',
daily: 'Daily',
weekly: 'Weekly',
monthly: 'Monthly'
}
const STYLE = `
main.container { max-width: 760px; padding-top: 2rem; padding-bottom: 3rem; }
.muted { color: var(--pico-muted-color); }
.notice { padding: .75rem 1rem; border-radius: var(--pico-border-radius); background: var(--pico-card-sectioning-background-color); margin-bottom: 1rem; }
.notice.error { border-left: 4px solid var(--pico-del-color); }
.notice.ok { border-left: 4px solid var(--pico-ins-color); }
.link-box { word-break: break-all; font-family: var(--pico-font-family-monospace); font-size: .85rem; }
.row-actions { display: flex; gap: .5rem; flex-wrap: wrap; align-items: center; }
.row-actions form { margin: 0; }
.row-actions button { margin: 0; padding: .35rem .75rem; font-size: .85rem; }
table td, table th { vertical-align: top; font-size: .9rem; }
fieldset.checks label { display: block; }
.albums a { display: block; padding: .6rem .9rem; margin-bottom: .5rem; border-radius: var(--pico-border-radius); background: var(--pico-card-background-color); box-shadow: var(--pico-card-box-shadow); text-decoration: none; }
`
// Forms with data-confirm ask before submitting
const CONFIRM_SCRIPT = `document.addEventListener('submit', function (e) {
var message = e.target.getAttribute('data-confirm')
if (message && !confirm(message)) e.preventDefault()
})`
function Layout ({ title, children }: { title: string, children: ComponentChildren }) {
return (
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="referrer" content="no-referrer"/>
<meta name="robots" content="noindex, nofollow"/>
<title>{title}</title>
<link rel="icon" href="/share/static/favicon.ico" type="image/x-icon"/>
<link type="text/css" rel="stylesheet" href="/share/static/pico.min.css"/>
<style dangerouslySetInnerHTML={{ __html: STYLE }}/>
</head>
<body>
<main class="container">{children}</main>
<script dangerouslySetInnerHTML={{ __html: CONFIRM_SCRIPT }}/>
</body>
</html>
)
}
function Notice ({ kind, children }: { kind: 'ok' | 'error', children: ComponentChildren }) {
return <div class={'notice ' + kind} role={kind === 'error' ? 'alert' : 'status'}>{children}</div>
}
// ----- visitors --------------------------------------------------------------
/** Shown in place of anything gated. Reveals nothing about what was asked for. */
export function AccessDenied ({ signedIn, invalidLink }: { signedIn: boolean, invalidLink?: boolean }) {
return (
<Layout title="Private photos">
<h1>Private photos</h1>
{invalidLink && <Notice kind="error">That link is no longer valid.</Notice>}
{signedIn
? <p>This page isn't available to you. <a href="/me">See the albums you can view</a>.</p>
: <>
<p>These photos are only visible through a personal invitation link. Open the link from your invitation email to continue.</p>
<RequestLinkForm/>
</>}
</Layout>
)
}
function RequestLinkForm () {
return (
<form method="post" action="/access">
<label>
Lost your link? Enter the email address you were invited with and we'll send a new one.
<input type="email" name="email" required autocomplete="email" placeholder="you@example.com"/>
</label>
<button type="submit">Email me a link</button>
</form>
)
}
export function LinkRequested () {
return (
<Layout title="Check your email">
<h1>Check your email</h1>
<p>If that address has been invited, a sign-in link is on its way. It works for 7 days.</p>
</Layout>
)
}
export interface RecipientHomeProps {
recipient: Recipient
shares: ShareRecord[]
saved?: boolean
emailEnabled: boolean
}
export function RecipientHome ({ recipient, shares, saved, emailEnabled }: RecipientHomeProps) {
return (
<Layout title="Your albums">
<hgroup>
<h1>Hi {recipient.name}</h1>
<p class="muted">Bookmark this page to come back to your albums. This browser stays signed in.</p>
</hgroup>
<section class="albums">
<h2>Albums</h2>
{shares.length
? shares.map(share => <a key={share.key} href={'/share/' + share.key}>{share.title || 'Shared album'}</a>)
: <p class="muted">Nothing has been shared with you yet.</p>}
</section>
<section>
<h2>Email notifications</h2>
{saved && <Notice kind="ok">Saved.</Notice>}
<form method="post" action="/me/notifications">
<fieldset>
<legend>Email me about new photos in these albums ({recipient.email}):</legend>
{FREQUENCIES.map(frequency => (
<label key={frequency}>
<input type="radio" name="frequency" value={frequency} checked={recipient.frequency === frequency}/>
{frequency === 'off' ? 'Never' : FREQUENCY_LABELS[frequency] + ' summary'}
</label>
))}
</fieldset>
{!emailEnabled && <p class="muted"><small>Email isn't set up on this server yet, so nothing will be sent for now.</small></p>}
<button type="submit">Save</button>
</form>
</section>
<section>
<form method="post" action="/logout">
<button type="submit" class="secondary outline">Sign out of this browser</button>
</form>
</section>
</Layout>
)
}
// ----- admin -----------------------------------------------------------------
export function AdminLogin ({ failed }: { failed?: boolean }) {
return (
<Layout title="Admin sign-in">
<h1>Admin</h1>
{failed && <Notice kind="error">Wrong password, or too many attempts. Try again in a few minutes.</Notice>}
<form method="post" action="/admin/login">
<input type="password" name="password" placeholder="Admin password" aria-label="Admin password" required autofocus/>
<button type="submit">Sign in</button>
</form>
</Layout>
)
}
export interface AdminShareRow { share: ShareRecord, recipients: number, assets: number }
export interface AdminRecipientRow { recipient: Recipient, shares: ShareRecord[], sessions: number }
export interface AdminDashboardProps {
shares: AdminShareRow[]
recipients: AdminRecipientRow[]
comments: Array<CommentRecord & { shareTitle: string }>
emailEnabled: boolean
message?: { kind: 'ok' | 'error', text: string }
}
export function AdminDashboard ({ shares, recipients, comments, emailEnabled, message }: AdminDashboardProps) {
return (
<Layout title="Admin">
<nav>
<ul><li><strong>Admin</strong></li></ul>
<ul>
<li>
<form method="post" action="/admin/notify" style="margin:0">
<button type="submit" class="secondary outline" style="margin:0">Check for new photos now</button>
</form>
</li>
<li>
<form method="post" action="/admin/logout" style="margin:0">
<button type="submit" class="secondary outline" style="margin:0">Sign out</button>
</form>
</li>
</ul>
</nav>
{message && <Notice kind={message.kind}>{message.text}</Notice>}
{!emailEnabled && <Notice kind="error">Email is not configured (SMTP_URL or SMTP_HOST, plus PUBLIC_BASE_URL), so invitations and notifications can't be sent. You can still copy links by hand.</Notice>}
<section>
<h2>Albums</h2>
<p class="muted">Add an Immich shared link here, then give recipients access to it. Only recipients can open it through this proxy.</p>
{shares.length > 0 && (
<table>
<thead><tr><th>Album</th><th>Recipients</th><th>Photos tracked</th><th></th></tr></thead>
<tbody>
{shares.map(({ share, recipients: count, assets }) => (
<tr key={share.key}>
<td>{share.title || 'Untitled'}<br/><small class="muted">{share.slug ? 's/' + share.slug : share.key.slice(0, 12) + '…'}{share.password ? ' · password stored' : ''}</small></td>
<td>{count}</td>
<td>{assets}</td>
<td>
<form method="post" action={'/admin/shares/' + encodeURIComponent(share.key) + '/delete'}
data-confirm='Remove this album? Recipients lose access and its comments are deleted.'>
<button type="submit" class="secondary outline" style="margin:0;padding:.3rem .6rem;font-size:.8rem">Remove</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
)}
<details open={!shares.length}>
<summary role="button" class="outline">Add an album</summary>
<form method="post" action="/admin/shares">
<label>
Immich share link or key
<input name="link" required placeholder="https://immich.example.com/share/AbC123… or /s/my-album"/>
</label>
<label>
Share password <small class="muted">(only if the Immich link has one; stored so recipients aren't asked for it)</small>
<input type="password" name="password" autocomplete="off"/>
</label>
<button type="submit">Add album</button>
</form>
</details>
</section>
<section>
<h2>Recipients</h2>
{recipients.length > 0 && (
<table>
<thead><tr><th>Name</th><th>Albums</th><th>Emails</th><th>Signed-in browsers</th></tr></thead>
<tbody>
{recipients.map(({ recipient, shares: granted, sessions }) => (
<tr key={recipient.id}>
<td><a href={'/admin/recipients/' + recipient.id}>{recipient.name}</a>{recipient.disabled && <> <small>(disabled)</small></>}<br/><small class="muted">{recipient.email}</small></td>
<td>{granted.map(s => s.title).join(', ') || <span class="muted">none</span>}</td>
<td>{FREQUENCY_LABELS[recipient.frequency]}</td>
<td>{sessions}</td>
</tr>
))}
</tbody>
</table>
)}
{shares.length
? (
<details open={!recipients.length}>
<summary role="button" class="outline">Add a recipient</summary>
<form method="post" action="/admin/recipients">
<div class="grid">
<label>Name<input name="name" required/></label>
<label>Email<input type="email" name="email" required/></label>
</div>
<ShareChecks shares={shares.map(row => row.share)} selected={[]}/>
<FrequencySelect value="weekly"/>
<label><input type="checkbox" name="sendInvite" value="1" checked={emailEnabled} disabled={!emailEnabled}/> Email them their invitation link now</label>
<button type="submit">Add recipient</button>
</form>
</details>
)
: <p class="muted">Add an album first.</p>}
</section>
<section>
<h2>Recent comments</h2>
{comments.length
? (
<table>
<tbody>
{comments.map(comment => (
<tr key={comment.id}>
<td style="width:72px"><img src={'/admin/thumb/' + encodeURIComponent(comment.shareKey) + '/' + comment.assetId} alt="" width={64} height={64} style="object-fit:cover;border-radius:4px" loading="lazy"/></td>
<td><strong>{comment.authorName}</strong> on {comment.shareTitle}<br/><small class="muted">{new Date(comment.createdAt).toLocaleString('en-GB')}</small></td>
<td style="white-space:pre-wrap">{comment.body}</td>
<td>
<form method="post" action={'/admin/comments/' + comment.id + '/delete'}>
<button type="submit" class="secondary outline" style="margin:0;padding:.3rem .6rem;font-size:.8rem">Delete</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
)
: <p class="muted">No comments yet.</p>}
</section>
</Layout>
)
}
function ShareChecks ({ shares, selected }: { shares: ShareRecord[], selected: string[] }) {
return (
<fieldset class="checks">
<legend>Albums they can see</legend>
{shares.map(share => (
<label key={share.key}>
<input type="checkbox" name="shares" value={share.key} checked={selected.includes(share.key)}/>
{share.title || 'Untitled'}
</label>
))}
</fieldset>
)
}
function FrequencySelect ({ value }: { value: Frequency }) {
return (
<label>
New-photo emails
<select name="frequency">
{FREQUENCIES.map(frequency => <option key={frequency} value={frequency} selected={value === frequency}>{FREQUENCY_LABELS[frequency]}</option>)}
</select>
</label>
)
}
export interface AdminRecipientProps {
recipient: Recipient
shares: ShareRecord[]
granted: string[]
sessions: number
activeLinks: number
emailEnabled: boolean
/** A link created by this request; shown once, never stored in plain text. */
newLink?: string
message?: { kind: 'ok' | 'error', text: string }
}
export function AdminRecipient ({ recipient, shares, granted, sessions, activeLinks, emailEnabled, newLink, message }: AdminRecipientProps) {
const base = '/admin/recipients/' + recipient.id
return (
<Layout title={recipient.name + ' · Admin'}>
<p><a href="/admin">← Admin</a></p>
<h1>{recipient.name}</h1>
{message && <Notice kind={message.kind}>{message.text}</Notice>}
{newLink && (
<article>
<header><strong>Personal link for {recipient.name}</strong></header>
<p class="link-box">{newLink}</p>
<footer><small class="muted">Shown once. Anyone with this link can see their albums. It doesn't expire; revoke access below to cancel it.</small></footer>
</article>
)}
<form method="post" action={base}>
<div class="grid">
<label>Name<input name="name" required value={recipient.name}/></label>
<label>Email<input type="email" name="email" required value={recipient.email}/></label>
</div>
<ShareChecks shares={shares} selected={granted}/>
<FrequencySelect value={recipient.frequency}/>
<label><input type="checkbox" name="disabled" value="1" checked={recipient.disabled}/> Disabled (blocks all their links and sessions)</label>
<button type="submit">Save</button>
</form>
<h2>Access</h2>
<p>{sessions} signed-in browser{sessions === 1 ? '' : 's'} · {activeLinks} working link{activeLinks === 1 ? '' : 's'}</p>
<div class="row-actions">
<form method="post" action={base + '/link'}>
<button type="submit">Create a new link</button>
</form>
<form method="post" action={base + '/link'}>
<input type="hidden" name="send" value="1"/>
<button type="submit" disabled={!emailEnabled}>Email them a new link</button>
</form>
<form method="post" action={base + '/revoke'} data-confirm='Sign them out everywhere and cancel all their links?'>
<button type="submit" class="secondary">Revoke all access</button>
</form>
<form method="post" action={base + '/delete'} data-confirm='Delete this recipient? Their comments stay, unattributed to an account.'>
<button type="submit" class="secondary outline">Delete recipient</button>
</form>
</div>
</Layout>
)
}
+66
View File
@@ -0,0 +1,66 @@
import { Asset, AssetType, isId, isKey, KeyType, SharedLink, slugLinksDisabled } from '@ipp/core'
import { Request } from 'express-serve-static-core'
import { getShareByKey } from './immich'
import { findMotionPhotoStill } from './share'
/*
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.
*/
export type ShareResolution =
| { ok: true, link: SharedLink }
| { ok: false, status: number, reason: string, passwordRequired?: boolean }
export type SharedAssetResolution =
| { ok: true, link: SharedLink, asset: Asset }
| { ok: false, status: number, reason: string, passwordRequired?: boolean }
export async function resolveShare (req: Request, keyType: KeyType): Promise<ShareResolution> {
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 }
}
export async function resolveSharedAsset (req: Request, keyType: KeyType, allowMotion = false): Promise<SharedAssetResolution> {
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' }
}
+253
View File
@@ -0,0 +1,253 @@
import express, { Express } from 'express'
import {
addNoStoreHeaders,
addResponseHeaders,
Asset,
AssetType,
asyncHandler,
CORE_PUBLIC_DIR,
decodeCookie,
errorHandler,
getKeyTypeFromShare,
healthcheck,
isKey,
KeyType,
respondToInvalidRequest,
sessionMiddleware,
slugLinksDisabled,
unlockHandler
} from '@ipp/core'
import { fetchAssetDetail, handleShareRequest } from './immich'
import { buildAssetMetadata } from './gallery/metadata'
import { assetBuffer } from './stream/asset'
import { downloadAssets } from './stream/download'
import { ImageSize } from './types'
import { canDownload, uploadHealthcheck } from './share'
import { ASSET_VERSION } from './version'
import { resolveShare, resolveSharedAsset } from './resolve'
import { deny, loadRecipient, requireRecipient, requireShareAccess } from './magic/session'
import { registerRecipientRoutes, registerSignInRoutes } from './magic/routes'
import { registerAdminRoutes } from './magic/admin'
import { getStore } from './magic/store'
/**
* Build the Express app. Call `loadConfig` first: routes read config as they
* are registered.
*
* Every route that shows anything from Immich sits behind two gates: a
* magic-link session (`requireRecipient`), and that recipient having been
* given the specific share (`requireShareAccess`).
*/
export function createApp (): Express {
const app = express()
// Behind a reverse proxy, so req.ip and req.protocol reflect the visitor
app.set('trust proxy', process.env.TRUST_PROXY ?? 'loopback, linklocal, uniquelocal')
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<typeof express.static>[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.
// These hold only the app's own code and styles, never anything from Immich.
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')
/*
[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. Answers "nothing here" as a 204.
*/
const uploadProbe = uploadHealthcheck()
if (uploadProbe) {
app.get(uploadProbe, (_req, res) => {
addNoStoreHeaders(res)
res.status(204).end()
})
}
// Open the store now, so a bad DATA_DIR fails at startup rather than on the first visitor
getStore()
// ----- public: magic-link sign-in and the admin console ---------------------
app.use(loadRecipient)
registerSignInRoutes(app)
registerAdminRoutes(app)
// ----- everything below needs a magic-link session --------------------------
app.use(requireRecipient)
registerRecipientRoutes(app)
/*
[ROUTE] The main URL a visitor opens from a shared link
*/
app.get('/:shareType(share|s)/:key/:mode(download)?', requireShareAccess, decodeCookie, asyncHandler(async (req, res) => {
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. Only reachable for a
share without a stored password, and only for a recipient of that share.
*/
app.post('/share/unlock', (req, res, next) => {
const key = req.body?.key
if (typeof key !== 'string' || !isKey(key) || !getStore().grantedShare(req.recipient!.id, key)) {
deny(req, res, 'Unlock for a share the recipient was not given')
return
}
next()
}, 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', requireShareAccess, 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?', requireShareAccess, 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', requireShareAccess, 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] 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)
return app
}
+18
View File
@@ -98,6 +98,23 @@ export interface MetadataConfig {
locationWebLink: boolean locationWebLink: boolean
} }
/** Per-photo comments for the signed-in recipient. */
export interface CommentsConfig {
// `/share/comments/<key>`; append `/<assetId>`
base: string
// Comment count per asset id, for the toolbar badge
counts: Record<string, number>
}
/** One comment as the comments API returns it. */
export interface CommentView {
id: number
author: string
body: string
createdAt: string
mine: boolean
}
/** /**
* Shape of the JSON init block embedded in `gallery.tsx` and consumed by * Shape of the JSON init block embedded in `gallery.tsx` and consumed by
* `client/init.ts`. The server writes it via `jsonForInlineScript`; the * `client/init.ts`. The server writes it via `jsonForInlineScript`; the
@@ -110,4 +127,5 @@ export interface InitParams {
metadataConfig?: MetadataConfig metadataConfig?: MetadataConfig
groupByDate?: GroupByDateMode | false groupByDate?: GroupByDateMode | false
metaBase?: string metaBase?: string
comments?: CommentsConfig
} }
+17 -5
View File
@@ -1,8 +1,8 @@
import { AssetType, jsonForInlineScript, ThemeScript } from '@ipp/core' import { AssetType, jsonForInlineScript, ThemeScript } from '@ipp/core'
import { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types' import { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } from '../shared/types'
import { ASSET_VERSION } from '../version' import { ASSET_VERSION } from '../version'
export type { GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode } export type { CommentsConfig, GalleryItem, LightboxConfig, MetadataConfig, GroupByDateMode }
export interface GalleryProps { export interface GalleryProps {
items: GalleryItem[] items: GalleryItem[]
@@ -26,6 +26,10 @@ export interface GalleryProps {
// Set when the upload service is assumed rather than configured: the button // Set when the upload service is assumed rather than configured: the button
// stays hidden until the client finds this URL answering // stays hidden until the client finds this URL answering
uploadHealthcheck?: string uploadHealthcheck?: string
// Comments on each photo, for a signed-in recipient
comments?: CommentsConfig
// The recipient's albums and notification settings
accountLink?: string
} }
export function Gallery (props: GalleryProps) { export function Gallery (props: GalleryProps) {
@@ -35,7 +39,8 @@ export function Gallery (props: GalleryProps) {
lightboxConfig: props.lightboxConfig, lightboxConfig: props.lightboxConfig,
metadataConfig: props.metadataConfig, metadataConfig: props.metadataConfig,
groupByDate: props.groupByDate, groupByDate: props.groupByDate,
metaBase: props.metaBase metaBase: props.metaBase,
comments: props.comments
}) })
const firstItem = props.items[0] const firstItem = props.items[0]
// og:image prefers the album cover (passed via props); for videos, previewUrl // og:image prefers the album cover (passed via props); for videos, previewUrl
@@ -74,8 +79,8 @@ export function Gallery (props: GalleryProps) {
<link type="text/css" rel="stylesheet" href={`/share/static/${ASSET_VERSION}/photoswipe-overrides.css`}/> <link type="text/css" rel="stylesheet" href={`/share/static/${ASSET_VERSION}/photoswipe-overrides.css`}/>
</head> </head>
<body> <body>
{(showHeaderText || props.showDownloadZip || props.uploadLink) && ( {(showHeaderText || props.showDownloadZip || props.uploadLink || props.accountLink) && (
<header id="header" hidden={!showHeaderText && !props.showDownloadZip && !!props.uploadHealthcheck}> <header id="header" hidden={!showHeaderText && !props.showDownloadZip && !props.accountLink && !!props.uploadHealthcheck}>
{showHeaderText && ( {showHeaderText && (
<div class="header-text"> <div class="header-text">
{props.showTitle && <h1>{props.title || 'Gallery'}</h1>} {props.showTitle && <h1>{props.title || 'Gallery'}</h1>}
@@ -104,6 +109,13 @@ export function Gallery (props: GalleryProps) {
</svg> </svg>
</a> </a>
)} )}
{props.accountLink && (
<a id="account-link" class="header-action" href={props.accountLink} title="Your albums and email settings" aria-label="Your albums and email settings">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path fill="currentColor" d="M12,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z"/>
</svg>
</a>
)}
</div> </div>
</header> </header>
)} )}
+461
View File
@@ -0,0 +1,461 @@
import express from 'express'
import { Server } from 'http'
import { AddressInfo } from 'net'
import { resolve } from 'path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { loadConfig } from '@ipp/core'
import { Recipient, setStore, Store } from '../src/magic/store'
import { Mail, setMailSender } from '../src/magic/mailer'
/*
End to end: the real app in front of a fake Immich. Proves that nothing is
reachable without a magic-link session, that a session only opens the
shares its recipient was given, and that comments, sign-out and the admin
console behave.
*/
const KEY_A = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
const KEY_B = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
const KEY_C = 'ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc'
const KEY_P = 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp'
const ASSET_1 = '11111111-1111-4111-8111-111111111111'
const ASSET_2 = '22222222-2222-4222-8222-222222222222'
const ASSET_B = '33333333-3333-4333-8333-333333333333'
const ASSET_P = '44444444-4444-4444-8444-444444444444'
const asset = (id: string) => ({
id,
type: 'IMAGE',
isTrashed: false,
visibility: 'timeline',
thumbhash: 'AAAA',
originalFileName: id + '.jpg',
originalMimeType: 'image/jpeg',
width: 400,
height: 300,
fileCreatedAt: '2026-01-01T00:00:00.000Z'
})
const link = (key: string, title: string, slug: string | null, assetIds: string[]) => ({
id: key.slice(0, 8),
key,
slug,
type: 'INDIVIDUAL',
description: title,
assets: assetIds.map(asset),
allowDownload: true,
allowUpload: false,
showMetadata: true,
expiresAt: null
})
const links: Record<string, ReturnType<typeof link>> = {
[KEY_A]: link(KEY_A, 'Holiday', 'holiday', [ASSET_1, ASSET_2]),
[KEY_B]: link(KEY_B, 'Wedding', null, [ASSET_B]),
[KEY_C]: link(KEY_C, 'Garden', null, [ASSET_1]),
[KEY_P]: link(KEY_P, 'Private party', null, [ASSET_P])
}
const PASSWORD = 'party-pw'
const IMMICH_TOKEN = 'immich-token-for-p'
let immichCalls = 0
let immich: Server
let server: Server
let base: string
let store: Store
const mails: Mail[] = []
let ann: Recipient
let bob: Recipient
let annLink: string
function startImmich (): Promise<Server> {
const fake = express()
fake.use(express.json())
fake.use((_req, _res, next) => { immichCalls++; next() })
fake.get('/api/server/version', (_req, res) => { res.json({ major: 3, minor: 0, patch: 0 }) })
fake.post('/api/shared-links/login', (req, res) => {
if (req.query.key === KEY_P && req.body?.password === PASSWORD) {
res.status(201).set('Set-Cookie', 'immich_shared_link_token=' + IMMICH_TOKEN + '; Path=/').json({})
} else {
res.status(401).json({ message: 'Invalid password' })
}
})
fake.get('/api/shared-links/me', (req, res) => {
const key = typeof req.query.key === 'string'
? req.query.key
: Object.values(links).find(l => l.slug === req.query.slug)?.key
const found = key ? links[key] : undefined
if (!found) {
res.status(401).json({ message: 'Invalid share key' })
} else if (key === KEY_P && !(req.headers.cookie || '').includes(IMMICH_TOKEN)) {
res.status(401).json({ message: 'Password required' })
} else {
res.json(found)
}
})
fake.get('/api/assets/:id/:kind', (req, res) => {
res.type('image/jpeg').send(Buffer.from('JPEG:' + req.params.id))
})
return new Promise(resolve => {
const s = fake.listen(0, '127.0.0.1', () => resolve(s))
})
}
beforeAll(async () => {
immich = await startImmich()
process.env.IMMICH_URL = 'http://127.0.0.1:' + (immich.address() as AddressInfo).port
process.env.ADMIN_PASSWORD = 'admin-secret'
process.env.SMTP_HOST = 'smtp.invalid'
process.env.PUBLIC_BASE_URL = ''
loadConfig({ defaultPath: resolve(__dirname, '../config.json') })
store = new Store(':memory:')
setStore(store)
setMailSender(async mail => { mails.push(mail) })
const now = new Date().toISOString()
store.upsertShare({ key: KEY_A, slug: 'holiday', title: 'Holiday', password: null }, now)
store.upsertShare({ key: KEY_B, slug: null, title: 'Wedding', password: null }, now)
store.upsertShare({ key: KEY_P, slug: null, title: 'Private party', password: PASSWORD }, now)
ann = store.createRecipient({ name: 'Ann', email: 'ann@example.com', frequency: 'off' }, now)
bob = store.createRecipient({ name: 'Bob', email: 'bob@example.com', frequency: 'off' }, now)
store.setRecipientShares(ann.id, [KEY_A], new Date().toISOString())
store.setRecipientShares(bob.id, [KEY_B], new Date().toISOString())
annLink = '/m/' + store.createMagicLink(ann.id, { purpose: 'invite', expiresAt: null }, now)
const { createApp } = await import('../src/server')
server = await new Promise(resolve => {
const s = createApp().listen(0, '127.0.0.1', () => resolve(s))
})
base = 'http://127.0.0.1:' + (server.address() as AddressInfo).port
})
afterAll(async () => {
setMailSender(undefined)
setStore(undefined)
store.close()
await new Promise(resolve => server.close(resolve))
await new Promise(resolve => immich.close(resolve))
})
interface Options {
cookie?: string
page?: boolean
method?: string
json?: unknown
form?: Record<string, string | string[]>
}
async function request (path: string, options: Options = {}) {
const headers: Record<string, string> = {}
if (options.cookie) headers.Cookie = options.cookie
if (options.page) headers.Accept = 'text/html,application/xhtml+xml'
let body: string | undefined
if (options.json !== undefined) {
headers['Content-Type'] = 'application/json'
body = JSON.stringify(options.json)
} else if (options.form) {
headers['Content-Type'] = 'application/x-www-form-urlencoded'
const params = new URLSearchParams()
for (const [k, v] of Object.entries(options.form)) for (const one of [v].flat()) params.append(k, one)
body = params.toString()
}
const res = await fetch(base + path, { method: options.method || (body ? 'POST' : 'GET'), headers, body, redirect: 'manual' })
return { res, text: await res.text() }
}
/** The `name=value` pair a response set for cookie `name`. */
function cookieFrom (res: Response, name: string): string | undefined {
const header = res.headers.getSetCookie().find(c => c.startsWith(name + '='))
return header?.split(';')[0]
}
async function signIn (path = annLink): Promise<string> {
const { res } = await request(path, { page: true })
const cookie = cookieFrom(res, 'imp_session')
if (!cookie) throw new Error('No session cookie from ' + path)
return cookie
}
const settle = () => new Promise(resolve => setTimeout(resolve, 50))
describe('without a magic-link session', () => {
it('shows nothing, and never asks Immich', async () => {
const before = immichCalls
const page = await request('/share/' + KEY_A, { page: true })
expect(page.res.status).toBe(401)
expect(page.text).toContain('personal invitation link')
expect(page.text).not.toContain('Holiday')
for (const path of [
'/share/photo/' + KEY_A + '/' + ASSET_1 + '/thumbnail',
'/share/video/' + KEY_A + '/' + ASSET_1,
'/share/meta/' + KEY_A + '/' + ASSET_1,
'/share/comments/' + KEY_A + '/' + ASSET_1,
'/share/' + KEY_A + '/download'
]) {
const { res, text } = await request(path)
expect(res.status, path).toBe(404)
expect(text, path).toBe('')
}
expect((await request('/s/holiday', { page: true })).res.status).toBe(401)
expect((await request('/', { page: true })).res.status).toBe(401)
expect((await request('/me', { page: true })).res.status).toBe(401)
expect((await request('/share/unlock', { json: { key: KEY_A, password: 'x' } })).res.status).toBe(404)
expect(immichCalls).toBe(before)
})
it('still serves the app\'s own static files', async () => {
expect((await request('/share/static/pico.min.css')).res.status).toBe(200)
})
it('refuses an unknown magic link', async () => {
const { res, text } = await request('/m/' + 'x'.repeat(43), { page: true })
expect(res.status).toBe(401)
expect(text).toContain('no longer valid')
expect(cookieFrom(res, 'imp_session')).toBeUndefined()
})
})
describe('signing in with a magic link', () => {
it('sets a long-lived, HttpOnly cookie and lands on the only album', async () => {
const { res } = await request(annLink, { page: true })
expect(res.status).toBe(303)
expect(res.headers.get('location')).toBe('/share/' + KEY_A)
const header = res.headers.getSetCookie().find(c => c.startsWith('imp_session='))!
expect(header).toContain('Max-Age=34560000')
expect(header).toContain('HttpOnly')
expect(header).toContain('SameSite=Lax')
expect(res.headers.get('referrer-policy')).toBe('no-referrer')
})
it('honours a same-site next path, and ignores an off-site one', async () => {
expect((await request(annLink + '?next=%2Fme', { page: true })).res.headers.get('location')).toBe('/me')
expect((await request(annLink + '?next=%2F%2Fevil.example', { page: true })).res.headers.get('location')).toBe('/share/' + KEY_A)
})
it('reuses the browser\'s existing session for the same recipient', async () => {
const cookie = await signIn()
const { res } = await request(annLink, { page: true, cookie })
expect(cookieFrom(res, 'imp_session')).toBeUndefined()
})
})
describe('a signed-in recipient', () => {
let cookie: string
beforeAll(async () => { cookie = await signIn() })
it('sees their album, by key and by slug, with comments and an account link', async () => {
const { res, text } = await request('/share/' + KEY_A, { page: true, cookie })
expect(res.status).toBe(200)
expect(text).toContain('Holiday')
expect(text).toContain('/share/comments/' + KEY_A)
expect(text).toContain('id="account-link"')
expect(res.headers.get('cache-control')).toBe('private, no-cache')
expect((await request('/s/holiday', { page: true, cookie })).res.status).toBe(200)
})
it('can load its photos, cached privately only', async () => {
const { res, text } = await request('/share/photo/' + KEY_A + '/' + ASSET_1 + '/thumbnail', { cookie })
expect(res.status).toBe(200)
expect(text).toBe('JPEG:' + ASSET_1)
expect(res.headers.get('cache-control')).toMatch(/^private/)
expect(res.headers.get('access-control-allow-origin')).toBeNull()
})
it('cannot see an album it was not given, or its photos', async () => {
const page = await request('/share/' + KEY_B, { page: true, cookie })
expect(page.res.status).toBe(404)
expect(page.text).not.toContain('Wedding')
expect((await request('/share/photo/' + KEY_B + '/' + ASSET_B + '/thumbnail', { cookie })).res.status).toBe(404)
// Its own share key cannot be used to pull another share's photo
expect((await request('/share/photo/' + KEY_A + '/' + ASSET_B + '/thumbnail', { cookie })).res.status).toBe(404)
})
it('lists its albums on /me, which / redirects to', async () => {
const root = await request('/', { page: true, cookie })
expect(root.res.status).toBe(303)
expect(root.res.headers.get('location')).toBe('/me')
const me = await request('/me', { page: true, cookie })
expect(me.text).toContain('Holiday')
expect(me.text).not.toContain('Wedding')
})
it('chooses how often it hears about new photos', async () => {
const { res, text } = await request('/me/notifications', { cookie, form: { frequency: 'weekly' } })
expect(res.status).toBe(200)
expect(text).toContain('Saved.')
expect(store.getRecipient(ann.id)).toMatchObject({ frequency: 'weekly' })
expect(store.getRecipient(ann.id)?.lastDigestAt).toBeTruthy()
await request('/me/notifications', { cookie, form: { frequency: 'monthly-ish' } })
expect(store.getRecipient(ann.id)?.frequency).toBe('weekly')
})
it('is never asked for a password the admin stored', async () => {
store.setRecipientShares(ann.id, [KEY_A, KEY_P], new Date().toISOString())
try {
const { res, text } = await request('/share/' + KEY_P, { page: true, cookie })
expect(res.status).toBe(200)
expect(text).toContain('Private party')
expect(text).not.toContain('type="password"')
} finally {
store.setRecipientShares(ann.id, [KEY_A], new Date().toISOString())
}
})
})
describe('comments', () => {
let annCookie: string
let bobCookie: string
const path = '/share/comments/' + KEY_A + '/' + ASSET_1
beforeAll(async () => {
annCookie = await signIn()
bobCookie = await signIn('/m/' + store.createMagicLink(bob.id, { purpose: 'invite', expiresAt: null }, new Date().toISOString()))
})
it('accepts JSON only, and checks length', async () => {
expect((await request(path, { cookie: annCookie, form: { body: 'hi' } })).res.status).toBe(415)
expect((await request(path, { cookie: annCookie, json: { body: ' ' } })).res.status).toBe(400)
expect((await request(path, { cookie: annCookie, json: { body: 'x'.repeat(2001) } })).res.status).toBe(400)
})
it('posts, lists, counts and deletes', async () => {
const posted = await request(path, { cookie: annCookie, json: { body: 'Lovely <b>light</b>' } })
expect(posted.res.status).toBe(201)
const comment = JSON.parse(posted.text)
expect(comment).toMatchObject({ author: 'Ann', body: 'Lovely <b>light</b>', mine: true })
const listed = JSON.parse((await request(path, { cookie: annCookie })).text)
expect(listed).toHaveLength(1)
const gallery = await request('/share/' + KEY_A, { page: true, cookie: annCookie })
expect(gallery.text).toContain('"counts":{"' + ASSET_1 + '":1}')
expect((await request(path + '/' + comment.id, { cookie: annCookie, method: 'DELETE' })).res.status).toBe(204)
expect(JSON.parse((await request(path, { cookie: annCookie })).text)).toEqual([])
})
it('cannot be read or written by someone without the album', async () => {
expect((await request(path, { cookie: bobCookie })).res.status).toBe(404)
expect((await request(path, { cookie: bobCookie, json: { body: 'sneaky' } })).res.status).toBe(404)
})
it('only on photos in the album', async () => {
const res = await request('/share/comments/' + KEY_A + '/' + ASSET_B, { cookie: annCookie, json: { body: 'wrong album' } })
expect(res.res.status).toBe(404)
})
it('cannot be deleted by another recipient', async () => {
// Give Bob the album too, then try to delete Ann's comment
store.setRecipientShares(bob.id, [KEY_A, KEY_B], new Date().toISOString())
try {
const comment = JSON.parse((await request(path, { cookie: annCookie, json: { body: 'mine' } })).text)
const asBob = JSON.parse((await request(path, { cookie: bobCookie })).text)
expect(asBob[0]).toMatchObject({ author: 'Ann', mine: false })
expect((await request(path + '/' + comment.id, { cookie: bobCookie, method: 'DELETE' })).res.status).toBe(404)
expect(store.getComment(comment.id)).toBeDefined()
} finally {
store.setRecipientShares(bob.id, [KEY_B], new Date().toISOString())
}
})
})
describe('ending access', () => {
it('signing out ends the session for good', async () => {
const cookie = await signIn()
const out = await request('/logout', { cookie, method: 'POST' })
expect(out.res.status).toBe(303)
expect((await request('/share/' + KEY_A, { page: true, cookie })).res.status).toBe(401)
})
it('a disabled recipient is locked out of an existing session', async () => {
const cara = store.createRecipient({ name: 'Cara', email: 'cara@example.com', frequency: 'off' }, new Date().toISOString())
store.setRecipientShares(cara.id, [KEY_A], new Date().toISOString())
const cookie = await signIn('/m/' + store.createMagicLink(cara.id, { purpose: 'invite', expiresAt: null }, new Date().toISOString()))
expect((await request('/share/' + KEY_A, { page: true, cookie })).res.status).toBe(200)
store.updateRecipient(cara.id, { name: 'Cara', email: 'cara@example.com', disabled: true })
expect((await request('/share/' + KEY_A, { page: true, cookie })).res.status).toBe(401)
})
})
describe('lost links', () => {
it('answers the same for unknown and known addresses, and emails only the known one', async () => {
mails.length = 0
const unknown = await request('/access', { form: { email: 'nobody@example.com' } })
expect(unknown.text).toContain('Check your email')
await settle()
expect(mails).toEqual([])
const known = await request('/access', { form: { email: 'ANN@example.com' } })
expect(known.text).toBe(unknown.text)
await settle()
expect(mails).toHaveLength(1)
expect(mails[0].to).toBe('ann@example.com')
const link = mails[0].text.match(/\/m\/[\w-]+/)![0]
expect((await request(link, { page: true })).res.status).toBe(303)
// A second request straight away is not emailed
await request('/access', { form: { email: 'ann@example.com' } })
await settle()
expect(mails).toHaveLength(1)
})
})
describe('admin console', () => {
let admin: string
it('asks for the password, and rejects a wrong one', async () => {
expect((await request('/admin', { page: true })).text).toContain('Admin password')
expect((await request('/admin/login', { form: { password: 'nope' } })).res.status).toBe(401)
expect((await request('/admin/shares', { form: { link: KEY_C } })).res.status).toBe(403)
})
it('signs in with a strict, path-scoped cookie', async () => {
const { res } = await request('/admin/login', { form: { password: 'admin-secret' } })
expect(res.status).toBe(303)
const header = res.headers.getSetCookie().find(c => c.startsWith('imp_admin='))!
expect(header).toContain('Path=/admin')
expect(header).toContain('SameSite=Strict')
admin = cookieFrom(res, 'imp_admin')!
const dashboard = await request('/admin', { page: true, cookie: admin })
expect(dashboard.text).toContain('Holiday')
expect(dashboard.text).toContain('Wedding')
})
it('adds an album from a pasted link', async () => {
const { text } = await request('/admin/shares', { cookie: admin, form: { link: 'https://immich.example.com/share/' + KEY_C } })
expect(text).toMatch(/Added (&quot;|")Garden(&quot;|")/)
expect(store.getShare(KEY_C)?.title).toBe('Garden')
// Its photos are recorded as already there, so nobody is notified about them
expect(store.countKnownAssets(KEY_C)).toBe(1)
})
it('rejects a share Immich does not know, and a missing password', async () => {
expect((await request('/admin/shares', { cookie: admin, form: { link: 'not-a-real-key' } })).text).toMatch(/didn(&#39;|')t accept/)
expect((await request('/admin/shares', { cookie: admin, form: { link: KEY_P } })).text).toContain('enter it too')
})
it('invites a recipient by email with a working link', async () => {
mails.length = 0
const { text } = await request('/admin/recipients', {
cookie: admin,
form: { name: 'Dee', email: 'dee@example.com', frequency: 'weekly', shares: [KEY_C], sendInvite: '1' }
})
expect(text).toContain('Invitation emailed to dee@example.com')
expect(mails).toHaveLength(1)
expect(mails[0].text).toContain('Garden')
const linkPath = mails[0].text.match(/\/m\/[\w-]+/)![0]
expect(text).toContain(linkPath)
const { res } = await request(linkPath, { page: true })
expect(res.headers.get('location')).toBe('/share/' + KEY_C)
})
it('revoking a recipient cancels their links and sessions', async () => {
const dee = store.getRecipientByEmail('dee@example.com')!
const linkPath = '/m/' + store.createMagicLink(dee.id, { purpose: 'invite', expiresAt: null }, new Date().toISOString())
const cookie = await signIn(linkPath)
await request('/admin/recipients/' + dee.id + '/revoke', { cookie: admin, method: 'POST' })
expect((await request('/share/' + KEY_C, { page: true, cookie })).res.status).toBe(401)
expect((await request(linkPath, { page: true })).res.status).toBe(401)
})
})
+147
View File
@@ -0,0 +1,147 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { Store } from '../src/magic/store'
import { nextDigestDue, scanShares, sendDueDigests } from '../src/magic/digest'
import { Mail } from '../src/magic/mailer'
const HOUR = 8
// Digests are scheduled in server-local time, so build every time locally
const at = (month: number, day: number, hour: number, minute = 0) => new Date(2026, month - 1, day, hour, minute)
const iso = (month: number, day: number, hour: number, minute = 0) => at(month, day, hour, minute).toISOString()
describe('nextDigestDue', () => {
it('lands on the next daily / weekly / monthly boundary at the digest hour', () => {
const start = iso(3, 10, 15, 30)
expect(nextDigestDue('daily', start, HOUR)).toEqual(at(3, 11, HOUR))
expect(nextDigestDue('weekly', start, HOUR)).toEqual(at(3, 17, HOUR))
expect(nextDigestDue('monthly', start, HOUR)).toEqual(at(4, 10, HOUR))
})
it('is never due when off or without a window', () => {
expect(nextDigestDue('off', iso(3, 10, 0))).toBeUndefined()
expect(nextDigestDue('daily', null)).toBeUndefined()
})
})
describe('scan and digest', () => {
let store: Store
let sent: Mail[]
const send = async (mail: Mail) => { sent.push(mail) }
const baseUrl = 'https://photos.example.com'
beforeEach(() => {
store = new Store(':memory:')
sent = []
})
afterEach(() => store.close())
function setup (frequency: 'daily' | 'weekly' | 'off' = 'daily') {
const share = store.upsertShare({ key: 'key-a', slug: null, title: 'Holiday', password: null }, iso(3, 1, 0))
const ann = store.createRecipient({ name: 'Ann', email: 'ann@example.com', frequency }, iso(3, 2, 10))
store.setRecipientShares(ann.id, [share.key], iso(3, 2, 10))
return { share, ann }
}
const digest = (now: Date, current: Map<string, Set<string>>, sender = send) =>
sendDueDigests({ store, send: sender, baseUrl, now, hour: HOUR }, current)
it('treats the first scan as a baseline, then reports only later photos', async () => {
setup()
let assets = ['a', 'b']
const list = async () => assets
// Baseline: photos already there are dated to when the share was added
await scanShares(store, list, iso(3, 2, 12))
assets = ['a', 'b', 'c']
const current = await scanShares(store, list, iso(3, 2, 13))
// Next morning, after the digest hour
expect(await digest(at(3, 3, HOUR, 5), current)).toBe(1)
expect(sent[0].to).toBe('ann@example.com')
expect(sent[0].subject).toContain('1 new photo')
expect(sent[0].text).toContain('Holiday')
// Links sign the recipient in and land on the album
expect(sent[0].text).toMatch(/https:\/\/photos\.example\.com\/m\/[\w-]+\?next=%2Fshare%2Fkey-a/)
})
it('waits until the digest is due, then does not repeat it', async () => {
const { ann } = setup()
await scanShares(store, async () => ['a'], iso(3, 2, 12))
const current = await scanShares(store, async () => ['a', 'b'], iso(3, 2, 13))
expect(await digest(at(3, 3, HOUR - 1), current)).toBe(0)
expect(await digest(at(3, 3, HOUR), current)).toBe(1)
expect(store.getRecipient(ann.id)?.lastDigestAt).toBe(iso(3, 3, HOUR))
expect(await digest(at(3, 3, HOUR + 5), current)).toBe(0)
})
it('sends nothing to recipients who opted out', async () => {
setup('off')
await scanShares(store, async () => ['a'], iso(3, 2, 12))
const current = await scanShares(store, async () => ['a', 'b'], iso(3, 2, 13))
expect(await digest(at(6, 1, HOUR), current)).toBe(0)
expect(sent).toEqual([])
})
it('sends nothing when nothing is new, but still moves the window on', async () => {
const { ann } = setup()
const current = await scanShares(store, async () => ['a'], iso(3, 2, 12))
expect(await digest(at(3, 3, HOUR), current)).toBe(0)
expect(store.getRecipient(ann.id)?.lastDigestAt).toBe(iso(3, 3, HOUR))
})
it('does not count photos removed before the digest', async () => {
setup()
await scanShares(store, async () => ['a'], iso(3, 2, 12))
await scanShares(store, async () => ['a', 'b'], iso(3, 2, 13))
const current = await scanShares(store, async () => ['a'], iso(3, 2, 14))
expect(await digest(at(3, 3, HOUR), current)).toBe(0)
})
it('keeps the window open when sending fails, so the next run retries', async () => {
const { ann } = setup()
await scanShares(store, async () => ['a'], iso(3, 2, 12))
const current = await scanShares(store, async () => ['a', 'b'], iso(3, 2, 13))
const failing = async () => { throw new Error('SMTP down') }
expect(await digest(at(3, 3, HOUR), current, failing)).toBe(0)
expect(store.getRecipient(ann.id)?.lastDigestAt).toBe(iso(3, 2, 10))
expect(await digest(at(3, 3, HOUR + 1), current)).toBe(1)
})
it('picks up photos added while Immich was unreachable on the next good scan', async () => {
setup()
await scanShares(store, async () => ['a'], iso(3, 2, 12))
const failed = await scanShares(store, async () => null, iso(3, 2, 13))
expect(failed.size).toBe(0)
const current = await scanShares(store, async () => ['a', 'b'], iso(3, 3, 7))
expect(await digest(at(3, 3, HOUR), current)).toBe(1)
})
it('does not report photos that were in an album before the recipient got it', async () => {
const { ann } = setup()
// An album added and granted to Ann after her window opened
store.upsertShare({ key: 'key-b', slug: null, title: 'Wedding', password: null }, iso(3, 2, 14))
const list = async (share: { key: string }) => share.key === 'key-a' ? ['a'] : ['b1', 'b2', 'b3']
await scanShares(store, list, iso(3, 2, 14))
store.setRecipientShares(ann.id, ['key-a', 'key-b'], iso(3, 2, 15))
const current = await scanShares(store, list, iso(3, 2, 16))
expect(await digest(at(3, 3, HOUR), current)).toBe(0)
})
it('groups several albums into one email', async () => {
const { ann } = setup()
store.upsertShare({ key: 'key-b', slug: null, title: 'Wedding', password: null }, iso(3, 1, 0))
store.setRecipientShares(ann.id, ['key-a', 'key-b'], iso(3, 2, 10))
let a = ['a1']
let b = ['b1']
const list = async (share: { key: string }) => share.key === 'key-a' ? a : b
await scanShares(store, list, iso(3, 2, 12))
a = ['a1', 'a2', 'a3']
b = ['b1', 'b2']
const current = await scanShares(store, list, iso(3, 2, 13))
expect(await digest(at(3, 3, HOUR), current)).toBe(1)
expect(sent[0].subject).toContain('3 new photos')
expect(sent[0].text).toContain('2 new photos in Holiday')
expect(sent[0].text).toContain('1 new photo in Wedding')
})
})
+157
View File
@@ -0,0 +1,157 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { Store } from '../src/magic/store'
import { hashToken, safeNextPath } from '../src/magic/tokens'
const T0 = '2026-01-01T00:00:00.000Z'
const T1 = '2026-01-02T00:00:00.000Z'
const T2 = '2026-01-03T00:00:00.000Z'
let store: Store
beforeEach(() => {
store = new Store(':memory:')
})
afterEach(() => {
store.close()
})
function recipient (email = 'ann@example.com', frequency: 'off' | 'daily' = 'off') {
return store.createRecipient({ name: 'Ann', email, frequency }, T0)
}
describe('magic links', () => {
it('signs in the recipient a live link belongs to', () => {
const ann = recipient()
const token = store.createMagicLink(ann.id, { purpose: 'invite', expiresAt: null }, T0)
expect(store.useMagicLink(token, T1)?.id).toBe(ann.id)
})
it('stores only a hash of the token', () => {
const ann = recipient()
const token = store.createMagicLink(ann.id, { purpose: 'invite', expiresAt: null }, T0)
const rows = store.db.prepare('SELECT token_hash FROM magic_links').all()
expect(rows).toEqual([{ token_hash: hashToken(token) }])
})
it('refuses an expired link, an unknown link, and a disabled recipient', () => {
const ann = recipient()
const expiring = store.createMagicLink(ann.id, { purpose: 'sign-in', expiresAt: T1 }, T0)
expect(store.useMagicLink(expiring, T1)).toBeUndefined()
expect(store.useMagicLink('not-a-real-token-at-all', T0)).toBeUndefined()
const forever = store.createMagicLink(ann.id, { purpose: 'invite', expiresAt: null }, T0)
store.updateRecipient(ann.id, { name: 'Ann', email: ann.email, disabled: true })
expect(store.useMagicLink(forever, T1)).toBeUndefined()
})
it('revoking access ends sessions and every link', () => {
const ann = recipient()
const link = store.createMagicLink(ann.id, { purpose: 'invite', expiresAt: null }, T0)
const session = store.createSession(ann.id, T0)
store.revokeAccess(ann.id)
expect(store.useMagicLink(link, T1)).toBeUndefined()
expect(store.getSession(session)).toBeUndefined()
})
it('rate-limits self-service link requests per address', () => {
expect(store.allowLinkRequest('ann@example.com', T1, T0)).toBe(true)
// Within the interval: refused
expect(store.allowLinkRequest('ANN@example.com', T1, T0)).toBe(false)
// After it: allowed
expect(store.allowLinkRequest('ann@example.com', T2, T1)).toBe(true)
})
})
describe('share access', () => {
it('grants a share by key or slug, only to recipients it was given to', () => {
const ann = recipient()
const bob = recipient('bob@example.com')
store.upsertShare({ key: 'key-a', slug: 'holiday', title: 'Holiday', password: null }, T0)
store.upsertShare({ key: 'key-b', slug: null, title: 'Other', password: null }, T0)
store.setRecipientShares(ann.id, ['key-a'], T0)
expect(store.grantedShare(ann.id, 'key-a')?.title).toBe('Holiday')
expect(store.grantedShare(ann.id, 'holiday')?.key).toBe('key-a')
expect(store.grantedShare(ann.id, 'key-b')).toBeUndefined()
expect(store.grantedShare(bob.id, 'key-a')).toBeUndefined()
})
it('keeps the original grant time when the grants are saved again', () => {
const ann = recipient()
store.upsertShare({ key: 'key-a', slug: null, title: 'A', password: null }, T0)
store.upsertShare({ key: 'key-b', slug: null, title: 'B', password: null }, T0)
store.setRecipientShares(ann.id, ['key-a'], T0)
store.setRecipientShares(ann.id, ['key-a', 'key-b'], T2)
expect(store.listRecipientShares(ann.id).map(s => [s.key, s.grantedAt])).toEqual([['key-a', T0], ['key-b', T2]])
store.setRecipientShares(ann.id, [], T2)
expect(store.listRecipientShares(ann.id)).toEqual([])
})
it('ignores grants for shares that do not exist', () => {
const ann = recipient()
store.setRecipientShares(ann.id, ['missing'], T0)
expect(store.listRecipientShares(ann.id)).toEqual([])
})
it('removing a share removes its grants and comments', () => {
const ann = recipient()
store.upsertShare({ key: 'key-a', slug: null, title: 'A', password: null }, T0)
store.setRecipientShares(ann.id, ['key-a'], T0)
store.addComment({ shareKey: 'key-a', assetId: 'x', recipient: ann, body: 'hi' }, T0)
store.deleteShare('key-a')
expect(store.grantedShare(ann.id, 'key-a')).toBeUndefined()
expect(store.countComments('key-a')).toEqual({})
})
})
describe('notification windows', () => {
it('opens the window when digests are turned on, not before', () => {
const ann = recipient()
expect(store.getRecipient(ann.id)?.lastDigestAt).toBeNull()
store.setFrequency(ann.id, 'weekly', T1)
expect(store.getRecipient(ann.id)?.lastDigestAt).toBe(T1)
// Switching between on-frequencies keeps the window
store.setFrequency(ann.id, 'daily', T2)
expect(store.getRecipient(ann.id)?.lastDigestAt).toBe(T1)
})
it('a recipient created with digests on starts their window then', () => {
expect(recipient('c@example.com', 'daily').lastDigestAt).toBe(T0)
})
it('finds assets first seen inside a window', () => {
store.upsertShare({ key: 'k', slug: null, title: 'K', password: null }, T0)
store.addAssets('k', ['old'], T0)
store.addAssets('k', ['new'], T1)
// A repeat insert keeps the first sighting
store.addAssets('k', ['old'], T2)
expect(store.assetsSeenBetween('k', T0, T2)).toEqual(['new'])
})
})
describe('comments', () => {
it('counts per asset and keeps the author name if the recipient is deleted', () => {
const ann = recipient()
store.upsertShare({ key: 'k', slug: null, title: 'K', password: null }, T0)
store.addComment({ shareKey: 'k', assetId: 'a', recipient: ann, body: 'one' }, T0)
store.addComment({ shareKey: 'k', assetId: 'a', recipient: ann, body: 'two' }, T1)
store.addComment({ shareKey: 'k', assetId: 'b', recipient: ann, body: 'three' }, T1)
expect(store.countComments('k')).toEqual({ a: 2, b: 1 })
store.deleteRecipient(ann.id)
const [first] = store.listComments('k', 'a')
expect(first).toMatchObject({ authorName: 'Ann', recipientId: null, body: 'one' })
})
})
describe('safeNextPath', () => {
it('allows same-site paths only', () => {
expect(safeNextPath('/share/abc')).toBe('/share/abc')
expect(safeNextPath('//evil.example.com')).toBeUndefined()
expect(safeNextPath('/\\evil.example.com')).toBeUndefined()
expect(safeNextPath('https://evil.example.com')).toBeUndefined()
expect(safeNextPath('/x\r\nSet-Cookie: a=b')).toBeUndefined()
expect(safeNextPath(['/a'])).toBeUndefined()
})
})
+18 -25
View File
@@ -1,7 +1,8 @@
services: services:
immich-public-proxy: immich-magic-proxy:
image: alangrainger/immich-public-proxy:latest build: .
container_name: immich-public-proxy image: immich-magic-proxy:latest
container_name: immich-magic-proxy
restart: always restart: always
ports: ports:
- "3000:3000" - "3000:3000"
@@ -10,32 +11,24 @@ services:
- ALL - ALL
security_opt: security_opt:
- no-new-privileges - no-new-privileges
volumes:
# Recipients, sessions, comments and notification state. Back this up.
# The container runs as uid 1000, which must be able to write here.
- ./data:/data
environment: environment:
PUBLIC_BASE_URL: https://your-proxy-url.com PUBLIC_BASE_URL: https://your-proxy-url.com
IMMICH_URL: http://your-internal-immich-server:2283 IMMICH_URL: http://your-internal-immich-server:2283
# Turns on the /admin console, where you add albums and recipients
ADMIN_PASSWORD: change-me-to-something-long
# Email for invitations and new-photo notifications. Either a URL...
SMTP_URL: smtp://user:password@smtp.example.com:587
# ...or SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS (and SMTP_SECURE=true for port 465)
MAIL_FROM: "Our photos <photos@example.com>"
SITE_NAME: Our photos
# Notifications go out at this hour, in this timezone
DIGEST_HOUR: 8
TZ: Etc/UTC
healthcheck: healthcheck:
test: curl -sf -m 4 http://localhost:3000/share/healthcheck -o /dev/null || exit 1 test: curl -sf -m 4 http://localhost:3000/share/healthcheck -o /dev/null || exit 1
start_period: 10s start_period: 10s
timeout: 5s timeout: 5s
# Optional: let visitors send photos back to Immich.
# Uncomment this service and see https://docs.ipp.nz/visitor-uploads
#
# ipp-upload:
# image: alangrainger/immich-public-proxy-upload:latest
# container_name: ipp-upload
# restart: always
# ports:
# - "3001:3000"
# read_only: true
# cap_drop:
# - ALL
# security_opt:
# - no-new-privileges
# environment:
# IMMICH_URL: http://your-internal-immich-server:2283
# PUBLIC_BASE_URL: https://your-proxy-url.com # IPP's URL, not this container's
# healthcheck:
# test: curl -sf -m 4 http://localhost:3000/healthcheck -o /dev/null || exit 1
# start_period: 10s
# timeout: 5s
+2 -2
View File
@@ -74,9 +74,9 @@ Grouping uses the date each photo was taken, and the headers use the same format
## `singleImage` ## `singleImage`
**Type:** `bool` · **Default:** `false` **Type:** `bool` · **Default:** `true`
Show a gallery page for a share that contains a single image, instead of opening the image file directly. Show a gallery page for a share that contains a single image, instead of opening the image file directly. On by default in this fork, so a single photo can still be commented on.
## `singleVideo` ## `singleVideo`
+10 -6
View File
@@ -138,7 +138,9 @@ With it off, a slug link gets a 404 and only the key form works.
## `uploadUrl` ## `uploadUrl`
**Type:** `string` · **Default:** `"/upload"` **Type:** `string` · **Default:** `""`
Off by default in this fork: the upload service does not check magic-link sessions, so anyone with a share key could reach its upload page.
Where the optional upload service (the `immich-public-proxy-upload` container) is served. A share whose "Allow public user to upload" option is on in Immich then shows an "Add photos" button in the gallery header, which opens that share's page on the upload service. To set up the service, see [Let visitors send photos back](/visitor-uploads). Where the optional upload service (the `immich-public-proxy-upload` container) is served. A share whose "Allow public user to upload" option is on in Immich then shows an "Add photos" button in the gallery header, which opens that share's page on the upload service. To set up the service, see [Let visitors send photos back](/visitor-uploads).
@@ -184,16 +186,18 @@ Send a custom response instead of the default 404. See [Error responses](/config
**Type:** `object` **Type:** `object`
Change the headers sent with photos, videos and static files. The default is a 30-day `Cache-Control` and a Change the headers sent with photos, videos and static files. The default is a 30-day browser-only `Cache-Control`.
permissive CORS header. The "download all" zip is always sent with `Cache-Control: no-store`, and the gallery page The "download all" zip is always sent with `Cache-Control: no-store`, and the gallery page with
uses its own [`gallery.cacheTime`](/config/gallery#cachetime). `Cache-Control: private, no-cache`.
In this fork every photo sits behind a magic-link session, so keep `Cache-Control` `private`: a `public` value lets a
CDN or shared proxy store a photo and hand it to anyone who asks for the same URL.
```json ```json
{ {
"ipp": { "ipp": {
"responseHeaders": { "responseHeaders": {
"Cache-Control": "public, max-age=2592000", "Cache-Control": "private, max-age=2592000"
"Access-Control-Allow-Origin": "*"
} }
} }
} }
+21
View File
@@ -22,6 +22,7 @@
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.21.1", "express": "^4.21.1",
"nodemailer": "^10.1.7",
"preact": "^10.29.2", "preact": "^10.29.2",
"tslib": "^2.8.1" "tslib": "^2.8.1"
}, },
@@ -33,6 +34,7 @@
"@types/cookie-session": "^2.0.49", "@types/cookie-session": "^2.0.49",
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/node": "^22", "@types/node": "^22",
"@types/nodemailer": "^8.0.2",
"@typescript-eslint/eslint-plugin": "^7", "@typescript-eslint/eslint-plugin": "^7",
"@typescript-eslint/parser": "^7", "@typescript-eslint/parser": "^7",
"concurrently": "^10.0.3", "concurrently": "^10.0.3",
@@ -1193,6 +1195,16 @@
"undici-types": "~6.21.0" "undici-types": "~6.21.0"
} }
}, },
"node_modules/@types/nodemailer": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz",
"integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/qs": { "node_modules/@types/qs": {
"version": "6.9.17", "version": "6.9.17",
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.17.tgz", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.17.tgz",
@@ -5278,6 +5290,15 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/nodemailer": {
"version": "10.1.7",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.7.tgz",
"integrity": "sha512-OQa6FDln5fLttmqSbjDiRYvFDOFNrBqfiOwHPlEbURil3b+vPB1v8xpi+Sp46drzNDlsTnNsS502vthmz56r4w==",
"license": "MIT-0",
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/normalize-path": { "node_modules/normalize-path": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",