Files
website/server/src/model/teams/teamVoiceSettings.model.js
wtclaude 61abb3ec89 feat(teams): phase 9 — one voice channel per Team, granted by a role
TEAMS.md §7.3. Each qualifying Team gets a Discord voice channel of its own
and a role that opens it, kept in step by a reconciler that rides the Team
reconcile it already depends on.

Access is a per-Team ROLE, always. §7.3 designed per-member overwrites with
escalation to a role above ~90 members; the org lead settled on roles always
(2026-08-18), which deletes `voice_overwrite_max`, the escalation and the
`mode` column — and moves the ceiling. Overwrites are capped per channel, so
the old shape's limit was "how big can one Team be"; roles are capped per
guild at 250, so the new one is "how many Teams can have voice at all". That
is a limit an operator must be told about before they hit it, so the panel
reports it and the pass refuses the create rather than letting Discord do it.

Three things §7.3 named that this codebase does not have, all settled by
asking the operator because nothing in the data model can answer:

  - "the staff role" — there is no staff-role concept anywhere. Now a list of
    role ids the admin designates; empty is a normal answer, since guild
    administrators bypass overwrites and what is really missing is a way to
    let NON-admin staff in.
  - the parent category — §7.3 said the bot creates it and gave the id nowhere
    to live (`team_integrations.team_id` is NOT NULL). The bot creates it and
    the server stores the id in settings.
  - whether the bot can act at all — nothing has ever checked. The operator
    invites the bot by hand and no invite URL with a permission integer exists
    in the tree, so a deployment can be one unticked box from every call
    failing. A preflight is now a PRECONDITION to enabling (422), not a
    per-Team error discovered afterwards.

Two more, decided rather than asked:

  - the threshold counts every active member, not linked ones. §7.3 wrote
    `voice_min_linked_members`; the operator is judging whether a Team is real,
    and link state answers a different question.
  - hidden Teams are never provisioned. A channel name is a game-sourced string
    published outside the site, which is exactly §2.8's concern —
    reservedNames.js already names "and eventually a Discord channel name" as a
    surface it protects — so the screen that suppresses a Team's page suppresses
    its channel, and a Team that becomes hidden takes the grace window.

Turning voice OFF tears nothing down: the pass suspends in both directions and
the panel offers per-row removal. A checkbox must not delete structure in
somebody's guild.

Fixes a phase 8 defect that blocks this phase's own artifact: `npm run swagger`
has been unable to run on `edge` at all. `param('teamId').custom((v) => ... ||
/^[0-9]+$/.test(v))` makes swagger-autogen's parser run away — a regex literal
followed directly by `.test(`. Hoisted to a const, as modules.router.js
already does. Underneath it, `teams.router.js` sits exactly at that parser's
per-file limit: at twenty `teamsRouter.*` statements it dies, at nineteen it
generates, and one more statement of ANY shape tips it — an unannotated route
does, and so does a bare `use`. So the voice routes are their own router file
mounted from `admin/index.js`, and teams.router.js keeps its nineteen.

Also breaks a require cycle this phase would have introduced:
teamSync -> teamVoiceSync -> teams.model -> teamSync left `teams.model` holding
the reconciler's exports object as it stood mid-load — the empty one, since
`module.exports = {…}` replaces rather than fills. The symptom is not in the
new code: it is `teamSync.intervalSeconds is not a function` thrown out of
`syncStatus()`, the freshness banner on every public Team page.

Tests: 1160 server (+40), 53 bot (+21), 284 client (+21). Swagger, routes
manifest and guards regenerated; the guard shape of the four new routes is
byte-identical to the existing admin-only ones.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-18 23:49:28 -05:00

257 lines
9.2 KiB
JavaScript

// ── The operator's voice controls ──────────────────────────────────────────
//
// TEAMS.md §7.3, phase 9. Five `settings` keys, in their own file for the reason
// `teamForumSettings` is: two of them are not ordinary keys. `teams_voice_enabled`
// has a server-side precondition (the bot must actually be able to manage channels
// and roles — §7.3 assumed it could and the tree has never checked), and
// `teams_voice_category_ref` is written by the SERVER after the bot reports what
// it created, not by the admin who is looking at the form.
//
// teams_voice_enabled '0' | '1' default '0' — off
// teams_voice_min_members 1 … 10000 default 5
// teams_voice_grace_days 0 … 90 default 7
// teams_voice_category_ref a channel id absent until the bot makes one
// teams_voice_staff_roles CSV of role ids empty by default
//
// **Every read fails closed**, the same bargain the forum settings take: a DB
// fault reports voice off, which costs a pass that does nothing and is repeated
// fifteen minutes later. Failing open would mean creating guild structure on the
// strength of a query that did not answer.
//
// **`teams_voice_staff_roles` exists because "the staff role" does not.** §7.3
// grants the staff role an overwrite on every Team channel; this codebase has no
// staff-role concept at all — `guild_config` knows a news channel, a modlog
// channel, an autorole and a filter allowlist, and none of them means "staff".
// Guild administrators bypass channel overwrites anyway, so what is actually
// missing is a way to let NON-admin staff in, and only the operator can say which
// of their Discord roles those are. Empty is a legitimate and common answer.
const settingsDb = require('../settings/settings.db')
const ENABLED_KEY = 'teams_voice_enabled'
const MIN_MEMBERS_KEY = 'teams_voice_min_members'
const GRACE_DAYS_KEY = 'teams_voice_grace_days'
const CATEGORY_KEY = 'teams_voice_category_ref'
const STAFF_ROLES_KEY = 'teams_voice_staff_roles'
const MIN_MEMBERS_DEFAULT = 5
const MIN_MEMBERS_MAX = 10000
const GRACE_DAYS_DEFAULT = 7
const GRACE_DAYS_MAX = 90
// Discord's guild-wide role cap. It is the ceiling on how many Teams can have
// voice at all, and it is here rather than in the bot because the admin panel has
// to be able to say "you are at 231 of 250" BEFORE a create fails — §7.3's error
// state per Team is a diagnosis, not a warning.
//
// The number is Discord's and core cannot read it; a guild that gets a different
// one is a guild where this warns early, which is the harmless direction.
const ROLE_CAP = 250
// The same shape `teamIntegration.model` validates a channel with. Core treats
// every Discord id as opaque and only checks it could be one.
const SNOWFLAKE_RE = /^[0-9]{5,32}$/
/** Is voice provisioning switched on? Fail closed. */
async function enabled() {
try {
return String(await settingsDb.get(ENABLED_KEY)) === '1'
} catch {
return false
}
}
/**
* The membership threshold, counting every active member (org lead, 2026-08-18).
*
* Fails closed to the DEFAULT rather than to zero, unlike the forum's edit window:
* zero here would mean "provision every Team including the one-person ones", which
* is the expensive direction against a 250-role cap. The default is the
* conservative answer, not the permissive one.
*/
async function minMembers() {
try {
const raw = await settingsDb.get(MIN_MEMBERS_KEY)
if (raw == null || raw === '') return MIN_MEMBERS_DEFAULT
const n = Number(raw)
if (!Number.isFinite(n) || n < 1 || n > MIN_MEMBERS_MAX) return MIN_MEMBERS_DEFAULT
return Math.floor(n)
} catch {
return MIN_MEMBERS_DEFAULT
}
}
/**
* How long a Team keeps its channel after it stops qualifying (§7.3).
*
* `0` is legitimate and means "remove on the next pass" — an operator who would
* rather not have stale channels lying about. A DB fault reports the default, so a
* transient error can never turn the window off and delete something early; the
* grace window's whole job is to not act in a hurry.
*/
async function graceDays() {
try {
const raw = await settingsDb.get(GRACE_DAYS_KEY)
if (raw == null || raw === '') return GRACE_DAYS_DEFAULT
const n = Number(raw)
if (!Number.isFinite(n) || n < 0 || n > GRACE_DAYS_MAX) return GRACE_DAYS_DEFAULT
return Math.floor(n)
} catch {
return GRACE_DAYS_DEFAULT
}
}
/**
* The parent category every Team channel is created under, or null.
*
* Not an admin field. The bot creates the category on the first pass that needs
* one and reports the id back; the server stores it here so the next pass reuses
* it instead of making a second. An operator who wants a different category
* deletes this value (or the category) and the next pass makes a fresh one — which
* is why it is exposed read-only in the panel with a clear button rather than as a
* text input somebody could point at a channel that is not a category.
*/
async function categoryRef() {
try {
const value = await settingsDb.get(CATEGORY_KEY)
const text = String(value || '').trim()
return SNOWFLAKE_RE.test(text) ? text : null
} catch {
return null
}
}
async function setCategoryRef(value, actorId = null) {
const text = String(value || '').trim()
if (text && !SNOWFLAKE_RE.test(text)) throw new Error('category ref must be a numeric channel id')
return settingsDb.set(CATEGORY_KEY, text || null, actorId)
}
/**
* The roles that see every Team voice channel, in addition to that Team's own.
*
* Stored as CSV for the same reason `filter_allow_roles` is — `settings.value` is
* a VARCHAR and a JSON array in it buys nothing when the elements are numeric ids.
* Unreadable entries are DROPPED rather than rejected on read: a hand-edited row
* with one bad id should cost that id, not every staff grant on the deployment.
*/
async function staffRoles() {
try {
const raw = await settingsDb.get(STAFF_ROLES_KEY)
return parseRoles(raw)
} catch {
return []
}
}
function parseRoles(raw) {
return String(raw || '')
.split(',')
.map((part) => part.trim())
.filter((part) => SNOWFLAKE_RE.test(part))
}
/**
* Validate an operator-supplied staff-role list on the way IN, where a typo can
* still be reported to the person who made it.
*
* Rejected rather than filtered, the same call the bridge's event list makes: a
* silently-dropped id is a settings screen that shows you saved something you did
* not, and a role that was supposed to see every Team channel and does not is a
* failure nobody would think to look for.
*/
function normaliseStaffRoles(input) {
const parts = Array.isArray(input)
? input
: String(input == null ? '' : input).split(',')
const seen = []
for (const part of parts) {
const id = String(part || '').trim()
if (!id) continue
if (!SNOWFLAKE_RE.test(id)) {
const err = new Error(`not a role id: ${id}`)
err.status = 400
throw err
}
if (!seen.includes(id)) seen.push(id)
}
return seen
}
/** Everything the reconciler and the admin panel both need, in one read. */
async function all() {
const [on, min, grace, category, staff] = await Promise.all([
enabled(), minMembers(), graceDays(), categoryRef(), staffRoles(),
])
return {
enabled: on,
minMembers: min,
graceDays: grace,
categoryRef: category,
staffRoles: staff,
roleCap: ROLE_CAP,
}
}
/**
* Persist an admin's save. Returns the settings as they now read, so the panel
* renders what was stored rather than what was typed.
*
* The enable PRECONDITION is not here: it needs the bot, and a settings module
* that reached across to another process to validate a write would be impossible
* to test and surprising to read. The controller asks the bot and refuses, in the
* same shape §7.2's acknowledgement refuses — 422 before the write, never a quiet
* failure after it.
*/
async function save({ enabled: on, minMembers: min, graceDays: grace, staffRoles: staff }, actorId = null) {
const next = {}
if (on !== undefined) next[ENABLED_KEY] = on ? '1' : '0'
if (min !== undefined) {
const n = Number(min)
if (!Number.isInteger(n) || n < 1 || n > MIN_MEMBERS_MAX) {
const err = new Error(`minimum members must be between 1 and ${MIN_MEMBERS_MAX}`)
err.status = 400
throw err
}
next[MIN_MEMBERS_KEY] = String(n)
}
if (grace !== undefined) {
const n = Number(grace)
if (!Number.isInteger(n) || n < 0 || n > GRACE_DAYS_MAX) {
const err = new Error(`the grace window must be between 0 and ${GRACE_DAYS_MAX} days`)
err.status = 400
throw err
}
next[GRACE_DAYS_KEY] = String(n)
}
if (staff !== undefined) next[STAFF_ROLES_KEY] = normaliseStaffRoles(staff).join(',')
for (const [key, value] of Object.entries(next)) {
// eslint-disable-next-line no-await-in-loop
await settingsDb.set(key, value, actorId)
}
return all()
}
module.exports = {
ENABLED_KEY,
MIN_MEMBERS_KEY,
GRACE_DAYS_KEY,
CATEGORY_KEY,
STAFF_ROLES_KEY,
MIN_MEMBERS_DEFAULT,
GRACE_DAYS_DEFAULT,
ROLE_CAP,
enabled,
minMembers,
graceDays,
categoryRef,
setCategoryRef,
staffRoles,
parseRoles,
normaliseStaffRoles,
all,
save,
}