Link the Steam account when a fleet machine reports a sign-in (#360)

A QR sign-in on Nestri's own hardware proves the Steam account, so `POST
/machine/enrolment` from a machine in `FLEET_ORGANISATION_ID` also links
it to the person. Hosts somebody brought never link (a machine vouching
for itself could attach any Steam account to anyone enrolled on it). A
Steam account already linked elsewhere stays there; the report is
recorded either way.

Tests: three new in `enrolment.test.ts` (fleet links and is idempotent,
own host does not link, taken account is left alone). 164 pass.
This commit is contained in:
Wanjohi
2026-10-07 15:43:20 +00:00
committed by GitHub
parent d0b4a6ce76
commit 27dc33f9ab
2 changed files with 112 additions and 7 deletions
+42 -6
View File
@@ -1,6 +1,9 @@
import { Actor } from '@nestri/core/actor';
import { Env } from '@nestri/core/env';
import { ErrorCodes, VisibleError } from '@nestri/core/error';
import { Machine } from '@nestri/core/machine/index';
import { Enrolment } from '@nestri/core/steam/enrolment';
import { Identity } from '@nestri/core/user/identity';
import { Hono } from 'hono';
import { describeRoute } from 'hono-openapi';
import { z } from 'zod';
@@ -27,6 +30,39 @@ import { ErrorResponses, machineOnly, Result, validator } from '../utils';
* ask, and none of them re-ask it.
*/
export namespace EnrolmentApi {
/**
* A sign-in on one of Nestri's own machines is also proof of the Steam
* account, so it links it: the person scanned a QR code on hardware we
* run, the Steam id is the subject of the token Valve issued there, and
* who they are came from the edge. Asking them to sign in to Steam a
* second time, in a browser, would prove nothing new.
*
* **Only the fleet.** On a host somebody brought, the report is that
* person's machine vouching for itself, and a machine can say anything.
* Linking from it would let any host operator attach any Steam account to
* any user enrolled on it.
*
* Never a reason to refuse the report. The sign-in happened and the
* enrolment is recorded either way; a Steam account already linked to
* somebody else stays theirs, and is left for the person to sort out on
* the website.
*/
async function linkIfFleet(machineId: string, userId: string, steamId: string) {
const fleet = Env.get().FLEET_ORGANISATION_ID;
if (!fleet) return;
const machine = await Machine.fromID(machineId);
if (machine?.organisationId !== fleet) return;
try {
await Identity.linkSteam({ userId, steamId });
} catch (err) {
if (err instanceof VisibleError) {
console.warn('a fleet sign-in was not linked', { machineId, userId, reason: err.message });
return;
}
throw err;
}
}
// Picked from the domain schema rather than restated, so the shape a host
// must send and the shape the record has cannot drift apart — including the
// Steam id's format, which is checked here at the boundary and therefore
@@ -61,13 +97,13 @@ export namespace EnrolmentApi {
validator('json', Reported),
async (c) => {
const body = c.req.valid('json');
return c.json({
data: await Enrolment.record({
machineId: Actor.machineID,
userId: body.userId,
steamId: body.steamId
})
const enrolment = await Enrolment.record({
machineId: Actor.machineID,
userId: body.userId,
steamId: body.steamId
});
await linkIfFleet(Actor.machineID, body.userId, body.steamId);
return c.json({ data: enrolment });
}
)
.post(
+70 -1
View File
@@ -4,14 +4,16 @@ import { AccessToken } from '@nestri/core/access-token/index';
import { Fixtures } from '@nestri/core/db/fixtures';
import { testDb } from '@nestri/core/db/test';
import { Identifier } from '@nestri/core/id';
import { Env } from '@nestri/core/env';
import { Machine } from '@nestri/core/machine/index';
import { app } from '../app/index';
import './setup';
import { TEST_FRONTEND_URL } from './setup';
const sql = testDb();
const createdUserIds: string[] = [];
const createdOrgIds: string[] = [];
/**
* A signed-in person, as a personal access token.
@@ -78,6 +80,10 @@ function list(host: { headers: Record<string, string> }) {
}
afterAll(async () => {
if (createdOrgIds.length > 0) {
await sql`delete from machine where organisation_id = any(${createdOrgIds})`;
await sql`delete from organisation where id = any(${createdOrgIds})`;
}
if (createdUserIds.length > 0) {
await sql`delete from "user" where id in ${sql(createdUserIds)}`;
createdUserIds.length = 0;
@@ -386,3 +392,66 @@ describe('The enrolment surface refuses a token', () => {
expect([...accepted].sort()).toEqual(['steamId', 'userId']);
});
});
describe('A sign-in on the fleet links the Steam account', () => {
/** A fleet host the API knows is the fleet, and a person to enrol on it. */
async function fleetHost(label: string) {
const operator = await Fixtures.owner(`${label}-operator`);
createdUserIds.push(operator.userId);
const f = await Fixtures.fleet(operator);
createdOrgIds.push(f.organisationId);
Env.init({
NODE_ENV: 'test',
FRONTEND_URL: TEST_FRONTEND_URL,
FLEET_ORGANISATION_ID: f.organisationId
});
const person = await Fixtures.owner(label);
createdUserIds.push(person.userId);
const [machine] = f.machines;
return {
person,
headers: {
'x-nestri-machine-id': machine!.id,
'x-nestri-machine-secret': machine!.secret,
'content-type': 'application/json'
}
};
}
const linked = (steam: string) =>
sql<{ user_id: string }[]>`
select user_id from linked_account
where provider = 'steam' and provider_account_id = ${steam} and time_deleted is null`;
test('a fleet host reporting a sign-in links that account to that person', async () => {
const host = await fleetHost('fleet-link');
const res = await enrol(host, { userId: host.person.userId, steamId: steamId(9001) });
expect(res.status).toBe(200);
expect((await linked(steamId(9001))).map((r) => r.user_id)).toEqual([host.person.userId]);
// Restated, as a host does after a restart: still one link.
expect((await enrol(host, { userId: host.person.userId, steamId: steamId(9001) })).status).toBe(
200
);
expect(await linked(steamId(9001))).toHaveLength(1);
});
test('a host somebody brought cannot link anything', async () => {
const host = await registeredHost('own-host-link');
const res = await enrol(host, { userId: host.userId, steamId: steamId(9002) });
expect(res.status).toBe(200);
expect(await linked(steamId(9002))).toHaveLength(0);
});
test('an account already linked elsewhere stays there, and the report still lands', async () => {
const host = await fleetHost('fleet-link-taken');
const first = await Fixtures.owner('first-holder');
createdUserIds.push(first.userId);
await sql`insert into linked_account (id, user_id, provider, provider_account_id)
values (${Identifier.ascending('linkedAccount')}, ${first.userId}, 'steam', ${steamId(9003)})`;
const res = await enrol(host, { userId: host.person.userId, steamId: steamId(9003) });
expect(res.status).toBe(200);
expect((await linked(steamId(9003))).map((r) => r.user_id)).toEqual([first.userId]);
});
});