@hubspot/app-connect-sdk 1.0.0-alpha.11 → 1.0.0-alpha.13

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 (199) hide show
  1. package/.turbo/turbo-format$colon$check.log +1 -1
  2. package/.turbo/turbo-test.log +81 -50
  3. package/.turbo/turbo-tsdown.log +119 -119
  4. package/build/tsconfig.browser.tsbuildinfo +1 -1
  5. package/build/tsconfig.server.tsbuildinfo +1 -1
  6. package/dist/browser/{HubSpotAppConnect-COQgPrFn.js → HubSpotAppConnect-DFe9b90e.js} +1 -2
  7. package/dist/browser/HubSpotAppConnect-DFe9b90e.js.map +1 -0
  8. package/dist/browser/create-crdncXsh.js.map +1 -1
  9. package/dist/browser/react/lovable.d.ts +1 -2
  10. package/dist/browser/react/lovable.js +1 -1
  11. package/dist/browser/react/lovable.js.map +1 -1
  12. package/dist/browser/react.d.ts +1 -2
  13. package/dist/browser/react.js +1 -1
  14. package/dist/server/api-client-core/apis/account/account-info.generated.js.map +1 -1
  15. package/dist/server/api-client-core/apis/account/audit-logs.generated.js.map +1 -1
  16. package/dist/server/api-client-core/apis/auth/oauth.generated.js.map +1 -1
  17. package/dist/server/api-client-core/apis/automation/actions.generated.js.map +1 -1
  18. package/dist/server/api-client-core/apis/automation/sequences.generated.js.map +1 -1
  19. package/dist/server/api-client-core/apis/business-units.generated.js.map +1 -1
  20. package/dist/server/api-client-core/apis/cms/authors.generated.js.map +1 -1
  21. package/dist/server/api-client-core/apis/cms/blog-settings.generated.js.map +1 -1
  22. package/dist/server/api-client-core/apis/cms/cms-content-audit.generated.js.map +1 -1
  23. package/dist/server/api-client-core/apis/cms/domains.generated.js.map +1 -1
  24. package/dist/server/api-client-core/apis/cms/hubdb.generated.js.map +1 -1
  25. package/dist/server/api-client-core/apis/cms/media-bridge.generated.js.map +1 -1
  26. package/dist/server/api-client-core/apis/cms/pages.generated.js.map +1 -1
  27. package/dist/server/api-client-core/apis/cms/posts.generated.js.map +1 -1
  28. package/dist/server/api-client-core/apis/cms/site-search.generated.js.map +1 -1
  29. package/dist/server/api-client-core/apis/cms/source-code.generated.js.map +1 -1
  30. package/dist/server/api-client-core/apis/cms/tags.generated.js.map +1 -1
  31. package/dist/server/api-client-core/apis/cms/url-mappings.generated.js.map +1 -1
  32. package/dist/server/api-client-core/apis/cms/url-redirects.generated.js.map +1 -1
  33. package/dist/server/api-client-core/apis/communication-preferences/subscriptions.generated.js.map +1 -1
  34. package/dist/server/api-client-core/apis/conversations/custom-channels.generated.js.map +1 -1
  35. package/dist/server/api-client-core/apis/conversations/visitor-identification.generated.js.map +1 -1
  36. package/dist/server/api-client-core/apis/conversations.generated.js.map +1 -1
  37. package/dist/server/api-client-core/apis/crm/app-uninstalls.generated.js.map +1 -1
  38. package/dist/server/api-client-core/apis/crm/appointments.generated.js.map +1 -1
  39. package/dist/server/api-client-core/apis/crm/associations-schema.generated.js.map +1 -1
  40. package/dist/server/api-client-core/apis/crm/associations.generated.js.map +1 -1
  41. package/dist/server/api-client-core/apis/crm/calling-extensions.generated.js.map +1 -1
  42. package/dist/server/api-client-core/apis/crm/calls.generated.js.map +1 -1
  43. package/dist/server/api-client-core/apis/crm/carts.generated.js.map +1 -1
  44. package/dist/server/api-client-core/apis/crm/commerce-payments.generated.js.map +1 -1
  45. package/dist/server/api-client-core/apis/crm/commerce-subscriptions.generated.js.map +1 -1
  46. package/dist/server/api-client-core/apis/crm/communications.generated.js.map +1 -1
  47. package/dist/server/api-client-core/apis/crm/companies.generated.js.map +1 -1
  48. package/dist/server/api-client-core/apis/crm/contacts.generated.js.map +1 -1
  49. package/dist/server/api-client-core/apis/crm/contracts.generated.js.map +1 -1
  50. package/dist/server/api-client-core/apis/crm/courses.generated.js.map +1 -1
  51. package/dist/server/api-client-core/apis/crm/crm-owners.generated.js.map +1 -1
  52. package/dist/server/api-client-core/apis/crm/custom-objects.generated.js.map +1 -1
  53. package/dist/server/api-client-core/apis/crm/deal-splits.generated.js.map +1 -1
  54. package/dist/server/api-client-core/apis/crm/deals.generated.js.map +1 -1
  55. package/dist/server/api-client-core/apis/crm/discounts.generated.js.map +1 -1
  56. package/dist/server/api-client-core/apis/crm/emails.generated.js.map +1 -1
  57. package/dist/server/api-client-core/apis/crm/exports.generated.js.map +1 -1
  58. package/dist/server/api-client-core/apis/crm/feedback-submissions.generated.js.map +1 -1
  59. package/dist/server/api-client-core/apis/crm/fees.generated.js.map +1 -1
  60. package/dist/server/api-client-core/apis/crm/goal-targets.generated.js.map +1 -1
  61. package/dist/server/api-client-core/apis/crm/imports.generated.js.map +1 -1
  62. package/dist/server/api-client-core/apis/crm/invoices.generated.js.map +1 -1
  63. package/dist/server/api-client-core/apis/crm/leads.generated.js.map +1 -1
  64. package/dist/server/api-client-core/apis/crm/limits-tracking.generated.js.map +1 -1
  65. package/dist/server/api-client-core/apis/crm/line-items.generated.js.map +1 -1
  66. package/dist/server/api-client-core/apis/crm/listings.generated.js.map +1 -1
  67. package/dist/server/api-client-core/apis/crm/lists.generated.js.map +1 -1
  68. package/dist/server/api-client-core/apis/crm/meetings.generated.js.map +1 -1
  69. package/dist/server/api-client-core/apis/crm/notes.generated.js.map +1 -1
  70. package/dist/server/api-client-core/apis/crm/object-library.generated.js.map +1 -1
  71. package/dist/server/api-client-core/apis/crm/objects.generated.js.map +1 -1
  72. package/dist/server/api-client-core/apis/crm/orders.generated.js.map +1 -1
  73. package/dist/server/api-client-core/apis/crm/partner-clients.generated.js.map +1 -1
  74. package/dist/server/api-client-core/apis/crm/partner-services.generated.js.map +1 -1
  75. package/dist/server/api-client-core/apis/crm/pipelines.generated.js.map +1 -1
  76. package/dist/server/api-client-core/apis/crm/postal-mail.generated.js.map +1 -1
  77. package/dist/server/api-client-core/apis/crm/products.generated.js.map +1 -1
  78. package/dist/server/api-client-core/apis/crm/projects.generated.js.map +1 -1
  79. package/dist/server/api-client-core/apis/crm/properties.generated.js.map +1 -1
  80. package/dist/server/api-client-core/apis/crm/property-validations.generated.js.map +1 -1
  81. package/dist/server/api-client-core/apis/crm/public-app-crm-cards.generated.js.map +1 -1
  82. package/dist/server/api-client-core/apis/crm/public-app-feature-flags.generated.js.map +1 -1
  83. package/dist/server/api-client-core/apis/crm/quotes.generated.js.map +1 -1
  84. package/dist/server/api-client-core/apis/crm/schemas.generated.js.map +1 -1
  85. package/dist/server/api-client-core/apis/crm/services.generated.js.map +1 -1
  86. package/dist/server/api-client-core/apis/crm/tasks.generated.js.map +1 -1
  87. package/dist/server/api-client-core/apis/crm/taxes.generated.js.map +1 -1
  88. package/dist/server/api-client-core/apis/crm/tickets.generated.js.map +1 -1
  89. package/dist/server/api-client-core/apis/crm/timeline.generated.js.map +1 -1
  90. package/dist/server/api-client-core/apis/crm/transcriptions.generated.js.map +1 -1
  91. package/dist/server/api-client-core/apis/crm/users.generated.js.map +1 -1
  92. package/dist/server/api-client-core/apis/crm/video-conferencing-extension.generated.js.map +1 -1
  93. package/dist/server/api-client-core/apis/events/manage-event-definitions.generated.js.map +1 -1
  94. package/dist/server/api-client-core/apis/events/send-event-completions.generated.js.map +1 -1
  95. package/dist/server/api-client-core/apis/events.generated.js.map +1 -1
  96. package/dist/server/api-client-core/apis/files.generated.js.map +1 -1
  97. package/dist/server/api-client-core/apis/marketing/campaigns-public-api.generated.js.map +1 -1
  98. package/dist/server/api-client-core/apis/marketing/marketing-emails.generated.js.map +1 -1
  99. package/dist/server/api-client-core/apis/marketing/marketing-events.generated.js.map +1 -1
  100. package/dist/server/api-client-core/apis/marketing/single-send.generated.js.map +1 -1
  101. package/dist/server/api-client-core/apis/marketing/transactional-single-send.generated.js.map +1 -1
  102. package/dist/server/api-client-core/apis/meta/origins.generated.js.map +1 -1
  103. package/dist/server/api-client-core/apis/scheduler/meetings.generated.js.map +1 -1
  104. package/dist/server/api-client-core/apis/settings/multicurrency.generated.js.map +1 -1
  105. package/dist/server/api-client-core/apis/settings/tax-rates.generated.js.map +1 -1
  106. package/dist/server/api-client-core/apis/settings/user-provisioning.generated.js.map +1 -1
  107. package/dist/server/api-client-core/apis/webhooks-journal.generated.js.map +1 -1
  108. package/dist/server/api-client-core/apis/webhooks.generated.js.map +1 -1
  109. package/dist/server/api-client-core/binary-data.js.map +1 -1
  110. package/dist/server/api-client-core/client.js +5 -1
  111. package/dist/server/api-client-core/client.js.map +1 -1
  112. package/dist/server/api-client-core/codegen-helpers/file-op-wrappers.js.map +1 -1
  113. package/dist/server/api-client-core/errors.js.map +1 -1
  114. package/dist/server/api-client-core/op.js.map +1 -1
  115. package/dist/server/api-client-core/pagination.js.map +1 -1
  116. package/dist/server/api-client-core/plugins/fetch-transport.js +28 -8
  117. package/dist/server/api-client-core/plugins/fetch-transport.js.map +1 -1
  118. package/dist/server/constants.js.map +1 -1
  119. package/dist/server/deno/start.js.map +1 -1
  120. package/dist/server/hono/hono-request-handler.js +21 -17
  121. package/dist/server/hono/hono-request-handler.js.map +1 -1
  122. package/dist/server/hono/hubspot-connect-routes/auth-complete.js +2 -1
  123. package/dist/server/hono/hubspot-connect-routes/auth-complete.js.map +1 -1
  124. package/dist/server/hono/hubspot-connect-routes/auth-init-session.js +3 -1
  125. package/dist/server/hono/hubspot-connect-routes/auth-init-session.js.map +1 -1
  126. package/dist/server/hono/hubspot-connect-routes/auth-logout.js +14 -8
  127. package/dist/server/hono/hubspot-connect-routes/auth-logout.js.map +1 -1
  128. package/dist/server/hono/hubspot-connect-routes/auth-refresh.js +26 -18
  129. package/dist/server/hono/hubspot-connect-routes/auth-refresh.js.map +1 -1
  130. package/dist/server/hono/hubspot-connect-routes/cimd-client-metadata-types.js.map +1 -1
  131. package/dist/server/hono/hubspot-connect-routes/cimd-public-routes.js +4 -1
  132. package/dist/server/hono/hubspot-connect-routes/cimd-public-routes.js.map +1 -1
  133. package/dist/server/hono/hubspot-connect-routes/fetch-hubspot-client-metadata.js.map +1 -1
  134. package/dist/server/hono/hubspot-connect-routes/hubspot-connect-routes.js.map +1 -1
  135. package/dist/server/hono/hubspot-connect-routes/load-hubspot-connect-routes-env.js.map +1 -1
  136. package/dist/server/hono/hubspot-connect-routes/oauth-client.js.map +1 -1
  137. package/dist/server/hono/hubspot-connect-routes/utils.js +5 -5
  138. package/dist/server/hono/hubspot-connect-routes/utils.js.map +1 -1
  139. package/dist/server/hono/types.d.ts +0 -5
  140. package/dist/server/hono/utils/cookie-utils.js.map +1 -1
  141. package/dist/server/hono/utils/cors-middleware.js.map +1 -1
  142. package/dist/server/import-app-keys.js.map +1 -1
  143. package/dist/server/lovable/create-app-function-start.d.ts +1 -1
  144. package/dist/server/lovable/create-app-function-start.js +4 -5
  145. package/dist/server/lovable/create-app-function-start.js.map +1 -1
  146. package/dist/server/lovable/hubspot-connect/index.js.map +1 -1
  147. package/dist/server/lovable/hubspot-connect/run-hubspot-connect-lovable-server.js +11 -11
  148. package/dist/server/lovable/hubspot-connect/run-hubspot-connect-lovable-server.js.map +1 -1
  149. package/dist/server/sanitize-request.js +0 -11
  150. package/dist/server/sanitize-request.js.map +1 -1
  151. package/dist/server/secure-start-core.js.map +1 -1
  152. package/dist/server/shared/constants.js +2 -2
  153. package/dist/server/shared/constants.js.map +1 -1
  154. package/dist/server/shared/encoding/base64.js.map +1 -1
  155. package/dist/server/shared/encoding/sha256.js.map +1 -1
  156. package/dist/server/shared/logger.js.map +1 -1
  157. package/dist/server/types.d.ts +1 -35
  158. package/dist/server/utils/cookie-utils.js.map +1 -1
  159. package/dist/server/utils/dpop-utils.js.map +1 -1
  160. package/dist/server/utils/env-utils.js +1 -1
  161. package/dist/server/utils/env-utils.js.map +1 -1
  162. package/dist/server/utils/hubspot-dpop-auth-headers.js +38 -0
  163. package/dist/server/utils/hubspot-dpop-auth-headers.js.map +1 -0
  164. package/dist/server/utils/jwk-utils.js.map +1 -1
  165. package/dist/server/utils/jwt-utils.js.map +1 -1
  166. package/package.json +16 -16
  167. package/src/browser/app-connect-controller/init.test.ts +4 -4
  168. package/src/browser/app-connect-controller/init.ts +2 -2
  169. package/src/browser/react/components/ConnectButton/ConnectButton.tsx +0 -1
  170. package/src/server/api-client-core/client.ts +5 -1
  171. package/src/server/api-client-core/plugins/fetch-transport.test.ts +114 -0
  172. package/src/server/api-client-core/plugins/fetch-transport.ts +65 -11
  173. package/src/server/api-client-core/plugins/index.ts +1 -0
  174. package/src/server/hono/hono-request-handler.ts +33 -19
  175. package/src/server/hono/hubspot-connect-routes/auth-complete.test.ts +2 -2
  176. package/src/server/hono/hubspot-connect-routes/auth-complete.ts +1 -0
  177. package/src/server/hono/hubspot-connect-routes/auth-init-session.test.ts +2 -2
  178. package/src/server/hono/hubspot-connect-routes/auth-init-session.ts +2 -0
  179. package/src/server/hono/hubspot-connect-routes/auth-logout.ts +21 -10
  180. package/src/server/hono/hubspot-connect-routes/auth-refresh.ts +18 -9
  181. package/src/server/hono/hubspot-connect-routes/cimd-public-routes.test.ts +7 -6
  182. package/src/server/hono/hubspot-connect-routes/cimd-public-routes.ts +5 -1
  183. package/src/server/hono/hubspot-connect-routes/hubspot-connect-routes.ts +2 -1
  184. package/src/server/hono/hubspot-connect-routes/utils.test.ts +16 -46
  185. package/src/server/hono/hubspot-connect-routes/utils.ts +6 -6
  186. package/src/server/hono/types.ts +0 -5
  187. package/src/server/lovable/create-app-function-start.ts +4 -4
  188. package/src/server/lovable/hubspot-connect/run-hubspot-connect-lovable-server.ts +12 -12
  189. package/src/server/sanitize-request.ts +1 -12
  190. package/src/server/types.ts +0 -36
  191. package/src/server/utils/env-utils.ts +1 -1
  192. package/src/server/utils/hubspot-dpop-auth-headers.test.ts +43 -0
  193. package/src/server/utils/hubspot-dpop-auth-headers.ts +48 -0
  194. package/src/shared/constants.ts +1 -1
  195. package/dist/browser/HubSpotAppConnect-COQgPrFn.js.map +0 -1
  196. package/dist/server/proxy.js +0 -68
  197. package/dist/server/proxy.js.map +0 -1
  198. package/src/server/proxy.test.ts +0 -80
  199. package/src/server/proxy.ts +0 -119
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","names":[],"sources":["../../src/server/constants.ts"],"sourcesContent":["/**\n * Cookie name carrying the DPoP-bound access token. Uses the\n * `__Host-` prefix so the browser only accepts it from a `Secure`\n * response with `Path=/` — a defense-in-depth against subdomain\n * cookie injection.\n */\nexport const HUBSPOT_ACCESS_TOKEN_COOKIE_NAME = '__Host-hs_access_token';\n\n/**\n * Cookie carrying the opaque app-session ID. Hashed before being put\n * on the wire as a DPoP `sid` claim.\n */\nexport const HUBSPOT_APP_SID_COOKIE_NAME = '__Host-hs_app_sid';\n\n/**\n * Cookie pinning the browser-facing app origin (e.g.\n * `https://app.example.com`) for the lifetime of an app session.\n * Set by `auth/init-session` from the request's `Origin` header and\n * read by:\n *\n * - The CORS middleware to emit a credentialed\n * `Access-Control-Allow-Origin` value (`*` is forbidden when\n * `Access-Control-Allow-Credentials: true`).\n * - `auth/complete` to rebuild the OAuth `redirect_uri` it sent to\n * HubSpot during `init-session` (the token endpoint validates that\n * the two values match).\n *\n * `__Host-` prefixed (Path=/, Secure, no Domain), so the same\n * function host can serve both `hubspot-connect` and `api` routes\n * and read the cookie from either.\n */\nexport const HUBSPOT_APP_ORIGIN_COOKIE_NAME = '__Host-hs_app_origin';\n\n/**\n * Prefix used for refresh-token cookies. Each session gets its own\n * cookie name (`hs_refresh_<sidHash>`) so multiple devices/tabs can\n * coexist without overwriting each other's refresh tokens.\n */\nexport const HUBSPOT_REFRESH_COOKIE_PREFIX = 'hs_refresh_';\n\nconst PROTECTED_COOKIE_NAMES = new Set([\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n]);\n\n/**\n * Returns `true` for cookies the SDK manages internally\n * (access token, session ID, any refresh-token cookie). The\n * `sanitizeRequest` helper uses this to strip these cookies from the\n * request before user code sees it, ensuring user route handlers\n * cannot accidentally leak them in logs or proxy them upstream.\n */\nexport function isProtectedCookieName(cookieName: string): boolean {\n return (\n PROTECTED_COOKIE_NAMES.has(cookieName) ||\n cookieName.startsWith(HUBSPOT_REFRESH_COOKIE_PREFIX)\n );\n}\n\n/**\n * Cookie carrying the PKCE code verifier between `init-session` and\n * `auth/complete`. Set with `SameSite=None; Secure; Partitioned` so the\n * frontend's credentialed cross-site `POST /auth/complete` (made from\n * the OAuth callback page on the app origin to the SDK's edge function\n * origin) carries it through. `Lax` would silently drop it on that\n * fetch, breaking every successful HubSpot redirect.\n */\nexport const TEMP_COOKIE_PKCE_VERIFIER = '__hs_pkce_verifier';\n\n/**\n * Cookie carrying the OAuth `state` value between `init-session` and\n * `auth/complete`. Compared against the `state` query parameter as the\n * primary CSRF defense. Same `SameSite=None; Secure; Partitioned`\n * attributes as `TEMP_COOKIE_PKCE_VERIFIER` for the same cross-site\n * `POST /auth/complete` reason.\n */\nexport const TEMP_COOKIE_OAUTH_STATE = '__hs_oauth_state';\n"],"mappings":";;;;;;;AAMA,MAAa,mCAAmC;;;;;AAMhD,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,MAAa,iCAAiC;;;;;;AAO9C,MAAa,gCAAgC;AAE7C,MAAM,yBAAyB,IAAI,IAAI;CACrC;CACA;CACA;CACD,CAAC;;;;;;;;AASF,SAAgB,sBAAsB,YAA6B;CACjE,OACE,uBAAuB,IAAI,WAAW,IACtC,WAAW,WAAA,cAAyC;;;;;;;;;;AAYxD,MAAa,4BAA4B;;;;;;;;AASzC,MAAa,0BAA0B"}
1
+ {"version":3,"file":"constants.js","names":[],"sources":["../../src/server/constants.ts"],"sourcesContent":["/**\n * Cookie name carrying the DPoP-bound access token. Uses the\n * `__Host-` prefix so the browser only accepts it from a `Secure`\n * response with `Path=/` — a defense-in-depth against subdomain\n * cookie injection.\n */\nexport const HUBSPOT_ACCESS_TOKEN_COOKIE_NAME = '__Host-hs_access_token';\n\n/**\n * Cookie carrying the opaque app-session ID. Hashed before being put\n * on the wire as a DPoP `sid` claim.\n */\nexport const HUBSPOT_APP_SID_COOKIE_NAME = '__Host-hs_app_sid';\n\n/**\n * Cookie pinning the browser-facing app origin (e.g.\n * `https://app.example.com`) for the lifetime of an app session.\n * Set by `auth/init-session` from the request's `Origin` header and\n * read by:\n *\n * - The CORS middleware to emit a credentialed\n * `Access-Control-Allow-Origin` value (`*` is forbidden when\n * `Access-Control-Allow-Credentials: true`).\n * - `auth/complete` to rebuild the OAuth `redirect_uri` it sent to\n * HubSpot during `init-session` (the token endpoint validates that\n * the two values match).\n *\n * `__Host-` prefixed (Path=/, Secure, no Domain), so the same\n * function host can serve both `hubspot-connect` and `api` routes\n * and read the cookie from either.\n */\nexport const HUBSPOT_APP_ORIGIN_COOKIE_NAME = '__Host-hs_app_origin';\n\n/**\n * Prefix used for refresh-token cookies. Each session gets its own\n * cookie name (`hs_refresh_<sidHash>`) so multiple devices/tabs can\n * coexist without overwriting each other's refresh tokens.\n */\nexport const HUBSPOT_REFRESH_COOKIE_PREFIX = 'hs_refresh_';\n\nconst PROTECTED_COOKIE_NAMES = new Set([\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n]);\n\n/**\n * Returns `true` for cookies the SDK manages internally\n * (access token, session ID, any refresh-token cookie). The\n * `sanitizeRequest` helper uses this to strip these cookies from the\n * request before user code sees it, ensuring user route handlers\n * cannot accidentally leak them in logs or proxy them upstream.\n */\nexport function isProtectedCookieName(cookieName: string): boolean {\n return (\n PROTECTED_COOKIE_NAMES.has(cookieName) ||\n cookieName.startsWith(HUBSPOT_REFRESH_COOKIE_PREFIX)\n );\n}\n\n/**\n * Cookie carrying the PKCE code verifier between `init-session` and\n * `auth/complete`. Set with `SameSite=None; Secure; Partitioned` so the\n * frontend's credentialed cross-site `POST /auth/complete` (made from\n * the OAuth callback page on the app origin to the SDK's edge function\n * origin) carries it through. `Lax` would silently drop it on that\n * fetch, breaking every successful HubSpot redirect.\n */\nexport const TEMP_COOKIE_PKCE_VERIFIER = '__hs_pkce_verifier';\n\n/**\n * Cookie carrying the OAuth `state` value between `init-session` and\n * `auth/complete`. Compared against the `state` query parameter as the\n * primary CSRF defense. Same `SameSite=None; Secure; Partitioned`\n * attributes as `TEMP_COOKIE_PKCE_VERIFIER` for the same cross-site\n * `POST /auth/complete` reason.\n */\nexport const TEMP_COOKIE_OAUTH_STATE = '__hs_oauth_state';\n"],"mappings":";;;;;;;AAMA,MAAa,mCAAmC;;;;;AAMhD,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,MAAa,iCAAiC;;;;;;AAO9C,MAAa,gCAAgC;AAE7C,MAAM,yBAAyB,IAAI,IAAI;CACrC;CACA;CACA;AACF,CAAC;;;;;;;;AASD,SAAgB,sBAAsB,YAA6B;CACjE,OACE,uBAAuB,IAAI,UAAU,KACrC,WAAW,WAAA,aAAwC;AAEvD;;;;;;;;;AAUA,MAAa,4BAA4B;;;;;;;;AASzC,MAAa,0BAA0B"}
@@ -1 +1 @@
1
- {"version":3,"file":"start.js","names":[],"sources":["../../../src/server/deno/start.ts"],"sourcesContent":["import {\n runSecureStart,\n type SecureStartAdapter,\n type SecureStartContext,\n type SecureStartLoader,\n} from '../secure-start-core.ts';\n\nexport type { SecureStartContext, SecureStartLoader };\n\nconst denoSecureStartAdapter: SecureStartAdapter = {\n readEnv: (key) => Deno.env.get(key),\n deleteEnv: (key) => {\n Deno.env.delete(key);\n },\n exit: (code) => Deno.exit(code),\n};\n\n/**\n * Deno entrypoint helper. Reads `HUBSPOT_APP_PRIVATE_KEY` from `Deno.env`\n * when CIMD or DPoP is enabled, imports the supplied loader, and invokes\n * `start` with `AppKeys` or `null`.\n */\nexport function secureStart(loader: SecureStartLoader): Promise<void> {\n return runSecureStart(loader, denoSecureStartAdapter);\n}\n"],"mappings":";;AASA,MAAM,yBAA6C;CACjD,UAAU,QAAQ,KAAK,IAAI,IAAI,IAAI;CACnC,YAAY,QAAQ;EAClB,KAAK,IAAI,OAAO,IAAI;;CAEtB,OAAO,SAAS,KAAK,KAAK,KAAK;CAChC;;;;;;AAOD,SAAgB,YAAY,QAA0C;CACpE,OAAO,eAAe,QAAQ,uBAAuB"}
1
+ {"version":3,"file":"start.js","names":[],"sources":["../../../src/server/deno/start.ts"],"sourcesContent":["import {\n runSecureStart,\n type SecureStartAdapter,\n type SecureStartContext,\n type SecureStartLoader,\n} from '../secure-start-core.ts';\n\nexport type { SecureStartContext, SecureStartLoader };\n\nconst denoSecureStartAdapter: SecureStartAdapter = {\n readEnv: (key) => Deno.env.get(key),\n deleteEnv: (key) => {\n Deno.env.delete(key);\n },\n exit: (code) => Deno.exit(code),\n};\n\n/**\n * Deno entrypoint helper. Reads `HUBSPOT_APP_PRIVATE_KEY` from `Deno.env`\n * when CIMD or DPoP is enabled, imports the supplied loader, and invokes\n * `start` with `AppKeys` or `null`.\n */\nexport function secureStart(loader: SecureStartLoader): Promise<void> {\n return runSecureStart(loader, denoSecureStartAdapter);\n}\n"],"mappings":";;AASA,MAAM,yBAA6C;CACjD,UAAU,QAAQ,KAAK,IAAI,IAAI,GAAG;CAClC,YAAY,QAAQ;EAClB,KAAK,IAAI,OAAO,GAAG;CACrB;CACA,OAAO,SAAS,KAAK,KAAK,IAAI;AAChC;;;;;;AAOA,SAAgB,YAAY,QAA0C;CACpE,OAAO,eAAe,QAAQ,sBAAsB;AACtD"}
@@ -1,10 +1,10 @@
1
1
  import { createHubSpotClient } from "../api-client-core/client.js";
2
- import { noopLogger } from "../shared/logger.js";
2
+ import { getHubSpotApiOrigin, isHubspotDpopEnabled } from "../utils/env-utils.js";
3
3
  import { fetchTransportPlugin } from "../api-client-core/plugins/fetch-transport.js";
4
4
  import { HUBSPOT_ACCESS_TOKEN_COOKIE_NAME, HUBSPOT_APP_SID_COOKIE_NAME } from "../constants.js";
5
- import { createHubSpotProxy } from "../proxy.js";
6
5
  import { parseCookies } from "../utils/cookie-utils.js";
7
6
  import { sanitizeRequest } from "../sanitize-request.js";
7
+ import { buildHubSpotDpopAuthHeaders } from "../utils/hubspot-dpop-auth-headers.js";
8
8
  import { corsMiddleware } from "./utils/cors-middleware.js";
9
9
  import { Hono } from "hono";
10
10
  //#region src/server/hono/hono-request-handler.ts
@@ -13,12 +13,13 @@ import { Hono } from "hono";
13
13
  *
14
14
  * - Strips SDK-managed cookies (access token, refresh, sid) from the
15
15
  * request before the app sees them, via `sanitizeRequest`.
16
- * - Exposes a `hubSpotProxy` on the Hono context so route handlers
16
+ * - Exposes a `hubSpot.client` on the Hono context so route handlers
17
17
  * can issue authenticated calls to HubSpot's API on behalf of the
18
18
  * browser session.
19
19
  */
20
20
  function createAppConnectRequestHandler(options) {
21
- const { registerRoutes, appKeys, logger = noopLogger } = options;
21
+ const { registerRoutes, appKeys } = options;
22
+ if (isHubspotDpopEnabled() && appKeys === null) throw new Error("createAppConnectRequestHandler: appKeys is required when HUBSPOT_DPOP_ENABLED is true");
22
23
  const app = new Hono();
23
24
  app.use("*", corsMiddleware());
24
25
  app.use("*", async (c, next) => {
@@ -32,23 +33,26 @@ function createAppConnectRequestHandler(options) {
32
33
  if (!cookie) throw new Error("Missing auth cookies");
33
34
  const cookies = parseCookies(cookie);
34
35
  const accessToken = cookies[HUBSPOT_ACCESS_TOKEN_COOKIE_NAME];
35
- const proxy = createHubSpotProxy({
36
- userCredentials: {
37
- accessToken,
38
- sessionId: cookies[HUBSPOT_APP_SID_COOKIE_NAME]
36
+ const sessionId = cookies[HUBSPOT_APP_SID_COOKIE_NAME];
37
+ const client = createHubSpotClient({ plugins: [fetchTransportPlugin({
38
+ getEndpoint: () => {
39
+ return getHubSpotApiOrigin();
39
40
  },
40
- appKeys,
41
- logger
42
- });
43
- const client = createHubSpotClient({ plugins: [fetchTransportPlugin({ getAccessToken: () => {
44
- if (!accessToken) throw new Error("Missing access token");
45
- return accessToken;
46
- } })] });
41
+ getAuthorizationHeaders: (ctx) => {
42
+ if (isHubspotDpopEnabled()) return buildHubSpotDpopAuthHeaders({
43
+ accessToken,
44
+ sessionId,
45
+ appKeys,
46
+ method: ctx.method,
47
+ targetUrl: ctx.targetUrl
48
+ });
49
+ return { Authorization: `Bearer ${accessToken}` };
50
+ }
51
+ })] });
47
52
  const sanitizedRequest = sanitizeRequest(request);
48
53
  const honoBindings = { hubSpot: {
49
- proxy,
50
54
  client,
51
- authenticated: proxy.authenticated
55
+ authenticated: Boolean(accessToken && sessionId)
52
56
  } };
53
57
  return app.fetch(sanitizedRequest, honoBindings);
54
58
  };
@@ -1 +1 @@
1
- {"version":3,"file":"hono-request-handler.js","names":[],"sources":["../../../src/server/hono/hono-request-handler.ts"],"sourcesContent":["import { Hono } from 'hono';\n\nimport { noopLogger, type Logger } from '../../shared/logger.ts';\nimport { createHubSpotClient } from '../api-client-core/client.ts';\nimport { fetchTransportPlugin } from '../api-client-core/plugins/fetch-transport.ts';\nimport {\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n} from '../constants.ts';\nimport { createHubSpotProxy } from '../proxy.ts';\nimport { sanitizeRequest } from '../sanitize-request.ts';\nimport type { AppKeys, UserCredentials } from '../types.ts';\nimport { parseCookies } from '../utils/cookie-utils.ts';\nimport type { AppConnectHonoBindings, AppConnectHonoEnv } from './types.ts';\nimport { corsMiddleware } from './utils/cors-middleware.ts';\n\n/**\n * Web-standard fetch handler signature returned by\n * {@link createAppConnectRequestHandler}.\n */\nexport type AppConnectFetchHandler = (\n request: Request\n) => Response | Promise<Response>;\n\n/**\n * Callback used to attach application routes to the SDK-owned Hono\n * app instance.\n */\nexport type RegisterAppConnectRoutesFunction = (\n app: Hono<AppConnectHonoEnv>\n) => void;\n\n/**\n * Options accepted by {@link createAppConnectRequestHandler}.\n */\nexport interface CreateAppConnectRequestHandlerOptions {\n /** Registers application routes on the SDK-owned Hono app. */\n registerRoutes: RegisterAppConnectRoutesFunction;\n /**\n * Imported app keys from `secureStart`, or `null` when CIMD and DPoP\n * are both disabled.\n */\n appKeys: AppKeys | null;\n /**\n * Optional logger. When omitted the SDK uses a no-op logger so\n * server-side state never leaks into the host application's\n * console.\n */\n logger?: Logger;\n}\n\n/**\n * Wraps a Hono app so its `fetch` handler additionally:\n *\n * - Strips SDK-managed cookies (access token, refresh, sid) from the\n * request before the app sees them, via `sanitizeRequest`.\n * - Exposes a `hubSpotProxy` on the Hono context so route handlers\n * can issue authenticated calls to HubSpot's API on behalf of the\n * browser session.\n */\nexport function createAppConnectRequestHandler(\n options: CreateAppConnectRequestHandlerOptions\n): AppConnectFetchHandler {\n const { registerRoutes, appKeys, logger = noopLogger } = options;\n const app = new Hono<AppConnectHonoEnv>();\n // Credentialed CORS first: preflights short-circuit with 204\n // before the auth check runs, and 401 responses still carry\n // `Access-Control-Allow-*` headers (the browser drops responses\n // without them on credentialed cross-site fetches).\n app.use('*', corsMiddleware());\n\n // Auth gate: every non-OPTIONS request must arrive with the\n // SDK-managed access-token + session-id cookies. The CORS\n // middleware above short-circuits OPTIONS, so this only runs on\n // real requests; missing cookies now surface as a normal 401 with\n // CORS headers attached on the way back out (the previous\n // implementation threw on a missing `Cookie` header before any\n // middleware ran, which broke browser preflights).\n app.use('*', async (c, next) => {\n const { authenticated } = c.env.hubSpot;\n if (!authenticated) {\n return c.json({ error: 'Unauthorized' }, 401);\n }\n\n await next();\n return;\n });\n\n registerRoutes(app);\n\n return (request: Request) => {\n const cookie = request.headers.get('Cookie');\n if (!cookie) {\n throw new Error('Missing auth cookies');\n }\n const cookies = parseCookies(cookie);\n const accessToken = cookies[HUBSPOT_ACCESS_TOKEN_COOKIE_NAME];\n const sessionId = cookies[HUBSPOT_APP_SID_COOKIE_NAME];\n\n const userCredentials: UserCredentials = { accessToken, sessionId };\n\n const proxy = createHubSpotProxy({\n userCredentials,\n appKeys,\n logger,\n });\n\n const client = createHubSpotClient({\n plugins: [\n fetchTransportPlugin({\n getAccessToken: () => {\n if (!accessToken) {\n throw new Error('Missing access token');\n }\n return accessToken;\n },\n }),\n ],\n });\n\n const sanitizedRequest = sanitizeRequest(request);\n\n const honoBindings: AppConnectHonoBindings = {\n hubSpot: {\n proxy,\n client,\n authenticated: proxy.authenticated,\n },\n };\n\n return app.fetch(sanitizedRequest, honoBindings);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4DA,SAAgB,+BACd,SACwB;CACxB,MAAM,EAAE,gBAAgB,SAAS,SAAS,eAAe;CACzD,MAAM,MAAM,IAAI,MAAyB;CAKzC,IAAI,IAAI,KAAK,gBAAgB,CAAC;CAS9B,IAAI,IAAI,KAAK,OAAO,GAAG,SAAS;EAC9B,MAAM,EAAE,kBAAkB,EAAE,IAAI;EAChC,IAAI,CAAC,eACH,OAAO,EAAE,KAAK,EAAE,OAAO,gBAAgB,EAAE,IAAI;EAG/C,MAAM,MAAM;GAEZ;CAEF,eAAe,IAAI;CAEnB,QAAQ,YAAqB;EAC3B,MAAM,SAAS,QAAQ,QAAQ,IAAI,SAAS;EAC5C,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,uBAAuB;EAEzC,MAAM,UAAU,aAAa,OAAO;EACpC,MAAM,cAAc,QAAQ;EAK5B,MAAM,QAAQ,mBAAmB;GAC/B,iBAAA;IAHyC;IAAa,WAFtC,QAAQ;IAKT;GACf;GACA;GACD,CAAC;EAEF,MAAM,SAAS,oBAAoB,EACjC,SAAS,CACP,qBAAqB,EACnB,sBAAsB;GACpB,IAAI,CAAC,aACH,MAAM,IAAI,MAAM,uBAAuB;GAEzC,OAAO;KAEV,CAAC,CACH,EACF,CAAC;EAEF,MAAM,mBAAmB,gBAAgB,QAAQ;EAEjD,MAAM,eAAuC,EAC3C,SAAS;GACP;GACA;GACA,eAAe,MAAM;GACtB,EACF;EAED,OAAO,IAAI,MAAM,kBAAkB,aAAa"}
1
+ {"version":3,"file":"hono-request-handler.js","names":[],"sources":["../../../src/server/hono/hono-request-handler.ts"],"sourcesContent":["import { Hono } from 'hono';\n\nimport { type Logger } from '../../shared/logger.ts';\nimport { createHubSpotClient } from '../api-client-core/client.ts';\nimport { fetchTransportPlugin } from '../api-client-core/plugins/fetch-transport.ts';\nimport {\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n} from '../constants.ts';\nimport { sanitizeRequest } from '../sanitize-request.ts';\nimport type { AppKeys } from '../types.ts';\nimport { parseCookies } from '../utils/cookie-utils.ts';\nimport {\n getHubSpotApiOrigin,\n isHubspotDpopEnabled,\n} from '../utils/env-utils.ts';\nimport { buildHubSpotDpopAuthHeaders } from '../utils/hubspot-dpop-auth-headers.ts';\nimport type { AppConnectHonoBindings, AppConnectHonoEnv } from './types.ts';\nimport { corsMiddleware } from './utils/cors-middleware.ts';\n\n/**\n * Web-standard fetch handler signature returned by\n * {@link createAppConnectRequestHandler}.\n */\nexport type AppConnectFetchHandler = (\n request: Request\n) => Response | Promise<Response>;\n\n/**\n * Callback used to attach application routes to the SDK-owned Hono\n * app instance.\n */\nexport type RegisterAppConnectRoutesFunction = (\n app: Hono<AppConnectHonoEnv>\n) => void;\n\n/**\n * Options accepted by {@link createAppConnectRequestHandler}.\n */\nexport interface CreateAppConnectRequestHandlerOptions {\n /** Registers application routes on the SDK-owned Hono app. */\n registerRoutes: RegisterAppConnectRoutesFunction;\n /**\n * Imported app keys from `secureStart`, or `null` when CIMD and DPoP\n * are both disabled.\n */\n appKeys: AppKeys | null;\n /**\n * Optional logger. When omitted the SDK uses a no-op logger so\n * server-side state never leaks into the host application's\n * console.\n */\n logger?: Logger;\n}\n\n/**\n * Wraps a Hono app so its `fetch` handler additionally:\n *\n * - Strips SDK-managed cookies (access token, refresh, sid) from the\n * request before the app sees them, via `sanitizeRequest`.\n * - Exposes a `hubSpot.client` on the Hono context so route handlers\n * can issue authenticated calls to HubSpot's API on behalf of the\n * browser session.\n */\nexport function createAppConnectRequestHandler(\n options: CreateAppConnectRequestHandlerOptions\n): AppConnectFetchHandler {\n const { registerRoutes, appKeys } = options;\n\n if (isHubspotDpopEnabled() && appKeys === null) {\n throw new Error(\n 'createAppConnectRequestHandler: appKeys is required when HUBSPOT_DPOP_ENABLED is true'\n );\n }\n\n const app = new Hono<AppConnectHonoEnv>();\n // Credentialed CORS first: preflights short-circuit with 204\n // before the auth check runs, and 401 responses still carry\n // `Access-Control-Allow-*` headers (the browser drops responses\n // without them on credentialed cross-site fetches).\n app.use('*', corsMiddleware());\n\n // Auth gate: every non-OPTIONS request must arrive with the\n // SDK-managed access-token + session-id cookies. The CORS\n // middleware above short-circuits OPTIONS, so this only runs on\n // real requests; missing cookies now surface as a normal 401 with\n // CORS headers attached on the way back out (the previous\n // implementation threw on a missing `Cookie` header before any\n // middleware ran, which broke browser preflights).\n app.use('*', async (c, next) => {\n const { authenticated } = c.env.hubSpot;\n if (!authenticated) {\n return c.json({ error: 'Unauthorized' }, 401);\n }\n\n await next();\n return;\n });\n\n registerRoutes(app);\n\n return (request: Request) => {\n const cookie = request.headers.get('Cookie');\n if (!cookie) {\n throw new Error('Missing auth cookies');\n }\n const cookies = parseCookies(cookie);\n const accessToken = cookies[HUBSPOT_ACCESS_TOKEN_COOKIE_NAME];\n const sessionId = cookies[HUBSPOT_APP_SID_COOKIE_NAME];\n\n const client = createHubSpotClient({\n plugins: [\n fetchTransportPlugin({\n getEndpoint: () => {\n return getHubSpotApiOrigin();\n },\n getAuthorizationHeaders: (ctx) => {\n if (isHubspotDpopEnabled()) {\n return buildHubSpotDpopAuthHeaders({\n accessToken: accessToken!,\n sessionId: sessionId!,\n appKeys: appKeys!,\n method: ctx.method,\n targetUrl: ctx.targetUrl,\n });\n }\n\n return {\n Authorization: `Bearer ${accessToken!}`,\n };\n },\n }),\n ],\n });\n\n const sanitizedRequest = sanitizeRequest(request);\n\n const honoBindings: AppConnectHonoBindings = {\n hubSpot: {\n client,\n authenticated: Boolean(accessToken && sessionId),\n },\n };\n\n return app.fetch(sanitizedRequest, honoBindings);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,+BACd,SACwB;CACxB,MAAM,EAAE,gBAAgB,YAAY;CAEpC,IAAI,qBAAqB,KAAK,YAAY,MACxC,MAAM,IAAI,MACR,uFACF;CAGF,MAAM,MAAM,IAAI,KAAwB;CAKxC,IAAI,IAAI,KAAK,eAAe,CAAC;CAS7B,IAAI,IAAI,KAAK,OAAO,GAAG,SAAS;EAC9B,MAAM,EAAE,kBAAkB,EAAE,IAAI;EAChC,IAAI,CAAC,eACH,OAAO,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG;EAG9C,MAAM,KAAK;CAEb,CAAC;CAED,eAAe,GAAG;CAElB,QAAQ,YAAqB;EAC3B,MAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ;EAC3C,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,sBAAsB;EAExC,MAAM,UAAU,aAAa,MAAM;EACnC,MAAM,cAAc,QAAQ;EAC5B,MAAM,YAAY,QAAQ;EAE1B,MAAM,SAAS,oBAAoB,EACjC,SAAS,CACP,qBAAqB;GACnB,mBAAmB;IACjB,OAAO,oBAAoB;GAC7B;GACA,0BAA0B,QAAQ;IAChC,IAAI,qBAAqB,GACvB,OAAO,4BAA4B;KACpB;KACF;KACF;KACT,QAAQ,IAAI;KACZ,WAAW,IAAI;IACjB,CAAC;IAGH,OAAO,EACL,eAAe,UAAU,cAC3B;GACF;EACF,CAAC,CACH,EACF,CAAC;EAED,MAAM,mBAAmB,gBAAgB,OAAO;EAEhD,MAAM,eAAuC,EAC3C,SAAS;GACP;GACA,eAAe,QAAQ,eAAe,SAAS;EACjD,EACF;EAEA,OAAO,IAAI,MAAM,kBAAkB,YAAY;CACjD;AACF"}
@@ -66,7 +66,8 @@ async function handleAuthComplete(c, options) {
66
66
  basePath: options.basePath,
67
67
  xForwardedProto,
68
68
  xForwardedHost,
69
- requestHostHeader
69
+ requestHostHeader,
70
+ appOrigin
70
71
  }) : hubspotConnectEnv.hubspotClientId;
71
72
  const redirectUri = buildFrontendOAuthRedirectUri(appOrigin);
72
73
  const tokenEndpointUrl = new URL("/oauth/v1/token", hubspotConnectEnv.hubspotOAuthApiOrigin).href;
@@ -1 +1 @@
1
- {"version":3,"file":"auth-complete.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/auth-complete.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport {\n AUTH_COMPLETE_CODE_PARAM,\n AUTH_COMPLETE_STATE_PARAM,\n} from '../../../shared/constants.ts';\nimport {\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n HUBSPOT_REFRESH_COOKIE_PREFIX,\n TEMP_COOKIE_OAUTH_STATE,\n TEMP_COOKIE_PKCE_VERIFIER,\n} from '../../constants.ts';\nimport { base64urlDecode } from '../../utils/base64-utils.ts';\nimport { parseCookies } from '../../utils/cookie-utils.ts';\nimport { serializeCookie, setResponseCookie } from '../utils/cookie-utils.ts';\nimport { REFRESH_COOKIE_MAX_AGE_SEC } from './constants.ts';\nimport {\n buildClientAssertion,\n buildClientAssertionFormParams,\n buildClientSecretFormParams,\n buildTokenEndpointDpopProof,\n requestOAuthToken,\n} from './oauth-client.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport {\n buildCimdClientIdUrlFromRequest,\n buildFrontendOAuthRedirectUri,\n clearTempCookie,\n isPositiveFiniteNumber,\n isSafeReturnPath,\n parseAppOriginHeader,\n} from './utils.ts';\n\ninterface OAuthStatePayload {\n return_path?: string;\n sid?: string;\n}\n\n/**\n * Cross-origin OAuth completion endpoint.\n *\n * Called from the React app on the frontend OAuth callback path\n * (`HUBSPOT_FRONTEND_CALLBACK_PATH`) once HubSpot has redirected the\n * browser back with `?code` + `?state`. The browser POSTs both\n * values here as a credentialed cross-site fetch — same partition as\n * `init-session`, so the temp PKCE/state cookies are visible — and\n * the SDK:\n *\n * 1. Validates `state` against the temp `__hs_oauth_state` cookie.\n * 2. Pulls the PKCE verifier from `__hs_pkce_verifier`.\n * 3. Rebuilds the same `redirect_uri` it sent to HubSpot during\n * `init-session` (frontend origin + the fixed callback path);\n * the OAuth token endpoint requires the two values to match.\n * 4. Exchanges `code` for an access + refresh token (with DPoP /\n * CIMD client-assertion when enabled).\n * 5. Sets the durable session cookies (access token, refresh) with\n * `SameSite=None; Secure; Partitioned` so they live in the\n * `(frontend, edge)` partition where subsequent API fetches will\n * read them.\n * 6. Clears the temp cookies.\n * 7. Returns `{ expires_at, return_path }` so the controller can\n * update its session-storage expiry tracking and navigate back to\n * the page the user started the connect flow from.\n */\nexport async function handleAuthComplete(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n) {\n const { appKeys, refreshCookiePath, hubspotConnectEnv } = options;\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n const code = c.req.query(AUTH_COMPLETE_CODE_PARAM);\n const state = c.req.query(AUTH_COMPLETE_STATE_PARAM);\n\n if (!code || !state) {\n return c.json({ error: 'Missing code or state' }, 400);\n }\n\n if (hubspotConnectEnv.isAppPrivateKeyRequired && !appKeys) {\n return c.json(\n {\n error:\n 'Server misconfiguration: HUBSPOT_APP_PRIVATE_KEY is required when CIMD or DPoP is enabled',\n },\n 500\n );\n }\n\n const cookies = parseCookies(c.req.header('Cookie'));\n const expectedState = cookies[TEMP_COOKIE_OAUTH_STATE];\n const codeVerifier = cookies[TEMP_COOKIE_PKCE_VERIFIER];\n const appOriginCookie = cookies[HUBSPOT_APP_ORIGIN_COOKIE_NAME];\n\n if (!expectedState || state !== decodeURIComponent(expectedState)) {\n return c.json({ error: 'State mismatch' }, 403);\n }\n if (!codeVerifier) {\n return c.json({ error: 'Missing PKCE verifier' }, 400);\n }\n // The redirect_uri the OAuth token endpoint validates must equal\n // the one we sent during init-session. We rebuild it from the\n // pinned origin cookie so that value is anchored server-side, not\n // taken from the (caller-controlled) request `Origin` on this call.\n const appOrigin = parseAppOriginHeader(appOriginCookie);\n if (!appOrigin) {\n return c.json({ error: 'Missing app origin cookie' }, 400);\n }\n\n let statePayload: OAuthStatePayload;\n try {\n statePayload = JSON.parse(\n new TextDecoder().decode(base64urlDecode(decodeURIComponent(state)))\n ) as OAuthStatePayload;\n } catch {\n return c.json({ error: 'Malformed state value' }, 400);\n }\n const returnPath = statePayload.return_path;\n if (!returnPath || !isSafeReturnPath(returnPath)) {\n return c.json({ error: 'Invalid return path in state' }, 400);\n }\n\n const sessionId = statePayload.sid;\n if (!sessionId) {\n return c.json({ error: 'Missing app session cookie' }, 400);\n }\n\n const decodedCodeVerifier = decodeURIComponent(codeVerifier);\n\n const clientId = hubspotConnectEnv.isCimdEnabled\n ? buildCimdClientIdUrlFromRequest({\n requestUrl: c.req.url,\n basePath: options.basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n })\n : hubspotConnectEnv.hubspotClientId;\n\n const redirectUri = buildFrontendOAuthRedirectUri(appOrigin);\n\n const tokenEndpointUrl = new URL(\n '/oauth/v1/token',\n hubspotConnectEnv.hubspotOAuthApiOrigin\n ).href;\n\n let dpopProof: string | undefined;\n if (hubspotConnectEnv.isDpopEnabled) {\n dpopProof = await buildTokenEndpointDpopProof({\n appKeys: appKeys!,\n tokenEndpointUrl,\n sessionIdHash: sessionId,\n });\n }\n\n let formParams: Record<string, string>;\n if (hubspotConnectEnv.isCimdEnabled) {\n const clientAssertion = await buildClientAssertion({\n appKeys: appKeys!,\n clientId,\n audience: tokenEndpointUrl,\n });\n formParams = {\n grant_type: 'authorization_code',\n code,\n code_verifier: decodedCodeVerifier,\n redirect_uri: redirectUri,\n ...buildClientAssertionFormParams({ clientId, clientAssertion }),\n };\n } else {\n formParams = {\n grant_type: 'authorization_code',\n code,\n code_verifier: decodedCodeVerifier,\n redirect_uri: redirectUri,\n ...buildClientSecretFormParams({\n clientId,\n clientSecret: hubspotConnectEnv.hubspotClientSecret,\n }),\n };\n }\n\n const tokenResult = await requestOAuthToken({\n tokenEndpointUrl,\n isDpopEnabled: hubspotConnectEnv.isDpopEnabled,\n ...(dpopProof !== undefined ? { dpopProof } : {}),\n formParams,\n });\n if (!tokenResult.ok) {\n return c.json(\n { error: `Token exchange failed: ${tokenResult.errorText}` },\n 502\n );\n }\n\n const {\n access_token: accessToken,\n refresh_token: refreshToken,\n expires_in,\n } = tokenResult.body;\n if (!refreshToken) {\n return c.json({ error: 'Token response missing refresh_token' }, 502);\n }\n if (!isPositiveFiniteNumber(expires_in)) {\n return c.json(\n { error: 'Token response missing or invalid expires_in' },\n 502\n );\n }\n\n const expiresAt = Date.now() + expires_in * 1000;\n const refreshCookieName = `${HUBSPOT_REFRESH_COOKIE_PREFIX}${sessionId}`;\n\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n value: accessToken,\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: expires_in,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: refreshCookieName,\n value: refreshToken,\n path: refreshCookiePath,\n sameSite: 'None',\n partitioned: true,\n maxAge: REFRESH_COOKIE_MAX_AGE_SEC,\n }),\n });\n setResponseCookie({ c, value: clearTempCookie(TEMP_COOKIE_PKCE_VERIFIER) });\n setResponseCookie({ c, value: clearTempCookie(TEMP_COOKIE_OAUTH_STATE) });\n\n return c.json({ expires_at: expiresAt, return_path: returnPath });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,eAAsB,mBACpB,GACA,SACA;CACA,MAAM,EAAE,SAAS,mBAAmB,sBAAsB;CAC1D,MAAM,kBAAkB,EAAE,IAAI,OAAO,oBAAoB,IAAI,KAAA;CAC7D,MAAM,iBAAiB,EAAE,IAAI,OAAO,mBAAmB,IAAI,KAAA;CAC3D,MAAM,oBAAoB,EAAE,IAAI,OAAO,OAAO,IAAI,KAAA;CAClD,MAAM,OAAO,EAAE,IAAI,MAAM,yBAAyB;CAClD,MAAM,QAAQ,EAAE,IAAI,MAAM,0BAA0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B,0BAA0B;EAAE,CAAC;CAC3E,kBAAkB;EAAE;EAAG,OAAO,gBAAgB,wBAAwB;EAAE,CAAC;CAEzE,OAAO,EAAE,KAAK;EAAE,YAAY;EAAW,aAAa;EAAY,CAAC"}
1
+ {"version":3,"file":"auth-complete.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/auth-complete.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport {\n AUTH_COMPLETE_CODE_PARAM,\n AUTH_COMPLETE_STATE_PARAM,\n} from '../../../shared/constants.ts';\nimport {\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n HUBSPOT_REFRESH_COOKIE_PREFIX,\n TEMP_COOKIE_OAUTH_STATE,\n TEMP_COOKIE_PKCE_VERIFIER,\n} from '../../constants.ts';\nimport { base64urlDecode } from '../../utils/base64-utils.ts';\nimport { parseCookies } from '../../utils/cookie-utils.ts';\nimport { serializeCookie, setResponseCookie } from '../utils/cookie-utils.ts';\nimport { REFRESH_COOKIE_MAX_AGE_SEC } from './constants.ts';\nimport {\n buildClientAssertion,\n buildClientAssertionFormParams,\n buildClientSecretFormParams,\n buildTokenEndpointDpopProof,\n requestOAuthToken,\n} from './oauth-client.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport {\n buildCimdClientIdUrlFromRequest,\n buildFrontendOAuthRedirectUri,\n clearTempCookie,\n isPositiveFiniteNumber,\n isSafeReturnPath,\n parseAppOriginHeader,\n} from './utils.ts';\n\ninterface OAuthStatePayload {\n return_path?: string;\n sid?: string;\n}\n\n/**\n * Cross-origin OAuth completion endpoint.\n *\n * Called from the React app on the frontend OAuth callback path\n * (`HUBSPOT_FRONTEND_CALLBACK_PATH`) once HubSpot has redirected the\n * browser back with `?code` + `?state`. The browser POSTs both\n * values here as a credentialed cross-site fetch — same partition as\n * `init-session`, so the temp PKCE/state cookies are visible — and\n * the SDK:\n *\n * 1. Validates `state` against the temp `__hs_oauth_state` cookie.\n * 2. Pulls the PKCE verifier from `__hs_pkce_verifier`.\n * 3. Rebuilds the same `redirect_uri` it sent to HubSpot during\n * `init-session` (frontend origin + the fixed callback path);\n * the OAuth token endpoint requires the two values to match.\n * 4. Exchanges `code` for an access + refresh token (with DPoP /\n * CIMD client-assertion when enabled).\n * 5. Sets the durable session cookies (access token, refresh) with\n * `SameSite=None; Secure; Partitioned` so they live in the\n * `(frontend, edge)` partition where subsequent API fetches will\n * read them.\n * 6. Clears the temp cookies.\n * 7. Returns `{ expires_at, return_path }` so the controller can\n * update its session-storage expiry tracking and navigate back to\n * the page the user started the connect flow from.\n */\nexport async function handleAuthComplete(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n) {\n const { appKeys, refreshCookiePath, hubspotConnectEnv } = options;\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n const code = c.req.query(AUTH_COMPLETE_CODE_PARAM);\n const state = c.req.query(AUTH_COMPLETE_STATE_PARAM);\n\n if (!code || !state) {\n return c.json({ error: 'Missing code or state' }, 400);\n }\n\n if (hubspotConnectEnv.isAppPrivateKeyRequired && !appKeys) {\n return c.json(\n {\n error:\n 'Server misconfiguration: HUBSPOT_APP_PRIVATE_KEY is required when CIMD or DPoP is enabled',\n },\n 500\n );\n }\n\n const cookies = parseCookies(c.req.header('Cookie'));\n const expectedState = cookies[TEMP_COOKIE_OAUTH_STATE];\n const codeVerifier = cookies[TEMP_COOKIE_PKCE_VERIFIER];\n const appOriginCookie = cookies[HUBSPOT_APP_ORIGIN_COOKIE_NAME];\n\n if (!expectedState || state !== decodeURIComponent(expectedState)) {\n return c.json({ error: 'State mismatch' }, 403);\n }\n if (!codeVerifier) {\n return c.json({ error: 'Missing PKCE verifier' }, 400);\n }\n // The redirect_uri the OAuth token endpoint validates must equal\n // the one we sent during init-session. We rebuild it from the\n // pinned origin cookie so that value is anchored server-side, not\n // taken from the (caller-controlled) request `Origin` on this call.\n const appOrigin = parseAppOriginHeader(appOriginCookie);\n if (!appOrigin) {\n return c.json({ error: 'Missing app origin cookie' }, 400);\n }\n\n let statePayload: OAuthStatePayload;\n try {\n statePayload = JSON.parse(\n new TextDecoder().decode(base64urlDecode(decodeURIComponent(state)))\n ) as OAuthStatePayload;\n } catch {\n return c.json({ error: 'Malformed state value' }, 400);\n }\n const returnPath = statePayload.return_path;\n if (!returnPath || !isSafeReturnPath(returnPath)) {\n return c.json({ error: 'Invalid return path in state' }, 400);\n }\n\n const sessionId = statePayload.sid;\n if (!sessionId) {\n return c.json({ error: 'Missing app session cookie' }, 400);\n }\n\n const decodedCodeVerifier = decodeURIComponent(codeVerifier);\n\n const clientId = hubspotConnectEnv.isCimdEnabled\n ? buildCimdClientIdUrlFromRequest({\n requestUrl: c.req.url,\n basePath: options.basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n appOrigin,\n })\n : hubspotConnectEnv.hubspotClientId;\n\n const redirectUri = buildFrontendOAuthRedirectUri(appOrigin);\n\n const tokenEndpointUrl = new URL(\n '/oauth/v1/token',\n hubspotConnectEnv.hubspotOAuthApiOrigin\n ).href;\n\n let dpopProof: string | undefined;\n if (hubspotConnectEnv.isDpopEnabled) {\n dpopProof = await buildTokenEndpointDpopProof({\n appKeys: appKeys!,\n tokenEndpointUrl,\n sessionIdHash: sessionId,\n });\n }\n\n let formParams: Record<string, string>;\n if (hubspotConnectEnv.isCimdEnabled) {\n const clientAssertion = await buildClientAssertion({\n appKeys: appKeys!,\n clientId,\n audience: tokenEndpointUrl,\n });\n formParams = {\n grant_type: 'authorization_code',\n code,\n code_verifier: decodedCodeVerifier,\n redirect_uri: redirectUri,\n ...buildClientAssertionFormParams({ clientId, clientAssertion }),\n };\n } else {\n formParams = {\n grant_type: 'authorization_code',\n code,\n code_verifier: decodedCodeVerifier,\n redirect_uri: redirectUri,\n ...buildClientSecretFormParams({\n clientId,\n clientSecret: hubspotConnectEnv.hubspotClientSecret,\n }),\n };\n }\n\n const tokenResult = await requestOAuthToken({\n tokenEndpointUrl,\n isDpopEnabled: hubspotConnectEnv.isDpopEnabled,\n ...(dpopProof !== undefined ? { dpopProof } : {}),\n formParams,\n });\n if (!tokenResult.ok) {\n return c.json(\n { error: `Token exchange failed: ${tokenResult.errorText}` },\n 502\n );\n }\n\n const {\n access_token: accessToken,\n refresh_token: refreshToken,\n expires_in,\n } = tokenResult.body;\n if (!refreshToken) {\n return c.json({ error: 'Token response missing refresh_token' }, 502);\n }\n if (!isPositiveFiniteNumber(expires_in)) {\n return c.json(\n { error: 'Token response missing or invalid expires_in' },\n 502\n );\n }\n\n const expiresAt = Date.now() + expires_in * 1000;\n const refreshCookieName = `${HUBSPOT_REFRESH_COOKIE_PREFIX}${sessionId}`;\n\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n value: accessToken,\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: expires_in,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: refreshCookieName,\n value: refreshToken,\n path: refreshCookiePath,\n sameSite: 'None',\n partitioned: true,\n maxAge: REFRESH_COOKIE_MAX_AGE_SEC,\n }),\n });\n setResponseCookie({ c, value: clearTempCookie(TEMP_COOKIE_PKCE_VERIFIER) });\n setResponseCookie({ c, value: clearTempCookie(TEMP_COOKIE_OAUTH_STATE) });\n\n return c.json({ expires_at: expiresAt, return_path: returnPath });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,eAAsB,mBACpB,GACA,SACA;CACA,MAAM,EAAE,SAAS,mBAAmB,sBAAsB;CAC1D,MAAM,kBAAkB,EAAE,IAAI,OAAO,mBAAmB,KAAK,KAAA;CAC7D,MAAM,iBAAiB,EAAE,IAAI,OAAO,kBAAkB,KAAK,KAAA;CAC3D,MAAM,oBAAoB,EAAE,IAAI,OAAO,MAA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MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;EACV,CAAC;CACH,CAAC;CACD,kBAAkB;EAAE;EAAG,OAAO,gBAAgB,yBAAyB;CAAE,CAAC;CAC1E,kBAAkB;EAAE;EAAG,OAAO,gBAAgB,uBAAuB;CAAE,CAAC;CAExE,OAAO,EAAE,KAAK;EAAE,YAAY;EAAW,aAAa;CAAW,CAAC;AAClE"}
@@ -32,8 +32,10 @@ async function handleAuthInitSession(c, options) {
32
32
  basePath: options.basePath,
33
33
  xForwardedProto,
34
34
  xForwardedHost,
35
- requestHostHeader
35
+ requestHostHeader,
36
+ appOrigin
36
37
  }) : hubspotConnectEnv.hubspotClientId;
38
+ console.log("clientId", clientId);
37
39
  const redirectUri = buildFrontendOAuthRedirectUri(appOrigin);
38
40
  const authorizeUrl = new URL(hubspotConnectEnv.hubspotAuthorizationEndpoint);
39
41
  authorizeUrl.searchParams.set("response_type", "code");
@@ -1 +1 @@
1
- {"version":3,"file":"auth-init-session.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/auth-init-session.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport {\n HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n TEMP_COOKIE_OAUTH_STATE,\n TEMP_COOKIE_PKCE_VERIFIER,\n} from '../../constants.ts';\nimport { base64url } from '../../utils/base64-utils.ts';\nimport { sha256base64url } from '../../utils/crypto-utils.ts';\nimport { serializeCookie, setResponseCookie } from '../utils/cookie-utils.ts';\nimport { OAUTH_TEMP_MAX_AGE_SEC, SESSION_MAX_AGE_SEC } from './constants.ts';\nimport { deriveHubSpotAuthorizeScopesFromClientMetadata } from './fetch-hubspot-client-metadata.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport {\n buildCimdClientIdUrlFromRequest,\n buildFrontendOAuthRedirectUri,\n isSafeReturnPath,\n parseAppOriginHeader,\n} from './utils.ts';\n\nexport async function handleAuthInitSession(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n) {\n const { hubspotConnectEnv, cimdClientMetadata } = options;\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n const url = new URL(c.req.url);\n const returnPath = url.searchParams.get('return_path') ?? '/';\n if (!isSafeReturnPath(returnPath)) {\n return c.text('Invalid return_path', 400);\n }\n\n // The app origin pins the OAuth `redirect_uri` (which lands on the\n // frontend, not on this edge function) and, via the persisted\n // `__Host-hs_app_origin` cookie, drives credentialed\n // `Access-Control-Allow-Origin` on every subsequent SDK response.\n const appOrigin = parseAppOriginHeader(c.req.header('Origin'));\n if (!appOrigin) {\n return c.text(\n 'Missing or invalid Origin header; init-session must be called from a browser',\n 400\n );\n }\n\n const sessionIdBytes = new Uint8Array(32);\n crypto.getRandomValues(sessionIdBytes);\n const sessionId = base64url(sessionIdBytes);\n const sessionIdHash = await sha256base64url(sessionId);\n\n const codeVerifierBytes = new Uint8Array(32);\n crypto.getRandomValues(codeVerifierBytes);\n const codeVerifier = base64url(codeVerifierBytes);\n const codeChallenge = await sha256base64url(codeVerifier);\n\n const stateValue = base64url(\n new TextEncoder().encode(\n JSON.stringify({\n return_path: returnPath,\n sid: sessionIdHash,\n })\n )\n );\n\n const clientId = hubspotConnectEnv.isCimdEnabled\n ? buildCimdClientIdUrlFromRequest({\n requestUrl: c.req.url,\n basePath: options.basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n })\n : hubspotConnectEnv.hubspotClientId;\n\n const redirectUri = buildFrontendOAuthRedirectUri(appOrigin);\n\n const authorizeUrl = new URL(hubspotConnectEnv.hubspotAuthorizationEndpoint);\n authorizeUrl.searchParams.set('response_type', 'code');\n authorizeUrl.searchParams.set('client_id', clientId);\n authorizeUrl.searchParams.set('redirect_uri', redirectUri);\n authorizeUrl.searchParams.set('code_challenge', codeChallenge);\n authorizeUrl.searchParams.set('code_challenge_method', 'S256');\n authorizeUrl.searchParams.set('state', stateValue);\n authorizeUrl.searchParams.set('sid', sessionIdHash);\n\n if (!hubspotConnectEnv.isCimdEnabled) {\n const scopesResult =\n deriveHubSpotAuthorizeScopesFromClientMetadata(cimdClientMetadata);\n if (!scopesResult.ok) {\n return c.text(scopesResult.message, scopesResult.status as 500 | 502);\n }\n authorizeUrl.searchParams.set('scope', scopesResult.scope);\n if (scopesResult.optionalScope !== undefined) {\n authorizeUrl.searchParams.set(\n 'optional_scope',\n scopesResult.optionalScope\n );\n }\n }\n\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n value: appOrigin,\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: SESSION_MAX_AGE_SEC,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_APP_SID_COOKIE_NAME,\n value: sessionId,\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: SESSION_MAX_AGE_SEC,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: TEMP_COOKIE_PKCE_VERIFIER,\n value: encodeURIComponent(codeVerifier),\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: OAUTH_TEMP_MAX_AGE_SEC,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: TEMP_COOKIE_OAUTH_STATE,\n value: encodeURIComponent(stateValue),\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: OAUTH_TEMP_MAX_AGE_SEC,\n }),\n });\n\n return c.json({ authorization_url: authorizeUrl.toString() });\n}\n"],"mappings":";;;;;;;;AAqBA,eAAsB,sBACpB,GACA,SACA;CACA,MAAM,EAAE,mBAAmB,uBAAuB;CAClD,MAAM,kBAAkB,EAAE,IAAI,OAAO,oBAAoB,IAAI,KAAA;CAC7D,MAAM,iBAAiB,EAAE,IAAI,OAAO,mBAAmB,IAAI,KAAA;CA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C,mBAAmB;EACpE,IAAI,CAAC,aAAa,IAChB,OAAO,EAAE,KAAK,aAAa,SAAS,aAAa,OAAoB;EAEvE,aAAa,aAAa,IAAI,SAAS,aAAa,MAAM;EAC1D,IAAI,aAAa,kBAAkB,KAAA,GACjC,aAAa,aAAa,IACxB,kBACA,aAAa,cACd;;CAIL,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;GACT,CAAC;EACH,CAAC;CACF,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;GACT,CAAC;EACH,CAAC;CACF,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO,mBAAmB,aAAa;GACvC,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;GACT,CAAC;EACH,CAAC;CACF,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO,mBAAmB,WAAW;GACrC,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;GACT,CAAC;EACH,CAAC;CAEF,OAAO,EAAE,KAAK,EAAE,mBAAmB,aAAa,UAAU,EAAE,CAAC"}
1
+ {"version":3,"file":"auth-init-session.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/auth-init-session.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport {\n HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n TEMP_COOKIE_OAUTH_STATE,\n TEMP_COOKIE_PKCE_VERIFIER,\n} from '../../constants.ts';\nimport { base64url } from '../../utils/base64-utils.ts';\nimport { sha256base64url } from '../../utils/crypto-utils.ts';\nimport { serializeCookie, setResponseCookie } from '../utils/cookie-utils.ts';\nimport { OAUTH_TEMP_MAX_AGE_SEC, SESSION_MAX_AGE_SEC } from './constants.ts';\nimport { deriveHubSpotAuthorizeScopesFromClientMetadata } from './fetch-hubspot-client-metadata.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport {\n buildCimdClientIdUrlFromRequest,\n buildFrontendOAuthRedirectUri,\n isSafeReturnPath,\n parseAppOriginHeader,\n} from './utils.ts';\n\nexport async function handleAuthInitSession(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n) {\n const { hubspotConnectEnv, cimdClientMetadata } = options;\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n const url = new URL(c.req.url);\n const returnPath = url.searchParams.get('return_path') ?? '/';\n if (!isSafeReturnPath(returnPath)) {\n return c.text('Invalid return_path', 400);\n }\n\n // The app origin pins the OAuth `redirect_uri` (which lands on the\n // frontend, not on this edge function) and, via the persisted\n // `__Host-hs_app_origin` cookie, drives credentialed\n // `Access-Control-Allow-Origin` on every subsequent SDK response.\n const appOrigin = parseAppOriginHeader(c.req.header('Origin'));\n if (!appOrigin) {\n return c.text(\n 'Missing or invalid Origin header; init-session must be called from a browser',\n 400\n );\n }\n\n const sessionIdBytes = new Uint8Array(32);\n crypto.getRandomValues(sessionIdBytes);\n const sessionId = base64url(sessionIdBytes);\n const sessionIdHash = await sha256base64url(sessionId);\n\n const codeVerifierBytes = new Uint8Array(32);\n crypto.getRandomValues(codeVerifierBytes);\n const codeVerifier = base64url(codeVerifierBytes);\n const codeChallenge = await sha256base64url(codeVerifier);\n\n const stateValue = base64url(\n new TextEncoder().encode(\n JSON.stringify({\n return_path: returnPath,\n sid: sessionIdHash,\n })\n )\n );\n\n const clientId = hubspotConnectEnv.isCimdEnabled\n ? buildCimdClientIdUrlFromRequest({\n requestUrl: c.req.url,\n basePath: options.basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n appOrigin,\n })\n : hubspotConnectEnv.hubspotClientId;\n\n console.log('clientId', clientId);\n const redirectUri = buildFrontendOAuthRedirectUri(appOrigin);\n\n const authorizeUrl = new URL(hubspotConnectEnv.hubspotAuthorizationEndpoint);\n authorizeUrl.searchParams.set('response_type', 'code');\n authorizeUrl.searchParams.set('client_id', clientId);\n authorizeUrl.searchParams.set('redirect_uri', redirectUri);\n authorizeUrl.searchParams.set('code_challenge', codeChallenge);\n authorizeUrl.searchParams.set('code_challenge_method', 'S256');\n authorizeUrl.searchParams.set('state', stateValue);\n authorizeUrl.searchParams.set('sid', sessionIdHash);\n\n if (!hubspotConnectEnv.isCimdEnabled) {\n const scopesResult =\n deriveHubSpotAuthorizeScopesFromClientMetadata(cimdClientMetadata);\n if (!scopesResult.ok) {\n return c.text(scopesResult.message, scopesResult.status as 500 | 502);\n }\n authorizeUrl.searchParams.set('scope', scopesResult.scope);\n if (scopesResult.optionalScope !== undefined) {\n authorizeUrl.searchParams.set(\n 'optional_scope',\n scopesResult.optionalScope\n );\n }\n }\n\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n value: appOrigin,\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: SESSION_MAX_AGE_SEC,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_APP_SID_COOKIE_NAME,\n value: sessionId,\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: SESSION_MAX_AGE_SEC,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: TEMP_COOKIE_PKCE_VERIFIER,\n value: encodeURIComponent(codeVerifier),\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: OAUTH_TEMP_MAX_AGE_SEC,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: TEMP_COOKIE_OAUTH_STATE,\n value: encodeURIComponent(stateValue),\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: OAUTH_TEMP_MAX_AGE_SEC,\n }),\n });\n\n return c.json({ authorization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AI,aAAa,QAAQ;CACnD,aAAa,aAAa,IAAI,gBAAgB,WAAW;CACzD,aAAa,aAAa,IAAI,kBAAkB,aAAa;CAC7D,aAAa,aAAa,IAAI,yBAAyB,MAAM;CAC7D,aAAa,aAAa,IAAI,SAAS,UAAU;CACjD,aAAa,aAAa,IAAI,OAAO,aAAa;CAElD,IAAI,CAAC,kBAAkB,eAAe;EACpC,MAAM,eACJ,+CAA+C,kBAAkB;EACnE,IAAI,CAAC,aAAa,IAChB,OAAO,EAAE,KAAK,aAAa,SAAS,aAAa,MAAmB;EAEtE,aAAa,aAAa,IAAI,SAAS,aAAa,KAAK;EACzD,IAAI,aAAa,kBAAkB,KAAA,GACjC,aAAa,aAAa,IACxB,kBACA,aAAa,aACf;CAEJ;CAEA,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;EACV,CAAC;CACH,CAAC;CACD,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;EACV,CAAC;CACH,CAAC;CACD,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO,mBAAmB,YAAY;GACtC,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;EACV,CAAC;CACH,CAAC;CACD,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO,mBAAmB,UAAU;GACpC,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;EACV,CAAC;CACH,CAAC;CAED,OAAO,EAAE,KAAK,EAAE,mBAAmB,aAAa,SAAS,EAAE,CAAC;AAC9D"}
@@ -2,7 +2,7 @@ import { HUBSPOT_ACCESS_TOKEN_COOKIE_NAME, HUBSPOT_APP_ORIGIN_COOKIE_NAME, HUBSP
2
2
  import { parseCookies } from "../../utils/cookie-utils.js";
3
3
  import { serializeCookie, setResponseCookie } from "../utils/cookie-utils.js";
4
4
  import { buildClientAssertion } from "./oauth-client.js";
5
- import { buildCimdClientIdUrlFromRequest } from "./utils.js";
5
+ import { buildCimdClientIdUrlFromRequest, parseAppOriginHeader } from "./utils.js";
6
6
  //#region src/server/hono/hubspot-connect-routes/auth-logout.ts
7
7
  async function revokeToken(options) {
8
8
  const { revokeEndpointUrl, body, logger } = options;
@@ -24,13 +24,19 @@ async function handleAuthLogout(c, options) {
24
24
  const requestHostHeader = c.req.header("host") ?? void 0;
25
25
  const cookies = parseCookies(c.req.header("Cookie"));
26
26
  const accessToken = cookies[HUBSPOT_ACCESS_TOKEN_COOKIE_NAME];
27
- const clientId = hubspotConnectEnv.isCimdEnabled ? buildCimdClientIdUrlFromRequest({
28
- requestUrl: c.req.url,
29
- basePath,
30
- xForwardedProto,
31
- xForwardedHost,
32
- requestHostHeader
33
- }) : hubspotConnectEnv.hubspotClientId;
27
+ let clientId;
28
+ if (hubspotConnectEnv.isCimdEnabled) {
29
+ const appOrigin = parseAppOriginHeader(c.req.header("Origin"));
30
+ if (!appOrigin) return c.json({ error: "Missing or invalid Origin header" }, 400);
31
+ clientId = buildCimdClientIdUrlFromRequest({
32
+ requestUrl: c.req.url,
33
+ basePath,
34
+ xForwardedProto,
35
+ xForwardedHost,
36
+ requestHostHeader,
37
+ appOrigin
38
+ });
39
+ } else clientId = hubspotConnectEnv.hubspotClientId;
34
40
  const revokeEndpointUrl = new URL("/oauth/v1/revoke", hubspotConnectEnv.hubspotOAuthApiOrigin).href;
35
41
  if (accessToken) if (hubspotConnectEnv.isCimdEnabled) {
36
42
  if (!appKeys) return c.json({ error: "Server misconfiguration: HUBSPOT_APP_PRIVATE_KEY is required when CIMD is enabled" }, 500);
@@ -1 +1 @@
1
- {"version":3,"file":"auth-logout.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/auth-logout.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport type { Logger } from '../../../shared/logger.ts';\nimport {\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n HUBSPOT_REFRESH_COOKIE_PREFIX,\n} from '../../constants.ts';\nimport { parseCookies } from '../../utils/cookie-utils.ts';\nimport { serializeCookie, setResponseCookie } from '../utils/cookie-utils.ts';\nimport { buildClientAssertion } from './oauth-client.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport { buildCimdClientIdUrlFromRequest } from './utils.ts';\n\nasync function revokeToken(options: {\n revokeEndpointUrl: string;\n body: URLSearchParams;\n logger: Logger;\n}): Promise<void> {\n const { revokeEndpointUrl, body, logger } = options;\n try {\n const response = await fetch(revokeEndpointUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n });\n if (!response.ok) {\n logger.warn(\n `HubSpot token revoke returned HTTP ${response.status} ${response.statusText}`\n );\n }\n } catch (error) {\n logger.warn('HubSpot token revoke request failed', error);\n }\n}\n\nexport async function handleAuthLogout(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n) {\n const { appKeys, refreshCookiePath, basePath, hubspotConnectEnv, logger } =\n options;\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n const cookies = parseCookies(c.req.header('Cookie'));\n const accessToken = cookies[HUBSPOT_ACCESS_TOKEN_COOKIE_NAME];\n\n const clientId = hubspotConnectEnv.isCimdEnabled\n ? buildCimdClientIdUrlFromRequest({\n requestUrl: c.req.url,\n basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n })\n : hubspotConnectEnv.hubspotClientId;\n\n const revokeEndpointUrl = new URL(\n '/oauth/v1/revoke',\n hubspotConnectEnv.hubspotOAuthApiOrigin\n ).href;\n\n if (accessToken) {\n if (hubspotConnectEnv.isCimdEnabled) {\n if (!appKeys) {\n return c.json(\n {\n error:\n 'Server misconfiguration: HUBSPOT_APP_PRIVATE_KEY is required when CIMD is enabled',\n },\n 500\n );\n }\n const clientAssertion = await buildClientAssertion({\n appKeys,\n clientId,\n audience: revokeEndpointUrl,\n });\n await revokeToken({\n revokeEndpointUrl,\n body: new URLSearchParams({\n token: accessToken,\n token_type_hint: 'access_token',\n client_id: clientId,\n client_assertion_type:\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\n client_assertion: clientAssertion,\n }),\n logger,\n });\n } else {\n await revokeToken({\n revokeEndpointUrl,\n body: new URLSearchParams({\n token: accessToken,\n token_type_hint: 'access_token',\n client_id: clientId,\n client_secret: hubspotConnectEnv.hubspotClientSecret,\n }),\n logger,\n });\n }\n }\n\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n value: '',\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_APP_SID_COOKIE_NAME,\n value: '',\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n value: '',\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n\n Object.keys(cookies).forEach((cookieName) => {\n if (cookieName.startsWith(HUBSPOT_REFRESH_COOKIE_PREFIX)) {\n setResponseCookie({\n c,\n value: serializeCookie({\n name: cookieName,\n value: '',\n path: refreshCookiePath,\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n }\n });\n\n return c.json({ redirect_to: '/' });\n}\n"],"mappings":";;;;;;AAeA,eAAe,YAAY,SAIT;CAChB,MAAM,EAAE,mBAAmB,MAAM,WAAW;CAC5C,IAAI;EACF,MAAM,WAAW,MAAM,MAAM,mBAAmB;GAC9C,QAAQ;GACR,SA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ACT,CAAC;EACH,CAAC;CACF,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;GACT,CAAC;EACH,CAAC;CACF,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;GACT,CAAC;EACH,CAAC;CAEF,OAAO,KAAK,QAAQ,CAAC,SAAS,eAAe;EAC3C,IAAI,WAAW,WAAA,cAAyC,EACtD,kBAAkB;GAChB;GACA,OAAO,gBAAgB;IACrB,MAAM;IACN,OAAO;IACP,MAAM;IACN,UAAU;IACV,aAAa;IACb,QAAQ;IACT,CAAC;GACH,CAAC;GAEJ;CAEF,OAAO,EAAE,KAAK,EAAE,aAAa,KAAK,CAAC"}
1
+ {"version":3,"file":"auth-logout.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/auth-logout.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport type { Logger } from '../../../shared/logger.ts';\nimport {\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n HUBSPOT_REFRESH_COOKIE_PREFIX,\n} from '../../constants.ts';\nimport { parseCookies } from '../../utils/cookie-utils.ts';\nimport { serializeCookie, setResponseCookie } from '../utils/cookie-utils.ts';\nimport { buildClientAssertion } from './oauth-client.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport {\n buildCimdClientIdUrlFromRequest,\n parseAppOriginHeader,\n} from './utils.ts';\n\nasync function revokeToken(options: {\n revokeEndpointUrl: string;\n body: URLSearchParams;\n logger: Logger;\n}): Promise<void> {\n const { revokeEndpointUrl, body, logger } = options;\n try {\n const response = await fetch(revokeEndpointUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n });\n if (!response.ok) {\n logger.warn(\n `HubSpot token revoke returned HTTP ${response.status} ${response.statusText}`\n );\n }\n } catch (error) {\n logger.warn('HubSpot token revoke request failed', error);\n }\n}\n\nexport async function handleAuthLogout(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n) {\n const { appKeys, refreshCookiePath, basePath, hubspotConnectEnv, logger } =\n options;\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n const cookies = parseCookies(c.req.header('Cookie'));\n const accessToken = cookies[HUBSPOT_ACCESS_TOKEN_COOKIE_NAME];\n\n let clientId: string;\n if (hubspotConnectEnv.isCimdEnabled) {\n const appOrigin = parseAppOriginHeader(c.req.header('Origin'));\n if (!appOrigin) {\n return c.json({ error: 'Missing or invalid Origin header' }, 400);\n }\n clientId = buildCimdClientIdUrlFromRequest({\n requestUrl: c.req.url,\n basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n appOrigin,\n });\n } else {\n clientId = hubspotConnectEnv.hubspotClientId;\n }\n\n const revokeEndpointUrl = new URL(\n '/oauth/v1/revoke',\n hubspotConnectEnv.hubspotOAuthApiOrigin\n ).href;\n\n if (accessToken) {\n if (hubspotConnectEnv.isCimdEnabled) {\n if (!appKeys) {\n return c.json(\n {\n error:\n 'Server misconfiguration: HUBSPOT_APP_PRIVATE_KEY is required when CIMD is enabled',\n },\n 500\n );\n }\n const clientAssertion = await buildClientAssertion({\n appKeys,\n clientId,\n audience: revokeEndpointUrl,\n });\n await revokeToken({\n revokeEndpointUrl,\n body: new URLSearchParams({\n token: accessToken,\n token_type_hint: 'access_token',\n client_id: clientId,\n client_assertion_type:\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\n client_assertion: clientAssertion,\n }),\n logger,\n });\n } else {\n await revokeToken({\n revokeEndpointUrl,\n body: new URLSearchParams({\n token: accessToken,\n token_type_hint: 'access_token',\n client_id: clientId,\n client_secret: hubspotConnectEnv.hubspotClientSecret,\n }),\n logger,\n });\n }\n }\n\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n value: '',\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_APP_SID_COOKIE_NAME,\n value: '',\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_APP_ORIGIN_COOKIE_NAME,\n value: '',\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n\n Object.keys(cookies).forEach((cookieName) => {\n if (cookieName.startsWith(HUBSPOT_REFRESH_COOKIE_PREFIX)) {\n setResponseCookie({\n c,\n value: serializeCookie({\n name: cookieName,\n value: '',\n path: refreshCookiePath,\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n }\n });\n\n return c.json({ redirect_to: '/' });\n}\n"],"mappings":";;;;;;AAkBA,eAAe,YAAY,SAIT;CAChB,MAAM,EAAE,mBAAmB,MAAM,WAAW;CAC5C,IAAI;EACF,MAAM,WAAW,MAAM,MAAM,mBAAmB;GAC9C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oCAAoC;GAC/D;EACF,CAAC;EACD,IAAI,CAAC,SAAS,IACZ,OAAO,KACL,sCAAsC,SAAS,OAAO,GAAG,SAAS,YACpE;CAEJ,SAAS,OAAO;EACd,OAAO,KAAK,uCAAuC,KAAK;CAC1D;AACF;AAEA,eAAsB,iBACpB,GACA,SACA;CACA,MAAM,EAAE,SAAS,mBAAmB,UAAU,mBAAmB,WAC/D;CACF,MAAM,kBAAkB,EAAE,IAAI,OAAO,mBAAmB,KAAK,KAAA;CAC7D,MAAM,iBAAiB,EAAE,IAAI,OAAO,kBAAkB,KAAK,KAAA;CAC3D,MAAM,oBAAoB,EA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,UAAU;GACV,aAAa;GACb,QAAQ;EACV,CAAC;CACH,CAAC;CAED,OAAO,KAAK,OAAO,EAAE,SAAS,eAAe;EAC3C,IAAI,WAAW,WAAA,aAAwC,GACrD,kBAAkB;GAChB;GACA,OAAO,gBAAgB;IACrB,MAAM;IACN,OAAO;IACP,MAAM;IACN,UAAU;IACV,aAAa;IACb,QAAQ;GACV,CAAC;EACH,CAAC;CAEL,CAAC;CAED,OAAO,EAAE,KAAK,EAAE,aAAa,IAAI,CAAC;AACpC"}
@@ -4,7 +4,7 @@ import { parseCookies } from "../../utils/cookie-utils.js";
4
4
  import { serializeCookie, setResponseCookie } from "../utils/cookie-utils.js";
5
5
  import { REFRESH_COOKIE_MAX_AGE_SEC } from "./constants.js";
6
6
  import { buildClientAssertion, buildClientAssertionFormParams, buildClientSecretFormParams, buildTokenEndpointDpopProof, requestOAuthToken } from "./oauth-client.js";
7
- import { buildCimdClientIdUrlFromRequest, isPositiveFiniteNumber } from "./utils.js";
7
+ import { buildCimdClientIdUrlFromRequest, isPositiveFiniteNumber, parseAppOriginHeader } from "./utils.js";
8
8
  //#region src/server/hono/hubspot-connect-routes/auth-refresh.ts
9
9
  async function handleAuthRefresh(c, options) {
10
10
  const { appKeys, refreshCookiePath, basePath, hubspotConnectEnv } = options;
@@ -19,13 +19,19 @@ async function handleAuthRefresh(c, options) {
19
19
  const refreshCookieName = `${HUBSPOT_REFRESH_COOKIE_PREFIX}${sidHash}`;
20
20
  const refreshToken = cookies[refreshCookieName];
21
21
  if (!refreshToken) return c.json({ error: "Missing refresh token" }, 401);
22
- const clientId = hubspotConnectEnv.isCimdEnabled ? buildCimdClientIdUrlFromRequest({
23
- requestUrl: c.req.url,
24
- basePath,
25
- xForwardedProto,
26
- xForwardedHost,
27
- requestHostHeader
28
- }) : hubspotConnectEnv.hubspotClientId;
22
+ let clientId;
23
+ if (hubspotConnectEnv.isCimdEnabled) {
24
+ const appOrigin = parseAppOriginHeader(c.req.header("Origin"));
25
+ if (!appOrigin) return c.json({ error: "Missing or invalid Origin header" }, 400);
26
+ clientId = buildCimdClientIdUrlFromRequest({
27
+ requestUrl: c.req.url,
28
+ basePath,
29
+ xForwardedProto,
30
+ xForwardedHost,
31
+ requestHostHeader,
32
+ appOrigin
33
+ });
34
+ } else clientId = hubspotConnectEnv.hubspotClientId;
29
35
  const tokenEndpointUrl = new URL("/oauth/v1/token", hubspotConnectEnv.hubspotOAuthApiOrigin).href;
30
36
  let dpopProof;
31
37
  if (hubspotConnectEnv.isDpopEnabled) dpopProof = await buildTokenEndpointDpopProof({
@@ -34,19 +40,21 @@ async function handleAuthRefresh(c, options) {
34
40
  sessionIdHash: sidHash
35
41
  });
36
42
  let formParams;
37
- if (hubspotConnectEnv.isCimdEnabled) formParams = {
38
- grant_type: "refresh_token",
39
- refresh_token: refreshToken,
40
- ...buildClientAssertionFormParams({
43
+ if (hubspotConnectEnv.isCimdEnabled) {
44
+ const clientAssertion = await buildClientAssertion({
45
+ appKeys,
41
46
  clientId,
42
- clientAssertion: await buildClientAssertion({
43
- appKeys,
47
+ audience: tokenEndpointUrl
48
+ });
49
+ formParams = {
50
+ grant_type: "refresh_token",
51
+ refresh_token: refreshToken,
52
+ ...buildClientAssertionFormParams({
44
53
  clientId,
45
- audience: tokenEndpointUrl
54
+ clientAssertion
46
55
  })
47
- })
48
- };
49
- else formParams = {
56
+ };
57
+ } else formParams = {
50
58
  grant_type: "refresh_token",
51
59
  refresh_token: refreshToken,
52
60
  ...buildClientSecretFormParams({
@@ -1 +1 @@
1
- {"version":3,"file":"auth-refresh.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/auth-refresh.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport {\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n HUBSPOT_REFRESH_COOKIE_PREFIX,\n} from '../../constants.ts';\nimport { parseCookies } from '../../utils/cookie-utils.ts';\nimport { sha256base64url } from '../../utils/crypto-utils.ts';\nimport { serializeCookie, setResponseCookie } from '../utils/cookie-utils.ts';\nimport { REFRESH_COOKIE_MAX_AGE_SEC } from './constants.ts';\nimport {\n buildClientAssertion,\n buildClientAssertionFormParams,\n buildClientSecretFormParams,\n buildTokenEndpointDpopProof,\n requestOAuthToken,\n} from './oauth-client.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport {\n buildCimdClientIdUrlFromRequest,\n isPositiveFiniteNumber,\n} from './utils.ts';\n\nexport async function handleAuthRefresh(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n) {\n const { appKeys, refreshCookiePath, basePath, hubspotConnectEnv } = options;\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n const cookies = parseCookies(c.req.header('Cookie'));\n const sessionId = cookies[HUBSPOT_APP_SID_COOKIE_NAME];\n if (!sessionId) {\n return c.json({ error: 'Missing session cookie' }, 401);\n }\n\n if (hubspotConnectEnv.isAppPrivateKeyRequired && !appKeys) {\n return c.json(\n {\n error:\n 'Server misconfiguration: HUBSPOT_APP_PRIVATE_KEY is required when CIMD or DPoP is enabled',\n },\n 500\n );\n }\n\n const sidHash = await sha256base64url(sessionId);\n const refreshCookieName = `${HUBSPOT_REFRESH_COOKIE_PREFIX}${sidHash}`;\n const refreshToken = cookies[refreshCookieName];\n if (!refreshToken) {\n return c.json({ error: 'Missing refresh token' }, 401);\n }\n\n const clientId = hubspotConnectEnv.isCimdEnabled\n ? buildCimdClientIdUrlFromRequest({\n requestUrl: c.req.url,\n basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n })\n : hubspotConnectEnv.hubspotClientId;\n\n const tokenEndpointUrl = new URL(\n '/oauth/v1/token',\n hubspotConnectEnv.hubspotOAuthApiOrigin\n ).href;\n\n let dpopProof: string | undefined;\n if (hubspotConnectEnv.isDpopEnabled) {\n dpopProof = await buildTokenEndpointDpopProof({\n appKeys: appKeys!,\n tokenEndpointUrl,\n sessionIdHash: sidHash,\n });\n }\n\n let formParams: Record<string, string>;\n if (hubspotConnectEnv.isCimdEnabled) {\n const clientAssertion = await buildClientAssertion({\n appKeys: appKeys!,\n clientId,\n audience: tokenEndpointUrl,\n });\n formParams = {\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n ...buildClientAssertionFormParams({ clientId, clientAssertion }),\n };\n } else {\n formParams = {\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n ...buildClientSecretFormParams({\n clientId,\n clientSecret: hubspotConnectEnv.hubspotClientSecret,\n }),\n };\n }\n\n const tokenResult = await requestOAuthToken({\n tokenEndpointUrl,\n isDpopEnabled: hubspotConnectEnv.isDpopEnabled,\n ...(dpopProof !== undefined ? { dpopProof } : {}),\n formParams,\n });\n if (!tokenResult.ok) {\n return c.json(\n { error: `Token refresh failed: ${tokenResult.errorText}` },\n 502\n );\n }\n\n const {\n access_token: newAccessToken,\n refresh_token: newRefreshToken,\n expires_in,\n } = tokenResult.body;\n\n if (!newRefreshToken) {\n return c.json({ error: 'Token response missing refresh_token' }, 502);\n }\n if (!isPositiveFiniteNumber(expires_in)) {\n return c.json(\n { error: 'Token response missing or invalid expires_in' },\n 502\n );\n }\n\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n value: newAccessToken,\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: expires_in,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: refreshCookieName,\n value: newRefreshToken,\n path: refreshCookiePath,\n sameSite: 'None',\n partitioned: true,\n maxAge: REFRESH_COOKIE_MAX_AGE_SEC,\n }),\n });\n\n // Cookies prefixed with HUBSPOT_REFRESH_COOKIE_PREFIX that don't match the\n // new refresh cookie name are stale and need to be cleared.\n Object.keys(cookies).forEach((cookieName) => {\n if (\n cookieName.startsWith(HUBSPOT_REFRESH_COOKIE_PREFIX) &&\n cookieName !== refreshCookieName\n ) {\n setResponseCookie({\n c,\n value: serializeCookie({\n name: cookieName,\n value: '',\n path: refreshCookiePath,\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n }\n });\n\n return c.json({ expires_in });\n}\n"],"mappings":";;;;;;;;AAwBA,eAAsB,kBACpB,GACA,SACA;CACA,MAAM,EAAE,SAAS,mBAAmB,UAAU,sBAAsB;CACpE,MAAM,kBAAkB,EAAE,IAAI,OAAO,oBAAoB,IAAI,KAAA;CAC7D,MAAM,iBAAiB,EAAE,IAAI,OAAO,mBAAmB,IAAI,KAAA;CAC3D,MAAM,oBAAoB,EAAE,IAAI,OAAO,OAAO,IAAI,KAAA;CAClD,MAAM,UAAU,aAAa,EAAE,IAAI,OAAO,SAAS,CAAC;CACpD,MAAM,YAAY,QAAQ;CAC1B,IAAI,CAAC,WACH,OAAO,EAAE,KAAK,EAAE,OAAO,0BAA0B,EAAE,IAAI;CAGzD,IAAI,kBAAkB,2BAA2B,CAAC,SAChD,OAAO,EAAE,KACP,EACE,OACE,6FACH,EACD,IACD;CAGH,MAAM,UAAU,MAAM,gBAAgB,UAAU;CAChD,MAAM,oBAAoB,GAAG,gCAAgC;CAC7D,MAAM,eAAe,QAAQ;CAC7B,IAAI,CAAC,cACH,OAAO,EAAE,KAAK,EAAE,OAAO,yBAAyB,EAAE,IAAI;CAGxD,MAAM,WAAW,kBAAkB,gBAC/B,gCAAgC;EAC9B,YAAY,EAAE,IAAI;EAClB;EACA;EACA;EACA;EACD,CAAC,GACF,kBAAkB;CAEtB,MAAM,mBAAmB,IAAI,IAC3B,mBACA,kBAAkB,sBACnB,CAAC;CAEF,IAAI;CACJ,IAAI,kBAAkB,eACpB,YAAY,MAAM,4BAA4B;EACnC;EACT;EACA,eAAe;EAChB,CAAC;CAGJ,IAAI;CACJ,IAAI,kBAAkB,eAMpB,aAAa;EACX,YAAY;EACZ,eAAe;EACf,GAAG,+BAA+B;GAAE;GAAU,iBAAA,MARlB,qBAAqB;IACxC;IACT;IACA,UAAU;IACX,CAAC;GAI+D,CAAC;EACjE;MAED,aAAa;EACX,YAAY;EACZ,eAAe;EACf,GAAG,4BAA4B;GAC7B;GACA,cAAc,kBAAkB;GACjC,CAAC;EACH;CAGH,MAAM,cAAc,MAAM,kBAAkB;EAC1C;EACA,eAAe,kBAAkB;EACjC,GAAI,cAAc,KAAA,IAAY,EAAE,WAAW,GAAG,EAAE;EAChD;EACD,CAAC;CACF,IAAI,CAAC,YAAY,IACf,OAAO,EAAE,KACP,EAAE,OAAO,yBAAyB,YAAY,aAAa,EAC3D,IACD;CAGH,MAAM,EACJ,cAAc,gBACd,eAAe,iBACf,eACE,YAAY;CAEhB,IAAI,CAAC,iBACH,OAAO,EAAE,KAAK,EAAE,OAAO,wCAAwC,EAAE,IAAI;CAEvE,IAAI,CAAC,uBAAuB,WAAW,EACrC,OAAO,EAAE,KACP,EAAE,OAAO,gDAAgD,EACzD,IACD;CAGH,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;GACT,CAAC;EACH,CAAC;CACF,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;GACT,CAAC;EACH,CAAC;CAIF,OAAO,KAAK,QAAQ,CAAC,SAAS,eAAe;EAC3C,IACE,WAAW,WAAA,cAAyC,IACpD,eAAe,mBAEf,kBAAkB;GAChB;GACA,OAAO,gBAAgB;IACrB,MAAM;IACN,OAAO;IACP,MAAM;IACN,UAAU;IACV,aAAa;IACb,QAAQ;IACT,CAAC;GACH,CAAC;GAEJ;CAEF,OAAO,EAAE,KAAK,EAAE,YAAY,CAAC"}
1
+ {"version":3,"file":"auth-refresh.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/auth-refresh.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport {\n HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n HUBSPOT_APP_SID_COOKIE_NAME,\n HUBSPOT_REFRESH_COOKIE_PREFIX,\n} from '../../constants.ts';\nimport { parseCookies } from '../../utils/cookie-utils.ts';\nimport { sha256base64url } from '../../utils/crypto-utils.ts';\nimport { serializeCookie, setResponseCookie } from '../utils/cookie-utils.ts';\nimport { REFRESH_COOKIE_MAX_AGE_SEC } from './constants.ts';\nimport {\n buildClientAssertion,\n buildClientAssertionFormParams,\n buildClientSecretFormParams,\n buildTokenEndpointDpopProof,\n requestOAuthToken,\n} from './oauth-client.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport {\n buildCimdClientIdUrlFromRequest,\n isPositiveFiniteNumber,\n parseAppOriginHeader,\n} from './utils.ts';\n\nexport async function handleAuthRefresh(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n) {\n const { appKeys, refreshCookiePath, basePath, hubspotConnectEnv } = options;\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n const cookies = parseCookies(c.req.header('Cookie'));\n const sessionId = cookies[HUBSPOT_APP_SID_COOKIE_NAME];\n if (!sessionId) {\n return c.json({ error: 'Missing session cookie' }, 401);\n }\n\n if (hubspotConnectEnv.isAppPrivateKeyRequired && !appKeys) {\n return c.json(\n {\n error:\n 'Server misconfiguration: HUBSPOT_APP_PRIVATE_KEY is required when CIMD or DPoP is enabled',\n },\n 500\n );\n }\n\n const sidHash = await sha256base64url(sessionId);\n const refreshCookieName = `${HUBSPOT_REFRESH_COOKIE_PREFIX}${sidHash}`;\n const refreshToken = cookies[refreshCookieName];\n if (!refreshToken) {\n return c.json({ error: 'Missing refresh token' }, 401);\n }\n\n let clientId: string;\n if (hubspotConnectEnv.isCimdEnabled) {\n const appOrigin = parseAppOriginHeader(c.req.header('Origin'));\n if (!appOrigin) {\n return c.json({ error: 'Missing or invalid Origin header' }, 400);\n }\n clientId = buildCimdClientIdUrlFromRequest({\n requestUrl: c.req.url,\n basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n appOrigin,\n });\n } else {\n clientId = hubspotConnectEnv.hubspotClientId;\n }\n\n const tokenEndpointUrl = new URL(\n '/oauth/v1/token',\n hubspotConnectEnv.hubspotOAuthApiOrigin\n ).href;\n\n let dpopProof: string | undefined;\n if (hubspotConnectEnv.isDpopEnabled) {\n dpopProof = await buildTokenEndpointDpopProof({\n appKeys: appKeys!,\n tokenEndpointUrl,\n sessionIdHash: sidHash,\n });\n }\n\n let formParams: Record<string, string>;\n if (hubspotConnectEnv.isCimdEnabled) {\n const clientAssertion = await buildClientAssertion({\n appKeys: appKeys!,\n clientId,\n audience: tokenEndpointUrl,\n });\n formParams = {\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n ...buildClientAssertionFormParams({ clientId, clientAssertion }),\n };\n } else {\n formParams = {\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n ...buildClientSecretFormParams({\n clientId,\n clientSecret: hubspotConnectEnv.hubspotClientSecret,\n }),\n };\n }\n\n const tokenResult = await requestOAuthToken({\n tokenEndpointUrl,\n isDpopEnabled: hubspotConnectEnv.isDpopEnabled,\n ...(dpopProof !== undefined ? { dpopProof } : {}),\n formParams,\n });\n if (!tokenResult.ok) {\n return c.json(\n { error: `Token refresh failed: ${tokenResult.errorText}` },\n 502\n );\n }\n\n const {\n access_token: newAccessToken,\n refresh_token: newRefreshToken,\n expires_in,\n } = tokenResult.body;\n\n if (!newRefreshToken) {\n return c.json({ error: 'Token response missing refresh_token' }, 502);\n }\n if (!isPositiveFiniteNumber(expires_in)) {\n return c.json(\n { error: 'Token response missing or invalid expires_in' },\n 502\n );\n }\n\n setResponseCookie({\n c,\n value: serializeCookie({\n name: HUBSPOT_ACCESS_TOKEN_COOKIE_NAME,\n value: newAccessToken,\n path: '/',\n sameSite: 'None',\n partitioned: true,\n maxAge: expires_in,\n }),\n });\n setResponseCookie({\n c,\n value: serializeCookie({\n name: refreshCookieName,\n value: newRefreshToken,\n path: refreshCookiePath,\n sameSite: 'None',\n partitioned: true,\n maxAge: REFRESH_COOKIE_MAX_AGE_SEC,\n }),\n });\n\n // Cookies prefixed with HUBSPOT_REFRESH_COOKIE_PREFIX that don't match the\n // new refresh cookie name are stale and need to be cleared.\n Object.keys(cookies).forEach((cookieName) => {\n if (\n cookieName.startsWith(HUBSPOT_REFRESH_COOKIE_PREFIX) &&\n cookieName !== refreshCookieName\n ) {\n setResponseCookie({\n c,\n value: serializeCookie({\n name: cookieName,\n value: '',\n path: refreshCookiePath,\n sameSite: 'None',\n partitioned: true,\n maxAge: 0,\n }),\n });\n }\n });\n\n return c.json({ expires_in });\n}\n"],"mappings":";;;;;;;;AAyBA,eAAsB,kBACpB,GACA,SACA;CACA,MAAM,EAAE,SAAS,mBAAmB,UAAU,sBAAsB;CACpE,MAAM,kBAAkB,EAAE,IAAI,OAAO,mBAAmB,KAAK,KAAA;CAC7D,MAAM,iBAAiB,EAAE,IAAI,OAAO,kBAAkB,KAAK,KAAA;CAC3D,MAAM,oBAAoB,EAAE,IAAI,OAAO,MAAM,KAAK,KAAA;CAClD,MAAM,UAAU,aAAa,EAAE,IAAI,OAAO,QAAQ,CAAC;CACnD,MAAM,YAAY,QAAQ;CAC1B,IAAI,CAAC,WACH,OAAO,EAAE,KAAK,EAAE,OAAO,yBAAyB,GAAG,GAAG;CAGxD,IAAI,kBAAkB,2BAA2B,CAAC,SAChD,OAAO,EAAE,KACP,EACE,OACE,4FACJ,GACA,GACF;CAGF,MAAM,UAAU,MAAM,gBAAgB,SAAS;CAC/C,MAAM,oBAAoB,GAAG,gCAAgC;CAC7D,MAAM,eAAe,QAAQ;CAC7B,IAAI,CAAC,cACH,OAAO,EAAE,KAAK,EAAE,OAAO,wBAAwB,GAAG,GAAG;CAGvD,IAAI;CACJ,IAAI,kBAAkB,eAAe;EACnC,MAAM,YAAY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;CACD,kBAAkB;EAChB;EACA,OAAO,gBAAgB;GACrB,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,aAAa;GACb,QAAQ;EACV,CAAC;CACH,CAAC;CAID,OAAO,KAAK,OAAO,EAAE,SAAS,eAAe;EAC3C,IACE,WAAW,WAAA,aAAwC,KACnD,eAAe,mBAEf,kBAAkB;GAChB;GACA,OAAO,gBAAgB;IACrB,MAAM;IACN,OAAO;IACP,MAAM;IACN,UAAU;IACV,aAAa;IACb,QAAQ;GACV,CAAC;EACH,CAAC;CAEL,CAAC;CAED,OAAO,EAAE,KAAK,EAAE,WAAW,CAAC;AAC9B"}
@@ -1 +1 @@
1
- {"version":3,"file":"cimd-client-metadata-types.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/cimd-client-metadata-types.ts"],"sourcesContent":["/**\n * Caller-supplied scope configuration for the CIMD document served at\n * `{basePath}/client.json`. `redirect_uri` and `jwks_uri` are derived at\n * request time by the hubspot-connect routes.\n */\nexport interface HubSpotConnectCimdClientMetadata {\n scope: HubSpotConnectCimdClientScope;\n}\n\nexport interface HubSpotConnectCimdClientScope {\n required: string[];\n optional?: string[];\n}\n\n/**\n * JSON body returned by `GET {basePath}/client.json` (HubSpot CIMD).\n */\nexport interface HubSpotConnectCimdClientDocument {\n redirect_uri: string;\n jwks_uri: string;\n scope: HubSpotConnectCimdClientScope;\n}\n\nexport function assertHubSpotConnectCimdClientMetadata(\n value: HubSpotConnectCimdClientMetadata\n): void {\n const required = value.scope?.required;\n const requiredOk =\n Array.isArray(required) &&\n required.length > 0 &&\n required.every((s) => typeof s === 'string' && s.length > 0);\n if (!requiredOk) {\n throw new Error(\n 'HubSpotConnectCimdClientMetadata.scope.required must be a non-empty array of non-empty strings'\n );\n }\n const optional = value.scope.optional;\n if (optional === undefined) {\n return;\n }\n if (!Array.isArray(optional)) {\n throw new Error(\n 'HubSpotConnectCimdClientMetadata.scope.optional must be an array when set'\n );\n }\n if (\n optional.length > 0 &&\n !optional.every((s) => typeof s === 'string' && s.length > 0)\n ) {\n throw new Error(\n 'HubSpotConnectCimdClientMetadata.scope.optional entries must be non-empty strings'\n );\n }\n}\n"],"mappings":";AAuBA,SAAgB,uCACd,OACM;CACN,MAAM,WAAW,MAAM,OAAO;CAK9B,IAAI,EAHF,MAAM,QAAQ,SAAS,IACvB,SAAS,SAAS,KAClB,SAAS,OAAO,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,EAAE,GAE5D,MAAM,IAAI,MACR,iGACD;CAEH,MAAM,WAAW,MAAM,MAAM;CAC7B,IAAI,aAAa,KAAA,GACf;CAEF,IAAI,CAAC,MAAM,QAAQ,SAAS,EAC1B,MAAM,IAAI,MACR,4EACD;CAEH,IACE,SAAS,SAAS,KAClB,CAAC,SAAS,OAAO,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,EAAE,EAE7D,MAAM,IAAI,MACR,oFACD"}
1
+ {"version":3,"file":"cimd-client-metadata-types.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/cimd-client-metadata-types.ts"],"sourcesContent":["/**\n * Caller-supplied scope configuration for the CIMD document served at\n * `{basePath}/client.json`. `redirect_uri` and `jwks_uri` are derived at\n * request time by the hubspot-connect routes.\n */\nexport interface HubSpotConnectCimdClientMetadata {\n scope: HubSpotConnectCimdClientScope;\n}\n\nexport interface HubSpotConnectCimdClientScope {\n required: string[];\n optional?: string[];\n}\n\n/**\n * JSON body returned by `GET {basePath}/client.json` (HubSpot CIMD).\n */\nexport interface HubSpotConnectCimdClientDocument {\n redirect_uri: string;\n jwks_uri: string;\n scope: HubSpotConnectCimdClientScope;\n}\n\nexport function assertHubSpotConnectCimdClientMetadata(\n value: HubSpotConnectCimdClientMetadata\n): void {\n const required = value.scope?.required;\n const requiredOk =\n Array.isArray(required) &&\n required.length > 0 &&\n required.every((s) => typeof s === 'string' && s.length > 0);\n if (!requiredOk) {\n throw new Error(\n 'HubSpotConnectCimdClientMetadata.scope.required must be a non-empty array of non-empty strings'\n );\n }\n const optional = value.scope.optional;\n if (optional === undefined) {\n return;\n }\n if (!Array.isArray(optional)) {\n throw new Error(\n 'HubSpotConnectCimdClientMetadata.scope.optional must be an array when set'\n );\n }\n if (\n optional.length > 0 &&\n !optional.every((s) => typeof s === 'string' && s.length > 0)\n ) {\n throw new Error(\n 'HubSpotConnectCimdClientMetadata.scope.optional entries must be non-empty strings'\n );\n }\n}\n"],"mappings":";AAuBA,SAAgB,uCACd,OACM;CACN,MAAM,WAAW,MAAM,OAAO;CAK9B,IAAI,EAHF,MAAM,QAAQ,QAAQ,KACtB,SAAS,SAAS,KAClB,SAAS,OAAO,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,CAAC,IAE3D,MAAM,IAAI,MACR,gGACF;CAEF,MAAM,WAAW,MAAM,MAAM;CAC7B,IAAI,aAAa,KAAA,GACf;CAEF,IAAI,CAAC,MAAM,QAAQ,QAAQ,GACzB,MAAM,IAAI,MACR,2EACF;CAEF,IACE,SAAS,SAAS,KAClB,CAAC,SAAS,OAAO,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,CAAC,GAE5D,MAAM,IAAI,MACR,mFACF;AAEJ"}
@@ -7,12 +7,15 @@ async function handleCimdClientJson(c, options) {
7
7
  const xForwardedProto = c.req.header("x-forwarded-proto") ?? void 0;
8
8
  const xForwardedHost = c.req.header("x-forwarded-host") ?? void 0;
9
9
  const requestHostHeader = c.req.header("host") ?? void 0;
10
+ const appOrigin = c.req.query("app_origin");
11
+ if (!appOrigin) return c.text("Missing app origin", 400);
10
12
  const forwarded = {
11
13
  requestUrl: c.req.url,
12
14
  basePath,
13
15
  xForwardedProto,
14
16
  xForwardedHost,
15
- requestHostHeader
17
+ requestHostHeader,
18
+ appOrigin
16
19
  };
17
20
  const body = {
18
21
  redirect_uri: buildOAuthRedirectUriFromRequest(forwarded),
@@ -1 +1 @@
1
- {"version":3,"file":"cimd-public-routes.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/cimd-public-routes.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport type { JwkSet } from '../../types.ts';\nimport { getJwkThumbprint } from '../../utils/jwk-utils.ts';\nimport type { HubSpotConnectCimdClientDocument } from './cimd-client-metadata-types.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport {\n buildHubSpotAppJwksUrlFromRequest,\n buildOAuthRedirectUriFromRequest,\n type BuildOAuthRedirectUriFromRequestOptions,\n} from './utils.ts';\n\nexport async function handleCimdClientJson(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n): Promise<Response> {\n const { cimdClientMetadata, basePath } = options;\n if (!cimdClientMetadata) {\n return c.text('CIMD client metadata is not configured', 500);\n }\n\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n\n const forwarded: BuildOAuthRedirectUriFromRequestOptions = {\n requestUrl: c.req.url,\n basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n };\n\n const body: HubSpotConnectCimdClientDocument = {\n redirect_uri: buildOAuthRedirectUriFromRequest(forwarded),\n jwks_uri: buildHubSpotAppJwksUrlFromRequest(forwarded),\n scope: cimdClientMetadata.scope,\n };\n\n return c.text(JSON.stringify(body, null, 2), 200, {\n 'Content-Type': 'application/json; charset=utf-8',\n });\n}\n\nexport async function handleCimdAppJwks(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n): Promise<Response> {\n const { appKeys, hubspotConnectEnv } = options;\n if (!hubspotConnectEnv.isCimdEnabled) {\n return c.text('Not found', 404);\n }\n if (!appKeys) {\n return c.text('Missing app keys', 503);\n }\n\n const kid = await getJwkThumbprint({\n publicKeyJwk: appKeys.appPublicKeyJwk,\n });\n\n const jwk = {\n ...appKeys.appPublicKeyJwk,\n kid,\n use: 'sig',\n alg: 'ES256',\n key_ops: ['verify'],\n ext: true,\n } as JsonWebKey;\n\n const jwks: JwkSet = { keys: [jwk] };\n return c.json(jwks);\n}\n"],"mappings":";;;AAYA,eAAsB,qBACpB,GACA,SACmB;CACnB,MAAM,EAAE,oBAAoB,aAAa;CACzC,IAAI,CAAC,oBACH,OAAO,EAAE,KAAK,0CAA0C,IAAI;CAG9D,MAAM,kBAAkB,EAAE,IAAI,OAAO,oBAAoB,IAAI,KAAA;CAC7D,MAAM,iBAAiB,EAAE,IAAI,OAAO,mBAAmB,IAAI,KAAA;CAC3D,MAAM,oBAAoB,EAAE,IAAI,OAAO,OAAO,IAAI,KAAA;CAElD,MAAM,YAAqD;EACzD,YAAY,EAAE,IAAI;EAClB;EACA;EACA;EACA;EACD;CAED,MAAM,OAAyC;EAC7C,cAAc,iCAAiC,UAAU;EACzD,UAAU,kCAAkC,UAAU;EACtD,OAAO,mBAAmB;EAC3B;CAED,OAAO,EAAE,KAAK,KAAK,UAAU,MAAM,MAAM,EAAE,EAAE,KAAK,EAChD,gBAAgB,mCACjB,CAAC;;AAGJ,eAAsB,kBACpB,GACA,SACmB;CACnB,MAAM,EAAE,SAAS,sBAAsB;CACvC,IAAI,CAAC,kBAAkB,eACrB,OAAO,EAAE,KAAK,aAAa,IAAI;CAEjC,IAAI,CAAC,SACH,OAAO,EAAE,KAAK,oBAAoB,IAAI;CAGxC,MAAM,MAAM,MAAM,iBAAiB,EACjC,cAAc,QAAQ,iBACvB,CAAC;CAWF,MAAM,OAAe,EAAE,MAAM,CAAC;EAR5B,GAAG,QAAQ;EACX;EACA,KAAK;EACL,KAAK;EACL,SAAS,CAAC,SAAS;EACnB,KAAK;EAG0B,CAAC,EAAE;CACpC,OAAO,EAAE,KAAK,KAAK"}
1
+ {"version":3,"file":"cimd-public-routes.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/cimd-public-routes.ts"],"sourcesContent":["import type { Context } from 'hono';\n\nimport type { JwkSet } from '../../types.ts';\nimport { getJwkThumbprint } from '../../utils/jwk-utils.ts';\nimport type { HubSpotConnectCimdClientDocument } from './cimd-client-metadata-types.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\nimport {\n buildHubSpotAppJwksUrlFromRequest,\n buildOAuthRedirectUriFromRequest,\n type BuildOAuthRedirectUriFromRequestOptions,\n} from './utils.ts';\n\nexport async function handleCimdClientJson(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n): Promise<Response> {\n const { cimdClientMetadata, basePath } = options;\n if (!cimdClientMetadata) {\n return c.text('CIMD client metadata is not configured', 500);\n }\n\n const xForwardedProto = c.req.header('x-forwarded-proto') ?? undefined;\n const xForwardedHost = c.req.header('x-forwarded-host') ?? undefined;\n const requestHostHeader = c.req.header('host') ?? undefined;\n const appOrigin = c.req.query('app_origin');\n if (!appOrigin) {\n return c.text('Missing app origin', 400);\n }\n const forwarded: BuildOAuthRedirectUriFromRequestOptions = {\n requestUrl: c.req.url,\n basePath,\n xForwardedProto,\n xForwardedHost,\n requestHostHeader,\n appOrigin,\n };\n\n const body: HubSpotConnectCimdClientDocument = {\n redirect_uri: buildOAuthRedirectUriFromRequest(forwarded),\n jwks_uri: buildHubSpotAppJwksUrlFromRequest(forwarded),\n scope: cimdClientMetadata.scope,\n };\n\n return c.text(JSON.stringify(body, null, 2), 200, {\n 'Content-Type': 'application/json; charset=utf-8',\n });\n}\n\nexport async function handleCimdAppJwks(\n c: Context,\n options: HubSpotConnectOAuthRouteOptions\n): Promise<Response> {\n const { appKeys, hubspotConnectEnv } = options;\n if (!hubspotConnectEnv.isCimdEnabled) {\n return c.text('Not found', 404);\n }\n if (!appKeys) {\n return c.text('Missing app keys', 503);\n }\n\n const kid = await getJwkThumbprint({\n publicKeyJwk: appKeys.appPublicKeyJwk,\n });\n\n const jwk = {\n ...appKeys.appPublicKeyJwk,\n kid,\n use: 'sig',\n alg: 'ES256',\n key_ops: ['verify'],\n ext: true,\n } as JsonWebKey;\n\n const jwks: JwkSet = { keys: [jwk] };\n return c.json(jwks);\n}\n"],"mappings":";;;AAYA,eAAsB,qBACpB,GACA,SACmB;CACnB,MAAM,EAAE,oBAAoB,aAAa;CACzC,IAAI,CAAC,oBACH,OAAO,EAAE,KAAK,0CAA0C,GAAG;CAG7D,MAAM,kBAAkB,EAAE,IAAI,OAAO,mBAAmB,KAAK,KAAA;CAC7D,MAAM,iBAAiB,EAAE,IAAI,OAAO,kBAAkB,KAAK,KAAA;CAC3D,MAAM,oBAAoB,EAAE,IAAI,OAAO,MAAM,KAAK,KAAA;CAClD,MAAM,YAAY,EAAE,IAAI,MAAM,YAAY;CAC1C,IAAI,CAAC,WACH,OAAO,EAAE,KAAK,sBAAsB,GAAG;CAEzC,MAAM,YAAqD;EACzD,YAAY,EAAE,IAAI;EAClB;EACA;EACA;EACA;EACA;CACF;CAEA,MAAM,OAAyC;EAC7C,cAAc,iCAAiC,SAAS;EACxD,UAAU,kCAAkC,SAAS;EACrD,OAAO,mBAAmB;CAC5B;CAEA,OAAO,EAAE,KAAK,KAAK,UAAU,MAAM,MAAM,CAAC,GAAG,KAAK,EAChD,gBAAgB,kCAClB,CAAC;AACH;AAEA,eAAsB,kBACpB,GACA,SACmB;CACnB,MAAM,EAAE,SAAS,sBAAsB;CACvC,IAAI,CAAC,kBAAkB,eACrB,OAAO,EAAE,KAAK,aAAa,GAAG;CAEhC,IAAI,CAAC,SACH,OAAO,EAAE,KAAK,oBAAoB,GAAG;CAGvC,MAAM,MAAM,MAAM,iBAAiB,EACjC,cAAc,QAAQ,gBACxB,CAAC;CAWD,MAAM,OAAe,EAAE,MAAM,CAAC;EAR5B,GAAG,QAAQ;EACX;EACA,KAAK;EACL,KAAK;EACL,SAAS,CAAC,QAAQ;EAClB,KAAK;CAGyB,CAAC,EAAE;CACnC,OAAO,EAAE,KAAK,IAAI;AACpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-hubspot-client-metadata.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/fetch-hubspot-client-metadata.ts"],"sourcesContent":["import type { HubSpotConnectCimdClientMetadata } from './cimd-client-metadata-types.ts';\n\nexport interface DeriveHubSpotAuthorizeScopesFromClientMetadataSuccess {\n ok: true;\n scope: string;\n optionalScope?: string;\n}\n\nexport interface DeriveHubSpotAuthorizeScopesFromClientMetadataFailure {\n ok: false;\n status: number;\n message: string;\n}\n\nexport type DeriveHubSpotAuthorizeScopesFromClientMetadataResult =\n | DeriveHubSpotAuthorizeScopesFromClientMetadataSuccess\n | DeriveHubSpotAuthorizeScopesFromClientMetadataFailure;\n\n/**\n * Builds `scope` and `optional_scope` query values for HubSpot\n * `/oauth/authorize` from in-memory client metadata (same shape as\n * `HubSpotConnectCimdClientMetadata` / `startHubSpotConnectFunction({ client })`).\n */\nexport function deriveHubSpotAuthorizeScopesFromClientMetadata(\n metadata: HubSpotConnectCimdClientMetadata\n): DeriveHubSpotAuthorizeScopesFromClientMetadataResult {\n const required = metadata.scope?.required;\n const requiredOk =\n Array.isArray(required) &&\n required.length > 0 &&\n required.every((s) => typeof s === 'string' && s.length > 0);\n\n if (!requiredOk) {\n return {\n ok: false,\n status: 500,\n message: 'Invalid or empty scope.required in client metadata',\n };\n }\n\n const scope = required.join(' ');\n\n const optionalRaw = metadata.scope.optional;\n if (optionalRaw == null) {\n return { ok: true, scope };\n }\n\n if (!Array.isArray(optionalRaw)) {\n return {\n ok: false,\n status: 500,\n message: 'Invalid scope.optional in client metadata',\n };\n }\n\n if (optionalRaw.length === 0) {\n return { ok: true, scope };\n }\n\n if (!optionalRaw.every((s) => typeof s === 'string' && s.length > 0)) {\n return {\n ok: false,\n status: 500,\n message: 'Invalid scope.optional in client metadata',\n };\n }\n\n return {\n ok: true,\n scope,\n optionalScope: optionalRaw.join(' '),\n };\n}\n"],"mappings":";;;;;;AAuBA,SAAgB,+CACd,UACsD;CACtD,MAAM,WAAW,SAAS,OAAO;CAMjC,IAAI,EAJF,MAAM,QAAQ,SAAS,IACvB,SAAS,SAAS,KAClB,SAAS,OAAO,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,EAAE,GAG5D,OAAO;EACL,IAAI;EACJ,QAAQ;EACR,SAAS;EACV;CAGH,MAAM,QAAQ,SAAS,KAAK,IAAI;CAEhC,MAAM,cAAc,SAAS,MAAM;CACnC,IAAI,eAAe,MACjB,OAAO;EAAE,IAAI;EAAM;EAAO;CAG5B,IAAI,CAAC,MAAM,QAAQ,YAAY,EAC7B,OAAO;EACL,IAAI;EACJ,QAAQ;EACR,SAAS;EACV;CAGH,IAAI,YAAY,WAAW,GACzB,OAAO;EAAE,IAAI;EAAM;EAAO;CAG5B,IAAI,CAAC,YAAY,OAAO,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,EAAE,EAClE,OAAO;EACL,IAAI;EACJ,QAAQ;EACR,SAAS;EACV;CAGH,OAAO;EACL,IAAI;EACJ;EACA,eAAe,YAAY,KAAK,IAAI;EACrC"}
1
+ {"version":3,"file":"fetch-hubspot-client-metadata.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/fetch-hubspot-client-metadata.ts"],"sourcesContent":["import type { HubSpotConnectCimdClientMetadata } from './cimd-client-metadata-types.ts';\n\nexport interface DeriveHubSpotAuthorizeScopesFromClientMetadataSuccess {\n ok: true;\n scope: string;\n optionalScope?: string;\n}\n\nexport interface DeriveHubSpotAuthorizeScopesFromClientMetadataFailure {\n ok: false;\n status: number;\n message: string;\n}\n\nexport type DeriveHubSpotAuthorizeScopesFromClientMetadataResult =\n | DeriveHubSpotAuthorizeScopesFromClientMetadataSuccess\n | DeriveHubSpotAuthorizeScopesFromClientMetadataFailure;\n\n/**\n * Builds `scope` and `optional_scope` query values for HubSpot\n * `/oauth/authorize` from in-memory client metadata (same shape as\n * `HubSpotConnectCimdClientMetadata` / `startHubSpotConnectFunction({ client })`).\n */\nexport function deriveHubSpotAuthorizeScopesFromClientMetadata(\n metadata: HubSpotConnectCimdClientMetadata\n): DeriveHubSpotAuthorizeScopesFromClientMetadataResult {\n const required = metadata.scope?.required;\n const requiredOk =\n Array.isArray(required) &&\n required.length > 0 &&\n required.every((s) => typeof s === 'string' && s.length > 0);\n\n if (!requiredOk) {\n return {\n ok: false,\n status: 500,\n message: 'Invalid or empty scope.required in client metadata',\n };\n }\n\n const scope = required.join(' ');\n\n const optionalRaw = metadata.scope.optional;\n if (optionalRaw == null) {\n return { ok: true, scope };\n }\n\n if (!Array.isArray(optionalRaw)) {\n return {\n ok: false,\n status: 500,\n message: 'Invalid scope.optional in client metadata',\n };\n }\n\n if (optionalRaw.length === 0) {\n return { ok: true, scope };\n }\n\n if (!optionalRaw.every((s) => typeof s === 'string' && s.length > 0)) {\n return {\n ok: false,\n status: 500,\n message: 'Invalid scope.optional in client metadata',\n };\n }\n\n return {\n ok: true,\n scope,\n optionalScope: optionalRaw.join(' '),\n };\n}\n"],"mappings":";;;;;;AAuBA,SAAgB,+CACd,UACsD;CACtD,MAAM,WAAW,SAAS,OAAO;CAMjC,IAAI,EAJF,MAAM,QAAQ,QAAQ,KACtB,SAAS,SAAS,KAClB,SAAS,OAAO,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,CAAC,IAG3D,OAAO;EACL,IAAI;EACJ,QAAQ;EACR,SAAS;CACX;CAGF,MAAM,QAAQ,SAAS,KAAK,GAAG;CAE/B,MAAM,cAAc,SAAS,MAAM;CACnC,IAAI,eAAe,MACjB,OAAO;EAAE,IAAI;EAAM;CAAM;CAG3B,IAAI,CAAC,MAAM,QAAQ,WAAW,GAC5B,OAAO;EACL,IAAI;EACJ,QAAQ;EACR,SAAS;CACX;CAGF,IAAI,YAAY,WAAW,GACzB,OAAO;EAAE,IAAI;EAAM;CAAM;CAG3B,IAAI,CAAC,YAAY,OAAO,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,CAAC,GACjE,OAAO;EACL,IAAI;EACJ,QAAQ;EACR,SAAS;CACX;CAGF,OAAO;EACL,IAAI;EACJ;EACA,eAAe,YAAY,KAAK,GAAG;CACrC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"hubspot-connect-routes.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/hubspot-connect-routes.ts"],"sourcesContent":["import type { Hono } from 'hono';\n\nimport { noopLogger, type Logger } from '../../../shared/logger.ts';\nimport type { AppKeys } from '../../types.ts';\nimport { corsMiddleware } from '../utils/cors-middleware.ts';\nimport { handleAuthComplete } from './auth-complete.ts';\nimport { handleAuthInitSession } from './auth-init-session.ts';\nimport { handleAuthLogout } from './auth-logout.ts';\nimport { handleAuthRefresh } from './auth-refresh.ts';\nimport { assertHubSpotConnectCimdClientMetadata } from './cimd-client-metadata-types.ts';\nimport type { HubSpotConnectCimdClientMetadata } from './cimd-client-metadata-types.ts';\nimport {\n handleCimdAppJwks,\n handleCimdClientJson,\n} from './cimd-public-routes.ts';\nimport type { HubSpotConnectRoutesEnv } from './load-hubspot-connect-routes-env.ts';\n\n/**\n * Options accepted by {@link registerHubSpotConnectRoutes}.\n */\nexport interface RegisterHubSpotConnectRoutesOptions {\n /** The Hono app to mount the OAuth routes on. */\n app: Hono;\n /**\n * Imported app keys from `secureStart`, or `null` when CIMD and DPoP\n * are both disabled.\n */\n appKeys: AppKeys | null;\n /**\n * Path the routes are mounted under (no trailing slash). Used to\n * scope refresh-token cookies via `Path=${basePath}/auth`.\n */\n basePath: string;\n /**\n * OAuth and client-mode settings, typically from\n * {@link loadHubSpotConnectRoutesEnv}.\n */\n hubspotConnectEnv: HubSpotConnectRoutesEnv;\n /**\n * Scope configuration for `GET /client.json` and for authorize URL\n * scopes when CIMD is off. Always required.\n */\n cimdClientMetadata: HubSpotConnectCimdClientMetadata;\n /**\n * Optional logger. When omitted the SDK uses a no-op logger so\n * server-side state never leaks into the host application's\n * console.\n */\n logger?: Logger;\n}\n\n/**\n * Mounts hubspot-connect routes: OAuth (`/auth/...`); `GET /client.json`\n * from `cimdClientMetadata`; `GET /jwks.json` when CIMD is enabled.\n */\nexport function registerHubSpotConnectRoutes(\n options: RegisterHubSpotConnectRoutesOptions\n): void {\n const {\n app,\n appKeys,\n basePath,\n hubspotConnectEnv,\n cimdClientMetadata,\n logger = noopLogger,\n } = options;\n\n if (!cimdClientMetadata) {\n throw new Error(\n 'registerHubSpotConnectRoutes: cimdClientMetadata is required'\n );\n }\n assertHubSpotConnectCimdClientMetadata(cimdClientMetadata);\n\n const refreshCookiePath = `${basePath}/auth`;\n const oauthRouteOptions = {\n appKeys,\n refreshCookiePath,\n logger,\n basePath,\n hubspotConnectEnv,\n cimdClientMetadata,\n };\n\n // Credentialed CORS for the cross-origin Lovable / Supabase shape.\n // Echoes the request `Origin` (or the pinned `__Host-hs_app_origin`\n // cookie value once init-session has run) and short-circuits OPTIONS\n // preflights with a 204 before any route handler runs.\n app.use('*', corsMiddleware());\n\n app.get('/client.json', (c) => handleCimdClientJson(c, oauthRouteOptions));\n if (hubspotConnectEnv.isCimdEnabled) {\n app.get('/jwks.json', (c) => handleCimdAppJwks(c, oauthRouteOptions));\n }\n\n app.get('/auth/init-session', (c) =>\n handleAuthInitSession(c, oauthRouteOptions)\n );\n app.post('/auth/complete', (c) => handleAuthComplete(c, oauthRouteOptions));\n app.post('/auth/refresh', (c) => handleAuthRefresh(c, oauthRouteOptions));\n app.post('/auth/logout', (c) => handleAuthLogout(c, oauthRouteOptions));\n}\n"],"mappings":";;;;;;;;;;;;;AAuDA,SAAgB,6BACd,SACM;CACN,MAAM,EACJ,KACA,SACA,UACA,mBACA,oBACA,SAAS,eACP;CAEJ,IAAI,CAAC,oBACH,MAAM,IAAI,MACR,+DACD;CAEH,uCAAuC,mBAAmB;CAG1D,MAAM,oBAAoB;EACxB;EACA,mBAAA,GAH2B,SAAS;EAIpC;EACA;EACA;EACA;EACD;CAMD,IAAI,IAAI,KAAK,gBAAgB,CAAC;CAE9B,IAAI,IAAI,iBAAiB,MAAM,qBAAqB,GAAG,kBAAkB,CAAC;CAC1E,IAAI,kBAAkB,eACpB,IAAI,IAAI,eAAe,MAAM,kBAAkB,GAAG,kBAAkB,CAAC;CAGvE,IAAI,IAAI,uBAAuB,MAC7B,sBAAsB,GAAG,kBAAkB,CAC5C;CACD,IAAI,KAAK,mBAAmB,MAAM,mBAAmB,GAAG,kBAAkB,CAAC;CAC3E,IAAI,KAAK,kBAAkB,MAAM,kBAAkB,GAAG,kBAAkB,CAAC;CACzE,IAAI,KAAK,iBAAiB,MAAM,iBAAiB,GAAG,kBAAkB,CAAC"}
1
+ {"version":3,"file":"hubspot-connect-routes.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/hubspot-connect-routes.ts"],"sourcesContent":["import type { Hono } from 'hono';\n\nimport { noopLogger, type Logger } from '../../../shared/logger.ts';\nimport type { AppKeys } from '../../types.ts';\nimport { corsMiddleware } from '../utils/cors-middleware.ts';\nimport { handleAuthComplete } from './auth-complete.ts';\nimport { handleAuthInitSession } from './auth-init-session.ts';\nimport { handleAuthLogout } from './auth-logout.ts';\nimport { handleAuthRefresh } from './auth-refresh.ts';\nimport { assertHubSpotConnectCimdClientMetadata } from './cimd-client-metadata-types.ts';\nimport type { HubSpotConnectCimdClientMetadata } from './cimd-client-metadata-types.ts';\nimport {\n handleCimdAppJwks,\n handleCimdClientJson,\n} from './cimd-public-routes.ts';\nimport type { HubSpotConnectRoutesEnv } from './load-hubspot-connect-routes-env.ts';\nimport type { HubSpotConnectOAuthRouteOptions } from './types.ts';\n\n/**\n * Options accepted by {@link registerHubSpotConnectRoutes}.\n */\nexport interface RegisterHubSpotConnectRoutesOptions {\n /** The Hono app to mount the OAuth routes on. */\n app: Hono;\n /**\n * Imported app keys from `secureStart`, or `null` when CIMD and DPoP\n * are both disabled.\n */\n appKeys: AppKeys | null;\n /**\n * Path the routes are mounted under (no trailing slash). Used to\n * scope refresh-token cookies via `Path=${basePath}/auth`.\n */\n basePath: string;\n /**\n * OAuth and client-mode settings, typically from\n * {@link loadHubSpotConnectRoutesEnv}.\n */\n hubspotConnectEnv: HubSpotConnectRoutesEnv;\n /**\n * Scope configuration for `GET /client.json` and for authorize URL\n * scopes when CIMD is off. Always required.\n */\n cimdClientMetadata: HubSpotConnectCimdClientMetadata;\n /**\n * Optional logger. When omitted the SDK uses a no-op logger so\n * server-side state never leaks into the host application's\n * console.\n */\n logger?: Logger;\n}\n\n/**\n * Mounts hubspot-connect routes: OAuth (`/auth/...`); `GET /client.json`\n * from `cimdClientMetadata`; `GET /jwks.json` when CIMD is enabled.\n */\nexport function registerHubSpotConnectRoutes(\n options: RegisterHubSpotConnectRoutesOptions\n): void {\n const {\n app,\n appKeys,\n basePath,\n hubspotConnectEnv,\n cimdClientMetadata,\n logger = noopLogger,\n } = options;\n\n if (!cimdClientMetadata) {\n throw new Error(\n 'registerHubSpotConnectRoutes: cimdClientMetadata is required'\n );\n }\n assertHubSpotConnectCimdClientMetadata(cimdClientMetadata);\n\n const refreshCookiePath = `${basePath}/auth`;\n const oauthRouteOptions: HubSpotConnectOAuthRouteOptions = {\n appKeys,\n refreshCookiePath,\n logger,\n basePath,\n hubspotConnectEnv,\n cimdClientMetadata,\n };\n\n // Credentialed CORS for the cross-origin Lovable / Supabase shape.\n // Echoes the request `Origin` (or the pinned `__Host-hs_app_origin`\n // cookie value once init-session has run) and short-circuits OPTIONS\n // preflights with a 204 before any route handler runs.\n app.use('*', corsMiddleware());\n\n app.get('/client.json', (c) => handleCimdClientJson(c, oauthRouteOptions));\n if (hubspotConnectEnv.isCimdEnabled) {\n app.get('/jwks.json', (c) => handleCimdAppJwks(c, oauthRouteOptions));\n }\n\n app.get('/auth/init-session', (c) =>\n handleAuthInitSession(c, oauthRouteOptions)\n );\n app.post('/auth/complete', (c) => handleAuthComplete(c, oauthRouteOptions));\n app.post('/auth/refresh', (c) => handleAuthRefresh(c, oauthRouteOptions));\n app.post('/auth/logout', (c) => handleAuthLogout(c, oauthRouteOptions));\n}\n"],"mappings":";;;;;;;;;;;;;AAwDA,SAAgB,6BACd,SACM;CACN,MAAM,EACJ,KACA,SACA,UACA,mBACA,oBACA,SAAS,eACP;CAEJ,IAAI,CAAC,oBACH,MAAM,IAAI,MACR,8DACF;CAEF,uCAAuC,kBAAkB;CAGzD,MAAM,oBAAqD;EACzD;EACA,mBAAA,GAH2B,SAAS;EAIpC;EACA;EACA;EACA;CACF;CAMA,IAAI,IAAI,KAAK,eAAe,CAAC;CAE7B,IAAI,IAAI,iBAAiB,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;CACzE,IAAI,kBAAkB,eACpB,IAAI,IAAI,eAAe,MAAM,kBAAkB,GAAG,iBAAiB,CAAC;CAGtE,IAAI,IAAI,uBAAuB,MAC7B,sBAAsB,GAAG,iBAAiB,CAC5C;CACA,IAAI,KAAK,mBAAmB,MAAM,mBAAmB,GAAG,iBAAiB,CAAC;CAC1E,IAAI,KAAK,kBAAkB,MAAM,kBAAkB,GAAG,iBAAiB,CAAC;CACxE,IAAI,KAAK,iBAAiB,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AACxE"}
@@ -1 +1 @@
1
- {"version":3,"file":"load-hubspot-connect-routes-env.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/load-hubspot-connect-routes-env.ts"],"sourcesContent":["import {\n getHubSpotAuthorizationEndpoint,\n getHubSpotOAuthApiOrigin,\n isHubspotCimdEnabled,\n isHubspotDpopEnabled,\n requireHubSpotClientId,\n requireHubSpotClientSecret,\n} from '../../utils/env-utils.ts';\n\n/**\n * HubSpot OAuth and client-mode settings read once for hubspot-connect\n * routes. Built by {@link loadHubSpotConnectRoutesEnv}.\n */\nexport type HubSpotConnectRoutesEnv =\n | HubSpotConnectRoutesEnvCimd\n | HubSpotConnectRoutesEnvClientSecret;\n\nexport interface HubSpotConnectRoutesEnvCimd {\n hubspotAuthorizationEndpoint: string;\n hubspotOAuthApiOrigin: string;\n isCimdEnabled: true;\n isDpopEnabled: boolean;\n isAppPrivateKeyRequired: boolean;\n}\n\nexport interface HubSpotConnectRoutesEnvClientSecret {\n hubspotAuthorizationEndpoint: string;\n hubspotOAuthApiOrigin: string;\n isCimdEnabled: false;\n isDpopEnabled: boolean;\n isAppPrivateKeyRequired: boolean;\n hubspotClientId: string;\n hubspotClientSecret: string;\n}\n\n/**\n * Reads hubspot-connect environment variables from `process.env` or\n * `Deno.env` and returns a typed object for\n * {@link registerHubSpotConnectRoutes}.\n */\nexport function loadHubSpotConnectRoutesEnv(): HubSpotConnectRoutesEnv {\n const hubspotAuthorizationEndpoint = getHubSpotAuthorizationEndpoint();\n const hubspotOAuthApiOrigin = getHubSpotOAuthApiOrigin();\n const isCimdEnabled = isHubspotCimdEnabled();\n const isDpopEnabled = isHubspotDpopEnabled();\n const isAppPrivateKeyRequired = isCimdEnabled || isDpopEnabled;\n\n if (isCimdEnabled) {\n return {\n hubspotAuthorizationEndpoint,\n hubspotOAuthApiOrigin,\n isCimdEnabled: true,\n isDpopEnabled,\n isAppPrivateKeyRequired,\n };\n }\n\n return {\n hubspotAuthorizationEndpoint,\n hubspotOAuthApiOrigin,\n isCimdEnabled: false,\n isDpopEnabled,\n isAppPrivateKeyRequired,\n hubspotClientId: requireHubSpotClientId(),\n hubspotClientSecret: requireHubSpotClientSecret(),\n };\n}\n"],"mappings":";;;;;;;AAwCA,SAAgB,8BAAuD;CACrE,MAAM,+BAA+B,iCAAiC;CACtE,MAAM,wBAAwB,0BAA0B;CACxD,MAAM,gBAAgB,sBAAsB;CAC5C,MAAM,gBAAgB,sBAAsB;CAC5C,MAAM,0BAA0B,iBAAiB;CAEjD,IAAI,eACF,OAAO;EACL;EACA;EACA,eAAe;EACf;EACA;EACD;CAGH,OAAO;EACL;EACA;EACA,eAAe;EACf;EACA;EACA,iBAAiB,wBAAwB;EACzC,qBAAqB,4BAA4B;EAClD"}
1
+ {"version":3,"file":"load-hubspot-connect-routes-env.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/load-hubspot-connect-routes-env.ts"],"sourcesContent":["import {\n getHubSpotAuthorizationEndpoint,\n getHubSpotOAuthApiOrigin,\n isHubspotCimdEnabled,\n isHubspotDpopEnabled,\n requireHubSpotClientId,\n requireHubSpotClientSecret,\n} from '../../utils/env-utils.ts';\n\n/**\n * HubSpot OAuth and client-mode settings read once for hubspot-connect\n * routes. Built by {@link loadHubSpotConnectRoutesEnv}.\n */\nexport type HubSpotConnectRoutesEnv =\n | HubSpotConnectRoutesEnvCimd\n | HubSpotConnectRoutesEnvClientSecret;\n\nexport interface HubSpotConnectRoutesEnvCimd {\n hubspotAuthorizationEndpoint: string;\n hubspotOAuthApiOrigin: string;\n isCimdEnabled: true;\n isDpopEnabled: boolean;\n isAppPrivateKeyRequired: boolean;\n}\n\nexport interface HubSpotConnectRoutesEnvClientSecret {\n hubspotAuthorizationEndpoint: string;\n hubspotOAuthApiOrigin: string;\n isCimdEnabled: false;\n isDpopEnabled: boolean;\n isAppPrivateKeyRequired: boolean;\n hubspotClientId: string;\n hubspotClientSecret: string;\n}\n\n/**\n * Reads hubspot-connect environment variables from `process.env` or\n * `Deno.env` and returns a typed object for\n * {@link registerHubSpotConnectRoutes}.\n */\nexport function loadHubSpotConnectRoutesEnv(): HubSpotConnectRoutesEnv {\n const hubspotAuthorizationEndpoint = getHubSpotAuthorizationEndpoint();\n const hubspotOAuthApiOrigin = getHubSpotOAuthApiOrigin();\n const isCimdEnabled = isHubspotCimdEnabled();\n const isDpopEnabled = isHubspotDpopEnabled();\n const isAppPrivateKeyRequired = isCimdEnabled || isDpopEnabled;\n\n if (isCimdEnabled) {\n return {\n hubspotAuthorizationEndpoint,\n hubspotOAuthApiOrigin,\n isCimdEnabled: true,\n isDpopEnabled,\n isAppPrivateKeyRequired,\n };\n }\n\n return {\n hubspotAuthorizationEndpoint,\n hubspotOAuthApiOrigin,\n isCimdEnabled: false,\n isDpopEnabled,\n isAppPrivateKeyRequired,\n hubspotClientId: requireHubSpotClientId(),\n hubspotClientSecret: requireHubSpotClientSecret(),\n };\n}\n"],"mappings":";;;;;;;AAwCA,SAAgB,8BAAuD;CACrE,MAAM,+BAA+B,gCAAgC;CACrE,MAAM,wBAAwB,yBAAyB;CACvD,MAAM,gBAAgB,qBAAqB;CAC3C,MAAM,gBAAgB,qBAAqB;CAC3C,MAAM,0BAA0B,iBAAiB;CAEjD,IAAI,eACF,OAAO;EACL;EACA;EACA,eAAe;EACf;EACA;CACF;CAGF,OAAO;EACL;EACA;EACA,eAAe;EACf;EACA;EACA,iBAAiB,uBAAuB;EACxC,qBAAqB,2BAA2B;CAClD;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-client.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/oauth-client.ts"],"sourcesContent":["import type { AppKeys } from '../../types.ts';\nimport { signDpopProof } from '../../utils/dpop-utils.ts';\nimport { signJwt } from '../../utils/jwt-utils.ts';\n\n/**\n * Lifetime of the OAuth `client_assertion` JWT in seconds. Short by\n * design — RFC 7521 recommends short-lived assertions, and HubSpot's\n * authorization server rejects assertions older than ~5 minutes.\n */\nconst CLIENT_ASSERTION_TTL_SEC = 60;\n\n/**\n * The `client_assertion_type` value mandated by RFC 7523 §2.2 for\n * JWT-bearer client authentication.\n */\nconst JWT_BEARER_ASSERTION_TYPE =\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';\n\n/**\n * Wire shape of a HubSpot OAuth token-endpoint success response.\n */\nexport interface OAuthTokenResponse {\n /** New DPoP-bound access token (sender-constrained). */\n access_token: string;\n /** New refresh token, opaque to the client. */\n refresh_token: string;\n /** Lifetime of `access_token` in seconds. */\n expires_in: number;\n}\n\nexport interface BuildClientAssertionOptions {\n appKeys: AppKeys;\n /** Client ID URL — used as both `iss` and `sub`. */\n clientId: string;\n /** Token-endpoint URL — used as `aud`. */\n audience: string;\n}\n\n/**\n * Mints a short-lived ES256 JWT used as the `client_assertion`\n * parameter when calling HubSpot's token endpoint, per RFC 7523.\n */\nexport async function buildClientAssertion(\n options: BuildClientAssertionOptions\n): Promise<string> {\n const { appKeys, clientId, audience } = options;\n return signJwt({\n privateKey: appKeys.appPrivateKey,\n payload: {\n iss: clientId,\n sub: clientId,\n aud: audience,\n jti: crypto.randomUUID(),\n },\n ttlSeconds: CLIENT_ASSERTION_TTL_SEC,\n });\n}\n\nexport interface BuildTokenEndpointDpopProofOptions {\n appKeys: AppKeys;\n /** Token-endpoint URL — used as the DPoP `htu` claim. */\n tokenEndpointUrl: string;\n /** Hash of the app session ID — used as the DPoP `sid` claim. */\n sessionIdHash: string;\n}\n\n/**\n * Signs a DPoP proof for a `POST` to HubSpot's token endpoint. RFC 9449\n * binds the resulting access token to the proving public key so that\n * later API calls must come from the same key holder.\n */\nexport async function buildTokenEndpointDpopProof(\n options: BuildTokenEndpointDpopProofOptions\n): Promise<string> {\n const { appKeys, tokenEndpointUrl, sessionIdHash } = options;\n return signDpopProof({\n appKeys,\n claims: {\n htm: 'POST',\n htu: tokenEndpointUrl,\n jti: crypto.randomUUID(),\n iat: Math.floor(Date.now() / 1000),\n sid: sessionIdHash,\n },\n });\n}\n\nexport interface RequestOAuthTokenOptions {\n tokenEndpointUrl: string;\n /** Body parameters; serialized to `application/x-www-form-urlencoded`. */\n formParams: Record<string, string>;\n /**\n * When true, a `DPoP` header is required and `dpopProof` must be set.\n */\n isDpopEnabled: boolean;\n /**\n * DPoP proof for this request; required when `isDpopEnabled` is true.\n */\n dpopProof?: string;\n}\n\nexport interface RequestOAuthTokenSuccess {\n ok: true;\n body: OAuthTokenResponse;\n}\n\nexport interface RequestOAuthTokenFailure {\n ok: false;\n /** HTTP status returned by the upstream endpoint. */\n status: number;\n /** Error body as text — used to compose the SDK's error response. */\n errorText: string;\n}\n\nexport type RequestOAuthTokenResult =\n | RequestOAuthTokenSuccess\n | RequestOAuthTokenFailure;\n\n/**\n * POSTs an `application/x-www-form-urlencoded` body to a HubSpot token\n * endpoint. Attaches a `DPoP` header when `isDpopEnabled` is true and\n * `dpopProof` is provided. Reads the response once — either\n * as JSON on success or as text on failure — so callers never have to\n * consume the body twice.\n */\nexport async function requestOAuthToken(\n options: RequestOAuthTokenOptions\n): Promise<RequestOAuthTokenResult> {\n const { tokenEndpointUrl, formParams, dpopProof, isDpopEnabled } = options;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (isDpopEnabled) {\n if (!dpopProof) {\n throw new Error('DPoP proof is required when DPoP is enabled');\n }\n headers.DPoP = dpopProof;\n }\n const tokenResponse = await fetch(tokenEndpointUrl, {\n method: 'POST',\n headers,\n body: new URLSearchParams(formParams),\n });\n if (!tokenResponse.ok) {\n const errorText = await tokenResponse.text();\n return { ok: false, status: tokenResponse.status, errorText };\n }\n const body = (await tokenResponse.json()) as OAuthTokenResponse;\n return { ok: true, body };\n}\n\n/**\n * Form parameters always present on the OAuth `client_assertion` flow.\n * Spread into the call site's `formParams`.\n */\nexport function buildClientAssertionFormParams(input: {\n clientId: string;\n clientAssertion: string;\n}): Record<string, string> {\n const { clientId, clientAssertion } = input;\n return {\n client_id: clientId,\n client_assertion_type: JWT_BEARER_ASSERTION_TYPE,\n client_assertion: clientAssertion,\n };\n}\n\nexport interface BuildClientSecretFormParamsOptions {\n clientId: string;\n clientSecret: string;\n}\n\nexport function buildClientSecretFormParams(\n options: BuildClientSecretFormParamsOptions\n): Record<string, string> {\n const { clientId, clientSecret } = options;\n return {\n client_id: clientId,\n client_secret: clientSecret,\n };\n}\n"],"mappings":";;;;;;;;AASA,MAAM,2BAA2B;;;;;AAMjC,MAAM,4BACJ;;;;;AA0BF,eAAsB,qBACpB,SACiB;CACjB,MAAM,EAAE,SAAS,UAAU,aAAa;CACxC,OAAO,QAAQ;EACb,YAAY,QAAQ;EACpB,SAAS;GACP,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK,OAAO,YAAY;GACzB;EACD,YAAY;EACb,CAAC;;;;;;;AAgBJ,eAAsB,4BACpB,SACiB;CACjB,MAAM,EAAE,SAAS,kBAAkB,kBAAkB;CACrD,OAAO,cAAc;EACnB;EACA,QAAQ;GACN,KAAK;GACL,KAAK;GACL,KAAK,OAAO,YAAY;GACxB,KAAK,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;GAClC,KAAK;GACN;EACF,CAAC;;;;;;;;;AAyCJ,eAAsB,kBACpB,SACkC;CAClC,MAAM,EAAE,kBAAkB,YAAY,WAAW,kBAAkB;CACnE,MAAM,UAAkC,EACtC,gBAAgB,qCACjB;CACD,IAAI,eAAe;EACjB,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,8CAA8C;EAEhE,QAAQ,OAAO;;CAEjB,MAAM,gBAAgB,MAAM,MAAM,kBAAkB;EAClD,QAAQ;EACR;EACA,MAAM,IAAI,gBAAgB,WAAW;EACtC,CAAC;CACF,IAAI,CAAC,cAAc,IAAI;EACrB,MAAM,YAAY,MAAM,cAAc,MAAM;EAC5C,OAAO;GAAE,IAAI;GAAO,QAAQ,cAAc;GAAQ;GAAW;;CAG/D,OAAO;EAAE,IAAI;EAAM,MAAA,MADC,cAAc,MAAM;EACf;;;;;;AAO3B,SAAgB,+BAA+B,OAGpB;CACzB,MAAM,EAAE,UAAU,oBAAoB;CACtC,OAAO;EACL,WAAW;EACX,uBAAuB;EACvB,kBAAkB;EACnB;;AAQH,SAAgB,4BACd,SACwB;CACxB,MAAM,EAAE,UAAU,iBAAiB;CACnC,OAAO;EACL,WAAW;EACX,eAAe;EAChB"}
1
+ {"version":3,"file":"oauth-client.js","names":[],"sources":["../../../../src/server/hono/hubspot-connect-routes/oauth-client.ts"],"sourcesContent":["import type { AppKeys } from '../../types.ts';\nimport { signDpopProof } from '../../utils/dpop-utils.ts';\nimport { signJwt } from '../../utils/jwt-utils.ts';\n\n/**\n * Lifetime of the OAuth `client_assertion` JWT in seconds. Short by\n * design — RFC 7521 recommends short-lived assertions, and HubSpot's\n * authorization server rejects assertions older than ~5 minutes.\n */\nconst CLIENT_ASSERTION_TTL_SEC = 60;\n\n/**\n * The `client_assertion_type` value mandated by RFC 7523 §2.2 for\n * JWT-bearer client authentication.\n */\nconst JWT_BEARER_ASSERTION_TYPE =\n 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';\n\n/**\n * Wire shape of a HubSpot OAuth token-endpoint success response.\n */\nexport interface OAuthTokenResponse {\n /** New DPoP-bound access token (sender-constrained). */\n access_token: string;\n /** New refresh token, opaque to the client. */\n refresh_token: string;\n /** Lifetime of `access_token` in seconds. */\n expires_in: number;\n}\n\nexport interface BuildClientAssertionOptions {\n appKeys: AppKeys;\n /** Client ID URL — used as both `iss` and `sub`. */\n clientId: string;\n /** Token-endpoint URL — used as `aud`. */\n audience: string;\n}\n\n/**\n * Mints a short-lived ES256 JWT used as the `client_assertion`\n * parameter when calling HubSpot's token endpoint, per RFC 7523.\n */\nexport async function buildClientAssertion(\n options: BuildClientAssertionOptions\n): Promise<string> {\n const { appKeys, clientId, audience } = options;\n return signJwt({\n privateKey: appKeys.appPrivateKey,\n payload: {\n iss: clientId,\n sub: clientId,\n aud: audience,\n jti: crypto.randomUUID(),\n },\n ttlSeconds: CLIENT_ASSERTION_TTL_SEC,\n });\n}\n\nexport interface BuildTokenEndpointDpopProofOptions {\n appKeys: AppKeys;\n /** Token-endpoint URL — used as the DPoP `htu` claim. */\n tokenEndpointUrl: string;\n /** Hash of the app session ID — used as the DPoP `sid` claim. */\n sessionIdHash: string;\n}\n\n/**\n * Signs a DPoP proof for a `POST` to HubSpot's token endpoint. RFC 9449\n * binds the resulting access token to the proving public key so that\n * later API calls must come from the same key holder.\n */\nexport async function buildTokenEndpointDpopProof(\n options: BuildTokenEndpointDpopProofOptions\n): Promise<string> {\n const { appKeys, tokenEndpointUrl, sessionIdHash } = options;\n return signDpopProof({\n appKeys,\n claims: {\n htm: 'POST',\n htu: tokenEndpointUrl,\n jti: crypto.randomUUID(),\n iat: Math.floor(Date.now() / 1000),\n sid: sessionIdHash,\n },\n });\n}\n\nexport interface RequestOAuthTokenOptions {\n tokenEndpointUrl: string;\n /** Body parameters; serialized to `application/x-www-form-urlencoded`. */\n formParams: Record<string, string>;\n /**\n * When true, a `DPoP` header is required and `dpopProof` must be set.\n */\n isDpopEnabled: boolean;\n /**\n * DPoP proof for this request; required when `isDpopEnabled` is true.\n */\n dpopProof?: string;\n}\n\nexport interface RequestOAuthTokenSuccess {\n ok: true;\n body: OAuthTokenResponse;\n}\n\nexport interface RequestOAuthTokenFailure {\n ok: false;\n /** HTTP status returned by the upstream endpoint. */\n status: number;\n /** Error body as text — used to compose the SDK's error response. */\n errorText: string;\n}\n\nexport type RequestOAuthTokenResult =\n | RequestOAuthTokenSuccess\n | RequestOAuthTokenFailure;\n\n/**\n * POSTs an `application/x-www-form-urlencoded` body to a HubSpot token\n * endpoint. Attaches a `DPoP` header when `isDpopEnabled` is true and\n * `dpopProof` is provided. Reads the response once — either\n * as JSON on success or as text on failure — so callers never have to\n * consume the body twice.\n */\nexport async function requestOAuthToken(\n options: RequestOAuthTokenOptions\n): Promise<RequestOAuthTokenResult> {\n const { tokenEndpointUrl, formParams, dpopProof, isDpopEnabled } = options;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (isDpopEnabled) {\n if (!dpopProof) {\n throw new Error('DPoP proof is required when DPoP is enabled');\n }\n headers.DPoP = dpopProof;\n }\n const tokenResponse = await fetch(tokenEndpointUrl, {\n method: 'POST',\n headers,\n body: new URLSearchParams(formParams),\n });\n if (!tokenResponse.ok) {\n const errorText = await tokenResponse.text();\n return { ok: false, status: tokenResponse.status, errorText };\n }\n const body = (await tokenResponse.json()) as OAuthTokenResponse;\n return { ok: true, body };\n}\n\n/**\n * Form parameters always present on the OAuth `client_assertion` flow.\n * Spread into the call site's `formParams`.\n */\nexport function buildClientAssertionFormParams(input: {\n clientId: string;\n clientAssertion: string;\n}): Record<string, string> {\n const { clientId, clientAssertion } = input;\n return {\n client_id: clientId,\n client_assertion_type: JWT_BEARER_ASSERTION_TYPE,\n client_assertion: clientAssertion,\n };\n}\n\nexport interface BuildClientSecretFormParamsOptions {\n clientId: string;\n clientSecret: string;\n}\n\nexport function buildClientSecretFormParams(\n options: BuildClientSecretFormParamsOptions\n): Record<string, string> {\n const { clientId, clientSecret } = options;\n return {\n client_id: clientId,\n client_secret: clientSecret,\n };\n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