Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): unified actor middleware + ChannelType dm widen (phase 1-2)

Simone952f59a2e7c3
diff --git a/src/shared/src/utils/community-roles.ts b/src/shared/src/utils/community-roles.ts
index 95e597bec..dc58d5521 100644
--- a/src/shared/src/utils/community-roles.ts
+++ b/src/shared/src/utils/community-roles.ts
@@ -1,6 +1,13 @@
export type CommunityRole = "owner" | "admin" | "member"
export type ChannelType = "text" | "forum"
-export type StoredChannelType = "text" | "forum" | "forum_post" | "thread"
+// Every value the `community_channel.type` column can hold. DMs became channels
+// with `type='dm'` in migration 0068 (`isDm` below has always checked for it),
+// but this union previously omitted `dm` — a real type-level gap. Widened to
+// the full stored set so code that switches on a channel's stored type is
+// exhaustive over DM channels too. (We keep `forum_post`, NOT the `post` rename
+// from the abandoned PR-408 batch1 — see
+// plans/22-community-unified-actor-route-unify.md §7 ADAPT.)
+export type StoredChannelType = "text" | "forum" | "forum_post" | "thread" | "dm"
export const ROLES = {
OWNER: "owner",
diff --git a/src/web/src/lib/middleware/community-actor.test.ts b/src/web/src/lib/middleware/community-actor.test.ts
new file mode 100644
index 000000000..ffe4ad983
--- /dev/null
+++ b/src/web/src/lib/middleware/community-actor.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest, NextResponse } from "next/server"
+
+// The unified actor is a thin router over two collaborators:
+// - resolveBotActor (crk_ → bot identity) — the bot path;
+// - withAuth (session/al_ → human AuthContext) — the human path, delegated
+// VERBATIM so we don't re-test its internals here.
+// We mock both so this file tests only the routing + actor-shape adaptation +
+// the crk_-never-falls-through invariant. Behavior of each collaborator is
+// covered by their own suites (community-agent-runner-auth.test.ts, auth.test.ts).
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
+}))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+const mockResolveBotActor = vi.fn()
+vi.mock("./community-agent-runner-auth", () => ({
+ resolveBotActor: (...a: unknown[]) => mockResolveBotActor(...a),
+}))
+
+// withAuth is a higher-order wrapper: withAuth(handler) → (req, ctx) => ….
+// Our mock invokes the wrapped handler with a canned human AuthContext so we
+// can assert the actor adaptation. `mockHumanCtx` lets a test simulate an
+// auth failure by having the mock short-circuit instead of calling through.
+let mockHumanCtx: Record<string, unknown> | null = {
+ env: { DB: {} },
+ userId: "human_1",
+ email: "[email protected]",
+ workspaceId: "ws_1",
+ user: { isBot: false },
+}
+vi.mock("./auth", () => ({
+ withAuth: (handler: (r: NextRequest, ctx: any) => Promise<Response>) =>
+ async (req: NextRequest, _ctx?: unknown) => {
+ if (!mockHumanCtx) return NextResponse.json({ error: "unauthorized" }, { status: 401 })
+ return handler(req, { ...mockHumanCtx, params: undefined })
+ },
+}))
+
+import { withCommunityActor, rejectBot, requireBot, type CommunityActor } from "./community-actor"
+
+const handler = vi.fn(async (_req: NextRequest, ctx: any) => NextResponse.json({ ok: true, actor: ctx.actor }))
+
+const bearer = (v: string) => new NextRequest("http://localhost/x", { headers: { Authorization: v } })
+
+describe("withCommunityActor", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockHumanCtx = { env: { DB: {} }, userId: "human_1", email: "[email protected]", workspaceId: "ws_1", user: { isBot: false } }
+ })
+
+ const wrapped = withCommunityActor(handler)
+
+ it("resolves a crk_ bearer to a bot actor (kind:bot, userId=botUserId)", async () => {
+ mockResolveBotActor.mockResolvedValue({
+ kind: "bot",
+ actor: { botUserId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" },
+ })
+ const res = await wrapped(bearer("Bearer crk_abc"))
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as { actor: CommunityActor }
+ expect(body.actor).toEqual({ kind: "bot", userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" })
+ })
+
+ it("a crk_ bearer that fails to resolve returns the error response and NEVER falls through to human", async () => {
+ mockResolveBotActor.mockResolvedValue({
+ kind: "error",
+ response: NextResponse.json({ error: "runner key revoked or unknown" }, { status: 401 }),
+ })
+ const res = await wrapped(bearer("Bearer crk_bad"))
+ expect(res.status).toBe(401)
+ expect(await res.json()).toEqual({ error: "runner key revoked or unknown" })
+ // The human path must not have run — handler saw no human actor.
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it("routes a session request (no bearer) to the human path via withAuth", async () => {
+ const res = await wrapped(new NextRequest("http://localhost/x"))
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as { actor: CommunityActor }
+ expect(body.actor).toEqual({ kind: "human", userId: "human_1", email: "[email protected]", workspaceId: "ws_1" })
+ // Bot resolution must not have been attempted for a non-crk_ request.
+ expect(mockResolveBotActor).not.toHaveBeenCalled()
+ })
+
+ it("routes an al_ machine-token bearer to the human path (not the bot path)", async () => {
+ const res = await wrapped(bearer("Bearer al_machinetoken"))
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as { actor: CommunityActor }
+ expect(body.actor.kind).toBe("human")
+ expect(mockResolveBotActor).not.toHaveBeenCalled()
+ })
+
+ it("propagates a human auth failure from withAuth unchanged", async () => {
+ mockHumanCtx = null // simulate withAuth 401
+ const res = await wrapped(new NextRequest("http://localhost/x"))
+ expect(res.status).toBe(401)
+ expect(handler).not.toHaveBeenCalled()
+ })
+})
+
+describe("rejectBot / requireBot guards", () => {
+ const human: CommunityActor = { kind: "human", userId: "h", email: "e" }
+ const bot: CommunityActor = { kind: "bot", userId: "b", ownerUserId: "o", machineId: "m" }
+
+ it("rejectBot: 403 for a bot, null for a human", () => {
+ expect(rejectBot(bot)?.status).toBe(403)
+ expect(rejectBot(human)).toBeNull()
+ })
+
+ it("requireBot: 403 for a human, null for a bot", () => {
+ expect(requireBot(human)?.status).toBe(403)
+ expect(requireBot(bot)).toBeNull()
+ })
+})
diff --git a/src/web/src/lib/middleware/community-actor.ts b/src/web/src/lib/middleware/community-actor.ts
new file mode 100644
index 000000000..cfe33f8da
--- /dev/null
+++ b/src/web/src/lib/middleware/community-actor.ts
@@ -0,0 +1,152 @@
+import { NextRequest, NextResponse } from "next/server"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { getDb } from "@/lib/db"
+import { withAuth, type AuthContext } from "./auth"
+import { resolveBotActor } from "./community-agent-runner-auth"
+
+/**
+ * The unified community actor — the single identity a `/api/community/*` route
+ * handler runs as, whether the caller is a signed-in human (Better-Auth session
+ * or `al_` machine token) or a bot (a `crk_` runner key). It fuses the two
+ * pre-existing wrappers (`withAuth` for humans, `withAgentRunnerAuth` for bots)
+ * behind one decorator so a route can serve both callers and branch on
+ * `actor.kind` for the few genuinely bot-specific semantics (channel-alignment
+ * gate on send, invite owner-gate on join) — see
+ * plans/22-community-unified-actor-route-unify.md.
+ *
+ * Discriminated on `kind` (NOT a flat `isBot` boolean): the semantic branches
+ * read `actor.kind === "bot"` and, in that arm, `ownerUserId`/`machineId` are
+ * present without a non-null assertion. `userId` is common to both arms — for a
+ * bot it IS the bot's own user id ("bots are users"), so an unbranched handler
+ * that only reads `actor.userId` works identically for either caller.
+ */
+export type CommunityActor =
+ | {
+ kind: "human"
+ userId: string
+ email: string
+ /** Present on the `al_`/session human path; absent for a bot. */
+ workspaceId?: string
+ }
+ | {
+ kind: "bot"
+ /** The bot's OWN user id (`= botUserId`). */
+ userId: string
+ /** The bot's OWNER (the human who minted the runner key). */
+ ownerUserId: string
+ machineId: string
+ }
+
+export interface CommunityActorContext {
+ env: Env
+ actor: CommunityActor
+ params?: Record<string, string>
+}
+
+export type CommunityActorHandler = (
+ req: NextRequest,
+ ctx: CommunityActorContext,
+) => Promise<NextResponse | Response>
+
+/**
+ * Wrap a `/api/community/*` route handler with unified actor resolution.
+ *
+ * Auth routing (by the `Authorization` header):
+ * - `Bearer crk_…` → bot path: resolve via the shared `resolveBotActor`.
+ * A `crk_` bearer that FAILS to resolve returns its 401/503 and NEVER
+ * falls through to the human path (a malformed bot token must not be
+ * retried as an anonymous human — that would leak the human 401 shape and
+ * mask a revoked key).
+ * - anything else → human path: delegated VERBATIM to `withAuth`, reusing its
+ * machine-token KV cache, Better-Auth session guard (bot-session rejection,
+ * soft-delete check), and Set-Cookie refresh untouched. The human
+ * `AuthContext` is adapted into `{ kind: "human", … }`.
+ *
+ * A bot request never pays the session-validation cost; a human never hits the
+ * runner-key lookups.
+ */
+export function withCommunityActor(handler: CommunityActorHandler) {
+ return async (
+ req: NextRequest,
+ context?: { params?: Promise<Record<string, string>> | Record<string, string> },
+ ): Promise<NextResponse | Response> => {
+ const resolvedParams = context?.params
+ ? context.params instanceof Promise
+ ? await context.params
+ : context.params
+ : undefined
+
+ const authHeader = req.headers.get("Authorization")
+
+ // Bot path — only when a crk_ bearer is actually present. `resolveBotActor`
+ // returns `not_bot` for any other header (including an `al_` machine token
+ // or a session cookie), which we route to the human `withAuth` path below.
+ if (authHeader?.startsWith("Bearer ") && authHeader.slice(7).trim().startsWith("crk_")) {
+ const { env } = await getCloudflareContext({ async: true })
+ const cloudflareEnv = env as Env
+ const db = getDb(cloudflareEnv.DB)
+
+ const resolved = await resolveBotActor(db, authHeader)
+ if (resolved.kind === "error") return resolved.response
+ // A crk_ bearer that resolves to `not_bot` is unreachable (the guard above
+ // guarantees the crk_ prefix), but treat it as an auth failure rather than
+ // silently falling through to the human path.
+ if (resolved.kind === "not_bot") {
+ return NextResponse.json({ error: "invalid runner key" }, { status: 401 })
+ }
+
+ return handler(req, {
+ env: cloudflareEnv,
+ actor: {
+ kind: "bot",
+ userId: resolved.actor.botUserId,
+ ownerUserId: resolved.actor.ownerUserId,
+ machineId: resolved.actor.machineId,
+ },
+ params: resolvedParams,
+ })
+ }
+
+ // Human path — delegate verbatim to withAuth, adapting its AuthContext into
+ // the unified actor. withAuth owns all human auth behavior (KV cache,
+ // session guard, Set-Cookie refresh); we do not reimplement any of it.
+ const delegated = withAuth(async (r, humanCtx: AuthContext & { params?: Record<string, string> }) => {
+ return handler(r, {
+ env: humanCtx.env,
+ actor: {
+ kind: "human",
+ userId: humanCtx.userId,
+ email: humanCtx.email,
+ workspaceId: humanCtx.workspaceId,
+ },
+ params: humanCtx.params,
+ })
+ })
+ return delegated(req, context)
+ }
+}
+
+/**
+ * Guard for a route (or branch) that a bot must NEVER reach — the privilege-
+ * escalation red line (`/bots/*`, `/daemon/*`, human management surfaces) and
+ * the human side of a bot-only verb. Returns a 403 `NextResponse` when the
+ * actor is a bot, else `null` (proceed). Enforced by the actor's authz, not by
+ * "no one calls it".
+ */
+export function rejectBot(actor: CommunityActor): NextResponse | null {
+ if (actor.kind === "bot") {
+ return NextResponse.json({ error: "forbidden: not available to bots" }, { status: 403 })
+ }
+ return null
+}
+
+/**
+ * Symmetric guard for a bot-only verb (inboxPull/inboxSnapshot/ack/nap, and
+ * resolve as a bot op): a human actor → 403 (capability symmetry, Gener #116).
+ */
+export function requireBot(actor: CommunityActor): NextResponse | null {
+ if (actor.kind !== "bot") {
+ return NextResponse.json({ error: "forbidden: bot-only endpoint" }, { status: 403 })
+ }
+ return null
+}
diff --git a/src/web/src/lib/middleware/community-agent-runner-auth.ts b/src/web/src/lib/middleware/community-agent-runner-auth.ts
index 4f7a84da7..ee68033c4 100644
--- a/src/web/src/lib/middleware/community-agent-runner-auth.ts
+++ b/src/web/src/lib/middleware/community-agent-runner-auth.ts
@@ -1,10 +1,23 @@
import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { queries, withD1Retry, createLogger } from "@alook/shared"
+import type { Database } from "@alook/shared"
import { getDb } from "@/lib/db"
const log = createLogger({ service: "community-agent-runner-auth" })
+/**
+ * The bot identity resolved from a `crk_` runner key — the BOT's own user id,
+ * its OWNER's user id, and the machine it's bound to. Shared by both
+ * `withAgentRunnerAuth` (the legacy `/agent/*` wrapper) and the unified
+ * `withCommunityActor` (see community-actor.ts).
+ */
+export interface ResolvedBotActor {
+ botUserId: string
+ ownerUserId: string
+ machineId: string
+}
+
interface AgentRunnerAuthContext {
env: Env
/** The BOT's own user id — `row.agentId` from `findActiveAgentRunnerKeyByBearer`. */
@@ -48,23 +61,91 @@ async function lookupOr503<T>(
}
/**
- * Agent-runner auth middleware for the CLI bridge (`/api/community/agent/*`).
- * Requires `Authorization: Bearer crk_…`. Cloned from `withCommunityDaemonAuth`
- * but needs BOTH a bot identity and an owner identity — both come off the
- * single `findActiveAgentRunnerKeyByBearer` row, no extra DB call required.
+ * Resolve a `crk_` runner-key bearer to a bot identity, shared by
+ * `withAgentRunnerAuth` and the unified `withCommunityActor`. Returns a
+ * 3-variant discriminant:
+ * - `{ kind: "bot", actor }` — a valid runner key; `actor` is the resolved
+ * {botUserId, ownerUserId, machineId}.
+ * - `{ kind: "not_bot" }` — no `Bearer crk_…` header at all; the caller
+ * MAY fall through to another auth path
+ * (this is how `withCommunityActor` routes a
+ * human request to `withAuth`).
+ * - `{ kind: "error", response }` — a `crk_` bearer that failed to resolve
+ * (bad/revoked key, bot inactive, binding
+ * mismatch → 401; transient D1 → 503). NEVER
+ * falls through — a malformed bot token must
+ * not be silently retried as a human.
*
- * Field mapping (do not invert): `row.userId` is the bot's OWNER;
- * `row.agentId` is the BOT's own user id. `row.doName` here is the runner
- * key's own DO-hash, unrelated to wake dispatch — never threaded through.
+ * Field mapping (do not invert): `row.userId` is the bot's OWNER; `row.agentId`
+ * is the BOT's own user id. `row.doName` is the runner key's own DO-hash,
+ * unrelated to wake dispatch — never threaded through.
*
* D1-transient failure semantics: each of the 3 D1 reads runs through
* `withD1Retry`; on retry-exhaust we return 503 + `Retry-After: 1` (RFC 9110
- * §15.6.4). What that buys us: 401 is reserved for real auth failures (bad
- * token, revoked runner key, bot deleted, binding mismatch) — so a
- * transient D1 blip surfaces as "temporarily unavailable" and does NOT
- * trip the CLI's runner-key rotation path (which is only ever driven by
- * 401). The CLI itself does not auto-retry on 503 today; the bot's next
- * wake naturally re-issues the command against a healthy D1.
+ * §15.6.4). 401 is reserved for real auth failures (bad token, revoked runner
+ * key, bot deleted, binding mismatch) — so a transient D1 blip surfaces as
+ * "temporarily unavailable" and does NOT trip the CLI's runner-key rotation
+ * path (only ever driven by 401).
+ */
+export async function resolveBotActor(
+ db: Database,
+ authHeader: string | null,
+): Promise<
+ | { kind: "bot"; actor: ResolvedBotActor }
+ | { kind: "not_bot" }
+ | { kind: "error"; response: NextResponse }
+> {
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
+ return { kind: "not_bot" }
+ }
+ const raw = authHeader.slice(7).trim()
+ if (!raw.startsWith("crk_")) {
+ return { kind: "not_bot" }
+ }
+
+ const rowLookup = await lookupOr503("findActiveAgentRunnerKeyByBearer", () =>
+ queries.communityMachine.findActiveAgentRunnerKeyByBearer(db, raw),
+ )
+ if (!rowLookup.ok) return { kind: "error", response: rowLookup.response }
+ const row = rowLookup.value
+ if (!row) {
+ return { kind: "error", response: NextResponse.json({ error: "runner key revoked or unknown" }, { status: 401 }) }
+ }
+
+ const botLookup = await lookupOr503("getUserInternal", () =>
+ queries.user.getUserInternal(db, row.agentId),
+ )
+ if (!botLookup.ok) return { kind: "error", response: botLookup.response }
+ const botUser = botLookup.value
+ if (!botUser || !botUser.isBot || botUser.deletedAt !== null) {
+ return { kind: "error", response: NextResponse.json({ error: "bot not found or inactive" }, { status: 401 }) }
+ }
+
+ const bindingLookup = await lookupOr503("getBotBinding", () =>
+ queries.communityBot.getBotBinding(db, row.agentId),
+ )
+ if (!bindingLookup.ok) return { kind: "error", response: bindingLookup.response }
+ const binding = bindingLookup.value
+ if (!binding || binding.machineId !== row.machineId) {
+ return { kind: "error", response: NextResponse.json({ error: "bot binding mismatch" }, { status: 401 }) }
+ }
+
+ return {
+ kind: "bot",
+ actor: { botUserId: row.agentId, ownerUserId: row.userId, machineId: row.machineId },
+ }
+}
+
+/**
+ * Agent-runner auth middleware for the CLI bridge (`/api/community/agent/*`).
+ * Requires `Authorization: Bearer crk_…`. Now a thin adapter over the shared
+ * `resolveBotActor` — behavior is unchanged: a missing/non-`crk_` bearer 401s
+ * here (this wrapper is bot-only, so `not_bot` maps to the same 401 the old
+ * inline check returned).
+ *
+ * NOTE (migration): this wrapper stays live until the last `/agent/*` route is
+ * moved onto `withCommunityActor`; then it and the `/agent` tree are deleted
+ * together. See plans/22-community-unified-actor-route-unify.md §9.
*/
export function withAgentRunnerAuth(handler: AgentRunnerAuthenticatedHandler) {
return async (
@@ -78,11 +159,13 @@ export function withAgentRunnerAuth(handler: AgentRunnerAuthenticatedHandler) {
: undefined
const authHeader = req.headers.get("Authorization")
+ // Preserve the old messages: a missing/malformed Bearer vs a non-crk_
+ // bearer 401'd with distinct copy. `resolveBotActor` collapses both to
+ // `not_bot`, so re-derive the specific 401 here (bot-only wrapper).
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return NextResponse.json({ error: "missing or malformed Authorization header" }, { status: 401 })
}
- const raw = authHeader.slice(7).trim()
- if (!raw.startsWith("crk_")) {
+ if (!authHeader.slice(7).trim().startsWith("crk_")) {
return NextResponse.json({ error: "invalid runner key" }, { status: 401 })
}
@@ -90,38 +173,19 @@ export function withAgentRunnerAuth(handler: AgentRunnerAuthenticatedHandler) {
const cloudflareEnv = env as Env
const db = getDb(cloudflareEnv.DB)
- const rowLookup = await lookupOr503("findActiveAgentRunnerKeyByBearer", () =>
- queries.communityMachine.findActiveAgentRunnerKeyByBearer(db, raw),
- )
- if (!rowLookup.ok) return rowLookup.response
- const row = rowLookup.value
- if (!row) {
- return NextResponse.json({ error: "runner key revoked or unknown" }, { status: 401 })
- }
-
- const botLookup = await lookupOr503("getUserInternal", () =>
- queries.user.getUserInternal(db, row.agentId),
- )
- if (!botLookup.ok) return botLookup.response
- const botUser = botLookup.value
- if (!botUser || !botUser.isBot || botUser.deletedAt !== null) {
- return NextResponse.json({ error: "bot not found or inactive" }, { status: 401 })
- }
-
- const bindingLookup = await lookupOr503("getBotBinding", () =>
- queries.communityBot.getBotBinding(db, row.agentId),
- )
- if (!bindingLookup.ok) return bindingLookup.response
- const binding = bindingLookup.value
- if (!binding || binding.machineId !== row.machineId) {
- return NextResponse.json({ error: "bot binding mismatch" }, { status: 401 })
+ const resolved = await resolveBotActor(db, authHeader)
+ if (resolved.kind === "error") return resolved.response
+ // `not_bot` is unreachable here (the crk_ guard above already returned), but
+ // handle it defensively as the same 401 the guard would have produced.
+ if (resolved.kind === "not_bot") {
+ return NextResponse.json({ error: "invalid runner key" }, { status: 401 })
}
return handler(req, {
env: cloudflareEnv,
- botUserId: row.agentId,
- ownerUserId: row.userId,
- machineId: row.machineId,
+ botUserId: resolved.actor.botUserId,
+ ownerUserId: resolved.actor.ownerUserId,
+ machineId: resolved.actor.machineId,
params: resolvedParams,
})
}