diff --git a/src/author-dashboard.test.ts b/src/author-dashboard.test.ts deleted file mode 100644 index 9bcdbf19..00000000 --- a/src/author-dashboard.test.ts +++ /dev/null @@ -1,416 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { AuthorDashboardManager, type AuthorProfile } from "./author-dashboard.js"; - -describe("AuthorDashboardManager", () => { - describe("initialization", () => { - it("creates manager instance", () => { - const manager = new AuthorDashboardManager(); - assert(manager); - }); - - it("initializes with empty caches", () => { - const manager = new AuthorDashboardManager(); - assert.deepEqual(manager.getAuthorsCache(), []); - }); - }); - - describe("author management - CRUD", () => { - let manager: AuthorDashboardManager; - - beforeEach(() => { - manager = new AuthorDashboardManager(); - }); - - it("creates new author profile", async () => { - const author = await manager.createAuthor( - "user@example.com", - "John Doe", - ); - - assert(author.id); - assert.equal(author.email, "user@example.com"); - assert.equal(author.name, "John Doe"); - assert(author.created_at); - assert(author.updated_at); - }); - - it("creates author with optional data", async () => { - const author = await manager.createAuthor("user@example.com", "Jane", { - bio: "Plugin developer", - website: "https://example.com", - }); - - assert.equal(author.bio, "Plugin developer"); - assert.equal(author.website, "https://example.com"); - }); - - it("gets author profile by id", async () => { - const created = await manager.createAuthor( - "test@example.com", - "Test User", - ); - const retrieved = await manager.getAuthorProfile(created.id); - - assert(retrieved); - assert.equal(retrieved.id, created.id); - assert.equal(retrieved.email, "test@example.com"); - }); - - it("returns null for non-existent author", async () => { - const result = await manager.getAuthorProfile("non-existent"); - assert.equal(result, null); - }); - - it("updates author profile", async () => { - const author = await manager.createAuthor("user@example.com", "John"); - const updated = await manager.updateAuthorProfile(author.id, { - bio: "Updated bio", - }); - - assert(updated); - assert.equal(updated.bio, "Updated bio"); - assert.equal(updated.email, "user@example.com"); - assert(updated.updated_at >= author.updated_at); - }); - - it("returns null when updating non-existent author", async () => { - const result = await manager.updateAuthorProfile("non-existent", { - bio: "test", - }); - assert.equal(result, null); - }); - }); - - describe("author verification", () => { - let manager: AuthorDashboardManager; - - beforeEach(() => { - manager = new AuthorDashboardManager(); - }); - - it("verifies author with github id", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - const verified = await manager.verifyAuthor(author.id, "github123"); - - assert.equal(verified, true); - const updated = await manager.getAuthorProfile(author.id); - assert(updated?.verified_at); - assert.equal(updated?.github_id, "github123"); - }); - - it("marks author as publisher verified", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - await manager.verifyAuthor(author.id, "github123"); - const published = await manager.markPublisherVerified(author.id); - - assert.equal(published, true); - const updated = await manager.getAuthorProfile(author.id); - assert(updated?.verified_publisher_at); - }); - - it("cannot mark unverified author as publisher", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - const result = await manager.markPublisherVerified(author.id); - assert.equal(result, false); - }); - }); - - describe("analytics - aggregation", () => { - let manager: AuthorDashboardManager; - - beforeEach(() => { - manager = new AuthorDashboardManager(); - }); - - it("records plugin analytics", async () => { - await manager.recordPluginAnalytics("plugin/test", { - date: "2026-04-15", - downloads: 100, - ratings_count: 10, - avg_rating: 4.5, - install_success_rate: 95.5, - update_adoption_rate: 80, - }); - - const analytics = await manager.getPluginAnalytics( - "plugin/test", - new Date("2026-04-10"), - new Date("2026-04-20"), - ); - - assert.equal(analytics.length, 1); - assert.equal(analytics[0].downloads, 100); - }); - - it("filters analytics by date range", async () => { - await manager.recordPluginAnalytics("plugin/test", { - date: "2026-04-15", - downloads: 100, - ratings_count: 10, - avg_rating: 4.5, - install_success_rate: 95.5, - update_adoption_rate: 80, - }); - - await manager.recordPluginAnalytics("plugin/test", { - date: "2026-04-20", - downloads: 200, - ratings_count: 20, - avg_rating: 4.6, - install_success_rate: 96, - update_adoption_rate: 85, - }); - - const early = await manager.getPluginAnalytics( - "plugin/test", - new Date("2026-04-10"), - new Date("2026-04-16"), - ); - assert.equal(early.length, 1); - - const all = await manager.getPluginAnalytics( - "plugin/test", - new Date("2026-04-10"), - new Date("2026-04-30"), - ); - assert.equal(all.length, 2); - }); - - it("calculates author analytics summary", async () => { - const author = await manager.createAuthor( - "user@example.com", - "Author", - ); - - await manager.recordPluginAnalytics("plugin/one", { - date: "2026-04-15", - downloads: 100, - ratings_count: 10, - avg_rating: 4.5, - install_success_rate: 95.5, - update_adoption_rate: 80, - }); - - const summary = await manager.getAuthorAnalytics( - author.id, - new Date("2026-04-10"), - new Date("2026-04-20"), - ); - - assert(summary.total_downloads >= 0); - assert.equal(summary.avg_rating, 4.5); - assert.equal(summary.verified, false); - }); - - it("returns zero for non-existent author analytics", async () => { - const summary = await manager.getAuthorAnalytics( - "non-existent", - new Date("2026-04-10"), - new Date("2026-04-20"), - ); - - assert.equal(summary.total_downloads, 0); - assert.equal(summary.verified, false); - }); - - it("calculates total downloads", async () => { - await manager.recordPluginAnalytics("plugin/one", { - date: "2026-04-15", - downloads: 100, - ratings_count: 10, - avg_rating: 4.5, - install_success_rate: 95.5, - update_adoption_rate: 80, - }); - - const total = await manager.getTotalDownloads("any-author"); - assert(total > 0); - }); - - it("calculates average rating", async () => { - await manager.recordPluginAnalytics("plugin/one", { - date: "2026-04-15", - downloads: 100, - ratings_count: 10, - avg_rating: 4.5, - install_success_rate: 95.5, - update_adoption_rate: 80, - }); - - const avg = await manager.getAverageRating("any-author"); - assert.equal(avg, 4.5); - }); - }); - - describe("publishing workflow", () => { - let manager: AuthorDashboardManager; - - beforeEach(() => { - manager = new AuthorDashboardManager(); - }); - - it("starts publishing workflow", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - const workflow = await manager.startPublishing( - author.id, - "plugin/test", - "1.0.0", - ); - - assert(workflow); - assert.equal(workflow.plugin_id, "plugin/test"); - assert.equal(workflow.version, "1.0.0"); - assert.equal(workflow.status, "draft"); - }); - - it("returns null when starting workflow for non-existent author", async () => { - const workflow = await manager.startPublishing( - "non-existent", - "plugin/test", - "1.0.0", - ); - assert.equal(workflow, null); - }); - - it("retrieves publishing workflow", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - const created = await manager.startPublishing( - author.id, - "plugin/test", - "1.0.0", - ); - assert(created); - - const retrieved = await manager.getPublishingWorkflow(created.id); - assert(retrieved); - assert.equal(retrieved.plugin_id, "plugin/test"); - }); - - it("runs validation checks", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - const workflow = await manager.startPublishing( - author.id, - "plugin/test", - "1.0.0", - ); - assert(workflow); - - const result = await manager.runValidationChecks(workflow); - - assert.equal(result.passed, true); - assert(result.checks.length > 0); - assert(result.checks.every((c) => c.status === "pass")); - }); - - it("publishes version after validation", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - const workflow = await manager.startPublishing( - author.id, - "plugin/test", - "1.0.0", - ); - assert(workflow); - - await manager.runValidationChecks(workflow); - const published = await manager.publishVersion(workflow); - - assert.equal(published, true); - }); - }); - - describe("notifications", () => { - let manager: AuthorDashboardManager; - - beforeEach(() => { - manager = new AuthorDashboardManager(); - }); - - it("adds notification", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - const notification = await manager.addNotification( - author.id, - "review_submitted", - { plugin_id: "plugin/test", rating: 5 }, - ); - - assert(notification.id); - assert.equal(notification.author_id, author.id); - assert.equal(notification.type, "review_submitted"); - assert(notification.created_at); - }); - - it("retrieves author notifications", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - - await manager.addNotification(author.id, "review_submitted", { - plugin_id: "plugin/test", - }); - await manager.addNotification(author.id, "download_milestone", { - milestone: 1000, - }); - - const notifications = await manager.getNotifications(author.id); - assert.equal(notifications.length, 2); - }); - - it("marks notification as read", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - const notification = await manager.addNotification( - author.id, - "review_submitted", - {}, - ); - - const marked = await manager.markNotificationRead(notification.id); - assert.equal(marked, true); - - const retrieved = await manager.getNotifications(author.id); - assert(retrieved[0].read_at); - }); - - it("counts unread notifications", async () => { - const author = await manager.createAuthor("user@example.com", "User"); - - await manager.addNotification(author.id, "review_submitted", {}); - const n2 = await manager.addNotification(author.id, "download_milestone", {}); - await manager.markNotificationRead(n2.id); - - const unread = await manager.getUnreadCount(author.id); - assert.equal(unread, 1); - }); - - it("returns empty notifications for non-existent author", async () => { - const notifications = await manager.getNotifications("non-existent"); - assert.deepEqual(notifications, []); - }); - }); - - describe("cache methods", () => { - let manager: AuthorDashboardManager; - - beforeEach(() => { - manager = new AuthorDashboardManager(); - }); - - it("sets and gets authors cache", async () => { - const mockAuthors: AuthorProfile[] = [ - { - id: "1", - email: "test@example.com", - name: "Test", - created_at: "2026-04-15T00:00:00Z", - updated_at: "2026-04-15T00:00:00Z", - }, - ]; - - manager.setAuthorsCache(mockAuthors); - assert.deepEqual(manager.getAuthorsCache(), mockAuthors); - }); - - it("accepts empty cache", () => { - manager.setAuthorsCache([]); - assert.deepEqual(manager.getAuthorsCache(), []); - }); - }); -}); diff --git a/src/author-dashboard.ts b/src/author-dashboard.ts deleted file mode 100644 index bb2c0ae0..00000000 --- a/src/author-dashboard.ts +++ /dev/null @@ -1,348 +0,0 @@ -import { randomUUID } from "crypto"; - -export interface AuthorProfile { - id: string; - github_id?: string; - email: string; - name: string; - bio?: string; - website?: string; - verified_at?: string; - verified_publisher_at?: string; - profile_picture_url?: string; - created_at: string; - updated_at: string; -} - -export interface PluginAnalytics { - plugin_id: string; - date: string; - downloads: number; - ratings_count: number; - avg_rating: number; - install_success_rate: number; - update_adoption_rate: number; -} - -export interface ValidationCheck { - name: string; - status: "pending" | "pass" | "fail"; - message?: string; -} - -export interface PublishingWorkflow { - id: string; - plugin_id: string; - version: string; - status: "draft" | "validation" | "review" | "published"; - validation_checks: ValidationCheck[]; - created_at: string; -} - -export interface Notification { - id: string; - author_id: string; - type: string; - data: Record; - read_at?: string; - created_at: string; -} - -export interface AnalyticsSummary { - total_downloads: number; - total_plugins: number; - avg_rating: number; - verified: boolean; - lifetime_downloads: number; -} - -export interface ValidationResult { - passed: boolean; - checks: ValidationCheck[]; - errors: string[]; -} - -export class AuthorDashboardManager { - private authorsCache: AuthorProfile[] = []; - private analyticsCache: PluginAnalytics[] = []; - private workflowsCache: PublishingWorkflow[] = []; - private notificationsCache: Notification[] = []; - - // Author management - async createAuthor( - email: string, - name: string, - data?: Partial, - ): Promise { - const now = new Date().toISOString(); - const author: AuthorProfile = { - id: randomUUID(), - email, - name, - created_at: now, - updated_at: now, - ...data, - }; - - this.authorsCache.push(author); - return author; - } - - async getAuthorProfile(authorId: string): Promise { - const author = this.authorsCache.find((a) => a.id === authorId); - return author || null; - } - - async updateAuthorProfile( - authorId: string, - data: Partial, - ): Promise { - const author = this.authorsCache.find((a) => a.id === authorId); - if (!author) return null; - - const updated: AuthorProfile = { - ...author, - ...data, - updated_at: new Date().toISOString(), - id: author.id, // Preserve ID - email: author.email, // Preserve email - name: author.name, // Preserve name - created_at: author.created_at, // Preserve creation date - }; - - const idx = this.authorsCache.indexOf(author); - this.authorsCache[idx] = updated; - return updated; - } - - async verifyAuthor(authorId: string, github_id: string): Promise { - const author = await this.getAuthorProfile(authorId); - if (!author) return false; - - await this.updateAuthorProfile(authorId, { - github_id, - verified_at: new Date().toISOString(), - }); - - return true; - } - - async markPublisherVerified(authorId: string): Promise { - const author = await this.getAuthorProfile(authorId); - if (!author || !author.verified_at) return false; - - await this.updateAuthorProfile(authorId, { - verified_publisher_at: new Date().toISOString(), - }); - - return true; - } - - // Analytics - async recordPluginAnalytics( - pluginId: string, - analytics: Omit, - ): Promise { - this.analyticsCache.push({ - plugin_id: pluginId, - ...analytics, - }); - } - - async getPluginAnalytics( - pluginId: string, - from: Date, - to: Date, - ): Promise { - const fromStr = from.toISOString().split("T")[0]; - const toStr = to.toISOString().split("T")[0]; - - return this.analyticsCache.filter( - (a) => - a.plugin_id === pluginId && a.date >= fromStr && a.date <= toStr, - ); - } - - async getAuthorAnalytics( - authorId: string, - from: Date, - to: Date, - ): Promise { - const author = await this.getAuthorProfile(authorId); - if (!author) { - return { - total_downloads: 0, - total_plugins: 0, - avg_rating: 0, - verified: false, - lifetime_downloads: 0, - }; - } - - const fromStr = from.toISOString().split("T")[0]; - const toStr = to.toISOString().split("T")[0]; - - const relevantAnalytics = this.analyticsCache.filter( - (a) => a.date >= fromStr && a.date <= toStr, - ); - - const totalDownloads = relevantAnalytics.reduce( - (sum, a) => sum + a.downloads, - 0, - ); - const avgRating = - relevantAnalytics.length > 0 - ? relevantAnalytics.reduce((sum, a) => sum + a.avg_rating, 0) / - relevantAnalytics.length - : 0; - - return { - total_downloads: totalDownloads, - total_plugins: new Set(relevantAnalytics.map((a) => a.plugin_id)).size, - avg_rating: Math.round(avgRating * 100) / 100, - verified: !!author.verified_publisher_at, - lifetime_downloads: this.analyticsCache.reduce( - (sum, a) => sum + a.downloads, - 0, - ), - }; - } - - async getTotalDownloads(authorId: string): Promise { - return this.analyticsCache.reduce((sum) => sum + 1, 0); - } - - async getAverageRating(authorId: string): Promise { - if (this.analyticsCache.length === 0) return 0; - const avg = - this.analyticsCache.reduce((sum, a) => sum + a.avg_rating, 0) / - this.analyticsCache.length; - return Math.round(avg * 100) / 100; - } - - // Publishing workflow - async startPublishing( - authorId: string, - pluginId: string, - version: string, - ): Promise { - const author = await this.getAuthorProfile(authorId); - if (!author) return null; - - const workflow: PublishingWorkflow = { - id: randomUUID(), - plugin_id: pluginId, - version, - status: "draft", - validation_checks: [], - created_at: new Date().toISOString(), - }; - - this.workflowsCache.push(workflow); - return workflow; - } - - async getPublishingWorkflow(workflowId: string): Promise { - return this.workflowsCache.find((w) => w.id === workflowId) || null; - } - - async runValidationChecks( - workflow: PublishingWorkflow, - ): Promise { - const checks: ValidationCheck[] = [ - { name: "syntax-check", status: "pass" }, - { name: "tests-pass", status: "pass" }, - { name: "version-valid", status: "pass" }, - { name: "manifest-valid", status: "pass" }, - ]; - - const updatedWorkflow = { - ...workflow, - status: "validation" as const, - validation_checks: checks, - }; - - const idx = this.workflowsCache.indexOf(workflow); - if (idx >= 0) { - this.workflowsCache[idx] = updatedWorkflow; - } - - return { - passed: checks.every((c) => c.status === "pass"), - checks, - errors: [], - }; - } - - async publishVersion(workflow: PublishingWorkflow): Promise { - const idx = this.workflowsCache.findIndex((w) => w.id === workflow.id); - if (idx >= 0) { - this.workflowsCache[idx] = { - ...this.workflowsCache[idx], - status: "published" as const, - }; - return true; - } - - return false; - } - - // Notifications - async addNotification( - authorId: string, - type: string, - data: Record, - ): Promise { - const notification: Notification = { - id: randomUUID(), - author_id: authorId, - type, - data, - created_at: new Date().toISOString(), - }; - - this.notificationsCache.push(notification); - return notification; - } - - async getNotifications(authorId: string): Promise { - return this.notificationsCache.filter((n) => n.author_id === authorId); - } - - async markNotificationRead(notificationId: string): Promise { - const notification = this.notificationsCache.find( - (n) => n.id === notificationId, - ); - if (!notification) return false; - - notification.read_at = new Date().toISOString(); - return true; - } - - async getUnreadCount(authorId: string): Promise { - return this.notificationsCache.filter( - (n) => n.author_id === authorId && !n.read_at, - ).length; - } - - // Cache methods for testing - setAuthorsCache(authors: AuthorProfile[]): void { - this.authorsCache = authors; - } - - setAnalyticsCache(analytics: PluginAnalytics[]): void { - this.analyticsCache = analytics; - } - - setWorkflowsCache(workflows: PublishingWorkflow[]): void { - this.workflowsCache = workflows; - } - - setNotificationsCache(notifications: Notification[]): void { - this.notificationsCache = notifications; - } - - getAuthorsCache(): AuthorProfile[] { - return this.authorsCache; - } -} diff --git a/src/author-notifications.test.ts b/src/author-notifications.test.ts deleted file mode 100644 index 5143662f..00000000 --- a/src/author-notifications.test.ts +++ /dev/null @@ -1,452 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { AuthorNotificationEngine } from "./author-notifications.js"; - -// ─── Helpers ────────────────────────────────────────────────────────────────── - -// ─── Tests ──────────────────────────────────────────────────────────────────── - -describe("AuthorNotificationEngine", () => { - describe("initialization", () => { - it("creates engine instance", () => { - const engine = new AuthorNotificationEngine(); - assert(engine); - }); - - it("starts with empty caches", () => { - const engine = new AuthorNotificationEngine(); - assert.equal(engine.getNotificationsCache().size, 0); - assert.equal(engine.getPreferencesCache().size, 0); - assert.equal(engine.getDigestSettingsCache().size, 0); - }); - }); - - describe("createNotification", () => { - let engine: AuthorNotificationEngine; - - beforeEach(() => { - engine = new AuthorNotificationEngine(); - }); - - it("creates a notification", () => { - const notif = engine.createNotification( - "author-1", - "new_review", - "New review", - "User left a 5-star review", - ); - assert(notif.id); - assert.equal(notif.authorId, "author-1"); - assert.equal(notif.type, "new_review"); - assert.equal(notif.read, false); - }); - - it("includes plugin ID when provided", () => { - const notif = engine.createNotification( - "author-1", - "new_review", - "New review", - "Review message", - {}, - "plugin-stripe", - ); - assert.equal(notif.pluginId, "plugin-stripe"); - }); - - it("stores metadata", () => { - const metadata = { reviewerId: "user-123", rating: 5 }; - const notif = engine.createNotification( - "author-1", - "new_review", - "New review", - "Message", - metadata, - ); - assert.deepEqual(notif.metadata, metadata); - }); - - it("assigns channels based on notification type", () => { - const critical = engine.createNotification( - "author-1", - "security_alert", - "Security", - "Alert", - ); - assert(critical.channels.includes("in_app")); - assert(critical.channels.includes("email")); - - const nonCritical = engine.createNotification("author-1", "new_review", "Review", "Message"); - assert(nonCritical.channels.length > 0); - }); - - it("retrieves notification by ID", () => { - const created = engine.createNotification("author-1", "new_review", "Title", "Message"); - const found = engine.getNotification(created.id); - assert.equal(found?.id, created.id); - }); - - it("returns null for unknown notification", () => { - const notif = engine.getNotification("unknown"); - assert.equal(notif, null); - }); - }); - - describe("getAuthorNotifications", () => { - let engine: AuthorNotificationEngine; - - beforeEach(() => { - engine = new AuthorNotificationEngine(); - engine.createNotification("author-1", "new_review", "Review 1", "Message 1"); - engine.createNotification("author-1", "new_review", "Review 2", "Message 2"); - engine.createNotification("author-2", "new_review", "Review 3", "Message 3"); - }); - - it("returns all notifications for an author", () => { - const notifs = engine.getAuthorNotifications("author-1"); - assert.equal(notifs.length, 2); - assert(notifs.every((n) => n.authorId === "author-1")); - }); - - it("filters unread notifications", () => { - const allNotifs = engine.getAuthorNotifications("author-1"); - const unread = engine.getAuthorNotifications("author-1", true); - assert.equal(allNotifs.length, 2); - assert.equal(unread.length, 2); - - // Mark one as read - engine.markAsRead(allNotifs[0].id); - const stillUnread = engine.getAuthorNotifications("author-1", true); - assert.equal(stillUnread.length, 1); - }); - - it("sorts by creation date (newest first)", () => { - const notifs = engine.getAuthorNotifications("author-1"); - for (let i = 1; i < notifs.length; i++) { - assert( - new Date(notifs[i - 1].createdAt) >= new Date(notifs[i].createdAt), - ); - } - }); - - it("respects limit parameter", () => { - for (let i = 0; i < 30; i++) { - engine.createNotification("author-1", "new_review", `Review ${i}`, "Message"); - } - const notifs = engine.getAuthorNotifications("author-1", false, 10); - assert(notifs.length <= 10); - }); - - it("returns empty for unknown author", () => { - const notifs = engine.getAuthorNotifications("unknown"); - assert.equal(notifs.length, 0); - }); - }); - - describe("markAsRead", () => { - let engine: AuthorNotificationEngine; - - beforeEach(() => { - engine = new AuthorNotificationEngine(); - }); - - it("marks notification as read", () => { - const notif = engine.createNotification("author-1", "new_review", "Title", "Message"); - assert(!notif.read); - - const marked = engine.markAsRead(notif.id); - assert(marked?.read); - assert(marked?.readAt); - }); - - it("returns null for unknown notification", () => { - const result = engine.markAsRead("unknown"); - assert.equal(result, null); - }); - - it("markMultipleAsRead marks all unread", () => { - engine.createNotification("author-1", "new_review", "1", "Message 1"); - engine.createNotification("author-1", "new_review", "2", "Message 2"); - engine.createNotification("author-1", "new_review", "3", "Message 3"); - - const count = engine.markMultipleAsRead("author-1"); - assert.equal(count, 3); - - const remaining = engine.getAuthorNotifications("author-1", true); - assert.equal(remaining.length, 0); - }); - }); - - describe("deleteNotification", () => { - let engine: AuthorNotificationEngine; - - beforeEach(() => { - engine = new AuthorNotificationEngine(); - }); - - it("deletes a notification", () => { - const notif = engine.createNotification("author-1", "new_review", "Title", "Message"); - const deleted = engine.deleteNotification(notif.id); - assert(deleted); - assert.equal(engine.getNotification(notif.id), null); - }); - - it("returns false for unknown notification", () => { - const deleted = engine.deleteNotification("unknown"); - assert(!deleted); - }); - }); - - describe("notification preferences", () => { - let engine: AuthorNotificationEngine; - - beforeEach(() => { - engine = new AuthorNotificationEngine(); - }); - - it("sets notification preference", () => { - const pref = engine.setPreference("author-1", "new_review", ["in_app", "email"], true); - assert.equal(pref.authorId, "author-1"); - assert.equal(pref.notificationType, "new_review"); - assert(pref.enabled); - }); - - it("disables notification type", () => { - engine.disableNotificationType("author-1", "new_review"); - const pref = engine.getPreference("author-1", "new_review"); - assert(!pref?.enabled); - }); - - it("enables notification type", () => { - engine.enableNotificationType("author-1", "new_review", ["in_app"]); - const pref = engine.getPreference("author-1", "new_review"); - assert(pref?.enabled); - }); - - it("gets author preferences", () => { - engine.setPreference("author-1", "new_review", ["in_app"], true); - engine.setPreference("author-1", "security_alert", ["email"], true); - const prefs = engine.getAuthorPreferences("author-1"); - assert(prefs.length >= 2); - }); - - it("returns null for unknown preference", () => { - const pref = engine.getPreference("author-1", "new_review"); - assert.equal(pref, null); - }); - }); - - describe("digest settings", () => { - let engine: AuthorNotificationEngine; - - beforeEach(() => { - engine = new AuthorNotificationEngine(); - }); - - it("sets digest settings", () => { - const settings = engine.setDigestSettings( - "author-1", - "daily", - ["new_review", "download_milestone"], - undefined, - "09:00", - ); - assert.equal(settings.frequency, "daily"); - assert.equal(settings.preferredTime, "09:00"); - }); - - it("includes preferred day for weekly digest", () => { - const settings = engine.setDigestSettings( - "author-1", - "weekly", - ["new_review"], - 1, // Monday - ); - assert.equal(settings.preferredDay, 1); - }); - - it("retrieves digest settings", () => { - engine.setDigestSettings("author-1", "daily", ["new_review"]); - const found = engine.getDigestSettings("author-1"); - assert.equal(found?.frequency, "daily"); - }); - - it("returns null for unknown digest settings", () => { - const settings = engine.getDigestSettings("unknown"); - assert.equal(settings, null); - }); - }); - - describe("compileDigest", () => { - let engine: AuthorNotificationEngine; - - beforeEach(() => { - engine = new AuthorNotificationEngine(); - engine.setDigestSettings( - "author-1", - "daily", - ["new_review", "download_milestone"], - ); - }); - - it("compiles digest from queued entries", () => { - engine.createNotification("author-1", "new_review", "Review 1", "Message 1"); - engine.createNotification("author-1", "download_milestone", "Milestone", "100 downloads!"); - engine.createNotification("author-1", "security_alert", "Alert", "Alert"); // Not in includeTypes - - const digest = engine.compileDigest("author-1", "daily"); - assert(digest); - assert.equal(digest.totalCount, 2); // Only new_review and download_milestone - }); - - it("returns null if no pending entries", () => { - const digest = engine.compileDigest("author-1", "daily"); - assert.equal(digest, null); - }); - - it("returns null if frequency mismatch", () => { - engine.createNotification("author-1", "new_review", "Review", "Message"); - const digest = engine.compileDigest("author-1", "weekly"); // Settings are daily - assert.equal(digest, null); - }); - - it("clears queue after compilation", () => { - engine.createNotification("author-1", "new_review", "Review", "Message"); - engine.compileDigest("author-1", "daily"); - const pending = engine.getPendingDigestEntries("author-1"); - assert.equal(pending.length, 0); - }); - - it("includes unread count in digest", () => { - engine.createNotification("author-1", "new_review", "Review 1", "Msg 1"); - engine.createNotification("author-1", "new_review", "Review 2", "Msg 2"); - const digest = engine.compileDigest("author-1", "daily"); - assert(digest); - assert(digest.unreadCount > 0); - }); - - it("tracks last digest sent time", () => { - engine.createNotification("author-1", "new_review", "Review", "Message"); - engine.compileDigest("author-1", "daily"); - const lastTime = engine.getLastDigestTime("author-1"); - assert(lastTime); - assert(lastTime > new Date(Date.now() - 60000)); // Less than 1 minute ago - }); - }); - - describe("event-based notifications", () => { - let engine: AuthorNotificationEngine; - - beforeEach(() => { - engine = new AuthorNotificationEngine(); - }); - - it("notifyNewReview creates review notification", () => { - const notif = engine.notifyNewReview( - "author-1", - "plugin-stripe", - "user-reviewer", - 5, - "Great plugin!", - ); - assert.equal(notif.type, "new_review"); - assert(notif.message.includes("5★")); - assert.equal(notif.pluginId, "plugin-stripe"); - }); - - it("notifyDownloadMilestone for valid milestone", () => { - const notif = engine.notifyDownloadMilestone("author-1", "plugin-stripe", 1000); - assert(notif); - assert.equal(notif.type, "download_milestone"); - assert(notif.message.includes("1000")); - }); - - it("notifyDownloadMilestone returns null for non-milestone number", () => { - const notif = engine.notifyDownloadMilestone("author-1", "plugin-stripe", 999); - assert.equal(notif, null); - }); - - it("notifySecurityAlert includes severity", () => { - const notif = engine.notifySecurityAlert( - "author-1", - "plugin-stripe", - "XSS vulnerability", - "high", - ); - assert.equal(notif.type, "security_alert"); - assert(notif.message.includes("HIGH")); - }); - - it("notifyRatingThreshold triggers on low rating", () => { - const notif = engine.notifyRatingThreshold("author-1", "plugin-stripe", 3.5, 4.0); - assert(notif); - assert.equal(notif.type, "rating_threshold"); - assert(notif.message.includes("3.5")); - }); - - it("notifyRatingThreshold returns null if above threshold", () => { - const notif = engine.notifyRatingThreshold("author-1", "plugin-stripe", 4.5, 4.0); - assert.equal(notif, null); - }); - - it("notifyDependencyUpdate creates notification", () => { - const notif = engine.notifyDependencyUpdate( - "author-1", - "plugin-stripe", - "@stripe/api", - "1.2.3", - ); - assert.equal(notif.type, "dependency_update"); - assert(notif.message.includes("1.2.3")); - }); - - it("notifyCommunityDigest creates digest notification", () => { - engine.setDigestSettings("author-1", "daily", ["new_review"]); - engine.createNotification("author-1", "new_review", "Review", "Message"); - const digest = engine.compileDigest("author-1", "daily"); - - if (digest) { - const notif = engine.notifyCommunityDigest("author-1", digest); - assert.equal(notif.type, "community_digest"); - assert(notif.message.includes("updates")); - } - }); - }); - - describe("notification statistics", () => { - let engine: AuthorNotificationEngine; - - beforeEach(() => { - engine = new AuthorNotificationEngine(); - }); - - it("counts total notifications", () => { - engine.createNotification("author-1", "new_review", "1", "Msg"); - engine.createNotification("author-1", "new_review", "2", "Msg"); - engine.createNotification("author-1", "security_alert", "Alert", "Msg"); - - const stats = engine.getNotificationStats("author-1"); - assert.equal(stats.totalNotifications, 3); - }); - - it("counts unread notifications", () => { - const n1 = engine.createNotification("author-1", "new_review", "1", "Msg"); - engine.createNotification("author-1", "new_review", "2", "Msg"); - - engine.markAsRead(n1.id); - const stats = engine.getNotificationStats("author-1"); - assert.equal(stats.unreadCount, 1); - assert.equal(stats.byStatus.read, 1); - assert.equal(stats.byStatus.unread, 1); - }); - - it("counts by notification type", () => { - engine.createNotification("author-1", "new_review", "Review", "Msg"); - engine.createNotification("author-1", "new_review", "Review 2", "Msg"); - engine.createNotification("author-1", "security_alert", "Alert", "Msg"); - - const stats = engine.getNotificationStats("author-1"); - assert.equal(stats.byType.new_review, 2); - assert.equal(stats.byType.security_alert, 1); - }); - }); -}); diff --git a/src/author-notifications.ts b/src/author-notifications.ts deleted file mode 100644 index 82668e5f..00000000 --- a/src/author-notifications.ts +++ /dev/null @@ -1,473 +0,0 @@ -import { IdGenerators } from "./id-generator.js"; -// ─── Types ──────────────────────────────────────────────────────────────────── - -export type NotificationType = - | "new_review" - | "new_rating" - | "download_milestone" - | "update_reminder" - | "security_alert" - | "dependency_update" - | "plugin_published" - | "rating_threshold" - | "community_digest" - | "comment_reply"; - -export type NotificationChannel = "in_app" | "email" | "digest"; -export type DigestFrequency = "daily" | "weekly" | "monthly" | "off"; - -export interface Notification { - id: string; - authorId: string; - type: NotificationType; - pluginId?: string; - title: string; - message: string; - metadata: Record; - read: boolean; - channels: NotificationChannel[]; - createdAt: string; - readAt?: string; -} - -export interface NotificationPreference { - authorId: string; - notificationType: NotificationType; - channels: NotificationChannel[]; - enabled: boolean; - updatedAt: string; -} - -export interface DigestSettings { - authorId: string; - frequency: DigestFrequency; - preferredDay?: number; // 0=Sun, 6=Sat for weekly; day of month for monthly - preferredTime?: string; // HH:MM format - includeTypes: NotificationType[]; - updatedAt: string; -} - -export interface DigestEntry { - id: string; - title: string; - message: string; - type: NotificationType; - createdAt: string; -} - -export interface CompiledDigest { - authorId: string; - frequency: DigestFrequency; - period: string; // "2025-04-14 to 2025-04-20" - entries: DigestEntry[]; - totalCount: number; - unreadCount: number; - compiledAt: string; -} - -export interface NotificationStats { - totalNotifications: number; - unreadCount: number; - byType: Record; - byStatus: { read: number; unread: number }; -} - -export interface DownloadMilestoneEvent { - pluginId: string; - authorId: string; - milestone: number; // 100, 500, 1000, etc. - currentDownloads: number; - achievedAt: string; -} - -// ─── AuthorNotificationEngine ───────────────────────────────────────────────── - -export class AuthorNotificationEngine { - private notifications: Map = new Map(); - private preferences: Map = new Map(); - private digestSettings: Map = new Map(); - private digestQueue: Map = new Map(); // authorId → entries - private lastDigestSent: Map = new Map(); // authorId → ISO date - - // ─── Notification creation & management ──────────────────────────────────── - - /** - * Create and send a notification to an author. - */ - createNotification( - authorId: string, - type: NotificationType, - title: string, - message: string, - metadata: Record = {}, - pluginId?: string, - ): Notification { - const id = IdGenerators.notification(); - - // Get author's notification preference for this type - const prefKey = `${authorId}:${type}`; - const pref = this.preferences.get(prefKey) || this.getDefaultPreference(authorId, type); - - const notification: Notification = { - id, - authorId, - type, - pluginId, - title, - message, - metadata, - read: false, - channels: pref.channels, - createdAt: new Date().toISOString(), - }; - - this.notifications.set(id, notification); - - // Add to digest queue if digest is enabled - const digestSettings = this.digestSettings.get(authorId); - if (digestSettings && digestSettings.includeTypes.includes(type)) { - const queue = this.digestQueue.get(authorId) || []; - queue.push({ - id: notification.id, - title, - message, - type, - createdAt: notification.createdAt, - }); - this.digestQueue.set(authorId, queue); - } - - return notification; - } - - private getDefaultPreference(authorId: string, type: NotificationType): NotificationPreference { - // Default preferences: send critical alerts to in_app, others to digest - const criticalTypes: NotificationType[] = ["security_alert", "rating_threshold"]; - const channels: NotificationChannel[] = criticalTypes.includes(type) - ? ["in_app", "email"] - : ["in_app", "digest"]; - - return { - authorId, - notificationType: type, - channels, - enabled: true, - updatedAt: new Date().toISOString(), - }; - } - - getNotification(notificationId: string): Notification | null { - return this.notifications.get(notificationId) || null; - } - - getAuthorNotifications(authorId: string, unreadOnly = false, limit = 50): Notification[] { - return [...this.notifications.values()] - .filter((n) => n.authorId === authorId && (!unreadOnly || !n.read)) - .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()) - .slice(0, limit); - } - - markAsRead(notificationId: string): Notification | null { - const notif = this.notifications.get(notificationId); - if (!notif) return null; - notif.read = true; - notif.readAt = new Date().toISOString(); - return notif; - } - - markMultipleAsRead(authorId: string): number { - const authorsNotifs = this.getAuthorNotifications(authorId, true); - let count = 0; - for (const notif of authorsNotifs) { - notif.read = true; - notif.readAt = new Date().toISOString(); - count++; - } - return count; - } - - deleteNotification(notificationId: string): boolean { - return this.notifications.delete(notificationId); - } - - // ─── Notification preferences ───────────────────────────────────────────── - - /** - * Set notification preferences for an author and notification type. - */ - setPreference( - authorId: string, - type: NotificationType, - channels: NotificationChannel[], - enabled: boolean, - ): NotificationPreference { - const key = `${authorId}:${type}`; - const pref: NotificationPreference = { - authorId, - notificationType: type, - channels: enabled ? channels : [], - enabled, - updatedAt: new Date().toISOString(), - }; - this.preferences.set(key, pref); - return pref; - } - - getPreference(authorId: string, type: NotificationType): NotificationPreference | null { - const key = `${authorId}:${type}`; - return this.preferences.get(key) || null; - } - - getAuthorPreferences(authorId: string): NotificationPreference[] { - return [...this.preferences.values()].filter((p) => p.authorId === authorId); - } - - disableNotificationType(authorId: string, type: NotificationType): NotificationPreference { - return this.setPreference(authorId, type, [], false); - } - - enableNotificationType( - authorId: string, - type: NotificationType, - channels: NotificationChannel[] = ["in_app", "email"], - ): NotificationPreference { - return this.setPreference(authorId, type, channels, true); - } - - // ─── Digest management ───────────────────────────────────────────────────── - - /** - * Configure digest settings for an author. - */ - setDigestSettings( - authorId: string, - frequency: DigestFrequency, - types: NotificationType[], - preferredDay?: number, - preferredTime?: string, - ): DigestSettings { - const settings: DigestSettings = { - authorId, - frequency, - preferredDay, - preferredTime: preferredTime || "09:00", - includeTypes: types, - updatedAt: new Date().toISOString(), - }; - this.digestSettings.set(authorId, settings); - return settings; - } - - getDigestSettings(authorId: string): DigestSettings | null { - return this.digestSettings.get(authorId) || null; - } - - /** - * Compile a digest from queued entries. - */ - compileDigest(authorId: string, frequency: DigestFrequency): CompiledDigest | null { - const settings = this.digestSettings.get(authorId); - if (!settings || settings.frequency !== frequency) return null; - - const entries = this.digestQueue.get(authorId) || []; - if (entries.length === 0) return null; - - const unreadNotifs = this.getAuthorNotifications(authorId, true); - const unreadCount = unreadNotifs.length; - - // Determine period based on frequency - const now = new Date(); - let period = ""; - if (frequency === "daily") { - period = now.toISOString().split("T")[0]; - } else if (frequency === "weekly") { - const weekStart = new Date(now); - weekStart.setDate(now.getDate() - now.getDay()); - const weekEnd = new Date(weekStart); - weekEnd.setDate(weekStart.getDate() + 6); - period = `${weekStart.toISOString().split("T")[0]} to ${weekEnd.toISOString().split("T")[0]}`; - } else if (frequency === "monthly") { - period = now.toISOString().slice(0, 7); - } - - const digest: CompiledDigest = { - authorId, - frequency, - period, - entries: entries.slice(0, 100), // limit to 100 entries per digest - totalCount: entries.length, - unreadCount, - compiledAt: new Date().toISOString(), - }; - - this.lastDigestSent.set(authorId, new Date().toISOString()); - // Clear queue after compiling - this.digestQueue.set(authorId, []); - - return digest; - } - - getLastDigestTime(authorId: string): Date | null { - const time = this.lastDigestSent.get(authorId); - return time ? new Date(time) : null; - } - - getPendingDigestEntries(authorId: string): DigestEntry[] { - return this.digestQueue.get(authorId) || []; - } - - // ─── Event-based notifications ───────────────────────────────────────────── - - /** - * Send notification when a plugin receives a new review. - */ - notifyNewReview( - authorId: string, - pluginId: string, - reviewerId: string, - rating: number, - comment: string, - ): Notification { - return this.createNotification( - authorId, - "new_review", - `New review for your plugin`, - `${reviewerId} left a ${rating}★ review: "${comment.slice(0, 100)}..."`, - { reviewerId, rating, comment }, - pluginId, - ); - } - - /** - * Send notification on download milestones (100, 500, 1000, etc.). - */ - notifyDownloadMilestone( - authorId: string, - pluginId: string, - currentDownloads: number, - ): Notification | null { - const milestones = [100, 500, 1000, 5000, 10000, 50000, 100000]; - const milestone = milestones.find((m) => m === currentDownloads); - - if (!milestone) return null; - - return this.createNotification( - authorId, - "download_milestone", - `🎉 Milestone reached!`, - `Your plugin has reached ${milestone} downloads!`, - { milestone, currentDownloads }, - pluginId, - ); - } - - /** - * Send security alert for vulnerabilities. - */ - notifySecurityAlert( - authorId: string, - pluginId: string, - vulnerability: string, - severity: "low" | "medium" | "high" | "critical", - ): Notification { - return this.createNotification( - authorId, - "security_alert", - `⚠️ Security alert`, - `${severity.toUpperCase()}: ${vulnerability}. Please review and update.`, - { vulnerability, severity }, - pluginId, - ); - } - - /** - * Send notification when rating drops below threshold. - */ - notifyRatingThreshold( - authorId: string, - pluginId: string, - currentRating: number, - threshold: number, - ): Notification | null { - if (currentRating >= threshold) return null; - - return this.createNotification( - authorId, - "rating_threshold", - `Rating alert`, - `Your plugin's rating dropped to ${currentRating.toFixed(1)}★ (threshold: ${threshold}★)`, - { currentRating, threshold }, - pluginId, - ); - } - - /** - * Send notification for dependency updates available. - */ - notifyDependencyUpdate( - authorId: string, - pluginId: string, - dependency: string, - newVersion: string, - ): Notification { - return this.createNotification( - authorId, - "dependency_update", - `Dependency update available`, - `${dependency} has a new version: ${newVersion}. Consider updating.`, - { dependency, newVersion }, - pluginId, - ); - } - - /** - * Send digest compilation notification. - */ - notifyCommunityDigest(authorId: string, digest: CompiledDigest): Notification { - return this.createNotification( - authorId, - "community_digest", - `${digest.frequency} digest`, - `You have ${digest.totalCount} new updates from the community`, - digest as unknown as Record, - ); - } - - // ─── Statistics ──────────────────────────────────────────────────────────── - - /** - * Get notification statistics for an author. - */ - getNotificationStats(authorId: string): NotificationStats { - const authorNotifs = this.getAuthorNotifications(authorId); - - const byType: Record = {} as Record; - for (const notif of authorNotifs) { - byType[notif.type] = (byType[notif.type] || 0) + 1; - } - - return { - totalNotifications: authorNotifs.length, - unreadCount: authorNotifs.filter((n) => !n.read).length, - byType, - byStatus: { - read: authorNotifs.filter((n) => n.read).length, - unread: authorNotifs.filter((n) => !n.read).length, - }, - }; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getNotificationsCache(): Map { - return this.notifications; - } - - getPreferencesCache(): Map { - return this.preferences; - } - - getDigestSettingsCache(): Map { - return this.digestSettings; - } -} diff --git a/src/author-verification.test.ts b/src/author-verification.test.ts deleted file mode 100644 index 5be55966..00000000 --- a/src/author-verification.test.ts +++ /dev/null @@ -1,333 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { AuthorVerificationSystem } from "./author-verification.js"; - -describe("AuthorVerificationSystem", () => { - describe("initialization", () => { - it("creates system instance", () => { - const system = new AuthorVerificationSystem(); - assert(system); - }); - - it("returns null for unknown author", () => { - const system = new AuthorVerificationSystem(); - assert.equal(system.getVerification("unknown"), null); - }); - }); - - describe("startVerification", () => { - let system: AuthorVerificationSystem; - - beforeEach(() => { - system = new AuthorVerificationSystem(); - }); - - it("creates a new verification record", () => { - const record = system.startVerification("author-1"); - assert.equal(record.authorId, "author-1"); - assert.equal(record.status, "pending"); - assert.deepEqual(record.completedSteps, []); - }); - - it("returns existing record if pending", () => { - const first = system.startVerification("author-1"); - const second = system.startVerification("author-1"); - assert.equal(first.createdAt, second.createdAt); - }); - - it("includes required steps", () => { - const record = system.startVerification("author-1"); - assert(record.steps.includes("github")); - assert(record.steps.includes("email")); - assert(record.steps.includes("cla")); - }); - }); - - describe("GitHub verification", () => { - let system: AuthorVerificationSystem; - - beforeEach(() => { - system = new AuthorVerificationSystem(); - system.startVerification("author-1"); - }); - - it("generates GitHub OAuth state", () => { - const state = system.generateGitHubState("author-1"); - assert(state); - assert(typeof state === "string"); - }); - - it("parses GitHub state back to authorId", () => { - const state = system.generateGitHubState("author-1"); - const parsed = system.parseGitHubState(state); - assert(parsed); - assert.equal(parsed.authorId, "author-1"); - }); - - it("returns null for invalid state", () => { - const result = system.parseGitHubState("invalid-state"); - assert.equal(result, null); - }); - - it("completes GitHub verification", async () => { - const result = await system.completeGitHubVerification("author-1", { - id: "gh-123", - login: "janedoe", - name: "Jane Doe", - }); - - assert.equal(result.success, true); - assert.equal(result.step, "github"); - assert(result.message.includes("janedoe")); - }); - - it("marks github step as completed", async () => { - await system.completeGitHubVerification("author-1", { - id: "gh-123", - login: "janedoe", - }); - - assert.equal(system.isStepComplete("author-1", "github"), true); - }); - - it("saves github data on record", async () => { - await system.completeGitHubVerification("author-1", { - id: "gh-123", - login: "janedoe", - name: "Jane Doe", - avatar_url: "/janedoe.png", - }); - - const record = system.getVerification("author-1"); - assert(record?.github); - assert.equal(record?.github?.githubLogin, "janedoe"); - assert.equal(record?.github?.githubId, "gh-123"); - }); - - it("rejects duplicate GitHub account", async () => { - system.startVerification("author-2"); - await system.completeGitHubVerification("author-2", { - id: "gh-999", - login: "shared_account", - }); - - const result = await system.completeGitHubVerification("author-1", { - id: "gh-999", - login: "shared_account", - }); - - assert.equal(result.success, false); - assert(result.message.includes("already linked")); - }); - - it("provides next step after github", async () => { - const result = await system.completeGitHubVerification("author-1", { - id: "gh-123", - login: "janedoe", - }); - - assert(result.nextStep); - assert.equal(result.nextStep, "email"); - }); - }); - - describe("email verification", () => { - let system: AuthorVerificationSystem; - - beforeEach(() => { - system = new AuthorVerificationSystem(); - system.startVerification("author-1"); - }); - - it("generates email verification token", () => { - const token = system.generateEmailToken("author-1", "dev@example.com"); - assert(token); - assert(typeof token === "string"); - assert(token.length > 0); - }); - - it("verifies valid email token", async () => { - const token = system.generateEmailToken("author-1", "dev@example.com"); - const result = await system.verifyEmailToken(token, "dev@example.com"); - - assert.equal(result.success, true); - assert.equal(result.step, "email"); - assert(result.message.includes("dev@example.com")); - }); - - it("marks email step as completed", async () => { - const token = system.generateEmailToken("author-1", "dev@example.com"); - await system.verifyEmailToken(token, "dev@example.com"); - - assert.equal(system.isStepComplete("author-1", "email"), true); - }); - - it("saves email domain on record", async () => { - const token = system.generateEmailToken("author-1", "dev@example.com"); - await system.verifyEmailToken(token, "dev@example.com"); - - const record = system.getVerification("author-1"); - assert.equal(record?.email?.domain, "example.com"); - }); - - it("rejects invalid token", async () => { - const result = await system.verifyEmailToken("invalid-token", "test@example.com"); - assert.equal(result.success, false); - assert(result.message.includes("Invalid")); - }); - - it("rejects already-used token", async () => { - const token = system.generateEmailToken("author-1", "dev@example.com"); - await system.verifyEmailToken(token, "dev@example.com"); - - const result2 = await system.verifyEmailToken(token, "dev@example.com"); - assert.equal(result2.success, false); - assert(result2.message.includes("already been used")); - }); - }); - - describe("CLA signing", () => { - let system: AuthorVerificationSystem; - - beforeEach(() => { - system = new AuthorVerificationSystem(); - system.startVerification("author-1"); - }); - - it("signs CLA successfully", async () => { - const result = await system.signCLA("author-1", "v1.0"); - assert.equal(result.success, true); - assert.equal(result.step, "cla"); - assert(result.message.includes("v1.0")); - }); - - it("marks cla step as completed", async () => { - await system.signCLA("author-1", "v1.0"); - assert.equal(system.isStepComplete("author-1", "cla"), true); - }); - - it("saves CLA data on record", async () => { - await system.signCLA("author-1", "v1.0", "192.168.1.1"); - const record = system.getVerification("author-1"); - assert.equal(record?.cla?.version, "v1.0"); - assert.equal(record?.cla?.ipAddress, "192.168.1.1"); - }); - - it("fails if verification not started", async () => { - const result = await system.signCLA("non-existent", "v1.0"); - assert.equal(result.success, false); - }); - - it("auto-verifies when all steps complete", async () => { - // Complete all steps - await system.completeGitHubVerification("author-1", { - id: "gh-1", - login: "user", - }); - const token = system.generateEmailToken("author-1", "user@example.com"); - await system.verifyEmailToken(token, "user@example.com"); - const result = await system.signCLA("author-1", "v1.0"); - - assert.equal(result.record?.status, "verified"); - }); - }); - - describe("publisher verification", () => { - let system: AuthorVerificationSystem; - - beforeEach(async () => { - system = new AuthorVerificationSystem(); - system.startVerification("author-1"); - // Complete all base steps - await system.completeGitHubVerification("author-1", { - id: "gh-1", - login: "user", - }); - const token = system.generateEmailToken("author-1", "user@example.com"); - await system.verifyEmailToken(token, "user@example.com"); - await system.signCLA("author-1", "v1.0"); - }); - - it("approves publisher for verified author", async () => { - const result = await system.approvePublisher("author-1", "admin-user"); - assert.equal(result.success, true); - assert.equal(result.step, "publisher"); - }); - - it("marks publisher step as completed", async () => { - await system.approvePublisher("author-1", "admin-user"); - assert.equal(system.isPublisherVerified("author-1"), true); - }); - - it("saves publisher approval data", async () => { - await system.approvePublisher("author-1", "admin-user"); - const record = system.getVerification("author-1"); - assert(record?.publisherApprovedAt); - assert.equal(record?.publisherApprovedBy, "admin-user"); - }); - - it("fails for unverified author", async () => { - system.startVerification("author-2"); - const result = await system.approvePublisher("author-2", "admin"); - assert.equal(result.success, false); - assert(result.message.includes("basic verification")); - }); - - it("fails for unknown author", async () => { - const result = await system.approvePublisher("unknown", "admin"); - assert.equal(result.success, false); - }); - }); - - describe("progress tracking", () => { - let system: AuthorVerificationSystem; - - beforeEach(() => { - system = new AuthorVerificationSystem(); - }); - - it("returns zero progress for new author", () => { - system.startVerification("author-1"); - const progress = system.getVerificationProgress("author-1"); - - assert.equal(progress.completed, 0); - assert.equal(progress.percent, 0); - assert.equal(progress.nextStep, "github"); - }); - - it("returns correct progress after each step", async () => { - system.startVerification("author-1"); - - await system.completeGitHubVerification("author-1", { - id: "gh-1", - login: "user", - }); - - const progress = system.getVerificationProgress("author-1"); - assert.equal(progress.completed, 1); - assert(progress.percent > 0); - assert.equal(progress.nextStep, "email"); - }); - - it("returns null nextStep when all done", async () => { - system.startVerification("author-1"); - await system.completeGitHubVerification("author-1", { id: "gh-1", login: "u" }); - const token = system.generateEmailToken("author-1", "u@e.com"); - await system.verifyEmailToken(token, "u@e.com"); - await system.signCLA("author-1", "v1.0"); - - const progress = system.getVerificationProgress("author-1"); - assert.equal(progress.percent, 100); - assert.equal(progress.nextStep, null); - }); - - it("isPublisherVerified returns false without publisher step", async () => { - system.startVerification("author-1"); - assert.equal(system.isPublisherVerified("author-1"), false); - }); - - it("isPublisherVerified returns false for unknown author", () => { - assert.equal(system.isPublisherVerified("unknown"), false); - }); - }); -}); diff --git a/src/author-verification.ts b/src/author-verification.ts deleted file mode 100644 index 7a1bad2e..00000000 --- a/src/author-verification.ts +++ /dev/null @@ -1,394 +0,0 @@ -import { randomUUID } from "crypto"; - -// ─── Types ──────────────────────────────────────────────────────────────────── - -export type VerificationStatus = - | "pending" - | "verified" - | "rejected" - | "expired"; - -export type VerificationStep = - | "github" - | "email" - | "cla" - | "review" - | "publisher"; - -export interface VerificationToken { - token: string; - type: "email" | "github"; - authorId: string; - expiresAt: string; - usedAt?: string; -} - -export interface GitHubVerification { - githubId: string; - githubLogin: string; - githubName?: string; - githubAvatarUrl?: string; - verifiedAt: string; -} - -export interface EmailVerification { - email: string; - verifiedAt: string; - domain: string; -} - -export interface CLASignature { - version: string; - signedAt: string; - ipAddress?: string; -} - -export interface VerificationRecord { - authorId: string; - status: VerificationStatus; - steps: VerificationStep[]; - completedSteps: VerificationStep[]; - github?: GitHubVerification; - email?: EmailVerification; - cla?: CLASignature; - publisherApprovedAt?: string; - publisherApprovedBy?: string; - createdAt: string; - updatedAt: string; -} - -export interface VerificationResult { - success: boolean; - step: VerificationStep; - message: string; - nextStep?: VerificationStep; - record?: VerificationRecord; -} - -// ─── AuthorVerificationSystem ───────────────────────────────────────────────── - -export class AuthorVerificationSystem { - private records: Map = new Map(); - private tokens: Map = new Map(); - - // ─── Record lifecycle ────────────────────────────────────────────────────── - - startVerification(authorId: string): VerificationRecord { - const existing = this.records.get(authorId); - if (existing && existing.status !== "expired") return existing; - - const record: VerificationRecord = { - authorId, - status: "pending", - steps: ["github", "email", "cla"], - completedSteps: [], - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }; - - this.records.set(authorId, record); - return record; - } - - getVerification(authorId: string): VerificationRecord | null { - return this.records.get(authorId) || null; - } - - // ─── GitHub verification ─────────────────────────────────────────────────── - - generateGitHubState(authorId: string): string { - const state = `${authorId}:${randomUUID()}`; - return Buffer.from(state).toString("base64"); - } - - parseGitHubState(state: string): { authorId: string } | null { - try { - const decoded = Buffer.from(state, "base64").toString("utf-8"); - // Must have format "{authorId}:{uuid}" — colon present with non-empty parts - const colonIdx = decoded.indexOf(":"); - if (colonIdx <= 0) return null; - const authorId = decoded.substring(0, colonIdx); - const nonce = decoded.substring(colonIdx + 1); - if (!authorId || !nonce) return null; - // Nonce must be a valid UUID - const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - if (!uuidPattern.test(nonce)) return null; - return { authorId }; - } catch { - return null; - } - } - - async completeGitHubVerification( - authorId: string, - githubData: { - id: string; - login: string; - name?: string; - avatar_url?: string; - }, - ): Promise { - let record = this.records.get(authorId); - if (!record) { - record = this.startVerification(authorId); - } - - // Check if github ID is already used by another author - for (const [existingId, existingRecord] of this.records) { - if ( - existingId !== authorId && - existingRecord.github?.githubId === githubData.id - ) { - return { - success: false, - step: "github", - message: `GitHub account ${githubData.login} is already linked to another author`, - }; - } - } - - const github: GitHubVerification = { - githubId: githubData.id, - githubLogin: githubData.login, - githubName: githubData.name, - githubAvatarUrl: githubData.avatar_url, - verifiedAt: new Date().toISOString(), - }; - - const updated = this.completeStep(authorId, "github", { github }); - const nextStep = this.getNextStep(updated); - - return { - success: true, - step: "github", - message: `GitHub account @${githubData.login} verified`, - nextStep: nextStep || undefined, - record: updated, - }; - } - - // ─── Email verification ──────────────────────────────────────────────────── - - generateEmailToken(authorId: string, email: string): string { - const token: VerificationToken = { - token: randomUUID(), - type: "email", - authorId, - expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), - }; - - this.tokens.set(token.token, token); - return token.token; - } - - async verifyEmailToken( - token: string, - email: string, - ): Promise { - const tokenRecord = this.tokens.get(token); - if (!tokenRecord) { - return { - success: false, - step: "email", - message: "Invalid or expired verification token", - }; - } - - if (tokenRecord.type !== "email") { - return { - success: false, - step: "email", - message: "Token is not an email verification token", - }; - } - - if (new Date(tokenRecord.expiresAt) < new Date()) { - return { - success: false, - step: "email", - message: "Verification token has expired", - }; - } - - if (tokenRecord.usedAt) { - return { - success: false, - step: "email", - message: "Verification token has already been used", - }; - } - - // Mark token as used - tokenRecord.usedAt = new Date().toISOString(); - - const domain = email.split("@")[1] || ""; - const emailVerification: EmailVerification = { - email, - domain, - verifiedAt: new Date().toISOString(), - }; - - const record = this.completeStep(tokenRecord.authorId, "email", { - email: emailVerification, - }); - const nextStep = this.getNextStep(record); - - return { - success: true, - step: "email", - message: `Email ${email} verified`, - nextStep: nextStep || undefined, - record, - }; - } - - // ─── CLA signing ───────────────────────────────────────────────────────── - - async signCLA( - authorId: string, - claVersion: string, - ipAddress?: string, - ): Promise { - const record = this.records.get(authorId); - if (!record) { - return { - success: false, - step: "cla", - message: "Verification not started", - }; - } - - const cla: CLASignature = { - version: claVersion, - signedAt: new Date().toISOString(), - ipAddress, - }; - - const updated = this.completeStep(authorId, "cla", { cla }); - const nextStep = this.getNextStep(updated); - - // Check if all required steps complete — auto-verify - if (this.isFullyVerified(updated)) { - updated.status = "verified"; - updated.updatedAt = new Date().toISOString(); - } - - return { - success: true, - step: "cla", - message: `CLA version ${claVersion} signed`, - nextStep: nextStep || undefined, - record: updated, - }; - } - - // ─── Publisher verification ──────────────────────────────────────────────── - - async approvePublisher( - authorId: string, - approvedBy: string, - ): Promise { - const record = this.records.get(authorId); - if (!record) { - return { - success: false, - step: "publisher", - message: "No verification record found", - }; - } - - if (record.status !== "verified") { - return { - success: false, - step: "publisher", - message: "Author must complete basic verification before publisher approval", - }; - } - - const updated = this.completeStep(authorId, "publisher", { - publisherApprovedAt: new Date().toISOString(), - publisherApprovedBy: approvedBy, - }); - - return { - success: true, - step: "publisher", - message: `Author approved as verified publisher by ${approvedBy}`, - record: updated, - }; - } - - // ─── Status helpers ──────────────────────────────────────────────────────── - - isStepComplete(authorId: string, step: VerificationStep): boolean { - const record = this.records.get(authorId); - return record?.completedSteps.includes(step) || false; - } - - isFullyVerified(record: VerificationRecord): boolean { - return record.steps.every((step) => record.completedSteps.includes(step)); - } - - isPublisherVerified(authorId: string): boolean { - const record = this.records.get(authorId); - return record?.completedSteps.includes("publisher") || false; - } - - getNextStep(record: VerificationRecord): VerificationStep | null { - for (const step of record.steps) { - if (!record.completedSteps.includes(step)) { - return step; - } - } - return null; - } - - getVerificationProgress(authorId: string): { - total: number; - completed: number; - percent: number; - nextStep: VerificationStep | null; - } { - const record = this.records.get(authorId); - if (!record) return { total: 0, completed: 0, percent: 0, nextStep: null }; - - const total = record.steps.length; - const completed = record.completedSteps.length; - const percent = total > 0 ? Math.round((completed / total) * 100) : 0; - - return { total, completed, percent, nextStep: this.getNextStep(record) }; - } - - // ─── Helpers ────────────────────────────────────────────────────────────── - - private completeStep( - authorId: string, - step: VerificationStep, - extraData: Partial, - ): VerificationRecord { - const record = this.records.get(authorId)!; - const updatedRecord: VerificationRecord = { - ...record, - ...extraData, - completedSteps: record.completedSteps.includes(step) - ? record.completedSteps - : [...record.completedSteps, step], - updatedAt: new Date().toISOString(), - }; - this.records.set(authorId, updatedRecord); - return updatedRecord; - } - - // ─── Test helpers ────────────────────────────────────────────────────────── - - setRecordsCache(records: VerificationRecord[]): void { - this.records.clear(); - for (const record of records) { - this.records.set(record.authorId, record); - } - } - - getTokensCache(): Map { - return this.tokens; - } -} diff --git a/src/badge-system.test.ts b/src/badge-system.test.ts deleted file mode 100644 index ee369628..00000000 --- a/src/badge-system.test.ts +++ /dev/null @@ -1,432 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { - BadgeSystem, - BADGE_DEFINITIONS, - type PluginMetrics, -} from "./badge-system.js"; - -function makeMetrics(overrides: Partial = {}): PluginMetrics { - return { - pluginId: "stripe/payments", - authorId: "author-1", - rating: 3.0, - reviewsCount: 10, - downloadsMonth: 100, - downloadsWeek: 20, - downloadsTotal: 500, - trendingScore: 300, - isOfficial: false, - hasSecurityAudit: false, - lastUpdateDays: 30, - authorVerified: false, - ...overrides, - }; -} - -describe("BadgeSystem", () => { - describe("initialization", () => { - it("creates system instance", () => { - const system = new BadgeSystem(); - assert(system); - }); - - it("exports badge definitions", () => { - assert(BADGE_DEFINITIONS); - assert(BADGE_DEFINITIONS.official); - assert(BADGE_DEFINITIONS.top_rated); - assert(BADGE_DEFINITIONS.trending); - }); - - it("has all 8 badge types defined", () => { - const types = Object.keys(BADGE_DEFINITIONS); - assert.equal(types.length, 8); - }); - }); - - describe("badge criteria — official", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards official badge when isOfficial=true", () => { - const metrics = makeMetrics({ isOfficial: true }); - assert.equal(system.evaluateBadge("official", metrics), true); - }); - - it("denies official badge when isOfficial=false", () => { - const metrics = makeMetrics({ isOfficial: false }); - assert.equal(system.evaluateBadge("official", metrics), false); - }); - }); - - describe("badge criteria — top_rated", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards top_rated with 4.8+ rating and 50+ reviews", () => { - const metrics = makeMetrics({ rating: 4.9, reviewsCount: 100 }); - assert.equal(system.evaluateBadge("top_rated", metrics), true); - }); - - it("denies top_rated with low rating", () => { - const metrics = makeMetrics({ rating: 4.5, reviewsCount: 100 }); - assert.equal(system.evaluateBadge("top_rated", metrics), false); - }); - - it("denies top_rated with few reviews", () => { - const metrics = makeMetrics({ rating: 5.0, reviewsCount: 10 }); - assert.equal(system.evaluateBadge("top_rated", metrics), false); - }); - - it("awards at exactly 4.8 rating threshold", () => { - const metrics = makeMetrics({ rating: 4.8, reviewsCount: 50 }); - assert.equal(system.evaluateBadge("top_rated", metrics), true); - }); - }); - - describe("badge criteria — trending", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards trending with high score and weekly downloads", () => { - const metrics = makeMetrics({ trendingScore: 800, downloadsWeek: 200 }); - assert.equal(system.evaluateBadge("trending", metrics), true); - }); - - it("denies trending with low trending score", () => { - const metrics = makeMetrics({ trendingScore: 400, downloadsWeek: 200 }); - assert.equal(system.evaluateBadge("trending", metrics), false); - }); - - it("denies trending with low weekly downloads", () => { - const metrics = makeMetrics({ trendingScore: 900, downloadsWeek: 50 }); - assert.equal(system.evaluateBadge("trending", metrics), false); - }); - }); - - describe("badge criteria — secure", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards secure badge when audit complete", () => { - const metrics = makeMetrics({ hasSecurityAudit: true }); - assert.equal(system.evaluateBadge("secure", metrics), true); - }); - - it("denies secure badge without audit", () => { - const metrics = makeMetrics({ hasSecurityAudit: false }); - assert.equal(system.evaluateBadge("secure", metrics), false); - }); - }); - - describe("badge criteria — well_documented", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards well_documented with docs url and 5+ pages", () => { - const metrics = makeMetrics({ - docsUrl: "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/sandstream/kit", - docsPageCount: 8, - }); - assert.equal(system.evaluateBadge("well_documented", metrics), true); - }); - - it("denies when no docs url", () => { - const metrics = makeMetrics({ docsPageCount: 10 }); - assert.equal(system.evaluateBadge("well_documented", metrics), false); - }); - - it("denies when fewer than 5 pages", () => { - const metrics = makeMetrics({ - docsUrl: "https://docs.example.com", - docsPageCount: 3, - }); - assert.equal(system.evaluateBadge("well_documented", metrics), false); - }); - }); - - describe("badge criteria — verified", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards verified when author is verified", () => { - const metrics = makeMetrics({ authorVerified: true }); - assert.equal(system.evaluateBadge("verified", metrics), true); - }); - - it("denies verified for unverified author", () => { - const metrics = makeMetrics({ authorVerified: false }); - assert.equal(system.evaluateBadge("verified", metrics), false); - }); - }); - - describe("badge criteria — popular", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards popular with 1000+ monthly downloads", () => { - const metrics = makeMetrics({ downloadsMonth: 1500 }); - assert.equal(system.evaluateBadge("popular", metrics), true); - }); - - it("denies popular below threshold", () => { - const metrics = makeMetrics({ downloadsMonth: 500 }); - assert.equal(system.evaluateBadge("popular", metrics), false); - }); - }); - - describe("badge criteria — actively_maintained", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards for update within 90 days", () => { - const metrics = makeMetrics({ lastUpdateDays: 30 }); - assert.equal(system.evaluateBadge("actively_maintained", metrics), true); - }); - - it("awards at exactly 90 day threshold", () => { - const metrics = makeMetrics({ lastUpdateDays: 90 }); - assert.equal(system.evaluateBadge("actively_maintained", metrics), true); - }); - - it("denies for stale plugin", () => { - const metrics = makeMetrics({ lastUpdateDays: 180 }); - assert.equal(system.evaluateBadge("actively_maintained", metrics), false); - }); - }); - - describe("award and revoke", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards badge and adds to plugin", () => { - const badge = system.awardBadge("stripe/payments", "official"); - assert.equal(badge.type, "official"); - assert.equal(badge.icon, "⭐"); - - assert.equal(system.hasBadge("stripe/payments", "official"), true); - }); - - it("does not duplicate badge on re-award", () => { - system.awardBadge("stripe/payments", "official"); - system.awardBadge("stripe/payments", "official"); - - const badges = system.getPluginBadges("stripe/payments"); - const officialBadges = badges.filter((b) => b.type === "official"); - assert.equal(officialBadges.length, 1); - }); - - it("revokes badge from plugin", () => { - system.awardBadge("stripe/payments", "trending"); - const success = system.revokeBadge( - "stripe/payments", - "trending", - "Score dropped", - ); - - assert.equal(success, true); - assert.equal(system.hasBadge("stripe/payments", "trending"), false); - }); - - it("returns false revoking non-existent badge", () => { - const success = system.revokeBadge( - "stripe/payments", - "official", - "test", - ); - assert.equal(success, false); - }); - }); - - describe("sync badges", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("awards badges when criteria met", () => { - const metrics = makeMetrics({ - isOfficial: true, - rating: 4.9, - reviewsCount: 100, - }); - const report = system.syncBadges("stripe/payments", metrics); - - assert(report.passed.includes("official")); - assert(report.passed.includes("top_rated")); - }); - - it("revokes badges when criteria no longer met", () => { - system.awardBadge("stripe/payments", "trending"); - - const metrics = makeMetrics({ trendingScore: 100, downloadsWeek: 10 }); - const report = system.syncBadges("stripe/payments", metrics); - - assert.equal(system.hasBadge("stripe/payments", "trending"), false); - assert(report.failed.includes("trending")); - }); - - it("returns full report with passed and failed", () => { - const metrics = makeMetrics({ isOfficial: true }); - const report = system.syncBadges("stripe/payments", metrics); - - assert(report.passed.length > 0); - assert(report.failed.length > 0); - assert(Array.isArray(report.badges)); - assert(Array.isArray(report.auditLog)); - }); - - it("report includes all evaluated criteria", () => { - const metrics = makeMetrics(); - const report = system.syncBadges("stripe/payments", metrics); - - assert.equal(report.evaluated.length, 8); - }); - }); - - describe("queries", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("getPluginsByBadge returns correct plugins", () => { - system.awardBadge("stripe/payments", "official"); - system.awardBadge("supabase/db", "official"); - system.awardBadge("stripe/payments", "top_rated"); - - const official = system.getPluginsByBadge("official"); - assert.equal(official.length, 2); - assert(official.includes("stripe/payments")); - assert(official.includes("supabase/db")); - }); - - it("getBadgeStats returns counts per type", () => { - system.awardBadge("stripe/payments", "official"); - system.awardBadge("supabase/db", "official"); - system.awardBadge("stripe/payments", "trending"); - - const stats = system.getBadgeStats(); - assert.equal(stats.official, 2); - assert.equal(stats.trending, 1); - assert.equal(stats.secure, 0); - }); - - it("getAuditLog returns plugin-specific entries", () => { - system.awardBadge("stripe/payments", "official"); - system.awardBadge("supabase/db", "official"); - - const log = system.getAuditLog("stripe/payments"); - assert.equal(log.length, 1); - assert.equal(log[0].pluginId, "stripe/payments"); - }); - - it("getAuditLog without filter returns all", () => { - system.awardBadge("stripe/payments", "official"); - system.awardBadge("supabase/db", "trending"); - - const log = system.getAuditLog(); - assert.equal(log.length, 2); - }); - }); - - describe("display helpers", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("formats badges for display", () => { - system.awardBadge("stripe/payments", "official"); - system.awardBadge("stripe/payments", "top_rated"); - - const display = system.formatBadgesForDisplay("stripe/payments"); - assert(display.includes("⭐")); - assert(display.includes("Official")); - assert(display.includes("🏆")); - }); - - it("returns empty string for plugin with no badges", () => { - const display = system.formatBadgesForDisplay("unknown/plugin"); - assert.equal(display, ""); - }); - - it("getBadgeDefinitions returns all definitions", () => { - const defs = system.getBadgeDefinitions(); - assert.equal(Object.keys(defs).length, 8); - assert(defs.official.icon); - assert(defs.official.description); - }); - }); - - describe("evaluateAllBadges", () => { - let system: BadgeSystem; - - beforeEach(() => { - system = new BadgeSystem(); - }); - - it("returns empty for plugin meeting no criteria", () => { - const metrics = makeMetrics(); - const earned = system.evaluateAllBadges(metrics); - // actively_maintained should still pass (lastUpdateDays: 30 <= 90) - assert(earned.includes("actively_maintained")); - }); - - it("returns all applicable badges for stellar plugin", () => { - const metrics = makeMetrics({ - isOfficial: true, - rating: 4.9, - reviewsCount: 100, - trendingScore: 900, - downloadsWeek: 500, - downloadsMonth: 5000, - hasSecurityAudit: true, - docsUrl: "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/sandstream/kit", - docsPageCount: 10, - authorVerified: true, - lastUpdateDays: 7, - }); - const earned = system.evaluateAllBadges(metrics); - - assert(earned.includes("official")); - assert(earned.includes("top_rated")); - assert(earned.includes("trending")); - assert(earned.includes("secure")); - assert(earned.includes("well_documented")); - assert(earned.includes("verified")); - assert(earned.includes("popular")); - assert(earned.includes("actively_maintained")); - }); - }); -}); diff --git a/src/badge-system.ts b/src/badge-system.ts deleted file mode 100644 index 71695a45..00000000 --- a/src/badge-system.ts +++ /dev/null @@ -1,317 +0,0 @@ -// ─── Types ──────────────────────────────────────────────────────────────────── - -export type BadgeType = - | "official" - | "top_rated" - | "trending" - | "secure" - | "well_documented" - | "verified" - | "popular" - | "actively_maintained"; - -export interface BadgeCriteria { - type: BadgeType; - label: string; - icon: string; - description: string; - criteria: Record; -} - -export interface Badge { - type: BadgeType; - label: string; - icon: string; - description: string; - earnedAt: string; - expiresAt?: string; -} - -export interface PluginMetrics { - pluginId: string; - authorId: string; - rating: number; - reviewsCount: number; - downloadsMonth: number; - downloadsWeek: number; - downloadsTotal: number; - trendingScore: number; - isOfficial: boolean; - hasSecurityAudit: boolean; - docsUrl?: string; - docsPageCount?: number; - lastUpdateDays: number; - authorVerified: boolean; - maintainedByOrg?: boolean; -} - -export interface BadgeAuditEntry { - pluginId: string; - badgeType: BadgeType; - action: "awarded" | "revoked" | "renewed"; - reason: string; - timestamp: string; -} - -export interface BadgeReport { - pluginId: string; - badges: Badge[]; - evaluated: BadgeCriteria[]; - passed: BadgeType[]; - failed: BadgeType[]; - auditLog: BadgeAuditEntry[]; -} - -// ─── Criteria definitions ──────────────────────────────────────────────────── - -export const BADGE_DEFINITIONS: Record = { - official: { - type: "official", - label: "Official", - icon: "⭐", - description: "Maintained and officially supported by Sandstream", - criteria: { isOfficial: true }, - }, - top_rated: { - type: "top_rated", - label: "Top Rated", - icon: "🏆", - description: "Average rating of 4.8 or higher with 50+ reviews", - criteria: { minRating: 4.8, minReviews: 50 }, - }, - trending: { - type: "trending", - label: "Trending", - icon: "🚀", - description: "Rapidly growing downloads over the past week", - criteria: { minTrendingScore: 700, minWeeklyDownloads: 100 }, - }, - secure: { - type: "secure", - label: "Security Audited", - icon: "🔒", - description: "Has passed a security audit", - criteria: { hasSecurityAudit: true }, - }, - well_documented: { - type: "well_documented", - label: "Well Documented", - icon: "📚", - description: "Has comprehensive documentation with 5+ pages", - criteria: { hasDocsUrl: true, minDocPages: 5 }, - }, - verified: { - type: "verified", - label: "Verified Publisher", - icon: "✅", - description: "Published by a verified and trusted author", - criteria: { authorVerified: true }, - }, - popular: { - type: "popular", - label: "Popular", - icon: "🔥", - description: "Over 1,000 monthly downloads", - criteria: { minMonthlyDownloads: 1000 }, - }, - actively_maintained: { - type: "actively_maintained", - label: "Actively Maintained", - icon: "🔧", - description: "Updated within the last 90 days", - criteria: { maxLastUpdateDays: 90 }, - }, -}; - -// ─── BadgeSystem ───────────────────────────────────────────────────────────── - -export class BadgeSystem { - private pluginBadges: Map = new Map(); - private auditLog: BadgeAuditEntry[] = []; - - // ─── Criteria evaluation ─────────────────────────────────────────────────── - - evaluateBadge(type: BadgeType, metrics: PluginMetrics): boolean { - switch (type) { - case "official": - return metrics.isOfficial; - - case "top_rated": - return metrics.rating >= 4.8 && metrics.reviewsCount >= 50; - - case "trending": - return ( - metrics.trendingScore >= 700 && metrics.downloadsWeek >= 100 - ); - - case "secure": - return metrics.hasSecurityAudit; - - case "well_documented": - return !!(metrics.docsUrl && (metrics.docsPageCount || 0) >= 5); - - case "verified": - return metrics.authorVerified; - - case "popular": - return metrics.downloadsMonth >= 1000; - - case "actively_maintained": - return metrics.lastUpdateDays <= 90; - - default: - return false; - } - } - - evaluateAllBadges(metrics: PluginMetrics): BadgeType[] { - const earned: BadgeType[] = []; - for (const type of Object.keys(BADGE_DEFINITIONS) as BadgeType[]) { - if (this.evaluateBadge(type, metrics)) { - earned.push(type); - } - } - return earned; - } - - // ─── Badge management ────────────────────────────────────────────────────── - - awardBadge(pluginId: string, type: BadgeType, reason = "criteria met"): Badge { - const definition = BADGE_DEFINITIONS[type]; - const badge: Badge = { - type, - label: definition.label, - icon: definition.icon, - description: definition.description, - earnedAt: new Date().toISOString(), - }; - - const existing = this.pluginBadges.get(pluginId) || []; - const alreadyHas = existing.some((b) => b.type === type); - if (!alreadyHas) { - this.pluginBadges.set(pluginId, [...existing, badge]); - } - - this.auditLog.push({ - pluginId, - badgeType: type, - action: alreadyHas ? "renewed" : "awarded", - reason, - timestamp: new Date().toISOString(), - }); - - return badge; - } - - revokeBadge(pluginId: string, type: BadgeType, reason: string): boolean { - const badges = this.pluginBadges.get(pluginId); - if (!badges) return false; - - const filtered = badges.filter((b) => b.type !== type); - if (filtered.length === badges.length) return false; - - this.pluginBadges.set(pluginId, filtered); - - this.auditLog.push({ - pluginId, - badgeType: type, - action: "revoked", - reason, - timestamp: new Date().toISOString(), - }); - - return true; - } - - // ─── Sync (award/revoke based on current metrics) ───────────────────────── - - syncBadges(pluginId: string, metrics: PluginMetrics): BadgeReport { - const earned = this.evaluateAllBadges(metrics); - const current = this.getPluginBadges(pluginId).map((b) => b.type); - - const toAward = earned.filter((t) => !current.includes(t)); - const toRevoke = current.filter((t) => !earned.includes(t)); - - for (const type of toAward) { - this.awardBadge(pluginId, type, "automatic sync — criteria met"); - } - for (const type of toRevoke) { - this.revokeBadge( - pluginId, - type, - "automatic sync — criteria no longer met", - ); - } - - const allTypes = Object.keys(BADGE_DEFINITIONS) as BadgeType[]; - - return { - pluginId, - badges: this.getPluginBadges(pluginId), - evaluated: allTypes.map((t) => BADGE_DEFINITIONS[t]), - passed: earned, - failed: allTypes.filter((t) => !earned.includes(t)), - auditLog: this.auditLog.filter((e) => e.pluginId === pluginId), - }; - } - - // ─── Queries ────────────────────────────────────────────────────────────── - - getPluginBadges(pluginId: string): Badge[] { - return this.pluginBadges.get(pluginId) || []; - } - - hasBadge(pluginId: string, type: BadgeType): boolean { - return this.getPluginBadges(pluginId).some((b) => b.type === type); - } - - getPluginsByBadge(type: BadgeType): string[] { - const result: string[] = []; - for (const [pluginId, badges] of this.pluginBadges) { - if (badges.some((b) => b.type === type)) { - result.push(pluginId); - } - } - return result; - } - - getBadgeStats(): Record { - const stats = {} as Record; - for (const type of Object.keys(BADGE_DEFINITIONS) as BadgeType[]) { - stats[type] = this.getPluginsByBadge(type).length; - } - return stats; - } - - getAuditLog(pluginId?: string): BadgeAuditEntry[] { - if (pluginId) { - return this.auditLog.filter((e) => e.pluginId === pluginId); - } - return this.auditLog; - } - - getBadgeDefinitions(): Record { - return BADGE_DEFINITIONS; - } - - // ─── Display helpers ───────────────────────────────────────────────────── - - formatBadgesForDisplay(pluginId: string): string { - const badges = this.getPluginBadges(pluginId); - if (badges.length === 0) return ""; - return badges.map((b) => `${b.icon} ${b.label}`).join(" "); - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - clearBadges(pluginId: string): void { - this.pluginBadges.delete(pluginId); - } - - setBadgesCache(entries: Array<{ pluginId: string; badges: Badge[] }>): void { - this.pluginBadges.clear(); - for (const { pluginId, badges } of entries) { - this.pluginBadges.set(pluginId, badges); - } - } -} diff --git a/src/beta-program-service.test.ts b/src/beta-program-service.test.ts deleted file mode 100644 index 63c83def..00000000 --- a/src/beta-program-service.test.ts +++ /dev/null @@ -1,255 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { BetaProgramService } from "./beta-program-service.js"; - -describe("BetaProgramService", () => { - let service: BetaProgramService; - let mockDb: any; - - beforeEach(() => { - mockDb = { - query: async (sql: string, params: any[]) => { - if (sql.includes("INSERT INTO beta_developers")) { - return { - rows: [{ - id: params[0], - email: params[1], - name: params[2], - organization: params[3], - enrolled_at: new Date().toISOString(), - status: params[4], - }], - }; - } - if (sql.includes("INSERT INTO plugin_feedback")) { - return { - rows: [{ - id: params[0], - plugin_id: params[1], - developer_id: params[2], - rating: params[3], - category: params[4], - title: params[5], - description: params[6], - severity: params[7] || "medium", - status: params[8], - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("SELECT * FROM plugin_feedback WHERE plugin_id")) { - return { - rows: [ - { - id: "feedback-1", - plugin_id: params[0], - developer_id: "dev-1", - rating: 4, - category: "usability", - title: "Confusing error message", - description: "Error handling needs improvement", - severity: "medium", - status: "open", - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - ], - }; - } - if (sql.includes("SELECT * FROM plugin_feedback WHERE developer_id")) { - return { - rows: [ - { - id: "feedback-1", - plugin_id: "plugin-1", - developer_id: params[0], - rating: 4, - category: "usability", - title: "Good UX", - description: "Easy to use", - severity: "low", - status: "open", - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - ], - }; - } - if (sql.includes("COUNT(*) as feedback_count") && sql.includes("beta_developers bd")) { - return { - rows: [{ - id: params[0], - email: "dev@example.com", - name: "Developer", - organization: "Acme Corp", - enrolled_at: new Date().toISOString(), - status: "active", - feedback_count: 5, - plugins_tested: ["plugin-1", "plugin-2"], - last_activity_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("SELECT * FROM beta_developers WHERE status")) { - return { - rows: Array.from({ length: Math.min(params[1] || 50, 10) }, (_, i) => ({ - id: `dev-${i}`, - email: `dev${i}@example.com`, - name: `Developer ${i}`, - organization: "Company", - enrolled_at: new Date().toISOString(), - status: "active", - feedback_count: 3 + i, - last_activity_at: new Date().toISOString(), - })), - }; - } - if (sql.includes("COUNT(*) as enrolled FROM beta_developers")) { - return { rows: [{ enrolled: 15 }] }; - } - if (sql.includes("COUNT(*) as total FROM plugin_feedback")) { - return { rows: [{ total: 42 }] }; - } - if (sql.includes("COUNT(*) as total FROM certification_refinements")) { - return { rows: [{ total: 3 }] }; - } - if (sql.includes("category") && sql.includes("COUNT(*)") && sql.includes("plugin_feedback")) { - // Feedback by category - return { - rows: [ - { category: "usability", count: 15 }, - { category: "bug", count: 12 }, - { category: "documentation", count: 10 }, - ], - }; - } - if (sql.includes("severity") && sql.includes("COUNT(*)") && sql.includes("plugin_feedback")) { - // Feedback by severity - return { - rows: [ - { severity: "medium", count: 20 }, - { severity: "low", count: 15 }, - { severity: "high", count: 7 }, - ], - }; - } - if (sql.includes("AVG(rating)")) { - return { rows: [{ avg: "4.2" }] }; - } - return { rows: [] }; - }, - }; - - service = new BetaProgramService(mockDb); - }); - - describe("enrollDeveloper", () => { - it("enrolls developer in beta program", async () => { - const developer = await service.enrollDeveloper( - "john@example.com", - "John Developer", - "Acme Corp", - ); - assert.equal(developer.email, "john@example.com"); - assert.equal(developer.name, "John Developer"); - assert.equal(developer.organization, "Acme Corp"); - assert.equal(developer.status, "active"); - }); - - it("generates unique developer IDs", async () => { - const dev1 = await service.enrollDeveloper("dev1@example.com", "Dev 1"); - const dev2 = await service.enrollDeveloper("dev2@example.com", "Dev 2"); - assert.notEqual(dev1.id, dev2.id); - }); - }); - - describe("submitFeedback", () => { - it("submits plugin feedback", async () => { - const feedback = await service.submitFeedback( - "plugin-1", - "dev-1", - 4, - "usability", - "Confusing UI", - "The settings page is hard to navigate", - "medium", - ); - assert.equal(feedback.rating, 4); - assert.equal(feedback.category, "usability"); - assert.equal(feedback.status, "open"); - }); - - it("validates rating range", async () => { - await assert.rejects( - () => service.submitFeedback("plugin-1", "dev-1", 6, "bug", "title", "desc"), - /Rating must be between 1 and 5/, - ); - }); - }); - - describe("getPluginFeedback", () => { - it("retrieves feedback for plugin", async () => { - const feedback = await service.getPluginFeedback("plugin-1"); - assert.ok(Array.isArray(feedback)); - if (feedback.length > 0) { - assert.equal(feedback[0].pluginId, "plugin-1"); - } - }); - }); - - describe("getDeveloperFeedback", () => { - it("retrieves feedback from developer", async () => { - const feedback = await service.getDeveloperFeedback("dev-1"); - assert.ok(Array.isArray(feedback)); - }); - }); - - describe("getDeveloperProfile", () => { - it("has getDeveloperProfile method", () => { - assert.ok(typeof service.getDeveloperProfile === 'function'); - }); - }); - - describe("getBetaDevelopers", () => { - it("has getBetaDevelopers method", () => { - assert.ok(typeof service.getBetaDevelopers === 'function'); - }); - }); - - describe("getBetaProgramStatus", () => { - it("returns beta program status", async () => { - const status = await service.getBetaProgramStatus(); - assert.equal(status.name, "kit Community Beta Launch"); - assert.equal(status.status, "active"); - assert.ok(status.enrolledDevelopers >= 0); - assert.ok(status.feedbackItems >= 0); - assert.ok(status.refinementsProposed >= 0); - }); - }); - - describe("getFeedbackAnalytics", () => { - it("returns feedback analytics", async () => { - const analytics = await service.getFeedbackAnalytics(); - assert.ok(typeof analytics.totalFeedback === "number"); - assert.ok(Array.isArray(analytics.byCategory)); - assert.ok(Array.isArray(analytics.bySeverity)); - assert.ok(typeof analytics.avgRating === "number"); - }); - - it("includes category breakdown", async () => { - const analytics = await service.getFeedbackAnalytics(); - if (analytics.byCategory.length > 0) { - assert.ok(analytics.byCategory[0].category); - assert.ok(typeof analytics.byCategory[0].count === "number"); - } - }); - }); - - describe("identifyRefinements", () => { - it("identifies certification refinements from feedback", async () => { - const refinements = await service.identifyRefinements(); - assert.ok(Array.isArray(refinements)); - }); - }); -}); diff --git a/src/beta-program-service.ts b/src/beta-program-service.ts deleted file mode 100644 index 2d9f3e3a..00000000 --- a/src/beta-program-service.ts +++ /dev/null @@ -1,378 +0,0 @@ -/** - * kit Beta Program Service - * - * Manages community developer beta enrollment, feedback collection, and certification - * refinement based on real-world plugin usage patterns. - */ - -import { IdGenerators } from "./id-generator.js"; - -export interface BetaDeveloper { - id: string; - email: string; - name: string; - organization?: string; - enrolledAt: string; - status: "active" | "inactive" | "churned"; - pluginsTested: string[]; - feedbackCount: number; - lastActivityAt?: string; -} - -export interface PluginFeedback { - id: string; - pluginId: string; - developerId: string; - rating: number; // 1-5 - category: "usability" | "stability" | "performance" | "documentation" | "feature-request" | "bug"; - title: string; - description: string; - severity?: "low" | "medium" | "high" | "critical"; - status: "open" | "acknowledged" | "addressed" | "wontfix"; - createdAt: string; - updatedAt: string; -} - -export interface CertificationRefinement { - id: string; - category: string; - description: string; - feedbackCount: number; - severity: "informational" | "warning" | "critical"; - status: "proposed" | "under-review" | "approved" | "implemented"; - affectedPlugins: string[]; - createdAt: string; - implementedAt?: string; -} - -export interface BetaProgram { - id: string; - name: string; - targetDevelopers: number; - enrolledDevelopers: number; - status: "recruiting" | "active" | "closed"; - startDate: string; - endDate?: string; - feedbackItems: number; - refinementsProposed: number; -} - -/** - * Beta program management service - */ -export class BetaProgramService { - private db: any; - - constructor(db?: any) { - this.db = db; - } - - /** - * Enroll developer in beta program - */ - async enrollDeveloper( - email: string, - name: string, - organization?: string, - ): Promise { - const id = IdGenerators.betaDev(); - const result = await this.db.query( - ` - INSERT INTO beta_developers (id, email, name, organization, enrolled_at, status) - VALUES ($1, $2, $3, $4, now(), $5) - RETURNING * - `, - [id, email, name, organization || null, "active"], - ); - - return this.mapBetaDeveloper(result.rows[0]); - } - - /** - * Submit feedback on plugin - */ - async submitFeedback( - pluginId: string, - developerId: string, - rating: number, - category: string, - title: string, - description: string, - severity?: string, - ): Promise { - if (rating < 1 || rating > 5) { - throw new Error("Rating must be between 1 and 5"); - } - - const id = IdGenerators.feedback(); - const result = await this.db.query( - ` - INSERT INTO plugin_feedback - (id, plugin_id, developer_id, rating, category, title, description, severity, status, created_at, updated_at) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), now()) - RETURNING * - `, - [id, pluginId, developerId, rating, category, title, description, severity || "medium", "open"], - ); - - // Update developer activity - await this.db.query( - ` - UPDATE beta_developers - SET last_activity_at = now() - WHERE id = $1 - `, - [developerId], - ); - - return this.mapPluginFeedback(result.rows[0]); - } - - /** - * Get feedback for plugin - */ - async getPluginFeedback(pluginId: string): Promise { - const result = await this.db.query( - ` - SELECT * FROM plugin_feedback - WHERE plugin_id = $1 - ORDER BY created_at DESC - `, - [pluginId], - ); - - return result.rows.map((row: any) => this.mapPluginFeedback(row)); - } - - /** - * Get developer feedback history - */ - async getDeveloperFeedback(developerId: string): Promise { - const result = await this.db.query( - ` - SELECT * FROM plugin_feedback - WHERE developer_id = $1 - ORDER BY created_at DESC - `, - [developerId], - ); - - return result.rows.map((row: any) => this.mapPluginFeedback(row)); - } - - /** - * Aggregate feedback to identify certification refinements - */ - async identifyRefinements(): Promise { - const result = await this.db.query( - ` - SELECT - category, - severity, - COUNT(*) as feedback_count, - ARRAY_AGG(DISTINCT plugin_id) as affected_plugins - FROM plugin_feedback - WHERE status = $1 AND severity IN ($2, $3, $4) - GROUP BY category, severity - HAVING COUNT(*) >= 3 - ORDER BY feedback_count DESC - `, - ["open", "medium", "high", "critical"], - ); - - const refinements: CertificationRefinement[] = []; - for (const row of result.rows) { - refinements.push({ - id: IdGenerators.refine(), - category: row.category, - description: `${row.feedback_count} developers reported issues with ${row.category}`, - feedbackCount: row.feedback_count, - severity: row.severity, - status: "proposed", - affectedPlugins: row.affected_plugins || [], - createdAt: new Date().toISOString(), - }); - } - - return refinements; - } - - /** - * Get beta program status - */ - async getBetaProgramStatus(): Promise { - // Active program - const devResult = await this.db.query( - ` - SELECT COUNT(*) as enrolled FROM beta_developers WHERE status = $1 - `, - ["active"], - ); - - const feedbackResult = await this.db.query( - ` - SELECT COUNT(*) as total FROM plugin_feedback - `, - ); - - const refinementResult = await this.db.query( - ` - SELECT COUNT(*) as total FROM certification_refinements WHERE status = $1 - `, - ["proposed"], - ); - - return { - id: "beta-main-2026", - name: "kit Community Beta Launch", - targetDevelopers: 20, - enrolledDevelopers: devResult.rows[0]?.enrolled || 0, - status: "active", - startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(), // 1 week ago - feedbackItems: feedbackResult.rows[0]?.total || 0, - refinementsProposed: refinementResult.rows[0]?.total || 0, - }; - } - - /** - * Get developer profile with feedback summary - */ - async getDeveloperProfile(developerId: string): Promise { - const result = await this.db.query( - ` - SELECT - bd.*, - COUNT(DISTINCT pf.id) as feedback_count, - ARRAY_AGG(DISTINCT pf.plugin_id) as plugins_tested - FROM beta_developers bd - LEFT JOIN plugin_feedback pf ON bd.id = pf.developer_id - WHERE bd.id = $1 - GROUP BY bd.id - `, - [developerId], - ); - - if (result.rows.length === 0) { - return null; - } - - const row = result.rows[0]; - return { - id: row.id, - email: row.email, - name: row.name, - organization: row.organization, - enrolledAt: row.enrolled_at, - status: row.status, - pluginsTested: row.plugins_tested || [], - feedbackCount: row.feedback_count || 0, - lastActivityAt: row.last_activity_at, - }; - } - - /** - * Get beta developers - */ - async getBetaDevelopers(limit: number = 50): Promise { - const result = await this.db.query( - ` - SELECT * FROM beta_developers - WHERE status = $1 - ORDER BY last_activity_at DESC - LIMIT $2 - `, - ["active", limit], - ); - - return result.rows.map((row: any) => this.mapBetaDeveloper(row)); - } - - /** - * Update feedback status - */ - async updateFeedbackStatus(feedbackId: string, status: string): Promise { - await this.db.query( - ` - UPDATE plugin_feedback - SET status = $1, updated_at = now() - WHERE id = $2 - `, - [status, feedbackId], - ); - } - - /** - * Get feedback analytics - */ - async getFeedbackAnalytics(): Promise<{ - totalFeedback: number; - byCategory: { category: string; count: number }[]; - bySeverity: { severity: string; count: number }[]; - avgRating: number; - }> { - const totalResult = await this.db.query(`SELECT COUNT(*) as total FROM plugin_feedback`); - - const categoryResult = await this.db.query( - ` - SELECT category, COUNT(*) as count - FROM plugin_feedback - GROUP BY category - ORDER BY count DESC - `, - ); - - const severityResult = await this.db.query( - ` - SELECT severity, COUNT(*) as count - FROM plugin_feedback - GROUP BY severity - ORDER BY count DESC - `, - ); - - const ratingResult = await this.db.query(`SELECT AVG(rating) as avg FROM plugin_feedback`); - - return { - totalFeedback: totalResult.rows[0]?.total || 0, - byCategory: categoryResult.rows.map((row: any) => ({ - category: row.category, - count: row.count, - })), - bySeverity: severityResult.rows.map((row: any) => ({ - severity: row.severity, - count: row.count, - })), - avgRating: parseFloat(ratingResult.rows[0]?.avg) || 0, - }; - } - - private mapBetaDeveloper(row: any): BetaDeveloper { - return { - id: row.id, - email: row.email, - name: row.name, - organization: row.organization, - enrolledAt: row.enrolled_at, - status: row.status, - pluginsTested: row.plugins_tested || [], - feedbackCount: row.feedback_count || 0, - lastActivityAt: row.last_activity_at, - }; - } - - private mapPluginFeedback(row: any): PluginFeedback { - return { - id: row.id, - pluginId: row.plugin_id, - developerId: row.developer_id, - rating: row.rating, - category: row.category, - title: row.title, - description: row.description, - severity: row.severity, - status: row.status, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; - } -} diff --git a/src/certification-workflow-model.ts b/src/certification-workflow-model.ts deleted file mode 100644 index 6a459196..00000000 --- a/src/certification-workflow-model.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Certification Workflow Engine — data models - * Multi-stage approval workflow for plugin certifications - */ - -export type WorkflowStage = "validation" | "review" | "approval" | "release" | "completed"; -export type ApprovalStatus = "pending" | "approved" | "rejected" | "escalated" | "blocked"; -export type ReviewerRole = "validator" | "reviewer" | "approver" | "release_manager" | "admin"; - -export interface CertificationWorkflow { - id: string; - plugin_id: string; - plugin_version: string; - plugin_name: string; - current_stage: WorkflowStage; - status: ApprovalStatus; - validation_report_id?: string; - created_by: string; - created_at: string; - started_at?: string; - completed_at?: string; - expires_at?: string; - stages_completed: WorkflowStage[]; - approval_chain: ApprovalStep[]; - audit_trail: WorkflowAuditEvent[]; -} - -export interface ApprovalStep { - id: string; - workflow_id: string; - stage: WorkflowStage; - step_number: number; - required_role: ReviewerRole; - assigned_to?: string; - assigned_to_name?: string; - status: ApprovalStatus; - approved_by?: string; - approved_by_name?: string; - approved_at?: string; - rejection_reason?: string; - comments?: string; - deadline?: string; - escalated: boolean; - escalated_to?: string; - created_at: string; - updated_at: string; -} - -export interface WorkflowAuditEvent { - id: string; - workflow_id: string; - stage: WorkflowStage; - event_type: string; // "stage_entered", "approved", "rejected", "commented", "escalated" - actor_id: string; - actor_name: string; - actor_role: ReviewerRole; - details: Record; - timestamp: string; - created_at: string; -} - -export interface ApprovalChainTemplate { - id: string; - name: string; - certification_tier: string; // bronze, silver, gold, platinum - stages: { - stage: WorkflowStage; - step_number: number; - required_role: ReviewerRole; - min_approval_count: number; - escalation_deadline_hours?: number; - can_auto_approve?: boolean; - }[]; - created_at: string; - updated_at: string; -} - -export interface WorkflowMetrics { - total_workflows: number; - active_workflows: number; - completed_workflows: number; - failed_workflows: number; - average_completion_hours: number; - average_stage_duration_hours: Record; - approval_rate_percent: number; - rejection_rate_percent: number; - escalation_rate_percent: number; - bottleneck_stage: WorkflowStage; -} - -export interface ReviewerAssignment { - id: string; - workflow_id: string; - approval_step_id: string; - reviewer_id: string; - reviewer_name: string; - reviewer_role: ReviewerRole; - assigned_at: string; - response_deadline: string; - responded_at?: string; - response: "approved" | "rejected" | "escalated" | "no_response"; -} diff --git a/src/certification-workflow-service.test.ts b/src/certification-workflow-service.test.ts deleted file mode 100644 index 7cbcb3bc..00000000 --- a/src/certification-workflow-service.test.ts +++ /dev/null @@ -1,386 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { - createCertificationWorkflow, - assignReviewer, - approveStep, - rejectStep, - escalateStep, - getWorkflowStatus, - getPendingApprovals, - getAuditTrail, - getWorkflowMetrics, - listTemplates, - getWorkflowProgress, -} from "./certification-workflow-service.js"; - -describe("certification-workflow-service", () => { - const pluginId = "plugin-123"; - const version = "1.0.0"; - const userId = "user-456"; - - describe("createCertificationWorkflow", () => { - it("creates workflow for bronze tier", () => { - const { workflow, error } = createCertificationWorkflow( - pluginId, - version, - "Test Plugin", - "bronze", - userId, - ); - - assert.ok(!error); - assert.ok(workflow.id); - assert.equal(workflow.plugin_id, pluginId); - assert.equal(workflow.current_stage, "validation"); - assert.equal(workflow.status, "pending"); - }); - - it("creates approval chain with stages", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - assert.ok(workflow.approval_chain.length >= 3); - assert.ok( - workflow.approval_chain.some((s) => s.stage === "validation"), - ); - assert.ok(workflow.approval_chain.some((s) => s.stage === "review")); - }); - - it("creates audit trail entry", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "gold", - userId, - ); - - assert.ok(workflow.audit_trail.length > 0); - assert.ok( - workflow.audit_trail.some((e) => e.event_type === "workflow_created"), - ); - }); - }); - - describe("assignReviewer", () => { - it("assigns reviewer to step", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const step = workflow.approval_chain[0]; - - const { assignment, error } = assignReviewer( - workflow.id, - step.id, - "reviewer-123", - "John Reviewer", - "reviewer", - ); - - assert.ok(!error); - assert.ok(assignment.id); - assert.equal(assignment.reviewer_id, "reviewer-123"); - }); - - it("sets response deadline", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const step = workflow.approval_chain[0]; - const { assignment } = assignReviewer( - workflow.id, - step.id, - "reviewer-123", - "John Reviewer", - "reviewer", - ); - - assert.ok(assignment.response_deadline); - const deadline = new Date(assignment.response_deadline); - const now = new Date(); - assert.ok(deadline > now); - }); - }); - - describe("approveStep", () => { - it("approves step and moves to next stage", () => { - const { workflow: w1 } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const step = w1.approval_chain[0]; - const { step: approved, error } = approveStep( - w1.id, - step.id, - "reviewer-123", - "John Reviewer", - "Looks good", - ); - - assert.ok(!error); - assert.equal(approved?.status, "approved"); - assert.ok(approved?.approved_at); - - const { workflow: w2 } = getWorkflowStatus(w1.id); - assert.ok(w2?.current_stage !== "validation"); - }); - - it("records audit event", () => { - const { workflow: w1 } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const step = w1.approval_chain[0]; - approveStep(w1.id, step.id, "reviewer-123", "John Reviewer"); - - const { events } = getAuditTrail(w1.id); - assert.ok(events.some((e) => e.event_type === "approved")); - }); - - it("marks workflow completed when last step approved", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - // Approve all steps - workflow.approval_chain.forEach((step) => { - approveStep(workflow.id, step.id, "reviewer", "Reviewer"); - }); - - const { workflow: updated } = getWorkflowStatus(workflow.id); - assert.equal(updated?.status, "approved"); - assert.equal(updated?.completed_at, updated?.completed_at); // has value - }); - }); - - describe("rejectStep", () => { - it("rejects step and fails workflow", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const step = workflow.approval_chain[0]; - const { step: rejected } = rejectStep( - workflow.id, - step.id, - "reviewer-123", - "John Reviewer", - "Does not meet security standards", - ); - - assert.equal(rejected?.status, "rejected"); - assert.ok(rejected?.rejection_reason); - - const { workflow: w } = getWorkflowStatus(workflow.id); - assert.equal(w?.status, "rejected"); - }); - }); - - describe("escalateStep", () => { - it("escalates step to higher authority", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const step = workflow.approval_chain[0]; - const { step: escalated } = escalateStep( - workflow.id, - step.id, - "reviewer-123", - "admin-456", - "Needs expert review", - ); - - assert.equal(escalated?.escalated, true); - assert.equal(escalated?.escalated_to, "admin-456"); - assert.equal(escalated?.status, "escalated"); - }); - }); - - describe("getWorkflowStatus", () => { - it("returns workflow status", () => { - const { workflow: w1 } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const { workflow: w2 } = getWorkflowStatus(w1.id); - - assert.equal(w2?.id, w1.id); - assert.equal(w2?.status, "pending"); - }); - - it("fails for nonexistent workflow", () => { - const { workflow, error } = getWorkflowStatus("nonexistent"); - - assert.ok(error); - assert.ok(!workflow); - }); - }); - - describe("getPendingApprovals", () => { - it("gets pending approvals for reviewer", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const step = workflow.approval_chain[0]; - assignReviewer(workflow.id, step.id, "reviewer-123", "Reviewer", "reviewer"); - - const { pending } = getPendingApprovals("reviewer-123"); - - assert.ok(pending.length > 0); - assert.ok(pending.some((s) => s.assigned_to === "reviewer-123")); - }); - }); - - describe("getAuditTrail", () => { - it("returns audit trail for workflow", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const { events } = getAuditTrail(workflow.id); - - assert.ok(events.length > 0); - assert.ok(events.some((e) => e.event_type === "workflow_created")); - }); - - it("tracks workflow changes", () => { - const { workflow: w1 } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const step = w1.approval_chain[0]; - assignReviewer(w1.id, step.id, "reviewer-123", "Reviewer", "reviewer"); - approveStep(w1.id, step.id, "reviewer-123", "Reviewer"); - - const { events } = getAuditTrail(w1.id); - - assert.ok(events.some((e) => e.event_type === "reviewer_assigned")); - assert.ok(events.some((e) => e.event_type === "approved")); - }); - }); - - describe("getWorkflowProgress", () => { - it("calculates workflow progress", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const { progress_percent } = getWorkflowProgress(workflow.id); - - assert.equal(progress_percent, 0); // No steps approved yet - }); - - it("increases progress as steps complete", () => { - const { workflow } = createCertificationWorkflow( - pluginId, - version, - "Plugin", - "bronze", - userId, - ); - - const step1 = workflow.approval_chain[0]; - approveStep(workflow.id, step1.id, "reviewer", "Reviewer"); - - const { progress_percent } = getWorkflowProgress(workflow.id); - - assert.ok(progress_percent > 0); - assert.ok(progress_percent < 100); - }); - }); - - describe("listTemplates", () => { - it("lists approval chain templates", () => { - const { templates } = listTemplates(); - - assert.ok(templates.length > 0); - assert.ok( - templates.some((t) => t.certification_tier === "bronze"), - ); - assert.ok(templates.some((t) => t.certification_tier === "gold")); - }); - - it("templates have stages", () => { - const { templates } = listTemplates(); - - templates.forEach((t) => { - assert.ok(t.stages.length > 0); - t.stages.forEach((s) => { - assert.ok(s.stage); - assert.ok(s.required_role); - assert.ok(s.min_approval_count >= 1); - }); - }); - }); - }); - - describe("getWorkflowMetrics", () => { - it("returns workflow metrics", () => { - createCertificationWorkflow(pluginId, version, "Plugin", "bronze", userId); - - const metrics = getWorkflowMetrics(); - - assert.ok(metrics.total_workflows >= 1); - assert.ok(metrics.average_completion_hours > 0); - assert.ok(metrics.approval_rate_percent >= 0); - }); - }); -}); diff --git a/src/certification-workflow-service.ts b/src/certification-workflow-service.ts deleted file mode 100644 index 88370b80..00000000 --- a/src/certification-workflow-service.ts +++ /dev/null @@ -1,411 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - CertificationWorkflow, - ApprovalStep, - WorkflowAuditEvent, - ApprovalChainTemplate, - WorkflowMetrics, - ReviewerAssignment, - WorkflowStage, - ReviewerRole, -} from "./certification-workflow-model.js"; - -const workflows = new Map(); -const templates = new Map(); -const assignments = new Map(); - -// Default approval chain templates -const DEFAULT_TEMPLATES: ApprovalChainTemplate[] = [ - { - id: `template_${randomUUID()}`, - name: "Bronze Tier Chain", - certification_tier: "bronze", - stages: [ - { stage: "validation", step_number: 1, required_role: "validator", min_approval_count: 1 }, - { stage: "review", step_number: 2, required_role: "reviewer", min_approval_count: 1 }, - { stage: "approval", step_number: 3, required_role: "approver", min_approval_count: 1 }, - { stage: "release", step_number: 4, required_role: "release_manager", min_approval_count: 1 }, - ], - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - { - id: `template_${randomUUID()}`, - name: "Gold Tier Chain", - certification_tier: "gold", - stages: [ - { stage: "validation", step_number: 1, required_role: "validator", min_approval_count: 1 }, - { stage: "review", step_number: 2, required_role: "reviewer", min_approval_count: 2 }, - { stage: "approval", step_number: 3, required_role: "approver", min_approval_count: 2 }, - { stage: "release", step_number: 4, required_role: "release_manager", min_approval_count: 1 }, - ], - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, -]; - -DEFAULT_TEMPLATES.forEach((t) => templates.set(t.id, t)); - -/** - * Create certification workflow - */ -export function createCertificationWorkflow( - plugin_id: string, - plugin_version: string, - plugin_name: string, - tier: string, - created_by: string, -): { workflow: CertificationWorkflow; error?: string } { - const template = Array.from(templates.values()).find((t) => t.certification_tier === tier); - - if (!template) { - return { workflow: {} as CertificationWorkflow, error: "Template not found" }; - } - - const workflow: CertificationWorkflow = { - id: `workflow_${randomUUID()}`, - plugin_id, - plugin_version, - plugin_name, - current_stage: "validation", - status: "pending", - created_by, - created_at: new Date().toISOString(), - started_at: new Date().toISOString(), - stages_completed: [], - approval_chain: [], - audit_trail: [], - }; - - // Build approval chain from template - template.stages.forEach((stage) => { - const step: ApprovalStep = { - id: `step_${randomUUID()}`, - workflow_id: workflow.id, - stage: stage.stage, - step_number: stage.step_number, - required_role: stage.required_role, - status: "pending", - escalated: false, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - workflow.approval_chain.push(step); - }); - - workflows.set(workflow.id, workflow); - logEvent(workflow.id, "validation", "workflow_created", created_by, "admin", { - tier, - }); - - return { workflow }; -} - -/** - * Assign reviewer to approval step - */ -export function assignReviewer( - workflow_id: string, - step_id: string, - reviewer_id: string, - reviewer_name: string, - reviewer_role: ReviewerRole, -): { assignment: ReviewerAssignment; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow) { - return { assignment: {} as ReviewerAssignment, error: "Workflow not found" }; - } - - const step = workflow.approval_chain.find((s) => s.id === step_id); - if (!step) { - return { assignment: {} as ReviewerAssignment, error: "Step not found" }; - } - - const deadline = new Date(); - deadline.setHours(deadline.getHours() + 48); - - const assignment: ReviewerAssignment = { - id: `assign_${randomUUID()}`, - workflow_id, - approval_step_id: step_id, - reviewer_id, - reviewer_name, - reviewer_role, - assigned_at: new Date().toISOString(), - response_deadline: deadline.toISOString(), - response: "no_response", - }; - - assignments.set(assignment.id, assignment); - step.assigned_to = reviewer_id; - step.assigned_to_name = reviewer_name; - - logEvent(workflow_id, step.stage, "reviewer_assigned", reviewer_id, reviewer_role, { - step_id, - reviewer_name, - }); - - return { assignment }; -} - -/** - * Approve approval step - */ -export function approveStep( - workflow_id: string, - step_id: string, - approved_by: string, - approved_by_name: string, - comments?: string, -): { step: ApprovalStep | null; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow) { - return { step: null, error: "Workflow not found" }; - } - - const step = workflow.approval_chain.find((s) => s.id === step_id); - if (!step) { - return { step: null, error: "Step not found" }; - } - - step.status = "approved"; - step.approved_by = approved_by; - step.approved_by_name = approved_by_name; - step.approved_at = new Date().toISOString(); - step.comments = comments; - step.updated_at = new Date().toISOString(); - - // Move to next stage - const nextStep = workflow.approval_chain.find( - (s) => s.step_number === step.step_number + 1, - ); - if (nextStep) { - workflow.current_stage = nextStep.stage; - } else { - workflow.current_stage = "completed"; - workflow.status = "approved"; - workflow.completed_at = new Date().toISOString(); - } - - workflow.stages_completed.push(step.stage); - - logEvent(workflow_id, step.stage, "approved", approved_by, "approver", { - step_id, - comments, - }); - - return { step }; -} - -/** - * Reject approval step - */ -export function rejectStep( - workflow_id: string, - step_id: string, - rejected_by: string, - rejected_by_name: string, - reason: string, -): { step: ApprovalStep | null; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow) { - return { step: null, error: "Workflow not found" }; - } - - const step = workflow.approval_chain.find((s) => s.id === step_id); - if (!step) { - return { step: null, error: "Step not found" }; - } - - step.status = "rejected"; - step.approved_by = rejected_by; - step.approved_by_name = rejected_by_name; - step.rejection_reason = reason; - step.updated_at = new Date().toISOString(); - - workflow.status = "rejected"; - - logEvent(workflow_id, step.stage, "rejected", rejected_by, "reviewer", { - step_id, - reason, - }); - - return { step }; -} - -/** - * Escalate step to higher authority - */ -export function escalateStep( - workflow_id: string, - step_id: string, - escalated_by: string, - escalated_to: string, - reason: string, -): { step: ApprovalStep | null; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow) { - return { step: null, error: "Workflow not found" }; - } - - const step = workflow.approval_chain.find((s) => s.id === step_id); - if (!step) { - return { step: null, error: "Step not found" }; - } - - step.escalated = true; - step.escalated_to = escalated_to; - step.status = "escalated"; - step.updated_at = new Date().toISOString(); - - logEvent(workflow_id, step.stage, "escalated", escalated_by, "reviewer", { - step_id, - escalated_to, - reason, - }); - - return { step }; -} - -/** - * Get workflow status - */ -export function getWorkflowStatus( - workflow_id: string, -): { workflow: CertificationWorkflow | null; error?: string } { - const workflow = workflows.get(workflow_id); - return { - workflow: workflow || null, - error: workflow ? undefined : "Workflow not found", - }; -} - -/** - * Get pending approvals for reviewer - */ -export function getPendingApprovals( - reviewer_id: string, -): { pending: ApprovalStep[] } { - const pending: ApprovalStep[] = []; - - workflows.forEach((workflow) => { - workflow.approval_chain.forEach((step) => { - if (step.assigned_to === reviewer_id && step.status === "pending") { - pending.push(step); - } - }); - }); - - return { pending }; -} - -/** - * Log audit event - */ -function logEvent( - workflow_id: string, - stage: WorkflowStage, - event_type: string, - actor_id: string, - actor_role: ReviewerRole, - details: Record, -): void { - const workflow = workflows.get(workflow_id); - if (!workflow) return; - - const event: WorkflowAuditEvent = { - id: `event_${randomUUID()}`, - workflow_id, - stage, - event_type, - actor_id, - actor_name: actor_id, - actor_role, - details, - timestamp: new Date().toISOString(), - created_at: new Date().toISOString(), - }; - - workflow.audit_trail.push(event); -} - -/** - * Get audit trail - */ -export function getAuditTrail(workflow_id: string): { events: WorkflowAuditEvent[] } { - const workflow = workflows.get(workflow_id); - return { events: workflow?.audit_trail || [] }; -} - -/** - * Get workflow metrics - */ -export function getWorkflowMetrics(): WorkflowMetrics { - const allWorkflows = Array.from(workflows.values()); - const completed = allWorkflows.filter((w) => w.status === "approved").length; - const rejected = allWorkflows.filter((w) => w.status === "rejected").length; - const active = allWorkflows.filter( - (w) => w.status === "pending" || w.status === "escalated", - ).length; - - const stages: Record = { - validation: 0, - review: 0, - approval: 0, - release: 0, - completed: 0, - }; - - allWorkflows.forEach((w) => { - w.stages_completed.forEach((stage) => { - stages[stage]++; - }); - }); - - const stageDurations: Record = { - validation: 4, - review: 6, - approval: 8, - release: 2, - completed: 20, - }; - - return { - total_workflows: allWorkflows.length, - active_workflows: active, - completed_workflows: completed, - failed_workflows: rejected, - average_completion_hours: 20, - average_stage_duration_hours: stageDurations, - approval_rate_percent: allWorkflows.length > 0 ? (completed / allWorkflows.length) * 100 : 0, - rejection_rate_percent: allWorkflows.length > 0 ? (rejected / allWorkflows.length) * 100 : 0, - escalation_rate_percent: 5, - bottleneck_stage: "review", - }; -} - -/** - * List approval chain templates - */ -export function listTemplates(): { templates: ApprovalChainTemplate[] } { - return { templates: Array.from(templates.values()) }; -} - -/** - * Get workflow progress - */ -export function getWorkflowProgress(workflow_id: string): { progress_percent: number; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow) { - return { progress_percent: 0, error: "Workflow not found" }; - } - - const totalSteps = workflow.approval_chain.length; - const completedSteps = workflow.approval_chain.filter( - (s) => s.status === "approved" || s.status === "rejected", - ).length; - - const progress = totalSteps > 0 ? (completedSteps / totalSteps) * 100 : 0; - - return { progress_percent: progress }; -} diff --git a/src/moderation-system.test.ts b/src/moderation-system.test.ts deleted file mode 100644 index 4789bf42..00000000 --- a/src/moderation-system.test.ts +++ /dev/null @@ -1,523 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { - ModerationSystem, - type ModerationReport, - type ContentType, - type ViolationType, -} from "./moderation-system.js"; - -// ─── Helpers ────────────────────────────────────────────────────────────────── - -function makeReport( - system: ModerationSystem, - contentId: string, - contentType: ContentType = "review", - overrides: { reason?: ViolationType; reportedBy?: string; description?: string } = {}, -): ModerationReport { - return system.fileReport( - contentId, - contentType, - overrides.reportedBy || "user-reporter", - overrides.reason || "spam", - overrides.description || "This looks like spam", - ); -} - -// ─── Tests ──────────────────────────────────────────────────────────────────── - -describe("ModerationSystem", () => { - describe("initialization", () => { - it("creates system instance", () => { - const system = new ModerationSystem(); - assert(system); - }); - - it("starts with empty caches", () => { - const system = new ModerationSystem(); - assert.equal(system.getReportsCache().size, 0); - assert.equal(system.getActionsCache().size, 0); - assert.equal(system.getAppealCache().size, 0); - }); - }); - - describe("fileReport", () => { - let system: ModerationSystem; - - beforeEach(() => { - system = new ModerationSystem(); - }); - - it("files a moderation report", () => { - const report = makeReport(system, "review-1"); - assert(report.id); - assert.equal(report.contentId, "review-1"); - assert.equal(report.status, "pending"); - }); - - it("stores report metadata", () => { - const report = makeReport(system, "review-1", "review", { - reason: "abuse", - reportedBy: "user-a", - description: "Offensive language", - }); - assert.equal(report.reason, "abuse"); - assert.equal(report.reportedBy, "user-a"); - assert.equal(report.description, "Offensive language"); - }); - - it("records evidence", () => { - const evidence = ["screenshot.png", "logs.txt"]; - const report = system.fileReport("review-1", "review", "user-a", "spam", "Spam", evidence); - assert.deepEqual(report.evidence, evidence); - }); - - it("supports all content types", () => { - const types: ContentType[] = ["plugin", "review", "comment", "author"]; - for (const type of types) { - const report = makeReport(system, `content-${type}`, type); - assert.equal(report.contentType, type); - } - }); - }); - - describe("getReport / getContentReports", () => { - let system: ModerationSystem; - - beforeEach(() => { - system = new ModerationSystem(); - makeReport(system, "review-1"); - makeReport(system, "review-1", "review", { reason: "abuse" }); - makeReport(system, "review-2"); - }); - - it("retrieves report by ID", () => { - const reports = [...system.getReportsCache().values()]; - const found = system.getReport(reports[0].id); - assert(found); - assert.equal(found.id, reports[0].id); - }); - - it("returns null for unknown report", () => { - const report = system.getReport("unknown"); - assert.equal(report, null); - }); - - it("gets all reports for content", () => { - const reports = system.getContentReports("review-1"); - assert.equal(reports.length, 2); - assert(reports.every((r) => r.contentId === "review-1")); - }); - - it("returns empty for unknown content", () => { - const reports = system.getContentReports("unknown"); - assert.equal(reports.length, 0); - }); - }); - - describe("moderation queue", () => { - let system: ModerationSystem; - - beforeEach(() => { - system = new ModerationSystem(); - }); - - it("adds reports to queue with low priority for 1 report", () => { - makeReport(system, "content-1"); - const queue = system.getQueue(); - assert.equal(queue.length, 1); - assert.equal(queue[0].priority, "low"); - }); - - it("escalates priority with multiple reports", () => { - for (let i = 0; i < 3; i++) { - makeReport(system, "content-1"); - } - const queue = system.getQueue(); - assert.equal(queue[0].priority, "medium"); - }); - - it("escalates to high priority at 5 reports", () => { - for (let i = 0; i < 5; i++) { - makeReport(system, "content-1"); - } - const queue = system.getQueue(); - assert.equal(queue[0].priority, "high"); - }); - - it("escalates to critical at 10 reports", () => { - for (let i = 0; i < 10; i++) { - makeReport(system, "content-1"); - } - const queue = system.getQueue(); - assert.equal(queue[0].priority, "critical"); - }); - - it("prioritizes high-severity violations", () => { - system.fileReport("content-1", "review", "user-a", "spam", "spam"); - system.fileReport("content-2", "review", "user-b", "malware", "malware alert"); - - const queue = system.getQueue(); - const malwareEntry = queue.find((q) => q.contentId === "content-2"); - assert(malwareEntry); - assert.equal(malwareEntry.priority, "critical"); - }); - - it("sorts queue by priority", () => { - for (let i = 0; i < 10; i++) system.fileReport(`content-${i}`, "review", "user", "spam", ""); - - const queue = system.getQueue(); - for (let i = 1; i < queue.length; i++) { - const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 }; - assert( - priorityOrder[queue[i - 1].priority as keyof typeof priorityOrder] <= - priorityOrder[queue[i].priority as keyof typeof priorityOrder], - ); - } - }); - - it("respects limit parameter", () => { - for (let i = 0; i < 30; i++) system.fileReport(`content-${i}`, "review", "user", "spam", ""); - const queue = system.getQueue(5); - assert.equal(queue.length, 5); - }); - - it("provides queue stats", () => { - for (let i = 0; i < 3; i++) system.fileReport(`c-${i}`, "review", "user", "spam", ""); - const stats = system.getQueueStats(); - assert.equal(stats.total, 3); - assert(stats.low > 0); - }); - }); - - describe("detectSpam", () => { - let system: ModerationSystem; - - beforeEach(() => { - system = new ModerationSystem(); - }); - - it("detects abusive language", () => { - const signals = system.detectSpam("I hate this stupid plugin", {}); - assert(signals.hasAbusiveLanguage); - assert(signals.score > 0); - }); - - it("detects excessive links", () => { - const content = "Check out https://example.com and https://other.com and https://third.com and https://fourth.com"; - const signals = system.detectSpam(content, {}); - assert(signals.hasExcessiveLinks); - assert(signals.score > 0); - }); - - it("detects all-caps text", () => { - const signals = system.detectSpam("THIS IS SPAM AND YOU SHOULD BUY NOW", {}); - assert(signals.hasSuspiciousPatterns); - assert(signals.score > 0); - }); - - it("detects repeated characters", () => { - const signals = system.detectSpam("BUYYY NOOOWWWW!!!!!!", {}); - assert(signals.hasSuspiciousPatterns); - }); - - it("detects spam keywords", () => { - const signals = system.detectSpam("LIMITED OFFER - BUY NOW GUARANTEED!", {}); - assert(signals.hasSuspiciousPatterns); - }); - - it("detects new accounts", () => { - const createdAt = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(); - const signals = system.detectSpam("normal comment", { createdAt }); - assert(signals.isNewAccount); - assert(signals.score > 0); - }); - - it("does not flag old accounts as new", () => { - const createdAt = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(); - const signals = system.detectSpam("normal comment", { createdAt }); - assert(!signals.isNewAccount); - }); - - it("scores legitimate content as low", () => { - const signals = system.detectSpam("This is a legitimate review with helpful information.", {}); - assert(signals.score < 20); - }); - - it("scores spam as high", () => { - const signals = system.detectSpam( - "BUY NOW!!! LIMITED OFFER!!! CLICK HERE NOW https://spam.com https://spam2.com https://spam3.com", - { createdAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString() }, - ); - assert(signals.score >= 40); - }); - }); - - describe("takeAction", () => { - let system: ModerationSystem; - let reportId: string; - - beforeEach(() => { - system = new ModerationSystem(); - const report = makeReport(system, "review-1", "review", { reportedBy: "user-bad" }); - reportId = report.id; - }); - - it("issues a warning", () => { - const action = system.takeAction(reportId, "review-1", "warning", "Misleading content"); - assert.equal(action.action, "warning"); - assert.equal(action.reason, "Misleading content"); - }); - - it("unpublishes content", () => { - const action = system.takeAction(reportId, "review-1", "unpublish", "Violates guidelines"); - assert.equal(action.action, "unpublish"); - }); - - it("suspends user temporarily", () => { - const duration = 7; // days - const action = system.takeAction(reportId, "review-1", "suspend_user", "Abuse", duration); - assert.equal(action.action, "suspend_user"); - assert.equal(action.duration, duration); - }); - - it("bans user permanently", () => { - const action = system.takeAction(reportId, "review-1", "ban_user", "Repeated abuse"); - assert.equal(action.action, "ban_user"); - assert.equal(action.duration, undefined); - }); - - it("updates report status after action", () => { - system.takeAction(reportId, "review-1", "unpublish", "Violates guidelines"); - const report = system.getReport(reportId); - assert.equal(report?.status, "approved"); - }); - - it("tracks suspension expiration", () => { - system.takeAction(reportId, "review-1", "suspend_user", "Abuse", 7); - assert(system.isSuspended("user-bad")); - }); - - it("tracks permanent bans", () => { - system.takeAction(reportId, "review-1", "ban_user", "Repeated abuse"); - assert(system.isBanned("user-bad")); - }); - - it("gets suspension status", () => { - system.takeAction(reportId, "review-1", "suspend_user", "Abuse", 14); - const status = system.getSuspensionStatus("user-bad"); - assert(status); - assert(status.until > new Date()); - assert.equal(status.reason, "Abuse"); - }); - }); - - describe("fileAppeal", () => { - let system: ModerationSystem; - let actionId: string; - let reportId: string; - - beforeEach(() => { - system = new ModerationSystem(); - const report = makeReport(system, "review-1"); - reportId = report.id; - const action = system.takeAction(reportId, "review-1", "suspend_user", "Abuse", 7); - actionId = action.id; - }); - - it("files an appeal against an action", () => { - const appeal = system.fileAppeal( - actionId, - reportId, - "review-1", - "user-bad", - "I did not violate guidelines", - ); - assert(appeal.id); - assert.equal(appeal.status, "pending"); - }); - - it("updates report status to appealed", () => { - system.fileAppeal(actionId, reportId, "review-1", "user-bad", "Appeal reason"); - const report = system.getReport(reportId); - assert.equal(report?.status, "appealed"); - }); - - it("records appeal evidence", () => { - const evidence = ["context.txt", "explanation.pdf"]; - const appeal = system.fileAppeal( - actionId, - reportId, - "review-1", - "user-bad", - "Appeal reason", - evidence, - ); - assert.deepEqual(appeal.evidence, evidence); - }); - - it("retrieves appeal by ID", () => { - const appeal = system.fileAppeal(actionId, reportId, "review-1", "user-bad", "Appeal"); - const found = system.getAppeal(appeal.id); - assert.equal(found?.id, appeal.id); - }); - - it("returns null for unknown appeal", () => { - const appeal = system.getAppeal("unknown"); - assert.equal(appeal, null); - }); - }); - - describe("reviewAppeal", () => { - let system: ModerationSystem; - let actionId: string; - let reportId: string; - let appealId: string; - - beforeEach(() => { - system = new ModerationSystem(); - const report = makeReport(system, "review-1", "review", { reportedBy: "user-bad" }); - reportId = report.id; - const action = system.takeAction(reportId, "review-1", "suspend_user", "Abuse", 7); - actionId = action.id; - const appeal = system.fileAppeal(actionId, reportId, "review-1", "user-bad", "I was wronged"); - appealId = appeal.id; - }); - - it("upholds appeal decision", () => { - system.reviewAppeal(appealId, "moderator-1", "upheld", "Appeal rejected"); - const appeal = system.getAppeal(appealId); - assert.equal(appeal?.status, "upheld"); - assert.equal(appeal?.reviewedBy, "moderator-1"); - }); - - it("overturns appeal decision", () => { - system.reviewAppeal(appealId, "moderator-1", "overturned", "Decision reversed"); - const appeal = system.getAppeal(appealId); - assert.equal(appeal?.status, "overturned"); - }); - - it("removes suspension when appeal overturned", () => { - assert(system.isSuspended("user-bad")); - system.reviewAppeal(appealId, "moderator-1", "overturned", "Decision reversed"); - assert(!system.isSuspended("user-bad")); - }); - - it("removes ban when appeal overturned", () => { - const report2 = makeReport(system, "review-2", "review", { reportedBy: "user-bad2" }); - const action2 = system.takeAction(report2.id, "review-2", "ban_user", "Bad"); - const appeal2 = system.fileAppeal(action2.id, report2.id, "review-2", "user-bad2", "Appeal"); - - assert(system.isBanned("user-bad2")); - system.reviewAppeal(appeal2.id, "mod", "overturned", "Overturned"); - assert(!system.isBanned("user-bad2")); - }); - - it("returns null for non-pending appeal", () => { - system.reviewAppeal(appealId, "mod", "upheld", "Upheld"); - const result = system.reviewAppeal(appealId, "mod", "upheld", "Try again"); - assert.equal(result, null); - }); - - it("gets pending appeals", () => { - system.fileAppeal(actionId, reportId, "review-1", "user-bad", "Appeal 1"); - const report2 = makeReport(system, "review-2", "review", { reportedBy: "user-2" }); - const action2 = system.takeAction(report2.id, "review-2", "warning", "Warning"); - system.fileAppeal(action2.id, report2.id, "review-2", "user-2", "Appeal 2"); - - const pending = system.getPendingAppeals(); - assert(pending.length >= 2); - assert(pending.every((a) => a.status === "pending")); - }); - }); - - describe("community guidelines", () => { - let system: ModerationSystem; - - beforeEach(() => { - system = new ModerationSystem(); - }); - - it("registers a guideline", () => { - const guideline = system.registerGuideline( - "No spam", - "Do not post spam or promotional content", - ["Buy my plugin!", "Limited time offer"], - "warning", - ); - assert(guideline.id); - assert.equal(guideline.title, "No spam"); - assert.equal(guideline.active, true); - }); - - it("retrieves guideline by ID", () => { - const reg = system.registerGuideline("Respect", "Be respectful", [], "warning"); - const found = system.getGuideline(reg.id); - assert.equal(found?.id, reg.id); - }); - - it("returns null for unknown guideline", () => { - const found = system.getGuideline("unknown"); - assert.equal(found, null); - }); - - it("gets only active guidelines", () => { - system.registerGuideline("Active", "Stay active", [], "warning"); - const inactive = system.registerGuideline("Inactive", "Will disable", [], "warning"); - system.deactivateGuideline(inactive.id); - - const active = system.getActiveGuidelines(); - assert(active.every((g) => g.active)); - assert(!active.map((g) => g.id).includes(inactive.id)); - }); - - it("deactivates guideline", () => { - const guideline = system.registerGuideline("Test", "Test", [], "warning"); - const deactivated = system.deactivateGuideline(guideline.id); - assert(deactivated); - const found = system.getGuideline(guideline.id); - assert(!found?.active); - }); - }); - - describe("moderation stats", () => { - let system: ModerationSystem; - - beforeEach(() => { - system = new ModerationSystem(); - }); - - it("counts total reports", () => { - makeReport(system, "c1"); - makeReport(system, "c2"); - makeReport(system, "c3"); - const stats = system.getModerationStats(); - assert.equal(stats.totalReports, 3); - }); - - it("counts approved reports", () => { - const r1 = makeReport(system, "c1"); - system.takeAction(r1.id, "c1", "unpublish", "Bad"); - makeReport(system, "c2"); - const stats = system.getModerationStats(); - assert.equal(stats.approvedCount, 1); - }); - - it("counts suspensions and bans", () => { - const r1 = makeReport(system, "c1", "review", { reportedBy: "user-1" }); - const r2 = makeReport(system, "c2", "review", { reportedBy: "user-2" }); - system.takeAction(r1.id, "c1", "suspend_user", "Spam", 7); - system.takeAction(r2.id, "c2", "ban_user", "Abuse"); - const stats = system.getModerationStats(); - assert.equal(stats.suspensionsCount, 1); - assert.equal(stats.bansCount, 1); - }); - - it("returns all stats", () => { - const stats = system.getModerationStats(); - assert(typeof stats.totalReports === "number"); - assert(typeof stats.approvedCount === "number"); - assert(typeof stats.averageResolutionTimeMs === "number"); - }); - }); -}); diff --git a/src/moderation-system.ts b/src/moderation-system.ts deleted file mode 100644 index 13e89a43..00000000 --- a/src/moderation-system.ts +++ /dev/null @@ -1,539 +0,0 @@ -// ─── Types ──────────────────────────────────────────────────────────────────── - -import { IdGenerators } from "./id-generator.js"; - -export type ContentType = "plugin" | "review" | "comment" | "author"; -export type ViolationType = - | "spam" - | "abuse" - | "misleading" - | "copyright" - | "malware" - | "other"; -export type ModerationStatus = "pending" | "approved" | "rejected" | "appealed" | "resolved"; -export type AppealStatus = "pending" | "upheld" | "overturned" | "closed"; - -export interface ContentItem { - id: string; - type: ContentType; - pluginId?: string; - reviewId?: string; - commentId?: string; - authorId: string; - content: string; - metadata: Record; - createdAt: string; -} - -export interface ModerationReport { - id: string; - contentId: string; - contentType: ContentType; - reportedBy: string; - reason: ViolationType; - description: string; - evidence: string[]; - status: ModerationStatus; - createdAt: string; - updatedAt: string; -} - -export interface ModerationAction { - id: string; - reportId: string; - contentId: string; - action: "warning" | "suspend_comment" | "unpublish" | "suspend_user" | "ban_user"; - reason: string; - duration?: number; // in days, null = permanent - appliedBy: string; - appliedAt: string; - metadata: Record; -} - -export interface Appeal { - id: string; - actionId: string; - reportId: string; - contentId: string; - appealedBy: string; - reason: string; - evidence: string[]; - status: AppealStatus; - reviewedBy?: string; - reviewedAt?: string; - decision?: string; - createdAt: string; - updatedAt: string; -} - -export interface ModerationQueue { - reportId: string; - contentId: string; - contentType: ContentType; - reportCount: number; - priority: "low" | "medium" | "high" | "critical"; - createdAt: string; - reason?: string; -} - -export interface SpamSignals { - hasMultipleReports: boolean; - hasAbusiveLanguage: boolean; - hasExcessiveLinks: boolean; - hasSuspiciousPatterns: boolean; - isNewAccount: boolean; // created < 7 days ago - score: number; // 0-100 -} - -export interface ModerationStats { - totalReports: number; - approvedCount: number; - rejectedCount: number; - pendingCount: number; - appealsCount: number; - suspensionsCount: number; - bansCount: number; - averageResolutionTimeMs: number; -} - -export interface CommunityGuideline { - id: string; - title: string; - description: string; - examples: string[]; - consequenceLevel: "warning" | "suspension" | "ban"; - active: boolean; - createdAt: string; - updatedAt: string; -} - -// ─── ModerationSystem ───────────────────────────────────────────────────────── - -export class ModerationSystem { - private reports: Map = new Map(); - private actions: Map = new Map(); - private appeals: Map = new Map(); - private suspendedUsers: Map = new Map(); - private bannedUsers: Set = new Set(); - private guidelines: Map = new Map(); - private reportQueue: ModerationQueue[] = []; - - // ─── Reporting & Flagging ───────────────────────────────────────────────── - - /** - * File a moderation report against content (plugin, review, comment, author). - */ - fileReport( - contentId: string, - contentType: ContentType, - reportedBy: string, - reason: ViolationType, - description: string, - evidence: string[] = [], - ): ModerationReport { - const reportId = IdGenerators.report(); - const report: ModerationReport = { - id: reportId, - contentId, - contentType, - reportedBy, - reason, - description, - evidence, - status: "pending", - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }; - this.reports.set(reportId, report); - - // Add to moderation queue - this.updateQueue(contentId, contentType, reportedBy); - - return report; - } - - getReport(reportId: string): ModerationReport | null { - return this.reports.get(reportId) || null; - } - - getContentReports(contentId: string): ModerationReport[] { - return [...this.reports.values()].filter((r) => r.contentId === contentId); - } - - // ─── Queue Management ───────────────────────────────────────────────────── - - /** - * Update moderation queue with new report. - * Tracks priority based on report count and violation type. - */ - private updateQueue(contentId: string, contentType: ContentType, reportedBy: string): void { - const reports = this.getContentReports(contentId); - let priority: "low" | "medium" | "high" | "critical" = "low"; - - if (reports.length >= 10) { - priority = "critical"; - } else if (reports.length >= 5) { - priority = "high"; - } else if (reports.length >= 3) { - priority = "medium"; - } - - // Check for high-severity violations - if (reports.some((r) => ["malware", "copyright", "abuse"].includes(r.reason))) { - priority = "critical"; - } - - const queueEntry: ModerationQueue = { - reportId: reports[reports.length - 1].id, - contentId, - contentType, - reportCount: reports.length, - priority, - createdAt: new Date().toISOString(), - }; - - // Remove duplicate if exists - this.reportQueue = this.reportQueue.filter((q) => q.contentId !== contentId); - this.reportQueue.push(queueEntry); - this.reportQueue.sort( - (a, b) => - ({ critical: 0, high: 1, medium: 2, low: 3 }[b.priority] as number) - - ({ critical: 0, high: 1, medium: 2, low: 3 }[a.priority] as number), - ); - } - - getQueue(limit = 20): ModerationQueue[] { - return this.reportQueue.slice(0, limit); - } - - getQueueStats(): { - total: number; - critical: number; - high: number; - medium: number; - low: number; - } { - const stats = { total: this.reportQueue.length, critical: 0, high: 0, medium: 0, low: 0 }; - for (const q of this.reportQueue) { - stats[q.priority]++; - } - return stats; - } - - // ─── Automated Spam Detection ───────────────────────────────────────────── - - /** - * Analyze content for spam signals. - * Returns a score 0-100 indicating spam likelihood. - */ - detectSpam(content: string, metadata: Record): SpamSignals { - const signals: SpamSignals = { - hasMultipleReports: false, - hasAbusiveLanguage: false, - hasExcessiveLinks: false, - hasSuspiciousPatterns: false, - isNewAccount: false, - score: 0, - }; - - // Abusive language detection (simple keyword-based) - const abusiveWords = [ - "kill", - "hate", - "stupid", - "idiot", - "worthless", - "deserve to die", - ]; - if (abusiveWords.some((word) => content.toLowerCase().includes(word))) { - signals.hasAbusiveLanguage = true; - signals.score += 30; - } - - // Excessive links (> 3 links per 100 chars) - const linkCount = (content.match(/https?:\/\//g) || []).length; - if (linkCount > Math.max(3, content.length / 100)) { - signals.hasExcessiveLinks = true; - signals.score += 25; - } - - // Suspicious patterns: all caps, repeated chars, spam keywords - const allCaps = (content.match(/[A-Z]/g) || []).length > content.length * 0.8; - const repeatedChars = /(.)\1{4,}/.test(content); - const spamKeywords = [ - "click here now", - "buy now", - "limited offer", - "act now", - "guaranteed", - ]; - const hasSuspicious = - allCaps || repeatedChars || spamKeywords.some((kw) => content.toLowerCase().includes(kw)); - - if (hasSuspicious) { - signals.hasSuspiciousPatterns = true; - signals.score += 25; - } - - // Check if author is new - if (metadata.createdAt && typeof metadata.createdAt === "string") { - const createdDate = new Date(metadata.createdAt); - const ageMs = Date.now() - createdDate.getTime(); - const ageDays = ageMs / (1000 * 60 * 60 * 24); - if (ageDays < 7) { - signals.isNewAccount = true; - signals.score += 20; - } - } - - return signals; - } - - // ─── Moderation Actions ─────────────────────────────────────────────────── - - /** - * Take a moderation action: warning, suspend, or ban. - */ - takeAction( - reportId: string, - contentId: string, - action: "warning" | "suspend_comment" | "unpublish" | "suspend_user" | "ban_user", - reason: string, - duration?: number, - appliedBy: string = "system", - ): ModerationAction { - const actionId = IdGenerators.modAction(); - - const modAction: ModerationAction = { - id: actionId, - reportId, - contentId, - action, - reason, - duration, - appliedBy, - appliedAt: new Date().toISOString(), - metadata: {}, - }; - - this.actions.set(actionId, modAction); - - // Update report status - const report = this.reports.get(reportId); - if (report) { - report.status = action === "warning" ? "approved" : "approved"; - report.updatedAt = new Date().toISOString(); - } - - // Handle user suspensions/bans - const report2 = this.reports.get(reportId); - if (report2) { - if (action === "suspend_user" && duration) { - const until = new Date(Date.now() + duration * 24 * 60 * 60 * 1000); - this.suspendedUsers.set(report2.reportedBy, { until, reason }); - } else if (action === "ban_user") { - this.bannedUsers.add(report2.reportedBy); - } - } - - return modAction; - } - - getAction(actionId: string): ModerationAction | null { - return this.actions.get(actionId) || null; - } - - getContentActions(contentId: string): ModerationAction[] { - return [...this.actions.values()].filter((a) => a.contentId === contentId); - } - - isSuspended(userId: string): boolean { - const suspension = this.suspendedUsers.get(userId); - if (!suspension) return false; - return new Date() < suspension.until; - } - - isBanned(userId: string): boolean { - return this.bannedUsers.has(userId); - } - - getSuspensionStatus(userId: string): { until: Date; reason: string } | null { - return this.suspendedUsers.get(userId) || null; - } - - // ─── Appeals ────────────────────────────────────────────────────────────── - - /** - * File an appeal against a moderation action. - */ - fileAppeal( - actionId: string, - reportId: string, - contentId: string, - appealedBy: string, - reason: string, - evidence: string[] = [], - ): Appeal { - const appealId = IdGenerators.appeal(); - const appeal: Appeal = { - id: appealId, - actionId, - reportId, - contentId, - appealedBy, - reason, - evidence, - status: "pending", - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }; - - this.appeals.set(appealId, appeal); - - // Update report status - const report = this.reports.get(reportId); - if (report) { - report.status = "appealed"; - report.updatedAt = new Date().toISOString(); - } - - return appeal; - } - - getAppeal(appealId: string): Appeal | null { - return this.appeals.get(appealId) || null; - } - - getPendingAppeals(limit = 20): Appeal[] { - return [...this.appeals.values()] - .filter((a) => a.status === "pending") - .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()) - .slice(0, limit); - } - - /** - * Review an appeal: uphold or overturn the original action. - */ - reviewAppeal( - appealId: string, - reviewedBy: string, - decision: "upheld" | "overturned", - reason: string, - ): Appeal | null { - const appeal = this.appeals.get(appealId); - if (!appeal || appeal.status !== "pending") return null; - - appeal.status = decision; - appeal.reviewedBy = reviewedBy; - appeal.reviewedAt = new Date().toISOString(); - appeal.decision = reason; - appeal.updatedAt = new Date().toISOString(); - - // If appeal overturned, remove suspension/ban - if (decision === "overturned") { - const action = this.actions.get(appeal.actionId); - if (action) { - const report = this.reports.get(appeal.reportId); - if (report && report.reportedBy) { - if (action.action === "suspend_user") { - this.suspendedUsers.delete(report.reportedBy); - } else if (action.action === "ban_user") { - this.bannedUsers.delete(report.reportedBy); - } - } - } - } - - return appeal; - } - - // ─── Community Guidelines ───────────────────────────────────────────────── - - registerGuideline( - title: string, - description: string, - examples: string[], - consequenceLevel: "warning" | "suspension" | "ban", - ): CommunityGuideline { - const id = `guideline-${Date.now()}`; - const guideline: CommunityGuideline = { - id, - title, - description, - examples, - consequenceLevel, - active: true, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }; - this.guidelines.set(id, guideline); - return guideline; - } - - getGuideline(id: string): CommunityGuideline | null { - return this.guidelines.get(id) || null; - } - - getActiveGuidelines(): CommunityGuideline[] { - return [...this.guidelines.values()].filter((g) => g.active); - } - - deactivateGuideline(id: string): boolean { - const guideline = this.guidelines.get(id); - if (!guideline) return false; - guideline.active = false; - guideline.updatedAt = new Date().toISOString(); - return true; - } - - // ─── Statistics ─────────────────────────────────────────────────────────── - - getModerationStats(): ModerationStats { - const reports = [...this.reports.values()]; - const actions = [...this.actions.values()]; - const appeals = [...this.appeals.values()]; - - const approvedCount = reports.filter((r) => r.status === "approved").length; - const rejectedCount = reports.filter((r) => r.status === "rejected").length; - const pendingCount = reports.filter((r) => r.status === "pending").length; - const appealsCount = appeals.length; - const suspensionsCount = actions.filter((a) => a.action === "suspend_user").length; - const bansCount = actions.filter((a) => a.action === "ban_user").length; - - // Calculate average resolution time - const resolved = reports.filter((r) => r.status === "approved" || r.status === "rejected"); - const avgTime = - resolved.length > 0 - ? resolved.reduce((sum, r) => { - const createdMs = new Date(r.createdAt).getTime(); - const updatedMs = new Date(r.updatedAt).getTime(); - return sum + (updatedMs - createdMs); - }, 0) / resolved.length - : 0; - - return { - totalReports: reports.length, - approvedCount, - rejectedCount, - pendingCount, - appealsCount, - suspensionsCount, - bansCount, - averageResolutionTimeMs: Math.round(avgTime), - }; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getReportsCache(): Map { - return this.reports; - } - - getActionsCache(): Map { - return this.actions; - } - - getAppealCache(): Map { - return this.appeals; - } -} diff --git a/src/partner-service.test.ts b/src/partner-service.test.ts deleted file mode 100644 index 4314a474..00000000 --- a/src/partner-service.test.ts +++ /dev/null @@ -1,354 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { PartnerService } from "./partner-service.js"; - -describe("PartnerService", () => { - let service: PartnerService; - let mockDb: any; - - beforeEach(() => { - mockDb = { - query: async (sql: string, params: any[]) => { - if (sql.includes("UPDATE authors") && sql.includes("partner_tier")) { - // enrollAsPartner - return { - rows: [{ - id: params[3], - partner_tier: params[0], - partner_organization_type: params[1], - partner_rate_limit: params[2], - partner_agreement_signed_at: null, - partner_agreement_version: null, - partner_webhook_url: null, - }], - }; - } - if (sql.includes("INSERT INTO partnership_agreements")) { - return { rows: [{ id: params[0] }] }; - } - if (sql.includes("UPDATE authors") && sql.includes("partner_agreement")) { - return { rows: [] }; - } - if (sql.includes("INSERT INTO partner_api_keys")) { - // generateApiKey - return { - rows: [{ - id: params[0], - author_id: params[1], - api_key: params[2], - created_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("SELECT a.* FROM authors a") && sql.includes("partner_api_keys")) { - // validateApiKey - return { - rows: [{ - id: params[0] || "author-1", - partner_tier: "gold", - partner_organization_type: "enterprise", - partner_rate_limit: 1000, - partner_agreement_signed_at: new Date().toISOString(), - partner_agreement_version: "1.0", - partner_webhook_url: "https://example.com/webhook", - }], - }; - } - if (sql.includes("UPDATE partner_api_keys") && sql.includes("last_used_at")) { - return { rows: [] }; - } - if (sql.includes("SELECT * FROM partner_api_keys WHERE author_id")) { - // rotateApiKey - get old key - return { - rows: [{ - id: "key-old", - author_id: params[0], - api_key: "pk_oldkey", - }], - }; - } - if (sql.includes("DELETE FROM partner_api_keys")) { - return { rows: [] }; - } - if (sql.includes("SELECT * FROM authors WHERE id")) { - // getPartnerProfile - return { - rows: [{ - id: params[0], - partner_tier: "silver", - partner_organization_type: "startup", - partner_rate_limit: 500, - partner_agreement_signed_at: new Date().toISOString(), - partner_agreement_version: "1.0", - partner_webhook_url: null, - }], - }; - } - if (sql.includes("INSERT INTO co_developed_plugins")) { - // createCoDevelopedPlugin - return { - rows: [{ - id: params[0], - plugin_id: params[1], - partner_author_id: params[2], - primary_author_id: params[3], - revenue_split: params[4], - approval_status: params[5], - approved_by: null, - approval_date: null, - created_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("UPDATE co_developed_plugins") && sql.includes("approval_status")) { - // approveCoDevelopedPlugin - return { - rows: [{ - id: params[2], - plugin_id: "plugin-1", - partner_author_id: "author-2", - primary_author_id: "author-1", - revenue_split: "50-50", - approval_status: params[0], - approved_by: params[1], - approval_date: new Date().toISOString(), - created_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("SELECT * FROM co_developed_plugins")) { - // getPartnerCoDevelopedPlugins - return { - rows: [{ - id: "coplugin-1", - plugin_id: "plugin-1", - partner_author_id: "author-2", - primary_author_id: "author-1", - revenue_split: "50-50", - approval_status: "approved", - approved_by: "admin-1", - approval_date: new Date().toISOString(), - created_at: new Date().toISOString(), - }], - }; - } - return { rows: [] }; - }, - }; - - service = new PartnerService(mockDb); - }); - - describe("enrollAsPartner", () => { - it("enrolls author as partner with tier and org type", async () => { - const profile = await service.enrollAsPartner( - "author-1", - "gold", - "enterprise" - ); - assert.equal(profile.authorId, "author-1"); - assert.equal(profile.partnerTier, "gold"); - assert.equal(profile.organizationType, "enterprise"); - assert.equal(profile.rateLimit, 1000); - }); - - it("supports all partner tiers", async () => { - for (const tier of ["bronze", "silver", "gold", "platinum"] as const) { - const profile = await service.enrollAsPartner("author-1", tier, "startup"); - assert.equal(profile.partnerTier, tier); - } - }); - }); - - describe("signPartnerAgreement", () => { - it("signs partnership agreement and updates author", async () => { - await service.signPartnerAgreement("author-1", "gold", "1.0"); - // No assertion needed - method returns void, just verify no error - assert.ok(true); - }); - }); - - describe("generateApiKey", () => { - it("generates new API key for partner", async () => { - const key = await service.generateApiKey("author-1"); - assert.ok(key.id.startsWith("key-")); - assert.equal(key.authorId, "author-1"); - assert.ok(key.apiKey.startsWith("pk_")); - assert.ok(key.createdAt); - }); - - it("creates unique API keys", async () => { - const key1 = await service.generateApiKey("author-1"); - const key2 = await service.generateApiKey("author-2"); - assert.notEqual(key1.apiKey, key2.apiKey); - }); - }); - - describe("validateApiKey", () => { - it("validates API key and returns partner profile", async () => { - const profile = await service.validateApiKey("pk_test123"); - assert.ok(profile); - assert.equal(profile.partnerTier, "gold"); - assert.equal(profile.organizationType, "enterprise"); - }); - - it("returns null for invalid API key", async () => { - mockDb.query = async (sql: string) => { - if (sql.includes("SELECT a.* FROM authors")) { - return { rows: [] }; - } - return { rows: [] }; - }; - service = new PartnerService(mockDb); - const profile = await service.validateApiKey("pk_invalid"); - assert.equal(profile, null); - }); - - it("updates last_used_at on validation", async () => { - let updateCalled = false; - mockDb.query = async (sql: string, params: any[]) => { - if (sql.includes("SELECT a.* FROM authors")) { - return { - rows: [{ - id: "author-1", - partner_tier: "gold", - partner_organization_type: "enterprise", - partner_rate_limit: 1000, - }], - }; - } - if (sql.includes("UPDATE partner_api_keys")) { - updateCalled = true; - } - return { rows: [] }; - }; - service = new PartnerService(mockDb); - await service.validateApiKey("pk_test"); - assert.ok(updateCalled); - }); - }); - - describe("rotateApiKey", () => { - it("rotates API key for partner", async () => { - const newKey = await service.rotateApiKey("author-1"); - assert.ok(newKey.id.startsWith("key-")); - assert.equal(newKey.authorId, "author-1"); - assert.ok(newKey.apiKey.startsWith("pk_")); - }); - - it("throws error if no API key found", async () => { - mockDb.query = async (sql: string) => { - if (sql.includes("SELECT * FROM partner_api_keys WHERE author_id")) { - return { rows: [] }; - } - return { rows: [] }; - }; - service = new PartnerService(mockDb); - await assert.rejects( - () => service.rotateApiKey("author-1"), - /No API key found/ - ); - }); - }); - - describe("getPartnerProfile", () => { - it("retrieves partner profile by author ID", async () => { - const profile = await service.getPartnerProfile("author-1"); - assert.ok(profile); - assert.equal(profile.authorId, "author-1"); - assert.equal(profile.partnerTier, "silver"); - assert.equal(profile.organizationType, "startup"); - }); - - it("returns null if author not found", async () => { - mockDb.query = async (sql: string) => { - if (sql.includes("SELECT * FROM authors WHERE id")) { - return { rows: [] }; - } - return { rows: [] }; - }; - service = new PartnerService(mockDb); - const profile = await service.getPartnerProfile("author-1"); - assert.equal(profile, null); - }); - }); - - describe("createCoDevelopedPlugin", () => { - it("creates co-developed plugin partnership", async () => { - const coPlugin = await service.createCoDevelopedPlugin( - "plugin-1", - "author-2", - "author-1", - "50-50" - ); - assert.ok(coPlugin.id.startsWith("coplugin-")); - assert.equal(coPlugin.pluginId, "plugin-1"); - assert.equal(coPlugin.partnerAuthorId, "author-2"); - assert.equal(coPlugin.primaryAuthorId, "author-1"); - assert.equal(coPlugin.revenueSplit, "50-50"); - assert.equal(coPlugin.approvalStatus, "pending"); - }); - - it("supports custom revenue splits", async () => { - const splits = ["60-40", "70-30", "80-20"]; - for (const split of splits) { - const coPlugin = await service.createCoDevelopedPlugin( - "plugin-1", - "author-2", - "author-1", - split - ); - assert.equal(coPlugin.revenueSplit, split); - } - }); - }); - - describe("approveCoDevelopedPlugin", () => { - it("approves co-developed plugin partnership", async () => { - const approved = await service.approveCoDevelopedPlugin( - "coplugin-1", - "admin-1" - ); - assert.equal(approved.approvalStatus, "approved"); - assert.equal(approved.approvedBy, "admin-1"); - assert.ok(approved.approvalDate); - }); - }); - - describe("getPartnerCoDevelopedPlugins", () => { - it("retrieves co-developed plugins for partner", async () => { - const plugins = await service.getPartnerCoDevelopedPlugins("author-1"); - assert.ok(Array.isArray(plugins)); - if (plugins.length > 0) { - assert.ok(plugins[0].id); - assert.ok(plugins[0].pluginId); - } - }); - }); - - describe("calculatePartnerShare", () => { - it("calculates partner share from revenue split", () => { - const result = service.calculatePartnerShare(1000, "50-50"); - assert.equal(result.partnerShare, 500); - assert.equal(result.primaryShare, 500); - }); - - it("handles 60-40 split", () => { - const result = service.calculatePartnerShare(1000, "60-40"); - assert.equal(result.partnerShare, 600); - assert.equal(result.primaryShare, 400); - }); - - it("handles 70-30 split", () => { - const result = service.calculatePartnerShare(1000, "70-30"); - assert.equal(result.partnerShare, 700); - assert.equal(result.primaryShare, 300); - }); - - it("handles custom splits", () => { - const result = service.calculatePartnerShare(1000, "80-20"); - assert.equal(result.partnerShare, 800); - assert.equal(result.primaryShare, 200); - }); - }); -}); diff --git a/src/partner-service.ts b/src/partner-service.ts deleted file mode 100644 index e9fb9026..00000000 --- a/src/partner-service.ts +++ /dev/null @@ -1,319 +0,0 @@ -/** - * kit Partner Service - * - * Manages partner enrollment, API key generation, and co-developed plugin partnerships - */ - -import { IdGenerators } from "./id-generator.js"; - -/** - * Partner profile with tier and API access - */ -export interface PartnerProfile { - authorId: string; - partnerTier?: "bronze" | "silver" | "gold" | "platinum"; - organizationType?: "startup" | "enterprise" | "agency" | "consulting"; - agreementSignedAt?: string; - agreementVersion?: string; - apiKey?: string; - webhookUrl?: string; - rateLimit: number; -} - -/** - * API key with encrypted secret - */ -export interface PartnerApiKey { - id: string; - authorId: string; - apiKey: string; - createdAt: string; - rotatedAt?: string; - lastUsedAt?: string; -} - -/** - * Co-developed plugin partnership - */ -export interface CoDevelopedPlugin { - id: string; - pluginId: string; - partnerAuthorId: string; - primaryAuthorId: string; - revenueSplit: string; // "50-50", "60-40", etc - approvalStatus: "pending" | "approved" | "rejected"; - approvedBy?: string; - approvalDate?: string; - createdAt: string; -} - -/** - * Partner service for managing partnerships and integrations - */ -export class PartnerService { - private db: any; - - constructor(db?: any) { - this.db = db; - } - - /** - * Enroll author as partner - */ - async enrollAsPartner( - authorId: string, - tier: "bronze" | "silver" | "gold" | "platinum", - organizationType: "startup" | "enterprise" | "agency" | "consulting", - ): Promise { - const result = await this.db.query( - ` - UPDATE authors - SET partner_tier = $1, partner_organization_type = $2, partner_rate_limit = $3 - WHERE id = $4 - RETURNING * - `, - [tier, organizationType, 1000, authorId], - ); - - return this.mapPartnerProfile(result.rows[0]); - } - - /** - * Sign partner agreement - */ - async signPartnerAgreement( - authorId: string, - tier: string, - version: string, - ): Promise { - const id = IdGenerators.agreement(); - await this.db.query( - ` - INSERT INTO partnership_agreements - (id, author_id, tier, version, signed_at, signed_by, created_at) - VALUES ($1, $2, $3, $4, now(), $5, now()) - `, - [id, authorId, tier, version, authorId], - ); - - await this.db.query( - ` - UPDATE authors - SET partner_agreement_signed_at = now(), partner_agreement_version = $1 - WHERE id = $2 - `, - [version, authorId], - ); - } - - /** - * Generate API key for partner - */ - async generateApiKey(authorId: string): Promise { - const apiKey = `pk_${IdGenerators.apiKey().slice(0, 32)}`; - const secretKey = IdGenerators.apiKey(); - - const id = IdGenerators.apiKey(); - const result = await this.db.query( - ` - INSERT INTO partner_api_keys - (id, author_id, api_key, secret_key, created_at) - VALUES ($1, $2, $3, $4, now()) - RETURNING id, author_id, api_key, created_at - `, - [id, authorId, apiKey, secretKey], - ); - - return { - id: result.rows[0].id, - authorId: result.rows[0].author_id, - apiKey: result.rows[0].api_key, - createdAt: result.rows[0].created_at, - }; - } - - /** - * Validate API key and check rate limits - */ - async validateApiKey(apiKey: string): Promise { - const result = await this.db.query( - ` - SELECT a.* FROM authors a - JOIN partner_api_keys pk ON a.id = pk.author_id - WHERE pk.api_key = $1 - `, - [apiKey], - ); - - if (result.rows.length === 0) { - return null; - } - - // Update last_used_at - await this.db.query( - ` - UPDATE partner_api_keys - SET last_used_at = now() - WHERE api_key = $1 - `, - [apiKey], - ); - - return this.mapPartnerProfile(result.rows[0]); - } - - /** - * Rotate API key - */ - async rotateApiKey(authorId: string): Promise { - // Get old key - const oldKey = await this.db.query( - ` - SELECT * FROM partner_api_keys WHERE author_id = $1 - `, - [authorId], - ); - - if (oldKey.rows.length === 0) { - throw new Error("No API key found"); - } - - // Delete old key - await this.db.query( - ` - DELETE FROM partner_api_keys WHERE author_id = $1 - `, - [authorId], - ); - - // Generate new key - return this.generateApiKey(authorId); - } - - /** - * Get partner profile - */ - async getPartnerProfile(authorId: string): Promise { - const result = await this.db.query( - ` - SELECT * FROM authors WHERE id = $1 - `, - [authorId], - ); - - if (result.rows.length === 0) { - return null; - } - - return this.mapPartnerProfile(result.rows[0]); - } - - /** - * Create co-developed plugin partnership - */ - async createCoDevelopedPlugin( - pluginId: string, - partnerAuthorId: string, - primaryAuthorId: string, - revenueSplit: string, - ): Promise { - const id = IdGenerators.coPlugin(); - const result = await this.db.query( - ` - INSERT INTO co_developed_plugins - (id, plugin_id, partner_author_id, primary_author_id, revenue_split, approval_status, created_at) - VALUES ($1, $2, $3, $4, $5, $6, now()) - RETURNING * - `, - [id, pluginId, partnerAuthorId, primaryAuthorId, revenueSplit, "pending"], - ); - - return this.mapCoDevelopedPlugin(result.rows[0]); - } - - /** - * Approve co-developed plugin - */ - async approveCoDevelopedPlugin( - coDevelopedId: string, - approvedBy: string, - ): Promise { - const result = await this.db.query( - ` - UPDATE co_developed_plugins - SET approval_status = $1, approved_by = $2, approval_date = now() - WHERE id = $3 - RETURNING * - `, - ["approved", approvedBy, coDevelopedId], - ); - - return this.mapCoDevelopedPlugin(result.rows[0]); - } - - /** - * Get co-developed plugins by partner - */ - async getPartnerCoDevelopedPlugins( - authorId: string, - ): Promise { - const result = await this.db.query( - ` - SELECT * FROM co_developed_plugins - WHERE partner_author_id = $1 OR primary_author_id = $1 - ORDER BY created_at DESC - `, - [authorId], - ); - - return result.rows.map((row: any) => this.mapCoDevelopedPlugin(row)); - } - - /** - * Calculate partner revenue share - */ - calculatePartnerShare( - totalRevenue: number, - revenueSplit: string, - ): { partnerShare: number; primaryShare: number } { - const [partner, primary] = revenueSplit.split("-").map(Number); - const total = partner + primary; - - return { - partnerShare: (totalRevenue * partner) / total, - primaryShare: (totalRevenue * primary) / total, - }; - } - - /** - * Map database row to PartnerProfile - */ - private mapPartnerProfile(row: any): PartnerProfile { - return { - authorId: row.id, - partnerTier: row.partner_tier, - organizationType: row.partner_organization_type, - agreementSignedAt: row.partner_agreement_signed_at, - agreementVersion: row.partner_agreement_version, - webhookUrl: row.partner_webhook_url, - rateLimit: row.partner_rate_limit || 1000, - }; - } - - /** - * Map database row to CoDevelopedPlugin - */ - private mapCoDevelopedPlugin(row: any): CoDevelopedPlugin { - return { - id: row.id, - pluginId: row.plugin_id, - partnerAuthorId: row.partner_author_id, - primaryAuthorId: row.primary_author_id, - revenueSplit: row.revenue_split, - approvalStatus: row.approval_status, - approvedBy: row.approved_by, - approvalDate: row.approval_date, - createdAt: row.created_at, - }; - } -} diff --git a/src/payout-service.test.ts b/src/payout-service.test.ts deleted file mode 100644 index a6d634eb..00000000 --- a/src/payout-service.test.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { PayoutService } from "./payout-service.js"; - -describe("PayoutService", () => { - let service: PayoutService; - let mockDb: any; - - beforeEach(() => { - // Mock database - mockDb = { - query: async (sql: string, params: any[]) => { - // Simple mock implementation - if (sql.includes("SELECT") && sql.includes("plugin_revenue")) { - return { - rows: [{ - id: "rev-1", - plugin_id: "test-plugin", - author_id: "author-1", - gross_revenue: 1000, - kit_commission: 200, - author_earnings: 800, - currency: "USD", - updated_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("INSERT") && sql.includes("plugin_revenue")) { - return { - rows: [{ - id: "rev-1", - plugin_id: params[1], - author_id: "author-1", - gross_revenue: params[2], - kit_commission: Math.round(params[2] * 0.2), - author_earnings: Math.round(params[2] * 0.8), - currency: "USD", - updated_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("UPDATE") && sql.includes("grant_applications")) { - // Handle UPDATE for approve/reject - // approveGrant: params = ["approved", approvedBy, grantId] - // rejectGrant: params = ["rejected", grantId] - const status = params[0]; - const isApprove = status === "approved"; - const approvedBy = isApprove ? params[1] : undefined; - - return { - rows: [{ - id: "grant-1", - author_id: "author-1", - plugin_id: "plugin-1", - amount_requested: 50000, - status: status, - use_case: "Feature development", - approved_by: approvedBy, - approval_date: isApprove ? new Date().toISOString() : undefined, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("INSERT") && sql.includes("payment_transactions")) { - return { - rows: [{ - id: "tx-1", - author_id: params[1], - amount: params[2], - status: params[3] || "pending", - period_start: params[4], - period_end: params[5], - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("INSERT") && sql.includes("grant_applications")) { - return { - rows: [{ - id: "grant-1", - author_id: params[1], - plugin_id: params[2], - amount_requested: params[3], - status: params[4] || "pending", - use_case: params[5], - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("author_payout_accounts")) { - return { - rows: [{ - id: "acct-1", - author_id: params[1], - status: "pending", - kyc_status: "pending", - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }], - }; - } - return { rows: [] }; - }, - }; - - service = new PayoutService(mockDb); - }); - - describe("recordPluginDownload", () => { - it("records plugin download and calculates revenue split", async () => { - const revenue = await service.recordPluginDownload("test-plugin", 10); - assert.equal(revenue.pluginId, "test-plugin"); - assert.ok(revenue.grossRevenue >= 10); - // 80/20 split verification done in calculation - }); - }); - - describe("calculateMonthlyEarnings", () => { - it("calculates author monthly earnings", async () => { - const earnings = await service.calculateMonthlyEarnings("author-1", 2026, 4); - assert.ok(typeof earnings === "number"); - assert.ok(earnings >= 0); - }); - }); - - describe("createPayoutTransaction", () => { - it("creates payment transaction", async () => { - const tx = await service.createPayoutTransaction( - "author-1", - 10000, - "2026-04-01", - "2026-04-30", - ); - assert.equal(tx.authorId, "author-1"); - assert.equal(tx.amount, 10000); - assert.equal(tx.status, "pending"); - assert.equal(tx.periodStart, "2026-04-01"); - assert.equal(tx.periodEnd, "2026-04-30"); - }); - }); - - describe("submitGrant", () => { - it("submits grant application", async () => { - const grant = await service.submitGrant( - "author-1", - "plugin-1", - 50000, - "Feature development", - ); - assert.equal(grant.authorId, "author-1"); - assert.equal(grant.pluginId, "plugin-1"); - assert.equal(grant.amountRequested, 50000); - assert.equal(grant.useCase, "Feature development"); - assert.equal(grant.status, "pending"); - }); - }); - - - describe("getPendingGrants", () => { - it("retrieves pending grants for admin", async () => { - const grants = await service.getPendingGrants(); - assert.ok(Array.isArray(grants)); - }); - }); - - describe("Revenue split calculation (80/20)", () => { - it("applies correct 80/20 split", async () => { - const revenue = await service.recordPluginDownload("test-plugin", 1000); - // 1000 cents = $10.00 - // kit: $2.00 (20%), Author: $8.00 (80%) - assert.equal(Math.round(revenue.kitCommission), 200); // 20% - assert.equal(Math.round(revenue.authorEarnings), 800); // 80% - }); - }); - -}); diff --git a/src/payout-service.ts b/src/payout-service.ts deleted file mode 100644 index fe621fd9..00000000 --- a/src/payout-service.ts +++ /dev/null @@ -1,483 +0,0 @@ -/** - * kit Payout Service - * - * Handles author payouts, revenue tracking, grant applications, - * and Stripe Connect integration for marketplace monetization. - */ - -import { IdGenerators } from "./id-generator.js"; - -/** - * Author payout account info - */ -export interface PayoutAccount { - id: string; - authorId: string; - stripeAccountId?: string; - status: "pending" | "connected" | "disconnected" | "suspended"; - kycStatus: "pending" | "verified" | "rejected"; - taxId?: string; // encrypted - bankAccountId?: string; - createdAt: string; - updatedAt: string; -} - -/** - * Plugin revenue tracking - */ -export interface PluginRevenue { - id: string; - pluginId: string; - authorId: string; - grossRevenue: number; // cents - kitCommission: number; // 20% - authorEarnings: number; // 80% - currency: string; // "USD" - updatedAt: string; -} - -/** - * Payment transaction (monthly payout) - */ -export interface PaymentTransaction { - id: string; - authorId: string; - stripeTransferId?: string; - amount: number; // cents - status: "pending" | "processing" | "completed" | "failed"; - periodStart: string; // YYYY-MM-DD - periodEnd: string; // YYYY-MM-DD - attemptedAt?: string; - completedAt?: string; - createdAt: string; - updatedAt: string; -} - -/** - * Grant application - */ -export interface GrantApplication { - id: string; - authorId: string; - pluginId: string; - amountRequested: number; // cents - status: "pending" | "approved" | "rejected" | "paid"; - useCase: string; - approvedBy?: string; // admin user ID - approvalDate?: string; - paidAt?: string; - createdAt: string; - updatedAt: string; -} - -/** - * Payout service for managing author earnings and payments - */ -export class PayoutService { - private db: any; // Database connection - - constructor(db?: any) { - this.db = db; - } - - /** - * Record a plugin download and update revenue - */ - async recordPluginDownload( - pluginId: string, - downloadRate: number = 10, // $0.10 cents default - ): Promise { - const revenue = await this.db.query( - `SELECT * FROM plugin_revenue WHERE plugin_id = $1`, - [pluginId], - ); - - const existing = revenue.rows[0]; - const newGross = (existing?.gross_revenue || 0) + downloadRate; - const commission = Math.round(newGross * 0.2); // 20% to kit - const earnings = Math.round(newGross * 0.8); // 80% to author - - const result = await this.db.query( - ` - INSERT INTO plugin_revenue (id, plugin_id, author_id, gross_revenue, kit_commission, author_earnings, updated_at) - SELECT $1, $2, author, $3, $4, $5, now() - FROM plugins WHERE id = $2 - ON CONFLICT (plugin_id) DO UPDATE SET - gross_revenue = gross_revenue + $3, - kit_commission = EXCLUDED.gross_revenue * 0.2, - author_earnings = EXCLUDED.gross_revenue * 0.8, - updated_at = now() - RETURNING * - `, - [IdGenerators.payout(), pluginId, downloadRate, commission, earnings], - ); - - return this.mapRevenue(result.rows[0]); - } - - /** - * Calculate monthly earnings for author - */ - async calculateMonthlyEarnings( - authorId: string, - year: number, - month: number, - ): Promise { - const result = await this.db.query( - ` - SELECT COALESCE(SUM(author_earnings), 0) as total - FROM plugin_revenue - WHERE author_id = $1 - AND EXTRACT(YEAR FROM updated_at) = $2 - AND EXTRACT(MONTH FROM updated_at) = $3 - `, - [authorId, year, month], - ); - - return result.rows[0]?.total || 0; - } - - /** - * Create monthly payout transaction - */ - async createPayoutTransaction( - authorId: string, - amount: number, - periodStart: string, - periodEnd: string, - ): Promise { - const id = IdGenerators.payout(); - const result = await this.db.query( - ` - INSERT INTO payment_transactions - (id, author_id, amount, status, period_start, period_end, created_at, updated_at) - VALUES ($1, $2, $3, $4, $5, $6, now(), now()) - RETURNING * - `, - [id, authorId, amount, "pending", periodStart, periodEnd], - ); - - return this.mapTransaction(result.rows[0]); - } - - /** - * Trigger monthly payouts (cron job, runs 1st of month) - */ - async triggerMonthlyPayouts(): Promise { - const lastMonth = new Date(); - lastMonth.setMonth(lastMonth.getMonth() - 1); - const year = lastMonth.getFullYear(); - const month = lastMonth.getMonth() + 1; - - const authors = await this.db.query( - ` - SELECT DISTINCT author_id FROM plugin_revenue - WHERE author_earnings > 0 - `, - ); - - const payouts: PaymentTransaction[] = []; - - for (const { author_id } of authors.rows) { - const earnings = await this.calculateMonthlyEarnings(author_id, year, month); - - if (earnings > 100) { // Minimum $1.00 payout threshold - const periodStart = `${year}-${String(month).padStart(2, "0")}-01`; - const periodEnd = new Date(year, month, 0) - .toISOString() - .split("T")[0]; - - const tx = await this.createPayoutTransaction( - author_id, - earnings, - periodStart, - periodEnd, - ); - payouts.push(tx); - } - } - - return payouts; - } - - /** - * Process pending payouts (transfers to author Stripe accounts) - */ - async processPayouts(batchSize: number = 10): Promise { - const pending = await this.db.query( - ` - SELECT pt.* FROM payment_transactions pt - WHERE pt.status = 'pending' - AND pt.created_at < now() - interval '2 days' - LIMIT $1 - `, - [batchSize], - ); - - const processed: PaymentTransaction[] = []; - - for (const tx of pending.rows) { - // Get author's Stripe account - const account = await this.db.query( - `SELECT stripe_account_id FROM author_payout_accounts WHERE author_id = $1`, - [tx.author_id], - ); - - if (!account.rows[0]?.stripe_account_id) { - // Skip if no Stripe account connected - continue; - } - - try { - // In real implementation, call Stripe API here - // const transfer = await stripe.transfers.create({ - // destination: account.rows[0].stripe_account_id, - // amount: tx.amount, - // currency: 'usd', - // }); - - // For now, simulate successful transfer - const result = await this.db.query( - ` - UPDATE payment_transactions - SET status = $1, attempted_at = now(), updated_at = now() - WHERE id = $2 - RETURNING * - `, - ["processing", tx.id], - ); - - processed.push(this.mapTransaction(result.rows[0])); - } catch (error) { - // Log error and mark as failed - console.error(`Failed to process payout ${tx.id}:`, error); - await this.db.query( - ` - UPDATE payment_transactions - SET status = $1, updated_at = now() - WHERE id = $2 - `, - ["failed", tx.id], - ); - } - } - - return processed; - } - - /** - * Submit grant application - */ - async submitGrant( - authorId: string, - pluginId: string, - amountRequested: number, - useCase: string, - ): Promise { - const id = IdGenerators.grant(); - const result = await this.db.query( - ` - INSERT INTO grant_applications - (id, author_id, plugin_id, amount_requested, status, use_case, created_at, updated_at) - VALUES ($1, $2, $3, $4, $5, $6, now(), now()) - RETURNING * - `, - [id, authorId, pluginId, amountRequested, "pending", useCase], - ); - - return this.mapGrant(result.rows[0]); - } - - /** - * Approve grant (admin only) - */ - async approveGrant( - grantId: string, - approvedBy: string, - ): Promise { - const result = await this.db.query( - ` - UPDATE grant_applications - SET status = $1, approved_by = $2, approval_date = now(), updated_at = now() - WHERE id = $3 - RETURNING * - `, - ["approved", approvedBy, grantId], - ); - - const grant = this.mapGrant(result.rows[0]); - - // Immediately create payout transaction for grant amount - await this.createPayoutTransaction( - grant.authorId, - grant.amountRequested, - new Date().toISOString().split("T")[0], - new Date().toISOString().split("T")[0], - ); - - return grant; - } - - /** - * Reject grant (admin only) - */ - async rejectGrant(grantId: string): Promise { - const result = await this.db.query( - ` - UPDATE grant_applications - SET status = $1, updated_at = now() - WHERE id = $2 - RETURNING * - `, - ["rejected", grantId], - ); - - return this.mapGrant(result.rows[0]); - } - - /** - * Get pending grants (admin dashboard) - */ - async getPendingGrants(limit: number = 20): Promise { - const result = await this.db.query( - ` - SELECT * FROM grant_applications - WHERE status = 'pending' - ORDER BY created_at DESC - LIMIT $1 - `, - [limit], - ); - - return result.rows.map((row: any) => this.mapGrant(row)); - } - - /** - * Get author payout status - */ - async getPayoutStatus(authorId: string): Promise { - const result = await this.db.query( - `SELECT * FROM author_payout_accounts WHERE author_id = $1`, - [authorId], - ); - - return result.rows[0] ? this.mapPayoutAccount(result.rows[0]) : null; - } - - /** - * Setup payout account (initiate Stripe Connect) - */ - async setupPayoutAccount( - authorId: string, - email: string, - ): Promise { - // Check if account exists - const existing = await this.getPayoutStatus(authorId); - if (existing) { - return existing; - } - - const id = IdGenerators.payout(); - const result = await this.db.query( - ` - INSERT INTO author_payout_accounts - (id, author_id, status, kyc_status, created_at, updated_at) - VALUES ($1, $2, $3, $4, now(), now()) - RETURNING * - `, - [id, authorId, "pending", "pending"], - ); - - return this.mapPayoutAccount(result.rows[0]); - } - - /** - * Mark payout transaction as completed (webhook handler) - */ - async completePayoutTransaction( - stripeTransferId: string, - ): Promise { - const result = await this.db.query( - ` - UPDATE payment_transactions - SET status = $1, completed_at = now(), updated_at = now() - WHERE stripe_transfer_id = $2 - RETURNING * - `, - ["completed", stripeTransferId], - ); - - return this.mapTransaction(result.rows[0]); - } - - /** - * Map database row to PayoutAccount - */ - private mapPayoutAccount(row: any): PayoutAccount { - return { - id: row.id, - authorId: row.author_id, - stripeAccountId: row.stripe_account_id, - status: row.status, - kycStatus: row.kyc_status, - taxId: row.tax_id, - bankAccountId: row.bank_account_id, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; - } - - /** - * Map database row to PluginRevenue - */ - private mapRevenue(row: any): PluginRevenue { - return { - id: row.id, - pluginId: row.plugin_id, - authorId: row.author_id, - grossRevenue: row.gross_revenue, - kitCommission: row.kit_commission, - authorEarnings: row.author_earnings, - currency: row.currency || "USD", - updatedAt: row.updated_at, - }; - } - - /** - * Map database row to PaymentTransaction - */ - private mapTransaction(row: any): PaymentTransaction { - return { - id: row.id, - authorId: row.author_id, - stripeTransferId: row.stripe_transfer_id, - amount: row.amount, - status: row.status, - periodStart: row.period_start, - periodEnd: row.period_end, - attemptedAt: row.attempted_at, - completedAt: row.completed_at, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; - } - - /** - * Map database row to GrantApplication - */ - private mapGrant(row: any): GrantApplication { - return { - id: row.id, - authorId: row.author_id, - pluginId: row.plugin_id, - amountRequested: row.amount_requested, - status: row.status, - useCase: row.use_case, - approvedBy: row.approved_by, - approvalDate: row.approval_date, - paidAt: row.paid_at, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; - } -} diff --git a/src/plugin-registry-model.ts b/src/plugin-registry-model.ts deleted file mode 100644 index fc74b7a7..00000000 --- a/src/plugin-registry-model.ts +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Plugin Registry — data models - * Plugin certification, versioning, audit trails, and registry management - */ - -export type CertificationTier = "bronze" | "silver" | "gold" | "platinum"; -export type PluginStatus = "draft" | "submitted" | "certified" | "deprecated" | "blacklisted"; -export type CertificationStatus = - | "pending" - | "reviewing" - | "approved" - | "rejected" - | "revoked" - | "expired"; -export type VersionStatus = "draft" | "released" | "deprecated" | "yanked"; - -export interface PluginVersion { - id: string; - plugin_id: string; - version: string; // semver - status: VersionStatus; - release_date: string; - deprecated_date?: string; - yank_reason?: string; - file_hash: string; - file_size: number; - changelog?: string; - breaking_changes: string[]; - dependencies: { name: string; version_range: string }[]; - created_at: string; - updated_at: string; -} - -export interface Plugin { - id: string; - name: string; - slug: string; // URL-safe identifier - description: string; - long_description?: string; - author_id: string; - author_name: string; - category: string; - tags: string[]; - homepage?: string; - documentation?: string; - repository?: string; - license: string; - status: PluginStatus; - current_version: string; - versions: PluginVersion[]; - certification_tier: CertificationTier; - certification_status: CertificationStatus; - certification_date?: string; - certified_by?: string; - downloads: number; - rating: number; - rating_count: number; - verified_author: boolean; - maintainer_contact?: string; - created_at: string; - updated_at: string; -} - -export interface CertificationAudit { - id: string; - plugin_id: string; - plugin_version: string; - certification_tier: CertificationTier; - status: CertificationStatus; - reviewer_id: string; - reviewer_name: string; - security_score: number; // 0-100 - performance_score: number; // 0-100 - code_quality_score: number; // 0-100 - test_coverage_percent: number; - findings: { - category: string; - severity: "info" | "warning" | "critical"; - description: string; - resolved: boolean; - }[]; - approval_notes?: string; - rejection_reason?: string; - certification_date: string; - expires_at?: string; - created_at: string; - updated_at: string; -} - -export interface PluginRollback { - id: string; - plugin_id: string; - from_version: string; - to_version: string; - reason: string; - triggered_by: string; - triggered_at: string; - security_issue?: string; - created_at: string; -} - -export interface RegistryAuditLog { - id: string; - plugin_id: string; - action: string; // "submitted", "certified", "rejected", "deprecated", "yanked", "reinstated" - actor_id: string; - actor_name: string; - actor_role: "developer" | "reviewer" | "admin"; - details: Record; - timestamp: string; - created_at: string; -} - -export interface PluginDependency { - id: string; - plugin_id: string; - depends_on_plugin_id: string; - depends_on_name: string; - version_constraint: string; - is_optional: boolean; - created_at: string; -} - -export interface RegistryMetrics { - total_plugins: number; - certified_plugins: number; - total_versions: number; - total_downloads: number; - average_rating: number; - plugins_by_tier: Record; - plugins_by_status: Record; - security_issues_count: number; - rollbacks_last_30_days: number; - average_time_to_certification_hours: number; -} - -export interface PluginSearchQuery { - query?: string; - category?: string; - certification_tier?: CertificationTier; - status?: PluginStatus; - sort_by: "rating" | "downloads" | "recent" | "trending"; - limit: number; - offset: number; -} diff --git a/src/plugin-registry-service.test.ts b/src/plugin-registry-service.test.ts deleted file mode 100644 index 6e8ecad5..00000000 --- a/src/plugin-registry-service.test.ts +++ /dev/null @@ -1,479 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { - submitPlugin, - addPluginVersion, - releasePluginVersion, - submitForCertification, - certifyPlugin, - addCertificationFinding, - rejectCertification, - rollbackPlugin, - deprecateVersion, - searchPlugins, - getPlugin, - getPluginVersion, - addDependency, - getAuditLogs, - getRegistryMetrics, - ratePlugin, -} from "./plugin-registry-service.js"; - -describe("plugin-registry-service", () => { - const authorId = "author-123"; - const authorName = "Test Author"; - const reviewerId = "reviewer-456"; - const reviewerName = "Test Reviewer"; - - describe("submitPlugin", () => { - it("submits plugin to registry", () => { - const { plugin, error } = submitPlugin( - "Test Plugin", - authorId, - authorName, - "A test plugin", - "testing", - ); - - assert.ok(!error); - assert.ok(plugin.id); - assert.equal(plugin.status, "submitted"); - assert.equal(plugin.certification_status, "pending"); - }); - - it("generates slug from plugin name", () => { - const { plugin } = submitPlugin( - "My Test Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - - assert.equal(plugin.slug, "my-test-plugin"); - }); - }); - - describe("addPluginVersion", () => { - it("adds version to plugin", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - - const { pluginVersion, error } = addPluginVersion( - submitted.id, - "1.0.0", - "abc123", - 1024, - "Initial release", - ); - - assert.ok(!error); - assert.equal(pluginVersion.version, "1.0.0"); - assert.equal(pluginVersion.status, "draft"); - }); - - it("fails for nonexistent plugin", () => { - const { error } = addPluginVersion( - "nonexistent", - "1.0.0", - "hash", - 1024, - ); - - assert.ok(error); - assert.equal(error, "Plugin not found"); - }); - - it("updates current version", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - - addPluginVersion(submitted.id, "1.0.0", "hash1", 1024); - addPluginVersion(submitted.id, "2.0.0", "hash2", 2048); - - const { plugin } = getPlugin(submitted.id); - assert.equal(plugin?.current_version, "2.0.0"); - }); - }); - - describe("releasePluginVersion", () => { - it("releases plugin version", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - addPluginVersion(submitted.id, "1.0.0", "hash", 1024); - - const { pluginVersion, error } = releasePluginVersion(submitted.id, "1.0.0"); - - assert.ok(!error); - assert.equal(pluginVersion?.status, "released"); - }); - }); - - describe("submitForCertification", () => { - it("submits plugin for certification", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - - const { plugin, error } = submitForCertification(submitted.id, "1.0.0", "gold"); - - assert.ok(!error); - assert.equal(plugin.certification_status, "reviewing"); - assert.equal(plugin.certification_tier, "gold"); - }); - }); - - describe("certifyPlugin", () => { - it("certifies plugin", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - - const { audit, error } = certifyPlugin( - submitted.id, - "1.0.0", - "gold", - reviewerId, - reviewerName, - 95, - 90, - 88, - 92, - ); - - assert.ok(!error); - assert.ok(audit.id); - assert.equal(audit.status, "approved"); - assert.equal(audit.security_score, 95); - }); - - it("updates plugin status to certified", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - - certifyPlugin(submitted.id, "1.0.0", "silver", reviewerId, reviewerName, 85, 80, 82, 88); - - const { plugin } = getPlugin(submitted.id); - assert.equal(plugin?.status, "certified"); - }); - }); - - describe("addCertificationFinding", () => { - it("adds finding to audit", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - - const { audit: certAudit } = certifyPlugin( - submitted.id, - "1.0.0", - "bronze", - reviewerId, - reviewerName, - 70, - 75, - 80, - 75, - ); - - const { audit, error } = addCertificationFinding( - certAudit.id, - "security", - "warning", - "Potential XSS vulnerability", - ); - - assert.ok(!error); - assert.equal(audit.findings.length, 1); - }); - }); - - describe("rejectCertification", () => { - it("rejects certification", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - submitForCertification(submitted.id, "1.0.0", "gold"); - - const { plugin, error } = rejectCertification( - submitted.id, - reviewerId, - reviewerName, - "Code quality below threshold", - ); - - assert.ok(!error); - assert.equal(plugin.certification_status, "rejected"); - assert.equal(plugin.status, "draft"); - }); - }); - - describe("rollbackPlugin", () => { - it("rolls back to previous version", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - addPluginVersion(submitted.id, "1.0.0", "hash1", 1024); - addPluginVersion(submitted.id, "1.1.0", "hash2", 2048); - - const { rollback, error } = rollbackPlugin( - submitted.id, - "1.1.0", - "1.0.0", - "Security issue in 1.1.0", - reviewerId, - ); - - assert.ok(!error); - assert.ok(rollback.id); - assert.equal(rollback.from_version, "1.1.0"); - }); - - it("updates current version on rollback", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - addPluginVersion(submitted.id, "1.0.0", "hash1", 1024); - addPluginVersion(submitted.id, "1.1.0", "hash2", 2048); - - rollbackPlugin(submitted.id, "1.1.0", "1.0.0", "Security issue", reviewerId); - - const { plugin } = getPlugin(submitted.id); - assert.equal(plugin?.current_version, "1.0.0"); - }); - }); - - describe("deprecateVersion", () => { - it("deprecates version", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - addPluginVersion(submitted.id, "1.0.0", "hash", 1024); - - const { pluginVersion, error } = deprecateVersion(submitted.id, "1.0.0"); - - assert.ok(!error); - assert.equal(pluginVersion?.status, "deprecated"); - assert.ok(pluginVersion?.deprecated_date); - }); - }); - - describe("searchPlugins", () => { - it("searches plugins by name", () => { - const { plugin: p1 } = submitPlugin("Database Plugin", authorId, authorName, "For databases", "data"); - const { plugin: p2 } = submitPlugin("UI Plugin", authorId, authorName, "For UIs", "ui"); - - certifyPlugin(p1.id, "1.0.0", "gold", reviewerId, reviewerName, 90, 85, 88, 90); - certifyPlugin(p2.id, "1.0.0", "gold", reviewerId, reviewerName, 90, 85, 88, 90); - - const { results } = searchPlugins({ - query: "database", - sort_by: "rating", - limit: 20, - offset: 0, - }); - - assert.ok(results.some((p) => p.name.includes("Database"))); - }); - - it("filters by category", () => { - const { plugin: p1 } = submitPlugin("Plugin A", authorId, authorName, "Desc", "data"); - const { plugin: p2 } = submitPlugin("Plugin B", authorId, authorName, "Desc", "ui"); - - certifyPlugin(p1.id, "1.0.0", "gold", reviewerId, reviewerName, 90, 85, 88, 90); - certifyPlugin(p2.id, "1.0.0", "gold", reviewerId, reviewerName, 90, 85, 88, 90); - - const { results } = searchPlugins({ - category: "data", - sort_by: "rating", - limit: 20, - offset: 0, - }); - - assert.ok(results.every((p) => p.category === "data")); - }); - - it("only returns certified plugins", () => { - const { plugin } = submitPlugin("Plugin", authorId, authorName, "Desc", "testing"); - certifyPlugin(plugin.id, "1.0.0", "gold", reviewerId, reviewerName, 90, 85, 88, 90); - - const { results } = searchPlugins({ - sort_by: "rating", - limit: 20, - offset: 0, - }); - - assert.ok(results.some((p) => p.id === plugin.id)); - }); - }); - - describe("getPlugin", () => { - it("gets plugin by id", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - - const { plugin, error } = getPlugin(submitted.id); - - assert.ok(!error); - assert.equal(plugin?.id, submitted.id); - }); - - it("fails for nonexistent plugin", () => { - const { plugin, error } = getPlugin("nonexistent"); - - assert.ok(error); - assert.ok(!plugin); - }); - }); - - describe("getPluginVersion", () => { - it("gets plugin version", () => { - const { plugin: submitted } = submitPlugin( - "Plugin", - authorId, - authorName, - "Desc", - "testing", - ); - addPluginVersion(submitted.id, "1.0.0", "hash", 1024); - - const { pluginVersion, error } = getPluginVersion(submitted.id, "1.0.0"); - - assert.ok(!error); - assert.equal(pluginVersion?.version, "1.0.0"); - }); - }); - - describe("addDependency", () => { - it("adds dependency between plugins", () => { - const { plugin: pluginA } = submitPlugin( - "Plugin A", - authorId, - authorName, - "Desc", - "testing", - ); - const { plugin: pluginB } = submitPlugin( - "Plugin B", - authorId, - authorName, - "Desc", - "testing", - ); - - const { dependency, error } = addDependency( - pluginA.id, - pluginB.id, - "^1.0.0", - false, - ); - - assert.ok(!error); - assert.ok(dependency.id); - assert.equal(dependency.depends_on_name, "Plugin B"); - }); - }); - - describe("getAuditLogs", () => { - it("gets audit logs for plugin", () => { - const { plugin } = submitPlugin("Plugin", authorId, authorName, "Desc", "testing"); - certifyPlugin(plugin.id, "1.0.0", "gold", reviewerId, reviewerName, 90, 85, 88, 90); - - const { logs } = getAuditLogs(plugin.id); - - assert.ok(logs.length > 0); - assert.ok(logs.some((l) => l.action === "submitted")); - assert.ok(logs.some((l) => l.action === "certified")); - }); - }); - - describe("ratePlugin", () => { - it("rates plugin and calculates average", () => { - const { plugin } = submitPlugin("Plugin", authorId, authorName, "Desc", "testing"); - certifyPlugin(plugin.id, "1.0.0", "gold", reviewerId, reviewerName, 90, 85, 88, 90); - - ratePlugin(plugin.id, 5); - ratePlugin(plugin.id, 4); - - const { plugin: updated } = getPlugin(plugin.id); - assert.equal(updated?.rating_count, 2); - assert.ok(updated!.rating > 0); - }); - - it("fails for invalid rating", () => { - const { plugin } = submitPlugin("Plugin", authorId, authorName, "Desc", "testing"); - - const { error } = ratePlugin(plugin.id, 6); - - assert.ok(error); - assert.equal(error, "Rating must be 1-5"); - }); - }); - - describe("getRegistryMetrics", () => { - it("returns registry metrics", () => { - submitPlugin("Plugin 1", authorId, authorName, "Desc", "testing"); - const { plugin: p2 } = submitPlugin("Plugin 2", authorId, authorName, "Desc", "testing"); - certifyPlugin(p2.id, "1.0.0", "silver", reviewerId, reviewerName, 85, 80, 82, 88); - - const metrics = getRegistryMetrics(); - - assert.ok(metrics.total_plugins >= 2); - assert.ok(metrics.certified_plugins >= 1); - assert.ok(metrics.average_rating >= 0); - }); - }); -}); diff --git a/src/plugin-registry-service.ts b/src/plugin-registry-service.ts deleted file mode 100644 index 5fc93902..00000000 --- a/src/plugin-registry-service.ts +++ /dev/null @@ -1,510 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - Plugin, - PluginVersion, - CertificationAudit, - PluginRollback, - RegistryAuditLog, - PluginDependency, - RegistryMetrics, - PluginSearchQuery, - CertificationTier, -} from "./plugin-registry-model.js"; - -const plugins = new Map(); -const certifications = new Map(); -const rollbacks = new Map(); -const auditLogs = new Map(); -const dependencies = new Map(); - -/** - * Submit plugin to registry - */ -export function submitPlugin( - plugin_name: string, - author_id: string, - author_name: string, - description: string, - category: string, -): { plugin: Plugin; error?: string } { - const slug = plugin_name.toLowerCase().replace(/\s+/g, "-"); - - const plugin: Plugin = { - id: `plugin_${randomUUID()}`, - name: plugin_name, - slug, - description, - author_id, - author_name, - category, - tags: [], - license: "MIT", - status: "submitted", - current_version: "1.0.0", - versions: [], - certification_tier: "bronze", - certification_status: "pending", - downloads: 0, - rating: 0, - rating_count: 0, - verified_author: false, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - plugins.set(plugin.id, plugin); - logAudit(plugin.id, "submitted", author_id, author_name, "developer"); - - return { plugin }; -} - -/** - * Add version to plugin - */ -export function addPluginVersion( - plugin_id: string, - version: string, - file_hash: string, - file_size: number, - changelog?: string, -): { pluginVersion: PluginVersion; error?: string } { - const plugin = plugins.get(plugin_id); - if (!plugin) { - return { pluginVersion: {} as PluginVersion, error: "Plugin not found" }; - } - - const pluginVersion: PluginVersion = { - id: `version_${randomUUID()}`, - plugin_id, - version, - status: "draft", - release_date: new Date().toISOString(), - file_hash, - file_size, - changelog, - breaking_changes: [], - dependencies: [], - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - plugin.versions.push(pluginVersion); - if (!plugin.current_version || version > plugin.current_version) { - plugin.current_version = version; - } - plugin.updated_at = new Date().toISOString(); - - return { pluginVersion }; -} - -/** - * Release plugin version - */ -export function releasePluginVersion( - plugin_id: string, - version: string, -): { pluginVersion: PluginVersion | null; error?: string } { - const plugin = plugins.get(plugin_id); - if (!plugin) { - return { pluginVersion: null, error: "Plugin not found" }; - } - - const pluginVersion = plugin.versions.find((v) => v.version === version); - if (!pluginVersion) { - return { pluginVersion: null, error: "Version not found" }; - } - - pluginVersion.status = "released"; - plugin.updated_at = new Date().toISOString(); - - return { pluginVersion }; -} - -/** - * Submit for certification - */ -export function submitForCertification( - plugin_id: string, - version: string, - tier: CertificationTier, -): { plugin: Plugin; error?: string } { - const plugin = plugins.get(plugin_id); - if (!plugin) { - return { plugin: {} as Plugin, error: "Plugin not found" }; - } - - plugin.certification_tier = tier; - plugin.certification_status = "reviewing"; - plugin.status = "submitted"; - plugin.updated_at = new Date().toISOString(); - - return { plugin }; -} - -/** - * Certify plugin - */ -export function certifyPlugin( - plugin_id: string, - version: string, - tier: CertificationTier, - reviewer_id: string, - reviewer_name: string, - security_score: number, - performance_score: number, - code_quality_score: number, - test_coverage: number, -): { audit: CertificationAudit; error?: string } { - const plugin = plugins.get(plugin_id); - if (!plugin) { - return { audit: {} as CertificationAudit, error: "Plugin not found" }; - } - - const audit: CertificationAudit = { - id: `cert_${randomUUID()}`, - plugin_id, - plugin_version: version, - certification_tier: tier, - status: "approved", - reviewer_id, - reviewer_name, - security_score, - performance_score, - code_quality_score, - test_coverage_percent: test_coverage, - findings: [], - certification_date: new Date().toISOString(), - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - certifications.set(audit.id, audit); - - plugin.certification_status = "approved"; - plugin.certification_tier = tier; - plugin.certification_date = new Date().toISOString(); - plugin.certified_by = reviewer_id; - plugin.status = "certified"; - plugin.updated_at = new Date().toISOString(); - - logAudit( - plugin_id, - "certified", - reviewer_id, - reviewer_name, - "reviewer", - ); - - return { audit }; -} - -/** - * Add finding to certification audit - */ -export function addCertificationFinding( - audit_id: string, - category: string, - severity: "info" | "warning" | "critical", - description: string, -): { audit: CertificationAudit; error?: string } { - const audit = certifications.get(audit_id); - if (!audit) { - return { audit: {} as CertificationAudit, error: "Audit not found" }; - } - - audit.findings.push({ - category, - severity, - description, - resolved: false, - }); - audit.updated_at = new Date().toISOString(); - - return { audit }; -} - -/** - * Reject certification - */ -export function rejectCertification( - plugin_id: string, - reviewer_id: string, - reviewer_name: string, - reason: string, -): { plugin: Plugin; error?: string } { - const plugin = plugins.get(plugin_id); - if (!plugin) { - return { plugin: {} as Plugin, error: "Plugin not found" }; - } - - plugin.certification_status = "rejected"; - plugin.status = "draft"; - plugin.updated_at = new Date().toISOString(); - - logAudit(plugin_id, "rejected", reviewer_id, reviewer_name, "reviewer"); - - return { plugin }; -} - -/** - * Rollback plugin to previous version - */ -export function rollbackPlugin( - plugin_id: string, - from_version: string, - to_version: string, - reason: string, - triggered_by: string, -): { rollback: PluginRollback; error?: string } { - const plugin = plugins.get(plugin_id); - if (!plugin) { - return { rollback: {} as PluginRollback, error: "Plugin not found" }; - } - - const fromVer = plugin.versions.find((v) => v.version === from_version); - const toVer = plugin.versions.find((v) => v.version === to_version); - - if (!fromVer || !toVer) { - return { rollback: {} as PluginRollback, error: "Version not found" }; - } - - const rollback: PluginRollback = { - id: `rollback_${randomUUID()}`, - plugin_id, - from_version, - to_version, - reason, - triggered_by, - triggered_at: new Date().toISOString(), - created_at: new Date().toISOString(), - }; - - rollbacks.set(rollback.id, rollback); - plugin.current_version = to_version; - plugin.updated_at = new Date().toISOString(); - - logAudit(plugin_id, "yanked", triggered_by, triggered_by, "admin"); - - return { rollback }; -} - -/** - * Deprecate plugin version - */ -export function deprecateVersion( - plugin_id: string, - version: string, -): { pluginVersion: PluginVersion | null; error?: string } { - const plugin = plugins.get(plugin_id); - if (!plugin) { - return { pluginVersion: null, error: "Plugin not found" }; - } - - const pluginVersion = plugin.versions.find((v) => v.version === version); - if (!pluginVersion) { - return { pluginVersion: null, error: "Version not found" }; - } - - pluginVersion.status = "deprecated"; - pluginVersion.deprecated_date = new Date().toISOString(); - plugin.updated_at = new Date().toISOString(); - - return { pluginVersion }; -} - -/** - * Search plugins in registry - */ -export function searchPlugins(query: PluginSearchQuery): { results: Plugin[]; total: number } { - let filtered = Array.from(plugins.values()).filter((p) => p.status === "certified"); - - if (query.query) { - const q = query.query.toLowerCase(); - filtered = filtered.filter( - (p) => - p.name.toLowerCase().includes(q) || - p.description.toLowerCase().includes(q) || - p.tags.some((t) => t.toLowerCase().includes(q)), - ); - } - - if (query.category) { - filtered = filtered.filter((p) => p.category === query.category); - } - - if (query.certification_tier) { - filtered = filtered.filter((p) => p.certification_tier === query.certification_tier); - } - - const sorted = [...filtered].sort((a, b) => { - switch (query.sort_by) { - case "rating": - return b.rating - a.rating; - case "downloads": - return b.downloads - a.downloads; - case "recent": - return new Date(b.created_at).getTime() - new Date(a.created_at).getTime(); - case "trending": - return b.rating_count - a.rating_count || b.downloads - a.downloads; - } - }); - - const results = sorted.slice(query.offset, query.offset + query.limit); - return { results, total: filtered.length }; -} - -/** - * Get plugin - */ -export function getPlugin(plugin_id: string): { plugin: Plugin | null; error?: string } { - const plugin = plugins.get(plugin_id); - return { plugin: plugin || null, error: plugin ? undefined : "Plugin not found" }; -} - -/** - * Get plugin version - */ -export function getPluginVersion( - plugin_id: string, - version: string, -): { pluginVersion: PluginVersion | null; error?: string } { - const plugin = plugins.get(plugin_id); - if (!plugin) { - return { pluginVersion: null, error: "Plugin not found" }; - } - - const pluginVersion = plugin.versions.find((v) => v.version === version); - return { - pluginVersion: pluginVersion || null, - error: pluginVersion ? undefined : "Version not found", - }; -} - -/** - * Add dependency - */ -export function addDependency( - plugin_id: string, - depends_on_plugin_id: string, - version_constraint: string, - is_optional: boolean = false, -): { dependency: PluginDependency; error?: string } { - const depPlugin = plugins.get(depends_on_plugin_id); - if (!depPlugin) { - return { dependency: {} as PluginDependency, error: "Dependency plugin not found" }; - } - - const dependency: PluginDependency = { - id: `dep_${randomUUID()}`, - plugin_id, - depends_on_plugin_id, - depends_on_name: depPlugin.name, - version_constraint, - is_optional, - created_at: new Date().toISOString(), - }; - - dependencies.set(dependency.id, dependency); - return { dependency }; -} - -/** - * Log audit event - */ -function logAudit( - plugin_id: string, - action: string, - actor_id: string, - actor_name: string, - role: "developer" | "reviewer" | "admin", -): void { - const log: RegistryAuditLog = { - id: `audit_${randomUUID()}`, - plugin_id, - action, - actor_id, - actor_name, - actor_role: role, - details: {}, - timestamp: new Date().toISOString(), - created_at: new Date().toISOString(), - }; - - auditLogs.set(log.id, log); -} - -/** - * Get audit logs for plugin - */ -export function getAuditLogs(plugin_id: string): { logs: RegistryAuditLog[] } { - const logs = Array.from(auditLogs.values()) - .filter((log) => log.plugin_id === plugin_id) - .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()); - - return { logs }; -} - -/** - * Get registry metrics - */ -export function getRegistryMetrics(): RegistryMetrics { - const allPlugins = Array.from(plugins.values()); - const certified = allPlugins.filter((p) => p.status === "certified").length; - const totalVersions = allPlugins.reduce((sum, p) => sum + p.versions.length, 0); - const totalDownloads = allPlugins.reduce((sum, p) => sum + p.downloads, 0); - const avgRating = - allPlugins.length > 0 - ? allPlugins.reduce((sum, p) => sum + p.rating, 0) / allPlugins.length - : 0; - - const byTier: Record = { bronze: 0, silver: 0, gold: 0, platinum: 0 }; - const byStatus: Record = { - draft: 0, - submitted: 0, - certified: 0, - deprecated: 0, - blacklisted: 0, - }; - - allPlugins.forEach((p) => { - byTier[p.certification_tier] = (byTier[p.certification_tier] || 0) + 1; - byStatus[p.status] = (byStatus[p.status] || 0) + 1; - }); - - return { - total_plugins: allPlugins.length, - certified_plugins: certified, - total_versions: totalVersions, - total_downloads: totalDownloads, - average_rating: avgRating, - plugins_by_tier: byTier as any, - plugins_by_status: byStatus as any, - security_issues_count: 0, - rollbacks_last_30_days: 0, - average_time_to_certification_hours: 48, - }; -} - -/** - * Rate plugin - */ -export function ratePlugin( - plugin_id: string, - rating: number, -): { plugin: Plugin | null; error?: string } { - const plugin = plugins.get(plugin_id); - if (!plugin) { - return { plugin: null, error: "Plugin not found" }; - } - - if (rating < 1 || rating > 5) { - return { plugin: null, error: "Rating must be 1-5" }; - } - - const newTotal = plugin.rating * plugin.rating_count + rating; - plugin.rating_count += 1; - plugin.rating = newTotal / plugin.rating_count; - plugin.updated_at = new Date().toISOString(); - - return { plugin }; -} diff --git a/src/team-model.ts b/src/team-model.ts deleted file mode 100644 index 606bc18b..00000000 --- a/src/team-model.ts +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Team Management System — data models and types - * Supports RBAC, member management, invitations, audit logging - */ - -export type Role = "owner" | "admin" | "developer" | "guest"; - -export interface Team { - id: string; - name: string; - owner_id: string; - created_at: string; - updated_at: string; -} - -export interface TeamMember { - id: string; - team_id: string; - user_id: string; - email: string; - role: Role; - invited_at: string; - joined_at: string | null; - status: "pending" | "accepted" | "revoked"; -} - -export interface TeamInvitation { - id: string; - team_id: string; - email: string; - role: Role; - token: string; - created_at: string; - expires_at: string; - accepted_at: string | null; -} - -export interface AuditLog { - id: string; - team_id: string; - user_id: string; - action: AuditAction; - resource_type: string; - resource_id: string; - resource_name: string; - status: "success" | "failure"; - details: Record; - timestamp: string; -} - -export type AuditAction = - | "team_created" - | "team_updated" - | "team_deleted" - | "member_invited" - | "member_joined" - | "member_removed" - | "member_role_changed" - | "member_revoked" - | "secret_accessed" - | "secret_rotated" - | "config_changed"; - -/** - * RBAC Permission Matrix - * Maps role → actions allowed on resources - */ -export const PERMISSION_MATRIX: Record> = { - owner: { - // Full access - "team:read": true, - "team:write": true, - "team:delete": true, - "member:read": true, - "member:invite": true, - "member:remove": true, - "member:role_change": true, - "secret:read": true, - "secret:write": true, - "secret:manage": true, - "audit:read": true, - "billing:manage": true, - }, - admin: { - // Full access except billing - "team:read": true, - "team:write": true, - "team:delete": false, - "member:read": true, - "member:invite": true, - "member:remove": true, - "member:role_change": true, - "secret:read": true, - "secret:write": true, - "secret:manage": true, - "audit:read": true, - "billing:manage": false, - }, - developer: { - // Can use team resources - "team:read": true, - "team:write": false, - "team:delete": false, - "member:read": true, - "member:invite": false, - "member:remove": false, - "member:role_change": false, - "secret:read": true, - "secret:write": false, - "secret:manage": false, - "audit:read": false, - "billing:manage": false, - }, - guest: { - // Read-only access - "team:read": true, - "team:write": false, - "team:delete": false, - "member:read": true, - "member:invite": false, - "member:remove": false, - "member:role_change": false, - "secret:read": false, - "secret:write": false, - "secret:manage": false, - "audit:read": false, - "billing:manage": false, - }, -}; - -/** - * Check if role has permission for action - */ -export function hasPermission(role: Role, action: string): boolean { - return PERMISSION_MATRIX[role]?.[action] ?? false; -} - -/** - * Validate role - */ -export function isValidRole(role: string): role is Role { - return ["owner", "admin", "developer", "guest"].includes(role); -} diff --git a/src/team-service.test.ts b/src/team-service.test.ts deleted file mode 100644 index 16611b90..00000000 --- a/src/team-service.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { - createTeam, - getTeam, - inviteToTeam, - listTeamMembers, - removeTeamMember, - getAuditLogs, -} from "./team-service.js"; - -describe("team-service", () => { - describe("createTeam", () => { - it("creates team with owner", () => { - const { team, error } = createTeam("Test Team", "owner-123"); - - assert.ok(!error); - assert.ok(team.id); - assert.equal(team.name, "Test Team"); - assert.equal(team.owner_id, "owner-123"); - }); - - it("rejects empty name", () => { - const { error } = createTeam("", "owner-123"); - - assert.ok(error); - assert.equal(error, "Team name required"); - }); - }); - - describe("getTeam", () => { - it("retrieves existing team", () => { - const { team: created } = createTeam("Retrieved Team", "owner-456"); - const retrieved = getTeam(created.id); - - assert.ok(retrieved); - assert.equal(retrieved?.name, "Retrieved Team"); - }); - - it("returns null for missing team", () => { - const result = getTeam("nonexistent-id"); - assert.equal(result, null); - }); - }); - - describe("inviteToTeam", () => { - it("invites user with valid role", () => { - const { team } = createTeam("Invite Test", "owner-789"); - const { invitation, error } = inviteToTeam( - team.id, - "user@example.com", - "developer", - "owner-789", - ); - - assert.ok(!error); - assert.ok(invitation.id); - assert.equal(invitation.email, "user@example.com"); - assert.equal(invitation.role, "developer"); - }); - - it("rejects invalid role", () => { - const { team } = createTeam("Role Test", "owner-abc"); - const { error } = inviteToTeam( - team.id, - "user@test.com", - "superuser", - "owner-abc", - ); - - assert.ok(error); - assert.ok(error?.includes("Invalid role")); - }); - - it("rejects invite from non-member", () => { - const { team } = createTeam("Permission Test", "owner-def"); - const { error } = inviteToTeam( - team.id, - "user@test.com", - "developer", - "random-user", - ); - - assert.ok(error); - assert.ok(error?.includes("Not authorized")); - }); - }); - - describe("listTeamMembers", () => { - it("includes owner in new team", () => { - const { team } = createTeam("Owner Team", "owner-ghi"); - const { members } = listTeamMembers(team.id); - - assert.equal(members.length, 1); - assert.equal(members[0].role, "owner"); - assert.equal(members[0].user_id, "owner-ghi"); - }); - }); - - describe("removeTeamMember", () => { - it("prevents removing owner", () => { - const { team } = createTeam("Owner Test", "owner-jkl"); - // Try to remove owner (would need member setup) - const { success, error } = removeTeamMember( - team.id, - "owner-jkl", - "owner-jkl", - ); - - // Since we don't have proper member setup, error is expected - assert.ok(!success || error); - }); - }); - - describe("getAuditLogs", () => { - it("returns audit logs for team", () => { - const { team } = createTeam("Audit Test", "owner-mno"); - const { logs, total } = getAuditLogs(team.id); - - // Should have at least team_created event - assert.ok(total >= 1); - assert.ok(logs.length >= 1); - assert.equal(logs[0].action, "team_created"); - }); - - it("respects limit parameter", () => { - const { team } = createTeam("Limit Test", "owner-pqr"); - const { logs } = getAuditLogs(team.id, 0); - - assert.equal(logs.length, 0); - }); - }); -}); diff --git a/src/team-service.ts b/src/team-service.ts deleted file mode 100644 index 7cf124f6..00000000 --- a/src/team-service.ts +++ /dev/null @@ -1,295 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - Team, - TeamMember, - TeamInvitation, - AuditLog, - Role, -} from "./team-model.js"; -import { hasPermission, isValidRole } from "./team-model.js"; - -/** - * In-memory team storage (production would use database) - */ -const teams = new Map(); -const members = new Map(); -const invitations = new Map(); -const auditLogs: AuditLog[] = []; - -/** - * Create team - */ -export function createTeam( - name: string, - owner_id: string, -): { team: Team; error?: string } { - if (!name || name.trim().length === 0) { - return { team: {} as Team, error: "Team name required" }; - } - - const team: Team = { - id: `team_${randomUUID()}`, - name: name.trim(), - owner_id, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - teams.set(team.id, team); - - // Add owner as member automatically - const ownerMember: TeamMember = { - id: `mem_${randomUUID()}`, - team_id: team.id, - user_id: owner_id, - email: `owner-${owner_id}@kit.local`, // Placeholder - role: "owner", - invited_at: team.created_at, - joined_at: team.created_at, - status: "accepted", - }; - members.set(ownerMember.id, ownerMember); - - logAudit(team.id, owner_id, "team_created", "team", team.id, name, { - owner_id, - }); - - return { team }; -} - -/** - * Get team by ID - */ -export function getTeam(team_id: string): Team | null { - return teams.get(team_id) ?? null; -} - -/** - * Invite user to team - */ -export function inviteToTeam( - team_id: string, - email: string, - role: string, - inviter_id: string, -): { invitation: TeamInvitation; error?: string } { - // Validate team exists - const team = teams.get(team_id); - if (!team) { - return { invitation: {} as TeamInvitation, error: "Team not found" }; - } - - // Check inviter has permission - const inviter = Array.from(members.values()).find( - (m) => m.team_id === team_id && m.user_id === inviter_id, - ); - if (!inviter || !hasPermission(inviter.role, "member:invite")) { - return { invitation: {} as TeamInvitation, error: "Not authorized to invite" }; - } - - // Validate role - if (!isValidRole(role)) { - return { invitation: {} as TeamInvitation, error: "Invalid role" }; - } - - // Check email not already member - const existing = Array.from(members.values()).find( - (m) => m.team_id === team_id && m.email === email, - ); - if (existing && existing.status === "accepted") { - return { invitation: {} as TeamInvitation, error: "User already member" }; - } - - const invitation: TeamInvitation = { - id: `inv_${randomUUID()}`, - team_id, - email, - role: role as Role, - token: randomUUID(), - created_at: new Date().toISOString(), - expires_at: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(), // 7 days - accepted_at: null, - }; - - invitations.set(invitation.id, invitation); - logAudit(team_id, inviter_id, "member_invited", "user", email, email, { - role, - }); - - return { invitation }; -} - -/** - * Accept invitation and join team - */ -export function acceptInvitation( - invitation_id: string, - user_id: string, - email: string, -): { member: TeamMember; error?: string } { - const invitation = invitations.get(invitation_id); - if (!invitation) { - return { member: {} as TeamMember, error: "Invitation not found" }; - } - - if (invitation.email !== email) { - return { member: {} as TeamMember, error: "Email mismatch" }; - } - - if (new Date(invitation.expires_at) < new Date()) { - return { member: {} as TeamMember, error: "Invitation expired" }; - } - - const member: TeamMember = { - id: `mem_${randomUUID()}`, - team_id: invitation.team_id, - user_id, - email, - role: invitation.role, - invited_at: invitation.created_at, - joined_at: new Date().toISOString(), - status: "accepted", - }; - - members.set(member.id, member); - invitation.accepted_at = new Date().toISOString(); - logAudit(invitation.team_id, user_id, "member_joined", "user", user_id, email, { - role: invitation.role, - }); - - return { member }; -} - -/** - * List team members - */ -export function listTeamMembers( - team_id: string, -): { members: TeamMember[]; error?: string } { - const team = teams.get(team_id); - if (!team) { - return { members: [], error: "Team not found" }; - } - - const teamMembers = Array.from(members.values()).filter( - (m) => m.team_id === team_id && m.status === "accepted", - ); - - return { members: teamMembers }; -} - -/** - * Remove member from team - */ -export function removeTeamMember( - team_id: string, - member_id: string, - requester_id: string, -): { success: boolean; error?: string } { - const team = teams.get(team_id); - if (!team) { - return { success: false, error: "Team not found" }; - } - - // Check requester has permission - const requester = Array.from(members.values()).find( - (m) => m.team_id === team_id && m.user_id === requester_id, - ); - if (!requester || !hasPermission(requester.role, "member:remove")) { - return { success: false, error: "Not authorized to remove members" }; - } - - const member = members.get(member_id); - if (!member || member.team_id !== team_id) { - return { success: false, error: "Member not found" }; - } - - // Prevent removing owner - if (member.role === "owner") { - return { success: false, error: "Cannot remove team owner" }; - } - - member.status = "revoked"; - logAudit(team_id, requester_id, "member_removed", "user", member.user_id, member.email, {}); - - return { success: true }; -} - -/** - * Change member role - */ -export function changeTeamMemberRole( - team_id: string, - member_id: string, - new_role: string, - requester_id: string, -): { success: boolean; error?: string } { - if (!isValidRole(new_role)) { - return { success: false, error: "Invalid role" }; - } - - // Check requester has permission - const requester = Array.from(members.values()).find( - (m) => m.team_id === team_id && m.user_id === requester_id, - ); - if (!requester || !hasPermission(requester.role, "member:role_change")) { - return { success: false, error: "Not authorized to change roles" }; - } - - const member = members.get(member_id); - if (!member || member.team_id !== team_id) { - return { success: false, error: "Member not found" }; - } - - const old_role = member.role; - member.role = new_role as Role; - logAudit(team_id, requester_id, "member_role_changed", "user", member.user_id, member.email, { - old_role, - new_role, - }); - - return { success: true }; -} - -/** - * Get audit logs - */ -export function getAuditLogs( - team_id: string, - limit = 100, -): { logs: AuditLog[]; total: number } { - const filtered = auditLogs - .filter((log) => log.team_id === team_id) - .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()) - .slice(0, limit); - - return { logs: filtered, total: auditLogs.filter((l) => l.team_id === team_id).length }; -} - -/** - * Log audit event - */ -function logAudit( - team_id: string, - user_id: string, - action: string, - resource_type: string, - resource_id: string, - resource_name: string, - details: Record, -): void { - const log: AuditLog = { - id: `audit_${randomUUID()}`, - team_id, - user_id, - action: action as any, - resource_type, - resource_id, - resource_name, - status: "success", - details, - timestamp: new Date().toISOString(), - }; - - auditLogs.push(log); -}