SHADE is young: 0.1.0-next.2 is a pre-release, and 0.1.0 isn't out yet.

SHADE
Writing a plugin

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/token routes are served by the API's admin role at /api/packages/<name>/….
  • A session/token route that hands out personal data, such as a CSV of what visitors sent, may set personal: 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 rateLimit is { limit, windowMs, key }: limit a whole number of at least 1, windowMs a whole number of milliseconds of at least 1000. key is what is counted: ip (any route), token (session and token routes only), account (account routes only). The loader refuses any other.
  • A session route 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.
  • public routes are served by the public role at /api/v1/account/<name>/…, with CORS for the site origin. They must declare a rateLimit, 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); use idempotent: true for anything that creates orders or payments and webhook for provider callbacks (timestamp, signature and delivery id checked over the raw body before the handler runs: Incoming webhooks).
  • A public route 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 public route whose answer other sites load (a script they include) sets crossOrigin: true: the API then sends Cross-Origin-Resource-Policy: cross-origin instead of same-origin. Only public routes may; the loader refuses it elsewhere.
  • A public GET route whose answer may be cached (a card, a script other sites include) declares cache. See Cache headers and SVG answers.
  • account routes 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: a summary, and the query and body schemas 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' }
  })
}
  • cache is { maxAgeSeconds, staleWhileRevalidateSeconds? } (type ModuleRouteCache), whole seconds from 1 to 86400 (a day). Only on public GET routes: 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 no private). It is part of the route's http line, GET /card.svg (public, cached 300 s, stale 60 s), so a changed cache asks the admin again.
  • Cache-Control is public, max-age=300, stale-while-revalidate=60 only on a 200 answer to a GET of such a route that sets no cookie. Everything else is no-store: routes without cache, account, session and token routes always, errors, refusals and rate limits, other statuses, and answers with Set-Cookie.
  • The module's own cache headers are dropped: Cache-Control, Expires, Pragma, Surrogate-Control, X-Accel-Expires and the CDNs' CDN-Cache-Control headers. Only cache decides.
  • X-Content-Type-Options: nosniff on every answer, and Content-Security-Policy in place of the handler's: an SVG answer (image/svg+xml) gets default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'none'; sandbox: its own styles and data: 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), e2e plugins-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 }; roles is 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 by request.account; ctx.actor is 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's find and erase). 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 uses teamMemberReference instead (on delete set null). An account's id kept in a plain text or uuid column 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 accountReference column must be in the tables of one of the module's personalData sources 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 a accountReference: refer to the person's contact instead (contactReference, see Contacts), and read a signed-in account's own rows with ownedByContact(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 Origin header 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 sets Origin to 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 GET route must only read. Every change is a POST, PUT, PATCH or DELETE, which needs the site's Origin.
  • Answers are the account's. They are sent with cache-control: no-store, whatever the handler sets; an account route cannot declare cache. An idempotent account route keeps its keys per account.
  • From a frontend. callAccountRoute(plugin, path, options) of @shadestack/client sends the cookie; see Frameworks. The route is in the OpenAPI document under the accountSession scheme.
  • Tests. Core's account-probe fixture (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 only can (its abilities: short keys joined by dots, jobs.read), includes (lower roles whose abilities it has too), scope and default. No names that are prototype members, at most 50 roles, 100 abilities a role and 50 names in includes or in one give grant. validateModule refuses an unknown role, a cycle of includes and 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'] }, with auth: { 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, in db.tables), and the column a accountReference that 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 no personalData source of the module's lists it. Read and write it on account routes with ownedBy(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>_organisation is 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's accounts.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 the tables of one of the module's personalData sources, or the module does not load: its find gives a person the rows of their organisations (ownedByOrganisation(column, { email })), and its keepReason says they are the organisation's (or its erase deletes them). For a row the law keeps, such as an order, use organisationReference(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's organisation-probe fixture is a small, complete example.
  • A scope is one of the module's own tables, named without its prefix: scope: 'workshops' is repairs_workshops, which must be in db.tables and have an id column. 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), so inScope never 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: [...] } in can names 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 gets request.account.roles: each { role, scope, abilities }, with its scope (null without one) and every ability it gives. A plain auth: '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, beside ownedBy. Use it on every query of a scoped route: the route's ability alone lets a mechanic of one workshop through, inScope keeps 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: by is request.account, account names the account ({ id } or { email }), then the role, its scope and take. 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: by naming 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 as accounts.roles; giving a role that can give others raises a security alert.
  • Never write account_roles yourself. 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 is role 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 say assigns on that line; SHADE reads it as can 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 its scope and scopeTable, 'locations') and hand your services a request.account with its roles; a service that gives roles gets accountRouteContext(moduleContext(ctx, '<name>'), account), the context an account route of your module gets for that account, as the appointments module's server/service.test.ts does. The testing entry is for tests only (*.test.ts, e2e/, helpers only they import): shade-module build refuses a module whose shipped code (the server bundle, the site, shared and admin sources) imports @shadestack/module-sdk/testing or test-database, and on an instance a server package's import() 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 assignAccountRole is 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.