Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@noah/mega-radio

MEGA Radio (the WAKE album) for members of the MEGA.dev Discord: sign in with Kody, verify with Discord, listen with repeat.

FollowForkOpen app

Files

move.test.ts

321 lines · 16.4 KB · TypeScript
/** The one-time data move (src/move.ts): payload, validation, import, conflicts and the window handoff. */
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { webcrypto } from 'node:crypto'
import { IMPORTED_KEY, MIGRATED_KEY, MIGRATION_FORMAT, MOVE_JS, READY_WAIT_MS, REPEAT_KEY } from '../src/move.ts'
import { LOCAL_ORIGINS, NEW_ORIGIN, OLD_ORIGIN, PROD_ORIGINS, originsFor } from '../src/origins.ts'
import { movePage, renderPage, withOrigins } from '../src/page.ts'

const O = PROD_ORIGINS
const ALLOWED = new Set([REPEAT_KEY, MIGRATED_KEY, IMPORTED_KEY])
const tick = () => new Promise((r) => setTimeout(r, 0))

type Ev = { origin: string; source: unknown; data: unknown }
type Win = ReturnType<typeof fakeWindow>

/** A tiny window: recording localStorage, message listeners, manual timers, window.open. */
function fakeWindow(origin: string, initial: Record<string, string> = {}, path = '/') {
	const data: Record<string, string> = { ...initial }
	const reads: string[] = []
	const writes: string[] = []
	const listeners: ((e: Ev) => void)[] = []
	const timers = new Map<number, () => void>()
	const posted: { msg: any; target: string }[] = []
	let id = 0
	const win: any = {
		localStorage: {
			getItem: (k: string) => (reads.push(k), k in data ? data[k] : null),
			setItem: (k: string, v: string) => (writes.push(k), (data[k] = String(v))),
			removeItem: (k: string) => { throw new Error(`removeItem(${k}) must never be called`) },
			clear: () => { throw new Error('clear() must never be called') },
		},
		location: { origin, pathname: path, search: '', hash: '', href: origin + path, replace: (u: string) => (win.replaced = u) },
		crypto: webcrypto,
		URL,
		opener: null as any,
		opened: null as any,
		openedUrl: '',
		open: (u: string) => ((win.openedUrl = u), win.opened),
		addEventListener: (t: string, f: (e: Ev) => void) => t === 'message' && listeners.push(f),
		removeEventListener: (t: string, f: (e: Ev) => void) => { const i = listeners.indexOf(f); if (i >= 0) listeners.splice(i, 1) },
		setTimeout: (f: () => void) => (timers.set(++id, f), id),
		clearTimeout: (i: number) => timers.delete(i),
		dispatch: (e: Ev) => listeners.slice().forEach((f) => f(e)),
		fireTimers: () => { const fs = [...timers.values()]; timers.clear(); fs.forEach((f) => f()) },
		data, reads, writes, posted, listeners,
	}
	new Function('window', MOVE_JS)(win)
	return win
}
const api = (w: Win) => w.__megaRadioMove
const onlyApproved = (...ws: Win[]) => ws.forEach((w) => [...w.reads, ...w.writes].forEach((k: string) => assert.ok(ALLOWED.has(k), `touched ${k}`)))
const payloadFor = (repeat: string, exportedAt = '2026-11-24T14:00:00.000Z') => ({ format: MIGRATION_FORMAT, version: 1, exportedAt, data: { [REPEAT_KEY]: repeat } })

test('export then import round-trips the repeat setting, and only it', async () => {
	for (const mode of ['off', 'all', 'one']) {
		const old = fakeWindow(OLD_ORIGIN, { [REPEAT_KEY]: mode, theme: 'dark', 'bbw-deals:x': '1', 'mega-radio:other': 'z' }, '/mega-radio/')
		const p = api(old).buildPayload()
		assert.equal(p.format, 'noah/mega-radio-migration')
		assert.equal(p.version, 1)
		assert.ok(!Number.isNaN(Date.parse(p.exportedAt)))
		assert.deepEqual(p.data, { [REPEAT_KEY]: mode })
		const nw = fakeWindow(NEW_ORIGIN)
		const r = await api(nw).importPayload(JSON.parse(JSON.stringify(p)), () => assert.fail('no conflict expected'))
		assert.equal(r.status, 'imported')
		assert.equal(nw.data[REPEAT_KEY], mode)
		assert.equal(JSON.parse(nw.data[IMPORTED_KEY]).exportedAt, p.exportedAt)
		assert.deepEqual(old.writes, [])
		onlyApproved(old, nw)
	}
})

test('an invalid repeat value on OLD is not exported', () => {
	const old = fakeWindow(OLD_ORIGIN, { [REPEAT_KEY]: 'loud' })
	assert.deepEqual(api(old).buildPayload().data, {})
	assert.equal(api(old).hasData(), false)
})

test('malformed payloads, a wrong format and an unknown version are rejected with nothing written', async () => {
	const ok = payloadFor('all')
	const bad: [unknown, RegExp][] = [
		[null, /not MEGA Radio data/],
		[[], /not MEGA Radio data/],
		['{}', /not MEGA Radio data/],
		[{}, /format/],
		[{ ...ok, format: 'noah/bbw-deals-migration' }, /format/],
		[{ ...ok, version: 2 }, /version 2; expected 1/],
		[{ ...ok, version: '1' }, /version "1"/],
		[{ ...ok, extra: 1 }, /unexpected field: extra/],
		[{ ...ok, exportedAt: undefined }, /export time/],
		[{ ...ok, exportedAt: 'yesterday' }, /export time/],
		[{ ...ok, data: null }, /no items/],
		[{ ...ok, data: ['all'] }, /no items/],
		[{ ...ok, data: { [REPEAT_KEY]: 'loud' } }, /bad value/],
		[{ ...ok, data: { [REPEAT_KEY]: 1 } }, /bad value/],
		[{ ...ok, data: { [REPEAT_KEY]: 'all', theme: 'dark' } }, /does not know: theme/],
		[{ ...ok, data: { [MIGRATED_KEY]: 'x' } }, /does not know/],
	]
	for (const [p, msg] of bad) {
		const nw = fakeWindow(NEW_ORIGIN, { [REPEAT_KEY]: 'one' })
		const r = await api(nw).importPayload(p, () => assert.fail('must not ask'))
		assert.equal(r.status, 'error', JSON.stringify(p))
		assert.match(r.message, msg)
		assert.deepEqual(nw.writes, [], `wrote for ${JSON.stringify(p)}`)
		assert.equal(nw.data[REPEAT_KEY], 'one')
	}
})

test('a second import of the same payload does nothing and says it already ran', async () => {
	const nw = fakeWindow(NEW_ORIGIN)
	const p = payloadFor('all')
	assert.equal((await api(nw).importPayload(p, () => 'replace')).status, 'imported')
	nw.data[REPEAT_KEY] = 'one' // changed on NEW afterwards
	const writes = nw.writes.length
	const again = await api(nw).importPayload(p, () => assert.fail('must not ask'))
	assert.equal(again.status, 'already')
	assert.match(again.message, /already imported/)
	assert.equal(nw.writes.length, writes)
	assert.equal(nw.data[REPEAT_KEY], 'one')
})

test('conflicts are never overwritten silently', async () => {
	const asked: unknown[] = []
	const keep = fakeWindow(NEW_ORIGIN, { [REPEAT_KEY]: 'one' })
	const r1 = await api(keep).importPayload(payloadFor('all'), (c: unknown) => (asked.push(c), 'keep'))
	assert.deepEqual(asked, [{ key: REPEAT_KEY, current: 'one', incoming: 'all' }])
	assert.equal(r1.status, 'imported')
	assert.equal(keep.data[REPEAT_KEY], 'one')

	const rep = fakeWindow(NEW_ORIGIN, { [REPEAT_KEY]: 'one' })
	await api(rep).importPayload(payloadFor('all'), async () => 'replace')
	assert.equal(rep.data[REPEAT_KEY], 'all')

	const none = fakeWindow(NEW_ORIGIN, { [REPEAT_KEY]: 'one' })
	const r3 = await api(none).importPayload(payloadFor('all'), () => undefined)
	assert.equal(r3.status, 'error')
	assert.deepEqual(none.writes, [])

	const same = fakeWindow(NEW_ORIGIN, { [REPEAT_KEY]: 'all' })
	await api(same).importPayload(payloadFor('all'), () => assert.fail('same value: no question'))
	assert.equal(same.data[REPEAT_KEY], 'all')
})

/** Deliver like a browser: record, drop on a targetOrigin mismatch, dispatch asynchronously. */
function deliver(to: Win, msg: unknown, target: string, fromOrigin: string, source: unknown) {
	to.posted.push({ msg, target })
	if (target === '*') throw new Error('targetOrigin * is not allowed')
	if (target !== to.location.origin) return
	const copy = structuredClone(msg)
	queueMicrotask(() => to.dispatch({ origin: fromOrigin, source, data: copy }))
}

/** OLD and NEW wired together with one WindowProxy each: OLD.open() returns NEW's, NEW.opener is OLD's. */
function link(old: Win, nw: Win) {
	const proxyOfNew: any = { postMessage: (m: unknown, t: string) => deliver(nw, m, t, old.location.origin, proxyOfOld) }
	const proxyOfOld: any = { postMessage: (m: unknown, t: string) => deliver(old, m, t, nw.location.origin, proxyOfNew) }
	old.opened = proxyOfNew
	nw.opener = proxyOfOld
}
function pair(oldData: Record<string, string>, newData: Record<string, string> = {}) {
	const old = fakeWindow(OLD_ORIGIN, oldData, '/mega-radio/')
	const nw = fakeWindow(NEW_ORIGIN, newData, '/move')
	link(old, nw)
	return { old, nw }
}

test('window handoff: OLD sends only after NEW is ready, NEW imports, OLD sets the migrated marker', async () => {
	const { old, nw } = pair({ [REPEAT_KEY]: 'all', theme: 'dark' })
	const states: string[] = []
	const h = api(old).startHandoff(O, (s: string) => states.push(s))
	assert.ok(old.openedUrl.startsWith(`${NEW_ORIGIN}/move?nonce=`))
	assert.ok(!old.openedUrl.includes('all'), 'no data in the URL')
	assert.equal(new URL(old.openedUrl).searchParams.get('nonce'), h.nonce)
	assert.equal(api(nw).acceptHandoff(O, h.nonce, () => 'replace', () => {}), true)
	for (let i = 0; i < 5; i++) await tick()
	assert.deepEqual(states, ['waiting', 'sent', 'done'])
	assert.equal(nw.data[REPEAT_KEY], 'all')
	assert.ok(JSON.parse(old.data[MIGRATED_KEY]).migratedAt)
	assert.equal(old.data[REPEAT_KEY], 'all', 'old data stays in place')
	for (const w of [old, nw]) for (const p of w.posted) assert.notEqual(p.target, '*')
	onlyApproved(old, nw)
	assert.equal(api(old).isMigrated(), true)
})

test('running the move again does not duplicate or overwrite anything', async () => {
	const { old, nw } = pair({ [REPEAT_KEY]: 'one' })
	const h1 = api(old).startHandoff(O, () => {})
	api(nw).acceptHandoff(O, h1.nonce, () => 'replace', () => {})
	for (let i = 0; i < 5; i++) await tick()
	nw.data[REPEAT_KEY] = 'off' // visitor changed it on NEW
	const nw2 = fakeWindow(NEW_ORIGIN, { ...nw.data }, '/move')
	link(old, nw2)
	const states: string[] = []
	const asked: unknown[] = []
	const h2 = api(old).startHandoff(O, (s: string) => states.push(s))
	api(nw2).acceptHandoff(O, h2.nonce, (c: unknown) => (asked.push(c), 'keep'), () => {})
	for (let i = 0; i < 5; i++) await tick()
	assert.deepEqual(states, ['waiting', 'sent', 'done'])
	assert.equal(nw2.data[REPEAT_KEY], 'off')
	assert.deepEqual(asked, [{ key: REPEAT_KEY, current: 'off', incoming: 'one' }])
})

test('OLD ignores messages from other origins, other windows and wrong nonces', async () => {
	const old = fakeWindow(OLD_ORIGIN, { [REPEAT_KEY]: 'all' })
	const child = { posted: [] as any[], postMessage(m: unknown, t: string) { this.posted.push({ m, t }) } }
	old.opened = child
	const states: string[] = []
	const h = api(old).startHandoff(O, (s: string) => states.push(s))
	old.dispatch({ origin: 'https://evil.example', source: child, data: { type: 'ready', nonce: h.nonce } })
	old.dispatch({ origin: OLD_ORIGIN, source: child, data: { type: 'ready', nonce: h.nonce } })
	old.dispatch({ origin: NEW_ORIGIN, source: {}, data: { type: 'ready', nonce: h.nonce } })
	old.dispatch({ origin: NEW_ORIGIN, source: child, data: { type: 'ready', nonce: 'f'.repeat(32) } })
	old.dispatch({ origin: NEW_ORIGIN, source: child, data: 'ready' })
	old.dispatch({ origin: NEW_ORIGIN, source: child, data: { type: 'imported', nonce: h.nonce } }) // before ready
	assert.deepEqual(child.posted, [])
	assert.equal(old.data[MIGRATED_KEY], undefined)
	old.dispatch({ origin: NEW_ORIGIN, source: child, data: { type: 'ready', nonce: h.nonce } })
	assert.equal(child.posted.length, 1)
	assert.equal(child.posted[0].t, NEW_ORIGIN)
	assert.deepEqual(child.posted[0].m.payload.data, { [REPEAT_KEY]: 'all' })
	old.dispatch({ origin: 'https://evil.example', source: child, data: { type: 'imported', nonce: h.nonce } })
	old.dispatch({ origin: NEW_ORIGIN, source: child, data: { type: 'imported', nonce: 'x' } })
	assert.equal(old.data[MIGRATED_KEY], undefined)
	old.dispatch({ origin: NEW_ORIGIN, source: child, data: { type: 'error', nonce: h.nonce, message: 'nope' } })
	assert.deepEqual(states, ['waiting', 'sent', 'error'])
	assert.equal(old.data[MIGRATED_KEY], undefined)
})

test('OLD waits 2 minutes for ready, then offers the file fallback; a late ready is ignored', () => {
	assert.equal(READY_WAIT_MS, 120000)
	const old = fakeWindow(OLD_ORIGIN, { [REPEAT_KEY]: 'all' })
	const child = { posted: [] as any[], postMessage(m: unknown, t: string) { this.posted.push({ m, t }) } }
	old.opened = child
	const states: string[] = []
	const h = api(old).startHandoff(O, (s: string) => states.push(s))
	old.fireTimers()
	old.dispatch({ origin: NEW_ORIGIN, source: child, data: { type: 'ready', nonce: h.nonce } })
	assert.deepEqual(states, ['waiting', 'timeout'])
	assert.deepEqual(child.posted, [])
})

test('a blocked popup reports blocked', () => {
	const old = fakeWindow(OLD_ORIGIN, { [REPEAT_KEY]: 'all' })
	const states: string[] = []
	assert.equal(api(old).startHandoff(O, (s: string) => states.push(s)), null)
	assert.deepEqual(states, ['blocked'])
})

test('NEW says ready to the exact OLD origin and ignores other origins, other windows and wrong nonces', async () => {
	const nw = fakeWindow(NEW_ORIGIN, {}, '/move')
	const opener = { posted: [] as any[], postMessage(m: unknown, t: string) { this.posted.push({ m, t }) } }
	nw.opener = opener
	const n = 'a'.repeat(32)
	assert.equal(api(nw).acceptHandoff(O, n, () => 'replace', () => {}), true)
	assert.deepEqual(opener.posted, [{ m: { type: 'ready', nonce: n }, t: OLD_ORIGIN }])
	const payload = payloadFor('one')
	nw.dispatch({ origin: 'https://evil.example', source: opener, data: { type: 'payload', nonce: n, payload } })
	nw.dispatch({ origin: NEW_ORIGIN, source: opener, data: { type: 'payload', nonce: n, payload } })
	nw.dispatch({ origin: OLD_ORIGIN, source: {}, data: { type: 'payload', nonce: n, payload } })
	nw.dispatch({ origin: OLD_ORIGIN, source: opener, data: { type: 'payload', nonce: 'b'.repeat(32), payload } })
	await tick()
	assert.deepEqual(nw.writes, [])
	nw.dispatch({ origin: OLD_ORIGIN, source: opener, data: { type: 'payload', nonce: n, payload } })
	await tick(); await tick()
	assert.equal(nw.data[REPEAT_KEY], 'one')
	assert.deepEqual(opener.posted[1], { m: { type: 'imported', nonce: n, already: false }, t: OLD_ORIGIN })
	// a second payload on the same page is ignored
	nw.dispatch({ origin: OLD_ORIGIN, source: opener, data: { type: 'payload', nonce: n, payload: payloadFor('all', '2026-11-25T00:00:00.000Z') } })
	await tick()
	assert.equal(nw.data[REPEAT_KEY], 'one')
	onlyApproved(nw)
})

test('NEW replies with an error for a bad payload and writes nothing', async () => {
	const nw = fakeWindow(NEW_ORIGIN, {}, '/move')
	const opener = { posted: [] as any[], postMessage(m: unknown, t: string) { this.posted.push({ m, t }) } }
	nw.opener = opener
	const n = 'c'.repeat(32)
	api(nw).acceptHandoff(O, n, () => 'replace', () => {})
	nw.dispatch({ origin: OLD_ORIGIN, source: opener, data: { type: 'payload', nonce: n, payload: { ...payloadFor('all'), version: 9 } } })
	await tick(); await tick()
	assert.equal(opener.posted[1].m.type, 'error')
	assert.match(opener.posted[1].m.message, /version 9/)
	assert.equal(opener.posted[1].t, OLD_ORIGIN)
	assert.deepEqual(nw.writes, [])
})

test('NEW does not start a handoff without an opener or with a malformed nonce', () => {
	const nw = fakeWindow(NEW_ORIGIN)
	assert.equal(api(nw).acceptHandoff(O, 'a'.repeat(32), () => 'keep', () => {}), false)
	nw.opener = { postMessage: () => assert.fail('no ready for a bad nonce') }
	assert.equal(api(nw).acceptHandoff(O, '<script>', () => 'keep', () => {}), false)
	assert.equal(api(nw).acceptHandoff(O, null, () => 'keep', () => {}), false)
})

test('OLD URLs map to the matching NEW URL', () => {
	const w = fakeWindow(OLD_ORIGIN)
	const u = (pathname: string, search = '', hash = '') => api(w).newUrlFor({ pathname, search, hash }, O)
	assert.equal(u('/mega-radio'), `${NEW_ORIGIN}/`)
	assert.equal(u('/mega-radio/'), `${NEW_ORIGIN}/`)
	assert.equal(u('/mega-radio/move', '?a=1', '#x'), `${NEW_ORIGIN}/move?a=1#x`)
	assert.equal(u('/mega-radio-other/'), `${NEW_ORIGIN}/mega-radio-other/`)
})

test('origins: exact production pair, loopback uses the local pair', () => {
	assert.deepEqual(originsFor('https://mega-radio--noah.kody.run'), { old: 'https://noah.kody.run', new: 'https://mega-radio--noah.kody.run', oldBase: '/mega-radio' })
	assert.deepEqual(originsFor('https://noah.kody.run/mega-radio'), PROD_ORIGINS)
	assert.deepEqual(originsFor('http://127.0.0.1:8781/mega-radio'), LOCAL_ORIGINS)
	assert.deepEqual(originsFor('http://mega-radio--noah.localhost:8782'), LOCAL_ORIGINS)
	assert.deepEqual(originsFor('https://evil.localhost.example'), PROD_ORIGINS)
	assert.deepEqual(originsFor(undefined), PROD_ORIGINS)
})

test('pages carry the origins and load the move script; the import page has the file picker', () => {
	for (const base of ['/mega-radio', '']) {
		const page = withOrigins(renderPage(base, { kind: 'signed-out', loginHref: '/l' }), O)
		assert.ok(page.includes(`<html lang="en" data-old-origin="${OLD_ORIGIN}" data-new-origin="${NEW_ORIGIN}" data-old-base="/mega-radio" data-app-base="${base}">`))
		assert.ok(page.includes(`<script src="${base}/move.js" defer></script>`))
		const mv = movePage(base)
		assert.ok(mv.includes('data-move-page') && mv.includes('data-move-file') && mv.includes('Import data'))
	}
})