Phase 3, part 3 (`docs/design.md`, "Next"): personal API tokens, for scripts. Two-factor sign-in comes next as its own PR. **Making them** - On the account page, in a new API Tokens card. You give each token: - a name - how long it lasts: 7 days, 30 days, 90 days or 1 year - what it may do: permissions you hold, picked for each product of yours or catalog whose team you're on (moderators and admins can also pick everywhere) - The token is shown once, with a Copy button. Only its hash is stored. - The card lists active tokens: what each grants, when it expires, and when it was last used. Each can be revoked; revoked and expired ones are folded away below. - Tokens are made and revoked only from a website session, so a token can't make tokens. Limits: 20 active tokens, 50 grants each, 1 year at most. **Using them** - Send `Authorization: Bearer t5de_pat_...`. - A token works only on routes that check a permission: - product info, publishing, locks and history - uploading and retracting revisions of a product: these now check `revision:upload` and `revision:retract` - a catalog's settings, key, team, members, invites and hosted products - file blocks, and assigning cases - Everywhere else answers 403 `token_not_allowed`, including making a new product, reports, `/me` and the console. A wrong, revoked or expired token gets 401 `bad_token`. - Each check is the intersection of what the token grants and what the person holds now: a token never does more than its owner can, and losing a role takes it from the token at once. **Audit** - Actions taken with a token are recorded as the person, with `token: <name>` added to the details. - Making and revoking a token are audited as `token.create` and `token.revoke`. **Migration** `0014_api_tokens`: the `api_token` table. **Checks** - 56 API tests pass. The new `tokens.test.ts` covers: - only permissions held now can be granted - grants are limited to their product or catalog - session-only routes refuse tokens - uploads by token - the audit marking and last use - revoked and expired tokens - a moderator demoted while their token was active - Type checks pass. - On a local hub, through the website: - the card shows what can be granted - making a token (refused without any permission chosen); the token was shown once - using it for a granted edit and the member list; refused for what it wasn't given, and on `/me` - its last use on the account page, and the audit entry naming it - Revoke, after which the token got 401 Phase 3, part 3 (`docs/design.md`, "Next"): personal API tokens, for scripts. Two-factor sign-in comes next as its own PR. **Making them** - On the account page, in a new API Tokens card. You give each token: - a name - how long it lasts: 7 days, 30 days, 90 days or 1 year - what it may do: permissions you hold, picked for each product of yours or catalog whose team you're on (moderators and admins can also pick everywhere) - The token is shown once, with a Copy button. Only its hash is stored. - The card lists active tokens: what each grants, when it expires, and when it was last used. Each can be revoked; revoked and expired ones are folded away below. - Tokens are made and revoked only from a website session, so a token can't make tokens. Limits: 20 active tokens, 50 grants each, 1 year at most. **Using them** - Send `Authorization: Bearer t5de_pat_...`. - A token works only on routes that check a permission: - product info, publishing, locks and history - uploading and retracting revisions of a product: these now check `revision:upload` and `revision:retract` - a catalog's settings, key, team, members, invites and hosted products - file blocks, and assigning cases - Everywhere else answers 403 `token_not_allowed`, including making a new product, reports, `/me` and the console. A wrong, revoked or expired token gets 401 `bad_token`. - Each check is the intersection of what the token grants and what the person holds now: a token never does more than its owner can, and losing a role takes it from the token at once. **Audit** - Actions taken with a token are recorded as the person, with `token: <name>` added to the details. - Making and revoking a token are audited as `token.create` and `token.revoke`. **Migration** `0014_api_tokens`: the `api_token` table. **Checks** - 56 API tests pass. The new `tokens.test.ts` covers: - only permissions held now can be granted - grants are limited to their product or catalog - session-only routes refuse tokens - uploads by token - the audit marking and last use - revoked and expired tokens - a moderator demoted while their token was active - Type checks pass. - On a local hub, through the website: - the card shows what can be granted - making a token (refused without any permission chosen); the token was shown once - using it for a granted edit and the member list; refused for what it wasn't given, and on `/me` - its last use on the account page, and the audit entry naming it - Revoke, after which the token got 401 Note: the permission list also offers permissions for which no route takes tokens yet, such as `import:*` and `stats:read`. They'll work once those features have routes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Note: the permission list also offers permissions for which no route takes tokens yet, such as `import:*` and `stats:read`. They'll work once those features have routes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: dhkatz <[email protected]>
99 lines
4.5 KiB
TypeScript
99 lines
4.5 KiB
TypeScript
// The hub's API, called from server components and server actions. Calls go to the API's internal address
|
|
// (API_URL) with the visitor's cookie, so the API sees the same session the browser has.
|
|
import "server-only";
|
|
import { treaty } from "@elysiajs/eden";
|
|
import type { App } from "@t5de/api";
|
|
import { headers } from "next/headers";
|
|
import { cache } from "react";
|
|
|
|
const apiURL = process.env.API_URL ?? "http://localhost:4101";
|
|
|
|
/** The visitor's cookie and address, to pass on to the API. */
|
|
async function forwarded(): Promise<Record<string, string>> {
|
|
const incoming = await headers();
|
|
const forward: Record<string, string> = {};
|
|
for (const name of ["cookie", "x-forwarded-for", "user-agent"]) {
|
|
const value = incoming.get(name);
|
|
if (value) forward[name] = value;
|
|
}
|
|
return forward;
|
|
}
|
|
|
|
/**
|
|
* The API's /api/v1 routes, as the person making this request. (Never await the client itself: it's a proxy, and
|
|
* awaiting it would call a route named "then".)
|
|
*/
|
|
export const api = treaty<App>(apiURL, { headers: forwarded }).api.v1;
|
|
|
|
type V1 = typeof api;
|
|
type Problem = { error: string; message: string };
|
|
/** What a route answers when it succeeds (the API's error shape is part of its declared answers). */
|
|
type Ok<T> = Exclude<T, Problem>;
|
|
type Data<Route extends (...args: any[]) => Promise<{ data: unknown }>> = Ok<
|
|
NonNullable<Awaited<ReturnType<Route>>["data"]>
|
|
>;
|
|
|
|
export type Person = Data<V1["me"]["get"]>["person"];
|
|
export type Account = Data<V1["account"]["get"]>;
|
|
export type Link = Account["links"][number];
|
|
export type Challenge = Account["challenges"][number];
|
|
export type AgeInfo = Data<V1["age"]["get"]>;
|
|
export type OnlineEntry = Data<V1["online"]["get"]>["online"][number];
|
|
export type ConsoleData = Data<V1["console"]["get"]>;
|
|
export type AuditEntry = ConsoleData["audit"][number];
|
|
export type CaseSummary = Data<V1["cases"]["get"]>["cases"][number];
|
|
export type CasePage = Data<ReturnType<V1["cases"]>["get"]>;
|
|
export type NotificationEntry = Data<V1["notifications"]["get"]>["notifications"][number];
|
|
export type TokenList = Data<V1["account"]["tokens"]["get"]>;
|
|
export type TokenEntry = TokenList["tokens"][number];
|
|
export type TokenScope = TokenList["scopes"][number];
|
|
export type CatalogPage = Data<ReturnType<V1["catalogs"]>["get"]>;
|
|
export type CatalogMember = Data<ReturnType<V1["catalogs"]>["members"]["get"]>["members"][number];
|
|
export type CatalogInvite = Data<ReturnType<V1["catalogs"]>["invites"]["get"]>["invites"][number];
|
|
export type HostedProduct = Data<ReturnType<V1["catalogs"]>["products"]["get"]>["products"][number];
|
|
export type CatalogTeam = Data<ReturnType<V1["catalogs"]>["team"]["get"]>;
|
|
export type ProductSummary = Data<V1["products"]["get"]>["products"][number];
|
|
export type ProductPage = Data<ReturnType<V1["products"]>["get"]>;
|
|
export type Revision = ProductPage["revisions"][number];
|
|
export type InfoEntry = Data<ReturnType<V1["products"]>["history"]["get"]>["entries"][number];
|
|
export type ManagedProduct = Data<V1["console"]["products"]["get"]>["products"][number];
|
|
export type Catalog = Data<V1["catalogs"]["get"]>["catalogs"][number];
|
|
export type LibraryEntry = Data<V1["library"]["get"]>["library"][number];
|
|
export type HostedRoom = Data<V1["hosted-rooms"]["get"]>["rooms"][number];
|
|
|
|
/** An error the API answered: message is written to be shown as is. */
|
|
export class ApiError extends Error {
|
|
constructor(
|
|
readonly status: number,
|
|
readonly slug: string,
|
|
message: string,
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
type Answer<T> = { data: T; error: null } | { data: null; error: { status: unknown; value: unknown } };
|
|
|
|
/** The answer's data, or throws ApiError with the API's message. */
|
|
export function unwrap<T>(answer: Answer<T>): Ok<NonNullable<T>> {
|
|
if (answer.error) {
|
|
const status = typeof answer.error.status === "number" ? answer.error.status : 500;
|
|
const value = answer.error.value as { error?: unknown; message?: unknown } | null;
|
|
const slug = typeof value?.error === "string" ? value.error : "error";
|
|
const message =
|
|
typeof value?.message === "string" && value.message
|
|
? value.message
|
|
: "Something went wrong. Try again in a moment.";
|
|
throw new ApiError(status, slug, message);
|
|
}
|
|
return answer.data as Ok<NonNullable<T>>;
|
|
}
|
|
|
|
/** Who's signed in, or undefined. Once per request. */
|
|
export const getMe = cache(async (): Promise<Person | undefined> => {
|
|
const { data } = await api.me.get();
|
|
return data && "person" in data ? data.person : undefined;
|
|
});
|
|
|
|
export const isModerator = (p: Pick<Person, "role"> | undefined) => p?.role === "moderator" || p?.role === "admin";
|