mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
feat: per-group webhook ingress, custom webhooks, GitHub App tenant isolation
Add POST /webhook/{groupId} with per-group secrets (KV tenant:{groupId}), a custom provider (X-WebHooker-Signature HMAC, arbitrary JSON -> custom events through the route pipeline), and GitHub App installation isolation (Group.installationId) with automatic provisioning on installation.created (inst-{id} groups or binding matching owners groups). Includes WebhookPanel admin UI, custom route template, docs and 157 passing tests.
This commit is contained in:
34 files changed
+1711
-183
No files matched your search
@@ -16,6 +16,7 @@ import {
|
||||
import { getSendLog, getSendLogById } from "../lib/send-log";
|
||||
import { getAuditLog, recordAudit } from "../lib/audit";
|
||||
import { createInvite, listInvites, revokeInvite, getInvite, acceptInvite } from "./invites";
|
||||
import { getTenantSecret, setTenantSecret, deleteTenantSecret } from "./tenants";
|
||||
import { log } from "../lib/log";
|
||||
|
||||
const VALID_FILTER_TYPES = new Set(["event", "repo", "actor", "action", "branch", "keyword"]);
|
||||
@@ -277,6 +278,13 @@ export function validateGroups(
|
||||
error: `group "${g.id}".providers must be a list of "github" | "gitea" | "gitlab"`,
|
||||
};
|
||||
}
|
||||
if (g.installationId !== undefined && g.installationId !== null) {
|
||||
if (typeof g.installationId !== "number" || !Number.isInteger(g.installationId)) {
|
||||
return { ok: false, error: `group "${g.id}".installationId must be an integer` };
|
||||
}
|
||||
} else {
|
||||
delete g.installationId;
|
||||
}
|
||||
if (g.emoji !== undefined && typeof g.emoji !== "boolean") {
|
||||
return { ok: false, error: `group "${g.id}".emoji must be a boolean` };
|
||||
}
|
||||
@@ -463,6 +471,7 @@ export function createAdminRoutes(): Hono<AuthEnv> {
|
||||
if (prev.lang !== g.lang) fields.push("lang");
|
||||
if (!deepEqual(prev.logTarget, g.logTarget)) fields.push("logTarget");
|
||||
if (!deepEqual(prev.providers ?? [], g.providers ?? [])) fields.push("providers");
|
||||
if (prev.installationId !== g.installationId) fields.push("installationId");
|
||||
if (!deepEqual(prev.owners ?? [], g.owners ?? [])) fields.push("owners");
|
||||
if (!deepEqual(prev.members ?? normalizeGroupMembers(prev), g.members))
|
||||
fields.push("members");
|
||||
@@ -490,6 +499,7 @@ export function createAdminRoutes(): Hono<AuthEnv> {
|
||||
groupId: g.id,
|
||||
ip: clientIp(c),
|
||||
});
|
||||
await deleteTenantSecret(c.env.KV, g.id).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -746,6 +756,76 @@ export function createAdminRoutes(): Hono<AuthEnv> {
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
// ---- Group webhook ingress (owner +) ----
|
||||
app.get("/api/groups/:groupId/webhook", requireAnyAccess(), async (c) => {
|
||||
const groupId = param(c, "groupId");
|
||||
const access = requireGroupRole(c, groupId, "owner");
|
||||
if (!access.ok) {
|
||||
return c.json(
|
||||
{ error: access.status === 404 ? "Group not found" : "Forbidden" },
|
||||
access.status,
|
||||
);
|
||||
}
|
||||
const origin = c.env.BASE_URL ?? new URL(c.req.url).origin;
|
||||
return c.json({
|
||||
url: `${origin.replace(/\/$/, "")}/webhook/${groupId}`,
|
||||
hasSecret: (await getTenantSecret(c.env.KV, groupId)) != null,
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/api/groups/:groupId/webhook/regenerate", requireAnyAccess(), async (c) => {
|
||||
const groupId = param(c, "groupId");
|
||||
const access = requireGroupRole(c, groupId, "owner");
|
||||
if (!access.ok) {
|
||||
return c.json(
|
||||
{ error: access.status === 404 ? "Group not found" : "Forbidden" },
|
||||
access.status,
|
||||
);
|
||||
}
|
||||
const secret = await setTenantSecret(c.env.KV, groupId);
|
||||
const auth = currentAuth(c);
|
||||
await recordAudit(c.env.DB, {
|
||||
ts: Date.now(),
|
||||
actorId: auth.session.userId,
|
||||
actorLogin: auth.session.login,
|
||||
action: "webhook.secret.regenerate",
|
||||
targetType: "group",
|
||||
targetId: groupId,
|
||||
groupId,
|
||||
ip: clientIp(c),
|
||||
});
|
||||
const origin = c.env.BASE_URL ?? new URL(c.req.url).origin;
|
||||
return c.json({
|
||||
ok: true,
|
||||
url: `${origin.replace(/\/$/, "")}/webhook/${groupId}`,
|
||||
secret,
|
||||
});
|
||||
});
|
||||
|
||||
app.delete("/api/groups/:groupId/webhook", requireAnyAccess(), async (c) => {
|
||||
const groupId = param(c, "groupId");
|
||||
const access = requireGroupRole(c, groupId, "owner");
|
||||
if (!access.ok) {
|
||||
return c.json(
|
||||
{ error: access.status === 404 ? "Group not found" : "Forbidden" },
|
||||
access.status,
|
||||
);
|
||||
}
|
||||
await deleteTenantSecret(c.env.KV, groupId);
|
||||
const auth = currentAuth(c);
|
||||
await recordAudit(c.env.DB, {
|
||||
ts: Date.now(),
|
||||
actorId: auth.session.userId,
|
||||
actorLogin: auth.session.login,
|
||||
action: "webhook.secret.delete",
|
||||
targetType: "group",
|
||||
targetId: groupId,
|
||||
groupId,
|
||||
ip: clientIp(c),
|
||||
});
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
// ---- Audit log (any access; group admins see only their groups) ----
|
||||
app.get("/api/audit", requireAnyAccess(), async (c) => {
|
||||
const auth = currentAuth(c);
|
||||
|
||||
@@ -96,6 +96,62 @@ export function groupAcceptsProvider(group: Group, provider?: string): boolean {
|
||||
return allowed.includes(provider ?? "github");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an event from a GitHub App `installationId` is allowed into this
|
||||
* group. A group bound to an installation only accepts events from that
|
||||
* installation (hard tenant isolation). Unbound groups accept everything here
|
||||
* (their access is governed by `owners`/`providers` instead).
|
||||
*/
|
||||
export function groupAcceptsInstallation(group: Group, installationId?: number): boolean {
|
||||
if (group.installationId == null) return true;
|
||||
return installationId != null && group.installationId === installationId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-provision a GitHub App installation on `installation.created`:
|
||||
* 1. No-op when a group is already bound to this installation id.
|
||||
* 2. Otherwise bind every unbound group whose `owners` match the installing
|
||||
* account login (so existing org groups light up automatically).
|
||||
* 3. Otherwise create a dedicated `inst-{installationId}` group bound to the
|
||||
* installation. Returns the group that now owns the installation.
|
||||
*/
|
||||
export async function ensureInstallationGroup(
|
||||
kv: KVNamespace,
|
||||
installationId: number,
|
||||
accountLogin: string,
|
||||
): Promise<Group | null> {
|
||||
const groups = await loadGroups(kv);
|
||||
const existing = groups.find((g) => g.installationId === installationId);
|
||||
if (existing) return existing;
|
||||
|
||||
const login = accountLogin.trim().toLowerCase();
|
||||
const candidates = groups.filter(
|
||||
(g) =>
|
||||
g.installationId == null &&
|
||||
login.length > 0 &&
|
||||
(g.owners ?? []).some((o) => o.trim().toLowerCase() === login),
|
||||
);
|
||||
if (candidates.length > 0) {
|
||||
const next = groups.map((g) => (candidates.includes(g) ? { ...g, installationId } : g));
|
||||
await saveGroups(kv, next);
|
||||
return next.find((g) => g.id === candidates[0]!.id) ?? null;
|
||||
}
|
||||
|
||||
const gid = `inst-${installationId}`;
|
||||
const dedicated = groups.find((g) => g.id === gid);
|
||||
const group: Group = {
|
||||
id: gid,
|
||||
name: accountLogin.trim() || `Installation ${installationId}`,
|
||||
adminIds: [],
|
||||
installationId,
|
||||
};
|
||||
await saveGroups(
|
||||
kv,
|
||||
dedicated ? groups.map((g) => (g.id === gid ? { ...g, ...group } : g)) : [...groups, group],
|
||||
);
|
||||
return group;
|
||||
}
|
||||
|
||||
export interface AccessScope {
|
||||
isSuper: boolean;
|
||||
/** Groups the user may view. When isSuper, this is every group. */
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { log } from "../lib/log";
|
||||
|
||||
/**
|
||||
* Per-group webhook tenant secrets. A group can opt into its own webhook
|
||||
* ingress (`POST /webhook/{groupId}`) with an independent secret, so SaaS
|
||||
* users can configure their own GitHub/Gitea/custom webhooks without sharing
|
||||
* (or even knowing) the operator's global secrets.
|
||||
*/
|
||||
const TENANT_KEY = (groupId: string): string => `tenant:${groupId}`;
|
||||
|
||||
/** 32 random bytes → 64 hex chars. */
|
||||
export function generateTenantSecret(): string {
|
||||
const bytes = new Uint8Array(32);
|
||||
crypto.getRandomValues(bytes);
|
||||
return Array.from(bytes)
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
export async function getTenantSecret(kv: KVNamespace, groupId: string): Promise<string | null> {
|
||||
try {
|
||||
return await kv.get(TENANT_KEY(groupId), "text");
|
||||
} catch (err) {
|
||||
log.warn({ err, groupId }, "Failed to read tenant webhook secret");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Generate (or regenerate) the group's webhook secret. */
|
||||
export async function setTenantSecret(kv: KVNamespace, groupId: string): Promise<string> {
|
||||
const secret = generateTenantSecret();
|
||||
await kv.put(TENANT_KEY(groupId), secret);
|
||||
return secret;
|
||||
}
|
||||
|
||||
export async function deleteTenantSecret(kv: KVNamespace, groupId: string): Promise<void> {
|
||||
await kv.delete(TENANT_KEY(groupId));
|
||||
}
|
||||
Reference in new issue
Block a user