CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 | /**
* Block H — App marketplace + bot identities.
*
* Known permission names. These are the vocabulary that apps declare and
* installers grant. Permissions are string-matched at request time — for v1,
* handlers that consume app tokens call `hasPermission(token, "issues:write")`
* and fail closed when absent.
*
* Higher-level permissions imply lower ones (write implies read) so the UI
* only presents one level at a time.
*/
import { createHash, randomBytes } from "node:crypto";
import { and, desc, eq, ilike, isNull, or, sql } from "drizzle-orm";
import { db } from "../db";
import {
apps,
appBots,
appInstallations,
appInstallTokens,
appEvents,
users,
type App,
type AppInstallation,
} from "../db/schema";
export const KNOWN_PERMISSIONS = [
"contents:read",
"contents:write",
"issues:read",
"issues:write",
"pulls:read",
"pulls:write",
"checks:read",
"checks:write",
"deployments:read",
"deployments:write",
"metadata:read",
] as const;
export type Permission = (typeof KNOWN_PERMISSIONS)[number];
export const KNOWN_EVENTS = [
"push",
"issues",
"issue_comment",
"pull_request",
"pull_request_review",
"check_run",
"deployment",
"release",
] as const;
export type EventName = (typeof KNOWN_EVENTS)[number];
// ---------- Pure helpers ----------
/**
* Slugify an app name — lowercase alphanumeric + dashes, trim leading/trailing
* dashes, cap at 40 chars.
*/
export function slugify(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 40);
}
/** Bot usernames are always `<slug>[bot]`. */
export function botUsername(slug: string): string {
return `${slug}[bot]`;
}
/** Is `granted` a subset of `requested`? Used when validating install forms. */
export function permissionsSubset(
granted: readonly string[],
requested: readonly string[]
): boolean {
const req = new Set(requested);
return granted.every((g) => req.has(g));
}
/** Normalise + de-dup permissions. Drops unknown values. */
export function normalisePermissions(input: readonly string[]): Permission[] {
const seen = new Set<string>();
const out: Permission[] = [];
for (const p of input) {
if ((KNOWN_PERMISSIONS as readonly string[]).includes(p) && !seen.has(p)) {
seen.add(p);
out.push(p as Permission);
}
}
return out;
}
/** Parse a JSON permission list out of the DB column. */
export function parsePermissions(raw: string | null | undefined): Permission[] {
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return normalisePermissions(parsed);
} catch {
return [];
}
}
/** write:* implies read:* on the same resource family. */
export function hasPermission(
granted: readonly string[],
required: string
): boolean {
if (granted.includes(required)) return true;
// write implies read
if (required.endsWith(":read")) {
const writeEquivalent = required.replace(":read", ":write");
return granted.includes(writeEquivalent);
}
return false;
}
export function generateBearerToken(): { token: string; hash: string } {
const token = "ghi_" + randomBytes(24).toString("hex");
const hash = createHash("sha256").update(token).digest("hex");
return { token, hash };
}
export function hashBearer(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
// ---------- DB helpers ----------
export async function listPublicApps(query = ""): Promise<App[]> {
try {
const rows = await db
.select()
.from(apps)
.where(
query
? and(
eq(apps.isPublic, true),
or(
ilike(apps.name, `%${query}%`),
ilike(apps.description, `%${query}%`),
ilike(apps.slug, `%${query}%`)
)!
)
: eq(apps.isPublic, true)
)
.orderBy(desc(apps.createdAt))
.limit(100);
return rows;
} catch {
return [];
}
}
export async function getAppBySlug(slug: string): Promise<App | null> {
try {
const [r] = await db
.select()
.from(apps)
.where(eq(apps.slug, slug))
.limit(1);
return r || null;
} catch {
return null;
}
}
export interface CreateAppArgs {
name: string;
description?: string;
iconUrl?: string;
homepageUrl?: string;
webhookUrl?: string;
creatorId: string;
permissions: readonly string[];
defaultEvents?: readonly string[];
isPublic?: boolean;
}
/** Create an app + matching bot. Slug is derived from name; retries on collision. */
export async function createApp(args: CreateAppArgs): Promise<App | null> {
const baseSlug = slugify(args.name) || "app";
for (let attempt = 0; attempt < 6; attempt++) {
const slug = attempt === 0 ? baseSlug : `${baseSlug}-${randomBytes(2).toString("hex")}`;
const webhookSecret = randomBytes(24).toString("hex");
try {
const [row] = await db
.insert(apps)
.values({
slug,
name: args.name,
description: args.description || "",
iconUrl: args.iconUrl,
homepageUrl: args.homepageUrl,
webhookUrl: args.webhookUrl,
webhookSecret,
creatorId: args.creatorId,
permissions: JSON.stringify(normalisePermissions(args.permissions)),
defaultEvents: JSON.stringify(
(args.defaultEvents || []).filter((e) =>
(KNOWN_EVENTS as readonly string[]).includes(e)
)
),
isPublic: args.isPublic ?? true,
})
.returning();
if (!row) return null;
// Create matching bot account
await db.insert(appBots).values({
appId: row.id,
username: botUsername(slug),
displayName: `${args.name} (bot)`,
avatarUrl: args.iconUrl,
});
return row;
} catch (err: any) {
if (String(err?.message || "").includes("duplicate")) continue;
console.error("[marketplace] createApp:", err);
return null;
}
}
return null;
}
export async function listInstallationsForApp(
appId: string
): Promise<AppInstallation[]> {
try {
return await db
.select()
.from(appInstallations)
.where(
and(eq(appInstallations.appId, appId), isNull(appInstallations.uninstalledAt))
)
.orderBy(desc(appInstallations.createdAt));
} catch {
return [];
}
}
export async function listInstallationsForTarget(
targetType: "user" | "org" | "repository",
targetId: string
): Promise<Array<AppInstallation & { app: App | null }>> {
try {
const rows = await db
.select({
install: appInstallations,
app: apps,
})
.from(appInstallations)
.leftJoin(apps, eq(appInstallations.appId, apps.id))
.where(
and(
eq(appInstallations.targetType, targetType),
eq(appInstallations.targetId, targetId),
isNull(appInstallations.uninstalledAt)
)
)
.orderBy(desc(appInstallations.createdAt));
return rows.map((r) => ({ ...r.install, app: r.app }));
} catch {
return [];
}
}
export interface InstallArgs {
appId: string;
installedBy: string;
targetType: "user" | "org" | "repository";
targetId: string;
grantedPermissions: readonly string[];
}
export async function installApp(
args: InstallArgs
): Promise<AppInstallation | null> {
try {
// Find the app to validate permissions
const [app] = await db
.select()
.from(apps)
.where(eq(apps.id, args.appId))
.limit(1);
if (!app) return null;
const appPerms = parsePermissions(app.permissions);
const granted = normalisePermissions(args.grantedPermissions);
// Only allow granting what the app actually requests
const filtered = granted.filter((p) => appPerms.includes(p));
// If a non-uninstalled row exists, soft-update it (idempotent)
const [existing] = await db
.select()
.from(appInstallations)
.where(
and(
eq(appInstallations.appId, args.appId),
eq(appInstallations.targetType, args.targetType),
eq(appInstallations.targetId, args.targetId),
isNull(appInstallations.uninstalledAt)
)
)
.limit(1);
if (existing) {
await db
.update(appInstallations)
.set({ grantedPermissions: JSON.stringify(filtered) })
.where(eq(appInstallations.id, existing.id));
await db.insert(appEvents).values({
appId: args.appId,
installationId: existing.id,
kind: "installed",
payload: JSON.stringify({ updated: true }),
});
return existing;
}
const [row] = await db
.insert(appInstallations)
.values({
appId: args.appId,
installedBy: args.installedBy,
targetType: args.targetType,
targetId: args.targetId,
grantedPermissions: JSON.stringify(filtered),
})
.returning();
if (row) {
await db.insert(appEvents).values({
appId: args.appId,
installationId: row.id,
kind: "installed",
payload: JSON.stringify({
targetType: args.targetType,
targetId: args.targetId,
}),
});
}
return row || null;
} catch (err) {
console.error("[marketplace] installApp:", err);
return null;
}
}
export async function uninstallApp(installationId: string): Promise<boolean> {
try {
const [row] = await db
.update(appInstallations)
.set({ uninstalledAt: new Date() })
.where(
and(
eq(appInstallations.id, installationId),
isNull(appInstallations.uninstalledAt)
)
)
.returning();
if (row) {
await db.insert(appEvents).values({
appId: row.appId,
installationId: row.id,
kind: "uninstalled",
});
// Revoke all tokens
await db
.update(appInstallTokens)
.set({ revokedAt: new Date() })
.where(
and(
eq(appInstallTokens.installationId, installationId),
isNull(appInstallTokens.revokedAt)
)
);
return true;
}
return false;
} catch (err) {
console.error("[marketplace] uninstallApp:", err);
return false;
}
}
/** Issue a bearer token scoped to a single installation. Default TTL: 1h. */
export async function issueInstallToken(
installationId: string,
ttlSeconds = 3600
): Promise<{ token: string; expiresAt: Date } | null> {
try {
const { token, hash } = generateBearerToken();
const expiresAt = new Date(Date.now() + ttlSeconds * 1000);
await db
.insert(appInstallTokens)
.values({ installationId, tokenHash: hash, expiresAt });
return { token, expiresAt };
} catch (err) {
console.error("[marketplace] issueInstallToken:", err);
return null;
}
}
/**
* Verify a bearer and return the matched installation + permissions. Returns
* null when the token is unknown, revoked, or expired.
*/
export async function verifyInstallToken(
token: string
): Promise<{
installation: AppInstallation;
app: App;
botUsername: string;
permissions: Permission[];
} | null> {
if (!token || !token.startsWith("ghi_")) return null;
const hash = hashBearer(token);
try {
const [row] = await db
.select({
inst: appInstallations,
app: apps,
tok: appInstallTokens,
})
.from(appInstallTokens)
.innerJoin(
appInstallations,
eq(appInstallTokens.installationId, appInstallations.id)
)
.innerJoin(apps, eq(appInstallations.appId, apps.id))
.where(eq(appInstallTokens.tokenHash, hash))
.limit(1);
if (!row) return null;
if (row.tok.revokedAt) return null;
if (row.tok.expiresAt < new Date()) return null;
if (row.inst.uninstalledAt) return null;
if (row.inst.suspendedAt) return null;
const perms = parsePermissions(row.inst.grantedPermissions);
const slug = row.app.slug;
return {
installation: row.inst,
app: row.app,
botUsername: botUsername(slug),
permissions: perms,
};
} catch {
return null;
}
}
/** Admin-ish listing of an app's recent event log. */
export async function listEventsForApp(
appId: string,
limit = 50
): Promise<Array<typeof appEvents.$inferSelect>> {
try {
return await db
.select()
.from(appEvents)
.where(eq(appEvents.appId, appId))
.orderBy(desc(appEvents.createdAt))
.limit(limit);
} catch {
return [];
}
}
/** Count live installs — for app detail page. */
export async function countInstalls(appId: string): Promise<number> {
try {
const [r] = await db
.select({ n: sql<number>`count(*)::int` })
.from(appInstallations)
.where(
and(
eq(appInstallations.appId, appId),
isNull(appInstallations.uninstalledAt)
)
);
return Number(r?.n || 0);
} catch {
return 0;
}
}
|