@antelopejs/dms-saas 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1042 +1,94 @@
1
- # @antelopejs/dms-saas
2
-
3
1
  <div align="center">
4
- <a href="./LICENSE"><img alt="License" src="https://img.shields.io/badge/license-Apache--2.0-blue?style=for-the-badge&labelColor=000000"></a>
5
- <a href="https://discord.gg/sjK28QHrA7"><img src="https://img.shields.io/badge/Discord-18181B?logo=discord&style=for-the-badge&color=000000" alt="Discord"></a>
6
- <a href="https://antelopejs.com"><img src="https://img.shields.io/badge/Docs-18181B?style=for-the-badge&color=000000" alt="Documentation"></a>
7
- </div>
8
-
9
- SaaS extension module for the AntelopeJS DMS.
10
-
11
- Adds multi-tenant billing, plans, workspace switching, self-service workspace creation, refund policies, segments, reminders, and Stripe integration on top of the core DMS multi-tenant primitives.
12
-
13
- See the design documents in `dms/saas/` (sibling repo) for the full architectural reference.
14
2
 
15
- ## Vue frontend development
16
-
17
- The module registers `frontend-vue/dms.frontend.ts` with the Vue 3 Inertia
18
- adapter. It preserves the `DmsSaas*` component names, the `auth/no-workspace`
19
- page override, client-only displays, global guards, and English/French catalogs.
20
- Public module configuration is exposed under `public.dmsSaas`. Stripe secrets
21
- are never exposed to the frontend.
22
-
23
- The backend integration requires `@antelopejs/dms`. Frontend source
24
- verification runs through `@antelopejs/dms-frontend` and the DMS frontend
25
- source shipped in that published DMS package; no sibling checkout or local
26
- package link is required.
3
+ # @antelopejs/dms-saas
27
4
 
28
- This package lives in `packages/dms-saas` of the `AntelopeJS/dms-saas`
29
- workspace. From that directory run `pnpm install`,
30
- `pnpm --dir frontend-vue install`, `pnpm build`, `pnpm typecheck`, and
31
- `pnpm test:frontend`. The frontend check generates a temporary workspace, then
32
- builds client, SSR, and email bundles and runs Vue typechecking. To run the
33
- playground frontend during backend development, use `pnpm frontend:dev`; this
34
- dispatches through the core CLI as `ajs dms dev`. The playground connects to
35
- MongoDB at `mongodb://localhost:27017` unless `MONGO_URL` is set, either in the
36
- environment or in `playground/.env`.
37
- Sign-in with GitHub and Google is wired to `GITHUB_CLIENT_ID`,
38
- `GITHUB_CLIENT_SECRET`, `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`, read the
39
- same way: a provider's button appears on the login and register screens once
40
- both of its values are set, with
41
- `http://localhost:3001/auth/oauth/<provider>/callback` registered as its
42
- callback URL.
5
+ <a href="https://www.npmjs.com/package/@antelopejs/dms-saas"><img alt="npm" src="https://img.shields.io/npm/v/@antelopejs/dms-saas?style=for-the-badge&labelColor=000000&color=000000"></a>
6
+ <a href="./LICENSE"><img alt="License" src="https://img.shields.io/npm/l/@antelopejs/dms-saas?style=for-the-badge&labelColor=000000&color=000000"></a>
7
+ <a href="https://discord.gg/sjK28QHrA7"><img alt="Discord" src="https://img.shields.io/badge/Discord-18181B?logo=discord&style=for-the-badge&color=000000"></a>
8
+ <a href="https://dms.antelopejs.com/docs/modules/saas"><img alt="Documentation" src="https://img.shields.io/badge/Docs-18181B?style=for-the-badge&color=000000"></a>
43
9
 
44
- ### Playground data set
10
+ Sign-up, plans, Stripe billing and a back office for a multi-tenant AntelopeJS DMS.
45
11
 
46
- On its first start against an empty database, the playground writes a data set
47
- to review every screen with: sign in as `admin@example.com` with the password
48
- `Playground-Admin-1!` (a platform admin who also owns the `acme` workspace).
49
- Every other seeded account, platform admins `hugo@antelope.io` and
50
- `sofia@antelope.io` and the workspace owners and members, uses the same
51
- password.
12
+ </div>
52
13
 
53
- It holds the feature and plan catalogue (Free, Starter, Pro, Team, Business
54
- per seat, Enterprise yearly and hidden, Growth 2024 retired), thirteen
55
- workspaces in every billing state (active, trialing, free, complimentary with
56
- and without an end date, past due, pending payment, suspended, cancelled) with
57
- their members and pending invitations, invoices in every status, credit notes,
58
- plan migrations, segments, internal notes, billing rules and legal documents.
59
- Dates are relative to the first start, and Stripe ids are fake: nothing calls
60
- Stripe for them.
14
+ ![The SaaS back office dashboard: what needs attention, recurring revenue and workspaces by status](https://raw.githubusercontent.com/AntelopeJS/dms-saas/main/packages/dms-saas/docs/images/dashboard.png)
61
15
 
62
- The seed lives in `playground/src/seed` and runs once: the platform admin
63
- account, written last, marks it complete. Drop the database to start over. On
64
- each later start it only adds newly registered permissions to the seeded plans,
65
- so pages added to the module stay visible to workspace owners. Segment counts
66
- appear after the first segment recompute (every 15 minutes), and the running
67
- plan migration turns to "reconciliation required" on the next restart, as an
68
- interrupted migration does.
16
+ ## What it does
69
17
 
70
- ## Completing a registration that entered without a workspace
18
+ - Adds public pricing and registration screens, legal pages, and a completion screen for OAuth sign-ins.
19
+ - Defines plans whose permissions cap what each workspace can do, with features, limits, trials and seat pricing.
20
+ - Bills through Stripe: checkout, subscriptions, invoices, credit notes, refunds and Stripe Tax, with plans kept in sync.
21
+ - Gives workspace owners their settings: general, members, billing and data export.
22
+ - Gives the platform owner a back office: workspaces, users, segments, plan migrations, billing rules and legal documents.
71
23
 
72
- An account can reach the product before it owns anything to log into: an OAuth
73
- sign-in for an unknown e-mail, or any entry point the core answers with
74
- `requires_tenant_assignment`. The `auth/no-workspace` page is where that
75
- account opens its first workspace — on the free plan, with a card when
76
- `registration.paymentMethod` asks for one — and
77
- `POST /api/saas/register/finalize` provisions it and answers with a token pair
78
- for the workspace it just created, so the visitor lands signed in instead of
79
- back on the login screen.
24
+ ## Install
80
25
 
81
- The page never touches those tokens. It posts the call through the frontend
82
- loader's generic `POST /auth/establish` route, naming the endpoint to call and
83
- its payload; the loader calls `/api/saas/register/finalize` itself over its own
84
- server-to-server channel to the DMS API and writes its session cookie from what
85
- comes back. Because that route turns a backend endpoint into a login, it only
86
- calls endpoints the deployment named, so a project serving this page must
87
- declare the finalize endpoint in the frontend server's environment:
26
+ Run the AntelopeJS CLI from the root of a project that loads `@antelopejs/dms` in multi-tenant mode, with an e-mail module and a file storage:
88
27
 
89
28
  ```bash
90
- # .env of the frontend server
91
- DMS_AUTH_ESTABLISH_ENDPOINTS=/api/saas/register/finalize
92
- ```
93
-
94
- Without it the loader answers `403` and a visitor who has just registered stays
95
- signed out. A replacement completion screen keeps the same requirement, and can build
96
- its request with the auto-imported `buildSessionEstablishRequest()` helper
97
- rather than restating the endpoint and the payload shape.
98
-
99
- ## Tenant owner permissions
100
-
101
- The `dms-saas.plan-intersection` permissions resolver runs at order 100. For a
102
- member whose `isTenantOwner` is true in the requested tenant, it grants all
103
- explicit permissions from that tenant's resolved plan, including inherited
104
- permissions, regardless of assigned roles. Permissions outside the plan are
105
- removed even when a role grants them. Other members retain only the intersection
106
- of their incoming permissions and the resolved plan.
107
-
108
- A plan grants exactly the ids it lists, nothing nested under them: the plan
109
- editor's permission tree adds a node's descendants and ancestors when it is
110
- ticked, so plans built from the UI list every component id, and plans seeded by
111
- code must list them too.
112
-
113
- Tenant ownership never grants `*`, even if a plan contains it. An incoming `*`
114
- (including the DMS platform owner's wildcard) retains the existing behavior:
115
- the wildcard survives, and other incoming permissions are intersected with the
116
- plan. Without a subscription, a `planId`, or an existing plan, the resolver
117
- preserves incoming permissions and grants nothing new. This compatibility
118
- fallback is not a denial of access for tenants with missing billing data.
119
-
120
- Applications define their business permissions and can project the capabilities
121
- that survive the plan into resource-specific actions in later resolvers. They
122
- do not need a separate tenant-owner grant list. Subscription access gates remain
123
- independent and unchanged. This resolver alone does not constrain
124
- `defaultGranted` permissions or guards that do not consult effective permissions.
125
-
126
- ## Registration
127
-
128
- Public registration is short: an account (name, e-mail, password) and the
129
- acceptance of the terms, plus a card when the deployment asks for one. The
130
- workspace it opens lands on the catalogue's first free plan — the lowest
131
- `order` among active plans priced 0 and open to individuals — under a default
132
- name its owner renames from the workspace settings. Customer type, billing
133
- address, VAT number and plan choice belong to the upgrade flow. Registration
134
- answers `409 saas.errors.plan.no_free_plan` while the catalogue has no such
135
- plan.
136
-
137
- `POST /api/saas/register` holds the password to the DMS password policy
138
- (`isPasswordCompliant` from `@antelopejs/interface-dms/auth/password`) before
139
- it looks the e-mail up or creates anything, and answers
140
- `400 saas.errors.registration.password_policy` otherwise. The OAuth completion
141
- carries no password.
142
-
143
- Two module options shape it:
144
-
145
- ```json
146
- {
147
- "modules": {
148
- "dms-saas": {
149
- "config": {
150
- "admissionMode": "open",
151
- "registration": { "paymentMethod": "required" }
152
- }
153
- }
154
- }
155
- }
156
- ```
157
-
158
- `registration.paymentMethod` decides whether registration asks for a card:
159
-
160
- | Value | Behaviour |
161
- | --- | --- |
162
- | `required` (default) | The card step is shown and must be completed. The workspace gets a Stripe customer holding that card and a free subscription — a local one while the free plan is off Stripe, which the upgrade checkout replaces on that customer — and the free-workspace-per-card cap applies when it is on. |
163
- | `optional` | The card step is shown, and the visitor may choose to add a card later. Without a card the workspace is card-less, as under `none`. |
164
- | `none` | The card step is never shown, `GET /api/saas/register/setup-intent` answers `400 saas.errors.registration.payment_method_disabled`, and Stripe is never called: the workspace gets a local free subscription with no Stripe customer, which the upgrade checkout creates when the owner first pays. A card sent anyway is ignored. |
165
-
166
- The free-workspace-per-card cap ("Free workspaces per card" in the operator
167
- billing rules) is off by default (`0`): limiting free workspaces per person is
168
- usually the consuming SaaS's own business rule. An operator may turn it on;
169
- it then asks a card of every free workspace created in the app.
170
-
171
- Under `optional` and `none`, a card-less workspace has no card fingerprint, so
172
- the free-workspace-per-card cap does not apply to it: the only remaining limit
173
- on free workspaces is one account per e-mail address.
174
-
175
- The option covers both public entry points — `POST /api/saas/register` and the
176
- `auth/no-workspace` completion — and nothing else: invitation sign-up never
177
- asks for a plan or a card, whatever `admissionMode` and
178
- `registration.paymentMethod` say. Tenant-side workspace creation keeps
179
- requiring a card.
180
-
181
- `admissionMode: "invitation-only"` closes public registration: every
182
- `/api/saas/register` route answers `403 saas.errors.registration_closed` before
183
- looking at the card policy, the registration screens render a "registration by
184
- invitation only" state instead of the form, and the login page drops its
185
- sign-up link. Invitations keep working.
186
-
187
- Both values reach the browser through the frontend module options
188
- (`useDmsRuntimeConfig().public.dmsSaas.admissionMode` and
189
- `.registrationPaymentMethod`); `useSaasRegistration()` already reads them.
190
-
191
- The Stripe SetupIntent behind the card step is restricted to cards on the
192
- server (`allowed_payment_method_types: ["card"]`, since Stripe is retiring
193
- `payment_method_types` on SetupIntent creation); the Payment Element is
194
- created from its client secret alone, since Stripe refuses
195
- `paymentMethodTypes` next to a `clientSecret`.
196
-
197
- ## Default plan
198
-
199
- A workspace is never without a plan. The default plan is the catalogue's
200
- first free plan — the lowest `order` among active plans priced 0 and open to
201
- individuals — unless `defaultPlanSlug` names another such plan:
202
-
203
- ```json
204
- { "modules": { "dms-saas": { "config": { "defaultPlanSlug": "free" } } } }
205
- ```
206
-
207
- It is what registration opens, and it is attached, as an active card-less
208
- subscription, to every workspace that has no subscription at all — the
209
- platform's `default` tenant and workspaces created outside dms-saas included.
210
- The backfill runs at startup and with the billing-state recompute every 15
211
- minutes, and the billing page covers a workspace on first read; each pass is
212
- idempotent and never touches a workspace that holds any subscription. While
213
- the catalogue has no free plan, nothing is attached and a warning is logged.
214
-
215
- Once attached, the plan's permissions cap the workspace's members like any
216
- other plan (see [Tenant owner permissions](#tenant-owner-permissions)).
217
-
218
- ## Stripe API version and webhooks
219
-
220
- Every Stripe request is made with API version `2026-08-26.dahlia`, the version
221
- the installed `stripe` SDK (v22) is generated for (`STRIPE_API_VERSION` in
222
- `src/stripe/client.ts`; the build fails if the two drift apart).
223
-
224
- A webhook endpoint renders its events in its **own** API version, set in the
225
- Stripe Dashboard (Developers → Webhooks → the endpoint → API version), not in
226
- the version of the requests. **Every endpoint that targets
227
- `/api/saas/webhooks/stripe` must use `2026-08-26.dahlia`.** Until it does,
228
- dms-saas still accepts events rendered in older versions: the fields basil
229
- moved — the subscription billing period (now on each subscription item), the
230
- invoice's subscription (`parent.subscription_details`), invoice and credit
231
- note taxes (`total_taxes`), and the credit note refund (`refunds`) — are read
232
- from their basil location first and from their older one second. The clover
233
- and dahlia releases moved none of the fields dms-saas reads.
234
-
235
- New subscriptions, whether created at registration or by Checkout, are opened
236
- in the `classic` billing mode (`billing_mode[type]=classic`). Since
237
- `2025-09-30.clover` Stripe defaults new subscriptions to `flexible`, which no
238
- longer invoices a free-to-paid upgrade at once and records Customer Portal
239
- cancellations as `cancel_at` instead of `cancel_at_period_end`; the plan-change
240
- flows rely on the `classic` behaviour every existing subscription has.
241
-
242
- Checkout Sessions opt out of Stripe Managed Payments
243
- (`managed_payments[enabled]=false`). An account that enabled Managed Payments
244
- applies it to every session by default, but dms-saas is its own merchant of
245
- record: it collects tax ids, runs Stripe Tax on its invoices, injects invoice
246
- items and issues credit notes, none of which a Managed Payments session allows.
247
-
248
- ## Starting a paid plan
249
-
250
- Moving a workspace without a Stripe subscription to a paid plan opens a Stripe
251
- Checkout Session. The request is recorded on the subscription as a pending
252
- checkout before Stripe is called, and the session's completion or expiry
253
- webhook resolves it. A pending checkout never blocks the owner for good:
254
-
255
- - when Stripe refuses to open the session (a 4xx answer), the pending
256
- checkout, the trial it reserved and the Stripe customer it created are
257
- rolled back, and the request answers
258
- `422 saas.errors.billing.checkout_rejected`; the owner can retry at once;
259
- - when Stripe cannot be reached or answers a 5xx, a session may exist, so the
260
- pending checkout stays and the request answers
261
- `503 saas.errors.billing.checkout_unavailable`;
262
- - the next attempt reconciles what it finds: a pending checkout whose recorded
263
- session has expired, or which never recorded a session within 15 minutes, is
264
- released and a new session is opened. Its redirect URL only reaches the
265
- owner once the session is recorded, so an unrecorded session is one nobody
266
- can pay;
267
- - a recorded session that is still open answers
268
- `409 saas.errors.plan.checkout_in_progress`, and any other pending plan
269
- change `409 saas.errors.plan.change_in_progress`.
270
-
271
- ## Plans and Stripe
272
-
273
- dms-saas keeps every plan billed through Stripe linked to a Stripe product and
274
- price that match it, whoever writes the plan: the platform-owner plan editor,
275
- or a module that seeds its catalogue straight into the plan table. A writer
276
- sets the plan's name, description, price, currency, interval and billing mode,
277
- and leaves `paymentProviderRefs` alone — dms-saas owns it.
278
-
279
- A plan is billed through Stripe when its price is above 0, or when it is
280
- already linked to a Stripe price its subscriptions may be billed on. A plan
281
- priced 0 that never was stays off Stripe: its workspaces hold a local free
282
- subscription.
283
-
284
- The sync runs:
285
-
286
- - when the plan editor creates or saves a plan, after writing it (a Stripe
287
- error is reported to the editor, and the next pass retries the sync);
288
- - once DMS has initialised the database at startup, in the background, for
289
- every active plan;
290
- - whenever a plan is about to be offered or billed — the tenant plan catalogue,
291
- a plan change, an operator action, a new workspace — so a plan written after
292
- startup is linked the first time it matters.
293
-
294
- Outside the editor, a failed sync is logged and retried on the next pass; the
295
- plan meanwhile shows as not payable, and choosing it answers
296
- `400 saas.errors.plan.not_synced_with_stripe` as before. With a placeholder
297
- Stripe key, every sync is skipped.
298
-
299
- Each sync compares the plan with the terms recorded in
300
- `paymentProviderRefs.stripeSyncedTerms` and calls Stripe only when they differ:
301
-
302
- | What changed | Stripe effect |
303
- | --- | --- |
304
- | Nothing | none |
305
- | Name, description, or the billing settings' tax code | the product is updated in place |
306
- | Price, currency, interval or billing mode | a new price is created and the previous one archived; existing subscriptions stay on their price |
307
-
308
- Amounts are sent in the currency's minor unit (price × 100) and the currency
309
- in lowercase. A plan linked before the terms were recorded is read back from
310
- Stripe once: a price that still matches is kept, so its subscriptions still
311
- resolve to the plan.
312
-
313
- Every Stripe creation carries an idempotency key derived from the plan id, its
314
- creation time and the request, so replicas syncing the same plan at once, or a
315
- retry within Stripe's 24-hour window, land on the same product and price. Only
316
- `paymentProviderRefs` is written back: a sync never rolls back a concurrent
317
- edit, and one that raced an edit is out of line again and redone on the next
318
- pass.
319
-
320
- ## Plan feature labels and values
321
-
322
- A feature's `displayName` and `tooltip` are localized fields
323
- (`@Localized`, falling back to `en`): the row stores one value per locale and
324
- every reader gets the text in the viewer's language, taken from the
325
- `x-content-language` header the DMS frontend sends. The tenant plan pages and
326
- the plan admin pages show it as written; the features table in the platform
327
- admin edits it one language at a time.
328
-
329
- A module declaring features writes every locale at once through
330
- `localize("*")`, never i18n keys:
331
-
332
- ```ts
333
- const row = FeatureModel.fromPlainData({
334
- _id: "cloud.plan.egress",
335
- displayName: { en: "Included egress", fr: "Trafic sortant inclus" },
336
- tooltip: { en: "Outbound traffic", fr: "Trafic sortant" },
337
- // ...
338
- }).localize("*");
339
- await GetModel(FeatureModel).insert(row);
340
- ```
341
-
342
- Read a row with `localizeFeature(feature, locale)` from
343
- `@antelopejs/interface-dms-saas/plans`. A row without a value in the viewer's
344
- locale or in `en` has no tooltip.
345
-
346
- Values are formatted from the feature's `valueType` and `unit`: `-1` reads as
347
- unlimited, booleans as ✓/—, numbers are grouped in the viewer's locale. A
348
- `per <unit>` unit makes the value a price in the plan's currency, and
349
- `currency units` an amount of it. Known units are scaled to something a person
350
- reads at a glance; any other unit is shown verbatim after the grouped number.
351
- A text value follows the same convention as labels: a `$<key>` value is
352
- translated in the declaring module's locales, anything else is shown as stored.
353
-
354
- | Stored unit | Quantity reads as | `per <unit>` price reads as |
355
- |-------------|-------------------|-----------------------------|
356
- | `byte(s)` | bytes, KB, MB, GB or TB (powers of 1000) | per GB |
357
- | `minute(s)` | minutes | per minute |
358
-
359
- A module declaring features in its own units teaches the plan pages how they
360
- read with `registerPlanFeatureUnit`, auto-imported like the other dms-saas
361
- composables. Call it from a frontend plugin that runs on the server and in the
362
- browser, so server-rendered and hydrated values agree. Each scale says how
363
- many stored units it holds; a quantity takes the largest scale it fills, and a
364
- `per <unit>` price reads per `priceScale`. Labels are full i18n keys the module
365
- ships in its own locales, each a node holding a `quantity` message
366
- (`{value}`, pluralised on the scaled value) and a `price` message (`{price}`):
367
-
368
- ```ts
369
- // frontend-vue/app/plugins/plan-feature-units.ts
370
- const MINUTES_PER_HOUR = 60;
371
- const vcpuHour = { label: "cloud.plan.units.vcpu_hour", size: MINUTES_PER_HOUR };
372
-
373
- export default defineDmsPlugin(() => {
374
- registerPlanFeatureUnit(["vCPU-minute", "vCPU-minutes"], {
375
- scales: [vcpuHour],
376
- priceScale: vcpuHour,
377
- });
378
- });
379
- ```
380
-
381
- ```json
382
- {
383
- "cloud": {
384
- "plan": {
385
- "units": {
386
- "vcpu_hour": {
387
- "quantity": "{value} vCPU-hour | {value} vCPU-hours",
388
- "price": "{price} / vCPU-hour"
389
- }
390
- }
391
- }
392
- }
393
- }
394
- ```
395
-
396
- Units match case-insensitively, and a registered unit takes precedence over a
397
- built-in one of the same name.
398
-
399
- ## Extension points
400
-
401
- ### Consuming this module
402
-
403
- A module that extends dms-saas depends on the separately published interface
404
- package (`"@antelopejs/interface-dms-saas"` in its `dependencies`) and
405
- imports the extension points from it. The dms-saas runtime package remains a
406
- separate dependency for modules that need the implementation; its package root
407
- boots the registration graph:
408
-
409
- | Subpath | Surface |
410
- | --- | --- |
411
- | `@antelopejs/interface-dms-saas` | every extension point except `db`: billing, data API, pages, plans, provisioning and registration flat, plus the `invoiceLineItems` and `workspaceLifecycle` namespaces |
412
- | `@antelopejs/interface-dms-saas/billing` | customer balance, upcoming invoice preview and complimentary subscription state |
413
- | `@antelopejs/interface-dms-saas/data-api` | hidden-value data API filters |
414
- | `@antelopejs/interface-dms-saas/db` | canonical SaaS tables and data models |
415
- | `@antelopejs/interface-dms-saas/hidden-filter` | the `HiddenStringFilter` decorator on its own |
416
- | `@antelopejs/interface-dms-saas/invoice-line-items` | provider registration, line item types, line key helpers |
417
- | `@antelopejs/interface-dms-saas/page-definitions` | page and module ids, slugs and descriptors |
418
- | `@antelopejs/interface-dms-saas/pages` | workspace settings category and tenant billing page extensions |
419
- | `@antelopejs/interface-dms-saas/plans` | plan projections, catalog builder, and price normalization |
420
- | `@antelopejs/interface-dms-saas/provisioning` | provisioning hook payload |
421
- | `@antelopejs/interface-dms-saas/registration` | public registration capture limits |
422
- | `@antelopejs/interface-dms-saas/workspace-lifecycle` | workspace lifecycle events and operator actions |
423
-
424
- `invoiceLineItems` and `workspaceLifecycle` come off the root entry as
425
- namespaces because each carries an `internal` proxy namespace of its own; `db`
426
- is reachable only through its subpath, since importing it registers the SaaS
427
- tables.
428
-
429
- This module declares the interface package name in `antelopeJs.implements`, so as
430
- long as both modules run in the same AntelopeJS project, those imports are
431
- detoured to the running dms-saas instance instead of a second copy pulled from
432
- `node_modules`. Registration goes through an interface proxy on top of that: a
433
- provider registered before dms-saas is constructed is held and replayed on
434
- attach, replayed again when dms-saas is reloaded, and dropped when the
435
- registering module is unloaded.
436
-
437
- The interface package must be released before dms-saas, which depends on it
438
- through `>=<interface version> <0.<minor + 1>.0`: dms-saas implements the
439
- interface, so it caps the range below the next minor and a breaking interface
440
- minor never reaches a dms-saas that does not implement it. During workspace
441
- development pnpm resolves that range to the sibling package. Release the interface package first,
442
- then
443
- release dms-saas, and update consumers to the published interface version.
444
-
445
- ### Public screens
446
-
447
- dms-saas ships a working registration screen so a fresh project can sell from
448
- day one. It is a reference implementation, not a design: the module owns the
449
- money and the compliance of the flow, the consuming SaaS owns the conversion.
450
-
451
- Replacing it takes two steps. Turn the bundled page off in the module config —
452
- page registration is keyed by slug, so declaring a second page on `register`
453
- races the bundled one instead of overriding it:
454
-
455
- ```json
456
- {
457
- "modules": {
458
- "dms-saas": {
459
- "config": {
460
- "publicScreens": { "register": false }
461
- }
462
- }
463
- }
464
- }
465
- ```
466
-
467
- Then register your own page on the `register` slug and build it on the
468
- `useSaasRegistration()` composable the Vue adapter auto-imports. It holds the
469
- whole flow — the card policy, the Stripe setup intent and card confirmation,
470
- the order the requirements are validated in, the provisioning call and the
471
- landing route — and renders nothing, so a re-themed screen keeps the same
472
- steps:
473
-
474
- ```vue
475
- <script setup lang="ts">
476
- const {
477
- form, // name, email, password, hasAcceptedLegal, skipsPaymentMethod
478
- paymentElementId,
479
- canSkipPaymentMethod, // true under `optional`
480
- isPaymentStepVisible, // bind with v-show so the Stripe element stays mounted
481
- passwordStrength, // { strength, score, color } for <DmsPasswordStrength>
482
- isRegistrationClosed, // render the invitation-only state instead of the form
483
- errorMessage,
484
- isSubmitting,
485
- submit,
486
- } = useSaasRegistration({ redirectTo: "/welcome" });
487
- </script>
29
+ ajs project modules add @antelopejs/dms-saas
488
30
  ```
489
31
 
490
- Nothing it returns throws: a failure surfaces as a translated `errorMessage`,
491
- and `submit()` resolves to the new tenant id or `null`. A password outside the
492
- DMS policy stops `submit()` before the card is confirmed. The workspace name is
493
- the localised `saas.register.default_workspace_name`. Every screen stays
494
- enabled by default, so an existing project needs no configuration change.
495
-
496
- ### Registration extras and the provisioning hook
32
+ ## Quick start
497
33
 
498
- A SaaS that captures its own fields at signup — referral source, team size,
499
- anything — sends them as `extras` on the registration payload and writes them
500
- from a `TENANT_BEING_PROVISIONED` listener. dms-saas forwards the object
501
- verbatim: it never reads it, never stores it, never returns it. The data stays
502
- the consumer's, and so does the schema.
34
+ Give the module its Stripe keys from the environment:
503
35
 
504
36
  ```ts
505
- import type { TenantBeingProvisionedPayload } from "@antelopejs/interface-dms-saas/provisioning";
506
- import {
507
- Hook,
508
- RegisterHook,
509
- } from "@antelopejs/interface-dms/hooks";
510
-
511
- RegisterHook(
512
- Hook.TENANT_BEING_PROVISIONED,
513
- async ({ tenantId, userId, extras }: TenantBeingProvisionedPayload) => {
514
- await storeOnboardingAnswers(tenantId, userId, extras);
515
- return undefined;
37
+ // antelope.config.ts
38
+ export default defineConfig({
39
+ name: "my-saas",
40
+ envOverrides: {
41
+ STRIPE_SECRET_KEY: "modules.dms-saas.config.stripe.secretKey",
42
+ STRIPE_PUBLISHABLE_KEY: "modules.dms-saas.config.stripe.publishableKey",
43
+ STRIPE_WEBHOOK_SECRET: "modules.dms-saas.config.stripe.webhookSecret",
516
44
  },
517
- );
518
- ```
519
-
520
- `storeOnboardingAnswers` is your module's persistence function. Keep the explicit `undefined` return: this hook's handler contract is `Promise<undefined>`, not `Promise<void>`.
521
-
522
- **Contract**
523
-
524
- - The hook is emitted inside the provisioning transaction, once the workspace
525
- is complete and before it is handed back. Listeners run in series and are
526
- awaited; **a listener that throws cancels the registration** — tenant,
527
- subscription, Stripe customer and, on the password path, the account itself
528
- are rolled back. That is the point: a workspace that is paid for but missing
529
- the data its owner filled in is worse than no workspace.
530
- - It runs while the per-card provisioning lock is held, so a slow listener
531
- slows every concurrent signup on that card. Write, do not call out.
532
- - `extras` reaches both entry points — password registration and the
533
- OAuth-entry completion — and is absent when the consumer captured nothing.
534
- - Registration is public and unauthenticated, so `extras` is bounded before it
535
- is forwarded: **4 KB serialised, 64 keys, 4 levels deep**, and no
536
- `__proto__` / `constructor` / `prototype` key. Anything above answers 400
537
- with `saas.errors.registration.extras_*`. `REGISTRATION_EXTRAS_LIMITS` is
538
- available from `dms-saas/registration` so a consumer can bound
539
- its own capture first.
540
- - Nothing else in dms-saas depends on a listener existing: with no listener
541
- registered, registration behaves exactly as before.
542
-
543
- On the browser side, `useSaasRegistration()` takes the capture as an option
544
- and sends it with the rest of the form:
545
-
546
- ```vue
547
- <script setup lang="ts">
548
- const answers = reactive({ referral: "", teamSize: "" });
549
- const { form, submit } = useSaasRegistration({ extras: () => answers });
550
- </script>
551
- ```
552
-
553
- ### Invoice line items
554
-
555
- `RegisterInvoiceLineItemsProvider` lets a module bill its own metered usage on
556
- the workspace's subscription invoice. When Stripe opens the renewal invoice of
557
- a billing cycle, dms-saas asks every registered provider for the lines it wants
558
- and pushes them as Stripe invoice items while the invoice is still a draft, so
559
- they are charged on finalization.
560
-
561
- dms-saas stays agnostic: it never interprets a line. What a metric is, how it
562
- is measured and how it is priced belong to the provider.
563
-
564
- ```ts
565
- import {
566
- RegisterInvoiceLineItemsProvider,
567
- UnregisterInvoiceLineItemsProvider,
568
- } from "@antelopejs/interface-dms-saas/invoice-line-items";
569
-
570
- const PROVIDER_ID = "cloud";
571
-
572
- export async function construct(): Promise<void> {
573
- RegisterInvoiceLineItemsProvider({
574
- id: PROVIDER_ID,
575
- resolve: async ({ tenantId, periodStart, periodEnd, currency }) => {
576
- const usage = await aggregateUsage(tenantId, periodStart, periodEnd);
577
- return [
578
- {
579
- key: "vcpu-minutes",
580
- description: "vCPU minutes",
581
- amountCents: usage.vcpuCents,
582
- quantity: usage.vcpuMinutes,
583
- unit: "minute",
584
- },
585
- {
586
- key: "included-credit",
587
- description: "Included usage credit",
588
- amountCents: -usage.includedCreditCents,
45
+ modules: {
46
+ "dms-saas": {
47
+ source: { type: "package", package: "@antelopejs/dms-saas", version: "^0.6.0" },
48
+ config: {
49
+ stripe: {
50
+ secretKey: "sk_test_placeholder",
51
+ publishableKey: "pk_test_placeholder",
52
+ webhookSecret: "whsec_placeholder",
589
53
  },
590
- ];
591
- },
592
- });
593
- }
594
-
595
- export async function stop(): Promise<void> {
596
- UnregisterInvoiceLineItemsProvider(PROVIDER_ID);
597
- }
598
- ```
599
-
600
- **Contract**
601
-
602
- - Providers run on `subscription_cycle` invoices only — never on a
603
- subscription's first invoice nor on one-off invoices, which have no closed
604
- usage period behind them.
605
- - `periodStart` / `periodEnd` are the boundaries of the **cycle that just
606
- closed**, not of the upcoming cycle the plan line covers.
607
- - `amountCents` is an integer total in the invoice currency and may be
608
- negative: that is how a plan's included credit is deducted. Zero-amount lines
609
- are dropped. A structurally invalid line (non-integer amount, empty key or
610
- description, oversized or `:`-carrying key) fails the webhook event once
611
- every provider has run: it is usage that would otherwise never be billed.
612
- - `key` is the unit of idempotency, namespaced by the provider `id`. The same
613
- key is injected at most once per invoice, whatever the number of webhook
614
- redeliveries or concurrent workers — so keep it stable across cycles and
615
- never derive it from a timestamp. Neither `id` nor `key` may contain `:`,
616
- which joins them, and together they must stay under 150 characters — they
617
- compose the Stripe idempotency key. `quantity` and `unit` are recorded as
618
- Stripe metadata for auditability; the amount charged is always
619
- `amountCents`.
620
- - A resolver that throws is logged and skipped: the other providers still run
621
- and the invoice is still mirrored. Once every provider has been attempted,
622
- a partial injection fails the webhook so it surfaces instead of silently
623
- underbilling the cycle — replays cannot double-charge, every line being
624
- idempotent.
625
- - Resolvers run inside the Stripe webhook request. Read pre-aggregated
626
- rollups; a resolver that computes usage on the fly delays the webhook
627
- response for every provider.
628
- - Register in `construct()`, unregister in `stop()`. An `id` must be unique
629
- across modules: registering one that is already taken replaces the previous
630
- provider, whose usage lines then stop being invoiced. Registration is keyed
631
- by `id` all the way down to the interface proxy — which is both why a clash
632
- cannot be refused without stranding whichever module registered first, and
633
- why it is only reported at error level once dms-saas is attached. Two modules
634
- registering the same `id` before that collapse into one silently, so pick an
635
- `id` no other module could plausibly choose.
636
- - Resolvers are also called to price the [upcoming invoice
637
- preview](#upcoming-invoice-preview). Such a call carries `isPreview: true`,
638
- a synthetic `upcoming_<subscription id>` `invoiceId`, and a `periodEnd` set
639
- to the time of the request: the running cycle's usage so far. Its lines are
640
- only quoted to Stripe, never invoiced. A resolver that throws or returns an
641
- invalid line then makes the preview `unavailable` rather than short.
642
-
643
- ### Upcoming invoice preview
644
-
645
- `GetUpcomingInvoicePreview` returns what Stripe will bill the current
646
- workspace next, tax included, so a page can show the exact VAT and total before
647
- the invoice exists. Stripe computes every figure (Stripe Tax: country, VAT
648
- number, reverse charge); dms-saas copies them without recomputing any.
649
-
650
- ```ts
651
- import { GetUpcomingInvoicePreview } from "@antelopejs/interface-dms-saas/billing";
652
-
653
- const preview = await GetUpcomingInvoicePreview({ tenantId, userId });
654
- if (preview.status === "available") {
655
- const { taxMinorUnits, totalMinorUnits, currency } = preview;
656
- render({ tax: taxMinorUnits, total: totalMinorUnits, currency });
657
- }
658
- ```
659
-
660
- The scope must come from a trusted authentication boundary: the call rejects
661
- with `403` a user who is not a member of the tenant or is refused by the tenant
662
- access gate (a workspace awaiting its first payment, or suspended).
663
-
664
- The result is always one of three states, and Stripe errors never throw:
665
-
666
- | `status` | Meaning | `reason` |
667
- | --- | --- | --- |
668
- | `available` | Stripe priced the next invoice | — |
669
- | `absent` | Nothing to bill next | `free_plan`, `complimentary`, `customer_not_configured`, `subscription_not_configured` (no plan, or no Stripe subscription yet), `no_upcoming_invoice` (the subscription ends with the current cycle) |
670
- | `unavailable` | An invoice is due but cannot be priced exactly right now; the cause is logged | `stripe_not_configured` (placeholder keys), `tax_not_configured` (Stripe Tax inactive), `tax_location_invalid`, `tax_location_required`, `tax_calculation_failed`, `usage_unavailable` (a line items provider failed), `provider_error` (any other Stripe failure) |
671
-
672
- A missing payment method does not prevent a preview: Stripe prices the invoice
673
- all the same.
674
-
675
- An `available` preview carries:
676
-
677
- - `currency` (uppercase ISO 4217) and integer amounts in its minor units:
678
- `subtotalMinorUnits` (lines before discounts and tax),
679
- `totalExcludingTaxMinorUnits`, `taxMinorUnits`, `totalMinorUnits` (tax
680
- included) and `amountDueMinorUnits` (after the customer balance).
681
- - `taxes`: one entry per tax Stripe applied, with its amount, taxable amount,
682
- `ratePercentage`, `country`, `taxType` (`vat`…), `taxabilityReason` and
683
- `isReverseCharge`. `taxCountry` and `isReverseCharge` summarize them; a
684
- reverse-charged invoice has a zero tax amount and `isReverseCharge: true`.
685
- - `lines`: `subscription` for the plan, `usage` for the lines quoted by the
686
- [invoice line items](#invoice-line-items) providers (with their
687
- `usageLineKey`), `invoice_item` for any other pending Stripe item. Each has
688
- its pre-tax amount, its tax and its period. `hasMoreLines` flags a list
689
- Stripe truncated; the totals are always complete.
690
- - `periodStart` / `periodEnd` (the cycle the invoice closes), `billingDate`
691
- (when Stripe issues it), `usageThrough` (how far the quoted usage runs, null
692
- without usage lines) and `computedAt`. Dates are ISO 8601 strings.
693
-
694
- Usage is quoted up to the time of the request with the same providers, paid
695
- coverage window and line validation as the renewal invoice, so the preview's
696
- tax covers plan and usage together. It is an estimate of a cycle still running:
697
- the renewal invoice bills the whole cycle.
698
-
699
- Previews are cached per workspace for an hour, shared by every instance through
700
- the database. Set `upcomingInvoicePreviewCacheTtlSeconds` to change that
701
- lifetime, or to `0` to price every request. A cached preview is dropped as soon
702
- as the workspace's subscription (plan change, status) or billing identity
703
- (address, VAT number) changes locally, and when Stripe reports an invoice
704
- created, finalized, paid or voided, a subscription updated or deleted, or a
705
- customer updated. `unavailable` results are never cached. Display
706
- `computedAt` to tell the reader how current the figures are.
707
-
708
- The Stripe reads a page renders (this preview, the billing status, the VAT
709
- check) give up after `stripe.readTimeoutMs` (4000 ms by default) and are not
710
- retried unless `stripe.readMaxNetworkRetries` says so: a slow Stripe makes the
711
- preview `unavailable` rather than holding the page. Writes keep the Stripe
712
- SDK's own timeout and retries.
713
-
714
- ### Workspace settings pages
715
-
716
- A module adding a page to a workspace's settings takes the side-effect-free
717
- `workspaceSettingsCategory` descriptor from the interface rather than
718
- rebuilding its hierarchy and metadata. The descriptor supports synchronous
719
- `PageController` declarations but is intentionally not reference-equal to the
720
- registered runtime object. Runtime code that requires canonical identity can
721
- await `GetWorkspaceSettingsCategory()` after the SaaS runtime implements the
722
- interface.
723
-
724
- ```ts
725
- import { PageController, RegisterPage } from "@antelopejs/interface-dms/page";
726
- import { workspaceSettingsCategory } from "@antelopejs/interface-dms-saas/pages";
727
-
728
- @RegisterPage()
729
- export class WorkspaceRegistriesController extends PageController("registries", {
730
- displayName: "$cloud.workspace.registries.title",
731
- category: workspaceSettingsCategory,
732
- icon: "i-ph-package",
733
- order: 10,
734
- }) {}
735
- ```
736
-
737
- Extensions of the existing tenant billing page register components through
738
- stable page and anchor identifiers. They do not import the page controller,
739
- which would load the module's page registration graph. An anchor names a block
740
- (`tenantBillingPage.components.planCard`) wherever the page lays it out: the
741
- plan card sits in a two-column grid, and a block placed after it stacks under
742
- it in the same column.
743
-
744
- ```ts
745
- import { CustomComponent } from "@antelopejs/interface-dms/base/custom";
746
- import {
747
- RegisterTenantBillingPageExtension,
748
- tenantBillingPage,
749
- type TenantBillingPageExtensionRegistration,
750
- } from "@antelopejs/interface-dms-saas/pages";
751
-
752
- let billingBlocks: TenantBillingPageExtensionRegistration | undefined;
753
-
754
- export function construct(): void {
755
- billingBlocks = RegisterTenantBillingPageExtension({
756
- name: "CloudBillingBlocks",
757
- components: [
758
- {
759
- key: "inProgressInvoice",
760
- component: CustomComponent("CloudInProgressInvoice"),
761
- side: "after",
762
- anchorKey: tenantBillingPage.components.planCard,
763
54
  },
764
- ],
765
- });
766
- }
767
-
768
- export function stop(): void {
769
- billingBlocks?.unregister();
770
- billingBlocks = undefined;
771
- }
772
- ```
773
-
774
- Platform modules can extend the SaaS platform-owner workspace detail without
775
- importing its controller or the private `saasModule` instance. Use
776
- `platformSaasModule`, `platformWorkspaceDetailPage`, and
777
- `RegisterPlatformWorkspaceDetailPageExtension` from the same public `pages`
778
- entry point. `platformSaasModule` is also a synchronous descriptor; runtime
779
- code that requires the registered module root can await
780
- `GetPlatformSaasModule()`. Platform data controllers that must hide a tenant
781
- routing field can import `HiddenStringFilter` from
782
- `@antelopejs/interface-dms-saas/data-api`; the underlying
783
- SaaS data controllers and database models remain private.
784
-
785
- ### Platform-owner operations and workspace lifecycle
786
-
787
- The platform-owner workspace page provides suspension, reactivation, immediate
788
- Stripe-backed upgrades, and Stripe customer-balance credits. Every request
789
- uses a caller-supplied operation ID and creates a private durable command intent
790
- before any Stripe or lifecycle effect. The command state retains the actor,
791
- tenant, action, redacted-safe values, attempts, outcome, and effective time.
792
- Retrying the same ID and values resumes an eligible failed operation; reusing
793
- it with different values is rejected.
794
-
795
- Operator attempts do not use leases or timed takeover. A definitive failure
796
- whose execution has finished may retry with the same operation and provider
797
- payload for 23 hours from intent creation. This preserves a one-hour margin
798
- inside Stripe's minimum 24-hour idempotency retention. An unknown outcome,
799
- including lost journal acknowledgement, requires reconciliation instead.
800
-
801
- Suspension, reactivation, and immediate plan changes persist a subscription
802
- transition before effects. Its revision fences competing local transitions and
803
- deletion; the operator journal must succeed before its intent is cleared.
804
- An ordinary subscription write rejects pending transitions and deletion markers.
805
- This does not provide distributed transactions or fence an external request
806
- that has already left the process.
807
-
808
- Inspect an operation through the platform-owner-only endpoint
809
- `GET /api/saas/workspaces/:tenantId/operations/:operationId`. A running or
810
- reconciliation-required operation may have an old executor still active.
811
- Before resolving it, establish **both** that the previous executor is stopped
812
- or quiescent and what happened externally, using the persisted operation,
813
- provider request details, and provider records. A matching Stripe read alone
814
- does not establish quiescence. There is deliberately no force-success endpoint
815
- that clears the intent without those proofs. This trades automatic crash
816
- recovery and availability for protection against conflicting external effects.
817
-
818
- Bulk plan migrations capture an immutable workspace list and resolved target
819
- configuration before admitting an execution. Each workspace gets a persisted
820
- outcome and a subscription transition before provider effects. A crash after
821
- changing `planId` does not remove that workspace from the snapshot. Running
822
- jobs never use timed takeover; startup marks interrupted jobs as
823
- `reconciliation_required`, retaining their per-workspace evidence and pending
824
- subscription intents instead of blindly replaying effects.
825
-
826
- The `migrate-and-delete` endpoint requests a migration only.
827
- Inspect `GET /api/saas/plans-deletion/migrations/:migrationId` for the snapshot,
828
- outcomes, and reconciliation requirements. **Snapshot completion does not retire
829
- the source plan.** The source remains available even at zero observed references;
830
- workspaces arriving after capture are outside this job. Any later retirement
831
- requires a separate procedure that establishes writer quiescence. A current
832
- reference count cannot exclude a suspended writer that already validated the plan.
833
-
834
- Migration reconciliation requires stopping or proving quiescence of the prior
835
- executor and establishing the provider, subscription, permission-cleanup, and
836
- notification outcomes. A target `planId` or matching Stripe response alone is
837
- not sufficient. Failed core lifecycle admissions may also remain closed to
838
- destruction until their evidence is resolved. There is no automatic force-success
839
- or effect-replay endpoint; arbitrary hooks are not made idempotent by a job ID.
840
-
841
- Self-service cancellation, deferred plan changes, and administrative free grants
842
- also admit subscription intent before Stripe effects. An ambiguous schedule
843
- replacement retains the previous mirror and pending intent; it does not attempt
844
- to restore or erase provider state blindly. Owners can inspect these intents and
845
- the irreversible deletion marker through the workspace `admin-state` endpoint.
846
-
847
- Checkout holds a `checkout` intent until the exact recorded session completes
848
- or expires. Completion admits one callback executor and writes a terminal session
849
- receipt only after its awaited provider effects finish. Unknown callback outcomes
850
- retain intent rather than enabling timed replay. A session whose ID was never
851
- acknowledged locally requires manual reconciliation, including executor quiescence.
852
- Trial reservations are permanent across checkout expiration; uncertain attempts
853
- do not receive another trial. Checkout automation remains best-effort, outside
854
- the terminal receipt, and does not promise exactly-once delivery or external order.
855
-
856
- Stripe webhook dispatch admits an event once and fences completion with its
857
- admitted revision. An old `pending` record never permits timed takeover. Handler
858
- failures become `reconciliation_required`, which blocks replay because the
859
- attempt may have partial effects. Redelivery receives an error while unresolved, rather than a successful acknowledgement or another execution.
860
-
861
- Inspect `stripe_webhook_events` by Stripe event ID for its result, revision, and
862
- error message. Recovery requires establishing the prior executor's quiescence
863
- and the handler's database and external outcomes; do not delete the admission
864
- or resend blindly. There is no automatic recovery endpoint. Unresolved records
865
- remain indefinitely. The existing retention policy still removes old terminal
866
- `success`/`skipped` receipts, so deduplication is not guaranteed after that window.
867
-
868
- Revision mutations require the published database interface `0.1.6` or later
869
- and an adapter implementing that contract. The MongoDB test adapter uses `1.3.1`,
870
- and any DMS release carrying this module satisfies the requirement. Every
871
- record is written with a revision, and these mutations refuse a record without
872
- one; see [Upgrading](#upgrading) for rows written by earlier builds.
873
-
874
- Lifecycle-dependent modules register a required consumer through the public
875
- interface:
876
-
877
- ```ts
878
- import {
879
- RegisterWorkspaceLifecycleConsumer,
880
- type WorkspaceLifecycleConsumerRegistration,
881
- } from "@antelopejs/interface-dms-saas/workspace-lifecycle";
882
-
883
- let lifecycleRegistration: WorkspaceLifecycleConsumerRegistration | undefined;
884
-
885
- export function construct(): void {
886
- lifecycleRegistration = RegisterWorkspaceLifecycleConsumer({
887
- name: "cloud.workspaces",
888
- transitions: ["suspended", "reactivation_requested"],
889
- async consume(message) {
890
- const receipt = await applyWorkspaceLifecycle(message);
891
- return {
892
- receiptId: receipt.id,
893
- effectiveAt: receipt.effectiveAt,
894
- };
895
55
  },
896
- });
897
- }
898
-
899
- export function stop(): void {
900
- lifecycleRegistration?.unregister();
901
- lifecycleRegistration = undefined;
902
- }
56
+ // dms, api, mongodb, auth-jwt, nodemailer, file-storage-local, ...
57
+ },
58
+ });
903
59
  ```
904
60
 
905
- Registration may happen before dms-saas construction: dms-saas replays buffered
906
- consumers when it attaches its module-owned registry. Registrations are removed
907
- automatically when their owning module unloads; the explicit handle remains
908
- available for module stop compatibility. Register required consumers during
909
- module construction, before module startup reconciliation. Messages carry
910
- stable `tenantId` and `operationId` values. Deliveries and receipts are
911
- persisted; a persisted success is skipped on later retries. Concurrent
912
- reconcilers may invoke the same consumer more than once before its receipt is
913
- persisted. Consumers must deduplicate concurrent calls by operation identity;
914
- the outbox does not provide exactly-once execution or ordering of external
915
- effects. Failed deliveries remain available to startup reconciliation and a
916
- five-minute retry worker. Suspension
917
- closes SaaS access before consumer delivery. Reactivation keeps SaaS access
918
- closed until every required consumer returns a durable receipt; the consumer
919
- therefore owns any product-specific sleep or wake work.
920
-
921
- #### Successful workspace creation
922
-
923
- Provisioning reserves free-workspace capacity per card and trial eligibility
924
- per email/card identity before issuing provider effects. Reservations do not
925
- expire. An unknown provider or persistence outcome keeps the reservation and
926
- the account for reconciliation; the service never replays opaque provisioning
927
- hooks or stores their `extras`. Known provider handles and the attempt ID are
928
- persisted separately from billing profiles. Stripe customer metadata also
929
- contains the attempt ID for investigating a lost creation response.
930
-
931
- Platform owners inspect the first 100 unresolved records through
932
- `GET /api/saas/workspaces/provisioning-attempts` and an individual record through
933
- `GET /api/saas/workspaces/:tenantId/provisioning-attempt`. Preparing records can
934
- represent an executor that disappeared before recording its error. Establish
935
- executor quiescence, provider cancellation or successful creation, and tenant
936
- closure before repairing a record or releasing an allocation. This release
937
- does not provide an automated repair command. Never release uncertain
938
- reservations by age or re-run non-idempotent hooks with guessed input.
939
-
940
- Every consumer declares the transitions it handles, for example
941
- `transitions: ["created"]` for creation only or all three when it also handles
942
- suspension and reactivation. A consumer must return a durable receipt and
943
- deduplicate effects by `operationId`:
944
- `workspace-created:<tenantId>` remains stable across delivery retries.
61
+ Then point a Stripe webhook at `https://<api>/api/saas/webhooks/stripe`, set `DMS_AUTH_ESTABLISH_ENDPOINTS=/api/saas/register/finalize` in the frontend server's environment, and publish a free plan in **Modules › SaaS › Plans**: registration opens every workspace on it. With placeholder keys the module still runs, and the Stripe-backed blocks say so.
945
62
 
946
- Self-service provisioning writes a creation marker in the existing lifecycle
947
- outbox **before inserting the tenant**. Only after ownership, billing records
948
- and every `TENANT_BEING_PROVISIONED` listener succeed does it allow payment
949
- confirmation. Trials and creations without an invoice require no payment;
950
- zero-total invoices already marked paid are not paid again. An invoice-backed
951
- creation becomes committed only after Stripe reports its first invoice paid.
952
- Consumer failures never roll back committed workspaces.
63
+ ## Compatibility
953
64
 
954
- Inventory reconcilers must check the public provisioning gate before creating
955
- external resources. This check prevents a concurrent inventory scan from
956
- provisioning a tenant whose membership, hooks or payment are still incomplete.
957
- It does not replace tenant existence, authorization or suspension checks.
958
-
959
- ```ts
960
- import { IsWorkspaceProvisioningCommitted } from
961
- "@antelopejs/interface-dms-saas/workspace-lifecycle";
962
-
963
- async function reconcileTenant(tenantId: string): Promise<void> {
964
- if (!(await IsWorkspaceProvisioningCommitted(tenantId))) return;
965
- await ensureWorkspaceResources(tenantId);
966
- }
967
- ```
65
+ | Package | Version |
66
+ | --- | --- |
67
+ | `@antelopejs/dms` | `>=0.9.0 <1.0.0` |
68
+ | `@antelopejs/interface-dms` | `>=0.7.0 <1.0.0` |
69
+ | `@antelopejs/dms-frontend` (renderer) | `>=0.6.0 <0.7.0` |
70
+ | `@antelopejs/interface-dms-saas` | `>=0.4.0 <0.5.0` |
71
+ | Stripe API version | `2026-08-26.dahlia` |
968
72
 
969
- The gate returns true for legacy/default/bootstrap tenants without a creation
970
- marker. It returns false for preparing, unpaid or cancelled creations, and
971
- propagates storage failures; callers must fail closed. Cancellation leaves a
972
- tombstone so even a partial rollback cannot make an orphaned tenant eligible.
973
- Do not delete these markers while the tenant may remain in an inventory.
73
+ On DMS 0.8, use `@antelopejs/dms-saas` 0.5. Before upgrading an existing database, read [Upgrading](https://dms.antelopejs.com/docs/modules/saas/faq#upgrading).
974
74
 
975
- Reconciliation recovers a crash after successful payment but before delivery,
976
- partial consumer fan-out and lost receipts. It may deliver a message again
977
- when a consumer commits its effect before the receipt is saved. Consumers must
978
- make their resource creation and ownership linkage idempotent. Delivery skips
979
- tenants already deleted when the attempt starts; consumers must also tolerate
980
- deletion racing with an in-flight attempt.
75
+ ## Documentation
981
76
 
982
- A definitive card decline permits rollback only after tenant lifecycle
983
- admission closes and all required deletion hooks succeed. An incomplete
984
- closure preserves data, account ownership, and recovery markers. Rollback
985
- never drops the tenant schema or the lifecycle/invitation tombstones. An
986
- ambiguous payment error preserves the tenant and account because a timeout can
987
- hide a successful charge. Reconciliation checks payment status but never starts
988
- another charge. A crash before payment, an unpaid ambiguous result, or an
989
- interrupted pre-payment preparation requires payment/provisioning recovery;
990
- it never emits `created` merely because the tenant exists. HTTP creation requests
991
- are not made idempotent by the delivery operation ID.
77
+ - [Introduction](https://dms.antelopejs.com/docs/modules/saas/introduction)
78
+ - [Installation](https://dms.antelopejs.com/docs/modules/saas/installation)
79
+ - [Configuration](https://dms.antelopejs.com/docs/modules/saas/configuration)
80
+ - [Usage](https://dms.antelopejs.com/docs/modules/saas/usage/public-screens)
81
+ - [Extending](https://dms.antelopejs.com/docs/modules/saas/extending)
82
+ - [FAQ](https://dms.antelopejs.com/docs/modules/saas/faq)
83
+ - [Stripe](https://dms.antelopejs.com/docs/modules/saas/stripe)
84
+ - [Operations](https://dms.antelopejs.com/docs/modules/saas/operations)
992
85
 
993
- Register consumers before startup reconciliation; use the existing
994
- tenant inventory and gate for bootstrap/backfill rather than treating `created`
995
- as a historical inventory API.
86
+ The guide's sources live in [`packages/dms-saas/docs`](https://github.com/AntelopeJS/dms-saas/tree/main/packages/dms-saas/docs). The module ships the `dms-saas` Claude Code skill in [`packages/dms-saas/skills`](https://github.com/AntelopeJS/dms-saas/tree/main/packages/dms-saas/skills), declared under `antelopeJs.skills`.
996
87
 
997
- ## Upgrading
88
+ ## Contributing
998
89
 
999
- ### Rows written by earlier builds
90
+ This package lives in the [`AntelopeJS/dms-saas`](https://github.com/AntelopeJS/dms-saas) pnpm workspace, next to `@antelopejs/interface-dms-saas`. Read [CONTRIBUTING.md](https://github.com/AntelopeJS/dms-saas/blob/main/CONTRIBUTING.md) and the [repository README](https://github.com/AntelopeJS/dms-saas#contributing) for the development commands.
1000
91
 
1001
- Billing no longer infers state from rows that predate the current fields. Rows
1002
- imported from the pre-DMS codebase or written by earlier builds must be fixed
1003
- in the database, with writers stopped, before upgrading:
92
+ ## License
1004
93
 
1005
- - **`features.displayName` and `features.tooltip`** are localized. Rows
1006
- written by earlier builds hold a plain string (often a `$` i18n key) that
1007
- the localized readers cannot use. Drop the `features` table and let the
1008
- declaring modules write it again on startup, then re-enter any feature
1009
- created by hand.
1010
- - **`tenant_subscriptions.isComplimentary`** is required. Only
1011
- `isComplimentary: true` makes a subscription complimentary; a missing value
1012
- is read as not complimentary. Set `isComplimentary: true` on admin gifts that
1013
- lack it (typically rows with no `stripeCustomerId`, no `stripeSubscriptionId`
1014
- and a status other than `pending_payment`), otherwise they are billed and
1015
- shown as paid plans. Backfill `isComplimentary: false` on every other row
1016
- that lacks the field, including workspaces created through paid provisioning
1017
- before this change, so the stored rows match the table type.
1018
- - **`invoices.documentType`** is required. Invoice lists and reads only match
1019
- `documentType: "invoice"`; a row without it is neither listed nor readable.
1020
- Set `documentType: "invoice"` on every invoice row that lacks it.
1021
- - **`stripe_webhook_events.result`** no longer accepts `failed`. Such attempts
1022
- may carry partial effects: establish their outcome as described for
1023
- `reconciliation_required` above, then set their result to
1024
- `reconciliation_required` or delete the record once resolved.
1025
- - **`revision`** is required on `tenant_subscriptions`, `segments`,
1026
- `user_segments`, `plan_migrations`, `stripe_webhook_events`,
1027
- `saas_lifecycle_deliveries` and `saas_operator_actions`. Revision-fenced
1028
- writes no longer adopt a row without one: they refuse it, so the workflow
1029
- holding that row stalls. Give every row lacking the field (absent or `null`)
1030
- an initial revision, any unique string such as a fresh UUID. Segments created
1031
- through the platform data API by earlier builds are the usual case.
1032
- - **`tenant_subscriptions.paidUsagePeriods`** is required. It is the only
1033
- source of usage coverage: a renewal invoice bills usage only inside a period
1034
- recorded for its own Stripe subscription, and a missing ledger is no longer
1035
- read as "bill the whole window". Rows lacking it (or holding `null`) are
1036
- typically default-plan, free-plan and pending-checkout subscriptions, and
1037
- workspaces created through paid provisioning. Set it by kind:
1038
- - a row with a `stripeSubscriptionId`, not complimentary:
1039
- `[{ stripeSubscriptionId, start, end: null }]`, where `start` is the Stripe
1040
- subscription's `start_date` (or any earlier date), so renewals keep billing
1041
- their whole window;
1042
- - every other row (no Stripe subscription, or `isComplimentary: true`): `[]`.
94
+ [Apache-2.0](./LICENSE)