mirror of
https://github.com/nestriness/nestri.git
synced 2026-09-19 17:25:19 +03:00
feat(core): a box is a row, a session is the billing unit
Migration 1 of 0048, and the first of the seven weeks — nothing about a live
feed works without these two tables, so it is not a cleanup during them.
box a VM someone owns: an id that is also its DNS label, an editable
label, an owning user, the machine it sits on, a tier and a state.
Owned by a person and placed on a team's hardware, which are two
different relationships, hence both userId and machineId.
session one run of one box by one linked Steam account, and what costs
money. Separate from box because the ticket changes after bind as
addresses are discovered — the vsock contract calls it "a stream,
not one value" — so it is a column a client polls, not a value it
is handed once.
Box states are neslet's own three and no more. `starting` and `stopping` are
the obvious additions and both are omitted because nothing would ever write
them; a failed box is `stopped` with stopClean false, which is how neslet
models it too.
The generated migration would have failed on live rows in three ways, so it
is hand-written and tested against a database seeded at the old schema:
- machine.team_id becomes notNull, and *every existing row is null* because
the old registration path passed null. Personal teams are backfilled for
machine owners first, reusing a team they already own rather than minting
a second, with the owner membership row repaired where missing.
- game_download.host_id becomes a foreign key. It held free-form strings,
so unattributable rows are deleted before the cast — the only destructive
statement here, and a considered loss: it is a progress report neslet
re-derives from disk.
- Team.createPersonal was written and documented in packages/core/CLAUDE.md
as part of the login flow and never actually called, so no user has a
team. ensurePersonal is idempotent and now runs on every login, which is
what backfills accounts the migration does not reach.
Verified on a seeded legacy database: three null-team machines backfilled, an
existing team reused rather than duplicated, a blank display name handled, and
both unattributable download rows dropped while the attributable one survived.
Also fixes two things this work ran into rather than caused:
- Database.client() built a new postgres pool on every call, and use()
called it twice per invocation — pools of ten connections held for a 30s
idle timeout. Invisible in a Worker where requests are short; the suite
crossed 100 connections and Postgres said "sorry, too many clients
already" in whichever file ran last, which reads as a flaky test rather
than a leak. Now one pool per connection string.
- download.test.ts asserted against `hst_…` host ids, which is exactly the
unattributable row the new foreign key exists to refuse.
There is no "no team" any more: PATCH /machine/:id took teamId null to mean
"mine alone" and now requires a team, because the personal team is the one to
name. Its test is updated to the new contract rather than deleted.
113 → 128 tests, 0 fail.
This commit is contained in:
@@ -4,6 +4,7 @@ import { Examples } from '@nestri/core/examples';
|
||||
import { Identifier } from '@nestri/core/id';
|
||||
import { Machine } from '@nestri/core/machine/index';
|
||||
import { Member } from '@nestri/core/team/member';
|
||||
import { Team } from '@nestri/core/team/index';
|
||||
import { Hono } from 'hono';
|
||||
import { describeRoute } from 'hono-openapi';
|
||||
import { z } from 'zod';
|
||||
@@ -56,7 +57,8 @@ export namespace MachineApi {
|
||||
example: Examples.Machine.label
|
||||
}),
|
||||
teamId: z.string().optional().meta({
|
||||
description: 'Register the box into a team rather than to the user alone'
|
||||
description:
|
||||
'Team to own this hardware. Defaults to the caller’s personal team, which always exists'
|
||||
})
|
||||
})
|
||||
),
|
||||
@@ -74,10 +76,37 @@ export namespace MachineApi {
|
||||
);
|
||||
}
|
||||
|
||||
// `machine.teamId` is notNull since 0048, so a team has to be
|
||||
// resolved rather than defaulted to null. The order is: what the
|
||||
// caller asked for, then the team they are acting inside, then
|
||||
// their personal team — which `ensurePersonal` makes if this is a
|
||||
// user who predates 0048 and has none.
|
||||
const owningTeam =
|
||||
teamId ??
|
||||
(actor.type === 'member'
|
||||
? actor.properties.teamID
|
||||
: await Team.ensurePersonal({ displayName: Actor.userID }));
|
||||
|
||||
// A caller naming a team must belong to it. Without this, `teamId`
|
||||
// would be a way to park hardware in somebody else's team.
|
||||
if (teamId) {
|
||||
const membership = await Member.findByTeamAndUser({
|
||||
teamId,
|
||||
userId: Actor.userID
|
||||
});
|
||||
if (!membership) {
|
||||
throw new VisibleError(
|
||||
'forbidden',
|
||||
ErrorCodes.Permission.FORBIDDEN,
|
||||
'You are not a member of that team'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const registered = await Machine.register({
|
||||
id: Identifier.ascending('machine'),
|
||||
ownerUserId: Actor.userID,
|
||||
teamId: teamId ?? (actor.type === 'member' ? actor.properties.teamID : null),
|
||||
teamId: owningTeam,
|
||||
label
|
||||
});
|
||||
|
||||
@@ -89,9 +118,9 @@ export namespace MachineApi {
|
||||
notPublic,
|
||||
describeRoute({
|
||||
tags: ['Machine'],
|
||||
summary: 'Move a box into a team, or out of one',
|
||||
summary: 'Move a box to another team',
|
||||
description:
|
||||
'Scope a machine you own to a team you belong to, or pass teamId: null to make it yours alone again. This is not ownership transfer — the owner does not change.',
|
||||
'Move a machine you own to a team you belong to. Hardware always belongs to exactly one team since 0048, so there is no way to unscope — name your personal team instead. This is not ownership transfer: the owner does not change.',
|
||||
responses: {
|
||||
200: {
|
||||
content: { 'application/json': { schema: Result(Machine.Info) } },
|
||||
@@ -105,8 +134,9 @@ export namespace MachineApi {
|
||||
validator(
|
||||
'json',
|
||||
z.object({
|
||||
teamId: z.string().nullable().meta({
|
||||
description: 'Team to scope the box to, or null to scope it to you alone'
|
||||
teamId: z.string().meta({
|
||||
description:
|
||||
'Team to move the box to. There is no “no team” — to unscope, name your personal team'
|
||||
})
|
||||
})
|
||||
),
|
||||
@@ -125,18 +155,16 @@ export namespace MachineApi {
|
||||
// Verified before the write. `setTeam` scopes to the owner but
|
||||
// knows nothing about who belongs to the target team, so this is
|
||||
// the only place that check exists.
|
||||
if (teamId) {
|
||||
const membership = await Member.findByTeamAndUser({
|
||||
teamId,
|
||||
userId: Actor.userID
|
||||
});
|
||||
if (!membership) {
|
||||
throw new VisibleError(
|
||||
'forbidden',
|
||||
ErrorCodes.Permission.FORBIDDEN,
|
||||
'You are not a member of that team'
|
||||
);
|
||||
}
|
||||
const membership = await Member.findByTeamAndUser({
|
||||
teamId,
|
||||
userId: Actor.userID
|
||||
});
|
||||
if (!membership) {
|
||||
throw new VisibleError(
|
||||
'forbidden',
|
||||
ErrorCodes.Permission.FORBIDDEN,
|
||||
'You are not a member of that team'
|
||||
);
|
||||
}
|
||||
|
||||
const machine = await Machine.setTeam({
|
||||
|
||||
@@ -378,16 +378,18 @@ describe('Box access', () => {
|
||||
const res = await app.request('/machine/mch_whatever', {
|
||||
method: 'PATCH',
|
||||
headers: { ...adminHeaders(), 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ teamId: null })
|
||||
body: JSON.stringify({ teamId: 'tem_whatever' })
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
const body = (await res.json()) as any;
|
||||
expect(body.message).toContain('user session');
|
||||
});
|
||||
|
||||
test('teamId is required on the body, and may be null', async () => {
|
||||
// Null is "make it mine alone" — a different thing from omitting the
|
||||
// field, which would leave the scope ambiguous.
|
||||
test('teamId is required on the body, and null is no longer a value', async () => {
|
||||
// Null used to mean "make it mine alone". Since 0048 made
|
||||
// `machine.teamId` notNull there is no such state — hardware belongs to
|
||||
// exactly one team and the personal team is the one to name — so null is
|
||||
// now a validation error rather than a meaning.
|
||||
const missing = await app.request('/machine/mch_whatever', {
|
||||
method: 'PATCH',
|
||||
headers: { ...adminHeaders(), 'content-type': 'application/json' },
|
||||
@@ -400,8 +402,15 @@ describe('Box access', () => {
|
||||
headers: { ...adminHeaders(), 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ teamId: null })
|
||||
});
|
||||
expect(explicitNull.status).toBe(400);
|
||||
|
||||
const named = await app.request('/machine/mch_whatever', {
|
||||
method: 'PATCH',
|
||||
headers: { ...adminHeaders(), 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ teamId: 'tem_whatever' })
|
||||
});
|
||||
// Past validation, refused at the handler for being admin.
|
||||
expect(explicitNull.status).toBe(403);
|
||||
expect(named.status).toBe(403);
|
||||
});
|
||||
|
||||
test('entitlement requires machine credentials, not a user session', async () => {
|
||||
|
||||
Reference in New Issue
Block a user