@wildo-ai/wildo-cli 1.1.14 → 1.1.16

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 (211) hide show
  1. package/dist/src/commands/context/journey.command.d.ts.map +1 -1
  2. package/dist/src/commands/context/journey.command.js +12 -0
  3. package/dist/src/commands/context/journey.command.js.map +1 -1
  4. package/dist/src/commands/creation/drive.command.d.ts.map +1 -1
  5. package/dist/src/commands/creation/drive.command.js +2 -1
  6. package/dist/src/commands/creation/drive.command.js.map +1 -1
  7. package/dist/src/commands/generate/email-command.utils.d.ts +2 -0
  8. package/dist/src/commands/generate/email-command.utils.d.ts.map +1 -1
  9. package/dist/src/commands/generate/email-command.utils.js +5 -0
  10. package/dist/src/commands/generate/email-command.utils.js.map +1 -1
  11. package/dist/src/commands/init.command.d.ts.map +1 -1
  12. package/dist/src/commands/init.command.js +7 -2
  13. package/dist/src/commands/init.command.js.map +1 -1
  14. package/dist/src/commands/local/deregister.command.d.ts.map +1 -1
  15. package/dist/src/commands/local/deregister.command.js +4 -0
  16. package/dist/src/commands/local/deregister.command.js.map +1 -1
  17. package/dist/src/commands/local/dev.command.d.ts +50 -0
  18. package/dist/src/commands/local/dev.command.d.ts.map +1 -1
  19. package/dist/src/commands/local/dev.command.js +144 -1
  20. package/dist/src/commands/local/dev.command.js.map +1 -1
  21. package/dist/src/commands/local/jobs-command.utils.d.ts +24 -0
  22. package/dist/src/commands/local/jobs-command.utils.d.ts.map +1 -0
  23. package/dist/src/commands/local/jobs-command.utils.js +44 -0
  24. package/dist/src/commands/local/jobs-command.utils.js.map +1 -0
  25. package/dist/src/commands/local/jobs-run.command.d.ts +7 -0
  26. package/dist/src/commands/local/jobs-run.command.d.ts.map +1 -0
  27. package/dist/src/commands/local/jobs-run.command.js +92 -0
  28. package/dist/src/commands/local/jobs-run.command.js.map +1 -0
  29. package/dist/src/commands/local/jobs.command.d.ts +7 -0
  30. package/dist/src/commands/local/jobs.command.d.ts.map +1 -0
  31. package/dist/src/commands/local/jobs.command.js +59 -0
  32. package/dist/src/commands/local/jobs.command.js.map +1 -0
  33. package/dist/src/commands/local/tunnel.command.d.ts +84 -0
  34. package/dist/src/commands/local/tunnel.command.d.ts.map +1 -0
  35. package/dist/src/commands/local/tunnel.command.js +274 -0
  36. package/dist/src/commands/local/tunnel.command.js.map +1 -0
  37. package/dist/src/commands/providers/grant-export.command.d.ts +16 -0
  38. package/dist/src/commands/providers/grant-export.command.d.ts.map +1 -0
  39. package/dist/src/commands/providers/grant-export.command.js +78 -0
  40. package/dist/src/commands/providers/grant-export.command.js.map +1 -0
  41. package/dist/src/commands/providers/grant-import.command.d.ts +15 -0
  42. package/dist/src/commands/providers/grant-import.command.d.ts.map +1 -0
  43. package/dist/src/commands/providers/grant-import.command.js +78 -0
  44. package/dist/src/commands/providers/grant-import.command.js.map +1 -0
  45. package/dist/src/kernel/command-runner.d.ts.map +1 -1
  46. package/dist/src/kernel/command-runner.js +4 -6
  47. package/dist/src/kernel/command-runner.js.map +1 -1
  48. package/dist/src/kernel/hooks.d.ts.map +1 -1
  49. package/dist/src/kernel/hooks.js +2 -1
  50. package/dist/src/kernel/hooks.js.map +1 -1
  51. package/dist/src/kernel/json-document-output.d.ts +7 -0
  52. package/dist/src/kernel/json-document-output.d.ts.map +1 -1
  53. package/dist/src/kernel/json-document-output.js +8 -0
  54. package/dist/src/kernel/json-document-output.js.map +1 -1
  55. package/dist/src/kernel/types.d.ts +8 -0
  56. package/dist/src/kernel/types.d.ts.map +1 -1
  57. package/dist/src/kernel/types.js.map +1 -1
  58. package/dist/src/services/application/app-bootstrap.service.d.ts +65 -7
  59. package/dist/src/services/application/app-bootstrap.service.d.ts.map +1 -1
  60. package/dist/src/services/application/app-bootstrap.service.js +94 -15
  61. package/dist/src/services/application/app-bootstrap.service.js.map +1 -1
  62. package/dist/src/services/application/app-local-runtime-addresses.service.d.ts +1 -1
  63. package/dist/src/services/application/app-local-runtime-addresses.service.d.ts.map +1 -1
  64. package/dist/src/services/application/app-local-runtime-addresses.service.js.map +1 -1
  65. package/dist/src/services/application/app-runtime-targets.service.d.ts.map +1 -1
  66. package/dist/src/services/application/app-runtime-targets.service.js +16 -2
  67. package/dist/src/services/application/app-runtime-targets.service.js.map +1 -1
  68. package/dist/src/services/application/application-dependency-alignment.service.d.ts +20 -0
  69. package/dist/src/services/application/application-dependency-alignment.service.d.ts.map +1 -1
  70. package/dist/src/services/application/application-dependency-alignment.service.js +32 -2
  71. package/dist/src/services/application/application-dependency-alignment.service.js.map +1 -1
  72. package/dist/src/services/application/application-runtime-bootstrap.service.d.ts +13 -0
  73. package/dist/src/services/application/application-runtime-bootstrap.service.d.ts.map +1 -1
  74. package/dist/src/services/application/application-runtime-bootstrap.service.js +32 -0
  75. package/dist/src/services/application/application-runtime-bootstrap.service.js.map +1 -1
  76. package/dist/src/services/application/environment-provider-configurations.service.d.ts +7 -0
  77. package/dist/src/services/application/environment-provider-configurations.service.d.ts.map +1 -1
  78. package/dist/src/services/application/environment-provider-configurations.service.js +1 -1
  79. package/dist/src/services/application/environment-provider-configurations.service.js.map +1 -1
  80. package/dist/src/services/application/local-tunnel.service.d.ts +153 -0
  81. package/dist/src/services/application/local-tunnel.service.d.ts.map +1 -0
  82. package/dist/src/services/application/local-tunnel.service.js +295 -0
  83. package/dist/src/services/application/local-tunnel.service.js.map +1 -0
  84. package/dist/src/services/application/provider-runtime-sync.service.d.ts.map +1 -1
  85. package/dist/src/services/application/provider-runtime-sync.service.js +3 -0
  86. package/dist/src/services/application/provider-runtime-sync.service.js.map +1 -1
  87. package/dist/src/services/application/saas-skeleton.service.d.ts +7 -0
  88. package/dist/src/services/application/saas-skeleton.service.d.ts.map +1 -1
  89. package/dist/src/services/application/saas-skeleton.service.js +2 -0
  90. package/dist/src/services/application/saas-skeleton.service.js.map +1 -1
  91. package/dist/src/services/catalog/service-address-resolver.service.d.ts +7 -1
  92. package/dist/src/services/catalog/service-address-resolver.service.d.ts.map +1 -1
  93. package/dist/src/services/catalog/service-address-resolver.service.js +6 -3
  94. package/dist/src/services/catalog/service-address-resolver.service.js.map +1 -1
  95. package/dist/src/services/companion/companion-client.service.d.ts +17 -0
  96. package/dist/src/services/companion/companion-client.service.d.ts.map +1 -1
  97. package/dist/src/services/companion/companion-client.service.js +21 -0
  98. package/dist/src/services/companion/companion-client.service.js.map +1 -1
  99. package/dist/src/services/companion/creation-drive.service.d.ts +18 -0
  100. package/dist/src/services/companion/creation-drive.service.d.ts.map +1 -1
  101. package/dist/src/services/companion/creation-drive.service.js +70 -1
  102. package/dist/src/services/companion/creation-drive.service.js.map +1 -1
  103. package/dist/src/services/credentials/application-secrets.service.d.ts +6 -0
  104. package/dist/src/services/credentials/application-secrets.service.d.ts.map +1 -1
  105. package/dist/src/services/credentials/application-secrets.service.js +1 -1
  106. package/dist/src/services/credentials/application-secrets.service.js.map +1 -1
  107. package/dist/src/services/credentials/provider-env-vars.utils.d.ts.map +1 -1
  108. package/dist/src/services/credentials/provider-env-vars.utils.js +3 -1
  109. package/dist/src/services/credentials/provider-env-vars.utils.js.map +1 -1
  110. package/dist/src/services/credentials/secrets-writer.service.d.ts +11 -2
  111. package/dist/src/services/credentials/secrets-writer.service.d.ts.map +1 -1
  112. package/dist/src/services/credentials/secrets-writer.service.js +12 -3
  113. package/dist/src/services/credentials/secrets-writer.service.js.map +1 -1
  114. package/dist/src/services/deployment/ci-deploy-generator.service.d.ts.map +1 -1
  115. package/dist/src/services/deployment/ci-deploy-generator.service.js +3 -3
  116. package/dist/src/services/deployment/ci-deploy-generator.service.js.map +1 -1
  117. package/dist/src/services/deployment/docker/docker-compose-generator.service.d.ts +12 -3
  118. package/dist/src/services/deployment/docker/docker-compose-generator.service.d.ts.map +1 -1
  119. package/dist/src/services/deployment/docker/docker-compose-generator.service.js +40 -22
  120. package/dist/src/services/deployment/docker/docker-compose-generator.service.js.map +1 -1
  121. package/dist/src/services/deployment/framework-pod-network-membership.d.ts +6 -0
  122. package/dist/src/services/deployment/framework-pod-network-membership.d.ts.map +1 -1
  123. package/dist/src/services/deployment/framework-pod-network-membership.js +17 -3
  124. package/dist/src/services/deployment/framework-pod-network-membership.js.map +1 -1
  125. package/dist/src/services/deployment/k8s/k8s-manifest-generator.service.d.ts +4 -1
  126. package/dist/src/services/deployment/k8s/k8s-manifest-generator.service.d.ts.map +1 -1
  127. package/dist/src/services/deployment/k8s/k8s-manifest-generator.service.js +17 -7
  128. package/dist/src/services/deployment/k8s/k8s-manifest-generator.service.js.map +1 -1
  129. package/dist/src/services/deployment/k8s/k8s-manifest.schemas.d.ts +7 -0
  130. package/dist/src/services/deployment/k8s/k8s-manifest.schemas.d.ts.map +1 -1
  131. package/dist/src/services/deployment/k8s/k8s-manifest.schemas.js.map +1 -1
  132. package/dist/src/services/deployment/k8s/k8s-secrets-generator.service.d.ts.map +1 -1
  133. package/dist/src/services/deployment/k8s/k8s-secrets-generator.service.js +15 -9
  134. package/dist/src/services/deployment/k8s/k8s-secrets-generator.service.js.map +1 -1
  135. package/dist/src/services/deployment/k8s/kind-pod-host-gateway.d.ts +43 -0
  136. package/dist/src/services/deployment/k8s/kind-pod-host-gateway.d.ts.map +1 -0
  137. package/dist/src/services/deployment/k8s/kind-pod-host-gateway.js +12 -0
  138. package/dist/src/services/deployment/k8s/kind-pod-host-gateway.js.map +1 -0
  139. package/dist/src/services/deployment/k8s/off-cluster-backing-services.d.ts +3 -1
  140. package/dist/src/services/deployment/k8s/off-cluster-backing-services.d.ts.map +1 -1
  141. package/dist/src/services/deployment/k8s/off-cluster-backing-services.js.map +1 -1
  142. package/dist/src/services/deployment/local-dev-late-workspace-members.service.d.ts +163 -0
  143. package/dist/src/services/deployment/local-dev-late-workspace-members.service.d.ts.map +1 -0
  144. package/dist/src/services/deployment/local-dev-late-workspace-members.service.js +356 -0
  145. package/dist/src/services/deployment/local-dev-late-workspace-members.service.js.map +1 -0
  146. package/dist/src/services/environment/authored-infra-config.utils.d.ts +13 -3
  147. package/dist/src/services/environment/authored-infra-config.utils.d.ts.map +1 -1
  148. package/dist/src/services/environment/authored-infra-config.utils.js +24 -4
  149. package/dist/src/services/environment/authored-infra-config.utils.js.map +1 -1
  150. package/dist/src/services/environment/container-host-gateway-listen-host.d.ts +6 -0
  151. package/dist/src/services/environment/container-host-gateway-listen-host.d.ts.map +1 -1
  152. package/dist/src/services/environment/container-host-gateway-listen-host.js +6 -0
  153. package/dist/src/services/environment/container-host-gateway-listen-host.js.map +1 -1
  154. package/dist/src/services/environment/env-configuration-generator.service.d.ts +12 -0
  155. package/dist/src/services/environment/env-configuration-generator.service.d.ts.map +1 -1
  156. package/dist/src/services/environment/env-configuration-generator.service.js +37 -5
  157. package/dist/src/services/environment/env-configuration-generator.service.js.map +1 -1
  158. package/dist/src/services/environment/env-vars-builder.service.d.ts +2 -1
  159. package/dist/src/services/environment/env-vars-builder.service.d.ts.map +1 -1
  160. package/dist/src/services/environment/env-vars-builder.service.js +47 -32
  161. package/dist/src/services/environment/env-vars-builder.service.js.map +1 -1
  162. package/dist/src/services/environment/environment-lifecycle.service.d.ts +7 -4
  163. package/dist/src/services/environment/environment-lifecycle.service.d.ts.map +1 -1
  164. package/dist/src/services/environment/environment-lifecycle.service.js +14 -18
  165. package/dist/src/services/environment/environment-lifecycle.service.js.map +1 -1
  166. package/dist/src/services/environment/environment-setup.service.d.ts.map +1 -1
  167. package/dist/src/services/environment/environment-setup.service.js +17 -6
  168. package/dist/src/services/environment/environment-setup.service.js.map +1 -1
  169. package/dist/src/services/environment/environment.service.d.ts +4 -3
  170. package/dist/src/services/environment/environment.service.d.ts.map +1 -1
  171. package/dist/src/services/environment/environment.service.js +0 -1
  172. package/dist/src/services/environment/environment.service.js.map +1 -1
  173. package/dist/src/services/framework/framework-docker-publish.service.d.ts +55 -15
  174. package/dist/src/services/framework/framework-docker-publish.service.d.ts.map +1 -1
  175. package/dist/src/services/framework/framework-docker-publish.service.js +115 -25
  176. package/dist/src/services/framework/framework-docker-publish.service.js.map +1 -1
  177. package/dist/src/services/framework/package-install.service.d.ts +7 -0
  178. package/dist/src/services/framework/package-install.service.d.ts.map +1 -1
  179. package/dist/src/services/framework/package-install.service.js +8 -1
  180. package/dist/src/services/framework/package-install.service.js.map +1 -1
  181. package/dist/src/services/registry/application-provider-connection.service.d.ts +16 -1
  182. package/dist/src/services/registry/application-provider-connection.service.d.ts.map +1 -1
  183. package/dist/src/services/registry/application-provider-connection.service.js +23 -0
  184. package/dist/src/services/registry/application-provider-connection.service.js.map +1 -1
  185. package/dist/src/services/registry/provider-grant-transfer.service.d.ts +48 -0
  186. package/dist/src/services/registry/provider-grant-transfer.service.d.ts.map +1 -0
  187. package/dist/src/services/registry/provider-grant-transfer.service.js +144 -0
  188. package/dist/src/services/registry/provider-grant-transfer.service.js.map +1 -0
  189. package/dist/src/services/registry/provider-module-scaffold.service.d.ts.map +1 -1
  190. package/dist/src/services/registry/provider-module-scaffold.service.js +10 -3
  191. package/dist/src/services/registry/provider-module-scaffold.service.js.map +1 -1
  192. package/dist/src/services/security/csp-sync.service.d.ts.map +1 -1
  193. package/dist/src/services/security/csp-sync.service.js +21 -2
  194. package/dist/src/services/security/csp-sync.service.js.map +1 -1
  195. package/dist/tsconfig.build.tsbuildinfo +1 -1
  196. package/package.json +19 -19
  197. package/templates/infra/docker-compose/docker-compose.wildo-platform.yml.hbs +16 -7
  198. package/templates/infra/k8s/platform/platform-crontabs-batches-manager/deployment.yaml.hbs +13 -0
  199. package/templates/saas/i18n/email/system/remote-agent-task-updated/labels.en.ts +11 -0
  200. package/templates/saas/i18n/email/system/remote-agent-task-updated/template.tsx +56 -0
  201. package/templates/saas/i18n/engine/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.en.ts +61 -0
  202. package/templates/saas/i18n/engine/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.fr.ts +61 -0
  203. package/templates/saas/scenarios/add-technical-doc/files/technical-doc/docusaurus.config.ts.hbs +5 -4
  204. package/templates/saas/scenarios/add-technical-doc/files/technical-doc/package.json.hbs +1 -1
  205. package/templates/saas/scenarios/add-technical-doc/files/technical-doc/scripts/substitute-api-origin.mjs +97 -32
  206. package/templates/saas/scenarios/add-technical-doc/files/technical-doc/src/plugins/api-reference-pages.ts +7 -6
  207. package/templates/saas/skeleton/.wildo-saas/wildo-dev-companion/scripts/dev-supervised.sh +18 -4
  208. package/templates/saas/skeleton/frontend/nginx-config/default.conf.hbs +1 -1
  209. package/templates/saas/skeleton/frontend/src/generated/csp.generated.json.hbs +4 -4
  210. package/templates/saas/skeleton/infrastructure/local/wildo.infra.local.config.ts.hbs +2 -0
  211. package/wildo-framework.info.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"application-provider-connection.service.js","sourceRoot":"","sources":["../../../../src/services/registry/application-provider-connection.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EACL,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,6BAA6B,EAC7B,wBAAwB,EACxB,6BAA6B,EAC7B,iCAAiC,EACjC,+BAA+B,EAC/B,eAAe,GAEhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,0CAA0C,EAAE,sCAAsC,EAAE,MAAM,sCAAsC,CAAC;AAE1I,OAAO,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,MAAM,oDAAoD,CAAC;AAgDlH;;;GAGG;AACH,MAAM,OAAO,wCAAyC,SAAQ,KAAK;IAGtD;IACA;IACA;IACA;IALX,YACE,OAAe,EACN,MAAc,EACd,SAAkB,EAClB,sBAA+B,EAC/B,IAAa;QAEtB,KAAK,CAAC,OAAO,CAAC,CAAC;QALN,WAAM,GAAN,MAAM,CAAQ;QACd,cAAS,GAAT,SAAS,CAAS;QAClB,2BAAsB,GAAtB,sBAAsB,CAAS;QAC/B,SAAI,GAAJ,IAAI,CAAS;QAGtB,IAAI,CAAC,IAAI,GAAG,0CAA0C,CAAC;IACzD,CAAC;CACF;AAED,gFAAgF;AAChF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WAAW;YAChD,OAAO,yBAAyB,CAAC;IACrC,CAAC;AACH,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,wBAAwB,CAAC,OAAwC;IAC/E,QAAQ,OAAO,EAAE,CAAC;QAChB,KAAK,+BAA+B,CAAC,OAAO;YAC1C,OAAO,+BAA+B,CAAC;QACzC,KAAK,+BAA+B,CAAC,YAAY;YAC/C,OAAO,qHAAqH,CAAC;QAC/H,KAAK,+BAA+B,CAAC,cAAc;YACjD,OAAO,2HAA2H,CAAC;QACrI,KAAK,+BAA+B,CAAC,OAAO;YAC1C,OAAO,4EAA4E,CAAC;QACtF,KAAK,+BAA+B,CAAC,WAAW;YAC9C,OAAO,0EAA0E,CAAC;IACtF,CAAC;AACH,CAAC","sourcesContent":["/**\n * The APPLICATION's own provider connection, driven from the terminal against the RUNNING application (#3579).\n *\n * Not the same thing as `provider-connect.service.ts`. That one runs a vendor consent outside any application and keeps\n * the token in a local probe store, for a module's live proof. This one asks a running application to connect ITS OWN\n * vendor account (#3398): the grant lands in the application's `applicationProviderCredentials` store, sealed and renewed\n * there, and the CLI never sees a token.\n *\n * ## What the terminal does, and what the browser must\n *\n * The CLI signs in as the application's local administrator (the candidates the local-credentials rule names, the same\n * ones `wildo frontend look` uses), or, for a deployed application named with `--api-url`, as the administrator the\n * operator names and whose password they type. It calls `POST /connections/:providerRef/start` with an application target, and opens the\n * authorize URL it answers. The vendor then sends the browser back to the application's callback, which hands `state` and\n * `code` to the frontend, and the FRONTEND completes the attempt (`POST /connections/complete`) with its own bearer token.\n * The completion checks that the finisher is the initiator, so the browser must be signed in to the application as the\n * same administrator. That is deliberate in the engine (`handleComplete`) and is not worked around here.\n *\n * `listApplicationConnections` reads `GET /connections/linked?ownerScope=application` and `disconnect…` calls\n * `DELETE /connections/application/:connectionRef`. Both are refused by the application to anyone but a super-administrator.\n *\n * ## What is never printed\n *\n * No password and no token: the answers carry none, and a refusal is reduced to its status, type, message reference and\n * code, which the application's error envelope already sanitizes.\n */\n\nimport {\n AuthFactorLevel,\n AuthMethod,\n MAIN_API_BASE_PATH,\n MANUAL_CONTROLLER_ROUTES_URLS,\n ManualControllerRouteKey,\n ProviderConnectionRefusalCode,\n ProviderCredentialValidationState,\n ProviderOAuth2RevocationOutcome,\n WildoHeaderKeys,\n type LinkedProviderConnectionView,\n} from '@wildo-ai/saas-models';\nimport { ExternalProvider_Connection_DelegationMode, ExternalProvider_Connection_OwnerScope } from '@wildo-ai/external-connectors-models';\n\nimport { resolveInteractiveFrontend, signInCandidates } from '~wildo-cli/services/frontend/frontend-look.service';\n\n/** Where the running application's API and interactive frontend answer. */\nexport interface ApplicationApiTarget {\n /** The backend's origin (`VITE_API_BASE_URL`), without the `/api/v1` prefix. */\n readonly apiBaseUrl: string;\n /**\n * The frontend service name the callback sends the browser back to (`VITE_FRONTEND_SERVICE_NAME`). Absent only for a\n * remote target given without one, which can list and disconnect but not start a connection.\n */\n readonly frontendServiceName?: string;\n /** Where the person signs in, for the message telling them which browser session finishes the connection. */\n readonly frontendUrl: string;\n}\n\n/** One administrator identity to sign in with. `label` names where it came from; the password is never printed. */\nexport interface ApplicationSignInCandidate {\n readonly label: string;\n readonly email: string;\n readonly password: string;\n}\n\n/**\n * A DEPLOYED application, named by the operator (#3579): its API origin, its interactive frontend's service name, and the\n * administrator the operator signs in as, whose password they typed. The local stack's are read from the application\n * instead.\n */\nexport interface RemoteApplicationTarget {\n readonly apiUrl: string;\n readonly frontendServiceName?: string;\n readonly email: string;\n readonly password: string;\n}\n\n/** One row a disconnect deleted, as the application answers it. Never a token. */\nexport interface ApplicationConnectionDisconnectedRow {\n readonly credentialId: string;\n readonly providerRef: string;\n readonly secretSlug: string;\n readonly vendorRevocation: ProviderOAuth2RevocationOutcome;\n}\n\n/** The answer of `DELETE /connections/application/:connectionRef`. */\nexport interface ApplicationConnectionDisconnectAnswer {\n readonly connectionRef: string;\n readonly disconnected: readonly ApplicationConnectionDisconnectedRow[];\n}\n\n/**\n * The application refused a request: its status and the framework error envelope's stable fields. `message` is written\n * for the operator, from those fields only.\n */\nexport class ApplicationConnectionRequestRefusedError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly errorType?: string,\n readonly customMessageReference?: string,\n readonly code?: string,\n ) {\n super(message);\n this.name = 'ApplicationConnectionRequestRefusedError';\n }\n}\n\n/** Why the CLI could not sign in. The password is never part of the message. */\nexport class ApplicationSignInRefusedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ApplicationSignInRefusedError';\n }\n}\n\nexport type FetchLike = (url: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<Response>;\n\n/**\n * How long one request to the running application may take, its answer's body included (the signal stays armed while\n * the body is read). A person is waiting at the terminal. Sign-in and listing answer in well under a second; a disconnect\n * revokes the grant at each vendor before it answers, which is the slow case, and a minute leaves room for a vendor that\n * is slow without leaving the command hanging on one that never answers.\n */\nconst APPLICATION_CONNECTION_REQUEST_TIMEOUT_MS = 60_000;\n\nconst requestDeadline = (): AbortSignal => AbortSignal.timeout(APPLICATION_CONNECTION_REQUEST_TIMEOUT_MS);\n\n/** What the operator reads for a refusal the application answered: the cause, by the status and the stable code. */\nfunction describeRefusal(act: string, status: number, error: { type?: string; customMessageReference?: string; code?: string }): string {\n const fields = [error.type, error.customMessageReference, error.code].filter((field): field is string => typeof field === 'string' && field.length > 0);\n const detail = fields.length === 0 ? '' : ` (${fields.join(' · ')})`;\n const hint = status === 403\n ? ' The signed-in account is not a super-administrator of the application.'\n : status === 401\n ? ' The sign-in was not accepted.'\n : error.code === ProviderConnectionRefusalCode.CONNECTION_NOT_ADMISSIBLE\n ? ' The provider does not admit the application\\'s own connection (APPLICATION × SERVICE).'\n : error.code === ProviderConnectionRefusalCode.PROVIDER_NOT_CONNECTABLE\n ? ' The provider declares no OAuth2 consent; its application credential is set in the deployment environment.'\n : '';\n return `The application refused to ${act}: HTTP ${status}${detail}.${hint}`;\n}\n\n/**\n * A signed-in session with the running application, for the three application-connection acts. Holds the access token\n * and the refresh cookie in memory only, and signs out at {@link signOut}.\n */\nexport class ApplicationProviderConnectionClient {\n private accessToken: string | undefined;\n private refreshCookie: string | undefined;\n private signedInEmail: string | undefined;\n\n constructor(\n private readonly target: ApplicationApiTarget,\n // outbound-deadline: every call through fetchImpl passes `signal: requestDeadline()` in `init`.\n private readonly fetchImpl: FetchLike = (url, init) => fetch(url, init),\n ) {}\n\n /** Where the person signs in to finish a connection in the browser. */\n get frontendUrl(): string {\n return this.target.frontendUrl;\n }\n\n /** The administrator the session was opened as, after {@link signIn}. */\n get email(): string | undefined {\n return this.signedInEmail;\n }\n\n /**\n * Sign in with the first candidate the application accepts: identify, then the password factor through\n * `POST /auth/authenticate` (the step that mints the token; `/auth/authenticate/password` never does). An account that\n * asks a second factor is refused: the CLI does not answer one.\n */\n async signIn(candidates: readonly ApplicationSignInCandidate[]): Promise<ApplicationSignInCandidate> {\n if (candidates.length === 0) {\n throw new ApplicationSignInRefusedError('No local administrator credential found (the application\\'s infrastructure/local/secrets/secrets.json has no admin).');\n }\n const refusals: string[] = [];\n for (const candidate of candidates) {\n const identified = await this.post(MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.AUTH_IDENTIFY], { email: candidate.email });\n const sessionId = (identified.body as { sessionId?: unknown } | undefined)?.sessionId;\n if (!identified.ok || typeof sessionId !== 'string') {\n refusals.push(`${candidate.label}: identify answered HTTP ${identified.status}`);\n continue;\n }\n const authenticated = await this.post(MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.AUTH_AUTHENTICATE], {\n sessionId,\n email: candidate.email,\n password: candidate.password,\n method: AuthMethod.PASSWORD,\n factorLevel: AuthFactorLevel.FIRST,\n });\n const answer = authenticated.body as { accessToken?: unknown; requiresMFA?: unknown } | undefined;\n if (authenticated.ok && answer?.requiresMFA === true) {\n refusals.push(`${candidate.label}: the account asks a second factor, which the CLI does not answer`);\n continue;\n }\n if (!authenticated.ok || typeof answer?.accessToken !== 'string' || answer.accessToken.length === 0) {\n refusals.push(`${candidate.label}: the password was not accepted (HTTP ${authenticated.status})`);\n continue;\n }\n this.accessToken = answer.accessToken;\n this.refreshCookie = readCookieHeader(authenticated.response);\n this.signedInEmail = candidate.email;\n return candidate;\n }\n throw new ApplicationSignInRefusedError(`Could not sign in to ${this.target.apiBaseUrl} as an administrator: ${refusals.join('; ')}.`);\n }\n\n /**\n * Begin connecting the application's own account at `providerRef`: answers the vendor's authorize URL. The header naming\n * the frontend is what lets the callback send the browser back to the screen that completes the attempt.\n */\n async startConnection(providerRef: string, options: { scopes?: readonly string[]; connectionParameters?: Readonly<Record<string, string>> } = {}): Promise<string> {\n if (this.target.frontendServiceName === undefined) {\n throw new ApplicationSignInRefusedError('Name the application\\'s interactive frontend service (`--frontend-service`): the vendor sends the browser back to it, and it completes the connection.');\n }\n const path = MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.PROVIDER_CONNECTION_START].replace(':providerRef', encodeURIComponent(providerRef));\n const answer = await this.authorized('POST', path, 'start the application\\'s connection', {\n target: { ownerScope: ExternalProvider_Connection_OwnerScope.APPLICATION, delegation: ExternalProvider_Connection_DelegationMode.SERVICE },\n ...(options.scopes === undefined ? {} : { scopes: [...options.scopes] }),\n ...(options.connectionParameters === undefined || Object.keys(options.connectionParameters).length === 0 ? {} : { connectionParameters: { ...options.connectionParameters } }),\n });\n const authorizeUrl = (answer as { authorizeUrl?: unknown }).authorizeUrl;\n if (typeof authorizeUrl !== 'string' || authorizeUrl.length === 0) {\n throw new ApplicationConnectionRequestRefusedError('The application answered no authorize URL.', 200);\n }\n return authorizeUrl;\n }\n\n /** The application's own connections: standing, scopes and the vendor's last refusal, never a token. */\n async listConnections(): Promise<readonly LinkedProviderConnectionView[]> {\n const path = `${MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.PROVIDER_CONNECTION_LIST]}?ownerScope=${ExternalProvider_Connection_OwnerScope.APPLICATION}`;\n const answer = await this.authorized('GET', path, 'list the application\\'s connections');\n return ((answer as { connections?: LinkedProviderConnectionView[] }).connections ?? []);\n }\n\n /** Disconnect the application's own account at one connection: the rows deleted and what each vendor answered. */\n async disconnect(connectionRef: string): Promise<ApplicationConnectionDisconnectAnswer> {\n const path = MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.PROVIDER_CONNECTION_APPLICATION_DISCONNECT].replace(':connectionRef', encodeURIComponent(connectionRef));\n return await this.authorized('DELETE', path, `disconnect '${connectionRef}'`) as ApplicationConnectionDisconnectAnswer;\n }\n\n /** End the session the CLI opened. Best-effort: a sign-out that fails leaves a session that expires on its own. */\n async signOut(): Promise<void> {\n if (this.accessToken === undefined) return;\n try {\n await this.fetchImpl(this.url(MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.AUTH_LOGOUT]), {\n method: 'POST',\n headers: {\n ...this.baseHeaders(),\n [WildoHeaderKeys.AUTHORIZATION]: `Bearer ${this.accessToken}`,\n ...(this.refreshCookie === undefined ? {} : { cookie: this.refreshCookie }),\n },\n body: '{}',\n signal: requestDeadline(),\n });\n } catch {\n // The session expires on its own.\n } finally {\n this.accessToken = undefined;\n this.refreshCookie = undefined;\n }\n }\n\n private async authorized(method: string, path: string, act: string, body?: unknown): Promise<unknown> {\n if (this.accessToken === undefined) throw new ApplicationSignInRefusedError('Sign in before calling the application.');\n const response = await this.fetchImpl(this.url(path), {\n method,\n headers: { ...this.baseHeaders(), [WildoHeaderKeys.AUTHORIZATION]: `Bearer ${this.accessToken}` },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n signal: requestDeadline(),\n });\n const parsed = await readJson(response);\n if (!response.ok) {\n const error = ((parsed as { error?: { type?: string; customMessageReference?: string; code?: string } } | undefined)?.error) ?? {};\n throw new ApplicationConnectionRequestRefusedError(describeRefusal(act, response.status, error), response.status, error.type, error.customMessageReference, error.code);\n }\n return parsed ?? {};\n }\n\n private async post(path: string, body: unknown): Promise<{ ok: boolean; status: number; body: unknown; response: Response }> {\n const response = await this.fetchImpl(this.url(path), { method: 'POST', headers: this.baseHeaders(), body: JSON.stringify(body), signal: requestDeadline() });\n return { ok: response.ok, status: response.status, body: await readJson(response), response };\n }\n\n private baseHeaders(): Record<string, string> {\n return {\n 'content-type': 'application/json',\n // What the application's own frontend sends; the start leg records it so the callback returns the browser there.\n ...(this.target.frontendServiceName === undefined ? {} : { [WildoHeaderKeys.FRONTEND_SERVICE_NAME]: this.target.frontendServiceName }),\n };\n }\n\n private url(path: string): string {\n return `${this.target.apiBaseUrl.replace(/\\/+$/, '')}${MAIN_API_BASE_PATH}${path}`;\n }\n}\n\nasync function readJson(response: Response): Promise<unknown> {\n try {\n const text = await response.text();\n return text.length === 0 ? undefined : JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/** The cookies a sign-in set, as one `Cookie` header, so the sign-out can name the session it ends. */\nfunction readCookieHeader(response: Response): string | undefined {\n const headers = response.headers as Headers & { getSetCookie?: () => string[] };\n const setCookies = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];\n const pairs = setCookies.map((cookie) => cookie.split(';')[0]?.trim()).filter((pair): pair is string => typeof pair === 'string' && pair.includes('='));\n return pairs.length === 0 ? undefined : pairs.join('; ');\n}\n\n/**\n * Where the running application answers, from its interactive frontend's generated `.env` (`VITE_API_BASE_URL`,\n * `VITE_FRONTEND_SERVICE_NAME`) and its runtime address: the same resolution `wildo frontend look` makes. Refused when\n * either value is missing, because the callback could then not send the browser back to the screen that completes.\n */\nexport async function resolveApplicationApiTarget(appRoot: string): Promise<ApplicationApiTarget> {\n const frontend = await resolveInteractiveFrontend(appRoot);\n if (frontend.apiBaseUrl === null || frontend.serviceName === null) {\n throw new ApplicationSignInRefusedError(\n 'The interactive frontend\\'s .env declares no VITE_API_BASE_URL or VITE_FRONTEND_SERVICE_NAME, so the CLI cannot reach the application, '\n + 'and the vendor could not send the browser back to the screen that completes the connection. Run `wildo local init` (or regenerate the frontend env) and try again.',\n );\n }\n return { apiBaseUrl: frontend.apiBaseUrl, frontendServiceName: frontend.serviceName, frontendUrl: frontend.url };\n}\n\n/** The hosts a typed password may reach over plain http: this machine only. */\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);\n\n/**\n * Refuse to send a typed administrator password where it would travel in clear text: an `--api-url` must be https, or\n * http on this machine's loopback. A URL that does not parse is refused too.\n */\nexport function assertPasswordMayTravelTo(apiUrl: string): void {\n let parsed: URL;\n try {\n parsed = new URL(apiUrl);\n } catch {\n throw new ApplicationSignInRefusedError(`--api-url is not a URL: '${apiUrl}'.`);\n }\n if (parsed.protocol === 'https:') return;\n if (parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname)) return;\n throw new ApplicationSignInRefusedError(`--api-url must be https (or http on localhost): the administrator's password would travel to '${parsed.host}' in clear text.`);\n}\n\n/**\n * Open a signed-in session with the running application. Sign it out when done.\n *\n * - `remote`: a deployed application the operator names, signed in as the administrator they typed.\n * - otherwise the local stack, from the application root, signed in as its local administrator.\n */\nexport async function openApplicationConnectionSession(\n options: { readonly appRoot: string | null; readonly frameworkRoot: string | null; readonly remote?: RemoteApplicationTarget },\n fetchImpl?: FetchLike,\n): Promise<ApplicationProviderConnectionClient> {\n if (options.remote !== undefined) {\n assertPasswordMayTravelTo(options.remote.apiUrl);\n const apiBaseUrl = options.remote.apiUrl.replace(/\\/+$/, '').replace(new RegExp(`${MAIN_API_BASE_PATH}$`), '');\n const client = new ApplicationProviderConnectionClient({\n apiBaseUrl,\n ...(options.remote.frontendServiceName === undefined ? {} : { frontendServiceName: options.remote.frontendServiceName }),\n frontendUrl: 'the application\\'s own frontend',\n }, fetchImpl);\n await client.signIn([{ label: 'the administrator given', email: options.remote.email, password: options.remote.password }]);\n return client;\n }\n if (options.appRoot === null) {\n throw new ApplicationSignInRefusedError('No targeted app root detected. Run it from the application root (where wildo.saas.config.ts is), or name a deployed application with --api-url.');\n }\n const client = new ApplicationProviderConnectionClient(await resolveApplicationApiTarget(options.appRoot), fetchImpl);\n await client.signIn(signInCandidates(options.appRoot, options.frameworkRoot).map((candidate) => ({ label: candidate.source, email: candidate.email, password: candidate.password })));\n return client;\n}\n\n/**\n * The connection a ref names: the one keyed on it, else the one that serves it (a member of a declared shared connection\n * is disconnected through its base). `undefined` when the application holds none.\n */\nexport function findApplicationConnection(connections: readonly LinkedProviderConnectionView[], ref: string): LinkedProviderConnectionView | undefined {\n return connections.find((connection) => connection.connectionRef === ref) ?? connections.find((connection) => connection.servesRefs.includes(ref));\n}\n\n/** What a connection's standing means to the operator, from its validation state and whether it is turned on. */\nexport function describeApplicationConnectionStanding(connection: LinkedProviderConnectionView): string {\n if (!connection.enabled) return 'turned off';\n switch (connection.validationState) {\n case ProviderCredentialValidationState.VALID:\n return 'healthy (the vendor accepted it on its last use)';\n case ProviderCredentialValidationState.INVALID:\n return `refused by the vendor: reconnect it${connection.validationError === undefined ? '' : ` (${connection.validationError})`}`;\n case ProviderCredentialValidationState.UNVALIDATED:\n return 'connected, not yet used';\n }\n}\n\n/** What telling the vendor achieved, in words the operator acts on. */\nexport function describeVendorRevocation(outcome: ProviderOAuth2RevocationOutcome): string {\n switch (outcome) {\n case ProviderOAuth2RevocationOutcome.REVOKED:\n return 'the vendor withdrew the grant';\n case ProviderOAuth2RevocationOutcome.NOT_DECLARED:\n return 'the vendor was not told (the provider declares no revocation endpoint): remove the app at the vendor\\'s own console';\n case ProviderOAuth2RevocationOutcome.NOT_CONFIGURED:\n return 'the vendor was not told (the application\\'s client registration for it is unset): remove the app at the vendor\\'s console';\n case ProviderOAuth2RevocationOutcome.REFUSED:\n return 'the vendor refused the revocation: remove the app at the vendor\\'s console';\n case ProviderOAuth2RevocationOutcome.UNREACHABLE:\n return 'the vendor could not be reached: remove the app at the vendor\\'s console';\n }\n}\n"]}
1
+ {"version":3,"file":"application-provider-connection.service.js","sourceRoot":"","sources":["../../../../src/services/registry/application-provider-connection.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;A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AAG,CAAC,CAAC,CAAC;AACrJ,CAAC;AAED,iHAAiH;AACjH,MAAM,UAAU,qCAAqC,CAAC,UAAwC;IAC5F,IAAI,CAAC,UAAU,CAAC,OAAO;QAAE,OAAO,YAAY,CAAC;IAC7C,QAAQ,UAAU,CAAC,eAAe,EAAE,CAAC;QACnC,KAAK,iCAAiC,CAAC,KAAK;YAC1C,OAAO,kDAAkD,CAAC;QAC5D,KAAK,iCAAiC,CAAC,OAAO;YAC5C,OAAO,sCAAsC,UAAU,CAAC,eAAe,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,UAAU,CAAC,eAAe,GAAG,EAAE,CAAC;QACpI,KAAK,iCAAiC,CAAC,WAAW;YAChD,OAAO,yBAAyB,CAAC;IACrC,CAAC;AACH,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,wBAAwB,CAAC,OAAwC;IAC/E,QAAQ,OAAO,EAAE,CAAC;QAChB,KAAK,+BAA+B,CAAC,OAAO;YAC1C,OAAO,+BAA+B,CAAC;QACzC,KAAK,+BAA+B,CAAC,YAAY;YAC/C,OAAO,qHAAqH,CAAC;QAC/H,KAAK,+BAA+B,CAAC,cAAc;YACjD,OAAO,2HAA2H,CAAC;QACrI,KAAK,+BAA+B,CAAC,OAAO;YAC1C,OAAO,4EAA4E,CAAC;QACtF,KAAK,+BAA+B,CAAC,WAAW;YAC9C,OAAO,0EAA0E,CAAC;IACtF,CAAC;AACH,CAAC","sourcesContent":["/**\n * The APPLICATION's own provider connection, driven from the terminal against the RUNNING application (#3579).\n *\n * Not the same thing as `provider-connect.service.ts`. That one runs a vendor consent outside any application and keeps\n * the token in a local probe store, for a module's live proof. This one asks a running application to connect ITS OWN\n * vendor account (#3398): the grant lands in the application's `applicationProviderCredentials` store, sealed and renewed\n * there, and the CLI never sees a token.\n *\n * ## What the terminal does, and what the browser must\n *\n * The CLI signs in as the application's local administrator (the candidates the local-credentials rule names, the same\n * ones `wildo frontend look` uses), or, for a deployed application named with `--api-url`, as the administrator the\n * operator names and whose password they type. It calls `POST /connections/:providerRef/start` with an application target, and opens the\n * authorize URL it answers. The vendor then sends the browser back to the application's callback, which hands `state` and\n * `code` to the frontend, and the FRONTEND completes the attempt (`POST /connections/complete`) with its own bearer token.\n * The completion checks that the finisher is the initiator, so the browser must be signed in to the application as the\n * same administrator. That is deliberate in the engine (`handleComplete`) and is not worked around here.\n *\n * `listApplicationConnections` reads `GET /connections/linked?ownerScope=application` and `disconnect…` calls\n * `DELETE /connections/application/:connectionRef`. Both are refused by the application to anyone but a super-administrator.\n *\n * ## What is never printed\n *\n * No password and no token: the answers carry none, and a refusal is reduced to its status, type, message reference and\n * code, which the application's error envelope already sanitizes.\n */\n\nimport {\n AuthFactorLevel,\n AuthMethod,\n MAIN_API_BASE_PATH,\n MANUAL_CONTROLLER_ROUTES_URLS,\n ManualControllerRouteKey,\n ProviderConnectionRefusalCode,\n ProviderCredentialValidationState,\n ProviderOAuth2RevocationOutcome,\n WildoHeaderKeys,\n type LinkedProviderConnectionView,\n type ProviderGrantImportAnswer,\n type ProviderGrantTransferDocument,\n type ProviderGrantTransferOwner,\n} from '@wildo-ai/saas-models';\nimport { ExternalProvider_Connection_DelegationMode, ExternalProvider_Connection_OwnerScope } from '@wildo-ai/external-connectors-models';\n\nimport { resolveInteractiveFrontend, signInCandidates } from '~wildo-cli/services/frontend/frontend-look.service';\n\n/** Where the running application's API and interactive frontend answer. */\nexport interface ApplicationApiTarget {\n /** The backend's origin (`VITE_API_BASE_URL`), without the `/api/v1` prefix. */\n readonly apiBaseUrl: string;\n /**\n * The frontend service name the callback sends the browser back to (`VITE_FRONTEND_SERVICE_NAME`). Absent only for a\n * remote target given without one, which can list and disconnect but not start a connection.\n */\n readonly frontendServiceName?: string;\n /** Where the person signs in, for the message telling them which browser session finishes the connection. */\n readonly frontendUrl: string;\n}\n\n/** One administrator identity to sign in with. `label` names where it came from; the password is never printed. */\nexport interface ApplicationSignInCandidate {\n readonly label: string;\n readonly email: string;\n readonly password: string;\n}\n\n/**\n * A DEPLOYED application, named by the operator (#3579): its API origin, its interactive frontend's service name, and the\n * administrator the operator signs in as, whose password they typed. The local stack's are read from the application\n * instead.\n */\nexport interface RemoteApplicationTarget {\n readonly apiUrl: string;\n readonly frontendServiceName?: string;\n readonly email: string;\n readonly password: string;\n}\n\n/** One row a disconnect deleted, as the application answers it. Never a token. */\nexport interface ApplicationConnectionDisconnectedRow {\n readonly credentialId: string;\n readonly providerRef: string;\n readonly secretSlug: string;\n readonly vendorRevocation: ProviderOAuth2RevocationOutcome;\n}\n\n/** The answer of `DELETE /connections/application/:connectionRef`. */\nexport interface ApplicationConnectionDisconnectAnswer {\n readonly connectionRef: string;\n readonly disconnected: readonly ApplicationConnectionDisconnectedRow[];\n}\n\n/**\n * The application refused a request: its status and the framework error envelope's stable fields. `message` is written\n * for the operator, from those fields only.\n */\nexport class ApplicationConnectionRequestRefusedError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly errorType?: string,\n readonly customMessageReference?: string,\n readonly code?: string,\n ) {\n super(message);\n this.name = 'ApplicationConnectionRequestRefusedError';\n }\n}\n\n/** Why the CLI could not sign in. The password is never part of the message. */\nexport class ApplicationSignInRefusedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ApplicationSignInRefusedError';\n }\n}\n\nexport type FetchLike = (url: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<Response>;\n\n/**\n * How long one request to the running application may take, its answer's body included (the signal stays armed while\n * the body is read). A person is waiting at the terminal. Sign-in and listing answer in well under a second; a disconnect\n * revokes the grant at each vendor before it answers, which is the slow case, and a minute leaves room for a vendor that\n * is slow without leaving the command hanging on one that never answers.\n */\nconst APPLICATION_CONNECTION_REQUEST_TIMEOUT_MS = 60_000;\n\nconst requestDeadline = (): AbortSignal => AbortSignal.timeout(APPLICATION_CONNECTION_REQUEST_TIMEOUT_MS);\n\n/** What the operator reads for a refusal the application answered: the cause, by the status and the stable code. */\nfunction describeRefusal(act: string, status: number, error: { type?: string; customMessageReference?: string; code?: string }): string {\n const fields = [error.type, error.customMessageReference, error.code].filter((field): field is string => typeof field === 'string' && field.length > 0);\n const detail = fields.length === 0 ? '' : ` (${fields.join(' · ')})`;\n const hint = status === 403\n ? ' The signed-in account is not a super-administrator of the application.'\n : status === 401\n ? ' The sign-in was not accepted.'\n : error.code === ProviderConnectionRefusalCode.CONNECTION_NOT_ADMISSIBLE\n ? ' The provider does not admit the application\\'s own connection (APPLICATION × SERVICE).'\n : error.code === ProviderConnectionRefusalCode.PROVIDER_NOT_CONNECTABLE\n ? ' The provider declares no OAuth2 consent; its application credential is set in the deployment environment.'\n : '';\n return `The application refused to ${act}: HTTP ${status}${detail}.${hint}`;\n}\n\n/**\n * A signed-in session with the running application, for the three application-connection acts. Holds the access token\n * and the refresh cookie in memory only, and signs out at {@link signOut}.\n */\nexport class ApplicationProviderConnectionClient {\n private accessToken: string | undefined;\n private refreshCookie: string | undefined;\n private signedInEmail: string | undefined;\n\n constructor(\n private readonly target: ApplicationApiTarget,\n // outbound-deadline: every call through fetchImpl passes `signal: requestDeadline()` in `init`.\n private readonly fetchImpl: FetchLike = (url, init) => fetch(url, init),\n ) {}\n\n /** Where the person signs in to finish a connection in the browser. */\n get frontendUrl(): string {\n return this.target.frontendUrl;\n }\n\n /** The administrator the session was opened as, after {@link signIn}. */\n get email(): string | undefined {\n return this.signedInEmail;\n }\n\n /**\n * Sign in with the first candidate the application accepts: identify, then the password factor through\n * `POST /auth/authenticate` (the step that mints the token; `/auth/authenticate/password` never does). An account that\n * asks a second factor is refused: the CLI does not answer one.\n */\n async signIn(candidates: readonly ApplicationSignInCandidate[]): Promise<ApplicationSignInCandidate> {\n if (candidates.length === 0) {\n throw new ApplicationSignInRefusedError('No local administrator credential found (the application\\'s infrastructure/local/secrets/secrets.json has no admin).');\n }\n const refusals: string[] = [];\n for (const candidate of candidates) {\n const identified = await this.post(MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.AUTH_IDENTIFY], { email: candidate.email });\n const sessionId = (identified.body as { sessionId?: unknown } | undefined)?.sessionId;\n if (!identified.ok || typeof sessionId !== 'string') {\n refusals.push(`${candidate.label}: identify answered HTTP ${identified.status}`);\n continue;\n }\n const authenticated = await this.post(MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.AUTH_AUTHENTICATE], {\n sessionId,\n email: candidate.email,\n password: candidate.password,\n method: AuthMethod.PASSWORD,\n factorLevel: AuthFactorLevel.FIRST,\n });\n const answer = authenticated.body as { accessToken?: unknown; requiresMFA?: unknown } | undefined;\n if (authenticated.ok && answer?.requiresMFA === true) {\n refusals.push(`${candidate.label}: the account asks a second factor, which the CLI does not answer`);\n continue;\n }\n if (!authenticated.ok || typeof answer?.accessToken !== 'string' || answer.accessToken.length === 0) {\n refusals.push(`${candidate.label}: the password was not accepted (HTTP ${authenticated.status})`);\n continue;\n }\n this.accessToken = answer.accessToken;\n this.refreshCookie = readCookieHeader(authenticated.response);\n this.signedInEmail = candidate.email;\n return candidate;\n }\n throw new ApplicationSignInRefusedError(`Could not sign in to ${this.target.apiBaseUrl} as an administrator: ${refusals.join('; ')}.`);\n }\n\n /**\n * Begin connecting the application's own account at `providerRef`: answers the vendor's authorize URL. The header naming\n * the frontend is what lets the callback send the browser back to the screen that completes the attempt.\n */\n async startConnection(providerRef: string, options: { scopes?: readonly string[]; connectionParameters?: Readonly<Record<string, string>> } = {}): Promise<string> {\n if (this.target.frontendServiceName === undefined) {\n throw new ApplicationSignInRefusedError('Name the application\\'s interactive frontend service (`--frontend-service`): the vendor sends the browser back to it, and it completes the connection.');\n }\n const path = MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.PROVIDER_CONNECTION_START].replace(':providerRef', encodeURIComponent(providerRef));\n const answer = await this.authorized('POST', path, 'start the application\\'s connection', {\n target: { ownerScope: ExternalProvider_Connection_OwnerScope.APPLICATION, delegation: ExternalProvider_Connection_DelegationMode.SERVICE },\n ...(options.scopes === undefined ? {} : { scopes: [...options.scopes] }),\n ...(options.connectionParameters === undefined || Object.keys(options.connectionParameters).length === 0 ? {} : { connectionParameters: { ...options.connectionParameters } }),\n });\n const authorizeUrl = (answer as { authorizeUrl?: unknown }).authorizeUrl;\n if (typeof authorizeUrl !== 'string' || authorizeUrl.length === 0) {\n throw new ApplicationConnectionRequestRefusedError('The application answered no authorize URL.', 200);\n }\n return authorizeUrl;\n }\n\n /** The application's own connections: standing, scopes and the vendor's last refusal, never a token. */\n async listConnections(): Promise<readonly LinkedProviderConnectionView[]> {\n const path = `${MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.PROVIDER_CONNECTION_LIST]}?ownerScope=${ExternalProvider_Connection_OwnerScope.APPLICATION}`;\n const answer = await this.authorized('GET', path, 'list the application\\'s connections');\n return ((answer as { connections?: LinkedProviderConnectionView[] }).connections ?? []);\n }\n\n /** Disconnect the application's own account at one connection: the rows deleted and what each vendor answered. */\n async disconnect(connectionRef: string): Promise<ApplicationConnectionDisconnectAnswer> {\n const path = MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.PROVIDER_CONNECTION_APPLICATION_DISCONNECT].replace(':connectionRef', encodeURIComponent(connectionRef));\n return await this.authorized('DELETE', path, `disconnect '${connectionRef}'`) as ApplicationConnectionDisconnectAnswer;\n }\n\n /**\n * EXPORT one stored grant in its portable form (grant seeding, development and test only): the document holds tokens,\n * so the caller writes it only where the operator asked. The application records the export.\n */\n async exportGrant(input: { owner: ProviderGrantTransferOwner; connectionRef: string; secretSlug?: string }): Promise<ProviderGrantTransferDocument> {\n const answer = await this.authorized('POST', MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.PROVIDER_CONNECTION_GRANT_EXPORT], 'export the grant', {\n owner: input.owner,\n connectionRef: input.connectionRef,\n ...(input.secretSlug === undefined ? {} : { secretSlug: input.secretSlug }),\n });\n const document = (answer as { document?: ProviderGrantTransferDocument }).document;\n if (document === undefined) throw new ApplicationConnectionRequestRefusedError('The application answered no grant document.', 200);\n return document;\n }\n\n /** IMPORT an exported grant for `owner` (grant seeding): where it was stored. Never a token. */\n async importGrant(input: { owner: ProviderGrantTransferOwner; document: ProviderGrantTransferDocument; replaceExisting?: boolean }): Promise<ProviderGrantImportAnswer> {\n return await this.authorized('POST', MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.PROVIDER_CONNECTION_GRANT_IMPORT], 'import the grant', {\n owner: input.owner,\n document: input.document,\n ...(input.replaceExisting === true ? { replaceExisting: true } : {}),\n }) as ProviderGrantImportAnswer;\n }\n\n /** End the session the CLI opened. Best-effort: a sign-out that fails leaves a session that expires on its own. */\n async signOut(): Promise<void> {\n if (this.accessToken === undefined) return;\n try {\n await this.fetchImpl(this.url(MANUAL_CONTROLLER_ROUTES_URLS[ManualControllerRouteKey.AUTH_LOGOUT]), {\n method: 'POST',\n headers: {\n ...this.baseHeaders(),\n [WildoHeaderKeys.AUTHORIZATION]: `Bearer ${this.accessToken}`,\n ...(this.refreshCookie === undefined ? {} : { cookie: this.refreshCookie }),\n },\n body: '{}',\n signal: requestDeadline(),\n });\n } catch {\n // The session expires on its own.\n } finally {\n this.accessToken = undefined;\n this.refreshCookie = undefined;\n }\n }\n\n private async authorized(method: string, path: string, act: string, body?: unknown): Promise<unknown> {\n if (this.accessToken === undefined) throw new ApplicationSignInRefusedError('Sign in before calling the application.');\n const response = await this.fetchImpl(this.url(path), {\n method,\n headers: { ...this.baseHeaders(), [WildoHeaderKeys.AUTHORIZATION]: `Bearer ${this.accessToken}` },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n signal: requestDeadline(),\n });\n const parsed = await readJson(response);\n if (!response.ok) {\n const error = ((parsed as { error?: { type?: string; customMessageReference?: string; code?: string } } | undefined)?.error) ?? {};\n throw new ApplicationConnectionRequestRefusedError(describeRefusal(act, response.status, error), response.status, error.type, error.customMessageReference, error.code);\n }\n return parsed ?? {};\n }\n\n private async post(path: string, body: unknown): Promise<{ ok: boolean; status: number; body: unknown; response: Response }> {\n const response = await this.fetchImpl(this.url(path), { method: 'POST', headers: this.baseHeaders(), body: JSON.stringify(body), signal: requestDeadline() });\n return { ok: response.ok, status: response.status, body: await readJson(response), response };\n }\n\n private baseHeaders(): Record<string, string> {\n return {\n 'content-type': 'application/json',\n // What the application's own frontend sends; the start leg records it so the callback returns the browser there.\n ...(this.target.frontendServiceName === undefined ? {} : { [WildoHeaderKeys.FRONTEND_SERVICE_NAME]: this.target.frontendServiceName }),\n };\n }\n\n private url(path: string): string {\n return `${this.target.apiBaseUrl.replace(/\\/+$/, '')}${MAIN_API_BASE_PATH}${path}`;\n }\n}\n\nasync function readJson(response: Response): Promise<unknown> {\n try {\n const text = await response.text();\n return text.length === 0 ? undefined : JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/** The cookies a sign-in set, as one `Cookie` header, so the sign-out can name the session it ends. */\nfunction readCookieHeader(response: Response): string | undefined {\n const headers = response.headers as Headers & { getSetCookie?: () => string[] };\n const setCookies = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];\n const pairs = setCookies.map((cookie) => cookie.split(';')[0]?.trim()).filter((pair): pair is string => typeof pair === 'string' && pair.includes('='));\n return pairs.length === 0 ? undefined : pairs.join('; ');\n}\n\n/**\n * Where the running application answers, from its interactive frontend's generated `.env` (`VITE_API_BASE_URL`,\n * `VITE_FRONTEND_SERVICE_NAME`) and its runtime address: the same resolution `wildo frontend look` makes. Refused when\n * either value is missing, because the callback could then not send the browser back to the screen that completes.\n */\nexport async function resolveApplicationApiTarget(appRoot: string): Promise<ApplicationApiTarget> {\n const frontend = await resolveInteractiveFrontend(appRoot);\n if (frontend.apiBaseUrl === null || frontend.serviceName === null) {\n throw new ApplicationSignInRefusedError(\n 'The interactive frontend\\'s .env declares no VITE_API_BASE_URL or VITE_FRONTEND_SERVICE_NAME, so the CLI cannot reach the application, '\n + 'and the vendor could not send the browser back to the screen that completes the connection. Run `wildo local init` (or regenerate the frontend env) and try again.',\n );\n }\n return { apiBaseUrl: frontend.apiBaseUrl, frontendServiceName: frontend.serviceName, frontendUrl: frontend.url };\n}\n\n/** The hosts a typed password may reach over plain http: this machine only. */\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);\n\n/**\n * Refuse to send a typed administrator password where it would travel in clear text: an `--api-url` must be https, or\n * http on this machine's loopback. A URL that does not parse is refused too.\n */\nexport function assertPasswordMayTravelTo(apiUrl: string): void {\n let parsed: URL;\n try {\n parsed = new URL(apiUrl);\n } catch {\n throw new ApplicationSignInRefusedError(`--api-url is not a URL: '${apiUrl}'.`);\n }\n if (parsed.protocol === 'https:') return;\n if (parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname)) return;\n throw new ApplicationSignInRefusedError(`--api-url must be https (or http on localhost): the administrator's password would travel to '${parsed.host}' in clear text.`);\n}\n\n/**\n * Open a signed-in session with the running application. Sign it out when done.\n *\n * - `remote`: a deployed application the operator names, signed in as the administrator they typed.\n * - otherwise the local stack, from the application root, signed in as its local administrator.\n */\nexport async function openApplicationConnectionSession(\n options: { readonly appRoot: string | null; readonly frameworkRoot: string | null; readonly remote?: RemoteApplicationTarget },\n fetchImpl?: FetchLike,\n): Promise<ApplicationProviderConnectionClient> {\n if (options.remote !== undefined) {\n assertPasswordMayTravelTo(options.remote.apiUrl);\n const apiBaseUrl = options.remote.apiUrl.replace(/\\/+$/, '').replace(new RegExp(`${MAIN_API_BASE_PATH}$`), '');\n const client = new ApplicationProviderConnectionClient({\n apiBaseUrl,\n ...(options.remote.frontendServiceName === undefined ? {} : { frontendServiceName: options.remote.frontendServiceName }),\n frontendUrl: 'the application\\'s own frontend',\n }, fetchImpl);\n await client.signIn([{ label: 'the administrator given', email: options.remote.email, password: options.remote.password }]);\n return client;\n }\n if (options.appRoot === null) {\n throw new ApplicationSignInRefusedError('No targeted app root detected. Run it from the application root (where wildo.saas.config.ts is), or name a deployed application with --api-url.');\n }\n const client = new ApplicationProviderConnectionClient(await resolveApplicationApiTarget(options.appRoot), fetchImpl);\n await client.signIn(signInCandidates(options.appRoot, options.frameworkRoot).map((candidate) => ({ label: candidate.source, email: candidate.email, password: candidate.password })));\n return client;\n}\n\n/**\n * The connection a ref names: the one keyed on it, else the one that serves it (a member of a declared shared connection\n * is disconnected through its base). `undefined` when the application holds none.\n */\nexport function findApplicationConnection(connections: readonly LinkedProviderConnectionView[], ref: string): LinkedProviderConnectionView | undefined {\n return connections.find((connection) => connection.connectionRef === ref) ?? connections.find((connection) => connection.servesRefs.includes(ref));\n}\n\n/** What a connection's standing means to the operator, from its validation state and whether it is turned on. */\nexport function describeApplicationConnectionStanding(connection: LinkedProviderConnectionView): string {\n if (!connection.enabled) return 'turned off';\n switch (connection.validationState) {\n case ProviderCredentialValidationState.VALID:\n return 'healthy (the vendor accepted it on its last use)';\n case ProviderCredentialValidationState.INVALID:\n return `refused by the vendor: reconnect it${connection.validationError === undefined ? '' : ` (${connection.validationError})`}`;\n case ProviderCredentialValidationState.UNVALIDATED:\n return 'connected, not yet used';\n }\n}\n\n/** What telling the vendor achieved, in words the operator acts on. */\nexport function describeVendorRevocation(outcome: ProviderOAuth2RevocationOutcome): string {\n switch (outcome) {\n case ProviderOAuth2RevocationOutcome.REVOKED:\n return 'the vendor withdrew the grant';\n case ProviderOAuth2RevocationOutcome.NOT_DECLARED:\n return 'the vendor was not told (the provider declares no revocation endpoint): remove the app at the vendor\\'s own console';\n case ProviderOAuth2RevocationOutcome.NOT_CONFIGURED:\n return 'the vendor was not told (the application\\'s client registration for it is unset): remove the app at the vendor\\'s console';\n case ProviderOAuth2RevocationOutcome.REFUSED:\n return 'the vendor refused the revocation: remove the app at the vendor\\'s console';\n case ProviderOAuth2RevocationOutcome.UNREACHABLE:\n return 'the vendor could not be reached: remove the app at the vendor\\'s console';\n }\n}\n"]}
@@ -0,0 +1,48 @@
1
+ import { ProviderGrantTransferRefusalCode, type ProviderGrantTransferDocument, type ProviderGrantTransferOwner } from '@wildo-ai/saas-models';
2
+ /** What the operator types for `--owner`, by scope: the prefix before the colon. */
3
+ export declare enum GrantTransferOwnerPrefix {
4
+ USER = "user",
5
+ ORGANIZATION = "organization",
6
+ APPLICATION = "application"
7
+ }
8
+ /**
9
+ * Read `--owner`: `user:<email>`, `organization:<id or slug>`, or `application`. Throws, naming the forms, on anything
10
+ * else.
11
+ */
12
+ export declare function parseGrantTransferOwner(text: string): ProviderGrantTransferOwner;
13
+ /** The owner, as a person reads it. */
14
+ export declare function describeGrantTransferOwner(owner: ProviderGrantTransferOwner): string;
15
+ /**
16
+ * Refuse unless the application answers on this machine. A grant transfer is for a framework or application
17
+ * developer's LOCAL stack (and the QA VM's, which is one); a deployed application is never its target.
18
+ */
19
+ export declare function assertLocalGrantTransferTarget(apiBaseUrl: string): void;
20
+ /** Where `export` writes the document: a file (created 0600), or stdout. */
21
+ export interface GrantDocumentDestination {
22
+ /** A path, or `-` / undefined for stdout. */
23
+ readonly out?: string;
24
+ /** stdout is a terminal. */
25
+ readonly stdoutIsTerminal: boolean;
26
+ /** The operator asked for the document on the terminal (`--to-terminal`). */
27
+ readonly toTerminal: boolean;
28
+ }
29
+ /**
30
+ * Write the document where the operator asked. A file is created with mode 0600 BEFORE anything is written (and an
31
+ * existing file is re-moded 0600 before it is truncated), so the tokens are never readable by another user even for an
32
+ * instant. stdout is refused when it is a terminal, unless `toTerminal`: a token on the screen is a token in the
33
+ * scrollback, a screen share and a terminal recording.
34
+ *
35
+ * @returns where it went, for the message.
36
+ */
37
+ export declare function writeGrantTransferDocument(document: ProviderGrantTransferDocument, destination: GrantDocumentDestination, writeStdout?: (text: string) => void): string;
38
+ /** Read a document from a file, or from stdin when `from` is `-`; refuses anything that is not an export of this format. */
39
+ export declare function readGrantTransferDocument(from: string, readStdin?: () => string): ProviderGrantTransferDocument;
40
+ /**
41
+ * What to do next, for each refusal the transfer routes answer WITH a code on the wire: a 400 or a 409. The two 404s
42
+ * (`OWNER_NOT_FOUND`, `GRANT_NOT_FOUND`) carry no code to a client, so they have no entry here; the CLI names them by
43
+ * their status and message reference instead.
44
+ */
45
+ export declare const GRANT_TRANSFER_REFUSAL_HINTS: Readonly<Partial<Record<ProviderGrantTransferRefusalCode, string>>>;
46
+ /** The hint for a refusal's code, when the code is one of the transfer routes'. */
47
+ export declare function grantTransferRefusalHint(code: string | undefined): string | undefined;
48
+ //# sourceMappingURL=provider-grant-transfer.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-grant-transfer.service.d.ts","sourceRoot":"","sources":["../../../../src/services/registry/provider-grant-transfer.service.ts"],"names":[],"mappings":"AAeA,OAAO,EAGL,gCAAgC,EAChC,KAAK,6BAA6B,EAClC,KAAK,0BAA0B,EAChC,MAAM,uBAAuB,CAAC;AAM/B,oFAAoF;AACpF,oBAAY,wBAAwB;IAClC,IAAI,SAAS;IACb,YAAY,iBAAiB;IAC7B,WAAW,gBAAgB;CAC5B;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,0BAA0B,CAiBhF;AAED,uCAAuC;AACvC,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,0BAA0B,GAAG,MAAM,CAMpF;AAED;;;GAGG;AACH,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAavE;AAED,4EAA4E;AAC5E,MAAM,WAAW,wBAAwB;IACvC,6CAA6C;IAC7C,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,4BAA4B;IAC5B,QAAQ,CAAC,gBAAgB,EAAE,OAAO,CAAC;IACnC,6EAA6E;IAC7E,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;CAC9B;AAED;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CACxC,QAAQ,EAAE,6BAA6B,EACvC,WAAW,EAAE,wBAAwB,EACrC,WAAW,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAgD,GAC9E,MAAM,CAuBR;AAED,4HAA4H;AAC5H,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,GAAE,MAAM,MAAsC,GAAG,6BAA6B,CAe9I;AAED;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,gCAAgC,EAAE,MAAM,CAAC,CAAC,CAU5G,CAAC;AAEF,mFAAmF;AACnF,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAIrF"}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Grant seeding from the terminal (2026-11-18): `wildo providers grant export` and `wildo providers grant import`.
3
+ *
4
+ * The running application does the work (`POST /connections/transfers/export|import`): it alone holds the data key a
5
+ * stored grant is sealed under, and it records both acts. This module holds what the terminal owns:
6
+ *
7
+ * - **Which owner.** `user:<email>`, `organization:<id or slug>` or `application`, read into the route's owner shape.
8
+ * - **Which deployment.** Only the LOCAL stack of an application root, whose API answers on this machine's loopback. A
9
+ * deployed application is refused here, whatever its runtime, and the application itself refuses any runtime that is
10
+ * not `development` or `test`: two fences, one on each side.
11
+ * - **Where the document goes.** It holds the grant's tokens. It is written to a file created 0600, or to stdout when
12
+ * stdout is a pipe or a redirect. It is never written to a terminal unless the operator says so.
13
+ */
14
+ import { closeSync, constants as fsConstants, fchmodSync, ftruncateSync, openSync, readFileSync, writeSync } from 'node:fs';
15
+ import { ProviderGrantTransferDocumentSchema, ProviderGrantTransferOwnerSchema, ProviderGrantTransferRefusalCode, } from '@wildo-ai/saas-models';
16
+ import { ExternalProvider_Connection_OwnerScope } from '@wildo-ai/external-connectors-models';
17
+ /** The hosts the CLI accepts as "this machine" for a grant transfer. */
18
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
19
+ /** What the operator types for `--owner`, by scope: the prefix before the colon. */
20
+ export var GrantTransferOwnerPrefix;
21
+ (function (GrantTransferOwnerPrefix) {
22
+ GrantTransferOwnerPrefix["USER"] = "user";
23
+ GrantTransferOwnerPrefix["ORGANIZATION"] = "organization";
24
+ GrantTransferOwnerPrefix["APPLICATION"] = "application";
25
+ })(GrantTransferOwnerPrefix || (GrantTransferOwnerPrefix = {}));
26
+ /**
27
+ * Read `--owner`: `user:<email>`, `organization:<id or slug>`, or `application`. Throws, naming the forms, on anything
28
+ * else.
29
+ */
30
+ export function parseGrantTransferOwner(text) {
31
+ const trimmed = text.trim();
32
+ const separator = trimmed.indexOf(':');
33
+ const prefix = separator === -1 ? trimmed : trimmed.slice(0, separator);
34
+ const value = separator === -1 ? '' : trimmed.slice(separator + 1).trim();
35
+ const candidate = prefix === GrantTransferOwnerPrefix.APPLICATION && value === ''
36
+ ? { ownerScope: ExternalProvider_Connection_OwnerScope.APPLICATION }
37
+ : prefix === GrantTransferOwnerPrefix.USER
38
+ ? { ownerScope: ExternalProvider_Connection_OwnerScope.USER, email: value }
39
+ : prefix === GrantTransferOwnerPrefix.ORGANIZATION
40
+ ? { ownerScope: ExternalProvider_Connection_OwnerScope.ORGANIZATION, organization: value }
41
+ : undefined;
42
+ const parsed = candidate === undefined ? undefined : ProviderGrantTransferOwnerSchema.safeParse(candidate);
43
+ if (parsed === undefined || !parsed.success) {
44
+ throw new Error(`--owner is user:<email>, organization:<id or slug> or application; '${text}' is not.`);
45
+ }
46
+ return parsed.data;
47
+ }
48
+ /** The owner, as a person reads it. */
49
+ export function describeGrantTransferOwner(owner) {
50
+ switch (owner.ownerScope) {
51
+ case ExternalProvider_Connection_OwnerScope.USER: return `the person ${owner.email}`;
52
+ case ExternalProvider_Connection_OwnerScope.ORGANIZATION: return `the organization ${owner.organization}`;
53
+ case ExternalProvider_Connection_OwnerScope.APPLICATION: return 'the application itself';
54
+ }
55
+ }
56
+ /**
57
+ * Refuse unless the application answers on this machine. A grant transfer is for a framework or application
58
+ * developer's LOCAL stack (and the QA VM's, which is one); a deployed application is never its target.
59
+ */
60
+ export function assertLocalGrantTransferTarget(apiBaseUrl) {
61
+ let host;
62
+ try {
63
+ host = new URL(apiBaseUrl).hostname;
64
+ }
65
+ catch {
66
+ throw new Error(`The application's API address '${apiBaseUrl}' is not a URL.`);
67
+ }
68
+ if (!LOOPBACK_HOSTS.has(host)) {
69
+ throw new Error(`A grant moves only between LOCAL development stacks, and this application answers at '${host}', not on this machine. `
70
+ + 'Run the command from the application root of a local stack (`wildo local dev`).');
71
+ }
72
+ }
73
+ /**
74
+ * Write the document where the operator asked. A file is created with mode 0600 BEFORE anything is written (and an
75
+ * existing file is re-moded 0600 before it is truncated), so the tokens are never readable by another user even for an
76
+ * instant. stdout is refused when it is a terminal, unless `toTerminal`: a token on the screen is a token in the
77
+ * scrollback, a screen share and a terminal recording.
78
+ *
79
+ * @returns where it went, for the message.
80
+ */
81
+ export function writeGrantTransferDocument(document, destination, writeStdout = (text) => { process.stdout.write(text); }) {
82
+ const text = `${JSON.stringify(document, null, 2)}\n`;
83
+ if (destination.out !== undefined && destination.out !== '-') {
84
+ // O_NOFOLLOW: a symbolic link at the path is refused, so the tokens are never written through it to somewhere else.
85
+ const fd = openSync(destination.out, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_NOFOLLOW, 0o600);
86
+ try {
87
+ fchmodSync(fd, 0o600);
88
+ // Emptied only once the mode is 0600, then written from the start.
89
+ ftruncateSync(fd, 0);
90
+ writeSync(fd, text, 0, 'utf8');
91
+ }
92
+ finally {
93
+ closeSync(fd);
94
+ }
95
+ return destination.out;
96
+ }
97
+ if (destination.stdoutIsTerminal && !destination.toTerminal) {
98
+ throw new Error('The grant document holds tokens and stdout is a terminal: write it to a file with --out <file> (created 0600), '
99
+ + 'pipe it to the next command, or pass --to-terminal if you really mean to print it.');
100
+ }
101
+ writeStdout(text);
102
+ return 'stdout';
103
+ }
104
+ /** Read a document from a file, or from stdin when `from` is `-`; refuses anything that is not an export of this format. */
105
+ export function readGrantTransferDocument(from, readStdin = () => readFileSync(0, 'utf8')) {
106
+ const text = from === '-' ? readStdin() : readFileSync(from, 'utf8');
107
+ let json;
108
+ try {
109
+ json = JSON.parse(text);
110
+ }
111
+ catch {
112
+ throw new Error(`${from === '-' ? 'stdin' : from} is not JSON: it must be what \`wildo providers grant export\` wrote.`);
113
+ }
114
+ const parsed = ProviderGrantTransferDocumentSchema.safeParse(json);
115
+ if (!parsed.success) {
116
+ // Paths and messages only: an issue's input is never echoed, since it may be a token.
117
+ const where = parsed.error.issues.slice(0, 5).map((issue) => `${issue.path.join('.') || '(document)'}: ${issue.message}`).join('; ');
118
+ throw new Error(`${from === '-' ? 'stdin' : from} is not a grant export of a format this CLI reads (${where}).`);
119
+ }
120
+ return parsed.data;
121
+ }
122
+ /**
123
+ * What to do next, for each refusal the transfer routes answer WITH a code on the wire: a 400 or a 409. The two 404s
124
+ * (`OWNER_NOT_FOUND`, `GRANT_NOT_FOUND`) carry no code to a client, so they have no entry here; the CLI names them by
125
+ * their status and message reference instead.
126
+ */
127
+ export const GRANT_TRANSFER_REFUSAL_HINTS = {
128
+ [ProviderGrantTransferRefusalCode.RUNTIME_NOT_DEVELOPMENT]: 'The application does not run as `development` or `test`, and grants move only between such stacks.',
129
+ [ProviderGrantTransferRefusalCode.SLOT_AMBIGUOUS]: 'The connection holds several slots for that owner: name one with --slot.',
130
+ [ProviderGrantTransferRefusalCode.NOT_AN_OAUTH2_GRANT]: 'The connection holds a pasted credential, not a vendor’s grant: set the value in the other stack directly.',
131
+ [ProviderGrantTransferRefusalCode.OWNER_SCOPE_MISMATCH]: 'Name an owner of the scope the grant was consented for (user, organization or application).',
132
+ [ProviderGrantTransferRefusalCode.SLOT_NOT_STORABLE]: 'The document\u2019s slot is not an account credential slot this application\u2019s provider declares: install the same provider version as the exporting stack.',
133
+ [ProviderGrantTransferRefusalCode.CONNECTION_NOT_SERVED]: 'This application does not serve that connection through an OAuth2 client: install and configure the provider (same OAuth2 client as the exporting stack) first.',
134
+ [ProviderGrantTransferRefusalCode.CONNECTION_NOT_ADMISSIBLE]: 'The provider does not admit a connection owned at that scope.',
135
+ [ProviderGrantTransferRefusalCode.GRANT_ALREADY_HELD]: 'The owner already holds a grant for that connection: pass --replace to replace it.',
136
+ [ProviderGrantTransferRefusalCode.GRANT_RENEWAL_REFUSED]: 'The vendor refused the exported refresh token (revoked, expired, or issued to another OAuth2 client): connect again where it was exported from, then export again.',
137
+ };
138
+ /** The hint for a refusal's code, when the code is one of the transfer routes'. */
139
+ export function grantTransferRefusalHint(code) {
140
+ return code !== undefined && Object.hasOwn(GRANT_TRANSFER_REFUSAL_HINTS, code)
141
+ ? GRANT_TRANSFER_REFUSAL_HINTS[code]
142
+ : undefined;
143
+ }
144
+ //# sourceMappingURL=provider-grant-transfer.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-grant-transfer.service.js","sourceRoot":"","sources":["../../../../src/services/registry/provider-grant-transfer.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,SAAS,EAAE,SAAS,IAAI,WAAW,EAAE,UAAU,EAAE,aAAa,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAE5H,OAAO,EACL,mCAAmC,EACnC,gCAAgC,EAChC,gCAAgC,GAGjC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,sCAAsC,EAAE,MAAM,sCAAsC,CAAC;AAE9F,wEAAwE;AACxE,MAAM,cAAc,GAAwB,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AAEhG,oFAAoF;AACpF,MAAM,CAAN,IAAY,wBAIX;AAJD,WAAY,wBAAwB;IAClC,yCAAa,CAAA;IACb,yDAA6B,CAAA;IAC7B,uDAA2B,CAAA;AAC7B,CAAC,EAJW,wBAAwB,KAAxB,wBAAwB,QAInC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CAAC,IAAY;IAClD,MAAM,OAAO,GAAG,IA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A4B,CAAC,IAAwC,CAAC;QACxE,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Grant seeding from the terminal (2026-11-18): `wildo providers grant export` and `wildo providers grant import`.\n *\n * The running application does the work (`POST /connections/transfers/export|import`): it alone holds the data key a\n * stored grant is sealed under, and it records both acts. This module holds what the terminal owns:\n *\n * - **Which owner.** `user:<email>`, `organization:<id or slug>` or `application`, read into the route's owner shape.\n * - **Which deployment.** Only the LOCAL stack of an application root, whose API answers on this machine's loopback. A\n * deployed application is refused here, whatever its runtime, and the application itself refuses any runtime that is\n * not `development` or `test`: two fences, one on each side.\n * - **Where the document goes.** It holds the grant's tokens. It is written to a file created 0600, or to stdout when\n * stdout is a pipe or a redirect. It is never written to a terminal unless the operator says so.\n */\nimport { closeSync, constants as fsConstants, fchmodSync, ftruncateSync, openSync, readFileSync, writeSync } from 'node:fs';\n\nimport {\n ProviderGrantTransferDocumentSchema,\n ProviderGrantTransferOwnerSchema,\n ProviderGrantTransferRefusalCode,\n type ProviderGrantTransferDocument,\n type ProviderGrantTransferOwner,\n} from '@wildo-ai/saas-models';\nimport { ExternalProvider_Connection_OwnerScope } from '@wildo-ai/external-connectors-models';\n\n/** The hosts the CLI accepts as \"this machine\" for a grant transfer. */\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);\n\n/** What the operator types for `--owner`, by scope: the prefix before the colon. */\nexport enum GrantTransferOwnerPrefix {\n USER = 'user',\n ORGANIZATION = 'organization',\n APPLICATION = 'application',\n}\n\n/**\n * Read `--owner`: `user:<email>`, `organization:<id or slug>`, or `application`. Throws, naming the forms, on anything\n * else.\n */\nexport function parseGrantTransferOwner(text: string): ProviderGrantTransferOwner {\n const trimmed = text.trim();\n const separator = trimmed.indexOf(':');\n const prefix = separator === -1 ? trimmed : trimmed.slice(0, separator);\n const value = separator === -1 ? '' : trimmed.slice(separator + 1).trim();\n const candidate = prefix === GrantTransferOwnerPrefix.APPLICATION && value === ''\n ? { ownerScope: ExternalProvider_Connection_OwnerScope.APPLICATION }\n : prefix === GrantTransferOwnerPrefix.USER\n ? { ownerScope: ExternalProvider_Connection_OwnerScope.USER, email: value }\n : prefix === GrantTransferOwnerPrefix.ORGANIZATION\n ? { ownerScope: ExternalProvider_Connection_OwnerScope.ORGANIZATION, organization: value }\n : undefined;\n const parsed = candidate === undefined ? undefined : ProviderGrantTransferOwnerSchema.safeParse(candidate);\n if (parsed === undefined || !parsed.success) {\n throw new Error(`--owner is user:<email>, organization:<id or slug> or application; '${text}' is not.`);\n }\n return parsed.data;\n}\n\n/** The owner, as a person reads it. */\nexport function describeGrantTransferOwner(owner: ProviderGrantTransferOwner): string {\n switch (owner.ownerScope) {\n case ExternalProvider_Connection_OwnerScope.USER: return `the person ${owner.email}`;\n case ExternalProvider_Connection_OwnerScope.ORGANIZATION: return `the organization ${owner.organization}`;\n case ExternalProvider_Connection_OwnerScope.APPLICATION: return 'the application itself';\n }\n}\n\n/**\n * Refuse unless the application answers on this machine. A grant transfer is for a framework or application\n * developer's LOCAL stack (and the QA VM's, which is one); a deployed application is never its target.\n */\nexport function assertLocalGrantTransferTarget(apiBaseUrl: string): void {\n let host: string;\n try {\n host = new URL(apiBaseUrl).hostname;\n } catch {\n throw new Error(`The application's API address '${apiBaseUrl}' is not a URL.`);\n }\n if (!LOOPBACK_HOSTS.has(host)) {\n throw new Error(\n `A grant moves only between LOCAL development stacks, and this application answers at '${host}', not on this machine. `\n + 'Run the command from the application root of a local stack (`wildo local dev`).',\n );\n }\n}\n\n/** Where `export` writes the document: a file (created 0600), or stdout. */\nexport interface GrantDocumentDestination {\n /** A path, or `-` / undefined for stdout. */\n readonly out?: string;\n /** stdout is a terminal. */\n readonly stdoutIsTerminal: boolean;\n /** The operator asked for the document on the terminal (`--to-terminal`). */\n readonly toTerminal: boolean;\n}\n\n/**\n * Write the document where the operator asked. A file is created with mode 0600 BEFORE anything is written (and an\n * existing file is re-moded 0600 before it is truncated), so the tokens are never readable by another user even for an\n * instant. stdout is refused when it is a terminal, unless `toTerminal`: a token on the screen is a token in the\n * scrollback, a screen share and a terminal recording.\n *\n * @returns where it went, for the message.\n */\nexport function writeGrantTransferDocument(\n document: ProviderGrantTransferDocument,\n destination: GrantDocumentDestination,\n writeStdout: (text: string) => void = (text) => { process.stdout.write(text); },\n): string {\n const text = `${JSON.stringify(document, null, 2)}\\n`;\n if (destination.out !== undefined && destination.out !== '-') {\n // O_NOFOLLOW: a symbolic link at the path is refused, so the tokens are never written through it to somewhere else.\n const fd = openSync(destination.out, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_NOFOLLOW, 0o600);\n try {\n fchmodSync(fd, 0o600);\n // Emptied only once the mode is 0600, then written from the start.\n ftruncateSync(fd, 0);\n writeSync(fd, text, 0, 'utf8');\n } finally {\n closeSync(fd);\n }\n return destination.out;\n }\n if (destination.stdoutIsTerminal && !destination.toTerminal) {\n throw new Error(\n 'The grant document holds tokens and stdout is a terminal: write it to a file with --out <file> (created 0600), '\n + 'pipe it to the next command, or pass --to-terminal if you really mean to print it.',\n );\n }\n writeStdout(text);\n return 'stdout';\n}\n\n/** Read a document from a file, or from stdin when `from` is `-`; refuses anything that is not an export of this format. */\nexport function readGrantTransferDocument(from: string, readStdin: () => string = () => readFileSync(0, 'utf8')): ProviderGrantTransferDocument {\n const text = from === '-' ? readStdin() : readFileSync(from, 'utf8');\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n throw new Error(`${from === '-' ? 'stdin' : from} is not JSON: it must be what \\`wildo providers grant export\\` wrote.`);\n }\n const parsed = ProviderGrantTransferDocumentSchema.safeParse(json);\n if (!parsed.success) {\n // Paths and messages only: an issue's input is never echoed, since it may be a token.\n const where = parsed.error.issues.slice(0, 5).map((issue) => `${issue.path.join('.') || '(document)'}: ${issue.message}`).join('; ');\n throw new Error(`${from === '-' ? 'stdin' : from} is not a grant export of a format this CLI reads (${where}).`);\n }\n return parsed.data;\n}\n\n/**\n * What to do next, for each refusal the transfer routes answer WITH a code on the wire: a 400 or a 409. The two 404s\n * (`OWNER_NOT_FOUND`, `GRANT_NOT_FOUND`) carry no code to a client, so they have no entry here; the CLI names them by\n * their status and message reference instead.\n */\nexport const GRANT_TRANSFER_REFUSAL_HINTS: Readonly<Partial<Record<ProviderGrantTransferRefusalCode, string>>> = {\n [ProviderGrantTransferRefusalCode.RUNTIME_NOT_DEVELOPMENT]: 'The application does not run as `development` or `test`, and grants move only between such stacks.',\n [ProviderGrantTransferRefusalCode.SLOT_AMBIGUOUS]: 'The connection holds several slots for that owner: name one with --slot.',\n [ProviderGrantTransferRefusalCode.NOT_AN_OAUTH2_GRANT]: 'The connection holds a pasted credential, not a vendor’s grant: set the value in the other stack directly.',\n [ProviderGrantTransferRefusalCode.OWNER_SCOPE_MISMATCH]: 'Name an owner of the scope the grant was consented for (user, organization or application).',\n [ProviderGrantTransferRefusalCode.SLOT_NOT_STORABLE]: 'The document\\u2019s slot is not an account credential slot this application\\u2019s provider declares: install the same provider version as the exporting stack.',\n [ProviderGrantTransferRefusalCode.CONNECTION_NOT_SERVED]: 'This application does not serve that connection through an OAuth2 client: install and configure the provider (same OAuth2 client as the exporting stack) first.',\n [ProviderGrantTransferRefusalCode.CONNECTION_NOT_ADMISSIBLE]: 'The provider does not admit a connection owned at that scope.',\n [ProviderGrantTransferRefusalCode.GRANT_ALREADY_HELD]: 'The owner already holds a grant for that connection: pass --replace to replace it.',\n [ProviderGrantTransferRefusalCode.GRANT_RENEWAL_REFUSED]: 'The vendor refused the exported refresh token (revoked, expired, or issued to another OAuth2 client): connect again where it was exported from, then export again.',\n};\n\n/** The hint for a refusal's code, when the code is one of the transfer routes'. */\nexport function grantTransferRefusalHint(code: string | undefined): string | undefined {\n return code !== undefined && Object.hasOwn(GRANT_TRANSFER_REFUSAL_HINTS, code)\n ? GRANT_TRANSFER_REFUSAL_HINTS[code as ProviderGrantTransferRefusalCode]\n : undefined;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"provider-module-scaffold.service.d.ts","sourceRoot":"","sources":["../../../../src/services/registry/provider-module-scaffold.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,OAAO,EAA2C,6BAA6B,EAAE,KAAK,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAGvJ,OAAO,EAQL,KAAK,0BAA0B,EAC/B,KAAK,kBAAkB,EACxB,MAAM,mEAAmE,CAAC;AAE3E;;;GAGG;AACH,eAAO,MAAM,6BAA6B,4BAA4B,CAAC;AAEvE,uDAAuD;AACvD,oBAAY,oBAAoB;IAC9B,mEAAmE;IACnE,OAAO,YAAY;IACnB,+EAA+E;IAC/E,MAAM,WAAW;CAClB;AAED,MAAM,WAAW,qBAAqB;IACpC,sGAAsG;IACtG,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,kDAAkD;IAClD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,sDAAsD;IACtD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,uGAAuG;IACvG,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,+FAA+F;IAC/F,QAAQ,CAAC,YAAY,CAAC,EAAE;QAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,QAAQ,EAAE,0BAA0B,CAAC;QAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,WAAW,GAAG,iBAAiB,CAAC,CAAA;KAAE,CAAC;IACjL,QAAQ,CAAC,IAAI,EAAE,oBAAoB,CAAC;IACpC,2FAA2F;IAC3F,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAA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AQ,CAAC,IAAI,CAAC,EAAE;QAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,OAAO,CAAC;YAAC,GAAG,EAAE,MAAM,CAAC;YAAC,WAAW,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC,CAAA;KAAE,CAAC;CACxJ;AA4CD,uHAAuH;AACvH,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,0BAA0B,CAAC;IAC9C;;;OAGG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;IAChC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,WAAW,GAAG,iBAAiB,CAAC,CAAC;CAC7E;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,kBAAkB,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,EAAE,MAAM,EAAE,UAAU,GAAG,eAAe,EAAE,CA8I5H;AAoVD;;;;GAIG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,0BAA0B,CAAC;IAAC,MAAM,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,WAAW,GAAG,iBAAiB,CAAC,CAAA;CAAE,CAAC,CAWhM;AAED,iHAAiH;AACjH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,qBAAqB,GAAG,qBAAqB,CA8D1F"}
1
+ {"version":3,"file":"provider-module-scaffold.service.d.ts","sourceRoot":"","sources":["../../../../src/services/registry/provider-module-scaffold.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;YAAC,QAAQ,EAAE,OAAO,CAAC;YAAC,GAAG,EAAE,MAAM,CAAC;YAAC,WAAW,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC,CAAA;KAAE,CAAC;CACxJ;AA4CD,uHAAuH;AACvH,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,0BAA0B,CAAC;IAC9C;;;OAGG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;IAChC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,WAAW,GAAG,iBAAiB,CAAC,CAAC;CAC7E;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,kBAAkB,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,EAAE,MAAM,EAAE,UAAU,GAAG,eAAe,EAAE,CA8I5H;AA2VD;;;;GAIG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,0BAA0B,CAAC;IAAC,MAAM,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,WAAW,GAAG,iBAAiB,CAAC,CAAA;CAAE,CAAC,CAWhM;AAED,iHAAiH;AACjH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,qBAAqB,GAAG,qBAAqB,CA8D1F"}
@@ -594,13 +594,20 @@ function renderPackageJson(input) {
594
594
  exports: exportsMap,
595
595
  scripts: { build: 'tsc -p tsconfig.json', dev: 'tsc -p tsconfig.json --watch --preserveWatchOutput' },
596
596
  dependencies: { '@wildo-ai/external-connectors-models': '*', '@wildo-ai/external-connectors-private': '*', '@wildo-ai/saas-models': '*', zod: '*' },
597
- devDependencies: { typescript: '*' },
597
+ // Node's types travel with the facet (#4009): `"*"` resolves to the installing application's own pin.
598
+ devDependencies: { '@types/node': '*', typescript: '*' },
598
599
  }, null, 2)}\n`;
599
600
  }
601
+ /**
602
+ * A backend facet runs on Node, always, so it compiles against Node's types (#4009): `types: ['node']` beside the
603
+ * ES2022 library, and `@types/node` among the facet's own devDependencies ({@link renderPackageJson}). Without them a
604
+ * module using `URL`, `FormData`, `Blob`, `Buffer` or `node:crypto` compiled in no application that installed it
605
+ * (Mailgun and Amazon Bedrock, measured 2026-11-17). `check:provider-modules` holds every registry module to it.
606
+ */
600
607
  const TSCONFIG = `${JSON.stringify({
601
- '//': 'Self-contained on purpose: the same file builds this facet in the framework checkout and in every application it is installed into, so it extends nothing either place may lack.',
608
+ '//': 'Self-contained on purpose: the same file builds this facet in the framework checkout and in every application it is installed into, so it extends nothing either place may lack. Node\'s types are declared because a backend facet always runs on Node (#4009).',
602
609
  compilerOptions: {
603
- target: 'ES2022', lib: ['ES2022'], module: 'preserve', moduleResolution: 'bundler', strict: true, isolatedModules: true, esModuleInterop: true,
610
+ target: 'ES2022', lib: ['ES2022'], types: ['node'], module: 'preserve', moduleResolution: 'bundler', strict: true, isolatedModules: true, esModuleInterop: true,
604
611
  skipLibCheck: true, forceConsistentCasingInFileNames: true, noEmitOnError: true, declaration: true, rootDir: 'src', outDir: 'dist',
605
612
  },
606
613
  include: ['src/**/*'],