v0.12.0 — REST API + personal access tokens

A bidirectional API so other apps (Home Assistant, phone shortcuts, scripts,
and the coming MCP server) can read and update the homestead.

- ApiToken model (sha256-hashed, scoped, with prefix/lastUsed/expiry/revoke)
- authenticateRequest() accepts EITHER a NextAuth cookie session OR a Bearer
  PAT; cookie sessions get full access, tokens are limited to their scopes
  (write implies read; resource and global wildcards). ApiError + handleApiError
- Shared service layer (plants/tasks/locations/plant-types) reused by every
  endpoint and, later, the MCP server — logic lives once
- /api/v1: plants (read + add log), plant-types, locations, tasks (read/create/
  complete), and a whoami/discovery root
- Settings → API tokens: create with per-resource read/write checkboxes, raw
  token shown once, revoke; tokens added to backup/restore
- Pure tests for scope matching + token hashing; verified end-to-end (401/403/
  201, lastUsedAt) against a running server

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-15 23:55:58 -05:00
parent cdb21ed58a
commit c5bf108cb9
27 changed files with 880 additions and 4 deletions

22
src/lib/api/scopes.ts Normal file
View File

@@ -0,0 +1,22 @@
// Client-safe scope constants (no server deps) — shared by the auth helper,
// the token routes, and the token-management UI.
export const KNOWN_SCOPES = [
"plants:read", "plants:write",
"plant-types:read", "plant-types:write",
"locations:read", "locations:write",
"tasks:read", "tasks:write",
"items:read", "items:write",
] as const;
export type KnownScope = (typeof KNOWN_SCOPES)[number];
// Resources for the token-creation UI (read/write columns). `soon` marks
// domains whose endpoints are still being built.
export const SCOPE_RESOURCES: { key: string; label: string; soon?: boolean }[] = [
{ key: "plants", label: "Plants" },
{ key: "plant-types", label: "Plant types" },
{ key: "locations", label: "Locations" },
{ key: "tasks", label: "Tasks & reminders" },
{ key: "items", label: "Inventory", soon: true },
];