@agent-native/core 0.12.24 → 0.12.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/agent/production-agent.d.ts +9 -2
  2. package/dist/agent/production-agent.d.ts.map +1 -1
  3. package/dist/agent/production-agent.js +36 -35
  4. package/dist/agent/production-agent.js.map +1 -1
  5. package/dist/agent/thread-data-builder.d.ts +16 -1
  6. package/dist/agent/thread-data-builder.d.ts.map +1 -1
  7. package/dist/agent/thread-data-builder.js +132 -0
  8. package/dist/agent/thread-data-builder.js.map +1 -1
  9. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  10. package/dist/client/agent-chat-adapter.js +15 -3
  11. package/dist/client/agent-chat-adapter.js.map +1 -1
  12. package/dist/client/progress/RunsTray.d.ts.map +1 -1
  13. package/dist/client/progress/RunsTray.js +3 -1
  14. package/dist/client/progress/RunsTray.js.map +1 -1
  15. package/dist/client/sse-event-processor.d.ts.map +1 -1
  16. package/dist/client/sse-event-processor.js +4 -1
  17. package/dist/client/sse-event-processor.js.map +1 -1
  18. package/dist/onboarding/default-steps.d.ts.map +1 -1
  19. package/dist/onboarding/default-steps.js +8 -1
  20. package/dist/onboarding/default-steps.js.map +1 -1
  21. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  22. package/dist/server/agent-chat-plugin.js +53 -2
  23. package/dist/server/agent-chat-plugin.js.map +1 -1
  24. package/dist/server/credential-provider.d.ts +2 -2
  25. package/dist/server/credential-provider.d.ts.map +1 -1
  26. package/dist/server/credential-provider.js +22 -1
  27. package/dist/server/credential-provider.js.map +1 -1
  28. package/dist/server/google-oauth.js +1 -1
  29. package/dist/server/google-oauth.js.map +1 -1
  30. package/package.json +1 -1
@@ -54,7 +54,7 @@ export declare function readDeployCredentialEnv(key: string): string | undefined
54
54
  */
55
55
  export declare function isDeployCredentialFallbackAllowed(): boolean;
56
56
  export declare function canUseDeployCredentialFallbackForRequest(): boolean;
57
- type BuilderCredentialSource = "user" | "org" | "env";
57
+ type BuilderCredentialSource = "user" | "org" | "workspace" | "env";
58
58
  /**
59
59
  * Resolve a Builder credential for the current request. User/org credentials
60
60
  * win; deployment env is only a fallback. This lets local/root .env keys keep
@@ -145,7 +145,7 @@ export declare function deleteBuilderCredentials(email: string, options?: {
145
145
  /**
146
146
  * Resolve a request-scoped secret. Reads from `app_secrets` first (current
147
147
  * user override, active org, then workspace row); falls back to `process.env`
148
- * only for unauthenticated/CLI/background contexts.
148
+ * only when the deploy fallback policy allows it.
149
149
  */
150
150
  export declare function resolveSecret(key: string): Promise<string | null>;
151
151
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"credential-provider.d.ts","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAKH;;;;;;;;GAQG;AACH,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAChC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAC9B;IAAE,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAK5C;AAED,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;gBAElB,IAAI,EAAE;QAChB,kBAAkB,EAAE,MAAM,CAAC;QAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB;CAUF;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEvE;AAED;;;;;GA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AO,CAE9C;AAED,yEAAyE;AACzE,wBAAgB,qBAAqB,IAAI,MAAM,CAO9C;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,IAAI,MAAM,CAKjD;AAED;;;GAGG;AACH,wBAAgB,gCAAgC,IAAI,MAAM,CAKzD;AAED,uEAAuE;AACvE,wBAAgB,oBAAoB,IAAI,MAAM,GAAG,IAAI,CAGpD"}
@@ -100,6 +100,27 @@ async function resolveScopedBuilderCredential(key) {
100
100
  });
101
101
  if (orgSecret)
102
102
  return { value: orgSecret.value, source: "org" };
103
+ // Older setup flows wrote shared credentials at workspace scope.
104
+ // Keep reading those rows so status UIs and runtime resolution agree
105
+ // for users who connected before org-scoped Builder credentials existed.
106
+ const workspaceSecret = await readAppSecret({
107
+ key,
108
+ scope: "workspace",
109
+ scopeId: orgId,
110
+ });
111
+ if (workspaceSecret) {
112
+ return { value: workspaceSecret.value, source: "workspace" };
113
+ }
114
+ }
115
+ else {
116
+ const soloWorkspaceSecret = await readAppSecret({
117
+ key,
118
+ scope: "workspace",
119
+ scopeId: `solo:${email}`,
120
+ });
121
+ if (soloWorkspaceSecret) {
122
+ return { value: soloWorkspaceSecret.value, source: "workspace" };
123
+ }
103
124
  }
104
125
  }
105
126
  catch {
@@ -257,7 +278,7 @@ export async function deleteBuilderCredentials(email, options) {
257
278
  /**
258
279
  * Resolve a request-scoped secret. Reads from `app_secrets` first (current
259
280
  * user override, active org, then workspace row); falls back to `process.env`
260
- * only for unauthenticated/CLI/background contexts.
281
+ * only when the deploy fallback policy allows it.
261
282
  */
262
283
  export async function resolveSecret(key) {
263
284
  const email = getRequestUserEmail();
@@ -1 +1 @@
1
- {"version":3,"file":"credential-provider.js","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM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C,CAAC,IAAI,CAAC;IACX,CAAC;IACD,uEAAuE;IACvE,mDAAmD;IACnD,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;AAClC,CAAC;AAED,8EAA8E;AAC9E,uEAAuE;AACvE,iEAAiE;AACjE,8EAA8E;AAE9E;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;AAC3C,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,qBAAqB;IACnC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,oBAAoB;QAChC,OAAO,CAAC,GAAG,CAAC,QAAQ;QACpB,OAAO,CAAC,GAAG,CAAC,gBAAgB;QAC5B,gCAAgC,CACjC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,wBAAwB;QACpC,gDAAgD,CACjD,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gCAAgC;IAC9C,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,iCAAiC;QAC7C,+CAA+C,CAChD,CAAC;AACJ,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,oBAAoB;IAClC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;IAC5C,OAAO,GAAG,CAAC,CAAC,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC","sourcesContent":["/**\n * Credential provider abstraction.\n *\n * Every feature that needs an external credential (Anthropic API key,\n * Google OAuth tokens, OpenAI key, Slack bot token, etc.) should go through\n * one of the resolve*() helpers here instead of reading `process.env`\n * directly. That way the same feature can work in three modes:\n *\n * 1. User set their own key in .env → use it directly\n * 2. User connected Builder via `/cli-auth` → route through Builder proxy\n * 3. Neither → throw FeatureNotConfigured\n *\n * Templates catch FeatureNotConfigured and show a \"Connect Builder (1 click) /\n * set up your own key (guide)\" card.\n *\n * Today these helpers are used by the Builder-hosted LLM gateway, and the\n * shape is meant to grow to cover future managed credential integrations\n * (e.g. additional Builder-hosted services) without rewrites.\n */\n\nimport { getRequestUserEmail, getRequestOrgId } from \"./request-context.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\n\n/**\n * Decide which `app_secrets` scope a Builder/credential write should use.\n *\n * Org scope (\"everyone in this org sees these credentials\") wins when the\n * connecting user is an owner or admin of an active org — the write\n * privileges shared infra. A plain member or a user without an active\n * org falls through to per-user scope so a teammate can't silently\n * overwrite the org-shared connection.\n */\nexport function resolveCredentialWriteScope(\n email: string,\n orgId: string | null | undefined,\n role: string | null | undefined,\n): { scope: \"user\" | \"org\"; scopeId: string } {\n if (orgId && (role === \"owner\" || role === \"admin\")) {\n return { scope: \"org\", scopeId: orgId };\n }\n return { scope: \"user\", scopeId: email };\n}\n\nexport class FeatureNotConfiguredError extends Error {\n readonly requiredCredential: string;\n readonly builderConnectUrl?: string;\n readonly byokDocsUrl?: string;\n\n constructor(opts: {\n requiredCredential: string;\n message?: string;\n builderConnectUrl?: string;\n byokDocsUrl?: string;\n }) {\n super(\n opts.message ??\n `Feature requires credential \"${opts.requiredCredential}\". Connect Builder or set your own key.`,\n );\n this.name = \"FeatureNotConfiguredError\";\n this.requiredCredential = opts.requiredCredential;\n this.builderConnectUrl = opts.builderConnectUrl;\n this.byokDocsUrl = opts.byokDocsUrl;\n }\n}\n\n/**\n * Deployment-level credential fallback for single-tenant/local operation.\n * Multi-tenant call sites must gate this explicitly before calling.\n */\nexport function readDeployCredentialEnv(key: string): string | undefined {\n return process.env[key] || undefined;\n}\n\n/**\n * Deployment-level credentials are safe as a runtime fallback only in local /\n * single-tenant contexts. In hosted production with a shared database, every\n * signed-in user needs their own user/org/workspace credential so one deploy\n * key does not silently power another tenant's chat.\n */\nexport function isDeployCredentialFallbackAllowed(): boolean {\n if (process.env.NODE_ENV !== \"production\") return true;\n return isLocalDatabase();\n}\n\nexport function canUseDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (!email) return true;\n return isDeployCredentialFallbackAllowed();\n}\n\n// ---------------------------------------------------------------------------\n// Builder credential resolution:\n//\n// 1. **Request-scoped credentials.** A signed-in user can connect Builder\n// through the CLI-auth flow. Owner/admin connections land at org scope;\n// member/no-org connections land at user scope.\n//\n// 2. **Deployment fallback.** BUILDER_PRIVATE_KEY in env still makes local\n// and single-tenant deploys work out of the box, but it no longer blocks\n// per-user connect. Request-scoped credentials win whenever present.\n//\n// To run multi-tenant SaaS: prefer leaving BUILDER_PRIVATE_KEY unset unless a\n// shared fallback identity is intentional.\n// ---------------------------------------------------------------------------\n\ntype BuilderCredentialSource = \"user\" | \"org\" | \"env\";\n\nasync function resolveScopedBuilderCredential(\n key: string,\n): Promise<{ value: string; source: \"user\" | \"org\" } | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n\n // 1. Per-user override: a user can paste their own key in settings to\n // overrule the org-shared one (handy for a personal sandbox).\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret) return { value: userSecret.value, source: \"user\" };\n\n // 2. Per-org shared credential: when one teammate connects Builder\n // as an owner/admin we write the OAuth result at org scope so\n // every member of that org gets the AI chat working without\n // re-running the connect flow. Resolution falls back here\n // silently — the caller never has to know which scope answered.\n const orgId = getRequestOrgId();\n if (orgId) {\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret) return { value: orgSecret.value, source: \"org\" };\n }\n } catch {\n // Secrets table not ready — treat as missing.\n }\n return null;\n}\n\n/**\n * Resolve a Builder credential for the current request. User/org credentials\n * win; deployment env is only a fallback. This lets local/root .env keys keep\n * a template working while still allowing users to connect their own Builder\n * account from Settings or onboarding.\n */\nexport async function resolveBuilderCredential(\n key: string,\n): Promise<string | null> {\n const scoped = await resolveScopedBuilderCredential(key);\n if (scoped) return scoped.value;\n if (!canUseDeployCredentialFallbackForRequest()) return null;\n return readDeployCredentialEnv(key) ?? null;\n}\n\n/**\n * True when `BUILDER_PRIVATE_KEY` is set at the deployment level. This means\n * a deploy-level fallback exists; it does not prevent per-user connect.\n */\nexport function isBuilderEnvManaged(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/**\n * Resolve the Builder private key for the current request. User/org OAuth\n * credentials win; deploy-level `BUILDER_PRIVATE_KEY` is the fallback.\n */\nexport async function resolveBuilderPrivateKey(): Promise<string | null> {\n return resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n}\n\n/**\n * Resolve the current user's Builder auth header.\n * Returns `\"Bearer <key>\"` or null.\n */\nexport async function resolveBuilderAuthHeader(): Promise<string | null> {\n const key = await resolveBuilderPrivateKey();\n return key ? `Bearer ${key}` : null;\n}\n\n/**\n * Check whether the current user has a Builder private key configured\n * (per-user or deployment-level).\n */\nexport async function resolveHasBuilderPrivateKey(): Promise<boolean> {\n return !!(await resolveBuilderPrivateKey());\n}\n\n/**\n * Resolve where the effective Builder private key came from. Used by status\n * UIs so they can distinguish a deploy fallback from a user/org connection.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n if (scoped) return scoped.source;\n return canUseDeployCredentialFallbackForRequest() &&\n process.env.BUILDER_PRIVATE_KEY\n ? \"env\"\n : null;\n}\n\n/**\n * Resolve all per-user Builder credentials. Used by the status endpoint\n * and agent-chat-plugin to get orgName, userId, etc.\n */\nexport async function resolveBuilderCredentials(): Promise<{\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n}> {\n const [privateKey, publicKey, userId, orgName, orgKind] = await Promise.all([\n resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\"),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n resolveBuilderCredential(\"BUILDER_ORG_NAME\"),\n resolveBuilderCredential(\"BUILDER_ORG_KIND\"),\n ]);\n return { privateKey, publicKey, userId, orgName, orgKind };\n}\n\nconst BUILDER_CREDENTIAL_KEYS = [\n \"BUILDER_PRIVATE_KEY\",\n \"BUILDER_PUBLIC_KEY\",\n \"BUILDER_USER_ID\",\n \"BUILDER_ORG_NAME\",\n \"BUILDER_ORG_KIND\",\n] as const;\n\n/**\n * Write Builder credentials to `app_secrets`.\n *\n * Scope decision (see `resolveCredentialWriteScope`): when the connecting\n * user is owner/admin of an active org we write at `scope: \"org\"` so every\n * member of that org auto-resolves the credentials via\n * `resolveBuilderCredential`'s org fallback — no per-user re-connect\n * needed. A plain member or a user with no active org writes at\n * `scope: \"user\"` (the safe default that doesn't trample the org's shared\n * connection).\n *\n * Returns the actual scope/scopeId used so the caller can show \"Connected\n * for Builder.io\" vs \"Connected (personal)\" in the UI.\n */\nexport async function writeBuilderCredentials(\n email: string,\n creds: {\n privateKey: string;\n publicKey: string;\n userId?: string | null;\n orgName?: string | null;\n orgKind?: string | null;\n },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { writeAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n\n const entries: Array<{ key: string; value: string }> = [\n { key: \"BUILDER_PRIVATE_KEY\", value: creds.privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: creds.publicKey },\n ];\n if (creds.userId) {\n entries.push({ key: \"BUILDER_USER_ID\", value: creds.userId });\n }\n if (creds.orgName) {\n entries.push({ key: \"BUILDER_ORG_NAME\", value: creds.orgName });\n }\n if (creds.orgKind) {\n entries.push({ key: \"BUILDER_ORG_KIND\", value: creds.orgKind });\n }\n await Promise.all(\n entries.map(({ key, value }) =>\n writeAppSecret({\n key,\n value,\n scope: target.scope,\n scopeId: target.scopeId,\n }),\n ),\n );\n return target;\n}\n\n/**\n * Delete Builder credentials.\n *\n * Default behaviour: clears only this user's per-user override (so a\n * member can disconnect their personal Builder identity without\n * collapsing the org-wide connection for every teammate). To revoke the\n * org's shared connection, pass `{ orgId, role }` for an owner/admin —\n * matching the same authority gate `writeBuilderCredentials` uses on\n * write. Plain members can never reach the org-scoped row.\n */\nexport async function deleteBuilderCredentials(\n email: string,\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { deleteAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n await Promise.all(\n BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n ),\n );\n return target;\n}\n\n// ---------------------------------------------------------------------------\n// Generic request-scoped secret resolution\n//\n// New consumers should prefer this over reading `process.env.X` directly.\n// User-pasted and shared secrets live in `app_secrets` (encrypted). The\n// settings UI / onboarding panels can write user, org, or workspace rows.\n// Deploy-level env vars are the fallback for unauthenticated/CLI/background\n// contexts where there's no user to scope by — never the silent fallback\n// for an authenticated request, since on a multi-tenant deploy that would\n// silently identify every user as whoever set the deploy-level key\n// (KVesta Space, 2026-04).\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a request-scoped secret. Reads from `app_secrets` first (current\n * user override, active org, then workspace row); falls back to `process.env`\n * only for unauthenticated/CLI/background contexts.\n */\nexport async function resolveSecret(key: string): Promise<string | null> {\n const email = getRequestUserEmail();\n if (email) {\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n // Per-user override first.\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret?.value) return userSecret.value;\n\n const orgId = getRequestOrgId();\n if (orgId) {\n // Fall back to the active org's shared row, when present. Builder\n // Connect uses this first-class org scope.\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret?.value) return orgSecret.value;\n\n // Registered secrets historically used \"workspace\" scope for\n // org-shared configuration. Keep reading it so Settings status and\n // runtime resolution agree.\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret?.value) return workspaceSecret.value;\n } else {\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret?.value) return soloWorkspaceSecret.value;\n }\n } catch {\n // Secrets table not ready — treat as missing.\n }\n // Authenticated multi-tenant context: never fall back to process.env.\n // The deploy-level value would silently impersonate the actual key\n // owner across every tenant. Local/single-tenant deployments keep the\n // original env fallback for BYO-server workflows.\n return canUseDeployCredentialFallbackForRequest()\n ? process.env[key] || null\n : null;\n }\n // Unauthenticated / local-dev / CLI / background context: env fallback\n // is safe because there's no user to mis-identify.\n return process.env[key] || null;\n}\n\n// ---------------------------------------------------------------------------\n// Synchronous helpers — env-only fallbacks for contexts where per-user\n// lookup isn't possible (sync isConfigured checks, CLI scripts).\n// ---------------------------------------------------------------------------\n\n/**\n * True when a Builder private key is configured at the deployment level.\n *\n * This is the same env-only check as `isBuilderEnvManaged()`. For \"does this\n * request have access to Builder via user/org/env credentials?\" use the async\n * `resolveHasBuilderPrivateKey()`.\n */\nexport function hasBuilderPrivateKey(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/** The origin for Builder-proxied API calls. Overridable for testing. */\nexport function getBuilderProxyOrigin(): string {\n return (\n process.env.BUILDER_PROXY_ORIGIN ||\n process.env.AIR_HOST ||\n process.env.BUILDER_API_HOST ||\n \"https://ai-services.builder.io\"\n );\n}\n\n/**\n * Base URL for the public Builder LLM gateway (distinct from the internal\n * proxy origin above — the public gateway lives at\n * api.builder.io/agent-native/gateway, while the internal origin is\n * ai-services.builder.io).\n * Override via BUILDER_GATEWAY_BASE_URL for staging / testing.\n */\nexport function getBuilderGatewayBaseUrl(): string {\n return (\n process.env.BUILDER_GATEWAY_BASE_URL ||\n \"https://api.builder.io/agent-native/gateway/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed image generation.\n * Override via BUILDER_IMAGE_GENERATION_BASE_URL for staging / testing.\n */\nexport function getBuilderImageGenerationBaseUrl(): string {\n return (\n process.env.BUILDER_IMAGE_GENERATION_BASE_URL ||\n \"https://api.builder.io/agent-native/images/v1\"\n );\n}\n\n/** Authorization header value for Builder-proxied calls (env-only). */\nexport function getBuilderAuthHeader(): string | null {\n const key = process.env.BUILDER_PRIVATE_KEY;\n return key ? `Bearer ${key}` : null;\n}\n"]}
1
+ {"version":3,"file":"credential-provider.js","sourceRoot":"","sources":["../../src/server/credential-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAAa,EACb,KAAgC,EAChC,IAA+B;IAE/B,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,CAAC,EAAE,CAAC;QACpD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC1C,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC3C,CAAC;AAED,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IACzC,kBAAkB,CAAS;IAC3B,iBAAiB,CAAU;IAC3B,WAAW,CAAU;IAE9B,YAAY,IAKX;QACC,KAAK,CACH,IAAI,CAAC,OAAO;YACV,gCAAgC,IAAI,CAAC,kBAAkB,yCAAyC,CACnG,CAAC;QACF,IAAI,CAA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,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;IACD,uEAAuE;IACvE,mDAAmD;IACnD,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;AAClC,CAAC;AAED,8EAA8E;AAC9E,uEAAuE;AACvE,iEAAiE;AACjE,8EAA8E;AAE9E;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;AAC3C,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,qBAAqB;IACnC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,oBAAoB;QAChC,OAAO,CAAC,GAAG,CAAC,QAAQ;QACpB,OAAO,CAAC,GAAG,CAAC,gBAAgB;QAC5B,gCAAgC,CACjC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,wBAAwB;QACpC,gDAAgD,CACjD,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gCAAgC;IAC9C,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,iCAAiC;QAC7C,+CAA+C,CAChD,CAAC;AACJ,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,oBAAoB;IAClC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;IAC5C,OAAO,GAAG,CAAC,CAAC,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC","sourcesContent":["/**\n * Credential provider abstraction.\n *\n * Every feature that needs an external credential (Anthropic API key,\n * Google OAuth tokens, OpenAI key, Slack bot token, etc.) should go through\n * one of the resolve*() helpers here instead of reading `process.env`\n * directly. That way the same feature can work in three modes:\n *\n * 1. User set their own key in .env → use it directly\n * 2. User connected Builder via `/cli-auth` → route through Builder proxy\n * 3. Neither → throw FeatureNotConfigured\n *\n * Templates catch FeatureNotConfigured and show a \"Connect Builder (1 click) /\n * set up your own key (guide)\" card.\n *\n * Today these helpers are used by the Builder-hosted LLM gateway, and the\n * shape is meant to grow to cover future managed credential integrations\n * (e.g. additional Builder-hosted services) without rewrites.\n */\n\nimport { getRequestUserEmail, getRequestOrgId } from \"./request-context.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\n\n/**\n * Decide which `app_secrets` scope a Builder/credential write should use.\n *\n * Org scope (\"everyone in this org sees these credentials\") wins when the\n * connecting user is an owner or admin of an active org — the write\n * privileges shared infra. A plain member or a user without an active\n * org falls through to per-user scope so a teammate can't silently\n * overwrite the org-shared connection.\n */\nexport function resolveCredentialWriteScope(\n email: string,\n orgId: string | null | undefined,\n role: string | null | undefined,\n): { scope: \"user\" | \"org\"; scopeId: string } {\n if (orgId && (role === \"owner\" || role === \"admin\")) {\n return { scope: \"org\", scopeId: orgId };\n }\n return { scope: \"user\", scopeId: email };\n}\n\nexport class FeatureNotConfiguredError extends Error {\n readonly requiredCredential: string;\n readonly builderConnectUrl?: string;\n readonly byokDocsUrl?: string;\n\n constructor(opts: {\n requiredCredential: string;\n message?: string;\n builderConnectUrl?: string;\n byokDocsUrl?: string;\n }) {\n super(\n opts.message ??\n `Feature requires credential \"${opts.requiredCredential}\". Connect Builder or set your own key.`,\n );\n this.name = \"FeatureNotConfiguredError\";\n this.requiredCredential = opts.requiredCredential;\n this.builderConnectUrl = opts.builderConnectUrl;\n this.byokDocsUrl = opts.byokDocsUrl;\n }\n}\n\n/**\n * Deployment-level credential fallback for single-tenant/local operation.\n * Multi-tenant call sites must gate this explicitly before calling.\n */\nexport function readDeployCredentialEnv(key: string): string | undefined {\n return process.env[key] || undefined;\n}\n\n/**\n * Deployment-level credentials are safe as a runtime fallback only in local /\n * single-tenant contexts. In hosted production with a shared database, every\n * signed-in user needs their own user/org/workspace credential so one deploy\n * key does not silently power another tenant's chat.\n */\nexport function isDeployCredentialFallbackAllowed(): boolean {\n if (process.env.NODE_ENV !== \"production\") return true;\n return isLocalDatabase();\n}\n\nexport function canUseDeployCredentialFallbackForRequest(): boolean {\n const email = getRequestUserEmail();\n if (!email) return true;\n return isDeployCredentialFallbackAllowed();\n}\n\n// ---------------------------------------------------------------------------\n// Builder credential resolution:\n//\n// 1. **Request-scoped credentials.** A signed-in user can connect Builder\n// through the CLI-auth flow. Owner/admin connections land at org scope;\n// member/no-org connections land at user scope.\n//\n// 2. **Deployment fallback.** BUILDER_PRIVATE_KEY in env still makes local\n// and single-tenant deploys work out of the box, but it no longer blocks\n// per-user connect. Request-scoped credentials win whenever present.\n//\n// To run multi-tenant SaaS: prefer leaving BUILDER_PRIVATE_KEY unset unless a\n// shared fallback identity is intentional.\n// ---------------------------------------------------------------------------\n\ntype BuilderCredentialSource = \"user\" | \"org\" | \"workspace\" | \"env\";\n\nasync function resolveScopedBuilderCredential(\n key: string,\n): Promise<{ value: string; source: \"user\" | \"org\" | \"workspace\" } | null> {\n const email = getRequestUserEmail();\n if (!email) return null;\n\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n\n // 1. Per-user override: a user can paste their own key in settings to\n // overrule the org-shared one (handy for a personal sandbox).\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret) return { value: userSecret.value, source: \"user\" };\n\n // 2. Per-org shared credential: when one teammate connects Builder\n // as an owner/admin we write the OAuth result at org scope so\n // every member of that org gets the AI chat working without\n // re-running the connect flow. Resolution falls back here\n // silently — the caller never has to know which scope answered.\n const orgId = getRequestOrgId();\n if (orgId) {\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret) return { value: orgSecret.value, source: \"org\" };\n\n // Older setup flows wrote shared credentials at workspace scope.\n // Keep reading those rows so status UIs and runtime resolution agree\n // for users who connected before org-scoped Builder credentials existed.\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret) {\n return { value: workspaceSecret.value, source: \"workspace\" };\n }\n } else {\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret) {\n return { value: soloWorkspaceSecret.value, source: \"workspace\" };\n }\n }\n } catch {\n // Secrets table not ready — treat as missing.\n }\n return null;\n}\n\n/**\n * Resolve a Builder credential for the current request. User/org credentials\n * win; deployment env is only a fallback. This lets local/root .env keys keep\n * a template working while still allowing users to connect their own Builder\n * account from Settings or onboarding.\n */\nexport async function resolveBuilderCredential(\n key: string,\n): Promise<string | null> {\n const scoped = await resolveScopedBuilderCredential(key);\n if (scoped) return scoped.value;\n if (!canUseDeployCredentialFallbackForRequest()) return null;\n return readDeployCredentialEnv(key) ?? null;\n}\n\n/**\n * True when `BUILDER_PRIVATE_KEY` is set at the deployment level. This means\n * a deploy-level fallback exists; it does not prevent per-user connect.\n */\nexport function isBuilderEnvManaged(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/**\n * Resolve the Builder private key for the current request. User/org OAuth\n * credentials win; deploy-level `BUILDER_PRIVATE_KEY` is the fallback.\n */\nexport async function resolveBuilderPrivateKey(): Promise<string | null> {\n return resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n}\n\n/**\n * Resolve the current user's Builder auth header.\n * Returns `\"Bearer <key>\"` or null.\n */\nexport async function resolveBuilderAuthHeader(): Promise<string | null> {\n const key = await resolveBuilderPrivateKey();\n return key ? `Bearer ${key}` : null;\n}\n\n/**\n * Check whether the current user has a Builder private key configured\n * (per-user or deployment-level).\n */\nexport async function resolveHasBuilderPrivateKey(): Promise<boolean> {\n return !!(await resolveBuilderPrivateKey());\n}\n\n/**\n * Resolve where the effective Builder private key came from. Used by status\n * UIs so they can distinguish a deploy fallback from a user/org connection.\n */\nexport async function resolveBuilderCredentialSource(): Promise<BuilderCredentialSource | null> {\n const scoped = await resolveScopedBuilderCredential(\"BUILDER_PRIVATE_KEY\");\n if (scoped) return scoped.source;\n return canUseDeployCredentialFallbackForRequest() &&\n process.env.BUILDER_PRIVATE_KEY\n ? \"env\"\n : null;\n}\n\n/**\n * Resolve all per-user Builder credentials. Used by the status endpoint\n * and agent-chat-plugin to get orgName, userId, etc.\n */\nexport async function resolveBuilderCredentials(): Promise<{\n privateKey: string | null;\n publicKey: string | null;\n userId: string | null;\n orgName: string | null;\n orgKind: string | null;\n}> {\n const [privateKey, publicKey, userId, orgName, orgKind] = await Promise.all([\n resolveBuilderCredential(\"BUILDER_PRIVATE_KEY\"),\n resolveBuilderCredential(\"BUILDER_PUBLIC_KEY\"),\n resolveBuilderCredential(\"BUILDER_USER_ID\"),\n resolveBuilderCredential(\"BUILDER_ORG_NAME\"),\n resolveBuilderCredential(\"BUILDER_ORG_KIND\"),\n ]);\n return { privateKey, publicKey, userId, orgName, orgKind };\n}\n\nconst BUILDER_CREDENTIAL_KEYS = [\n \"BUILDER_PRIVATE_KEY\",\n \"BUILDER_PUBLIC_KEY\",\n \"BUILDER_USER_ID\",\n \"BUILDER_ORG_NAME\",\n \"BUILDER_ORG_KIND\",\n] as const;\n\n/**\n * Write Builder credentials to `app_secrets`.\n *\n * Scope decision (see `resolveCredentialWriteScope`): when the connecting\n * user is owner/admin of an active org we write at `scope: \"org\"` so every\n * member of that org auto-resolves the credentials via\n * `resolveBuilderCredential`'s org fallback — no per-user re-connect\n * needed. A plain member or a user with no active org writes at\n * `scope: \"user\"` (the safe default that doesn't trample the org's shared\n * connection).\n *\n * Returns the actual scope/scopeId used so the caller can show \"Connected\n * for Builder.io\" vs \"Connected (personal)\" in the UI.\n */\nexport async function writeBuilderCredentials(\n email: string,\n creds: {\n privateKey: string;\n publicKey: string;\n userId?: string | null;\n orgName?: string | null;\n orgKind?: string | null;\n },\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { writeAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n\n const entries: Array<{ key: string; value: string }> = [\n { key: \"BUILDER_PRIVATE_KEY\", value: creds.privateKey },\n { key: \"BUILDER_PUBLIC_KEY\", value: creds.publicKey },\n ];\n if (creds.userId) {\n entries.push({ key: \"BUILDER_USER_ID\", value: creds.userId });\n }\n if (creds.orgName) {\n entries.push({ key: \"BUILDER_ORG_NAME\", value: creds.orgName });\n }\n if (creds.orgKind) {\n entries.push({ key: \"BUILDER_ORG_KIND\", value: creds.orgKind });\n }\n await Promise.all(\n entries.map(({ key, value }) =>\n writeAppSecret({\n key,\n value,\n scope: target.scope,\n scopeId: target.scopeId,\n }),\n ),\n );\n return target;\n}\n\n/**\n * Delete Builder credentials.\n *\n * Default behaviour: clears only this user's per-user override (so a\n * member can disconnect their personal Builder identity without\n * collapsing the org-wide connection for every teammate). To revoke the\n * org's shared connection, pass `{ orgId, role }` for an owner/admin —\n * matching the same authority gate `writeBuilderCredentials` uses on\n * write. Plain members can never reach the org-scoped row.\n */\nexport async function deleteBuilderCredentials(\n email: string,\n options?: { orgId?: string | null; role?: string | null },\n): Promise<{ scope: \"user\" | \"org\"; scopeId: string }> {\n const { deleteAppSecret } = await import(\"../secrets/storage.js\");\n const target = resolveCredentialWriteScope(\n email,\n options?.orgId ?? null,\n options?.role ?? null,\n );\n await Promise.all(\n BUILDER_CREDENTIAL_KEYS.map((key) =>\n deleteAppSecret({\n key,\n scope: target.scope,\n scopeId: target.scopeId,\n }).catch(() => {}),\n ),\n );\n return target;\n}\n\n// ---------------------------------------------------------------------------\n// Generic request-scoped secret resolution\n//\n// New consumers should prefer this over reading `process.env.X` directly.\n// User-pasted and shared secrets live in `app_secrets` (encrypted). The\n// settings UI / onboarding panels can write user, org, or workspace rows.\n// Deploy-level env vars are the fallback for unauthenticated/CLI/background\n// contexts where there's no user to scope by — never the silent fallback\n// for an authenticated request, since on a multi-tenant deploy that would\n// silently identify every user as whoever set the deploy-level key\n// (KVesta Space, 2026-04).\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a request-scoped secret. Reads from `app_secrets` first (current\n * user override, active org, then workspace row); falls back to `process.env`\n * only when the deploy fallback policy allows it.\n */\nexport async function resolveSecret(key: string): Promise<string | null> {\n const email = getRequestUserEmail();\n if (email) {\n try {\n const { readAppSecret } = await import(\"../secrets/storage.js\");\n // Per-user override first.\n const userSecret = await readAppSecret({\n key,\n scope: \"user\",\n scopeId: email,\n });\n if (userSecret?.value) return userSecret.value;\n\n const orgId = getRequestOrgId();\n if (orgId) {\n // Fall back to the active org's shared row, when present. Builder\n // Connect uses this first-class org scope.\n const orgSecret = await readAppSecret({\n key,\n scope: \"org\",\n scopeId: orgId,\n });\n if (orgSecret?.value) return orgSecret.value;\n\n // Registered secrets historically used \"workspace\" scope for\n // org-shared configuration. Keep reading it so Settings status and\n // runtime resolution agree.\n const workspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: orgId,\n });\n if (workspaceSecret?.value) return workspaceSecret.value;\n } else {\n const soloWorkspaceSecret = await readAppSecret({\n key,\n scope: \"workspace\",\n scopeId: `solo:${email}`,\n });\n if (soloWorkspaceSecret?.value) return soloWorkspaceSecret.value;\n }\n } catch {\n // Secrets table not ready — treat as missing.\n }\n // Authenticated multi-tenant context: never fall back to process.env.\n // The deploy-level value would silently impersonate the actual key\n // owner across every tenant. Local/single-tenant deployments keep the\n // original env fallback for BYO-server workflows.\n return canUseDeployCredentialFallbackForRequest()\n ? process.env[key] || null\n : null;\n }\n // Unauthenticated / local-dev / CLI / background context: env fallback\n // is safe because there's no user to mis-identify.\n return process.env[key] || null;\n}\n\n// ---------------------------------------------------------------------------\n// Synchronous helpers — env-only fallbacks for contexts where per-user\n// lookup isn't possible (sync isConfigured checks, CLI scripts).\n// ---------------------------------------------------------------------------\n\n/**\n * True when a Builder private key is configured at the deployment level.\n *\n * This is the same env-only check as `isBuilderEnvManaged()`. For \"does this\n * request have access to Builder via user/org/env credentials?\" use the async\n * `resolveHasBuilderPrivateKey()`.\n */\nexport function hasBuilderPrivateKey(): boolean {\n return !!process.env.BUILDER_PRIVATE_KEY;\n}\n\n/** The origin for Builder-proxied API calls. Overridable for testing. */\nexport function getBuilderProxyOrigin(): string {\n return (\n process.env.BUILDER_PROXY_ORIGIN ||\n process.env.AIR_HOST ||\n process.env.BUILDER_API_HOST ||\n \"https://ai-services.builder.io\"\n );\n}\n\n/**\n * Base URL for the public Builder LLM gateway (distinct from the internal\n * proxy origin above — the public gateway lives at\n * api.builder.io/agent-native/gateway, while the internal origin is\n * ai-services.builder.io).\n * Override via BUILDER_GATEWAY_BASE_URL for staging / testing.\n */\nexport function getBuilderGatewayBaseUrl(): string {\n return (\n process.env.BUILDER_GATEWAY_BASE_URL ||\n \"https://api.builder.io/agent-native/gateway/v1\"\n );\n}\n\n/**\n * Base URL for Builder-managed image generation.\n * Override via BUILDER_IMAGE_GENERATION_BASE_URL for staging / testing.\n */\nexport function getBuilderImageGenerationBaseUrl(): string {\n return (\n process.env.BUILDER_IMAGE_GENERATION_BASE_URL ||\n \"https://api.builder.io/agent-native/images/v1\"\n );\n}\n\n/** Authorization header value for Builder-proxied calls (env-only). */\nexport function getBuilderAuthHeader(): string | null {\n const key = process.env.BUILDER_PRIVATE_KEY;\n return key ? `Bearer ${key}` : null;\n}\n"]}
@@ -26,7 +26,7 @@ function htmlResponse(html, status = 200) {
26
26
  * headline and secondary line. Used by every template that goes through the
27
27
  * shared Google OAuth flow. */
28
28
  function oauthSuccessCloseTabHtml(headline, footnote) {
29
- return `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Connected</title></head><body style="background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column"><svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-bottom:14px" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M9 12l2 2l4 -4"/></svg><p style="font-size:16px;margin:0 0 12px 0">${headline}</p><p style="font-size:13px;color:#888;margin:0">${footnote}</p></body></html>`;
29
+ return `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Connected</title></head><body style="background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column"><svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-bottom:14px" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M9 12l2 2l4 -4"/></svg><p style="font-size:16px;margin:0 0 12px 0">${headline}</p><p style="font-size:13px;color:#888;margin:0">${footnote}</p><script>setTimeout(function(){try{window.close()}catch(e){}},250)</script></body></html>`;
30
30
  }
31
31
  /**
32
32
  * HTML escape — minimal but covers the cases that matter when interpolating
@@ -1 +1 @@
1
- {"version":3,"file":"google-oauth.js","sourceRoot":"","sources":["../../src/server/google-oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AACZ,OAAO,EACL,UAAU,EACV,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnD,+EAA+E;AAE/E;;oDAEoD;AACpD,SAAS,YAAY,CAAC,IAAY,EAAE,MAAM,GAAG,GAAG;IAC9C,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;QACxB,MAAM;QACN,OAAO,EAAE,EAAE,cAAc,EAAE,0BAA0B,EAAE;KACxD,CAAC,CAAC;AACL,CAAC;AAED;;;gCAGgC;AAChC,SAAS,wBAAwB,CAAC,QAAgB,EAAE,QAAgB;IAClE,OAAO,4hBAA4hB,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AC,CAAC,EAAE,CAAC;IACjD,MAAM,GAAG,GAAG,SAAS,CAAC,CAAC,CAAC,aAAa,SAAS,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC;IACjE,IAAI,YAAY,EAAE,CAAC;QACjB,MAAM,QAAQ,GAAG,0BAA0B,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;QACjE,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAC9C,wEAAwE;QACxE,yEAAyE;QACzE,qEAAqE;QACrE,qEAAqE;QACrE,yEAAyE;QACzE,OAAO,YAAY,CACjB,isBAAisB,GAAG,2FAA2F,YAAY,2bAA2b,YAAY,4KAA4K,CAC/5C,CAAC;IACJ,CAAC;IACD,OAAO,YAAY,CACjB,wBAAwB,CACtB,GAAG,EACH,oDAAoD,CACrD,CACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared Google OAuth utilities for all templates.\n *\n * Handles platform detection (desktop/mobile), state encoding,\n * session token creation, and deep-link responses — the logic\n * that was previously copy-pasted across every template's\n * google-auth.ts handler.\n */\n\nimport crypto from \"node:crypto\";\nimport {\n getHeader,\n getQuery,\n setResponseStatus,\n setResponseHeader,\n type H3Event,\n} from \"h3\";\nimport {\n addSession,\n getSession,\n getSessionMaxAge,\n safeReturnPath,\n setFrameworkSessionCookie,\n} from \"./auth.js\";\nimport { getAppName } from \"./app-name.js\";\nimport { writeDesktopSso } from \"./desktop-sso.js\";\n\n// ─── Platform Detection ─────────────────────────────────────────────────────\n\n/** Return an HTML response with the correct Content-Type.\n * Uses a web-standard Response to ensure the header survives\n * Nitro dev mode's mock-node-response pipeline. */\nfunction htmlResponse(html: string, status = 200): Response {\n return new Response(html, {\n status,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Shared markup for OAuth success \"close this tab\" pages. Renders a green\n * check icon above the message, with a little breathing room between the\n * headline and secondary line. Used by every template that goes through the\n * shared Google OAuth flow. */\nfunction oauthSuccessCloseTabHtml(headline: string, footnote: string): string {\n return `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#22c55e\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M9 12l2 2l4 -4\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0\">${headline}</p><p style=\"font-size:13px;color:#888;margin:0\">${footnote}</p></body></html>`;\n}\n\n/**\n * HTML escape — minimal but covers the cases that matter when interpolating\n * user-controlled values into our OAuth callback HTML. Mirrors the helper in\n * email-template.ts; kept inline here to avoid a circular import.\n */\nfunction escapeHtml(s: string): string {\n return String(s ?? \"\")\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Detect requests from the Agent Native desktop app specifically.\n *\n * The desktop app appends `AgentNativeDesktop/<version>` to its user-agent\n * (see `packages/desktop-app/src/main/index.ts`). We check for that marker\n * rather than matching generic `Electron`, which would also match other\n * Electron-based webviews like Builder.io's Fusion, Slack desktop, Discord,\n * etc. Falsely treating those as \"the desktop app\" sends users to the\n * `agentnative://oauth-complete` deep-link success page after Google sign-in,\n * where the protocol handler can't fire and the \"Open Agent Native\" button\n * does nothing.\n *\n * Kept exported as `isElectron` for backwards compatibility with consumers.\n */\nexport function isElectron(event: H3Event): boolean {\n return /AgentNativeDesktop/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/** Detect requests from a mobile browser (iOS/Android). */\nexport function isMobile(event: H3Event): boolean {\n return /iPhone|iPad|iPod|Android/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/**\n * Build the static allowlist of origins we trust for `getOrigin`. Reads\n * `APP_URL` and `BETTER_AUTH_URL` (both are deployment-known public URLs).\n * Each entry is normalised to `${proto}://${host}` (no path). Duplicates\n * collapse, invalid entries are dropped silently.\n */\nfunction getConfiguredOriginAllowlist(): Set<string> {\n const out = new Set<string>();\n for (const raw of [process.env.APP_URL, process.env.BETTER_AUTH_URL]) {\n if (!raw) continue;\n try {\n const u = new URL(raw);\n out.add(`${u.protocol}//${u.host}`);\n } catch {\n // Ignore — env value isn't a parseable URL.\n }\n }\n return out;\n}\n\n/**\n * Get the origin from forwarded headers or Host.\n *\n * Defends against Host-header injection: in production we require the\n * resolved origin to match `APP_URL` / `BETTER_AUTH_URL`, falling back to\n * those values when the inbound headers are missing or don't match. In\n * dev we accept the inbound `Host` so localhost / ngrok / preview hosts\n * keep working without configuration. The protocol defaults to `https`\n * in production (so a TLS-terminating proxy that drops `x-forwarded-proto`\n * doesn't downgrade us to plain HTTP).\n */\nexport function getOrigin(event: H3Event): string {\n const headerHost =\n getHeader(event, \"x-forwarded-host\") || getHeader(event, \"host\");\n const isProd = process.env.NODE_ENV === \"production\";\n const headerProto =\n getHeader(event, \"x-forwarded-proto\") || (isProd ? \"https\" : \"http\");\n\n if (isProd) {\n const allow = getConfiguredOriginAllowlist();\n // If the deploy declares its public URL, prefer it over inbound headers.\n if (allow.size > 0) {\n const inbound = headerHost ? `${headerProto}://${headerHost}` : \"\";\n if (inbound && allow.has(inbound)) return inbound;\n // Inbound didn't match — fall back to the first configured origin.\n return [...allow][0];\n }\n // No allowlist configured: still default to https, but accept the\n // inbound Host (best we can do without a configured base URL).\n return `${headerProto}://${headerHost ?? \"\"}`;\n }\n\n return `${headerProto}://${headerHost ?? \"localhost\"}`;\n}\n\nfunction normalizeAppBasePath(value: string | undefined): string {\n if (!value || value === \"/\") return \"\";\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return `/${trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\")}`;\n}\n\n/** App mount prefix, if the template is served under APP_BASE_PATH. */\nexport function getAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\n/** Build an absolute same-origin URL that preserves APP_BASE_PATH. */\nexport function getAppUrl(event: H3Event, path = \"/\"): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${getOrigin(event)}${getAppBasePath()}${cleanPath}`;\n}\n\nfunction isWorkspaceOAuthCallbackRelayEnabled(): boolean {\n return (\n process.env.AGENT_NATIVE_WORKSPACE === \"1\" ||\n process.env.VITE_AGENT_NATIVE_WORKSPACE === \"1\"\n );\n}\n\nfunction isFrameworkOAuthCallbackPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/_agent-native/\") &&\n (pathname.endsWith(\"/callback\") || pathname.includes(\"/callback/\"))\n );\n}\n\nfunction getOriginalRequestPath(event: H3Event): string {\n const mountedPathname = (event as any).context?._mountedPathname;\n if (typeof mountedPathname === \"string\" && mountedPathname) {\n return mountedPathname;\n }\n\n const urlPathname = (event as any).url?.pathname;\n if (typeof urlPathname === \"string\" && urlPathname) return urlPathname;\n\n const nodeUrl = event.node?.req?.url;\n if (typeof nodeUrl === \"string\" && nodeUrl) {\n const queryStart = nodeUrl.indexOf(\"?\");\n return queryStart >= 0 ? nodeUrl.slice(0, queryStart) : nodeUrl;\n }\n\n const eventPath = (event as any).path;\n if (typeof eventPath === \"string\" && eventPath) {\n const queryStart = eventPath.indexOf(\"?\");\n return queryStart >= 0 ? eventPath.slice(0, queryStart) : eventPath;\n }\n\n return \"/\";\n}\n\nfunction isRequestUnderAppBasePath(event: H3Event): boolean {\n const basePath = getAppBasePath();\n if (!basePath) return false;\n const requestPath = getOriginalRequestPath(event);\n return (\n requestPath === `${basePath}/_agent-native` ||\n requestPath.startsWith(`${basePath}/_agent-native/`)\n );\n}\n\nfunction getDefaultOAuthRedirectUrl(event: H3Event, path: string): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n if (\n isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(cleanPath)\n ) {\n return `${getOrigin(event)}${cleanPath}`;\n }\n const basePath = isRequestUnderAppBasePath(event) ? getAppBasePath() : \"\";\n return `${getOrigin(event)}${basePath}${cleanPath}`;\n}\n\n// ─── redirect_uri Allowlist ──────────────────────────────────────────────────\n\n/**\n * Validate a user-supplied `redirect_uri` for OAuth flows.\n *\n * Defends against authorization-code interception (RFC 6819 §4.4.1.7):\n * even though the upstream provider (Google/Atlassian/Zoom) refuses\n * unregistered redirect URIs, prefix-style registrations and side\n * registrations on the same host let a malicious caller swap in an\n * attacker-controlled URI that the provider still accepts. We reject any\n * candidate that isn't on this server's own origin AND under the\n * framework's `/_agent-native/` namespace. Returns the validated URI on\n * success, or `undefined` on rejection — callers must treat `undefined`\n * as a 400.\n *\n * The intentional shape is exact-prefix:\n * - Origin must equal `getOrigin(event)` — no Host-header injection\n * reusing somebody else's registered redirect URI.\n * - Path must start with `${appBasePath}/_agent-native/` so we never\n * hand auth codes to a public marketing or open-redirect endpoint\n * on the same registered host.\n *\n * For desktop / native flows that need ephemeral `http://127.0.0.1:<port>`\n * loopback URIs, callers should validate those at the template level\n * with a dedicated allowlist — this helper rejects them by design.\n */\nexport function isAllowedOAuthRedirectUri(\n candidate: string,\n event: H3Event,\n): boolean {\n if (typeof candidate !== \"string\" || candidate.length === 0) return false;\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n return false;\n }\n // Must be same origin as our server.\n const expectedOrigin = getOrigin(event);\n let expectedUrl: URL;\n try {\n expectedUrl = new URL(expectedOrigin);\n } catch {\n return false;\n }\n if (url.protocol !== expectedUrl.protocol) return false;\n if (url.host !== expectedUrl.host) return false;\n // Must live under the framework's namespace. Workspace deploys can route\n // root /_agent-native/* to Dispatch even when Dispatch itself is mounted at\n // /dispatch, but app-prefixed requests should not be able to swap their\n // callback to that root namespace.\n const basePath = getAppBasePath();\n const allowedPrefixes =\n basePath && isRequestUnderAppBasePath(event)\n ? [\n `${basePath}/_agent-native/`,\n ...(isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(url.pathname)\n ? [\"/_agent-native/\"]\n : []),\n ]\n : [\"/_agent-native/\"];\n if (!allowedPrefixes.some((prefix) => url.pathname.startsWith(prefix))) {\n return false;\n }\n return true;\n}\n\n/**\n * Resolve the `redirect_uri` for an outbound OAuth `auth-url` request.\n *\n * Reads `?redirect_uri=` from the query and validates it via\n * `isAllowedOAuthRedirectUri`. Returns:\n * - the validated URI when supplied and allowed, OR\n * - the framework default when no override was supplied, OR\n * - `null` when an override was supplied but rejected — callers must\n * respond with 400 in that case.\n *\n * Templates that need a non-default redirect path can pass it via\n * `defaultPath` (e.g. `\"/_agent-native/google/desktop-callback\"` for\n * desktop flows).\n */\nexport function resolveOAuthRedirectUri(\n event: H3Event,\n defaultPath = \"/_agent-native/google/callback\",\n): string | null {\n const supplied = getQuery(event).redirect_uri;\n if (typeof supplied === \"string\" && supplied.length > 0) {\n return isAllowedOAuthRedirectUri(supplied, event) ? supplied : null;\n }\n return getDefaultOAuthRedirectUrl(event, defaultPath);\n}\n\n// ─── OAuth State ─────────────────────────────────────────────────────────────\n\nexport interface OAuthStatePayload {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n /**\n * Same-origin path to redirect to after a successful web-flow sign-in.\n * Threaded through the (HMAC-signed) state so it survives the round trip\n * to Google. Validated again on decode via safeReturnPath as defence in\n * depth. Has no effect on desktop / mobile / add-account flows, which\n * use their own deep-link / close-tab handling.\n */\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Ephemeral in-memory state-signing key for development. Generated lazily\n * on first read so dev sessions don't depend on filesystem writability or\n * env-var configuration. Sessions reset on each restart, which is fine\n * for dev — no real users / production data are involved.\n */\nlet _devStateSigningKey: string | undefined;\n\n/**\n * Derive a server-only signing key for HMAC verification of OAuth state.\n *\n * Uses a dedicated secret — never an OAuth client secret. Reusing a\n * client_secret (which is shared with Google / GitHub / Atlassian) as our\n * own HMAC key conflates two trust domains: rotating the client secret\n * silently invalidates every in-flight OAuth state, and any leak of the\n * client secret also lets an attacker forge our state envelopes.\n *\n * Resolution order:\n * 1. OAUTH_STATE_SECRET (preferred — dedicated to this purpose)\n * 2. BETTER_AUTH_SECRET (already used by Better Auth as a server secret)\n * 3. In dev only, an ephemeral random key (per-process)\n *\n * In production, throws if neither secret is set.\n */\nfunction getStateSigningKey(): string {\n const secret =\n process.env.OAUTH_STATE_SECRET || process.env.BETTER_AUTH_SECRET;\n if (secret) return secret;\n\n const isProd = process.env.NODE_ENV === \"production\";\n if (isProd) {\n throw new Error(\n \"OAuth state signing requires a server secret. \" +\n \"Set OAUTH_STATE_SECRET or BETTER_AUTH_SECRET in production.\",\n );\n }\n\n if (!_devStateSigningKey) {\n _devStateSigningKey = crypto.randomBytes(32).toString(\"hex\");\n }\n return _devStateSigningKey;\n}\n\n/**\n * Options for the named-argument form of {@link encodeOAuthState}.\n * Prefer this form — the positional overload is easy to misuse (the mail\n * and calendar templates historically passed `flowId` in the `returnUrl`\n * slot, smuggling state into a defence-in-depth path).\n */\nexport interface EncodeOAuthStateOptions {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Encode OAuth state into a signed base64url string.\n * The state is HMAC-signed so the callback can verify it wasn't forged,\n * preventing CSRF attacks on the OAuth flow.\n *\n * Two call shapes are supported:\n * - Recommended: pass an options object — clear, mismatch-proof.\n * `encodeOAuthState({ redirectUri, owner, desktop, ... })`\n * - Legacy positional form (kept working for backward compatibility):\n * `encodeOAuthState(redirectUri, owner, desktop, addAccount, app, returnUrl, flowId)`.\n * Callers should migrate to the options form — see the audit on\n * templates/mail and templates/calendar where the positional shape\n * led to `flowId` being smuggled in via the `returnUrl` slot.\n */\nexport function encodeOAuthState(opts: EncodeOAuthStateOptions): string;\nexport function encodeOAuthState(\n redirectUri: string,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string;\nexport function encodeOAuthState(\n redirectUriOrOpts: string | EncodeOAuthStateOptions,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string {\n const opts: EncodeOAuthStateOptions =\n typeof redirectUriOrOpts === \"string\"\n ? {\n redirectUri: redirectUriOrOpts,\n owner,\n desktop,\n addAccount,\n app,\n returnUrl,\n flowId,\n }\n : redirectUriOrOpts;\n\n const nonce = crypto.randomBytes(8).toString(\"hex\");\n const payload: Record<string, string | boolean> = {\n n: nonce,\n r: opts.redirectUri,\n };\n if (opts.owner) payload.o = opts.owner;\n if (opts.desktop) payload.d = true;\n if (opts.addAccount) payload.a = true;\n if (opts.app) payload.app = opts.app;\n if (opts.returnUrl) payload.r2 = opts.returnUrl;\n if (opts.flowId) payload.f = opts.flowId;\n const data = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const sig = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n return `${data}.${sig}`;\n}\n\n/**\n * Decode and verify OAuth state from the callback's state query parameter.\n * Rejects forged or tampered state by checking the HMAC signature.\n * Falls back to the provided URI if decoding or verification fails.\n */\nexport function decodeOAuthState(\n stateParam: string | undefined,\n fallbackUri: string,\n): OAuthStatePayload {\n if (stateParam) {\n try {\n const dotIdx = stateParam.lastIndexOf(\".\");\n if (dotIdx === -1) return { redirectUri: fallbackUri };\n\n const data = stateParam.slice(0, dotIdx);\n const sig = stateParam.slice(dotIdx + 1);\n const expected = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n\n if (\n sig.length !== expected.length ||\n !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))\n ) {\n return { redirectUri: fallbackUri };\n }\n\n const parsed = JSON.parse(Buffer.from(data, \"base64url\").toString());\n return {\n redirectUri: parsed.r || fallbackUri,\n owner: parsed.o || undefined,\n desktop: !!parsed.d,\n addAccount: !!parsed.a,\n app: typeof parsed.app === \"string\" ? parsed.app : undefined,\n // Pass returnUrl through as-is — same-origin validation runs at the\n // consumer (oauthCallbackResponse → safeReturnPath). The state is\n // HMAC-signed, but we still validate at consumption as defence in\n // depth in case the signing key ever leaks.\n returnUrl: typeof parsed.r2 === \"string\" ? parsed.r2 : undefined,\n flowId: parsed.f || undefined,\n };\n } catch {}\n }\n return { redirectUri: fallbackUri };\n}\n\n// ─── Session Creation ────────────────────────────────────────────────────────\n\nexport interface OAuthOwnerResult {\n owner: string | undefined;\n hasProductionSession: boolean;\n}\n\n/**\n * Determine the token owner from the current session and OAuth state.\n * Call this BEFORE exchangeCode to get the owner parameter.\n */\nexport async function resolveOAuthOwner(\n event: H3Event,\n stateOwner?: string,\n): Promise<OAuthOwnerResult> {\n const existingSession = await getSession(event);\n const hasProductionSession = !!existingSession?.email;\n const owner = hasProductionSession\n ? existingSession!.email\n : stateOwner || undefined;\n\n return { owner, hasProductionSession };\n}\n\nexport interface OAuthSessionResult {\n sessionToken: string | undefined;\n}\n\n/**\n * Create a session token after a successful OAuth exchange.\n *\n * Desktop and mobile apps have separate cookie jars from the system\n * browser, so they always get a fresh session token (even if the browser\n * already has one). The token is then passed via deep link so the native\n * app can inject it.\n */\nexport async function createOAuthSession(\n event: H3Event,\n email: string,\n opts: {\n hasProductionSession: boolean;\n desktop?: boolean;\n },\n): Promise<OAuthSessionResult> {\n const mobile = isMobile(event);\n const needsDeepLink = opts.desktop || mobile;\n const maxAge = getSessionMaxAge();\n\n let sessionToken: string | undefined;\n if (!opts.hasProductionSession || needsDeepLink) {\n sessionToken = crypto.randomBytes(32).toString(\"hex\");\n await addSession(sessionToken, email);\n setFrameworkSessionCookie(event, sessionToken);\n // Desktop SSO: record this session in the home-dir broker file so\n // sibling templates (each with its own database) can resolve the\n // same token without a DB row of their own. Only the PRIMARY\n // sign-in writes the broker — if a production session already\n // exists, this is an add-account flow (connecting a secondary\n // Google account for scraping) and must never switch the active\n // user across sibling templates.\n if (opts.desktop && !opts.hasProductionSession) {\n await writeDesktopSso({\n email,\n token: sessionToken,\n expiresAt: Date.now() + maxAge * 1000,\n });\n }\n }\n\n return { sessionToken };\n}\n\n// ─── Callback Responses ──────────────────────────────────────────────────────\n\n/**\n * Return the appropriate response after a successful OAuth callback.\n *\n * Handles mobile deep links, desktop deep links, add-account close-tab\n * pages, and plain web redirects — so templates don't have to.\n */\nexport function oauthCallbackResponse(\n event: H3Event,\n email: string,\n opts: {\n sessionToken?: string;\n desktop?: boolean;\n addAccount?: boolean;\n /**\n * Same-origin path to return the viewer to after a successful web\n * sign-in. Validated via safeReturnPath; falls back to \"/\" for any\n * shape that escapes same-origin. Has no effect on desktop / mobile\n * / add-account flows — those use their own deep-link handling.\n */\n returnUrl?: string;\n flowId?: string;\n appName?: string;\n },\n): Response | string | unknown | Promise<Response | string | unknown> {\n const mobile = isMobile(event);\n const query = getQuery(event);\n const callbackState =\n typeof query.state === \"string\" && query.state.length > 0\n ? query.state\n : undefined;\n\n // Mobile: deep link back to native app\n if (mobile) {\n const deepLink = buildOAuthCompleteDeepLink(\n opts.sessionToken,\n callbackState,\n );\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\"><title>Connected</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Connected! Returning to app…</p><script>window.location.href=${JSON.stringify(deepLink)};setTimeout(function(){window.location.href=\"/\"},1500)</script></body></html>`,\n );\n }\n\n // Desktop add-account: close-tab page (must come before general desktop check\n // to ensure no deep link fires and the existing session is never switched).\n if (opts.desktop && opts.addAccount) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n ),\n );\n }\n\n // Electron desktop exchange flow: mail/calendar still pass a flow id so the\n // renderer can poll as a fallback, but the main handoff should use the\n // protocol deep link so the popup returns focus to the desktop app.\n if (opts.desktop && opts.flowId && isElectron(event) && opts.sessionToken) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Desktop exchange flow (non-Electron tray app): the tray app polls the\n // desktop-exchange endpoint for the token — no deep link needed.\n if (opts.desktop && opts.flowId) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Signed in as ${safeEmail}!` : \"Signed in!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n ),\n );\n }\n\n // Desktop login: deep link back to Electron app — only when the callback\n // request actually carries the AgentNativeDesktop UA marker. Without this\n // check, any client whose OAuth state was minted with `desktop=true` (e.g.\n // a stale link, or an upstream that wrongly set `?desktop=1`) would land\n // on the `agentnative://` page where the deep link can't fire and the\n // \"Open Agent Native\" button does nothing — surfaces inside Builder.io's\n // Fusion webview hit this exact dead-end. Fall through to the web flow\n // for non-Agent-Native-Desktop clients so they get a real redirect.\n if (opts.desktop && isElectron(event)) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Add-account web flow: close-tab page. The email is rendered into the\n // page via DOM `textContent` (safe), but we still JSON-stringify so a\n // payload containing `</script>` can't break out of the script tag —\n // and explicitly assert it's a string so a callbacks like `null` or\n // an object won't end up serialised into the page.\n if (opts.addAccount) {\n const safeEmail = JSON.stringify(typeof email === \"string\" ? email : \"\");\n return htmlResponse(`<!DOCTYPE html><html><body><script>\n window.close();\n var p = document.createElement('p');\n p.style.cssText = 'font-family:system-ui;text-align:center;margin-top:40vh';\n p.textContent = 'Connected ' + ${safeEmail} + '! You can close this tab.';\n document.body.appendChild(p);\n </script></body></html>`);\n }\n\n // Web: redirect to the requested return path (validated same-origin) or\n // \"/\" if no return was supplied / the return failed validation. Returning\n // an empty string body keeps h3's `prepareResponseBody` → `FastResponse`\n // path, which merges the prepared event headers (Location + any cookies\n // set via `setCookie(event, ...)`).\n setResponseStatus(event, 302);\n setResponseHeader(event, \"Location\", safeReturnPath(opts.returnUrl));\n return \"\";\n}\n\n/** HTML error page for OAuth failures. The message is HTML-escaped — most\n * callers pass `error.message` from a token-exchange or userinfo failure,\n * which can echo upstream provider strings (and historically attacker-\n * controlled query params via the `error_description` field). */\nexport function oauthErrorPage(message: string): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connection failed</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;text-align:center\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#ef4444\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M15 9l-6 6\"/><path d=\"M9 9l6 6\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0;color:#ddd\">${safe}</p><p style=\"font-size:13px;color:#888;margin:0\"><a href=\"/\" style=\"color:#888;text-decoration:underline;text-underline-offset:3px\">Back to login</a></p></body></html>`,\n 400,\n );\n}\n\nexport function oauthDesktopExchangePage(\n message = \"Returning to the app...\",\n): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Returning</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p style=\"font-size:14px\">${safe}</p><script>window.close()</script></body></html>`,\n );\n}\n\n// ─── Internal ────────────────────────────────────────────────────────────────\n\nfunction resolveOAuthAppName(explicit?: string): string {\n const raw = explicit || getAppName() || \"Agent Native\";\n if (!/^[a-z0-9_-]+$/.test(raw)) return raw;\n return raw\n .split(/[-_]+/)\n .filter(Boolean)\n .map((word) => word[0].toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nfunction buildOAuthCompleteDeepLink(\n sessionToken?: string,\n state?: string,\n): string {\n const params = new URLSearchParams();\n if (sessionToken) params.set(\"token\", sessionToken);\n if (state) params.set(\"state\", state);\n const suffix = params.toString();\n return suffix\n ? `agentnative://oauth-complete?${suffix}`\n : \"agentnative://oauth-complete\";\n}\n\nfunction desktopSuccessPage(\n _event: H3Event,\n email?: string,\n sessionToken?: string,\n state?: string,\n): Response {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n if (sessionToken) {\n const deepLink = buildOAuthCompleteDeepLink(sessionToken, state);\n const deepLinkJson = JSON.stringify(deepLink);\n // Defence in depth: if this page somehow gets served to a UA that isn't\n // the Agent Native desktop app (server gate bypassed, stale link, etc.),\n // skip the `agentnative://` deep link entirely and bounce to the app\n // root. The deep link silently fails outside the desktop app and the\n // \"Open Agent Native\" button is a dead end in a generic browser/webview.\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title><style>@keyframes spin{to{transform:rotate(360deg)}}@keyframes fadeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.spinner{width:28px;height:28px;border:2px solid #333;border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}.fallback{display:none;flex-direction:column;align-items:center;gap:8px;animation:fadeIn .2s ease-out}.fallback.show{display:flex}</style></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;gap:16px\"><p style=\"font-size:16px;margin:0\">${msg}</p><div id=\"loading\" class=\"spinner\"></div><div id=\"fallback\" class=\"fallback\"><a href=${deepLinkJson} style=\"display:inline-block;padding:10px 24px;background:#fff;color:#000;border-radius:8px;text-decoration:none;font-size:14px;font-weight:500\">Open Agent Native</a><p style=\"font-size:12px;color:#666;margin:0\">If the app didn\\u2019t open automatically, click the button above.</p></div><script>(function(){var ua=(navigator.userAgent||\"\");if(ua.indexOf(\"AgentNativeDesktop\")===-1){window.location.replace(\"/\");return}window.location.href=${deepLinkJson};setTimeout(function(){document.getElementById(\"loading\").style.display=\"none\";document.getElementById(\"fallback\").classList.add(\"show\")},3000)})()</script></body></html>`,\n );\n }\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n \"You can close this tab and return to Agent Native.\",\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"google-oauth.js","sourceRoot":"","sources":["../../src/server/google-oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,IAAI,CAAC;AACZ,OAAO,EACL,UAAU,EACV,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,yBAAyB,GAC1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnD,+EAA+E;AAE/E;;oDAEoD;AACpD,SAAS,YAAY,CAAC,IAAY,EAAE,MAAM,GAAG,GAAG;IAC9C,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;QACxB,MAAM;QACN,OAAO,EAAE,EAAE,cAAc,EAAE,0BAA0B,EAAE;KACxD,CAAC,CAAC;AACL,CAAC;AAED;;;gCAGgC;AAChC,SAAS,wBAAwB,CAAC,QAAgB,EAAE,QAAgB;IAClE,OAAO,4hBAA4hB,QAAQ,qDAAqD,QAAQ,8FAA8F,CAA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AG,GAAG,SAAS,CAAC,CAAC,CAAC,aAAa,SAAS,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC;IACjE,IAAI,YAAY,EAAE,CAAC;QACjB,MAAM,QAAQ,GAAG,0BAA0B,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;QACjE,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAC9C,wEAAwE;QACxE,yEAAyE;QACzE,qEAAqE;QACrE,qEAAqE;QACrE,yEAAyE;QACzE,OAAO,YAAY,CACjB,isBAAisB,GAAG,2FAA2F,YAAY,2bAA2b,YAAY,4KAA4K,CAC/5C,CAAC;IACJ,CAAC;IACD,OAAO,YAAY,CACjB,wBAAwB,CACtB,GAAG,EACH,oDAAoD,CACrD,CACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Shared Google OAuth utilities for all templates.\n *\n * Handles platform detection (desktop/mobile), state encoding,\n * session token creation, and deep-link responses — the logic\n * that was previously copy-pasted across every template's\n * google-auth.ts handler.\n */\n\nimport crypto from \"node:crypto\";\nimport {\n getHeader,\n getQuery,\n setResponseStatus,\n setResponseHeader,\n type H3Event,\n} from \"h3\";\nimport {\n addSession,\n getSession,\n getSessionMaxAge,\n safeReturnPath,\n setFrameworkSessionCookie,\n} from \"./auth.js\";\nimport { getAppName } from \"./app-name.js\";\nimport { writeDesktopSso } from \"./desktop-sso.js\";\n\n// ─── Platform Detection ─────────────────────────────────────────────────────\n\n/** Return an HTML response with the correct Content-Type.\n * Uses a web-standard Response to ensure the header survives\n * Nitro dev mode's mock-node-response pipeline. */\nfunction htmlResponse(html: string, status = 200): Response {\n return new Response(html, {\n status,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/** Shared markup for OAuth success \"close this tab\" pages. Renders a green\n * check icon above the message, with a little breathing room between the\n * headline and secondary line. Used by every template that goes through the\n * shared Google OAuth flow. */\nfunction oauthSuccessCloseTabHtml(headline: string, footnote: string): string {\n return `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#22c55e\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M9 12l2 2l4 -4\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0\">${headline}</p><p style=\"font-size:13px;color:#888;margin:0\">${footnote}</p><script>setTimeout(function(){try{window.close()}catch(e){}},250)</script></body></html>`;\n}\n\n/**\n * HTML escape — minimal but covers the cases that matter when interpolating\n * user-controlled values into our OAuth callback HTML. Mirrors the helper in\n * email-template.ts; kept inline here to avoid a circular import.\n */\nfunction escapeHtml(s: string): string {\n return String(s ?? \"\")\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Detect requests from the Agent Native desktop app specifically.\n *\n * The desktop app appends `AgentNativeDesktop/<version>` to its user-agent\n * (see `packages/desktop-app/src/main/index.ts`). We check for that marker\n * rather than matching generic `Electron`, which would also match other\n * Electron-based webviews like Builder.io's Fusion, Slack desktop, Discord,\n * etc. Falsely treating those as \"the desktop app\" sends users to the\n * `agentnative://oauth-complete` deep-link success page after Google sign-in,\n * where the protocol handler can't fire and the \"Open Agent Native\" button\n * does nothing.\n *\n * Kept exported as `isElectron` for backwards compatibility with consumers.\n */\nexport function isElectron(event: H3Event): boolean {\n return /AgentNativeDesktop/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/** Detect requests from a mobile browser (iOS/Android). */\nexport function isMobile(event: H3Event): boolean {\n return /iPhone|iPad|iPod|Android/i.test(getHeader(event, \"user-agent\") || \"\");\n}\n\n/**\n * Build the static allowlist of origins we trust for `getOrigin`. Reads\n * `APP_URL` and `BETTER_AUTH_URL` (both are deployment-known public URLs).\n * Each entry is normalised to `${proto}://${host}` (no path). Duplicates\n * collapse, invalid entries are dropped silently.\n */\nfunction getConfiguredOriginAllowlist(): Set<string> {\n const out = new Set<string>();\n for (const raw of [process.env.APP_URL, process.env.BETTER_AUTH_URL]) {\n if (!raw) continue;\n try {\n const u = new URL(raw);\n out.add(`${u.protocol}//${u.host}`);\n } catch {\n // Ignore — env value isn't a parseable URL.\n }\n }\n return out;\n}\n\n/**\n * Get the origin from forwarded headers or Host.\n *\n * Defends against Host-header injection: in production we require the\n * resolved origin to match `APP_URL` / `BETTER_AUTH_URL`, falling back to\n * those values when the inbound headers are missing or don't match. In\n * dev we accept the inbound `Host` so localhost / ngrok / preview hosts\n * keep working without configuration. The protocol defaults to `https`\n * in production (so a TLS-terminating proxy that drops `x-forwarded-proto`\n * doesn't downgrade us to plain HTTP).\n */\nexport function getOrigin(event: H3Event): string {\n const headerHost =\n getHeader(event, \"x-forwarded-host\") || getHeader(event, \"host\");\n const isProd = process.env.NODE_ENV === \"production\";\n const headerProto =\n getHeader(event, \"x-forwarded-proto\") || (isProd ? \"https\" : \"http\");\n\n if (isProd) {\n const allow = getConfiguredOriginAllowlist();\n // If the deploy declares its public URL, prefer it over inbound headers.\n if (allow.size > 0) {\n const inbound = headerHost ? `${headerProto}://${headerHost}` : \"\";\n if (inbound && allow.has(inbound)) return inbound;\n // Inbound didn't match — fall back to the first configured origin.\n return [...allow][0];\n }\n // No allowlist configured: still default to https, but accept the\n // inbound Host (best we can do without a configured base URL).\n return `${headerProto}://${headerHost ?? \"\"}`;\n }\n\n return `${headerProto}://${headerHost ?? \"localhost\"}`;\n}\n\nfunction normalizeAppBasePath(value: string | undefined): string {\n if (!value || value === \"/\") return \"\";\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return `/${trimmed.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\")}`;\n}\n\n/** App mount prefix, if the template is served under APP_BASE_PATH. */\nexport function getAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\n/** Build an absolute same-origin URL that preserves APP_BASE_PATH. */\nexport function getAppUrl(event: H3Event, path = \"/\"): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${getOrigin(event)}${getAppBasePath()}${cleanPath}`;\n}\n\nfunction isWorkspaceOAuthCallbackRelayEnabled(): boolean {\n return (\n process.env.AGENT_NATIVE_WORKSPACE === \"1\" ||\n process.env.VITE_AGENT_NATIVE_WORKSPACE === \"1\"\n );\n}\n\nfunction isFrameworkOAuthCallbackPath(pathname: string): boolean {\n return (\n pathname.startsWith(\"/_agent-native/\") &&\n (pathname.endsWith(\"/callback\") || pathname.includes(\"/callback/\"))\n );\n}\n\nfunction getOriginalRequestPath(event: H3Event): string {\n const mountedPathname = (event as any).context?._mountedPathname;\n if (typeof mountedPathname === \"string\" && mountedPathname) {\n return mountedPathname;\n }\n\n const urlPathname = (event as any).url?.pathname;\n if (typeof urlPathname === \"string\" && urlPathname) return urlPathname;\n\n const nodeUrl = event.node?.req?.url;\n if (typeof nodeUrl === \"string\" && nodeUrl) {\n const queryStart = nodeUrl.indexOf(\"?\");\n return queryStart >= 0 ? nodeUrl.slice(0, queryStart) : nodeUrl;\n }\n\n const eventPath = (event as any).path;\n if (typeof eventPath === \"string\" && eventPath) {\n const queryStart = eventPath.indexOf(\"?\");\n return queryStart >= 0 ? eventPath.slice(0, queryStart) : eventPath;\n }\n\n return \"/\";\n}\n\nfunction isRequestUnderAppBasePath(event: H3Event): boolean {\n const basePath = getAppBasePath();\n if (!basePath) return false;\n const requestPath = getOriginalRequestPath(event);\n return (\n requestPath === `${basePath}/_agent-native` ||\n requestPath.startsWith(`${basePath}/_agent-native/`)\n );\n}\n\nfunction getDefaultOAuthRedirectUrl(event: H3Event, path: string): string {\n const cleanPath = path.startsWith(\"/\") ? path : `/${path}`;\n if (\n isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(cleanPath)\n ) {\n return `${getOrigin(event)}${cleanPath}`;\n }\n const basePath = isRequestUnderAppBasePath(event) ? getAppBasePath() : \"\";\n return `${getOrigin(event)}${basePath}${cleanPath}`;\n}\n\n// ─── redirect_uri Allowlist ──────────────────────────────────────────────────\n\n/**\n * Validate a user-supplied `redirect_uri` for OAuth flows.\n *\n * Defends against authorization-code interception (RFC 6819 §4.4.1.7):\n * even though the upstream provider (Google/Atlassian/Zoom) refuses\n * unregistered redirect URIs, prefix-style registrations and side\n * registrations on the same host let a malicious caller swap in an\n * attacker-controlled URI that the provider still accepts. We reject any\n * candidate that isn't on this server's own origin AND under the\n * framework's `/_agent-native/` namespace. Returns the validated URI on\n * success, or `undefined` on rejection — callers must treat `undefined`\n * as a 400.\n *\n * The intentional shape is exact-prefix:\n * - Origin must equal `getOrigin(event)` — no Host-header injection\n * reusing somebody else's registered redirect URI.\n * - Path must start with `${appBasePath}/_agent-native/` so we never\n * hand auth codes to a public marketing or open-redirect endpoint\n * on the same registered host.\n *\n * For desktop / native flows that need ephemeral `http://127.0.0.1:<port>`\n * loopback URIs, callers should validate those at the template level\n * with a dedicated allowlist — this helper rejects them by design.\n */\nexport function isAllowedOAuthRedirectUri(\n candidate: string,\n event: H3Event,\n): boolean {\n if (typeof candidate !== \"string\" || candidate.length === 0) return false;\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n return false;\n }\n // Must be same origin as our server.\n const expectedOrigin = getOrigin(event);\n let expectedUrl: URL;\n try {\n expectedUrl = new URL(expectedOrigin);\n } catch {\n return false;\n }\n if (url.protocol !== expectedUrl.protocol) return false;\n if (url.host !== expectedUrl.host) return false;\n // Must live under the framework's namespace. Workspace deploys can route\n // root /_agent-native/* to Dispatch even when Dispatch itself is mounted at\n // /dispatch, but app-prefixed requests should not be able to swap their\n // callback to that root namespace.\n const basePath = getAppBasePath();\n const allowedPrefixes =\n basePath && isRequestUnderAppBasePath(event)\n ? [\n `${basePath}/_agent-native/`,\n ...(isWorkspaceOAuthCallbackRelayEnabled() &&\n isFrameworkOAuthCallbackPath(url.pathname)\n ? [\"/_agent-native/\"]\n : []),\n ]\n : [\"/_agent-native/\"];\n if (!allowedPrefixes.some((prefix) => url.pathname.startsWith(prefix))) {\n return false;\n }\n return true;\n}\n\n/**\n * Resolve the `redirect_uri` for an outbound OAuth `auth-url` request.\n *\n * Reads `?redirect_uri=` from the query and validates it via\n * `isAllowedOAuthRedirectUri`. Returns:\n * - the validated URI when supplied and allowed, OR\n * - the framework default when no override was supplied, OR\n * - `null` when an override was supplied but rejected — callers must\n * respond with 400 in that case.\n *\n * Templates that need a non-default redirect path can pass it via\n * `defaultPath` (e.g. `\"/_agent-native/google/desktop-callback\"` for\n * desktop flows).\n */\nexport function resolveOAuthRedirectUri(\n event: H3Event,\n defaultPath = \"/_agent-native/google/callback\",\n): string | null {\n const supplied = getQuery(event).redirect_uri;\n if (typeof supplied === \"string\" && supplied.length > 0) {\n return isAllowedOAuthRedirectUri(supplied, event) ? supplied : null;\n }\n return getDefaultOAuthRedirectUrl(event, defaultPath);\n}\n\n// ─── OAuth State ─────────────────────────────────────────────────────────────\n\nexport interface OAuthStatePayload {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n /**\n * Same-origin path to redirect to after a successful web-flow sign-in.\n * Threaded through the (HMAC-signed) state so it survives the round trip\n * to Google. Validated again on decode via safeReturnPath as defence in\n * depth. Has no effect on desktop / mobile / add-account flows, which\n * use their own deep-link / close-tab handling.\n */\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Ephemeral in-memory state-signing key for development. Generated lazily\n * on first read so dev sessions don't depend on filesystem writability or\n * env-var configuration. Sessions reset on each restart, which is fine\n * for dev — no real users / production data are involved.\n */\nlet _devStateSigningKey: string | undefined;\n\n/**\n * Derive a server-only signing key for HMAC verification of OAuth state.\n *\n * Uses a dedicated secret — never an OAuth client secret. Reusing a\n * client_secret (which is shared with Google / GitHub / Atlassian) as our\n * own HMAC key conflates two trust domains: rotating the client secret\n * silently invalidates every in-flight OAuth state, and any leak of the\n * client secret also lets an attacker forge our state envelopes.\n *\n * Resolution order:\n * 1. OAUTH_STATE_SECRET (preferred — dedicated to this purpose)\n * 2. BETTER_AUTH_SECRET (already used by Better Auth as a server secret)\n * 3. In dev only, an ephemeral random key (per-process)\n *\n * In production, throws if neither secret is set.\n */\nfunction getStateSigningKey(): string {\n const secret =\n process.env.OAUTH_STATE_SECRET || process.env.BETTER_AUTH_SECRET;\n if (secret) return secret;\n\n const isProd = process.env.NODE_ENV === \"production\";\n if (isProd) {\n throw new Error(\n \"OAuth state signing requires a server secret. \" +\n \"Set OAUTH_STATE_SECRET or BETTER_AUTH_SECRET in production.\",\n );\n }\n\n if (!_devStateSigningKey) {\n _devStateSigningKey = crypto.randomBytes(32).toString(\"hex\");\n }\n return _devStateSigningKey;\n}\n\n/**\n * Options for the named-argument form of {@link encodeOAuthState}.\n * Prefer this form — the positional overload is easy to misuse (the mail\n * and calendar templates historically passed `flowId` in the `returnUrl`\n * slot, smuggling state into a defence-in-depth path).\n */\nexport interface EncodeOAuthStateOptions {\n redirectUri: string;\n owner?: string;\n desktop?: boolean;\n addAccount?: boolean;\n app?: string;\n returnUrl?: string;\n flowId?: string;\n}\n\n/**\n * Encode OAuth state into a signed base64url string.\n * The state is HMAC-signed so the callback can verify it wasn't forged,\n * preventing CSRF attacks on the OAuth flow.\n *\n * Two call shapes are supported:\n * - Recommended: pass an options object — clear, mismatch-proof.\n * `encodeOAuthState({ redirectUri, owner, desktop, ... })`\n * - Legacy positional form (kept working for backward compatibility):\n * `encodeOAuthState(redirectUri, owner, desktop, addAccount, app, returnUrl, flowId)`.\n * Callers should migrate to the options form — see the audit on\n * templates/mail and templates/calendar where the positional shape\n * led to `flowId` being smuggled in via the `returnUrl` slot.\n */\nexport function encodeOAuthState(opts: EncodeOAuthStateOptions): string;\nexport function encodeOAuthState(\n redirectUri: string,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string;\nexport function encodeOAuthState(\n redirectUriOrOpts: string | EncodeOAuthStateOptions,\n owner?: string,\n desktop?: boolean,\n addAccount?: boolean,\n app?: string,\n returnUrl?: string,\n flowId?: string,\n): string {\n const opts: EncodeOAuthStateOptions =\n typeof redirectUriOrOpts === \"string\"\n ? {\n redirectUri: redirectUriOrOpts,\n owner,\n desktop,\n addAccount,\n app,\n returnUrl,\n flowId,\n }\n : redirectUriOrOpts;\n\n const nonce = crypto.randomBytes(8).toString(\"hex\");\n const payload: Record<string, string | boolean> = {\n n: nonce,\n r: opts.redirectUri,\n };\n if (opts.owner) payload.o = opts.owner;\n if (opts.desktop) payload.d = true;\n if (opts.addAccount) payload.a = true;\n if (opts.app) payload.app = opts.app;\n if (opts.returnUrl) payload.r2 = opts.returnUrl;\n if (opts.flowId) payload.f = opts.flowId;\n const data = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const sig = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n return `${data}.${sig}`;\n}\n\n/**\n * Decode and verify OAuth state from the callback's state query parameter.\n * Rejects forged or tampered state by checking the HMAC signature.\n * Falls back to the provided URI if decoding or verification fails.\n */\nexport function decodeOAuthState(\n stateParam: string | undefined,\n fallbackUri: string,\n): OAuthStatePayload {\n if (stateParam) {\n try {\n const dotIdx = stateParam.lastIndexOf(\".\");\n if (dotIdx === -1) return { redirectUri: fallbackUri };\n\n const data = stateParam.slice(0, dotIdx);\n const sig = stateParam.slice(dotIdx + 1);\n const expected = crypto\n .createHmac(\"sha256\", getStateSigningKey())\n .update(data)\n .digest(\"base64url\");\n\n if (\n sig.length !== expected.length ||\n !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))\n ) {\n return { redirectUri: fallbackUri };\n }\n\n const parsed = JSON.parse(Buffer.from(data, \"base64url\").toString());\n return {\n redirectUri: parsed.r || fallbackUri,\n owner: parsed.o || undefined,\n desktop: !!parsed.d,\n addAccount: !!parsed.a,\n app: typeof parsed.app === \"string\" ? parsed.app : undefined,\n // Pass returnUrl through as-is — same-origin validation runs at the\n // consumer (oauthCallbackResponse → safeReturnPath). The state is\n // HMAC-signed, but we still validate at consumption as defence in\n // depth in case the signing key ever leaks.\n returnUrl: typeof parsed.r2 === \"string\" ? parsed.r2 : undefined,\n flowId: parsed.f || undefined,\n };\n } catch {}\n }\n return { redirectUri: fallbackUri };\n}\n\n// ─── Session Creation ────────────────────────────────────────────────────────\n\nexport interface OAuthOwnerResult {\n owner: string | undefined;\n hasProductionSession: boolean;\n}\n\n/**\n * Determine the token owner from the current session and OAuth state.\n * Call this BEFORE exchangeCode to get the owner parameter.\n */\nexport async function resolveOAuthOwner(\n event: H3Event,\n stateOwner?: string,\n): Promise<OAuthOwnerResult> {\n const existingSession = await getSession(event);\n const hasProductionSession = !!existingSession?.email;\n const owner = hasProductionSession\n ? existingSession!.email\n : stateOwner || undefined;\n\n return { owner, hasProductionSession };\n}\n\nexport interface OAuthSessionResult {\n sessionToken: string | undefined;\n}\n\n/**\n * Create a session token after a successful OAuth exchange.\n *\n * Desktop and mobile apps have separate cookie jars from the system\n * browser, so they always get a fresh session token (even if the browser\n * already has one). The token is then passed via deep link so the native\n * app can inject it.\n */\nexport async function createOAuthSession(\n event: H3Event,\n email: string,\n opts: {\n hasProductionSession: boolean;\n desktop?: boolean;\n },\n): Promise<OAuthSessionResult> {\n const mobile = isMobile(event);\n const needsDeepLink = opts.desktop || mobile;\n const maxAge = getSessionMaxAge();\n\n let sessionToken: string | undefined;\n if (!opts.hasProductionSession || needsDeepLink) {\n sessionToken = crypto.randomBytes(32).toString(\"hex\");\n await addSession(sessionToken, email);\n setFrameworkSessionCookie(event, sessionToken);\n // Desktop SSO: record this session in the home-dir broker file so\n // sibling templates (each with its own database) can resolve the\n // same token without a DB row of their own. Only the PRIMARY\n // sign-in writes the broker — if a production session already\n // exists, this is an add-account flow (connecting a secondary\n // Google account for scraping) and must never switch the active\n // user across sibling templates.\n if (opts.desktop && !opts.hasProductionSession) {\n await writeDesktopSso({\n email,\n token: sessionToken,\n expiresAt: Date.now() + maxAge * 1000,\n });\n }\n }\n\n return { sessionToken };\n}\n\n// ─── Callback Responses ──────────────────────────────────────────────────────\n\n/**\n * Return the appropriate response after a successful OAuth callback.\n *\n * Handles mobile deep links, desktop deep links, add-account close-tab\n * pages, and plain web redirects — so templates don't have to.\n */\nexport function oauthCallbackResponse(\n event: H3Event,\n email: string,\n opts: {\n sessionToken?: string;\n desktop?: boolean;\n addAccount?: boolean;\n /**\n * Same-origin path to return the viewer to after a successful web\n * sign-in. Validated via safeReturnPath; falls back to \"/\" for any\n * shape that escapes same-origin. Has no effect on desktop / mobile\n * / add-account flows — those use their own deep-link handling.\n */\n returnUrl?: string;\n flowId?: string;\n appName?: string;\n },\n): Response | string | unknown | Promise<Response | string | unknown> {\n const mobile = isMobile(event);\n const query = getQuery(event);\n const callbackState =\n typeof query.state === \"string\" && query.state.length > 0\n ? query.state\n : undefined;\n\n // Mobile: deep link back to native app\n if (mobile) {\n const deepLink = buildOAuthCompleteDeepLink(\n opts.sessionToken,\n callbackState,\n );\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\"><title>Connected</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Connected! Returning to app…</p><script>window.location.href=${JSON.stringify(deepLink)};setTimeout(function(){window.location.href=\"/\"},1500)</script></body></html>`,\n );\n }\n\n // Desktop add-account: close-tab page (must come before general desktop check\n // to ensure no deep link fires and the existing session is never switched).\n if (opts.desktop && opts.addAccount) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n ),\n );\n }\n\n // Electron desktop exchange flow: mail/calendar still pass a flow id so the\n // renderer can poll as a fallback, but the main handoff should use the\n // protocol deep link so the popup returns focus to the desktop app.\n if (opts.desktop && opts.flowId && isElectron(event) && opts.sessionToken) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Desktop exchange flow (non-Electron tray app): the tray app polls the\n // desktop-exchange endpoint for the token — no deep link needed.\n if (opts.desktop && opts.flowId) {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const safeAppName = escapeHtml(resolveOAuthAppName(opts.appName));\n const msg = safeEmail ? `Signed in as ${safeEmail}!` : \"Signed in!\";\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n `You can close this tab and return to ${safeAppName}.`,\n ),\n );\n }\n\n // Desktop login: deep link back to Electron app — only when the callback\n // request actually carries the AgentNativeDesktop UA marker. Without this\n // check, any client whose OAuth state was minted with `desktop=true` (e.g.\n // a stale link, or an upstream that wrongly set `?desktop=1`) would land\n // on the `agentnative://` page where the deep link can't fire and the\n // \"Open Agent Native\" button does nothing — surfaces inside Builder.io's\n // Fusion webview hit this exact dead-end. Fall through to the web flow\n // for non-Agent-Native-Desktop clients so they get a real redirect.\n if (opts.desktop && isElectron(event)) {\n return desktopSuccessPage(event, email, opts.sessionToken, callbackState);\n }\n\n // Add-account web flow: close-tab page. The email is rendered into the\n // page via DOM `textContent` (safe), but we still JSON-stringify so a\n // payload containing `</script>` can't break out of the script tag —\n // and explicitly assert it's a string so a callbacks like `null` or\n // an object won't end up serialised into the page.\n if (opts.addAccount) {\n const safeEmail = JSON.stringify(typeof email === \"string\" ? email : \"\");\n return htmlResponse(`<!DOCTYPE html><html><body><script>\n window.close();\n var p = document.createElement('p');\n p.style.cssText = 'font-family:system-ui;text-align:center;margin-top:40vh';\n p.textContent = 'Connected ' + ${safeEmail} + '! You can close this tab.';\n document.body.appendChild(p);\n </script></body></html>`);\n }\n\n // Web: redirect to the requested return path (validated same-origin) or\n // \"/\" if no return was supplied / the return failed validation. Returning\n // an empty string body keeps h3's `prepareResponseBody` → `FastResponse`\n // path, which merges the prepared event headers (Location + any cookies\n // set via `setCookie(event, ...)`).\n setResponseStatus(event, 302);\n setResponseHeader(event, \"Location\", safeReturnPath(opts.returnUrl));\n return \"\";\n}\n\n/** HTML error page for OAuth failures. The message is HTML-escaped — most\n * callers pass `error.message` from a token-exchange or userinfo failure,\n * which can echo upstream provider strings (and historically attacker-\n * controlled query params via the `error_description` field). */\nexport function oauthErrorPage(message: string): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connection failed</title></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;text-align:center\"><svg width=\"44\" height=\"44\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#ef4444\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"margin-bottom:14px\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M15 9l-6 6\"/><path d=\"M9 9l6 6\"/></svg><p style=\"font-size:16px;margin:0 0 12px 0;color:#ddd\">${safe}</p><p style=\"font-size:13px;color:#888;margin:0\"><a href=\"/\" style=\"color:#888;text-decoration:underline;text-underline-offset:3px\">Back to login</a></p></body></html>`,\n 400,\n );\n}\n\nexport function oauthDesktopExchangePage(\n message = \"Returning to the app...\",\n): Response {\n const safe = escapeHtml(message);\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Returning</title></head><body style=\"background:#111;color:#aaa;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p style=\"font-size:14px\">${safe}</p><script>window.close()</script></body></html>`,\n );\n}\n\n// ─── Internal ────────────────────────────────────────────────────────────────\n\nfunction resolveOAuthAppName(explicit?: string): string {\n const raw = explicit || getAppName() || \"Agent Native\";\n if (!/^[a-z0-9_-]+$/.test(raw)) return raw;\n return raw\n .split(/[-_]+/)\n .filter(Boolean)\n .map((word) => word[0].toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nfunction buildOAuthCompleteDeepLink(\n sessionToken?: string,\n state?: string,\n): string {\n const params = new URLSearchParams();\n if (sessionToken) params.set(\"token\", sessionToken);\n if (state) params.set(\"state\", state);\n const suffix = params.toString();\n return suffix\n ? `agentnative://oauth-complete?${suffix}`\n : \"agentnative://oauth-complete\";\n}\n\nfunction desktopSuccessPage(\n _event: H3Event,\n email?: string,\n sessionToken?: string,\n state?: string,\n): Response {\n const safeEmail = email ? escapeHtml(email) : \"\";\n const msg = safeEmail ? `Connected ${safeEmail}!` : \"Connected!\";\n if (sessionToken) {\n const deepLink = buildOAuthCompleteDeepLink(sessionToken, state);\n const deepLinkJson = JSON.stringify(deepLink);\n // Defence in depth: if this page somehow gets served to a UA that isn't\n // the Agent Native desktop app (server gate bypassed, stale link, etc.),\n // skip the `agentnative://` deep link entirely and bounce to the app\n // root. The deep link silently fails outside the desktop app and the\n // \"Open Agent Native\" button is a dead end in a generic browser/webview.\n return htmlResponse(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Connected</title><style>@keyframes spin{to{transform:rotate(360deg)}}@keyframes fadeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.spinner{width:28px;height:28px;border:2px solid #333;border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}.fallback{display:none;flex-direction:column;align-items:center;gap:8px;animation:fadeIn .2s ease-out}.fallback.show{display:flex}</style></head><body style=\"background:#111;color:#ccc;font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;flex-direction:column;gap:16px\"><p style=\"font-size:16px;margin:0\">${msg}</p><div id=\"loading\" class=\"spinner\"></div><div id=\"fallback\" class=\"fallback\"><a href=${deepLinkJson} style=\"display:inline-block;padding:10px 24px;background:#fff;color:#000;border-radius:8px;text-decoration:none;font-size:14px;font-weight:500\">Open Agent Native</a><p style=\"font-size:12px;color:#666;margin:0\">If the app didn\\u2019t open automatically, click the button above.</p></div><script>(function(){var ua=(navigator.userAgent||\"\");if(ua.indexOf(\"AgentNativeDesktop\")===-1){window.location.replace(\"/\");return}window.location.href=${deepLinkJson};setTimeout(function(){document.getElementById(\"loading\").style.display=\"none\";document.getElementById(\"fallback\").classList.add(\"show\")},3000)})()</script></body></html>`,\n );\n }\n return htmlResponse(\n oauthSuccessCloseTabHtml(\n msg,\n \"You can close this tab and return to Agent Native.\",\n ),\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.12.24",
3
+ "version": "0.12.25",
4
4
  "type": "module",
5
5
  "description": "Framework for agent-native application development — where AI agents and UI share state via files",
6
6
  "license": "MIT",