feat(phase-4a): groups sync + X-Project-Key header substrate
Foundational work for the upcoming group-scoped sharing feature.
Schema (migration 0003_groups.sql + drizzle schema):
- memory_access enum ('ro' | 'rw') reserved for Agent B's project_shares
- groups (id, oidc_iss, name, display_name, …) keyed by (oidc_iss, name)
so different IdPs can both have e.g. "platform" without colliding
- user_groups (user_id, group_id, synced_at) PK (user_id, group_id)
Auth (auth.ts + lib/auth/sync-groups.ts):
- jwt callback now syncs `profile.groups` after upserting the user
- syncUserGroupsFromClaim runs in a single tx: upserts each group,
inserts new memberships, deletes ones no longer in the claim
- missing/empty claim → user has zero groups (wipe memberships)
- EntraID GUID-vs-name edge case: we treat whatever strings the claim
emits as names verbatim; groups overage (>200 groups → no claim)
is documented as unsupported in v1
UserContext + JWT (lib/mcp/context.ts, lib/auth/jwt.ts):
- AuthenticatedClaims.groups surfaced from verified JWT payload
- UserContext.groups: string[] — live from OIDC token claim, falls
back to DB snapshot for CLI (HMAC) tokens which carry no claim
- UserContext.defaultProjectKey: optional, set from header
MCP route (app/api/mcp/route.ts):
- reads X-Project-Key header, validates against ProjectKey Zod schema,
400 on invalid; empty/missing leaves defaultProjectKey undefined
- auto-upserts the header-supplied project so first-use works without
a separate project.identify call
Tools (lib/mcp/tools.ts):
- withDefaultProject helper injects ctx.defaultProjectKey when the
caller omits `project`. Per-tool defaultScope hint avoids breaking
snippet.put (user-scope default) while making memory.write
(project-scope default) honor the header
- applied to memory.write/list/search/update and all snippet.* tools
Web UI:
- /settings/groups debug page lists current memberships with synced_at
and a clear empty state pointing at README troubleshooting
- /settings/tokens grows a "Pin to project" dropdown; selected key is
baked into the generated `claude mcp add` snippet as
`--header "X-Project-Key: <key>"`. The JWT itself stays
identity-only — pinning is purely a UX shortcut
- settings landing page links to /settings/groups
- README troubleshooting bullet covers the empty-groups path for
Authentik / EntraID / Keycloak
Refactor:
- extracted resolveProjectId + upsertProject from memory-actions.ts
into lib/projects.ts so the MCP route can reuse upsertProject
Verification:
- pnpm typecheck clean
- SKIP_ENV_VALIDATION=true pnpm build clean; /settings/groups in route table
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ import {
|
||||
jsonb,
|
||||
uniqueIndex,
|
||||
index,
|
||||
primaryKey,
|
||||
customType,
|
||||
vector,
|
||||
varchar,
|
||||
@@ -37,6 +38,10 @@ const textArray = customType<{ data: string[]; driverData: string }>({
|
||||
export const memoryScope = pgEnum("memory_scope", ["project", "user"]);
|
||||
export const memoryVisibility = pgEnum("memory_visibility", ["private", "shared", "team"]);
|
||||
export const auditActor = pgEnum("audit_actor", ["mcp", "web", "system"]);
|
||||
// Reserved here so 0003 (this file's matching migration) owns it. Used
|
||||
// by Agent B's upcoming `project_shares` table to express RO vs RW
|
||||
// grants per shared group.
|
||||
export const memoryAccess = pgEnum("memory_access", ["ro", "rw"]);
|
||||
|
||||
// ---------- tables ----------
|
||||
|
||||
@@ -152,6 +157,43 @@ export const cliTokens = pgTable(
|
||||
}),
|
||||
);
|
||||
|
||||
export const groups = pgTable(
|
||||
"groups",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
// OIDC issuer this group originates from — pairs with `name` so two
|
||||
// IdPs can both have a "platform" group without collision.
|
||||
oidcIss: text("oidc_iss").notNull(),
|
||||
name: text("name").notNull(),
|
||||
// Optional human-friendly label. Most IdPs only emit names, so this
|
||||
// is usually NULL; reserved for future enrichment.
|
||||
displayName: text("display_name"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(t) => ({
|
||||
uniqueIssName: uniqueIndex("groups_iss_name_uq").on(t.oidcIss, t.name),
|
||||
}),
|
||||
);
|
||||
|
||||
export const userGroups = pgTable(
|
||||
"user_groups",
|
||||
{
|
||||
userId: uuid("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
groupId: uuid("group_id")
|
||||
.notNull()
|
||||
.references(() => groups.id, { onDelete: "cascade" }),
|
||||
// Refreshed on every sign-in that re-observes this membership.
|
||||
syncedAt: timestamp("synced_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(t) => ({
|
||||
pk: primaryKey({ columns: [t.userId, t.groupId] }),
|
||||
userIdx: index("user_groups_user_idx").on(t.userId),
|
||||
}),
|
||||
);
|
||||
|
||||
export const auditLog = pgTable(
|
||||
"audit_log",
|
||||
{
|
||||
@@ -188,3 +230,7 @@ export type CliToken = typeof cliTokens.$inferSelect;
|
||||
export type NewCliToken = typeof cliTokens.$inferInsert;
|
||||
export type AuditEntry = typeof auditLog.$inferSelect;
|
||||
export type NewAuditEntry = typeof auditLog.$inferInsert;
|
||||
export type Group = typeof groups.$inferSelect;
|
||||
export type NewGroup = typeof groups.$inferInsert;
|
||||
export type UserGroup = typeof userGroups.$inferSelect;
|
||||
export type NewUserGroup = typeof userGroups.$inferInsert;
|
||||
|
||||
Reference in New Issue
Block a user