feat: full plan execution - CI/CD, critical fixes, UX polish, secondary/advanced features, E2E + docs
Phase 0 (CI/CD): fix root typecheck to cover api+worker+web; reconcile migration story into idempotent db:migrate (db:sync + db:triggers); add Gitea Actions quality/deploy/smoke workflow; rewrite README/AGENTS/DEPLOY docs; add requireWorkspaceAccess + recordActivityForEntity conventions. Phase 1 (critical fixes): calendar delete + drag/resize DnD; canvas card CRUD + bulk save + debounced autosave; logout route; graph edge workspaceId derivation; real analytics endpoints (drop Math.random); task board droppable columns + reorder persistence; Tiptap notes editor with sanitized HTML rendering; remove insecure passkey auth; domain/owner scoping (IDOR) on all by-ID routes + search/ export/realtime scoping; command palette routing + agent mention fetch; agent activity SSE handler; graph fly-to with tracked positions. Phase 2 (UX polish): login on design system; Sonner toasts app-wide; shared Loading/Empty/Error state components; working density/sidebarPos/reduce-motion settings; Inter typography; consolidated status-colors lib; unified detail routes; dashboard sort/realtime/responsive fixes; mobile responsive; a11y (radiogroups, sanitized snippets, badge labels). Phase 3 (features): daily notes timezone fix + delete + autosave + mood/energy create; active-domain store + topbar picker; graph domain picker + navigable entity links; tag assign/remove UI + server-side tag filter; real CSV export + import validation; custom fields on tasks. Phase 4 (advanced): migrate job worker into apps/worker (webhook delivery with HMAC, recurring spawn, ai_dispatch disabled); webhook queue helper + entity event enqueuing + test endpoint fix; recurring scheduledJobs pipeline; agents CRUD + permission editing + activity filters; real notifications feed; MCP polish (validation, error codes, domain scoping, dead sql leftover). Phase 5 (E2E + docs): rewrite Playwright suite for the Vite SPA (15 specs, new auth helpers, chromium-only in CI); add ephemeral-Postgres e2e CI job; rewrite docs/API.md for the real Hono API.
This commit is contained in:
@@ -1,4 +1,21 @@
|
||||
import { db, sql, activityFeed } from "@project-e/db";
|
||||
import {
|
||||
db,
|
||||
sql,
|
||||
activityFeed,
|
||||
tasks,
|
||||
habits,
|
||||
projects,
|
||||
notes,
|
||||
canvases,
|
||||
dailyNotes,
|
||||
calendarEvents,
|
||||
webhooks,
|
||||
agents,
|
||||
customFields,
|
||||
dashboardWidgets,
|
||||
} from "@project-e/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { AnyPgColumn, AnyPgTable } from "drizzle-orm/pg-core";
|
||||
|
||||
export interface RecordActivityParams {
|
||||
actor: string;
|
||||
@@ -24,3 +41,79 @@ export async function recordActivity(params: RecordActivityParams): Promise<void
|
||||
const payload = JSON.stringify({ type: entityType, action, id: entityId, workspace_id: workspaceId });
|
||||
await sql`SELECT pg_notify('project_e_events', ${payload}::text)`;
|
||||
}
|
||||
|
||||
// ── recordActivityForEntity ────────────────────────────────────────────────────
|
||||
// Variant that derives the workspaceId from the entity itself when the caller
|
||||
// omits it. Keeps `recordActivity` unchanged so existing call sites compile as-is.
|
||||
|
||||
export interface RecordActivityForEntityParams {
|
||||
actor: string;
|
||||
action: string;
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
changes?: Record<string, unknown>;
|
||||
workspaceId?: string | null;
|
||||
}
|
||||
|
||||
interface EntityWorkspaceLookup {
|
||||
table: AnyPgTable;
|
||||
idColumn: AnyPgColumn;
|
||||
workspaceColumn: AnyPgColumn;
|
||||
}
|
||||
|
||||
// Maps an entityType (as recorded in activity_feed) to the table + column that
|
||||
// holds its owning workspace/domain. Tables with domain_id use that; webhooks
|
||||
// store it as workspace_id.
|
||||
const entityWorkspaceLookups: Record<string, EntityWorkspaceLookup> = {
|
||||
task: { table: tasks, idColumn: tasks.id, workspaceColumn: tasks.domainId },
|
||||
habit: { table: habits, idColumn: habits.id, workspaceColumn: habits.domainId },
|
||||
project: { table: projects, idColumn: projects.id, workspaceColumn: projects.domainId },
|
||||
note: { table: notes, idColumn: notes.id, workspaceColumn: notes.domainId },
|
||||
canvas: { table: canvases, idColumn: canvases.id, workspaceColumn: canvases.domainId },
|
||||
daily_note: { table: dailyNotes, idColumn: dailyNotes.id, workspaceColumn: dailyNotes.domainId },
|
||||
calendar_event: { table: calendarEvents, idColumn: calendarEvents.id, workspaceColumn: calendarEvents.domainId },
|
||||
webhook: { table: webhooks, idColumn: webhooks.id, workspaceColumn: webhooks.workspaceId },
|
||||
agent: { table: agents, idColumn: agents.id, workspaceColumn: agents.domainId },
|
||||
custom_field: { table: customFields, idColumn: customFields.id, workspaceColumn: customFields.domainId },
|
||||
dashboard_widget: { table: dashboardWidgets, idColumn: dashboardWidgets.id, workspaceColumn: dashboardWidgets.domainId },
|
||||
};
|
||||
|
||||
async function resolveEntityWorkspaceId(entityType: string, entityId: string): Promise<string | null> {
|
||||
const lookup = entityWorkspaceLookups[entityType];
|
||||
if (!lookup) return null;
|
||||
|
||||
const [row] = await db
|
||||
.select({ workspaceId: lookup.workspaceColumn })
|
||||
.from(lookup.table)
|
||||
.where(eq(lookup.idColumn, entityId))
|
||||
.limit(1);
|
||||
|
||||
// AnyPgColumn erases the concrete type, so the selected value is `unknown`.
|
||||
return (row?.workspaceId as string | undefined) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record an activity event, deriving the workspaceId from the entity when not
|
||||
* provided (or empty). Unknown entity types or unresolvable entities are logged
|
||||
* and skipped rather than crashing the request.
|
||||
*/
|
||||
export async function recordActivityForEntity(params: RecordActivityForEntityParams): Promise<void> {
|
||||
let workspaceId = params.workspaceId;
|
||||
|
||||
if (!workspaceId || workspaceId.trim() === "") {
|
||||
workspaceId = await resolveEntityWorkspaceId(params.entityType, params.entityId);
|
||||
if (!workspaceId) {
|
||||
console.warn(`[activity] Could not resolve workspace for ${params.entityType}:${params.entityId}; skipping activity`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await recordActivity({
|
||||
actor: params.actor,
|
||||
action: params.action,
|
||||
entityType: params.entityType,
|
||||
entityId: params.entityId,
|
||||
changes: params.changes,
|
||||
workspaceId,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@ import { createMiddleware } from "hono/factory";
|
||||
import type { Context, Next } from "hono";
|
||||
import { jwtVerify, SignJWT } from "jose";
|
||||
import { createHash } from "node:crypto";
|
||||
import { db, users, apiKeys } from "@project-e/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { db, users, apiKeys, domains } from "@project-e/db";
|
||||
import { and, asc, eq } from "drizzle-orm";
|
||||
|
||||
const AUTH_SECRET = new TextEncoder().encode(process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET || "fallback-secret-change-me");
|
||||
const COOKIE_NAME = "session";
|
||||
@@ -101,10 +101,44 @@ export async function requireAuth(c: Context): Promise<AuthUser> {
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function resolveActiveDomain(user: { id: string; email: string; name?: string | null }): Promise<{ id: string; name: string; created: boolean }> {
|
||||
const { domains } = await import("@project-e/db");
|
||||
const { asc } = await import("drizzle-orm");
|
||||
/**
|
||||
* Require access to a workspace (domain). Verifies the workspace exists and,
|
||||
* when a user is present on the context, that the user owns it.
|
||||
*
|
||||
* Ownership fallback: domain rows created before the ownership model was
|
||||
* introduced may have a NULL ownerId. For those rows we fall back to the
|
||||
* existence check only, so legacy data isn't locked out.
|
||||
*
|
||||
* @returns the domain row so callers can reuse it (id, name, slug, ownerId, …)
|
||||
* @throws AuthError 403 FORBIDDEN when workspaceId is missing/empty or not owned
|
||||
* @throws AuthError 404 NOT_FOUND when no such workspace exists
|
||||
*/
|
||||
export async function requireWorkspaceAccess(c: Context, workspaceId: string): Promise<typeof domains.$inferSelect> {
|
||||
if (!workspaceId || workspaceId.trim() === "") {
|
||||
throw new AuthError("Workspace ID is required", 403, "FORBIDDEN");
|
||||
}
|
||||
|
||||
const [domain] = await db
|
||||
.select()
|
||||
.from(domains)
|
||||
.where(eq(domains.id, workspaceId))
|
||||
.limit(1);
|
||||
|
||||
if (!domain) {
|
||||
throw new AuthError("Workspace not found", 404, "NOT_FOUND");
|
||||
}
|
||||
|
||||
const user = c.get("user");
|
||||
// Single-user/personal app: ownership is enforced when a user is known.
|
||||
// Rows with NULL ownerId (legacy) are allowed through the existence check above.
|
||||
if (user && domain.ownerId !== null && domain.ownerId !== user.id) {
|
||||
throw new AuthError("You do not have access to this workspace", 403, "FORBIDDEN");
|
||||
}
|
||||
|
||||
return domain;
|
||||
}
|
||||
|
||||
export async function resolveActiveDomain(user: { id: string; email: string; name?: string | null }): Promise<{ id: string; name: string; created: boolean }> {
|
||||
const [existing] = await db
|
||||
.select({ id: domains.id, name: domains.name })
|
||||
.from(domains)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { db, jobs, webhooks } from "@project-e/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
/**
|
||||
* Enqueue a single webhook delivery job for a specific webhook. Used directly by
|
||||
* the test endpoint and by `enqueueWebhooks` for every matching webhook. The
|
||||
* worker reads this job, signs the payload with the webhook secret, delivers it
|
||||
* via fetch, and records the delivery row.
|
||||
*/
|
||||
export async function enqueueWebhookDelivery({
|
||||
webhookId,
|
||||
event,
|
||||
entityType,
|
||||
entityId,
|
||||
data,
|
||||
workspaceId,
|
||||
}: {
|
||||
webhookId: string;
|
||||
event: string;
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
data?: Record<string, unknown>;
|
||||
workspaceId: string;
|
||||
}): Promise<void> {
|
||||
await db.insert(jobs).values({
|
||||
type: "webhook_delivery",
|
||||
payload: {
|
||||
webhook_id: webhookId,
|
||||
event,
|
||||
entity_type: entityType,
|
||||
entity_id: entityId,
|
||||
data: data ?? {},
|
||||
timestamp: new Date().toISOString(),
|
||||
workspace_id: workspaceId,
|
||||
},
|
||||
status: "pending",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue webhook deliveries for every active webhook in a workspace that
|
||||
* subscribes to the given event. Never throws — failures are logged and the
|
||||
* caller's request proceeds, matching the activity-feed behavior.
|
||||
*/
|
||||
export async function enqueueWebhooks({
|
||||
workspaceId,
|
||||
event,
|
||||
entityType,
|
||||
entityId,
|
||||
data,
|
||||
}: {
|
||||
workspaceId: string;
|
||||
event: string;
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
data?: Record<string, unknown>;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const activeWebhooks = await db.select()
|
||||
.from(webhooks)
|
||||
.where(and(eq(webhooks.workspaceId, workspaceId), eq(webhooks.active, true)));
|
||||
|
||||
const matches = activeWebhooks.filter((webhook) =>
|
||||
(webhook.events ?? []).includes(event)
|
||||
);
|
||||
|
||||
for (const webhook of matches) {
|
||||
await enqueueWebhookDelivery({
|
||||
webhookId: webhook.id,
|
||||
event,
|
||||
entityType,
|
||||
entityId,
|
||||
data,
|
||||
workspaceId,
|
||||
});
|
||||
}
|
||||
|
||||
if (matches.length > 0) {
|
||||
console.log(`[webhooks] Enqueued ${matches.length} delivery job(s) for ${entityType}.${event}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[webhooks] Failed to enqueue webhook deliveries for ${entityType}.${event}:`, error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user