Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/229.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add the `/pair` page, where a signed-in person approves a hardware listener by the code it shows, and a Devices list with Remove in Menu > Settings
2 changes: 2 additions & 0 deletions web-app/e2e/listen-fake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ export async function serveListening(page: Page, options: ListenOptions = {}): P
await page.route('**/api/v1/workspace/team', route => route.request().method() === 'GET'
? route.fulfill({ json: { linked: options.teamLinked ?? true } })
: route.fallback());
// Settings > Devices lists the person's hardware listeners; the listening specs have none.
await page.route('**/api/v1/devices', route => route.fulfill({ json: { items: [] } }));
await page.route(/\/api\/v1\/(onboarding|workspace\/name)$/, route => {
const state = options.onboarding;
if (state === undefined) return route.fallback();
Expand Down
137 changes: 137 additions & 0 deletions web-app/e2e/pair.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { expect, type Page, test } from '@playwright/test';
import { type ListenOptions, serveListening } from './listen-fake.ts';
import { openMenu } from './menu.ts';

test.use({ locale: 'en-US', timezoneId: 'UTC' });

const ACCESS = {
workspace_id: '00000000-0000-4000-8000-000000000001',
principal: { id: '00000000-0000-4000-8000-000000000002', kind: 'human', display_name: 'Ada Lovelace' },
role: 'member',
scopes: ['context:read', 'context:write', 'capture:ingest'],
meetings: { kind: 'accessible' },
permission_revision: 1,
};
const CODE = '12345678';
const CAPABILITIES = { mic: true, screen: false, light: 'mono', speaker: false };
const CSRF = 'csrf-pair';

const device = (n: number, status: string, last_used_at: string | null) => ({
id: `00000000-0000-4000-8000-00000000000${n}`,
name: n === 1 ? 'Kitchen Pi' : 'Desk lamp',
capabilities: CAPABILITIES,
status,
approved_by: ACCESS.principal,
created_at: '2026-11-23T09:00:00.000Z',
approved_at: '2026-11-23T09:01:00.000Z',
last_used_at,
revoked_at: null,
});

/**
* Routed stand-in for `DevicesApi` (stand-in until the S1 server merges): one pending device under
* CODE, and the server's lockout, where the sixth wrong code in a row answers 403.
*/
async function devicesApi(page: Page) {
const state = { wrong: 0, answers: [] as unknown[], devices: [device(1, 'approved', '2026-11-23T10:15:00.000Z'), device(2, 'approved', null)] };
await page.context().addCookies([{ name: 'sanctum_csrf', value: CSRF, url: test.info().project.use.baseURL! }]);
const refuse = (tag: string, status: number) => ({ status, json: { _tag: tag, code: tag === 'NotFound' ? 'not_found' : 'forbidden', message: tag, retryable: false } });
const lookUp = (code: string) => {
if (code.replace('-', '') === CODE) return null;
state.wrong += 1;
return state.wrong > 5 ? refuse('Forbidden', 403) : refuse('NotFound', 404);
};
await page.route('**/api/v1/device/pending?*', route => {
const refusal = lookUp(new URL(route.request().url()).searchParams.get('user_code')!);
return route.fulfill(refusal ?? { json: { name: 'Kitchen Pi', capabilities: CAPABILITIES, expires_at: '2026-11-23T10:10:00.000Z' } });
});
await page.route('**/api/v1/device/approve', route => {
expect(route.request().headers()['x-csrf-token']).toBe(CSRF);
const body = route.request().postDataJSON();
state.answers.push(body);
return route.fulfill(lookUp(body.user_code) ?? { json: device(1, body.approve ? 'approved' : 'denied', null) });
});
await page.route('**/api/v1/devices**', route => {
if (route.request().method() === 'GET') return route.fulfill({ json: { items: state.devices } });
const target = state.devices.find(d => route.request().url().endsWith(d.id))!;
Object.assign(target, { status: 'revoked', revoked_at: '2026-11-23T10:20:00.000Z' });
return route.fulfill({ status: 204 });
});
return state;
}

async function signedIn(page: Page, code = '') {
await serveListening(page, { configured: true, access: ACCESS });
const api = await devicesApi(page);
await page.goto(`/pair${code}`);
return api;
}

test('a signed-out visitor signs in and comes back with the code kept', async ({ page }) => {
const options: ListenOptions = { configured: true, access: null };
await serveListening(page, options);
await devicesApi(page);
await page.route('**/auth/login?*', route => {
options.access = ACCESS;
return route.fulfill({ status: 302, headers: { location: new URL(route.request().url()).searchParams.get('return_to')! } });
});
await page.goto(`/pair?code=${CODE}`);
await page.getByRole('link', { name: 'Sign in to pair' }).click();
await expect(page).toHaveURL(`/pair?code=${CODE}`);
await expect(page.getByLabel('Code on the device')).toHaveValue('1234-5678');
});

test('shows the device before approval and approves it', async ({ page }) => {
const api = await signedIn(page, `?code=${CODE}`);
await page.getByRole('button', { name: 'Continue' }).click();
await expect(page.getByText('Kitchen Pi')).toBeVisible();
await expect(page.getByRole('list', { name: 'What it has' })).toHaveText('MicrophoneLight');
await expect(page.getByText('It records the room while its light is steady or its screen shows listening.')).toBeVisible();
await page.getByRole('button', { name: 'Approve' }).click();
await expect(page.getByRole('heading', { name: 'Paired' })).toBeVisible();
expect(api.answers).toEqual([{ user_code: CODE, approve: true }]);
});

test('deny leaves the device not paired', async ({ page }) => {
const api = await signedIn(page);
await page.getByLabel('Code on the device').fill('1234 5678');
await page.getByRole('button', { name: 'Continue' }).click();
await page.getByRole('button', { name: 'Deny' }).click();
await expect(page.getByRole('heading', { name: 'Not paired' })).toBeVisible();
expect(api.answers).toEqual([{ user_code: CODE, approve: false }]);
});

test('a wrong code shows one inline error, and the lockout shows the lock message', async ({ page }) => {
await signedIn(page);
const input = page.getByLabel('Code on the device');
for (let attempt = 1; attempt <= 5; attempt++) {
await input.fill(`0000-000${attempt}`);
await page.getByRole('button', { name: 'Continue' }).click();
await expect(page.getByRole('alert')).toHaveText('No device is waiting for this code. Check the code on the device.');
}
await input.fill('0000-0009');
await page.getByRole('button', { name: 'Continue' }).click();
await expect(page.getByRole('alert')).toHaveText('Too many wrong codes. Wait 10 minutes, then try again.');
});

test('fits a phone with no horizontal scroll', async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await signedIn(page, `?code=${CODE}`);
await page.getByRole('button', { name: 'Continue' }).click();
await expect(page.getByRole('button', { name: 'Approve' })).toBeVisible();
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
});

test('Settings lists each device, and Remove asks once and revokes it', async ({ page }) => {
await serveListening(page, { configured: true, access: ACCESS });
await devicesApi(page);
await page.goto('/');
const devices = (await openMenu(page, 'Settings')).getByRole('region', { name: 'Devices' });
const kitchen = devices.locator('.listen-settings > div').filter({ hasText: 'Kitchen Pi' });
await expect(kitchen).toContainText(/approved · last used Nov 23, 2026/);
await expect(devices.locator('.listen-settings > div').filter({ hasText: 'Desk lamp' })).toContainText('approved · never used');
page.once('dialog', confirm => confirm.accept());
await kitchen.getByRole('button', { name: 'Remove' }).click();
await expect(kitchen).toContainText('revoked');
await expect(kitchen.getByRole('button', { name: 'Remove' })).toHaveCount(0);
});
58 changes: 58 additions & 0 deletions web-app/src/lib/devices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/** Browser client of `DevicesApi`, derived from the shared contract so paths and schemas cannot drift. */
import { FetchHttpClient, HttpApi, HttpApiClient, HttpClient, HttpClientRequest } from '@effect/platform';
import { type Device, type DeviceCapabilities, type DeviceId, DevicesApi, Forbidden, NotFound, Unauthenticated, Unavailable, type UtcTimestamp } from '@sanctum/contracts';
import { Effect } from 'effect';
import { csrfToken } from './session.ts';

/** The devices group with the API-wide error envelope `SanctumApi` serves. */
class PairApi extends HttpApi.make('sanctum').add(DevicesApi).addError(Unauthenticated).addError(Forbidden).addError(NotFound).addError(Unavailable) {}

/** Why a call gave no answer: `locked` is the 403 after too many wrong codes (the server counts them, not the page). */
export type Refusal = 'signed_out' | 'not_found' | 'locked' | 'failed';

const REFUSALS: Partial<Record<string, Refusal>> = { Unauthenticated: 'signed_out', NotFound: 'not_found', Forbidden: 'locked' };

/** A device waiting for approval, as `GET /device/pending` describes it. */
export interface PendingDevice {
readonly name: string;
readonly capabilities: DeviceCapabilities;
readonly expires_at: UtcTimestamp;
}

export interface DevicesClient {
pending(userCode: string): Promise<PendingDevice | Refusal>;
approve(userCode: string, approve: boolean): Promise<Device | Refusal>;
list(): Promise<{ readonly items: ReadonlyArray<Device> } | Refusal>;
revoke(deviceId: DeviceId): Promise<void | Refusal>;
}

// Every failure, network and decode included, carries a `_tag`; it settles to a refusal the page can name.
const settle = <A, E extends { readonly _tag: string }>(effect: Effect.Effect<A, E>): Promise<A | Refusal> =>
Effect.runPromise(effect.pipe(Effect.catchAll(error => Effect.succeed(REFUSALS[error._tag] ?? 'failed'))));

/** Same-origin by default: the session cookie authenticates every call, and mutations carry the CSRF header. */
export function makeDevicesClient(baseUrl = globalThis.location?.origin ?? ''): DevicesClient {
const transformClient = HttpClient.mapRequest(request => {
const token = csrfToken();
return token === undefined ? request : HttpClientRequest.setHeader(request, 'x-csrf-token', decodeURIComponent(token));
});
const api = Effect.runSync(HttpApiClient.make(PairApi, { baseUrl, transformClient }).pipe(Effect.provide(FetchHttpClient.layer))).devices;
return {
pending: user_code => settle(api.pendingDevice({ urlParams: { user_code } })),
approve: (user_code, approve) => settle(api.approveDevice({ payload: { user_code, approve } })),
list: () => settle(api.listDevices()),
revoke: device_id => settle(api.revokeDevice({ path: { device_id } })),
};
}

/** The 8 digits of a pairing code typed with any hyphens or spaces, else null. */
export const codeDigits = (input: string): string | null => {
const digits = input.replace(/[\s-]/g, '');
return /^\d{8}$/.test(digits) ? digits : null;
};

/** Typed input as the device shows its code: up to 8 digits, a hyphen after the fourth (`1234-5678`). */
export const formatCode = (input: string): string => {
const digits = input.replace(/\D/g, '').slice(0, 8);
return digits.length > 4 ? `${digits.slice(0, 4)}-${digits.slice(4)}` : digits;
};
3 changes: 3 additions & 0 deletions web-app/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import './styles.css';
const AccountPage = lazy(() => import('./pages/auth/index.tsx').then(module => ({ default: module.AccountPage })));
const ConsentPage = lazy(() => import('./pages/auth/index.tsx').then(module => ({ default: module.ConsentPage })));
const InvitePage = lazy(() => import('./pages/auth/index.tsx').then(module => ({ default: module.InvitePage })));
const PairPage = lazy(() => import('./pages/pair/index.tsx').then(module => ({ default: module.PairPage })));

const container = document.getElementById('root');
if (!container) throw new Error('Missing #root element');
Expand All @@ -22,6 +23,8 @@ createRoot(container).render(
<ConsentPage />
) : invitation !== undefined ? (
<InvitePage id={invitation} />
) : path === '/pair' ? (
<PairPage />
) : (
<ListenPage />
)}
Expand Down
65 changes: 65 additions & 0 deletions web-app/src/pages/listen/DevicesSection.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Settings > Devices: the hardware listeners this person approved (an admin sees the workspace's),
* with their last use, and Remove, which revokes the device's credential.
*/
import type { Device } from '@sanctum/contracts';
import { useCallback, useEffect, useState } from 'react';
import { makeDevicesClient, type Refusal } from '../../lib/devices.ts';

const devices = makeDevicesClient();
const when = new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' });

function DeviceRow({ device, onRemove }: { device: Device; onRemove: (device: Device) => void }) {
return (
<div>
<dt>{device.name}</dt>
<dd>
<span className="tabular-nums">
{device.status} · {device.last_used_at === null ? 'never used' : `last used ${when.format(new Date(device.last_used_at))}`}
</span>
{device.status === 'approved' && (
<span className="listen-signin-actions"><button type="button" data-danger onClick={() => onRemove(device)}>Remove</button></span>
)}
</dd>
</div>
);
}

function DeviceList({ list, onRemove }: { list: ReadonlyArray<Device>; onRemove: (device: Device) => void }) {
return (
<dl className="listen-panel listen-settings">
{list.length === 0 && (
<div>
<dt>None yet</dt>
<dd>
<span>Type the code a device shows</span>
<span className="listen-signin-actions"><a href="/pair" data-primary>Pair a device</a></span>
</dd>
</div>
)}
{list.map(device => <DeviceRow key={device.id} device={device} onRemove={onRemove} />)}
</dl>
);
}

export function DevicesSection() {
const [list, setList] = useState<ReadonlyArray<Device> | Refusal | null>(null);
const [failure, setFailure] = useState<string | null>(null);
const refresh = useCallback(() => devices.list().then(answer => setList(typeof answer === 'string' ? answer : answer.items)), []);
useEffect(() => void refresh(), [refresh]);

const remove = (device: Device) => {
if (!window.confirm(`Remove ${device.name}? It stops recording and must be paired again.`)) return;
setFailure(null);
void devices.revoke(device.id).then(answer => (answer === undefined ? refresh() : setFailure('The device was not removed. Try again.')));
};

if (list === null) return <p>Loading…</p>;
if (typeof list === 'string') return <p role="alert" className="listen-local-gap">Devices could not be read.</p>;
return (
<>
<DeviceList list={list} onRemove={remove} />
{failure && <p role="alert" className="listen-local-gap">{failure}</p>}
</>
);
}
11 changes: 10 additions & 1 deletion web-app/src/pages/listen/SettingsSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const TeamWidgets = lazy(() => import('./WorkosTeam.tsx').then(module => ({ defa
const SetUpTeam = lazy(() => import('./WorkosTeam.tsx').then(module => ({ default: module.SetUpTeam })));
const TeamPanel = lazy(() => import('../auth/team.tsx').then(module => ({ default: module.TeamPanel })));
const ProfilePanel = lazy(() => import('../auth/team.tsx').then(module => ({ default: module.ProfilePanel })));
const DevicesSection = lazy(() => import('./DevicesSection.tsx').then(module => ({ default: module.DevicesSection })));

const MICROPHONE: Record<PermissionState, string> = {
unknown: 'Not requested yet',
Expand Down Expand Up @@ -254,7 +255,14 @@ function deviceRows(permission: PermissionState, engine: CaptureView, fullscreen
];
}

/** Settings section in four groups: Account, Device, Data and Welcome. Real device and session facts, and the unselected policies stated as unselected. */
/** The hardware listeners paired to this person; they need a session to list. */
const devicesGroup = (signIn: SignInState) => signIn.status === 'signed_in' && (
<Group title="Devices">
<Suspense fallback={<p>Loading…</p>}><DevicesSection /></Suspense>
</Group>
);

/** Settings section in five groups: Account, Device, Devices (signed in), Data and Welcome. Real device and session facts, and the unselected policies stated as unselected. */
export function SettingsSection({ permission, engine, client, signIn, notice, onSignInChange, onWelcome, fullscreen }: SettingsProps) {
return (
<>
Expand All @@ -265,6 +273,7 @@ export function SettingsSection({ permission, engine, client, signIn, notice, on
<Group title="Device">
<Rows rows={deviceRows(permission, engine, fullscreen)} />
</Group>
{devicesGroup(signIn)}
<Group title="Data">
<Rows rows={[['Retention', 'Not selected: nothing is deleted automatically']]} />
<LocalRecordings engine={engine} />
Expand Down
Loading