462 lines
20 KiB
TypeScript
462 lines
20 KiB
TypeScript
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 ("|")Garden("|")/)
|
|
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('|')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)
|
|
})
|
|
})
|