# 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](https://github.com/iivankin/openworkspace/blob/master/packages/email/README.md)) 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.

```ts
// 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](https://github.com/iivankin/openworkspace/tree/master/examples/notes-module). It has every part this page mentions.

## [Scaffold](#scaffold)

In your deployment project, run:

```sh
bunx @open-workspace/create module time-off
```

This 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:

1. `bun install`
2. `bun run db:generate:time-off` to create the first migration
3. `bun run deploy`

The scaffold leaves out Settings, Administration and permissions. Copy them from Notes when you need them.

## [How a module is built](#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                  |

```ts
// 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](#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](https://github.com/iivankin/openworkspace/blob/master/packages/core/alchemy/index.ts)         | Deploy        | OpenWorkspace, WorkspaceModuleInfra, OidcClient, SamlApp, Webhook, and their types                                   |
| [@open-workspace/core/module](https://github.com/iivankin/openworkspace/blob/master/packages/core/worker/module-api.ts)      | Worker        | WorkspaceModule, auth and permission middleware, the database, MCP and webhook helpers, AI helpers                   |
| [@open-workspace/core/schema](https://github.com/iivankin/openworkspace/blob/master/packages/core/worker/db/schema.ts)       | 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](https://github.com/iivankin/openworkspace/blob/master/packages/core/shared/index.ts)           | Both          | Permission and webhook event types, email address helpers, invariant, required                                       |
| [@open-workspace/core/ui](https://github.com/iivankin/openworkspace/blob/master/packages/core/src/ui.ts)                     | Browser       | ClientModule, UI components, admin panel layout, AppSwitcher, useAuth, the API client                                |
| [@open-workspace/core/dev](https://github.com/iivankin/openworkspace/blob/master/packages/core/dev/stack.ts)                 | Local         | devWorkspaceStack, demoSeed                                                                                          |
| [@open-workspace/core/testing](https://github.com/iivankin/openworkspace/blob/master/packages/core/testing/index.ts)         | bun test      | testWorkspaceStack, deployTestStack, useFreshWorkspace, MCP token helpers                                            |
| [@open-workspace/core/testing/worker](https://github.com/iivankin/openworkspace/blob/master/packages/core/testing/worker.ts) | Test Worker   | testWorker and test hooks                                                                                            |
| [@open-workspace/core/testing/e2e](https://github.com/iivankin/openworkspace/blob/master/packages/core/testing/e2e.ts)       | Playwright    | e2eConfig, deployE2eStack                                                                                            |

## [Tables and migrations](#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-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.

```ts
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 ones `byDefault`.
* Permissions are what an administrator can grant a member. Guard their routes with `requirePermission(id)`, under `/api/admin/<section>`.
* A `teamAddress` section on `ClientModule` adds settings to a team’s address under **Administration → Teams**, such as a shared inbox’s signature. It has no save button of its own: call `useAddressSection({ dirty, save })`from `@open-workspace/core/ui`. “Save address” is enabled when the address or any section is `dirty`. It saves the address first, then calls `save`for each dirty section, and closes the editor only if all of them succeed. If a `save` throws, its message is shown and the editor stays open. `save`goes through your own routes; guard them with `requirePermission("manage_teams")`. The section gets the form’s current `delivery` (and a forward’s `forwardTo`), so it can hide as soon as the delivery changes: unmount the component that calls `useAddressSection`, and it stops taking part.
* A `userAddress` section does the same for a person’s address under **Administration → People**; guard its routes with `requirePermission("manage_people")`.
* An address delivers as `inbox` (its own mailbox), `list` (a team’s mailing list), `alias` (into the mailbox `aliasOf`) or `forward` (to the outside addresses `forwardTo`), and an inbox may be its domain’s `catchAll`. `hooks.mailboxSaved` runs after an address is created or changed (its delivery, name, team or members, as the `mailbox.*` webhooks say), and `hooks.mailboxDeleted` after one is deleted. Deleting a mailbox deletes its aliases first, so both run for each of them.
* Don’t write `mailboxes` yourself. `createMailboxAddress` and `deleteMailboxAddress` from `@open-workspace/core/module` create 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 the `mailbox.created`and `mailbox.deleted` webhooks and run the hooks above. Who may create the address is yours to check. An alias gets the `ownerUserId` or `teamId` of the mailbox it delivers into, and `createdByUserId` names the person it was made for.
* `hooks.mailboxAccessChanged` runs 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 against `mailboxAccess` (`canSend`) and `users.status` (a disabled person keeps their rows in `mailboxAccess`) and remove what no longer holds. `mailboxAccess` lists only mailboxes: for an alias into a team’s mailing list, check the person’s `teamMembership` of its team instead, or only make aliases into mailboxes.
* Register MCP tools through `tool(scope)`, and implement them by calling your own routes through `api`, 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 with `queueWebhookEvent`.

The Worker refuses to start if two modules use the same name, permission, scope, or webhook event.

## [Backups](#backups)

With `OpenWorkspace({ backups })` on, core writes a snapshot every day ([Backups](/docs/configuration.md#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`:

```ts
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 under `backups/<id>/<module>/<folder>/`. Use folders for whatever restores apart, such as mail’s addresses.
* `putObject(bytes, { extension, contentType })`: stores bytes once under `backups/objects/<sha256>.<extension>` and resolves to the hash. Name it in a line as `object: "<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](#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](#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.

```ts
// 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`).
