@mastra/factory 0.2.2 → 0.3.0-alpha.2
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/CHANGELOG.md +54 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +54 -6
- package/dist/auth.js.map +1 -1
- package/dist/factory.d.ts +10 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +35 -4
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/integrations/base.d.ts +25 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +23 -8
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/sandbox-release.d.ts +38 -0
- package/dist/integrations/github/sandbox-release.d.ts.map +1 -0
- package/dist/integrations/github/sandbox-release.js +74 -0
- package/dist/integrations/github/sandbox-release.js.map +1 -0
- package/dist/integrations/github/sandbox.d.ts +10 -0
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +18 -1
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +1 -1
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +4 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +52 -17
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/routes/surface.d.ts +3 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +2 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +2 -0
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +43 -12
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/start-coordinator.js +1 -1
- package/dist/rules/transition-service.d.ts +17 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +29 -1
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/sandbox/fleet.d.ts +12 -1
- package/dist/sandbox/fleet.d.ts.map +1 -1
- package/dist/sandbox/fleet.js +35 -1
- package/dist/sandbox/fleet.js.map +1 -1
- package/dist/spa-static.js +2 -1
- package/dist/spa-static.js.map +1 -1
- package/dist/state-signing.d.ts +8 -1
- package/dist/state-signing.d.ts.map +1 -1
- package/dist/state-signing.js +5 -2
- package/dist/state-signing.js.map +1 -1
- package/dist/storage/domains/channel-identity/base.d.ts +96 -0
- package/dist/storage/domains/channel-identity/base.d.ts.map +1 -0
- package/dist/storage/domains/channel-identity/base.js +149 -0
- package/dist/storage/domains/channel-identity/base.js.map +1 -0
- package/dist/storage/domains/source-control/base.d.ts +51 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +91 -0
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +13 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +35 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +19 -3
- package/dist/workspace.js.map +1 -1
- package/package.json +5 -5
package/dist/sandbox/fleet.d.ts
CHANGED
|
@@ -46,7 +46,11 @@ export interface MaterializationSandbox {
|
|
|
46
46
|
export interface SandboxCreateOptions {
|
|
47
47
|
/** Reattach to this existing provider VM instead of provisioning a new one. */
|
|
48
48
|
providerSandboxId?: string;
|
|
49
|
-
/**
|
|
49
|
+
/**
|
|
50
|
+
* Environment variables for commands run in the sandbox. Adapter-level
|
|
51
|
+
* only: merged into every `executeCommand`, never baked into the provider
|
|
52
|
+
* VM (see `SandboxFleet.#build`).
|
|
53
|
+
*/
|
|
50
54
|
env?: Record<string, string>;
|
|
51
55
|
/** Provider working directory for this sandbox. */
|
|
52
56
|
workingDirectory?: string;
|
|
@@ -188,6 +192,13 @@ export declare class SandboxFleet {
|
|
|
188
192
|
/**
|
|
189
193
|
* Provision a new sandbox (persisting its provider id on first open) or
|
|
190
194
|
* reattach to the stored one. Returns a started, live sandbox.
|
|
195
|
+
*
|
|
196
|
+
* Concurrent calls for the same binding coalesce onto one in-flight
|
|
197
|
+
* provision/reattach and share its sandbox handle — N simultaneous requests
|
|
198
|
+
* for one cold session (e.g. several browser tabs polling right after boot)
|
|
199
|
+
* must not each fire their own `POST /sandbox` against the provider.
|
|
200
|
+
* Failures are not cached: once the shared attempt settles, the next call
|
|
201
|
+
* starts fresh.
|
|
191
202
|
*/
|
|
192
203
|
ensureSandbox(store: SandboxBindingStore, onProgress?: ProgressFn): Promise<MaterializationSandbox>;
|
|
193
204
|
ensureSandbox(store: SandboxBindingStore, env?: Record<string, string>, onProgress?: ProgressFn, options?: EnsureSandboxOptions): Promise<MaterializationSandbox>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fleet.d.ts","sourceRoot":"","sources":["../../src/sandbox/fleet.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE/D,gEAAgE;AAChE,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,OAAO,IAAI,OAAO,CAAC;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC,CAAC;IAC3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,cAAc,GAAG,IAAI;IAIzC,oDAAoD;IACpD,YAAY,IAAI,IAAI;IAIpB;;;;;;;OAOG;IACH,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM;IAM5C;;;;OAIG;IACH,0BAA0B,CAAC,YAAY,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM;IAgD3E;;;;;;;;;;OAUG;IACG,aAAa,CAAC,KAAK,EAAE,mBAAmB,EAAE,UAAU,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC,sBAAsB,CAAC;IACnG,aAAa,CACjB,KAAK,EAAE,mBAAmB,EAC1B,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,UAAU,CAAC,EAAE,UAAU,EACvB,OAAO,CAAC,EAAE,oBAAoB,GAC7B,OAAO,CAAC,sBAAsB,CAAC;IAqFlC;;;;;;;OAOG;IACG,eAAe,CAAC,KAAK,EAAE,mBAAmB,EAAE,OAAO,CAAC,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IAclG;;;;;OAKG;IACG,eAAe,CACnB,iBAAiB,EAAE,MAAM,EACzB,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,sBAAsB,CAAC;CASnC"}
|
package/dist/sandbox/fleet.js
CHANGED
|
@@ -36,6 +36,19 @@ var SandboxBudgetError = class extends Error {
|
|
|
36
36
|
}
|
|
37
37
|
};
|
|
38
38
|
/**
|
|
39
|
+
* Stable identity for one binding's in-flight provision work, used to coalesce
|
|
40
|
+
* concurrent `ensureSandbox` calls. Prefer `checkpointName` — it is a pure
|
|
41
|
+
* function of the owning session and is set before the first provision, which
|
|
42
|
+
* is exactly when the herd forms (the stored `sandboxId` is still null then).
|
|
43
|
+
* Fall back to the stored provider id, and skip coalescing entirely for
|
|
44
|
+
* bindings with neither: keying those on a shared constant would wrongly
|
|
45
|
+
* funnel *different* bindings onto one sandbox.
|
|
46
|
+
*/
|
|
47
|
+
function coalesceKey(store) {
|
|
48
|
+
if (store.checkpointName) return `checkpoint:${store.checkpointName}`;
|
|
49
|
+
if (store.sandboxId) return `sandbox:${store.sandboxId}`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
39
52
|
* Adapt a cloned `WorkspaceSandbox` to the minimal surface this module needs.
|
|
40
53
|
* Lifecycle goes through the `_`-prefixed wrappers when present (they add
|
|
41
54
|
* status tracking and concurrency safety on `MastraSandbox` subclasses),
|
|
@@ -98,6 +111,8 @@ var SandboxFleet = class {
|
|
|
98
111
|
#config;
|
|
99
112
|
#factory;
|
|
100
113
|
#liveCount = 0;
|
|
114
|
+
/** In-flight `ensureSandbox` work, keyed per binding so concurrent callers coalesce. */
|
|
115
|
+
#inflight = /* @__PURE__ */ new Map();
|
|
101
116
|
constructor(config) {
|
|
102
117
|
this.#config = config;
|
|
103
118
|
}
|
|
@@ -191,6 +206,14 @@ var SandboxFleet = class {
|
|
|
191
206
|
* passed both as the logical `id` (providers that reattach by construction
|
|
192
207
|
* id, e.g. local) and as the provider-native `sandboxId` hint (Railway) so
|
|
193
208
|
* reattach works across the provider matrix.
|
|
209
|
+
*
|
|
210
|
+
* `env` is deliberately NOT forwarded to the provider clone: remote
|
|
211
|
+
* providers bake creation-time env into the VM for its whole lifetime
|
|
212
|
+
* (`POST /sandbox`), which would persist credentials like `GH_TOKEN` inside
|
|
213
|
+
* a VM that can outlive the session and be reused by another user via the
|
|
214
|
+
* sandbox pool. Instead the env lives only on the adapter, which merges it
|
|
215
|
+
* into every `executeCommand` — commands see the (refreshable) token, but
|
|
216
|
+
* the VM itself never stores it.
|
|
194
217
|
*/
|
|
195
218
|
#build(opts) {
|
|
196
219
|
if (this.#factory) return this.#factory(opts);
|
|
@@ -200,7 +223,6 @@ var SandboxFleet = class {
|
|
|
200
223
|
id: opts.providerSandboxId,
|
|
201
224
|
sandboxId: opts.providerSandboxId
|
|
202
225
|
} : {},
|
|
203
|
-
...opts.env ? { env: opts.env } : {},
|
|
204
226
|
...opts.workingDirectory ? { workingDirectory: opts.workingDirectory } : {},
|
|
205
227
|
...opts.idleTimeoutMinutes !== void 0 ? { idleTimeoutMinutes: opts.idleTimeoutMinutes } : {},
|
|
206
228
|
...opts.checkpointName ? { checkpointName: opts.checkpointName } : {}
|
|
@@ -210,6 +232,18 @@ var SandboxFleet = class {
|
|
|
210
232
|
const env = typeof envOrProgress === "function" ? void 0 : envOrProgress;
|
|
211
233
|
const onProgress = typeof envOrProgress === "function" ? envOrProgress : progressOrOptions;
|
|
212
234
|
const options = typeof envOrProgress === "function" ? progressOrOptions ?? {} : maybeOptions;
|
|
235
|
+
const key = coalesceKey(store);
|
|
236
|
+
if (!key) return this.#ensureSandboxUncoalesced(store, env, onProgress, options);
|
|
237
|
+
const existing = this.#inflight.get(key);
|
|
238
|
+
if (existing) return existing;
|
|
239
|
+
const promise = this.#ensureSandboxUncoalesced(store, env, onProgress, options).finally(() => {
|
|
240
|
+
if (this.#inflight.get(key) === promise) this.#inflight.delete(key);
|
|
241
|
+
});
|
|
242
|
+
this.#inflight.set(key, promise);
|
|
243
|
+
return promise;
|
|
244
|
+
}
|
|
245
|
+
/** The single provision/reattach attempt behind {@link ensureSandbox}. */
|
|
246
|
+
async #ensureSandboxUncoalesced(store, env, onProgress, options) {
|
|
213
247
|
const idleTimeoutMinutes = this.idleMinutes;
|
|
214
248
|
const checkpointName = store.checkpointName;
|
|
215
249
|
if (store.sandboxId) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fleet.js","names":["#config","#liveCount","#factory","#build"],"sources":["../../src/sandbox/fleet.ts"],"sourcesContent":["/**\n * Project sandbox fleet: provisioning, reattach, teardown, and budgeting.\n *\n * Server-hosted projects never run on the web host itself. Each project gets\n * its own isolated sandbox (a `WorkspaceSandbox`, e.g. a Railway VM) `clone()`d\n * from the machine the factory was configured with. This module owns everything\n * about that fleet — which provider is active, where checkouts live inside a\n * sandbox, the idle window, the per-replica budget, and the\n * provision/reattach/teardown lifecycle — but knows nothing about what runs\n * inside a sandbox (git materialization lives with its feature, e.g. the\n * GitHub integration's `sandbox.ts`).\n *\n * The fleet is constructed once at boot with the machine config (or none, when\n * sandboxes are disabled) and handed to consumers — no global registry.\n * Persistence of the provider's reattach id is delegated to the caller via\n * {@link SandboxBindingStore}, so the fleet stays storage-agnostic. Tests can\n * swap the low-level construction via {@link SandboxFleet.setFactory}.\n */\n\nimport path from 'node:path';\n\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\n\n/** Minimal command result shape sandbox consumers depend on. */\nexport interface SandboxCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Minimal live-sandbox surface fleet consumers need: an id, a way to start it,\n * a way to learn the provider's reattach id, and command execution.\n */\nexport interface MaterializationSandbox {\n readonly id: string;\n start(): Promise<void>;\n getInfo(): Promise<{ metadata?: Record<string, unknown> }>;\n executeCommand(\n command: string,\n args?: string[],\n options?: { timeout?: number; env?: Record<string, string | undefined> },\n ): Promise<SandboxCommandResult>;\n /** Update an environment variable for future commands in this sandbox. */\n setEnvironmentVariable?(name: string, value: string): void;\n /** Tear down the underlying VM. Optional: providers without it are no-ops. */\n stop?(): Promise<void>;\n}\n\n/** Options for building (or reattaching) one sandbox. */\nexport interface SandboxCreateOptions {\n /** Reattach to this existing provider VM instead of provisioning a new one. */\n providerSandboxId?: string;\n /** Environment variables baked into the sandbox. */\n env?: Record<string, string>;\n /** Provider working directory for this sandbox. */\n workingDirectory?: string;\n /** Idle teardown window (minutes). The provider stops the VM after this idle period. */\n idleTimeoutMinutes?: number;\n /** Provider checkpoint used to seed and preserve this sandbox's filesystem. */\n checkpointName?: string;\n}\n\n/**\n * A coarse-grained step of the sandbox-preparation flow, reported as it happens\n * so the UI can show the user what the server is doing instead of a static\n * \"Preparing…\" toast. `phase` is a stable machine token; `message` is\n * user-facing copy.\n */\nexport interface PrepareProgress {\n phase: 'reattaching' | 'provisioning' | 'preparing-workspace' | 'cloning' | 'pulling' | 'finalizing' | 'done';\n message: string;\n}\n\n/** Callback invoked with each preparation step. Best-effort; never throws. */\nexport type ProgressFn = (event: PrepareProgress) => void;\n\n/** Invoke a progress callback without letting it break the actual work. */\nexport function reportProgress(onProgress: ProgressFn | undefined, event: PrepareProgress): void {\n if (!onProgress) return;\n try {\n onProgress(event);\n } catch {\n // Progress reporting must never break the actual work.\n }\n}\n\n/**\n * Factory that builds a (not-yet-started) sandbox. When `providerSandboxId` is\n * provided the sandbox should reattach to that existing VM instead of\n * provisioning a new one.\n */\nexport type SandboxFactory = (opts: SandboxCreateOptions) => MaterializationSandbox;\n\n/** Raised when provisioning would exceed the per-replica sandbox budget. */\nexport class SandboxBudgetError extends Error {\n readonly code = 'sandbox-budget-exceeded' as const;\n constructor(readonly max: number) {\n super(\n `Sandbox budget exceeded: this server already has ${max} active sandbox(es), ` +\n `the configured per-replica maximum. Close an existing repository's sandbox and try again.`,\n );\n this.name = 'SandboxBudgetError';\n }\n}\n\n/** Optional knobs for provisioning/reattaching one sandbox. */\nexport interface EnsureSandboxOptions {\n /** Provider working directory for this sandbox. */\n workingDirectory?: string;\n}\n\n/**\n * Where a feature persists its sandbox binding. The fleet reads the stored\n * reattach id and writes updates through this seam so it stays agnostic of\n * the owning table (GitHub projects today, anything else tomorrow).\n */\nexport interface SandboxBindingStore {\n /** Stored provider reattach id from a previous provisioning, if any. */\n readonly sandboxId: string | null;\n /** Provider checkpoint used to seed and preserve this sandbox's filesystem. */\n readonly checkpointName?: string;\n /** Persist a freshly provisioned provider id, or clear a stale one with `null`. */\n setSandboxId(id: string | null): Promise<void>;\n /** Clear all stored sandbox state (reattach id + materialization mark) on teardown. */\n clear(): Promise<void>;\n}\n\n/**\n * Adapt a cloned `WorkspaceSandbox` to the minimal surface this module needs.\n * Lifecycle goes through the `_`-prefixed wrappers when present (they add\n * status tracking and concurrency safety on `MastraSandbox` subclasses),\n * falling back to the plain methods for interface-only implementations.\n */\nfunction toMaterializationSandbox(\n sandbox: WorkspaceSandbox,\n initialEnvironment: Record<string, string> = {},\n): MaterializationSandbox {\n if (typeof sandbox.executeCommand !== 'function') {\n throw new Error(\n `Sandbox provider '${sandbox.provider}' does not implement executeCommand() — cannot materialize repos.`,\n );\n }\n const lifecycle = sandbox as { _start?(): Promise<void>; _stop?(): Promise<void> };\n const environment = { ...initialEnvironment };\n return {\n id: sandbox.id,\n start: async () => {\n await (lifecycle._start ?? sandbox.start)?.call(sandbox);\n },\n getInfo: async () => (await sandbox.getInfo?.()) ?? {},\n executeCommand: (command, args, options) =>\n sandbox.executeCommand!(command, args, {\n ...options,\n env: { ...environment, ...options?.env },\n }),\n setEnvironmentVariable: (name, value) => {\n environment[name] = value;\n },\n stop: async () => {\n await (lifecycle._stop ?? sandbox.stop)?.call(sandbox);\n },\n };\n}\n\n/**\n * The provider's reattach id for a started sandbox. For Railway this is the\n * underlying `railwaySandboxId` in `getInfo().metadata`. Providers without a\n * provider-native id (e.g. local) reattach by construction id, so fall back\n * to the sandbox's own logical id.\n */\nasync function readProviderSandboxId(sandbox: MaterializationSandbox): Promise<string | undefined> {\n const info = await sandbox.getInfo();\n const id = info.metadata?.railwaySandboxId ?? info.metadata?.sandboxId;\n return typeof id === 'string' ? id : sandbox.id;\n}\n\n/** Keep each path piece a single safe segment (no separators or traversal). */\nfunction sanitizeSegment(segment: string): string {\n const cleaned = segment.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^\\.+/, '');\n return cleaned || 'repo';\n}\n\n/** Resolve a workdir under `root`, refusing any path that escapes the configured root. */\nexport function resolveContainedLocalWorkdir(root: string, ...segments: string[]): string {\n const resolvedRoot = path.resolve(root);\n const resolved = path.resolve(resolvedRoot, ...segments);\n if (resolved !== resolvedRoot && resolved.startsWith(`${resolvedRoot}${path.sep}`)) return resolved;\n throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);\n}\n\n/**\n * Factory-resolved sandbox runtime the fleet is constructed with: the machine\n * projects clone their per-project sandboxes from, plus the knobs the factory\n * resolved around it.\n */\nexport interface SandboxFleetConfig {\n /**\n * Template machine (validated by the factory to implement `clone()`).\n * Never started — acts purely as the credential/default holder that\n * per-project sandboxes are cloned from.\n */\n machine: WorkspaceSandbox;\n /** In-sandbox base directory repos check out under (no trailing slash). */\n workdirBase: string;\n /** Per-replica cap on concurrently provisioned sandboxes. 0 = unlimited. */\n maxSandboxes?: number;\n}\n\n/**\n * The sandbox fleet for one deployment. Constructed once at boot — with a\n * config when a sandbox machine was configured, or without one when sandboxes\n * are disabled (every provisioning entry point then throws and\n * {@link enabled} reports `false` so features stay off).\n */\nexport class SandboxFleet {\n readonly #config: SandboxFleetConfig | undefined;\n #factory: SandboxFactory | undefined;\n #liveCount = 0;\n\n constructor(config?: SandboxFleetConfig) {\n this.#config = config;\n }\n\n /**\n * True when a sandbox machine was configured. The factory validates the\n * machine implements `clone()` at boot, so a configured fleet is usable —\n * sandbox-backed projects stay off only when the slot was omitted.\n */\n get enabled(): boolean {\n return this.#config !== undefined;\n }\n\n /**\n * Name of the active sandbox provider — the configured machine's `provider`\n * discriminator (`'railway'`, `'local'`, …), or `'none'` when the fleet was\n * constructed without a config. Diagnostic only; feature gating goes\n * through {@link enabled}.\n */\n get provider(): string {\n return this.#config?.machine.provider ?? 'none';\n }\n\n /**\n * Idle teardown window for provisioned sandboxes, in minutes; defaults to 30.\n * Read back from the machine's own config when it exposes one\n * (Railway's `idleTimeoutMinutes`) — the knob lives on the sandbox, the\n * fleet only needs it to schedule GC and stamp sandbox clones. Advisory:\n * providers without idle GC ignore it, and a re-open detects a torn-down VM\n * and re-provisions cleanly.\n */\n get idleMinutes(): number {\n const machine = this.#config?.machine as { idleTimeoutMinutes?: unknown } | undefined;\n const minutes = machine?.idleTimeoutMinutes;\n return typeof minutes === 'number' && Number.isFinite(minutes) && minutes > 0 ? minutes : 30;\n }\n\n /**\n * Per-replica cap on concurrently *provisioned* sandboxes. 0 means unlimited.\n * This is a lightweight per-process budget to keep a single replica from\n * exhausting provider quota — it is not a global, cross-replica scheduler\n * (that is a deferred follow-up).\n */\n get maxSandboxes(): number {\n return this.#config?.maxSandboxes ?? 0;\n }\n\n /**\n * Count of sandboxes this fleet has freshly provisioned and not yet torn\n * down. Reattaches to existing VMs do not count (they reuse an already-billed\n * sandbox). Used to enforce {@link maxSandboxes}.\n */\n get liveCount(): number {\n return this.#liveCount;\n }\n\n /** For tests: reset the live-sandbox counter to a known state. */\n __resetLiveCount(value = 0): void {\n this.#liveCount = value;\n }\n\n /** Override the sandbox factory (tests). */\n setFactory(factory: SandboxFactory): void {\n this.#factory = factory;\n }\n\n /** Reset to the default machine-cloning factory. */\n resetFactory(): void {\n this.#factory = undefined;\n }\n\n /**\n * Compute the in-sandbox working directory for a repo: a nested\n * `<base>/<owner>/<name>` layout under the factory-resolved checkout base.\n * Nesting keeps same-name repos apart (`acme/api` vs `other/api`) — cloud\n * sandboxes are one-per-project so it's merely tidy there, but local\n * checkouts share one host root where it prevents collisions. Server-side\n * only; never derived from client input.\n */\n computeWorkdir(repoFullName: string): string {\n if (!this.#config) throw new Error('No sandbox configured');\n const [owner, name] = repoFullName.split('/', 2);\n return `${this.#config.workdirBase}/${sanitizeSegment(owner || 'unknown')}/${sanitizeSegment(name || 'repo')}`;\n }\n\n /**\n * Compute the host working directory for a local GitHub session checkout.\n * This is server-derived only: repo pieces are sanitized and the trusted\n * session id is kept as a single path segment under the configured local root.\n */\n computeLocalSessionWorkdir(repoFullName: string, sessionId: string): string {\n if (!this.#config) throw new Error('No sandbox configured');\n if (this.#config.machine.provider !== 'local') {\n throw new Error('Local session workdirs require the local sandbox provider');\n }\n\n const localRoot = (this.#config.machine as { workingDirectory?: unknown }).workingDirectory;\n if (typeof localRoot !== 'string' || localRoot.length === 0) {\n throw new Error('Local sandbox working directory is not configured');\n }\n\n const [owner, name] = repoFullName.split('/', 2);\n return resolveContainedLocalWorkdir(\n localRoot,\n 'github-sessions',\n sanitizeSegment(owner || 'unknown'),\n sanitizeSegment(name || 'repo'),\n sanitizeSegment(sessionId),\n );\n }\n\n /**\n * Build a (not-yet-started) sandbox: the test-provided factory when set,\n * otherwise a per-project clone of the configured machine. The stored id is\n * passed both as the logical `id` (providers that reattach by construction\n * id, e.g. local) and as the provider-native `sandboxId` hint (Railway) so\n * reattach works across the provider matrix.\n */\n #build(opts: SandboxCreateOptions): MaterializationSandbox {\n if (this.#factory) return this.#factory(opts);\n if (!this.#config) throw new Error('No sandbox configured');\n const clone = this.#config.machine.clone!({\n ...(opts.providerSandboxId ? { id: opts.providerSandboxId, sandboxId: opts.providerSandboxId } : {}),\n ...(opts.env ? { env: opts.env } : {}),\n ...(opts.workingDirectory ? { workingDirectory: opts.workingDirectory } : {}),\n ...(opts.idleTimeoutMinutes !== undefined ? { idleTimeoutMinutes: opts.idleTimeoutMinutes } : {}),\n ...(opts.checkpointName ? { checkpointName: opts.checkpointName } : {}),\n });\n return toMaterializationSandbox(clone, opts.env);\n }\n\n /**\n * Provision a new sandbox (persisting its provider id on first open) or\n * reattach to the stored one. Returns a started, live sandbox.\n */\n async ensureSandbox(store: SandboxBindingStore, onProgress?: ProgressFn): Promise<MaterializationSandbox>;\n async ensureSandbox(\n store: SandboxBindingStore,\n env?: Record<string, string>,\n onProgress?: ProgressFn,\n options?: EnsureSandboxOptions,\n ): Promise<MaterializationSandbox>;\n async ensureSandbox(\n store: SandboxBindingStore,\n envOrProgress?: Record<string, string> | ProgressFn,\n progressOrOptions?: ProgressFn | EnsureSandboxOptions,\n maybeOptions: EnsureSandboxOptions = {},\n ): Promise<MaterializationSandbox> {\n const env = typeof envOrProgress === 'function' ? undefined : envOrProgress;\n const onProgress =\n typeof envOrProgress === 'function' ? envOrProgress : (progressOrOptions as ProgressFn | undefined);\n const options =\n typeof envOrProgress === 'function'\n ? ((progressOrOptions as EnsureSandboxOptions | undefined) ?? {})\n : maybeOptions;\n const idleTimeoutMinutes = this.idleMinutes;\n const checkpointName = store.checkpointName;\n\n // Reattach path: if we have a stored sandbox id, try to reattach. The VM may\n // have been torn down by the provider's idle GC (or otherwise died), in which\n // case `start()` fails. Recover by clearing the stale id and provisioning a\n // fresh sandbox so the next open succeeds instead of being permanently wedged.\n if (store.sandboxId) {\n reportProgress(onProgress, { phase: 'reattaching', message: 'Reconnecting to your sandbox…' });\n const reattached = this.#build({\n providerSandboxId: store.sandboxId,\n idleTimeoutMinutes,\n ...(checkpointName ? { checkpointName } : {}),\n ...(env ? { env } : {}),\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n });\n try {\n await reattached.start();\n return reattached;\n } catch {\n await store.setSandboxId(null);\n // fall through to fresh provision below\n }\n }\n\n // Fresh provision: enforce the per-replica budget before spending quota.\n const max = this.maxSandboxes;\n if (max > 0 && this.#liveCount >= max) {\n throw new SandboxBudgetError(max);\n }\n\n reportProgress(onProgress, { phase: 'provisioning', message: 'Provisioning a new sandbox…' });\n const sandbox = this.#build({\n idleTimeoutMinutes,\n ...(checkpointName ? { checkpointName } : {}),\n ...(env ? { env } : {}),\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n });\n await sandbox.start();\n this.#liveCount += 1;\n\n const providerSandboxId = await readProviderSandboxId(sandbox);\n if (providerSandboxId) {\n await store.setSandboxId(providerSandboxId);\n }\n\n return sandbox;\n }\n\n /**\n * Tear down a sandbox binding: stop the live VM (best-effort) and clear the\n * persisted state through the binding store so the next open re-provisions\n * cleanly. Decrements the per-replica live-sandbox counter.\n *\n * @param store the binding to tear down\n * @param sandbox an already-reattached live sandbox to stop, when available\n */\n async teardownSandbox(store: SandboxBindingStore, sandbox?: MaterializationSandbox): Promise<void> {\n if (sandbox?.stop) {\n try {\n await sandbox.stop();\n } catch {\n // Best-effort: the VM may already be gone (idle GC). Still clear the binding.\n }\n }\n if (store.sandboxId) {\n if (this.#liveCount > 0) this.#liveCount -= 1;\n await store.clear();\n }\n }\n\n /**\n * Reattach to an already-provisioned sandbox by its provider id and start it.\n * Used by the workspace seam when opening a project that was already\n * materialized (sandbox id + workdir carried on controller state), so no DB\n * round-trip is needed.\n */\n async reattachSandbox(\n providerSandboxId: string,\n options: EnsureSandboxOptions = {},\n ): Promise<MaterializationSandbox> {\n const sandbox = this.#build({\n providerSandboxId,\n idleTimeoutMinutes: this.idleMinutes,\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n });\n await sandbox.start();\n return sandbox;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8EA,SAAgB,eAAe,YAAoC,OAA8B;CAC/F,IAAI,CAAC,YAAY;CACjB,IAAI;EACF,WAAW,KAAK;CAClB,QAAQ,CAER;AACF;;AAUA,IAAa,qBAAb,cAAwC,MAAM;CAEvB;CADrB,OAAgB;CAChB,YAAY,KAAsB;EAChC,MACE,oDAAoD,IAAI,+GAE1D;EAJmB,KAAA,MAAA;EAKnB,KAAK,OAAO;CACd;AACF;;;;;;;AA8BA,SAAS,yBACP,SACA,qBAA6C,CAAC,GACtB;CACxB,IAAI,OAAO,QAAQ,mBAAmB,YACpC,MAAM,IAAI,MACR,qBAAqB,QAAQ,SAAS,kEACxC;CAEF,MAAM,YAAY;CAClB,MAAM,cAAc,EAAE,GAAG,mBAAmB;CAC5C,OAAO;EACL,IAAI,QAAQ;EACZ,OAAO,YAAY;GACjB,OAAO,UAAU,UAAU,QAAQ,MAAA,EAAQ,KAAK,OAAO;EACzD;EACA,SAAS,YAAa,MAAM,QAAQ,UAAU,KAAM,CAAC;EACrD,iBAAiB,SAAS,MAAM,YAC9B,QAAQ,eAAgB,SAAS,MAAM;GACrC,GAAG;GACH,KAAK;IAAE,GAAG;IAAa,GAAG,SAAS;GAAI;EACzC,CAAC;EACH,yBAAyB,MAAM,UAAU;GACvC,YAAY,QAAQ;EACtB;EACA,MAAM,YAAY;GAChB,OAAO,UAAU,SAAS,QAAQ,KAAA,EAAO,KAAK,OAAO;EACvD;CACF;AACF;;;;;;;AAQA,eAAe,sBAAsB,SAA8D;CACjG,MAAM,OAAO,MAAM,QAAQ,QAAQ;CACnC,MAAM,KAAK,KAAK,UAA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IAAI,KAAKA,aAAa,GAAG,KAAKA,cAAc;GAC5C,MAAM,MAAM,MAAM;EACpB;CACF;;;;;;;CAQA,MAAM,gBACJ,mBACA,UAAgC,CAAC,GACA;EACjC,MAAM,UAAU,KAAKE,OAAO;GAC1B;GACA,oBAAoB,KAAK;GACzB,GAAI,QAAQ,mBAAmB,EAAE,kBAAkB,QAAQ,iBAAiB,IAAI,CAAC;EACnF,CAAC;EACD,MAAM,QAAQ,MAAM;EACpB,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"fleet.js","names":["#config","#inflight","#liveCount","#factory","#ensureSandboxUncoalesced","#build"],"sources":["../../src/sandbox/fleet.ts"],"sourcesContent":["/**\n * Project sandbox fleet: provisioning, reattach, teardown, and budgeting.\n *\n * Server-hosted projects never run on the web host itself. Each project gets\n * its own isolated sandbox (a `WorkspaceSandbox`, e.g. a Railway VM) `clone()`d\n * from the machine the factory was configured with. This module owns everything\n * about that fleet — which provider is active, where checkouts live inside a\n * sandbox, the idle window, the per-replica budget, and the\n * provision/reattach/teardown lifecycle — but knows nothing about what runs\n * inside a sandbox (git materialization lives with its feature, e.g. the\n * GitHub integration's `sandbox.ts`).\n *\n * The fleet is constructed once at boot with the machine config (or none, when\n * sandboxes are disabled) and handed to consumers — no global registry.\n * Persistence of the provider's reattach id is delegated to the caller via\n * {@link SandboxBindingStore}, so the fleet stays storage-agnostic. Tests can\n * swap the low-level construction via {@link SandboxFleet.setFactory}.\n */\n\nimport path from 'node:path';\n\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\n\n/** Minimal command result shape sandbox consumers depend on. */\nexport interface SandboxCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Minimal live-sandbox surface fleet consumers need: an id, a way to start it,\n * a way to learn the provider's reattach id, and command execution.\n */\nexport interface MaterializationSandbox {\n readonly id: string;\n start(): Promise<void>;\n getInfo(): Promise<{ metadata?: Record<string, unknown> }>;\n executeCommand(\n command: string,\n args?: string[],\n options?: { timeout?: number; env?: Record<string, string | undefined> },\n ): Promise<SandboxCommandResult>;\n /** Update an environment variable for future commands in this sandbox. */\n setEnvironmentVariable?(name: string, value: string): void;\n /** Tear down the underlying VM. Optional: providers without it are no-ops. */\n stop?(): Promise<void>;\n}\n\n/** Options for building (or reattaching) one sandbox. */\nexport interface SandboxCreateOptions {\n /** Reattach to this existing provider VM instead of provisioning a new one. */\n providerSandboxId?: string;\n /**\n * Environment variables for commands run in the sandbox. Adapter-level\n * only: merged into every `executeCommand`, never baked into the provider\n * VM (see `SandboxFleet.#build`).\n */\n env?: Record<string, string>;\n /** Provider working directory for this sandbox. */\n workingDirectory?: string;\n /** Idle teardown window (minutes). The provider stops the VM after this idle period. */\n idleTimeoutMinutes?: number;\n /** Provider checkpoint used to seed and preserve this sandbox's filesystem. */\n checkpointName?: string;\n}\n\n/**\n * A coarse-grained step of the sandbox-preparation flow, reported as it happens\n * so the UI can show the user what the server is doing instead of a static\n * \"Preparing…\" toast. `phase` is a stable machine token; `message` is\n * user-facing copy.\n */\nexport interface PrepareProgress {\n phase: 'reattaching' | 'provisioning' | 'preparing-workspace' | 'cloning' | 'pulling' | 'finalizing' | 'done';\n message: string;\n}\n\n/** Callback invoked with each preparation step. Best-effort; never throws. */\nexport type ProgressFn = (event: PrepareProgress) => void;\n\n/** Invoke a progress callback without letting it break the actual work. */\nexport function reportProgress(onProgress: ProgressFn | undefined, event: PrepareProgress): void {\n if (!onProgress) return;\n try {\n onProgress(event);\n } catch {\n // Progress reporting must never break the actual work.\n }\n}\n\n/**\n * Factory that builds a (not-yet-started) sandbox. When `providerSandboxId` is\n * provided the sandbox should reattach to that existing VM instead of\n * provisioning a new one.\n */\nexport type SandboxFactory = (opts: SandboxCreateOptions) => MaterializationSandbox;\n\n/** Raised when provisioning would exceed the per-replica sandbox budget. */\nexport class SandboxBudgetError extends Error {\n readonly code = 'sandbox-budget-exceeded' as const;\n constructor(readonly max: number) {\n super(\n `Sandbox budget exceeded: this server already has ${max} active sandbox(es), ` +\n `the configured per-replica maximum. Close an existing repository's sandbox and try again.`,\n );\n this.name = 'SandboxBudgetError';\n }\n}\n\n/** Optional knobs for provisioning/reattaching one sandbox. */\nexport interface EnsureSandboxOptions {\n /** Provider working directory for this sandbox. */\n workingDirectory?: string;\n}\n\n/**\n * Where a feature persists its sandbox binding. The fleet reads the stored\n * reattach id and writes updates through this seam so it stays agnostic of\n * the owning table (GitHub projects today, anything else tomorrow).\n */\nexport interface SandboxBindingStore {\n /** Stored provider reattach id from a previous provisioning, if any. */\n readonly sandboxId: string | null;\n /** Provider checkpoint used to seed and preserve this sandbox's filesystem. */\n readonly checkpointName?: string;\n /** Persist a freshly provisioned provider id, or clear a stale one with `null`. */\n setSandboxId(id: string | null): Promise<void>;\n /** Clear all stored sandbox state (reattach id + materialization mark) on teardown. */\n clear(): Promise<void>;\n}\n\n/**\n * Stable identity for one binding's in-flight provision work, used to coalesce\n * concurrent `ensureSandbox` calls. Prefer `checkpointName` — it is a pure\n * function of the owning session and is set before the first provision, which\n * is exactly when the herd forms (the stored `sandboxId` is still null then).\n * Fall back to the stored provider id, and skip coalescing entirely for\n * bindings with neither: keying those on a shared constant would wrongly\n * funnel *different* bindings onto one sandbox.\n */\nfunction coalesceKey(store: SandboxBindingStore): string | undefined {\n if (store.checkpointName) return `checkpoint:${store.checkpointName}`;\n if (store.sandboxId) return `sandbox:${store.sandboxId}`;\n return undefined;\n}\n\n/**\n * Adapt a cloned `WorkspaceSandbox` to the minimal surface this module needs.\n * Lifecycle goes through the `_`-prefixed wrappers when present (they add\n * status tracking and concurrency safety on `MastraSandbox` subclasses),\n * falling back to the plain methods for interface-only implementations.\n */\nfunction toMaterializationSandbox(\n sandbox: WorkspaceSandbox,\n initialEnvironment: Record<string, string> = {},\n): MaterializationSandbox {\n if (typeof sandbox.executeCommand !== 'function') {\n throw new Error(\n `Sandbox provider '${sandbox.provider}' does not implement executeCommand() — cannot materialize repos.`,\n );\n }\n const lifecycle = sandbox as { _start?(): Promise<void>; _stop?(): Promise<void> };\n const environment = { ...initialEnvironment };\n return {\n id: sandbox.id,\n start: async () => {\n await (lifecycle._start ?? sandbox.start)?.call(sandbox);\n },\n getInfo: async () => (await sandbox.getInfo?.()) ?? {},\n executeCommand: (command, args, options) =>\n sandbox.executeCommand!(command, args, {\n ...options,\n env: { ...environment, ...options?.env },\n }),\n setEnvironmentVariable: (name, value) => {\n environment[name] = value;\n },\n stop: async () => {\n await (lifecycle._stop ?? sandbox.stop)?.call(sandbox);\n },\n };\n}\n\n/**\n * The provider's reattach id for a started sandbox. For Railway this is the\n * underlying `railwaySandboxId` in `getInfo().metadata`. Providers without a\n * provider-native id (e.g. local) reattach by construction id, so fall back\n * to the sandbox's own logical id.\n */\nasync function readProviderSandboxId(sandbox: MaterializationSandbox): Promise<string | undefined> {\n const info = await sandbox.getInfo();\n const id = info.metadata?.railwaySandboxId ?? info.metadata?.sandboxId;\n return typeof id === 'string' ? id : sandbox.id;\n}\n\n/** Keep each path piece a single safe segment (no separators or traversal). */\nfunction sanitizeSegment(segment: string): string {\n const cleaned = segment.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^\\.+/, '');\n return cleaned || 'repo';\n}\n\n/** Resolve a workdir under `root`, refusing any path that escapes the configured root. */\nexport function resolveContainedLocalWorkdir(root: string, ...segments: string[]): string {\n const resolvedRoot = path.resolve(root);\n const resolved = path.resolve(resolvedRoot, ...segments);\n if (resolved !== resolvedRoot && resolved.startsWith(`${resolvedRoot}${path.sep}`)) return resolved;\n throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);\n}\n\n/**\n * Factory-resolved sandbox runtime the fleet is constructed with: the machine\n * projects clone their per-project sandboxes from, plus the knobs the factory\n * resolved around it.\n */\nexport interface SandboxFleetConfig {\n /**\n * Template machine (validated by the factory to implement `clone()`).\n * Never started — acts purely as the credential/default holder that\n * per-project sandboxes are cloned from.\n */\n machine: WorkspaceSandbox;\n /** In-sandbox base directory repos check out under (no trailing slash). */\n workdirBase: string;\n /** Per-replica cap on concurrently provisioned sandboxes. 0 = unlimited. */\n maxSandboxes?: number;\n}\n\n/**\n * The sandbox fleet for one deployment. Constructed once at boot — with a\n * config when a sandbox machine was configured, or without one when sandboxes\n * are disabled (every provisioning entry point then throws and\n * {@link enabled} reports `false` so features stay off).\n */\nexport class SandboxFleet {\n readonly #config: SandboxFleetConfig | undefined;\n #factory: SandboxFactory | undefined;\n #liveCount = 0;\n /** In-flight `ensureSandbox` work, keyed per binding so concurrent callers coalesce. */\n readonly #inflight = new Map<string, Promise<MaterializationSandbox>>();\n\n constructor(config?: SandboxFleetConfig) {\n this.#config = config;\n }\n\n /**\n * True when a sandbox machine was configured. The factory validates the\n * machine implements `clone()` at boot, so a configured fleet is usable —\n * sandbox-backed projects stay off only when the slot was omitted.\n */\n get enabled(): boolean {\n return this.#config !== undefined;\n }\n\n /**\n * Name of the active sandbox provider — the configured machine's `provider`\n * discriminator (`'railway'`, `'local'`, …), or `'none'` when the fleet was\n * constructed without a config. Diagnostic only; feature gating goes\n * through {@link enabled}.\n */\n get provider(): string {\n return this.#config?.machine.provider ?? 'none';\n }\n\n /**\n * Idle teardown window for provisioned sandboxes, in minutes; defaults to 30.\n * Read back from the machine's own config when it exposes one\n * (Railway's `idleTimeoutMinutes`) — the knob lives on the sandbox, the\n * fleet only needs it to schedule GC and stamp sandbox clones. Advisory:\n * providers without idle GC ignore it, and a re-open detects a torn-down VM\n * and re-provisions cleanly.\n */\n get idleMinutes(): number {\n const machine = this.#config?.machine as { idleTimeoutMinutes?: unknown } | undefined;\n const minutes = machine?.idleTimeoutMinutes;\n return typeof minutes === 'number' && Number.isFinite(minutes) && minutes > 0 ? minutes : 30;\n }\n\n /**\n * Per-replica cap on concurrently *provisioned* sandboxes. 0 means unlimited.\n * This is a lightweight per-process budget to keep a single replica from\n * exhausting provider quota — it is not a global, cross-replica scheduler\n * (that is a deferred follow-up).\n */\n get maxSandboxes(): number {\n return this.#config?.maxSandboxes ?? 0;\n }\n\n /**\n * Count of sandboxes this fleet has freshly provisioned and not yet torn\n * down. Reattaches to existing VMs do not count (they reuse an already-billed\n * sandbox). Used to enforce {@link maxSandboxes}.\n */\n get liveCount(): number {\n return this.#liveCount;\n }\n\n /** For tests: reset the live-sandbox counter to a known state. */\n __resetLiveCount(value = 0): void {\n this.#liveCount = value;\n }\n\n /** Override the sandbox factory (tests). */\n setFactory(factory: SandboxFactory): void {\n this.#factory = factory;\n }\n\n /** Reset to the default machine-cloning factory. */\n resetFactory(): void {\n this.#factory = undefined;\n }\n\n /**\n * Compute the in-sandbox working directory for a repo: a nested\n * `<base>/<owner>/<name>` layout under the factory-resolved checkout base.\n * Nesting keeps same-name repos apart (`acme/api` vs `other/api`) — cloud\n * sandboxes are one-per-project so it's merely tidy there, but local\n * checkouts share one host root where it prevents collisions. Server-side\n * only; never derived from client input.\n */\n computeWorkdir(repoFullName: string): string {\n if (!this.#config) throw new Error('No sandbox configured');\n const [owner, name] = repoFullName.split('/', 2);\n return `${this.#config.workdirBase}/${sanitizeSegment(owner || 'unknown')}/${sanitizeSegment(name || 'repo')}`;\n }\n\n /**\n * Compute the host working directory for a local GitHub session checkout.\n * This is server-derived only: repo pieces are sanitized and the trusted\n * session id is kept as a single path segment under the configured local root.\n */\n computeLocalSessionWorkdir(repoFullName: string, sessionId: string): string {\n if (!this.#config) throw new Error('No sandbox configured');\n if (this.#config.machine.provider !== 'local') {\n throw new Error('Local session workdirs require the local sandbox provider');\n }\n\n const localRoot = (this.#config.machine as { workingDirectory?: unknown }).workingDirectory;\n if (typeof localRoot !== 'string' || localRoot.length === 0) {\n throw new Error('Local sandbox working directory is not configured');\n }\n\n const [owner, name] = repoFullName.split('/', 2);\n return resolveContainedLocalWorkdir(\n localRoot,\n 'github-sessions',\n sanitizeSegment(owner || 'unknown'),\n sanitizeSegment(name || 'repo'),\n sanitizeSegment(sessionId),\n );\n }\n\n /**\n * Build a (not-yet-started) sandbox: the test-provided factory when set,\n * otherwise a per-project clone of the configured machine. The stored id is\n * passed both as the logical `id` (providers that reattach by construction\n * id, e.g. local) and as the provider-native `sandboxId` hint (Railway) so\n * reattach works across the provider matrix.\n *\n * `env` is deliberately NOT forwarded to the provider clone: remote\n * providers bake creation-time env into the VM for its whole lifetime\n * (`POST /sandbox`), which would persist credentials like `GH_TOKEN` inside\n * a VM that can outlive the session and be reused by another user via the\n * sandbox pool. Instead the env lives only on the adapter, which merges it\n * into every `executeCommand` — commands see the (refreshable) token, but\n * the VM itself never stores it.\n */\n #build(opts: SandboxCreateOptions): MaterializationSandbox {\n if (this.#factory) return this.#factory(opts);\n if (!this.#config) throw new Error('No sandbox configured');\n const clone = this.#config.machine.clone!({\n ...(opts.providerSandboxId ? { id: opts.providerSandboxId, sandboxId: opts.providerSandboxId } : {}),\n ...(opts.workingDirectory ? { workingDirectory: opts.workingDirectory } : {}),\n ...(opts.idleTimeoutMinutes !== undefined ? { idleTimeoutMinutes: opts.idleTimeoutMinutes } : {}),\n ...(opts.checkpointName ? { checkpointName: opts.checkpointName } : {}),\n });\n return toMaterializationSandbox(clone, opts.env);\n }\n\n /**\n * Provision a new sandbox (persisting its provider id on first open) or\n * reattach to the stored one. Returns a started, live sandbox.\n *\n * Concurrent calls for the same binding coalesce onto one in-flight\n * provision/reattach and share its sandbox handle — N simultaneous requests\n * for one cold session (e.g. several browser tabs polling right after boot)\n * must not each fire their own `POST /sandbox` against the provider.\n * Failures are not cached: once the shared attempt settles, the next call\n * starts fresh.\n */\n async ensureSandbox(store: SandboxBindingStore, onProgress?: ProgressFn): Promise<MaterializationSandbox>;\n async ensureSandbox(\n store: SandboxBindingStore,\n env?: Record<string, string>,\n onProgress?: ProgressFn,\n options?: EnsureSandboxOptions,\n ): Promise<MaterializationSandbox>;\n async ensureSandbox(\n store: SandboxBindingStore,\n envOrProgress?: Record<string, string> | ProgressFn,\n progressOrOptions?: ProgressFn | EnsureSandboxOptions,\n maybeOptions: EnsureSandboxOptions = {},\n ): Promise<MaterializationSandbox> {\n const env = typeof envOrProgress === 'function' ? undefined : envOrProgress;\n const onProgress =\n typeof envOrProgress === 'function' ? envOrProgress : (progressOrOptions as ProgressFn | undefined);\n const options =\n typeof envOrProgress === 'function'\n ? ((progressOrOptions as EnsureSandboxOptions | undefined) ?? {})\n : maybeOptions;\n\n const key = coalesceKey(store);\n if (!key) return this.#ensureSandboxUncoalesced(store, env, onProgress, options);\n\n const existing = this.#inflight.get(key);\n if (existing) return existing;\n\n const promise = this.#ensureSandboxUncoalesced(store, env, onProgress, options).finally(() => {\n // Only clear when this is still the entry we own.\n if (this.#inflight.get(key) === promise) this.#inflight.delete(key);\n });\n this.#inflight.set(key, promise);\n return promise;\n }\n\n /** The single provision/reattach attempt behind {@link ensureSandbox}. */\n async #ensureSandboxUncoalesced(\n store: SandboxBindingStore,\n env: Record<string, string> | undefined,\n onProgress: ProgressFn | undefined,\n options: EnsureSandboxOptions,\n ): Promise<MaterializationSandbox> {\n const idleTimeoutMinutes = this.idleMinutes;\n const checkpointName = store.checkpointName;\n\n // Reattach path: if we have a stored sandbox id, try to reattach. The VM may\n // have been torn down by the provider's idle GC (or otherwise died), in which\n // case `start()` fails. Recover by clearing the stale id and provisioning a\n // fresh sandbox so the next open succeeds instead of being permanently wedged.\n if (store.sandboxId) {\n reportProgress(onProgress, { phase: 'reattaching', message: 'Reconnecting to your sandbox…' });\n const reattached = this.#build({\n providerSandboxId: store.sandboxId,\n idleTimeoutMinutes,\n ...(checkpointName ? { checkpointName } : {}),\n ...(env ? { env } : {}),\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n });\n try {\n await reattached.start();\n return reattached;\n } catch {\n await store.setSandboxId(null);\n // fall through to fresh provision below\n }\n }\n\n // Fresh provision: enforce the per-replica budget before spending quota.\n const max = this.maxSandboxes;\n if (max > 0 && this.#liveCount >= max) {\n throw new SandboxBudgetError(max);\n }\n\n reportProgress(onProgress, { phase: 'provisioning', message: 'Provisioning a new sandbox…' });\n const sandbox = this.#build({\n idleTimeoutMinutes,\n ...(checkpointName ? { checkpointName } : {}),\n ...(env ? { env } : {}),\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n });\n await sandbox.start();\n this.#liveCount += 1;\n\n const providerSandboxId = await readProviderSandboxId(sandbox);\n if (providerSandboxId) {\n await store.setSandboxId(providerSandboxId);\n }\n\n return sandbox;\n }\n\n /**\n * Tear down a sandbox binding: stop the live VM (best-effort) and clear the\n * persisted state through the binding store so the next open re-provisions\n * cleanly. Decrements the per-replica live-sandbox counter.\n *\n * @param store the binding to tear down\n * @param sandbox an already-reattached live sandbox to stop, when available\n */\n async teardownSandbox(store: SandboxBindingStore, sandbox?: MaterializationSandbox): Promise<void> {\n if (sandbox?.stop) {\n try {\n await sandbox.stop();\n } catch {\n // Best-effort: the VM may already be gone (idle GC). Still clear the binding.\n }\n }\n if (store.sandboxId) {\n if (this.#liveCount > 0) this.#liveCount -= 1;\n await store.clear();\n }\n }\n\n /**\n * Reattach to an already-provisioned sandbox by its provider id and start it.\n * Used by the workspace seam when opening a project that was already\n * materialized (sandbox id + workdir carried on controller state), so no DB\n * round-trip is needed.\n */\n async reattachSandbox(\n providerSandboxId: string,\n options: EnsureSandboxOptions = {},\n ): Promise<MaterializationSandbox> {\n const sandbox = this.#build({\n providerSandboxId,\n idleTimeoutMinutes: this.idleMinutes,\n ...(options.workingDirectory ? { workingDirectory: options.workingDirectory } : {}),\n });\n await sandbox.start();\n return sandbox;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkFA,SAAgB,eAAe,YAAoC,OAA8B;CAC/F,IAAI,CAAC,YAAY;CACjB,IAAI;EACF,WAAW,KAAK;CAClB,QAAQ,CAER;AACF;;AAUA,IAAa,qBAAb,cAAwC,MAAM;CAEvB;CADrB,OAAgB;CAChB,YAAY,KAAsB;EAChC,MACE,oDAAoD,IAAI,+GAE1D;EAJmB,KAAA,MAAA;EAKnB,KAAK,OAAO;CACd;AACF;;;;;;;;;;AAiCA,SAAS,YAAY,OA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,IAAI,KAAKA,aAAa,GAAG,KAAKA,cAAc;GAC5C,MAAM,MAAM,MAAM;EACpB;CACF;;;;;;;CAQA,MAAM,gBACJ,mBACA,UAAgC,CAAC,GACA;EACjC,MAAM,UAAU,KAAKG,OAAO;GAC1B;GACA,oBAAoB,KAAK;GACzB,GAAI,QAAQ,mBAAmB,EAAE,kBAAkB,QAAQ,iBAAiB,IAAI,CAAC;EACnF,CAAC;EACD,MAAM,QAAQ,MAAM;EACpB,OAAO;CACT;AACF"}
|
package/dist/spa-static.js
CHANGED
package/dist/spa-static.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spa-static.js","names":[],"sources":["../src/spa-static.ts"],"sourcesContent":["/**\n * Same-origin SPA serving for production.\n *\n * In dev the SPA is served by Vite (:5173) which proxies API paths to the\n * server (:4111) — this module is effectively idle there. In production the\n * built SPA (vite output) is served by the API server itself at `/`, so the\n * app is a single origin and no CORS / separate static host is required.\n *\n * The middleware is mounted via the Mastra entry's `server.middleware`, which\n * the deployer applies before routes: real file hits and SPA navigations are\n * answered here, everything else falls through to the API routes.\n */\n\nimport { existsSync } from 'node:fs';\nimport { readFile, stat } from 'node:fs/promises';\nimport { dirname, extname, join, normalize, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { Context } from 'hono';\n\nconst MIME: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json',\n '.webmanifest': 'application/manifest+json',\n '.map': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.txt': 'text/plain; charset=utf-8',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.wasm': 'application/wasm',\n};\n\n/** Server-owned path prefixes the SPA middleware must never answer for. */\nconst SERVER_PREFIXES = ['/api', '/web', '/auth'];\n\n/**\n * Locate the built SPA (a dir containing `index.html`). Checked in order:\n * 1. `MASTRACODE_UI_DIST` — explicit override for custom layouts.\n * 2. `factory/` under cwd — both `mastra dev` (cwd is the Mastra public dir)\n * and `mastra start` (cwd is `.mastra/output`) expose assets this way.\n * 3. `factory/` next to the bundled server module.\n * 4. Source-layout fallbacks under `MASTRA_PROJECT_ROOT` or cwd.\n * Returns `undefined` when no build is found (e.g. plain `mastra dev` without\n * a prior vite build), in which case the middleware is simply not mounted.\n */\nexport function resolveUiDistDir(): string | undefined {\n const projectRoot = process.env.MASTRA_PROJECT_ROOT?.trim();\n const candidates = [\n process.env.MASTRACODE_UI_DIST,\n resolve(process.cwd(), 'factory'),\n join(dirname(fileURLToPath(import.meta.url)), 'factory'),\n projectRoot && resolve(projectRoot, 'src/mastra/public/factory'),\n resolve(process.cwd(), 'src/mastra/public/factory'),\n ];\n for (const candidate of candidates) {\n if (candidate && existsSync(join(candidate, 'index.html'))) return resolve(candidate);\n }\n return undefined;\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile();\n } catch {\n return false;\n }\n}\n\nasync function serveFile(c: Context, filePath: string, immutable: boolean): Promise<Response> {\n const data = await readFile(filePath);\n c.header('Content-Type', MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream');\n // Vite emits content-hashed filenames under assets/ — cache those forever;\n // index.html (and anything unhashed) must revalidate so deploys roll out.\n c.header('Cache-Control', immutable ? 'public, max-age=31536000, immutable' : 'no-cache');\n return c.body(new Uint8Array(data));\n}\n\n/**\n * Hono middleware serving the built SPA from `uiDist`:\n * - exact file hits (js/css/assets) are served directly,\n * - GET navigations to non-server paths fall back to `index.html` (SPA\n * client-side routing),\n * - `/api`, `/web`, `/auth` and non-GET requests always pass through.\n */\nexport function createSpaStaticMiddleware(uiDist: string) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n if (c.req.method !== 'GET' && c.req.method !== 'HEAD') return next();\n const path = c.req.path;\n if (SERVER_PREFIXES.some(prefix => path === prefix || path.startsWith(`${prefix}/`))) return next();\n\n // Resolve the request path inside uiDist, rejecting traversal escapes.\n const relative = normalize(decodeURIComponent(path)).replace(/^[/\\\\]+/, '');\n const filePath = resolve(uiDist, relative);\n // Use a trailing separator so a sibling like \"ui.key\" can't slip past the\n // prefix check (same pattern as fs-routes.ts isWithinRoot).\n const uiDistPrefix = uiDist.endsWith(sep) ? uiDist : uiDist + sep;\n if (filePath.startsWith(uiDistPrefix) && relative !== '' && (await isFile(filePath))) {\n return serveFile(c, filePath, relative.startsWith('assets/'));\n }\n\n // SPA fallback: serve index.html for root and html navigations.\n const accept = c.req.header('Accept') ?? '';\n if (path === '/' || accept.includes('text/html')) {\n return serveFile(c, join(uiDist, 'index.html'), false);\n }\n\n return next();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,MAAM,OAA+B;CACnC,SAAS;CACT,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,gBAAgB;CAChB,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,UAAU;CACV,QAAQ;CACR,SAAS;AACX;;AAGA,MAAM,kBAAkB;CAAC;CAAQ;CAAQ;
|
|
1
|
+
{"version":3,"file":"spa-static.js","names":[],"sources":["../src/spa-static.ts"],"sourcesContent":["/**\n * Same-origin SPA serving for production.\n *\n * In dev the SPA is served by Vite (:5173) which proxies API paths to the\n * server (:4111) — this module is effectively idle there. In production the\n * built SPA (vite output) is served by the API server itself at `/`, so the\n * app is a single origin and no CORS / separate static host is required.\n *\n * The middleware is mounted via the Mastra entry's `server.middleware`, which\n * the deployer applies before routes: real file hits and SPA navigations are\n * answered here, everything else falls through to the API routes.\n */\n\nimport { existsSync } from 'node:fs';\nimport { readFile, stat } from 'node:fs/promises';\nimport { dirname, extname, join, normalize, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { Context } from 'hono';\n\nconst MIME: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json',\n '.webmanifest': 'application/manifest+json',\n '.map': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.txt': 'text/plain; charset=utf-8',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.wasm': 'application/wasm',\n};\n\n/** Server-owned path prefixes the SPA middleware must never answer for. */\nconst SERVER_PREFIXES = ['/api', '/web', '/auth', '/connect'];\n\n/**\n * Locate the built SPA (a dir containing `index.html`). Checked in order:\n * 1. `MASTRACODE_UI_DIST` — explicit override for custom layouts.\n * 2. `factory/` under cwd — both `mastra dev` (cwd is the Mastra public dir)\n * and `mastra start` (cwd is `.mastra/output`) expose assets this way.\n * 3. `factory/` next to the bundled server module.\n * 4. Source-layout fallbacks under `MASTRA_PROJECT_ROOT` or cwd.\n * Returns `undefined` when no build is found (e.g. plain `mastra dev` without\n * a prior vite build), in which case the middleware is simply not mounted.\n */\nexport function resolveUiDistDir(): string | undefined {\n const projectRoot = process.env.MASTRA_PROJECT_ROOT?.trim();\n const candidates = [\n process.env.MASTRACODE_UI_DIST,\n resolve(process.cwd(), 'factory'),\n join(dirname(fileURLToPath(import.meta.url)), 'factory'),\n projectRoot && resolve(projectRoot, 'src/mastra/public/factory'),\n resolve(process.cwd(), 'src/mastra/public/factory'),\n ];\n for (const candidate of candidates) {\n if (candidate && existsSync(join(candidate, 'index.html'))) return resolve(candidate);\n }\n return undefined;\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile();\n } catch {\n return false;\n }\n}\n\nasync function serveFile(c: Context, filePath: string, immutable: boolean): Promise<Response> {\n const data = await readFile(filePath);\n c.header('Content-Type', MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream');\n // Vite emits content-hashed filenames under assets/ — cache those forever;\n // index.html (and anything unhashed) must revalidate so deploys roll out.\n c.header('Cache-Control', immutable ? 'public, max-age=31536000, immutable' : 'no-cache');\n return c.body(new Uint8Array(data));\n}\n\n/**\n * Hono middleware serving the built SPA from `uiDist`:\n * - exact file hits (js/css/assets) are served directly,\n * - GET navigations to non-server paths fall back to `index.html` (SPA\n * client-side routing),\n * - `/api`, `/web`, `/auth` and non-GET requests always pass through.\n */\nexport function createSpaStaticMiddleware(uiDist: string) {\n return async (c: Context, next: () => Promise<void>): Promise<Response | void> => {\n if (c.req.method !== 'GET' && c.req.method !== 'HEAD') return next();\n const path = c.req.path;\n if (SERVER_PREFIXES.some(prefix => path === prefix || path.startsWith(`${prefix}/`))) return next();\n\n // Resolve the request path inside uiDist, rejecting traversal escapes.\n const relative = normalize(decodeURIComponent(path)).replace(/^[/\\\\]+/, '');\n const filePath = resolve(uiDist, relative);\n // Use a trailing separator so a sibling like \"ui.key\" can't slip past the\n // prefix check (same pattern as fs-routes.ts isWithinRoot).\n const uiDistPrefix = uiDist.endsWith(sep) ? uiDist : uiDist + sep;\n if (filePath.startsWith(uiDistPrefix) && relative !== '' && (await isFile(filePath))) {\n return serveFile(c, filePath, relative.startsWith('assets/'));\n }\n\n // SPA fallback: serve index.html for root and html navigations.\n const accept = c.req.header('Accept') ?? '';\n if (path === '/' || accept.includes('text/html')) {\n return serveFile(c, join(uiDist, 'index.html'), false);\n }\n\n return next();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,MAAM,OAA+B;CACnC,SAAS;CACT,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,gBAAgB;CAChB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,CAAC,GAAG,OAAO,KAAK;EAGlG,MAAM,WAAW,UAAU,mBAAmB,IAAI,CAAC,CAAC,CAAC,QAAQ,WAAW,EAAE;EAC1E,MAAM,WAAW,QAAQ,QAAQ,QAAQ;EAGzC,MAAM,eAAe,OAAO,SAAS,GAAG,IAAI,SAAS,SAAS;EAC9D,IAAI,SAAS,WAAW,YAAY,KAAK,aAAa,MAAO,MAAM,OAAO,QAAQ,GAChF,OAAO,UAAU,GAAG,UAAU,SAAS,WAAW,SAAS,CAAC;EAI9D,MAAM,SAAS,EAAE,IAAI,OAAO,QAAQ,KAAK;EACzC,IAAI,SAAS,OAAO,OAAO,SAAS,WAAW,GAC7C,OAAO,UAAU,GAAG,KAAK,QAAQ,YAAY,GAAG,KAAK;EAGvD,OAAO,KAAK;CACd;AACF"}
|
package/dist/state-signing.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Shared OAuth/install `state` signing for web integrations.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* The GitHub, Linear, and Slack OAuth/OIDC flows each round-trip a signed `state`
|
|
5
|
+
* value
|
|
5
6
|
* through the third party to bind the callback to the `(orgId, userId)` tenant
|
|
6
7
|
* that initiated it (CSRF protection + tenant routing). The signer is a system
|
|
7
8
|
* facility: `MastraFactory` creates ONE signer at boot and hands it to every
|
|
@@ -25,6 +26,12 @@
|
|
|
25
26
|
export interface StateTenant {
|
|
26
27
|
orgId: string;
|
|
27
28
|
userId: string;
|
|
29
|
+
/**
|
|
30
|
+
* Per-`state` random value. A signed `state` stays valid for its whole
|
|
31
|
+
* lifetime, so a flow that must not run twice off one `state` (account
|
|
32
|
+
* binding, for instance) can key single-use bookkeeping on this.
|
|
33
|
+
*/
|
|
34
|
+
nonce: string;
|
|
28
35
|
}
|
|
29
36
|
/** Signs and verifies OAuth `state` values bound to a `(orgId, userId)` tenant. */
|
|
30
37
|
export interface StateSigner {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state-signing.d.ts","sourceRoot":"","sources":["../src/state-signing.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"state-signing.d.ts","sourceRoot":"","sources":["../src/state-signing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAIH,qEAAqE;AACrE,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;CACf;AAED,mFAAmF;AACnF,MAAM,WAAW,WAAW;IAC1B,kDAAkD;IAClD,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IAC5C,+EAA+E;IAC/E,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,WAAW,GAAG,IAAI,CAAC;IACtD;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B;AAYD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,WAAW,CAyC9D"}
|
package/dist/state-signing.js
CHANGED
|
@@ -3,7 +3,8 @@ import { createHmac, randomBytes, timingSafeEqual } from "crypto";
|
|
|
3
3
|
/**
|
|
4
4
|
* Shared OAuth/install `state` signing for web integrations.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
6
|
+
* The GitHub, Linear, and Slack OAuth/OIDC flows each round-trip a signed `state`
|
|
7
|
+
* value
|
|
7
8
|
* through the third party to bind the callback to the `(orgId, userId)` tenant
|
|
8
9
|
* that initiated it (CSRF protection + tenant routing). The signer is a system
|
|
9
10
|
* facility: `MastraFactory` creates ONE signer at boot and hands it to every
|
|
@@ -59,11 +60,13 @@ function createStateSigner(secret) {
|
|
|
59
60
|
const parsed = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
|
|
60
61
|
if (typeof parsed.orgId !== "string" || typeof parsed.userId !== "string") return null;
|
|
61
62
|
if (typeof parsed.issuedAt !== "number" || !Number.isFinite(parsed.issuedAt)) return null;
|
|
63
|
+
if (typeof parsed.nonce !== "string" || parsed.nonce.length === 0) return null;
|
|
62
64
|
const age = Date.now() - parsed.issuedAt;
|
|
63
65
|
if (age < 0 || age > STATE_MAX_AGE_MS) return null;
|
|
64
66
|
return {
|
|
65
67
|
orgId: parsed.orgId,
|
|
66
|
-
userId: parsed.userId
|
|
68
|
+
userId: parsed.userId,
|
|
69
|
+
nonce: parsed.nonce
|
|
67
70
|
};
|
|
68
71
|
} catch {
|
|
69
72
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state-signing.js","names":[],"sources":["../src/state-signing.ts"],"sourcesContent":["/**\n * Shared OAuth/install `state` signing for web integrations.\n *\n *
|
|
1
|
+
{"version":3,"file":"state-signing.js","names":[],"sources":["../src/state-signing.ts"],"sourcesContent":["/**\n * Shared OAuth/install `state` signing for web integrations.\n *\n * The GitHub, Linear, and Slack OAuth/OIDC flows each round-trip a signed `state`\n * value\n * through the third party to bind the callback to the `(orgId, userId)` tenant\n * that initiated it (CSRF protection + tenant routing). The signer is a system\n * facility: `MastraFactory` creates ONE signer at boot and hands it to every\n * registered integration through `IntegrationContext` (see\n * `./factory-integration.ts`), so all integrations sign and verify with the\n * same secret.\n *\n * Secret resolution happens in the factory, not here: explicit\n * `config.stateSecret` → the GitHub integration's webhook secret → a\n * per-process random secret. A random secret is NOT stable across replicas —\n * a `state` signed by one replica cannot be verified by another — which is\n * what the `stable` flag reports. The factory fails loud at boot when a\n * registered integration requires a stable signer but only a random one is\n * available.\n *\n * The wire format (base64url JSON payload + `.` + HMAC-SHA256 base64url\n * signature) is unchanged from the previous `github/config.ts` implementation\n * so in-flight OAuth states survive a deploy.\n */\n\nimport { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';\n\n/** Verified `(orgId, userId)` tenant carried by a signed `state`. */\nexport interface StateTenant {\n orgId: string;\n userId: string;\n /**\n * Per-`state` random value. A signed `state` stays valid for its whole\n * lifetime, so a flow that must not run twice off one `state` (account\n * binding, for instance) can key single-use bookkeeping on this.\n */\n nonce: string;\n}\n\n/** Signs and verifies OAuth `state` values bound to a `(orgId, userId)` tenant. */\nexport interface StateSigner {\n /** Build a signed `state` bound to the tenant. */\n sign(orgId: string, userId: string): string;\n /** Verify a signed `state`; returns the bound tenant, or `null` if invalid. */\n verify(state: string | undefined): StateTenant | null;\n /**\n * True when the signer was built from an explicit deployment-stable secret.\n * False means a per-process random secret: fine for single-process/local\n * dev, broken for multi-replica deploys (see module docs).\n */\n readonly stable: boolean;\n}\n\ninterface StatePayload {\n orgId: string;\n userId: string;\n nonce: string;\n issuedAt: number;\n}\n\n/** Signed `state` values expire after this window to bound the CSRF token. */\nconst STATE_MAX_AGE_MS = 10 * 60 * 1000;\n\n/**\n * Create a state signer. With a `secret`, the signer is deployment-stable\n * (`stable: true`); without one it falls back to a per-process random secret\n * (`stable: false`).\n */\nexport function createStateSigner(secret?: string): StateSigner {\n const stable = typeof secret === 'string' && secret.length > 0;\n const key = stable ? secret : randomBytes(32).toString('hex');\n return {\n stable,\n sign(orgId: string, userId: string): string {\n const payload: StatePayload = {\n orgId,\n userId,\n nonce: randomBytes(8).toString('hex'),\n issuedAt: Date.now(),\n };\n const body = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');\n const sig = createHmac('sha256', key).update(body).digest('base64url');\n return `${body}.${sig}`;\n },\n verify(state: string | undefined): StateTenant | null {\n if (!state) return null;\n const dot = state.lastIndexOf('.');\n if (dot <= 0) return null;\n const body = state.slice(0, dot);\n const sig = state.slice(dot + 1);\n const expected = createHmac('sha256', key).update(body).digest('base64url');\n const sigBuf = Buffer.from(sig);\n const expectedBuf = Buffer.from(expected);\n if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {\n return null;\n }\n try {\n const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as StatePayload;\n if (typeof parsed.orgId !== 'string' || typeof parsed.userId !== 'string') return null;\n if (typeof parsed.issuedAt !== 'number' || !Number.isFinite(parsed.issuedAt)) return null;\n if (typeof parsed.nonce !== 'string' || parsed.nonce.length === 0) return null;\n const age = Date.now() - parsed.issuedAt;\n if (age < 0 || age > STATE_MAX_AGE_MS) return null;\n return { orgId: parsed.orgId, userId: parsed.userId, nonce: parsed.nonce };\n } catch {\n return null;\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,mBAAmB,MAAU;;;;;;AAOnC,SAAgB,kBAAkB,QAA8B;CAC9D,MAAM,SAAS,OAAO,WAAW,YAAY,OAAO,SAAS;CAC7D,MAAM,MAAM,SAAS,SAAS,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CAC5D,OAAO;EACL;EACA,KAAK,OAAe,QAAwB;GAC1C,MAAM,UAAwB;IAC5B;IACA;IACA,OAAO,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK;IACpC,UAAU,KAAK,IAAI;GACrB;GACA,MAAM,OAAO,OAAO,KAAK,KAAK,UAAU,OAAO,GAAG,MAAM,CAAC,CAAC,SAAS,WAAW;GAE9E,OAAO,GAAG,KAAK,GADH,WAAW,UAAU,GAAG,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,WACtC;EACtB;EACA,OAAO,OAA+C;GACpD,IAAI,CAAC,OAAO,OAAO;GACnB,MAAM,MAAM,MAAM,YAAY,GAAG;GACjC,IAAI,OAAO,GAAG,OAAO;GACrB,MAAM,OAAO,MAAM,MAAM,GAAG,GAAG;GAC/B,MAAM,MAAM,MAAM,MAAM,MAAM,CAAC;GAC/B,MAAM,WAAW,WAAW,UAAU,GAAG,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,WAAW;GAC1E,MAAM,SAAS,OAAO,KAAK,GAAG;GAC9B,MAAM,cAAc,OAAO,KAAK,QAAQ;GACxC,IAAI,OAAO,WAAW,YAAY,UAAU,CAAC,gBAAgB,QAAQ,WAAW,GAC9E,OAAO;GAET,IAAI;IACF,MAAM,SAAS,KAAK,MAAM,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;IACzE,IAAI,OAAO,OAAO,UAAU,YAAY,OAAO,OAAO,WAAW,UAAU,OAAO;IAClF,IAAI,OAAO,OAAO,aAAa,YAAY,CAAC,OAAO,SAAS,OAAO,QAAQ,GAAG,OAAO;IACrF,IAAI,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,WAAW,GAAG,OAAO;IAC1E,MAAM,MAAM,KAAK,IAAI,IAAI,OAAO;IAChC,IAAI,MAAM,KAAK,MAAM,kBAAkB,OAAO;IAC9C,OAAO;KAAE,OAAO,OAAO;KAAO,QAAQ,OAAO;KAAQ,OAAO,OAAO;IAAM;GAC3E,QAAQ;IACN,OAAO;GACT;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { FactoryStorageDomain } from '@mastra/core/storage';
|
|
2
|
+
import type { CollectionSchema } from '@mastra/core/storage';
|
|
3
|
+
/**
|
|
4
|
+
* A reverse index from a platform sender identity to a Mastra tenant.
|
|
5
|
+
*
|
|
6
|
+
* Inbound channel events (a Slack DM, a Discord mention, ...) carry only the
|
|
7
|
+
* platform-side sender ids — there is no Mastra `(orgId, userId)` on the event.
|
|
8
|
+
* Model credentials, however, resolve **per-tenant**, so a channel run cannot
|
|
9
|
+
* load the sender's stored model credentials until we know which tenant the
|
|
10
|
+
* sender is. This domain holds that mapping: an authenticated web user links
|
|
11
|
+
* their platform account, and the dispatch seam reads it back to stamp the
|
|
12
|
+
* tenant onto the run's request context.
|
|
13
|
+
*
|
|
14
|
+
* One row per `(platform, external_team_id, external_user_id)` — the same
|
|
15
|
+
* platform user in two workspaces (two team ids) is two independent links, so
|
|
16
|
+
* multi-workspace falls out of the key. `platform` is generic (`'slack'` today,
|
|
17
|
+
* reusable for Discord/Telegram later). The `external_` prefix disambiguates
|
|
18
|
+
* the platform-side ids from the tenant ids (`org_id` / `user_id`) that cohabit
|
|
19
|
+
* the row.
|
|
20
|
+
*/
|
|
21
|
+
export interface ChannelAccountLink {
|
|
22
|
+
/** Undefined for personal accounts (no organization). */
|
|
23
|
+
orgId?: string;
|
|
24
|
+
userId: string;
|
|
25
|
+
/**
|
|
26
|
+
* Which Factory project this sender's channel runs route to. Unset until
|
|
27
|
+
* the user picks one (or the dispatch path auto-stamps their only factory).
|
|
28
|
+
*/
|
|
29
|
+
defaultFactoryProjectId?: string;
|
|
30
|
+
linkedAt: Date;
|
|
31
|
+
}
|
|
32
|
+
/** The reverse-lookup key: a platform sender identity. */
|
|
33
|
+
export interface ChannelAccountLinkKey {
|
|
34
|
+
platform: string;
|
|
35
|
+
externalTeamId: string;
|
|
36
|
+
externalUserId: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Human-readable labels for a linked identity, captured at link time (e.g.
|
|
40
|
+
* from Slack OIDC id_token claims). Display-only — never part of the key.
|
|
41
|
+
*/
|
|
42
|
+
export interface ChannelAccountLinkNames {
|
|
43
|
+
externalTeamName?: string;
|
|
44
|
+
externalUserName?: string;
|
|
45
|
+
}
|
|
46
|
+
export declare const CHANNEL_ACCOUNT_LINKS_SCHEMA: CollectionSchema;
|
|
47
|
+
/** A link row with its platform sender key, as listed for a tenant user. */
|
|
48
|
+
export interface ChannelAccountLinkEntry extends ChannelAccountLink, ChannelAccountLinkKey, ChannelAccountLinkNames {
|
|
49
|
+
}
|
|
50
|
+
export declare class ChannelIdentityStorage extends FactoryStorageDomain {
|
|
51
|
+
#private;
|
|
52
|
+
constructor();
|
|
53
|
+
init(): Promise<void>;
|
|
54
|
+
dangerouslyClearAll(): Promise<void>;
|
|
55
|
+
/**
|
|
56
|
+
* Bind a platform sender identity to a Mastra tenant. Last-write-wins: a
|
|
57
|
+
* re-link (e.g. the same Slack user connecting a different tenant) replaces
|
|
58
|
+
* the stored tenant and refreshes `linkedAt`.
|
|
59
|
+
*/
|
|
60
|
+
saveAccountLink({ platform, externalTeamId, externalUserId, orgId, userId, externalTeamName, externalUserName, }: ChannelAccountLinkKey & ChannelAccountLinkNames & {
|
|
61
|
+
orgId?: string;
|
|
62
|
+
userId: string;
|
|
63
|
+
}): Promise<ChannelAccountLink>;
|
|
64
|
+
/**
|
|
65
|
+
* Set (or clear, with `null`) which Factory project a link's channel runs
|
|
66
|
+
* route to. The `userId` guard makes this self-service only — a caller can
|
|
67
|
+
* never repoint another tenant's link. Returns whether a row was updated.
|
|
68
|
+
*
|
|
69
|
+
* Note: `saveAccountLink` deliberately omits this column from its upsert
|
|
70
|
+
* row, so a re-link keeps the stored default.
|
|
71
|
+
*/
|
|
72
|
+
setDefaultFactory({ platform, externalTeamId, externalUserId, userId, factoryProjectId, }: ChannelAccountLinkKey & {
|
|
73
|
+
userId: string;
|
|
74
|
+
factoryProjectId: string | null;
|
|
75
|
+
}): Promise<boolean>;
|
|
76
|
+
/** Resolve the tenant a platform sender is linked to, or `null` if unlinked. */
|
|
77
|
+
getAccountLink({ platform, externalTeamId, externalUserId, }: ChannelAccountLinkKey): Promise<ChannelAccountLink | null>;
|
|
78
|
+
/** Remove a platform sender's link. Returns whether a row was deleted. */
|
|
79
|
+
deleteAccountLink({ platform, externalTeamId, externalUserId }: ChannelAccountLinkKey): Promise<boolean>;
|
|
80
|
+
/**
|
|
81
|
+
* All platform identities linked to a tenant user, for the "Connected
|
|
82
|
+
* accounts" settings surface. Keyed by the tenant `userId` alone — a link
|
|
83
|
+
* belongs to the person, and their personal/org context at link time does
|
|
84
|
+
* not change who may see or sever it.
|
|
85
|
+
*/
|
|
86
|
+
listAccountLinksForUser(userId: string): Promise<ChannelAccountLinkEntry[]>;
|
|
87
|
+
/**
|
|
88
|
+
* Remove one of the tenant user's own links, addressed by its sender key.
|
|
89
|
+
* The `userId` guard makes the delete self-service only: a caller can never
|
|
90
|
+
* sever another tenant's link even with a known sender key.
|
|
91
|
+
*/
|
|
92
|
+
deleteAccountLinkForUser({ userId, platform, externalTeamId, externalUserId, }: ChannelAccountLinkKey & {
|
|
93
|
+
userId: string;
|
|
94
|
+
}): Promise<boolean>;
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=base.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/channel-identity/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAqB,MAAM,sBAAsB,CAAC;AAEhF;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,WAAW,kBAAkB;IACjC,yDAAyD;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,QAAQ,EAAE,IAAI,CAAC;CAChB;AAED,0DAA0D;AAC1D,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,eAAO,MAAM,4BAA4B,EAAE,gBAoB1C,CAAC;AAwBF,4EAA4E;AAC5E,MAAM,WAAW,uBAAwB,SAAQ,kBAAkB,EAAE,qBAAqB,EAAE,uBAAuB;CAAG;AAatH,qBAAa,sBAAuB,SAAQ,oBAAoB;;;IAKxD,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAIrB,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC;IAQ1C;;;;OAIG;IACG,eAAe,CAAC,EACpB,QAAQ,EACR,cAAc,EACd,cAAc,EACd,KAAK,EACL,MAAM,EACN,gBAAgB,EAChB,gBAAgB,GACjB,EAAE,qBAAqB,GACtB,uBAAuB,GAAG;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAkB5F;;;;;;;OAOG;IACG,iBAAiB,CAAC,EACtB,QAAQ,EACR,cAAc,EACd,cAAc,EACd,MAAM,EACN,gBAAgB,GACjB,EAAE,qBAAqB,GAAG;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC;IAcjG,gFAAgF;IAC1E,cAAc,CAAC,EACnB,QAAQ,EACR,cAAc,EACd,cAAc,GACf,EAAE,qBAAqB,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAS7D,0EAA0E;IACpE,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAc,EAAE,cAAc,EAAE,EAAE,qBAAqB,GAAG,OAAO,CAAC,OAAO,CAAC;IAS9G;;;;;OAKG;IACG,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,uBAAuB,EAAE,CAAC;IAKjF;;;;OAIG;IACG,wBAAwB,CAAC,EAC7B,MAAM,EACN,QAAQ,EACR,cAAc,EACd,cAAc,GACf,EAAE,qBAAqB,GAAG;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC;CASjE"}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { FactoryStorageDomain } from "@mastra/core/storage";
|
|
2
|
+
//#region src/storage/domains/channel-identity/base.ts
|
|
3
|
+
const CHANNEL_ACCOUNT_LINKS_SCHEMA = {
|
|
4
|
+
name: "channel_account_links",
|
|
5
|
+
columns: {
|
|
6
|
+
id: { type: "uuid-pk" },
|
|
7
|
+
platform: { type: "text" },
|
|
8
|
+
external_team_id: { type: "text" },
|
|
9
|
+
external_user_id: { type: "text" },
|
|
10
|
+
org_id: {
|
|
11
|
+
type: "text",
|
|
12
|
+
nullable: true
|
|
13
|
+
},
|
|
14
|
+
user_id: { type: "text" },
|
|
15
|
+
external_team_name: {
|
|
16
|
+
type: "text",
|
|
17
|
+
nullable: true
|
|
18
|
+
},
|
|
19
|
+
external_user_name: {
|
|
20
|
+
type: "text",
|
|
21
|
+
nullable: true
|
|
22
|
+
},
|
|
23
|
+
default_factory_project_id: {
|
|
24
|
+
type: "text",
|
|
25
|
+
nullable: true
|
|
26
|
+
},
|
|
27
|
+
linked_at: { type: "timestamp" }
|
|
28
|
+
},
|
|
29
|
+
uniqueIndexes: [{
|
|
30
|
+
name: "channel_account_links_sender_key",
|
|
31
|
+
columns: [
|
|
32
|
+
"platform",
|
|
33
|
+
"external_team_id",
|
|
34
|
+
"external_user_id"
|
|
35
|
+
]
|
|
36
|
+
}]
|
|
37
|
+
};
|
|
38
|
+
function toLink(row) {
|
|
39
|
+
return {
|
|
40
|
+
...row.org_id ? { orgId: row.org_id } : {},
|
|
41
|
+
userId: row.user_id,
|
|
42
|
+
...row.default_factory_project_id ? { defaultFactoryProjectId: row.default_factory_project_id } : {},
|
|
43
|
+
linkedAt: row.linked_at
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function toEntry(row) {
|
|
47
|
+
return {
|
|
48
|
+
...toLink(row),
|
|
49
|
+
platform: row.platform,
|
|
50
|
+
externalTeamId: row.external_team_id,
|
|
51
|
+
externalUserId: row.external_user_id,
|
|
52
|
+
...row.external_team_name ? { externalTeamName: row.external_team_name } : {},
|
|
53
|
+
...row.external_user_name ? { externalUserName: row.external_user_name } : {}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
var ChannelIdentityStorage = class extends FactoryStorageDomain {
|
|
57
|
+
constructor() {
|
|
58
|
+
super("channel-identity");
|
|
59
|
+
}
|
|
60
|
+
async init() {
|
|
61
|
+
await this.ensureCollections([CHANNEL_ACCOUNT_LINKS_SCHEMA]);
|
|
62
|
+
}
|
|
63
|
+
async dangerouslyClearAll() {
|
|
64
|
+
await this.ops.deleteMany("channel_account_links", {});
|
|
65
|
+
}
|
|
66
|
+
get #db() {
|
|
67
|
+
return this.ops;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Bind a platform sender identity to a Mastra tenant. Last-write-wins: a
|
|
71
|
+
* re-link (e.g. the same Slack user connecting a different tenant) replaces
|
|
72
|
+
* the stored tenant and refreshes `linkedAt`.
|
|
73
|
+
*/
|
|
74
|
+
async saveAccountLink({ platform, externalTeamId, externalUserId, orgId, userId, externalTeamName, externalUserName }) {
|
|
75
|
+
return toLink(await this.#db.upsertOne("channel_account_links", [
|
|
76
|
+
"platform",
|
|
77
|
+
"external_team_id",
|
|
78
|
+
"external_user_id"
|
|
79
|
+
], {
|
|
80
|
+
platform,
|
|
81
|
+
external_team_id: externalTeamId,
|
|
82
|
+
external_user_id: externalUserId,
|
|
83
|
+
org_id: orgId ?? null,
|
|
84
|
+
user_id: userId,
|
|
85
|
+
external_team_name: externalTeamName ?? null,
|
|
86
|
+
external_user_name: externalUserName ?? null,
|
|
87
|
+
linked_at: /* @__PURE__ */ new Date()
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Set (or clear, with `null`) which Factory project a link's channel runs
|
|
92
|
+
* route to. The `userId` guard makes this self-service only — a caller can
|
|
93
|
+
* never repoint another tenant's link. Returns whether a row was updated.
|
|
94
|
+
*
|
|
95
|
+
* Note: `saveAccountLink` deliberately omits this column from its upsert
|
|
96
|
+
* row, so a re-link keeps the stored default.
|
|
97
|
+
*/
|
|
98
|
+
async setDefaultFactory({ platform, externalTeamId, externalUserId, userId, factoryProjectId }) {
|
|
99
|
+
return await this.#db.updateMany("channel_account_links", {
|
|
100
|
+
user_id: userId,
|
|
101
|
+
platform,
|
|
102
|
+
external_team_id: externalTeamId,
|
|
103
|
+
external_user_id: externalUserId
|
|
104
|
+
}, { default_factory_project_id: factoryProjectId }) > 0;
|
|
105
|
+
}
|
|
106
|
+
/** Resolve the tenant a platform sender is linked to, or `null` if unlinked. */
|
|
107
|
+
async getAccountLink({ platform, externalTeamId, externalUserId }) {
|
|
108
|
+
const row = await this.#db.findOne("channel_account_links", {
|
|
109
|
+
platform,
|
|
110
|
+
external_team_id: externalTeamId,
|
|
111
|
+
external_user_id: externalUserId
|
|
112
|
+
});
|
|
113
|
+
return row ? toLink(row) : null;
|
|
114
|
+
}
|
|
115
|
+
/** Remove a platform sender's link. Returns whether a row was deleted. */
|
|
116
|
+
async deleteAccountLink({ platform, externalTeamId, externalUserId }) {
|
|
117
|
+
return await this.#db.deleteMany("channel_account_links", {
|
|
118
|
+
platform,
|
|
119
|
+
external_team_id: externalTeamId,
|
|
120
|
+
external_user_id: externalUserId
|
|
121
|
+
}) > 0;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* All platform identities linked to a tenant user, for the "Connected
|
|
125
|
+
* accounts" settings surface. Keyed by the tenant `userId` alone — a link
|
|
126
|
+
* belongs to the person, and their personal/org context at link time does
|
|
127
|
+
* not change who may see or sever it.
|
|
128
|
+
*/
|
|
129
|
+
async listAccountLinksForUser(userId) {
|
|
130
|
+
return (await this.#db.findMany("channel_account_links", { user_id: userId })).map(toEntry);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Remove one of the tenant user's own links, addressed by its sender key.
|
|
134
|
+
* The `userId` guard makes the delete self-service only: a caller can never
|
|
135
|
+
* sever another tenant's link even with a known sender key.
|
|
136
|
+
*/
|
|
137
|
+
async deleteAccountLinkForUser({ userId, platform, externalTeamId, externalUserId }) {
|
|
138
|
+
return await this.#db.deleteMany("channel_account_links", {
|
|
139
|
+
user_id: userId,
|
|
140
|
+
platform,
|
|
141
|
+
external_team_id: externalTeamId,
|
|
142
|
+
external_user_id: externalUserId
|
|
143
|
+
}) > 0;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
//#endregion
|
|
147
|
+
export { CHANNEL_ACCOUNT_LINKS_SCHEMA, ChannelIdentityStorage };
|
|
148
|
+
|
|
149
|
+
//# sourceMappingURL=base.js.map
|