Authenticate and authorize every route: org layer + Supabase JWKS
Until now every HTTP route was unauthenticated. A probe against the
running server returned a farm's `edgeProxyToken` and a printer's
`accessCode` to an anonymous caller, and that pair is enough to connect
as a farm's gateway and drive its printers. The previous commit stopped
the credentials appearing in responses; this one makes the routes ask
who is calling.
Authentication. Access tokens are verified against the Supabase
project's published JWKS via `createSupabaseJwtVerifier` from
`@continuum/ts-core`: RS256, public key only, no secret in this
process. It replaces the HS256 `@elysiajs/jwt` path, where
`SUPABASE_JWT_SECRET` was simultaneously the verification key and a
key that could mint tokens, present in the environment of every
instance. `src/auth/verifier.ts` builds it at module load so a
misconfigured deployment fails at boot rather than on first login.
The edge-gateway token stays symmetric and that is not an
inconsistency: this service is both its issuer and its only verifier,
so there is no second party to keep a secret from. It now carries an
`exp`, which it did not, despite the response saying
`expiresInSeconds: 3600`.
Tenancy. An org layer above farms - `organisations`,
`org_members(org_id, user_id, role)`, `farms.org_id` - so a farm can
have more than one operator without sharing an account. `farms.owner_id`
is gone. Authorization is one rule applied everywhere: resolve the
thing being acted on back to an organisation and check the caller's
role there, user -> org -> farm -> printer, with nothing in between
carrying permissions of its own. The ladder is
`viewer` < `operator` < `owner`; printer commands and job submission
need `operator`, because they move physical machines, and that is the
one boundary here that is not about data.
A non-member gets 404, not 403: a 403 would confirm that a given farm
or printer id exists and belongs to someone, which is an enumeration
oracle over the whole system. 403 is kept for a member who may see the
record but not do this to it.
List endpoints scope in the `where` clause, not after the query - a
filter applied to the result is one `return` away from being skipped.
They are also bounded now (`limit`/`offset`, default 50, max 200
refused rather than clamped).
`ownerId` and `submittedBy` no longer come from request bodies. Nor do
the printer telemetry columns: `POST /printers` is narrowed to the
columns a client owns, because a client that could POST
`status: "idle"` could make the scheduler send work to a printer that
is mid-print.
Also fills the CRUD gaps that made the API unusable - PATCH and DELETE
for farms, printers, jobs and orgs, and membership management - plus
one error shape for the whole API via `toErrorResponse`, so an
authorization failure is a throw that leaves the handler rather than a
status somebody has to remember to set.
Guards on the two changes that cannot be undone through the API:
removing or demoting an organisation's last owner, and deleting an
organisation while farms are still attached (it would cascade to every
printer, print job and stored frame).
Migration 0001 is hand-edited after generation. drizzle-kit emitted
`ADD COLUMN org_id uuid NOT NULL`, which cannot apply to a populated
table, and dropped `owner_id` without moving what it encodes anywhere.
It now adds the column nullable, creates one organisation per distinct
legacy owner with that user as its `owner` member, points each farm at
it, and only then tightens the column and drops `owner_id`. Verified
both ways: from empty via `drizzle-kit migrate`, and against a seeded
database where two farms shared an owner and a third did not.
Testing. `scripts/dev-auth.ts` is a local RS256 issuer publishing a
JWKS at the path the backend fetches, so the real verification path is
testable without a Supabase project. The alternative was a test-only
bypass in the backend - an env var making it trust an unsigned token -
which would be a permanent hole one misconfiguration from production,
and would mean the code under test is not the code that ships.
- `tests/authz.test.ts` (19 tests): the role ladder written out in full
rather than derived the same way the implementation derives it, and
the real JWKS path - a token signed by a key outside the JWKS, an
expired token and a token with `aud: "anon"` (Supabase's own anon key
is a valid project JWT) are all rejected, with the same message, so
probing cannot tell which part of a forged token to fix next.
- `scripts/e2e-authz.sh` (68 assertions, real Postgres, real routes):
four users across two organisations; anonymous 401s, cross-org 404s,
viewer-cannot-command, operator-cannot-rotate, a spoofed
`submittedBy` in the body ignored, no credential in any read, and the
rotated token still minting an edge JWT.
- `scripts/e2e-edge.sh` updated for the org layer and now authenticates
as a seeded `operator` - the weakest role that should work, so the
run would fail if the command boundary were not where it claims to
be. Re-verified against both live printers: telemetry from `h2c` and
`p1p` persisted, and an authenticated `set_fan_speed` went
HTTP -> WebSocket -> MQTT -> P1P and back `ok:true`, fan returned
to 0.
Two bugs found in the test scripts while writing this, both the same
shape as the earlier `pkill -f` incident: `kill "${PID:-0}"` with an
unset PID signals the whole process group, including the harness, and
`uuidgen` is not installed in this sandbox.
This commit is contained in:
+54
-35
@@ -1,61 +1,80 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import jwt from "@elysiajs/jwt";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { UnauthorizedError } from "@continuum/ts-core";
|
||||
import { db } from "../db";
|
||||
import { farms } from "../db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { listMemberships, requireUser } from "../auth";
|
||||
|
||||
const EDGE_TOKEN_TTL_SECONDS = 3600;
|
||||
|
||||
/**
|
||||
* Verifies Supabase-issued JWTs (HS256, shared secret) and issues short-lived
|
||||
* edge-gateway tokens scoped to a single farm for the /ws/edge/v1 handshake.
|
||||
* Two different kinds of authentication meet here, and they are not the same
|
||||
* mechanism:
|
||||
*
|
||||
* - **Users** present a Supabase-issued access token, verified against the
|
||||
* project's JWKS (RS256, public key, no secret in this process). That is
|
||||
* `requireUser` and it guards everything user-facing.
|
||||
* - **Edge gateways** present their farm's `edgeProxyToken` - a credential
|
||||
* provisioned onto a machine, not held by a person - and trade it for a
|
||||
* short-lived edge JWT that `/ws/edge/v1` accepts. That one *is* symmetric:
|
||||
* this service is both its issuer and its only verifier, so there is no
|
||||
* second party to keep a secret from.
|
||||
*
|
||||
* `POST /edge-token` is therefore deliberately not behind `requireUser`:
|
||||
* a gateway has no user account to log in as. Its `edgeProxyToken` is the
|
||||
* credential, and it is only ever handed out by
|
||||
* `POST /farms/:id/edge-proxy-token`, which is behind `requireUser` and
|
||||
* requires the `owner` role.
|
||||
*/
|
||||
export const authRoutes = new Elysia({ prefix: "/auth" })
|
||||
.use(
|
||||
jwt({
|
||||
name: "supabaseJwt",
|
||||
secret: process.env.SUPABASE_JWT_SECRET ?? "dev-secret-change-me",
|
||||
}),
|
||||
)
|
||||
.use(
|
||||
jwt({
|
||||
name: "edgeJwt",
|
||||
secret: process.env.EDGE_JWT_SECRET ?? "dev-edge-secret-change-me",
|
||||
}),
|
||||
)
|
||||
.post(
|
||||
"/session",
|
||||
async ({ supabaseJwt, headers, set }) => {
|
||||
const authHeader = headers.authorization;
|
||||
const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : undefined;
|
||||
if (!token) {
|
||||
set.status = 401;
|
||||
return { error: { code: "UNAUTHORIZED", message: "Missing bearer token" } };
|
||||
}
|
||||
|
||||
const payload = await supabaseJwt.verify(token);
|
||||
if (!payload) {
|
||||
set.status = 401;
|
||||
return { error: { code: "UNAUTHORIZED", message: "Invalid or expired token" } };
|
||||
}
|
||||
|
||||
return { userId: payload.sub, email: payload.email, role: payload.role };
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/edge-token",
|
||||
async ({ edgeJwt, body, set }) => {
|
||||
const farm = await db.query.farms.findFirst({ where: eq(farms.id, body.farmId) });
|
||||
async ({ edgeJwt, body }) => {
|
||||
const farm = await db.query.farms.findFirst({
|
||||
columns: { id: true, edgeProxyToken: true },
|
||||
where: eq(farms.id, body.farmId),
|
||||
});
|
||||
// One message for both "no such farm" and "wrong token": a gateway
|
||||
// being reprovisioned cannot tell which half it got wrong, but neither
|
||||
// can someone walking farm ids.
|
||||
if (!farm || farm.edgeProxyToken !== body.edgeProxyToken) {
|
||||
set.status = 401;
|
||||
return { error: { code: "UNAUTHORIZED", message: "Unknown farm or bad proxy token" } };
|
||||
throw new UnauthorizedError("Unknown farm or bad proxy token");
|
||||
}
|
||||
|
||||
const token = await edgeJwt.sign({ farmId: farm.id, scope: "edge" });
|
||||
return { token, expiresInSeconds: 3600 };
|
||||
const token = await edgeJwt.sign({
|
||||
farmId: farm.id,
|
||||
scope: "edge",
|
||||
exp: Math.floor(Date.now() / 1000) + EDGE_TOKEN_TTL_SECONDS,
|
||||
});
|
||||
return { token, expiresInSeconds: EDGE_TOKEN_TTL_SECONDS };
|
||||
},
|
||||
{
|
||||
body: t.Object({
|
||||
farmId: t.String({ format: "uuid" }),
|
||||
edgeProxyToken: t.String(),
|
||||
edgeProxyToken: t.String({ minLength: 1 }),
|
||||
}),
|
||||
detail: { tags: ["auth"], summary: "Trade a farm's proxy token for an edge JWT" },
|
||||
},
|
||||
)
|
||||
.use(requireUser)
|
||||
/**
|
||||
* Who the caller is and what they can reach. A client calls this once after
|
||||
* sign-in: the memberships it returns are what every other endpoint
|
||||
* authorizes against, so a UI can decide what to even offer without
|
||||
* probing endpoints for 403s.
|
||||
*/
|
||||
.get(
|
||||
"/session",
|
||||
async ({ user }) => ({
|
||||
user,
|
||||
memberships: await listMemberships(user.id),
|
||||
}),
|
||||
{ detail: { tags: ["auth"], summary: "The caller's identity and organisation roles" } },
|
||||
);
|
||||
|
||||
+130
-46
@@ -1,38 +1,79 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { NotFoundError } from "@continuum/ts-core";
|
||||
import { db } from "../db";
|
||||
import { farms } from "../db/schema";
|
||||
import { farmProjection } from "../db/projections";
|
||||
import { requireFarm, requireOrg, requireUser, visibleFarms } from "../auth";
|
||||
import { PaginationQuery, paginate } from "./pagination";
|
||||
|
||||
const IdParams = t.Object({ id: t.String({ format: "uuid" }) });
|
||||
|
||||
export const farmRoutes = new Elysia({ prefix: "/farms" })
|
||||
// A projection rather than `select *`: the table holds
|
||||
// `edgeProxyToken`, which trades for an edge JWT and so must never leave
|
||||
// the server in a list or a fetch. See src/db/projections.ts.
|
||||
.get("/", async () => db.query.farms.findMany({ columns: farmProjection.columns }))
|
||||
.get("/:id", async ({ params, set }) => {
|
||||
const farm = await db.query.farms.findFirst({
|
||||
columns: farmProjection.columns,
|
||||
where: eq(farms.id, params.id),
|
||||
});
|
||||
if (!farm) {
|
||||
set.status = 404;
|
||||
return { error: { code: "NOT_FOUND", message: `Farm ${params.id} not found` } };
|
||||
}
|
||||
return farm;
|
||||
})
|
||||
.use(requireUser)
|
||||
/**
|
||||
* Farms in the caller's organisations. The scoping is in the `where`, not
|
||||
* applied to the result afterwards: a filter that runs after the query is
|
||||
* one `return` away from being skipped, and it also makes the database read
|
||||
* rows it is not allowed to show.
|
||||
*
|
||||
* A projection rather than `select *`, because the table holds
|
||||
* `edgeProxyToken`, which trades for an edge JWT - see src/db/projections.ts.
|
||||
*/
|
||||
.get(
|
||||
"/",
|
||||
async ({ user, query }) => {
|
||||
const scope = query.orgId
|
||||
? and(visibleFarms(user.id), eq(farms.orgId, query.orgId))
|
||||
: visibleFarms(user.id);
|
||||
return db.query.farms.findMany({
|
||||
columns: farmProjection.columns,
|
||||
where: scope,
|
||||
orderBy: [desc(farms.createdAt)],
|
||||
...paginate(query),
|
||||
});
|
||||
},
|
||||
{
|
||||
query: t.Object({
|
||||
orgId: t.Optional(t.String({ format: "uuid" })),
|
||||
...PaginationQuery,
|
||||
}),
|
||||
detail: { tags: ["farms"], summary: "Farms in the caller's organisations" },
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/:id",
|
||||
async ({ user, params }) => {
|
||||
const { role } = await requireFarm(user.id, params.id, "viewer");
|
||||
const farm = await db.query.farms.findFirst({
|
||||
columns: farmProjection.columns,
|
||||
where: eq(farms.id, params.id),
|
||||
});
|
||||
if (!farm) throw new NotFoundError(`Farm ${params.id} not found`);
|
||||
return { ...farm, role };
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["farms"] } },
|
||||
)
|
||||
.post(
|
||||
"/",
|
||||
async ({ body, set }) => {
|
||||
// The generated token is deliberately not returned here either. A farm
|
||||
// is created far more often than a gateway is provisioned, and a
|
||||
// credential that comes back from a routine create ends up in logs,
|
||||
// browser history and screenshots. Fetch it when a gateway actually
|
||||
// needs it, through the endpoint below.
|
||||
async ({ user, body, set }) => {
|
||||
// `orgId` comes from the body and is then authorized, which is the
|
||||
// right way round: the caller says where the farm should go, and the
|
||||
// check is whether they own that organisation. What must never come
|
||||
// from the body is *who the caller is* - that is `user.id`, from a
|
||||
// verified token, and it is why there is no `ownerId` field here any
|
||||
// more.
|
||||
await requireOrg(user.id, body.orgId, "owner", "creating a farm");
|
||||
|
||||
// The generated token is deliberately not returned. A farm is created
|
||||
// far more often than a gateway is provisioned, and a credential that
|
||||
// comes back from a routine create ends up in logs, browser history and
|
||||
// screenshots. Fetch it when a gateway actually needs it, below.
|
||||
const [farm] = await db
|
||||
.insert(farms)
|
||||
.values({
|
||||
name: body.name,
|
||||
ownerId: body.ownerId,
|
||||
orgId: body.orgId,
|
||||
edgeProxyToken: crypto.randomUUID(),
|
||||
location: body.location,
|
||||
})
|
||||
@@ -42,12 +83,50 @@ export const farmRoutes = new Elysia({ prefix: "/farms" })
|
||||
},
|
||||
{
|
||||
body: t.Object({
|
||||
name: t.String({ minLength: 1 }),
|
||||
ownerId: t.String({ format: "uuid" }),
|
||||
location: t.Optional(t.String()),
|
||||
name: t.String({ minLength: 1, maxLength: 200 }),
|
||||
orgId: t.String({ format: "uuid" }),
|
||||
location: t.Optional(t.String({ maxLength: 500 })),
|
||||
}),
|
||||
detail: { tags: ["farms"] },
|
||||
},
|
||||
)
|
||||
.patch(
|
||||
"/:id",
|
||||
async ({ user, params, body }) => {
|
||||
await requireFarm(user.id, params.id, "owner", "editing a farm");
|
||||
// `orgId` is not patchable here on purpose: moving a farm between
|
||||
// organisations changes who can see its print history and would need
|
||||
// the `owner` role in *both*, so it wants its own endpoint rather than
|
||||
// a field on a general update.
|
||||
const [farm] = await db
|
||||
.update(farms)
|
||||
.set({ ...body, updatedAt: new Date() })
|
||||
.where(eq(farms.id, params.id))
|
||||
.returning(farmProjection.returning);
|
||||
if (!farm) throw new NotFoundError(`Farm ${params.id} not found`);
|
||||
return farm;
|
||||
},
|
||||
{
|
||||
params: IdParams,
|
||||
body: t.Object({
|
||||
name: t.Optional(t.String({ minLength: 1, maxLength: 200 })),
|
||||
location: t.Optional(t.String({ maxLength: 500 })),
|
||||
settings: t.Optional(t.Record(t.String(), t.Unknown())),
|
||||
}),
|
||||
detail: { tags: ["farms"] },
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
"/:id",
|
||||
async ({ user, params }) => {
|
||||
await requireFarm(user.id, params.id, "owner", "deleting a farm");
|
||||
// Cascades to the farm's printers and print jobs, per the schema's
|
||||
// foreign keys. Worth knowing before calling it.
|
||||
await db.delete(farms).where(eq(farms.id, params.id));
|
||||
return { deleted: params.id };
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["farms"] } },
|
||||
)
|
||||
/**
|
||||
* Issues a *new* `edgeProxyToken` for this farm and returns it once.
|
||||
*
|
||||
@@ -62,26 +141,31 @@ export const farmRoutes = new Elysia({ prefix: "/farms" })
|
||||
* token until it is reconfigured, which is the right trade for a credential
|
||||
* that drives physical machines - but it does mean this is not a "show me
|
||||
* the token" button.
|
||||
*
|
||||
* NOT YET AUTHENTICATED, like every route here. Until it is, this is a
|
||||
* better-shaped hole, not a closed one.
|
||||
*/
|
||||
.post("/:id/edge-proxy-token", async ({ params, set }) => {
|
||||
const token = crypto.randomUUID();
|
||||
const [farm] = await db
|
||||
.update(farms)
|
||||
.set({ edgeProxyToken: token, updatedAt: new Date() })
|
||||
.where(eq(farms.id, params.id))
|
||||
.returning({ id: farms.id });
|
||||
.post(
|
||||
"/:id/edge-proxy-token",
|
||||
async ({ user, params }) => {
|
||||
await requireFarm(user.id, params.id, "owner", "rotating a farm's gateway credential");
|
||||
|
||||
if (!farm) {
|
||||
set.status = 404;
|
||||
return { error: { code: "NOT_FOUND", message: `Farm ${params.id} not found` } };
|
||||
}
|
||||
const token = crypto.randomUUID();
|
||||
const [farm] = await db
|
||||
.update(farms)
|
||||
.set({ edgeProxyToken: token, updatedAt: new Date() })
|
||||
.where(eq(farms.id, params.id))
|
||||
.returning({ id: farms.id });
|
||||
if (!farm) throw new NotFoundError(`Farm ${params.id} not found`);
|
||||
|
||||
return {
|
||||
farmId: farm.id,
|
||||
edgeProxyToken: token,
|
||||
note: "Any gateway still using the previous token must be reconfigured.",
|
||||
};
|
||||
});
|
||||
return {
|
||||
farmId: farm.id,
|
||||
edgeProxyToken: token,
|
||||
note: "Any gateway still using the previous token must be reconfigured.",
|
||||
};
|
||||
},
|
||||
{
|
||||
params: IdParams,
|
||||
detail: {
|
||||
tags: ["farms"],
|
||||
summary: "Rotate and return this farm's edge-proxy token (owner only)",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
+79
-19
@@ -1,27 +1,61 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { ConflictError, NotFoundError } from "@continuum/ts-core";
|
||||
import { db } from "../db";
|
||||
import { printJobs } from "../db/schema";
|
||||
import { getUploadUrl, jobFileKey } from "../s3";
|
||||
import { requireFarm, requireJob, requireUser, visibleJobs } from "../auth";
|
||||
import { PaginationQuery, paginate } from "./pagination";
|
||||
|
||||
const IdParams = t.Object({ id: t.String({ format: "uuid" }) });
|
||||
|
||||
export const jobRoutes = new Elysia({ prefix: "/jobs" })
|
||||
.get("/", async ({ query }) => {
|
||||
if (query.farmId) {
|
||||
return db.select().from(printJobs).where(eq(printJobs.farmId, query.farmId));
|
||||
}
|
||||
return db.select().from(printJobs);
|
||||
}, { query: t.Object({ farmId: t.Optional(t.String({ format: "uuid" })) }) })
|
||||
.get("/:id", async ({ params, set }) => {
|
||||
const job = await db.query.printJobs.findFirst({ where: eq(printJobs.id, params.id) });
|
||||
if (!job) {
|
||||
set.status = 404;
|
||||
return { error: { code: "NOT_FOUND", message: `Print job ${params.id} not found` } };
|
||||
}
|
||||
return job;
|
||||
})
|
||||
.use(requireUser)
|
||||
.get(
|
||||
"/",
|
||||
async ({ user, query }) => {
|
||||
const scope = query.farmId
|
||||
? and(visibleJobs(user.id), eq(printJobs.farmId, query.farmId))
|
||||
: visibleJobs(user.id);
|
||||
return db.query.printJobs.findMany({
|
||||
where: scope,
|
||||
orderBy: [desc(printJobs.createdAt)],
|
||||
...paginate(query),
|
||||
});
|
||||
},
|
||||
{
|
||||
query: t.Object({
|
||||
farmId: t.Optional(t.String({ format: "uuid" })),
|
||||
...PaginationQuery,
|
||||
}),
|
||||
detail: { tags: ["jobs"], summary: "Print jobs in the caller's organisations" },
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/:id",
|
||||
async ({ user, params }) => {
|
||||
await requireJob(user.id, params.id, "viewer");
|
||||
const job = await db.query.printJobs.findFirst({ where: eq(printJobs.id, params.id) });
|
||||
if (!job) throw new NotFoundError(`Print job ${params.id} not found`);
|
||||
return job;
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["jobs"] } },
|
||||
)
|
||||
/**
|
||||
* Creates the job row and hands back a presigned URL to PUT the file to.
|
||||
*
|
||||
* `operator`, matching printer commands: a queued job is a request to move
|
||||
* a machine, even though nothing dispatches it yet. Which is the other
|
||||
* thing to know about this endpoint - it ends at a `queued` row and an
|
||||
* upload URL. Nothing transitions the status and nothing reaches a gateway,
|
||||
* because the gateway has no start-print command yet (see the note in
|
||||
* continuum-proxy's uplink protocol). Jobs accumulate until it does.
|
||||
*/
|
||||
.post(
|
||||
"/",
|
||||
async ({ body, set }) => {
|
||||
async ({ user, body, set }) => {
|
||||
await requireFarm(user.id, body.farmId, "operator", "submitting a print job");
|
||||
|
||||
const jobId = crypto.randomUUID();
|
||||
const r2ObjectKey = jobFileKey(body.farmId, jobId, body.fileName);
|
||||
|
||||
@@ -32,7 +66,10 @@ export const jobRoutes = new Elysia({ prefix: "/jobs" })
|
||||
farmId: body.farmId,
|
||||
fileName: body.fileName,
|
||||
r2ObjectKey,
|
||||
submittedBy: body.submittedBy,
|
||||
// From the verified token, never from the body. It used to be a
|
||||
// `submittedBy` field the caller filled in, which made the audit
|
||||
// trail a suggestion rather than a record.
|
||||
submittedBy: user.id,
|
||||
})
|
||||
.returning();
|
||||
|
||||
@@ -43,9 +80,32 @@ export const jobRoutes = new Elysia({ prefix: "/jobs" })
|
||||
{
|
||||
body: t.Object({
|
||||
farmId: t.String({ format: "uuid" }),
|
||||
fileName: t.String({ minLength: 1 }),
|
||||
fileName: t.String({ minLength: 1, maxLength: 500 }),
|
||||
contentType: t.Optional(t.String()),
|
||||
submittedBy: t.String({ format: "uuid" }),
|
||||
}),
|
||||
detail: { tags: ["jobs"], summary: "Queue a print job and get an upload URL" },
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
"/:id",
|
||||
async ({ user, params }) => {
|
||||
await requireJob(user.id, params.id, "operator", "deleting a print job");
|
||||
const job = await db.query.printJobs.findFirst({
|
||||
columns: { status: true },
|
||||
where: eq(printJobs.id, params.id),
|
||||
});
|
||||
if (!job) throw new NotFoundError(`Print job ${params.id} not found`);
|
||||
|
||||
// Only a job that has not reached a printer. Cancelling a running print
|
||||
// means telling the gateway to stop, which is a command and not a row
|
||||
// deletion - and deleting the row of a print in progress would leave
|
||||
// the printer running work nothing is tracking.
|
||||
if (job.status !== "queued" && job.status !== "uploading") {
|
||||
throw new ConflictError(`Print job ${params.id} is ${job.status} and cannot be deleted`);
|
||||
}
|
||||
|
||||
await db.delete(printJobs).where(eq(printJobs.id, params.id));
|
||||
return { deleted: params.id };
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["jobs"], summary: "Delete a job that has not started" } },
|
||||
);
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import { and, count, eq, ne } from "drizzle-orm";
|
||||
import { ConflictError, NotFoundError } from "@continuum/ts-core";
|
||||
import { db } from "../db";
|
||||
import { farms, orgMembers, organisations, ORG_ROLES } from "../db/schema";
|
||||
import { listMemberships, requireOrg, requireUser } from "../auth";
|
||||
|
||||
const RoleSchema = t.Union(ORG_ROLES.map((role) => t.Literal(role)));
|
||||
const IdParams = t.Object({ id: t.String({ format: "uuid" }) });
|
||||
const MemberParams = t.Object({
|
||||
id: t.String({ format: "uuid" }),
|
||||
userId: t.String({ format: "uuid" }),
|
||||
});
|
||||
|
||||
/**
|
||||
* Counts the organisation's owners, used to refuse the one change that cannot
|
||||
* be undone through the API: removing or demoting its last `owner` leaves
|
||||
* nobody who can add one back, and the org's farms and printers with it.
|
||||
*/
|
||||
async function ownersOtherThan(orgId: string, userId: string): Promise<number> {
|
||||
const [row] = await db
|
||||
.select({ n: count() })
|
||||
.from(orgMembers)
|
||||
.where(and(eq(orgMembers.orgId, orgId), eq(orgMembers.role, "owner"), ne(orgMembers.userId, userId)));
|
||||
return Number(row?.n ?? 0);
|
||||
}
|
||||
|
||||
export const orgRoutes = new Elysia({ prefix: "/orgs" })
|
||||
.use(requireUser)
|
||||
/**
|
||||
* Only the caller's own organisations - there is no endpoint that lists all
|
||||
* of them, by design. An organisation the caller is not a member of should
|
||||
* be indistinguishable from one that does not exist.
|
||||
*/
|
||||
.get("/", async ({ user }) => listMemberships(user.id), {
|
||||
detail: { tags: ["orgs"], summary: "Organisations the caller belongs to" },
|
||||
})
|
||||
.post(
|
||||
"/",
|
||||
async ({ user, body, set }) => {
|
||||
// One transaction: an organisation with no owner is unreachable by
|
||||
// everyone including its creator, and that is exactly the state a
|
||||
// failure between these two inserts would leave behind.
|
||||
const org = await db.transaction(async (tx) => {
|
||||
const [created] = await tx
|
||||
.insert(organisations)
|
||||
.values({ name: body.name })
|
||||
.returning();
|
||||
await tx
|
||||
.insert(orgMembers)
|
||||
.values({ orgId: created!.id, userId: user.id, role: "owner" });
|
||||
return created!;
|
||||
});
|
||||
set.status = 201;
|
||||
return { ...org, role: "owner" as const };
|
||||
},
|
||||
{
|
||||
body: t.Object({ name: t.String({ minLength: 1, maxLength: 200 }) }),
|
||||
detail: { tags: ["orgs"], summary: "Create an organisation, owned by the caller" },
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/:id",
|
||||
async ({ user, params }) => {
|
||||
const role = await requireOrg(user.id, params.id, "viewer");
|
||||
const org = await db.query.organisations.findFirst({
|
||||
where: eq(organisations.id, params.id),
|
||||
});
|
||||
// Membership resolved, so the row is there; the throw is for the
|
||||
// vanishingly small window where it was deleted in between.
|
||||
if (!org) throw new NotFoundError(`Organisation ${params.id} not found`);
|
||||
return { ...org, role };
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["orgs"] } },
|
||||
)
|
||||
.patch(
|
||||
"/:id",
|
||||
async ({ user, params, body }) => {
|
||||
await requireOrg(user.id, params.id, "owner", "renaming an organisation");
|
||||
const [org] = await db
|
||||
.update(organisations)
|
||||
.set({ ...body, updatedAt: new Date() })
|
||||
.where(eq(organisations.id, params.id))
|
||||
.returning();
|
||||
if (!org) throw new NotFoundError(`Organisation ${params.id} not found`);
|
||||
return org;
|
||||
},
|
||||
{
|
||||
params: IdParams,
|
||||
body: t.Object({
|
||||
name: t.Optional(t.String({ minLength: 1, maxLength: 200 })),
|
||||
settings: t.Optional(t.Record(t.String(), t.Unknown())),
|
||||
}),
|
||||
detail: { tags: ["orgs"] },
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
"/:id",
|
||||
async ({ user, params }) => {
|
||||
await requireOrg(user.id, params.id, "owner", "deleting an organisation");
|
||||
|
||||
// Deleting the org cascades to its farms, their printers, every print
|
||||
// job and every stored frame embedding. That is far too much to lose to
|
||||
// a mistyped id, so this refuses while any farm is still attached and
|
||||
// makes the caller delete them one at a time first.
|
||||
const [attached] = await db
|
||||
.select({ n: count() })
|
||||
.from(farms)
|
||||
.where(eq(farms.orgId, params.id));
|
||||
if (Number(attached?.n ?? 0) > 0) {
|
||||
throw new ConflictError(
|
||||
`Organisation ${params.id} still has ${attached!.n} farm(s); delete them first`,
|
||||
);
|
||||
}
|
||||
|
||||
await db.delete(organisations).where(eq(organisations.id, params.id));
|
||||
return { deleted: params.id };
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["orgs"] } },
|
||||
)
|
||||
.get(
|
||||
"/:id/members",
|
||||
async ({ user, params }) => {
|
||||
await requireOrg(user.id, params.id, "viewer");
|
||||
return db
|
||||
.select({
|
||||
userId: orgMembers.userId,
|
||||
role: orgMembers.role,
|
||||
joinedAt: orgMembers.createdAt,
|
||||
})
|
||||
.from(orgMembers)
|
||||
.where(eq(orgMembers.orgId, params.id));
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["orgs"], summary: "List members and their roles" } },
|
||||
)
|
||||
/**
|
||||
* Add a member or change their role. PUT rather than POST: the caller
|
||||
* states the role this user should have, and sending it twice is the same
|
||||
* as sending it once.
|
||||
*
|
||||
* There is no invitation flow yet - this takes a Supabase user id directly,
|
||||
* so adding someone means knowing their id. That is the right shape for an
|
||||
* API and the wrong shape for a UI, which will need an invite-by-email
|
||||
* endpoint on top of it.
|
||||
*/
|
||||
.put(
|
||||
"/:id/members/:userId",
|
||||
async ({ user, params, body }) => {
|
||||
await requireOrg(user.id, params.id, "owner", "managing membership");
|
||||
|
||||
// Demoting the last owner is the same mistake as deleting them, so it
|
||||
// is refused the same way. Written against "owners other than this
|
||||
// one" rather than "is this me" so it also covers one owner demoting
|
||||
// another, which is the same hole from the other side.
|
||||
if (body.role !== "owner" && (await ownersOtherThan(params.id, params.userId)) === 0) {
|
||||
throw new ConflictError(
|
||||
params.userId === user.id
|
||||
? "You are the only owner of this organisation; promote another owner before demoting yourself"
|
||||
: "That is the only owner of this organisation; promote another owner first",
|
||||
);
|
||||
}
|
||||
|
||||
const [member] = await db
|
||||
.insert(orgMembers)
|
||||
.values({ orgId: params.id, userId: params.userId, role: body.role })
|
||||
.onConflictDoUpdate({
|
||||
target: [orgMembers.orgId, orgMembers.userId],
|
||||
set: { role: body.role, updatedAt: new Date() },
|
||||
})
|
||||
.returning({
|
||||
userId: orgMembers.userId,
|
||||
role: orgMembers.role,
|
||||
joinedAt: orgMembers.createdAt,
|
||||
});
|
||||
return member;
|
||||
},
|
||||
{
|
||||
params: MemberParams,
|
||||
body: t.Object({ role: RoleSchema }),
|
||||
detail: { tags: ["orgs"], summary: "Add a member or change their role" },
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
"/:id/members/:userId",
|
||||
async ({ user, params }) => {
|
||||
await requireOrg(user.id, params.id, "owner", "managing membership");
|
||||
|
||||
if ((await ownersOtherThan(params.id, params.userId)) === 0) {
|
||||
throw new ConflictError(
|
||||
"That is the only owner of this organisation; promote another owner first",
|
||||
);
|
||||
}
|
||||
|
||||
const [removed] = await db
|
||||
.delete(orgMembers)
|
||||
.where(and(eq(orgMembers.orgId, params.id), eq(orgMembers.userId, params.userId)))
|
||||
.returning({ userId: orgMembers.userId });
|
||||
if (!removed) throw new NotFoundError(`User ${params.userId} is not a member`);
|
||||
return { removed: removed.userId };
|
||||
},
|
||||
{ params: MemberParams, detail: { tags: ["orgs"], summary: "Remove a member" } },
|
||||
);
|
||||
@@ -0,0 +1,21 @@
|
||||
import { t } from "elysia";
|
||||
|
||||
/**
|
||||
* Shared `limit`/`offset` query parameters for the list endpoints.
|
||||
*
|
||||
* Every list here is unbounded in principle - a farm accumulates print jobs
|
||||
* forever - so a default limit is applied whether or not the caller asks for
|
||||
* one. `maximum` is enforced by the validator rather than silently clamped:
|
||||
* a client that asks for 10,000 rows should be told no, not handed 200 and
|
||||
* left to conclude that is all there is.
|
||||
*/
|
||||
export const PaginationQuery = {
|
||||
limit: t.Optional(t.Integer({ minimum: 1, maximum: 200, default: 50 })),
|
||||
offset: t.Optional(t.Integer({ minimum: 0, default: 0 })),
|
||||
};
|
||||
|
||||
export const DEFAULT_LIMIT = 50;
|
||||
|
||||
export function paginate(query: { limit?: number; offset?: number }) {
|
||||
return { limit: query.limit ?? DEFAULT_LIMIT, offset: query.offset ?? 0 };
|
||||
}
|
||||
+147
-49
@@ -1,52 +1,145 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { NotFoundError } from "@continuum/ts-core";
|
||||
import { PrinterCommandSchema } from "@continuum/ts-types";
|
||||
import { db } from "../db";
|
||||
import { printers } from "../db/schema";
|
||||
import { PrinterInsertSchema } from "../db/validators";
|
||||
import { printerProjection } from "../db/projections";
|
||||
import { PrinterCommandSchema } from "@continuum/ts-types";
|
||||
import { requireFarm, requirePrinter, requireUser, visiblePrinters } from "../auth";
|
||||
import { PaginationQuery, paginate } from "./pagination";
|
||||
import { isGatewayOnline, sendPrinterCommand } from "./ws/edge";
|
||||
|
||||
const IdParams = t.Object({ id: t.String({ format: "uuid" }) });
|
||||
|
||||
/**
|
||||
* The columns a client may set, derived from the table's insert schema so a
|
||||
* renamed column still fails to compile.
|
||||
*
|
||||
* Everything left out is owned by the gateway, not by the API: `status`,
|
||||
* the temperatures, layer counts, progress, `vendorState`, `lastSeenAt` and
|
||||
* the rest are written only by `persistTelemetry` in routes/ws/edge.ts. A
|
||||
* client that could POST `status: "idle"` could make the scheduler send work
|
||||
* to a printer that is mid-print.
|
||||
*/
|
||||
const PRINTER_WRITABLE = [
|
||||
"farmId",
|
||||
"name",
|
||||
"vendor",
|
||||
"lanAddress",
|
||||
"serialNumber",
|
||||
"accessCode",
|
||||
"gatewayPrinterId",
|
||||
"metadata",
|
||||
] as const;
|
||||
|
||||
const PrinterCreateSchema = t.Pick(PrinterInsertSchema, PRINTER_WRITABLE);
|
||||
// `farmId` omitted: moving a printer to another farm would move its print
|
||||
// history across an authorization boundary, so it is not a field on an update.
|
||||
const PrinterUpdateSchema = t.Partial(
|
||||
t.Omit(PrinterCreateSchema, ["farmId"]),
|
||||
);
|
||||
|
||||
export const printerRoutes = new Elysia({ prefix: "/printers" })
|
||||
// A projection rather than `select *`: `printers.accessCode` is the
|
||||
// printer's LAN password (Bambu uses it for MQTT and as the FTPS password)
|
||||
// and must not leave the server. See src/db/projections.ts.
|
||||
.get("/", async ({ query }) => db.query.printers.findMany({
|
||||
columns: printerProjection.columns,
|
||||
where: query.farmId ? eq(printers.farmId, query.farmId) : undefined,
|
||||
}), { query: t.Object({ farmId: t.Optional(t.String({ format: "uuid" })) }) })
|
||||
.get("/:id", async ({ params, set }) => {
|
||||
const printer = await db.query.printers.findFirst({
|
||||
columns: printerProjection.columns,
|
||||
where: eq(printers.id, params.id),
|
||||
});
|
||||
if (!printer) {
|
||||
set.status = 404;
|
||||
return { error: { code: "NOT_FOUND", message: `Printer ${params.id} not found` } };
|
||||
}
|
||||
return printer;
|
||||
})
|
||||
.use(requireUser)
|
||||
// Scoped through farm -> org membership, and a projection rather than
|
||||
// `select *`: `printers.accessCode` is the printer's LAN password (Bambu
|
||||
// uses it for MQTT and as the FTPS password) and must not leave the server.
|
||||
// See src/db/projections.ts.
|
||||
.get(
|
||||
"/",
|
||||
async ({ user, query }) => {
|
||||
const scope = query.farmId
|
||||
? and(visiblePrinters(user.id), eq(printers.farmId, query.farmId))
|
||||
: visiblePrinters(user.id);
|
||||
return db.query.printers.findMany({
|
||||
columns: printerProjection.columns,
|
||||
where: scope,
|
||||
orderBy: [desc(printers.createdAt)],
|
||||
...paginate(query),
|
||||
});
|
||||
},
|
||||
{
|
||||
query: t.Object({
|
||||
farmId: t.Optional(t.String({ format: "uuid" })),
|
||||
...PaginationQuery,
|
||||
}),
|
||||
detail: { tags: ["printers"], summary: "Printers in the caller's organisations" },
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/:id",
|
||||
async ({ user, params }) => {
|
||||
await requirePrinter(user.id, params.id, "viewer");
|
||||
const printer = await db.query.printers.findFirst({
|
||||
columns: printerProjection.columns,
|
||||
where: eq(printers.id, params.id),
|
||||
});
|
||||
if (!printer) throw new NotFoundError(`Printer ${params.id} not found`);
|
||||
return printer;
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["printers"] } },
|
||||
)
|
||||
.post(
|
||||
"/",
|
||||
async ({ body, set }) => {
|
||||
// `body` is already validated + shaped against the Drizzle table by
|
||||
// PrinterInsertSchema, so it can go straight into `.values()` with no
|
||||
// hand-mapping of individual fields.
|
||||
const [printer] = await db.insert(printers).values(body).returning(printerProjection.returning);
|
||||
async ({ user, body, set }) => {
|
||||
await requireFarm(user.id, body.farmId, "owner", "adding a printer");
|
||||
const [printer] = await db
|
||||
.insert(printers)
|
||||
.values(body)
|
||||
.returning(printerProjection.returning);
|
||||
set.status = 201;
|
||||
return printer;
|
||||
},
|
||||
// Derived from `printers` via drizzle-typebox - see src/db/validators.ts.
|
||||
// Add or rename a column in the schema and this validator updates itself.
|
||||
{ body: PrinterInsertSchema },
|
||||
{ body: PrinterCreateSchema, detail: { tags: ["printers"] } },
|
||||
)
|
||||
.patch(
|
||||
"/:id",
|
||||
async ({ user, params, body }) => {
|
||||
await requirePrinter(user.id, params.id, "owner", "editing a printer");
|
||||
const [printer] = await db
|
||||
.update(printers)
|
||||
.set({ ...body, updatedAt: new Date() })
|
||||
.where(eq(printers.id, params.id))
|
||||
.returning(printerProjection.returning);
|
||||
if (!printer) throw new NotFoundError(`Printer ${params.id} not found`);
|
||||
return printer;
|
||||
},
|
||||
{
|
||||
params: IdParams,
|
||||
body: PrinterUpdateSchema,
|
||||
detail: {
|
||||
tags: ["printers"],
|
||||
summary: "Edit a printer's configuration (name, address, credentials, gateway id)",
|
||||
},
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
"/:id",
|
||||
async ({ user, params }) => {
|
||||
await requirePrinter(user.id, params.id, "owner", "deleting a printer");
|
||||
await db.delete(printers).where(eq(printers.id, params.id));
|
||||
return { deleted: params.id };
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["printers"] } },
|
||||
)
|
||||
/**
|
||||
* Sends a command to the printer through its farm's gateway and waits for
|
||||
* the gateway's answer.
|
||||
*
|
||||
* `operator`, not `viewer`: every command in the set moves or heats a
|
||||
* physical machine, and the blast radius of getting this boundary wrong is
|
||||
* a ruined print or a hot end driven into a plate. It is the one role
|
||||
* boundary here that is not about data.
|
||||
*/
|
||||
.post(
|
||||
"/:id/commands",
|
||||
async ({ params, body, set }) => {
|
||||
async ({ user, params, body, set }) => {
|
||||
await requirePrinter(user.id, params.id, "operator", "sending a printer command");
|
||||
try {
|
||||
const result = await sendPrinterCommand(params.id, body);
|
||||
if (!result.ok) {
|
||||
// 502, not 400: the request was fine and was delivered: it was the
|
||||
// 502, not 400: the request was fine and was delivered; it was the
|
||||
// printer or its gateway that would not carry it out.
|
||||
set.status = 502;
|
||||
return {
|
||||
@@ -64,7 +157,10 @@ export const printerRoutes = new Elysia({ prefix: "/printers" })
|
||||
// its farm has no gateway connected right now.
|
||||
set.status = 409;
|
||||
return {
|
||||
error: { code: "PRINTER_UNREACHABLE", message: err instanceof Error ? err.message : String(err) },
|
||||
error: {
|
||||
code: "PRINTER_UNREACHABLE",
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
@@ -72,22 +168,24 @@ export const printerRoutes = new Elysia({ prefix: "/printers" })
|
||||
// schema - so this route cannot drift into offering something no gateway
|
||||
// can execute. Note what is absent: there is no "start a print" command
|
||||
// yet, deliberately.
|
||||
{ body: PrinterCommandSchema },
|
||||
{ params: IdParams, body: PrinterCommandSchema, detail: { tags: ["printers"] } },
|
||||
)
|
||||
.get("/:id/gateway", async ({ params, set }) => {
|
||||
const printer = await db.query.printers.findFirst({
|
||||
columns: { farmId: true, gatewayPrinterId: true },
|
||||
where: eq(printers.id, params.id),
|
||||
});
|
||||
if (!printer) {
|
||||
set.status = 404;
|
||||
return { error: { code: "NOT_FOUND", message: `Printer ${params.id} not found` } };
|
||||
}
|
||||
// Whether a command sent right now could even be delivered - worth being
|
||||
// able to ask before trying, since the answer changes on its own.
|
||||
return {
|
||||
claimed: printer.gatewayPrinterId !== null,
|
||||
gatewayPrinterId: printer.gatewayPrinterId,
|
||||
gatewayOnline: isGatewayOnline(printer.farmId),
|
||||
};
|
||||
});
|
||||
.get(
|
||||
"/:id/gateway",
|
||||
async ({ user, params }) => {
|
||||
await requirePrinter(user.id, params.id, "viewer");
|
||||
const printer = await db.query.printers.findFirst({
|
||||
columns: { farmId: true, gatewayPrinterId: true },
|
||||
where: eq(printers.id, params.id),
|
||||
});
|
||||
if (!printer) throw new NotFoundError(`Printer ${params.id} not found`);
|
||||
// Whether a command sent right now could even be delivered - worth being
|
||||
// able to ask before trying, since the answer changes on its own.
|
||||
return {
|
||||
claimed: printer.gatewayPrinterId !== null,
|
||||
gatewayPrinterId: printer.gatewayPrinterId,
|
||||
gatewayOnline: isGatewayOnline(printer.farmId),
|
||||
};
|
||||
},
|
||||
{ params: IdParams, detail: { tags: ["printers"] } },
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user