Files
immich-magic-proxy/app/tests/magicAccess.test.ts
T

640 lines
29 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'
import { browserName } from '../src/magic/views'
/*
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'
// In Immich but never added to the proxy: opened by their Immich links
const KEY_D = 'ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'
const KEY_E = 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
const ASSET_1 = '11111111-1111-4111-8111-111111111111'
const ASSET_2 = '22222222-2222-4222-8222-222222222222'
const ASSET_B = '33333333-3333-4333-8333-333333333333'
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]),
[KEY_D]: link(KEY_D, 'Picnic', null, [ASSET_2]),
[KEY_E]: link(KEY_E, 'Beach', 'beach', [ASSET_1])
}
const PASSWORD = 'party-pw'
const IMMICH_TOKEN = 'immich-token-for-p'
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
userAgent?: 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.userAgent) headers['User-Agent'] = options.userAgent
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)
})
})
describe('public shares', () => {
it('an Immich link not seen before opens for anyone, without comments, and is recorded as public', async () => {
const page = await request('/share/' + KEY_D, { page: true })
expect(page.res.status).toBe(200)
expect(page.text).toContain('Picnic')
expect(page.text).not.toContain('/share/comments/')
expect(page.res.headers.get('vary')).toContain('Cookie')
expect(store.getShare(KEY_D)).toMatchObject({ title: 'Picnic', public: true, password: null })
const photo = await request('/share/photo/' + KEY_D + '/' + ASSET_2 + '/thumbnail')
expect(photo.res.status).toBe(200)
expect(photo.text).toBe('JPEG:' + ASSET_2)
// Another share's photo can't be pulled through this one
expect((await request('/share/photo/' + KEY_D + '/' + ASSET_1 + '/thumbnail')).res.status).toBe(404)
// Comments stay recipient-only
expect((await request('/share/comments/' + KEY_D + '/' + ASSET_2)).res.status).toBe(404)
expect((await request('/share/comments/' + KEY_D + '/' + ASSET_2, { json: { body: 'hi' } })).res.status).toBe(404)
})
it('opens by slug too, recording the share under its key', async () => {
expect((await request('/s/beach', { page: true })).res.status).toBe(200)
expect(store.getShare(KEY_E)).toMatchObject({ slug: 'beach', public: true })
})
it('refuses a key Immich does not know, and asks Immich about it only once', async () => {
const unknown = 'z'.repeat(67)
const before = immichCalls
expect((await request('/share/' + unknown, { page: true })).res.status).toBe(401)
expect((await request('/share/' + unknown, { page: true })).res.status).toBe(401)
expect(immichCalls - before).toBe(1)
expect(store.getShare(unknown)).toBeUndefined()
})
it('a recipient not given the share can view it, but not comment', async () => {
const cookie = await signIn()
const page = await request('/share/' + KEY_D, { page: true, cookie })
expect(page.res.status).toBe(200)
expect(page.text).not.toContain('/share/comments/')
expect((await request('/share/comments/' + KEY_D + '/' + ASSET_2, { cookie, json: { body: 'hi' } })).res.status).toBe(404)
})
it('the admin can switch a share to sign-in only, and back', async () => {
const login = await request('/admin/login', { form: { password: 'admin-secret' } })
const admin = cookieFrom(login.res, 'imp_admin')!
const dashboard = await request('/admin', { page: true, cookie: admin })
expect(dashboard.text).toContain('Picnic')
expect(dashboard.text).toContain('Public link works')
await request('/admin/shares/' + KEY_D + '/access', { cookie: admin, form: { public: '0' } })
expect(store.getShare(KEY_D)?.public).toBe(false)
expect((await request('/share/' + KEY_D, { page: true })).res.status).toBe(401)
expect((await request('/share/photo/' + KEY_D + '/' + ASSET_2 + '/thumbnail')).res.status).toBe(404)
expect((await request('/share/' + KEY_D, { page: true, cookie: await signIn() })).res.status).toBe(404)
await request('/admin/shares/' + KEY_D + '/access', { cookie: admin, form: { public: ['0', '1'] } })
expect(store.getShare(KEY_D)?.public).toBe(true)
expect((await request('/share/' + KEY_D, { page: true })).res.status).toBe(200)
})
it('needs the admin session to change access', async () => {
await request('/admin/shares/' + KEY_D + '/access', { form: { public: '0' } })
expect(store.getShare(KEY_D)?.public).toBe(true)
})
})
describe('activity', () => {
const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1'
it('counts gallery views against the album, the recipient and the browser', async () => {
const shareBefore = store.shareActivity().get(KEY_A)!
const annBefore = store.recipientActivity(ann.id).views
const { res } = await request(annLink, { page: true, userAgent: IPHONE })
const cookie = cookieFrom(res, 'imp_session')!
await request('/share/' + KEY_A, { page: true, cookie, userAgent: IPHONE })
await request('/share/' + KEY_A, { page: true, cookie, userAgent: IPHONE })
// Photos and metadata aren't views; only the gallery page is
await request('/share/photo/' + KEY_A + '/' + ASSET_1 + '/thumbnail', { cookie })
const share = store.shareActivity().get(KEY_A)!
expect(share.views - shareBefore.views).toBe(2)
expect(share.anonymousViews).toBe(shareBefore.anonymousViews)
expect(share.lastViewedAt).not.toBeNull()
expect(store.recipientActivity(ann.id).views - annBefore).toBe(2)
const browser = store.listSessions(ann.id).find(s => s.userAgent === IPHONE)!
expect(browser.views).toBe(2)
expect(browserName(browser.userAgent)).toBe('Safari on iPhone')
})
it('counts views of a public share by visitors who aren\'t signed in', async () => {
const before = store.shareActivity().get(KEY_D)!
await request('/share/' + KEY_D, { page: true })
const after = store.shareActivity().get(KEY_D)!
expect(after.views - before.views).toBe(1)
expect(after.anonymousViews - before.anonymousViews).toBe(1)
})
it('lists each browser for the admin, who can sign one out', async () => {
await signIn()
const others = store.listSessions(ann.id).map(s => s.id)
const kept = await signIn()
const keptId = store.listSessions(ann.id).map(s => s.id).find(id => !others.includes(id))!
const login = await request('/admin/login', { form: { password: 'admin-secret' } })
const admin = cookieFrom(login.res, 'imp_admin')!
const page = await request('/admin/recipients/' + ann.id, { page: true, cookie: admin })
expect(page.text).toContain('Safari on iPhone')
expect(page.text).toMatch(/album views?, last/)
// Sign out one browser; the others stay signed in
const target = others[0]
await request('/admin/recipients/' + ann.id + '/sessions/' + target + '/revoke', { cookie: admin, method: 'POST' })
const left = store.listSessions(ann.id).map(s => s.id)
expect(left).not.toContain(target)
expect(left).toContain(keptId)
expect((await request('/share/' + KEY_A, { page: true, cookie: kept })).res.status).toBe(200)
// Another recipient's browser can't be signed out from this page
const bobs = store.listSessions(bob.id)
if (bobs.length) {
await request('/admin/recipients/' + ann.id + '/sessions/' + bobs[0].id + '/revoke', { cookie: admin, method: 'POST' })
expect(store.listSessions(bob.id)).toHaveLength(bobs.length)
}
// Not without the admin session
await request('/admin/recipients/' + ann.id + '/sessions/' + keptId + '/revoke', { method: 'POST' })
expect(store.listSessions(ann.id).map(s => s.id)).toContain(keptId)
})
it('shows views and hearts on the dashboard', async () => {
const login = await request('/admin/login', { form: { password: 'admin-secret' } })
const admin = cookieFrom(login.res, 'imp_admin')!
const page = await request('/admin', { page: true, cookie: admin })
expect(page.text).toContain('<th>Views</th>')
expect(page.text).toContain('not signed in')
})
})
describe('hearts', () => {
let cookie: string
beforeAll(async () => { cookie = await signIn() })
const heart = (key: string, id: string, method: string, as = cookie) => request('/share/hearts/' + key + '/' + id, { cookie: as, method })
it('a recipient hearts a photo once, and can take it back', async () => {
let res = await heart(KEY_A, ASSET_1, 'PUT')
expect(res.res.status).toBe(200)
expect(JSON.parse(res.text)).toEqual({ count: 1, mine: true })
res = await heart(KEY_A, ASSET_1, 'PUT')
expect(JSON.parse(res.text)).toEqual({ count: 1, mine: true })
const page = await request('/share/' + KEY_A, { page: true, cookie })
expect(page.text).toContain('/share/hearts/' + KEY_A)
expect(page.text).toContain('"mine":["' + ASSET_1 + '"]')
res = await heart(KEY_A, ASSET_1, 'DELETE')
expect(JSON.parse(res.text)).toEqual({ count: 0, mine: false })
})
it('only on photos in the album', async () => {
expect((await heart(KEY_A, ASSET_B, 'PUT')).res.status).toBe(404)
})
it('not for someone without the album, or not signed in', async () => {
const bobCookie = await signIn('/m/' + store.createMagicLink(bob.id, { purpose: 'invite', expiresAt: null }, new Date().toISOString()))
expect((await heart(KEY_A, ASSET_1, 'PUT', bobCookie)).res.status).toBe(404)
expect((await request('/share/hearts/' + KEY_A + '/' + ASSET_1, { method: 'PUT' })).res.status).toBe(404)
// A public share's anonymous visitors don't get hearts at all
const page = await request('/share/' + KEY_D, { page: true })
expect(page.text).not.toContain('/share/hearts/')
expect((await request('/share/hearts/' + KEY_D + '/' + ASSET_2, { method: 'PUT' })).res.status).toBe(404)
})
})