Build a client module
Many clients get a system, not a website: their software is SHADE, the official modules they need and one module of their own, with a frontend in any framework on SHADE's accounts. This guide builds that module of their own from the first command to a server package. Sign-in, permissions, validation of what SHADE stores, rate limits, the audit log, the error log and privacy stay SHADE's; the module holds only what is specific to the client. Every step links to the part of Writing a module that has the details.
As the example, a bicycle repair shop: customers ask for a quote on the shop's site and follow their repairs in their account, the staff work through the repairs in the admin, and a weekly post on the site says what was repaired.
1. Start the repository
In the SHADE workspace (for SHADE's maintainers for now), with SHADE's
command shade-module
(Starting a module repository):
node shade/shade/module-sdk/bin/shade-module.mjs init repairs --out modules/repairs
init writes modules/repairs/ (a module that loads, validates and packages as it is) with a dependency on the
SDK from npm, in SHADE's range ("@shadestack/module-sdk": "^0.1.0-next.2" today), with no .npmrc. Inside the workspace, change it
to "workspace:^" so the module uses the SDK you are working on. Then:
# SHADE's .env
SHADE_DEV_MODULES=../modules/repairs
pnpm dev
and switch the module on under Modules. Give the repository to the client: it is theirs.
The module uses SHADE only through @shadestack/module-sdk. Its names are a promise: every one is in
the SDK's contract with the version that added it, none goes without a deprecation kept for at least a minor version,
and CHANGELOG.md in the SDK says what changed. Write shade: '^0.1.0' in the manifest: before SHADE 1.0 that means
0.1.x only; see The SHADE versions a module works with.
2. Its tables
The repairs are the module's own records, not content: tables in server/repairs.sql.ts, prefixed with the module's
name (Naming rules).
import { createdAt, id, teamMemberReference, accountReference } from '@shadestack/module-sdk/server'
import { pgTable, text } from 'drizzle-orm/pg-core'
export const repairsJobs = pgTable('repairs_jobs', {
id: id(),
customer: accountReference('customer_id').notNull(), // the account (a foreign key); the rows go with it
bike: text('bike').notNull(),
status: text('status').notNull().default('received'),
handledBy: teamMemberReference('handled_by'), // a team member; null when they are deleted
createdAt: createdAt()
})
pnpm db:generate writes the migration into the module's own migrations/; SHADE applies it on start, with a history
table of its own (Database). Content the site shows and editors edit, with drafts and
versions, is a collection instead (Collections from modules).
A table with a accountReference holds accounts' personal data: list it in a personalData source that finds and
erases it, or the module does not load (Personal data).
3. Permissions
The module's actions, declared once, granted to editors by default if you want, and checked first in every service (Permissions):
export const ACTIONS = { 'repairs.read': [], 'repairs.manage': [] } as const
declare module '@shadestack/module-sdk/shared' {
interface ActionRegistry { 'repairs.read': true, 'repairs.manage': true }
}
// in the manifest
permissions: { actions: ACTIONS, grants: { editor: ['repairs.read', 'repairs.manage'] } }
export async function setStatus(ctx: ServiceContext, id: string, input: unknown) {
assertCan(ctx.actor, 'repairs.manage')
const { status } = parseInput(StatusInput, input)
return ctx.db.transaction(async (tx) => {
const [job] = await tx.update(repairsJobs).set({ status }).where(eq(repairsJobs.id, id)).returning()
if (!job) throw notFound('Repair not found')
await recordAudit(tx, ctx, { action: 'repairs.manage', targetType: 'repair', targetId: id, summary: `Repair set to ${status}` })
return job
})
}
4. Routes
Thin: parse the input with a schema, call the service, return (Routes).
- Session routes (the default) serve the module's admin screens, at
/api/packages/repairs/…, with the editor's own rights. - A public route for the quote request, at
/api/v1/account/repairs/quote. Anyone on the internet can call it, so it must declare a rate limit, and its handler validates everything and keeps out spam itself:{ method: 'POST', path: '/quote', auth: 'public', rateLimit: { limit: 5, windowMs: 60_000, key: 'ip' }, doc: { summary: 'Asks for a quote', body: QuoteInput }, handler: (ctx, request) => askQuote(ctx, request.body) } - Account routes for "my repairs": the account arrives as
request.account, andownedByreads only their rows (Account routes):{ method: 'GET', path: '/mine', auth: 'account', handler: (ctx, request) => ctx.db.select().from(repairsJobs).where(ownedBy(repairsJobs.customer, request.account)) }
An accountGETroute changes nothing; every change is aPOST,PUT,PATCHorDELETE, which must come from the site's origin. The frontend calls it withcallAccountRoute('repairs', '/mine')from@shadestack/client(Sites in other frameworks). - Routes for staff: when people with different jobs use the system on its site, such as the
mechanics of a workshop and their foreman, declare account roles instead of a role column of your own. A route
needs an ability, SHADE checks it before your code runs, and
inScopekeeps each mechanic to their workshop's rows:accounts: { roles: { mechanic: { scope: 'workshops', can: ['jobs.read'] }, foreman: { scope: 'workshops', includes: ['mechanic'], can: ['mechanics.assign', { ability: 'accounts.roles.give', roles: ['mechanic'] }] } } } { method: 'GET', path: '/workshop/jobs', auth: { account: 'jobs.read' }, handler: (ctx, request) => ctx.db.select().from(repairsJobs).where(inScope(repairsJobs.workshopId, request.account, 'jobs.read')) }
An admin gives the first foreman their role on the Accounts screen; the foreman givesmechanicin their own workshop withassignAccountRole, the only way your module gives roles (Account roles). Bounded on purpose: one scope per role, no rules language, not for separate customers in one install, no single sign-on.
5. Content, as the module itself
The weekly post is written by a schedule, which runs as the module's own actor with exactly the grants its
manifest lists in uses, shown to the admin on the install consent:
uses: ['collections.website-posts.create', 'collections.website-posts.publish'],
schedules: [{ name: 'weekly-post', intervalMs: 7 * 24 * 3_600_000, run: async (ctx) => {
const post = await createEntry(ctx, 'posts', { data: { title: 'Repaired this week', slug: `repaired-${week()}` } })
await publishEntry(ctx, 'posts', post.id, {})
} }]
Core's content services check the permission, validate, write in a transaction and audit the post as
package:repairs (Content services). Public and account routes act as the module too;
session routes act as the editor and never get more from uses. What can never be
granted (accounts, roles, tokens, settings, the logs, the forms collection, …) is listed under
uses. A module that only touches its own tables needs no grants.
6. In the admin
Pages, a sidebar group of its own, dashboard cards, a panel beside an entry editor and a section of Settings, all in
the manifest's admin part (Where a module appears in the
admin):
admin: {
locales: 'admin/locales',
pages: [{ path: '/modules/repairs/jobs', file: 'admin/JobsPage.vue' }],
sidebar: { group: { label: 'repairs.sidebar.group', icon: 'i-lucide-wrench' },
entries: [{ label: 'repairs.sidebar.jobs', icon: 'i-lucide-list', to: '/modules/repairs/jobs', requires: 'repairs.read' }] },
widgets: [{ id: 'waiting', label: 'repairs.widgets.waiting', file: 'admin/WaitingWidget.vue', requires: 'repairs.read' }],
settings: [{ id: 'general', label: 'repairs.settings.title', file: 'admin/RepairsSettings.vue' }]
}
Screens use the admin's Vue, Nuxt UI and composables without importing them, and build their forms with the admin's
own field components (FieldForm, FieldRenderer; Forms from the admin's field components).
A settings section is for admins only: every route it calls starts with assertModuleAdmin(ctx). Texts go in
admin/locales/en.json and nl.json, with the same keys (Its texts).
7. Building on another module
When the client's module builds on another module (an official one, such as the website module once it is one), it
says so with the versions it works with, within one major version of it: 1.2.0, ^1.2.0 or ~1.2.0, never *,
>=1.0.0 or a range across major versions. A patch or minor release of the other module then needs no
new release of the client's; its next major version does:
requires: { website: '^1.0.0' },
uses: ['collections.website-pages.read']
SHADE loads the other module first, refuses the client's module while the other is missing or of another version, and
counts it as off while the other is off; the other can't be switched off, uninstalled or updated past the range while
the client's module is on. Its uses may name the other module's collections only when that module shares them
(shares: { collections: ['website-pages'] }), and the install consent names both modules
(Modules that build on other modules).
8. Tests
- Unit:
module.test.tsfrominitchecks the manifest (validateModule) and its texts in both languages (checkModuleTexts). Test your services' rules here too. - Postgres:
...testDatabase()from@shadestack/module-sdk/test-databaseinvitest.config.ts, thencreateTestDatabase(),loadModules([plugin], …)andmoduleContext(ctx, 'repairs')from@shadestack/module-sdk/testing: test that an editor withoutrepairs.manageis refused, that an account sees only their own repairs, that a mechanic of one workshop never reads another's jobs (memberships intables.accountRoles), that the job's post is audited as the module. - Browser:
e2e/playwright.config.tswithmoduleE2eConfigruns against SHADE's test instance with the module installed as a package;e2e/site.config.tsfor the site (Its browser tests).
pnpm test, pnpm typecheck and the browser tests in the workspace before every release.
9. Package, sign and install
pnpm package # dist/repairs-<version>.shade-module.json
pnpm exec shade-module sign dist/repairs-<version>.shade-module.json --name rg-digital --key <private key file>
build refuses a module that reads process.env (secrets are settings), checks the manifest, and refuses one whose
parts need a capability it does not declare, naming it: the repair shop declares
capabilities: { http: {}, schedule: {}, accounts: {}, personalData: {} } for its routes, its weekly post, its customers'
and mechanics' roles and its personal data (shade-module capabilities prints what a manifest needs). It writes the
declaration into the package with uses and the modules it requires, and warns about deprecated SDK names it uses. The signature covers all of it; the private key never goes
in a repository (Packaging and signing).
On the client's instance an admin installs the file under Modules → Install package: the consent lists what it can
do, an admin agrees to trust it, and it runs after a restart
(Installing a trusted module). For each release raise
version in module.ts and package.json; an update that asks for more (a new capability, a new route for anyone, a
new grant, a shared collection it starts using) asks for consent again.
What SHADE checks, and what is yours
The SDK is a contract, not a sandbox. A trusted module runs inside the API's process: SHADE makes the honest path the easy one, but whatever the module's own code does is the module author's to get right.
| SHADE checks | Yours |
|---|---|
| Who is signed in: the team on session routes, the account on account routes (401 otherwise); cross-site requests and other origins refused on account routes | What each route lets that person do: assertCan first in every service, ownedBy on every query of an account's rows (a route that forgets it shows every account's data) |
| An account route's ability, from the account's roles read on every request (403 otherwise); who may give which role, in which scope, audited | inScope on every query of a scoped route (a route that forgets it shows one workshop's mechanics every workshop's rows) |
That a manifest is well formed: names, prefixes, routes, rate limits declared, uses grantable, required modules present and in range | The rate limit is enough for what the route costs; spam and abuse protection on public routes (a honeypot, a captcha of your own, limits per address) |
| The permission, input and audit of core's own services (content services, media, email) | Validating your own input with a schema (parseInput), writing in a transaction, and recordAudit for your own changes |
The module actor's grants (uses): nothing else, and never admins' actions | Asking only for the grants you need; never making up an actor of your own to get around them |
| Personal data tables that refer to accounts are registered (the module does not load otherwise) | Every other personal data you keep (names, addresses in your own columns) in a personalData source and a retention kind |
| Secrets as encrypted settings, the module's own only | Never logging them, never sending them to a browser |
| The signature and consent of the package; the stylesheet scoped to its own markup | What your admin screens and site parts render: escaping, what they fetch, what they show to whom |
| An error in a widget, panel or settings section stays in its box and goes to the error log | Errors in your own routes and schedules that are expected: answer with SHADE's errors (notFound, validation, …), never a stack trace |
Webhook signatures over the raw body when a route declares webhook | Idempotency of what a webhook or a retried request does (idempotent: true, or by the provider's id) |
When something the module needs is missing from the SDK, ask for it to be added to the SDK (and its contract) rather than importing core's files: a module that reaches past the SDK breaks on SHADE's next version, and the contract can't warn it.