Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(terminal): add doom deathmatch over webrtc (#113476)

Marius Andra1d86ac380fc0
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 00eac712c2cc..810cc221b1eb 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -5396,6 +5396,61 @@ export interface EventMatchResponseApi {
matches: EventMatchApi[]
}
+/**
+ * * `offer` - offer
+ * * `answer` - answer
+ */
+export type TerminalNetplayDescriptionTypeEnumApi =
+ (typeof TerminalNetplayDescriptionTypeEnumApi)[keyof typeof TerminalNetplayDescriptionTypeEnumApi]
+
+export const TerminalNetplayDescriptionTypeEnumApi = {
+ Offer: 'offer',
+ Answer: 'answer',
+} as const
+
+export interface TerminalNetplayDescriptionApi {
+ /** WebRTC session description type.
+ *
+ * * `offer` - offer
+ * * `answer` - answer */
+ type: TerminalNetplayDescriptionTypeEnumApi
+ /**
+ * WebRTC session description with ICE candidates.
+ * @maxLength 16384
+ */
+ sdp: string
+}
+
+export interface TerminalNetplayReceivedSignalApi {
+ /** Peer that sent the description. */
+ sender: string
+ description: TerminalNetplayDescriptionApi
+}
+
+export interface TerminalNetplayMailboxApi {
+ /** Descriptions received since the last read. */
+ signals: TerminalNetplayReceivedSignalApi[]
+}
+
+export interface TerminalNetplaySignalApi {
+ /**
+ * Room code shown by the game host.
+ * @pattern ^[A-Z0-9]{4,12}$
+ */
+ room: string
+ /**
+ * Peer that sent the description.
+ * @pattern ^[a-z0-9]{1,32}$
+ */
+ sender: string
+ /**
+ * Peer that receives the description.
+ * @pattern ^[a-z0-9]{1,32}$
+ */
+ recipient: string
+ description: TerminalNetplayDescriptionApi
+}
+
export interface UploadedMediaApi {
readonly id: string
/** The file's original name. */
@@ -6823,6 +6878,21 @@ export const PropertyDefinitionsListType = {
Session: 'session',
} as const
+export type TerminalNetplayMailboxRetrieveParams = {
+ /**
+ * Peer whose mailbox to read. The host reads 'host'.
+ * @minLength 1
+ * @pattern ^[a-z0-9]{1,32}$
+ */
+ peer: string
+ /**
+ * Room code shown by the game host.
+ * @minLength 1
+ * @pattern ^[A-Z0-9]{4,12}$
+ */
+ room: string
+}
+
export type UploadedMediaListParams = {
/**
* Number of results to return per page.
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 21d6a79df9ee..27f568e5cb52 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -99,6 +99,9 @@ import type {
SearchIntentRequestApi,
SearchIntentResponseApi,
SharingConfigurationApi,
+ TerminalNetplayMailboxApi,
+ TerminalNetplayMailboxRetrieveParams,
+ TerminalNetplaySignalApi,
ToolbarEntitlementsApi,
TwoFactorStatusApi,
UploadedMediaApi,
@@ -2687,6 +2690,59 @@ export const taxonomicSearchIntentMatchEventsCreate = async (
})
}
+export const getTerminalNetplayMailboxRetrieveUrl = (
+ projectId: string,
+ params: TerminalNetplayMailboxRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/terminal_netplay/mailbox/?${stringifiedParams}`
+ : `/api/projects/${projectId}/terminal_netplay/mailbox/`
+}
+
+/**
+ * Read and clear a terminal's WebRTC mailbox. Reading the host mailbox keeps the room open.
+ */
+export const terminalNetplayMailboxRetrieve = async (
+ projectId: string,
+ params: TerminalNetplayMailboxRetrieveParams,
+ options?: RequestInit
+): Promise<TerminalNetplayMailboxApi> => {
+ return apiMutator<TerminalNetplayMailboxApi>(getTerminalNetplayMailboxRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getTerminalNetplaySignalCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/terminal_netplay/signal/`
+}
+
+/**
+ * Send a WebRTC session description to another terminal in a Doom room.
+ */
+export const terminalNetplaySignalCreate = async (
+ projectId: string,
+ terminalNetplaySignalApi: TerminalNetplaySignalApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getTerminalNetplaySignalCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(terminalNetplaySignalApi),
+ })
+}
+
export const getUploadedMediaListUrl = (projectId: string, params: UploadedMediaListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 9d1835710214..2858211738a7 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -1228,6 +1228,33 @@ export const TaxonomicSearchIntentMatchEventsCreateBody = /* @__PURE__ */ zod.ob
.describe('What the person typed into the events list search box, which matched no event name.'),
})
+/**
+ * Send a WebRTC session description to another terminal in a Doom room.
+ */
+export const terminalNetplaySignalCreateBodyRoomRegExp = new RegExp('^[A-Z0-9]{4,12}$')
+export const terminalNetplaySignalCreateBodySenderRegExp = new RegExp('^[a-z0-9]{1,32}$')
+export const terminalNetplaySignalCreateBodyRecipientRegExp = new RegExp('^[a-z0-9]{1,32}$')
+export const terminalNetplaySignalCreateBodyDescriptionSdpMax = 16384
+
+export const TerminalNetplaySignalCreateBody = /* @__PURE__ */ zod.object({
+ room: zod.string().regex(terminalNetplaySignalCreateBodyRoomRegExp).describe('Room code shown by the game host.'),
+ sender: zod.string().regex(terminalNetplaySignalCreateBodySenderRegExp).describe('Peer that sent the description.'),
+ recipient: zod
+ .string()
+ .regex(terminalNetplaySignalCreateBodyRecipientRegExp)
+ .describe('Peer that receives the description.'),
+ description: zod.object({
+ type: zod
+ .enum(['offer', 'answer'])
+ .describe('\* `offer` - offer\n\* `answer` - answer')
+ .describe('WebRTC session description type.\n\n\* `offer` - offer\n\* `answer` - answer'),
+ sdp: zod
+ .string()
+ .max(terminalNetplaySignalCreateBodyDescriptionSdpMax)
+ .describe('WebRTC session description with ICE candidates.'),
+ }),
+})
+
/**
*
* When object storage is available this API allows upload of media which can be used, for example, in text cards on dashboards.
diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.ts
index 5d92e72395d5..0e253c2b1b44 100644
--- a/frontend/src/scenes/terminal/posthogFilesystem.ts
+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts
@@ -120,6 +120,8 @@ Folders open in the Files tab when the simple side panel is enabled.
Optional tools download on first use: nvim, node, pi, nyancat, and doom.
In Doom, W/S move, A/D strafe, left/right arrows turn, Space fires, E opens doors,
and Shift runs. Use Capture mouse to turn with the mouse; left-click fires.
+For a deathmatch, one player runs doom -server -deathmatch and shares the room code.
+Other players in this project run doom -connect <code>. The host presses Space to start.
Saving a .sql insight updates its query and preserves its query options.
Use run report.sql to execute SQL, or run --help for JSON, CSV, and TSV exports.
diff --git a/frontend/src/scenes/terminal/terminal-packages.json b/frontend/src/scenes/terminal/terminal-packages.json
index aee8628846aa..0f5c8557a077 100644
--- a/frontend/src/scenes/terminal/terminal-packages.json
+++ b/frontend/src/scenes/terminal/terminal-packages.json
@@ -28,14 +28,15 @@
},
"doom": {
"name": "Doom (Freedoom)",
- "version": "0.13.0-2",
- "file": "archives/doom-0.13.0-2-linux-i386.tar.gz",
- "sha256": "4943c6d37922eac98473d9d20554d02dd8cc01948fb81edc150ba30d2f0ae6c6",
- "size": 10501917,
- "archiveSize": 29552640,
+ "version": "0.13.0-4",
+ "file": "archives/doom-0.13.0-4-linux-i386.tar.gz",
+ "baseUrl": "https://raw.githubusercontent.com/PostHog/terminal-assets/c1cea5819fbe981dddbd0bf85513e92f52e178da",
+ "sha256": "a12596c8ad98315bcfbda5aec405702f11088ddaf5ff57d504de95c7693a88bb",
+ "size": 10553882,
+ "archiveSize": 29757440,
"dependencies": [],
"commands": {
- "doom": "/opt/posthog-packages/doom-0.13.0-2/bin/doom"
+ "doom": "/opt/posthog-packages/doom-0.13.0-4/bin/doom"
}
},
"sl": {
diff --git a/frontend/src/scenes/terminal/terminalLogic.test.ts b/frontend/src/scenes/terminal/terminalLogic.test.ts
index 07545c205dd5..c9146f0e939f 100644
--- a/frontend/src/scenes/terminal/terminalLogic.test.ts
+++ b/frontend/src/scenes/terminal/terminalLogic.test.ts
@@ -19,6 +19,7 @@ import { PosthogFilesystem } from './posthogFilesystem'
import { TerminalConfirmation } from './terminalConfirmation'
import { terminalDockLogic } from './terminalDockLogic'
import { terminalLogic } from './terminalLogic'
+import { TerminalNetplay } from './terminalNetplay'
import { TerminalRuntime } from './terminalRuntime'
import { TerminalSession } from './TerminalSession'
@@ -159,7 +160,8 @@ describe('terminal lifecycle', () => {
expect.anything(),
expect.anything(),
expect.any(Function),
- '/posthog/files/Research'
+ '/posthog/files/Research',
+ expect.any(TerminalNetplay)
)
const view = jest.mocked(TerminalSession).mock.results[0].value.view
view.focus.mockClear()
diff --git a/frontend/src/scenes/terminal/terminalLogic.ts b/frontend/src/scenes/terminal/terminalLogic.ts
index 352019e2b268..9b7dce6f397a 100644
--- a/frontend/src/scenes/terminal/terminalLogic.ts
+++ b/frontend/src/scenes/terminal/terminalLogic.ts
@@ -20,6 +20,7 @@ import { PosthogFilesystem } from './posthogFilesystem'
import { TerminalAI } from './terminalAI'
import { TerminalConfirmation } from './terminalConfirmation'
import { terminalDockLogic } from './terminalDockLogic'
+import { TerminalNetplay } from './terminalNetplay'
import { TerminalRuntime } from './terminalRuntime'
import { TerminalSession } from './TerminalSession'
@@ -564,7 +565,8 @@ export const terminalLogic = kea<terminalLogicType>([
}, 'clock-sync')
}
},
- folder ?? undefined
+ folder ?? undefined,
+ new TerminalNetplay(String(projectId), controller.signal)
)
if (controller.signal.aborted) {
return
diff --git a/frontend/src/scenes/terminal/terminalNetplay.test.ts b/frontend/src/scenes/terminal/terminalNetplay.test.ts
new file mode 100644
index 000000000000..acf286ba87d7
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalNetplay.test.ts
@@ -0,0 +1,284 @@
+import { ApiError } from 'lib/api-error'
+
+import { terminalNetplayMailboxRetrieve, terminalNetplaySignalCreate } from '~/generated/core/api'
+
+import { FrameDecoder, TerminalNetplay, encodeFrame } from './terminalNetplay'
+
+jest.mock('~/generated/core/api', () => ({
+ terminalNetplayMailboxRetrieve: jest.fn(),
+ terminalNetplaySignalCreate: jest.fn(),
+}))
+
+class FakeChannel extends EventTarget {
+ readyState: RTCDataChannelState = 'open'
+ binaryType = 'blob'
+ send = jest.fn()
+}
+
+class FakeConnection extends EventTarget {
+ static created: FakeConnection[] = []
+ static configure?: (connection: FakeConnection) => void
+ iceGatheringState: RTCIceGatheringState = 'complete'
+ localDescription: { sdp: string } | null = null
+ channel = new FakeChannel()
+ createDataChannel = jest.fn(() => this.channel)
+ setRemoteDescription = jest.fn(async () => {})
+ setLocalDescription = jest.fn(async () => {
+ this.localDescription = { sdp: `local sdp ${FakeConnection.created.indexOf(this)}` }
+ })
+ close = jest.fn()
+
+ constructor() {
+ super()
+ FakeConnection.created.push(this)
+ FakeConnection.configure?.(this)
+ }
+}
+
+describe('terminal Doom netplay', () => {
+ const mailbox = terminalNetplayMailboxRetrieve as jest.Mock
+ const signal = terminalNetplaySignalCreate as jest.Mock
+ const originalConnection = globalThis.RTCPeerConnection
+ let session: AbortController
+ let netplay: TerminalNetplay
+ let guest: { peer: number; text: string; bytes: number[] }[]
+
+ const fromGuest = (peer: number, payload: string | number[]): void => {
+ const bytes = typeof payload === 'string' ? new TextEncoder().encode(payload) : Uint8Array.from(payload)
+ for (const byte of encodeFrame(peer, bytes)) {
+ netplay.receive(byte)
+ }
+ }
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ FakeConnection.created = []
+ FakeConnection.configure = undefined
+ globalThis.RTCPeerConnection = FakeConnection as unknown as typeof RTCPeerConnection
+ mailbox.mockReset().mockResolvedValue({ signals: [] })
+ signal.mockReset().mockResolvedValue(undefined)
+ session = new AbortController()
+ netplay = new TerminalNetplay('42', session.signal)
+ guest = []
+ const decoder = new FrameDecoder()
+ netplay.attach((bytes) => {
+ for (const byte of bytes) {
+ const frame = decoder.push(byte)
+ if (frame) {
+ const payload = Array.from(frame.subarray(1))
+ guest.push({ peer: frame[0], text: new TextDecoder().decode(frame.slice(1)), bytes: payload })
+ }
+ }
+ })
+ })
+
+ afterEach(() => {
+ session.abort()
+ jest.useRealTimers()
+ globalThis.RTCPeerConnection = originalConnection
+ })
+
+ it('keeps SLIP escape bytes intact in both directions', () => {
+ const decoder = new FrameDecoder()
+ const frames = [...encodeFrame(7, Uint8Array.from([0xc0, 1, 0xdb, 0xdc]))]
+ .map((byte) => decoder.push(byte))
+ .filter(Boolean)
+
+ expect(frames).toEqual([Uint8Array.from([7, 0xc0, 1, 0xdb, 0xdc])])
+ })
+
+ it('hosts a room, answers an offer, and relays packets until the game launches', async () => {
+ fromGuest(255, 'host')
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(guest).toEqual([
+ { peer: 255, text: expect.stringMatching(/^room [A-Z0-9]{6}$/), bytes: expect.any(Array) },
+ ])
+ const room = guest[0].text.slice(5)
+ expect(mailbox).toHaveBeenLastCalledWith('42', { room, peer: 'host' }, expect.anything())
+
+ mailbox.mockResolvedValueOnce({ signals: [{ sender: 'abc', description: { type: 'offer', sdp: 'offer' } }] })
+ await jest.advanceTimersByTimeAsync(1000)
+
+ const [connection] = FakeConnection.created
+ expect(connection.setRemoteDescription).toHaveBeenCalledWith({ type: 'offer', sdp: 'offer' })
+ expect(signal).toHaveBeenCalledWith(
+ '42',
+ { room, sender: 'host', recipient: 'abc', description: { type: 'answer', sdp: 'local sdp 0' } },
+ expect.anything()
+ )
+ expect(mailbox.mock.calls[0][2].headers['X-Terminal-Netplay-Token']).toMatch(/^[a-f0-9]{64}$/)
+ expect(signal.mock.calls[0][2].headers).toEqual(mailbox.mock.calls[0][2].headers)
+
+ connection.channel.dispatchEvent(new MessageEvent('message', { data: Uint8Array.from([1, 2, 3]).buffer }))
+ fromGuest(1, [9, 8])
+ fromGuest(2, [7])
+
+ expect(guest[1]).toEqual({ peer: 1, text: expect.any(String), bytes: [1, 2, 3] })
+ expect(connection.channel.send).toHaveBeenCalledTimes(1)
+ expect(connection.channel.send).toHaveBeenCalledWith(Uint8Array.from([9, 8]))
+
+ fromGuest(255, 'launched')
+ const polls = mailbox.mock.calls.length
+ await jest.advanceTimersByTimeAsync(5000)
+ expect(mailbox).toHaveBeenCalledTimes(polls)
+ expect(connection.close).not.toHaveBeenCalled()
+ })
+
+ it('joins a room and relays packets with the host as peer 0', async () => {
+ mailbox.mockResolvedValueOnce({ signals: [{ sender: 'host', description: { type: 'answer', sdp: 'answer' } }] })
+
+ fromGuest(255, 'join abc123')
+ await jest.advanceTimersByTimeAsync(500)
+
+ const [connection] = FakeConnection.created
+ expect(signal).toHaveBeenCalledWith(
+ '42',
+ expect.objectContaining({
+ room: 'ABC123',
+ recipient: 'host',
+ description: { type: 'offer', sdp: 'local sdp 0' },
+ }),
+ expect.anything()
+ )
+ expect(connection.setRemoteDescription).toHaveBeenCalledWith({ type: 'answer', sdp: 'answer' })
+ expect(guest).toEqual([{ peer: 255, text: 'joined', bytes: expect.any(Array) }])
+ expect(signal.mock.calls[0][2].headers['X-Terminal-Netplay-Token']).toMatch(/^[a-f0-9]{64}$/)
+ expect(mailbox.mock.calls[0][2].headers).toEqual(signal.mock.calls[0][2].headers)
+
+ connection.channel.dispatchEvent(new MessageEvent('message', { data: Uint8Array.from([4]).buffer }))
+ fromGuest(0, [5])
+
+ expect(guest[1].peer).toBe(0)
+ expect(guest[1].bytes).toEqual([4])
+ expect(connection.channel.send).toHaveBeenCalledWith(Uint8Array.from([5]))
+ })
+
+ it('ignores repeated offers from the same player', async () => {
+ const offer = { sender: 'abc', description: { type: 'offer', sdp: 'offer' } }
+ mailbox.mockResolvedValue({ signals: [offer, offer] })
+
+ fromGuest(255, 'host')
+ await jest.advanceTimersByTimeAsync(2000)
+
+ expect(FakeConnection.created).toHaveLength(1)
+ expect(signal).toHaveBeenCalledTimes(1)
+ })
+
+ it('closes rejected offers and reuses their peer slots', async () => {
+ FakeConnection.configure = (connection) => {
+ connection.setRemoteDescription.mockRejectedValue(new Error('Invalid SDP'))
+ }
+ mailbox.mockResolvedValueOnce({
+ signals: ['a', 'b', 'c'].map((sender) => ({ sender, description: { type: 'offer', sdp: 'invalid' } })),
+ })
+ fromGuest(255, 'host')
+ await jest.advanceTimersByTimeAsync(0)
+ for (const connection of FakeConnection.created) {
+ expect(connection.close).toHaveBeenCalledTimes(1)
+ }
+ expect(signal).not.toHaveBeenCalled()
+
+ FakeConnection.configure = undefined
+ mailbox.mockResolvedValueOnce({ signals: [{ sender: 'a', description: { type: 'offer', sdp: 'valid' } }] })
+ await jest.advanceTimersByTimeAsync(1000)
+ const connection = FakeConnection.created[3]
+ fromGuest(1, [7])
+
+ expect(connection.channel.send).toHaveBeenCalledWith(Uint8Array.from([7]))
+ expect(signal).toHaveBeenCalledTimes(1)
+ })
+
+ it('bounds pending connections and releases them when the channel never opens', async () => {
+ FakeConnection.configure = (connection) => {
+ connection.channel.readyState = 'connecting'
+ }
+ mailbox.mockResolvedValueOnce({
+ signals: Array.from({ length: 17 }, (_, index) => ({
+ sender: `player${index}`,
+ description: { type: 'offer', sdp: 'offer' },
+ })),
+ })
+ fromGuest(255, 'host')
+ await jest.advanceTimersByTimeAsync(0)
+ expect(FakeConnection.created).toHaveLength(16)
+
+ await jest.advanceTimersByTimeAsync(20_000)
+ for (const connection of FakeConnection.created) {
+ expect(connection.close).toHaveBeenCalledTimes(1)
+ }
+ FakeConnection.configure = undefined
+ mailbox.mockResolvedValueOnce({
+ signals: [{ sender: 'player0', description: { type: 'offer', sdp: 'retry' } }],
+ })
+ await jest.advanceTimersByTimeAsync(1000)
+ fromGuest(1, [7])
+ expect(FakeConnection.created[16].channel.send).toHaveBeenCalledWith(Uint8Array.from([7]))
+ })
+
+ it('ignores answers from anyone other than the host', async () => {
+ mailbox
+ .mockResolvedValueOnce({ signals: [{ sender: 'other', description: { type: 'answer', sdp: 'forged' } }] })
+ .mockResolvedValueOnce({ signals: [{ sender: 'host', description: { type: 'answer', sdp: 'answer' } }] })
+ fromGuest(255, 'join ABC123')
+ await jest.advanceTimersByTimeAsync(500)
+ const [connection] = FakeConnection.created
+ expect(connection.setRemoteDescription).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(500)
+ expect(connection.setRemoteDescription).toHaveBeenCalledWith({ type: 'answer', sdp: 'answer' })
+ })
+
+ it('discards a mailbox response that arrives after the session ends', async () => {
+ let respond!: (value: unknown) => void
+ mailbox.mockReturnValueOnce(new Promise((resolve) => (respond = resolve)))
+ fromGuest(255, 'host')
+ session.abort()
+ respond({ signals: [{ sender: 'abc', description: { type: 'offer', sdp: 'offer' } }] })
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(FakeConnection.created).toHaveLength(0)
+ expect(guest).toEqual([])
+ })
+
+ it('closes pending negotiations when the host launches', async () => {
+ FakeConnection.configure = (connection) => {
+ connection.channel.readyState = 'connecting'
+ }
+ mailbox.mockResolvedValueOnce({ signals: [{ sender: 'abc', description: { type: 'offer', sdp: 'offer' } }] })
+ fromGuest(255, 'host')
+ await jest.advanceTimersByTimeAsync(0)
+ fromGuest(255, 'launched')
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(FakeConnection.created[0].close).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([
+ [
+ 'an unknown room',
+ () =>
+ signal.mockRejectedValueOnce(
+ new ApiError('Not found', 404, undefined, { detail: 'No deathmatch room has this code.' })
+ ),
+ 'error No deathmatch room has this code.',
+ ],
+ [
+ 'too many connection attempts',
+ () =>
+ signal.mockRejectedValueOnce(
+ new ApiError('Throttled', 429, undefined, { detail: 'Try again in 30 seconds.' })
+ ),
+ 'error Try again in 30 seconds.',
+ ],
+ ['a host that never answers', () => {}, 'error The host did not answer. Check the room code and try again.'],
+ ])('reports %s to Doom', async (_name, setup, message) => {
+ setup()
+
+ fromGuest(255, 'join ABC123')
+ await jest.advanceTimersByTimeAsync(30_000)
+
+ expect(guest).toEqual([{ peer: 255, text: message, bytes: expect.any(Array) }])
+ expect(FakeConnection.created[0].close).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/scenes/terminal/terminalNetplay.ts b/frontend/src/scenes/terminal/terminalNetplay.ts
new file mode 100644
index 000000000000..b454363587aa
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalNetplay.ts
@@ -0,0 +1,441 @@
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api-error'
+
+import { terminalNetplayMailboxRetrieve, terminalNetplaySignalCreate } from '~/generated/core/api'
+import type { TerminalNetplayReceivedSignalApi } from '~/generated/core/api.schemas'
+
+// Doom's network module in PostHog/terminal-assets sends SLIP frames over the guest's third serial port.
+// The first byte names the peer: guest frames name the destination, and host frames name the source.
+const SLIP_END = 0xc0
+const SLIP_ESC = 0xdb
+const SLIP_ESC_END = 0xdc
+const SLIP_ESC_ESC = 0xdd
+const HOST_PEER = 0
+const CONTROL_PEER = 255
+const MAX_FRAME = 1500
+
+const ROOM_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
+const ICE_SERVERS: RTCIceServer[] = [{ urls: 'stun:stun.cloudflare.com:3478' }]
+const HOST_POLL_MS = 1000
+const JOIN_POLL_MS = 500
+const JOIN_TIMEOUT_MS = 20_000
+const GATHER_TIMEOUT_MS = 3000
+const MAX_PENDING_PEERS = 16
+
+interface HostLobby {
+ room: string
+ token: string
+ game: AbortSignal
+ signal: AbortSignal
+ peers: Map<string, number>
+ pending: Set<string>
+}
+
+export function encodeFrame(peer: number, payload: Uint8Array): Uint8Array {
+ const bytes = [SLIP_END]
+ for (const byte of [peer, ...payload]) {
+ if (byte === SLIP_END) {
+ bytes.push(SLIP_ESC, SLIP_ESC_END)
+ } else if (byte === SLIP_ESC) {
+ bytes.push(SLIP_ESC, SLIP_ESC_ESC)
+ } else {
+ bytes.push(byte)
+ }
+ }
+ bytes.push(SLIP_END)
+ return Uint8Array.from(bytes)
+}
+
+export class FrameDecoder {
+ private frame: number[] = []
+ private escaped = false
+ private overflow = false
+
+ push(byte: number): Uint8Array | null {
+ if (byte === SLIP_END) {
+ const frame = this.overflow || !this.frame.length ? null : Uint8Array.from(this.frame)
+ this.frame = []
+ this.escaped = false
+ this.overflow = false
+ return frame
+ }
+ if (this.escaped) {
+ byte = byte === SLIP_ESC_END ? SLIP_END : byte === SLIP_ESC_ESC ? SLIP_ESC : byte
+ this.escaped = false
+ } else if (byte === SLIP_ESC) {
+ this.escaped = true
+ return null
+ }
+ if (this.frame.length <= MAX_FRAME) {
+ this.frame.push(byte)
+ } else {
+ this.overflow = true
+ }
+ return null
+ }
+}
+
+function randomCode(alphabet: string, length: number): string {
+ return Array.from(
+ crypto.getRandomValues(new Uint8Array(length)),
+ (value) => alphabet[value % alphabet.length]
+ ).join('')
+}
+
+function sleep(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal.aborted) {
+ resolve()
+ return
+ }
+ const timer = setTimeout(done, ms)
+ signal.addEventListener('abort', done, { once: true })
+ function done(): void {
+ clearTimeout(timer)
+ signal.removeEventListener('abort', done)
+ resolve()
+ }
+ })
+}
+
+// Sending complete descriptions avoids a second signaling round trip for each ICE candidate.
+function gathered(connection: RTCPeerConnection, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ const timer = setTimeout(done, GATHER_TIMEOUT_MS)
+ connection.addEventListener('icegatheringstatechange', check)
+ signal.addEventListener('abort', done, { once: true })
+ check()
+ function check(): void {
+ if (signal.aborted || connection.iceGatheringState === 'complete') {
+ done()
+ }
+ }
+ function done(): void {
+ clearTimeout(timer)
+ connection.removeEventListener('icegatheringstatechange', check)
+ signal.removeEventListener('abort', done)
+ resolve()
+ }
+ })
+}
+
+function opened(channel: RTCDataChannel, timeout: number, signal: AbortSignal): Promise<boolean> {
+ return new Promise((resolve) => {
+ if (signal.aborted) {
+ resolve(false)
+ return
+ }
+ if (channel.readyState === 'open') {
+ resolve(true)
+ return
+ }
+ const timer = setTimeout(() => done(false), timeout)
+ const open = (): void => done(true)
+ const close = (): void => done(false)
+ channel.addEventListener('open', open)
+ channel.addEventListener('close', close)
+ signal.addEventListener('abort', close, { once: true })
+ function done(result: boolean): void {
+ clearTimeout(timer)
+ channel.removeEventListener('open', open)
+ channel.removeEventListener('close', close)
+ signal.removeEventListener('abort', close)
+ resolve(result)
+ }
+ })
+}
+
+class NetplayError extends Error {}
+
+/** Relays Doom network frames between this terminal's VM and other players' browsers over WebRTC. */
+export class TerminalNetplay {
+ private decoder = new FrameDecoder()
+ private encoder = new TextEncoder()
+ private send?: (bytes: Uint8Array) => void
+ private game?: AbortController
+ private lobby?: AbortController
+ private channels = new Map<number, RTCDataChannel>()
+
+ constructor(
+ private projectId: string,
+ signal: AbortSignal
+ ) {
+ signal.addEventListener('abort', () => this.endGame(), { once: true })
+ }
+
+ attach(send: (bytes: Uint8Array) => void): void {
+ this.send = send
+ }
+
+ receive(byte: number): void {
+ const frame = this.decoder.push(byte)
+ if (!frame) {
+ return
+ }
+ if (frame[0] === CONTROL_PEER) {
+ this.control(new TextDecoder().decode(frame.subarray(1)))
+ return
+ }
+ const channel = this.channels.get(frame[0])
+ if (channel?.readyState === 'open') {
+ channel.send(frame.slice(1))
+ }
+ }
+
+ private control(message: string): void {
+ if (message === 'host') {
+ void this.host(this.newGame())
+ } else if (message.startsWith('join ')) {
+ void this.join(message.slice(5).toUpperCase(), this.newGame())
+ } else if (message === 'launched') {
+ // Doom accepts no players after launch, so the room can expire.
+ this.lobby?.abort()
+ }
+ }
+
+ private reply(message: string): void {
+ this.send?.(encodeFrame(CONTROL_PEER, this.encoder.encode(message)))
+ }
+
+ private newGame(): AbortSignal {
+ this.endGame()
+ this.game = new AbortController()
+ return this.game.signal
+ }
+
+ private endGame(): void {
+ this.lobby?.abort()
+ this.game?.abort()
+ this.channels.clear()
+ }
+
+ private connect(
+ peer: number,
+ game: AbortSignal
+ ): { connection: RTCPeerConnection; channel: RTCDataChannel; close: () => void } {
+ const connection = new RTCPeerConnection({ iceServers: ICE_SERVERS })
+ // Doom resends lost packets itself, so late packets are worse than lost ones.
+ const channel = connection.createDataChannel('doom', {
+ negotiated: true,
+ id: 0,
+ ordered: false,
+ maxRetransmits: 0,
+ })
+ channel.binaryType = 'arraybuffer'
+ let closed = false
+ channel.addEventListener('message', ({ data }: MessageEvent<ArrayBuffer>) => {
+ if (!closed && !game.aborted && data.byteLength <= MAX_FRAME) {
+ this.send?.(encodeFrame(peer, new Uint8Array(data)))
+ }
+ })
+ const close = (): void => {
+ if (closed) {
+ return
+ }
+ closed = true
+ game.removeEventListener('abort', close)
+ channel.removeEventListener('close', close)
+ connection.close()
+ if (this.channels.get(peer) === channel) {
+ this.channels.delete(peer)
+ }
+ }
+ game.addEventListener('abort', close, { once: true })
+ channel.addEventListener('close', close, { once: true })
+ this.channels.set(peer, channel)
+ return { connection, channel, close }
+ }
+
+ private async host(game: AbortSignal): Promise<void> {
+ const room = randomCode(ROOM_ALPHABET, 6)
+ const lobby = (this.lobby = new AbortController())
+ const signal = lobby.signal
+ const token = randomCode('0123456789abcdef', 64)
+ const state: HostLobby = { room, token, game, signal, peers: new Map(), pending: new Set() }
+ let announced = false
+ while (!signal.aborted) {
+ try {
+ const { signals } = await terminalNetplayMailboxRetrieve(
+ this.projectId,
+ { room, peer: 'host' },
+ { signal, headers: { 'X-Terminal-Netplay-Token': token } }
+ )
+ if (signal.aborted) {
+ return
+ }
+ if (!announced) {
+ announced = true
+ this.reply(`room ${room}`)
+ posthog.capture('terminal deathmatch hosted')
+ }
+ this.acceptOffers(state, signals)
+ } catch (error) {
+ if (signal.aborted) {
+ return
+ }
+ if (!announced) {
+ this.reply(`error ${this.describe(error, 'Could not open a deathmatch room. Try again.')}`)
+ return
+ }
+ }
+ await sleep(HOST_POLL_MS, signal)
+ }
+ }
+
+ private acceptOffers(lobby: HostLobby, signals: TerminalNetplayReceivedSignalApi[]): void {
+ for (const { sender, description } of signals) {
+ if (description.type !== 'offer' || lobby.peers.has(sender) || lobby.pending.size >= MAX_PENDING_PEERS) {
+ continue
+ }
+ const allocated = new Set(lobby.peers.values())
+ let peer = HOST_PEER + 1
+ while (allocated.has(peer)) {
+ peer++
+ }
+ if (peer < CONTROL_PEER) {
+ lobby.peers.set(sender, peer)
+ lobby.pending.add(sender)
+ void this.accept(lobby, sender, description.sdp, peer)
+ }
+ }
+ }
+
+ private async accept(lobby: HostLobby, sender: string, sdp: string, peer: number): Promise<void> {
+ const negotiation = new AbortController()
+ const signal = negotiation.signal
+ const abort = (): void => negotiation.abort()
+ const timeout = setTimeout(abort, JOIN_TIMEOUT_MS)
+ lobby.signal.addEventListener('abort', abort, { once: true })
+ let close: (() => void) | undefined
+ let connected = false
+ try {
+ const client = this.connect(peer, lobby.game)
+ close = client.close
+ signal.addEventListener('abort', client.close, { once: true })
+ const { connection, channel } = client
+ await connection.setRemoteDescription({ type: 'offer', sdp })
+ if (signal.aborted) {
+ return
+ }
+ await connection.setLocalDescription()
+ await gathered(connection, signal)
+ if (signal.aborted || !connection.localDescription) {
+ return
+ }
+ await terminalNetplaySignalCreate(
+ this.projectId,
+ {
+ room: lobby.room,
+ sender: 'host',
+ recipient: sender,
+ description: { type: 'answer', sdp: connection.localDescription.sdp },
+ },
+ { signal, headers: { 'X-Terminal-Netplay-Token': lobby.token } }
+ )
+ connected = await opened(channel, JOIN_TIMEOUT_MS, signal)
+ } catch {
+ // The joining player reports the failure when the answer does not arrive.
+ } finally {
+ clearTimeout(timeout)
+ lobby.signal.removeEventListener('abort', abort)
+ if (close) {
+ signal.removeEventListener('abort', close)
+ }
+ lobby.pending.delete(sender)
+ if (!connected) {
+ close?.()
+ lobby.peers.delete(sender)
+ }
+ }
+ }
+
+ private async waitForAnswer(
+ room: string,
+ peer: string,
+ token: string,
+ deadline: number,
+ game: AbortSignal
+ ): Promise<string | undefined> {
+ while (!game.aborted) {
+ if (Date.now() > deadline) {
+ throw new NetplayError('The host did not answer. Check the room code and try again.')
+ }
+ await sleep(JOIN_POLL_MS, game)
+ if (game.aborted) {
+ return
+ }
+ const { signals } = await terminalNetplayMailboxRetrieve(
+ this.projectId,
+ { room, peer },
+ { signal: game, headers: { 'X-Terminal-Netplay-Token': token } }
+ )
+ const answer = signals.find(({ sender, description }) => sender === 'host' && description.type === 'answer')
+ if (answer) {
+ return answer.description.sdp
+ }
+ }
+ }
+
+ private async join(room: string, game: AbortSignal): Promise<void> {
+ const id = randomCode('abcdefghijklmnopqrstuvwxyz0123456789', 16)
+ const token = randomCode('0123456789abcdef', 64)
+ const deadline = Date.now() + JOIN_TIMEOUT_MS
+ let close: (() => void) | undefined
+ let connected = false
+ try {
+ const client = this.connect(HOST_PEER, game)
+ close = client.close
+ const { connection, channel } = client
+ await connection.setLocalDescription()
+ await gathered(connection, game)
+ if (game.aborted || !connection.localDescription) {
+ return
+ }
+ await terminalNetplaySignalCreate(
+ this.projectId,
+ {
+ room,
+ sender: id,
+ recipient: 'host',
+ description: { type: 'offer', sdp: connection.localDescription.sdp },
+ },
+ { signal: game, headers: { 'X-Terminal-Netplay-Token': token } }
+ )
+ const answer = await this.waitForAnswer(room, id, token, deadline, game)
+ if (game.aborted || !answer) {
+ return
+ }
+ await connection.setRemoteDescription({ type: 'answer', sdp: answer })
+ connected = await opened(channel, Math.max(deadline - Date.now(), 5000), game)
+ if (!connected) {
+ throw new NetplayError(
+ 'Could not connect to the host. A firewall or VPN may block peer-to-peer connections.'
+ )
+ }
+ if (!game.aborted) {
+ this.reply('joined')
+ posthog.capture('terminal deathmatch joined', { success: true })
+ }
+ } catch (error) {
+ if (!game.aborted) {
+ this.reply(`error ${this.describe(error, 'Could not join the deathmatch. Try again.')}`)
+ posthog.capture('terminal deathmatch joined', { success: false })
+ }
+ } finally {
+ if (!connected) {
+ close?.()
+ }
+ }
+ }
+
+ private describe(error: unknown, fallback: string): string {
+ if (error instanceof NetplayError) {
+ return error.message
+ }
+ if (error instanceof ApiError && (error.status === 404 || error.status === 429) && error.detail) {
+ return error.detail
+ }
+ return fallback
+ }
+}
diff --git a/frontend/src/scenes/terminal/terminalRuntime.ts b/frontend/src/scenes/terminal/terminalRuntime.ts
index 98af61f299cf..304913773c17 100644
--- a/frontend/src/scenes/terminal/terminalRuntime.ts
+++ b/frontend/src/scenes/terminal/terminalRuntime.ts
@@ -9,6 +9,7 @@ import vgaBiosUrl from './assets/vgabios.bin?url'
import { NinePServer } from './ninepServer'
import packageManifest from './terminal-packages.json'
import { DISPLAY_SCRIPT, TerminalDisplayInput } from './terminalDisplay'
+import { TerminalNetplay } from './terminalNetplay'
import { TerminalPackages } from './terminalPackages'
import { TerminalWorkerClient } from './TerminalWorkerClient'
@@ -93,11 +94,19 @@ export class TerminalRuntime {
this.emulator?.send({ type: 'display', visible: false })
}
+ private attachNetplay(emulator: TerminalWorkerClient, netplay?: TerminalNetplay): void {
+ if (netplay) {
+ netplay.attach((bytes) => emulator.serial_send_bytes(2, bytes))
+ emulator.add_listener('serial2-output-byte', (byte: number) => netplay.receive(byte))
+ }
+ }
+
async start(
server: NinePServer,
signal: AbortSignal,
onReady: () => void,
- folder = '/posthog/files'
+ folder = '/posthog/files',
+ netplay?: TerminalNetplay
): Promise<void> {
if (signal.aborted || this.disposed) {
return
@@ -151,6 +160,7 @@ export class TerminalRuntime {
const abort = (): void => this.dispose()
signal.addEventListener('abort', abort, { once: true })
this.removeAbortListener = () => signal.removeEventListener('abort', abort)
+ this.attachNetplay(emulator, netplay)
let boot = ''
let configured = false
emulator.add_listener('serial1-output-byte', (byte: number) => {
diff --git a/frontend/src/scenes/terminal/terminalWorker.ts b/frontend/src/scenes/terminal/terminalWorker.ts
index d31bc8ab187f..bdca9680d441 100644
--- a/frontend/src/scenes/terminal/terminalWorker.ts
+++ b/frontend/src/scenes/terminal/terminalWorker.ts
@@ -39,12 +39,12 @@ let emulator: WorkerV86 | undefined
let visible = false
let nextRequest = 0
const replies = new Map<number, { tag: number; reply: (bytes: Uint8Array) => void }>()
-const serial = [new Uint8Array(8192), new Uint8Array(8192)]
-const lengths = [0, 0]
+const serial = [new Uint8Array(8192), new Uint8Array(8192), new Uint8Array(8192)]
+const lengths = [0, 0, 0]
let flushScheduled = false
function flushSerial(): void {
- for (const port of [0, 1]) {
+ for (const port of [0, 1, 2]) {
if (lengths[port]) {
const bytes = serial[port].slice(0, lengths[port])
lengths[port] = 0
@@ -109,11 +109,14 @@ function receive(message: TerminalWorkerRequest): void {
disable_mouse: true,
disable_speaker: true,
uart1: true,
+ // Doom multiplayer frames; see terminalNetplay.ts.
+ uart2: true,
autostart: false,
}) as WorkerV86
const vm = emulator
vm.add_listener('serial0-output-byte', (byte: number) => output(0, byte))
vm.add_listener('serial1-output-byte', (byte: number) => output(1, byte))
+ vm.add_listener('serial2-output-byte', (byte: number) => output(2, byte))
vm.add_listener('emulator-loaded', () => {
// Linux uses a graphical framebuffer; retain v86's headless VGA text adapter for boot.
Object.assign(vm.screen_adapter, {
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index b37064c384ff..8ba5053400ba 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -8,6 +8,7 @@ from posthog.api import (
metalytics,
my_notifications,
project,
+ terminal_netplay,
user_integration,
user_push_token,
)
@@ -126,6 +127,12 @@ projects_router.register(
"project_my_notifications",
["project_id"],
)
+projects_router.register(
+ r"terminal_netplay",
+ terminal_netplay.TerminalNetplayViewSet,
+ "project_terminal_netplay",
+ ["project_id"],
+)
# Tasks endpoints
diff --git a/posthog/api/terminal_netplay.py b/posthog/api/terminal_netplay.py
new file mode 100644
index 000000000000..908b55543c0f
--- /dev/null
+++ b/posthog/api/terminal_netplay.py
@@ -0,0 +1,218 @@
+import re
+import json
+import hashlib
+from typing import TYPE_CHECKING, cast
+
+from django.http import HttpResponse
+
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.exceptions import NotFound, PermissionDenied, Throttled, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.utils import action
+from posthog.auth import SessionAuthentication
+from posthog.models.user import User
+from posthog.ph_client import feature_enabled_or_false
+from posthog.redis import get_client
+from posthog.token_bucket import BucketUnavailable, Budget, consume
+
+if TYPE_CHECKING:
+ from redis.client import Pipeline
+
+# Browser terminals exchange WebRTC session descriptions through short-lived mailboxes.
+# Game traffic flows directly between browsers, so this only carries a few messages per player.
+HOST = "host"
+ROOM_TTL_SECONDS = 30
+MAILBOX_TTL_SECONDS = 60
+MAILBOX_LIMIT = 16
+OFFER_BUDGET = Budget(burst=4, per_hour=120)
+ROOM_SIGNAL_BUDGET = Budget(burst=16, per_hour=3600)
+PEER_PATTERN = r"^[a-z0-9]{1,32}$"
+ROOM_PATTERN = r"^[A-Z0-9]{4,12}$"
+TOKEN_HEADER = "X-Terminal-Netplay-Token"
+TOKEN_PARAMETER = OpenApiParameter(
+ TOKEN_HEADER,
+ str,
+ OpenApiParameter.HEADER,
+ required=True,
+ pattern=r"^[a-f0-9]{64}$",
+ description="Random token unique to this terminal's game. Keep it private and reuse it for all signaling requests.",
+)
+
+
+class TerminalNetplayRoom:
+ def __init__(self, team_id: int, room: str, owner: str, user_id: int) -> None:
+ self.key = f"terminal_netplay:{team_id}:{room}"
+ self.owner = owner.encode()
+ self.user_id = user_id
+ self.client = get_client()
+
+ def _host(self, pipeline: Pipeline) -> bytes:
+ host = cast(bytes | None, pipeline.get(self.key))
+ if host is None:
+ raise NotFound("No deathmatch room has this code. Check the code and try again.")
+ return host
+
+ def _check_owner(self, owner: bytes | None) -> None:
+ if owner != self.owner:
+ raise PermissionDenied("This terminal does not own that player. Start a new game and try again.")
+
+ def _mailbox_key(self, host: bytes, peer: str) -> str:
+ # A new host token isolates mailboxes left behind by an expired room with the same code.
+ return f"{self.key}:{host.decode()}:{peer}"
+
+ def _peer_owner(self, pipeline: Pipeline, host: bytes, peer: str) -> bytes | None:
+ if peer == HOST:
+ return host
+ key = f"{self._mailbox_key(host, peer)}:owner"
+ pipeline.watch(key)
+ return cast(bytes | None, pipeline.get(key))
+
+ def _consume_budget(self, key: str, budget: Budget) -> None:
+ decision = consume(key, budget, client=self.client)
+ if isinstance(decision, BucketUnavailable):
+ raise Throttled(wait=1, detail="Signaling is temporarily unavailable. Try again.")
+ if not decision.allowed:
+ raise Throttled(wait=decision.retry_after, detail="Too many connection attempts. Wait and try again.")
+
+ def send(self, sender: str, recipient: str, description: dict[str, str]) -> None:
+ is_offer = sender != HOST and recipient == HOST and description["type"] == "offer"
+ is_answer = sender == HOST and recipient != HOST and description["type"] == "answer"
+ if not (is_offer or is_answer):
+ raise ValidationError("Send offers to the host and answers to the joining player.")
+ direction = description["type"]
+ self._consume_budget(
+ f"{self.key}:rate:{direction}:user:{self.user_id}", OFFER_BUDGET if is_offer else ROOM_SIGNAL_BUDGET
+ )
+ room_charged = False
+
+ def deliver(pipeline: Pipeline) -> None:
+ nonlocal room_charged
+ host = self._host(pipeline)
+ registered_owner = self._peer_owner(pipeline, host, sender)
+ if is_answer or registered_owner is not None:
+ self._check_owner(registered_owner)
+ recipient_owner = self._peer_owner(pipeline, host, recipient) if is_answer else None
+ if is_answer and recipient_owner is None:
+ raise NotFound("This player is no longer in the room. Ask them to join again.")
+ key = self._mailbox_key(host, recipient)
+ pipeline.watch(key)
+ if cast(int, pipeline.llen(key)) >= MAILBOX_LIMIT:
+ raise Throttled(wait=1, detail="This player's connection mailbox is full. Try again shortly.")
+ if not room_charged:
+ self._consume_budget(f"{self.key}:rate:{direction}", ROOM_SIGNAL_BUDGET)
+ room_charged = True
+ message = json.dumps({"sender": sender, "description": description})
+ pipeline.multi()
+ if is_offer:
+ pipeline.set(f"{self._mailbox_key(host, sender)}:owner", self.owner, ex=MAILBOX_TTL_SECONDS)
+ elif recipient_owner is not None:
+ pipeline.set(f"{key}:owner", recipient_owner, ex=MAILBOX_TTL_SECONDS)
+ pipeline.rpush(key, message)
+ pipeline.expire(key, MAILBOX_TTL_SECONDS)
+
+ self.client.transaction(deliver, self.key)
+
+ def read(self, peer: str) -> list[bytes]:
+ def consume(pipeline: Pipeline) -> None:
+ host = cast(bytes | None, pipeline.get(self.key))
+ if peer == HOST:
+ if host is not None:
+ self._check_owner(host)
+ host = self.owner
+ else:
+ host = self._host(pipeline)
+ self._check_owner(self._peer_owner(pipeline, host, peer))
+ key = self._mailbox_key(host, peer)
+ pipeline.multi()
+ if peer == HOST:
+ pipeline.set(self.key, self.owner, ex=ROOM_TTL_SECONDS)
+ pipeline.lrange(key, 0, -1)
+ pipeline.delete(key)
+
+ return cast(list[bytes], self.client.transaction(consume, self.key)[-2])
+
+
+class TerminalNetplayDescriptionSerializer(serializers.Serializer):
+ type = serializers.ChoiceField(choices=["offer", "answer"], help_text="WebRTC session description type.")
+ sdp = serializers.CharField(max_length=16384, help_text="WebRTC session description with ICE candidates.")
+
+
+class TerminalNetplaySignalSerializer(serializers.Serializer):
+ room = serializers.RegexField(ROOM_PATTERN, help_text="Room code shown by the game host.")
+ sender = serializers.RegexField(PEER_PATTERN, help_text="Peer that sent the description.")
+ recipient = serializers.RegexField(PEER_PATTERN, help_text="Peer that receives the description.")
+ description = TerminalNetplayDescriptionSerializer()
+
+
+class TerminalNetplayMailboxQuerySerializer(serializers.Serializer):
+ room = serializers.RegexField(ROOM_PATTERN, help_text="Room code shown by the game host.")
+ peer = serializers.RegexField(PEER_PATTERN, help_text="Peer whose mailbox to read. The host reads 'host'.")
+
+
+class TerminalNetplayReceivedSignalSerializer(serializers.Serializer):
+ sender = serializers.CharField(help_text="Peer that sent the description.")
+ description = TerminalNetplayDescriptionSerializer()
+
+
+class TerminalNetplayMailboxSerializer(serializers.Serializer):
+ signals = TerminalNetplayReceivedSignalSerializer(many=True, help_text="Descriptions received since the last read.")
+
+
+class TerminalNetplayViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "INTERNAL"
+ authentication_classes = [SessionAuthentication]
+
+ def _check_enabled(self, request: Request) -> None:
+ if not isinstance(request.successful_authenticator, SessionAuthentication):
+ raise PermissionDenied("Sign in to use the terminal.")
+ user = cast(User, request.user)
+ if not feature_enabled_or_false(
+ "posthog-terminal",
+ str(user.distinct_id),
+ groups={"organization": str(self.team.organization_id)},
+ ):
+ raise PermissionDenied("The terminal is not enabled for this account.")
+
+ def _room(self, request: Request, room: str) -> TerminalNetplayRoom:
+ token = request.headers.get(TOKEN_HEADER, "")
+ if re.fullmatch(r"[a-f0-9]{64}", token) is None:
+ raise PermissionDenied("The game token is missing or invalid. Start a new game and try again.")
+ user = cast(User, request.user)
+ owner = hashlib.sha256(f"{user.pk}:{token}".encode()).hexdigest()
+ return TerminalNetplayRoom(self.team_id, room, owner, user.pk)
+
+ @extend_schema(
+ tags=["core"],
+ request=TerminalNetplaySignalSerializer,
+ parameters=[TOKEN_PARAMETER],
+ responses={204: OpenApiResponse(description="Delivered."), 404: OpenApiResponse(description="No such room.")},
+ description="Send a WebRTC session description to another terminal in a Doom room.",
+ )
+ @action(methods=["POST"], detail=False)
+ def signal(self, request: Request, **kwargs: object) -> HttpResponse:
+ self._check_enabled(request)
+ serializer = TerminalNetplaySignalSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ self._room(request, data["room"]).send(data["sender"], data["recipient"], data["description"])
+ return HttpResponse(status=status.HTTP_204_NO_CONTENT)
+
+ @extend_schema(
+ tags=["core"],
+ parameters=[TerminalNetplayMailboxQuerySerializer, TOKEN_PARAMETER],
+ responses={200: TerminalNetplayMailboxSerializer},
+ description="Read and clear a terminal's WebRTC mailbox. Reading the host mailbox keeps the room open.",
+ )
+ @action(methods=["GET"], detail=False)
+ def mailbox(self, request: Request, **kwargs: object) -> Response:
+ self._check_enabled(request)
+ serializer = TerminalNetplayMailboxQuerySerializer(data=request.query_params)
+ serializer.is_valid(raise_exception=True)
+ room = serializer.validated_data["room"]
+ peer = serializer.validated_data["peer"]
+ messages = self._room(request, room).read(peer)
+ return Response({"signals": [json.loads(message) for message in messages]})
diff --git a/posthog/api/test/test_terminal_netplay.py b/posthog/api/test/test_terminal_netplay.py
new file mode 100644
index 000000000000..6b044814366c
--- /dev/null
+++ b/posthog/api/test/test_terminal_netplay.py
@@ -0,0 +1,249 @@
+import hashlib
+from typing import TYPE_CHECKING
+
+import time_machine
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import Organization, PersonalAPIKey, Team, User
+from posthog.models.personal_api_key import hash_key_value
+from posthog.redis import get_client
+from posthog.token_bucket import BucketUnavailable
+
+if TYPE_CHECKING:
+ from rest_framework.response import _MonkeyPatchedResponse
+
+OFFER = {"type": "offer", "sdp": "v=0 offer"}
+ANSWER = {"type": "answer", "sdp": "v=0 answer"}
+
+
+class TestTerminalNetplay(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ get_client().flushdb()
+ self.enabled = self.enterContext(
+ patch("posthog.api.terminal_netplay.feature_enabled_or_false", return_value=True)
+ )
+ self.url = f"/api/projects/{self.team.id}/terminal_netplay"
+
+ def _token(self, peer: str) -> str:
+ return hashlib.sha256(peer.encode()).hexdigest()
+
+ def _signal(
+ self,
+ room: str,
+ sender: str,
+ recipient: str,
+ description: dict[str, str],
+ url: str | None = None,
+ token: str | None = None,
+ ) -> _MonkeyPatchedResponse:
+ return self.client.post(
+ f"{url or self.url}/signal/",
+ {"room": room, "sender": sender, "recipient": recipient, "description": description},
+ format="json",
+ HTTP_X_TERMINAL_NETPLAY_TOKEN=self._token(sender) if token is None else token,
+ )
+
+ def _mailbox(
+ self, room: str, peer: str, url: str | None = None, token: str | None = None
+ ) -> _MonkeyPatchedResponse:
+ return self.client.get(
+ f"{url or self.url}/mailbox/",
+ {"room": room, "peer": peer},
+ HTTP_X_TERMINAL_NETPLAY_TOKEN=self._token(peer) if token is None else token,
+ )
+
+ def test_host_and_client_exchange_descriptions(self) -> None:
+ self.assertEqual(self._mailbox("ROOM42", "host").json(), {"signals": []})
+
+ self.assertEqual(self._signal("ROOM42", "abc", "host", OFFER).status_code, status.HTTP_204_NO_CONTENT)
+ self.assertEqual(self._mailbox("ROOM42", "host").json(), {"signals": [{"sender": "abc", "description": OFFER}]})
+ self.assertEqual(self._mailbox("ROOM42", "host").json(), {"signals": []})
+
+ self.assertEqual(self._signal("ROOM42", "host", "abc", ANSWER).status_code, status.HTTP_204_NO_CONTENT)
+ self.assertEqual(
+ self._mailbox("ROOM42", "abc").json(), {"signals": [{"sender": "host", "description": ANSWER}]}
+ )
+
+ def test_joining_a_closed_room_returns_not_found(self) -> None:
+ response = self._signal("NOROOM", "abc", "host", OFFER)
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.json()["detail"], "No deathmatch room has this code. Check the code and try again.")
+
+ @parameterized.expand([("host",), ("abc",)])
+ def test_only_the_owner_can_read_or_send_as_a_peer(self, peer: str) -> None:
+ self._mailbox("ROOM42", "host")
+ self._signal("ROOM42", "abc", "host", OFFER)
+ self._signal("ROOM42", "host", "abc", ANSWER)
+ recipient, description = ("abc", ANSWER) if peer == "host" else ("host", OFFER)
+
+ self.assertEqual(self._mailbox("ROOM42", peer, token="f" * 64).status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(
+ self._signal("ROOM42", peer, recipient, description, token="f" * 64).status_code,
+ status.HTTP_403_FORBIDDEN,
+ )
+ expected = OFFER if peer == "host" else ANSWER
+ self.assertEqual(self._mailbox("ROOM42", peer).json()["signals"][0]["description"], expected)
+
+ def test_tokens_are_bound_to_the_signed_in_user(self) -> None:
+ self._mailbox("ROOM42", "host")
+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ self.client.force_login(teammate)
+
+ self.assertEqual(self._mailbox("ROOM42", "host").status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(self._signal("ROOM42", "host", "abc", ANSWER).status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(self._signal("ROOM42", "abc", "host", OFFER).status_code, status.HTTP_204_NO_CONTENT)
+
+ @parameterized.expand([("",), ("invalid",), ("a" * 65,)])
+ def test_requires_a_valid_game_token(self, token: str) -> None:
+ self.assertEqual(self._mailbox("ROOM42", "host", token=token).status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(
+ self._signal("ROOM42", "abc", "host", OFFER, token=token).status_code, status.HTTP_403_FORBIDDEN
+ )
+
+ @parameterized.expand(
+ [("abc", "host", ANSWER), ("abc", "other", OFFER), ("host", "abc", OFFER), ("host", "host", ANSWER)]
+ )
+ def test_rejects_invalid_signal_routes(self, sender: str, recipient: str, description: dict[str, str]) -> None:
+ self._mailbox("ROOM42", "host")
+ self.assertEqual(
+ self._signal("ROOM42", sender, recipient, description).status_code, status.HTTP_400_BAD_REQUEST
+ )
+
+ def test_expired_rooms_reject_signals_and_do_not_reuse_mailboxes(self) -> None:
+ self._mailbox("ROOM42", "host")
+ self._signal("ROOM42", "abc", "host", OFFER)
+ self._signal("ROOM42", "host", "abc", ANSWER)
+ get_client().delete(f"terminal_netplay:{self.team.id}:ROOM42")
+
+ self.assertEqual(self._signal("ROOM42", "host", "abc", ANSWER).status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(self._mailbox("ROOM42", "abc").status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(self._mailbox("ROOM42", "host", token="f" * 64).json(), {"signals": []})
+ self.assertEqual(self._mailbox("ROOM42", "abc").status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_host_cannot_answer_an_unregistered_player(self) -> None:
+ self._mailbox("ROOM42", "host")
+ self.assertEqual(self._signal("ROOM42", "host", "unknown", ANSWER).status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_answer_ownership_lasts_as_long_as_the_mailbox(self) -> None:
+ with time_machine.travel(timezone.now(), tick=False) as clock:
+ self._mailbox("ROOM42", "host")
+ self._signal("ROOM42", "abc", "host", OFFER)
+ clock.shift(25)
+ self._mailbox("ROOM42", "host")
+ self._signal("ROOM42", "host", "abc", ANSWER)
+ clock.shift(25)
+ self._mailbox("ROOM42", "host")
+ clock.shift(11)
+
+ self.assertEqual(
+ self._signal("ROOM42", "abc", "host", OFFER, token="f" * 64).status_code,
+ status.HTTP_403_FORBIDDEN,
+ )
+ self.assertEqual(self._mailbox("ROOM42", "abc").json()["signals"][0]["description"], ANSWER)
+
+ def test_rooms_are_scoped_to_the_project(self) -> None:
+ self._mailbox("ROOM42", "host")
+ other = Team.objects.create(organization=self.organization, name="Other project")
+ other_url = f"/api/projects/{other.id}/terminal_netplay"
+
+ self.assertEqual(self._signal("ROOM42", "abc", "host", OFFER, other_url).status_code, 404)
+
+ def test_other_organizations_cannot_use_the_room(self) -> None:
+ self._mailbox("ROOM42", "host")
+ other = Team.objects.create(organization=Organization.objects.create(name="Other"), name="Other")
+
+ response = self._signal("ROOM42", "abc", "host", OFFER, f"/api/projects/{other.id}/terminal_netplay")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_offer_limit_cannot_be_bypassed_with_new_peer_ids_or_tokens(self) -> None:
+ with time_machine.travel(timezone.now(), tick=False) as clock:
+ self._mailbox("ROOM42", "host")
+ self._mailbox("OTHER42", "host")
+ for index in range(4):
+ self.assertEqual(self._signal("ROOM42", f"p{index}", "host", OFFER).status_code, 204)
+
+ response = self._signal("ROOM42", "newpeer", "host", OFFER, token="f" * 64)
+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+ self.assertEqual(response["Retry-After"], "30")
+ self.assertEqual(self._signal("OTHER42", "abc", "host", OFFER).status_code, 204)
+ self.assertEqual(self._signal("ROOM42", "host", "p0", ANSWER).status_code, 204)
+
+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ self.client.force_login(teammate)
+ self.assertEqual(self._signal("ROOM42", "teammate", "host", OFFER).status_code, 204)
+ self.client.force_login(self.user)
+ clock.shift(25)
+ self._mailbox("ROOM42", "host")
+ clock.shift(5)
+ self.assertEqual(self._signal("ROOM42", "retry", "host", OFFER).status_code, 204)
+
+ @parameterized.expand([("room_rate", False), ("mailbox_capacity", True)])
+ def test_flooding_cannot_evict_queued_offers(self, _name: str, allow_refill: bool) -> None:
+ with time_machine.travel(timezone.now(), tick=False) as clock:
+ self._mailbox("ROOM42", "host")
+ for index in range(17):
+ if index % 4 == 0:
+ teammate = User.objects.create_and_join(self.organization, f"player{index}@example.com", "password")
+ self.client.force_login(teammate)
+ response = self._signal("ROOM42", f"p{index}", "host", OFFER)
+ self.assertEqual(response.status_code, 204 if index < 16 else 429)
+ if allow_refill:
+ clock.shift(1)
+
+ self.client.force_login(self.user)
+ signals = self._mailbox("ROOM42", "host").json()["signals"]
+ self.assertEqual([signal["sender"] for signal in signals], [f"p{index}" for index in range(16)])
+ self.client.force_login(teammate)
+ self.assertEqual(self._signal("ROOM42", "retry", "host", OFFER).status_code, 204 if allow_refill else 429)
+
+ def test_signaling_fails_closed_when_the_rate_limiter_is_unavailable(self) -> None:
+ self._mailbox("ROOM42", "host")
+ with patch("posthog.api.terminal_netplay.consume", return_value=BucketUnavailable(error="unavailable")):
+ self.assertEqual(self._signal("ROOM42", "abc", "host", OFFER).status_code, 429)
+ self.assertEqual(self._mailbox("ROOM42", "host").json(), {"signals": []})
+
+ @parameterized.expand(
+ [
+ ("lowercase_room", {"room": "room42"}),
+ ("short_room", {"room": "AB"}),
+ ("uppercase_peer", {"sender": "ABC"}),
+ ("unknown_type", {"description": {"type": "candidate", "sdp": "x"}}),
+ ("large_description", {"description": {"type": "offer", "sdp": "x" * 16385}}),
+ ]
+ )
+ def test_rejects_invalid_signals(self, _name: str, override: dict[str, object]) -> None:
+ self._mailbox("ROOM42", "host")
+ body = {"room": "ROOM42", "sender": "abc", "recipient": "host", "description": OFFER, **override}
+
+ response = self.client.post(f"{self.url}/signal/", body, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_requires_the_terminal_flag(self) -> None:
+ self.enabled.return_value = False
+
+ self.assertEqual(self._mailbox("ROOM42", "host").status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(self._signal("ROOM42", "abc", "host", OFFER).status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_requires_a_session(self) -> None:
+ self.client.logout()
+
+ self.assertEqual(self._mailbox("ROOM42", "host").status_code, status.HTTP_401_UNAUTHORIZED)
+
+ def test_personal_api_keys_cannot_use_signaling(self) -> None:
+ token = "phx_test_terminal_netplay_key"
+ PersonalAPIKey.objects.create(user=self.user, label="Test", secure_value=hash_key_value(token), scopes=["*"])
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ self.assertEqual(self._mailbox("ROOM42", "host").status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(self._signal("ROOM42", "abc", "host", OFFER).status_code, status.HTTP_403_FORBIDDEN)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5ba80fd36800..ef9e2983ed1b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -107721,6 +107721,61 @@ export namespace Schemas {
temperature?: number | null;
}
+ /**
+ * * `offer` - offer
+ * * `answer` - answer
+ */
+ export type TerminalNetplayDescriptionTypeEnum = typeof TerminalNetplayDescriptionTypeEnum[keyof typeof TerminalNetplayDescriptionTypeEnum];
+
+
+ export const TerminalNetplayDescriptionTypeEnum = {
+ Offer: 'offer',
+ Answer: 'answer',
+ } as const;
+
+ export interface TerminalNetplayDescription {
+ /** WebRTC session description type.
+ *
+ * * `offer` - offer
+ * * `answer` - answer */
+ type: TerminalNetplayDescriptionTypeEnum;
+ /**
+ * WebRTC session description with ICE candidates.
+ * @maxLength 16384
+ */
+ sdp: string;
+ }
+
+ export interface TerminalNetplayReceivedSignal {
+ /** Peer that sent the description. */
+ sender: string;
+ description: TerminalNetplayDescription;
+ }
+
+ export interface TerminalNetplayMailbox {
+ /** Descriptions received since the last read. */
+ signals: TerminalNetplayReceivedSignal[];
+ }
+
+ export interface TerminalNetplaySignal {
+ /**
+ * Room code shown by the game host.
+ * @pattern ^[A-Z0-9]{4,12}$
+ */
+ room: string;
+ /**
+ * Peer that sent the description.
+ * @pattern ^[a-z0-9]{1,32}$
+ */
+ sender: string;
+ /**
+ * Peer that receives the description.
+ * @pattern ^[a-z0-9]{1,32}$
+ */
+ recipient: string;
+ description: TerminalNetplayDescription;
+ }
+
export type TestHogRequestOutputConfigOptionsItem = {
/**
* Stable category key.
@@ -126027,6 +126082,21 @@ export namespace Schemas {
Txt: 'txt',
} as const;
+ export type TerminalNetplayMailboxRetrieveParams = {
+ /**
+ * Peer whose mailbox to read. The host reads 'host'.
+ * @minLength 1
+ * @pattern ^[a-z0-9]{1,32}$
+ */
+ peer: string;
+ /**
+ * Room code shown by the game host.
+ * @minLength 1
+ * @pattern ^[A-Z0-9]{4,12}$
+ */
+ room: string;
+ };
+
export type TodayBriefingRetrieveParams = {
/**
* IANA timezone of the person's browser, for example Europe/Prague. The briefing day starts at 8:00 in it. Defaults to the project timezone.