Files
loki/drizzle/0138_token_sessions.sql
Cato 198d77e523 feat(auth): an agent's token opens a browser session, with the token's power and no more (#1679)
* feat(auth): an agent's token opens a browser session, with the token's power and no more

A browser cannot send a Bearer header on a page load, so a Viewer seat with a
ck_ token was sent to sign-in from /projects, /terminal, the workbench,
history and feedback.

- POST /api/token-session (Bearer ck_ only) mints a link that opens once,
  within two minutes. The link carries a random code; the server keeps its
  SHA-256 (token_sessions, migration 0138). The token is never in the link.
- GET /api/auth/loki/token-session (an AccountKit plugin endpoint) opens it:
  a session for the token's user that ends after an hour, is never
  refreshed, and is recorded as the token's before its cookie is set.
- Such a session reads like the user (pages, GET on the API) and writes only
  where a token is accepted: the proxy marks its writes and person-only
  routes read them as signed out. It never reaches tokens, a shell, the
  password, linked sign-ins or export, nor AccountKit's passkey and second
  factor endpoints. Revoking or expiring the token signs it out.

Tests: scripts/test/token-session.ts (landing paths, the refused routes, the
middleware decision, the wiring); scripts/test/token-session-db.ts in
test:db (single use, expiry, revoked and expired tokens, hash-only storage).

* style(drizzle): format the 0138 snapshot and journal
2026-11-12 22:24:41 +01:00

20 lines
1.3 KiB
SQL

-- A browser session opened with an agent's ck_ token: one row per single-use
-- exchange link (src/lib/auth/token-session.ts). New table only.
CREATE TABLE "token_sessions" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"code_hash" text NOT NULL,
"user_id" uuid NOT NULL,
"agent_token_id" uuid,
"next_path" text DEFAULT '/' NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"used_at" timestamp with time zone,
"session_id" text,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "token_sessions" ADD CONSTRAINT "token_sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "token_sessions" ADD CONSTRAINT "token_sessions_agent_token_id_agent_tokens_id_fk" FOREIGN KEY ("agent_token_id") REFERENCES "public"."agent_tokens"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "uq_token_sessions_code_hash" ON "token_sessions" USING btree ("code_hash");--> statement-breakpoint
CREATE UNIQUE INDEX "uq_token_sessions_session_id" ON "token_sessions" USING btree ("session_id");--> statement-breakpoint
CREATE INDEX "idx_token_sessions_user_id" ON "token_sessions" USING btree ("user_id");