Routes
A :param that is . or .. (also written %2E%2E) or not valid percent-encoding matches no route: it answers
404, so a parameter can never step to another path of an untrusted module's worker. Route handlers receive a
ServiceContext and a framework-agnostic ModuleRequest; they parse input with a schema and
call the service. auth is session (admin, default), token (read token; it may only do read actions),
public (anonymous visitors) or account (a visitor who signed in). On session and token routes
ctx.actor is the team member or token, with their own rights; on public and account routes it is the module's own
actor, with what its uses lists.
session/tokenroutes are served by the API's admin role at/api/packages/<name>/….- A
session/tokenroute that hands out personal data, such as a CSV of what visitors sent, may setpersonal: true: it then answers a signed-in session only, never a token, whatever the token's member may read. The forms module's CSV download is one. - A
rateLimitis{ limit, windowMs, key }:limita whole number of at least 1,windowMsa whole number of milliseconds of at least 1000.keyis what is counted:ip(any route),token(session and token routes only),account(account routes only). The loader refuses any other. - A
sessionroute may take a larger request body than the API's default of 1 MB:bodyLimit, in bytes, a whole number up to 10 MB (experimental; the import module takes a file's text this way). A larger body is refused with 413 before the handler runs. Other routes keep the default. publicroutes are served by the public role at/api/v1/account/<name>/…, with CORS for the site origin. They must declare arateLimit, counted per IP (the loader refuses one without,a public route needs a rate limit, and one counted per token, since anyone can send a new token each time); useidempotent: truefor anything that creates orders or payments andwebhookfor provider callbacks (timestamp, signature and delivery id checked over the raw body before the handler runs: Incoming webhooks).- A
publicroute that takes a form from visitors (a booking, a sign-up) uses SHADE's spam check, the one core's forms use (experimental in 0.1; see Spam checks on public forms). - A
publicroute whose answer other sites load (a script they include) setscrossOrigin: true: the API then sendsCross-Origin-Resource-Policy: cross-origininstead ofsame-origin. Only public routes may; the loader refuses it elsewhere. - A
publicGETroute whose answer may be cached (a card, a script other sites include) declarescache. See Cache headers and SVG answers. accountroutes are served next to the public ones, at/api/v1/account/<name>/…, and never on the admin's mount. See Account routes.- A public or account route may describe itself for the API's OpenAPI document with
doc: asummary, and thequeryandbodyschemas its handler parses with. Without one it is listed by method and path.
Spam checks on public forms
The site's islands send two extra fields with every form they post: website, a hidden field people leave empty
(the honeypot), and elapsedMs, how long the form was open. A route that takes a form spreads SpamCheckFields into
its input, declares SPAM_CHECK_RATE_LIMIT (5 posts per IP in 10 minutes) and asks isSpam before it does anything:
import { isSpam, parseInput, SPAM_CHECK_RATE_LIMIT, SpamCheckFields } from '@shadestack/module-sdk/server'
import * as z from 'zod'
const SignUpInput = z.object({ email: z.email().max(254), ...SpamCheckFields })
{
method: 'POST',
path: '/sign-up',
auth: 'public',
rateLimit: SPAM_CHECK_RATE_LIMIT,
handler: async (ctx, request) => {
const input = parseInput(SignUpInput, request.body)
// A filled-in honeypot, or a form open under 3 seconds or for an unknown time: answer as if it worked, keep nothing.
if (isSpam(input)) return { ok: true }
// …
}
}
A bot gets the same answer as a person, so it learns nothing. The names are experimental in 0.1 (see Experimental manifest parts) until a second module uses them; appointments' bookings are the first.
Cache headers and SVG answers
SHADE sets the cache and security headers of every module route's answer itself, once the
answer is final, for trusted and untrusted modules alike (apps/api/src/http/module-answers.ts). What a handler sets
of its own is replaced.
{
method: 'GET',
path: '/card.svg',
auth: 'public',
rateLimit: { limit: 600, windowMs: 60_000, key: 'ip' },
// Caches may keep a 200 answer 5 minutes, and serve it a minute more while they fetch a new one.
cache: { maxAgeSeconds: 300, staleWhileRevalidateSeconds: 60 },
handler: async (ctx, request) => new Response(await renderCard(ctx, request.query), {
headers: { 'content-type': 'image/svg+xml' }
})
}
cacheis{ maxAgeSeconds, staleWhileRevalidateSeconds? }(typeModuleRouteCache), whole seconds from 1 to 86400 (a day). Only onpublicGETroutes: the loader refuses it on account, session and token routes and on any other method (only public GET routes may be cached), and refuses keys it doesn't know (there is noprivate). It is part of the route'shttpline,GET /card.svg (public, cached 300 s, stale 60 s), so a changed cache asks the admin again.Cache-Controlispublic, max-age=300, stale-while-revalidate=60only on a200answer to aGETof such a route that sets no cookie. Everything else isno-store: routes withoutcache, account, session and token routes always, errors, refusals and rate limits, other statuses, and answers withSet-Cookie.- The module's own cache headers are dropped:
Cache-Control,Expires,Pragma,Surrogate-Control,X-Accel-Expiresand the CDNs'CDN-Cache-Controlheaders. Onlycachedecides. X-Content-Type-Options: nosniffon every answer, andContent-Security-Policyin place of the handler's: an SVG answer (image/svg+xml) getsdefault-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'none'; sandbox: its own styles anddata:images, no script, nothing loaded from elsewhere, and a sandbox, so even an SVG opened on its own never runs in SHADE's origin. Every other answer gets the API's own policy,default-src 'none'; frame-ancestors 'none', which loads and runs nothing.- Tests:
apps/api/test/http/module-answers.test.ts(both kinds of module),plugins.account-routes.test.ts(account and token routes), e2eplugins-untrusted.spec.ts(an SVG through the real sandbox).
Account routes
A account route is for "my orders", "my bookings", a wishlist: things that belong to one account.
Only trusted modules (server packages) may have them; untrusted modules keep public
and session.
import { ownedBy, parseInput, accountReference, type ModuleRoute } from '@shadestack/module-sdk/server'
export const shopWishlist = pgTable('shop_wishlist', {
id: id(),
accountId: accountReference('account_id').notNull(), // goes with the account (on delete cascade)
sku: text('sku').notNull()
})
export const routes: ModuleRoute[] = [
{ method: 'GET', path: '/wishlist', auth: 'account',
handler: (ctx, request) => ctx.db.select().from(shopWishlist).where(ownedBy(shopWishlist.accountId, request.account)) },
{ method: 'POST', path: '/wishlist', auth: 'account', rateLimit: { limit: 10, windowMs: 60_000, key: 'account' },
doc: { summary: 'Adds a product to the wishlist of the account', body: WishlistInput },
handler: (ctx, request) => addToWishlist(ctx, request.account, parseInput(WishlistInput, request.body)) }
]
- Who gets through. Accounts must be on, and the request must carry a session whose address is
confirmed; anyone else gets 401. The account reaches the handler as
request.account({ id, email, roles };rolesis empty unless the module has account roles; each is{ role, scope, abilities }). It is not an actor and holds no permissions, so the route decides byrequest.account;ctx.actoris the module's own actor. - Only their own rows.
ownedBy(column, request.account)is the where-clause for the account's own rows; with{ email }it finds the rows of the account with that address (a personal data source'sfindanderase). Without an account it throws UNAUTHORIZED rather than match every row. Look a row up with it, so another account's row is simply not found. - Account-owned columns use
accountReference. It is how SHADE knows a table holds accounts' data: the column is a foreign key to the accounts (on delete cascade), so the rows go with the account, the loader checks the personal data below, and the consent screen lists the table. A column referring to a team member usesteamMemberReferenceinstead (on delete set null). An account's id kept in a plaintextoruuidcolumn cannot be detected: nothing stops it, nothing erases it, and nothing tells the admin. Never store one that way. - Personal data. A table with a
accountReferencecolumn must be in thetablesof one of the module'spersonalDatasources that erases, or the module does not load (table "shop_wishlist" refers to account accounts: …):personalData: [{ key: 'wishlist', label: 'shop.privacy.wishlist', tables: [shopWishlist], find: (ctx, email) => ctx.db.select().from(shopWishlist).where(ownedBy(shopWishlist.accountId, { email })), erase: async (ctx, email) => (await ctx.db.delete(shopWishlist).where(ownedBy(shopWishlist.accountId, { email })).returning()).length }]
Rows the law makes you keep (keepReason) should not hang off an account: deleting the account deletes them. Store what you must keep (an order) without aaccountReference: refer to the person's contact instead (contactReference, see Contacts), and read a signed-in account's own rows withownedByContact(column, request.account). - Rate limits. 60 a minute per account unless the route declares its own, counted per account (
key: 'account', for account routes only) or per IP (key: 'ip'). On top of that, every account route allows 300 requests a minute per IP before the session is even read (USER_ROUTE_IP_LIMIT), so calls without a session, or with a new forged cookie each time, cannot go on forever. - From the site only. The browser sends the account's session cookie. SHADE trusts one origin with it, the Site
URL's, as Better Auth does for sign-in; other frontends are not trusted with it. CORS with
credentials allows that origin only; a request that changes something (anything but GET and HEAD) must carry an
Originheader that is the site's, or it gets 403; and a request the browser marks as coming from another site (Sec-Fetch-Site: cross-site) gets 403 whatever its method. A server calling an account route with an account's cookie setsOriginto the site's address. - GET changes nothing. The session cookie (SameSite=Lax) rides along when another site links to a GET route,
so an account
GETroute must only read. Every change is aPOST,PUT,PATCHorDELETE, which needs the site'sOrigin. - Answers are the account's. They are sent with
cache-control: no-store, whatever the handler sets; an account route cannot declarecache. Anidempotentaccount route keeps its keys per account. - From a frontend.
callAccountRoute(plugin, path, options)of@shadestack/clientsends the cookie; see Frameworks. The route is in the OpenAPI document under theaccountSessionscheme. - Tests. Core's
account-probefixture (shade/test/testing/fixtures/modules/account-probe) is a small, complete example: an account's notes, with its personal data and its routes, and account roles.
Account roles
For the people who work in a client's system on its site: the staff of a location, their managers.
The module declares the roles in its accounts part; SHADE keeps who has which, checks a route's ability before the
module's code runs, and audits every change. Admins give roles on the Accounts screen; a role's members may give lower
roles themselves.
import { assignAccountRole, inScope, parseInput, type ModuleRoute } from '@shadestack/module-sdk/server'
export default defineModule({
name: 'repairs',
// …
db: { tables: { repairsJobs, repairsWorkshops }, migrationsFolder: 'migrations' },
accounts: {
roles: {
mechanic: { scope: 'workshops', can: ['jobs.read', 'jobs.update'] },
foreman: { scope: 'workshops', includes: ['mechanic'], can: ['mechanics.assign', { ability: 'accounts.roles.give', roles: ['mechanic'] }] }
}
},
server: { routes }
})
export const routes: ModuleRoute[] = [
{ 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')) },
{ method: 'POST', path: '/workshop/mechanics', auth: { account: 'mechanics.assign' },
handler: (ctx, request) => {
const { email, workshop } = parseInput(MechanicInput, request.body)
return assignAccountRole(ctx, request.account, { account: { email }, role: 'mechanic', scope: workshop })
} }
]
- Roles have short names (
mechanic); SHADE stores them as<plugin>:<role>(repairs:mechanic), so two modules never share one. Each has onlycan(its abilities: short keys joined by dots,jobs.read),includes(lower roles whose abilities it has too),scopeanddefault. No names that are prototype members, at most 50 roles, 100 abilities a role and 50 names inincludesor in one give grant.validateModulerefuses an unknown role, a cycle ofincludesand anything else, naming it. - A default role (
default: true) is every signed-in account's, without anyone giving it: every account with a confirmed address has it while the module is loaded. Use it for what any customer may do, such as seeing their own bookings (customer: { default: true, can: ['bookings.own'] }, withauth: { account: 'bookings.own' }on the route). It has no scope, gives no roles and includes no role with a scope or one that gives roles; no role gives it, and admins don't see it in the roles they can give. Other roles may include it. Making a role the default is a new consent line (customer for every account), so the update asks again. Experimental until a second module uses it. - A profile table keeps what the module knows about an account, one row per account:
accounts: { profile: { table: 'repairs_profiles', column: 'account_id' } }. The table is one of the plugin's own (its SQL name, indb.tables), and the column aaccountReferencethat is unique and not null (the primary key, say); the table refers to accounts through no other column. SHADE finds and exports the row with the account's data and erases it with the account, so nopersonalDatasource of the module's lists it. Read and write it on account routes withownedBy(column, request.account). Never keep sign-in data there, and nothing about people without an account. Experimental until a second module uses it. scope: 'organisation'is SHADE's own scope kind (decision 0009): the role is given in one organisation, to one of its members, and leaving the organisation ends it. No table of the module's is needed (a table named<plugin>_organisationis never the scope).givenByRank: 'manager'lets the organisation's owners and managers give and take the role there,'owner'its owners only; without it, only the team (and a role'saccounts.roles.give) gives it. An owner or manager never gives a role to themselves. The site reaches this through the account API's/api/v1/account/organisations/{id}/roles. Experimental until a second module uses it.accounts: { roles: { viewer: { scope: 'organisation', can: ['orders.read'], givenByRank: 'manager' }, approver: { scope: 'organisation', includes: ['viewer'], can: ['orders.approve'], givenByRank: 'owner' } } }- An organisation's rows.
organisationReference(name)is a column for a row the organisation owns; it goes with the organisation (on delete cascade), never with one person. The table must be in thetablesof one of the module'spersonalDatasources, or the module does not load: itsfindgives a person the rows of their organisations (ownedByOrganisation(column, { email })), and itskeepReasonsays they are the organisation's (or itserasedeletes them). For a row the law keeps, such as an order, useorganisationReference(name, { keep: true }): the column becomes null when the organisation is deleted, so copy what the row must still say, such as its name. On account routes,ownedByOrganisation(column, request.account, 'orders.read')is the where-clause for the rows of the account's organisations where its role per organisation gives the ability. Deleting an organisation first shows the team or the owner how many rows each module keeps for it. Core'sorganisation-probefixture is a small, complete example. - A scope is one of the module's own tables, named without its prefix:
scope: 'workshops'isrepairs_workshops, which must be indb.tablesand have anidcolumn. A scoped role is given for one row (a workshop), checked to exist. One scope per role, no more nesting. Roles given per different tables never include each other, and one ability is given per one table only (a role without a scope may give it too), soinScopenever reads a team's id as a workshop's. - Changing a scope in an update (adding one, naming another table, removing it) leaves existing memberships
of that role giving nothing: SHADE counts a membership only while it fits the role as declared now. The admin
sees them marked in the account's Roles dialog and gives the role again. Removing a scope is a new consent line
(
mechanic everywhere), so the update asks again. { ability: 'accounts.roles.give', roles: [...] }incannames the roles its members may give and take: only roles it includes, never itself or a role beside or above it. A scoped role gives roles of the same scope, in the scopes where the member has it. Abilities stay their own namespace, apart from core's actions.- Routes need an ability with
auth: { account: '<ability>' }: SHADE answers 403 ("Your account roles do not allow this") unless one of the account's roles gives it, reading the memberships on every request (one query), so a role taken away counts at once. The handler getsrequest.account.roles: each{ role, scope, abilities }, with its scope (nullwithout one) and every ability it gives. A plainauth: 'account'route gets the roles too, without a check. inScope(column, account, ability)is the where-clause for rows in the scopes where the account has the ability, besideownedBy. Use it on every query of a scoped route: the route's ability alone lets a mechanic of one workshop through,inScopekeeps them to their workshop's rows. Only memberships with a scope count; without one it matches no row, without an account it throws UNAUTHORIZED. On a uuid column a scope that is no uuid matches no row.assignAccountRole(ctx, by, { account, role, scope, take })is the only way a module gives or takes a role:byisrequest.account,accountnames the account ({ id }or{ email }), then the role, itsscopeandtake. SHADE reads the giver's roles itself and refuses (FORBIDDEN) another module's role, one none of their roles can give, a scope where they don't have that role, and their own roles; an account without a confirmed address is NOT_FOUND. It works only on an account route, with the context SHADE gave that request, and only as the account who called it:bynaming anyone else (an id from the request body) is FORBIDDEN, and so is any call from a job, a public route or a session route. Audited asaccounts.roles; giving a role that can give others raises a security alert.- Never write
account_rolesyourself. It is core's table, outside the SDK; nothing stops a trusted module's raw SQL, but nothing then checks, audits or alerts either ("What this is not"). - On the consent: each role, its scope, every ability (with its included roles') and what it can give, a line
each (
role foreman per workshops,role foreman can give mechanic; a role without a scope isrole customer everywhere), and each account route with the ability it needs (GET /workshop/jobs (jobs.read)). An update that adds a role or an ability, changes or removes a scope, or widens what it can give, asks again. Packages signed before the rename sayassignson that line; SHADE reads it ascan give. - Admins give and take roles on the Accounts screen (
accounts.roles); uninstalling the module removes its roles (they are in its backup). Memberships are personal data, registered by SHADE. - Untrusted modules have no account roles.
- Tests: insert memberships with
tables.accountRoles(@shadestack/module-sdk/testing; a scoped one with itsscopeandscopeTable,'locations') and hand your services arequest.accountwith itsroles; a service that gives roles getsaccountRouteContext(moduleContext(ctx, '<name>'), account), the context an account route of your module gets for that account, as the appointments module'sserver/service.test.tsdoes. The testing entry is for tests only (*.test.ts,e2e/, helpers only they import):shade-module buildrefuses a module whose shipped code (the server bundle, the site, shared and admin sources) imports@shadestack/module-sdk/testingortest-database, and on an instance a server package'simport()of either fails however the name is written (the API's module hooks). - Another module's code that runs during your account route's request (a save check of an entry it saved) gets no
account: the request's account is bound to the module whose route it is, so its
assignAccountRoleis FORBIDDEN, as in a job. The events your route causes are heard later, on the worker, with no account either.
Raw bodies and webhooks
request.body is the body parsed as JSON when the request says it is JSON (Content-Type: application/json;
malformed JSON is refused with VALIDATION), and undefined otherwise. Routes that need the unparsed body (form-encoded
webhooks, signature checks) set rawBody: true or webhook; the handler then gets request.rawBody. Never trust a webhook body: re-fetch the resource from the provider. How SHADE checks a webhook, and how to verify one a provider
doesn't sign by fetching back, is in Incoming webhooks.
Outside hosts
The admin and the site only load from SHADE's own origins (Content-Security-Policy). A module that embeds something
from elsewhere declares the hosts, by kind: allowedSources: { site: { frame: ['https://maps.example.com'] }, admin: { img: ['https://tiles.example.com'] } } (kinds img, media, frame, connect, script, style,
font; https:// host names only, *. for subdomains except for script, where a wildcard could be any tenant of a
shared host such as *.github.io). The site allows them while the module is on; see
Request protection. They are the allowedSources capability, on the
consent. The hosts its server code calls are the network capability: network: { hosts: ['api.example.com'] }, or
fromSettings: ['buildHookUrl'] for a host an admin sets (trusted modules only). Its server code calls them with
moduleFetch(ctx, url, init), never Node's fetch or node:https: https only, public addresses only, redirects
checked, 10 seconds and 5 MB. See Network.