refactor: modularize into core/events/formatters/drivers

This commit is contained in:
RhenCloud 2026-08-03 03:36:36 +08:00
parent 7b341ff9f4
commit 0af6b9a4b8
No known key found for this signature in database
GPG key ID: A574A617378C4E0B
62 changed files with 2430 additions and 2015 deletions

69
src/web/groups.ts Normal file
View file

@ -0,0 +1,69 @@
import type { Env, Group } from "../types";
import { isAdminUser } from "./session";
import { log } from "../lib/log";
const GROUPS_KEY = "config:groups";
export async function loadGroups(kv: KVNamespace): Promise<Group[]> {
try {
const stored = await kv.get<Group[]>(GROUPS_KEY, "json");
if (Array.isArray(stored)) return stored;
} catch (err) {
log.warn({ err }, "Failed to load groups from KV");
}
return [];
}
export async function saveGroups(kv: KVNamespace, groups: Group[]): Promise<void> {
await kv.put(GROUPS_KEY, JSON.stringify(groups));
}
/** Case-insensitive match of a GitHub userId or login against a list of ids/logins. */
export function identityMatches(ids: string[], userId: string, login: string): boolean {
const wanted = ids.map((s) => s.trim()).filter(Boolean);
if (wanted.length === 0) return false;
return wanted.some((id) => id === userId || id.toLowerCase() === login.toLowerCase());
}
export function isGroupAdmin(group: Group, userId: string, login: string): boolean {
return identityMatches(group.adminIds ?? [], userId, login);
}
/**
* Whether an event originating from `owners` (org/user logins) is allowed into
* this group. A group with no owner restriction accepts everything.
*/
export function groupAcceptsOwners(group: Group, owners: string[]): boolean {
const restrict = (group.owners ?? []).map((s) => s.trim().toLowerCase()).filter(Boolean);
if (restrict.length === 0) return true;
const seen = owners.map((s) => s.trim().toLowerCase()).filter(Boolean);
return seen.some((o) => restrict.includes(o));
}
export interface AccessScope {
isSuper: boolean;
/** Groups the user may view/edit. When isSuper, this is every group. */
groups: Group[];
/** Ids of accessible groups, for quick membership checks. */
groupIds: Set<string>;
}
export function resolveScope(
env: Env,
groups: Group[],
userId: string,
login: string,
): AccessScope {
const isSuper = isAdminUser(env, userId, login);
const visible = isSuper ? groups : groups.filter((g) => isGroupAdmin(g, userId, login));
return {
isSuper,
groups: visible,
groupIds: new Set(visible.map((g) => g.id)),
};
}
/** True if the user is a super admin or manages at least one group. */
export function hasAnyAccess(scope: AccessScope): boolean {
return scope.isSuper || scope.groups.length > 0;
}