Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(integrations): add native Google OAuth and read-only APIs
Rahman471ddfc9cdfb
diff --git a/app/api/integrations/google/callback/route.ts b/app/api/integrations/google/callback/route.tsnew file mode 100644index 00000000..b02d9d5f--- /dev/null+++ b/app/api/integrations/google/callback/route.ts@@ -0,0 +1,22 @@+import { NextRequest, NextResponse } from "next/server";+import { completeGoogleAuthorization, googleFlowCookie } from "@/lib/infra/google-oauth-flow";+import { googlePublicOrigin } from "@/lib/infra/google-native-config";+export const runtime = "nodejs";+export const dynamic = "force-dynamic";+const headers = { "Cache-Control": "no-store, private", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff" };+export async function GET(req: NextRequest) {+ let origin: string;+ try { origin = googlePublicOrigin(); } catch { return NextResponse.json({ error: "google_public_https_origin_required" }, { status: 409, headers }); }+ if (req.headers.get("host")?.toLowerCase() !== new URL(origin).host) return NextResponse.json({ error: "invalid_google_callback" }, { status: 400, headers });+ const params = req.nextUrl.searchParams, state = params.get("state") || "";+ let success = false;+ try {+ if (!/^[A-Za-z0-9_-]{43}$/.test(state) || ["state", "code", "error", "iss"].some(k => params.getAll(k).length > 1) || (params.has("code") && params.has("error")) || (params.has("iss") && params.get("iss") !== "https://accounts.google.com")) throw new Error();+ const cookies = req.cookies.getAll(googleFlowCookie(state)); if (cookies.length !== 1) throw new Error();+ await completeGoogleAuthorization(state, cookies[0].value, params.get("code") ?? undefined, params.has("error"));+ success = true;+ } catch { /* No provider text, codes, tokens, state or callback URLs are reflected or logged. */ }+ const response = NextResponse.redirect(`${origin}/integrations?google=${success ? "authorized" : "retry"}`, { status: 303, headers });+ if (/^[A-Za-z0-9_-]{43}$/.test(state)) response.cookies.set(googleFlowCookie(state), "", { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 0 });+ return response;+}diff --git a/app/api/integrations/google/start/route.ts b/app/api/integrations/google/start/route.tsnew file mode 100644index 00000000..d5ba0bd5--- /dev/null+++ b/app/api/integrations/google/start/route.ts@@ -0,0 +1,27 @@+import { NextRequest, NextResponse } from "next/server";+import { getSessionContext } from "@/lib/auth/require-session";+import { beginGoogleAuthorization } from "@/lib/infra/google-oauth-flow";+import { googlePublicOrigin, isGoogleProvider } from "@/lib/infra/google-native-config";+import { identity, IntegrationError, metadataOnly } from "@/lib/infra/identity";+import { readSetupJson } from "@/lib/infra/setup-http";+import { audit } from "@/lib/host/audit-api";+export const runtime = "nodejs";+export const dynamic = "force-dynamic";+const headers = { "Cache-Control": "no-store, private", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff" };+export async function POST(req: NextRequest) {+ const ctx = await getSessionContext();+ if (ctx?.role !== "owner" || !ctx.session.device_id) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });+ try {+ const origin = googlePublicOrigin();+ if (req.headers.get("origin") !== origin || req.headers.get("host")?.toLowerCase() !== new URL(origin).host) throw new IntegrationError("google_same_origin_required", 403);+ const body = await readSetupJson(req); metadataOnly(body);+ if (Object.keys(body).some(k => !["user", "provider", "connection"].includes(k)) || !isGoogleProvider(String(body.provider))) throw new IntegrationError("invalid_google_request");+ const user = identity(body.user, "user"), connection = identity(body.connection, "connection"), provider = String(body.provider);+ if (!isGoogleProvider(provider)) throw new IntegrationError("invalid_google_request");+ const flow = await beginGoogleAuthorization(provider, { user, connection }, { deviceId: ctx.session.device_id, cookieScope: ctx.session.cookie_scope, cookieEpoch: ctx.session.cookie_epoch, sessionExpiresAt: ctx.session.expires_at });+ const response = NextResponse.json({ authorizationUrl: flow.authorizationUrl, expiresIn: flow.expiresIn }, { headers });+ response.cookies.set(flow.cookieName, flow.binding, { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: flow.expiresIn });+ void audit({ action: "infra.write", actor: ctx.session.device_id, target: `${user}/${provider}/${connection}`, ok: true, detail: "google.authorization.start" });+ return response;+ } catch (error) { return NextResponse.json({ error: error instanceof IntegrationError ? error.code : "google_authorization_start_failed" }, { status: error instanceof IntegrationError ? error.status : 400, headers }); }+}diff --git a/bin/mso.test.ts b/bin/mso.test.tsindex d7171282..744d531c 100644--- a/bin/mso.test.ts+++ b/bin/mso.test.ts@@ -119,6 +119,11 @@ describe("bin/mso", () => {// Credential input is delegated to a write-only browser capability; the// named CLI setup verb opens that form without placing keys in shell/tool JSON."POST /api/integrations/setup",+ // Google web OAuth needs a bound browser cookie; unlike device-code OAuth,+ // mso integrations authorize opens the native consent UI. Neither this+ // browser start nor Google's redirect callback may expose codes to a shell.+ "POST /api/integrations/google/start",+ "GET /api/integrations/google/callback","GET /api/sw","POST /api/v1/channels/telegram/[id]", // Provider callback: requires Telegram webhook signature, not a user CLI action."POST /api/v1/channels/discord/[id]", // Provider callback: requires Discord Ed25519 signature, not a user CLI action.diff --git a/claude-skills/integrations/SKILL.md b/claude-skills/integrations/SKILL.mdindex 1b993402..7edd13b7 100644--- a/claude-skills/integrations/SKILL.md+++ b/claude-skills/integrations/SKILL.md@@ -67,6 +67,16 @@ For **GitHub**, present OAuth-capable sources before the manual token fallback.Multiple deployment/account connections under one provider are first-class. Never overwrite `production` with `staging` merely because they use the same auth method.+### Native Google OAuth++Google Search Console and Google Analytics use native MSO OAuth, not a required Composio broker. Inspect the live catalog first: `google-oauth-app` stores a Web client configuration through private setup; `google-search-console` and `google-analytics` bind to that same owner's app and authorize separate accounts.++- Configure the Google app once. A saved client ID/secret is not a connected Google account.+- Service connections use `direct` / `oauth2`. Use `google.bind` for the existing app, then `connection.authorize` to obtain only a native UI entrypoint. OAuth state, code and tokens never belong in a tool response.+- The human completes top-level Google consent in native MSO. Do not invoke the browser callback from a tool or borrow saved browser cookies.+- Verify the exact connection, list actual properties, and use only operations returned by its catalog. An API key or GA measurement ID cannot substitute for Google user consent.+- Native grants cannot be shared or copied as authorization. Local disconnect does not claim Google-wide revocation.+### Transfer identitiesUse Integration Bundle v1 for deliberate portability. Plain JSON is metadata-only. Encrypted bundles may carry direct credentials through the dedicated private import/export path. OAuth sessions and externally managed connected-account secrets are not portable and require reauthorization.diff --git a/docs/INTEGRATION-PORTABILITY.md b/docs/INTEGRATION-PORTABILITY.mdindex 08bc8526..760fb434 100644--- a/docs/INTEGRATION-PORTABILITY.md+++ b/docs/INTEGRATION-PORTABILITY.md@@ -120,3 +120,14 @@ remain application-owned.References: Node.js `node:crypto` documentation and the OWASP Cryptographic StorageCheat Sheet. The protocol uses authenticated encryption and OS randomness ratherthan reversible obfuscation or an application-owned hardcoded encryption key.+++### Native Google authorization is not portable++The Google OAuth app configuration can use the existing explicit direct-field+transfer flow. A native Search Console or Analytics connection exports only its+app-binding metadata/configuration. Runtime account authorizations, pending flow+state, PKCE verifier, access tokens and refresh tokens are never exported, even+with credential export enabled. Imported/copied accounts need fresh Google+consent and actual API verification. This also applies to copies between+credential owners on the same installation.diff --git a/docs/INTEGRATIONS-NATIVE-GOOGLE.md b/docs/INTEGRATIONS-NATIVE-GOOGLE.mdnew file mode 100644index 00000000..63a3ecf1--- /dev/null+++ b/docs/INTEGRATIONS-NATIVE-GOOGLE.md@@ -0,0 +1,79 @@+# Native Google integrations++MSO owns the provider connection, consent lifecycle and bounded API dispatch. Composio is optional and is not needed by these Google providers. This is a scoped foundation, not complete Composio feature parity.++## One identity model++Credential owner → provider → named connection → source/authentication stays the existing MSO Integrations model. App configuration and a user's authorization are different records:++- `google-oauth-app` / direct / `oauth-app`: the installation's Google Web application client ID and secret, entered only through the existing private setup form. Saving validates configuration format, not account access.+- `google-search-console` / direct / `oauth2`: an explicit same-owner OAuth app binding and read-only Search Console authorization.+- `google-analytics` / direct / `oauth2`: an explicit same-owner OAuth app binding and read-only GA4 authorization.++A client ID, API key, GA measurement ID or browser login cookie does not grant private Search Console or Analytics access. Each named Google connection requires account consent. An imported/copied connection requires fresh user authorization even when app configuration is copied.++## Installation setup, then account connection++1. Set `OS_PUBLIC_ORIGIN` to the canonical HTTPS origin of this MSO installation. Never derive the OAuth redirect from an untrusted request header.+2. Select or create a Google Cloud project owned by the operator. Enable Search Console API and/or Analytics Admin API + Analytics Data API as needed.+3. Configure the Google consent screen and a **Web application** OAuth client. Register the exact redirect shown by MSO: `<OS_PUBLIC_ORIGIN>/api/integrations/google/callback`.+4. In MSO Integrations, create a Google OAuth app connection under the intended credential owner. Enter the client ID and secret through private setup. This is a once-per-app setup, not a key prompt for every end user.+5. Add a named Search Console or Google Analytics 4 connection, choose the app, then **Connect with Google → Continue to Google**. Consent runs in a top-level browser, not inside the ChatGPT embed.+6. Return to MSO, refresh, and **Verify API access**. An empty property/account list can be a valid result; it does not prove the desired property is accessible.++Google test-user restrictions, Workspace policy, consent-screen verification and API enablement remain Google's controls. MSO does not bypass them. Hosted centrally managed OAuth-app provisioning is a future distribution capability, not an implicit dependency or a claim of this release.++## Shared machine interface++The existing `integration_query` catalog includes each native Google's `operations` with strict JSON input schemas. The existing `integration_execute` resolves the exact credential owner and named connection.++Connection operations:++- `google.bind` with `{appConnection}` selects a configured app owned by the same credential owner.+- `google.operations.list` returns the connection's bounded read-operation schemas.+- `verify` tests a real Google read endpoint, rather than interpreting stored fields as authorization.+- `google.disconnect` forgets MSO's local grant. The result explicitly says it has **not** revoked the Google app itself. Review Google Account third-party connections to revoke the app across services.+- `integration_manage` / `connection.authorize` returns only a native UI entrypoint. It never exposes an authorization state, PKCE verifier, OAuth code or token to MCP.++Read operations:++| Operation | Purpose |+| --- | --- |+| `google.searchConsole.sites.list` | Accessible properties and permissions |+| `google.searchConsole.searchAnalytics.query` | Bounded Web/Image/video performance report |+| `google.searchConsole.sitemaps.list` | Existing sitemap metadata, not submission |+| `google.searchConsole.url.inspect` | Google's stored index inspection, not live crawl or indexing request |+| `google.analytics.accountSummaries.list` | Accessible accounts/properties, with pagination |+| `google.analytics.report.run` | Bounded GA4 report, not Measurement Protocol events |++Arguments use Google's camelCase field names; use the returned property identity verbatim. Follow schema bounds and pagination. Filters, custom metric syntaxes, service-account credentials, write operations, webhooks and broader Google products are not silently supported by this slice.++## Status semantics++`app-configured` is not a user connection. Service states distinguish `app-required`, `authorization-required`, `authorization-pending`, `authorized`, `verified`, `reauthorization-required`, `scope-missing`, `invalid` and `unavailable`. Failed verification never retains a stale green state. Consent alone does not verify access to a particular property. Changing a pinned OAuth app's credentials invalidates existing grants until reauthorization. Reconnect must retain the same Google account; disconnect explicitly before switching accounts.++## Security boundary++- Random state + PKCE S256, ten-minute single-use flow, hashed browser binding and a host-only Secure/HttpOnly/SameSite=Lax flow cookie. The existing main MSO session cookie remains Strict.+- Owner-only, same-origin start; callback checks the binding, exact app/connection revisions and the issuing device's current Owner role, session expiry and policy epoch. Callback failures do not echo provider messages or codes.+- Exchange and refresh use fixed official HTTPS endpoints, bounded bodies/timeouts and no redirect following. Read adapters also reject unknown arguments and arbitrary endpoints.+- Tokens remain in the existing owner-only locked/atomically written Integrations store. They are excluded from connection summaries, shared aliases, duplication, raw credential export and portable bundles.+- Network requests occur outside the file-store lock, with bounded app/connection leases and final revision checks.+- This code does not log token/code/query values. Operators must also keep reverse-proxy/access logs from retaining OAuth callback query strings. Infrastructure log policy is not proven by a unit test.+- Real Google consent/API access is a separate acceptance step requiring an authorized operator. Mock tests never constitute evidence that a production Google account is connected.++## Composio-class parity roadmap++This slice provides native catalog/configuration, explicit account consent, lifecycle status, refresh, local disconnect and shared machine/UI dispatch. It does not claim an equivalent provider inventory or every Composio feature.++Next phases: richer property selection and report UI; centralized provider-operation validation/adapter scaffolding; per-action activity/error history; optional service-account methods; triggers/webhooks and scoped write actions; managed OAuth-app distribution with documented Google verification; browser-verified setup journeys for each provider.++The user-requested **embed padding/margin** pass is deliberately separate and deferred: shared outer gutters, aligned header/form/help, narrow-width stacking, focus visibility and iframe height/scroll parity. Do not create a second design system or change auth semantics to repair spacing.++## Primary references++- https://developers.google.com/identity/protocols/oauth2/web-server+- https://developers.google.com/webmaster-tools/v1/sites/list+- https://developers.google.com/webmaster-tools/v1/searchanalytics/query+- https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/accountSummaries/list+- https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReportdiff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.mdindex a16d19b0..210448d1 100644--- a/docs/INTEGRATIONS.md+++ b/docs/INTEGRATIONS.md@@ -350,3 +350,24 @@ Telegram direct connections store the Bot API token plus an optional webhook secDiscord direct connections store the bot token and may also store the non-secret application ID and Interactions Ed25519 public key. Verification uses Discord REST bot identity. The public key is required before signed Discord Interactions can be accepted. Gateway event ingestion is intentionally not implied by a verified Discord connection.The Channels application resolves an exact credential user + named connection. If no compatible connection exists, setup remains in Integrations rather than exposing a token field inside Channels. See [CHANNELS.md](./CHANNELS.md).+++## Native Google OAuth: Search Console and GA4++MSO can own Google authorization directly; Composio is optional, not required.+Configure a same-owner `google-oauth-app` once through private setup, then bind+`google-search-console` or `google-analytics` named connections and authorize the+intended account in the native Owner browser. These private reporting APIs are+OAuth-only in this slice; an API key or GA measurement ID is not a substitute.++`mso integrations authorize <user> <provider> <connection>` opens the native+consent entrypoint without returning an OAuth code or state. Google web callback+routes are browser-bound protocol controls, unlike device-code provider flows.+The existing generic `integration_execute` exposes schema-listed read operations,+verification, app binding and local disconnect. No per-provider global MCP tool+or parallel credential store is added.++App configuration is not verified account access. Native Google user grants are+never shared, copied to another owner or exported, including encrypted/raw+credential formats. Read [Native Google integrations](./INTEGRATIONS-NATIVE-GOOGLE.md)+for setup, states, operations, security and the remaining Composio-class parity roadmap.diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 1ca1cc1d..d1d6f80c 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,24 @@+## 2026-09-25 — Native Google Integrations foundation++Native Google OAuth app configuration, Search Console and Google Analytics 4 now+use the existing Integrations identity/store and generic UI/CLI/MCP dispatch.+The consumer UI selects an OAuth app and opens Google consent instead of a+Composio project-key form. App-only configuration remains distinct from user+consent and actual API verification. Six bounded read operations cover property+listing, search analytics, sitemap metadata, stored URL inspection, GA account+summaries and GA4 reports. No Google write/event-sending action is introduced.++The callback uses single-use state, PKCE, a separate host-only browser binding,+issuing Owner-device/policy checks and app/connection revision pins. Runtime+Google grants stay out of shared/copy/export DTOs. Native user authorization and+actual property access still require an operator's real Google consent; tests+with synthetic identities do not establish a production connection.++This is not full Composio provider/trigger/UI parity. The user's global embed+padding/margin request remains a separate deferred task. Setup, exact operations,+security controls and remaining phases are documented in+[Native Google Integrations](./INTEGRATIONS-NATIVE-GOOGLE.md).+## 2026-09-24 — Add a first-class Memory graphMSO now has a Memory app (`/memory`, Launchpad and Spotlight “Memory”, CLI `mso memory-graph`) for a navigable knowledge graph. The owner-only `GET /api/v1/memory-graph` builds it from an optional markdown vault (`OS_MEMORY_GRAPH_ROOT` or a path typed in the app, jailed to `OS_FS_READ_ROOTS`), project `.mso/KNOWLEDGE.md`, bounded repo-local `.agent` memory, the signed-in device’s typed agent memory, and assistant memories. Unresolved `[[wikilinks]]` become ghost nodes; folders and projects color groups. The client offers web, radial, and layered layouts plus a local hop neighbourhood, and opens a note in Code on a second click, double-click, or Open. Layout ideas follow open-silong’s memory graph (MIT). This is not the Workflow session graph and does not require Obsidian. Production picks it up with `mso update` after the commit is on `origin/main`; a GitHub merge does not rebuild the systemd service by itself.diff --git a/docs/README.md b/docs/README.mdindex 23676839..245584fa 100644--- a/docs/README.md+++ b/docs/README.md@@ -37,6 +37,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`CLI.md`](./CLI.md) | Generated `mso` CLI contract || [`INTEGRATION-PORTABILITY.md`](./INTEGRATION-PORTABILITY.md) | Reviewed JSON identity transfers, encrypted credentials, SC interoperability and receiver limits || [`INTEGRATIONS.md`](./INTEGRATIONS.md) | Native temporary credential forms, direct HTTPS secret submission, CLI and ChatGPT Page |+| [`INTEGRATIONS-NATIVE-GOOGLE.md`](./INTEGRATIONS-NATIVE-GOOGLE.md) | Native Google OAuth app/account separation, Search Console and GA4 reads, browser binding, scope and parity limits || [`CHANNELS.md`](./CHANNELS.md) | Provider-neutral Telegram/Discord messaging, inbound verification, outbound send and Workflow bridge || [`PROJECT-MCP-CONNECTIONS.md`](./PROJECT-MCP-CONNECTIONS.md) | Named private connections, endpoint binding and identity for modular project MCPs || [`BATONLY-FEDERATION.md`](./BATONLY-FEDERATION.md) | Pull-based Batonly capability federation worker, MSO/SI-Coder execution boundary, polling, security and acceptance contract |diff --git a/lib/infra/catalog.ts b/lib/infra/catalog.tsindex 616aa93d..8fffe15e 100644--- a/lib/infra/catalog.ts+++ b/lib/infra/catalog.ts@@ -1,10 +1,13 @@+import { GOOGLE_PROVIDERS, GOOGLE_APP_PROVIDER, isGoogleProvider, normalizeGoogleConfig } from "./google-native-config";import { normalizeMcpEndpoint, parseMcpToolAllowlist } from "./mcp-policy";import { ADDITIONAL_PROVIDERS, type AdditionalProviderId } from "./additional-providers";import { INFRA_PROVIDER_IDS, type InfraProviderDefinition, type InfraProviderId, type InfraProviderValues } from "./types";const additional = Object.fromEntries(Object.entries(ADDITIONAL_PROVIDERS).map(([id, value]) => [id, { ...value, fields: value.fields.map(f => ({ ...f })) }])) as Record<AdditionalProviderId, InfraProviderDefinition>;+const google = Object.fromEntries(GOOGLE_PROVIDERS.map(p => [p.id, p])) as Record<"google-oauth-app" | "google-search-console" | "google-analytics", InfraProviderDefinition>;const definitions: Record<InfraProviderId, InfraProviderDefinition> = {...additional,+ ...google,dokploy: {id: "dokploy",title: "Dokploy",@@ -129,5 +132,6 @@ export function normalizeInfraValues(id: InfraProviderId, raw: Record<string, unif (out.mailApiToken && out.mailApiToken.length < 24) throw new Error("Hostinger Mail API token is too short");if (out.mailOrderId && !/^[A-Za-z0-9._-]{3,128}$/.test(out.mailOrderId)) throw new Error("Invalid Hostinger Mail order ID");}+ if (id === GOOGLE_APP_PROVIDER || isGoogleProvider(id)) return normalizeGoogleConfig(id, out);return out;}diff --git a/lib/infra/clients.ts b/lib/infra/clients.tsindex 4f1cb0ac..21f0d1b9 100644--- a/lib/infra/clients.ts+++ b/lib/infra/clients.ts@@ -1,3 +1,5 @@+import { isGoogleProvider, GOOGLE_APP_PROVIDER } from "./google-native-config";+import { nativeGoogleStatus } from "./google-native";import { recordConnectionCheck } from "./connection-health";import { credentialSnapshot, currentIntegrationSelection, resolveIntegration } from "./connection-service";import { verifyExternalIntegration } from "./connection-external";@@ -34,6 +36,7 @@ async function probeInfraProvider(id: InfraProviderId, candidate?: InfraProvider// Pin the credential revision before probing; never attribute an old request to new keys.export async function doctorInfraProvider(id: InfraProviderId, candidate?: InfraProviderValues): Promise<InfraDoctorResult> {+ if(isGoogleProvider(id)||id===GOOGLE_APP_PROVIDER)return candidate?{id,ok:null,detail:"Google OAuth consent and actual API verification required"}:nativeGoogleStatus(id,currentIntegrationSelection());if (candidate) return probeInfraProvider(id, candidate);const selector = currentIntegrationSelection();let snapshot;diff --git a/lib/infra/connection-dispatch.ts b/lib/infra/connection-dispatch.tsindex d95a4b61..ea8a7422 100644--- a/lib/infra/connection-dispatch.ts+++ b/lib/infra/connection-dispatch.ts@@ -1,3 +1,5 @@+import { isGoogleProvider, GOOGLE_APP_PROVIDER, googlePublicOrigin } from "./google-native-config";+import { bindGoogleApp, disconnectGoogle, runNativeGoogle, nativeGoogleStatus, googleOperations } from "./google-native";import { integrationManage } from "./connection-manage";import { integrationQuery, withIntegrationSelection, resolveIntegration } from "./connection-service";import { authorizeIntegration, composioConnectionCall } from "./connection-external";@@ -17,6 +19,12 @@ export async function manageIntegrationAction(raw:Record<string,unknown>){if(a.provider!=="convex-cloud")throw new IntegrationError("provider_operation_mismatch");return importConvexCliPersonalConnection(selectionFrom(a));}+ if(a.action==="connection.authorize"&&isGoogleProvider(String(a.provider))){+ if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);+ if(Object.keys(a).some(k=>!["action","confirm","user","provider","connection"].includes(k)))throw new IntegrationError("invalid_management_fields");+ const route=await resolveIntegration(String(a.provider),selectionFrom(a));+ return{user:route.user,provider:a.provider,connection:route.id,authorization:"owner-browser-required",openPath:googlePublicOrigin()+"/integrations?"+new URLSearchParams({provider:String(a.provider),user:route.user,connection:route.id})};+ }if(a.action!=="connection.authorize")return integrationManage(a);if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);if(Object.keys(a).some(k=>!["action","confirm","user","provider","connection","authConfigId","brokerConnection","createManaged"].includes(k)))throw new IntegrationError("invalid_management_fields");@@ -33,9 +41,17 @@ export async function executeIntegrationAction(raw:Record<string,unknown>){const user=identity(a.user,"user"),provider=identity(a.provider,"provider"),connection=identity(a.connection,"connection"),selection={user,connection};const route=await resolveIntegration(provider,selection);if(operation==="route")return route;+ if(operation==="verify"&&(isGoogleProvider(provider)||provider===GOOGLE_APP_PROVIDER))return nativeGoogleStatus(provider,selection);if(operation==="verify")return withIntegrationSelection(selection,()=>{if(!isInfraProviderId(provider))throw new IntegrationError("unknown_provider");return doctorInfraProvider(provider);});if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);const args=a.arguments??{};if(!args||typeof args!=="object"||Array.isArray(args))throw new IntegrationError("invalid_tool_arguments");+ if(isGoogleProvider(provider)){+ if(route.source!=="direct")throw new IntegrationError("google_native_connection_required",409);+ const body=args as Record<string,unknown>;+ if(operation==="google.bind"){if(Object.keys(body).some(k=>k!=="appConnection"))throw new IntegrationError("invalid_tool_arguments");return bindGoogleApp(provider,selection,body.appConnection)}+ if(operation==="google.disconnect"||operation==="google.operations.list"){if(Object.keys(body).length)throw new IntegrationError("invalid_tool_arguments");return operation==="google.disconnect"?disconnectGoogle(provider,selection):{operations:googleOperations(provider)}}+ return runNativeGoogle(provider,selection,operation,body);+ }if(operation==="composio.tool")return composioConnectionCall(provider,selection,String(a.tool),args as Record<string,unknown>);const verbs:Record<string,{provider:string;fields:string[];run:()=>Promise<unknown>}>= {"dokploy.projects.list":{provider:"dokploy",fields:[],run:()=>listDokployProjects()},diff --git a/lib/infra/connection-manage.ts b/lib/infra/connection-manage.tsindex 3cb4d92b..33d3c5b3 100644--- a/lib/infra/connection-manage.ts+++ b/lib/infra/connection-manage.ts@@ -1,3 +1,5 @@+import { clearGoogleRuntime } from "./google-native-state";+import { isGoogleProvider, GOOGLE_APP_PROVIDER } from "./google-native-config";import { variableKey, assertNoVariableReferences } from "./connection-variables";import {connectionMethod} from "./connection-registry";import { randomUUID } from "node:crypto";@@ -36,7 +38,7 @@ export async function integrationManage(input:Record<string,unknown>){const copy=structuredClone(profile);copy.id=target;// A duplicate must not retain an invisible dependency on a sharing owner.if(action==="user.duplicate")for(const rows of Object.values(copy.connections))for(const c of Object.values(rows))if(c.sharedFrom){const ref=c.sharedFrom,owner=state.users[ref.user]?.connections[ref.provider]?.[ref.connection];if(!owner)throw new IntegrationError("shared_backing_not_found",409);c.values={...owner.values};delete c.sharedFrom;}if(action==="user.duplicate")copy.uid=randomUUID();copy.label=connectionLabel(input.label??target);- for(const rows of Object.values(copy.connections))for(const c of Object.values(rows)){c.uid=randomUUID();c.revision++;c.updatedAt=Date.now();delete c.lease;if(action==="user.duplicate"&&input.copyCredentials!==true){c.values={};delete c.verifiedAt;}if(action==="user.duplicate"&&c.source!=="direct"){c.external=undefined;delete c.verifiedAt;}}+ for(const rows of Object.values(copy.connections))for(const c of Object.values(rows)){clearGoogleRuntime(c);c.uid=randomUUID();c.revision++;c.updatedAt=Date.now();delete c.lease;if(action==="user.duplicate"&&input.copyCredentials!==true){c.values={};delete c.verifiedAt;}if(action==="user.duplicate"&&c.source!=="direct"){c.external=undefined;delete c.verifiedAt;}}state.users[target]=copy;if(action==="user.rename"){for(const ref of Object.values(state.variables??{}))if(ref.user===user)ref.user=target;delete state.users[user];for(const u of Object.values(state.users))for(const rows of Object.values(u.connections))for(const c of Object.values(rows))if(c.sharedFrom?.user===user)c.sharedFrom.user=target;for(const b of state.bindings)if(b.user===user)b.user=target;if(state.defaultUser===user)state.defaultUser=target;}return{ok:true,action,user:target};@@ -53,10 +55,11 @@ export async function integrationManage(input:Record<string,unknown>){if(c.sharedFrom)throw new IntegrationError("shared_alias_copy_from_owner",409);const target=identity(input.target,"target"),targetUser=state.users[target];if(!targetUser)throw new IntegrationError("user_not_found",404);const targetConnection=identity(input.targetConnection??connection,"target_connection"),rows=targetUser.connections[provider]??{};if(Object.hasOwn(rows,targetConnection))throw new IntegrationError("connection_exists",409);- const clone=structuredClone(c);clone.id=targetConnection;clone.uid=randomUUID();clone.label=connectionLabel(input.label??c.label);clone.values=c.source==="direct"&&input.copyCredentials===true?{...c.values}:{};delete clone.sharedFrom;delete clone.external;delete clone.verifiedAt;delete clone.lastCheck;delete clone.lease;clone.revision=1;clone.createdAt=clone.updatedAt=Date.now();+ const clone=structuredClone(c);clone.id=targetConnection;clone.uid=randomUUID();clone.label=connectionLabel(input.label??c.label);clone.values=c.source==="direct"&&input.copyCredentials===true?{...c.values}:{};delete clone.sharedFrom;delete clone.external;delete clone.verifiedAt;delete clone.lastCheck;delete clone.lease;clearGoogleRuntime(clone);clone.revision=1;clone.createdAt=clone.updatedAt=Date.now();targetUser.connections[provider]={...rows,[targetConnection]:clone};if(input.makeDefault===true||!targetUser.defaults[provider])targetUser.defaults[provider]=targetConnection;return{ok:true,action,connection:summaryIn(state,target,clone)};}if(action==="connection.share"){+ if(isGoogleProvider(provider)||provider===GOOGLE_APP_PROVIDER)throw new IntegrationError("google_shared_authorization_not_supported",409);if(c.source!=="direct")throw new IntegrationError("external_connections_cannot_share",409);if(c.sharedFrom)throw new IntegrationError("shared_alias_cannot_share",409);const target=identity(input.target,"target"), targetUser=state.users[target];if(!targetUser)throw new IntegrationError("user_not_found",404);if(target===user)throw new IntegrationError("shared_alias_same_user",409);const rows=targetUser.connections[provider]??{},rawBase=String(input.label??connection).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"shared",base=rawBase.slice(0,56),id=Array.from({length:100},(_,i)=>i?`${base.slice(0,61-String(i+1).length)}-${i+1}`:base).find(x=>!Object.hasOwn(rows,x));if(!id)throw new IntegrationError("connection_alias_limit",409);identity(id,"connection");@@ -73,6 +76,7 @@ export async function integrationManage(input:Record<string,unknown>){if(action==="connection.default")profile.defaults[provider]=connection;if(action==="connection.rename"){c.label=connectionLabel(input.label);c.updatedAt=Date.now();}if(action==="connection.delete"){+ if(provider===GOOGLE_APP_PROVIDER&&Object.values(profile.connections).some(rows=>Object.values(rows).some(x=>isGoogleProvider(x.provider)&&x.values.appConnection===connection)))throw new IntegrationError("google_app_has_connections",409);if(Object.values(state.users).some(u=>Object.values(u.connections).some(rows=>Object.values(rows).some(x=>x.sharedFrom?.user===user&&x.sharedFrom.connection===connection&&x.provider===provider))))throw new IntegrationError("connection_has_shared_dependents",409);if(state.bindings.some(b=>b.user===user&&b.connections[provider]===connection))throw new IntegrationError("connection_has_folder_binding",409);if(Object.values(profile.connections).some(rows=>Object.values(rows).some(x=>x.source==="composio"&&x.external?.brokerConnection===connection&&provider==="composio")))throw new IntegrationError("broker_has_linked_connections",409);@@ -80,7 +84,7 @@ export async function integrationManage(input:Record<string,unknown>){}if(action==="credential.delete"){if(c.source!=="direct")throw new IntegrationError("external_secrets_forbidden");- if(input.key!==undefined){const key=identity(input.key,"key");if(!connectionMethod(provider,c.source,c.authMethod).fields.some(f=>f.key===key))throw new IntegrationError("unknown_credential_field");delete c.values[key];}else c.values={};c.revision++;delete c.verifiedAt;c.updatedAt=Date.now();+ if(input.key!==undefined){const key=identity(input.key,"key");if(!connectionMethod(provider,c.source,c.authMethod).fields.some(f=>f.key===key))throw new IntegrationError("unknown_credential_field");delete c.values[key];}else c.values={};clearGoogleRuntime(c);c.revision++;delete c.verifiedAt;delete c.lastCheck;c.updatedAt=Date.now();}return{ok:true,action,connection:summaryIn(state,user,c)};});diff --git a/lib/infra/connection-registry.ts b/lib/infra/connection-registry.tsindex dba5e5b3..a045ad33 100644--- a/lib/infra/connection-registry.ts+++ b/lib/infra/connection-registry.ts@@ -1,3 +1,5 @@+import { GOOGLE_READ_OPERATIONS } from "./google-api-catalog";+import { isGoogleProvider, GOOGLE_APP_PROVIDER, googleRedirectUri, googlePublicOrigin } from "./google-native-config";import { listInfraProviderDefinitions, getInfraProviderDefinition, isInfraProviderId } from "./catalog";import { setupFields, setupGuidance, setupMethods, type SetupMethod } from "./setup-guidance";import { IntegrationError, type ConnectionSource, type IntegrationConnection } from "./identity";@@ -17,7 +19,7 @@ export function providerDefinition(provider:string) {}export function connectionMethods(provider:string, source:ConnectionSource) {const p=providerDefinition(provider);- if(source==="direct") return setupMethods(p.id).map(m=>({id:m.id as string,label:provider==="github"?"Personal access token fallback":m.label,scope:provider==="convex-cloud"?(m.id==="deployment"?"deployment":"account"):provider==="composio"?m.id:provider==="dokploy"?"server":provider==="hostinger"&&m.id==="mail"?"mail-order":provider==="doku"?"merchant":"account",fields:setupFields(p.id,m.id),guidance:setupGuidance(p.id,m.id)}));+ if(source==="direct") return setupMethods(p.id).map(m=>({id:m.id as string,label:provider==="github"?"Personal access token fallback":m.label,scope:provider===GOOGLE_APP_PROVIDER?"client-configuration":isGoogleProvider(provider)?"read-only-account":provider==="convex-cloud"?(m.id==="deployment"?"deployment":"account"):provider==="composio"?m.id:provider==="dokploy"?"server":provider==="hostinger"&&m.id==="mail"?"mail-order":provider==="doku"?"merchant":"account",fields:setupFields(p.id,m.id),guidance:setupGuidance(p.id,m.id)}));if(source==="composio" && COMPOSIO[provider]) return COMPOSIO[provider].methods.map(id=>({id,label:id==="oauth2"?"OAuth2":"Hosted API key",scope:"account",fields:[],guidance:{url:"https://platform.composio.dev",reference:`https://docs.composio.dev/toolkits/${COMPOSIO[provider].toolkit}`,steps:["Configure a Composio project key under this same credential user.","Choose a matching authentication configuration for this provider and method.","Open the hosted authorization link. Enter credentials only on the provider/Composio page.","Return and refresh status. MSO stores routing identifiers, not provider OAuth tokens."]}}));if(source==="native-mcp" && NATIVE[provider])return[{id:"provider-oauth",label:"Provider-owned MCP / OAuth",scope:"account",fields:[],guidance:{url:NATIVE[provider].reference,reference:NATIVE[provider].reference,steps:["Connect the provider-owned MCP server in your client.","Complete authorization in that provider's browser flow.","Use this named MSO connection to identify the intended provider route; the authenticated MCP session remains client-owned.","MSO does not copy provider access/refresh tokens or silently fall back to a local key."]}}];throw new IntegrationError("unsupported_connection_source");@@ -36,7 +38,7 @@ function sourceLabel(provider:string,id:ConnectionSource){if(provider==="github") return id==="composio"?"Hosted OAuth (Composio)":id==="native-mcp"?"Provider OAuth / MCP":"Manual token fallback";return id==="direct"?"MSO direct":id==="composio"?"Composio":"Provider MCP";}-export function connectionCatalog(){return listInfraProviderDefinitions().map(p=>({id:p.id,title:p.title,description:p.description,sources:connectionSources(p.id).map(id=>({id,label:sourceLabel(p.id,id),methods:connectionMethods(p.id,id)}))}));}+export function connectionCatalog(){return listInfraProviderDefinitions().map(p=>({id:p.id,title:p.title,description:p.description,...googleCatalogInfo(p.id),sources:connectionSources(p.id).map(id=>({id,label:sourceLabel(p.id,id),methods:connectionMethods(p.id,id)}))}));}export function connectionSummary(user:string,c:IntegrationConnection,isDefault=false,values:Record<string,string>=c.values){const method=connectionMethod(c.provider,c.source,c.authMethod),missing=method.fields.filter(f=>f.required&&!values[f.key]).map(f=>f.key);return {user,id:c.id,label:c.label,provider:c.provider,source:c.source,authMethod:c.authMethod,scope:c.scope,revision:c.revision,isDefault,missing,fields:method.fields.map(f=>({...f,stored:Boolean(values[f.key])})),state:c.source==="direct"?(missing.length?"incomplete":c.lastCheck?(c.lastCheck.revision===c.revision?c.lastCheck.result:"configured"):c.verifiedAt?"verified":"configured"):c.external?.status??"authorization-required",verifiedAt:c.verifiedAt??null,lastCheck:c.lastCheck?.revision===c.revision?c.lastCheck:null,sharedFrom:c.sharedFrom??null,external:c.external??null};@@ -46,3 +48,9 @@ export const nativeDefinition=(provider:string)=>NATIVE[provider];export function legacyMethod(provider:string,values:Record<string,string>):SetupMethod {return provider==="composio"?(values.orgApiKey?"organization":"project"):provider==="convex-cloud"?(values.deployKey?"deployment":"personal"):provider==="doku"?(values.paymentClientId||values.paymentSecretKey?"payment":"mcp"):"direct";}++function googleCatalogInfo(provider:string){+ if(provider!==GOOGLE_APP_PROVIDER&&!isGoogleProvider(provider))return{};+ let callbackUrl:string|null=null,openPath:string|null=null;try{callbackUrl=googleRedirectUri();openPath=googlePublicOrigin()+"/integrations?provider="+provider}catch{}+ return{nativeGoogle:true,configurationOnly:provider===GOOGLE_APP_PROVIDER,callbackUrl,openPath,operations:GOOGLE_READ_OPERATIONS.filter(op=>op.provider===provider)};+}diff --git a/lib/infra/connection-service.ts b/lib/infra/connection-service.tsindex 28a921e5..925435ee 100644--- a/lib/infra/connection-service.ts+++ b/lib/infra/connection-service.ts@@ -1,3 +1,5 @@+import { googleConnectionMetadata, clearGoogleRuntime } from "./google-native-state";+import { isGoogleProvider, GOOGLE_APP_PROVIDER } from "./google-native-config";import { variableKey } from "./connection-variables";import { randomUUID } from "node:crypto";import { AsyncLocalStorage } from "node:async_hooks";@@ -15,7 +17,7 @@ export async function directConnectionValues(provider:string,selector:Connectionif(result.connection.source!=="direct")throw new IntegrationError("external_source_requires_own_executor",409);const copy={...resolveSharedConnection(state,result.user,result.connection).connection.values};if(context&&context.selector===selector)context.pinned.set(provider,copy);return copy;}-export function summaryIn(state:IntegrationState,user:string,c:IntegrationConnection){return connectionSummary(user,c,state.users[user].defaults[c.provider]===c.id,resolveSharedConnection(state,user,c).connection.values);}+export function summaryIn(state:IntegrationState,user:string,c:IntegrationConnection){return {...connectionSummary(user,c,state.users[user].defaults[c.provider]===c.id,resolveSharedConnection(state,user,c).connection.values),...googleConnectionMetadata(state,user,c)};}export async function resolveIntegration(provider:string,selector:ConnectionSelector={}){const state=await readIntegrationState(),resolved=selectConnection(state,provider,selector),c=resolved.connection;return{...summaryIn(state,resolved.user,c),resolution:resolved.reason,execution:c.source==="direct"?{route:"native-direct"}:c.source==="composio"?{route:"composio",connectedAccountId:c.external?.connectedAccountId??null,toolkit:c.external?.toolkit??null}:{route:"provider-mcp",endpoint:nativeDefinition(provider)?.url??null,authorization:"provider-client-owned"}};@@ -54,7 +56,7 @@ export async function saveConnectionValues(provider:string,selector:ConnectionSeif(Object.keys(values).some(k=>!allowed.has(k)))throw new IntegrationError("invalid_credential_fields");const normalized=normalizeInfraValues(provider,values),candidate={...c.values,...normalized};if(method.fields.some(f=>f.required&&!candidate[f.key]))throw new IntegrationError("required_fields_missing");- delete c.lastCheck; c.values=candidate;c.revision++;c.updatedAt=Date.now();if(verified)c.verifiedAt=Date.now();else delete c.verifiedAt;+ delete c.lastCheck; clearGoogleRuntime(c); c.values=candidate;c.revision++;c.updatedAt=Date.now();if(verified&&provider!==GOOGLE_APP_PROVIDER)c.verifiedAt=Date.now();else delete c.verifiedAt;return summaryIn(state,r.user,c);});}@@ -67,7 +69,7 @@ export async function integrationQuery(input:Record<string,unknown>){if(view==="request"){const provider=identity(input.provider,"provider");const catalog=connectionCatalog().find(p=>p.id===provider);if(!catalog)throw new IntegrationError("unknown_provider",404);if(!input.connection)return{provider,user:input.user??null,sources:catalog.sources,next:"choose named connection, source and auth; never pass keys through tool JSON"};- const route=await resolveIntegration(provider,selection);return{...route,guidance:connectionMethod(provider,route.source,route.authMethod).guidance,next:route.source==="direct"?"integration_setup_open with this user and connection":route.source==="composio"?"authorize, then sync until ACTIVE":"authorize the provider-owned MCP in your client"};+ const route=await resolveIntegration(provider,selection);return{...route,guidance:connectionMethod(provider,route.source,route.authMethod).guidance,next:isGoogleProvider(provider)?"Open native MSO Integrations to bind an OAuth app and authorize Google; never paste user tokens":route.source==="direct"?"integration_setup_open with this user and connection":route.source==="composio"?"authorize, then sync until ACTIVE":"authorize the provider-owned MCP in your client"};}if(!["snapshot","variables","users","connections","which"].includes(String(view)))throw new IntegrationError("unknown_query_view");const out=await integrationSnapshot(selection);if(view==="variables")return{variables:out.variables};if(view==="users")return{users:out.users,user:out.user};if(view==="which")return{user:out.user,resolution:out.resolution,bindings:out.bindings};if(view==="connections")return{user:out.user,connections:out.connections.filter(c=>!input.provider||c.provider===input.provider)};return out;diff --git a/lib/infra/connection-storage.ts b/lib/infra/connection-storage.tsindex 40632b2f..e8e4d163 100644--- a/lib/infra/connection-storage.ts+++ b/lib/infra/connection-storage.ts@@ -1,3 +1,4 @@+import { validateGoogleRuntime } from "./google-native-state";import { normalizeIntegrationVariables } from "./connection-variables";import { expandOwnerStorePath } from "@/lib/owner-store-path.js";import { constants, promises as fs } from "node:fs";@@ -20,7 +21,7 @@ async function readRaw():Promise<{raw:Record<string,unknown>;bytes:string}|null>function validate(d:IntegrationState):IntegrationState{if(d.version!==2||!d.instanceId||!d.users||typeof d.users!=="object"||Array.isArray(d.users)||!Array.isArray(d.bindings))throw new IntegrationError("invalid_integration_store");for(const [id,u] of Object.entries(d.users)){identity(id);if(u.id!==id||!u.connections||!u.defaults)throw new IntegrationError("invalid_integration_store");- for(const [p,rows]of Object.entries(u.connections)){identity(p);for(const [cid,c]of Object.entries(rows)){identity(cid);if(c.id!==cid||c.provider!==p||!c.uid||!Number.isInteger(c.revision)||!c.values||typeof c.values!=="object"||Array.isArray(c.values)||Object.values(c.values).some(v=>typeof v!=="string"))throw new IntegrationError("invalid_connection_store");connectionMethod(c.provider,c.source,c.authMethod);if(c.sharedFrom&&(!c.sharedFrom.user||!c.sharedFrom.connection||c.sharedFrom.provider!==p||c.source!=="direct"||Object.keys(c.values).length))throw new IntegrationError("invalid_shared_connection");if(c.source!=="direct"&&Object.keys(c.values).length)throw new IntegrationError("external_secrets_forbidden");}}+ for(const [p,rows]of Object.entries(u.connections)){identity(p);for(const [cid,c]of Object.entries(rows)){identity(cid);if(c.id!==cid||c.provider!==p||!c.uid||!Number.isInteger(c.revision)||!c.values||typeof c.values!=="object"||Array.isArray(c.values)||Object.values(c.values).some(v=>typeof v!=="string"))throw new IntegrationError("invalid_connection_store");connectionMethod(c.provider,c.source,c.authMethod);validateGoogleRuntime(c);if(c.sharedFrom&&(!c.sharedFrom.user||!c.sharedFrom.connection||c.sharedFrom.provider!==p||c.source!=="direct"||Object.keys(c.values).length))throw new IntegrationError("invalid_shared_connection");if(c.source!=="direct"&&Object.keys(c.values).length)throw new IntegrationError("external_secrets_forbidden");}}}normalizeIntegrationVariables(d);return d;diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.tsindex e511d9b7..599b8767 100644--- a/lib/infra/connection-ui.ts+++ b/lib/infra/connection-ui.ts@@ -1,12 +1,13 @@+import { GOOGLE_CONNECTION_UI_SCRIPT } from "./google-connection-ui";import { PROJECT_MCP_UI_SCRIPT } from "./project-mcp-ui";export { CONNECTION_MANAGER_STYLE } from "./connection-ui-style";import { PROVIDER_ICON_PATHS } from "./provider-icons";-export const CONNECTION_MANAGER_SCRIPT=PROJECT_MCP_UI_SCRIPT+`const PROVIDER_ICON_PATHS=${JSON.stringify(PROVIDER_ICON_PATHS)};`+String.raw`+export const CONNECTION_MANAGER_SCRIPT=GOOGLE_CONNECTION_UI_SCRIPT+PROJECT_MCP_UI_SCRIPT+`const PROVIDER_ICON_PATHS=${JSON.stringify(PROVIDER_ICON_PATHS)};`+String.raw`function mountConnectionManager(root,catalog,bridge,initial={}){let disposed=false,sequence=0,snapshot=initial.snapshot||{users:[],connections:[],bindings:[]},user=initial.user||snapshot.user||null,provider=catalog.find(p=>p.id===initial.provider)||catalog.find(p=>p.id==="github")||catalog[0];let detail,status,container,sidebarPanel,sidebarBackdrop,sidebarToggle,navButtons=[],navMode=["variables","ai-providers"].includes(initial.section)?initial.section:"provider",sidebarOpen=false;const ready=c=>c.state==="verified"||c.state==="ACTIVE";- const stateLabel=c=>ready(c)?"Verified":c.state==="incomplete"?"Needs setup":c.state==="configured"?"Not verified":c.state==="invalid"?"Access rejected":c.state==="unavailable"?"Check unavailable":c.state==="unconfigured"?"Needs setup":"Authorize";+ const stateLabel=c=>({"app-configured":"App configured · consent required","app-required":"OAuth app required","authorization-pending":"Consent pending","authorization-required":"Consent required","reauthorization-required":"Reconnect required","scope-missing":"Permission missing","authorized":"Authorized · verify access"}[c.state])||(ready(c)?"Verified":c.state==="incomplete"?"Needs setup":c.state==="configured"?"Not verified":c.state==="invalid"?"Access rejected":c.state==="unavailable"?"Check unavailable":c.state==="unconfigured"?"Needs setup":"Authorize");const mark=p=>{const wrap=n("span",undefined,"provider-mark"),svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),shape=document.createElementNS("http://www.w3.org/2000/svg","path");wrap.setAttribute("aria-hidden","true");svg.setAttribute("viewBox","0 0 24 24");shape.setAttribute("d",PROVIDER_ICON_PATHS[p.id]||"M8 2h8v5h5v10h-5v5H8v-5H3V7h5V2zm2 2v5H5v6h5v5h4v-5h5V9h-5V4z");svg.append(shape);wrap.append(svg);return wrap};const human=s=>s.replaceAll("-"," ").replaceAll("_"," ");const n=(tag,text,cls)=>{const v=integrationNode(tag,text);if(cls)v.className=cls;return v};@@ -133,12 +134,13 @@ function mountConnectionManager(root,catalog,bridge,initial={}){const rows=snapshot.connections.filter(c=>c.provider===provider.id);if(rows.length){const count=rows.filter(ready).length;detail.append(n("p",rows.length+" connection"+(rows.length===1?"":"s")+" · "+count+" verified","identity-summary-line"));}if(!rows.length){const empty=n("div",undefined,"identity-empty");empty.append(n("h3","Connect "+provider.title),n("p",user?"Add an account to start using "+provider.title+" in your projects.":bridge.manage?"Select a credential owner to add an account.":"Read the setup guide below, then sign in to connect your account."));const start=b("Add "+provider.title+" account",newConnection,"primary");start.disabled=!user||!bridge.manage;if(bridge.manage)empty.append(start);detail.append(empty);const help=n("details");help.append(n("summary","Connection methods & setup guides"));for(const s of provider.sources)for(const m of s.methods){const info=n("section");info.append(n("h3",s.label+" · "+m.label));guide(m,info);help.append(info)}detail.append(help)}for(const c of rows){const card=n("article",undefined,"connection-card");const top=n("header",undefined,"connection-heading"),name=n("div");name.append(n("h3",c.label),n("small",c.id));const state=n("span",stateLabel(c),"connection-state");state.dataset.ready=String(ready(c));top.append(name,state);card.append(top);const tags=n("div",undefined,"identity-tags");for(const value of [human(c.source),human(c.authMethod),c.sharedFrom?"Shared from "+c.sharedFrom.user:"",c.isDefault?"Default account":""])if(value)tags.append(n("span",value));card.append(tags);const actions=n("div",undefined,"identity-actions"),more=n("details",undefined,"identity-tools"),secondary=n("div",undefined,"identity-actions");more.append(n("summary","More"));more.append(secondary);+ if(provider.nativeGoogle&&!provider.configurationOnly){mountNativeGoogleConnection(card,c,{n,b,user,provider,catalog,snapshot,bridge,status,reload,selectProvider});detail.append(card);continue}const open=b(c.source==="direct"?(c.fields.some(f=>f.stored)?"Update credentials":"Finish setup"):"Authorize",()=>{if(c.source==="direct")void bridge.openSetup({user,provider:provider.id,connection:c.id}).catch(e=>status.textContent=textError(e));else external(c)});open.disabled=!bridge.manage;if(!c.sharedFrom)actions.append(open);const verify=b("Verify",async()=>{try{status.textContent="Checking selected connection…";const result=await bridge.execute({user,provider:provider.id,connection:c.id,operation:"verify"});await reload();status.textContent=(result.ok===true?"Verified: ":"Status: ")+result.detail}catch(e){status.textContent=textError(e)}});verify.disabled=!bridge.execute;actions.append(verify);const rename=b("Rename",()=>{detail.replaceChildren(n("h2","Rename connection"));const name=input("Label",c.label);detail.append(name.label,b("Save label",()=>change({action:"connection.rename",user,provider:provider.id,connection:c.id,label:name.input.value})),b("Cancel",()=>{navMode="provider";activateNav(navMode);drawProvider()}))});rename.disabled=!bridge.manage;secondary.append(rename);if(c.sharedFrom){card.append(n("p","Read-only shared backing: "+c.sharedFrom.user+" / "+c.sharedFrom.connection,"identity-muted"));}else if(c.source==="direct"){const fields=n("div",undefined,"identity-credential-status");for(const f of c.fields){const line=n("div");line.append(n("span",f.label));const fieldState=n("span",f.stored?"Stored":"Missing","credential-field-state");fieldState.dataset.stored=String(f.stored);line.append(fieldState);if(f.stored){const remove=b("Remove",()=>confirmation("Remove credential field",f.key,()=>change({action:"credential.delete",user,provider:provider.id,connection:c.id,key:f.key})),"danger");remove.disabled=!bridge.manage;line.append(remove)}fields.append(line)}card.append(fields);if(c.fields.some(f=>f.stored)){const clear=b("Clear credentials",()=>confirmation("Clear this connection's credential fields",c.id,()=>change({action:"credential.delete",user,provider:provider.id,connection:c.id})),"danger");clear.disabled=!bridge.manage;secondary.append(clear)}}if(!c.isDefault){const def=b("Make default",()=>change({action:"connection.default",user,provider:provider.id,connection:c.id}));def.disabled=!bridge.manage;secondary.append(def)}- if(c.sharedFrom){const unshare=b("Unshare",()=>confirmation("Remove shared alias",c.id,()=>change({action:"connection.unshare",user,provider:provider.id,connection:c.id})),"danger");unshare.disabled=!bridge.manage;secondary.append(unshare)}else{if(c.source==="direct"){const share=b("Share linked access",()=>shareConnection(c));share.disabled=!bridge.manage;secondary.append(share)}const duplicate=b("Copy to another owner",()=>copyConnection(c));duplicate.disabled=!bridge.manage;secondary.append(duplicate)}+ if(c.sharedFrom){const unshare=b("Unshare",()=>confirmation("Remove shared alias",c.id,()=>change({action:"connection.unshare",user,provider:provider.id,connection:c.id})),"danger");unshare.disabled=!bridge.manage;secondary.append(unshare)}else{if(c.source==="direct"&&!provider.nativeGoogle){const share=b("Share linked access",()=>shareConnection(c));share.disabled=!bridge.manage;secondary.append(share)}const duplicate=b("Copy to another owner",()=>copyConnection(c));duplicate.disabled=!bridge.manage;secondary.append(duplicate)}if(!c.sharedFrom){const del=b("Delete",()=>confirmation("Delete named connection",c.id,()=>change({action:"connection.delete",user,provider:provider.id,connection:c.id})),"danger");del.disabled=!bridge.manage;secondary.append(del);}actions.append(more);card.append(actions);if(c.lastCheck)card.append(n("small","Last checked "+new Date(c.lastCheck.checkedAt).toLocaleString()+" · "+stateLabel(c)));else if(c.verifiedAt)card.append(n("small","Last verified "+new Date(c.verifiedAt).toLocaleString()));detail.append(card);}}@@ -148,7 +150,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){for(const s of provider.sources){const o=n("option",s.label);o.value=s.id;source.append(o)}function changeAuth(){auth.replaceChildren();for(const m of provider.sources.find(s=>s.id===source.value).methods){const o=n("option",m.label+" · "+m.scope);o.value=m.id;auth.append(o)}previewGuide()}function previewGuide(){preview.replaceChildren();const method=provider.sources.find(s=>s.id===source.value).methods.find(m=>m.id===auth.value);if(method.fields.length)preview.append(n("p","Fields: "+method.fields.map(f=>f.label+(f.required?" *":"")).join(", ")));else preview.append(n("p","No provider tokens are stored locally for this source."));guide(method,preview)}source.addEventListener("change",changeAuth);auth.addEventListener("change",previewGuide);changeAuth();- const fields=n("div",undefined,"identity-fields");fields.append(label.label,sourceLabel,authLabel);const advanced=n("details");advanced.append(n("summary","Connection identifier"),id.label);detail.append(fields,advanced,preview,b("Create & connect",()=>change({action:"connection.create",user,provider:provider.id,connection:id.input.value,label:label.input.value,source:source.value,authMethod:auth.value},async()=>{await reload();if(source.value==="direct")await bridge.openSetup({user,provider:provider.id,connection:id.input.value});else{const created=snapshot.connections.find(c=>c.provider===provider.id&&c.id===id.input.value);if(created)external(created)}}),"primary"),b("Cancel",()=>{navMode="provider";activateNav(navMode);drawProvider()}));label.input.focus();+ const fields=n("div",undefined,"identity-fields");fields.append(label.label,sourceLabel,authLabel);const advanced=n("details");advanced.append(n("summary","Connection identifier"),id.label);detail.append(fields,advanced,preview,b("Create & connect",()=>change({action:"connection.create",user,provider:provider.id,connection:id.input.value,label:label.input.value,source:source.value,authMethod:auth.value},async()=>{await reload();if(provider.nativeGoogle&&!provider.configurationOnly)return;if(source.value==="direct")await bridge.openSetup({user,provider:provider.id,connection:id.input.value});else{const created=snapshot.connections.find(c=>c.provider===provider.id&&c.id===id.input.value);if(created)external(created)}}),"primary"),b("Cancel",()=>{navMode="provider";activateNav(navMode);drawProvider()}));label.input.focus();}function copyConnection(c){detail.replaceChildren(n("h2","Copy "+c.label),n("p","Creates an independent connection for another credential owner. Existing connections are never overwritten."));const targets=snapshot.users.filter(row=>row.id!==user).map(row=>({id:row.id,text:row.label+" · "+row.id})),target=choicePicker("Target credential owner",targets,targets[0]?.id||"",()=>sync()),id=input("New connection ID",c.id),label=input("New connection label",c.label),copy=input("","","checkbox"),make=input("","","checkbox");copy.label.className=make.label.className="identity-check";copy.label.append(document.createTextNode("Copy saved direct credentials"));copy.input.checked=c.source==="direct";copy.label.hidden=c.source!=="direct";make.label.append(document.createTextNode("Make the copied connection default for this service"));const submit=b("Copy connection",()=>change({action:"connection.duplicate",user,provider:provider.id,connection:c.id,target:target.value,targetConnection:id.input.value,label:label.input.value,copyCredentials:copy.input.checked,makeDefault:make.input.checked}),"primary"),sync=()=>{submit.disabled=!bridge.manage||!target.value||target.value===user||!id.input.value.trim()||!label.input.value.trim()};for(const control of[id.input,label.input])control.addEventListener("input",sync);sync();detail.append(target.wrap,id.label,label.label,copy.label,make.label,submit,b("Cancel",()=>{navMode="provider";activateNav(navMode);drawProvider()}));}function shareConnection(c){detail.replaceChildren(n("h2","Share "+c.label),n("p","Creates a read-only linked alias. Credential rotation stays with the current owner."));const targets=snapshot.users.filter(row=>row.id!==user).map(row=>({id:row.id,text:row.label+" · "+row.id})),target=choicePicker("Target credential owner",targets,targets[0]?.id||"",()=>sync()),label=input("New alias label",c.label),make=input("", "","checkbox");make.label.className="identity-check";make.label.append(document.createTextNode("Make this owner’s default for this service"));const submit=b("Create shared alias",()=>change({action:"connection.share",user,provider:provider.id,connection:c.id,target:target.value,label:label.input.value,makeDefault:make.input.checked}),"primary"),sync=()=>{submit.disabled=!bridge.manage||!target.value||target.value===user||!label.input.value.trim()};label.input.addEventListener("input",sync);sync();detail.append(target.wrap,label.label,make.label,submit,b("Cancel",()=>{navMode="provider";activateNav(navMode);drawProvider()}));}diff --git a/lib/infra/google-api-catalog.ts b/lib/infra/google-api-catalog.tsnew file mode 100644index 00000000..df6006a3--- /dev/null+++ b/lib/infra/google-api-catalog.ts@@ -0,0 +1,15 @@+const str = (maxLength = 2048) => ({ type: "string", minLength: 1, maxLength });+const num = (minimum: number, maximum: number) => ({ type: "integer", minimum, maximum });+const day = { ...str(10), pattern: "^\\d{4}-\\d{2}-\\d{2}$" };+const schema = (properties: Record<string, unknown>, required: string[] = []) => ({ type: "object", properties, required, additionalProperties: false });+const names = (maxItems: number) => ({ type: "array", minItems: 1, maxItems, items: schema({ name: { ...str(80), pattern: "^[A-Za-z][A-Za-z0-9_]{0,79}$" } }, ["name"]) });+export const GOOGLE_READ_OPERATIONS = [+ { name: "google.searchConsole.sites.list", provider: "google-search-console", description: "List Google Search Console properties accessible to this exact account and their permissions. Empty data does not imply an indexing result.", inputSchema: schema({}), readOnly: true },+ { name: "google.searchConsole.searchAnalytics.query", provider: "google-search-console", description: "Read a bounded date/query/page performance report. Missing rows do not prove non-indexing. Reuse siteUrl exactly from sites.list.",+ inputSchema: schema({ siteUrl: str(), startDate: day, endDate: day, dimensions: { type: "array", maxItems: 5, uniqueItems: true, items: { enum: ["date", "query", "page", "country", "device", "searchAppearance"] } }, type: { enum: ["web", "image", "video", "news", "discover", "googleNews"] }, rowLimit: num(1, 1000), startRow: num(0, 100000) }, ["siteUrl", "startDate", "endDate"]), readOnly: true },+ { name: "google.searchConsole.sitemaps.list", provider: "google-search-console", description: "Read existing sitemap submissions for the exact selected property. Does not submit a sitemap.", inputSchema: schema({ siteUrl: str() }, ["siteUrl"]), readOnly: true },+ { name: "google.searchConsole.url.inspect", provider: "google-search-console", description: "Read Google's stored URL index inspection result. This is not a live crawl or indexing request.", inputSchema: schema({ siteUrl: str(), inspectionUrl: str(), languageCode: str(35) }, ["siteUrl", "inspectionUrl"]), readOnly: true },+ { name: "google.analytics.accountSummaries.list", provider: "google-analytics", description: "Read accessible Google Analytics accounts and property summaries; follow nextPageToken using the same connection.", inputSchema: schema({ pageSize: num(1, 200), pageToken: str(2048) }), readOnly: true },+ { name: "google.analytics.report.run", provider: "google-analytics", description: "Read a bounded GA4 Data API report for properties/N. This is not Measurement Protocol and cannot send events or change configuration.",+ inputSchema: schema({ property: { ...str(40), pattern: "^properties/[1-9][0-9]{0,19}$" }, startDate: day, endDate: day, metrics: names(10), dimensions: names(9), limit: num(1, 1000), offset: num(0, 100000) }, ["property", "startDate", "endDate", "metrics"]), readOnly: true },+] as const;diff --git a/lib/infra/google-api-input.ts b/lib/infra/google-api-input.tsnew file mode 100644index 00000000..5e9f4de5--- /dev/null+++ b/lib/infra/google-api-input.ts@@ -0,0 +1,47 @@+import { IntegrationError } from "./identity";+const invalid = () => new IntegrationError("invalid_google_arguments");+export function keys(args: Record<string, unknown>, allowed: string[]) {+ if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).some(k => !allowed.includes(k))) throw invalid();+}+export function text(value: unknown, max = 2048): string {+ if (typeof value !== "string" || !value || value.length > max || /[\x00-\x20\x7f]/.test(value)) throw invalid();+ return value;+}+export function integer(value: unknown, min: number, max: number): number {+ if (!Number.isSafeInteger(value) || Number(value) < min || Number(value) > max) throw invalid();+ return Number(value);+}+export function date(value: unknown): string {+ const d = text(value, 10);+ if (!/^\d{4}-\d{2}-\d{2}$/.test(d) || !Number.isFinite(Date.parse(d)) || new Date(d).toISOString().slice(0, 10) !== d) throw invalid();+ return d;+}+export function dates(start: unknown, end: unknown) {+ const a = date(start), b = date(end); if (a > b) throw invalid(); return { startDate: a, endDate: b };+}+export function publicUrl(value: unknown): URL {+ const raw = text(value);+ let u: URL; try { u = new URL(raw); } catch { throw invalid(); }+ if (u.protocol !== "https:" || u.username || u.password || u.hash || !u.hostname.includes(".") || u.hostname.endsWith(".") || /^\[|^(?:\d{1,3}\.){3}\d{1,3}$/.test(u.hostname) || raw.includes("\\") || /%(?:2f|5c|00)/i.test(raw)) throw invalid();+ return u;+}+export function property(value: unknown): string {+ const raw = text(value);+ if (raw.startsWith("sc-domain:")) {+ if (!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(raw.slice(10))) throw invalid();+ } else { const u = publicUrl(raw); if (u.search) throw invalid(); }+ return raw;+}+export function inspection(site: string, value: unknown): string {+ const url = publicUrl(value);+ if (site.startsWith("sc-domain:")) { const domain = site.slice(10); if (url.hostname !== domain && !url.hostname.endsWith("." + domain)) throw invalid(); }+ else { const prefix = new URL(site); if (prefix.origin !== url.origin || !url.pathname.startsWith(prefix.pathname)) throw invalid(); }+ return text(value);+}+export function named(values: unknown, max: number) {+ if (!Array.isArray(values) || !values.length || values.length > max) throw invalid();+ return values.map(row => { if (!row || typeof row !== "object" || Array.isArray(row)) throw invalid(); keys(row, ["name"]); const name = text(row.name, 80); if (!/^[A-Za-z][A-Za-z0-9_]{0,79}$/.test(name)) throw invalid(); return { name }; });+}+export function enumeration(value: unknown, allowed: string[]): string {+ if (typeof value !== "string" || !allowed.includes(value)) throw invalid(); return value;+}diff --git a/lib/infra/google-api.test.ts b/lib/infra/google-api.test.tsnew file mode 100644index 00000000..5b3e3d41--- /dev/null+++ b/lib/infra/google-api.test.ts@@ -0,0 +1,65 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { executeGoogleRead, GOOGLE_READ_OPERATIONS } from "./google-api";+const TOKEN = "TEST_GOOGLE_ACCESS_NOT_REAL";+const response = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json" } });+beforeEach(() => vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response({}))));+afterEach(() => vi.unstubAllGlobals());+describe("bounded Google read operations", () => {+ it("publishes exactly six typed read-only operations with strict argument schemas", () => {+ expect(GOOGLE_READ_OPERATIONS).toHaveLength(6);+ for (const row of GOOGLE_READ_OPERATIONS) { expect(row.readOnly).toBe(true); expect(row.inputSchema.additionalProperties).toBe(false); }+ });+ it("reads exact Search Console property strings without relabelling permissions", async () => {+ const data = { siteEntry: [{ siteUrl: "sc-domain:example.test", permissionLevel: "siteRestrictedUser" }] };+ vi.mocked(fetch).mockResolvedValueOnce(response(data));+ expect(await executeGoogleRead("google-search-console", TOKEN, "google.searchConsole.sites.list", {})).toEqual(data);+ expect(fetch).toHaveBeenCalledWith("https://www.googleapis.com/webmasters/v3/sites", expect.objectContaining({ method: "GET", redirect: "error", cache: "no-store" }));+ });+ it("preserves a URL-prefix property when encoding the analytics endpoint", async () => {+ await executeGoogleRead("google-search-console", TOKEN, "google.searchConsole.searchAnalytics.query", { siteUrl: "https://example.test/blog/", startDate: "2026-09-01", endDate: "2026-09-20", type: "image", rowLimit: 10 });+ const [url, init] = vi.mocked(fetch).mock.calls[0];+ expect(url).toBe("https://www.googleapis.com/webmasters/v3/sites/https%3A%2F%2Fexample.test%2Fblog%2F/searchAnalytics/query");+ expect(JSON.parse(String(init?.body))).toMatchObject({ type: "image", rowLimit: 10, startRow: 0 });+ });+ it("lists existing sitemap metadata without invoking submission", async () => {+ await executeGoogleRead("google-search-console", TOKEN, "google.searchConsole.sitemaps.list", { siteUrl: "sc-domain:example.test" });+ expect(fetch).toHaveBeenCalledWith("https://www.googleapis.com/webmasters/v3/sites/sc-domain%3Aexample.test/sitemaps", expect.objectContaining({ method: "GET" }));+ });+ it("allows inspection of a real subdomain belonging to a domain property", async () => {+ await executeGoogleRead("google-search-console", TOKEN, "google.searchConsole.url.inspect", { siteUrl: "sc-domain:example.test", inspectionUrl: "https://sub.example.test/a" });+ expect(fetch).toHaveBeenCalledWith("https://searchconsole.googleapis.com/v1/urlInspection/index:inspect", expect.objectContaining({ method: "POST" }));+ });+ it.each(["https://example.test.evil.test/a", "https://evil.test/a", "https://[email protected]/a", "https://example.test/%2fsecret", "http://example.test/a"])("refuses out-of-property or malformed inspection %s", async inspectionUrl => {+ await expect(executeGoogleRead("google-search-console", TOKEN, "google.searchConsole.url.inspect", { siteUrl: "sc-domain:example.test", inspectionUrl })).rejects.toThrow("invalid_google_arguments");+ expect(fetch).not.toHaveBeenCalled();+ });+ it.each(["properties/1/../../accounts", "properties/1%2fadmin", "https://evil.test/", "properties/-1"])("refuses an unsafe GA property %s", async property => {+ await expect(executeGoogleRead("google-analytics", TOKEN, "google.analytics.report.run", { property, startDate: "2026-09-01", endDate: "2026-09-02", metrics: [{ name: "activeUsers" }] })).rejects.toThrow("invalid_google_arguments");+ expect(fetch).not.toHaveBeenCalled();+ });+ it("keeps GA pagination tokens and report counts without guessing totals", async () => {+ vi.mocked(fetch).mockResolvedValueOnce(response({ accountSummaries: [], nextPageToken: "next-page" }));+ expect(await executeGoogleRead("google-analytics", TOKEN, "google.analytics.accountSummaries.list", { pageSize: 5, pageToken: "page-2" })).toEqual({ accountSummaries: [], nextPageToken: "next-page" });+ expect(String(vi.mocked(fetch).mock.calls[0][0])).toContain("pageToken=page-2");+ await executeGoogleRead("google-analytics", TOKEN, "google.analytics.report.run", { property: "properties/1234", startDate: "2026-09-01", endDate: "2026-09-02", metrics: [{ name: "activeUsers" }], dimensions: [{ name: "country" }], limit: 20 });+ expect(vi.mocked(fetch).mock.calls[1][0]).toBe("https://analyticsdata.googleapis.com/v1beta/properties/1234:runReport");+ });+ it.each([{ rowLimit: 1001 }, { rowLimit: 0 }, { startDate: "2026-02-30" }, { dimensions: ["query", "query"] }, { customUrl: "https://evil.test" }])("refuses bounds, invalid dates, duplicate dimensions or extra parameters %j", async change => {+ await expect(executeGoogleRead("google-search-console", TOKEN, "google.searchConsole.searchAnalytics.query", { siteUrl: "sc-domain:example.test", startDate: "2026-09-01", endDate: "2026-09-02", ...change })).rejects.toThrow("invalid_google_arguments");+ });+ it.each([401, 403, 429, 500])("does not reflect upstream secrets from HTTP %s", async status => {+ vi.mocked(fetch).mockResolvedValueOnce(response({ error: { message: TOKEN, refresh_token: "PRIVATE_VALUE" } }, status));+ let error: unknown; try { await executeGoogleRead("google-search-console", TOKEN, "google.searchConsole.sites.list", {}); } catch (e) { error = e; }+ expect(String(error)).not.toMatch(/TEST_GOOGLE_ACCESS|PRIVATE_VALUE/); expect(String(error)).toMatch(/google_/);+ });+ it("never accepts a cross-provider operation or missing authorization", async () => {+ await expect(executeGoogleRead("google-analytics", TOKEN, "google.searchConsole.sites.list", {})).rejects.toThrow("provider_operation_mismatch");+ await expect(executeGoogleRead("google-search-console", "", "google.searchConsole.sites.list", {})).rejects.toThrow("authorization_required"); expect(fetch).not.toHaveBeenCalled();+ });+ it("caps responses and redacts a token reflected in success payloads", async () => {+ vi.mocked(fetch).mockResolvedValueOnce(new Response("{}", { headers: { "content-length": "9999999" } }));+ await expect(executeGoogleRead("google-search-console", TOKEN, "google.searchConsole.sites.list", {})).rejects.toThrow("response_limit");+ vi.mocked(fetch).mockResolvedValueOnce(response({ message: TOKEN, access_token: "OTHER_PRIVATE_TOKEN" }));+ expect(JSON.stringify(await executeGoogleRead("google-search-console", TOKEN, "google.searchConsole.sites.list", {}))).not.toMatch(/TEST_GOOGLE_ACCESS|OTHER_PRIVATE_TOKEN/);+ });+});diff --git a/lib/infra/google-api.ts b/lib/infra/google-api.tsnew file mode 100644index 00000000..f46e1fa6--- /dev/null+++ b/lib/infra/google-api.ts@@ -0,0 +1,64 @@+import { IntegrationError } from "./identity";+import type { GoogleProvider } from "./google-native-types";+import { GOOGLE_READ_OPERATIONS } from "./google-api-catalog";+import { keys, text, integer, dates, property, inspection, named, enumeration } from "./google-api-input";+export { GOOGLE_READ_OPERATIONS } from "./google-api-catalog";+const SITE = "https://www.googleapis.com/webmasters/v3/sites";+const MAX_RESPONSE = 2 * 1024 * 1024;+function target(operation: string, args: Record<string, unknown>): { url: string; body?: unknown } {+ switch (operation) {+ case "google.searchConsole.sites.list": keys(args, []); return { url: SITE };+ case "google.searchConsole.sitemaps.list": keys(args, ["siteUrl"]); return { url: `${SITE}/${encodeURIComponent(property(args.siteUrl))}/sitemaps` };+ case "google.searchConsole.searchAnalytics.query": {+ keys(args, ["siteUrl", "startDate", "endDate", "dimensions", "type", "rowLimit", "startRow"]);+ const dimensions = args.dimensions ?? ["query"];+ if (!Array.isArray(dimensions) || dimensions.length > 5 || new Set(dimensions).size !== dimensions.length) throw new IntegrationError("invalid_google_arguments");+ dimensions.forEach(d => enumeration(d, ["date", "query", "page", "country", "device", "searchAppearance"]));+ return { url: `${SITE}/${encodeURIComponent(property(args.siteUrl))}/searchAnalytics/query`, body: { ...dates(args.startDate, args.endDate), dimensions,+ type: enumeration(args.type ?? "web", ["web", "image", "video", "news", "discover", "googleNews"]), rowLimit: integer(args.rowLimit ?? 100, 1, 1000), startRow: integer(args.startRow ?? 0, 0, 100000) } };+ }+ case "google.searchConsole.url.inspect": {+ keys(args, ["siteUrl", "inspectionUrl", "languageCode"]); const siteUrl = property(args.siteUrl), languageCode = text(args.languageCode ?? "en-US", 35);+ if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(languageCode)) throw new IntegrationError("invalid_google_arguments");+ return { url: "https://searchconsole.googleapis.com/v1/urlInspection/index:inspect", body: { siteUrl, inspectionUrl: inspection(siteUrl, args.inspectionUrl), languageCode } };+ }+ case "google.analytics.accountSummaries.list": {+ keys(args, ["pageSize", "pageToken"]); const url = new URL("https://analyticsadmin.googleapis.com/v1beta/accountSummaries");+ url.searchParams.set("pageSize", String(integer(args.pageSize ?? 50, 1, 200)));+ if (args.pageToken !== undefined) url.searchParams.set("pageToken", text(args.pageToken));+ return { url: url.href };+ }+ case "google.analytics.report.run": {+ keys(args, ["property", "startDate", "endDate", "metrics", "dimensions", "limit", "offset"]);+ const prop = text(args.property, 40); if (!/^properties\/[1-9][0-9]{0,19}$/.test(prop)) throw new IntegrationError("invalid_google_arguments");+ return { url: `https://analyticsdata.googleapis.com/v1beta/${prop}:runReport`, body: { dateRanges: [dates(args.startDate, args.endDate)], metrics: named(args.metrics, 10),+ ...(args.dimensions === undefined ? {} : { dimensions: named(args.dimensions, 9) }), limit: String(integer(args.limit ?? 100, 1, 1000)), offset: String(integer(args.offset ?? 0, 0, 100000)) } };+ }+ default: throw new IntegrationError("google_operation_not_supported");+ }+}+function sanitize(value: unknown, accessToken: string, depth = 0): unknown {+ if (depth > 20) return "[depth limited]";+ if (typeof value === "string") return value.split(accessToken).join("[redacted]");+ if (Array.isArray(value)) return value.map(v => sanitize(v, accessToken, depth + 1));+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, /^(?:access_token|refresh_token|id_token|authorization|password|client_secret)$/i.test(k) ? "[redacted]" : sanitize(v, accessToken, depth + 1)]));+ return value;+}+export async function executeGoogleRead(provider: GoogleProvider, accessToken: string, operation: string, args: Record<string, unknown>): Promise<unknown> {+ if (!GOOGLE_READ_OPERATIONS.some(row => row.name === operation && row.provider === provider)) throw new IntegrationError("google_provider_operation_mismatch");+ if (typeof accessToken !== "string" || accessToken.length < 10 || accessToken.length > 16384 || /[\s\x00-\x1f\x7f]/.test(accessToken)) throw new IntegrationError("google_authorization_required", 401);+ const request = target(operation, args);+ try {+ const response = await fetch(request.url, { method: request.body ? "POST" : "GET", headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json", ...(request.body ? { "Content-Type": "application/json" } : {}) },+ ...(request.body ? { body: JSON.stringify(request.body) } : {}), redirect: "error", cache: "no-store", signal: AbortSignal.timeout(20_000) });+ if (!response.ok) { await response.body?.cancel().catch(() => undefined); throw new IntegrationError(response.status === 401 ? "google_reauthorization_required" : response.status === 403 ? "google_access_denied_or_api_disabled" : response.status === 429 ? "google_rate_limited" : "google_api_request_failed", [401, 403, 429].includes(response.status) ? response.status : 502); }+ if (Number(response.headers.get("content-length")) > MAX_RESPONSE) { await response.body?.cancel().catch(() => undefined); throw new IntegrationError("google_response_limit", 502); }+ const reader = response.body?.getReader(); if (!reader) throw new IntegrationError("google_invalid_response", 502);+ const chunks: Uint8Array[] = []; let bytes = 0;+ try { for (;;) { const part = await reader.read(); if (part.done) break; bytes += part.value.byteLength; if (bytes > MAX_RESPONSE) throw new IntegrationError("google_response_limit", 502); chunks.push(part.value); } }+ finally { await reader.cancel().catch(() => undefined); reader.releaseLock(); }+ const value: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8"));+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new IntegrationError("google_invalid_response", 502);+ return sanitize(value, accessToken);+ } catch (error) { throw error instanceof IntegrationError ? error : new IntegrationError("google_api_unavailable", 502); }+}diff --git a/lib/infra/google-connection-ui.ts b/lib/infra/google-connection-ui.tsnew file mode 100644index 00000000..3ba839ce--- /dev/null+++ b/lib/infra/google-connection-ui.ts@@ -0,0 +1,37 @@+/** One native Google panel is used by the manager and the embedded connection catalogue. */+export const GOOGLE_CONNECTION_UI_SCRIPT = String.raw`+function mountNativeGoogleConnection(card,c,ctx){+ const{n,b,user,provider,snapshot,bridge,status,reload,selectProvider}=ctx;+ const info=c.google||{},apps=snapshot.connections.filter(row=>row.provider==="google-oauth-app"&&!row.sharedFrom),choice=n("select"),label=n("label","Google OAuth app"),empty=n("option","Choose an app…");empty.value="";choice.append(empty);+ for(const app of apps){const option=n("option",app.label+" · "+app.id);option.value=app.id;choice.append(option)}choice.value=info.appConnection||"";label.append(choice);+ const note=n("p","Google user consent is separate from the OAuth app configuration. This connector reads data only; it cannot change properties or send Analytics events.","identity-muted");card.append(note);+ if(info.account?.email)card.append(n("p","Google account: "+info.account.email));+ if(info.requiredScope)card.append(n("small","Required permission: "+info.requiredScope));+ if(provider.callbackUrl){const callback=n("div",undefined,"identity-credential-status");callback.append(n("span","Register this exact redirect in Google Cloud"),n("small",provider.callbackUrl));card.append(callback)}+ else card.append(n("p","An installation owner must configure OS_PUBLIC_ORIGIN as the canonical HTTPS origin before authorization.","identity-muted"));+ const actions=n("div",undefined,"identity-actions"),linkBox=n("div");+ const fail=error=>{status.textContent=({google_app_setup_required:"Finish the Google OAuth app's private setup first.",google_app_required:"Choose a configured Google OAuth app owned by this same credential owner.",google_disconnect_before_app_change:"Disconnect this Google account before changing its OAuth app.",google_account_changed_disconnect_first:"Reconnect with the same Google account, or disconnect first to switch accounts.",google_reauthorization_required:"Google authorization expired or changed. Reconnect with Google.",google_required_scope_missing:"Google did not grant the required read-only permission. Reconnect and review the requested scope.",google_same_origin_required:"Open native MSO at its configured public HTTPS origin before connecting.",google_public_https_origin_required:"Configure this installation's public HTTPS origin before connecting.",connection_busy:"This connection is in use. Retry when the current operation finishes."}[error.code||error.message]||error.message||"Google operation failed.")};+ const run=async(operation,args={})=>{status.textContent="Working on the selected Google connection…";try{const result=await bridge.execute({user,provider:provider.id,connection:c.id,operation,arguments:args,confirm:true});await reload();return result}catch(error){fail(error)}};+ const bind=b("Use selected app",()=>run("google.bind",{appConnection:choice.value}));bind.disabled=!bridge.execute;card.append(label);actions.append(bind);+ const appSetup=b(apps.length?"Manage Google OAuth apps":"Set up Google OAuth app",()=>selectProvider(ctx.catalog.find(p=>p.id==="google-oauth-app")));actions.append(appSetup);+ if(bridge.googleAuthorize){+ const connect=b(info.account?"Reconnect with Google":"Connect with Google",async()=>{connect.disabled=true;status.textContent="Preparing private Google consent…";try{+ const flow=await bridge.googleAuthorize({user,provider:provider.id,connection:c.id}),url=new URL(flow.authorizationUrl);+ if(url.origin!=="https://accounts.google.com"||url.pathname!=="/o/oauth2/v2/auth")throw new Error("Invalid authorization response");+ linkBox.replaceChildren();const a=n("a","Continue to Google");a.href=url.href;a.target="_blank";a.rel="noopener noreferrer";linkBox.append(a,n("p","Complete consent in the new browser tab, then return and refresh. The link expires in ten minutes."));status.textContent="Authorization prepared, not connected yet.";+ }catch(error){fail(error)}finally{connect.disabled=false}});connect.disabled=!info.appConnection||!provider.callbackUrl;actions.append(connect);+ }else{+ const open=n("a","Open native MSO to authorize Google");if(provider.openPath){open.href=provider.openPath;open.target="_blank";open.rel="noopener noreferrer";if(bridge.openLink)open.addEventListener("click",event=>{event.preventDefault();bridge.openLink(provider.openPath)})}card.append(open,n("small","Google consent is completed in a top-level browser, never through an API key field or chat message."));+ }+ const verify=b("Verify API access",async()=>{const result=await run("verify");if(result)status.textContent=(result.ok?"Verified: ":"Status: ")+result.detail});verify.disabled=!bridge.execute;actions.append(verify,b("Refresh status",reload));+ const disconnect=b("Disconnect from MSO",async()=>{if(!window.confirm("Remove this Google authorization from MSO? This does not revoke the app in your Google account."))return;const result=await run("google.disconnect");if(result)status.textContent=result.detail});disconnect.disabled=!bridge.execute;actions.append(disconnect);+ card.append(actions,linkBox);+ const operations=n("details");operations.append(n("summary","Available read-only operations"));for(const op of provider.operations||[]){const row=n("div");row.append(n("small",op.name),n("p",op.description));operations.append(row)}card.append(operations);+ const more=n("details"),manage=n("div",undefined,"identity-actions");more.append(n("summary","Connection management"));+ if(bridge.manage){+ if(!c.isDefault)manage.append(b("Make default",async()=>{try{await bridge.manage({action:"connection.default",confirm:true,user,provider:provider.id,connection:c.id});await reload()}catch(error){fail(error)}}));+ manage.append(b("Delete connection",async()=>{if(!window.confirm("Delete this named Google connection and its local authorization?"))return;try{await bridge.manage({action:"connection.delete",confirm:true,user,provider:provider.id,connection:c.id});await reload()}catch(error){fail(error)}},"danger"));+ }+ more.append(manage,n("small","Google user authorizations are not shared or transferred to other owners. Each account requires explicit consent."));card.append(more);+}+`;diff --git a/lib/infra/google-native-config.ts b/lib/infra/google-native-config.tsnew file mode 100644index 00000000..b1792fdf--- /dev/null+++ b/lib/infra/google-native-config.ts@@ -0,0 +1,63 @@+import type { InfraProviderDefinition } from "./types";+import { IntegrationError, identity } from "./identity";+import type { GoogleProvider } from "./google-native-types";++export const GOOGLE_APP_PROVIDER = "google-oauth-app";+export const GOOGLE_CALLBACK_PATH = "/api/integrations/google/callback";+export const GOOGLE_SCOPES: Record<GoogleProvider, string> = {+ "google-search-console": "https://www.googleapis.com/auth/webmasters.readonly",+ "google-analytics": "https://www.googleapis.com/auth/analytics.readonly",+};+export const isGoogleProvider = (id: string): id is GoogleProvider => Object.hasOwn(GOOGLE_SCOPES, id);+export function googlePublicOrigin(): string {+ try {+ const url = new URL(process.env.OS_PUBLIC_ORIGIN || "");+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.pathname !== "/") throw new Error();+ return url.origin;+ } catch { throw new IntegrationError("google_public_https_origin_required", 409); }+}+export const googleRedirectUri = () => googlePublicOrigin() + GOOGLE_CALLBACK_PATH;+export const GOOGLE_PROVIDERS: InfraProviderDefinition[] = [+ { id: "google-oauth-app", title: "Google OAuth app", feature: false,+ description: "Configure this installation’s Google OAuth client once, then authorize separate Search Console and Analytics accounts. No Composio required.",+ fields: [+ { key: "clientId", label: "Google OAuth client ID", secret: false, required: true, description: "Web application client ID from your Google Cloud project." },+ { key: "clientSecret", label: "Google OAuth client secret", secret: true, required: true, description: "Enter only in this private form. App configuration is not user consent." },+ ] },+ ...(["google-search-console", "google-analytics"] as const).map(id => ({ id, feature: false,+ title: id === "google-search-console" ? "Google Search Console" : "Google Analytics 4",+ description: "Native read-only Google OAuth. Select a Google OAuth app, authorize the intended account, then verify actual API access. An API key alone cannot read private reports.",+ fields: [{ key: "appConnection", label: "Google OAuth app connection", secret: false, required: true, description: "An existing Google OAuth app under the same credential owner. Select it in the connection manager." }],+ })),+];+export function normalizeGoogleConfig(provider: string, raw: Record<string, unknown>): Record<string, string> {+ if (isGoogleProvider(provider)) return raw.appConnection ? { appConnection: identity(raw.appConnection, "app_connection") } : {};+ const out: Record<string, string> = {};+ if (raw.clientId) {+ if (typeof raw.clientId !== "string" || !/^[A-Za-z0-9._-]{8,220}\.apps\.googleusercontent\.com$/.test(raw.clientId.trim())) throw new IntegrationError("invalid_google_client_id");+ out.clientId = raw.clientId.trim();+ }+ if (raw.clientSecret) {+ if (typeof raw.clientSecret !== "string" || !/^[A-Za-z0-9_-]{12,256}$/.test(raw.clientSecret.trim())) throw new IntegrationError("invalid_google_client_secret");+ out.clientSecret = raw.clientSecret.trim();+ }+ return out;+}+export function googleGuidance(provider: string) {+ return {+ url: "https://console.cloud.google.com/auth/clients",+ reference: "https://developers.google.com/identity/protocols/oauth2/web-server",+ steps: provider === GOOGLE_APP_PROVIDER ? [+ "Create or select your own Google Cloud project. Enable Search Console API and/or Analytics Admin + Analytics Data APIs as needed.",+ "Configure the consent screen and create a Web application OAuth client. Configure this MSO installation’s public HTTPS origin first.",+ "Register the exact callback shown in the native Google connection panel. Never use a Composio callback.",+ "Enter the client ID and secret here. This saves app configuration only; each named Google account still needs its own consent and API verification.",+ "Testing-mode users, Workspace policies and Google app verification can limit authorization. MSO does not bypass these requirements.",+ ] : [+ "Create a Google OAuth app connection under the same credential owner, or reuse an existing one.",+ "Select that app in this connection’s Native Google setup. Open Google consent in a top-level browser, not an embedded webview.",+ "Authorize the intended account for this service’s read-only scope, then verify actual property access.",+ "No API key, measurement ID, browser cookie or Composio project key substitutes for Google user consent.",+ ],+ };+}diff --git a/lib/infra/google-native-lease.ts b/lib/infra/google-native-lease.tsnew file mode 100644index 00000000..3f306ceb--- /dev/null+++ b/lib/infra/google-native-lease.ts@@ -0,0 +1,25 @@+import { randomUUID } from "node:crypto";+import { mutateIntegrationState } from "./connection-storage";+import { assertNotBusy, IntegrationError, type ConnectionSelector, type IntegrationConnection, type IntegrationState } from "./identity";+import { googleTarget, googleApp } from "./google-native-state";+import type { GoogleProvider } from "./google-native-types";+export type GoogleLease = { user: string; provider: GoogleProvider; connection: string; c: IntegrationConnection; app: IntegrationConnection; id: string };+export function pinGoogle(state: IntegrationState, lease: GoogleLease) {+ const { c } = googleTarget(state, lease.provider, { user: lease.user, connection: lease.connection });+ const app = googleApp(state, lease.user, c.values.appConnection);+ if (c.uid !== lease.c.uid || c.revision !== lease.c.revision || app.uid !== lease.app.uid || app.revision !== lease.app.revision || c.lease?.id !== lease.id || app.lease?.id !== lease.id || c.lease.until <= Date.now() || app.lease.until <= Date.now()) throw new IntegrationError("google_connection_changed", 409);+ return { c, app };+}+export function acquireGoogleLease(state: IntegrationState, provider: GoogleProvider, selector: ConnectionSelector): GoogleLease {+ const { user, c } = googleTarget(state, provider, selector), app = googleApp(state, user, c.values.appConnection);+ assertNotBusy(c); assertNotBusy(app);+ const lease = { id: randomUUID(), until: Date.now() + 120000 };+ c.lease = lease; app.lease = lease;+ return { user, provider, connection: c.id, c: structuredClone(c), app: structuredClone(app), id: lease.id };+}+export async function releaseGoogleLease(lease: GoogleLease) {+ await mutateIntegrationState(state => {+ const rows = state.users[lease.user]?.connections;+ for (const c of [rows?.[lease.provider]?.[lease.connection], rows?.["google-oauth-app"]?.[lease.app.id]]) if (c?.lease?.id === lease.id) delete c.lease;+ });+}diff --git a/lib/infra/google-native-state.ts b/lib/infra/google-native-state.tsnew file mode 100644index 00000000..3bdb71b7--- /dev/null+++ b/lib/infra/google-native-state.ts@@ -0,0 +1,52 @@+import { GOOGLE_APP_PROVIDER, GOOGLE_SCOPES, isGoogleProvider, normalizeGoogleConfig, googleRedirectUri } from "./google-native-config";+import { IntegrationError, selectConnection, type ConnectionSelector, type IntegrationConnection, type IntegrationState } from "./identity";+import type { GoogleProvider } from "./google-native-types";++export function googleTarget(state: IntegrationState, provider: GoogleProvider, selector: ConnectionSelector) {+ const selected = selectConnection(state, provider, selector), c = selected.connection;+ if (c.source !== "direct" || c.authMethod !== "oauth2" || c.sharedFrom) throw new IntegrationError("google_native_connection_required", 409);+ return { user: selected.user, c };+}+export function googleApp(state: IntegrationState, user: string, id: string | undefined) {+ if (!id) throw new IntegrationError("google_app_required", 409);+ const app = state.users[user]?.connections[GOOGLE_APP_PROVIDER]?.[id];+ if (!app || app.source !== "direct" || app.authMethod !== "oauth-app" || app.sharedFrom) throw new IntegrationError("google_app_required", 409);+ const values = normalizeGoogleConfig(GOOGLE_APP_PROVIDER, app.values);+ if (!values.clientId || !values.clientSecret) throw new IntegrationError("google_app_setup_required", 409);+ return app;+}+export function assertGoogleGrantApp(c: IntegrationConnection, app: IntegrationConnection) {+ const grant = c.googleOAuth;+ if (!grant || grant.appConnection !== app.id || grant.appUid !== app.uid || grant.appRevision !== app.revision || grant.state !== "connected") throw new IntegrationError("google_reauthorization_required", 401);+ if (!isGoogleProvider(c.provider) || !grant.scopes.includes(GOOGLE_SCOPES[c.provider])) throw new IntegrationError("google_required_scope_missing", 403);+ return grant;+}+export function googleConnectionMetadata(state: IntegrationState, user: string, c: IntegrationConnection) {+ if (c.provider === GOOGLE_APP_PROVIDER) return { state: c.values.clientId && c.values.clientSecret ? "app-configured" : "incomplete", configurationOnly: true };+ if (!isGoogleProvider(c.provider)) return {};+ let app: IntegrationConnection;+ try { app = googleApp(state, user, c.values.appConnection); } catch { return { state: "app-required", google: { appConnection: c.values.appConnection || null } }; }+ const grant = c.googleOAuth;+ let redirectUri: string | null = null; try { redirectUri = googleRedirectUri(); } catch {}+ const active = !!grant && grant.appUid === app.uid && grant.appRevision === app.revision && grant.appConnection === app.id && grant.state === "connected" && grant.redirectUri === redirectUri;+ const requiredScope = GOOGLE_SCOPES[c.provider];+ const pending = c.googlePending && c.googlePending.expiresAt > Date.now() && c.googlePending.connectionUid === c.uid && c.googlePending.connectionRevision === c.revision && c.googlePending.appUid === app.uid && c.googlePending.appRevision === app.revision;+ const check = c.lastCheck?.revision === c.revision ? c.lastCheck.result : undefined;+ return { state: pending ? "authorization-pending" : !grant ? "authorization-required" : !active ? "reauthorization-required" : !grant.scopes.includes(requiredScope) ? "scope-missing" : check === "verified" ? "verified" : check === "invalid" ? "invalid" : check === "unavailable" ? "unavailable" : "authorized",+ google: { appConnection: app.id, requiredScope, account: grant ? { email: grant.email } : null,+ grantedScopes: grant?.scopes ?? [], accessExpiresAt: grant?.expiresAt ?? null, refreshAvailable: !!grant?.refreshToken,+ connectionOnly: true, note: "OAuth consent is not verification of a specific property. Verify actual API access." } };+}+export function clearGoogleRuntime(c: IntegrationConnection) { delete c.googleOAuth; delete c.googlePending; }+export function validateGoogleRuntime(c: IntegrationConnection) {+ if (!c.googleOAuth && !c.googlePending) return;+ const fail = () => { throw new IntegrationError("invalid_google_runtime_store"); };+ if (!isGoogleProvider(c.provider) || c.source !== "direct" || c.authMethod !== "oauth2" || c.sharedFrom) fail();+ const g = c.googleOAuth;+ if (g) {+ if (!g.redirectUri || !g.appConnection || !g.appUid || !Number.isSafeInteger(g.appRevision) || !g.subject || !g.email || !Array.isArray(g.scopes) || g.scopes.length > 30 || g.scopes.some(v => typeof v !== "string" || v.length > 256) || !Number.isFinite(g.expiresAt) || !Number.isFinite(g.updatedAt) || !["connected", "reauthorization-required"].includes(g.state)) fail();+ for (const token of [g.accessToken, g.refreshToken]) if (typeof token !== "string" || token.length > 16384 || /[\s\x00-\x1f\x7f]/.test(token)) fail();+ }+ const p = c.googlePending;+ if (p && (!/^[a-f0-9]{64}$/.test(p.stateHash) || !/^[a-f0-9]{64}$/.test(p.bindingHash) || !/^[A-Za-z0-9_-]{43,128}$/.test(p.verifier) || !Number.isFinite(p.expiresAt) || !Number.isSafeInteger(p.connectionRevision) || !Number.isSafeInteger(p.appRevision) || !p.redirectUri || !p.connectionUid || !p.appUid || !p.appConnection || !p.actor?.deviceId || typeof p.actor.cookieEpoch !== "string" || !p.actor.cookieScope || !Number.isFinite(p.actor.sessionExpiresAt))) fail();+}diff --git a/lib/infra/google-native-types.ts b/lib/infra/google-native-types.tsnew file mode 100644index 00000000..db184392--- /dev/null+++ b/lib/infra/google-native-types.ts@@ -0,0 +1,15 @@+/** Server-only OAuth grants live in the existing owner integration store, never a transfer DTO. */+export type GoogleProvider = "google-search-console" | "google-analytics";+export type GoogleActor = { deviceId: string; cookieScope: string; cookieEpoch: string; sessionExpiresAt: number };+export type GoogleGrant = {+ appConnection: string; appUid: string; appRevision: number; redirectUri: string;+ subject: string; email: string; scopes: string[];+ accessToken: string; refreshToken: string; expiresAt: number;+ state: "connected" | "reauthorization-required"; updatedAt: number;+};+export type GooglePending = {+ stateHash: string; bindingHash: string; verifier: string; expiresAt: number;+ connectionUid: string; connectionRevision: number;+ appConnection: string; appUid: string; appRevision: number; redirectUri: string;+ actor: GoogleActor;+};diff --git a/lib/infra/google-native.test.ts b/lib/infra/google-native.test.tsnew file mode 100644index 00000000..4805cccf--- /dev/null+++ b/lib/infra/google-native.test.ts@@ -0,0 +1,126 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import path from "node:path";+import os from "node:os";+const security = vi.hoisted(() => ({ role: "owner", epoch: "test-cookie-epoch-123456789" }));+vi.mock("@/lib/auth/device-store", () => ({ currentSessionPolicy: async () => ({ epoch: security.epoch }), getApprovedDevice: async () => ({ role: security.role }) }));+vi.mock("@/lib/auth/session-cookie", () => ({ configuredSessionCookieScope: () => "host" }));+let root: string;+let storage: typeof import("./connection-storage"), service: typeof import("./connection-service"), flow: typeof import("./google-oauth-flow"), native: typeof import("./google-native");+const selector = { user: "test-owner", connection: "search" };+const actor = () => ({ deviceId: "test-device", cookieScope: "host", cookieEpoch: security.epoch, sessionExpiresAt: Date.now() + 600000 });+const tokenResponse = () => ({ access_token: "TEST_ACCESS_NOT_REAL_123456", refresh_token: "TEST_REFRESH_NOT_REAL_123456", token_type: "Bearer", expires_in: 3600, scope: "openid email https://www.googleapis.com/auth/webmasters.readonly" });+const accountResponse = () => ({ sub: "test-user-123", email: "[email protected]", email_verified: true });+const response = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });+async function begin() { const start = await flow.beginGoogleAuthorization("google-search-console", selector, actor()); return { ...start, state: new URL(start.authorizationUrl).searchParams.get("state")! }; }+async function authorize() {+ const start = await begin();+ vi.mocked(fetch).mockResolvedValueOnce(response(tokenResponse())).mockResolvedValueOnce(response(accountResponse()));+ await flow.completeGoogleAuthorization(start.state, start.binding, "TEST_CODE_NOT_REAL"); return start;+}+beforeEach(async () => {+ root = await mkdtemp(path.join(os.tmpdir(), "mso-google-test-"));+ vi.resetModules(); vi.stubEnv("OS_INFRA_STORE", path.join(root, "infra.json")); vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("No real network in this test")));+ security.role = "owner"; security.epoch = "test-cookie-epoch-123456789";+ storage = await import("./connection-storage"); service = await import("./connection-service"); flow = await import("./google-oauth-flow"); native = await import("./google-native");+ await storage.mutateIntegrationState(d => {+ d.users[selector.user] = { id: selector.user, uid: "owner-uid", label: "Test owner", connections: {}, defaults: {} }; d.defaultUser = selector.user;+ const app = service.createConnectionIn(d, { user: selector.user, provider: "google-oauth-app", connection: "app", authMethod: "oauth-app" });+ app.values = { clientId: "123456789-test.apps.googleusercontent.com", clientSecret: "TEST_CLIENT_SECRET_NOT_REAL" };+ service.createConnectionIn(d, { user: selector.user, provider: "google-search-console", connection: "search", authMethod: "oauth2" }).values = { appConnection: "app" };+ });+});+afterEach(async () => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); await rm(root, { recursive: true, force: true }); });++describe("native Google lifecycle — isolated store, mocked Google", () => {+ it("rejects OAuth secrets at the public metadata boundary", async () => {+ for (const key of ["clientSecret", "client_secret", "access_token", "refresh_token", "code_verifier"])+ await expect(service.integrationQuery({ view: "catalog", [key]: "SYNTHETIC_ONLY" })).rejects.toThrow("secret_input_forbidden");+ });+ it("app configuration and bound metadata are not connected accounts", async () => {+ expect((await service.resolveIntegration("google-oauth-app", { ...selector, connection: "app" })).state).toBe("app-configured");+ expect((await service.resolveIntegration("google-search-console", selector)).state).toBe("authorization-required");+ expect((await native.nativeGoogleStatus("google-oauth-app", { ...selector, connection: "app" })).ok).toBeNull();+ expect(fetch).not.toHaveBeenCalled();+ });+ it("pins state, browser binding, PKCE and exact redirect, with minimal service scope", async () => {+ const start = await begin(), url = new URL(start.authorizationUrl);+ expect(url.origin).toBe("https://accounts.google.com"); expect(url.searchParams.get("code_challenge_method")).toBe("S256");+ expect(url.searchParams.get("redirect_uri")).toBe("https://mso.example.test/api/integrations/google/callback");+ expect(url.searchParams.get("scope")).not.toContain("analytics");+ expect((await service.resolveIntegration("google-search-console", selector)).state).toBe("authorization-pending");+ expect(JSON.stringify(await service.integrationSnapshot())).not.toContain(start.state);+ await expect(flow.completeGoogleAuthorization(start.state, "x".repeat(43), "TEST_CODE")).rejects.toThrow("expired_or_invalid");+ expect(fetch).not.toHaveBeenCalled();+ });+ it("consumes a successful code once and never exports runtime grants", async () => {+ const start = await authorize();+ const snapshot = await service.integrationSnapshot(); expect(snapshot.connections.find(c => c.provider === "google-search-console")?.state).toBe("authorized");+ expect(JSON.stringify(snapshot)).not.toMatch(/TEST_ACCESS|TEST_REFRESH|TEST_CLIENT_SECRET/);+ const { exportIntegrationData } = await import("./portable/data");+ const exported = JSON.stringify(await exportIntegrationData()); expect(exported).not.toMatch(/TEST_ACCESS|TEST_REFRESH|TEST_CLIENT_SECRET|googleOAuth|googlePending/);+ await expect(flow.completeGoogleAuthorization(start.state, start.binding, "TEST_CODE_AGAIN")).rejects.toThrow("expired_or_invalid");+ expect(fetch).toHaveBeenCalledTimes(2);+ });+ it("does not replace an account after a mismatched reconnect", async () => {+ await authorize(); const next = await begin();+ vi.mocked(fetch).mockResolvedValueOnce(response(tokenResponse())).mockResolvedValueOnce(response({ ...accountResponse(), sub: "another-user" }));+ await expect(flow.completeGoogleAuthorization(next.state, next.binding, "TEST_CODE_2")).rejects.toThrow("account_changed_disconnect_first");+ expect((await service.resolveIntegration("google-search-console", selector)).google?.account?.email).toBe("[email protected]");+ });+ it.each(["expired", "rotated-app", "role-revoked", "epoch-revoked"])("rejects a %s flow before token exchange", async kind => {+ const start = await begin();+ if (kind === "expired") await storage.mutateIntegrationState(d => { d.users[selector.user].connections["google-search-console"].search.googlePending!.expiresAt = 1; });+ if (kind === "rotated-app") await storage.mutateIntegrationState(d => { d.users[selector.user].connections["google-oauth-app"].app.revision++; });+ if (kind === "role-revoked") security.role = "operator";+ if (kind === "epoch-revoked") security.epoch = "another-cookie-epoch-123456";+ await expect(flow.completeGoogleAuthorization(start.state, start.binding, "TEST_CODE")).rejects.toThrow(); expect(fetch).not.toHaveBeenCalled();+ });+ it("denial consumes the authorization without losing an older grant", async () => {+ await authorize(); const next = await begin();+ await expect(flow.completeGoogleAuthorization(next.state, next.binding, undefined, true)).rejects.toThrow("consent_denied");+ expect(fetch).toHaveBeenCalledTimes(2);+ expect((await service.resolveIntegration("google-search-console", selector)).state).toBe("authorized");+ });+ it("refreshes expired access and only marks verified after an actual API response", async () => {+ await authorize(); await storage.mutateIntegrationState(d => { d.users[selector.user].connections["google-search-console"].search.googleOAuth!.expiresAt = 1; });+ vi.mocked(fetch).mockResolvedValueOnce(response({ ...tokenResponse(), refresh_token: undefined, scope: undefined })).mockResolvedValueOnce(response({ siteEntry: [] }));+ expect((await native.verifyNativeGoogle("google-search-console", selector)).ok).toBe(true);+ expect((await service.resolveIntegration("google-search-console", selector)).state).toBe("verified");+ expect(String(vi.mocked(fetch).mock.calls[2][1]?.body)).toContain("grant_type=refresh_token");+ });+ it("invalid_grant creates an actionable reconnect state without exposing the provider response", async () => {+ await authorize(); await storage.mutateIntegrationState(d => { d.users[selector.user].connections["google-search-console"].search.googleOAuth!.expiresAt = 1; });+ vi.mocked(fetch).mockResolvedValueOnce(response({ error: "invalid_grant", error_description: "TEST_REFRESH_NOT_REAL_123456" }, 400));+ const result = await native.verifyNativeGoogle("google-search-console", selector); expect(result.ok).toBe(false); expect(result.detail).toBe("google_reauthorization_required");+ expect((await service.resolveIntegration("google-search-console", selector)).state).toBe("reauthorization-required");+ });+ it.each([403, 503])("does not keep a stale green status after verification HTTP %s", async status => {+ await authorize(); vi.mocked(fetch).mockResolvedValueOnce(response({ siteEntry: [] }));+ expect((await native.verifyNativeGoogle("google-search-console", selector)).ok).toBe(true);+ vi.mocked(fetch).mockResolvedValueOnce(response({ error: "synthetic_failure" }, status));+ expect((await native.verifyNativeGoogle("google-search-console", selector)).ok).toBe(false);+ expect((await service.resolveIntegration("google-search-console", selector)).state).toBe(status === 403 ? "invalid" : "unavailable");+ expect((await storage.readIntegrationState()).users[selector.user].connections["google-search-console"].search.googleOAuth?.state).toBe("connected");+ });+ it("local disconnect is explicit and does not claim provider revocation", async () => {+ await authorize(); const result = await native.disconnectGoogle("google-search-console", selector);+ expect(result).toMatchObject({ disconnectedLocally: true, providerRevoked: false });+ await expect(native.runNativeGoogle("google-search-console", selector, "google.searchConsole.sites.list", {})).rejects.toThrow("reauthorization_required");+ });+ it("copied identities do not carry user authorization; sharing is refused", async () => {+ await authorize(); const { integrationManage } = await import("./connection-manage");+ await integrationManage({ action: "user.duplicate", user: selector.user, target: "other-owner", copyCredentials: true, confirm: true });+ expect((await storage.readIntegrationState()).users["other-owner"].connections["google-search-console"].search.googleOAuth).toBeUndefined();+ await expect(integrationManage({ action: "connection.share", ...selector, provider: "google-search-console", target: "other-owner", confirm: true })).rejects.toThrow("google_shared_authorization_not_supported");+ });+ it("saving app setup is configuration-only and requires no fabricated live credential probe", async () => {+ const setup = await import("./setup-capability");+ const opened = await setup.openIntegrationSetup("google-oauth-app", "test-operator", "oauth-app", { ...selector, connection: "app" });+ expect(opened.setup.redirectUri).toBe("https://mso.example.test/api/integrations/google/callback");+ const saved = await setup.consumeIntegrationSetup(opened.token, { clientId: "987654321-test.apps.googleusercontent.com" });+ expect(saved).toMatchObject({ verified: false, configurationOnly: true }); expect(fetch).not.toHaveBeenCalled();+ await expect(setup.openIntegrationSetup("google-search-console", "test-operator", "oauth2", selector)).rejects.toThrow("google_use_native_authorization");+ });+});diff --git a/lib/infra/google-native.ts b/lib/infra/google-native.tsnew file mode 100644index 00000000..819179d1--- /dev/null+++ b/lib/infra/google-native.ts@@ -0,0 +1,77 @@+import { mutateIntegrationState, readIntegrationState } from "./connection-storage";+import { GOOGLE_APP_PROVIDER, isGoogleProvider, googleRedirectUri } from "./google-native-config";+import { googleTarget, googleApp, assertGoogleGrantApp, clearGoogleRuntime, googleConnectionMetadata } from "./google-native-state";+import { acquireGoogleLease, pinGoogle, releaseGoogleLease } from "./google-native-lease";+import { IntegrationError, assertNotBusy, identity, type ConnectionSelector } from "./identity";+import { refreshGoogleTokens } from "./google-oauth-http";+import { executeGoogleRead, GOOGLE_READ_OPERATIONS } from "./google-api";+import type { GoogleProvider } from "./google-native-types";++export async function bindGoogleApp(provider: GoogleProvider, selection: ConnectionSelector, appConnection: unknown) {+ return mutateIntegrationState(d => {+ const { c, user } = googleTarget(d, provider, selection), app = googleApp(d, user, identity(appConnection, "app_connection"));+ assertNotBusy(c); assertNotBusy(app);+ if (c.values.appConnection !== app.id) {+ if (c.googleOAuth) throw new IntegrationError("google_disconnect_before_app_change", 409);+ c.values = { appConnection: app.id }; clearGoogleRuntime(c); c.revision++; c.updatedAt = Date.now(); delete c.lastCheck; delete c.verifiedAt;+ }+ return { user, provider, connection: c.id, ...googleConnectionMetadata(d, user, c) };+ });+}+export async function disconnectGoogle(provider: GoogleProvider, selection: ConnectionSelector) {+ return mutateIntegrationState(d => {+ const { c, user } = googleTarget(d, provider, selection); assertNotBusy(c); clearGoogleRuntime(c); c.revision++; c.updatedAt = Date.now(); delete c.verifiedAt; delete c.lastCheck;+ return { user, provider, connection: c.id, disconnectedLocally: true, providerRevoked: false, detail: "MSO authorization removed. To revoke the Google app itself, review Google Account third-party connections." };+ });+}+export async function runNativeGoogle(provider: GoogleProvider, selection: ConnectionSelector, operation: string, args: Record<string, unknown>, verify = false) {+ const lease = await mutateIntegrationState(d => {+ const { c, user } = googleTarget(d, provider, selection), app = googleApp(d, user, c.values.appConnection);+ const grant = assertGoogleGrantApp(c, app); if (grant.redirectUri !== googleRedirectUri()) throw new IntegrationError("google_reauthorization_required", 401);+ if (c.googlePending && c.googlePending.expiresAt > Date.now()) throw new IntegrationError("google_authorization_pending", 409);+ return acquireGoogleLease(d, provider, selection);+ });+ try {+ let grant = lease.c.googleOAuth!;+ if (grant.expiresAt <= Date.now() + 60_000) {+ const refreshed = await refreshGoogleTokens(lease.app.values, provider, grant.refreshToken, grant.scopes);+ grant = { ...grant, ...refreshed, updatedAt: Date.now() };+ await mutateIntegrationState(d => { pinGoogle(d, lease).c.googleOAuth = grant; });+ }+ const result = await executeGoogleRead(provider, grant.accessToken, operation, args);+ await mutateIntegrationState(d => {+ const { c } = pinGoogle(d, lease);+ if (verify) { c.lastCheck = { revision: c.revision, checkedAt: Date.now(), result: "verified" }; c.verifiedAt = Date.now(); }+ });+ return { user: lease.user, provider, connection: lease.connection, source: "direct", authMethod: "oauth2", readOnly: true, result };+ } catch (error) {+ if (error instanceof IntegrationError && ["google_reauthorization_required", "google_required_scope_missing"].includes(error.code)) await mutateIntegrationState(d => {+ const { c } = pinGoogle(d, lease);+ if (c.googleOAuth) c.googleOAuth = { ...c.googleOAuth, accessToken: "", refreshToken: "", state: "reauthorization-required", updatedAt: Date.now() };+ delete c.verifiedAt; c.lastCheck = { revision: c.revision, checkedAt: Date.now(), result: "invalid" };+ });+ else if (verify) await mutateIntegrationState(d => {+ const { c } = pinGoogle(d, lease);+ delete c.verifiedAt;+ c.lastCheck = { revision: c.revision, checkedAt: Date.now(), result: error instanceof IntegrationError && error.status === 403 ? "invalid" : "unavailable" };+ });+ throw error;+ } finally { await releaseGoogleLease(lease); }+}+export async function verifyNativeGoogle(provider: GoogleProvider, selection: ConnectionSelector) {+ try {+ const operation = provider === "google-search-console" ? "google.searchConsole.sites.list" : "google.analytics.accountSummaries.list";+ await runNativeGoogle(provider, selection, operation, {}, true);+ return { id: provider, ok: true, detail: "Native Google read-only API access verified. Select an exact returned property before reporting." };+ } catch (error) { return { id: provider, ok: false, detail: error instanceof IntegrationError ? error.code : "google_verification_unavailable" }; }+}+export async function nativeGoogleStatus(provider: GoogleProvider | typeof GOOGLE_APP_PROVIDER, selection: ConnectionSelector) {+ if (provider === GOOGLE_APP_PROVIDER) {+ const d = await readIntegrationState();+ try { googleApp(d, identity(selection.user, "user"), identity(selection.connection, "connection")); return { id: provider, ok: null, detail: "App configuration stored; validate by completing Google consent, not an app-only probe." }; }+ catch { return { id: provider, ok: null, detail: "google_app_setup_required" }; }+ }+ if (!isGoogleProvider(provider)) throw new IntegrationError("unknown_google_provider");+ return verifyNativeGoogle(provider, selection);+}+export function googleOperations(provider: string) { return GOOGLE_READ_OPERATIONS.filter(row => row.provider === provider); }diff --git a/lib/infra/google-oauth-flow.ts b/lib/infra/google-oauth-flow.tsnew file mode 100644index 00000000..03b28302--- /dev/null+++ b/lib/infra/google-oauth-flow.ts@@ -0,0 +1,71 @@+import { createHash, randomBytes } from "node:crypto";+import { currentSessionPolicy, getApprovedDevice } from "@/lib/auth/device-store";+import { configuredSessionCookieScope } from "@/lib/auth/session-cookie";+import { mutateIntegrationState } from "./connection-storage";+import { assertNotBusy, IntegrationError, type ConnectionSelector } from "./identity";+import { googleTarget, googleApp } from "./google-native-state";+import { GOOGLE_SCOPES, googleRedirectUri, isGoogleProvider } from "./google-native-config";+import { acquireGoogleLease, pinGoogle, releaseGoogleLease } from "./google-native-lease";+import { exchangeGoogleCode } from "./google-oauth-http";+import type { GoogleActor, GoogleProvider } from "./google-native-types";+export const GOOGLE_FLOW_TTL = 10 * 60_000;+const hash = (text: string) => createHash("sha256").update(text).digest("hex");+export const googleFlowCookie = (state: string) => "__Host-mso-google-" + hash(state).slice(0, 16);+const invalid = () => new IntegrationError("google_authorization_expired_or_invalid", 401);+export async function assertGoogleActor(actor: GoogleActor) {+ if (!actor.deviceId || actor.sessionExpiresAt <= Date.now() || actor.cookieScope !== configuredSessionCookieScope()) throw invalid();+ const policy = await currentSessionPolicy(actor.cookieScope), device = await getApprovedDevice(actor.deviceId);+ if (policy.epoch !== actor.cookieEpoch || device?.role !== "owner") throw invalid();+}+export async function beginGoogleAuthorization(provider: GoogleProvider, selection: ConnectionSelector, actor: GoogleActor) {+ await assertGoogleActor(actor);+ const redirectUri = googleRedirectUri(), state = randomBytes(32).toString("base64url"), binding = randomBytes(32).toString("base64url"), verifier = randomBytes(48).toString("base64url");+ const result = await mutateIntegrationState(d => {+ const { user, c } = googleTarget(d, provider, selection), app = googleApp(d, user, c.values.appConnection);+ assertNotBusy(c); assertNotBusy(app);+ c.googlePending = { stateHash: hash(state), bindingHash: hash(binding), verifier, expiresAt: Date.now() + GOOGLE_FLOW_TTL,+ redirectUri, connectionUid: c.uid, connectionRevision: c.revision, appConnection: app.id, appUid: app.uid, appRevision: app.revision, actor };+ return { clientId: app.values.clientId, email: c.googleOAuth?.email };+ });+ const url = new URL("https://accounts.google.com/o/oauth2/v2/auth");+ const params = { client_id: result.clientId, redirect_uri: redirectUri, response_type: "code", access_type: "offline", prompt: "consent select_account", scope: `openid email ${GOOGLE_SCOPES[provider]}`,+ state, code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256" };+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);+ if (result.email) url.searchParams.set("login_hint", result.email);+ // Returned only to the authenticated native browser start route, never an MCP tool response.+ return { authorizationUrl: url.href, cookieName: googleFlowCookie(state), binding, expiresIn: GOOGLE_FLOW_TTL / 1000 };+}+export async function completeGoogleAuthorization(state: string, binding: string, code?: string, denied = false) {+ if (!/^[A-Za-z0-9_-]{43}$/.test(state) || !/^[A-Za-z0-9_-]{43}$/.test(binding) || (!denied && (typeof code !== "string" || !code || code.length > 4096 || /[\x00-\x20\x7f]/.test(code)))) throw invalid();+ const claimed = await mutateIntegrationState(d => {+ for (const [user, owner] of Object.entries(d.users)) for (const [provider, rows] of Object.entries(owner.connections)) {+ if (!isGoogleProvider(provider)) continue;+ for (const c of Object.values(rows)) {+ const p = c.googlePending;+ if (!p || p.stateHash !== hash(state)) continue;+ if (p.bindingHash !== hash(binding) || p.expiresAt <= Date.now() || p.redirectUri !== googleRedirectUri() || p.connectionUid !== c.uid || p.connectionRevision !== c.revision) throw invalid();+ const app = googleApp(d, user, c.values.appConnection);+ if (app.id !== p.appConnection || app.uid !== p.appUid || app.revision !== p.appRevision) throw invalid();+ const lease = acquireGoogleLease(d, provider, { user, connection: c.id });+ delete c.googlePending; // Consume once, before contacting Google; failure needs a fresh authorization.+ return { lease, pending: p };+ }+ }+ throw invalid();+ });+ const { lease, pending } = claimed;+ try {+ await assertGoogleActor(pending.actor);+ if (denied) throw new IntegrationError("google_consent_denied", 403);+ const tokens = await exchangeGoogleCode(lease.app.values, lease.provider, code!, pending.verifier);+ if (lease.c.googleOAuth?.subject && lease.c.googleOAuth.subject !== tokens.subject) throw new IntegrationError("google_account_changed_disconnect_first", 409);+ await assertGoogleActor(pending.actor);+ await mutateIntegrationState(d => {+ const { c, app } = pinGoogle(d, lease);+ if (pending.expiresAt <= Date.now() || pending.redirectUri !== googleRedirectUri()) throw invalid();+ c.googleOAuth = { ...tokens, appConnection: app.id, appUid: app.uid, appRevision: app.revision, redirectUri: pending.redirectUri, state: "connected", updatedAt: Date.now() };+ c.revision++; c.updatedAt = Date.now(); delete c.lastCheck; delete c.verifiedAt;+ });+ return { user: lease.user, provider: lease.provider, connection: lease.connection, status: "authorized", verificationRequired: true };+ } finally { await releaseGoogleLease(lease); }+}diff --git a/lib/infra/google-oauth-http.ts b/lib/infra/google-oauth-http.tsnew file mode 100644index 00000000..0d66de1a--- /dev/null+++ b/lib/infra/google-oauth-http.ts@@ -0,0 +1,45 @@+import { IntegrationError } from "./identity";+import { GOOGLE_SCOPES, googleRedirectUri } from "./google-native-config";+import type { GoogleProvider } from "./google-native-types";++const TOKEN_URL = "https://oauth2.googleapis.com/token";+const USERINFO_URL = "https://openidconnect.googleapis.com/v1/userinfo";+const MAX_BYTES = 64 * 1024;+async function googleJson(url: typeof TOKEN_URL | typeof USERINFO_URL, init: RequestInit): Promise<Record<string, unknown>> {+ try {+ const response = await fetch(url, { ...init, redirect: "error", signal: AbortSignal.timeout(15_000), cache: "no-store" });+ if (Number(response.headers.get("content-length")) > MAX_BYTES) throw new IntegrationError("google_oauth_response_too_large", 502);+ const reader = response.body?.getReader(); if (!reader) throw new IntegrationError("google_oauth_invalid_response", 502);+ const chunks: Uint8Array[] = []; let bytes = 0;+ try { for (;;) { const part = await reader.read(); if (part.done) break; bytes += part.value.byteLength; if (bytes > MAX_BYTES) throw new IntegrationError("google_oauth_response_too_large", 502); chunks.push(part.value); } }+ finally { await reader.cancel().catch(() => undefined); reader.releaseLock(); }+ let data: unknown; try { data = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { throw new IntegrationError("google_oauth_invalid_response", 502); }+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new IntegrationError("google_oauth_invalid_response", 502);+ const row = data as Record<string, unknown>;+ if (!response.ok) throw new IntegrationError(row.error === "invalid_grant" ? "google_reauthorization_required" : response.status === 429 ? "google_oauth_rate_limited" : "google_oauth_request_failed", response.status === 429 ? 429 : 502);+ return row;+ } catch (error) { throw error instanceof IntegrationError ? error : new IntegrationError("google_oauth_unavailable", 502); }+}+function token(value: unknown): value is string { return typeof value === "string" && value.length > 10 && value.length <= 16_384 && !/[\s\x00-\x1f\x7f]/.test(value); }+export function googleTokenResult(data: Record<string, unknown>, provider: GoogleProvider, previousRefresh?: string) {+ const scopes = typeof data.scope === "string" ? data.scope.split(/\s+/).filter(Boolean) : [];+ if (!scopes.includes(GOOGLE_SCOPES[provider])) throw new IntegrationError("google_required_scope_missing", 403);+ if (!token(data.access_token) || String(data.token_type).toLowerCase() !== "bearer" || !Number.isFinite(data.expires_in) || Number(data.expires_in) < 30 || Number(data.expires_in) > 86400) throw new IntegrationError("google_oauth_invalid_tokens", 502);+ const refresh = data.refresh_token ?? previousRefresh;+ if (!token(refresh)) throw new IntegrationError("google_offline_access_required", 409);+ return { accessToken: data.access_token, refreshToken: refresh, expiresAt: Date.now() + Number(data.expires_in) * 1000, scopes };+}+export async function exchangeGoogleCode(app: Record<string, string>, provider: GoogleProvider, code: string, verifier: string) {+ const data = await googleJson(TOKEN_URL, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },+ body: new URLSearchParams({ client_id: app.clientId, client_secret: app.clientSecret, redirect_uri: googleRedirectUri(), grant_type: "authorization_code", code, code_verifier: verifier }) });+ const tokens = googleTokenResult(data, provider);+ const info = await googleJson(USERINFO_URL, { headers: { Authorization: `Bearer ${tokens.accessToken}`, Accept: "application/json" } });+ if (typeof info.sub !== "string" || !/^[A-Za-z0-9_-]{1,255}$/.test(info.sub) || typeof info.email !== "string" || info.email.length > 320 || !/^[^\s<>@]+@[^\s<>@]+$/.test(info.email) || info.email_verified !== true) throw new IntegrationError("google_identity_unverified", 403);+ return { ...tokens, subject: info.sub, email: info.email };+}+export async function refreshGoogleTokens(app: Record<string, string>, provider: GoogleProvider, refreshToken: string, grantedScopes: string[]) {+ const data = await googleJson(TOKEN_URL, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },+ body: new URLSearchParams({ client_id: app.clientId, client_secret: app.clientSecret, grant_type: "refresh_token", refresh_token: refreshToken }) });+ // RFC 6749 permits omitted scope when unchanged. The pinned previous grant is the fallback.+ return googleTokenResult({ ...data, scope: data.scope ?? grantedScopes.join(" ") }, provider, refreshToken);+}diff --git a/lib/infra/google-routes.test.ts b/lib/infra/google-routes.test.tsnew file mode 100644index 00000000..f8b284c7--- /dev/null+++ b/lib/infra/google-routes.test.ts@@ -0,0 +1,59 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+const mocks = vi.hoisted(() => ({ context: vi.fn(), begin: vi.fn(), complete: vi.fn(), audit: vi.fn() }));+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: mocks.context }));+vi.mock("@/lib/infra/google-oauth-flow", () => ({ beginGoogleAuthorization: mocks.begin, completeGoogleAuthorization: mocks.complete, googleFlowCookie: () => "__Host-mso-google-test" }));+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));+import { POST } from "@/app/api/integrations/google/start/route";+import { GET } from "@/app/api/integrations/google/callback/route";+const origin = "https://mso.example.test";+const actor = { role: "owner", session: { device_id: "test-device", cookie_scope: "host", cookie_epoch: "test-epoch-123456789", expires_at: 9999999999999 } };+beforeEach(() => {+ vi.clearAllMocks(); vi.stubEnv("OS_PUBLIC_ORIGIN", origin);+ mocks.context.mockResolvedValue(actor);+ mocks.begin.mockResolvedValue({ authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=TEST", cookieName: "__Host-mso-google-test", binding: "b".repeat(43), expiresIn: 600 });+ mocks.complete.mockResolvedValue({ status: "authorized" }); mocks.audit.mockResolvedValue(undefined);+});+afterEach(() => vi.unstubAllEnvs());+const request = (body: unknown = { user: "test-owner", provider: "google-search-console", connection: "search" }, headers: Record<string, string> = {}) => new NextRequest(origin + "/api/integrations/google/start", { method: "POST", headers: { host: "mso.example.test", origin, "content-type": "application/json", ...headers }, body: JSON.stringify(body) });+const callback = (query: string, cookie = "__Host-mso-google-test=" + "b".repeat(43)) => new NextRequest(origin + "/api/integrations/google/callback?" + query, { headers: { host: "mso.example.test", cookie } });+describe("native OAuth HTTP boundary", () => {+ it.each([null, { ...actor, role: "operator" }, { ...actor, role: "viewer" }])("denies non-owner start %j", async context => {+ mocks.context.mockResolvedValue(context); expect((await POST(request())).status).toBe(403); expect(mocks.begin).not.toHaveBeenCalled();+ });+ it("requires the configured native origin, not untrusted forwarded hosts", async () => {+ expect((await POST(request(undefined, { origin: "https://evil.test", "x-forwarded-host": "mso.example.test" }))).status).toBe(403);+ expect((await POST(request(undefined, { host: "evil.test" }))).status).toBe(403); expect(mocks.begin).not.toHaveBeenCalled();+ });+ it("sets a host-only finite HttpOnly/Secure/Lax binding without changing the main session cookie", async () => {+ const result = await POST(request()), cookie = result.headers.get("set-cookie")!;+ expect(result.status).toBe(200); expect(cookie).toContain("__Host-mso-google-test=");+ for (const attr of ["HttpOnly", "Secure", "SameSite=lax", "Max-Age=600", "Path=/"]) expect(cookie).toContain(attr);+ expect(cookie).not.toContain("Domain="); expect(cookie).not.toContain("session=");+ expect(result.headers.get("cache-control")).toContain("no-store");+ expect(JSON.stringify(mocks.audit.mock.calls)).not.toContain("state=");+ });+ it("refuses secret-bearing start input instead of accepting a copied browser session", async () => {+ const result = await POST(request({ user: "test-owner", provider: "google-search-console", connection: "search", accessToken: "NOT_REAL" }));+ expect(result.status).toBe(400); expect(mocks.begin).not.toHaveBeenCalled();+ });+ it("redirects a completed callback to a clean, fixed native URL", async () => {+ const state = "s".repeat(43), result = await GET(callback("state=" + state + "&code=TEST_CODE&returnTo=https://evil.test"));+ expect(result.status).toBe(303); expect(result.headers.get("location")).toBe(origin + "/integrations?google=authorized");+ expect(result.headers.get("set-cookie")).toContain("Max-Age=0");+ expect(result.headers.get("referrer-policy")).toBe("no-referrer");+ expect(JSON.stringify([...result.headers])).not.toContain("TEST_CODE");+ });+ it.each(["state=short&code=TEST", "state=" + "s".repeat(43) + "&state=other&code=TEST", "state=" + "s".repeat(43) + "&code=A&code=B", "state=" + "s".repeat(43) + "&code=A&error=denied", "state=" + "s".repeat(43) + "&iss=https://evil.test&code=A"])("rejects malformed callback parameters without reflecting them", async query => {+ const result = await GET(callback(query)); expect(result.headers.get("location")).toBe(origin + "/integrations?google=retry"); expect(mocks.complete).not.toHaveBeenCalled();+ });+ it("refuses missing or duplicate browser bindings", async () => {+ const query = "state=" + "s".repeat(43) + "&code=TEST";+ await GET(callback(query, "")); expect(mocks.complete).not.toHaveBeenCalled();+ });+ it("does not expose raw failures or user codes in redirects", async () => {+ mocks.complete.mockRejectedValue(new Error("PRIVATE_TOKEN_FROM_UPSTREAM"));+ const result = await GET(callback("state=" + "s".repeat(43) + "&code=PRIVATE_CODE"));+ expect(result.headers.get("location")).toBe(origin + "/integrations?google=retry"); expect(await result.text()).not.toContain("PRIVATE");+ });+});diff --git a/lib/infra/identity.ts b/lib/infra/identity.tsindex 12bed480..f103e44e 100644--- a/lib/infra/identity.ts+++ b/lib/infra/identity.ts@@ -1,3 +1,4 @@+import type { GoogleGrant, GooglePending } from "./google-native-types";import { randomUUID } from "node:crypto";import path from "node:path";import { realpathSync } from "node:fs";@@ -8,6 +9,8 @@ export type ExternalIdentity = { toolkit?: string; connectedAccountId?: string;export type IntegrationConnection = {id: string; uid: string; label: string; provider: string; source: ConnectionSource; authMethod: string;scope: string; revision: number; values: Record<string,string>; /** Read-only alias of another direct connection. */ sharedFrom?: { user: string; connection: string; provider: string }; external?: ExternalIdentity;+ /** Private runtime authorization; never copied into metadata or portable bundles. */+ googleOAuth?: GoogleGrant; googlePending?: GooglePending;createdAt: number; updatedAt: number; verifiedAt?: number;lastCheck?: { revision: number; checkedAt: number; result: "verified" | "invalid" | "unavailable" | "unconfigured" }; lease?: {id:string;until:number};};@@ -58,7 +61,7 @@ export function metadataOnly(value: unknown, depth = 0): void {if (depth > 12) throw new IntegrationError("metadata_too_deep");if (!value || typeof value !== "object") return;for (const [k,v] of Object.entries(value)) {- if (/^(values?|secrets?|secretValue|password|passphrase|token|apiKey|apiToken|accessToken|refreshToken|authorization|headers|__proto__|constructor|prototype)$/i.test(k)) throw new IntegrationError("secret_input_forbidden");+ if (/^(values?|secrets?|secretValue|password|passphrase|token|apiKey|apiToken|accessToken|refreshToken|authorization|headers|clientSecret|client_secret|access_token|refresh_token|id_token|codeVerifier|code_verifier|googleOAuth|googlePending|__proto__|constructor|prototype)$/i.test(k)) throw new IntegrationError("secret_input_forbidden");metadataOnly(v,depth+1);}}diff --git a/lib/infra/portable/mapping.ts b/lib/infra/portable/mapping.tsindex 6d742d05..928ea981 100644--- a/lib/infra/portable/mapping.ts+++ b/lib/infra/portable/mapping.ts@@ -1,5 +1,8 @@// Wire names are stable environment-key identifiers; native storage remains independent.export const FIELD_MAP:Record<string,Record<string,string>>={+ 'google-oauth-app':{GOOGLE_CLIENT_ID:'clientId',GOOGLE_CLIENT_SECRET:'clientSecret'},+ 'google-search-console':{GOOGLE_APP_CONNECTION:'appConnection'},+ 'google-analytics':{GOOGLE_APP_CONNECTION:'appConnection'},github:{GITHUB_TOKEN:'apiKey',GH_OWNER:'owner'},dokploy:{DOKPLOY_API_URL:'apiUrl',DOKPLOY_API_KEY:'apiKey',DOKPLOY_PUBLIC_IP:'publicIp'},cloudflare:{CLOUDFLARE_API_TOKEN:'apiToken',CLOUDFLARE_ZONE_ID:'zoneId',CLOUDFLARE_ACCOUNT_ID:'accountId'},diff --git a/lib/infra/setup-browser.ts b/lib/infra/setup-browser.tsindex e3ec2b63..e3d1938e 100644--- a/lib/infra/setup-browser.ts+++ b/lib/infra/setup-browser.ts@@ -1,6 +1,6 @@export const INTEGRATION_BROWSER_SCRIPT=String.raw`(async()=>{- const root=document.getElementById("setup"),endpoint=location.origin+"/api/integrations/setup",params=new URLSearchParams(location.search);let cleanup=()=>{},state={...(params.get("section")==="ai-providers"?{section:"ai-providers"}:{})},authController,wantsTransfer=params.get("transfer")==="1";+ const root=document.getElementById("setup"),endpoint=location.origin+"/api/integrations/setup",params=new URLSearchParams(location.search);let cleanup=()=>{},state={...(params.get("user")?{user:params.get("user")}:{ }),...(params.get("provider")?{provider:params.get("provider")}:{ }),...(params.get("section")==="ai-providers"?{section:"ai-providers"}:{})},authController,wantsTransfer=params.get("transfer")==="1";const error=data=>{const e=new Error(data.error||"integration_operation_failed");e.code=data.error;return e};async function json(url,init){const r=await fetch(url,{credentials:"same-origin",cache:"no-store",referrerPolicy:"no-referrer",...init});const data=await r.json();if(!r.ok)throw error(data);return data}const post=(mode,input)=>json("/api/v1/integrations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode,...input})});@@ -21,6 +21,7 @@ export const INTEGRATION_BROWSER_SCRIPT=String.raw`bridge.projectMcp=args=>json("/api/v1/project-mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(args)});bridge.query=args=>json("/api/v1/integrations?"+new URLSearchParams(args));bridge.manage=args=>post("manage",args);bridge.execute=args=>post("execute",args);+ bridge.googleAuthorize=body=>json("/api/integrations/google/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});bridge.aiConfig=()=>json("/api/config");bridge.aiCatalog=()=>json("/api/models/providers");bridge.aiModels=provider=>json("/api/models?provider="+encodeURIComponent(provider));bridge.aiSave=body=>json("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});bridge.aiRemove=provider=>json("/api/config?provider="+encodeURIComponent(provider),{method:"DELETE"});bridge.aiTest=()=>json("/api/models/test",{method:"POST"});bridge.aiOauth=body=>json("/api/oauth/openai",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});@@ -28,6 +29,8 @@ export const INTEGRATION_BROWSER_SCRIPT=String.raw`}if(owner&&wantsTransfer){openTransfer();return}cleanup=mountConnectionManager(root,INTEGRATIONS_CATALOG,bridge,state);+ if(params.get("google")===("authorized"))root.prepend(integrationNode("p","Google authorization completed. Choose the connection and verify API access; no property has been selected automatically."));+ else if(params.get("google")===("retry"))root.prepend(integrationNode("p","Google authorization was not completed. Retry from the intended connection after reviewing app setup, permissions, and account identity."));if(!owner&&authenticated)root.prepend(integrationNode("p","This device has "+role+" access. An Owner must approve Owner access before it can manage integrations."));if(!owner&&!authenticated){const link=integrationNode("a","Sign in to MSO as Owner");link.href="/login?returnTo=%2Fintegrations";link.className="primary integration-signin";link.target="_blank";link.rel="noopener noreferrer";root.prepend(link);const refresh=()=>{if(document.visibilityState!=="hidden")void loadManager()};document.addEventListener("visibilitychange",refresh,{signal:authController.signal});window.addEventListener("focus",refresh,{signal:authController.signal});}}diff --git a/lib/infra/setup-capability.ts b/lib/infra/setup-capability.tsindex 0bfc837f..148418aa 100644--- a/lib/infra/setup-capability.ts+++ b/lib/infra/setup-capability.ts@@ -1,3 +1,4 @@+import { GOOGLE_APP_PROVIDER, googleRedirectUri, isGoogleProvider } from "./google-native-config";import { createHash, randomBytes } from "node:crypto";import { constants, promises as fs } from "node:fs";import path from "node:path";@@ -50,15 +51,18 @@ async function target(g: Grant) {}async function schema(g: Grant) {const c=await target(g),method=connectionMethod(g.provider,"direct",g.method);+ let redirectUri: string | undefined;+ if(g.provider===GOOGLE_APP_PROVIDER)try{redirectUri=googleRedirectUri()}catch{}return {user:g.user,connection:c.id,label:c.label,source:c.source,authMethod:c.authMethod,scope:c.scope,provider:g.provider,title:getInfraProviderDefinition(g.provider).title,method:g.method,- expiresAt:g.expiresAt,store:"MSO named connection · owner-only permissions (0600)",+ ...(redirectUri?{redirectUri}:{}),expiresAt:g.expiresAt,store:"MSO named connection · owner-only permissions (0600)",fields:method.fields.map(f=>({...f,stored:Boolean(c.values[f.key])})),guidance:method.guidance,};}export async function openIntegrationSetup(provider: string, principal: string, method?: string, selection:ConnectionSelector={}) {if (!isInfraProviderId(provider)) throw new SetupError("unknown_provider", 400);+ if (isGoogleProvider(provider)) throw new SetupError("google_use_native_authorization", 409);if (!principal || principal.length > 256) throw new SetupError("authenticated_principal_required", 403);// A UI must never guess which user's deployment to rotate.if(!selection.user||!selection.connection)throw new SetupError("choose_user_and_connection",409);@@ -106,12 +110,13 @@ export async function consumeIntegrationSetup(token: string, raw: unknown) {await fs.writeFile(file, JSON.stringify(grant), { mode: 0o600 });// Probe candidate values before mutating the real store. Only safe enums/status// escape this boundary, never provider response text or credential values.- const result = await doctorInfraProvider(grant.provider, candidate);+ const configurationOnly = grant.provider === GOOGLE_APP_PROVIDER;+ const result = configurationOnly ? { ok: true } : await doctorInfraProvider(grant.provider, candidate);if (result.ok !== true) throw new SetupError(result.ok === null ? "live_validation_unavailable" : "credential_validation_failed", 422);if (grant.expiresAt <= Date.now()) throw invalid();grant.used = true;await fs.writeFile(file, JSON.stringify(grant), { mode: 0o600 });- await saveConnectionValues(grant.provider,{user:grant.user,connection:grant.connection},updates,{uid:grant.uid,revision:grant.revision},true);- return { ok: true, verified: true, provider: grant.provider,user:grant.user,connection:grant.connection,principal: grant.principal };+ await saveConnectionValues(grant.provider,{user:grant.user,connection:grant.connection},updates,{uid:grant.uid,revision:grant.revision},!configurationOnly);+ return { ok: true, verified: !configurationOnly, configurationOnly, provider: grant.provider,user:grant.user,connection:grant.connection,principal: grant.principal };});}diff --git a/lib/infra/setup-guidance.ts b/lib/infra/setup-guidance.tsindex 6532adc0..9a0e6d52 100644--- a/lib/infra/setup-guidance.ts+++ b/lib/infra/setup-guidance.ts@@ -1,9 +1,14 @@+import { GOOGLE_APP_PROVIDER, isGoogleProvider, googleGuidance } from "./google-native-config";import { ADDITIONAL_GUIDANCE, type AdditionalProviderId } from "./additional-providers";import { getInfraProviderDefinition } from "./catalog";import type { InfraProviderId } from "./types";-export type SetupMethod = "direct" | "project" | "organization" | "personal" | "deployment" | "mail" | "payment" | "mcp";+export type SetupMethod = "direct" | "project" | "organization" | "personal" | "deployment" | "mail" | "payment" | "mcp" | "oauth-app" | "oauth2";export function setupFields(provider: InfraProviderId, method: SetupMethod) {+ if (provider === GOOGLE_APP_PROVIDER || isGoogleProvider(provider)) {+ if (method !== (provider === GOOGLE_APP_PROVIDER ? "oauth-app" : "oauth2")) throw new Error("Unsupported Google authentication method");+ return getInfraProviderDefinition(provider).fields;+ }if (provider === "hostinger") {if (!["direct", "mail"].includes(method)) throw new Error("Choose Hostinger account or scoped Mail API token");const keys = method === "mail" ? ["mailApiToken", "mailOrderId"] : ["apiToken"];@@ -27,12 +32,14 @@ export function setupFields(provider: InfraProviderId, method: SetupMethod) {return getInfraProviderDefinition(provider).fields;}export function setupMethod(provider: InfraProviderId, method?: string): SetupMethod {- const value = method ?? (provider === "composio" ? "project" : provider === "convex-cloud" ? "personal" : provider === "doku" ? "mcp" : "direct");- if (!["direct", "project", "organization", "personal", "deployment", "mail", "payment", "mcp"].includes(value)) throw new Error("Unsupported authentication method");+ const value = method ?? (provider === GOOGLE_APP_PROVIDER ? "oauth-app" : isGoogleProvider(provider) ? "oauth2" : provider === "composio" ? "project" : provider === "convex-cloud" ? "personal" : provider === "doku" ? "mcp" : "direct");+ if (!["direct", "project", "organization", "personal", "deployment", "mail", "payment", "mcp", "oauth-app", "oauth2"].includes(value)) throw new Error("Unsupported authentication method");setupFields(provider, value as SetupMethod);return value as SetupMethod;}export function setupMethods(provider: InfraProviderId): Array<{id: SetupMethod; label: string}> {+ if (provider === GOOGLE_APP_PROVIDER) return [{ id: "oauth-app", label: "Google OAuth app (configuration only)" }];+ if (isGoogleProvider(provider)) return [{ id: "oauth2", label: "Native Google OAuth · read-only" }];if (provider === "hostinger") return [{ id: "direct", label: "Account API token" }, { id: "mail", label: "Scoped Mail API token" }];if (provider === "composio") return [{ id: "project", label: "Project API key" }, { id: "organization", label: "Organization API key" }];if (provider === "convex-cloud") return [{ id: "personal", label: "Personal access token" }, { id: "deployment", label: "Deployment key" }];@@ -40,6 +47,7 @@ export function setupMethods(provider: InfraProviderId): Array<{id: SetupMethod;return [{ id: "direct", label: "Direct credential" }];}export function setupGuidance(provider: InfraProviderId, method: SetupMethod) {+ if (provider === GOOGLE_APP_PROVIDER || isGoogleProvider(provider)) return googleGuidance(provider);if(provider==="doku")return method==="payment"?{url:"https://dashboard.doku.com/bo/developer/api-keys",reference:"https://developers.doku.com/get-started-with-doku-api/signature-component/non-snap/signature-component-from-request-header",steps:["Open DOKU Back Office → Developer → API Keys.","Use Client ID + Secret Key for the signed Non-SNAP payment API; the API Key is not a substitute for the HMAC Secret Key.","Choose sandbox first unless this project is explicitly approved for live payments.","Enter credentials only in this private setup form. MSO verifies them with a signed read-only status lookup before saving."]}:{url:"https://developers.doku.com/accept-payments/doku-mcp-server",reference:"https://developers.doku.com/accept-payments/doku-mcp-server",steps:["Open DOKU's official MCP Server guide and choose Sandbox first unless this project is explicitly approved for production payments.","Use the DOKU MCP Client ID + MCP API Key; do not substitute the Payment REST Secret Key.","Enter them only in this private setup form; do not paste them into chat, Baton notes, RR, Git, or project MCP JSON.","MSO calls the fixed official DOKU MCP endpoint with a read-only MCP initialize request before saving the connection."]};if (provider in ADDITIONAL_GUIDANCE) return ADDITIONAL_GUIDANCE[provider as AdditionalProviderId];const guides = {diff --git a/lib/infra/setup-ui.ts b/lib/infra/setup-ui.tsindex 88bfcd96..a3cd949d 100644--- a/lib/infra/setup-ui.ts+++ b/lib/infra/setup-ui.ts@@ -21,7 +21,7 @@ function mountIntegrationForm(root,setup,access){const back=()=>{if(typeof access?.onBack==="function"){const b=integrationNode("button","← All integrations");b.type="button";b.className="back-link";b.addEventListener("click",access.onBack);root.append(b)}};back();if(!token||!endpoint){root.append(integrationNode("h2","Secure form unavailable"),integrationNode("p","The chat host did not deliver private setup authorization. Reopen the form or use the browser entrypoint; never paste a credential into chat."));if(access?.openBrowser){const b=integrationNode("button","Open Integrations in browser");b.type="button";b.addEventListener("click",()=>access.openBrowser());root.append(b)}return()=>{root.replaceChildren();root.classList.remove("integration")}}const heading=integrationNode("h2",setup.title+" · "+(setup.label||setup.connection||"connection")),tag=integrationNode("span",setup.method+" · single-use session");tag.className="setup-tag";- root.append(tag,heading,integrationNode("p",[setup.user,setup.connection,setup.source,setup.scope].filter(Boolean).join(" → ")),integrationNode("p","API keys go directly to your MSO server. They are not sent to ChatGPT or saved in browser storage."));+ root.append(tag,heading,integrationNode("p",[setup.user,setup.connection,setup.source,setup.scope].filter(Boolean).join(" → ")),integrationNode("p","Credentials go directly to your MSO server. They are not sent to ChatGPT or saved in browser storage."));const grid=integrationNode("div"),form=integrationNode("form"),aside=integrationNode("aside");grid.className="setup-grid";form.autocomplete="off";form.setAttribute("action","#");const inputs=[];for(const f of setup.fields){@@ -31,9 +31,11 @@ function mountIntegrationForm(root,setup,access){if(f.secret){const toggle=integrationNode("button","Show");toggle.type="button";toggle.setAttribute("aria-label","Show or hide "+f.label);toggle.addEventListener("click",()=>{input.type=input.type==="password"?"text":"password";toggle.textContent=input.type==="password"?"Show":"Hide"});row.append(toggle)}wrap.append(label,row,integrationNode("small",f.description));form.append(wrap);}- const save=integrationNode("button","Validate & save"),status=integrationNode("p");save.type="button";save.className="primary";status.className="setup-status";status.setAttribute("role","status");status.setAttribute("aria-live","polite");form.append(save,status);+ const configurationOnly=setup.provider==="google-oauth-app";+ const save=integrationNode("button",configurationOnly?"Save OAuth app configuration":"Validate & save"),status=integrationNode("p");save.type="button";save.className="primary";status.className="setup-status";status.setAttribute("role","status");status.setAttribute("aria-live","polite");form.append(save,status);const guide=integrationNode("details"),summary=integrationNode("summary","How to get this credential"),steps=integrationNode("ol");guide.open=true;guide.append(summary);function link(url,label){const a=integrationNode("a",label);try{const u=new URL(url);if(u.protocol!=="https:")return integrationNode("span",label);a.href=u.href}catch{return integrationNode("span",label)}a.target="_blank";a.rel="noopener noreferrer";if(typeof access.openLink==="function")a.addEventListener("click",e=>{e.preventDefault();Promise.resolve(access.openLink(a.href)).catch(()=>{status.textContent="The host could not open this reference. Open the provider dashboard in your browser."})});return a}+ if(configurationOnly&&setup.redirectUri)guide.append(integrationNode("p","Register this exact authorized redirect URI in Google Cloud:"),integrationNode("small",setup.redirectUri));guide.append(link(setup.guidance.url,"Open official provider dashboard"));for(const text of setup.guidance.steps)steps.append(integrationNode("li",text));guide.append(steps,link(setup.guidance.reference,"Official documentation"));const storage=integrationNode("details");storage.append(integrationNode("summary","Storage and privacy"),integrationNode("p",setup.store),integrationNode("p","The form expires after 10 minutes and closes after a successful save. Existing keys are never displayed. Blank fields keep existing values. If a key was shared publicly, revoke it at its provider."));aside.append(guide,storage);grid.append(form,aside);root.append(grid);@@ -43,13 +45,13 @@ function mountIntegrationForm(root,setup,access){form.addEventListener("submit",e=>e.preventDefault());form.addEventListener("keydown",e=>{if(e.key==="Enter"&&e.target instanceof HTMLInputElement){e.preventDefault();save.click()}});save.addEventListener("click",async e=>{- e.preventDefault();if(used||save.disabled||!form.reportValidity())return;save.disabled=true;status.textContent="Checking provider access…";+ e.preventDefault();if(used||save.disabled||!form.reportValidity())return;save.disabled=true;status.textContent=configurationOnly?"Saving app configuration; user consent is separate…":"Checking provider access…";const values={};for(const f of inputs)if(f.input.value.trim())values[f.key]=f.input.value.trim();try{const response=await fetch(endpoint,{method:"POST",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},body:JSON.stringify({action:"save",values}),signal:AbortSignal.any([abort.signal,AbortSignal.timeout(45000)])});const data=await response.json();if(!response.ok){const messages={credential_validation_failed:"The provider rejected this key or could not be reached. Check key type, permissions, and expiry; nothing was saved.",invalid_credential_format:"Check the credential format and remove pasted line breaks.",connection_changed_reopen_setup:"This connection changed after the form opened. Reopen it before updating credentials.",required_fields_missing:"Complete all required fields.",enter_at_least_one_value:"Enter a value to update.",setup_expired_or_invalid:"Setup expired or already used. Open a new form."};throw new Error(messages[data.error]||"Unable to save. Reopen setup or check the provider; nothing was displayed.")}- used=true;clearTimeout(timer);inputs.forEach(f=>{f.input.value="";f.input.disabled=true});save.textContent="Saved";status.textContent="Verified and saved in MSO. This setup session is now closed.";+ used=true;clearTimeout(timer);inputs.forEach(f=>{f.input.value="";f.input.disabled=true});save.textContent="Saved";status.textContent=data.configurationOnly?"OAuth app configuration saved. Create or select a Google service connection to complete consent and verify API access.":"Verified and saved in MSO. This setup session is now closed.";}catch(error){status.textContent=error.message||"Connection failed. Check MSO connectivity."}finally{if(!used)save.disabled=false;for(const key of Object.keys(values))delete values[key]}});return()=>{abort.abort();clearTimeout(timer);inputs.forEach(f=>{f.input.value=""});root.replaceChildren();root.classList.remove("integration")};diff --git a/lib/infra/store.ts b/lib/infra/store.tsindex 4e914615..45476922 100644--- a/lib/infra/store.ts+++ b/lib/infra/store.ts@@ -1,3 +1,4 @@+import { clearGoogleRuntime } from "./google-native-state";import { assertNoVariableReferences } from "./connection-variables";import {randomUUID} from "node:crypto";import { getInfraProviderDefinition, normalizeInfraValues } from "./catalog";@@ -23,7 +24,7 @@ export async function setInfraProvider(id:InfraProviderId,raw:Record<string,unknconst method=connectionMethod(id,c.source,c.authMethod),normalized=normalizeInfraValues(id,raw);if(Object.keys(normalized).some(k=>!method.fields.some(f=>f.key===k)))throw new IntegrationError("connection_auth_mismatch",409);const values={...c.values,...normalized};if(method.fields.some(f=>f.required&&!values[f.key]))throw new IntegrationError("required_fields_missing");- c.values=values;c.revision++;c.updatedAt=Date.now();delete c.verifiedAt;return{...values};+ clearGoogleRuntime(c);c.values=values;c.revision++;c.updatedAt=Date.now();delete c.verifiedAt;return{...values};});}export async function removeInfraProvider(id:InfraProviderId){diff --git a/lib/infra/types.ts b/lib/infra/types.tsindex 67adc0b2..cef0e065 100644--- a/lib/infra/types.ts+++ b/lib/infra/types.ts@@ -1,43 +1,17 @@-export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger", "composio", "github", "vercel", "convex-cloud", "convex", "resend", "stripe", "clerk", "supabase", "telegram", "discord", "doku", "mcp", "openai-app"] as const;+export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger", "composio", "github", "vercel", "convex-cloud", "convex", "resend", "stripe", "clerk", "supabase", "telegram", "discord", "doku", "mcp", "openai-app", "google-oauth-app", "google-search-console", "google-analytics"] as const;export type InfraProviderId = (typeof INFRA_PROVIDER_IDS)[number];export type InfraProviderValues = Record<string, string>;-export type LegacyInfraStore = {- providers?: Partial<Record<InfraProviderId, InfraProviderValues>>;-};-+export type LegacyInfraStore = { providers?: Partial<Record<InfraProviderId, InfraProviderValues>> };export type InfraField = {- key: string;- label: string;- secret: boolean;- required: boolean;- placeholder?: string;- description: string;+ key: string; label: string; secret: boolean; required: boolean; placeholder?: string; description: string;};-export type InfraProviderDefinition = {- id: InfraProviderId;- title: string;- description: string;- feature: boolean;- fields: InfraField[];+ id: InfraProviderId; title: string; description: string; feature: boolean; fields: InfraField[];};-export type InfraProviderSummary = {- id: InfraProviderId;- title: string;- description: string;- feature: boolean;- configured: boolean;- missing: string[];- values: Record<string, string>;- fields: InfraField[];+ id: InfraProviderId; title: string; description: string; feature: boolean;+ configured: boolean; missing: string[]; values: Record<string, string>; fields: InfraField[];};--export type InfraDoctorResult = {- id: InfraProviderId;- ok: boolean | null;- detail: string;-};-+export type InfraDoctorResult = { id: InfraProviderId; ok: boolean | null; detail: string };export type { IntegrationState as InfraStore, ConnectionSelector, IntegrationConnection, IntegrationUser } from "./identity";diff --git a/scripts/e2e/google-integrations.mjs b/scripts/e2e/google-integrations.mjsnew file mode 100644index 00000000..977c31bd--- /dev/null+++ b/scripts/e2e/google-integrations.mjs@@ -0,0 +1,90 @@+#!/usr/bin/env node+// UI proof with synthetic identities and an intercepted provider transport. Never live OAuth.+import { chromium, expect } from "@playwright/test";+import { execFileSync } from "node:child_process";+import { createRequire } from "node:module";+import { mkdir, writeFile } from "node:fs/promises";+import path from "node:path";+const require = createRequire(import.meta.url);+const origin = "https://mso.example.com";+const html = execFileSync("bun", ["-e", 'import { integrationSetupPage } from "./lib/infra/setup-page"; console.log(integrationSetupPage().html)'], { encoding: "utf8", env: { ...process.env, OS_PUBLIC_ORIGIN: origin } });+const app = { id: "app", label: "Test Google app", provider: "google-oauth-app", source: "direct", authMethod: "oauth-app", state: "app-configured", scope: "client-configuration", fields: [{ key: "clientId", stored: true }, { key: "clientSecret", stored: true, secret: true }], isDefault: true };+const connection = provider => ({ id: "reporting", label: provider === "google-search-console" ? "Search reporting" : "Analytics reporting", provider, source: "direct", authMethod: "oauth2", state: "authorization-required", scope: "read-only-account", fields: [{ key: "appConnection", stored: true }], google: { appConnection: "app", account: null, requiredScope: provider === "google-search-console" ? "https://www.googleapis.com/auth/webmasters.readonly" : "https://www.googleapis.com/auth/analytics.readonly" }, isDefault: true });+const rows = [app, connection("google-search-console"), connection("google-analytics")];+const snapshot = () => ({ version: 2, user: "fixture", users: [{ id: "fixture", label: "Fixture owner", isDefault: true, connectionCount: 3 }], connections: rows, bindings: [] });+const checks = [], errors = [], requests = [], screenshots = [];+const check = (ok, name) => { checks.push({ name, passed: !!ok }); if (!ok) errors.push(name); };+const out = process.env.MSO_SCREENSHOT_DIR || path.join(process.cwd(), ".agent", "evidence", "google-ui");+process.umask(0o077); await mkdir(out, { recursive: true, mode: 0o700 });+const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });+try {+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });+ page.on("pageerror", error => errors.push(error.message));+ await page.route("**/*", async route => {+ const req = route.request(), url = new URL(req.url());+ if (url.origin !== origin) return route.fulfill({ status: 400, body: "External network disabled in this synthetic fixture" });+ if (url.pathname === "/integrations") return route.fulfill({ contentType: "text/html", body: html });+ if (url.pathname === "/api/auth/me") return route.fulfill({ json: { role: "owner", authenticated: true } });+ if (url.pathname === "/api/v1/integrations" && req.method() === "GET") return route.fulfill({ json: snapshot() });+ if (url.pathname === "/api/v1/integrations") {+ const body = req.postDataJSON(); requests.push(body);+ const row = rows.find(c => c.provider === body.provider && c.id === body.connection);+ if (body.operation === "verify" && row) row.state = "verified";+ if (body.operation === "google.disconnect" && row) { row.state = "authorization-required"; row.google.account = null; }+ return route.fulfill({ json: { ok: true, detail: "Synthetic fixture result — not a real connected Google account" } });+ }+ if (url.pathname === "/api/integrations/google/start") {+ requests.push({ kind: "browser-google-start", ...req.postDataJSON() });+ return route.fulfill({ json: { authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=SYNTHETIC_TEST_ONLY", expiresIn: 600 } });+ }+ if (url.pathname === "/api/v1/infra/setup") return route.fulfill({ json: { token: "SYNTHETIC_PRIVATE_FORM", setup: { user: "fixture", connection: "app", provider: "google-oauth-app", title: "Google OAuth app", label: "Test Google app", source: "direct", scope: "client-configuration", method: "oauth-app", expiresAt: Date.now() + 600000, store: "Synthetic in-memory transport only", fields: [{ key: "clientId", label: "Google OAuth client ID", required: true, secret: false }, { key: "clientSecret", label: "Google OAuth client secret", required: true, secret: true }], guidance: { url: "https://console.cloud.google.com/auth/clients", reference: "https://developers.google.com/identity/protocols/oauth2/web-server", steps: ["Configure your own Google client, then authorize users separately."] } } } });+ if (url.pathname === "/api/integrations/setup") { requests.push({ kind: "private-app-configuration" }); return route.fulfill({ json: { ok: true, verified: false, configurationOnly: true } }); }+ return route.fulfill({ status: 404, json: { error: "unhandled_synthetic_route" } });+ });+ const goto = async provider => { await page.goto(origin + "/integrations?user=fixture&provider=" + provider); await expect(page.getByRole("heading", { name: provider === "google-analytics" ? "Analytics reporting" : provider === "google-oauth-app" ? "Test Google app" : "Search reporting", exact: true })).toBeVisible(); };+ await goto("google-search-console");+ check(await page.getByRole("button", { name: "Connect with Google", exact: true }).isVisible(), "Native Google connect action is visible");+ check(await page.getByRole("textbox", { name: /Project API key/ }).count() === 0, "No Composio project-key prompt in native Google connection");+ await page.getByRole("combobox", { name: "Google OAuth app", exact: true }).selectOption("app");+ await page.getByRole("button", { name: "Use selected app", exact: true }).click();+ await expect.poll(() => requests.some(r => r.operation === "google.bind" && r.arguments?.appConnection === "app")).toBe(true);+ check(true, "App binding uses the existing generic integration executor");+ await page.getByRole("button", { name: "Connect with Google", exact: true }).click();+ const consent = page.getByRole("link", { name: "Continue to Google", exact: true }); await expect(consent).toBeVisible();+ check(await consent.getAttribute("target") === "_blank", "Consent opens a top-level browser, not an iframe");+ check(await consent.getAttribute("rel") === "noopener noreferrer", "Consent link has an isolated opener and no referrer");+ check(requests.some(r => r.kind === "browser-google-start" && r.user === "fixture" && r.provider === "google-search-console" && r.connection === "reporting"), "Browser authorization preserves the exact credential identity");+ check(!requests.some(r => r.action === "connection.authorize" && r.brokerConnection), "No Composio broker authorization request");+ await page.getByRole("button", { name: "Verify API access", exact: true }).click(); await expect(page.locator(".connection-state").filter({ hasText: "Verified" })).toBeVisible();+ check(true, "Verification is separate from authorization preparation");+ page.once("dialog", dialog => dialog.accept()); await page.getByRole("button", { name: "Disconnect from MSO", exact: true }).click();+ await expect(page.locator(".connection-state").filter({ hasText: "Consent required" })).toBeVisible(); check(true, "Disconnect returns to consent-required state");+ await goto("google-analytics"); await page.getByText("Available read-only operations", { exact: true }).click();+ await expect(page.getByText("google.analytics.report.run", { exact: true })).toBeVisible(); check(true, "GA4 report operation is discoverable in the same native UI");+ for (const viewport of [{ width: 390, height: 844 }, { width: 1440, height: 1000 }]) {+ await page.setViewportSize(viewport);+ for (const theme of ["light", "dark"]) {+ await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);+ check(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), `No native Google page overflow ${viewport.width} ${theme}`);+ await page.addScriptTag({ path: require.resolve("axe-core/axe.min.js") });+ const violations = await page.evaluate(async () => (await window.axe.run(document.querySelector(".integration-settings-content"), { runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21aa"] } })).violations.map(v => ({ id: v.id, impact: v.impact, nodes: v.nodes.map(node => ({ target: node.target, summary: node.failureSummary, html: node.html })) })));+ check(violations.length === 0, `Native Google content accessibility ${viewport.width} ${theme}: ${JSON.stringify(violations)}`);+ }+ const filename = path.join(out, `google-native-ui-${viewport.width}.png`); await page.screenshot({ path: filename, fullPage: true }); screenshots.push(filename);+ }+ await page.setViewportSize({ width: 1440, height: 1000 }); await goto("google-oauth-app");+ await page.getByRole("button", { name: "Update credentials", exact: true }).click();+ await page.getByRole("textbox", { name: "Google OAuth client ID", exact: false }).fill("123456789-fixture.apps.googleusercontent.com");+ await page.locator("#setup-clientSecret").fill("SYNTHETIC_CLIENT_SECRET_NOT_REAL");+ await page.getByRole("button", { name: "Save OAuth app configuration", exact: true }).click();+ await expect(page.getByRole("status")).toContainText("OAuth app configuration saved");+ check(!(await page.getByRole("status").innerText()).includes("Verified and saved"), "Saving app configuration does not claim verified account access");+ const file = path.join(out, "google-native-app-configuration.png"); await page.screenshot({ path: file, fullPage: true }); screenshots.push(file);+ check(await page.evaluate(() => localStorage.length === 0), "No credentials persisted to browser localStorage by the setup form");+} catch (error) { errors.push(error.stack || String(error)); }+finally {+ await browser.close();+ const report = { at: new Date().toISOString(), environment: "synthetic native UI; mocked Google and local provider transport", checks, errors, screenshots };+ const file = path.join(out, "google-native-ui-receipt.json"); await writeFile(file, JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report, null, 2)); console.log("Receipt: " + file); if (errors.length) process.exitCode = 1;+}diff --git a/scripts/mso-cli-integrations.sh b/scripts/mso-cli-integrations.shindex 073ebd3a..2042f6fa 100644--- a/scripts/mso-cli-integrations.sh+++ b/scripts/mso-cli-integrations.sh@@ -23,6 +23,13 @@ run_integrations() {[ $# -ge 2 ] || die "usage: mso integrations $sub <user> <provider> [connection]"query="view=$sub&user=$(enc "$1")&provider=$(enc "$2")"; [ -n "${3-}" ] && query="$query&connection=$(enc "$3")"jget "/api/v1/integrations?$query" ;;+ authorize)+ [ $# -eq 3 ] || die "usage: mso integrations authorize <user> <provider> <connection>"+ body=$(jq -nc --arg user "$1" --arg provider "$2" --arg connection "$3" '{mode:"manage",action:"connection.authorize",confirm:true,user:$user,provider:$provider,connection:$connection}')+ data=$(jpost "/api/v1/integrations" "$body")+ if jq -e '.openPath' >/dev/null <<<"$data"; then+ printf 'Complete authorization in the native Owner browser (no OAuth code is printed):\n%s\n' "$(jq -r .openPath <<<"$data")"+ elif tty_ok; then jq . <<<"$data"; else jq 'del(.privateUrl)+{notice:"Complete authorization in the private browser UI"}' <<<"$data"; fi ;;setup)[ $# -eq 3 ] || die "usage: mso integrations setup <user> <provider> <connection>"tty_ok || die "private setup links are terminal-only; use integration_setup_open from MCP"@@ -65,6 +72,6 @@ run_integrations() {[ $# -eq 1 ] || die 'usage: mso integrations execute <metadata-JSON with user, provider, connection, operation and confirm:true>'body=$(jq -ce 'if type=="object" then .+{mode:"execute"} else error("object required") end' <<<"$1")jpost "/api/v1/integrations" "$body" ;;- *) die 'usage: mso integrations import-sc|transfer|status|users|catalog|connections|which|request|resolve|create-user|create-connection|manage|setup|verify|route|hostinger-mail-orders|hostinger-mail-list|hostinger-mail-logs|execute' ;;+ *) die 'usage: mso integrations import-sc|transfer|status|users|catalog|connections|which|request|resolve|create-user|create-connection|manage|setup|authorize|verify|route|hostinger-mail-orders|hostinger-mail-list|hostinger-mail-logs|execute' ;;esac}diff --git a/scripts/verify-build.sh b/scripts/verify-build.shindex a25375fa..e247701b 100755--- a/scripts/verify-build.sh+++ b/scripts/verify-build.sh@@ -71,6 +71,12 @@ if ! node scripts/e2e/integrations-shell.mjs; thenexit 43fi+echo "== verify native Google Integrations UI (synthetic accounts)"+if ! node scripts/e2e/google-integrations.mjs; then+ echo "verification failed during native Google Integrations UI E2E" >&2+ exit 43+fi+echo "== verify shell-native server status"if ! node scripts/e2e/shell-status.mjs; thenecho "verification failed during shell-native server status E2E" >&2diff --git a/scripts/worktree-gates.test.ts b/scripts/worktree-gates.test.tsindex 4c8bb752..1fbba251 100644--- a/scripts/worktree-gates.test.ts+++ b/scripts/worktree-gates.test.ts@@ -56,6 +56,7 @@ function fixture(script: string) {for (const [file, label] of [["scripts/check-bundle.mjs", "bundle budget"],["scripts/e2e/bundle-performance.mjs", "deferred performance"],+ ["scripts/e2e/google-integrations.mjs", "native Google UI"],]) {writeFileSync(path.join(repo, file),`import fs from 'node:fs'; if (!fs.existsSync('.build-verified') || fs.existsSync('.env.local')) throw Error('unsafe bundle fixture'); console.log('isolated ${label} fixture passed');`);@@ -132,6 +133,7 @@ describe("isolated worktree release guards", () => {expect(run.stdout).toContain("isolated shell status fixture passed");expect(run.stdout).toContain("isolated bundle budget fixture passed");expect(run.stdout).toContain("isolated deferred performance fixture passed");+ expect(run.stdout).toContain("isolated native Google UI fixture passed");expect(readFileSync(path.join(repo, ".next/keep"), "utf8")).toBe("live marker",);