@stacksjs/defaults 0.75.544 → 0.75.551

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.
Files changed (34) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-auto-imports/SKILL.md +1 -1
  3. package/ai/skills/stacks-commerce/SKILL.md +6 -3
  4. package/ai/skills/stacks-database/SKILL.md +1 -1
  5. package/ai/skills/stacks-desktop/SKILL.md +188 -3
  6. package/ai/skills/stacks-licensing/SKILL.md +214 -0
  7. package/ai/skills/stacks-migrations/SKILL.md +2 -2
  8. package/ai/skills/stacks-models/SKILL.md +2 -2
  9. package/ai/skills/stacks-native/CATALOG.md +11 -11
  10. package/ai/skills/stacks-orm/SKILL.md +2 -2
  11. package/ai/skills/stacks-payments/SKILL.md +7 -6
  12. package/ai/skills/stacks-writing-for-agents/SKILL.md +1 -1
  13. package/app/Actions/Commerce/Licensing/LicenseActivateAction.ts +36 -0
  14. package/app/Actions/Commerce/Licensing/LicenseCheckAction.ts +31 -0
  15. package/app/Actions/Commerce/Licensing/LicenseDeactivateAction.ts +20 -0
  16. package/app/Actions/Commerce/Licensing/LicenseResendAction.ts +47 -0
  17. package/app/Actions/Commerce/Licensing/LicenseSeatDestroyAction.ts +25 -0
  18. package/app/Actions/Commerce/Licensing/LicenseSeatIndexAction.ts +20 -0
  19. package/app/Actions/Commerce/Licensing/LicenseSeatStoreAction.ts +28 -0
  20. package/app/Actions/Commerce/Licensing/LicenseTransferAction.ts +32 -0
  21. package/app/Actions/Commerce/Licensing/license-response.ts +34 -0
  22. package/app/Actions/Commerce/Licensing/license-seat-access.ts +31 -0
  23. package/app/Actions/Desktop/UpdateFeedAction.ts +35 -0
  24. package/app/Mail/LicenseEmail.ts +80 -0
  25. package/app/Models/commerce/LicenseActivation.ts +98 -0
  26. package/app/Models/commerce/LicenseKey.ts +149 -7
  27. package/app/Models/commerce/LicenseSeat.ts +56 -0
  28. package/bootstrap.ts +35 -0
  29. package/ide/vscode/package.json +1 -1
  30. package/package.json +5 -5
  31. package/resources/emails/license.stx +52 -0
  32. package/routes/desktop-updates.ts +11 -0
  33. package/routes/licensing.ts +35 -0
  34. package/routes/payments.ts +9 -1
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: stacks-actions
3
- description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 736 default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/app/Actions/.
3
+ description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 747 default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/app/Actions/.
4
4
  license: MIT
5
5
  compatibility: Bun >= 1.3.0, TypeScript
6
6
  allowed-tools: Read Edit Write Bash Grep Glob
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: stacks-auto-imports
3
- description: Use before adding imports in Stacks app code, checking available runtime functions, browser/server delivery, model globals, or registry generation. Covers Stacks auto-imports, the generated runtime inventory, stx client delivery and server boot (108 models).
3
+ description: Use before adding imports in Stacks app code, checking available runtime functions, browser/server delivery, model globals, or registry generation. Covers Stacks auto-imports, the generated runtime inventory, stx client delivery and server boot (110 models).
4
4
  license: MIT
5
5
  compatibility: Bun >= 1.3.0, TypeScript
6
6
  allowed-tools: Read Edit Write Bash Grep Glob
@@ -8,7 +8,7 @@ allowed-tools: Read Edit Write Bash Grep Glob
8
8
 
9
9
  # Stacks Commerce
10
10
 
11
- Comprehensive e-commerce module with 15 sub-modules and 37 models.
11
+ Comprehensive e-commerce module with 15 sub-modules and 39 models.
12
12
 
13
13
  ## Key Paths
14
14
  - Core package: `storage/framework/core/commerce/src/`
@@ -71,7 +71,7 @@ Each sub-module typically provides:
71
71
  - Delivery routes and their stops
72
72
  - Couriers
73
73
  - Digital deliveries
74
- - License keys
74
+ - License keys (the delivery CRUD; selling and activating licenses is `commerce.licensing`, see `stacks-licensing`)
75
75
  - **Live tracking** (`commerce.shippings.tracking`) - see below
76
76
 
77
77
  ## Commerce Models (20+)
@@ -97,7 +97,7 @@ Each sub-module typically provides:
97
97
  | Courier | name, phone, vehicleNumber, status, latitude, longitude, heading, lastPingAt | hasMany: DeliveryRoute, CourierPing |
98
98
  | CourierPing | latitude, longitude, heading, speed, accuracy, recordedAt | belongsTo: Courier, DeliveryRoute |
99
99
  | TaxRate | name, rate(0-100), type(VAT/GST/Sales Tax) | |
100
- | LicenseKey | key(XXXX-XXXX-XXXX-XXXX-XXXX), template, status | belongsTo: Customer, Product, Order |
100
+ | LicenseKey | key(XXXX-XXXX-XXXX-XXXX-XXXX), template, tier, status, updatesUntil, maxDevices, seats | belongsTo: Customer, Product, Order, Team; hasMany: LicenseActivation, LicenseSeat |
101
101
  | DigitalDelivery | downloadLimit, expiryDays, automaticDelivery | |
102
102
  | WaitlistProduct | product waitlist tracking | |
103
103
  | Receipt | receipt records | |
@@ -325,6 +325,9 @@ is the helper for when the count is genuinely what you want.
325
325
  - Coupon types: `fixed_amount` or `percentage`
326
326
  - Gift card codes are unique and auto-generated
327
327
  - License keys follow XXXX-XXXX-XXXX-XXXX-XXXX format
328
+ - Software licensing (issue from a payment webhook, device activations, team
329
+ seats, signed offline tokens, the desktop client) is `commerce.licensing`:
330
+ read `stacks-licensing`
328
331
  - Product dashboard is highlighted (`dashboard: { highlight: true }`)
329
332
  - Default seeder counts: Product(10), Order(20), Review(50), Payment(50),
330
333
  GiftCard(20), Customer(20), Coupon(15)
@@ -12,7 +12,7 @@ allowed-tools: Read Edit Write Bash Grep Glob
12
12
  - Database package: `storage/framework/core/database/src/`
13
13
  - Configuration: `config/database.ts`
14
14
  - QB config: `config/query-builder.ts`
15
- - Migrations: `database/migrations/` (249 migration files, `.sql` format)
15
+ - Migrations: `database/migrations/` (252 migration files, `.sql` format)
16
16
  - QB state: `.qb/`
17
17
  - ORM: `storage/framework/orm/`
18
18
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: stacks-desktop
3
- description: Use when building or publishing desktop applications with Stacks - Craft native windows, local launchers, helper processes, packaging, capability probes, or Mac App Store delivery. Covers @stacksjs/desktop-build and the browser bridge boundary.
3
+ description: Use when building or publishing desktop applications with Stacks - Craft native windows, web view apps on a local agent for macOS, Windows and Linux, local launchers, helper processes, packaging, signed auto-updates, capability probes, or Mac App Store delivery. Covers @stacksjs/desktop-build and the browser bridge boundary.
4
4
  license: MIT
5
5
  compatibility: Bun >= 1.3.0, TypeScript
6
6
  allowed-tools: Read Edit Write Bash Grep Glob
@@ -10,6 +10,9 @@ allowed-tools: Read Edit Write Bash Grep Glob
10
10
 
11
11
  ## Key Paths
12
12
  - Core package: `storage/framework/core/desktop/src/`
13
+ - Web view apps: `webview-agent.ts`, `webview-launcher.ts`, `webview-app.ts`; updates: `updater.ts`, `update-signing.ts`, `update-feed.ts`, `update-install.ts`
14
+ - Build and release actions: `storage/framework/core/actions/src/build/desktop-webview.ts`, `desktop-release.ts`
15
+ - Update feed: `storage/framework/defaults/app/Actions/Desktop/UpdateFeedAction.ts`, `defaults/routes/desktop-updates.ts`
13
16
  - Source: `storage/framework/core/desktop/src/index.ts`
14
17
  - System tray views: `storage/framework/defaults/views/system-tray/`
15
18
  - System tray layouts: `storage/framework/defaults/resources/layouts/`
@@ -348,12 +351,194 @@ export default {
348
351
  - `webkit` needs a craft-native whose `buildMacOSNative` takes `webkit`; the build checks Craft's source and fails by
349
352
  name rather than building a host with blank web views. `dockMenu` reaches the host through `craft-app.json`.
350
353
 
354
+ ## Web view apps on a local agent (`desktop.webview`)
355
+
356
+ The cross-platform desktop mode: the app's executable is a compiled Bun agent on 127.0.0.1, and its window is a
357
+ Craft web view (WKWebView, WebView2, WebKitGTK) pointed at that agent. One codebase runs on macOS, Windows and
358
+ Linux. Choose it over `macos` (AppKit screens, macOS only, Mac App Store) when the app needs a web UI, more than
359
+ one platform, or child processes.
360
+
361
+ ```ts
362
+ // config/desktop.ts
363
+ import type { DesktopConfig } from '@stacksjs/types'
364
+
365
+ export default {
366
+ webview: {
367
+ appName: 'Fettler',
368
+ appId: 'org.fettler.app', // bundle id, package id, single-instance id
369
+ window: { width: 1280, height: 800 }, // title defaults to appName
370
+ agent: { entry: 'app/Desktop/Agent.ts', views: 'resources/desktop' },
371
+ urlSchemes: ['fettler'],
372
+ updates: { feedUrl: 'https://fettler.org/api/updates', publicKeys: { main: 'ed25519-public:...' } },
373
+ runtime: { 'linux-x64': 'vendor/craft/linux-x64/craft' }, // Craft binaries for targets other than this machine
374
+ macos: { entitlements: {} }, windows: { certificatePath: 'certs/app.pfx' }, linux: { categories: ['Development'] },
375
+ },
376
+ } satisfies DesktopConfig
377
+ ```
378
+
379
+ The agent module adds the app's own request handling. Returning nothing lets the views answer:
380
+
381
+ ```ts
382
+ // app/Desktop/Agent.ts
383
+ import type { WebviewAgentModule } from '@stacksjs/desktop-build'
384
+
385
+ export default {
386
+ fetch(request, context) { // context: appName, version, origin, port, dataDir
387
+ if (new URL(request.url).pathname === '/api/run') return Response.json({ ok: true })
388
+ },
389
+ start({ launch, updater }) {}, // once, before the window opens; launch.args, launch.url
390
+ secondInstance({ args, url, cwd }) {}, // another launch of the app, forwarded here
391
+ beforeUpdate(manifest, current) {}, // return { refuse } or { warn } to gate an update
392
+ stop() {},
393
+ } satisfies WebviewAgentModule
394
+ ```
395
+
396
+ What the launcher (`runWebviewApp`) does, the same on every platform:
397
+
398
+ - **One instance.** A lock file in the data directory holds the pid, port and a secret. A second launch posts its
399
+ arguments (and the link that started it, when it is in `urlSchemes`) to `/__desktop/instance` with that secret,
400
+ the running agent's `secondInstance` gets them, and the second process exits without booting anything.
401
+ - **A remembered port.** Any free loopback port the first time, then the same one (`agent.port` file), so the
402
+ page's origin and its local storage survive a restart. A taken port falls back to a free one.
403
+ - **A one-time token for a cookie.** The window opens on `/?session=<token>`. That request sets an HttpOnly,
404
+ SameSite=Strict cookie and redirects to the same page without the token. The token works once and is not the
405
+ cookie. Every later request needs the cookie.
406
+ - **A Host check.** Only `127.0.0.1:<port>` and `localhost:<port>` are answered, so a DNS-rebinding page cannot
407
+ reach the agent. A request without the cookie gets 401, pages included.
408
+ - **A wider PATH.** `widenedPath()` puts `~/.local/bin`, `~/.bun/bin`, Homebrew and `/usr/local/bin` ahead of what
409
+ the process was given (see the launchd trap below).
410
+ - **One lifetime.** Closing the window ends the agent (`stop()` runs, the lock is released); a signal to the agent
411
+ closes the window. `craft.app.relaunch()` restarts the agent, not a bare window with a dead token.
412
+
413
+ `agent.publicPaths` opens paths to callers without the cookie (an MCP endpoint behind its own bearer token). The
414
+ app's handler must authenticate those itself; the views are never served there.
415
+
416
+ **Views.** `buddy dev:desktop` serves `agent.views` live through stx (`bun-plugin-stx/serve`, with the gate and the
417
+ agent module in its `onRequest`). `buddy build:desktop` builds them to static pages with stx's `buildStaticSite`
418
+ and compiles every file into the agent, so a built app reads no loose view files. Component directories for the
419
+ build come from the project's `stx.config.ts`; `agent.components` applies to the live server. A project that needs
420
+ its own view build puts it in `app/Desktop/build-views.ts` and writes to `DESKTOP_VIEWS_OUT`.
421
+
422
+ **Files the agent needs at runtime** are imported the Bun way, so they are compiled in on every platform:
423
+ `import data from './data.json' with { type: 'file' }`.
424
+
425
+ ### Processes live in the agent
426
+
427
+ Spawn `bun`, `git`, `ssh`, `docker`, a language server, anything process-shaped, from the agent module, and stream
428
+ to the page over `fetch` bodies or a WebSocket. Do not spawn from the page through the Craft bridge:
429
+
430
+ - Craft's `shell.spawn` inherits stdio and discards output; `shell.exec` blocks the UI thread. Neither streams.
431
+ - The page holds no credentials. Keep tokens in the agent (`Bun.secrets` for the OS keychain).
432
+ - The same agent code runs on all three platforms; a bridge call has to exist on each.
433
+
434
+ ### Building
435
+
436
+ ```bash
437
+ buddy dev:desktop # run from source, stx views live
438
+ buddy build:desktop # this machine's target
439
+ buddy build:desktop --target linux-x64,win32-x64 # cross-compile the agents
440
+ buddy build:desktop --target all --package # also make the installers this OS can make
441
+ ```
442
+
443
+ Output goes to `storage/framework/desktop/webview/<target>/`, with `build.json` listing every artifact.
444
+
445
+ | Target | What the build makes | Needs its own OS for |
446
+ |---|---|---|
447
+ | `darwin-*` | `<App>.app`: the agent as the executable, `craft-runtime` beside it, hardened runtime | Everything past the compiled agent: `codesign`, `notarytool`, `hdiutil` are macOS only |
448
+ | `win32-*` | `<App>.exe`, `craft-runtime.exe`, `windows.additionalFiles`, and `craft-package.json` | The MSI (WiX `candle` and `light`) and `signtool` |
449
+ | `linux-*` | One binary with Craft compiled into it, and `craft-package.json` | AppImage (`appimagetool`), deb (`dpkg-deb`), rpm (`rpmbuild`) |
450
+
451
+ Bun cross-compiles the agent for any target from any machine (`--target=bun-windows-x64`), so a Mac produces the
452
+ Windows and Linux executables. It does not produce their installers. `craft-package.json` is the input to Craft's
453
+ `packageApp`, with paths relative to its own folder; `--package` runs it when the machine matches the target.
454
+
455
+ Each target needs that platform's Craft web view binary: this machine's comes from `CRAFT_BIN` or `craft` on PATH,
456
+ every other from `webview.runtime['<target>']` or `CRAFT_BIN_<PLATFORM>_<ARCH>` (Craft publishes
457
+ `craft-<os>-<arch>.zip` with each release). On Linux the runtime is compiled into the agent and unpacked to the data
458
+ directory on first launch, because Craft's Linux packagers take one binary.
459
+
460
+ ### Updates
461
+
462
+ An update is one manifest per channel, platform and architecture, signed with Ed25519. The app carries the public
463
+ key; the private key stays with the releaser and never reaches the server.
464
+
465
+ ```bash
466
+ buddy desktop:update:keypair # prints both halves once; nothing is written
467
+ # public half -> webview.updates.publicKeys in config/desktop.ts
468
+ # private half -> DESKTOP_UPDATE_PRIVATE_KEY (a password manager or a CI secret)
469
+
470
+ buddy release:desktop --identity "Developer ID Application: Example (ABCDE12345)" --notary-profile example
471
+ buddy release:desktop --target linux-x64 --skip-build # installers built on another machine
472
+ buddy release:desktop --dry-run # no notarization, no upload; manifests written locally
473
+ ```
474
+
475
+ `release:desktop` checks everything that can refuse a release before it notarizes or uploads anything: a clean
476
+ tree at the built commit, a private key whose public half the config trusts, a version newer than what the channel
477
+ serves. Then per target:
478
+
479
+ - **macOS**: the `.app` must be signed with a Developer ID. It is notarized and stapled, zipped with `ditto` (what
480
+ an installed app updates from) and imaged into a signed, notarized DMG (what a person downloads).
481
+ `codesign --verify`, `spctl` and `stapler validate` run against the files that get uploaded.
482
+ - **Windows**: the MSI from `build:desktop --package` on Windows. With `windows.certificatePath` and
483
+ `DESKTOP_WINDOWS_CERTIFICATE_PASSWORD`, the executables are signed with `signtool` and Craft signs the MSI.
484
+ - **Linux**: the AppImage (what an installed app updates from), with the deb and rpm beside it.
485
+
486
+ Artifacts and manifests go through `@stacksjs/storage` to `updates.disk` under `updates.prefix`
487
+ (`desktop-updates/<channel>/<platform>-<arch>/latest.json`, artifacts under `<version>/`), plus a `release.json`
488
+ a download page can read.
489
+
490
+ The server side is one default action, `Actions/Desktop/UpdateFeedAction`, mounted at
491
+ `/api/updates/{platform}/{arch}` whenever `webview.updates` is configured. It serves the stored manifest as is
492
+ (204 when `?current=` is already that version, 404 when nothing was published). Override the action in
493
+ `app/Actions/Desktop/UpdateFeedAction.ts`, or mount it elsewhere in `routes/api.ts`.
494
+
495
+ In the app, the launcher checks once the window is up and every `updates.checkEveryHours` (default 24). The page
496
+ drives it at `/__desktop/update` (cookie required): `GET` is the status, `POST { action: 'check' }` asks the feed,
497
+ and `POST { action: 'install', acknowledge? }` installs. Installing verifies the manifest signature, the size and
498
+ the SHA-256, then:
499
+
500
+ | Installed as | Install step |
501
+ |---|---|
502
+ | macOS `.app` | Unpack beside the bundle, check the new bundle's signature, team and identifier against the running app, swap by rename (the old bundle is put back on failure), relaunch through `open` |
503
+ | Windows MSI | Check the installer's Authenticode publisher against the running executable when that is signed, then `msiexec /i ... /passive` detached, which starts the new version |
504
+ | Linux AppImage | Copy beside `$APPIMAGE`, rename over it, relaunch |
505
+ | Linux deb or rpm | Nothing is downloaded: a notice that the package manager updates it |
506
+
507
+ `beforeUpdate(manifest, { version })` in the agent module is the entitlement hook. `{ refuse: '...' }` stops the
508
+ update; `{ warn: '...' }` makes the status carry the warning and `install` require `acknowledge: true`, for a
509
+ license whose updates ended before that version.
510
+
511
+ ### Web view traps
512
+
513
+ - **launchd PATH.** An app opened from Finder gets `/usr/bin:/bin:/usr/sbin:/sbin`; a Linux `.desktop` launch skips
514
+ the shell profile. Tools that work in a terminal are missing. The launcher widens PATH for the agent and its
515
+ children; a tool installed somewhere unusual still needs an absolute path or a setting.
516
+ - **A sandboxed app cannot spawn tools.** `ssh`, `docker` or `bun` from inside the App Sandbox fail. Web view apps
517
+ are built unsandboxed with the hardened runtime, which means Developer ID distribution, not the Mac App Store.
518
+ - **Craft `shell.spawn` discards output.** See "Processes live in the agent".
519
+ - **Craft's single-instance hand-over is Windows and Linux only.** On macOS a second Craft with the same id opens
520
+ a second window, so the launcher never starts one there: the second launch still reaches `secondInstance`, and
521
+ raising the window is the app's to do. LaunchServices already keeps an app opened from Finder or the Dock to one
522
+ instance.
523
+ - **An older Craft opens its demo window when handed a flag it does not know.** The build reads the runtime binary
524
+ (`probeCraftFlags`) and the launcher passes `--single-instance`, `--deep-link` and `--app-name` only when present.
525
+ `--single-instance` is on Craft main and in no release up to 0.0.499.
526
+ - **URL schemes on macOS** are registered in the Info.plist, but a link opened by LaunchServices arrives as an Apple
527
+ Event, which a Bun executable does not receive. A link reaches the app as an argument on Windows and Linux, and
528
+ on macOS only when the executable is started with it.
529
+ - **A compiled agent autoloads nothing.** It is built with `--no-compile-autoload-bunfig` and
530
+ `--no-compile-autoload-dotenv`; read settings from the data directory, not from a `.env` beside the executable.
531
+ - **Do not swap a bundle by hand.** The trust check is what stops a stolen update key from installing another
532
+ team's app. An ad hoc signed development build has no team to compare with and refuses to self-update.
533
+
351
534
  ## CLI Commands
352
535
 
353
536
  ```bash
354
537
  buddy new <name> --desktop # a Stacks app that is also a native Mac app, API inside (macos.agent)
355
- buddy dev:desktop # start the desktop development server
356
- buddy build:desktop # build the launcher + Craft runtime payload
538
+ buddy dev:desktop # run the desktop app: webview, else macos, else the dev server window
539
+ buddy build:desktop # build it; --target and --package for a webview app, --native for macos
540
+ buddy desktop:update:keypair # the Ed25519 keypair that signs update manifests
541
+ buddy release:desktop # sign, notarize, and publish a webview app with signed update manifests
357
542
  buddy desktop:apple:init # generate the reusable GitHub Actions caller
358
543
  buddy desktop:apple:doctor # validate Apple tooling, identities, profile, and API key
359
544
  buddy desktop:apple:package # build, sandbox, sign, and create a Store .pkg
@@ -0,0 +1,214 @@
1
+ ---
2
+ name: stacks-licensing
3
+ description: Use when selling software licenses from a Stacks app - issuing a license key from a payment webhook, device activations and limits, team seats, refund revocation, resend and transfer, the Ed25519-signed offline license token, or the desktop license client with offline grace. Covers the licensing module of @stacksjs/commerce and @stacksjs/commerce/licensing/client.
4
+ license: MIT
5
+ compatibility: Bun >= 1.3.0, TypeScript
6
+ allowed-tools: Read Edit Write Bash Grep Glob
7
+ ---
8
+
9
+ # Software licensing
10
+
11
+ Licensing is part of `@stacksjs/commerce`. The server half issues and tracks
12
+ licenses; the client half runs inside a desktop app's agent and answers "are
13
+ paid features unlocked for this build?" with no network.
14
+
15
+ ```ts
16
+ import { licensing } from '@stacksjs/commerce' // server
17
+ import { createLicenseClient } from '@stacksjs/commerce/licensing/client' // desktop agent
18
+ ```
19
+
20
+ The client entry imports only `node:crypto`. Never import the package barrel
21
+ into a compiled agent: it pulls in the database and the models.
22
+
23
+ ## Key paths
24
+
25
+ - Server: `storage/framework/core/commerce/src/licensing/` (`service.ts`,
26
+ `keys.ts`, `resend.ts`, `token.ts`)
27
+ - Client: `storage/framework/core/commerce/src/licensing/client.ts`
28
+ - Models: `LicenseKey`, `LicenseActivation`, `LicenseSeat` in
29
+ `storage/framework/defaults/app/Models/commerce/`
30
+ - Actions: `storage/framework/defaults/app/Actions/Commerce/Licensing/`
31
+ - Routes: `storage/framework/defaults/routes/licensing.ts`, and the payment
32
+ webhook in `routes/payments.ts`
33
+ - Email: `defaults/app/Mail/LicenseEmail.ts`, `defaults/resources/emails/license.stx`
34
+ - Tests: `core/commerce/src/tests/licensing.test.ts`, `licensing-token.test.ts`
35
+
36
+ ## Tiers
37
+
38
+ | Tier | `updatesUntil` | `expiresAt` | Meaning |
39
+ |---|---|---|---|
40
+ | `standard` | issue date + 1 year | null | Builds released on or before `updatesUntil` stay unlocked for good (perpetual fallback). |
41
+ | `lifetime` | null | null | Every build, never expires. |
42
+ | `team` | null | issue date + 1 year | Every build while it runs, `seats` people. Renew with `extendLicense`. |
43
+
44
+ `maxDevices` defaults to 2 (per seat on a team license). Prices are not stored
45
+ on the tier: charge what you like, in integer cents, and pass the tier in the
46
+ purchase reference.
47
+
48
+ ## Setup
49
+
50
+ 1. `buddy license:keygen` prints an Ed25519 keypair. Set `LICENSE_SIGNING_KEY`
51
+ and `LICENSE_SIGNING_KEY_ID` in the server's environment. Embed the public
52
+ half in the app as `{ [keyId]: 'ed25519-public:...' }`.
53
+ 2. Licensing's tables belong to the `commerce` feature: enable it first
54
+ (`buddy commerce:install`), or their migrations are skipped. Then
55
+ `buddy migrate` creates `license_activations` and `license_seats` and adds
56
+ the license columns to `license_keys`.
57
+ 3. The licensing routes mount when `LICENSE_SIGNING_KEY` is set (or when
58
+ `STACKS_DEFAULT_ROUTES` names `licensing`). The webhook is the `payments`
59
+ bundle.
60
+
61
+ ## Selling a license
62
+
63
+ Start a checkout whose `reference` is a license purchase reference. Every
64
+ payment driver echoes the reference in its webhook, which is how issuing works
65
+ with any driver.
66
+
67
+ ```ts
68
+ import { licensing } from '@stacksjs/commerce'
69
+ import { paymentDriver } from '@stacksjs/payments'
70
+
71
+ const reference = licensing.licensePurchaseReference({ tier: 'standard' })
72
+ const session = await paymentDriver().checkout(payer, {
73
+ mode: 'payment',
74
+ lines: [{ name: 'Pro', unitAmount: 3900, quantity: 1 }],
75
+ successUrl: `https://example.com/thanks?purchase=${reference}`,
76
+ reference,
77
+ })
78
+ ```
79
+
80
+ `POST /webhooks/payments` then calls `licensing.handleLicensePaymentEvent(event)`
81
+ for every verified event:
82
+
83
+ - `checkout.completed` or `payment.succeeded` with a license reference issues
84
+ the license once (`license_keys.purchase_reference` is unique). A second
85
+ event for the same purchase fills in the buyer's address or the payment id
86
+ and never issues again.
87
+ - `refund.succeeded` for the license's payment adds to `amount_refunded`; once
88
+ it covers `amount_paid` the license becomes `refunded` and stops checking in
89
+ as valid. A retry is applied once.
90
+
91
+ The buyer's address comes from the event (`buyerEmailFromEvent`: checkout
92
+ `metadata.email` on any driver, otherwise where Stripe, Lemon Squeezy and Adyen
93
+ state it). The thank-you page reads the key with
94
+ `licensing.findLicenseByPurchase(reference)`.
95
+
96
+ To issue outside a webhook (a grant, a migration from another system) call
97
+ `licensing.issueLicense({ purchaseReference, tier, email })` with any unique
98
+ reference.
99
+
100
+ ## Server functions
101
+
102
+ | Function | Does |
103
+ |---|---|
104
+ | `issueLicense(input)` | The license for a purchase, created on first sight. Returns `{ license, created }`. |
105
+ | `handleLicensePaymentEvent(event)` | Issue or refund from a `PaymentEvent`. Returns `{ action, license? }`. |
106
+ | `activateLicense({ key, deviceHash, deviceName, platform, appVersion, email? })` | Take a device slot, answer a token. Beyond `maxDevices`: `device-limit` with the devices in use. |
107
+ | `deactivateLicense({ key, deviceHash })` | Release a device's slot. |
108
+ | `checkLicense({ key, deviceHash, appVersion? })` | Standing plus a fresh token, or `{ valid: false, reason }`. |
109
+ | `transferLicense({ key, fromEmail, toEmail })` | New owner address, every device released, key emailed. |
110
+ | `revokeLicense(key)` / `extendLicense(key, until)` | Stop or renew a license by hand. |
111
+ | `assignLicenseSeat({ key, userId })` / `unassignLicenseSeat` / `licenseSeats(key)` | Team seats. The user must be an active `TeamMember` of the license's `Team`. |
112
+ | `activeLicensesFor(email)` / `requestLicenseResend(email, deps)` | Resend by email, rate limited, same answer whether or not the address bought anything. |
113
+ | `findLicenseByKey` / `findLicenseByPurchase` / `licenseDevices` | Lookups. |
114
+ | `configureLicensing({ onIssued, signingKey, now, termYears })` | Process-wide defaults. `onIssued` replaces the default license email. |
115
+
116
+ Every function takes an optional last argument with the same options, which is
117
+ how tests pin the clock and the signing key.
118
+
119
+ A team license needs `teamId` at issue (or set `team_id` afterwards). A member
120
+ activates with the email of their seat; each seat has its own device limit.
121
+
122
+ ## Routes
123
+
124
+ | Route | Action | Notes |
125
+ |---|---|---|
126
+ | `POST /licenses/activate` | `LicenseActivateAction` | `{ key, deviceHash, deviceName?, platform?, appVersion?, email? }`. 409 `device-limit` lists `devices`. |
127
+ | `POST /licenses/deactivate` | `LicenseDeactivateAction` | `{ key, deviceHash }` |
128
+ | `POST /licenses/check` | `LicenseCheckAction` | Always 200 with `valid`; a 5xx means "ask again later". |
129
+ | `POST /licenses/resend` | `LicenseResendAction` | `{ email }`. 3 per address and 10 per IP an hour. |
130
+ | `POST /licenses/transfer` | `LicenseTransferAction` | `{ key, email, toEmail }` |
131
+ | `GET, POST, DELETE /licenses/seats` | `LicenseSeat*Action` | `auth` middleware; the caller must be an `owner` or `admin` of the license's team. |
132
+
133
+ The first three are CSRF-exempt (the key is the credential) and rate limited.
134
+ A 503 `not-configured` means the signing key is missing.
135
+
136
+ ## The token
137
+
138
+ `<base64url payload>.<base64url Ed25519 signature>`. The payload:
139
+
140
+ ```ts
141
+ { v: 1, kid, licenseId, tier, updatesUntil, expiresAt, deviceHash, issuedAt, checkBy }
142
+ ```
143
+
144
+ `licenseId` is the license's uuid, never the key. `deviceHash` is the SHA-256
145
+ of the device id, so the id never leaves the device. `checkBy` is 30 days after
146
+ `issuedAt`. Keys and signatures use the encodings of the desktop updater
147
+ (`@stacksjs/desktop` `updater.ts`): `ed25519-public:<base64url SPKI DER>`,
148
+ `ed25519-private:<base64url PKCS#8 DER>`, trusted keys as `{ keyId: publicKey }`.
149
+
150
+ - `signLicenseToken(input, { privateKey, keyId })`
151
+ - `verifyLicenseToken(token, publicKeys, deviceHash?)` throws a
152
+ `LicenseTokenError` whose `reason` is `malformed`, `unknown-key`,
153
+ `bad-signature` or `wrong-device`.
154
+ - `isEntitled({ tier, updatesUntil }, buildDate)` is the entitlement rule:
155
+ true for `lifetime` or a null `updatesUntil`, otherwise true exactly when
156
+ the build was released on or before `updatesUntil`.
157
+ - `tokenStanding(payload, { buildDate, now, lastCheckedAt })` applies the
158
+ clock: `{ licensed, pro, reason, perpetual, recheckDue }`.
159
+
160
+ ## The client
161
+
162
+ ```ts
163
+ const license = createLicenseClient({
164
+ endpoint: 'https://example.com/licenses',
165
+ publicKeys: { 'license-2026': 'ed25519-public:...' },
166
+ buildDate: BUILD_DATE, // the release date baked into this build
167
+ storage: {
168
+ get: name => Bun.secrets.get({ service: 'com.example.app', name }),
169
+ set: (name, value) => Bun.secrets.set({ service: 'com.example.app', name, value }),
170
+ delete: name => Bun.secrets.delete({ service: 'com.example.app', name }),
171
+ },
172
+ })
173
+
174
+ const result = await license.activate(key, { id: deviceId, name: hostname, platform: process.platform, appVersion })
175
+ if (!result.ok && result.reason === 'device-limit')
176
+ showDevicesInUse(result.devices)
177
+
178
+ const { pro } = await license.standing() // the only thing a feature gate needs
179
+ await license.release() // give this device's slot back
180
+ ```
181
+
182
+ `standing()` never throws for a network failure. Its rules:
183
+
184
+ - It asks the server again when 7 days have passed since the last successful
185
+ check, and stores the fresh token.
186
+ - A token for a license that is owned outright (`expiresAt` null: standard and
187
+ lifetime) never expires for the builds it covers, online or not.
188
+ - Any other token works offline until `checkBy` (30 days), then answers
189
+ `check-overdue` until a check succeeds.
190
+ - A definite "no" from the server (`revoked`, `refunded`, `released`) clears
191
+ the stored license. A 5xx or an unreachable server changes nothing.
192
+ - `pro` is `licensed` and `isEntitled(token, buildDate)`. A standard license on
193
+ a build released after `updatesUntil` is `licensed: true, pro: false`.
194
+
195
+ `verifyToken(token, publicKeys)` is exported standalone.
196
+
197
+ ## Gotchas
198
+
199
+ - Bake `buildDate` at release time. Reading the clock at runtime instead makes
200
+ every old build look new and locks standard licenses out after a year.
201
+ - The public key map is the trust root. Rotate by shipping a build that trusts
202
+ both ids before switching the server's private key.
203
+ - Send the device hash, never the id: `hashDeviceId(id)` on the client. The
204
+ server refuses anything that is not a 64-character hex SHA-256.
205
+ - Do not add a `useApi` route for `LicenseActivation` or `LicenseSeat`: a
206
+ direct write skips the device and seat limits.
207
+ - A refunded or revoked perpetual license keeps working on a device that never
208
+ comes online again. That is the cost of offline use; the 7 day re-check
209
+ closes it for any device that does.
210
+ - `LicenseKey` also backs the dashboard's license key deliveries
211
+ (`commerce.shippings.licenses`). A key created there with status
212
+ `unassigned` becomes `active` on its first activation.
213
+ - After changing a license model run `buddy generate:migrations` and commit the
214
+ snapshot with it.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: stacks-migrations
3
- description: Use when working with database migrations in a Stacks application - creating migration files, running migrations, fresh migration (drop + recreate), seeding after migration, migration file naming conventions, or the 249 built-in migration files. For the database API itself (queries, connections, SQL helpers), see stacks-database.
3
+ description: Use when working with database migrations in a Stacks application - creating migration files, running migrations, fresh migration (drop + recreate), seeding after migration, migration file naming conventions, or the 252 built-in migration files. For the database API itself (queries, connections, SQL helpers), see stacks-database.
4
4
  license: MIT
5
5
  compatibility: Bun >= 1.3.0, TypeScript, SQLite >= 3.47.2
6
6
  allowed-tools: Read Edit Write Bash Grep Glob
@@ -236,7 +236,7 @@ lossless widenings; reports everything destructive), then
236
236
  - Do not commit a second snapshot under `.qb/`; that indicates a missing `snapshotDir` configuration
237
237
  - If a generated SQLite migration rebuilds tables, test it against a copy of the current database and run `PRAGMA integrity_check` plus `PRAGMA foreign_key_check`
238
238
  - `--seed` flag after `migrate:fresh` seeds the database with factory data
239
- - 249 migration files exist by default for all framework models
239
+ - 252 migration files exist by default for all framework models
240
240
  - SQLite >= 3.47.2 is required (system requirement)
241
241
  - For the database API (queries, connections), see the `stacks-database` skill
242
242
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: stacks-models
3
- description: Use when defining or extending Stacks models, deriving migrations and CRUD, configuring attributes/relationships/traits/ownership, or preserving model inference. Covers defineModel, extendModel, model types, native data workflows, and the 108 built-in framework models.
3
+ description: Use when defining or extending Stacks models, deriving migrations and CRUD, configuring attributes/relationships/traits/ownership, or preserving model inference. Covers defineModel, extendModel, model types, native data workflows, and the 110 built-in framework models.
4
4
  license: MIT
5
5
  compatibility: Bun >= 1.3.0, TypeScript, SQLite >= 3.47.2
6
6
  allowed-tools: Read Edit Write Bash Grep Glob
@@ -438,7 +438,7 @@ honoured: fewer rows are seeded rather than a duplicate combination.
438
438
  ## Built-in models by category
439
439
 
440
440
  The ones below are worth knowing by name. They are a selection, not the set:
441
- `storage/framework/defaults/app/Models/` holds 108, and that directory is the
441
+ `storage/framework/defaults/app/Models/` holds 110, and that directory is the
442
442
  authority. This section said "All 62 built-in models by category" while
443
443
  listing fewer than that against 102 on disk, so an agent reading to the end
444
444
  had no way to tell it was short.