feat: the module skeleton and every bundle seam
module-rust, id 'rust', built from the Integration Kit's template. Phase 1's job
is the kit's own argument: get every seam working at once with almost nothing in
them, so that afterwards you break exactly one at a time.
What is here:
* /rust on all three tiers, because the loader holds module.json's mounts against
what is registered in BOTH directions -- so the declaration and the
registration land together or not at all. The player tier is honestly thin: it
answers the server list on the authenticated tier, delegating to the same model
the public tier uses so the two cannot drift while they are meant to be the
same. It is the address the app will call, registered now rather than moved
later.
* Two tables. rust_servers is configuration an operator writes; rust_server_state
is what a sidecar reported. Separate tables because they have different
writers, lifetimes and audiences -- and because purging observed state while
keeping the configuration is a thing an operator will want.
* Per-server sidecar tokens through ctx.secretBox, write-only in the API. The
admin list reports hasToken and never the credential, and an empty token on a
save leaves the stored one alone -- a form that posts its own blank field would
otherwise erase a credential every time somebody renamed a server.
* A real sidecar client. It never throws: every call answers {ok, status, data},
and the status is what tells a wrong URL from a wrong token from a mismatched
protocol -- all three present as 'the site says my server is offline' and each
has a different fix.
* The five guards, green: check:imports, check:swagger, check:externals, and both
suites.
What is deliberately NOT registered: the Team provider, triggers, audiences,
engagement seeds, notification streams, the four event catalogues, and the two
extension slots. Each arrives with the phase that has something real to put in
it, and a test asserts their absence so that removing it is deliberate. A
declared trigger nothing emits and a declared slot nothing fills are both
surfaces an operator can configure and then wait on, which is worse than an
absent one because the absence is visible.
Two corrections to the kit's template, both feedback for a later phase:
* registration.test.js read one page BY NAME to check declared slots are
rendered, so a module declaring none dies on ENOENT before reaching the loop
that would have been empty. It now scans every file under src/routes.
* test/_fakes.js supplied validator: {}. An admin router that builds validation
chains at file scope cannot be required with that, so the fake holds the real
express-validator -- for the same reason it holds a real express Router.
The kit was right about noGameConnection.test.js: its header predicts that a
module adding a sidecar client will see the check go red, names sidecarClient.js
as the file to allow, and says narrow it rather than delete it. That is exactly
what happened on the first run, and the fix was the one line the header names.
Installed into a real core and verified: the module reaches 'started', publishes
its capability, serves its chunk, and renders a server whose server.hello
originated in a live Rust server.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016wDDVXWMDz82WqE1i969r4
This commit is contained in:
154
server/test/_fakes.js
Normal file
154
server/test/_fakes.js
Normal file
@@ -0,0 +1,154 @@
|
||||
// ── Test doubles for what core hands the module ───────────────────────────
|
||||
//
|
||||
// Your server half is testable WITHOUT core, and that is not a convenience — it
|
||||
// is the contract holding. Everything a module may touch arrives on `ctx`
|
||||
// (MODULE_API.md §2.3), so a `ctx` this file can build is a complete statement of
|
||||
// what your module depends on. **If a test ever needs something that is not here,
|
||||
// either your module reached past the boundary or §2.3 needs a new member.** Both
|
||||
// are worth stopping for.
|
||||
//
|
||||
// The fake mirrors §2.3 member for member — including the freezing, so a module
|
||||
// that assigns to `ctx.something` fails here the way it would in core.
|
||||
//
|
||||
// This file lives under `test/`, which `checkImports.js` treats as not-shipped —
|
||||
// which is why it may `require('express')` when the module's own routers may not.
|
||||
// It builds a REAL express Router on purpose: a fake Router would only ever test
|
||||
// the fake.
|
||||
|
||||
const express = require('express')
|
||||
const expressValidator = require('express-validator')
|
||||
|
||||
/** Records every call, so a test can assert what the module asked for. */
|
||||
function spy(returns) {
|
||||
const fn = (...args) => {
|
||||
fn.calls.push(args)
|
||||
return typeof returns === 'function' ? returns(...args) : returns
|
||||
}
|
||||
fn.calls = []
|
||||
return fn
|
||||
}
|
||||
|
||||
function fakeLog() {
|
||||
return { error: spy(), warn: spy(), info: spy(), debug: spy() }
|
||||
}
|
||||
|
||||
function fakeCtx(overrides = {}) {
|
||||
// `freeze: false` is a test seam for a suite that wants to adjust the ctx it
|
||||
// installed. Core always freezes; the unfrozen variant is never a claim about
|
||||
// what a module is handed in production.
|
||||
const { freeze = true, ...rest } = overrides
|
||||
const logs = []
|
||||
const ctx = {
|
||||
moduleId: 'rust',
|
||||
paths: { moduleRoot: require('path').resolve(__dirname, '..', '..') },
|
||||
express,
|
||||
// The REAL express-validator, for the same reason express is real: the admin
|
||||
// router builds its validation chains at file scope, so `{}` here is not
|
||||
// something that file can even be required with.
|
||||
validator: expressValidator,
|
||||
db: { query: spy(Promise.resolve([])), pool: {} },
|
||||
log: (namespace) => {
|
||||
const log = fakeLog()
|
||||
logs.push({ namespace, log })
|
||||
return log
|
||||
},
|
||||
auth: { getUserFromRequest: spy(null) },
|
||||
// The engagement seam (§2.3). One method, recording, because that is the
|
||||
// whole of what a module may do with it: fire a declared event and stop.
|
||||
// Core's own emit is fire-and-forget and returns nothing, so this does too —
|
||||
// a fake that returned a receipt would invite a module to wait on one.
|
||||
// `reconcile` joined it at 1.10.0 — the ONE thing the event contract adds to
|
||||
// `ctx`, because an action is called BY core and is handed what it needs in
|
||||
// the envelope. Only the module knows when the game restarted, so only the
|
||||
// module can ask for the sweep.
|
||||
events: { emit: spy(undefined), reconcile: spy(undefined) },
|
||||
// A REVERSIBLE fake, not a recording one. Core's box is AES-256-GCM keyed by
|
||||
// the deployment's SECRET_ENC_KEY; what a test needs from it is that
|
||||
// `decrypt(encrypt(x)) === x`, because the bug this module could have is a
|
||||
// token stored under one shape and read under another. A spy returning a
|
||||
// constant would pass while proving nothing, and the tag makes an accidental
|
||||
// plaintext leak visible in an assertion.
|
||||
secretBox: {
|
||||
encrypt: (s) => `enc:${s}`,
|
||||
decrypt: (s) => {
|
||||
if (typeof s !== 'string' || !s.startsWith('enc:')) throw new Error('not encrypted by this box')
|
||||
return s.slice(4)
|
||||
},
|
||||
},
|
||||
activity: { log: spy(Promise.resolve()) },
|
||||
middleware: {
|
||||
requireAuth: (req, res, next) => next(),
|
||||
requireRole: () => (req, res, next) => next(),
|
||||
siteMode: (req, res, next) => next(),
|
||||
validate: (req, res, next) => next(),
|
||||
noindex: (req, res, next) => next(),
|
||||
// The factory returns a pass-through rather than a real limiter: a test
|
||||
// that tripped a rate limit would be a test whose result depended on how
|
||||
// many times the suite had run.
|
||||
rateLimit: (options) => Object.assign((req, res, next) => next(), { options }),
|
||||
accountChangeLimiter: (req, res, next) => next(),
|
||||
},
|
||||
site: { baseUrl: 'http://localhost:5173' },
|
||||
...rest,
|
||||
}
|
||||
// Non-enumerable, and that is not tidiness. Core freezes every object value on
|
||||
// `ctx` one level deep, so an enumerable recorder hung off it would be frozen
|
||||
// by the loop below and every `log.info` would throw on push. Keeping it out of
|
||||
// the enumeration also makes the fake more faithful: a module iterating `ctx`
|
||||
// sees §2.3's members and nothing a test put there.
|
||||
Object.defineProperty(ctx, 'logs', { value: logs, enumerable: false })
|
||||
if (!freeze) return ctx
|
||||
for (const value of Object.values(ctx)) {
|
||||
if (value && typeof value === 'object') Object.freeze(value)
|
||||
}
|
||||
return Object.freeze(ctx)
|
||||
}
|
||||
|
||||
/**
|
||||
* The registration api, recording rather than mounting.
|
||||
*
|
||||
* Copies core's `once()` rule (§2.4: "calling twice is an error"), so a module
|
||||
* that registers the same thing twice fails in its own suite rather than first on
|
||||
* an operator's install.
|
||||
*/
|
||||
function fakeApi() {
|
||||
const record = {
|
||||
routes: null, extensions: [], streams: null, legs: [], hooks: {}, teamProvider: null,
|
||||
triggers: null, audiences: null, engagementSeeds: null,
|
||||
eventBudgets: null, eventOptionSources: null, eventLeases: null, eventActions: null,
|
||||
}
|
||||
const called = new Set()
|
||||
const once = (name) => {
|
||||
if (called.has(name)) throw new Error(`${name}() called twice`)
|
||||
called.add(name)
|
||||
}
|
||||
const api = {
|
||||
registerRoutes(mounts) { once('registerRoutes'); record.routes = mounts },
|
||||
registerExtension(slot, router) { record.extensions.push({ slot, router }) },
|
||||
registerNotificationStreams(streams) { once('registerNotificationStreams'); record.streams = streams },
|
||||
registerAnnounceLeg(leg) { record.legs.push(leg) },
|
||||
registerPostHook(hook) { once('registerPostHook'); record.hooks.post = hook },
|
||||
// `once` here is not the general rule restated — it is a DIFFERENT rule that
|
||||
// happens to look the same. The others may not be called twice by ONE module;
|
||||
// this one holds a single value across the whole deployment, so a second
|
||||
// module registering a provider collides with the first. A fake cannot see
|
||||
// the second module, and asserting the half it can see is still worth doing.
|
||||
registerTeamProvider(provider) { once('registerTeamProvider'); record.teamProvider = provider },
|
||||
registerEventTriggers(triggers) { once('registerEventTriggers'); record.triggers = triggers },
|
||||
registerAudiences(audiences) { once('registerAudiences'); record.audiences = audiences },
|
||||
registerEngagementSeeds(seeds) { once('registerEngagementSeeds'); record.engagementSeeds = seeds },
|
||||
// The event contract (1.10.0). `once` on all four: a batch is a module's
|
||||
// COMPLETE statement about what it declares, so a second call is a module
|
||||
// changing its mind halfway through `register()` rather than adding to it.
|
||||
registerEventBudgets(budgets) { once('registerEventBudgets'); record.eventBudgets = budgets },
|
||||
registerEventOptionSources(sources) { once('registerEventOptionSources'); record.eventOptionSources = sources },
|
||||
registerEventLeases(leases) { once('registerEventLeases'); record.eventLeases = leases },
|
||||
registerEventActions(actions) { once('registerEventActions'); record.eventActions = actions },
|
||||
onBoot(fn) { once('onBoot'); record.hooks.onBoot = fn },
|
||||
onShutdown(fn) { once('onShutdown'); record.hooks.onShutdown = fn },
|
||||
}
|
||||
api.record = record
|
||||
return api
|
||||
}
|
||||
|
||||
module.exports = { fakeCtx, fakeApi, spy }
|
||||
149
server/test/checkImports.test.js
Normal file
149
server/test/checkImports.test.js
Normal file
@@ -0,0 +1,149 @@
|
||||
// The boundary check, checked.
|
||||
//
|
||||
// `scripts/checkImports.js` is the acceptance test for the whole module contract
|
||||
// (MODULE_API.md §5.1), and a check that has never been shown to fail is a check
|
||||
// nobody knows the state of. These point it at fixtures that break each rule and
|
||||
// assert it says so — and at prose that merely *describes* breaking them, which
|
||||
// is what it got wrong the first time it was run.
|
||||
//
|
||||
// **Every fixture is a template literal, and that is load-bearing.** The scanner
|
||||
// reads the files in this directory too, so an ordinary quoted string holding
|
||||
// `require('../../x')` would make this file fail the very check it is testing.
|
||||
// Templates are blanked by the stripper for exactly this class of text: source
|
||||
// being composed as data is not source being imported.
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const fs = require('node:fs')
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
|
||||
const { scan, stripCommentsAndTemplates, SERVER_ROOT, MODULE_ROOT } = require('../scripts/checkImports')
|
||||
|
||||
/** Write `files` into a throwaway module tree and scan it. */
|
||||
function scanFixture(files, { dev = new Set() } = {}) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'module-tpl-'))
|
||||
const src = path.join(root, 'server')
|
||||
for (const [name, source] of Object.entries(files)) {
|
||||
const file = path.join(src, name)
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true })
|
||||
fs.writeFileSync(file, source)
|
||||
}
|
||||
try {
|
||||
return scan(src, root, { shipped: (f) => !f.startsWith(path.join(src, 'test') + path.sep), dev })
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
test('the real server half is clean', () => {
|
||||
assert.deepStrictEqual(scan(SERVER_ROOT, MODULE_ROOT), [])
|
||||
})
|
||||
|
||||
test('catches a relative path that escapes the module root', () => {
|
||||
const found = scanFixture({ 'a.js': `require('../../server/src/utils/db')` })
|
||||
assert.strictEqual(found.length, 1)
|
||||
assert.strictEqual(found[0].why, 'escapes the module root')
|
||||
})
|
||||
|
||||
test('allows a relative path that stays inside it, however deep', () => {
|
||||
assert.deepStrictEqual(
|
||||
scanFixture({ 'deep/nested/a.js': `require('../../../module.json')` }),
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test('catches an absolute path', () => {
|
||||
const found = scanFixture({ 'a.js': `require('/etc/passwd')` })
|
||||
assert.strictEqual(found[0].why, 'absolute path')
|
||||
})
|
||||
|
||||
test('catches a bare specifier in shipped code, even a devDependency', () => {
|
||||
// The rule that makes the boundary real: express arrives on ctx. A shipped
|
||||
// file requiring it would fail on a real install, because a module lives
|
||||
// outside core's server/ and never reaches core's node_modules.
|
||||
const found = scanFixture({ 'a.js': `const express = require('express')` }, { dev: new Set(['express']) })
|
||||
assert.strictEqual(found.length, 1)
|
||||
assert.match(found[0].why, /should this come from ctx/)
|
||||
})
|
||||
|
||||
test('allows a devDependency in test code, which never runs inside core', () => {
|
||||
assert.deepStrictEqual(
|
||||
scanFixture({ 'test/a.js': `const express = require('express')` }, { dev: new Set(['express']) }),
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test('allows node builtins anywhere, with or without the node: prefix', () => {
|
||||
assert.deepStrictEqual(
|
||||
scanFixture({ 'a.js': `require('path'); require('node:fs'); import crypto from 'node:crypto'` }),
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test('allows node:test, which older Node versions omit from builtinModules', () => {
|
||||
// The first CI run failed on exactly this and on nothing else: `builtinModules`
|
||||
// omits `test` on Node 20 and includes it on Node 24, so every test file in
|
||||
// this suite was reported as breaking the module boundary. The check asks
|
||||
// Node (`isBuiltin`) rather than rebuilding the list, and treats the `node:`
|
||||
// prefix as sufficient on its own — a prefixed specifier can never resolve to
|
||||
// a package, whatever the running version enumerates.
|
||||
assert.deepStrictEqual(
|
||||
scanFixture({ 'a.js': `require('node:test'); require('node:test/reporters')` }),
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test('catches ESM and dynamic forms, not only require()', () => {
|
||||
const found = scanFixture({
|
||||
'a.js': [`import db from '../../core/db.js'`, `const x = await import('../../core/other.js')`].join('\n'),
|
||||
})
|
||||
assert.strictEqual(found.length, 2)
|
||||
})
|
||||
|
||||
test('ignores a violation that is only DESCRIBED in a comment', () => {
|
||||
// The first run of this check failed on its own documentation, and on
|
||||
// index.js's comment explaining why the module must never require('express').
|
||||
// Prose about the rule must not trip the rule.
|
||||
assert.deepStrictEqual(
|
||||
scanFixture({
|
||||
'a.js': [
|
||||
`// Never write require("../../server/src/utils/db") - it escapes the module root.`,
|
||||
`/* Nor import express from "express": core hands it over on ctx. */`,
|
||||
`const path = require('path')`,
|
||||
].join('\n'),
|
||||
}),
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test('ignores a specifier-shaped string inside a template literal', () => {
|
||||
assert.deepStrictEqual(
|
||||
scanFixture({ 'a.js': ['const sql = ', '`SELECT 1 -- require("../../x")`'].join('') }),
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test('a comment opener inside a string does not swallow the rest of the file', () => {
|
||||
// The reason this is a character walk and not a regexp: a URL in a string
|
||||
// contains `//`, and treating that as a comment would blank everything after
|
||||
// it — turning the check into one that silently passes.
|
||||
const found = scanFixture({
|
||||
'a.js': [`const url = 'https://example.com/x'`, `require('../../escaped')`].join('\n'),
|
||||
})
|
||||
assert.strictEqual(found.length, 1, 'the specifier after a URL string was missed')
|
||||
})
|
||||
|
||||
test('a quote inside a comment does not swallow the rest of the file', () => {
|
||||
const found = scanFixture({
|
||||
'a.js': [`// don't do this`, `require('../../escaped')`].join('\n'),
|
||||
})
|
||||
assert.strictEqual(found.length, 1)
|
||||
})
|
||||
|
||||
test('stripping preserves line numbers', () => {
|
||||
// Blanked rather than removed, so anything that later reports a line still
|
||||
// reports the right one.
|
||||
const src = ['/* a', 'b', 'c */', `require("x")`, ''].join('\n')
|
||||
assert.strictEqual(stripCommentsAndTemplates(src).split('\n').length, src.split('\n').length)
|
||||
})
|
||||
150
server/test/entry.test.js
Normal file
150
server/test/entry.test.js
Normal file
@@ -0,0 +1,150 @@
|
||||
// ── The registration handshake ────────────────────────────────────────────
|
||||
//
|
||||
// The one suite every module should have, whatever else it does. Core validates
|
||||
// all of this at boot and refuses to mount a module that fails — so testing it
|
||||
// here is the difference between finding out in half a second and finding out on
|
||||
// an operator's install.
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
|
||||
const { fakeCtx, fakeApi } = require('./_fakes')
|
||||
const manifest = require('../../module.json')
|
||||
|
||||
/** A fresh registration. `core.js` holds a module-level `ctx`, so reset it. */
|
||||
function register(ctx = fakeCtx()) {
|
||||
require('../core')._reset()
|
||||
const api = fakeApi()
|
||||
require('../index')(ctx, api)
|
||||
return { api, ctx }
|
||||
}
|
||||
|
||||
test('registers exactly the mounts module.json declares', () => {
|
||||
const { api } = register()
|
||||
|
||||
// Core compares these two and rejects a mismatch in EITHER direction: a prefix
|
||||
// declared and never registered is as fatal as a route registered and never
|
||||
// declared. Asserting against the manifest rather than against a literal is
|
||||
// what keeps the test true after a prefix is added.
|
||||
assert.deepStrictEqual(
|
||||
Object.keys(api.record.routes).sort(),
|
||||
Object.keys(manifest.mounts).sort(),
|
||||
)
|
||||
for (const [tier, prefixes] of Object.entries(manifest.mounts)) {
|
||||
assert.deepStrictEqual(Object.keys(api.record.routes[tier]).sort(), [...prefixes].sort())
|
||||
}
|
||||
})
|
||||
|
||||
test('all three tiers are mounted (R14)', () => {
|
||||
const { api } = register()
|
||||
|
||||
// Not the assertion above restated. That one says the manifest and the code
|
||||
// agree; this one says WHICH answer they agree on, so that deleting a tier from
|
||||
// both halves at once still fails. R14 puts this module on all three from the
|
||||
// start precisely so that a later phase adding a player surface does not have
|
||||
// to move an address clients are already calling.
|
||||
assert.deepStrictEqual(Object.keys(api.record.routes).sort(), ['admin', 'player', 'public'])
|
||||
for (const tier of ['admin', 'player', 'public']) {
|
||||
assert.deepStrictEqual(Object.keys(api.record.routes[tier]), ['/rust'])
|
||||
}
|
||||
})
|
||||
|
||||
test('every registered mount is a real express router', () => {
|
||||
const { api } = register()
|
||||
for (const byPrefix of Object.values(api.record.routes)) {
|
||||
for (const [prefix, router] of Object.entries(byPrefix)) {
|
||||
assert.strictEqual(typeof router, 'function', `${prefix} is not a router`)
|
||||
assert.ok(router.stack, `${prefix} has no middleware stack`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('prefixes are one segment, lowercase, no parameters', () => {
|
||||
// §2.4's rule, restated where a typo is cheap to find. Core enforces it, and a
|
||||
// module that fails it does not mount at all.
|
||||
for (const prefixes of Object.values(manifest.mounts)) {
|
||||
for (const prefix of prefixes) {
|
||||
assert.match(prefix, /^\/[a-z0-9][a-z0-9-]*$/, `illegal mount prefix ${prefix}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('registration touches no database and awaits nothing', () => {
|
||||
const ctx = fakeCtx()
|
||||
register(ctx)
|
||||
|
||||
// §2.2's first rule. Core requires `app.js` with the pool pointed at a dead
|
||||
// port in two build tools, so a query here would hang both — and the symptom is
|
||||
// a build that never finishes rather than an error naming this module.
|
||||
assert.deepStrictEqual(ctx.db.query.calls, [])
|
||||
})
|
||||
|
||||
test('registers both lifecycle hooks', () => {
|
||||
const { api } = register()
|
||||
assert.strictEqual(typeof api.record.hooks.onBoot, 'function')
|
||||
assert.strictEqual(typeof api.record.hooks.onShutdown, 'function')
|
||||
})
|
||||
|
||||
test('the manifest declares what the loader requires', () => {
|
||||
assert.match(manifest.id, /^[a-z][a-z0-9-]{1,31}$/)
|
||||
assert.match(manifest.version, /^\d+\.\d+\.\d+/)
|
||||
assert.ok(manifest.coreApi, 'coreApi is required — it is the version check')
|
||||
// Declaring a schema without a purge is refused: a module that can create
|
||||
// tables and cannot drop them leaves an operator with orphaned data.
|
||||
if (manifest.schema) assert.ok(manifest.purge, 'a schema fragment requires a purge file')
|
||||
// The chunk must be in a SUBDIRECTORY — the directory it sits in is what core
|
||||
// serves, so an entry in the module root would publish the whole module.
|
||||
if (manifest.client) assert.ok(manifest.client.entry.includes('/'), 'client.entry must be in a subdirectory')
|
||||
})
|
||||
|
||||
test('the manifest declares no extension slot it does not fill', () => {
|
||||
const { api } = register()
|
||||
|
||||
// §11.3 of the plan reads `extensions` as "declared, and held against reality
|
||||
// by the loader". Only the first half is true: the loader checks that a named
|
||||
// slot EXISTS (`registries.hasSlot`) and never checks that the module went on
|
||||
// to fill it — `checkDeclared` covers `mounts` alone. So a declaration with
|
||||
// nothing behind it loads cleanly and means nothing, which is exactly why this
|
||||
// module does not write one until it has an extension to register.
|
||||
//
|
||||
// The other half of that correction: `admin.users.detail` is the ONLY server
|
||||
// slot core declares. `site.footer.status` is a CLIENT slot and is registered
|
||||
// from the chunk — naming it here would fail the load with
|
||||
// `unknown extension slot "site.footer.status"`.
|
||||
const declared = manifest.extensions || []
|
||||
const filled = api.record.extensions.map((e) => e.slot)
|
||||
assert.deepStrictEqual([...declared].sort(), [...filled].sort())
|
||||
})
|
||||
|
||||
test('nothing is registered that has nothing behind it yet', () => {
|
||||
const { api } = register()
|
||||
|
||||
// The phase-1 statement, written down so that removing it is deliberate. A
|
||||
// declared trigger nothing emits and a declared slot nothing fills are both
|
||||
// surfaces an operator can configure and then wait on — worse than an absent
|
||||
// one, because the absence is visible. Each of these arrives with the phase
|
||||
// that has something real to put in it, and this assertion is what that phase
|
||||
// deletes.
|
||||
assert.strictEqual(api.record.teamProvider, null)
|
||||
assert.strictEqual(api.record.triggers, null)
|
||||
assert.strictEqual(api.record.audiences, null)
|
||||
assert.strictEqual(api.record.engagementSeeds, null)
|
||||
assert.strictEqual(api.record.streams, null)
|
||||
assert.strictEqual(api.record.eventBudgets, null)
|
||||
assert.strictEqual(api.record.eventOptionSources, null)
|
||||
assert.strictEqual(api.record.eventLeases, null)
|
||||
assert.strictEqual(api.record.eventActions, null)
|
||||
})
|
||||
|
||||
test('the module’s protocol version agrees with the manifest it ships beside', () => {
|
||||
const sidecar = require('../sidecarClient')
|
||||
|
||||
// The wire version is declared in three repos — here, `PROTOCOL_VERSION` in
|
||||
// the sidecar, and `overlay.toml` in the plugin overlay — and nothing in one
|
||||
// repo can check the other two. What CAN be checked is that this repo says one
|
||||
// thing: the number the client sends is the number an operator sees on a
|
||||
// freshly created server row, so a bump that edits one and not the other
|
||||
// configures every new server against a version the client does not speak.
|
||||
assert.strictEqual(typeof sidecar.PROTOCOL_VERSION, 'number')
|
||||
assert.ok(sidecar.PROTOCOL_VERSION >= 1)
|
||||
})
|
||||
151
server/test/noGameConnection.test.js
Normal file
151
server/test/noGameConnection.test.js
Normal file
@@ -0,0 +1,151 @@
|
||||
// ── §2.7's last rule, given the CI it does not have ───────────────────────
|
||||
//
|
||||
// `book/02-website-module.md` is explicit that "the website process never opens a
|
||||
// connection to a game server" is the **one boundary rule with no CI behind it**:
|
||||
// an outbound socket is not statically detectable the way an internal `require`
|
||||
// is, so in general the rule is held up by review and by understanding it.
|
||||
//
|
||||
// True of the general case, and not a reason to check nothing. A module can state
|
||||
// a narrower, completely decidable property about **itself**, and this one says:
|
||||
// the shipped server half references no networking primitive at all. Everything
|
||||
// it knows arrives from its own tables, which its sidecar writes.
|
||||
//
|
||||
// Adopted from the kit's acceptance run (`docs/modules/kit-acceptance.md`), where
|
||||
// a reader building a Rust module wrote it unprompted after reading that the rule
|
||||
// had no CI — and observed that for Rust in particular, which ships RCON over
|
||||
// WebSocket, `new WebSocket(rconUrl)` in `boot.js` is about ten lines away.
|
||||
//
|
||||
// ── NARROWED, NOT DELETED ─────────────────────────────────────────────────
|
||||
//
|
||||
// This module has a real sidecar client, so the check is narrowed to allow that
|
||||
// one file and keeps the rest of the tree under the ban. Talking to *the sidecar*
|
||||
// over HTTP is the expected shape and is not what §2.7 forbids — the rule is
|
||||
// about the **game server**.
|
||||
//
|
||||
// const MAY_OPEN_SOCKETS = new Set(['sidecarClient.js'])
|
||||
//
|
||||
// What that buys is a test naming the *one* file allowed to reach the network —
|
||||
// exactly the file a reviewer should read closely, and exactly the place a
|
||||
// game-server URL would appear if the rule were ever broken. The temptation on a
|
||||
// red run here is to add a second name; the answer is almost always to move the
|
||||
// call into `sidecarClient.js` instead.
|
||||
//
|
||||
// It is worth saying what this does NOT prove. `sidecarClient.js` is exempt, so
|
||||
// nothing here stops it being pointed at a game server's own port — it would
|
||||
// take a URL an operator typed. The decidable half is that no OTHER file can
|
||||
// reach the network at all, which is what keeps the exempt file small enough to
|
||||
// read.
|
||||
//
|
||||
// Scope: SHIPPED code only. `test/` and `scripts/` never run inside core's process.
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const SERVER_ROOT = path.resolve(__dirname, '..')
|
||||
const NOT_SHIPPED = new Set(['test', 'scripts', 'node_modules', 'swagger'])
|
||||
|
||||
/**
|
||||
* The one shipped file allowed to reach the network. See the header.
|
||||
*
|
||||
* Kept as a set of BASENAMES rather than paths, so that moving the file does not
|
||||
* silently re-ban it — a rename is meant to be a conversation.
|
||||
*/
|
||||
const MAY_OPEN_SOCKETS = new Set(['sidecarClient.js'])
|
||||
|
||||
/** Every shipped `.js` file under `server/`. */
|
||||
function shippedFiles(dir = SERVER_ROOT, out = []) {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.isDirectory()) {
|
||||
if (dir === SERVER_ROOT && NOT_SHIPPED.has(entry.name)) continue
|
||||
if (entry.name === 'node_modules') continue
|
||||
shippedFiles(path.join(dir, entry.name), out)
|
||||
} else if (entry.isFile() && entry.name.endsWith('.js')) {
|
||||
out.push(path.join(dir, entry.name))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Blank comments, so prose ABOUT the rule does not trip the rule.
|
||||
*
|
||||
* This file is itself the proof that it is needed: the paragraphs above say
|
||||
* "WebSocket" several times. `scripts/checkImports.js` documents hitting exactly
|
||||
* this on its own documentation, and it is the third time in this project's
|
||||
* history that a boundary check has failed on the text explaining it.
|
||||
*
|
||||
* Blanked rather than deleted, so line numbers in a failure still point at the
|
||||
* right line.
|
||||
*/
|
||||
function stripComments(src) {
|
||||
return src
|
||||
.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '))
|
||||
.replace(/^[ \t]*\/\/.*$/gm, '')
|
||||
}
|
||||
|
||||
// Each is a way a Node process opens a socket. Matched as identifiers, so a
|
||||
// column named `websocket_url` inside a SQL string would not fire.
|
||||
const NETWORKING = [
|
||||
/\brequire\(\s*['"](?:node:)?(?:net|tls|dgram|http|https|http2)['"]\s*\)/,
|
||||
/\bfrom\s+['"](?:node:)?(?:net|tls|dgram|http|https|http2)['"]/,
|
||||
/\brequire\(\s*['"](?:ws|socket\.io-client|undici|axios|node-fetch|got)['"]\s*\)/,
|
||||
/\bnew\s+WebSocket\b/,
|
||||
/\bfetch\s*\(/,
|
||||
/\bXMLHttpRequest\b/,
|
||||
/\bEventSource\b/,
|
||||
]
|
||||
|
||||
test('no shipped file references a networking primitive (§2.7)', () => {
|
||||
const offenders = []
|
||||
for (const file of shippedFiles()) {
|
||||
if (MAY_OPEN_SOCKETS.has(path.basename(file))) continue
|
||||
const code = stripComments(fs.readFileSync(file, 'utf8'))
|
||||
for (const pattern of NETWORKING) {
|
||||
if (pattern.test(code)) {
|
||||
offenders.push(`${path.relative(SERVER_ROOT, file)} matches ${pattern}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepStrictEqual(
|
||||
offenders,
|
||||
[],
|
||||
'the website process must never open a connection to a game server. If this is ' +
|
||||
'your sidecar client, allow that one file rather than removing the check — see ' +
|
||||
`the header of this file.\n ${offenders.join('\n ')}`,
|
||||
)
|
||||
})
|
||||
|
||||
test('every name on the allowlist is a file that exists and is shipped', () => {
|
||||
// A stale allowlist entry is a silent hole: the file it exempted was renamed,
|
||||
// the ban no longer covers the new name either (because the old one is still
|
||||
// listed and nothing matches it), and the check goes on passing. Holding the
|
||||
// list against the tree is what stops an exemption outliving its reason.
|
||||
const shipped = new Set(shippedFiles().map((f) => path.basename(f)))
|
||||
for (const name of MAY_OPEN_SOCKETS) {
|
||||
assert.ok(shipped.has(name), `${name} is allowed to open sockets but is not a shipped file`)
|
||||
}
|
||||
})
|
||||
|
||||
test('the check can actually fail — it is pointed at a real violation', () => {
|
||||
// A check that has never been shown to fail is a check nobody knows the state
|
||||
// of. This is the game-server dial the rule exists to stop.
|
||||
const violation = "const socket = new WebSocket('ws://10.0.0.5:28016/' + rconPassword)"
|
||||
assert.ok(
|
||||
NETWORKING.some((p) => p.test(stripComments(violation))),
|
||||
'the guard would not have caught a direct game-server dial',
|
||||
)
|
||||
})
|
||||
|
||||
test('prose describing the rule does not trip it', () => {
|
||||
const prose = [
|
||||
'// A game shipping RCON over WebSocket means a module COULD write',
|
||||
"// const s = new WebSocket(url); require('net')",
|
||||
'// in about ten lines. It must not.',
|
||||
'const x = 1',
|
||||
].join('\n')
|
||||
for (const pattern of NETWORKING) {
|
||||
assert.ok(!pattern.test(stripComments(prose)), `${pattern} fired on a comment`)
|
||||
}
|
||||
})
|
||||
116
server/test/schema.test.js
Normal file
116
server/test/schema.test.js
Normal file
@@ -0,0 +1,116 @@
|
||||
// ── The schema fragment, checked against §2.6's rules ─────────────────────
|
||||
//
|
||||
// Core validates the fragment at LOAD time and refuses to mount a module that
|
||||
// breaks a rule — with no tables created and no routes served. That is the right
|
||||
// behaviour and a slow way to find a typo, so the same rules are checked here.
|
||||
//
|
||||
// **This is also the suite that catches a half-finished rename.** Change the id
|
||||
// in `module.json` and forget a table name, and the prefix assertion below fails
|
||||
// immediately rather than at an operator's first boot.
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const manifest = require('../../module.json')
|
||||
|
||||
const read = (rel) => fs.readFileSync(path.resolve(__dirname, '..', '..', rel), 'utf8')
|
||||
|
||||
/**
|
||||
* Split a SQL file into statements the way core does.
|
||||
*
|
||||
* Core's own splitter is shared code (`utils/sqlStatements.js`) used by both the
|
||||
* loader and the schema replay — this is a small stand-in for a test, and it is
|
||||
* deliberately simple because the fragment it reads is deliberately simple. If
|
||||
* your schema grows a stored procedure or a string containing a semicolon, stop
|
||||
* trusting this and read the fragment a different way.
|
||||
*/
|
||||
function statements(sql) {
|
||||
return sql
|
||||
.split('\n')
|
||||
.filter((line) => !line.trim().startsWith('--'))
|
||||
.join('\n')
|
||||
.split(';')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
const schema = statements(read(manifest.schema))
|
||||
const purge = statements(read(manifest.purge))
|
||||
|
||||
// The allowlist core enforces. Note it is an ALLOWLIST and not a `DROP` denylist:
|
||||
// this file replays on every boot, so TRUNCATE or DELETE would empty a table on
|
||||
// every restart — which no denylist naming only DROP would have caught.
|
||||
const ALLOWED_VERBS = ['CREATE', 'ALTER', 'INSERT', 'UPDATE']
|
||||
|
||||
test('every statement starts with an allowed verb', () => {
|
||||
for (const statement of schema) {
|
||||
const verb = statement.split(/\s+/)[0].toUpperCase()
|
||||
assert.ok(ALLOWED_VERBS.includes(verb), `"${verb}" is not one of ${ALLOWED_VERBS.join(', ')}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('every table is prefixed with the module id', () => {
|
||||
for (const statement of schema) {
|
||||
const match = /^CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+`?([A-Za-z0-9_]+)`?/i.exec(statement)
|
||||
if (!match) continue
|
||||
assert.ok(
|
||||
match[1].startsWith(`${manifest.id}_`),
|
||||
`table "${match[1]}" is not prefixed "${manifest.id}_" — core will refuse to load this module`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('the fragment is idempotent — it replays on every boot', () => {
|
||||
for (const statement of schema) {
|
||||
if (/^CREATE\s+TABLE/i.test(statement)) {
|
||||
assert.match(statement, /IF\s+NOT\s+EXISTS/i, 'CREATE TABLE without IF NOT EXISTS')
|
||||
}
|
||||
if (/^ALTER\s+TABLE/i.test(statement) && /ADD\s+COLUMN/i.test(statement)) {
|
||||
assert.match(statement, /IF\s+NOT\s+EXISTS/i, 'ADD COLUMN without IF NOT EXISTS')
|
||||
}
|
||||
if (/^INSERT\s+INTO/i.test(statement)) {
|
||||
// A plain INSERT succeeds once and then fails the whole replay on the next
|
||||
// boot with a duplicate key — the classic "worked until I restarted it".
|
||||
assert.ok(
|
||||
/INSERT\s+IGNORE/i.test(statement) || /ON\s+DUPLICATE\s+KEY/i.test(statement),
|
||||
'INSERT must be IGNORE or carry ON DUPLICATE KEY — it runs again every boot',
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('purge drops every table the schema creates', () => {
|
||||
const created = schema
|
||||
.map((s) => /^CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+`?([A-Za-z0-9_]+)`?/i.exec(s))
|
||||
.filter(Boolean)
|
||||
.map((m) => m[1])
|
||||
const dropped = purge
|
||||
.map((s) => /^DROP\s+TABLE(?:\s+IF\s+EXISTS)?\s+`?([A-Za-z0-9_]+)`?/i.exec(s))
|
||||
.filter(Boolean)
|
||||
.map((m) => m[1])
|
||||
|
||||
for (const table of created) {
|
||||
assert.ok(dropped.includes(table), `${table} is created but never dropped — purge would orphan it`)
|
||||
}
|
||||
for (const table of dropped) {
|
||||
assert.ok(created.includes(table), `${table} is dropped but never created`)
|
||||
}
|
||||
})
|
||||
|
||||
test('purge drops in the reverse of creation order', () => {
|
||||
// With one table this proves nothing; with a parent and its children it is the
|
||||
// difference between a clean teardown and a purge that fails halfway, leaving
|
||||
// exactly the orphaned data it exists to remove.
|
||||
const created = schema
|
||||
.map((s) => /^CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+`?([A-Za-z0-9_]+)`?/i.exec(s))
|
||||
.filter(Boolean)
|
||||
.map((m) => m[1])
|
||||
const dropped = purge
|
||||
.map((s) => /^DROP\s+TABLE(?:\s+IF\s+EXISTS)?\s+`?([A-Za-z0-9_]+)`?/i.exec(s))
|
||||
.filter(Boolean)
|
||||
.map((m) => m[1])
|
||||
|
||||
assert.deepStrictEqual(dropped, [...created].reverse())
|
||||
})
|
||||
160
server/test/servers.test.js
Normal file
160
server/test/servers.test.js
Normal file
@@ -0,0 +1,160 @@
|
||||
// ── The servers model ─────────────────────────────────────────────────────
|
||||
//
|
||||
// No database and no express: the model takes rows and produces the shapes the
|
||||
// three tiers answer with, which is the whole reason the SQL lives in a separate
|
||||
// file from the logic.
|
||||
//
|
||||
// Two things here are worth more than the rest: **a token never leaves this
|
||||
// module**, and **a stale row cannot claim a server is up**.
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
|
||||
const { fakeCtx } = require('./_fakes')
|
||||
|
||||
function withCore(ctx = fakeCtx()) {
|
||||
require('../core')._reset()
|
||||
require('../core').init(ctx)
|
||||
return ctx
|
||||
}
|
||||
|
||||
const NOW = Date.parse('2026-09-15T12:00:00Z')
|
||||
|
||||
const serverRow = (over = {}) => ({
|
||||
id: 'main',
|
||||
name: 'Main · Vanilla',
|
||||
sidecarBaseUrl: 'http://10.0.0.5:8090',
|
||||
sidecarTokenEnc: 'enc:s3cret',
|
||||
protocol: 1,
|
||||
enabled: 1,
|
||||
sortOrder: 0,
|
||||
...over,
|
||||
})
|
||||
|
||||
const stateRow = (over = {}) => ({
|
||||
serverId: 'main',
|
||||
reachable: 1,
|
||||
online: 1,
|
||||
players: 42,
|
||||
maxPlayers: 100,
|
||||
hostname: 'Runic Gateway · Main',
|
||||
level: 'Procedural Map',
|
||||
seed: 1234,
|
||||
worldSize: 4000,
|
||||
bootId: 'boot-20260915T194502Z',
|
||||
protocol: 1,
|
||||
updatedAt: new Date(NOW - 10_000).toISOString(),
|
||||
...over,
|
||||
})
|
||||
|
||||
test('a fresh row reports what the server said', () => {
|
||||
withCore()
|
||||
const servers = require('../model/servers/servers.model')
|
||||
const shaped = servers.shapePublic(serverRow(), stateRow(), NOW)
|
||||
|
||||
assert.strictEqual(shaped.online, true)
|
||||
assert.strictEqual(shaped.players, 42)
|
||||
assert.strictEqual(shaped.stale, false)
|
||||
assert.strictEqual(shaped.worldSize, 4000)
|
||||
})
|
||||
|
||||
test('a stale row is reported offline, with no player count', () => {
|
||||
withCore()
|
||||
const servers = require('../model/servers/servers.model')
|
||||
|
||||
// The row says what was true when it was written and nothing has written it
|
||||
// since. Reporting its player count would put a number on a page that is
|
||||
// simply the last number anyone saw, with no way for a reader to tell.
|
||||
const old = stateRow({ updatedAt: new Date(NOW - servers.STALE_AFTER_MS - 1000).toISOString() })
|
||||
const shaped = servers.shapePublic(serverRow(), old, NOW)
|
||||
|
||||
assert.strictEqual(shaped.stale, true)
|
||||
assert.strictEqual(shaped.online, false)
|
||||
assert.strictEqual(shaped.players, 0)
|
||||
})
|
||||
|
||||
test('a server with no state row at all is stale rather than absent', () => {
|
||||
withCore()
|
||||
const servers = require('../model/servers/servers.model')
|
||||
|
||||
// A configured server nothing has polled yet. It belongs on the page — an
|
||||
// operator added it on purpose — and it must not claim to be online.
|
||||
const shaped = servers.shapePublic(serverRow(), undefined, NOW)
|
||||
|
||||
assert.strictEqual(shaped.id, 'main')
|
||||
assert.strictEqual(shaped.stale, true)
|
||||
assert.strictEqual(shaped.online, false)
|
||||
assert.strictEqual(shaped.updatedAt, null)
|
||||
})
|
||||
|
||||
test('the public shape carries nothing about the sidecar', () => {
|
||||
withCore()
|
||||
const servers = require('../model/servers/servers.model')
|
||||
const shaped = servers.shapePublic(serverRow(), stateRow(), NOW)
|
||||
|
||||
// Asserted over the WHOLE object rather than by naming the two fields that
|
||||
// would be worst: the failure this guards against is a field added later, by
|
||||
// someone who did not read this file, and an allowlist is the only assertion
|
||||
// that catches one.
|
||||
assert.deepStrictEqual(Object.keys(shaped).sort(), [
|
||||
'hostname', 'id', 'level', 'maxPlayers', 'name', 'online', 'players', 'seed', 'stale', 'updatedAt', 'worldSize',
|
||||
])
|
||||
})
|
||||
|
||||
test('the admin shape reports whether a token is stored, never the token', () => {
|
||||
withCore()
|
||||
const servers = require('../model/servers/servers.model')
|
||||
|
||||
// `listForAdmin` reads the database, so the shape is asserted through the piece
|
||||
// that does not: the rule is that `hasToken` is a boolean and no key anywhere
|
||||
// in the object holds the ciphertext or the plaintext.
|
||||
const row = serverRow()
|
||||
const shaped = {
|
||||
...servers.shapePublic(row, stateRow(), NOW),
|
||||
sidecarBaseUrl: row.sidecarBaseUrl,
|
||||
hasToken: Boolean(row.sidecarTokenEnc),
|
||||
}
|
||||
|
||||
assert.strictEqual(shaped.hasToken, true)
|
||||
const serialised = JSON.stringify(shaped)
|
||||
assert.ok(!serialised.includes('s3cret'), 'the plaintext token reached a response shape')
|
||||
assert.ok(!serialised.includes('enc:'), 'the stored ciphertext reached a response shape')
|
||||
})
|
||||
|
||||
test('a token round-trips through the box, and an empty one means “leave it alone”', () => {
|
||||
withCore()
|
||||
const servers = require('../model/servers/servers.model')
|
||||
|
||||
const enc = servers.encryptToken('s3cret')
|
||||
assert.notStrictEqual(enc, 's3cret')
|
||||
assert.strictEqual(servers.withToken(serverRow({ sidecarTokenEnc: enc })).token, 's3cret')
|
||||
|
||||
// All three spellings of "the operator did not type a new token". The admin
|
||||
// form can only ever show a blank field, so it posts one on every save that did
|
||||
// not intend to change the credential — and writing that through would erase
|
||||
// the token every time somebody renamed a server.
|
||||
assert.strictEqual(servers.encryptToken(''), null)
|
||||
assert.strictEqual(servers.encryptToken(null), null)
|
||||
assert.strictEqual(servers.encryptToken(undefined), null)
|
||||
})
|
||||
|
||||
test('a token that will not decrypt reports the server unconfigured rather than throwing', () => {
|
||||
const ctx = withCore()
|
||||
const servers = require('../model/servers/servers.model')
|
||||
|
||||
// The usual cause is a `SECRET_ENC_KEY` that changed. One server's unreadable
|
||||
// credential must not be able to fail the poll for the other five, and it must
|
||||
// not fail `onBoot` — which would make the whole module `startup_failed`.
|
||||
const shaped = servers.withToken(serverRow({ sidecarTokenEnc: 'not-encrypted-by-this-box' }))
|
||||
|
||||
assert.strictEqual(shaped.token, null)
|
||||
assert.strictEqual(shaped.baseUrl, 'http://10.0.0.5:8090')
|
||||
const errors = ctx.logs.flatMap((l) => l.log.error.calls)
|
||||
assert.strictEqual(errors.length, 1, 'the failure was swallowed without a word')
|
||||
})
|
||||
|
||||
test('a server with no token stored reads as having none', () => {
|
||||
withCore()
|
||||
const servers = require('../model/servers/servers.model')
|
||||
assert.strictEqual(servers.withToken(serverRow({ sidecarTokenEnc: null })).token, null)
|
||||
})
|
||||
Reference in New Issue
Block a user