Modules
A module adds an app to the workspace. It can bring its own database tables,
API routes, MCP tools, permissions and OAuth scopes, webhook events, and
screens: an app in the switcher, Settings sections, and Administration
sections. Mail (@open-workspace/email) is a
module.
You write a module inside your deployment project and list it in
alchemy.run.ts. Each deploy builds the listed modules and applies their
migrations, so you don’t register or publish anything.
// alchemy.run.ts
import { Email } from "@open-workspace/email/alchemy";
import { Notes } from "./modules/notes/alchemy.ts";
OpenWorkspace({
hostname: "mail.acme.com",
mailDomains: ["acme.com"],
modules: [Email(), Notes()],
});For a complete working example, read
examples/notes-module. It has every part this page
mentions.
Scaffold
In your deployment project, run:
bunx @open-workspace/create module time-offThis writes modules/time-off/ with a table, an API route with read and write
scopes, an MCP tool, a webhook event, and an app at /time-off. It also adds
the dependencies and a db:generate:time-off script to package.json, and
lists TimeOff() in alchemy.run.ts. If it can’t safely edit
alchemy.run.ts, it prints the lines to add instead.
Then:
bun installbun run db:generate:time-offto create the first migrationbun run deploy
The scaffold leaves out Settings, Administration and permissions. Copy them from Notes when you need them.
How a module is built
A module has three parts. Code they share (ids, scopes, permissions, webhook
events) goes in the module’s shared/ folder and imports only
@open-workspace/core/shared.
| Part | Type | Runs | What it declares |
|---|---|---|---|
| Alchemy | WorkspaceModuleInfra |
On deploy | The module’s name, its entry files and migrations, and the Cloudflare resources it binds |
| Server | WorkspaceModule |
In the Worker | Routes, permissions, OAuth scopes, MCP tools, webhook events, and queue, mail and cron handlers |
| Client | ClientModule |
In the browser | The app in the switcher, its screens, and Settings and Administration sections |
// modules/notes/alchemy.ts
export function Notes() {
return {
name: NOTES_MODULE, // "notes", never changed
server: { entry: join(import.meta.dirname, "index.ts") },
migrations: join(import.meta.dirname, "migrations"),
client: { entry: join(import.meta.dirname, "src", "client.tsx") },
} satisfies WorkspaceModuleInfra;
}Public API
Import core only through these entry points. Anything else in core can change in any release. Each entry file links to the types’ doc comments, which are the reference.
| Entry | Where it runs | What’s in it |
|---|---|---|
@open-workspace/core/alchemy |
Deploy | OpenWorkspace, WorkspaceModuleInfra, OidcClient, SamlApp, Webhook, and their types |
@open-workspace/core/module |
Worker | WorkspaceModule, auth and permission middleware, the database, MCP and webhook helpers, AI helpers |
@open-workspace/core/schema |
Worker, tools | Core’s tables (users, teams, mailboxes, mailboxAccess…), for a module’s schema and queries; loads in drizzle-kit too |
@open-workspace/core/shared |
Both | Permission and webhook event types, email address helpers, invariant, required |
@open-workspace/core/ui |
Browser | ClientModule, UI components, admin panel layout, AppSwitcher, useAuth, the API client |
@open-workspace/core/dev |
Local | devWorkspaceStack, demoSeed |
@open-workspace/core/testing |
bun test |
testWorkspaceStack, deployTestStack, useFreshWorkspace, MCP token helpers |
@open-workspace/core/testing/worker |
Test Worker | testWorker and test hooks |
@open-workspace/core/testing/e2e |
Playwright | e2eConfig, deployE2eStack |
Tables and migrations
Your tables live in the workspace’s D1 database, next to core’s, and can
reference core’s tables such as users.id (import them from
@open-workspace/core/schema). Declare them with Drizzle and
generate migrations with drizzle-kit generate. Read and write with
createDb(c.env.DB).
Once you’ve deployed, keep these stable:
- The module’s
name. Renaming it makes every migration run again. - Migration files. Add new ones; never edit, rename or delete a deployed one.
Prefix table names with the module’s name (Notes uses notes and
note_preferences), because all modules share one namespace.
Routes, scopes and permissions
Routes are Hono apps mounted under /api. Put requireAuth in front, and give
each route the OAuth scope a token needs with oauthScope(...). A route
without a scope refuses tokens. Browser sessions don’t use scopes.
const ownNotes = new Hono<AppEnv>()
.use("*", requireAuth)
.get("/", oauthScope(NOTES_READ_SCOPE), async (c) => { … })
.post("/", oauthScope(NOTES_WRITE_SCOPE), zValidator("json", noteInputSchema), async (c) => { … });- Scopes are named
area.name, in lowercase letters and underscores. Mark the everyday onesbyDefault. - Permissions are what an administrator can grant a member. Guard their
routes with
requirePermission(id), under/api/admin/<section>. - A
teamAddresssection onClientModuleadds settings to a team’s address under Administration → Teams, such as a shared inbox’s signature. It has no save button of its own: calluseAddressSection({ dirty, save })from@open-workspace/core/ui. “Save address” is enabled when the address or any section isdirty. It saves the address first, then callssavefor each dirty section, and closes the editor only if all of them succeed. If asavethrows, its message is shown and the editor stays open.savegoes through your own routes; guard them withrequirePermission("manage_teams"). The section gets the form’s currentdelivery(and a forward’sforwardTo), so it can hide as soon as the delivery changes: unmount the component that callsuseAddressSection, and it stops taking part. - A
userAddresssection does the same for a person’s address under Administration → People; guard its routes withrequirePermission("manage_people"). - An address delivers as
inbox(its own mailbox),list(a team’s mailing list),alias(into the mailboxaliasOf) orforward(to the outside addressesforwardTo), and an inbox may be its domain’scatchAll.hooks.mailboxSavedruns after an address is created or changed (its delivery, name, team or members, as themailbox.*webhooks say), andhooks.mailboxDeletedafter one is deleted. Deleting a mailbox deletes its aliases first, so both run for each of them. - Don’t write
mailboxesyourself.createMailboxAddressanddeleteMailboxAddressfrom@open-workspace/core/modulecreate and delete an address the way the admin API does: they check the domain, that the address is free and that its delivery is valid, send themailbox.createdandmailbox.deletedwebhooks and run the hooks above. Who may create the address is yours to check. An alias gets theownerUserIdorteamIdof the mailbox it delivers into, andcreatedByUserIdnames the person it was made for. hooks.mailboxAccessChangedruns after someone may have lost access to a mailbox: a person was disabled or taken off a team, a team’s members or send rights changed, a team address moved to another team, or an address stopped being a mailbox (became a list, an alias or a forward). If the module keeps something per person and mailbox, such as an alias made for them, check it againstmailboxAccess(canSend) andusers.status(a disabled person keeps their rows inmailboxAccess) and remove what no longer holds.mailboxAccesslists only mailboxes: for an alias into a team’s mailing list, check the person’steamMembershipof its team instead, or only make aliases into mailboxes.- Register MCP tools through
tool(scope), and implement them by calling your own routes throughapi, so a token only sees what its scopes allow. - Declare webhook events once in
shared/, on both the server and client parts, and send them withqueueWebhookEvent.
The Worker refuses to start if two modules use the same name, permission, scope, or webhook event.
Backups
With OpenWorkspace({ backups }) on, core writes a snapshot every day
(Backups): its own data first, then each module’s
part, a batch at a time on the hourly cron. A module joins with backup on
its WorkspaceModule:
backup: {
// One batch; resolves to where the next one starts, or null when done.
async export(env, snapshot) {
const after = snapshot.cursor;
const page = await notesAfter(env, after, 500);
snapshot.writeLines("notes", page.map((note) => ({ id: note.id, title: note.title, body: note.body })));
return page.length === 500 ? page.at(-1).id : null;
},
// What the routes that write a line's data require: core skips the line
// for a sign-in without it.
restoreScopes: () => ["notes.write"],
// One line back from `import backup`: add it unless it exists.
async restore(c, { folder, line, object }) {
const note = noteLineSchema.parse(line);
const added = await insertNoteIfMissing(c.env, note);
return { status: added ? "restored" : "exists" };
},
},snapshot gives the module core’s shared pieces:
cursor: what the last batch returned, kept in D1 between runs. Keep a batch small (a few hundred subrequests); core runs up to 25 an hour and a repeated batch must write the same lines again.writeLines(folder, lines): JSON lines underbackups/<id>/<module>/<folder>/. Use folders for whatever restores apart, such as mail’s addresses.putObject(bytes, { extension, contentType }): stores bytes once underbackups/objects/<sha256>.<extension>and resolves to the hash. Name it in a line asobject: "<sha256>.<extension>"; core deletes objects no kept snapshot names. Remember which items are stored, as mail keeps each message’s hash, so the next snapshot only writes their lines.error(message): shown under Administration → Backups.
import backup restores core’s data first, then sends each line of the
module’s part to restore in order, with the bytes of the object it names,
in a request of an administrator, if it holds what restoreScopes(item)
names (a permission’s scope needs that permission, which an administrator’s
session holds; any other scope binds only an app’s token). Name the scopes of
the routes that write the same data, so a restore does no more than the
module’s own API would; a line refused is reported as skipped, and sent again
by the next run. Add what is missing and leave what exists:
a restore runs again after a failure, and into workspaces that still have
most of their data.
Screens
The client entry exports a ClientModule. Load every screen with lazy().
- Build screens from
@open-workspace/core/ui, and start a full-page app’s header like the others: the workspace logo,<AppSwitcher current={MODULE} />, and the account menu. - Use the theme’s color tokens (
bg-surface,text-muted-foreground, …) so light and dark mode both work. - Keep the screens in the client entry’s folder, because Tailwind only scans that folder.
- In
package.json, list React, React Router, TanStack Query and sonner at core’s versions, if the module imports them.
Test locally
@open-workspace/core/dev runs the workspace on your computer with demo data
and a demo sign-in. You don’t need a Cloudflare account.
// dev.run.ts
const { stack, stackName } = devWorkspaceStack({
stack: "NotesExampleDev",
modules: [Notes()],
seed: [demoSeed],
port: 5180,
});
export { stackName };
export default stack;Run ALLOW_MOCK_AUTH=true alchemy dev dev.run.ts, open the app, and choose
Open seeded local demo.
For automated tests, see how the Notes example uses
@open-workspace/core/testing and /testing/e2e. Projects that use them need
@alchemy.run/test in their devDependencies, and Playwright must run under Bun
(bun --bun playwright test).