@mastra/factory 0.30.0 → 0.31.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -10
- package/dist/factory.d.ts +12 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +72 -31
- package/dist/factory.js.map +1 -1
- package/dist/integrations/gitlab/api.d.ts +3 -2
- package/dist/integrations/gitlab/api.d.ts.map +1 -1
- package/dist/integrations/gitlab/api.js +12 -9
- package/dist/integrations/gitlab/api.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.d.ts +5 -0
- package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/issue-reconcile-worker.js +17 -1
- package/dist/integrations/issue-reconcile-worker.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts +22 -13
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +63 -64
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/foundation/connect-binding.d.ts +125 -0
- package/dist/integrations/platform/foundation/connect-binding.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-binding.js +252 -0
- package/dist/integrations/platform/foundation/connect-binding.js.map +1 -0
- package/dist/integrations/platform/foundation/connect-event-poller.d.ts +49 -0
- package/dist/integrations/platform/foundation/connect-event-poller.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-event-poller.js +304 -0
- package/dist/integrations/platform/foundation/connect-event-poller.js.map +1 -0
- package/dist/integrations/platform/foundation/connect-events.d.ts +31 -0
- package/dist/integrations/platform/foundation/connect-events.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-events.js +7 -0
- package/dist/integrations/platform/foundation/connect-events.js.map +1 -0
- package/dist/integrations/platform/foundation/index.d.ts +10 -0
- package/dist/integrations/platform/foundation/index.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/index.js +6 -0
- package/dist/integrations/platform/foundation/intake.d.ts +39 -0
- package/dist/integrations/platform/foundation/intake.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/intake.js +45 -0
- package/dist/integrations/platform/foundation/intake.js.map +1 -0
- package/dist/integrations/platform/foundation/integration.d.ts +84 -0
- package/dist/integrations/platform/foundation/integration.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/integration.js +107 -0
- package/dist/integrations/platform/foundation/integration.js.map +1 -0
- package/dist/integrations/platform/github/event-worker.d.ts +2 -2
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +4 -8
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +3 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +131 -70
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/gitlab/connect-events.d.ts +22 -0
- package/dist/integrations/platform/gitlab/connect-events.d.ts.map +1 -0
- package/dist/integrations/platform/gitlab/connect-events.js +49 -0
- package/dist/integrations/platform/gitlab/connect-events.js.map +1 -0
- package/dist/integrations/platform/gitlab/integration.d.ts +24 -15
- package/dist/integrations/platform/gitlab/integration.d.ts.map +1 -1
- package/dist/integrations/platform/gitlab/integration.js +61 -26
- package/dist/integrations/platform/gitlab/integration.js.map +1 -1
- package/dist/integrations/platform/incidentio/intake.d.ts +33 -0
- package/dist/integrations/platform/incidentio/intake.d.ts.map +1 -0
- package/dist/integrations/platform/incidentio/intake.js +271 -0
- package/dist/integrations/platform/incidentio/intake.js.map +1 -0
- package/dist/integrations/platform/incidentio/integration.d.ts +11 -23
- package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/platform/incidentio/integration.js +27 -297
- package/dist/integrations/platform/incidentio/integration.js.map +1 -1
- package/dist/integrations/platform/jira/intake.d.ts +60 -0
- package/dist/integrations/platform/jira/intake.d.ts.map +1 -0
- package/dist/integrations/platform/jira/intake.js +445 -0
- package/dist/integrations/platform/jira/intake.js.map +1 -0
- package/dist/integrations/platform/jira/integration.d.ts +13 -37
- package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
- package/dist/integrations/platform/jira/integration.js +29 -468
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +5 -9
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts +3 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +9 -9
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/platform/logging.d.ts +6 -0
- package/dist/integrations/platform/logging.d.ts.map +1 -0
- package/dist/integrations/platform/logging.js +25 -0
- package/dist/integrations/platform/logging.js.map +1 -0
- package/dist/integrations/platform/platform-connect.d.ts +38 -0
- package/dist/integrations/platform/platform-connect.d.ts.map +1 -0
- package/dist/integrations/platform/platform-connect.js +109 -0
- package/dist/integrations/platform/platform-connect.js.map +1 -0
- package/dist/integrations/platform/vanta/integration.d.ts +12 -18
- package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
- package/dist/integrations/platform/vanta/integration.js +38 -38
- package/dist/integrations/platform/vanta/integration.js.map +1 -1
- package/dist/memory-embedder.d.ts +11 -0
- package/dist/memory-embedder.d.ts.map +1 -0
- package/dist/memory-embedder.js +19 -0
- package/dist/memory-embedder.js.map +1 -0
- package/dist/metrics/config.d.ts +1 -1
- package/dist/metrics/config.d.ts.map +1 -1
- package/dist/metrics/config.js +1 -0
- package/dist/metrics/config.js.map +1 -1
- package/dist/metrics/index.js +2 -2
- package/dist/metrics/index.js.map +1 -1
- package/dist/metrics/sandbox.d.ts +3 -3
- package/dist/metrics/sandbox.js +13 -13
- package/dist/metrics/sandbox.js.map +1 -1
- package/dist/metrics/session.d.ts +28 -0
- package/dist/metrics/session.d.ts.map +1 -0
- package/dist/metrics/session.js +76 -0
- package/dist/metrics/session.js.map +1 -0
- package/dist/routes/source-control-sessions.d.ts +5 -0
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +65 -7
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +5 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +1 -0
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts +29 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +156 -23
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/public-failure-reason.js +1 -1
- package/dist/rules/public-failure-reason.js.map +1 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +33 -9
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +2 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +4 -2
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/work-item-branch.d.ts +7 -1
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +9 -1
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/card-facts.d.ts.map +1 -1
- package/dist/work-items/card-facts.js +2 -2
- package/dist/work-items/card-facts.js.map +1 -1
- package/package.json +9 -9
- package/dist/integrations/platform/api-client.d.ts +0 -34
- package/dist/integrations/platform/api-client.d.ts.map +0 -1
- package/dist/integrations/platform/api-client.js +0 -186
- package/dist/integrations/platform/api-client.js.map +0 -1
- package/dist/integrations/platform/gitlab/event-worker.d.ts +0 -64
- package/dist/integrations/platform/gitlab/event-worker.d.ts.map +0 -1
- package/dist/integrations/platform/gitlab/event-worker.js +0 -304
- package/dist/integrations/platform/gitlab/event-worker.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory, and list the\n * Platform project connections whose Mastra Connect tools sessions get.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\n */\n\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\nimport { connectToolExclusion, offersSessionTools } from './session-tools.js';\n\ntype RouteContext = Context;\n\nexport interface PlatformConnectProvider {\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n}\n\n/**\n * Providers the Factory SPA may connect through these routes. Keys are the\n * SPA-facing provider slugs; `integrationId` is the Platform catalog id used\n * for new connect sessions. Provider-specific PRs extend this registry when\n * their Factory integrations are available.\n */\nexport const PLATFORM_CONNECT_PROVIDERS: Record<string, PlatformConnectProvider> = {\n jira: { integrationId: 'jira', connectionIntegrationIds: ['jira'] },\n 'incident-io': { integrationId: 'incident-io', connectionIntegrationIds: ['incident-io'] },\n gitlab: { integrationId: 'gitlab', connectionIntegrationIds: ['gitlab'] },\n vanta: { integrationId: 'vanta', connectionIntegrationIds: ['vanta'] },\n};\n\ninterface PlatformConnectionRow {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n displayName?: string | null;\n connectedAt?: string;\n}\n\ninterface PlatformSessionResponse {\n connectionId: string;\n integrationId: string;\n connectUrl: string;\n sessionToken: string;\n expiresAt: string;\n}\n\ninterface ProjectConnectionRow {\n id: string;\n integrationId: string;\n status: string;\n accountLabel?: string | null;\n}\n\ninterface CatalogEntry {\n id: string;\n displayName?: string | null;\n logoUrl?: string | null;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\n}\n\nexport interface ConnectToolsSource {\n client: PlatformApiClient;\n projectId: string;\n /**\n * `default`: sessions get Factory's own Connect tools for this project.\n * `custom`: the Factory's `tools` option sets session tools, and may or may\n * not include these connections.\n */\n toolsSource: 'default' | 'custom';\n /**\n * Resolves the tools a session started by this request would get from\n * `toolsSource`: the project's Connect tools before Factory's filters for\n * `default`, or what the `tools` option returns for `custom`. Rejects when\n * they can't be resolved.\n */\n resolveTools: (args: { requestContext: RequestContext }) => Promise<Record<string, unknown>>;\n}\n\n/** One tool as Settings › Tools lists it. */\nexport interface ListedConnectTool {\n name: string;\n description: string | null;\n /** The tool pauses the run until someone approves each call. */\n requiresApproval: boolean;\n /** Factory leaves this default Connect tool out of sessions: its name says it deletes or archives. */\n excluded?: 'destructive';\n}\n\n/** The one piece of setup the Factory lacks to list its project's connections. */\nexport type ConnectToolsSetupMissing = 'no_credentials' | 'no_project_id';\n\nconst MISSING_SETUP_MESSAGES: Record<ConnectToolsSetupMissing, string> = {\n no_credentials:\n 'This Factory has no Mastra Platform credentials. Set MASTRA_PLATFORM_SECRET_KEY or MASTRA_PLATFORM_ACCESS_TOKEN.',\n no_project_id: 'This Factory has Mastra Platform credentials but no MASTRA_PROJECT_ID.',\n};\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(c: RouteContext): PlatformConnectProvider | null {\n const provider = c.req.param('provider');\n return provider ? (PLATFORM_CONNECT_PROVIDERS[provider] ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n if (err instanceof PlatformApiError) {\n if (err.status === 409) {\n return c.json({ error: 'session_pending', message: err.message }, 409);\n }\n if (err.status === 403) {\n return c.json({ error: 'platform_forbidden', message: err.message }, 403);\n }\n }\n return c.json({ error: 'platform_request_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Lists the Platform project's connections for Settings › Tools whenever the\n * Factory has Platform credentials and `MASTRA_PROJECT_ID`, whatever its\n * `tools` option. `toolsSource` tells the panel whether sessions get these\n * connections by default or only through the Factory's own `tools` code.\n */\nexport function buildConnectToolsRoute(\n auth: RouteAuth,\n source: ConnectToolsSource | { missing: ConnectToolsSetupMissing },\n): ApiRoute {\n return registerApiRoute('/web/integrations/platform/connect-tools', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n if (auth.enabled()) {\n await auth.ensureUser(c);\n if (!auth.tenant(c)) return c.json({ error: 'unauthorized' }, 401);\n }\n if ('missing' in source) {\n // `connect_tools_off` stays the code so settings pages from older CLIs still read it.\n return c.json(\n { error: 'connect_tools_off', reason: source.missing, message: MISSING_SETUP_MESSAGES[source.missing] },\n 404,\n );\n }\n const { client, projectId, toolsSource } = source;\n try {\n const [listed, catalog] = await Promise.all([\n client.request<{ connections: ProjectConnectionRow[] }>(\n 'GET',\n `/v2/projects/${encodeURIComponent(projectId)}/connections`,\n ),\n client.request<{ integrations: CatalogEntry[] }>('GET', '/v2/integrations').catch((error: unknown) => {\n console.warn(\n `MastraFactory: listing connections without provider names; the Platform catalog failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n return { integrations: [] };\n }),\n ]);\n const entries = new Map(catalog.integrations.map(entry => [entry.id, entry]));\n const connections = listed.connections\n .filter(connection => offersSessionTools(connection.integrationId))\n .map(connection => {\n const entry = entries.get(connection.integrationId);\n return {\n id: connection.id,\n integrationId: connection.integrationId,\n providerName: entry?.displayName ?? connection.integrationId,\n logoUrl: entry?.logoUrl ?? null,\n accountLabel: connection.accountLabel ?? null,\n status: connection.status,\n };\n })\n .sort((a, b) => a.providerName.localeCompare(b.providerName));\n return c.json({ projectId, toolsSource, connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n });\n}\n\nfunction listedTool(name: string, tool: unknown, toolsSource: ConnectToolsSource['toolsSource']): ListedConnectTool[] {\n // Factory filters only its default Connect tools; a `tools` option reaches sessions as written.\n const exclusion = toolsSource === 'default' ? connectToolExclusion(name) : undefined;\n // GitHub and GitLab connections aren't listed, so neither are their tools.\n if (exclusion === 'source_control') return [];\n const { description, requireApproval } = (tool ?? {}) as { description?: unknown; requireApproval?: unknown };\n return [\n {\n name,\n description: typeof description === 'string' && description.trim() ? description.trim() : null,\n requiresApproval: requireApproval === true,\n ...(exclusion ? { excluded: exclusion } : {}),\n },\n ];\n}\n\n/**\n * Lists the tools sessions get from the Connect tools source, as the signed-in\n * caller's session would resolve them, for the tool lists in Settings › Tools.\n */\nexport function buildConnectToolListRoute(\n auth: RouteAuth,\n source: ConnectToolsSource | { missing: ConnectToolsSetupMissing },\n): ApiRoute {\n return registerApiRoute('/web/integrations/platform/connect-tools/tools', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n if (auth.enabled()) {\n await auth.ensureUser(c);\n if (!auth.tenant(c)) return c.json({ error: 'unauthorized' }, 401);\n }\n if ('missing' in source) {\n return c.json(\n { error: 'connect_tools_off', reason: source.missing, message: MISSING_SETUP_MESSAGES[source.missing] },\n 404,\n );\n }\n const { toolsSource, resolveTools } = source;\n const requestContext = (c.get('requestContext' as never) as RequestContext | undefined) ?? new RequestContext();\n try {\n const resolved = await resolveTools({ requestContext });\n const tools = Object.entries(resolved)\n .flatMap(([name, tool]) => listedTool(name, tool, toolsSource))\n .sort((a, b) => a.name.localeCompare(b.name));\n return c.json({ toolsSource, tools });\n } catch (err) {\n return c.json(\n {\n error: 'tools_unavailable',\n message: `Couldn't resolve the tools: ${err instanceof Error ? err.message : String(err)}`,\n },\n 502,\n );\n }\n },\n });\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes. Callers only mount these\n * when Platform machine credentials are configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth, client } = options;\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const result = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connections = result.connections.filter(connection =>\n provider.connectionIntegrationIds.includes(connection.integrationId),\n );\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/integrations/${encodeURIComponent(provider.integrationId)}/connect-sessions`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection belongs to this provider before minting so\n // one provider's page cannot reconnect a different provider's\n // connection through this route family.\n const listed = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connection = listed.connections.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/connections/${encodeURIComponent(connectionId)}/reconnect-session`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,6BAAsE;CACjF,MAAM;EAAE,eAAe;EAAQ,0BAA0B,CAAC,MAAM;CAAE;CAClE,eAAe;EAAE,eAAe;EAAe,0BAA0B,CAAC,aAAa;CAAE;CACzF,QAAQ;EAAE,eAAe;EAAU,0BAA0B,CAAC,QAAQ;CAAE;CACxE,OAAO;EAAE,eAAe;EAAS,0BAA0B,CAAC,OAAO;CAAE;AACvE;AAoEA,MAAM,yBAAmE;CACvE,gBACE;CACF,eAAe;AACjB;AAEA,eAAe,iBACb,GACA,MACiF;CACjF,IAAI,CAAC,KAAK,QAAQ,GAChB,OAAO,EAAE,UAAU,EAAE,KAAK;EAAE,OAAO;EAAiB,SAAS;CAA+B,GAAG,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U,OAAO,SAAS;IAC5C,MAAM,eAAe,EAAE,IAAI,MAAM,cAAc;IAC/C,IAAI,CAAC,cAAc,OAAO,EAAE,KAAK,EAAE,OAAO,sBAAsB,GAAG,GAAG;IACtE,IAAI;KASF,IAAI,EAJe,MADE,OAAO,QAAkD,OAAO,iBAAiB,EAAA,CAC5E,YAAY,MACpC,cACE,UAAU,OAAO,gBAAgB,SAAS,yBAAyB,SAAS,UAAU,aAAa,CAEzF,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,uBAAuB,GAAG,GAAG;KACrE,MAAM,UAAU,MAAM,OAAO,QAC3B,QACA,mBAAmB,mBAAmB,YAAY,EAAE,qBACpD,CAAC,CACH;KACA,EAAE,OAAO,iBAAiB,UAAU;KACpC,OAAO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory, and list the\n * Platform project connections whose Mastra Connect tools sessions get.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\n */\n\nimport type { ConnectClient } from '@mastra/connect';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\n\nimport type { Context } from 'hono';\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { PlatformConnectBinding } from '../foundation/connect-binding.js';\nimport { platformErrorMessage, platformErrorStatus } from '../platform-connect.js';\nimport { connectToolExclusion, offersSessionTools } from './session-tools.js';\n\ntype RouteContext = Context;\n\n/**\n * One provider the Factory SPA may connect through these routes. Platform\n * integrations register their own providers, so the route family only serves\n * providers whose integration is installed.\n */\nexport interface PlatformConnectProviderRegistration {\n /** SPA-facing provider slug, the `:provider` path segment. */\n provider: string;\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n /** The owning integration's Connect plumbing. */\n binding: PlatformConnectBinding;\n}\n\n/** An integration that registers providers with the platform connect routes. */\nexport interface PlatformConnectProviderSource {\n platformConnectProviders(): PlatformConnectProviderRegistration[];\n}\n\nexport function isPlatformConnectProviderSource(value: unknown): value is PlatformConnectProviderSource {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Partial<PlatformConnectProviderSource>).platformConnectProviders === 'function'\n );\n}\n\ninterface ProjectConnectionRow {\n id: string;\n integrationId: string;\n status: string;\n accountLabel?: string | null;\n}\n\ninterface CatalogEntry {\n id: string;\n displayName?: string | null;\n logoUrl?: string | null;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n providers: readonly PlatformConnectProviderRegistration[];\n}\n\nexport interface ConnectToolsSource {\n client: ConnectClient;\n projectId: string;\n /**\n * `default`: sessions get Factory's own Connect tools for this project.\n * `custom`: the Factory's `tools` option sets session tools, and may or may\n * not include these connections.\n */\n toolsSource: 'default' | 'custom';\n /**\n * Resolves the tools a session started by this request would get from\n * `toolsSource`: the project's Connect tools before Factory's filters for\n * `default`, or what the `tools` option returns for `custom`. Rejects when\n * they can't be resolved.\n */\n resolveTools: (args: { requestContext: RequestContext }) => Promise<Record<string, unknown>>;\n}\n\n/** One tool as Settings › Tools lists it. */\nexport interface ListedConnectTool {\n name: string;\n description: string | null;\n /** The tool pauses the run until someone approves each call. */\n requiresApproval: boolean;\n /** Factory leaves this default Connect tool out of sessions: its name says it deletes or archives. */\n excluded?: 'destructive';\n}\n\n/** The one piece of setup the Factory lacks to list its project's connections. */\nexport type ConnectToolsSetupMissing = 'no_credentials' | 'no_project_id';\n\nconst MISSING_SETUP_MESSAGES: Record<ConnectToolsSetupMissing, string> = {\n no_credentials:\n 'This Factory has no Mastra Platform credentials. Set MASTRA_PLATFORM_SECRET_KEY or MASTRA_PLATFORM_ACCESS_TOKEN.',\n no_project_id: 'This Factory has Mastra Platform credentials but no MASTRA_PROJECT_ID.',\n};\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(\n c: RouteContext,\n providers: ReadonlyMap<string, PlatformConnectProviderRegistration>,\n): PlatformConnectProviderRegistration | null {\n const provider = c.req.param('provider');\n return provider ? (providers.get(provider) ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n const status = platformErrorStatus(err);\n if (status === 409) {\n return c.json({ error: 'session_pending', message: platformErrorMessage(err) }, 409);\n }\n if (status === 403) {\n return c.json({ error: 'platform_forbidden', message: platformErrorMessage(err) }, 403);\n }\n return c.json({ error: 'platform_request_failed', message: platformErrorMessage(err) }, 502);\n}\n\n/**\n * Lists the Platform project's connections for Settings › Tools whenever the\n * Factory has Platform credentials and `MASTRA_PROJECT_ID`, whatever its\n * `tools` option. `toolsSource` tells the panel whether sessions get these\n * connections by default or only through the Factory's own `tools` code.\n */\nexport function buildConnectToolsRoute(\n auth: RouteAuth,\n source: ConnectToolsSource | { missing: ConnectToolsSetupMissing },\n): ApiRoute {\n return registerApiRoute('/web/integrations/platform/connect-tools', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n if (auth.enabled()) {\n await auth.ensureUser(c);\n if (!auth.tenant(c)) return c.json({ error: 'unauthorized' }, 401);\n }\n if ('missing' in source) {\n // `connect_tools_off` stays the code so settings pages from older CLIs still read it.\n return c.json(\n { error: 'connect_tools_off', reason: source.missing, message: MISSING_SETUP_MESSAGES[source.missing] },\n 404,\n );\n }\n const { client, projectId, toolsSource } = source;\n try {\n const [listed, catalog] = await Promise.all([\n client.request<{ connections: ProjectConnectionRow[] }>(\n 'GET',\n `/v2/projects/${encodeURIComponent(projectId)}/connections`,\n ),\n client.request<{ integrations: CatalogEntry[] }>('GET', '/v2/integrations').catch((error: unknown) => {\n console.warn(\n `MastraFactory: listing connections without provider names; the Platform catalog failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n return { integrations: [] };\n }),\n ]);\n const entries = new Map(catalog.integrations.map(entry => [entry.id, entry]));\n const connections = listed.connections\n .filter(connection => offersSessionTools(connection.integrationId))\n .map(connection => {\n const entry = entries.get(connection.integrationId);\n return {\n id: connection.id,\n integrationId: connection.integrationId,\n providerName: entry?.displayName ?? connection.integrationId,\n logoUrl: entry?.logoUrl ?? null,\n accountLabel: connection.accountLabel ?? null,\n status: connection.status,\n };\n })\n .sort((a, b) => a.providerName.localeCompare(b.providerName));\n return c.json({ projectId, toolsSource, connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n });\n}\n\nfunction listedTool(name: string, tool: unknown, toolsSource: ConnectToolsSource['toolsSource']): ListedConnectTool[] {\n // Factory filters only its default Connect tools; a `tools` option reaches sessions as written.\n const exclusion = toolsSource === 'default' ? connectToolExclusion(name) : undefined;\n // GitHub and GitLab connections aren't listed, so neither are their tools.\n if (exclusion === 'source_control') return [];\n const { description, requireApproval } = (tool ?? {}) as { description?: unknown; requireApproval?: unknown };\n return [\n {\n name,\n description: typeof description === 'string' && description.trim() ? description.trim() : null,\n requiresApproval: requireApproval === true,\n ...(exclusion ? { excluded: exclusion } : {}),\n },\n ];\n}\n\n/**\n * Lists the tools sessions get from the Connect tools source, as the signed-in\n * caller's session would resolve them, for the tool lists in Settings › Tools.\n */\nexport function buildConnectToolListRoute(\n auth: RouteAuth,\n source: ConnectToolsSource | { missing: ConnectToolsSetupMissing },\n): ApiRoute {\n return registerApiRoute('/web/integrations/platform/connect-tools/tools', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n if (auth.enabled()) {\n await auth.ensureUser(c);\n if (!auth.tenant(c)) return c.json({ error: 'unauthorized' }, 401);\n }\n if ('missing' in source) {\n return c.json(\n { error: 'connect_tools_off', reason: source.missing, message: MISSING_SETUP_MESSAGES[source.missing] },\n 404,\n );\n }\n const { toolsSource, resolveTools } = source;\n const requestContext = (c.get('requestContext' as never) as RequestContext | undefined) ?? new RequestContext();\n try {\n const resolved = await resolveTools({ requestContext });\n const tools = Object.entries(resolved)\n .flatMap(([name, tool]) => listedTool(name, tool, toolsSource))\n .sort((a, b) => a.name.localeCompare(b.name));\n return c.json({ toolsSource, tools });\n } catch (err) {\n return c.json(\n {\n error: 'tools_unavailable',\n message: `Couldn't resolve the tools: ${err instanceof Error ? err.message : String(err)}`,\n },\n 502,\n );\n }\n },\n });\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes for the registered\n * providers. Callers only mount these when Platform machine credentials are\n * configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth } = options;\n const providers = new Map(options.providers.map(registration => [registration.provider, registration]));\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c, providers);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const listed = await provider.binding.listConnections({ fresh: true });\n const connections = listed\n .filter(connection => provider.connectionIntegrationIds.includes(connection.integrationId))\n .map(connection => ({\n id: connection.id,\n integrationId: connection.integrationId,\n status: connection.status,\n accountLabel: connection.accountLabel,\n ...(connection.connectedAt ? { connectedAt: connection.connectedAt } : {}),\n }));\n const needsLinking = provider.binding.needsLinking;\n return c.json({ connections, ...(needsLinking.length > 0 ? { needsLinking } : {}) });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c, providers);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n // Through the project route, so the new connection is born linked\n // to the Factory project and its events are published to it.\n const session = await provider.binding.connect.createConnectSession(provider.integrationId);\n provider.binding.invalidateConnections();\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c, providers);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection is this project's and belongs to this\n // provider before minting, so one provider's page cannot reconnect\n // another provider's (or another project's) connection.\n const listed = await provider.binding.listConnections({ fresh: true });\n const connection = listed.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await provider.binding.connect.createReconnectSession(connectionId);\n provider.binding.invalidateConnections();\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/link-connections', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c, providers);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n if (!(await auth.isOrganizationAdmin(c, resolved.tenant.orgId))) {\n return c.json(\n {\n error: 'organization_admin_required',\n message: 'Organization administrator access is required to link connections.',\n },\n 403,\n );\n }\n try {\n const result = await provider.binding.linkOrgConnections();\n return c.json(result);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n ];\n}\n"],"mappings":";;;;;;AAkDA,SAAgB,gCAAgC,OAAwD;CACtG,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAiD,6BAA6B;AAE1F;AAmDA,MAAM,yBAAmE;CACvE,gBACE;CACF,eAAe;AACjB;AAEA,eAAe,iBACb,GACA,MACiF;CACjF,IAAI,CAAC,KAAK,QAAQ,GAChB,OAAO,EAAE,UAAU,EAAE,KAAK;EAAE,OAAO;EAAiB,SAAS;CAA+B,GAAG,GAAG,EAAE;CAEtG,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;AAEA,SAAS,kBACP,GACA,WAC4C;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ra/connect';
|
|
2
|
+
import type { PlatformConnectOption } from '../platform-connect.js';
|
|
3
|
+
/** A provider connection linked to the Factory's platform project. */
|
|
4
|
+
export interface PlatformConnection {
|
|
5
|
+
id: string;
|
|
6
|
+
integrationId: string;
|
|
7
|
+
status: 'active' | 'needs_reauth';
|
|
8
|
+
accountLabel: string | null;
|
|
9
|
+
/** End-user resource the connection is scoped to; null for a global connection. */
|
|
10
|
+
resourceId: string | null;
|
|
11
|
+
connectedAt: string | null;
|
|
12
|
+
}
|
|
13
|
+
/** An org connection the Factory could not link to its project, and why. */
|
|
14
|
+
export interface NeedsLinkingEntry {
|
|
15
|
+
connectionId: string;
|
|
16
|
+
reason: string;
|
|
17
|
+
}
|
|
18
|
+
export interface LinkOrgConnectionsResult {
|
|
19
|
+
/** Connections that were not in the project listing and are now linked. */
|
|
20
|
+
linked: string[];
|
|
21
|
+
needsLinking: NeedsLinkingEntry[];
|
|
22
|
+
}
|
|
23
|
+
export interface PlatformConnectBindingOptions {
|
|
24
|
+
/** The owning integration's id, for logs. */
|
|
25
|
+
integrationId: string;
|
|
26
|
+
/** Connect integration ids (provider keys) the integration owns. */
|
|
27
|
+
providerKeys: readonly string[];
|
|
28
|
+
connect?: PlatformConnectOption;
|
|
29
|
+
/** Link the org's global connections for `providerKeys` to the project before the first read. */
|
|
30
|
+
linkOrgConnectionsAtBoot?: boolean;
|
|
31
|
+
/** Narrows the provider's connections further, e.g. to one configured connection id. */
|
|
32
|
+
filter?: (connection: PlatformConnection) => boolean;
|
|
33
|
+
/** How long a connection listing is reused. Defaults to 30 seconds. */
|
|
34
|
+
cacheTtlMs?: number;
|
|
35
|
+
now?: () => number;
|
|
36
|
+
}
|
|
37
|
+
export declare const DEFAULT_CONNECTION_CACHE_TTL_MS = 30000;
|
|
38
|
+
/**
|
|
39
|
+
* Thrown by {@link PlatformConnectBinding.proxy} when the platform reports
|
|
40
|
+
* the connection needs to be reconnected. `status` is 401 so callers that map
|
|
41
|
+
* HTTP-ish errors treat it as "not connected".
|
|
42
|
+
*/
|
|
43
|
+
export declare class PlatformConnectionNotConnectedError extends Error {
|
|
44
|
+
readonly status = 401;
|
|
45
|
+
readonly connectionId: string;
|
|
46
|
+
constructor(connectionId: string, options?: {
|
|
47
|
+
cause?: unknown;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/** Whether an error is the platform (not the provider) saying the connection needs reauthentication. */
|
|
51
|
+
export declare function isPlatformNeedsReauth(error: unknown): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* The Connect plumbing a Platform integration needs: project-scoped
|
|
54
|
+
* connection listing, the connection proxy, and linking the org's existing
|
|
55
|
+
* connections to the Factory project. `PlatformConnectIntegration` wraps it;
|
|
56
|
+
* integrations with another base class (GitLab) compose it directly.
|
|
57
|
+
*/
|
|
58
|
+
export declare class PlatformConnectBinding {
|
|
59
|
+
#private;
|
|
60
|
+
readonly connect: ConnectClient;
|
|
61
|
+
readonly integrationId: string;
|
|
62
|
+
readonly providerKeys: readonly string[];
|
|
63
|
+
readonly linkOrgConnectionsAtBoot: boolean;
|
|
64
|
+
constructor(options: PlatformConnectBindingOptions);
|
|
65
|
+
/**
|
|
66
|
+
* The project's `active` and `needs_reauth` connections for the provider
|
|
67
|
+
* keys, from the project listing. Reused for 30 seconds; `fresh` skips the
|
|
68
|
+
* cache. Once boot linking has started, reads wait for it to settle, so
|
|
69
|
+
* they never see the listing from before the org's connections were
|
|
70
|
+
* linked.
|
|
71
|
+
*/
|
|
72
|
+
listConnections(options?: {
|
|
73
|
+
fresh?: boolean;
|
|
74
|
+
}): Promise<PlatformConnection[]>;
|
|
75
|
+
/** Active connections, sorted by id so aggregate page cursors stay valid across requests. */
|
|
76
|
+
activeConnections(): Promise<PlatformConnection[]>;
|
|
77
|
+
/** The first active connection for a provider key that matches `predicate`. */
|
|
78
|
+
connectionFor(providerKey: string, predicate?: (connection: PlatformConnection) => boolean): Promise<PlatformConnection | null>;
|
|
79
|
+
/** Drops the cached listing; the next read goes to the platform. */
|
|
80
|
+
invalidateConnections(): void;
|
|
81
|
+
/**
|
|
82
|
+
* Calls the provider through the connection proxy. A platform report that
|
|
83
|
+
* the connection needs reauthentication becomes
|
|
84
|
+
* {@link PlatformConnectionNotConnectedError}; a provider's own 409 stays a
|
|
85
|
+
* provider error.
|
|
86
|
+
*/
|
|
87
|
+
proxy(connectionId: string, request: ProxyRequestOptions): Promise<unknown>;
|
|
88
|
+
/**
|
|
89
|
+
* The proxy URL prefix for a connection, for provider clients that speak
|
|
90
|
+
* HTTP themselves and reach the platform through {@link proxyFetch}.
|
|
91
|
+
*/
|
|
92
|
+
proxyBaseUrl(connectionId: string): string;
|
|
93
|
+
/**
|
|
94
|
+
* A `fetch` for provider clients that speak HTTP themselves, sent through
|
|
95
|
+
* the connection proxy. Provider responses pass through unchanged. A
|
|
96
|
+
* platform-sourced 401 or 409 invalidates the connection cache, and the
|
|
97
|
+
* platform's `connection_needs_reauth` throws
|
|
98
|
+
* {@link PlatformConnectionNotConnectedError}, as {@link proxy} does.
|
|
99
|
+
*/
|
|
100
|
+
proxyFetch(): typeof globalThis.fetch;
|
|
101
|
+
/** Org connections the Factory could not link to its project. */
|
|
102
|
+
get needsLinking(): NeedsLinkingEntry[];
|
|
103
|
+
/** Runs `listener` whenever linking adds a connection to the project. */
|
|
104
|
+
onConnectionsLinked(listener: () => void): () => void;
|
|
105
|
+
/**
|
|
106
|
+
* Starts boot linking once and resolves when it settles, whether it linked
|
|
107
|
+
* everything or not. Failures are logged and kept in `needsLinking`.
|
|
108
|
+
*/
|
|
109
|
+
ensureBootLinked(): Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* Links the org's global connections for the provider keys that are not
|
|
112
|
+
* yet linked to the Factory project. The platform answers 204 whether a
|
|
113
|
+
* link was created or already existed, so the project listing is compared
|
|
114
|
+
* before and after.
|
|
115
|
+
*/
|
|
116
|
+
linkOrgConnections(): Promise<LinkOrgConnectionsResult>;
|
|
117
|
+
/**
|
|
118
|
+
* Org connections for these provider keys missing from `projectConnections`:
|
|
119
|
+
* links that were refused or failed, and connections made outside the
|
|
120
|
+
* Factory since it last linked. Pass the listing the caller acts on, so a
|
|
121
|
+
* connection linked in between can't hide from both.
|
|
122
|
+
*/
|
|
123
|
+
unlinkedOrgConnections(projectConnections: readonly PlatformConnection[]): Promise<string[]>;
|
|
124
|
+
}
|
|
125
|
+
//# sourceMappingURL=connect-binding.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-binding.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/foundation/connect-binding.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAqB,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAS7F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAEpE,sEAAsE;AACtE,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,QAAQ,GAAG,cAAc,CAAC;IAClC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,mFAAmF;IACnF,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,4EAA4E;AAC5E,MAAM,WAAW,iBAAiB;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,wBAAwB;IACvC,2EAA2E;IAC3E,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,YAAY,EAAE,iBAAiB,EAAE,CAAC;CACnC;AAED,MAAM,WAAW,6BAA6B;IAC5C,6CAA6C;IAC7C,aAAa,EAAE,MAAM,CAAC;IACtB,oEAAoE;IACpE,YAAY,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC,OAAO,CAAC,EAAE,qBAAqB,CAAC;IAChC,iGAAiG;IACjG,wBAAw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,IAAI,CAG5B;IAED;;;;;OAKG;IACG,KAAK,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,OAAO,CAAC,CAMhF;IAED;;;OAGG;IACH,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAEzC;IAED;;;;;;OAMG;IACH,UAAU,IAAI,OAAO,UAAU,CAAC,KAAK,CAkBpC;IAED,iEAAiE;IACjE,IAAI,YAAY,IAAI,iBAAiB,EAAE,CAEtC;IAED,yEAAyE;IACzE,mBAAmB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAGpD;IAED;;;OAGG;IACH,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CAoBhC;IAED;;;;;OAKG;IACG,kBAAkB,IAAI,OAAO,CAAC,wBAAwB,CAAC,CA0C5D;IAED;;;;;OAKG;IACG,sBAAsB,CAAC,kBAAkB,EAAE,SAAS,kBAAkB,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAKjG;CAkCF"}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { logPlatformInfo, logPlatformWarn } from "../logging.js";
|
|
2
|
+
import { connectProxyFetch, createPlatformConnectClient, platformErrorMessage, platformErrorStatus } from "../platform-connect.js";
|
|
3
|
+
import { MastraConnectError } from "@mastra/connect";
|
|
4
|
+
// src/integrations/platform/foundation/connect-binding.ts
|
|
5
|
+
const DEFAULT_CONNECTION_CACHE_TTL_MS = 3e4;
|
|
6
|
+
/**
|
|
7
|
+
* Thrown by {@link PlatformConnectBinding.proxy} when the platform reports
|
|
8
|
+
* the connection needs to be reconnected. `status` is 401 so callers that map
|
|
9
|
+
* HTTP-ish errors treat it as "not connected".
|
|
10
|
+
*/
|
|
11
|
+
var PlatformConnectionNotConnectedError = class extends Error {
|
|
12
|
+
status = 401;
|
|
13
|
+
connectionId;
|
|
14
|
+
constructor(connectionId, options) {
|
|
15
|
+
super(`Connection ${connectionId} needs to be reconnected in Mastra Platform.`, options);
|
|
16
|
+
this.name = "PlatformConnectionNotConnectedError";
|
|
17
|
+
this.connectionId = connectionId;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
/** Whether an error is the platform (not the provider) saying the connection needs reauthentication. */
|
|
21
|
+
function isPlatformNeedsReauth(error) {
|
|
22
|
+
return error instanceof MastraConnectError && error.source === "platform" && error.problemCode === "connection_needs_reauth";
|
|
23
|
+
}
|
|
24
|
+
const PERMISSION_REMEDY = "The Factory's platform credential cannot link this connection to the project. Grant it the integrations:write permission, or link the connection to the project in Mastra Platform.";
|
|
25
|
+
const NOT_LISTED_AFTER_LINK = "The platform accepted the link, but the connection is not in the Factory project yet. Retry linking, or link it in the platform.";
|
|
26
|
+
/**
|
|
27
|
+
* The Connect plumbing a Platform integration needs: project-scoped
|
|
28
|
+
* connection listing, the connection proxy, and linking the org's existing
|
|
29
|
+
* connections to the Factory project. `PlatformConnectIntegration` wraps it;
|
|
30
|
+
* integrations with another base class (GitLab) compose it directly.
|
|
31
|
+
*/
|
|
32
|
+
var PlatformConnectBinding = class {
|
|
33
|
+
connect;
|
|
34
|
+
integrationId;
|
|
35
|
+
providerKeys;
|
|
36
|
+
linkOrgConnectionsAtBoot;
|
|
37
|
+
#filter;
|
|
38
|
+
#cacheTtlMs;
|
|
39
|
+
#now;
|
|
40
|
+
#linkedListeners = /* @__PURE__ */ new Set();
|
|
41
|
+
#cache;
|
|
42
|
+
#generation = 0;
|
|
43
|
+
#bootLinking;
|
|
44
|
+
#needsLinking = /* @__PURE__ */ new Map();
|
|
45
|
+
constructor(options) {
|
|
46
|
+
this.integrationId = options.integrationId;
|
|
47
|
+
this.providerKeys = [...options.providerKeys];
|
|
48
|
+
this.connect = createPlatformConnectClient(options.connect);
|
|
49
|
+
this.linkOrgConnectionsAtBoot = options.linkOrgConnectionsAtBoot ?? false;
|
|
50
|
+
this.#filter = options.filter;
|
|
51
|
+
this.#cacheTtlMs = options.cacheTtlMs ?? 3e4;
|
|
52
|
+
this.#now = options.now ?? Date.now;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The project's `active` and `needs_reauth` connections for the provider
|
|
56
|
+
* keys, from the project listing. Reused for 30 seconds; `fresh` skips the
|
|
57
|
+
* cache. Once boot linking has started, reads wait for it to settle, so
|
|
58
|
+
* they never see the listing from before the org's connections were
|
|
59
|
+
* linked.
|
|
60
|
+
*/
|
|
61
|
+
async listConnections(options = {}) {
|
|
62
|
+
if (this.#bootLinking) await this.#bootLinking;
|
|
63
|
+
const cached = this.#cache;
|
|
64
|
+
if (!options.fresh && cached && this.#now() - cached.at < this.#cacheTtlMs) return cached.connections;
|
|
65
|
+
const generation = this.#generation;
|
|
66
|
+
const connections = this.#readProjectConnections();
|
|
67
|
+
this.#cache = {
|
|
68
|
+
at: this.#now(),
|
|
69
|
+
connections
|
|
70
|
+
};
|
|
71
|
+
connections.catch(() => {
|
|
72
|
+
if (this.#cache?.connections === connections && this.#generation === generation) this.#cache = void 0;
|
|
73
|
+
});
|
|
74
|
+
return connections;
|
|
75
|
+
}
|
|
76
|
+
/** Active connections, sorted by id so aggregate page cursors stay valid across requests. */
|
|
77
|
+
async activeConnections() {
|
|
78
|
+
return (await this.listConnections()).filter((connection) => connection.status === "active").sort((left, right) => left.id.localeCompare(right.id));
|
|
79
|
+
}
|
|
80
|
+
/** The first active connection for a provider key that matches `predicate`. */
|
|
81
|
+
async connectionFor(providerKey, predicate) {
|
|
82
|
+
return (await this.activeConnections()).find((connection) => connection.integrationId === providerKey && (!predicate || predicate(connection))) ?? null;
|
|
83
|
+
}
|
|
84
|
+
/** Drops the cached listing; the next read goes to the platform. */
|
|
85
|
+
invalidateConnections() {
|
|
86
|
+
this.#generation++;
|
|
87
|
+
this.#cache = void 0;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Calls the provider through the connection proxy. A platform report that
|
|
91
|
+
* the connection needs reauthentication becomes
|
|
92
|
+
* {@link PlatformConnectionNotConnectedError}; a provider's own 409 stays a
|
|
93
|
+
* provider error.
|
|
94
|
+
*/
|
|
95
|
+
async proxy(connectionId, request) {
|
|
96
|
+
try {
|
|
97
|
+
return await this.connect.proxy(connectionId, request);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
throw this.#mapPlatformError(connectionId, error);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The proxy URL prefix for a connection, for provider clients that speak
|
|
104
|
+
* HTTP themselves and reach the platform through {@link proxyFetch}.
|
|
105
|
+
*/
|
|
106
|
+
proxyBaseUrl(connectionId) {
|
|
107
|
+
return `${this.connect.baseUrl}/v2/connections/${encodeURIComponent(connectionId)}/proxy`;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A `fetch` for provider clients that speak HTTP themselves, sent through
|
|
111
|
+
* the connection proxy. Provider responses pass through unchanged. A
|
|
112
|
+
* platform-sourced 401 or 409 invalidates the connection cache, and the
|
|
113
|
+
* platform's `connection_needs_reauth` throws
|
|
114
|
+
* {@link PlatformConnectionNotConnectedError}, as {@link proxy} does.
|
|
115
|
+
*/
|
|
116
|
+
proxyFetch() {
|
|
117
|
+
const send = connectProxyFetch(this.connect);
|
|
118
|
+
return async (input, init) => {
|
|
119
|
+
const response = await send(input, init);
|
|
120
|
+
if (response.ok || !(response.headers.get("content-type") ?? "").includes("application/problem+json")) return response;
|
|
121
|
+
if (response.status === 401 || response.status === 409) this.invalidateConnections();
|
|
122
|
+
if (await response.clone().json().then((body) => body && typeof body === "object" ? body.type : void 0).catch(() => void 0) !== "connection_needs_reauth") return response;
|
|
123
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
124
|
+
const connectionId = /\/v2\/connections\/([^/]+)\/proxy(?:\/|$)/.exec(new URL(url).pathname)?.[1];
|
|
125
|
+
throw new PlatformConnectionNotConnectedError(connectionId ? decodeURIComponent(connectionId) : "unknown");
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/** Org connections the Factory could not link to its project. */
|
|
129
|
+
get needsLinking() {
|
|
130
|
+
return [...this.#needsLinking.values()];
|
|
131
|
+
}
|
|
132
|
+
/** Runs `listener` whenever linking adds a connection to the project. */
|
|
133
|
+
onConnectionsLinked(listener) {
|
|
134
|
+
this.#linkedListeners.add(listener);
|
|
135
|
+
return () => this.#linkedListeners.delete(listener);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Starts boot linking once and resolves when it settles, whether it linked
|
|
139
|
+
* everything or not. Failures are logged and kept in `needsLinking`.
|
|
140
|
+
*/
|
|
141
|
+
ensureBootLinked() {
|
|
142
|
+
if (!this.linkOrgConnectionsAtBoot) return Promise.resolve();
|
|
143
|
+
this.#bootLinking ??= this.linkOrgConnections().then((result) => {
|
|
144
|
+
if (result.linked.length > 0 || result.needsLinking.length > 0) logPlatformInfo("Linked org connections to the Factory project", {
|
|
145
|
+
integrationId: this.integrationId,
|
|
146
|
+
linked: result.linked.length,
|
|
147
|
+
needsLinking: result.needsLinking.length
|
|
148
|
+
});
|
|
149
|
+
}, (error) => {
|
|
150
|
+
logPlatformWarn("Could not link org connections to the Factory project", {
|
|
151
|
+
integrationId: this.integrationId,
|
|
152
|
+
error: platformErrorMessage(error)
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
return this.#bootLinking;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Links the org's global connections for the provider keys that are not
|
|
159
|
+
* yet linked to the Factory project. The platform answers 204 whether a
|
|
160
|
+
* link was created or already existed, so the project listing is compared
|
|
161
|
+
* before and after.
|
|
162
|
+
*/
|
|
163
|
+
async linkOrgConnections() {
|
|
164
|
+
const candidates = await this.#orgCandidates();
|
|
165
|
+
const linkedBefore = new Set((await this.connect.listConnections()).map((connection) => connection.id));
|
|
166
|
+
const attempted = [];
|
|
167
|
+
for (const connection of candidates) {
|
|
168
|
+
if (linkedBefore.has(connection.id)) {
|
|
169
|
+
this.#needsLinking.delete(connection.id);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
await this.connect.linkConnection(connection.id);
|
|
174
|
+
attempted.push(connection.id);
|
|
175
|
+
} catch (error) {
|
|
176
|
+
const status = platformErrorStatus(error);
|
|
177
|
+
const reason = status === 401 || status === 403 ? PERMISSION_REMEDY : platformErrorMessage(error);
|
|
178
|
+
this.#needsLinking.set(connection.id, {
|
|
179
|
+
connectionId: connection.id,
|
|
180
|
+
reason
|
|
181
|
+
});
|
|
182
|
+
logPlatformWarn("Could not link an org connection to the Factory project", {
|
|
183
|
+
integrationId: this.integrationId,
|
|
184
|
+
connectionId: connection.id,
|
|
185
|
+
...status === void 0 ? {} : { status },
|
|
186
|
+
error: platformErrorMessage(error)
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const linked = [];
|
|
191
|
+
if (attempted.length > 0) {
|
|
192
|
+
const linkedAfter = new Set((await this.connect.listConnections()).map((connection) => connection.id));
|
|
193
|
+
for (const connectionId of attempted) if (linkedAfter.has(connectionId)) {
|
|
194
|
+
this.#needsLinking.delete(connectionId);
|
|
195
|
+
linked.push(connectionId);
|
|
196
|
+
} else this.#needsLinking.set(connectionId, {
|
|
197
|
+
connectionId,
|
|
198
|
+
reason: NOT_LISTED_AFTER_LINK
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
if (linked.length > 0) {
|
|
202
|
+
this.invalidateConnections();
|
|
203
|
+
for (const listener of this.#linkedListeners) listener();
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
linked,
|
|
207
|
+
needsLinking: this.needsLinking
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Org connections for these provider keys missing from `projectConnections`:
|
|
212
|
+
* links that were refused or failed, and connections made outside the
|
|
213
|
+
* Factory since it last linked. Pass the listing the caller acts on, so a
|
|
214
|
+
* connection linked in between can't hide from both.
|
|
215
|
+
*/
|
|
216
|
+
async unlinkedOrgConnections(projectConnections) {
|
|
217
|
+
const linked = new Set(projectConnections.map((connection) => connection.id));
|
|
218
|
+
return (await this.#orgCandidates()).filter((connection) => !linked.has(connection.id)).map((connection) => connection.id);
|
|
219
|
+
}
|
|
220
|
+
async #orgCandidates() {
|
|
221
|
+
const keys = new Set(this.providerKeys);
|
|
222
|
+
return (await this.connect.request("GET", "/v2/connections")).connections.filter((connection) => keys.has(connection.integrationId) && !connection.resourceId && (connection.status === "active" || connection.status === "needs_reauth") && this.#accepts(toPlatformConnection(connection)));
|
|
223
|
+
}
|
|
224
|
+
async #readProjectConnections() {
|
|
225
|
+
return (await this.connect.listConnections({ providerKeys: this.providerKeys })).flatMap((connection) => {
|
|
226
|
+
if (connection.status !== "active" && connection.status !== "needs_reauth") return [];
|
|
227
|
+
const mapped = toPlatformConnection(connection);
|
|
228
|
+
return this.#accepts(mapped) ? [mapped] : [];
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
#accepts(connection) {
|
|
232
|
+
return !this.#filter || this.#filter(connection);
|
|
233
|
+
}
|
|
234
|
+
#mapPlatformError(connectionId, error) {
|
|
235
|
+
if (!(error instanceof MastraConnectError) || error.source !== "platform") return error;
|
|
236
|
+
if (error.status === 401 || error.status === 409) this.invalidateConnections();
|
|
237
|
+
return isPlatformNeedsReauth(error) ? new PlatformConnectionNotConnectedError(connectionId, { cause: error }) : error;
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
function toPlatformConnection(connection) {
|
|
241
|
+
return {
|
|
242
|
+
id: connection.id,
|
|
243
|
+
integrationId: connection.integrationId,
|
|
244
|
+
status: connection.status,
|
|
245
|
+
accountLabel: connection.accountLabel ?? null,
|
|
246
|
+
resourceId: connection.resourceId ?? null,
|
|
247
|
+
connectedAt: connection.connectedAt ?? null
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
export { DEFAULT_CONNECTION_CACHE_TTL_MS, PlatformConnectBinding, PlatformConnectionNotConnectedError, isPlatformNeedsReauth };
|
|
251
|
+
|
|
252
|
+
//# sourceMappingURL=connect-binding.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-binding.js","names":[],"sources":["../../../../src/integrations/platform/foundation/connect-binding.ts"],"sourcesContent":["import { MastraConnectError } from '@mastra/connect';\nimport type { ConnectClient, ProjectConnection, ProxyRequestOptions } from '@mastra/connect';\n\nimport { logPlatformInfo, logPlatformWarn } from '../logging.js';\nimport {\n connectProxyFetch,\n createPlatformConnectClient,\n platformErrorMessage,\n platformErrorStatus,\n} from '../platform-connect.js';\nimport type { PlatformConnectOption } from '../platform-connect.js';\n\n/** A provider connection linked to the Factory's platform project. */\nexport interface PlatformConnection {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n /** End-user resource the connection is scoped to; null for a global connection. */\n resourceId: string | null;\n connectedAt: string | null;\n}\n\n/** An org connection the Factory could not link to its project, and why. */\nexport interface NeedsLinkingEntry {\n connectionId: string;\n reason: string;\n}\n\nexport interface LinkOrgConnectionsResult {\n /** Connections that were not in the project listing and are now linked. */\n linked: string[];\n needsLinking: NeedsLinkingEntry[];\n}\n\nexport interface PlatformConnectBindingOptions {\n /** The owning integration's id, for logs. */\n integrationId: string;\n /** Connect integration ids (provider keys) the integration owns. */\n providerKeys: readonly string[];\n connect?: PlatformConnectOption;\n /** Link the org's global connections for `providerKeys` to the project before the first read. */\n linkOrgConnectionsAtBoot?: boolean;\n /** Narrows the provider's connections further, e.g. to one configured connection id. */\n filter?: (connection: PlatformConnection) => boolean;\n /** How long a connection listing is reused. Defaults to 30 seconds. */\n cacheTtlMs?: number;\n now?: () => number;\n}\n\nexport const DEFAULT_CONNECTION_CACHE_TTL_MS = 30_000;\n\n/**\n * Thrown by {@link PlatformConnectBinding.proxy} when the platform reports\n * the connection needs to be reconnected. `status` is 401 so callers that map\n * HTTP-ish errors treat it as \"not connected\".\n */\nexport class PlatformConnectionNotConnectedError extends Error {\n readonly status = 401;\n readonly connectionId: string;\n\n constructor(connectionId: string, options?: { cause?: unknown }) {\n super(`Connection ${connectionId} needs to be reconnected in Mastra Platform.`, options);\n this.name = 'PlatformConnectionNotConnectedError';\n this.connectionId = connectionId;\n }\n}\n\n/** Whether an error is the platform (not the provider) saying the connection needs reauthentication. */\nexport function isPlatformNeedsReauth(error: unknown): boolean {\n return (\n error instanceof MastraConnectError &&\n error.source === 'platform' &&\n error.problemCode === 'connection_needs_reauth'\n );\n}\n\nconst PERMISSION_REMEDY =\n \"The Factory's platform credential cannot link this connection to the project. Grant it the integrations:write permission, or link the connection to the project in Mastra Platform.\";\nconst NOT_LISTED_AFTER_LINK =\n 'The platform accepted the link, but the connection is not in the Factory project yet. Retry linking, or link it in the platform.';\n\n/**\n * The Connect plumbing a Platform integration needs: project-scoped\n * connection listing, the connection proxy, and linking the org's existing\n * connections to the Factory project. `PlatformConnectIntegration` wraps it;\n * integrations with another base class (GitLab) compose it directly.\n */\nexport class PlatformConnectBinding {\n readonly connect: ConnectClient;\n readonly integrationId: string;\n readonly providerKeys: readonly string[];\n readonly linkOrgConnectionsAtBoot: boolean;\n\n readonly #filter: ((connection: PlatformConnection) => boolean) | undefined;\n readonly #cacheTtlMs: number;\n readonly #now: () => number;\n readonly #linkedListeners = new Set<() => void>();\n\n #cache: { at: number; connections: Promise<PlatformConnection[]> } | undefined;\n #generation = 0;\n #bootLinking: Promise<void> | undefined;\n #needsLinking = new Map<string, NeedsLinkingEntry>();\n\n constructor(options: PlatformConnectBindingOptions) {\n this.integrationId = options.integrationId;\n this.providerKeys = [...options.providerKeys];\n this.connect = createPlatformConnectClient(options.connect);\n this.linkOrgConnectionsAtBoot = options.linkOrgConnectionsAtBoot ?? false;\n this.#filter = options.filter;\n this.#cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CONNECTION_CACHE_TTL_MS;\n this.#now = options.now ?? Date.now;\n }\n\n /**\n * The project's `active` and `needs_reauth` connections for the provider\n * keys, from the project listing. Reused for 30 seconds; `fresh` skips the\n * cache. Once boot linking has started, reads wait for it to settle, so\n * they never see the listing from before the org's connections were\n * linked.\n */\n async listConnections(options: { fresh?: boolean } = {}): Promise<PlatformConnection[]> {\n if (this.#bootLinking) await this.#bootLinking;\n const cached = this.#cache;\n if (!options.fresh && cached && this.#now() - cached.at < this.#cacheTtlMs) return cached.connections;\n const generation = this.#generation;\n const connections = this.#readProjectConnections();\n this.#cache = { at: this.#now(), connections };\n connections.catch(() => {\n // A failed read must not be served from the cache.\n if (this.#cache?.connections === connections && this.#generation === generation) this.#cache = undefined;\n });\n return connections;\n }\n\n /** Active connections, sorted by id so aggregate page cursors stay valid across requests. */\n async activeConnections(): Promise<PlatformConnection[]> {\n return (await this.listConnections())\n .filter(connection => connection.status === 'active')\n .sort((left, right) => left.id.localeCompare(right.id));\n }\n\n /** The first active connection for a provider key that matches `predicate`. */\n async connectionFor(\n providerKey: string,\n predicate?: (connection: PlatformConnection) => boolean,\n ): Promise<PlatformConnection | null> {\n return (\n (await this.activeConnections()).find(\n connection => connection.integrationId === providerKey && (!predicate || predicate(connection)),\n ) ?? null\n );\n }\n\n /** Drops the cached listing; the next read goes to the platform. */\n invalidateConnections(): void {\n this.#generation++;\n this.#cache = undefined;\n }\n\n /**\n * Calls the provider through the connection proxy. A platform report that\n * the connection needs reauthentication becomes\n * {@link PlatformConnectionNotConnectedError}; a provider's own 409 stays a\n * provider error.\n */\n async proxy(connectionId: string, request: ProxyRequestOptions): Promise<unknown> {\n try {\n return await this.connect.proxy(connectionId, request);\n } catch (error) {\n throw this.#mapPlatformError(connectionId, error);\n }\n }\n\n /**\n * The proxy URL prefix for a connection, for provider clients that speak\n * HTTP themselves and reach the platform through {@link proxyFetch}.\n */\n proxyBaseUrl(connectionId: string): string {\n return `${this.connect.baseUrl}/v2/connections/${encodeURIComponent(connectionId)}/proxy`;\n }\n\n /**\n * A `fetch` for provider clients that speak HTTP themselves, sent through\n * the connection proxy. Provider responses pass through unchanged. A\n * platform-sourced 401 or 409 invalidates the connection cache, and the\n * platform's `connection_needs_reauth` throws\n * {@link PlatformConnectionNotConnectedError}, as {@link proxy} does.\n */\n proxyFetch(): typeof globalThis.fetch {\n const send = connectProxyFetch(this.connect);\n return async (input, init) => {\n const response = await send(input, init);\n if (response.ok || !(response.headers.get('content-type') ?? '').includes('application/problem+json')) {\n return response;\n }\n if (response.status === 401 || response.status === 409) this.invalidateConnections();\n const problemType = await response\n .clone()\n .json()\n .then((body: unknown) => (body && typeof body === 'object' ? (body as { type?: unknown }).type : undefined))\n .catch(() => undefined);\n if (problemType !== 'connection_needs_reauth') return response;\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n const connectionId = /\\/v2\\/connections\\/([^/]+)\\/proxy(?:\\/|$)/.exec(new URL(url).pathname)?.[1];\n throw new PlatformConnectionNotConnectedError(connectionId ? decodeURIComponent(connectionId) : 'unknown');\n };\n }\n\n /** Org connections the Factory could not link to its project. */\n get needsLinking(): NeedsLinkingEntry[] {\n return [...this.#needsLinking.values()];\n }\n\n /** Runs `listener` whenever linking adds a connection to the project. */\n onConnectionsLinked(listener: () => void): () => void {\n this.#linkedListeners.add(listener);\n return () => this.#linkedListeners.delete(listener);\n }\n\n /**\n * Starts boot linking once and resolves when it settles, whether it linked\n * everything or not. Failures are logged and kept in `needsLinking`.\n */\n ensureBootLinked(): Promise<void> {\n if (!this.linkOrgConnectionsAtBoot) return Promise.resolve();\n this.#bootLinking ??= this.linkOrgConnections().then(\n result => {\n if (result.linked.length > 0 || result.needsLinking.length > 0) {\n logPlatformInfo('Linked org connections to the Factory project', {\n integrationId: this.integrationId,\n linked: result.linked.length,\n needsLinking: result.needsLinking.length,\n });\n }\n },\n error => {\n logPlatformWarn('Could not link org connections to the Factory project', {\n integrationId: this.integrationId,\n error: platformErrorMessage(error),\n });\n },\n );\n return this.#bootLinking;\n }\n\n /**\n * Links the org's global connections for the provider keys that are not\n * yet linked to the Factory project. The platform answers 204 whether a\n * link was created or already existed, so the project listing is compared\n * before and after.\n */\n async linkOrgConnections(): Promise<LinkOrgConnectionsResult> {\n const candidates = await this.#orgCandidates();\n const linkedBefore = new Set((await this.connect.listConnections()).map(connection => connection.id));\n const attempted: string[] = [];\n for (const connection of candidates) {\n if (linkedBefore.has(connection.id)) {\n this.#needsLinking.delete(connection.id);\n continue;\n }\n try {\n await this.connect.linkConnection(connection.id);\n attempted.push(connection.id);\n } catch (error) {\n const status = platformErrorStatus(error);\n const reason = status === 401 || status === 403 ? PERMISSION_REMEDY : platformErrorMessage(error);\n this.#needsLinking.set(connection.id, { connectionId: connection.id, reason });\n logPlatformWarn('Could not link an org connection to the Factory project', {\n integrationId: this.integrationId,\n connectionId: connection.id,\n ...(status === undefined ? {} : { status }),\n error: platformErrorMessage(error),\n });\n }\n }\n const linked: string[] = [];\n if (attempted.length > 0) {\n // A 204 doesn't prove the link: only a connection the project listing now shows counts.\n const linkedAfter = new Set((await this.connect.listConnections()).map(connection => connection.id));\n for (const connectionId of attempted) {\n if (linkedAfter.has(connectionId)) {\n this.#needsLinking.delete(connectionId);\n linked.push(connectionId);\n } else {\n this.#needsLinking.set(connectionId, { connectionId, reason: NOT_LISTED_AFTER_LINK });\n }\n }\n }\n if (linked.length > 0) {\n this.invalidateConnections();\n for (const listener of this.#linkedListeners) listener();\n }\n return { linked, needsLinking: this.needsLinking };\n }\n\n /**\n * Org connections for these provider keys missing from `projectConnections`:\n * links that were refused or failed, and connections made outside the\n * Factory since it last linked. Pass the listing the caller acts on, so a\n * connection linked in between can't hide from both.\n */\n async unlinkedOrgConnections(projectConnections: readonly PlatformConnection[]): Promise<string[]> {\n const linked = new Set(projectConnections.map(connection => connection.id));\n return (await this.#orgCandidates())\n .filter(connection => !linked.has(connection.id))\n .map(connection => connection.id);\n }\n\n async #orgCandidates(): Promise<ProjectConnection[]> {\n const keys = new Set(this.providerKeys);\n const org = await this.connect.request<{ connections: ProjectConnection[] }>('GET', '/v2/connections');\n return org.connections.filter(\n connection =>\n keys.has(connection.integrationId) &&\n !connection.resourceId &&\n (connection.status === 'active' || connection.status === 'needs_reauth') &&\n this.#accepts(toPlatformConnection(connection)),\n );\n }\n\n async #readProjectConnections(): Promise<PlatformConnection[]> {\n const connections = await this.connect.listConnections({ providerKeys: this.providerKeys });\n return connections.flatMap(connection => {\n if (connection.status !== 'active' && connection.status !== 'needs_reauth') return [];\n const mapped = toPlatformConnection(connection);\n return this.#accepts(mapped) ? [mapped] : [];\n });\n }\n\n #accepts(connection: PlatformConnection): boolean {\n return !this.#filter || this.#filter(connection);\n }\n\n #mapPlatformError(connectionId: string, error: unknown): unknown {\n if (!(error instanceof MastraConnectError) || error.source !== 'platform') return error;\n if (error.status === 401 || error.status === 409) this.invalidateConnections();\n return isPlatformNeedsReauth(error)\n ? new PlatformConnectionNotConnectedError(connectionId, { cause: error })\n : error;\n }\n}\n\nfunction toPlatformConnection(connection: ProjectConnection): PlatformConnection {\n return {\n id: connection.id,\n integrationId: connection.integrationId,\n status: connection.status as PlatformConnection['status'],\n accountLabel: connection.accountLabel ?? null,\n resourceId: connection.resourceId ?? null,\n connectedAt: connection.connectedAt ?? null,\n };\n}\n"],"mappings":";;;;AAkDA,MAAa,kCAAkC;;;;;;AAO/C,IAAa,sCAAb,cAAyD,MAAM;CAC7D,SAAkB;CAClB;CAEA,YAAY,cAAsB,SAA+B;EAC/D,MAAM,cAAc,aAAa,+CAA+C,OAAO;EACvF,KAAK,OAAO;EACZ,KAAK,eAAe;CACtB;AACF;;AAGA,SAAgB,sBAAsB,OAAyB;CAC7D,OACE,iBAAiB,sBACjB,MAAM,WAAW,cACjB,MAAM,gBAAgB;AAE1B;AAEA,MAAM,oBACJ;AACF,MAAM,wBACJ;;;;;;;AAQF,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CAEA;CACA;CACA;CACA,mCAA4B,IAAI,IAAgB;CAEhD;CACA,cAAc;CACd;CACA,gCAAgB,IAAI,IAA+B;CAEnD,YAAY,SAAwC;EAClD,KAAK,gBAAgB,QAAQ;E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,EAAE,OAAO,MAAM,CAAC,IACtE;CACN;AACF;AAEA,SAAS,qBAAqB,YAAmD;CAC/E,OAAO;EACL,IAAI,WAAW;EACf,eAAe,WAAW;EAC1B,QAAQ,WAAW;EACnB,cAAc,WAAW,gBAAgB;EACzC,YAAY,WAAW,cAAc;EACrC,aAAa,WAAW,eAAe;CACzC;AACF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { MastraWorker } from '@mastra/core/worker';
|
|
2
|
+
import type { WorkerDeps } from '@mastra/core/worker';
|
|
3
|
+
import type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';
|
|
4
|
+
import type { PlatformConnectEventRoute } from './connect-events.js';
|
|
5
|
+
/** Integration-storage id the deployment's Connect event poller keeps its cursors under. */
|
|
6
|
+
export declare const PLATFORM_CONNECT_EVENT_POLLER_STORAGE_ID = "platform-connect-event-poller";
|
|
7
|
+
type PollerSettings = {
|
|
8
|
+
version: 1;
|
|
9
|
+
connections: Record<string, {
|
|
10
|
+
afterEventId: string;
|
|
11
|
+
}>;
|
|
12
|
+
};
|
|
13
|
+
export type PlatformConnectEventPollerStorage = IntegrationStorageHandle<Record<string, unknown>, PollerSettings, Record<string, unknown>>;
|
|
14
|
+
export interface PlatformConnectEventPollerConfig {
|
|
15
|
+
storage: PlatformConnectEventPollerStorage;
|
|
16
|
+
routes: readonly PlatformConnectEventRoute[];
|
|
17
|
+
/** Defaults to the shortest `pollIntervalMs` the routes ask for, else 20 s. */
|
|
18
|
+
intervalMs?: number;
|
|
19
|
+
/** First delay between handler attempts; doubles per attempt. */
|
|
20
|
+
retryDelayMs?: number;
|
|
21
|
+
now?: () => number;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Reads each routed integration's active connections' platform event logs,
|
|
25
|
+
* through the integration's own Connect client, and
|
|
26
|
+
* hands every event to the integration's route. It is how Platform
|
|
27
|
+
* integrations receive provider webhooks until they read the events service.
|
|
28
|
+
*
|
|
29
|
+
* One replica polls at a time (lease). Each connection keeps its own cursor,
|
|
30
|
+
* saved after each handled event, so delivery is at-least-once: handlers
|
|
31
|
+
* dedupe on `dedupeKey`. A connection read for the first time starts at the
|
|
32
|
+
* present and asks its integration to reconcile once, since events from
|
|
33
|
+
* before then are not read.
|
|
34
|
+
*
|
|
35
|
+
* The event log carries no verification flag, so events reach handlers with
|
|
36
|
+
* `unverified: false`. That doesn't prove the platform checked the signature.
|
|
37
|
+
*/
|
|
38
|
+
export declare class PlatformConnectEventPoller extends MastraWorker {
|
|
39
|
+
#private;
|
|
40
|
+
readonly name = "platform-connect-event-poller";
|
|
41
|
+
constructor(config: PlatformConnectEventPollerConfig);
|
|
42
|
+
init(deps: WorkerDeps): Promise<void>;
|
|
43
|
+
start(): Promise<void>;
|
|
44
|
+
stop(): Promise<void>;
|
|
45
|
+
get isRunning(): boolean;
|
|
46
|
+
diagnostics(): Record<string, unknown>;
|
|
47
|
+
}
|
|
48
|
+
export {};
|
|
49
|
+
//# sourceMappingURL=connect-event-poller.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-event-poller.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/foundation/connect-event-poller.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAC;AAE9F,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAErE,4FAA4F;AAC5F,eAAO,MAAM,wCAAwC,kCAAkC,CAAC;AAexF,KAAK,cAAc,GAAG;IAAE,OAAO,EAAE,CAAC,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,CAAC;AAE5F,MAAM,MAAM,iCAAiC,GAA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