mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
fix(group): preserve identity through lifecycle
Group names are mutable and reusable, so they cannot own durable state. Preserve immutable identities across lifecycle operations and commit invite use with membership under transaction-time guards.
This commit is contained in:
1 parent
c853f2910f
commit
81af2053c0
6 files changed
+985
-179
No files matched your search
+7
-2
@@ -105,11 +105,16 @@ export type GroupRole = "owner" | "admin" | "viewer";
|
||||
|
||||
export interface GroupMember {
|
||||
/**
|
||||
* GitHub login (case-insensitive). Ids are matched when stored, logins
|
||||
* otherwise; identityMatches handles both.
|
||||
* GitHub login (case-insensitive). An unbound all-digit entry (legacy
|
||||
* `adminIds`) is read as a user id; see `memberMatches`.
|
||||
*/
|
||||
login: string;
|
||||
role: GroupRole;
|
||||
/**
|
||||
* Immutable GitHub user id of the member, bound by the server (invite
|
||||
* acceptance, the member's sign-in). Once bound, only that account matches.
|
||||
*/
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
export interface Group {
|
||||
|
||||
@@ -533,7 +533,7 @@ export async function adminInvite(event: H3Event): Promise<void> {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const result = await acceptInvite(env.KV, token, session.userId, session.login);
|
||||
const result = await acceptInvite(env, token, session.userId, session.login);
|
||||
if (result.ok) {
|
||||
await recordAudit(env.DB, {
|
||||
ts: Date.now(),
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import type { Env } from "../types";
|
||||
import { retiredGroupKey, type LifecycleStatements } from "../storage/config-store";
|
||||
import { idempotencyStore, instanceScope } from "../lib/idempotency";
|
||||
import { canUseD1 } from "../storage/d1";
|
||||
import { log } from "../lib/log";
|
||||
|
||||
/**
|
||||
* A deleted or renamed group id stays retired this long: queued deliveries
|
||||
* still addressed to it (queue retries span minutes, the DLQ up to days) can
|
||||
* then never reach an unrelated group that took over the id.
|
||||
*/
|
||||
const RETIRED_TTL_SECONDS = 4 * 86400;
|
||||
const ALIAS_TTL_SECONDS = 4 * 86400;
|
||||
|
||||
const retiredKey = retiredGroupKey;
|
||||
|
||||
function aliasKey(id: string): string {
|
||||
return `group:renamed:${id}`;
|
||||
}
|
||||
|
||||
/** D1 alias row: `group-alias:{from} {to}` (ids never contain spaces). */
|
||||
function aliasRowPrefix(from: string): string {
|
||||
return `group-alias:${from} `;
|
||||
}
|
||||
|
||||
/**
|
||||
* The first key past every key starting with `prefix` (its last character
|
||||
* incremented): `key >= prefix AND key < end` is a primary-key range, where
|
||||
* `substr(key, …) = prefix` scans the whole table.
|
||||
*/
|
||||
function prefixEnd(prefix: string): string {
|
||||
return prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1);
|
||||
}
|
||||
|
||||
function retireStatement(db: D1Database, id: string): D1PreparedStatement {
|
||||
const now = Date.now();
|
||||
return db
|
||||
.prepare(
|
||||
`INSERT INTO dedup_keys (key, claimed_at, expires_at) VALUES (?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET claimed_at = excluded.claimed_at, expires_at = excluded.expires_at`,
|
||||
)
|
||||
.bind(retiredKey(id), now, now + RETIRED_TTL_SECONDS * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Statements committed with a group's deletion: its send logs and audit
|
||||
* entries stay for super admins but no longer belong to any group (a later
|
||||
* group with the same id must not inherit them), its message tracking is
|
||||
* dropped, and the id is retired.
|
||||
*/
|
||||
export function deleteLifecycle(
|
||||
id: string,
|
||||
instance?: string,
|
||||
legacyId?: string,
|
||||
): LifecycleStatements {
|
||||
// The group's own chains only: under its instance, and — from before
|
||||
// instances — under the id it had back then. Rows under its current id may
|
||||
// belong to the group that had that id before instances.
|
||||
const prefixes = [
|
||||
...(instance ? [`${instanceScope(instance)}:`] : []),
|
||||
...(legacyId ? [`${legacyId}:`] : []),
|
||||
];
|
||||
return (db) => [
|
||||
db.prepare("UPDATE send_logs SET group_id = NULL WHERE group_id = ?").bind(id),
|
||||
db.prepare("UPDATE audit_logs SET group_id = NULL WHERE group_id = ?").bind(id),
|
||||
...prefixes.map((prefix) =>
|
||||
db
|
||||
.prepare("DELETE FROM message_tracking WHERE event_id >= ? AND event_id < ?")
|
||||
.bind(prefix, prefixEnd(prefix)),
|
||||
),
|
||||
retireStatement(db, id),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Statements committed with a group's rename: its history moves to the new id
|
||||
* (visible to the group, to nobody else), and the old id is retired. Message
|
||||
* tracking stays put: chains are keyed by the group's instance, and those from
|
||||
* before instances by its `legacyId` — neither changes with a rename.
|
||||
*/
|
||||
export function renameLifecycle(from: string, to: string): LifecycleStatements {
|
||||
return (db) => [
|
||||
db.prepare("UPDATE send_logs SET group_id = ? WHERE group_id = ?").bind(to, from),
|
||||
db.prepare("UPDATE audit_logs SET group_id = ? WHERE group_id = ?").bind(to, from),
|
||||
retireStatement(db, from),
|
||||
// Committed with the rename itself: queued deliveries for the old id can
|
||||
// always find the new one.
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO dedup_keys (key, claimed_at, expires_at) VALUES (?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET claimed_at = excluded.claimed_at, expires_at = excluded.expires_at`,
|
||||
)
|
||||
.bind(`${aliasRowPrefix(from)}${to}`, Date.now(), Date.now() + ALIAS_TTL_SECONDS * 1000),
|
||||
];
|
||||
}
|
||||
|
||||
/** Mark a group id as recently used (KV-only deployments; D1 does it in the transaction). */
|
||||
export async function retireGroupId(env: Env, id: string): Promise<void> {
|
||||
if (canUseD1(env.DB)) return;
|
||||
try {
|
||||
await idempotencyStore(env.DB, env.KV).claim(retiredKey(id), RETIRED_TTL_SECONDS);
|
||||
} catch (err) {
|
||||
log.warn({ err, id }, "Failed to retire group id");
|
||||
}
|
||||
}
|
||||
|
||||
export async function isGroupIdRetired(env: Env, id: string): Promise<boolean> {
|
||||
return idempotencyStore(env.DB, env.KV).has(retiredKey(id));
|
||||
}
|
||||
|
||||
/** Remember where a renamed group went (KV-only deployments; D1 records it in the rename). */
|
||||
export async function recordGroupRename(env: Env, from: string, to: string): Promise<void> {
|
||||
if (canUseD1(env.DB)) return;
|
||||
await env.KV.put(aliasKey(from), to, { expirationTtl: ALIAS_TTL_SECONDS });
|
||||
}
|
||||
|
||||
async function nextAlias(env: Env, id: string): Promise<string | null> {
|
||||
if (canUseD1(env.DB)) {
|
||||
const prefix = aliasRowPrefix(id);
|
||||
const row = await env.DB.prepare(
|
||||
`SELECT key FROM dedup_keys WHERE key >= ? AND key < ? AND expires_at > ?
|
||||
ORDER BY claimed_at DESC LIMIT 1`,
|
||||
)
|
||||
.bind(prefix, prefixEnd(prefix), Date.now())
|
||||
.first<{ key: string }>();
|
||||
return row ? row.key.slice(prefix.length) : null;
|
||||
}
|
||||
return env.KV.get(aliasKey(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* The current id of a group that may have been renamed (follows chains).
|
||||
* Read errors propagate: an unknown alias must not pass for "no alias".
|
||||
*/
|
||||
export async function resolveGroupAlias(env: Env, id: string): Promise<string> {
|
||||
return (await groupAliasChain(env, id)).at(-1)!;
|
||||
}
|
||||
|
||||
/** Every id a group had from `id` on, oldest first (`id` itself included). */
|
||||
export async function groupAliasChain(env: Env, id: string): Promise<string[]> {
|
||||
const chain = [id];
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const next = await nextAlias(env, chain.at(-1)!);
|
||||
if (!next || chain.includes(next)) break;
|
||||
chain.push(next);
|
||||
}
|
||||
return chain;
|
||||
}
|
||||
+261
-89
@@ -1,12 +1,15 @@
|
||||
import type { Env, Group, GroupMember, GroupRole } from "../types";
|
||||
import { isAdminUser } from "./session";
|
||||
import { log } from "../lib/log";
|
||||
import { migrateGroups, validateGroups } from "../config/schema";
|
||||
import { identityEntryMatches, isAdminUser } from "./session";
|
||||
import { getConfigStore } from "../config";
|
||||
|
||||
const GROUPS_KEY = "config:groups";
|
||||
const GROUPS_CACHE_TTL = 300_000;
|
||||
let groupsCache: { groups: Group[]; expiresAt: number } | null = null;
|
||||
import { idempotencyStore, unrecordedGuard } from "../lib/idempotency";
|
||||
import { ConfigConflictError } from "../storage/config-store";
|
||||
import { canUseD1 } from "../storage/d1";
|
||||
import type {
|
||||
GroupMutation,
|
||||
GuardedWrite,
|
||||
LifecycleStatements,
|
||||
LoadOptions,
|
||||
} from "../storage/config-store";
|
||||
|
||||
/**
|
||||
* Normalizes a group's member list. Groups stored with the legacy `adminIds`
|
||||
@@ -24,7 +27,8 @@ export function normalizeGroupMembers(group: Group): GroupMember[] {
|
||||
if (!login || seen.has(login.toLowerCase())) continue;
|
||||
const role: GroupRole = m?.role === "admin" || m?.role === "viewer" ? m.role : "owner";
|
||||
seen.add(login.toLowerCase());
|
||||
out.push({ login, role });
|
||||
const userId = typeof m?.userId === "string" && /^\d+$/.test(m.userId) ? m.userId : "";
|
||||
out.push(userId ? { login, role, userId } : { login, role });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -40,44 +44,155 @@ export function normalizeGroupMembers(group: Group): GroupMember[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function loadGroups(kv: KVNamespace): Promise<Group[]> {
|
||||
const store = getConfigStore(kv);
|
||||
if (store) return store.loadGroups();
|
||||
|
||||
if (groupsCache && Date.now() < groupsCache.expiresAt) {
|
||||
return groupsCache.groups;
|
||||
}
|
||||
try {
|
||||
const stored = await kv.get<Group[]>(GROUPS_KEY, "json");
|
||||
const groups = Array.isArray(stored) ? validateGroups(migrateGroups(stored)) : [];
|
||||
groupsCache = { groups, expiresAt: Date.now() + GROUPS_CACHE_TTL };
|
||||
return groups;
|
||||
} catch (err) {
|
||||
log.warn({ err }, "Failed to load groups from KV");
|
||||
}
|
||||
return [];
|
||||
export async function loadGroups(kv: KVNamespace, opts?: LoadOptions): Promise<Group[]> {
|
||||
return getConfigStore(kv).loadGroups(opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the full group set (super-admin bulk write): groups left out are
|
||||
* deleted with their routes and fragments, only changed groups are rewritten.
|
||||
*/
|
||||
export async function saveGroups(kv: KVNamespace, groups: Group[]): Promise<void> {
|
||||
const store = getConfigStore(kv);
|
||||
if (store) {
|
||||
await store.saveGroups(groups);
|
||||
groupsCache = null;
|
||||
return;
|
||||
}
|
||||
await kv.put(GROUPS_KEY, JSON.stringify(groups));
|
||||
groupsCache = null;
|
||||
await getConfigStore(kv).saveGroups(groups);
|
||||
}
|
||||
|
||||
export function invalidateGroupsCache(): void {
|
||||
groupsCache = null;
|
||||
/** Insert a group unless its id is taken; true when it was created. */
|
||||
export async function createGroup(kv: KVNamespace, group: Group): Promise<boolean> {
|
||||
return getConfigStore(kv).createGroup(group);
|
||||
}
|
||||
|
||||
/** Case-insensitive match of a GitHub userId or login against a list of ids/logins. */
|
||||
/**
|
||||
* Atomically read-modify-write one group. `mutate` gets the current stored
|
||||
* group and returns the replacement, or null to keep it unchanged.
|
||||
*/
|
||||
export async function updateGroup(
|
||||
kv: KVNamespace,
|
||||
id: string,
|
||||
mutate: GroupMutation,
|
||||
opts?: Pick<GuardedWrite<Group>, "guards" | "after">,
|
||||
): Promise<Group | null> {
|
||||
return getConfigStore(kv).updateGroup(id, mutate, opts);
|
||||
}
|
||||
|
||||
/** Delete one group with its routes and filter fragments. */
|
||||
export async function deleteGroup(
|
||||
kv: KVNamespace,
|
||||
id: string,
|
||||
opts?: GuardedWrite<Group> & { extra?: LifecycleStatements; version?: number },
|
||||
): Promise<void> {
|
||||
await getConfigStore(kv).deleteGroup(id, opts);
|
||||
}
|
||||
|
||||
/** Move a group (with its routes and fragments) to a new id atomically. */
|
||||
export async function renameGroup(
|
||||
kv: KVNamespace,
|
||||
from: string,
|
||||
to: string,
|
||||
opts?: GuardedWrite<Group> & { extra?: LifecycleStatements; transform?: (g: Group) => Group },
|
||||
): Promise<Group> {
|
||||
return getConfigStore(kv).renameGroup(from, to, opts);
|
||||
}
|
||||
|
||||
/** Kept for callers that reset state between tests; the store owns its caches. */
|
||||
export function invalidateGroupsCache(): void {}
|
||||
|
||||
/** Whether any entry names the user: all-digit entries are user ids, others 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());
|
||||
return ids.some((id) => identityEntryMatches(id, userId, login));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a member entry is this user. A member bound to a GitHub user id is
|
||||
* that account only — a login can be renamed and then claimed by someone
|
||||
* else, an id never changes. Unbound entries match like `identityMatches`.
|
||||
*/
|
||||
export function memberMatches(member: GroupMember, userId: string, login: string): boolean {
|
||||
if (member.userId) return member.userId === userId;
|
||||
return identityEntryMatches(member.login, userId, login);
|
||||
}
|
||||
|
||||
/**
|
||||
* A guard statement that aborts its transaction unless the user holds one of
|
||||
* `roles` in group `gid` as stored at that moment. Member entries match the
|
||||
* way `memberMatches` does: a bound entry by user id, an all-digit one by
|
||||
* user id, any other by `login` (pass "" to match by id only); groups still
|
||||
* on legacy `adminIds` count those as owners.
|
||||
*/
|
||||
export function memberRoleStatement(
|
||||
db: D1Database,
|
||||
gid: string,
|
||||
userId: string,
|
||||
login: string,
|
||||
roles: GroupRole[],
|
||||
): D1PreparedStatement {
|
||||
return db
|
||||
.prepare(
|
||||
`SELECT CASE WHEN EXISTS (
|
||||
SELECT 1 FROM (SELECT id, CASE WHEN json_valid(data) THEN data ELSE '{}' END AS data FROM d1_groups) g, json_each(g.data, '$.members') m
|
||||
WHERE g.id = ? AND json_extract(m.value, '$.role') IN (${roles.map(() => "?").join(", ")})
|
||||
AND (json_extract(m.value, '$.userId') = ?
|
||||
OR (json_extract(m.value, '$.userId') IS NULL AND (
|
||||
(json_extract(m.value, '$.login') NOT GLOB '*[^0-9]*'
|
||||
AND json_extract(m.value, '$.login') = ?)
|
||||
OR (json_extract(m.value, '$.login') GLOB '*[^0-9]*'
|
||||
AND lower(json_extract(m.value, '$.login')) = lower(?)))))
|
||||
) OR (? IN (${roles.map(() => "?").join(", ")}) AND EXISTS (
|
||||
SELECT 1 FROM (SELECT id, CASE WHEN json_valid(data) THEN data ELSE '{}' END AS data FROM d1_groups) g, json_each(g.data, '$.adminIds') a
|
||||
WHERE g.id = ? AND coalesce(json_array_length(g.data, '$.members'), 0) = 0
|
||||
AND ((a.value NOT GLOB '*[^0-9]*' AND a.value = ?)
|
||||
OR (a.value GLOB '*[^0-9]*' AND lower(a.value) = lower(?)))
|
||||
)) THEN 1 ELSE json('role revoked') END AS ok`,
|
||||
)
|
||||
.bind(gid, ...roles, userId, userId, login, "owner", ...roles, gid, userId, login);
|
||||
}
|
||||
|
||||
/**
|
||||
* Carry the user ids already bound to members over to a submitted member
|
||||
* list (matched by login): clients edit logins and roles, never the binding.
|
||||
*/
|
||||
export function carryMemberIds(next: Group, prev: Group | undefined): Group {
|
||||
if (!prev || !Array.isArray(next.members)) return next;
|
||||
const bound = new Map(
|
||||
normalizeGroupMembers(prev)
|
||||
.filter((m) => m.userId)
|
||||
.map((m) => [m.login.toLowerCase(), m.userId!]),
|
||||
);
|
||||
if (bound.size === 0) return next;
|
||||
return {
|
||||
...next,
|
||||
members: next.members.map((m) => {
|
||||
const userId = bound.get(m.login.trim().toLowerCase());
|
||||
return userId ? { ...m, userId } : m;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the signed-in user's id to the member entries that name them only by
|
||||
* login, so a later owner of that login (after a rename) never inherits the
|
||||
* membership. Best-effort; each group is a compare-and-swap.
|
||||
*/
|
||||
export async function bindMemberIds(
|
||||
kv: KVNamespace,
|
||||
groups: Group[],
|
||||
userId: string,
|
||||
login: string,
|
||||
): Promise<void> {
|
||||
const unbound = (g: Group): boolean =>
|
||||
normalizeGroupMembers(g).some(
|
||||
(m) => !m.userId && !/^\d+$/.test(m.login) && memberMatches(m, userId, login),
|
||||
);
|
||||
for (const group of groups.filter(unbound)) {
|
||||
await updateGroup(kv, group.id, (g) => {
|
||||
if (!unbound(g)) return null;
|
||||
const members = normalizeGroupMembers(g).map((m) =>
|
||||
!m.userId && !/^\d+$/.test(m.login) && memberMatches(m, userId, login)
|
||||
? { ...m, userId }
|
||||
: m,
|
||||
);
|
||||
return { ...g, members };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function isGroupAdmin(group: Group, userId: string, login: string): boolean {
|
||||
@@ -89,12 +204,8 @@ export function isGroupAdmin(group: Group, userId: string, login: string): boole
|
||||
* `adminIds` groups resolve to "owner" for every listed admin.
|
||||
*/
|
||||
export function memberRole(group: Group, userId: string, login: string): GroupRole | undefined {
|
||||
const members = normalizeGroupMembers(group);
|
||||
const wanted = members.filter((m) => {
|
||||
const candidate = m.login.trim().toLowerCase();
|
||||
return candidate === login.toLowerCase() || candidate === userId;
|
||||
});
|
||||
return wanted.length > 0 ? wanted[0]!.role : undefined;
|
||||
const member = normalizeGroupMembers(group).find((m) => memberMatches(m, userId, login));
|
||||
return member?.role;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -130,6 +241,27 @@ export function groupAcceptsInstallation(group: Group, installationId?: number):
|
||||
return installationId != null && group.installationId === installationId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the group may receive an event that arrived on the legacy global
|
||||
* endpoint (`POST /webhook`). Isolated groups (self-service personal groups)
|
||||
* only take events from their own `/webhook/{groupId}` ingress, unless a super
|
||||
* admin bound them to a source: a GitHub App installation or an `owners` list.
|
||||
*/
|
||||
/**
|
||||
* Whether a group is isolated. Personal groups (`u-{userId}`) created before
|
||||
* the flag existed count as isolated too, unless a super admin explicitly set
|
||||
* `isolated: false`.
|
||||
*/
|
||||
export function isIsolated(group: Group): boolean {
|
||||
return group.isolated ?? /^u-\d+$/.test(group.id);
|
||||
}
|
||||
|
||||
export function groupAcceptsGlobalIngress(group: Group): boolean {
|
||||
const isolated = isIsolated(group);
|
||||
if (!isolated) return true;
|
||||
return group.installationId != null || (group.owners ?? []).some((o) => o.trim().length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-provision a GitHub App installation on `installation.created`:
|
||||
* 1. No-op when a group is already bound to this installation id.
|
||||
@@ -137,63 +269,103 @@ export function groupAcceptsInstallation(group: Group, installationId?: number):
|
||||
* 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.
|
||||
*
|
||||
* Every write is an atomic create-if-absent or compare-and-swap update, so
|
||||
* concurrent deliveries converge on the same group without a lock.
|
||||
*/
|
||||
/** An automatic installation binding is remembered as long as delivery state (7 days). */
|
||||
const AUTO_BOUND_TTL_SECONDS = 7 * 86400;
|
||||
|
||||
export async function ensureInstallationGroup(
|
||||
kv: KVNamespace,
|
||||
installationId: number,
|
||||
accountLogin: string,
|
||||
db?: D1Database,
|
||||
): Promise<Group | null> {
|
||||
// A per-installation lock serializes concurrent `installation.created`
|
||||
// webhooks: without it two requests both pass the "no group bound" check,
|
||||
// both create `inst-{id}`, and the second save overwrites the first.
|
||||
const lockKey = `inst:lock:${installationId}`;
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
const holder = await kv.get(lockKey);
|
||||
if (!holder) break;
|
||||
const groups = await loadGroups(kv);
|
||||
const existing = groups.find((g) => g.installationId === installationId);
|
||||
if (existing) return existing;
|
||||
await new Promise((r) => setTimeout(r, 40 * (attempt + 1)));
|
||||
}
|
||||
// Each automatic binding is recorded (per installation and group) in the
|
||||
// transaction that makes it: a retry binds the groups an earlier attempt
|
||||
// did not reach, never again one it bound — an admin may have undone that.
|
||||
const claims = db ? idempotencyStore(db, kv) : null;
|
||||
const boundKey = (g: Group): string =>
|
||||
`installation-bound:${installationId}:${g.instance ?? g.id}`;
|
||||
const groups = await loadGroups(kv, { fresh: true });
|
||||
// Already bound somewhere (an earlier attempt): the matching groups still
|
||||
// unbound are bound all the same — that attempt may have failed midway.
|
||||
const existing = groups.find((g) => g.installationId === installationId);
|
||||
|
||||
let locked = false;
|
||||
try {
|
||||
await kv.put(lockKey, "1", { expirationTtl: 60 });
|
||||
locked = true;
|
||||
|
||||
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(
|
||||
const login = accountLogin.trim().toLowerCase();
|
||||
const candidates = groups.filter(
|
||||
(g) =>
|
||||
g.installationId == null &&
|
||||
login.length > 0 &&
|
||||
(g.owners ?? []).some((o) => o.trim().toLowerCase() === login),
|
||||
);
|
||||
let bound: Group | null = null;
|
||||
for (const candidate of candidates) {
|
||||
if (claims && (await claims.has(boundKey(candidate)))) continue;
|
||||
const key = boundKey(candidate);
|
||||
const now = Date.now();
|
||||
// Re-checked on the group as it is at the write: the same group (not one
|
||||
// that took over the id), still unbound, still owned by this account —
|
||||
// an `owners` list cleared meanwhile must not be reopened by a binding.
|
||||
const updated = await updateGroup(
|
||||
kv,
|
||||
candidate.id,
|
||||
(g) =>
|
||||
g.instance === candidate.instance &&
|
||||
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;
|
||||
(g.owners ?? []).some((o) => o.trim().toLowerCase() === login)
|
||||
? { ...g, installationId }
|
||||
: null,
|
||||
db && canUseD1(db)
|
||||
? {
|
||||
// Checked again at the write: an attempt that read before another
|
||||
// one bound (and an admin unbound) the group never binds it again.
|
||||
guards: (d): D1PreparedStatement[] => [unrecordedGuard(d, key)],
|
||||
// Recorded only when the binding was written (the statement before).
|
||||
after: (d): D1PreparedStatement[] => [
|
||||
d
|
||||
.prepare(
|
||||
`INSERT INTO dedup_keys (key, claimed_at, expires_at) SELECT ?, ?, ? WHERE changes() > 0
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
claimed_at = excluded.claimed_at, expires_at = excluded.expires_at`,
|
||||
)
|
||||
.bind(key, now, now + AUTO_BOUND_TTL_SECONDS * 1000),
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
).catch((err: unknown) => {
|
||||
// Refused at the write (bound before by another attempt, or still
|
||||
// contended): this group is left as it is.
|
||||
if (err instanceof ConfigConflictError) return null;
|
||||
throw err;
|
||||
});
|
||||
if (updated?.installationId === installationId) {
|
||||
bound ??= updated;
|
||||
// Without D1 transactions, recorded right after (best effort).
|
||||
if (claims && !(db && canUseD1(db))) await claims.claim(key, AUTO_BOUND_TTL_SECONDS);
|
||||
}
|
||||
|
||||
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;
|
||||
} finally {
|
||||
if (locked) await kv.delete(lockKey);
|
||||
}
|
||||
if (existing) return existing;
|
||||
if (bound) return bound;
|
||||
|
||||
const gid = `inst-${installationId}`;
|
||||
const group: Group = {
|
||||
id: gid,
|
||||
name: accountLogin.trim() || `Installation ${installationId}`,
|
||||
adminIds: [],
|
||||
installationId,
|
||||
};
|
||||
if (await createGroup(kv, group)) {
|
||||
// As stored (with the instance the server gave it), for its audit.
|
||||
return (await loadGroups(kv, { fresh: true })).find((g) => g.id === gid) ?? group;
|
||||
}
|
||||
// The id exists already: only a group already bound to this installation
|
||||
// (a concurrent delivery) is used. An unbound group that merely carries the
|
||||
// name is never bound — its members did not prove they own the installation.
|
||||
const current = (await loadGroups(kv, { fresh: true })).find((g) => g.id === gid);
|
||||
return current?.installationId === installationId ? current : null;
|
||||
}
|
||||
|
||||
export interface AccessScope {
|
||||
|
||||
+407
-79
@@ -1,4 +1,21 @@
|
||||
import { loadGroups, saveGroups, identityMatches, normalizeGroupMembers } from "./groups";
|
||||
import type { Env, Group } from "../types";
|
||||
import {
|
||||
loadGroups,
|
||||
updateGroup,
|
||||
memberMatches,
|
||||
memberRole,
|
||||
memberRoleStatement,
|
||||
normalizeGroupMembers,
|
||||
} from "./groups";
|
||||
import {
|
||||
acceptedKey,
|
||||
claimOnce,
|
||||
confirmClaim,
|
||||
idempotencyStore,
|
||||
recordStatement,
|
||||
} from "../lib/idempotency";
|
||||
import { canUseD1 } from "../storage/d1";
|
||||
import { ConfigConflictError } from "../storage/config-store";
|
||||
import { log } from "../lib/log";
|
||||
|
||||
export interface Invite {
|
||||
@@ -8,9 +25,46 @@ export interface Invite {
|
||||
expiresAt: number;
|
||||
createdBy: string;
|
||||
note?: string;
|
||||
/**
|
||||
* The invited group's immutable `instance` id. A group later re-created
|
||||
* under the same id has another instance, so the invite never admits anyone
|
||||
* to it. Absent on invites created before instances existed.
|
||||
*/
|
||||
groupInstance?: string;
|
||||
/**
|
||||
* Who issued it: a super admin, or a member who must still be an owner of
|
||||
* the group when the invite is used — an owner removed meanwhile cannot
|
||||
* have it let anyone in. Absent on older invites.
|
||||
*/
|
||||
issuer?: { super: true } | { userId: string; login: string };
|
||||
}
|
||||
|
||||
const INVITE_TTL = 24 * 3600;
|
||||
/** The invite belongs to an earlier group that had the same id. */
|
||||
class StaleInviteError extends Error {}
|
||||
|
||||
/**
|
||||
* The login is still on a member entry bound to another account (a member
|
||||
* who renamed since). Adding a second entry with that login would be dropped
|
||||
* as a duplicate — a "successful" join without access — so the owner must
|
||||
* clear the stale entry first.
|
||||
*/
|
||||
class MemberConflictError extends Error {}
|
||||
|
||||
function revokedKey(token: string): string {
|
||||
return `invite-revoked:${token}`;
|
||||
}
|
||||
|
||||
/** How long an invite stays claimed while one acceptance is being processed. */
|
||||
const INVITE_CLAIM_SECONDS = 120;
|
||||
|
||||
/** Invites are valid for seven days; their KV keys live exactly that long. */
|
||||
export const INVITE_LIFETIME_MS = 7 * 86400_000;
|
||||
const INDEX_TTL = INVITE_LIFETIME_MS / 1000;
|
||||
|
||||
/** KV TTL (seconds) for an invite expiring at `expiresAt` (KV minimum: 60). */
|
||||
function ttlFor(expiresAt: number): number {
|
||||
return Math.max(60, Math.ceil((expiresAt - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
function generateInviteToken(): string {
|
||||
const bytes = new Uint8Array(32);
|
||||
@@ -33,91 +87,208 @@ function indexKey(groupId: string): string {
|
||||
return `invite:group:${groupId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokens of a group's index. A failed read propagates: taken for an empty
|
||||
* index, it would be written back without the existing tokens, leaving those
|
||||
* invites valid but unlisted (and so impossible to revoke from the console).
|
||||
*/
|
||||
async function readIndex(kv: KVNamespace, groupId: string): Promise<string[]> {
|
||||
try {
|
||||
const raw = await kv.get<string[]>(indexKey(groupId), "json");
|
||||
return Array.isArray(raw) ? raw : [];
|
||||
} catch (err) {
|
||||
log.warn({ err, groupId }, "Failed to read invite index");
|
||||
return [];
|
||||
}
|
||||
const raw = await kv.get<string[]>(indexKey(groupId), "json");
|
||||
return Array.isArray(raw) ? raw : [];
|
||||
}
|
||||
|
||||
async function writeIndex(kv: KVNamespace, groupId: string, tokens: string[]): Promise<void> {
|
||||
await kv.put(indexKey(groupId), JSON.stringify(tokens), { expirationTtl: INVITE_TTL });
|
||||
await kv.put(indexKey(groupId), JSON.stringify(tokens), { expirationTtl: INDEX_TTL });
|
||||
}
|
||||
|
||||
async function removeFromIndex(kv: KVNamespace, groupId: string, token: string): Promise<void> {
|
||||
const tokens = (await readIndex(kv, groupId)).filter((t) => t !== token);
|
||||
await writeIndex(kv, groupId, tokens);
|
||||
/**
|
||||
* Per-invite membership key, written on its own (no read-modify-write): two
|
||||
* invites created at once can both lose their index entry to the other's
|
||||
* index write, but never their marker. Listing reads both — the index for
|
||||
* fresh writes, the markers (an eventually consistent `list`) for durability.
|
||||
*/
|
||||
function markerPrefix(groupId: string): string {
|
||||
return `invite:by-group:${groupId}:`;
|
||||
}
|
||||
|
||||
function listMarkers(kv: KVNamespace, groupId: string): Promise<string[]> {
|
||||
return listPrefix(kv, markerPrefix(groupId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-invite key under the issuing group's instance: it never moves, so the
|
||||
* group finds its invites even when moving them to a new id after a rename
|
||||
* failed halfway.
|
||||
*/
|
||||
function instancePrefix(instance: string): string {
|
||||
return `invite:by-instance:${instance}:`;
|
||||
}
|
||||
|
||||
async function listPrefix(kv: KVNamespace, prefix: string): Promise<string[]> {
|
||||
const tokens: string[] = [];
|
||||
let cursor: string | undefined;
|
||||
do {
|
||||
const page = await kv.list({ prefix, cursor });
|
||||
for (const k of page.keys) {
|
||||
if (k.name.startsWith(prefix)) tokens.push(k.name.slice(prefix.length));
|
||||
}
|
||||
cursor = page.list_complete ? undefined : (page as { cursor?: string }).cursor;
|
||||
} while (cursor);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** Every token listed for a group: by its index, its id markers or its instance markers. */
|
||||
async function groupTokens(kv: KVNamespace, groupId: string, instance?: string): Promise<string[]> {
|
||||
const [indexed, marked, owned] = await Promise.all([
|
||||
readIndex(kv, groupId),
|
||||
listMarkers(kv, groupId),
|
||||
instance ? listPrefix(kv, instancePrefix(instance)) : Promise.resolve([]),
|
||||
]);
|
||||
return [...new Set([...indexed, ...marked, ...owned])];
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the index without the given tokens — only when it lists any of them:
|
||||
* KV writes are the scarcest quota (Workers Free), and an unchanged index
|
||||
* needs no rewrite.
|
||||
*/
|
||||
async function dropFromIndex(kv: KVNamespace, groupId: string, gone: string[]): Promise<void> {
|
||||
const current = await readIndex(kv, groupId);
|
||||
const kept = current.filter((t) => !gone.includes(t));
|
||||
if (kept.length !== current.length) await writeIndex(kv, groupId, kept);
|
||||
}
|
||||
|
||||
/** Remove every listing link of an invite that is gone (index, id and instance markers). */
|
||||
async function removeFromIndex(kv: KVNamespace, invite: Invite, token: string): Promise<void> {
|
||||
await kv.delete(`${markerPrefix(invite.groupId)}${token}`);
|
||||
if (invite.groupInstance) await kv.delete(`${instancePrefix(invite.groupInstance)}${token}`);
|
||||
await dropFromIndex(kv, invite.groupId, [token]);
|
||||
}
|
||||
|
||||
export async function createInvite(kv: KVNamespace, invite: Invite): Promise<string> {
|
||||
const token = generateInviteToken();
|
||||
await kv.put(inviteKey(token), JSON.stringify(invite), { expirationTtl: INVITE_TTL });
|
||||
const ttl = { expirationTtl: ttlFor(invite.expiresAt) };
|
||||
await kv.put(inviteKey(token), JSON.stringify(invite), ttl);
|
||||
await kv.put(`${markerPrefix(invite.groupId)}${token}`, "1", ttl);
|
||||
if (invite.groupInstance) {
|
||||
await kv.put(`${instancePrefix(invite.groupInstance)}${token}`, "1", ttl);
|
||||
}
|
||||
const tokens = await readIndex(kv, invite.groupId);
|
||||
tokens.push(token);
|
||||
await writeIndex(kv, invite.groupId, tokens);
|
||||
return token;
|
||||
}
|
||||
|
||||
/** The invite, or null when it does not exist (any more). Read errors propagate. */
|
||||
export async function getInvite(kv: KVNamespace, token: string): Promise<Invite | null> {
|
||||
try {
|
||||
const raw = await kv.get<Invite>(inviteKey(token), "json");
|
||||
if (!raw) return null;
|
||||
if (Date.now() > raw.expiresAt) {
|
||||
await kv.delete(inviteKey(token));
|
||||
await removeFromIndex(kv, raw.groupId, token);
|
||||
return null;
|
||||
}
|
||||
return raw;
|
||||
} catch (err) {
|
||||
log.warn({ err }, "Failed to load invite");
|
||||
const raw = await kv.get<Invite>(inviteKey(token), "json");
|
||||
if (!raw) return null;
|
||||
if (Date.now() > raw.expiresAt) {
|
||||
await kv.delete(inviteKey(token));
|
||||
await removeFromIndex(kv, raw, token);
|
||||
return null;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
export async function consumeInvite(kv: KVNamespace, token: string): Promise<void> {
|
||||
const raw = await kv.get<Invite>(inviteKey(token), "json");
|
||||
await kv.delete(inviteKey(token));
|
||||
if (raw) await removeFromIndex(kv, raw.groupId, token);
|
||||
if (raw) await removeFromIndex(kv, raw, token);
|
||||
}
|
||||
|
||||
/** All pending (unexpired) invites of a group, via the per-group index. */
|
||||
/**
|
||||
* Whether an invite was issued by this very group, not by an earlier group
|
||||
* that had the same id (its index may outlive a failed cleanup). An invite from
|
||||
* before instances belongs to the group that had its id back then (`legacyId`).
|
||||
*/
|
||||
function issuedBy(
|
||||
invite: Invite,
|
||||
group: Pick<Group, "instance" | "legacyId"> | undefined,
|
||||
): boolean {
|
||||
if (!group?.instance) return true;
|
||||
if (invite.groupInstance) return invite.groupInstance === group.instance;
|
||||
return group.legacyId === invite.groupId;
|
||||
}
|
||||
|
||||
/**
|
||||
* All pending (unexpired) invites of a group, via the per-group index. With
|
||||
* the group given, invites of an earlier group under the same id are left
|
||||
* out (and removed): their links must not reach the new group's owners.
|
||||
*/
|
||||
export async function listInvites(
|
||||
kv: KVNamespace,
|
||||
groupId: string,
|
||||
group?: Pick<Group, "instance" | "legacyId">,
|
||||
): Promise<Array<Invite & { token: string }>> {
|
||||
try {
|
||||
const tokens = await readIndex(kv, groupId);
|
||||
const out: Array<Invite & { token: string }> = [];
|
||||
const stale: string[] = [];
|
||||
for (const token of tokens) {
|
||||
const invite = await getInvite(kv, token);
|
||||
if (invite && invite.groupId === groupId) {
|
||||
out.push({ ...invite, token });
|
||||
} else {
|
||||
stale.push(token);
|
||||
// Read errors propagate (the console shows a failure, not "no invites"),
|
||||
// and only tokens whose invite is known to be gone are pruned.
|
||||
// A pre-instance group may still have invites filed under the id it had
|
||||
// back then (a rename whose invite move failed).
|
||||
const formerId = group?.legacyId && group.legacyId !== groupId ? group.legacyId : undefined;
|
||||
const tokens = [
|
||||
...new Set([
|
||||
...(await groupTokens(kv, groupId, group?.instance)),
|
||||
...(formerId ? await groupTokens(kv, formerId) : []),
|
||||
]),
|
||||
];
|
||||
const out: Array<Invite & { token: string }> = [];
|
||||
const stale: string[] = [];
|
||||
for (const token of tokens) {
|
||||
const invite = await getInvite(kv, token);
|
||||
// Also the group's own invites still filed under a former id (a rename
|
||||
// whose invite move failed): they are usable, so they must be listed.
|
||||
const ours =
|
||||
invite != null &&
|
||||
issuedBy(invite, group) &&
|
||||
(invite.groupId === groupId ||
|
||||
(group?.instance != null && invite.groupInstance === group.instance) ||
|
||||
(formerId != null && !invite.groupInstance && invite.groupId === formerId));
|
||||
if (invite && ours) {
|
||||
out.push({ ...invite, token });
|
||||
} else {
|
||||
// Not this group's (gone, or issued by a former holder of the id — which
|
||||
// may live on under another id): only the listing link to this id goes;
|
||||
// the invite itself is not ours to revoke and expires on its own.
|
||||
await kv.delete(`${markerPrefix(groupId)}${token}`);
|
||||
// A gone invite's marker under this group's instance goes too, or every
|
||||
// later listing would find (and clean up after) it again until it expires.
|
||||
if (!invite && group?.instance) {
|
||||
await kv.delete(`${instancePrefix(group.instance)}${token}`);
|
||||
}
|
||||
stale.push(token);
|
||||
}
|
||||
if (stale.length > 0) {
|
||||
await writeIndex(
|
||||
kv,
|
||||
groupId,
|
||||
tokens.filter((t) => !stale.includes(t)),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
} catch (err) {
|
||||
log.warn({ err }, "Failed to list invites");
|
||||
return [];
|
||||
}
|
||||
// Re-read: an invite created meanwhile must stay listed.
|
||||
if (stale.length > 0) await dropFromIndex(kv, groupId, stale);
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function revokeInvite(kv: KVNamespace, token: string): Promise<void> {
|
||||
/**
|
||||
* Revoke an invite. With `db`, the revocation is first recorded in the
|
||||
* idempotency store (for the invite's lifetime): an acceptance already past
|
||||
* its KV read checks it inside its member write, so it cannot still join.
|
||||
*/
|
||||
export async function revokeInvite(
|
||||
kv: KVNamespace,
|
||||
token: string,
|
||||
db?: D1Database,
|
||||
guards?: (db: D1Database) => D1PreparedStatement[],
|
||||
): Promise<void> {
|
||||
const raw = await kv.get<Invite>(inviteKey(token), "json");
|
||||
if (db) {
|
||||
const ttl = ttlFor(raw?.expiresAt ?? Date.now() + INVITE_LIFETIME_MS);
|
||||
if (guards && canUseD1(db)) {
|
||||
// The revocation record commits only while the guards hold (e.g. the
|
||||
// revoking owner still is one): a request authorized before a role
|
||||
// change can no longer act after it.
|
||||
await db.batch([...guards(db), recordStatement(db, revokedKey(token), ttl)]);
|
||||
} else {
|
||||
await idempotencyStore(db, kv).claim(revokedKey(token), ttl);
|
||||
}
|
||||
}
|
||||
await kv.delete(inviteKey(token));
|
||||
if (raw) await removeFromIndex(kv, raw.groupId, token);
|
||||
if (raw) await removeFromIndex(kv, raw, token);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,9 +296,14 @@ export async function revokeInvite(kv: KVNamespace, token: string): Promise<void
|
||||
* Best-effort: a failure leaves the old invites in place (they will be
|
||||
* rejected as group-missing after the rename).
|
||||
*/
|
||||
export async function migrateInvites(kv: KVNamespace, from: string, to: string): Promise<void> {
|
||||
export async function migrateInvites(
|
||||
kv: KVNamespace,
|
||||
from: string,
|
||||
to: string,
|
||||
group?: Pick<Group, "instance" | "legacyId">,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const tokens = await readIndex(kv, from);
|
||||
const tokens = await groupTokens(kv, from);
|
||||
if (tokens.length === 0) {
|
||||
await kv.delete(indexKey(from));
|
||||
return;
|
||||
@@ -135,59 +311,211 @@ export async function migrateInvites(kv: KVNamespace, from: string, to: string):
|
||||
const moved: string[] = [];
|
||||
for (const token of tokens) {
|
||||
const invite = await kv.get<Invite>(inviteKey(token), "json");
|
||||
if (invite && invite.groupId === from) {
|
||||
await kv.put(inviteKey(token), JSON.stringify({ ...invite, groupId: to }), {
|
||||
expirationTtl: INVITE_TTL,
|
||||
});
|
||||
// Only the renamed group's own invites move (a former group's leftovers
|
||||
// stay behind); they get its instance, so they keep working under the
|
||||
// new id even when they date from before instances.
|
||||
if (invite && invite.groupId === from && issuedBy(invite, group)) {
|
||||
const groupInstance = invite.groupInstance ?? group?.instance;
|
||||
const ttl = { expirationTtl: ttlFor(invite.expiresAt) };
|
||||
await kv.put(
|
||||
inviteKey(token),
|
||||
JSON.stringify({ ...invite, groupId: to, groupInstance }),
|
||||
ttl,
|
||||
);
|
||||
await kv.put(`${markerPrefix(to)}${token}`, "1", ttl);
|
||||
if (groupInstance) await kv.put(`${instancePrefix(groupInstance)}${token}`, "1", ttl);
|
||||
await kv.delete(`${markerPrefix(from)}${token}`);
|
||||
moved.push(token);
|
||||
}
|
||||
}
|
||||
await kv.put(indexKey(to), JSON.stringify(moved), { expirationTtl: INVITE_TTL });
|
||||
const kept = (await readIndex(kv, to)).filter((t) => !moved.includes(t));
|
||||
await kv.put(indexKey(to), JSON.stringify([...kept, ...moved]), {
|
||||
expirationTtl: INDEX_TTL,
|
||||
});
|
||||
await kv.delete(indexKey(from));
|
||||
} catch (err) {
|
||||
log.warn({ err, from, to }, "Failed to migrate invites on group rename");
|
||||
}
|
||||
}
|
||||
|
||||
/** Revoke every pending invite of a deleted group. */
|
||||
export async function deleteGroupInvites(
|
||||
kv: KVNamespace,
|
||||
groupId: string,
|
||||
group?: Pick<Group, "instance" | "legacyId">,
|
||||
): Promise<void> {
|
||||
const instance = group?.instance;
|
||||
try {
|
||||
for (const token of await groupTokens(kv, groupId, instance)) {
|
||||
// Only the deleted group's own invites are revoked: one listed under
|
||||
// its id may have been issued by a group that lives on under another.
|
||||
const invite = await kv.get<Invite>(inviteKey(token), "json");
|
||||
if (
|
||||
invite &&
|
||||
issuedBy(invite, group) &&
|
||||
(invite.groupId === groupId || (instance != null && invite.groupInstance === instance))
|
||||
) {
|
||||
await kv.delete(inviteKey(token));
|
||||
}
|
||||
await kv.delete(`${markerPrefix(groupId)}${token}`);
|
||||
if (instance) await kv.delete(`${instancePrefix(instance)}${token}`);
|
||||
}
|
||||
await kv.delete(indexKey(groupId));
|
||||
} catch (err) {
|
||||
log.warn({ err, groupId }, "Failed to delete invites of a removed group");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the accepting user to the invited group (or upgrades their role when
|
||||
* they are already a viewer) and consumes the invite. The invited role is
|
||||
* never an owner — ownership stays with the inviter's discretion.
|
||||
*
|
||||
* The invite is claimed atomically before the membership changes, so two
|
||||
* people accepting the same link at once cannot both join; the member write is
|
||||
* a compare-and-swap on the group, so it never reverts a concurrent edit.
|
||||
*/
|
||||
export async function acceptInvite(
|
||||
kv: KVNamespace,
|
||||
env: Pick<Env, "KV" | "DB">,
|
||||
token: string,
|
||||
userId: string,
|
||||
login: string,
|
||||
/** The login identity checks may use ("" when it is not trusted as this user's). */
|
||||
matchLogin = login,
|
||||
): Promise<
|
||||
| { ok: true; groupId: string; role: "admin" | "viewer" }
|
||||
| { ok: false; reason: "invalid" | "group-missing" }
|
||||
| { ok: true; groupId: string; groupInstance?: string; role: "admin" | "viewer" }
|
||||
| { ok: false; reason: "invalid" | "group-missing" | "conflict" }
|
||||
> {
|
||||
const kv = env.KV;
|
||||
const invite = await getInvite(kv, token);
|
||||
if (!invite) return { ok: false, reason: "invalid" };
|
||||
const groups = await loadGroups(kv);
|
||||
const group = groups.find((g) => g.id === invite.groupId);
|
||||
if (!group) return { ok: false, reason: "group-missing" };
|
||||
|
||||
const members = normalizeGroupMembers(group);
|
||||
const idx = members.findIndex((m) => identityMatches([m.login], userId, login));
|
||||
if (idx >= 0) {
|
||||
if (invite.role === "admin" && members[idx]!.role === "viewer") {
|
||||
members[idx]!.role = "admin";
|
||||
}
|
||||
} else {
|
||||
members.push({ login, role: invite.role });
|
||||
const claims = idempotencyStore(env.DB, kv);
|
||||
const claimKey = `invite-used:${token}`;
|
||||
// A short claim while joining, confirmed for the invite's lifetime once
|
||||
// used: an attempt that fails and cannot give the claim back blocks the
|
||||
// invite for a couple of minutes, not until it expires.
|
||||
if ((await claimOnce(claims, claimKey, INVITE_CLAIM_SECONDS)) !== "claimed") {
|
||||
return { ok: false, reason: "invalid" };
|
||||
}
|
||||
const next = groups.map((g) =>
|
||||
g.id === group.id
|
||||
? {
|
||||
...g,
|
||||
if (await claims.has(revokedKey(token))) {
|
||||
await claims.release(claimKey).catch(() => undefined);
|
||||
return { ok: false, reason: "invalid" };
|
||||
}
|
||||
|
||||
let joined = false;
|
||||
let joinedId: string | undefined;
|
||||
let joinedInstance: string | undefined;
|
||||
/** The member who issued the invite is no longer an owner (it is void then). */
|
||||
const issuerGone = async (): Promise<boolean> => {
|
||||
const by = invite.issuer && "userId" in invite.issuer ? invite.issuer : null;
|
||||
if (!by) return false;
|
||||
const group = (await loadGroups(kv, { fresh: true })).find((g) =>
|
||||
invite.groupInstance ? g.instance === invite.groupInstance : g.legacyId === invite.groupId,
|
||||
);
|
||||
return !group || memberRole(group, by.userId, by.login) !== "owner";
|
||||
};
|
||||
try {
|
||||
// The invited group is the instance the invite was issued for, under
|
||||
// whatever id it has now. An invite from before instances only applies to
|
||||
// a group that existed back then, never to one created since.
|
||||
const groups = await loadGroups(kv, { fresh: true });
|
||||
const target = invite.groupInstance
|
||||
? groups.find((g) => g.instance === invite.groupInstance)
|
||||
: groups.find((g) => g.legacyId === invite.groupId);
|
||||
// Its group instance is gone for good: the invite can never be used.
|
||||
if (!target && invite.groupInstance) throw new StaleInviteError();
|
||||
if (!target) return { ok: false, reason: "group-missing" };
|
||||
// The invite is confirmed as used in the same transaction that adds the
|
||||
// member — only when that write went through (`changes()`: the member
|
||||
// update right before; a lost compare-and-swap changes nothing) and the
|
||||
// member is there after it: no crash between the two can leave a member
|
||||
// added and the invite still open, nor a retried write consume it unused.
|
||||
const confirmWithJoin = (db: D1Database): D1PreparedStatement[] => [
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO dedup_keys (key, claimed_at, expires_at)
|
||||
SELECT ?, ?, ? WHERE changes() > 0 AND EXISTS (
|
||||
SELECT 1 FROM (SELECT id, CASE WHEN json_valid(data) THEN data ELSE '{}' END AS data FROM d1_groups) g, json_each(g.data, '$.members') m
|
||||
WHERE g.id = ? AND json_extract(m.value, '$.userId') = ?)
|
||||
ON CONFLICT(key) DO UPDATE SET expires_at = excluded.expires_at`,
|
||||
)
|
||||
.bind(acceptedKey(claimKey), Date.now(), invite.expiresAt, target.id, userId),
|
||||
];
|
||||
// And it only commits while the invite is unused and not revoked: an
|
||||
// earlier acceptance whose answer was lost (its claim given back, its use
|
||||
// committed), or a revocation that landed after the KV read, aborts it.
|
||||
const issuer = invite.issuer && "userId" in invite.issuer ? invite.issuer : null;
|
||||
const unusedGuard = (db: D1Database): D1PreparedStatement[] => [
|
||||
db
|
||||
.prepare(
|
||||
"SELECT CASE WHEN EXISTS (SELECT 1 FROM dedup_keys WHERE key IN (?, ?) AND expires_at > ?) THEN json('invite used') ELSE 1 END AS ok",
|
||||
)
|
||||
.bind(acceptedKey(claimKey), revokedKey(token), Date.now()),
|
||||
...(issuer
|
||||
? [memberRoleStatement(db, target.id, issuer.userId, issuer.login, ["owner"])]
|
||||
: []),
|
||||
];
|
||||
const updated = await updateGroup(
|
||||
kv,
|
||||
target.id,
|
||||
(group) => {
|
||||
const sameInstance = invite.groupInstance
|
||||
? group.instance === invite.groupInstance
|
||||
: group.legacyId === invite.groupId;
|
||||
if (!sameInstance) throw new StaleInviteError();
|
||||
const members = normalizeGroupMembers(group);
|
||||
const idx = members.findIndex((m) => memberMatches(m, userId, matchLogin));
|
||||
if (idx >= 0) {
|
||||
if (invite.role === "admin" && members[idx]!.role === "viewer") {
|
||||
members[idx]!.role = "admin";
|
||||
}
|
||||
members[idx]!.userId ??= userId;
|
||||
} else {
|
||||
if (members.some((m) => m.login.toLowerCase() === login.toLowerCase())) {
|
||||
throw new MemberConflictError();
|
||||
}
|
||||
// Bound to the account that accepted, not to its (renamable) login.
|
||||
members.push({ login, role: invite.role, userId });
|
||||
}
|
||||
return {
|
||||
...group,
|
||||
members,
|
||||
adminIds: members.filter((m) => m.role === "owner").map((m) => m.login),
|
||||
}
|
||||
: g,
|
||||
};
|
||||
},
|
||||
{ guards: unusedGuard, after: confirmWithJoin },
|
||||
);
|
||||
joined = updated != null;
|
||||
joinedId = updated?.id;
|
||||
joinedInstance = updated?.instance;
|
||||
} catch (err) {
|
||||
// The invite stays usable once the owner resolved the conflict.
|
||||
if (err instanceof MemberConflictError) return { ok: false, reason: "conflict" };
|
||||
// Used meanwhile (by an acceptance whose answer was lost).
|
||||
if (
|
||||
err instanceof ConfigConflictError &&
|
||||
((await claims.has(acceptedKey(claimKey))) ||
|
||||
(await claims.has(revokedKey(token))) ||
|
||||
(await issuerGone()))
|
||||
) {
|
||||
return { ok: false, reason: "invalid" };
|
||||
}
|
||||
if (!(err instanceof StaleInviteError)) throw err;
|
||||
await consumeInvite(kv, token);
|
||||
return { ok: false, reason: "invalid" };
|
||||
} finally {
|
||||
if (!joined) await claims.release(claimKey).catch(() => undefined);
|
||||
}
|
||||
if (!joined) return { ok: false, reason: "group-missing" };
|
||||
await confirmClaim(claims, claimKey, ttlFor(invite.expiresAt)).catch((err: unknown) =>
|
||||
log.warn({ err }, "Failed to confirm an invite claim"),
|
||||
);
|
||||
await saveGroups(kv, next);
|
||||
await consumeInvite(kv, token);
|
||||
return { ok: true, groupId: group.id, role: invite.role };
|
||||
return {
|
||||
ok: true,
|
||||
groupId: joinedId ?? invite.groupId,
|
||||
groupInstance: joinedInstance,
|
||||
role: invite.role,
|
||||
};
|
||||
}
|
||||
+161
-8
@@ -4,8 +4,11 @@ import {
|
||||
getInvite,
|
||||
listInvites,
|
||||
revokeInvite,
|
||||
consumeInvite,
|
||||
acceptInvite,
|
||||
INVITE_LIFETIME_MS,
|
||||
} from "../server/lib/web/invites";
|
||||
import { createSqliteD1, createMemoryKV } from "./d1-sqlite";
|
||||
import { saveGroups, loadGroups, invalidateGroupsCache } from "../server/lib/web/groups";
|
||||
import type { Group } from "../server/lib/types";
|
||||
|
||||
@@ -46,9 +49,11 @@ const group: Group = {
|
||||
|
||||
describe("invites", () => {
|
||||
let kv: KVNamespace;
|
||||
let env: { KV: KVNamespace; DB: D1Database };
|
||||
|
||||
beforeEach(() => {
|
||||
kv = createMockKV();
|
||||
env = { KV: kv, DB: {} as D1Database };
|
||||
invalidateGroupsCache();
|
||||
});
|
||||
|
||||
@@ -81,6 +86,51 @@ describe("invites", () => {
|
||||
expect(invites[0]!.groupId).toBe("team");
|
||||
});
|
||||
|
||||
it("hides invites an earlier group under the same id left behind, without revoking them", async () => {
|
||||
const old = await createInvite(kv, {
|
||||
groupId: "team",
|
||||
role: "admin",
|
||||
expiresAt: Date.now() + 86400_000,
|
||||
createdBy: "former",
|
||||
groupInstance: "former-instance",
|
||||
});
|
||||
const legacy = await createInvite(kv, {
|
||||
groupId: "team",
|
||||
role: "viewer",
|
||||
expiresAt: Date.now() + 86400_000,
|
||||
createdBy: "former",
|
||||
});
|
||||
const mine = await createInvite(kv, {
|
||||
groupId: "team",
|
||||
role: "viewer",
|
||||
expiresAt: Date.now() + 86400_000,
|
||||
createdBy: "boss",
|
||||
groupInstance: "current",
|
||||
});
|
||||
// A group created after instances existed: neither older invite is its own.
|
||||
const listed = await listInvites(kv, "team", { instance: "current" });
|
||||
expect(listed.map((i) => i.token)).toEqual([mine]);
|
||||
// Their issuer may live on under another id: not this group's to revoke.
|
||||
expect(await getInvite(kv, old)).not.toBeNull();
|
||||
expect(await getInvite(kv, legacy)).not.toBeNull();
|
||||
expect((await listInvites(kv, "team", { instance: "current" })).map((i) => i.token)).toEqual([
|
||||
mine,
|
||||
]);
|
||||
});
|
||||
|
||||
it("still lists a renamed group's invites whose move to the new id failed", async () => {
|
||||
const token = await createInvite(kv, {
|
||||
groupId: "old",
|
||||
role: "viewer",
|
||||
expiresAt: Date.now() + 86400_000,
|
||||
createdBy: "boss",
|
||||
groupInstance: "inst-1",
|
||||
});
|
||||
// Renamed to "new"; moving the invite failed, it still names "old".
|
||||
const listed = await listInvites(kv, "new", { instance: "inst-1" });
|
||||
expect(listed.map((i) => i.token)).toEqual([token]);
|
||||
});
|
||||
|
||||
it("revokes an invite", async () => {
|
||||
const token = await createInvite(kv, {
|
||||
groupId: "team",
|
||||
@@ -100,15 +150,44 @@ describe("invites", () => {
|
||||
expiresAt: Date.now() + 86400_000,
|
||||
createdBy: "boss",
|
||||
});
|
||||
const result = await acceptInvite(kv, token, "777", "newbie");
|
||||
expect(result).toEqual({ ok: true, groupId: "team", role: "admin" });
|
||||
const result = await acceptInvite(env, token, "777", "newbie");
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
groupId: "team",
|
||||
groupInstance: expect.any(String),
|
||||
role: "admin",
|
||||
});
|
||||
expect(await getInvite(kv, token)).toBeNull();
|
||||
const groups = await loadGroups(kv);
|
||||
expect(groups[0]!.members).toContainEqual({ login: "newbie", role: "admin" });
|
||||
expect(groups[0]!.members).toContainEqual({ login: "newbie", role: "admin", userId: "777" });
|
||||
// adminIds stays in sync with owners only.
|
||||
expect(groups[0]!.adminIds).toEqual(["boss"]);
|
||||
});
|
||||
|
||||
it("refuses (and keeps the invite) when the login is on a member bound to another account", async () => {
|
||||
await saveGroups(kv, [
|
||||
{
|
||||
...group,
|
||||
members: [
|
||||
{ login: "boss", role: "owner" },
|
||||
// A member who renamed since; "newbie" now belongs to someone else.
|
||||
{ login: "newbie", role: "viewer", userId: "42" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
const token = await createInvite(kv, {
|
||||
groupId: "team",
|
||||
role: "admin",
|
||||
expiresAt: Date.now() + 86400_000,
|
||||
createdBy: "boss",
|
||||
});
|
||||
expect(await acceptInvite(env, token, "777", "newbie")).toEqual({
|
||||
ok: false,
|
||||
reason: "conflict",
|
||||
});
|
||||
expect(await getInvite(kv, token)).not.toBeNull();
|
||||
});
|
||||
|
||||
it("upgrades an existing viewer to admin", async () => {
|
||||
await saveGroups(kv, [
|
||||
{
|
||||
@@ -125,9 +204,49 @@ describe("invites", () => {
|
||||
expiresAt: Date.now() + 86400_000,
|
||||
createdBy: "boss",
|
||||
});
|
||||
await acceptInvite(kv, token, "777", "newbie");
|
||||
await acceptInvite(env, token, "777", "newbie");
|
||||
const groups = await loadGroups(kv);
|
||||
expect(groups[0]!.members).toContainEqual({ login: "newbie", role: "admin" });
|
||||
expect(groups[0]!.members).toContainEqual({ login: "newbie", role: "admin", userId: "777" });
|
||||
});
|
||||
|
||||
it("lets only one of two concurrent accepts use the invite", async () => {
|
||||
const { db } = createSqliteD1();
|
||||
const shared = { KV: kv, DB: db };
|
||||
await saveGroups(kv, [group]);
|
||||
const token = await createInvite(kv, {
|
||||
groupId: "team",
|
||||
role: "admin",
|
||||
expiresAt: Date.now() + INVITE_LIFETIME_MS,
|
||||
createdBy: "boss",
|
||||
});
|
||||
const results = await Promise.all([
|
||||
acceptInvite(shared, token, "1", "first"),
|
||||
acceptInvite(shared, token, "2", "second"),
|
||||
]);
|
||||
expect(results.filter((r) => r.ok)).toHaveLength(1);
|
||||
const members = (await loadGroups(kv))[0]!.members!.map((m) => m.login);
|
||||
expect(members.filter((m) => m === "first" || m === "second")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps an invite's KV key for its whole seven-day lifetime", async () => {
|
||||
const ttls = new Map<string, number>();
|
||||
const put = kv.put.bind(kv);
|
||||
(kv as { put: unknown }).put = async (
|
||||
key: string,
|
||||
value: string,
|
||||
opts?: { expirationTtl?: number },
|
||||
): Promise<void> => {
|
||||
ttls.set(key, opts?.expirationTtl ?? 0);
|
||||
await put(key, value, opts);
|
||||
};
|
||||
const token = await createInvite(kv, {
|
||||
groupId: "team",
|
||||
role: "viewer",
|
||||
expiresAt: Date.now() + INVITE_LIFETIME_MS,
|
||||
createdBy: "boss",
|
||||
});
|
||||
expect(ttls.get(`invite:${token}`)).toBeGreaterThan(6 * 86400);
|
||||
expect(ttls.get("invite:group:team")).toBeGreaterThan(6 * 86400);
|
||||
});
|
||||
|
||||
it("rejects expired or unknown invites", async () => {
|
||||
@@ -138,8 +257,8 @@ describe("invites", () => {
|
||||
expiresAt: Date.now() - 1000,
|
||||
createdBy: "boss",
|
||||
});
|
||||
expect(await acceptInvite(kv, token, "1", "x")).toEqual({ ok: false, reason: "invalid" });
|
||||
expect(await acceptInvite(kv, "deadbeef", "1", "x")).toEqual({ ok: false, reason: "invalid" });
|
||||
expect(await acceptInvite(env, token, "1", "x")).toEqual({ ok: false, reason: "invalid" });
|
||||
expect(await acceptInvite(env, "deadbeef", "1", "x")).toEqual({ ok: false, reason: "invalid" });
|
||||
});
|
||||
|
||||
it("rejects invites for missing groups", async () => {
|
||||
@@ -150,6 +269,40 @@ describe("invites", () => {
|
||||
expiresAt: Date.now() + 86400_000,
|
||||
createdBy: "boss",
|
||||
});
|
||||
expect(await acceptInvite(kv, token, "1", "x")).toEqual({ ok: false, reason: "group-missing" });
|
||||
expect(await acceptInvite(env, token, "1", "x")).toEqual({
|
||||
ok: false,
|
||||
reason: "group-missing",
|
||||
});
|
||||
// The failed attempt gave the invite back.
|
||||
await saveGroups(kv, [{ ...group, id: "ghost" }]);
|
||||
expect(await acceptInvite(env, token, "1", "x")).toMatchObject({ ok: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("invite listing quota", () => {
|
||||
it("writes nothing to KV when listing after an invite was used", async () => {
|
||||
const { kv } = createMemoryKV();
|
||||
const group = { instance: "i1" };
|
||||
const token = await createInvite(kv, {
|
||||
groupId: "g",
|
||||
role: "viewer",
|
||||
expiresAt: Date.now() + INVITE_LIFETIME_MS,
|
||||
createdBy: "1",
|
||||
groupInstance: "i1",
|
||||
});
|
||||
await consumeInvite(kv, token);
|
||||
let writes = 0;
|
||||
const put = kv.put.bind(kv);
|
||||
const del = kv.delete.bind(kv);
|
||||
kv.put = ((...args: Parameters<KVNamespace["put"]>) => {
|
||||
writes++;
|
||||
return put(...args);
|
||||
}) as KVNamespace["put"];
|
||||
kv.delete = ((key: string) => {
|
||||
writes++;
|
||||
return del(key);
|
||||
}) as KVNamespace["delete"];
|
||||
for (let i = 0; i < 3; i++) expect(await listInvites(kv, "g", group)).toEqual([]);
|
||||
expect(writes).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user