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

254 lines
11 KiB
TypeScript

import { mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { DatabaseSync } from 'node:sqlite'
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()
})
})
describe('public shares', () => {
it('a share added by the admin requires sign-in unless marked public', () => {
expect(store.upsertShare({ key: 'k1', slug: null, title: 'A', password: null }, T0).public).toBe(false)
expect(store.upsertShare({ key: 'k2', slug: null, title: 'B', password: null, public: true }, T0).public).toBe(true)
})
it('saving a share again keeps its setting unless one is given', () => {
store.upsertShare({ key: 'k1', slug: null, title: 'A', password: null, public: true }, T0)
expect(store.upsertShare({ key: 'k1', slug: null, title: 'A2', password: null }, T1).public).toBe(true)
expect(store.upsertShare({ key: 'k1', slug: null, title: 'A2', password: null, public: false }, T1).public).toBe(false)
store.setSharePublic('k1', true)
expect(store.getShare('k1')?.public).toBe(true)
})
it('a discovered share starts public, and never overwrites one on file', () => {
expect(store.addDiscoveredShare({ key: 'k1', slug: 'one', title: 'Found' }, T0)).toMatchObject({ public: true, password: null })
store.upsertShare({ key: 'k2', slug: null, title: 'Mine', password: 'pw' }, T0)
expect(store.addDiscoveredShare({ key: 'k2', slug: null, title: 'Other' }, T1)).toMatchObject({ title: 'Mine', password: 'pw', public: false })
})
it('finds a share by key or slug, and lists the setting', () => {
store.addDiscoveredShare({ key: 'k1', slug: 'one', title: 'Found' }, T0)
expect(store.findShare('k1')?.key).toBe('k1')
expect(store.findShare('one')?.key).toBe('k1')
expect(store.findShare('nope')).toBeUndefined()
expect(store.listShares()[0].public).toBe(true)
})
it('upgrades a database from before the setting, keeping its shares sign-in only', () => {
const dir = mkdtempSync(join(tmpdir(), 'imp-store-'))
try {
const path = join(dir, 'magic.db')
const old = new DatabaseSync(path)
old.exec(`CREATE TABLE shares (key TEXT PRIMARY KEY, slug TEXT, title TEXT NOT NULL DEFAULT '', password TEXT,
last_scanned_at TEXT, created_at TEXT NOT NULL)`)
old.prepare('INSERT INTO shares (key, slug, title, password, created_at) VALUES (?, ?, ?, ?, ?)').run('old', null, 'Old', null, T0)
old.close()
const upgraded = new Store(path)
expect(upgraded.getShare('old')?.public).toBe(false)
upgraded.close()
// Opening it again doesn't try to add the column twice
new Store(path).close()
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
})
describe('activity and hearts', () => {
it('counts views per share, recipient and browser, and lists browsers newest first', () => {
store.upsertShare({ key: 'k1', slug: null, title: 'A', password: null }, T0)
const ann = recipient()
const older = store.createSession(ann.id, T0, 'Firefox')
const newer = store.createSession(ann.id, T0, 'Chrome')
store.recordView('k1', {}, T1)
store.recordView('k1', { recipientId: ann.id, sessionToken: older, userAgent: 'Firefox 2' }, T1)
store.recordView('k1', { recipientId: ann.id, sessionToken: newer }, T2)
expect(store.shareActivity().get('k1')).toEqual({ views: 3, anonymousViews: 1, lastViewedAt: T2, hearts: 0 })
expect(store.recipientActivity(ann.id)).toEqual({ views: 2, lastViewedAt: T2 })
const [first, second] = store.listSessions(ann.id)
expect(first).toMatchObject({ views: 1, lastViewedAt: T2, userAgent: 'Chrome' })
expect(second).toMatchObject({ views: 1, lastViewedAt: T1, userAgent: 'Firefox 2' })
})
it('signs out one browser, only for its own recipient', () => {
const ann = recipient()
const bob = recipient('bob@example.com')
store.createSession(ann.id, T0)
const [session] = store.listSessions(ann.id)
expect(store.deleteSessionById(bob.id, session.id)).toBe(false)
expect(store.deleteSessionById(ann.id, session.id)).toBe(true)
expect(store.listSessions(ann.id)).toHaveLength(0)
})
it('hearts once per recipient per photo, and counts them', () => {
store.upsertShare({ key: 'k1', slug: null, title: 'A', password: null }, T0)
const ann = recipient()
const bob = recipient('bob@example.com')
expect(store.setHeart('k1', 'p1', ann.id, true, T0)).toBe(1)
expect(store.setHeart('k1', 'p1', ann.id, true, T0)).toBe(1)
expect(store.setHeart('k1', 'p1', bob.id, true, T0)).toBe(2)
expect(store.countHearts('k1')).toEqual({ p1: 2 })
expect(store.heartedBy('k1', ann.id)).toEqual(['p1'])
expect(store.shareActivity().get('k1')?.hearts).toBe(2)
expect(store.setHeart('k1', 'p1', ann.id, false, T0)).toBe(1)
// Deleting the share takes its hearts with it
store.deleteShare('k1')
expect(store.countHearts('k1')).toEqual({})
})
})