@larkup/marketplace 0.1.24 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/.env.example +3 -0
  2. package/CHANGELOG.md +180 -0
  3. package/README.md +34 -0
  4. package/db/drizzle/0000_hesitant_joseph.sql +69 -0
  5. package/db/drizzle/0001_deep_phil_sheldon.sql +1 -0
  6. package/db/drizzle/0002_jittery_living_mummy.sql +18 -0
  7. package/db/drizzle/meta/0000_snapshot.json +483 -0
  8. package/db/drizzle/meta/0001_snapshot.json +490 -0
  9. package/db/drizzle/meta/0002_snapshot.json +615 -0
  10. package/db/drizzle/meta/_journal.json +27 -0
  11. package/db/drizzle.config.ts +19 -0
  12. package/db/tsconfig.build.json +11 -0
  13. package/db/tsconfig.json +17 -0
  14. package/db/vitest.config.ts +11 -0
  15. package/package.json +31 -4
  16. package/src/db/builtin-tools.ts +613 -0
  17. package/src/db/client.ts +26 -0
  18. package/src/db/repo.test.ts +309 -0
  19. package/src/db/repo.ts +558 -0
  20. package/src/db/schema/audit.ts +27 -0
  21. package/src/db/schema/extensions.ts +73 -0
  22. package/src/db/schema/index.ts +5 -0
  23. package/src/db/schema/installations.ts +23 -0
  24. package/src/db/schema/publishers.ts +13 -0
  25. package/src/db/schema/versions.ts +22 -0
  26. package/src/db/seed.ts +33 -0
  27. package/src/db/validate.test.ts +79 -0
  28. package/src/db/validate.ts +84 -0
  29. package/src/output-sanitizer.test.ts +17 -0
  30. package/src/output-sanitizer.ts +8 -0
  31. package/src/storage-provider-s3.test.ts +110 -0
  32. package/src/storage-provider.ts +164 -13
  33. package/src/tool-extension.ts +247 -0
  34. package/src/tool-installer.ts +80 -109
  35. package/src/tool-loader.test.ts +120 -0
  36. package/src/tool-loader.ts +99 -37
  37. package/src/tool-manifest.schema.ts +89 -32
  38. package/src/tool-registry.ts +34 -111
  39. package/src/types.ts +217 -87
  40. package/vitest.config.ts +13 -0
package/src/db/repo.ts ADDED
@@ -0,0 +1,558 @@
1
+ /** Marketplace catalog queries. */
2
+
3
+ import { and, count, eq, ilike, isNull, or, sql } from 'drizzle-orm';
4
+ import type { MarketplaceDb } from './client.js';
5
+ import { auditEvents } from './schema/audit.js';
6
+ import {
7
+ extensionAccessKeys,
8
+ extensionWorkspaceGrants,
9
+ extensions,
10
+ type ACCESS_KEY_SCOPES,
11
+ } from './schema/extensions.js';
12
+ import { extensionVersions } from './schema/versions.js';
13
+ import { publishers } from './schema/publishers.js';
14
+ import { workspaceInstallations } from './schema/installations.js';
15
+ import { validateToolManifest } from './validate.js';
16
+
17
+ export class ManifestInvalidError extends Error {
18
+ constructor(readonly errors: string[]) {
19
+ super(`Invalid manifest: ${errors.join('; ')}`);
20
+ this.name = 'ManifestInvalidError';
21
+ }
22
+ }
23
+
24
+ /** Thrown when another publisher owns the extension id. */
25
+ export class NotOwnerError extends Error {
26
+ constructor(extensionId: string) {
27
+ super(`"${extensionId}" is published by a different publisher.`);
28
+ this.name = 'NotOwnerError';
29
+ }
30
+ }
31
+
32
+ /** Thrown when an extension version already exists. */
33
+ export class VersionExistsError extends Error {
34
+ constructor(extensionId: string, version: string) {
35
+ super(`"${extensionId}@${version}" is already published. Publish a new version instead.`);
36
+ this.name = 'VersionExistsError';
37
+ }
38
+ }
39
+
40
+ /** Thrown when a caller has no grant for a private extension. */
41
+ export class NotAuthorizedError extends Error {
42
+ constructor(extensionId: string) {
43
+ super(`"${extensionId}" is private and this workspace has no access grant.`);
44
+ this.name = 'NotAuthorizedError';
45
+ }
46
+ }
47
+
48
+ /** Thrown when an access key is missing, expired, revoked, or exhausted. */
49
+ export class InvalidAccessKeyError extends Error {
50
+ constructor(message = 'This access key is invalid, expired, or has no installs left.') {
51
+ super(message);
52
+ this.name = 'InvalidAccessKeyError';
53
+ }
54
+ }
55
+
56
+ export interface CatalogEntry {
57
+ id: string;
58
+ publisherId: string;
59
+ publisherName: string;
60
+ publisherVerification: 'unverified' | 'verified';
61
+ kind: string;
62
+ name: string;
63
+ description: string;
64
+ category: string;
65
+ packageName: string;
66
+ requiresSandbox: boolean;
67
+ distribution: string;
68
+ repositoryUrl: string | null;
69
+ license: string | null;
70
+ version: string;
71
+ manifest: unknown;
72
+ installs: number;
73
+ updatedAt: Date;
74
+ }
75
+
76
+ /** Limits private extensions to granted workspaces. Used for browse/search — never for exact-id lookup. */
77
+ function visibilityFilter(workspaceId: string | undefined) {
78
+ return workspaceId
79
+ ? or(
80
+ eq(extensions.distribution, 'public'),
81
+ sql`exists (select 1 from ${extensionWorkspaceGrants}
82
+ where ${extensionWorkspaceGrants.extensionId} = ${extensions.id}
83
+ and ${extensionWorkspaceGrants.workspaceId} = ${workspaceId})`,
84
+ )
85
+ : eq(extensions.distribution, 'public');
86
+ }
87
+
88
+ /** Whether a workspace holds an install grant for a private extension. */
89
+ async function hasWorkspaceGrant(
90
+ db: MarketplaceDb,
91
+ extensionId: string,
92
+ workspaceId: string | undefined,
93
+ ): Promise<boolean> {
94
+ if (!workspaceId) return false;
95
+ const [row] = await db
96
+ .select({ id: extensionWorkspaceGrants.id })
97
+ .from(extensionWorkspaceGrants)
98
+ .where(
99
+ and(
100
+ eq(extensionWorkspaceGrants.extensionId, extensionId),
101
+ eq(extensionWorkspaceGrants.workspaceId, workspaceId),
102
+ ),
103
+ )
104
+ .limit(1);
105
+ return Boolean(row);
106
+ }
107
+
108
+ async function latestVersionSubquery(db: MarketplaceDb, extensionId: string) {
109
+ const [latest] = await db
110
+ .select()
111
+ .from(extensionVersions)
112
+ .where(eq(extensionVersions.extensionId, extensionId))
113
+ .orderBy(sql`${extensionVersions.publishedAt} desc`)
114
+ .limit(1);
115
+ return latest;
116
+ }
117
+
118
+ export interface ListExtensionsOptions {
119
+ category?: string;
120
+ search?: string;
121
+ workspaceId?: string;
122
+ limit?: number;
123
+ offset?: number;
124
+ }
125
+
126
+ export async function listExtensions(
127
+ db: MarketplaceDb,
128
+ options: ListExtensionsOptions = {},
129
+ ): Promise<{ entries: CatalogEntry[]; total: number }> {
130
+ const conditions = [visibilityFilter(options.workspaceId)];
131
+ if (options.category) conditions.push(eq(extensions.category, options.category));
132
+ if (options.search) {
133
+ const q = `%${options.search}%`;
134
+ conditions.push(
135
+ or(
136
+ ilike(extensions.name, q),
137
+ ilike(extensions.description, q),
138
+ ilike(extensions.packageName, q),
139
+ )!,
140
+ );
141
+ }
142
+ const where = and(...conditions);
143
+
144
+ const rows = await db
145
+ .select({ ext: extensions, publisher: publishers })
146
+ .from(extensions)
147
+ .innerJoin(publishers, eq(extensions.publisherId, publishers.id))
148
+ .where(where)
149
+ .orderBy(extensions.name)
150
+ .limit(options.limit ?? 50)
151
+ .offset(options.offset ?? 0);
152
+
153
+ const [{ value: total }] = await db.select({ value: count() }).from(extensions).where(where);
154
+
155
+ const entries = await Promise.all(
156
+ rows.map(async ({ ext, publisher }) => {
157
+ const latest = await latestVersionSubquery(db, ext.id);
158
+ const [{ value: installs }] = await db
159
+ .select({ value: count() })
160
+ .from(workspaceInstallations)
161
+ .where(eq(workspaceInstallations.extensionId, ext.id));
162
+ return toEntry(ext, publisher, latest, installs);
163
+ }),
164
+ );
165
+
166
+ return { entries, total };
167
+ }
168
+
169
+ /**
170
+ * Fetches a single extension by its exact id. Unlike `listExtensions`, this
171
+ * always reveals a private extension's metadata — discovery by exact id is
172
+ * intentionally not gated (a manifest never carries secrets, only config
173
+ * schema/labels). `authorized` tells the caller whether this workspace may
174
+ * actually install it; enforce that separately, do not infer it from a 200.
175
+ */
176
+ export async function getExtension(
177
+ db: MarketplaceDb,
178
+ id: string,
179
+ options: { workspaceId?: string } = {},
180
+ ): Promise<{
181
+ entry: CatalogEntry;
182
+ versions: { version: string; publishedAt: Date }[];
183
+ authorized: boolean;
184
+ } | null> {
185
+ const [row] = await db
186
+ .select({ ext: extensions, publisher: publishers })
187
+ .from(extensions)
188
+ .innerJoin(publishers, eq(extensions.publisherId, publishers.id))
189
+ .where(eq(extensions.id, id))
190
+ .limit(1);
191
+ if (!row) return null;
192
+
193
+ const versionRows = await db
194
+ .select({ version: extensionVersions.version, publishedAt: extensionVersions.publishedAt })
195
+ .from(extensionVersions)
196
+ .where(eq(extensionVersions.extensionId, id))
197
+ .orderBy(sql`${extensionVersions.publishedAt} desc`);
198
+
199
+ const latest = await latestVersionSubquery(db, id);
200
+ const [{ value: installs }] = await db
201
+ .select({ value: count() })
202
+ .from(workspaceInstallations)
203
+ .where(eq(workspaceInstallations.extensionId, id));
204
+
205
+ const authorized =
206
+ row.ext.distribution === 'public' || (await hasWorkspaceGrant(db, id, options.workspaceId));
207
+
208
+ return {
209
+ entry: toEntry(row.ext, row.publisher, latest, installs),
210
+ versions: versionRows,
211
+ authorized,
212
+ };
213
+ }
214
+
215
+ function toEntry(
216
+ ext: typeof extensions.$inferSelect,
217
+ publisher: typeof publishers.$inferSelect,
218
+ latest: typeof extensionVersions.$inferSelect | undefined,
219
+ installs: number,
220
+ ): CatalogEntry {
221
+ return {
222
+ id: ext.id,
223
+ publisherId: ext.publisherId,
224
+ publisherName: publisher.name,
225
+ publisherVerification: publisher.verification,
226
+ kind: ext.kind,
227
+ name: ext.name,
228
+ description: ext.description,
229
+ category: ext.category,
230
+ packageName: ext.packageName,
231
+ requiresSandbox: ext.requiresSandbox,
232
+ distribution: ext.distribution,
233
+ repositoryUrl: ext.repositoryUrl,
234
+ license: ext.license,
235
+ version: latest?.version ?? '0.0.0',
236
+ manifest: latest?.manifest ?? {},
237
+ installs,
238
+ updatedAt: ext.updatedAt,
239
+ };
240
+ }
241
+
242
+ export interface PublishInput {
243
+ manifest: Record<string, unknown>;
244
+ publisherId: string;
245
+ publisherName?: string;
246
+ }
247
+
248
+ async function sha256Hex(input: string): Promise<string> {
249
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));
250
+ return Array.from(new Uint8Array(digest))
251
+ .map((b) => b.toString(16).padStart(2, '0'))
252
+ .join('');
253
+ }
254
+
255
+ /** Publishes an immutable extension version. */
256
+ export async function publishExtension(
257
+ db: MarketplaceDb,
258
+ input: PublishInput,
259
+ ): Promise<{ extensionId: string; version: string }> {
260
+ const manifest = {
261
+ ...input.manifest,
262
+ requiresSandbox: input.manifest.requiresSandbox !== false,
263
+ };
264
+ const validation = validateToolManifest(manifest);
265
+ if (!validation.valid) throw new ManifestInvalidError(validation.errors);
266
+
267
+ const m = manifest as {
268
+ id: string;
269
+ name: string;
270
+ description: string;
271
+ category: string;
272
+ packageName: string;
273
+ version: string;
274
+ repositoryUrl?: string;
275
+ license?: string;
276
+ kind?: string;
277
+ requiresSandbox: boolean;
278
+ distribution?: 'public' | 'private';
279
+ };
280
+
281
+ await db
282
+ .insert(publishers)
283
+ .values({ id: input.publisherId, name: input.publisherName ?? input.publisherId })
284
+ .onConflictDoNothing();
285
+
286
+ const [existing] = await db.select().from(extensions).where(eq(extensions.id, m.id)).limit(1);
287
+ if (existing && existing.publisherId !== input.publisherId) {
288
+ throw new NotOwnerError(m.id);
289
+ }
290
+
291
+ const [existingVersion] = await db
292
+ .select({ id: extensionVersions.id })
293
+ .from(extensionVersions)
294
+ .where(and(eq(extensionVersions.extensionId, m.id), eq(extensionVersions.version, m.version)))
295
+ .limit(1);
296
+ if (existingVersion) throw new VersionExistsError(m.id, m.version);
297
+
298
+ const now = new Date();
299
+ if (existing) {
300
+ await db
301
+ .update(extensions)
302
+ .set({
303
+ name: m.name,
304
+ description: m.description,
305
+ category: m.category,
306
+ packageName: m.packageName,
307
+ requiresSandbox: m.requiresSandbox,
308
+ distribution: m.distribution ?? 'public',
309
+ repositoryUrl: m.repositoryUrl ?? null,
310
+ license: m.license ?? null,
311
+ updatedAt: now,
312
+ })
313
+ .where(eq(extensions.id, m.id));
314
+ } else {
315
+ await db.insert(extensions).values({
316
+ id: m.id,
317
+ publisherId: input.publisherId,
318
+ kind: (m.kind as 'tool' | 'skill' | 'channel' | 'knowledge-integration') ?? 'tool',
319
+ name: m.name,
320
+ description: m.description,
321
+ category: m.category,
322
+ packageName: m.packageName,
323
+ requiresSandbox: m.requiresSandbox,
324
+ distribution: m.distribution ?? 'public',
325
+ repositoryUrl: m.repositoryUrl ?? null,
326
+ license: m.license ?? null,
327
+ });
328
+ }
329
+
330
+ const integrity = await sha256Hex(JSON.stringify(manifest));
331
+ await db.insert(extensionVersions).values({
332
+ id: crypto.randomUUID(),
333
+ extensionId: m.id,
334
+ version: m.version,
335
+ manifest,
336
+ integrity,
337
+ publishedBy: input.publisherId,
338
+ });
339
+
340
+ await db.insert(auditEvents).values({
341
+ id: crypto.randomUUID(),
342
+ actor: input.publisherId,
343
+ action: 'extension.published',
344
+ extensionId: m.id,
345
+ metadata: { version: m.version },
346
+ });
347
+
348
+ return { extensionId: m.id, version: m.version };
349
+ }
350
+
351
+ export async function recordInstall(
352
+ db: MarketplaceDb,
353
+ extensionId: string,
354
+ workspaceId: string,
355
+ ): Promise<{ installs: number } | null> {
356
+ const [ext] = await db
357
+ .select({ id: extensions.id, distribution: extensions.distribution })
358
+ .from(extensions)
359
+ .where(eq(extensions.id, extensionId));
360
+ if (!ext) return null;
361
+
362
+ if (ext.distribution === 'private' && !(await hasWorkspaceGrant(db, extensionId, workspaceId))) {
363
+ throw new NotAuthorizedError(extensionId);
364
+ }
365
+
366
+ await db
367
+ .insert(workspaceInstallations)
368
+ .values({ id: crypto.randomUUID(), extensionId, workspaceId })
369
+ .onConflictDoUpdate({
370
+ target: [workspaceInstallations.extensionId, workspaceInstallations.workspaceId],
371
+ set: { updatedAt: new Date() },
372
+ });
373
+
374
+ await db.insert(auditEvents).values({
375
+ id: crypto.randomUUID(),
376
+ actor: workspaceId,
377
+ action: 'extension.installed',
378
+ extensionId,
379
+ workspaceId,
380
+ });
381
+
382
+ const [{ value: installs }] = await db
383
+ .select({ value: count() })
384
+ .from(workspaceInstallations)
385
+ .where(eq(workspaceInstallations.extensionId, extensionId));
386
+
387
+ return { installs };
388
+ }
389
+
390
+ export async function grantWorkspaceAccess(
391
+ db: MarketplaceDb,
392
+ extensionId: string,
393
+ workspaceId: string,
394
+ ): Promise<void> {
395
+ await db
396
+ .insert(extensionWorkspaceGrants)
397
+ .values({ id: crypto.randomUUID(), extensionId, workspaceId })
398
+ .onConflictDoNothing();
399
+ await db.insert(auditEvents).values({
400
+ id: crypto.randomUUID(),
401
+ actor: 'system',
402
+ action: 'extension.grant_added',
403
+ extensionId,
404
+ workspaceId,
405
+ });
406
+ }
407
+
408
+ // Private tool access keys */
409
+
410
+ const ACCESS_KEY_PREFIX = 'lk_key_';
411
+
412
+ function generateAccessKey(): string {
413
+ const random = Buffer.from(crypto.getRandomValues(new Uint8Array(24))).toString('base64url');
414
+ return `${ACCESS_KEY_PREFIX}${random}`;
415
+ }
416
+
417
+ export interface IssueAccessKeyInput {
418
+ extensionId: string;
419
+ scope: (typeof ACCESS_KEY_SCOPES)[number];
420
+ /** Organization/user id this key is bound to. Omit for a shared/unscoped key. */
421
+ scopeId?: string;
422
+ maxInstalls?: number;
423
+ expiresAt?: Date;
424
+ createdBy: string;
425
+ }
426
+
427
+ /** Issues a new private-tool access key. The plaintext is returned once and never stored. */
428
+ export async function issueAccessKey(
429
+ db: MarketplaceDb,
430
+ input: IssueAccessKeyInput,
431
+ ): Promise<{ id: string; accessKey: string }> {
432
+ const [ext] = await db
433
+ .select({ id: extensions.id })
434
+ .from(extensions)
435
+ .where(eq(extensions.id, input.extensionId))
436
+ .limit(1);
437
+ if (!ext) throw new Error(`Unknown extension: "${input.extensionId}"`);
438
+
439
+ const accessKey = generateAccessKey();
440
+ const id = crypto.randomUUID();
441
+ await db.insert(extensionAccessKeys).values({
442
+ id,
443
+ extensionId: input.extensionId,
444
+ keyHash: await sha256Hex(accessKey),
445
+ keyPrefix: accessKey.slice(0, ACCESS_KEY_PREFIX.length + 6),
446
+ scope: input.scope,
447
+ scopeId: input.scopeId ?? null,
448
+ maxInstalls: input.maxInstalls ?? null,
449
+ expiresAt: input.expiresAt ?? null,
450
+ createdBy: input.createdBy,
451
+ });
452
+ await db.insert(auditEvents).values({
453
+ id: crypto.randomUUID(),
454
+ actor: input.createdBy,
455
+ action: 'extension.key_issued',
456
+ extensionId: input.extensionId,
457
+ metadata: { keyId: id, scope: input.scope, scopeId: input.scopeId },
458
+ });
459
+ return { id, accessKey };
460
+ }
461
+
462
+ /** Revokes an access key. Grants already redeemed from it are unaffected — revoke those separately. */
463
+ export async function revokeAccessKey(
464
+ db: MarketplaceDb,
465
+ extensionId: string,
466
+ keyId: string,
467
+ actor: string,
468
+ ): Promise<void> {
469
+ const result = await db
470
+ .update(extensionAccessKeys)
471
+ .set({ revokedAt: new Date() })
472
+ .where(
473
+ and(
474
+ eq(extensionAccessKeys.id, keyId),
475
+ eq(extensionAccessKeys.extensionId, extensionId),
476
+ isNull(extensionAccessKeys.revokedAt),
477
+ ),
478
+ )
479
+ .returning({ id: extensionAccessKeys.id });
480
+ if (!result.length) throw new Error('Access key not found or already revoked.');
481
+ await db.insert(auditEvents).values({
482
+ id: crypto.randomUUID(),
483
+ actor,
484
+ action: 'extension.key_revoked',
485
+ extensionId,
486
+ metadata: { keyId },
487
+ });
488
+ }
489
+
490
+ /** Lists access keys for an extension, admin-only — hashes are never returned. */
491
+ export async function listAccessKeys(db: MarketplaceDb, extensionId: string) {
492
+ return db
493
+ .select({
494
+ id: extensionAccessKeys.id,
495
+ keyPrefix: extensionAccessKeys.keyPrefix,
496
+ scope: extensionAccessKeys.scope,
497
+ scopeId: extensionAccessKeys.scopeId,
498
+ maxInstalls: extensionAccessKeys.maxInstalls,
499
+ installCount: extensionAccessKeys.installCount,
500
+ expiresAt: extensionAccessKeys.expiresAt,
501
+ revokedAt: extensionAccessKeys.revokedAt,
502
+ createdBy: extensionAccessKeys.createdBy,
503
+ createdAt: extensionAccessKeys.createdAt,
504
+ })
505
+ .from(extensionAccessKeys)
506
+ .where(eq(extensionAccessKeys.extensionId, extensionId))
507
+ .orderBy(sql`${extensionAccessKeys.createdAt} desc`);
508
+ }
509
+
510
+ /**
511
+ * Redeems an access key into a standing workspace grant. This is the one
512
+ * place a plaintext key is ever checked; everything downstream (visibility,
513
+ * install) reads the grant it creates, exactly like a key issued by hand
514
+ * through `grantWorkspaceAccess`.
515
+ */
516
+ export async function redeemAccessKey(
517
+ db: MarketplaceDb,
518
+ extensionId: string,
519
+ accessKey: string,
520
+ workspaceId: string,
521
+ ): Promise<void> {
522
+ if (!workspaceId?.trim())
523
+ throw new InvalidAccessKeyError('A workspaceId is required to redeem an access key.');
524
+ const keyHash = await sha256Hex(accessKey);
525
+ const now = new Date();
526
+
527
+ const [key] = await db
528
+ .select()
529
+ .from(extensionAccessKeys)
530
+ .where(
531
+ and(
532
+ eq(extensionAccessKeys.extensionId, extensionId),
533
+ eq(extensionAccessKeys.keyHash, keyHash),
534
+ isNull(extensionAccessKeys.revokedAt),
535
+ ),
536
+ )
537
+ .limit(1);
538
+
539
+ if (!key) throw new InvalidAccessKeyError();
540
+ if (key.expiresAt && key.expiresAt.getTime() <= now.getTime()) throw new InvalidAccessKeyError();
541
+ if (key.maxInstalls !== null && key.installCount >= key.maxInstalls)
542
+ throw new InvalidAccessKeyError();
543
+
544
+ await db
545
+ .update(extensionAccessKeys)
546
+ .set({ installCount: sql`${extensionAccessKeys.installCount} + 1` })
547
+ .where(eq(extensionAccessKeys.id, key.id));
548
+
549
+ await grantWorkspaceAccess(db, extensionId, workspaceId);
550
+ await db.insert(auditEvents).values({
551
+ id: crypto.randomUUID(),
552
+ actor: workspaceId,
553
+ action: 'extension.key_redeemed',
554
+ extensionId,
555
+ workspaceId,
556
+ metadata: { keyId: key.id },
557
+ });
558
+ }
@@ -0,0 +1,27 @@
1
+ import { index, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
2
+
3
+ export const AUDIT_ACTIONS = [
4
+ 'extension.published',
5
+ 'extension.installed',
6
+ 'extension.grant_added',
7
+ 'extension.grant_removed',
8
+ 'extension.deprecated',
9
+ 'extension.key_issued',
10
+ 'extension.key_redeemed',
11
+ 'extension.key_revoked',
12
+ ] as const;
13
+
14
+ /** Catalog audit trail. */
15
+ export const auditEvents = pgTable(
16
+ 'audit_events',
17
+ {
18
+ id: text('id').primaryKey(),
19
+ actor: text('actor').notNull(),
20
+ action: text('action', { enum: AUDIT_ACTIONS }).notNull(),
21
+ extensionId: text('extension_id'),
22
+ workspaceId: text('workspace_id'),
23
+ metadata: jsonb('metadata'),
24
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
25
+ },
26
+ (table) => [index('audit_events_extension_id_idx').on(table.extensionId)],
27
+ );
@@ -0,0 +1,73 @@
1
+ import { boolean, index, integer, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
2
+ import { publishers } from './publishers.js';
3
+
4
+ /** Supported Marketplace extension kinds. */
5
+ export const EXTENSION_KINDS = ['tool', 'skill', 'channel', 'knowledge-integration'] as const;
6
+
7
+ /** Remote Marketplace distribution modes. */
8
+ export const DISTRIBUTIONS = ['public', 'private'] as const;
9
+
10
+ /** Marketplace catalog entries. */
11
+ export const extensions = pgTable('extensions', {
12
+ /** Stable manifest id. */
13
+ id: text('id').primaryKey(),
14
+ publisherId: text('publisher_id')
15
+ .notNull()
16
+ .references(() => publishers.id),
17
+ kind: text('kind', { enum: EXTENSION_KINDS }).notNull().default('tool'),
18
+ name: text('name').notNull(),
19
+ description: text('description').notNull(),
20
+ category: text('category').notNull(),
21
+ packageName: text('package_name').notNull(),
22
+ /** Tools run in a sandbox unless explicitly opted out. */
23
+ requiresSandbox: boolean('requires_sandbox').notNull().default(true),
24
+ distribution: text('distribution', { enum: DISTRIBUTIONS }).notNull().default('public'),
25
+ repositoryUrl: text('repository_url'),
26
+ license: text('license'),
27
+ deprecatedAt: timestamp('deprecated_at', { withTimezone: true }),
28
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
29
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
30
+ });
31
+
32
+ /** Private extension access grants. */
33
+ export const extensionWorkspaceGrants = pgTable('extension_workspace_grants', {
34
+ id: text('id').primaryKey(),
35
+ extensionId: text('extension_id')
36
+ .notNull()
37
+ .references(() => extensions.id),
38
+ workspaceId: text('workspace_id').notNull(),
39
+ grantedAt: timestamp('granted_at', { withTimezone: true }).notNull().defaultNow(),
40
+ });
41
+
42
+ /** Scope a private-tool access key is bound to. */
43
+ export const ACCESS_KEY_SCOPES = ['workspace', 'organization', 'user'] as const;
44
+
45
+ /**
46
+ * Issued entitlement keys for private extensions. A key is never installed
47
+ * against directly — redeeming it (see `redeemAccessKey`) creates/refreshes a
48
+ * row in `extensionWorkspaceGrants`, which is what visibility and install
49
+ * checks actually read. The key itself only controls whether a new grant may
50
+ * be minted: it can expire, be revoked, and cap how many times it redeems.
51
+ */
52
+ export const extensionAccessKeys = pgTable(
53
+ 'extension_access_keys',
54
+ {
55
+ id: text('id').primaryKey(),
56
+ extensionId: text('extension_id')
57
+ .notNull()
58
+ .references(() => extensions.id),
59
+ keyHash: text('key_hash').notNull().unique(),
60
+ /** First chars of the plaintext key, for admin display/audit only. */
61
+ keyPrefix: text('key_prefix').notNull(),
62
+ scope: text('scope', { enum: ACCESS_KEY_SCOPES }).notNull(),
63
+ /** Organization/user id this key is bound to. Null = redeemable by any workspace that presents it. */
64
+ scopeId: text('scope_id'),
65
+ maxInstalls: integer('max_installs'),
66
+ installCount: integer('install_count').notNull().default(0),
67
+ expiresAt: timestamp('expires_at', { withTimezone: true }),
68
+ revokedAt: timestamp('revoked_at', { withTimezone: true }),
69
+ createdBy: text('created_by').notNull(),
70
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
71
+ },
72
+ (table) => [index('extension_access_keys_extension_id_idx').on(table.extensionId)],
73
+ );
@@ -0,0 +1,5 @@
1
+ export * from './publishers.js';
2
+ export * from './extensions.js';
3
+ export * from './versions.js';
4
+ export * from './installations.js';
5
+ export * from './audit.js';
@@ -0,0 +1,23 @@
1
+ import { index, pgTable, text, timestamp, unique } from 'drizzle-orm/pg-core';
2
+ import { extensions } from './extensions.js';
3
+
4
+ /** Per-workspace extension installations. */
5
+ export const workspaceInstallations = pgTable(
6
+ 'workspace_installations',
7
+ {
8
+ id: text('id').primaryKey(),
9
+ extensionId: text('extension_id')
10
+ .notNull()
11
+ .references(() => extensions.id),
12
+ workspaceId: text('workspace_id').notNull(),
13
+ installedAt: timestamp('installed_at', { withTimezone: true }).notNull().defaultNow(),
14
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
15
+ },
16
+ (table) => [
17
+ unique('workspace_installations_extension_workspace_unique').on(
18
+ table.extensionId,
19
+ table.workspaceId,
20
+ ),
21
+ index('workspace_installations_extension_id_idx').on(table.extensionId),
22
+ ],
23
+ );
@@ -0,0 +1,13 @@
1
+ import { pgTable, text, timestamp } from 'drizzle-orm/pg-core';
2
+
3
+ /** Marketplace publisher identities. */
4
+ export const publishers = pgTable('publishers', {
5
+ id: text('id').primaryKey(),
6
+ name: text('name').notNull(),
7
+ contactEmail: text('contact_email'),
8
+ verification: text('verification', { enum: ['unverified', 'verified'] })
9
+ .notNull()
10
+ .default('unverified'),
11
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
12
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
13
+ });