Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

push.test.ts

199 lines · 12.5 KB · TypeScript
import assert from 'node:assert/strict'
import { registerHooks } from 'node:module'
import { test } from 'node:test'

const STUB = `
const store = globalThis.__factoryStore ??= new Map();
export const packageStorage = () => ({
  async get(k) { return store.get(k) ?? null },
  async set(k, v) { store.set(k, JSON.stringify(v)) },
});
export const packageContext = { appBasePath: '/apps/factory/' };
export async function credential(key) { throw new Error('credential not mapped: ' + key); }
export async function credentials() { return [] }
export const kody = {};
export const workflows = null;
`
registerHooks({
	resolve(spec, ctx, next) {
		if (spec === 'kody:@kody/discord/post-message') return { url: `data:text/javascript,${encodeURIComponent('export default async () => ({ ok: true })')}`, shortCircuit: true }
		if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true }
		return next(spec, ctx)
	},
})

const { encryptPushPayload, b64urlEncode, b64urlDecode, hkdf, concat } = await import('./crypto.ts')
const { sendPush, setPushDepsForTests, pushPayload } = await import('./send.ts')
const { parseSubscription, upsertSub, listUserSubs, listAllSubs, isAllowedEndpoint } = await import('./store.ts')
const { pushForNewCard } = await import('./notify.ts')
const { shouldPushCard, resolveRules, defaultNotificationRules } = await import('../notifications/types.ts')
const { patchSettings } = await import('../lib/settings.ts')
const { saveRules } = await import('../notifications/store.ts')
const { handlePushApi, setVisitorForTests } = await import('../app/push-api.ts')
const { handleSentryIssueEvent } = await import('../signals/sentry/intake.ts')
const { upsertProject } = await import('../projects/config.ts')
const { default: signalsWebhook } = await import('../webhooks/signals.ts')

const reset = () => (globalThis as { __factoryStore?: Map<string, unknown> }).__factoryStore?.clear()

/** A browser-side subscription: key pair plus auth secret. */
async function browserKeys() {
	const pair = (await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits'])) as CryptoKeyPair
	const pub = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey))
	const auth = crypto.getRandomValues(new Uint8Array(16))
	return { pair, p256dh: b64urlEncode(pub), auth: b64urlEncode(auth) }
}

/** RFC 8291 decrypt, the browser's side, to prove the round trip. */
async function decrypt(body: Uint8Array, keys: Awaited<ReturnType<typeof browserKeys>>) {
	const salt = body.slice(0, 16)
	const rs = new DataView(body.buffer, body.byteOffset).getUint32(16)
	assert.equal(rs, 4096)
	const idlen = body[20]!
	const asPublic = body.slice(21, 21 + idlen)
	const cipher = body.slice(21 + idlen)
	const asKey = await crypto.subtle.importKey('raw', asPublic, { name: 'ECDH', namedCurve: 'P-256' }, false, [])
	const ecdh = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: asKey }, keys.pair.privateKey, 256))
	const enc = new TextEncoder()
	const ua = b64urlDecode(keys.p256dh)
	const ikm = await hkdf(b64urlDecode(keys.auth), ecdh, concat(enc.encode('WebPush: info\0'), ua, asPublic), 32)
	const cek = await hkdf(salt, ikm, enc.encode('Content-Encoding: aes128gcm\0'), 16)
	const nonce = await hkdf(salt, ikm, enc.encode('Content-Encoding: nonce\0'), 12)
	const k = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt'])
	const plain = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, k, cipher))
	assert.equal(plain.at(-1), 2, 'last record delimiter')
	return new TextDecoder().decode(plain.slice(0, -1))
}

test('RFC 8291: a browser can decrypt what the factory encrypts', async () => {
	const keys = await browserKeys()
	const body = await encryptPushPayload(keys, new TextEncoder().encode('{"title":"hi"}'))
	assert.equal(await decrypt(body, keys), '{"title":"hi"}')
	await assert.rejects(encryptPushPayload({ p256dh: 'AAAA', auth: keys.auth }, new Uint8Array(1)), /bad p256dh/)
})

test('subscriptions: only known push hosts, validated keys, stored per user', async () => {
	reset()
	const keys = await browserKeys()
	assert.equal(isAllowedEndpoint('https://fcm.googleapis.com/fcm/send/abc'), true)
	assert.equal(isAllowedEndpoint('https://wns2-by3p.notify.windows.com/w/?token=x'), true)
	assert.equal(isAllowedEndpoint('https://evil.example.com/push'), false)
	assert.equal(isAllowedEndpoint('http://fcm.googleapis.com/x'), false)
	assert.equal(parseSubscription({ endpoint: 'https://evil.example.com/x', keys }).ok, false)
	const ok = parseSubscription({ endpoint: 'https://fcm.googleapis.com/fcm/send/abc', keys: { p256dh: keys.p256dh, auth: keys.auth } })
	assert.equal(ok.ok, true)
	if (!ok.ok) return
	await upsertSub('u1', 'kent', ok, 'Chrome on macOS')
	await upsertSub('u1', 'kent', ok, 'Chrome on macOS again')
	await upsertSub('u2', 'other', { ...ok, endpoint: 'https://web.push.apple.com/x' }, 'Safari on iOS')
	assert.equal((await listUserSubs('u1')).length, 1, 're-subscribing the same endpoint updates it')
	assert.equal((await listAllSubs()).length, 2)
})

test('rules: push is on by default for sentry and signal cards and needs-attention, off for others', () => {
	const rule = resolveRules({ defaults: { categories: [], minSeverity: 'info', discordEnabled: false, wakeEnabled: false } as never, projects: {} }, 'kody')
	assert.equal(rule.pushEnabled, true, 'older stored rules get the push defaults')
	assert.equal(shouldPushCard(rule, { labels: ['sentry'], needsKent: false }), true)
	assert.equal(shouldPushCard(rule, { labels: ['source:signal'], needsKent: false }), true)
	assert.equal(shouldPushCard(rule, { labels: ['outage'], needsKent: false }), false)
	assert.equal(shouldPushCard(rule, { labels: [], needsKent: true }), true)
	assert.equal(shouldPushCard({ ...defaultNotificationRules().defaults, pushEnabled: false }, { labels: ['sentry'], needsKent: true }), false)
})

test('sendPush: signs VAPID per push origin through the credential, posts aes128gcm, drops gone devices', async () => {
	reset()
	const keys = await browserKeys()
	await patchSettings({ webPushVapidPublicKey: 'B'.repeat(87) })
	await upsertSub('u1', 'kent', { endpoint: 'https://fcm.googleapis.com/fcm/send/a', p256dh: keys.p256dh, auth: keys.auth }, 'A')
	await upsertSub('u1', 'kent', { endpoint: 'https://updates.push.services.mozilla.com/wpush/v2/b', p256dh: keys.p256dh, auth: keys.auth }, 'B')
	const signed: Array<{ host: string; claims: Record<string, unknown> }> = []
	const posts: Array<{ url: string; headers: Record<string, string>; body: Uint8Array }> = []
	setPushDepsForTests({
		sign: async (host, claims) => { signed.push({ host, claims }); return 'h.p.s' },
		fetch: (async (url: string, init: RequestInit) => {
			posts.push({ url, headers: init.headers as Record<string, string>, body: init.body as Uint8Array })
			return new Response(null, { status: url.includes('mozilla') ? 410 : 201 })
		}) as typeof fetch,
	})
	const r = await sendPush({ kind: 'card', title: 'Sentry: boom', body: 'x', path: '/work?card=wi_1', cardId: 'wi_1' })
	assert.deepEqual([r.sent, r.removed, r.failed], [1, 1, 0])
	assert.deepEqual(signed.map((s) => s.host).sort(), ['fcm.googleapis.com', 'updates.push.services.mozilla.com'])
	assert.equal(signed[0]!.claims.aud, 'https://' + signed[0]!.host)
	assert.match(String(signed[0]!.claims.sub), /^https:\/\//)
	assert.equal(posts[0]!.headers['Content-Encoding'], 'aes128gcm')
	assert.match(posts[0]!.headers.Authorization!, /^vapid t=h\.p\.s, k=B+$/)
	assert.equal(JSON.parse(await decrypt(posts[0]!.body, keys)).path, '/work?card=wi_1')
	assert.equal((await listUserSubs('u1')).length, 1, 'the 410 device was removed')
	setPushDepsForTests(null)
})

test('pushPayload keeps paths inside the app', () => {
	assert.equal(JSON.parse(pushPayload({ kind: 't', title: 't', body: '', path: '//evil.example.com' })).path, '/')
	assert.equal(JSON.parse(pushPayload({ kind: 't', title: 't', body: '', path: '/work?card=x' })).path, '/work?card=x')
})

test('no public key or no devices sends nothing and never throws', async () => {
	reset()
	assert.match(String((await sendPush({ kind: 't', title: 't', body: '', path: '/' })).skipped), /not configured/)
	await patchSettings({ webPushVapidPublicKey: 'B'.repeat(87) })
	assert.equal((await sendPush({ kind: 't', title: 't', body: '', path: '/' })).skipped, 'no subscribed devices')
	assert.deepEqual(await pushForNewCard({ id: 'wi', projectId: 'kody', title: 't', body: '', labels: ['outage'], needsKent: false, priority: 0 }), { skipped: 'rules' })
})

test('push API: signed-in visitor only, same user devices only, test push goes to that user', async () => {
	reset()
	const keys = await browserKeys()
	await patchSettings({ webPushVapidPublicKey: 'B'.repeat(87) })
	setVisitorForTests(async () => null)
	assert.equal((await handlePushApi('/api/push', new Request('https://x/api/push')))!.status, 401)
	setVisitorForTests(async () => ({ userId: 'u1', username: 'kent' }))
	const post = (path: string, body: unknown) => handlePushApi(path, new Request('https://x' + path, { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }))
	assert.equal((await post('/api/push/subscribe', { subscription: { endpoint: 'https://evil.example.com/x', keys } }))!.status, 400)
	const ok = await post('/api/push/subscribe', { subscription: { endpoint: 'https://fcm.googleapis.com/fcm/send/k', keys: { p256dh: keys.p256dh, auth: keys.auth } }, label: 'Chrome <script>' })
	assert.equal(ok!.status, 200)
	assert.equal(((await ok!.json()) as { device: { label: string } }).device.label, 'Chrome script')
	await upsertSub('u2', 'other', { endpoint: 'https://web.push.apple.com/o', p256dh: keys.p256dh, auth: keys.auth }, 'Other')
	const info = (await (await handlePushApi('/api/push', new Request('https://x/api/push')))!.json()) as { devices: Array<{ host: string }>; configured: boolean }
	assert.equal(info.configured, true)
	assert.deepEqual(info.devices.map((d) => d.host), ['fcm.googleapis.com'])
	const hits: string[] = []
	setPushDepsForTests({ sign: async () => 'j', fetch: (async (url: string) => { hits.push(url); return new Response(null, { status: 201 }) }) as typeof fetch })
	const t = await post('/api/push/test', {})
	assert.equal(((await t!.json()) as { sent: number }).sent, 1)
	assert.deepEqual(hits, ['https://fcm.googleapis.com/fcm/send/k'])
	setPushDepsForTests(null)
	setVisitorForTests(null)
})

const sentryEvent = (id = '4242', kodyId = 'sentry-events') => ({
	event: '@kody/sentry-events.issue.alerted',
	source: { type: 'package', kody_id: kodyId },
	payload: { resource: 'issue', action: 'created', kind: 'issue', issueId: id, shortId: 'KODY-1', title: 'TypeError: x is undefined', culprit: 'app/x.ts', level: 'error', projectSlug: 'kody', sentryProjectId: '7', url: 'https://sentry.io/issues/4242/', count: '3' },
})

test('Sentry intake: issue events file one card per issue and push it; other emitters write nothing', async () => {
	reset()
	await upsertProject({ id: 'kody', displayName: 'Kody', enabled: true, defaultRunnerId: 'single-agent', repos: [{ id: 'k', repoRef: 'kody-hq/kody', host: 'github', enabled: true }] } as never)
	const keys = await browserKeys()
	await patchSettings({ webPushVapidPublicKey: 'B'.repeat(87) })
	// No quiet hours, so the P1 push goes out whatever the clock says.
	await saveRules({ ...defaultNotificationRules(), defaults: { ...defaultNotificationRules().defaults, quietHours: { start: 0, end: 0, timeZone: 'America/Denver' } } })
	await upsertSub('u1', 'kent', { endpoint: 'https://fcm.googleapis.com/fcm/send/s', p256dh: keys.p256dh, auth: keys.auth }, 'A')
	const pushed: string[] = []
	setPushDepsForTests({ sign: async () => 'j', fetch: (async (_u: string, init: RequestInit) => { pushed.push(JSON.parse(await decrypt(init.body as Uint8Array, keys)).title); return new Response(null, { status: 201 }) }) as typeof fetch })

	assert.equal((await handleSentryIssueEvent(sentryEvent('4242', 'not-sentry'))).action, 'rejected')
	const first = await handleSentryIssueEvent(sentryEvent())
	assert.equal(first.action, 'created')
	const again = await handleSentryIssueEvent(sentryEvent())
	assert.equal(again.action, 'replayed')
	assert.equal(again.itemId, first.itemId)
	assert.deepEqual(pushed, ['P1 Sentry: TypeError: x is undefined'], 'one push for the new card, none for the replay')
	setPushDepsForTests(null)
})

test('a Sentry request on the factory signals webhook writes nothing and names the new home', async () => {
	const r = (await signalsWebhook({ request: { headers: { 'sentry-hook-resource': 'issue', 'sentry-hook-signature': 'aa' }, body: '{}' } })) as { ok: boolean; error: string }
	assert.equal(r.ok, false)
	assert.match(r.error, /@kody\/sentry-events/)
})