@zortexhq/indra-v2.5 0.2.1 → 0.2.3

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 (112) hide show
  1. package/dist/box-level1-setup.js +1 -1
  2. package/dist/calcom-level1-setup.js +1 -1
  3. package/dist/cli-run.js +1 -1
  4. package/dist/connector-worker.js +1 -1
  5. package/dist/discord-level1-setup.js +1 -1
  6. package/dist/dropbox-level1-setup.js +1 -1
  7. package/dist/figma-level1-setup.js +1 -1
  8. package/dist/freshdesk-level1-setup.js +1 -1
  9. package/dist/freshrss-level1-setup.js +1 -1
  10. package/dist/front-level1-setup.js +1 -1
  11. package/dist/gateway.js +1 -1
  12. package/dist/google-chat-level1-setup.js +1 -1
  13. package/dist/google-contacts-level1-setup.js +1 -1
  14. package/dist/hubspot-level1-setup.js +1 -1
  15. package/dist/joplin-selection.js +1 -1
  16. package/dist/local-cloud.js +1 -1
  17. package/dist/mattermost-level1-setup.js +1 -1
  18. package/dist/mcp.js +2 -2
  19. package/dist/measurement-context.js +1 -1
  20. package/dist/miniflux-level1-setup.js +1 -1
  21. package/dist/nextcloud-level1-setup.js +1 -1
  22. package/dist/operation-telemetry.js +1 -0
  23. package/dist/prepared-level1-setup.js +1 -0
  24. package/dist/profile.js +1 -1
  25. package/dist/proton-mail-level1-setup.js +1 -1
  26. package/dist/recovery-launch.js +10 -0
  27. package/dist/recovery-support.js +1 -1
  28. package/dist/recovery-surface.js +1 -0
  29. package/dist/recovery.js +1 -1
  30. package/dist/resident-host.js +2 -2
  31. package/dist/resident-jobs.js +1 -1
  32. package/dist/resident-platform.js +1 -1
  33. package/dist/resident-telemetry.js +1 -0
  34. package/dist/resource-telemetry.js +1 -0
  35. package/dist/salesforce-level1-setup.js +1 -1
  36. package/dist/smartsheet-level1-setup.js +1 -1
  37. package/dist/startup.js +2 -2
  38. package/dist/thunderbird-level1-setup.js +1 -1
  39. package/dist/update-cli.js +1 -1
  40. package/dist/wakatime-level1-setup.js +1 -1
  41. package/dist/wallabag-level1-setup.js +1 -1
  42. package/dist/web.js +2 -2
  43. package/dist/zendesk-level1-setup.js +1 -1
  44. package/dist/zoom-level1-setup.js +1 -1
  45. package/dist/zulip-level1-setup.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-core/dist/operational-hub.js +1 -0
  48. package/node_modules/@zortexhq/plugin-connector-level1/dist/chatgpt.js +1 -1
  49. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  50. package/node_modules/@zortexhq/plugin-connector-level1/dist/mcp-feedback.js +1 -0
  51. package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -0
  52. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  53. package/node_modules/@zortexhq/plugin-connector-level1/package.json +2 -0
  54. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  55. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
  56. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/server.js +1 -1
  57. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-catalog.js +1 -0
  58. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -0
  59. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -0
  60. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -0
  61. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app.html +42 -0
  62. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-client.js +1 -0
  63. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-forms.js +1 -0
  64. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/demo.js +1 -0
  65. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.css +47 -6
  66. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
  67. package/node_modules/@zortexhq/plugin-galaxy-ui/src/original/fonts/LICENSE.txt +92 -0
  68. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/feedback.js +1 -1
  69. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-bridge.js +1 -1
  70. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/index.js +1 -1
  71. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-actions.js +1 -1
  72. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/driver.js +1 -1
  73. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/index.js +1 -1
  74. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/operational-browser.js +1 -0
  75. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/session-routes.js +1 -1
  76. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/shared-session.js +1 -1
  77. package/node_modules/@zortexhq/plugin-posthog/dist/collection-status.js +1 -0
  78. package/node_modules/@zortexhq/plugin-posthog/dist/index.js +1 -1
  79. package/node_modules/@zortexhq/plugin-posthog/dist/indra.js +1 -1
  80. package/node_modules/@zortexhq/plugin-posthog/dist/local-cloud.js +1 -1
  81. package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
  82. package/node_modules/@zortexhq/plugin-posthog/dist/observations.js +1 -1
  83. package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -0
  84. package/node_modules/@zortexhq/plugin-posthog/dist/resources.js +1 -0
  85. package/node_modules/@zortexhq/plugin-posthog/dist/source-ids.js +1 -1
  86. package/node_modules/@zortexhq/plugin-process-local/dist/api/resources.js +1 -0
  87. package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
  88. package/node_modules/@zortexhq/plugin-process-local/dist/resource-sampler.js +1 -0
  89. package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
  90. package/node_modules/@zortexhq/plugin-process-local/package.json +3 -0
  91. package/node_modules/@zortexhq/plugin-telemetry/dist/api/collection.js +1 -0
  92. package/node_modules/@zortexhq/plugin-telemetry/dist/api/index.js +1 -1
  93. package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
  94. package/node_modules/@zortexhq/plugin-telemetry/dist/api/observations.js +1 -1
  95. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -0
  96. package/node_modules/@zortexhq/plugin-telemetry/dist/api/resources.js +1 -0
  97. package/node_modules/@zortexhq/plugin-telemetry/dist/api/source-ids.js +1 -0
  98. package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
  99. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -0
  100. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -0
  101. package/node_modules/@zortexhq/plugin-telemetry/dist/api/upstream-tools.js +1 -0
  102. package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
  103. package/node_modules/@zortexhq/plugin-telemetry/dist/resources.js +1 -0
  104. package/node_modules/@zortexhq/plugin-telemetry/package.json +3 -0
  105. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  106. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/storage-metadata.js +1 -0
  107. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  108. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/storage-metadata.js +1 -0
  109. package/package.json +6 -6
  110. package/release-provenance.json +26 -26
  111. package/update-manifest.json +379 -181
  112. package/dist/recovery-page.js +0 -215
package/dist/recovery.js CHANGED
@@ -1 +1 @@
1
- import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{validateJoplinSelection,validateJoplinResult}from"./joplin-selection.js";import{BROWSER_CONNECTION_DIAGNOSTICS,browserRecoveryErrorCode}from"@zortexhq/plugin-oauth-browser-driver/api";import{SETUP_RELOAD_NEXT}from"./setup-activation.js";import{createPreparedDiscordSource,createPreparedServiceSource,createPreparedWorkSource}from"@zortexhq/plugin-connector-level1";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{authorizationImage}from"@zortexhq/plugin-connector-core/api";import{createServer}from"node:http";import{randomBytes,randomUUID,timingSafeEqual}from"node:crypto";import{setTimeout as delay}from"node:timers/promises";import{isAbsolute}from"node:path";import{withFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{startupHistory}from"./startup.js";import{readOnboardingReport}from"./onboarding.js";import{HELP_CATALOG}from"./source-catalog.js";import{recoveryPage}from"./recovery-page.js";import{sourceSupport,recoverySetupFlags}from"./recovery-support.js";import{protectedRecoveryFormUrl,reviewedRecoveryAuthorizationUrl}from"./recovery-authorization-url.js";import{discoverNativeVaultCandidates}from"./native-vault-discovery.js";import{readRecoveryEvidence,saveRecoveryCheck,invalidateRecoveryEvidence,safeRecoverySource}from"./recovery-evidence.js";import{readPublicActionProgress}from"./public-action-progress.js";import{beginRecoveryProgress,readRecoveryProgress}from"./recovery-progress.js";const NATIVE_FILE_SOURCES=new Set(["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"]);const MAX_RECOVERY_REQUEST_BYTES=64*1024;const PUBLIC_ERROR_CODES=new Set([...BROWSER_CONNECTION_DIAGNOSTICS,"unknown","account_identity_unavailable","aborted","interrupted","unavailable","failed_precondition","permission_denied","unauthenticated","not_found","data_loss","deadline_exceeded","resource_exhausted","authorization_timeout","authorization_denied","google_connection_failed","automatic_authorization_unavailable","page_accessibility_unavailable","requested_account_row_unavailable","requested_account_chooser_not_shown","requested_account_not_selected","youtube_requested_account_identity_unavailable","google_unverified_app","helper_unavailable","helper_timeout","login_required","qr_scan_required","pairing_timeout","notion_page_selection_required","browser_session_unavailable","extension_command_timeout","credentials_required","automatic_authorization_unsupported","browser_driver_unavailable","authorization_client_registration_failed","authorization_client_registration_required","authorization_callback_unavailable","authorization_callback_rejected","authorization_token_exchange_failed","authorization_credential_validation_failed","authorization_scope_mismatch","authorization_credential_storage_failed","authorization_registration_unavailable","authorization_client_configuration_required","configuration_reload_required","authorization_https_redirect_required","device_authorization_unavailable","browser_agent_continuation","browser_session_limit"]);const PENDING_HELP={"configuration-required":["This source needs configuration before it can be registered.","Complete this app\u2019s local setup with the available tools, then resume its connection. Other apps remain usable."],"authorization-required":["This source needs authorization before it can be registered.","Continue enrollment with the available browser or computer tools."],"ambiguous-account":["More than one account could be used for this source.","Use the task context and saved binding to identify the account, then continue connecting."],"ambiguous-resource":["More than one data resource could be used for this source.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."],"custody-unavailable":["The source authorization store is unavailable.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."]};export function validateNativeFileResult(source,result){if(result&&typeof result==="object"&&"ok"in result){const value=result.ok;if(value&&typeof value==="object"&&"source"in value&&value.source===source&&"state"in value&&typeof value.state==="string"&&["configured","configuration-required","permission-required","unavailable"].includes(value.state)&&"reloadRequired"in value&&typeof value.reloadRequired==="boolean"&&"next"in value&&typeof value.next==="string"&&(!("enabled"in value)||typeof value.enabled==="boolean"))return{ok:value}}if(result&&typeof result==="object"&&"err"in result&&result.err&&typeof result.err==="object"&&"code"in result.err&&typeof result.err.code==="string")return{err:{code:result.err.code}};return{err:{code:"invalid_resident_response"}}}const sessions=new WeakMap;const pendingSetupReloads=new WeakMap;const activeSources=new WeakMap;export function activeRecoverySource(ctx){return activeSources.get(ctx)?.source}const waiting=new Set(["connecting","waiting-user","reading"]);function authorizationHelp(code,_source){if(code==="chrome_endpoint_missing")return["Chrome is not exposing a connection endpoint for Zortex.","Open Chrome with the available computer tools, complete its connection setup and resume this source."];if(code==="chrome_endpoint_unreadable"||code==="chrome_endpoint_invalid")return["Zortex could not read a valid Chrome connection endpoint.","Repair Chrome\u2019s local connection configuration and access, then resume this source. Website sign-in is not the cause of this endpoint failure."];if(code==="chrome_connection_timeout")return["Chrome did not finish establishing the connection to Zortex.","Inspect Chrome with the available computer tools, complete its pending connection step or repair the local endpoint, then resume."];if(code==="chrome_connection_closed"||code==="chrome_connection_required")return["The connection between Zortex and Chrome is unavailable.","Recover the local Chrome connection and retry the read. Website sign-in has not been checked."];if(code==="chrome_protocol_timeout")return["Chrome connected, but did not respond to a browser operation in time.","Recover the browser operation and retry the read. Website sign-in has not been checked."];if(code==="chrome_protocol_failed")return["Chrome rejected a browser operation required to read this source.","Check the browser operation and available Chrome support, repair the route and retry. Website sign-in has not been checked."];if(code==="chrome_page_failed")return["Chrome could not load or read the source page.","Inspect the source page with the available browser tools and retry the read after recovering the page."];if(code==="browser_session_unavailable")return["Zortex could not connect to Chrome. The website sign-in state has not been checked.","Recover Chrome and its local connection with the available browser or computer tools, then resume this source. Existing data and credentials are preserved."];if(code==="failed_precondition")return["The connection prerequisites could not be verified.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."];if(code==="authorization_callback_unavailable")return["The saved authorization callback is already in use. Existing credentials are preserved.","Inspect the existing callback owner and continue that transaction. Start a replacement only after the previous owner has settled."];if(code==="authorization_client_registration_required")return["A new authorization cannot start with this installation\u2019s saved OAuth client. Existing credentials are preserved.","Repair the saved OAuth client\u2019s missing or incompatible callback details, then continue connecting."];if(code==="configuration_reload_required")return["Settings saved; connection has not been verified.",SETUP_RELOAD_NEXT];if(code==="authorization_client_configuration_required")return["This provider requires an OAuth client configuration that this connector does not currently have. No sign-in link was created.","Configure a supported OAuth client or connection service with the available setup tools, then resume this source."];if(code==="authorization_client_registration_failed")return["The provider could not register this installation\u2019s OAuth client. No sign-in link was created.","Repair the provider registration endpoint or client settings, then resume enrollment."];if(code==="authorization_registration_unavailable")return["This provider has no supported OAuth client registration configured. No sign-in link was created.","Configure a supported OAuth client through the available setup path, then resume enrollment."];if(code==="authorization_https_redirect_required")return["This provider requires an HTTPS callback that this local connection flow does not provide.","Configure the connector\u2019s supported HTTPS callback path before resuming enrollment."];if(code==="device_authorization_unavailable")return["The provider did not return a usable device authorization challenge. No sign-in code is available.","Repair the device authorization endpoint or client settings, then request a new challenge."];if(code==="credentials_required")return["This source needs credentials entered on its protected local connection page.","Use the protected local connection page and configured credential source. Request missing credential input only when the available tools cannot supply it; keep credentials out of chat."];if(code==="automatic_authorization_unsupported")return["This source has no dedicated automatic authorization driver.","Continue on the connection page with the available browser or computer tools, then check source readiness."];if(code==="browser_driver_unavailable"||code==="helper_unavailable")return["An installed helper needed by this app is unavailable.","Repair the installed helper with the available setup tools, then resume this source."]}function reason(code,source){const help=authorizationHelp(code,source);if(help)return help[0];if(code==="page_accessibility_unavailable")return"Zortex could not complete the authorization page automatically.";if(["requested_account_row_unavailable","requested_account_chooser_not_shown","requested_account_not_selected","youtube_requested_account_identity_unavailable"].includes(code??""))return"Zortex could not automatically identify the account to connect.";if(code==="authorization_denied"||code==="aborted"||code==="interrupted")return"Sign-in or authorization was not completed.";if(code==="authorization_timeout"||code==="deadline_exceeded")return"Authorization timed out. The previous link has expired.";if(code==="permission_denied")return"The current authorization does not include the required permissions.";if(code==="account_identity_unavailable")return"Zortex could not verify which account is signed in to this app.";if(code==="login_required")return source&&(SIGNED_IN_SOURCES.has(source)||["x","instagram","linkedin"].includes(source))?"No signed-in session was found for this site in Chrome on this computer.":"The provider reported that a signed-in session is required.";if(code==="qr_scan_required")return"WhatsApp needs a one-time QR scan from your phone.";if(code==="pairing_timeout")return"The WhatsApp QR code was not scanned in time.";return"Connection or reading did not finish. Your data and existing connections are saved."}const SIGNED_IN_SOURCES=new Set(["steam","reddit","spotify"]);const SITE_SIGN_IN=Object.freeze({x:"https://x.com/i/flow/login",instagram:"https://www.instagram.com/accounts/login/",linkedin:"https://www.linkedin.com/login",steam:"https://steamcommunity.com/login/home/",reddit:"https://www.reddit.com/login/",spotify:"https://accounts.spotify.com/login"});export function connectableOther(row){return row.state!=="unavailable"}const OTHER_HELP={steam:["Steam is not connected yet.","Continue Steam Community sign-in with the available browser tools, then check its profile read."],reddit:["Reddit is not connected yet.","Continue Reddit sign-in with the available browser tools, then check its read."],spotify:["Spotify is not connected yet.","Continue Spotify Web sign-in with the available browser tools, then check its read."],"google-tasks":["Google Tasks has not been verified on this computer yet.","Reuse the saved Google connection or continue sign-in with the available tools, then check Tasks."],"netease-mail":["NetEase Mail needs an IMAP authorization code.","Use the available mail settings and protected connection page to configure IMAP, then continue enrollment. Request the code only if it cannot be obtained through available tools."],notebooklm:["NotebookLM needs a Google sign-in in its connection browser.","Continue the Google connection page with the available browser or computer tools."],stripe:["Stripe needs a provider connection.","Complete the requested connection on Stripe\u2019s page with the available browser tools."],openrouter:["OpenRouter needs a provider connection.","Complete the requested connection on OpenRouter\u2019s page with the available browser tools."],calendly:["Calendly has not been verified on this computer yet.","Reuse the saved connection or continue Calendly sign-in with the available tools, then check its Actions."],shopify:["Shopify needs store and application configuration.","Find the requested store and configure its application through the available provider tools, then continue on the protected local connection page."],activitywatch:["ActivityWatch needs its local service running on this computer.","Start or repair the local ActivityWatch service with the available computer tools, then verify the source read."]};function currentReadinessRow(state){const proof=state.readiness;if(state.state!=="connected"||state.verification||state.registration||!proof||!Number.isSafeInteger(proof.actions)||proof.actions<1)return;if(!proof.operation||!["not-run","succeeded"].includes(proof.operation.state))return;const checked=proof.operation.state==="succeeded",returned=proof.operation.state==="succeeded"?proof.operation.returned:void 0;if(returned!==void 0&&(!Number.isSafeInteger(returned)||returned<0))return;const read=returned===void 0?"not-attempted":returned===0?"empty":"first-record";return{connection:"connected",availability:"actions",actions:proof.actions,operation:proof.operation.state,read,state:read==="empty"?"empty":"complete",message:read==="first-record"?"Connected and the first record has been read.":read==="empty"?"The read succeeded, but no data is currently visible.":checked?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.",nextStep:read==="empty"?emptyHelp():"You can start using this source."}}function connectedRow(state){if(state.verification==="configuration-only")return{source:state.source,...typeof state.label==="string"?{label:state.label.slice(0,80)}:{},connection:"unknown",read:"not-attempted",state:"pending",message:"Settings saved; connection has not been verified.",nextStep:"Check the source connection and read its data."};const label=typeof state.label==="string"?state.label.slice(0,80):void 0;return{source:state.source,...label?{label}:{},connection:"connected",read:"not-attempted",state:"pending",message:"Connected. Available actions or data access have not been checked.",nextStep:"Run the readiness check for this connection.",...currentReadinessRow(state)}}function otherRow(state){const unavailable=state.state==="unavailable",[message,nextStep]=OTHER_HELP[state.source]??[`${typeof state.label==="string"?state.label:state.source} is not connected yet.`,"Continue the connection page with the available browser or computer tools."];const label=typeof state.label==="string"?state.label.slice(0,80):void 0;return{source:state.source,...label?{label}:{},connection:unavailable?"unavailable":"not-connected",read:"not-attempted",state:unavailable?"unavailable":"pending",message:unavailable&&typeof state.message==="string"&&!OTHER_HELP[state.source]?state.message.slice(0,300):message,nextStep:unavailable&&!OTHER_HELP[state.source]?"Inspect the source settings and repair the reported setup requirement before continuing.":nextStep}}function emptyHelp(_source){return"You can use this source. An empty result does not require another sign-in."}function safeUrl(source,value,ownedOrigin){try{if(typeof value!=="string"||value.length>24e3)return;const url=new URL(value);const graphDeviceSources=["onedrive","sharepoint","microsoft-planner","onenote"];const graphDeviceUrls=["https://login.microsoft.com/device","https://microsoft.com/devicelogin","https://login.microsoftonline.com/common/oauth2/deviceauth"];const routes={...Object.fromEntries(graphDeviceSources.map(source2=>[source2,graphDeviceUrls])),matrix:["https://account.matrix.org/authorize"],github:["https://github.com/login/device"],"microsoft-todo":["https://login.microsoftonline.com/common/oauth2/v2.0/authorize","https://login.microsoftonline.com/common/oauth2/deviceauth","https://microsoft.com/devicelogin"],gmail:["https://accounts.google.com/o/oauth2/v2/auth"],"google-drive":["https://accounts.google.com/o/oauth2/v2/auth"],"google-calendar":["https://accounts.google.com/o/oauth2/v2/auth"],"google-tasks":["https://accounts.google.com/o/oauth2/v2/auth"],youtube:["https://accounts.google.com/o/oauth2/v2/auth"],slack:["https://slack.com/oauth/v2/authorize"],outlook:["https://login.microsoftonline.com/common/oauth2/v2.0/authorize"],teams:["https://login.microsoftonline.com/common/oauth2/v2.0/authorize"],notion:["https://zortex-auth.pages.dev/notion/authorize","https://api.notion.com/v1/oauth/authorize"]};if(source==="whatsapp-web"&&url.protocol==="http:"&&url.hostname==="127.0.0.1"&&!url.username&&!url.password&&!url.hash&&!url.search&&/^\/[A-Za-z0-9_-]{32}$/.test(url.pathname))return url.href;if(url.protocol==="http:"&&url.hostname==="127.0.0.1"&&!url.username&&!url.password&&!url.hash&&!url.search&&/^\/connect\/[A-Za-z0-9_-]{32}$/.test(url.pathname))return url.href;if(url.protocol==="https:"&&!url.username&&!url.password&&!url.hash&&(routes[source]?.includes(url.origin+url.pathname)||ownedOrigin===url.origin)){if(source==="github"&&routes.github?.includes(url.origin+url.pathname)||(source==="microsoft-todo"||graphDeviceSources.includes(source))&&graphDeviceUrls.includes(url.origin+url.pathname))url.search="";return url.href}}catch{}return}const PAGE_GONE_MS=18e4;function seedRow(seed){const{source}=seed,setup=seed.configuration==="required",connection=setup?"unavailable":seed.connection;const positiveActions=Number.isSafeInteger(seed.actions)&&seed.actions>0;const failed=seed.read==="failed"||!!seed.errorCode||seed.availability==="none"||seed.availability==="actions"&&!positiveActions;const read=failed&&connection!=="unavailable"?"failed":connection==="connected"?seed.read:"not-attempted",actionsReady=connection==="connected"&&!failed&&seed.availability==="actions"&&positiveActions;return{source,connection,read,...seed.errorCode?{errorCode:PUBLIC_ERROR_CODES.has(seed.errorCode)?seed.errorCode:"unknown"}:{},...actionsReady?{availability:"actions",actions:seed.actions,operation:seed.operation??"not-run"}:connection==="connected"&&["first-record","empty"].includes(read)?{availability:"read",operation:"succeeded"}:{},...setup?{configuration:"required"}:{},state:connection==="unavailable"?"unavailable":actionsReady||read==="first-record"?"complete":read==="empty"?"empty":read==="failed"?"failed":"pending",message:setup?"This app still needs local setup.":connection==="unavailable"?"This source is not installed, is disabled, or is currently unavailable.":read==="first-record"?"Connected and the first record has been read.":read==="empty"?"The read succeeded, but no data is currently visible.":actionsReady?seed.operation==="succeeded"?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.":connection==="connected"&&read==="not-attempted"&&!seed.errorCode?"Connected. Available actions or data access have not been checked.":reason(seed.errorCode,source),nextStep:actionsReady||read==="first-record"?"You can start using this source.":read==="empty"?emptyHelp():setup?"Complete this app\u2019s local setup with the available tools, then resume its connection. Other apps remain usable.":connection==="connected"?"Run the readiness check for this connection.":""}}export function startGuidedRecovery(ctx,options){const existing=sessions.get(ctx);if(existing)return existing.then(async session=>{const snapshot=session.snapshot();const changed=snapshot.sources.length!==options.sources.length||options.sources.some(seed=>{const current=snapshot.sources.find(row=>row.source===seed.source),next=seedRow(seed);return!current||["connection","read","availability","actions","operation","configuration","message"].some(key=>current[key]!==next[key])});if(snapshot.state==="closed"||!activeSources.has(ctx)&&!snapshot.sources.concat(snapshot.others).some(row=>waiting.has(row.state))&&changed){await session.close();return startGuidedRecovery(ctx,options)}return session});const pending=createSession(ctx,options).catch(error=>{sessions.delete(ctx);throw error});sessions.set(ctx,pending);return pending}async function createSession(ctx,{sources,pageGoneMs=PAGE_GONE_MS,authorization}){const providerReadinessSources=new Set;if(!Array.isArray(sources)||sources.some(row=>!safeRecoverySource(row.source))||new Set(sources.map(row=>row.source)).size!==sources.length)throw Error("Invalid recovery sources.");if(!!authorization?.status!==!!(authorization?.read||authorization?.check))throw Error("Invalid recovery owner: status and checks must use the same owner.");const rows=sources.map(seed=>{const row=seedRow(seed),label=HELP_CATALOG.find(([source])=>source===seed.source)?.[1];if(label)row.label=label;return row});for(const row of rows)if(row.read==="failed")fail(row,row.errorCode);const others=[];let initialStates;try{initialStates=authorization?.status?await authorization.status(AbortSignal.timeout(15e3)):await ctx.get("zortexConnectorHub")?.status({signal:AbortSignal.timeout(15e3)});if(initialStates&&"ok"in initialStates){for(const state of initialStates.ok)if(!rows.some(row=>row.source===state.source)&&!others.some(row=>row.source===state.source)&&safeRecoverySource(state.source))others.push(state.state==="connected"?connectedRow(state):otherRow(state))}}catch{}if(authorization?.status)for(const row of rows){const state=initialStates&&"ok"in initialStates?initialStates.ok.find(item=>item.source===row.source):void 0;row.connection=state?.verification==="configuration-only"?"unknown":state?.state??"unknown";if(state?.verification==="configuration-only"){clearReadiness(row);delete row.errorCode;row.state="pending";row.message="Settings saved; connection has not been verified.";row.nextStep="Check the source connection and read its data."}else if(row.read==="failed"&&row.connection!=="unavailable"){fail(row,row.errorCode)}else if(row.connection!=="connected"){clearReadiness(row);delete row.errorCode;row.read="not-attempted";row.state=row.connection==="unavailable"?"unavailable":"pending";row.message=row.connection==="unknown"?"Current connection status is unavailable.":reason()}}if(initialStates&&"ok"in initialStates)for(const row of[...rows,...others]){const state=initialStates.ok.find(item=>item.source===row.source);const readiness=state&&currentReadinessRow(state);if(readiness){Object.assign(row,readiness);delete row.errorCode;providerReadinessSources.add(row.source)}else if(state?.verification==="configuration-only"){row.read="not-attempted";delete row.errorCode}if(state?.registration==="deferred"){clearReadiness(row);delete row.errorCode;row.registration="deferred";row.connection="unavailable";row.read="not-attempted";row.state="unavailable";row.message="Setup is required before this connector can be used.";row.nextStep="Complete the setup with the available tools; connection continues when the configuration is active."}}const listed=new Set([...rows,...others].map(row=>row.source));for(const[entry,label]of HELP_CATALOG){const source=entry==="teams"&&!listed.has("teams")?"microsoft-teams":entry;if(!listed.has(source)){others.push({source,label,connection:"unknown",read:"not-attempted",state:"pending",catalogOnly:true,message:"This is a directory entry; registration and connection have not been checked.",nextStep:"Inspect the installed source catalog and enable or configure the source when available."});listed.add(source)}}const token=randomBytes(32).toString("base64url"),nonce=randomBytes(24).toString("base64url");let origin="",closed=false,active,activeSource,owned,settled=false,closeTask;const continuations=new Map,configured=new Set;function releaseExecution(stop){if(owned!==stop)return;owned=void 0;active=void 0;activeSource=void 0;if(activeSources.get(ctx)?.owner===token)activeSources.delete(ctx)}let resolveDone;const done=new Promise(resolve=>{resolveDone=resolve});let resolveClosed;const closedPromise=new Promise(resolve=>{resolveClosed=resolve});const expiresAt=new Date(Date.now()+18e5).toISOString();const allRows=()=>rows.concat(others);const reloads=pendingSetupReloads.get(ctx)??new Map;pendingSetupReloads.set(ctx,reloads);function acceptResidentReload(state){if(state?.reloadRequired===true)reloads.set(state.source,SETUP_RELOAD_NEXT);else if(state?.reloadRequired===false){reloads.delete(state.source);const row=allRows().find(item=>item.source===state.source);if(row)delete row.reloadRequired}}if(initialStates&&"ok"in initialStates)for(const state of initialStates.ok)acceptResidentReload(state);function retainSetupReload(row){const next=reloads.get(row.source);if(next===void 0)return false;clearHandoff(row);clearReadiness(row);row.reloadRequired=true;row.connection="unknown";row.read="not-attempted";row.state="pending";row.message="Settings saved; connection has not been verified.";row.nextStep=next;delete row.errorCode;delete row.authorizationUrl;delete row.deviceUserCode;delete row.authorizationImage;delete row.setupReason;providerReadinessSources.delete(row.source);return true}for(const row of allRows())retainSetupReload(row);async function withSetupProgress(source,stop,configure){const progress=beginRecoveryProgress(ctx,source);progress.update("configuring","unverified");const interrupted=()=>progress.finish({connectionState:"unverified",errorCode:"aborted"});stop.signal.addEventListener("abort",interrupted,{once:true});try{if(stop.signal.aborted){interrupted();return{err:{code:"aborted"}}}const result=await configure();if("ok"in result&&result.ok.state==="configured"){const row=allRows().find(item=>item.source===source);if(result.ok.reloadRequired){reloads.set(source,result.ok.next);if(row)retainSetupReload(row)}else{reloads.delete(source);configured.add(source);if(row){clearReadiness(row);delete row.reloadRequired;delete row.configuration;delete row.registration;delete row.setupReason;row.connection="unknown"}}}progress.finish({connectionState:"unverified",..."err"in result?{errorCode:result.err.code}:result.ok.state!=="configured"?{errorCode:result.ok.state==="unavailable"?"unavailable":"failed_precondition"}:result.ok.reloadRequired?{errorCode:"configuration_reload_required"}:{}});return result}catch(error){progress.finish({connectionState:"unverified",errorCode:"unknown"});throw error}finally{stop.signal.removeEventListener("abort",interrupted)}}const externalProgressSources=new Set;function applyPending(result){if(!result||!("ok"in result))return;const pending=Array.isArray(result.pending)?result.pending:[];for(const row of allRows()){if(externalProgressSources.has(row.source))continue;if(retainSetupReload(row))continue;const item=pending.find(value=>value&&value.source===row.source&&typeof value.reason==="string"&&Object.hasOwn(PENDING_HELP,value.reason));const nextReason=row.connection==="connected"?void 0:item?.reason;if(nextReason===row.setupReason)continue;if(nextReason)row.setupReason=nextReason;else delete row.setupReason;if(nextReason){[row.message,row.nextStep]=PENDING_HELP[nextReason];if(row.registration==="deferred")row.nextStep="Complete the setup with the available tools; connection continues when the configuration is active."}else if(row.catalogOnly){row.message="This is a directory entry; registration and connection have not been checked.";row.nextStep="Inspect the installed source catalog and enable or configure the source when available."}else if(row.connection!=="connected"){row.message="This source is not connected.";row.nextStep="Check the connection and try again."}}}applyPending(initialStates);function evidenceVersions(){const parts=new Map,add=(source,value)=>{parts.set(source,[...parts.get(source)??[],value])};try{const fleet=ctx.get("indraFleet");if(fleet){for(const receipt of startupHistory(fleet).receipts)for(const result of receipt.sources)add(result.source,["receipt",receipt.requestId,result.progress?.startedAt??receipt.startedAt,result.progress?.endedAt,result.state,result.returned,result.error?.code]);for(const progress of fleet.status().sources??[])add(progress.source,["progress",progress.startedAt,progress.endedAt,progress.stage,progress.returned,progress.error?.code])}for(const saved of readRecoveryEvidence(ctx,allRows().map(row=>row.source)).values())add(saved.source,["help",saved.updatedAt,saved.read,saved.returned]);for(const progress of readRecoveryProgress(ctx))add(progress.source,["manual-progress",progress.startedAt,progress.endedAt,progress.stage,progress.connectionState,progress.returned,progress.errorCode,progress.readiness])}catch{return new Map}return new Map([...parts].map(([source,values])=>[source,JSON.stringify(values)]))}const blockedEvidence=new Map,initialEvidence=evidenceVersions();for(const row of allRows())if(row.connection!=="connected")blockedEvidence.set(row.source,initialEvidence.get(row.source));let statusRefresh,lastStatusRefresh=0,interactionGeneration=0;function refreshResidentStatus(){if(active||closed||statusRefresh||Date.now()-lastStatusRefresh<5e3)return;lastStatusRefresh=Date.now();const generation=interactionGeneration;statusRefresh=(async()=>{const versions=evidenceVersions();let states;try{const signal=AbortSignal.timeout(15e3);states=await(authorization?.status?authorization.status(signal):ctx.get("zortexConnectorHub")?.status({signal}))}catch{}const evidenceContext=authorization?.status?{get:name=>name==="zortexConnectorHub"?{status:async()=>states??{err:{code:"unavailable"}}}:ctx.get(name)}:ctx;const progress=versions.size?await readOnboardingReport(evidenceContext,{enabled:true}):void 0;if(active||closed||generation!==interactionGeneration)return;const currentVersions=evidenceVersions();const manualProgress=new Map(readRecoveryProgress(ctx).map(item=>[item.source,item]));if(states&&"ok"in states){for(const state of states.ok)if(safeRecoverySource(state.source)&&!allRows().some(row=>row.source===state.source))others.push(state.state==="connected"?connectedRow(state):otherRow(state))}for(const row of allRows()){if(waiting.has(row.state)&&!externalProgressSources.has(row.source)||busy(row.source))continue;const state=states&&"ok"in states?states.ok.find(item=>item.source===row.source):void 0;acceptResidentReload(state);if(retainSetupReload(row))continue;if(row.catalogOnly&&!state)continue;if(state){delete row.catalogOnly;if(typeof state.label==="string")row.label=state.label.slice(0,80)}const deferred=state?.registration==="deferred",changedRegistration=row.registration==="deferred"!==deferred;if(deferred)row.registration="deferred";else delete row.registration;const external=manualProgress.get(row.source),version=versions.get(row.source);const stableEvidence=version!==void 0&&version===currentVersions.get(row.source);if(!deferred&&state&&external&&external.stage!=="finished"&&stableEvidence){externalProgressSources.add(row.source);blockedEvidence.set(row.source,version);clearReadiness(row);clearHandoff(row);delete row.errorCode;delete row.setupReason;row.connection=state.state;row.read="not-attempted";row.state=external.stage==="configuring"?"connecting":external.stage;row.message=external.stage==="waiting-user"?"The existing connection transaction has an active sign-in page.":external.stage==="reading"?"The current connection is being checked for readable data.":"A connection attempt is in progress.";row.nextStep="Finish the existing connection attempt; this page updates automatically.";continue}const endedExternal=externalProgressSources.delete(row.source);const readiness=state&&currentReadinessRow(state);if(readiness){Object.assign(row,readiness);delete row.errorCode;providerReadinessSources.add(row.source);delete row.setupReason;continue}const lostProviderReadiness=providerReadinessSources.delete(row.source);const next=deferred?"unavailable":state?.verification==="configuration-only"?"unknown":state?.state??(states&&"ok"in states?"unavailable":"unknown");const newEvidence=version!==void 0&&version===currentVersions.get(row.source)&&(!blockedEvidence.has(row.source)||blockedEvidence.get(row.source)!==version);if(next!=="connected"||lostProviderReadiness||row.state==="actions-ready")blockedEvidence.set(row.source,version);const evidence=progress?.sources.find(item=>item.source===row.source);if(next==="not-connected"&&newEvidence&&evidence?.read==="failed"){row.connection=next;delete row.setupReason;fail(row,evidence.errorCode);continue}if(next==="connected"&&evidence?.connection==="connected"&&version!==void 0&&version===currentVersions.get(row.source)&&(!blockedEvidence.has(row.source)||blockedEvidence.get(row.source)!==version)){blockedEvidence.delete(row.source);clearReadiness(row);clearHandoff(row);delete row.setupReason;delete row.errorCode;Object.assign(row,seedRow(evidence));if(evidence.read==="failed")fail(row,evidence.errorCode);continue}if(!endedExternal&&!lostProviderReadiness&&row.state!=="actions-ready"&&row.connection===next&&!changedRegistration&&!(state?.verification==="configuration-only"&&row.message!=="Settings saved; connection has not been verified.")&&!(next==="unknown"&&!state&&row.message==="Settings saved; connection has not been verified."))continue;row.connection=next;clearReadiness(row);clearHandoff(row);delete row.setupReason;row.read="not-attempted";delete row.errorCode;row.state=next==="unavailable"?"unavailable":"pending";row.message=deferred?"Setup is required before this connector can be used.":state?.verification==="configuration-only"?"Settings saved; connection has not been verified.":next==="connected"?"Connected. Check again to verify the current connection.":next==="unknown"?"Current connection status is unavailable.":next==="unavailable"?"This source is currently unavailable.":"This source is not connected.";row.nextStep=deferred?"Complete the setup with the available tools; connection continues when the configuration is active.":state?.verification==="configuration-only"?"Check the source connection and read its data.":next==="connected"?"Check available actions or data access.":"Check the connection and try again."}applyPending(states);complete()})().finally(()=>{statusRefresh=void 0})}const terminal=row=>["complete","empty","actions-ready"].includes(row.state)||row.state==="unavailable"&&row.configuration!=="required"&&row.registration!=="deferred"&&!row.reloadRequired;const complete=()=>{const checked=allRows().filter(row=>!row.catalogOnly);if(!settled&&checked.some(row=>["complete","empty","actions-ready"].includes(row.state))&&checked.every(terminal)){settled=true;resolveDone()}};function report(links=false){const checked=allRows().filter(row=>!row.catalogOnly);const success=checked.length>0&&checked.every(row=>["complete","empty","actions-ready"].includes(row.state)&&row.connection==="connected");const publicReads=new Map(readPublicActionProgress(ctx).map(item=>[item.source,item]));const shown=row=>{const{authorizationUrl,authorizationInstructions,deviceUserCode,authorizationImage:qrImage,browserContinuation,...safe}=row;const signInUrl=!closed&&(row.connection!=="connected"||row.errorCode==="login_required")&&["pending","failed"].includes(row.state)&&Object.hasOwn(SITE_SIGN_IN,row.source)?SITE_SIGN_IN[row.source]:void 0;const setup=recoverySetupFlags(row.source,authorization);const support=sourceSupport(row,Object.keys(setup).length>0);const publicRead=publicReads.get(row.source);const publicRow={...safe,...setup,support,...publicRead?{publicRead}:{},...signInUrl?{signInUrl}:{},...links&&row.state==="waiting-user"&&browserContinuation?{browserContinuation}:{},...links&&row.state==="waiting-user"&&authorizationInstructions?{nextStep:authorizationInstructions}:{},...links&&row.state==="waiting-user"&&qrImage?{authorizationImage:{...qrImage}}:{},...links&&row.state==="waiting-user"&&authorizationUrl?{authorizationUrl,...deviceUserCode?{deviceUserCode}:{}}:{}};if(row.configuration==="required"&&support.reasonCode==="connector_unavailable"){}else if(support.state==="unsupported"){publicRow.state="unavailable";publicRow.message=support.message;publicRow.nextStep=support.nextStep}else if(row.registration==="deferred"||row.connection==="unavailable"){publicRow.message=support.message;publicRow.nextStep=support.nextStep}return publicRow};return{state:closed?"closed":success?"ready":checked.length>0&&checked.every(terminal)?"partial":"recovering",success,sources:rows.map(shown),others:others.map(shown),...activeSource?{activeSource}:{}}}function clearHandoff(row){delete row.browserContinuation;delete row.authorizationUrl;delete row.authorizationInstructions;delete row.deviceUserCode;delete row.authorizationImage}function clearReadiness(row){delete row.availability;delete row.actions;delete row.operation}function fail(row,code){clearHandoff(row);clearReadiness(row);delete row.authorizationUrl;delete row.deviceUserCode;delete row.authorizationImage;if(code)row.errorCode=PUBLIC_ERROR_CODES.has(code)?code:"unknown";else delete row.errorCode;row.state="failed";row.read="failed";if(row.source==="rednote"&&code==="unavailable"){row.message="The local RedNote service is unavailable.";row.nextStep="";return}if(row.source==="activitywatch"&&code==="unavailable"){row.message=OTHER_HELP.activitywatch[0];row.nextStep="";return}if(code==="unavailable"&&["spotify","reddit","steam","x","instagram","linkedin"].includes(row.source)){row.message="Live reading is currently unavailable. The website sign-in state has not been confirmed.";row.nextStep="";return}if(row.connection==="connected"&&code==="failed_precondition"&&["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(row.source)){row.message="Saved Google account access could not be verified.";row.nextStep="";return}const help=authorizationHelp(code,row.source);if(help){[row.message,row.nextStep]=help;return}row.message=reason(code,row.source);row.nextStep=""}function busy(source){return continuations.has(source)||(ctx.get("indraFleet")?.status().activeSources?.includes(source)??false)}async function run(row,stop,forceAuthorization,readOnly,repairLegacyClient=false,savedAccessOnly=false,readwiseMcpWrite=false,gmailWrite=false){const progress=beginRecoveryProgress(ctx,row.source);let returned,readiness,ownsFlow=true;const interrupted=()=>progress.finish({connectionState:row.connection==="connected"?"connected":"unverified",errorCode:"aborted"});stop.signal.addEventListener("abort",interrupted,{once:true});const hub=ctx.get("zortexConnectorHub");try{stop.signal.throwIfAborted();if(!hub){fail(row);return}const states=authorization?.status?await authorization.status(stop.signal):await hub.status({signal:stop.signal});stop.signal.throwIfAborted();if(!("ok"in states)){row.connection="unknown";fail(row);return}const state=states.ok.find(item=>item.source===row.source);if(!state||state.state==="unavailable"){row.state="unavailable";row.connection="unavailable";row.message="This source is not installed, is disabled, or is currently unavailable.";row.nextStep="Inspect the source settings and complete the available setup before resuming its connection.";return}delete row.catalogOnly;row.connection=state.state;if(readOnly&&state.state!=="connected"){fail(row,"unauthenticated");return}if(savedAccessOnly){const result2=authorization?await authorization.reconnectSaved?.(row.source,stop.signal):await hub.connect(row.source,{signal:stop.signal,retention:"transient",automatic:true,savedAccessOnly:true});if(!result2||!("ok"in result2)||result2.ok.source!==row.source||result2.ok.state!=="connected"){const code=result2&&"ok"in result2&&result2.ok.source===row.source&&result2.ok.state==="failed"?result2.ok.error?.code:void 0;fail(row,result2&&"err"in result2?browserRecoveryErrorCode(result2.err):code??"failed_precondition");return}row.connection="connected"}else if(state.state!=="connected"||forceAuthorization){const started=Date.now(),requestId=randomUUID();let residentOwned=false;const selectAccount=forceAuthorization&&!gmailWrite&&["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(row.source);const reauthorize=forceAuthorization&&repairLegacyClient&&["todoist","linear"].includes(row.source);const settings={...gmailWrite?{gmailWrite:true}:{},...readwiseMcpWrite?{readwiseMcpWrite:true}:{},...selectAccount?{selectAccount:true}:{},...reauthorize?{reauthorize:true}:{}};const result2=authorization?await authorization.connect(row.source,requestId,stop.signal,settings):await hub.connect(row.source,{signal:stop.signal,retention:"transient",automatic:true,...settings});residentOwned=!!authorization;if(!("ok"in result2)){fail(row,"err"in result2?browserRecoveryErrorCode(result2.err):"data_loss");return}let job=result2.ok,cancellation;const cancelResidentAuthorization=()=>{const current=job;if(!residentOwned||current.state!=="waiting-user"||!Number.isSafeInteger(current.generation)||typeof current.challengeRef!=="string"||!current.challengeRef)return;return cancellation??=authorization.cancel(requestId,current.generation,current.challengeRef).then(()=>void 0,()=>void 0)};try{stop.signal.throwIfAborted();if(!residentOwned&&job.state==="waiting-user"&&(!Number.isFinite(Date.parse(job.startedAt))||Date.parse(job.startedAt)<started)){ownsFlow=false;releaseExecution(stop);row.state="pending";row.message="Another sign-in is still waiting for authorization.";row.nextStep="Continue the existing transaction through its owning session, then check this source again.";return}const id=job.id;while(!stop.signal.aborted){if(job.id!==id||job.source!==row.source){fail(row);return}clearHandoff(row);if(job.state==="connected"){row.connection="connected";break}if(job.state!=="waiting-user"){fail(row,job.state==="cancelled"?"aborted":job.error?.code);return}if(row.source==="whatsapp-web"){row.state="waiting-user";row.message="Waiting for you to scan the QR code with WhatsApp on your phone.";row.nextStep="Settings \u2192 Linked devices \u2192 Link a device. The latest message will be read automatically after the scan. If you closed the page, use the link below to reopen it."}else{row.state="waiting-user";row.message="Authorization is in progress.";row.nextStep="Please wait. You do not need to click again."}const qrImage=authorizationImage(job.authorizationImage);if(qrImage){row.authorizationImage=qrImage;if(row.source!=="whatsapp-web"){row.message="The provider returned a QR authorization challenge.";row.nextStep=""}}const url=safeUrl(row.source,job.authorizationUrl,residentOwned?job.authorizationOrigin:void 0)??reviewedRecoveryAuthorizationUrl(row.source,job)??protectedRecoveryFormUrl(row.source,job,residentOwned);if(url){row.authorizationUrl=url;const prompt=job.devicePrompt;if(prompt?.kind==="device-code"&&typeof prompt.userCode==="string"&&/^[A-Z0-9-]{4,32}$/i.test(prompt.userCode))row.deviceUserCode=prompt.userCode}if(residentOwned&&typeof job.instructions==="string"&&job.instructions.trim()&&Buffer.byteLength(job.instructions)<=2048&&!/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u.test(job.instructions))row.authorizationInstructions=job.instructions;if(url||qrImage||row.authorizationInstructions){row.state="waiting-user";if(row.source!=="whatsapp-web"&&!qrImage){row.message="The connection page has an active sign-in or access step.";row.nextStep="Continue the live page with the available browser or computer tools. Request missing input only if those tools cannot complete the step."}}if(job.browserContinuation){row.browserContinuation=job.browserContinuation;row.nextStep="Continue the retained browser session through the browser-use Actions. Use browser.observe with its sessionId, then the returned controls with browser.click or browser.type. Keep polling this authorization job; only provider verification marks it connected."}progress.update(row.state,"unverified");if(residentOwned&&job.automationActive!==true)releaseExecution(stop);try{await delay(250,void 0,{signal:stop.signal})}catch(error){await cancelResidentAuthorization();throw error}const next=authorization?await authorization.job(requestId,stop.signal):hub.job(id);if(!("ok"in next)){fail(row);return}job=next.ok}}finally{if(stop.signal.aborted)await cancelResidentAuthorization()}}while(active&&owned!==stop)await delay(50,void 0,{signal:stop.signal});stop.signal.throwIfAborted();owned=stop;activeSource=row.source;active=continuations.get(row.source)?.task;activeSources.set(ctx,{source:row.source,owner:token});clearHandoff(row);row.state="reading";row.message="Connection confirmed. Checking available actions or data access.";row.nextStep="Checking available actions or data access.";progress.update("reading","connected");const result=authorization?.check?await authorization.check(row.source,stop.signal):authorization?.read?await authorization.read(row.source,{limit:1},stop.signal).then(result2=>"ok"in result2?{ok:{source:row.source,basis:"read",operation:{state:"succeeded",returned:result2.ok.returned}}}:"empty"in result2?{ok:{source:row.source,basis:"read",operation:{state:"succeeded",returned:0}}}:result2):await hub.check(row.source,{signal:stop.signal,retention:"transient"});stop.signal.throwIfAborted();if(!("ok"in result)){fail(row,"err"in result?browserRecoveryErrorCode(result.err):void 0);return}const check=result.ok;if(check.source!==row.source||check.basis==="actions"&&(!Number.isSafeInteger(check.actions)||check.actions<=0)){fail(row);return}if(!saveRecoveryCheck(ctx,check)){fail(row);row.message="Connection was checked, but progress could not be saved on this computer.";row.nextStep="Repair access to the data folder, then repeat the readiness check. The connection is saved.";return}readiness=check;if(check.basis==="actions"&&authorization?.status)providerReadinessSources.add(row.source);delete row.errorCode;row.availability=check.basis;row.operation=check.operation.state;if(check.basis==="actions")row.actions=check.actions;else delete row.actions;returned=check.operation.state==="succeeded"?check.operation.returned:void 0;row.read=returned===void 0?"not-attempted":returned>0?"first-record":"empty";row.state=row.read==="empty"?"empty":"complete";row.message=row.read==="first-record"?"Connected and the first record has been read.":row.read==="empty"?"The read succeeded, but no data is currently visible.":row.operation==="succeeded"?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.";row.nextStep=row.read==="empty"?emptyHelp():"This source is ready to use."}catch{if(!closed)fail(row,stop.signal.aborted?"aborted":void 0)}finally{progress.finish({connectionState:row.connection==="connected"?"connected":"unverified",...readiness&&!stop.signal.aborted&&["complete","empty"].includes(row.state)?{readiness}:{},...returned!==void 0?{returned}:{},...["failed","unavailable","pending"].includes(row.state)?{errorCode:row.errorCode??(row.state==="unavailable"?"unavailable":"unknown")}:{}});stop.signal.removeEventListener("abort",interrupted);clearHandoff(row);releaseExecution(stop);if(ownsFlow)stop.abort();complete()}}function startRecovery(row,stop,forceAuthorization=false,readOnly=false,repairLegacyClient=false,savedAccessOnly=false,readwiseMcpWrite=false,gmailWrite=false){interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});const task=Promise.resolve().then(()=>withFeedbackFlow(row.source,()=>run(row,stop,forceAuthorization,readOnly,repairLegacyClient,savedAccessOnly,readwiseMcpWrite,gmailWrite),{flowId:randomUUID(),source:row.source,mode:"manual",trigger:"tool"})).catch(()=>{if(!closed)fail(row)}).finally(()=>{if(continuations.get(row.source)?.stop===stop)continuations.delete(row.source);releaseExecution(stop)});continuations.set(row.source,{stop,task});active=task}function finishSetup(row,stop){releaseExecution(stop);if(configured.delete(row.source)&&!closed&&!stop.signal.aborted)startRecovery(row,stop);else stop.abort()}function reply(response,status,value){response.writeHead(status,{"Content-Type":"application/json; charset=utf-8"}).end(JSON.stringify(value))}const server=createServer((request,response)=>{void handle(request,response).catch(()=>{if(!response.headersSent)reply(response,500,{error:"request_failed"});else response.end()})});let lastSeen=0;async function handle(request,response){response.setHeader("Cache-Control","no-store");response.setHeader("Referrer-Policy","no-referrer");response.setHeader("X-Content-Type-Options","nosniff");response.setHeader("Content-Security-Policy",`default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`);if(request.headers.host!==new URL(origin).host){reply(response,403,{error:"forbidden"});return}if(request.method==="GET"&&request.url==="/"){response.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}).end(recoveryPage(nonce));return}if(request.method!=="POST"||request.url!=="/api"){reply(response,404,{error:"not_found"});return}const received=request.headers["x-zortex-recovery"];if(request.headers.origin!==origin||typeof received!=="string"||Buffer.byteLength(received)!==Buffer.byteLength(token)||!timingSafeEqual(Buffer.from(received),Buffer.from(token))){reply(response,403,{error:"forbidden"});return}lastSeen=Date.now();if(request.headers["content-type"]!=="application/json"){reply(response,415,{error:"json_required"});return}if(Number(request.headers["content-length"]??0)>MAX_RECOVERY_REQUEST_BYTES){request.resume();reply(response,413,{error:"too_large"});return}let bytes=0;const chunks=[];for await(const chunk of request){bytes+=chunk.length;if(bytes>MAX_RECOVERY_REQUEST_BYTES){reply(response,413,{error:"too_large"});return}chunks.push(chunk)}let body;try{body=JSON.parse(Buffer.concat(chunks).toString("utf8"))}catch{reply(response,400,{error:"invalid_request"});return}if(!body||typeof body!=="object"||Array.isArray(body)||Object.keys(body).some(key=>!["action","source","roots","libraryId","libraryType","port","executable","session","subdomain","region","instanceUrl","selection"].includes(key))||!["status","connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved","cancel","close","discover-native-vault","configure-native-files","configure-zotero","configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-copyq","configure-freshdesk","configure-smartsheet","configure-figma","configure-nextcloud","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))||!["connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved","cancel","discover-native-vault","configure-native-files","configure-zotero","configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-copyq","configure-freshdesk","configure-smartsheet","configure-figma","configure-nextcloud","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))&&body.source!==void 0||body.action!=="configure-native-files"&&body.roots!==void 0||body.action!=="configure-zotero"&&(body.libraryId!==void 0||body.libraryType!==void 0)||!["configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail"].includes(String(body.action))&&body.port!==void 0||body.action!=="configure-copyq"&&(body.executable!==void 0||body.session!==void 0)||body.action!=="configure-freshdesk"&&body.subdomain!==void 0||body.action!=="configure-smartsheet"&&body.region!==void 0||body.action!=="configure-nextcloud"&&body.instanceUrl!==void 0||!["configure-joplin","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-figma","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))&&body.selection!==void 0){reply(response,400,{error:"invalid_request"});return}if(body.action==="authorize-readwise-mcp"&&(body.source!=="readwise"||Object.keys(body).length!==2)){reply(response,400,{error:"invalid_request"});return}if(body.action==="authorize-gmail-write"&&(body.source!=="gmail"||Object.keys(body).length!==2)){reply(response,400,{error:"invalid_request"});return}if(body.action==="discover-native-vault"){const row2=allRows().find(item=>item.source==="obsidian");if(Object.keys(body).length!==2||body.source!=="obsidian"||!row2||!authorization?.configureNativeFiles){reply(response,400,{error:"invalid_request"});return}if(closed){reply(response,410,{error:"closed"});return}const result=await discoverNativeVaultCandidates("obsidian");if(closed){reply(response,410,{error:"closed"});return}reply(response,200,{state:result.state,candidates:result.candidates.filter(path=>path.length<=512)});return}if(body.action==="status"){refreshResidentStatus();reply(response,200,report(true));return}if(body.action==="close"){reply(response,200,{...report(),state:"closed"});setImmediate(()=>{void session.close()});return}if(body.action==="cancel"){const row2=allRows().find(item=>item.source===body.source),continuation=typeof body.source==="string"?continuations.get(body.source):void 0,current=continuation?.task??active,cancelStop=continuation?.stop??owned;if(!row2){reply(response,400,{error:"unknown_source"});return}if(closed){reply(response,410,{error:"closed"});return}if(!current||!continuation&&activeSource!==row2.source||!cancelStop){reply(response,409,{error:"verification_not_active",activeSource:activeSource??activeSources.get(ctx)?.source});return}row2.message="Cancelling verification.";row2.nextStep="Please wait.";cancelStop.abort();let finished=false;await Promise.race([current.then(()=>{finished=true}),delay(5e3)]);if(finished&&!closed){row2.state="failed";row2.read="not-attempted";row2.errorCode="aborted";row2.message="Verification was cancelled. You can choose another source.";row2.nextStep="Choose Connect when you are ready to try again."}reply(response,finished?200:202,report(true));return}if(body.action==="configure-zulip"){const row2=allRows().find(item=>item.source==="zulip");if(!authorization?.configureZulip||!row2||body.source!=="zulip"||!validZulipSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Zulip instance URL and email.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZulip(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zulip setup could not be saved.";row2.nextStep="Check the instance URL and email and try again.";return}row2.message="Zulip instance URL and email saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zulip setup could not be saved.";row2.nextStep="Check the instance URL and email and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-freshrss"){const row2=allRows().find(item=>item.source==="freshrss");if(!authorization?.configureFreshRSS||!row2||body.source!=="freshrss"||!validFreshRSSSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the FreshRSS instance URL and username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureFreshRSS(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The FreshRSS setup could not be saved.";row2.nextStep="Check the instance URL and username and try again.";return}row2.message="FreshRSS instance URL and username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The FreshRSS setup could not be saved.";row2.nextStep="Check the instance URL and username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-miniflux"){const row2=allRows().find(item=>item.source==="miniflux");if(!authorization?.configureMiniflux||!row2||body.source!=="miniflux"||!validMinifluxSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Miniflux instance URL and username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureMiniflux(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Miniflux setup could not be saved.";row2.nextStep="Check the instance URL and username and try again.";return}row2.message="Miniflux instance URL and username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Miniflux setup could not be saved.";row2.nextStep="Check the instance URL and username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-mattermost"){const row2=allRows().find(item=>item.source==="mattermost");if(!authorization?.configureMattermost||!row2||body.source!=="mattermost"||!validMattermostSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Mattermost instance URL and username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureMattermost(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Mattermost setup could not be saved.";row2.nextStep="Check the instance URL and username and try again.";return}row2.message="Mattermost instance URL and username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Mattermost setup could not be saved.";row2.nextStep="Check the instance URL and username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-wallabag"){const row2=allRows().find(item=>item.source==="wallabag");if(!authorization?.configureWallabag||!row2||body.source!=="wallabag"||!validWallabagSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Wallabag instance URL and username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureWallabag(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Wallabag setup could not be saved.";row2.nextStep="Check the instance URL and username and try again.";return}row2.message="Wallabag instance URL and username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Wallabag setup could not be saved.";row2.nextStep="Check the instance URL and username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-calcom"){const row2=allRows().find(item=>item.source==="calcom");if(!authorization?.configureCalcom||!row2||body.source!=="calcom"||!validCalcomSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Cal.com username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureCalcom(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Cal.com setup could not be saved.";row2.nextStep="Check the username and try again.";return}row2.message="Cal.com username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Cal.com setup could not be saved.";row2.nextStep="Check the username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-wakatime"){const row2=allRows().find(item=>item.source==="wakatime");if(!authorization?.configureWakatime||!row2||body.source!=="wakatime"||!validWakatimeSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the WakaTime username or account ID.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureWakatime(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The WakaTime setup could not be saved.";row2.nextStep="Check the username and try again.";return}row2.message="WakaTime username or account ID saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The WakaTime setup could not be saved.";row2.nextStep="Check the username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-nextcloud"){const row2=allRows().find(item=>item.source==="nextcloud");if(!authorization?.configureNextcloud||!row2||body.source!=="nextcloud"||!validNextcloudInstanceUrl(body.instanceUrl)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Nextcloud instance URL.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureNextcloud(body.instanceUrl,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Nextcloud setup could not be saved.";row2.nextStep="Check the instance URL and try again.";return}row2.message="Nextcloud instance URL saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Nextcloud setup could not be saved.";row2.nextStep="Check the instance URL and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-smartsheet"){const row2=allRows().find(item=>item.source==="smartsheet");if(!authorization?.configureSmartsheet||!row2||body.source!=="smartsheet"||typeof body.region!=="string"||!["us","eu","au"].includes(body.region)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Smartsheet region.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureSmartsheet(body.region,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Smartsheet setup could not be saved.";row2.nextStep="Check the region and try again.";return}row2.message="Smartsheet region saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Smartsheet setup could not be saved.";row2.nextStep="Check the region and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-figma"){const row2=allRows().find(item=>item.source==="figma");if(!authorization?.configureFigma||!row2||body.source!=="figma"||!["fields","oauth"].includes(String(body.selection))){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Figma personal access token mode.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureFigma(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Figma setup could not be saved.";row2.nextStep="Check the personal access token mode and try again.";return}row2.message="Figma connection mode saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Figma setup could not be saved.";row2.nextStep="Check the personal access token mode and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-freshdesk"){const row2=allRows().find(item=>item.source==="freshdesk");if(!authorization?.configureFreshdesk||!row2||body.source!=="freshdesk"||typeof body.subdomain!=="string"||!/^(?:[a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])$/.test(body.subdomain)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Freshdesk tenant.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureFreshdesk(body.subdomain,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Freshdesk setup could not be saved.";row2.nextStep="Check the tenant name and try again.";return}row2.message="Freshdesk tenant saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Freshdesk setup could not be saved.";row2.nextStep="Check the tenant name and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-wechat"){const row2=allRows().find(item=>item.source==="wechat");if(!authorization?.configureWeChat||!row2||body.source!=="wechat"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the WeChat local port.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureWeChat(body.port,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The WeChat setup could not be saved.";row2.nextStep="Check the local port and try again.";return}row2.message="WeChat setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The WeChat setup could not be saved.";row2.nextStep="Check the local port and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-joplin"){const row2=allRows().find(item=>item.source==="joplin");try{if(!authorization?.configureJoplin||!row2||body.source!=="joplin"||body.port!==void 0)throw Error();validateJoplinSelection(body.selection)}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy("joplin")){reply(response,409,{error:"connection_in_progress"});return}const selection=body.selection;if("phase"in selection&&selection.phase==="confirm"&&!invalidateRecoveryEvidence(ctx,"joplin")){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;owned=stop2;interactionGeneration++;activeSource="joplin";activeSources.set(ctx,{source:"joplin",owner:token});const disconnect=()=>{if(!response.writableEnded)stop2.abort()};response.once("close",disconnect);let result={err:{code:"invalid_setup_result"}};active=Promise.resolve().then(async()=>{result=validateJoplinResult(await withSetupProgress("joplin",stop2,()=>authorization.configureJoplin(selection,stop2.signal)))}).catch(()=>{result={err:{code:"pairing_failed"}}}).finally(()=>{response.removeListener("close",disconnect);releaseExecution(stop2)});await active;if(closed||response.destroyed)return;if("err"in result){reply(response,400,{error:"pairing_failed"});return}const pairing=result.ok;if(pairing.state==="configured"){row2.state="pending";row2.read="not-attempted";row2.message="Joplin paired. Note access has not been checked.";row2.nextStep=pairing.next;if(pairing.reloadRequired)reloads.set("joplin",pairing.next)}reply(response,200,{pairing});if(pairing.state==="configured")finishSetup(row2,stop2);return}if(body.action==="configure-thunderbird"){const row2=allRows().find(item=>item.source==="thunderbird");if(!authorization?.configureThunderbird||!row2||body.source!=="thunderbird"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Thunderbird local port.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureThunderbird(body.port,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Thunderbird setup could not be saved.";row2.nextStep="Check the local port and try again.";return}row2.message="Thunderbird setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Thunderbird setup could not be saved.";row2.nextStep="Check the local port and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-dropbox"){const row2=allRows().find(item=>item.source==="dropbox");try{const v=body.selection;if(!authorization?.configureDropbox||!row2||body.source!=="dropbox"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedServiceSource("dropbox",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Dropbox selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureDropbox(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Dropbox setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Dropbox setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Dropbox setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-box"){const row2=allRows().find(item=>item.source==="box");try{const v=body.selection;if(!authorization?.configureBox||!row2||body.source!=="box"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedServiceSource("box",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Box selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureBox(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Box setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Box setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Box setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-front"){const row2=allRows().find(item=>item.source==="front");try{const v=body.selection;if(!authorization?.configureFront||!row2||body.source!=="front"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("front",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Front selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureFront(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Front setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Front setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Front setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-hubspot"){const row2=allRows().find(item=>item.source==="hubspot");try{const v=body.selection;if(!authorization?.configureHubSpot||!row2||body.source!=="hubspot"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("hubspot",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving HubSpot selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureHubSpot(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The HubSpot setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="HubSpot setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The HubSpot setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-google-contacts"){const row2=allRows().find(item=>item.source==="google-contacts");try{const v=body.selection;if(!authorization?.configureGoogleContacts||!row2||body.source!=="google-contacts"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key)))throw Error("invalid");createPreparedServiceSource("google-contacts",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Google Contacts selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureGoogleContacts(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Google Contacts setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Google Contacts setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Google Contacts setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-google-chat"){const row2=allRows().find(item=>item.source==="google-chat");try{const v=body.selection;if(!authorization?.configureGoogleChat||!row2||body.source!=="google-chat"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key)))throw Error("invalid");createPreparedServiceSource("google-chat",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Google Chat selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureGoogleChat(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Google Chat setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Google Chat setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Google Chat setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-salesforce"){const row2=allRows().find(item=>item.source==="salesforce");try{const v=body.selection;if(!authorization?.configureSalesforce||!row2||body.source!=="salesforce"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["environment","clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("salesforce",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Salesforce selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureSalesforce(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Salesforce setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Salesforce setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Salesforce setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-zendesk"){const row2=allRows().find(item=>item.source==="zendesk");if(!authorization?.configureZendesk||!row2||body.source!=="zendesk"||!validZendeskSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Zendesk selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZendesk(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zendesk setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Zendesk setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zendesk setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-zoom"){const row2=allRows().find(item=>item.source==="zoom");try{const v=body.selection;if(!authorization?.configureZoom||!row2||body.source!=="zoom"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId"].includes(key)))throw Error("invalid");createPreparedServiceSource("zoom",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Zoom selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZoom(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zoom setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Zoom setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zoom setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-discord"){const row2=allRows().find(item=>item.source==="discord");try{const v=body.selection;if(!authorization?.configureDiscord||!row2||body.source!=="discord"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Discord selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureDiscord(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Discord setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Discord setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Discord setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-proton-mail"){const row2=allRows().find(item=>item.source==="proton-mail");if(!authorization?.configureProtonMail||!row2||body.source!=="proton-mail"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Proton Mail local port.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureProtonMail(body.port,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Proton Mail setup could not be saved.";row2.nextStep="Check the local port and try again.";return}row2.message="Proton Mail setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Proton Mail setup could not be saved.";row2.nextStep="Check the local port and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-copyq"){const row2=allRows().find(item=>item.source==="copyq");if(!authorization?.configureCopyQ||!row2||body.source!=="copyq"||typeof body.executable!=="string"||body.executable.length<1||body.executable.length>512||body.executable.includes("\0")||!isAbsolute(body.executable)||typeof body.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(body.session)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the CopyQ application and session.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureCopyQ(body.executable,body.session,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The CopyQ setup could not be saved.";row2.nextStep="Check the application path and session and try again.";return}row2.message="CopyQ setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The CopyQ setup could not be saved.";row2.nextStep="Check the application path and session and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-owntracks"){const row2=allRows().find(item=>item.source==="owntracks");if(!authorization?.configureOwnTracks||!row2||body.source!=="owntracks"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the OwnTracks local port.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureOwnTracks(body.port,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The OwnTracks setup could not be saved.";row2.nextStep="Check the local port and try again.";return}row2.message="OwnTracks setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The OwnTracks setup could not be saved.";row2.nextStep="Check the local port and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-zotero"){const row2=allRows().find(item=>item.source==="zotero");if(!authorization?.configureZotero||!row2||body.source!=="zotero"||typeof body.libraryId!=="string"||!(/^[1-9][0-9]{0,19}$/.test(body.libraryId)||body.libraryType==="user"&&body.libraryId==="0")||!["user","group"].includes(String(body.libraryType))){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Zotero library selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZotero(body.libraryId,body.libraryType,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zotero selection could not be saved.";row2.nextStep="Check the library ID and local setup, then try again.";return}row2.message="Zotero selection saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zotero selection could not be saved.";row2.nextStep="Check the local setup, then try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-native-files"){const row2=allRows().find(item=>item.source===body.source),roots=body.roots;if(!authorization?.configureNativeFiles||!row2||typeof body.source!=="string"||!NATIVE_FILE_SOURCES.has(body.source)||!Array.isArray(roots)||roots.length!==1||typeof roots[0]!=="string"||roots[0].length<1||roots[0].length>512||roots[0].includes("\0")||!isAbsolute(roots[0])){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){row2.message="Progress could not be saved on this computer. The folder selection has not been saved.";row2.nextStep="Check that the data folder is writable, then try again.";reply(response,503,report());return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the folder selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureNativeFiles(row2.source,roots,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result){row2.message="The folder selection could not be saved.";row2.nextStep="Check that the folder exists and is accessible, then try again.";return}if(result.ok.state!=="configured"){row2.message="The folder selection needs further setup.";row2.nextStep="Check the folder and its permissions, then try again.";return}row2.message="Folder selection saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The folder selection could not be saved.";row2.nextStep="Check that the folder exists and is accessible, then try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}const pendingReload=allRows().find(item=>item.source===body.source);if(pendingReload&&reloads.has(pendingReload.source)&&!closed&&!active){retainSetupReload(pendingReload);reply(response,200,report(true));return}const other=others.find(item=>item.source===body.source),row=rows.find(item=>item.source===body.source)??(other&&!other.catalogOnly&&connectableOther(other)&&["connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved"].includes(body.action)?other:void 0);if(!row||row.source==="joplin"&&body.action!=="read"||row.registration==="deferred"){reply(response,400,{error:"unknown_source"});return}if(closed){reply(response,410,{error:"closed"});return}if(continuations.has(row.source)){reply(response,200,report(true));return}if(active){reply(response,activeSource===row.source?200:409,activeSource===row.source?report(true):{error:"connection_in_progress",activeSource});return}if(activeSources.has(ctx)){reply(response,409,{error:"connection_in_progress",activeSource:activeSources.get(ctx)?.source});return}if(busy(row.source)){reply(response,409,{error:"connection_in_progress",activeSource:row.source});return}if(row.state==="unavailable"){reply(response,409,{error:"source_unavailable"});return}if(body.action==="reconnect-saved"&&!supportsSavedReconnect(row.source)){reply(response,400,{error:"saved_reconnect_unsupported"});return}if(body.action==="authorize"&&["google-chrome","microsoft-edge"].includes(row.source)){reply(response,400,{error:"authorization_not_supported"});return}if(!invalidateRecoveryEvidence(ctx,row.source)){fail(row);row.message="Progress could not be saved on this computer. A new connection has not been started.";row.nextStep="Check that the data folder is writable, then try again.";reply(response,503,report());return}const repairLegacyClient=row.errorCode==="authorization_client_registration_required";const stop=new AbortController;interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});delete row.errorCode;row.state="connecting";row.read="not-attempted";row.message="Preparing to connect.";if(!other||SIGNED_IN_SOURCES.has(row.source))row.nextStep="Please wait. You do not need to click again.";startRecovery(row,stop,body.action==="authorize"||body.action==="authorize-readwise-mcp"||body.action==="authorize-gmail-write",body.action==="read",repairLegacyClient,body.action==="reconnect-saved",body.action==="authorize-readwise-mcp",body.action==="authorize-gmail-write");reply(response,202,report(true))}server.requestTimeout=5e3;server.headersTimeout=5e3;server.keepAliveTimeout=1e3;await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error("Recovery listener unavailable.");origin=`http://127.0.0.1:${address.port}`;const timer=setTimeout(()=>{void session.close()},18e5);timer.unref();const gone=setInterval(()=>{if(lastSeen&&!active&&!continuations.size&&Date.now()-lastSeen>pageGoneMs)void session.close()},Math.min(15e3,Math.max(50,pageGoneMs/4)));gone.unref();const session={url:origin+"/#"+token,expiresAt,done,closed:closedPromise,snapshot:()=>report(),close(){return closeTask??=(async()=>{closed=true;clearTimeout(timer);clearInterval(gone);owned?.abort();for(const pending of continuations.values())pending.stop.abort();for(const row of allRows()){clearHandoff(row);if(waiting.has(row.state)){row.state="pending";row.message="This help session has ended.";row.nextStep=""}}server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()));let waitTimer;await Promise.race([Promise.all([active,...[...continuations.values()].map(item=>item.task)]),new Promise(resolve=>{waitTimer=setTimeout(resolve,1e3)})]);if(waitTimer)clearTimeout(waitTimer);if(!active&&activeSources.get(ctx)?.owner===token)activeSources.delete(ctx);sessions.delete(ctx);if(!settled){settled=true;resolveDone()}resolveClosed()})()}};ctx.effect(()=>()=>session.close());complete();return session}
1
+ import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{validateJoplinSelection,validateJoplinResult}from"./joplin-selection.js";import{BROWSER_CONNECTION_DIAGNOSTICS,browserRecoveryErrorCode}from"@zortexhq/plugin-oauth-browser-driver/api";import{SETUP_RELOAD_NEXT}from"./setup-activation.js";import{createPreparedDiscordSource,createPreparedServiceSource,createPreparedWorkSource}from"@zortexhq/plugin-connector-level1";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{authorizationImage}from"@zortexhq/plugin-connector-core/api";import{createServer}from"node:http";import{randomBytes,randomUUID,timingSafeEqual}from"node:crypto";import{setTimeout as delay}from"node:timers/promises";import{isAbsolute}from"node:path";import{withFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{startupHistory}from"./startup.js";import{readOnboardingReport}from"./onboarding.js";import{HELP_CATALOG}from"./source-catalog.js";import{recoveryLaunch}from"./recovery-launch.js";import{recoverySurface}from"./recovery-surface.js";import{sourceSupport,recoverySetupFlags}from"./recovery-support.js";import{protectedRecoveryFormUrl,reviewedRecoveryAuthorizationUrl}from"./recovery-authorization-url.js";import{discoverNativeVaultCandidates}from"./native-vault-discovery.js";import{readRecoveryEvidence,saveRecoveryCheck,invalidateRecoveryEvidence,safeRecoverySource}from"./recovery-evidence.js";import{readPublicActionProgress}from"./public-action-progress.js";import{beginRecoveryProgress,readRecoveryProgress}from"./recovery-progress.js";export async function keepRecoverySurfaceOpen(session,opened,signal){if(opened&&!signal.aborted&&session.snapshot().state!=="closed")await session.closed}const NATIVE_FILE_SOURCES=new Set(["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"]);const MAX_RECOVERY_REQUEST_BYTES=64*1024;const PUBLIC_ERROR_CODES=new Set([...BROWSER_CONNECTION_DIAGNOSTICS,"unknown","account_identity_unavailable","aborted","interrupted","unavailable","failed_precondition","permission_denied","unauthenticated","not_found","data_loss","deadline_exceeded","resource_exhausted","authorization_timeout","authorization_denied","google_connection_failed","automatic_authorization_unavailable","page_accessibility_unavailable","requested_account_row_unavailable","requested_account_chooser_not_shown","requested_account_not_selected","youtube_requested_account_identity_unavailable","google_unverified_app","helper_unavailable","helper_timeout","login_required","qr_scan_required","pairing_timeout","notion_page_selection_required","browser_session_unavailable","extension_command_timeout","credentials_required","automatic_authorization_unsupported","browser_driver_unavailable","authorization_client_registration_failed","authorization_client_registration_required","authorization_callback_unavailable","authorization_callback_rejected","authorization_token_exchange_failed","authorization_credential_validation_failed","authorization_scope_mismatch","authorization_credential_storage_failed","authorization_registration_unavailable","authorization_client_configuration_required","configuration_reload_required","authorization_https_redirect_required","device_authorization_unavailable","browser_agent_continuation","browser_session_limit"]);const PENDING_HELP={"configuration-required":["This source needs configuration before it can be registered.","Complete this app\u2019s local setup with the available tools, then resume its connection. Other apps remain usable."],"authorization-required":["This source needs authorization before it can be registered.","Continue enrollment with the available browser or computer tools."],"ambiguous-account":["More than one account could be used for this source.","Use the task context and saved binding to identify the account, then continue connecting."],"ambiguous-resource":["More than one data resource could be used for this source.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."],"custody-unavailable":["The source authorization store is unavailable.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."]};export function validateNativeFileResult(source,result){if(result&&typeof result==="object"&&"ok"in result){const value=result.ok;if(value&&typeof value==="object"&&"source"in value&&value.source===source&&"state"in value&&typeof value.state==="string"&&["configured","configuration-required","permission-required","unavailable"].includes(value.state)&&"reloadRequired"in value&&typeof value.reloadRequired==="boolean"&&"next"in value&&typeof value.next==="string"&&(!("enabled"in value)||typeof value.enabled==="boolean"))return{ok:value}}if(result&&typeof result==="object"&&"err"in result&&result.err&&typeof result.err==="object"&&"code"in result.err&&typeof result.err.code==="string")return{err:{code:result.err.code}};return{err:{code:"invalid_resident_response"}}}const sessions=new WeakMap;const pendingSetupReloads=new WeakMap;const activeSources=new WeakMap;export function activeRecoverySource(ctx){return activeSources.get(ctx)?.source}const waiting=new Set(["connecting","waiting-user","reading"]);function authorizationHelp(code,_source){if(code==="chrome_endpoint_missing")return["Chrome is not exposing a connection endpoint for Zortex.","Open Chrome with the available computer tools, complete its connection setup and resume this source."];if(code==="chrome_endpoint_unreadable"||code==="chrome_endpoint_invalid")return["Zortex could not read a valid Chrome connection endpoint.","Repair Chrome\u2019s local connection configuration and access, then resume this source. Website sign-in is not the cause of this endpoint failure."];if(code==="chrome_connection_timeout")return["Chrome did not finish establishing the connection to Zortex.","Inspect Chrome with the available computer tools, complete its pending connection step or repair the local endpoint, then resume."];if(code==="chrome_connection_closed"||code==="chrome_connection_required")return["The connection between Zortex and Chrome is unavailable.","Recover the local Chrome connection and retry the read. Website sign-in has not been checked."];if(code==="chrome_protocol_timeout")return["Chrome connected, but did not respond to a browser operation in time.","Recover the browser operation and retry the read. Website sign-in has not been checked."];if(code==="chrome_protocol_failed")return["Chrome rejected a browser operation required to read this source.","Check the browser operation and available Chrome support, repair the route and retry. Website sign-in has not been checked."];if(code==="chrome_page_failed")return["Chrome could not load or read the source page.","Inspect the source page with the available browser tools and retry the read after recovering the page."];if(code==="browser_session_unavailable")return["Zortex could not connect to Chrome. The website sign-in state has not been checked.","Recover Chrome and its local connection with the available browser or computer tools, then resume this source. Existing data and credentials are preserved."];if(code==="failed_precondition")return["The connection prerequisites could not be verified.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."];if(code==="authorization_callback_unavailable")return["The saved authorization callback is already in use. Existing credentials are preserved.","Inspect the existing callback owner and continue that transaction. Start a replacement only after the previous owner has settled."];if(code==="authorization_client_registration_required")return["A new authorization cannot start with this installation\u2019s saved OAuth client. Existing credentials are preserved.","Repair the saved OAuth client\u2019s missing or incompatible callback details, then continue connecting."];if(code==="configuration_reload_required")return["Settings saved; connection has not been verified.",SETUP_RELOAD_NEXT];if(code==="authorization_client_configuration_required")return["This provider requires an OAuth client configuration that this connector does not currently have. No sign-in link was created.","Configure a supported OAuth client or connection service with the available setup tools, then resume this source."];if(code==="authorization_client_registration_failed")return["The provider could not register this installation\u2019s OAuth client. No sign-in link was created.","Repair the provider registration endpoint or client settings, then resume enrollment."];if(code==="authorization_registration_unavailable")return["This provider has no supported OAuth client registration configured. No sign-in link was created.","Configure a supported OAuth client through the available setup path, then resume enrollment."];if(code==="authorization_https_redirect_required")return["This provider requires an HTTPS callback that this local connection flow does not provide.","Configure the connector\u2019s supported HTTPS callback path before resuming enrollment."];if(code==="device_authorization_unavailable")return["The provider did not return a usable device authorization challenge. No sign-in code is available.","Repair the device authorization endpoint or client settings, then request a new challenge."];if(code==="credentials_required")return["This source needs credentials entered on its protected local connection page.","Use the protected local connection page and configured credential source. Request missing credential input only when the available tools cannot supply it; keep credentials out of chat."];if(code==="automatic_authorization_unsupported")return["This source has no dedicated automatic authorization driver.","Continue on the connection page with the available browser or computer tools, then check source readiness."];if(code==="browser_driver_unavailable"||code==="helper_unavailable")return["An installed helper needed by this app is unavailable.","Repair the installed helper with the available setup tools, then resume this source."]}function reason(code,source){const help=authorizationHelp(code,source);if(help)return help[0];if(code==="page_accessibility_unavailable")return"Zortex could not complete the authorization page automatically.";if(["requested_account_row_unavailable","requested_account_chooser_not_shown","requested_account_not_selected","youtube_requested_account_identity_unavailable"].includes(code??""))return"Zortex could not automatically identify the account to connect.";if(code==="authorization_denied"||code==="aborted"||code==="interrupted")return"Sign-in or authorization was not completed.";if(code==="authorization_timeout"||code==="deadline_exceeded")return"Authorization timed out. The previous link has expired.";if(code==="permission_denied")return"The current authorization does not include the required permissions.";if(code==="account_identity_unavailable")return"Zortex could not verify which account is signed in to this app.";if(code==="login_required")return source&&(SIGNED_IN_SOURCES.has(source)||["x","instagram","linkedin"].includes(source))?"No signed-in session was found for this site in Chrome on this computer.":"The provider reported that a signed-in session is required.";if(code==="qr_scan_required")return"WhatsApp needs a one-time QR scan from your phone.";if(code==="pairing_timeout")return"The WhatsApp QR code was not scanned in time.";return"Connection or reading did not finish. Your data and existing connections are saved."}const SIGNED_IN_SOURCES=new Set(["steam","reddit","spotify"]);const SITE_SIGN_IN=Object.freeze({x:"https://x.com/i/flow/login",instagram:"https://www.instagram.com/accounts/login/",linkedin:"https://www.linkedin.com/login",steam:"https://steamcommunity.com/login/home/",reddit:"https://www.reddit.com/login/",spotify:"https://accounts.spotify.com/login"});export function connectableOther(row){return row.state!=="unavailable"}const OTHER_HELP={steam:["Steam is not connected yet.","Continue Steam Community sign-in with the available browser tools, then check its profile read."],reddit:["Reddit is not connected yet.","Continue Reddit sign-in with the available browser tools, then check its read."],spotify:["Spotify is not connected yet.","Continue Spotify Web sign-in with the available browser tools, then check its read."],"google-tasks":["Google Tasks has not been verified on this computer yet.","Reuse the saved Google connection or continue sign-in with the available tools, then check Tasks."],"netease-mail":["NetEase Mail needs an IMAP authorization code.","Use the available mail settings and protected connection page to configure IMAP, then continue enrollment. Request the code only if it cannot be obtained through available tools."],notebooklm:["NotebookLM needs a Google sign-in in its connection browser.","Continue the Google connection page with the available browser or computer tools."],stripe:["Stripe needs a provider connection.","Complete the requested connection on Stripe\u2019s page with the available browser tools."],openrouter:["OpenRouter needs a provider connection.","Complete the requested connection on OpenRouter\u2019s page with the available browser tools."],calendly:["Calendly has not been verified on this computer yet.","Reuse the saved connection or continue Calendly sign-in with the available tools, then check its Actions."],shopify:["Shopify needs store and application configuration.","Find the requested store and configure its application through the available provider tools, then continue on the protected local connection page."],activitywatch:["ActivityWatch needs its local service running on this computer.","Start or repair the local ActivityWatch service with the available computer tools, then verify the source read."]};function currentReadinessRow(state){const proof=state.readiness;if(state.state!=="connected"||state.verification||state.registration||!proof||!Number.isSafeInteger(proof.actions)||proof.actions<1)return;if(!proof.operation||!["not-run","succeeded"].includes(proof.operation.state))return;const checked=proof.operation.state==="succeeded",returned=proof.operation.state==="succeeded"?proof.operation.returned:void 0;if(returned!==void 0&&(!Number.isSafeInteger(returned)||returned<0))return;const read=returned===void 0?"not-attempted":returned===0?"empty":"first-record";return{connection:"connected",availability:"actions",actions:proof.actions,operation:proof.operation.state,read,state:read==="empty"?"empty":"complete",message:read==="first-record"?"Connected and the first record has been read.":read==="empty"?"The read succeeded, but no data is currently visible.":checked?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.",nextStep:read==="empty"?emptyHelp():"You can start using this source."}}function connectedRow(state){if(state.verification==="configuration-only")return{source:state.source,...typeof state.label==="string"?{label:state.label.slice(0,80)}:{},connection:"unknown",read:"not-attempted",state:"pending",message:"Settings saved; connection has not been verified.",nextStep:"Check the source connection and read its data."};const label=typeof state.label==="string"?state.label.slice(0,80):void 0;return{source:state.source,...label?{label}:{},connection:"connected",read:"not-attempted",state:"pending",message:"Connected. Available actions or data access have not been checked.",nextStep:"Run the readiness check for this connection.",...currentReadinessRow(state)}}function otherRow(state){const unavailable=state.state==="unavailable",[message,nextStep]=OTHER_HELP[state.source]??[`${typeof state.label==="string"?state.label:state.source} is not connected yet.`,"Continue the connection page with the available browser or computer tools."];const label=typeof state.label==="string"?state.label.slice(0,80):void 0;return{source:state.source,...label?{label}:{},connection:unavailable?"unavailable":"not-connected",read:"not-attempted",state:unavailable?"unavailable":"pending",message:unavailable&&typeof state.message==="string"&&!OTHER_HELP[state.source]?state.message.slice(0,300):message,nextStep:unavailable&&!OTHER_HELP[state.source]?"Inspect the source settings and repair the reported setup requirement before continuing.":nextStep}}function emptyHelp(_source){return"You can use this source. An empty result does not require another sign-in."}function safeUrl(source,value,ownedOrigin){try{if(typeof value!=="string"||value.length>24e3)return;const url=new URL(value);const graphDeviceSources=["onedrive","sharepoint","microsoft-planner","onenote"];const graphDeviceUrls=["https://login.microsoft.com/device","https://microsoft.com/devicelogin","https://login.microsoftonline.com/common/oauth2/deviceauth"];const routes={...Object.fromEntries(graphDeviceSources.map(source2=>[source2,graphDeviceUrls])),matrix:["https://account.matrix.org/authorize"],github:["https://github.com/login/device"],"microsoft-todo":["https://login.microsoftonline.com/common/oauth2/v2.0/authorize","https://login.microsoftonline.com/common/oauth2/deviceauth","https://microsoft.com/devicelogin"],gmail:["https://accounts.google.com/o/oauth2/v2/auth"],"google-drive":["https://accounts.google.com/o/oauth2/v2/auth"],"google-calendar":["https://accounts.google.com/o/oauth2/v2/auth"],"google-tasks":["https://accounts.google.com/o/oauth2/v2/auth"],youtube:["https://accounts.google.com/o/oauth2/v2/auth"],slack:["https://slack.com/oauth/v2/authorize"],outlook:["https://login.microsoftonline.com/common/oauth2/v2.0/authorize"],teams:["https://login.microsoftonline.com/common/oauth2/v2.0/authorize"],notion:["https://zortex-auth.pages.dev/notion/authorize","https://api.notion.com/v1/oauth/authorize"]};if(source==="whatsapp-web"&&url.protocol==="http:"&&url.hostname==="127.0.0.1"&&!url.username&&!url.password&&!url.hash&&!url.search&&/^\/[A-Za-z0-9_-]{32}$/.test(url.pathname))return url.href;if(url.protocol==="http:"&&url.hostname==="127.0.0.1"&&!url.username&&!url.password&&!url.hash&&!url.search&&/^\/connect\/[A-Za-z0-9_-]{32}$/.test(url.pathname))return url.href;if(url.protocol==="https:"&&!url.username&&!url.password&&!url.hash&&(routes[source]?.includes(url.origin+url.pathname)||ownedOrigin===url.origin)){if(source==="github"&&routes.github?.includes(url.origin+url.pathname)||(source==="microsoft-todo"||graphDeviceSources.includes(source))&&graphDeviceUrls.includes(url.origin+url.pathname))url.search="";return url.href}}catch{}return}const PAGE_GONE_MS=18e4;function seedRow(seed){const{source}=seed,setup=seed.configuration==="required",connection=setup?"unavailable":seed.connection;const positiveActions=Number.isSafeInteger(seed.actions)&&seed.actions>0;const failed=seed.read==="failed"||!!seed.errorCode||seed.availability==="none"||seed.availability==="actions"&&!positiveActions;const read=failed&&connection!=="unavailable"?"failed":connection==="connected"?seed.read:"not-attempted",actionsReady=connection==="connected"&&!failed&&seed.availability==="actions"&&positiveActions;return{source,connection,read,...seed.errorCode?{errorCode:PUBLIC_ERROR_CODES.has(seed.errorCode)?seed.errorCode:"unknown"}:{},...actionsReady?{availability:"actions",actions:seed.actions,operation:seed.operation??"not-run"}:connection==="connected"&&["first-record","empty"].includes(read)?{availability:"read",operation:"succeeded"}:{},...setup?{configuration:"required"}:{},state:connection==="unavailable"?"unavailable":actionsReady||read==="first-record"?"complete":read==="empty"?"empty":read==="failed"?"failed":"pending",message:setup?"This app still needs local setup.":connection==="unavailable"?"This source is not installed, is disabled, or is currently unavailable.":read==="first-record"?"Connected and the first record has been read.":read==="empty"?"The read succeeded, but no data is currently visible.":actionsReady?seed.operation==="succeeded"?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.":connection==="connected"&&read==="not-attempted"&&!seed.errorCode?"Connected. Available actions or data access have not been checked.":reason(seed.errorCode,source),nextStep:actionsReady||read==="first-record"?"You can start using this source.":read==="empty"?emptyHelp():setup?"Complete this app\u2019s local setup with the available tools, then resume its connection. Other apps remain usable.":connection==="connected"?"Run the readiness check for this connection.":""}}export function startGuidedRecovery(ctx,options){const existing=sessions.get(ctx);if(existing)return existing.then(async session=>{const snapshot=session.snapshot();const changed=snapshot.sources.length!==options.sources.length||options.sources.some(seed=>{const current=snapshot.sources.find(row=>row.source===seed.source),next=seedRow(seed);return!current||["connection","read","availability","actions","operation","configuration","message"].some(key=>current[key]!==next[key])});if(snapshot.state==="closed"||!activeSources.has(ctx)&&!snapshot.sources.concat(snapshot.others).some(row=>waiting.has(row.state))&&changed){await session.close();return startGuidedRecovery(ctx,options)}return session});const pending=createSession(ctx,options).catch(error=>{sessions.delete(ctx);throw error});sessions.set(ctx,pending);return pending}async function createSession(ctx,{sources,pageGoneMs=PAGE_GONE_MS,authorization}){const providerReadinessSources=new Set;if(!Array.isArray(sources)||sources.some(row=>!safeRecoverySource(row.source))||new Set(sources.map(row=>row.source)).size!==sources.length)throw Error("Invalid recovery sources.");if(!!authorization?.status!==!!(authorization?.read||authorization?.check))throw Error("Invalid recovery owner: status and checks must use the same owner.");const rows=sources.map(seed=>{const row=seedRow(seed),label=HELP_CATALOG.find(([source])=>source===seed.source)?.[1];if(label)row.label=label;return row});for(const row of rows)if(row.read==="failed")fail(row,row.errorCode);const others=[];let initialStates;try{initialStates=authorization?.status?await authorization.status(AbortSignal.timeout(15e3)):await ctx.get("zortexConnectorHub")?.status({signal:AbortSignal.timeout(15e3)});if(initialStates&&"ok"in initialStates){for(const state of initialStates.ok)if(!rows.some(row=>row.source===state.source)&&!others.some(row=>row.source===state.source)&&safeRecoverySource(state.source))others.push(state.state==="connected"?connectedRow(state):otherRow(state))}}catch{}if(authorization?.status)for(const row of rows){const state=initialStates&&"ok"in initialStates?initialStates.ok.find(item=>item.source===row.source):void 0;row.connection=state?.verification==="configuration-only"?"unknown":state?.state??"unknown";if(state?.verification==="configuration-only"){clearReadiness(row);delete row.errorCode;row.state="pending";row.message="Settings saved; connection has not been verified.";row.nextStep="Check the source connection and read its data."}else if(row.read==="failed"&&row.connection!=="unavailable"){fail(row,row.errorCode)}else if(row.connection!=="connected"){clearReadiness(row);delete row.errorCode;row.read="not-attempted";row.state=row.connection==="unavailable"?"unavailable":"pending";row.message=row.connection==="unknown"?"Current connection status is unavailable.":reason()}}if(initialStates&&"ok"in initialStates)for(const row of[...rows,...others]){const state=initialStates.ok.find(item=>item.source===row.source);const readiness=state&&currentReadinessRow(state);if(readiness){Object.assign(row,readiness);delete row.errorCode;providerReadinessSources.add(row.source)}else if(state?.verification==="configuration-only"){row.read="not-attempted";delete row.errorCode}if(state?.registration==="deferred"){clearReadiness(row);delete row.errorCode;row.registration="deferred";row.connection="unavailable";row.read="not-attempted";row.state="unavailable";row.message="Setup is required before this connector can be used.";row.nextStep="Complete the setup with the available tools; connection continues when the configuration is active."}}const listed=new Set([...rows,...others].map(row=>row.source));for(const[entry,label]of HELP_CATALOG){const source=entry==="teams"&&!listed.has("teams")?"microsoft-teams":entry;if(!listed.has(source)){others.push({source,label,connection:"unknown",read:"not-attempted",state:"pending",catalogOnly:true,message:"This is a directory entry; registration and connection have not been checked.",nextStep:"Inspect the installed source catalog and enable or configure the source when available."});listed.add(source)}}const token=randomBytes(32).toString("base64url"),nonce=randomBytes(24).toString("base64url");let origin="",closed=false,active,activeSource,owned,settled=false,closeTask;const continuations=new Map,configured=new Set;function releaseExecution(stop){if(owned!==stop)return;owned=void 0;active=void 0;activeSource=void 0;if(activeSources.get(ctx)?.owner===token)activeSources.delete(ctx)}let resolveDone;const done=new Promise(resolve=>{resolveDone=resolve});let resolveClosed;const closedPromise=new Promise(resolve=>{resolveClosed=resolve});const expiresAt=new Date(Date.now()+18e5).toISOString();const allRows=()=>rows.concat(others);const reloads=pendingSetupReloads.get(ctx)??new Map;pendingSetupReloads.set(ctx,reloads);function acceptResidentReload(state){if(state?.reloadRequired===true)reloads.set(state.source,SETUP_RELOAD_NEXT);else if(state?.reloadRequired===false){reloads.delete(state.source);const row=allRows().find(item=>item.source===state.source);if(row)delete row.reloadRequired}}if(initialStates&&"ok"in initialStates)for(const state of initialStates.ok)acceptResidentReload(state);function retainSetupReload(row){const next=reloads.get(row.source);if(next===void 0)return false;clearHandoff(row);clearReadiness(row);row.reloadRequired=true;row.connection="unknown";row.read="not-attempted";row.state="pending";row.message="Settings saved; connection has not been verified.";row.nextStep=next;delete row.errorCode;delete row.authorizationUrl;delete row.deviceUserCode;delete row.authorizationImage;delete row.setupReason;providerReadinessSources.delete(row.source);return true}for(const row of allRows())retainSetupReload(row);async function withSetupProgress(source,stop,configure){const progress=beginRecoveryProgress(ctx,source);progress.update("configuring","unverified");const interrupted=()=>progress.finish({connectionState:"unverified",errorCode:"aborted"});stop.signal.addEventListener("abort",interrupted,{once:true});try{if(stop.signal.aborted){interrupted();return{err:{code:"aborted"}}}const result=await configure();if("ok"in result&&result.ok.state==="configured"){const row=allRows().find(item=>item.source===source);if(result.ok.reloadRequired){reloads.set(source,result.ok.next);if(row)retainSetupReload(row)}else{reloads.delete(source);configured.add(source);if(row){clearReadiness(row);delete row.reloadRequired;delete row.configuration;delete row.registration;delete row.setupReason;row.connection="unknown"}}}progress.finish({connectionState:"unverified",..."err"in result?{errorCode:result.err.code}:result.ok.state!=="configured"?{errorCode:result.ok.state==="unavailable"?"unavailable":"failed_precondition"}:result.ok.reloadRequired?{errorCode:"configuration_reload_required"}:{}});return result}catch(error){progress.finish({connectionState:"unverified",errorCode:"unknown"});throw error}finally{stop.signal.removeEventListener("abort",interrupted)}}const externalProgressSources=new Set;function applyPending(result){if(!result||!("ok"in result))return;const pending=Array.isArray(result.pending)?result.pending:[];for(const row of allRows()){if(externalProgressSources.has(row.source))continue;if(retainSetupReload(row))continue;const item=pending.find(value=>value&&value.source===row.source&&typeof value.reason==="string"&&Object.hasOwn(PENDING_HELP,value.reason));const nextReason=row.connection==="connected"?void 0:item?.reason;if(nextReason===row.setupReason)continue;if(nextReason)row.setupReason=nextReason;else delete row.setupReason;if(nextReason){[row.message,row.nextStep]=PENDING_HELP[nextReason];if(row.registration==="deferred")row.nextStep="Complete the setup with the available tools; connection continues when the configuration is active."}else if(row.catalogOnly){row.message="This is a directory entry; registration and connection have not been checked.";row.nextStep="Inspect the installed source catalog and enable or configure the source when available."}else if(row.connection!=="connected"){row.message="This source is not connected.";row.nextStep="Check the connection and try again."}}}applyPending(initialStates);function evidenceVersions(){const parts=new Map,add=(source,value)=>{parts.set(source,[...parts.get(source)??[],value])};try{const fleet=ctx.get("indraFleet");if(fleet){for(const receipt of startupHistory(fleet).receipts)for(const result of receipt.sources)add(result.source,["receipt",receipt.requestId,result.progress?.startedAt??receipt.startedAt,result.progress?.endedAt,result.state,result.returned,result.error?.code]);for(const progress of fleet.status().sources??[])add(progress.source,["progress",progress.startedAt,progress.endedAt,progress.stage,progress.returned,progress.error?.code])}for(const saved of readRecoveryEvidence(ctx,allRows().map(row=>row.source)).values())add(saved.source,["help",saved.updatedAt,saved.read,saved.returned]);for(const progress of readRecoveryProgress(ctx))add(progress.source,["manual-progress",progress.startedAt,progress.endedAt,progress.stage,progress.connectionState,progress.returned,progress.errorCode,progress.readiness])}catch{return new Map}return new Map([...parts].map(([source,values])=>[source,JSON.stringify(values)]))}const blockedEvidence=new Map,initialEvidence=evidenceVersions();for(const row of allRows())if(row.connection!=="connected")blockedEvidence.set(row.source,initialEvidence.get(row.source));let statusRefresh,lastStatusRefresh=0,interactionGeneration=0;function refreshResidentStatus(){if(active||closed||statusRefresh||Date.now()-lastStatusRefresh<5e3)return;lastStatusRefresh=Date.now();const generation=interactionGeneration;statusRefresh=(async()=>{const versions=evidenceVersions();let states;try{const signal=AbortSignal.timeout(15e3);states=await(authorization?.status?authorization.status(signal):ctx.get("zortexConnectorHub")?.status({signal}))}catch{}const evidenceContext=authorization?.status?{get:name=>name==="zortexConnectorHub"?{status:async()=>states??{err:{code:"unavailable"}}}:ctx.get(name)}:ctx;const progress=versions.size?await readOnboardingReport(evidenceContext,{enabled:true}):void 0;if(active||closed||generation!==interactionGeneration)return;const currentVersions=evidenceVersions();const manualProgress=new Map(readRecoveryProgress(ctx).map(item=>[item.source,item]));if(states&&"ok"in states){for(const state of states.ok)if(safeRecoverySource(state.source)&&!allRows().some(row=>row.source===state.source))others.push(state.state==="connected"?connectedRow(state):otherRow(state))}for(const row of allRows()){if(waiting.has(row.state)&&!externalProgressSources.has(row.source)||busy(row.source))continue;const state=states&&"ok"in states?states.ok.find(item=>item.source===row.source):void 0;acceptResidentReload(state);if(retainSetupReload(row))continue;if(row.catalogOnly&&!state)continue;if(state){delete row.catalogOnly;if(typeof state.label==="string")row.label=state.label.slice(0,80)}const deferred=state?.registration==="deferred",changedRegistration=row.registration==="deferred"!==deferred;if(deferred)row.registration="deferred";else delete row.registration;const external=manualProgress.get(row.source),version=versions.get(row.source);const stableEvidence=version!==void 0&&version===currentVersions.get(row.source);if(!deferred&&state&&external&&external.stage!=="finished"&&stableEvidence){externalProgressSources.add(row.source);blockedEvidence.set(row.source,version);clearReadiness(row);clearHandoff(row);delete row.errorCode;delete row.setupReason;row.connection=state.state;row.read="not-attempted";row.state=external.stage==="configuring"?"connecting":external.stage;row.message=external.stage==="waiting-user"?"The existing connection transaction has an active sign-in page.":external.stage==="reading"?"The current connection is being checked for readable data.":"A connection attempt is in progress.";row.nextStep="Finish the existing connection attempt; this page updates automatically.";continue}const endedExternal=externalProgressSources.delete(row.source);const readiness=state&&currentReadinessRow(state);if(readiness){Object.assign(row,readiness);delete row.errorCode;providerReadinessSources.add(row.source);delete row.setupReason;continue}const lostProviderReadiness=providerReadinessSources.delete(row.source);const next=deferred?"unavailable":state?.verification==="configuration-only"?"unknown":state?.state??(states&&"ok"in states?"unavailable":"unknown");const newEvidence=version!==void 0&&version===currentVersions.get(row.source)&&(!blockedEvidence.has(row.source)||blockedEvidence.get(row.source)!==version);if(next!=="connected"||lostProviderReadiness||row.state==="actions-ready")blockedEvidence.set(row.source,version);const evidence=progress?.sources.find(item=>item.source===row.source);if(next==="not-connected"&&newEvidence&&evidence?.read==="failed"){row.connection=next;delete row.setupReason;fail(row,evidence.errorCode);continue}if(next==="connected"&&evidence?.connection==="connected"&&version!==void 0&&version===currentVersions.get(row.source)&&(!blockedEvidence.has(row.source)||blockedEvidence.get(row.source)!==version)){blockedEvidence.delete(row.source);clearReadiness(row);clearHandoff(row);delete row.setupReason;delete row.errorCode;Object.assign(row,seedRow(evidence));if(evidence.read==="failed")fail(row,evidence.errorCode);continue}if(!endedExternal&&!lostProviderReadiness&&row.state!=="actions-ready"&&row.connection===next&&!changedRegistration&&!(state?.verification==="configuration-only"&&row.message!=="Settings saved; connection has not been verified.")&&!(next==="unknown"&&!state&&row.message==="Settings saved; connection has not been verified."))continue;row.connection=next;clearReadiness(row);clearHandoff(row);delete row.setupReason;row.read="not-attempted";delete row.errorCode;row.state=next==="unavailable"?"unavailable":"pending";row.message=deferred?"Setup is required before this connector can be used.":state?.verification==="configuration-only"?"Settings saved; connection has not been verified.":next==="connected"?"Connected. Check again to verify the current connection.":next==="unknown"?"Current connection status is unavailable.":next==="unavailable"?"This source is currently unavailable.":"This source is not connected.";row.nextStep=deferred?"Complete the setup with the available tools; connection continues when the configuration is active.":state?.verification==="configuration-only"?"Check the source connection and read its data.":next==="connected"?"Check available actions or data access.":"Check the connection and try again."}applyPending(states);complete()})().finally(()=>{statusRefresh=void 0})}const terminal=row=>["complete","empty","actions-ready"].includes(row.state)||row.state==="unavailable"&&row.configuration!=="required"&&row.registration!=="deferred"&&!row.reloadRequired;const complete=()=>{const checked=allRows().filter(row=>!row.catalogOnly);if(!settled&&checked.some(row=>["complete","empty","actions-ready"].includes(row.state))&&checked.every(terminal)){settled=true;resolveDone()}};function report(links=false){const checked=allRows().filter(row=>!row.catalogOnly);const success=checked.length>0&&checked.every(row=>["complete","empty","actions-ready"].includes(row.state)&&row.connection==="connected");const publicReads=new Map(readPublicActionProgress(ctx).map(item=>[item.source,item]));const shown=row=>{const{authorizationUrl,authorizationInstructions,deviceUserCode,authorizationImage:qrImage,authorizationExpiresAt,browserContinuation,...safe}=row;const signInUrl=!closed&&(row.connection!=="connected"||row.errorCode==="login_required")&&["pending","failed"].includes(row.state)&&Object.hasOwn(SITE_SIGN_IN,row.source)?SITE_SIGN_IN[row.source]:void 0;const setup=recoverySetupFlags(row.source,authorization);const support=sourceSupport(row,Object.keys(setup).length>0);const publicRead=publicReads.get(row.source);const registered=!row.catalogOnly&&row.registration!=="deferred"&&row.connection!=="unavailable";const capabilities={...registered&&support.state==="supported"&&!row.reloadRequired&&!["joplin","google-chrome","microsoft-edge"].includes(row.source)&&!waiting.has(row.state)?{authorizationAvailable:true}:{},...registered&&authorization&&row.source==="gmail"?{gmailWriteAvailable:true}:{},...registered&&authorization&&row.source==="readwise"?{readwiseMcpWriteAvailable:true}:{},...registered&&supportsSavedReconnect(row.source)&&(!authorization||typeof authorization.reconnectSaved==="function")?{reconnectSavedAvailable:true}:{}};const publicRow={...safe,...setup,...capabilities,support,...publicRead?{publicRead}:{},...signInUrl?{signInUrl}:{},...links&&row.state==="waiting-user"&&browserContinuation?{browserContinuation}:{},...links&&row.state==="waiting-user"&&authorizationInstructions?{nextStep:authorizationInstructions}:{},...links&&row.state==="waiting-user"&&qrImage?{authorizationImage:{...qrImage}}:{},...links&&row.state==="waiting-user"&&authorizationExpiresAt?{authorizationExpiresAt}:{},...links&&row.state==="waiting-user"&&authorizationUrl?{authorizationUrl,...deviceUserCode?{deviceUserCode}:{}}:{}};if(row.configuration==="required"&&support.reasonCode==="connector_unavailable"){}else if(support.state==="unsupported"){publicRow.state="unavailable";publicRow.message=support.message;publicRow.nextStep=support.nextStep}else if(row.registration==="deferred"||row.connection==="unavailable"){publicRow.message=support.message;publicRow.nextStep=support.nextStep}return publicRow};return{state:closed?"closed":success?"ready":checked.length>0&&checked.every(terminal)?"partial":"recovering",success,sources:rows.map(shown),others:others.map(shown),...activeSource?{activeSource}:{}}}function clearHandoff(row){delete row.browserContinuation;delete row.authorizationUrl;delete row.authorizationInstructions;delete row.deviceUserCode;delete row.authorizationImage;delete row.authorizationExpiresAt}function clearReadiness(row){delete row.availability;delete row.actions;delete row.operation}function fail(row,code){clearHandoff(row);clearReadiness(row);delete row.authorizationUrl;delete row.deviceUserCode;delete row.authorizationImage;if(code)row.errorCode=PUBLIC_ERROR_CODES.has(code)?code:"unknown";else delete row.errorCode;row.state="failed";row.read="failed";if(row.source==="rednote"&&code==="unavailable"){row.message="The local RedNote service is unavailable.";row.nextStep="";return}if(row.source==="activitywatch"&&code==="unavailable"){row.message=OTHER_HELP.activitywatch[0];row.nextStep="";return}if(code==="unavailable"&&["spotify","reddit","steam","x","instagram","linkedin"].includes(row.source)){row.message="Live reading is currently unavailable. The website sign-in state has not been confirmed.";row.nextStep="";return}if(row.connection==="connected"&&code==="failed_precondition"&&["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(row.source)){row.message="Saved Google account access could not be verified.";row.nextStep="";return}const help=authorizationHelp(code,row.source);if(help){[row.message,row.nextStep]=help;return}row.message=reason(code,row.source);row.nextStep=""}function busy(source){return continuations.has(source)||(ctx.get("indraFleet")?.status().activeSources?.includes(source)??false)}async function run(row,stop,forceAuthorization,readOnly,repairLegacyClient=false,savedAccessOnly=false,readwiseMcpWrite=false,gmailWrite=false){const progress=beginRecoveryProgress(ctx,row.source);let returned,readiness,ownsFlow=true;const interrupted=()=>progress.finish({connectionState:row.connection==="connected"?"connected":"unverified",errorCode:"aborted"});stop.signal.addEventListener("abort",interrupted,{once:true});const hub=ctx.get("zortexConnectorHub");try{stop.signal.throwIfAborted();if(!hub){fail(row);return}const states=authorization?.status?await authorization.status(stop.signal):await hub.status({signal:stop.signal});stop.signal.throwIfAborted();if(!("ok"in states)){row.connection="unknown";fail(row);return}const state=states.ok.find(item=>item.source===row.source);if(!state||state.state==="unavailable"){row.state="unavailable";row.connection="unavailable";row.message="This source is not installed, is disabled, or is currently unavailable.";row.nextStep="Inspect the source settings and complete the available setup before resuming its connection.";return}delete row.catalogOnly;row.connection=state.state;if(readOnly&&state.state!=="connected"){fail(row,"unauthenticated");return}if(savedAccessOnly){const result2=authorization?await authorization.reconnectSaved?.(row.source,stop.signal):await hub.connect(row.source,{signal:stop.signal,retention:"transient",automatic:true,savedAccessOnly:true});if(!result2||!("ok"in result2)||result2.ok.source!==row.source||result2.ok.state!=="connected"){const code=result2&&"ok"in result2&&result2.ok.source===row.source&&result2.ok.state==="failed"?result2.ok.error?.code:void 0;fail(row,result2&&"err"in result2?browserRecoveryErrorCode(result2.err):code??"failed_precondition");return}row.connection="connected"}else if(state.state!=="connected"||forceAuthorization){const started=Date.now(),requestId=randomUUID();let residentOwned=false;const selectAccount=forceAuthorization&&!gmailWrite&&["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(row.source);const reauthorize=forceAuthorization&&repairLegacyClient&&["todoist","linear"].includes(row.source);const settings={manualPresentation:"return-url",...gmailWrite?{gmailWrite:true}:{},...readwiseMcpWrite?{readwiseMcpWrite:true}:{},...selectAccount?{selectAccount:true}:{},...reauthorize?{reauthorize:true}:{}};const result2=authorization?await authorization.connect(row.source,requestId,stop.signal,settings):await hub.connect(row.source,{signal:stop.signal,retention:"transient",automatic:false,...settings});residentOwned=!!authorization;if(!("ok"in result2)){fail(row,"err"in result2?browserRecoveryErrorCode(result2.err):"data_loss");return}let job=result2.ok,cancellation;const cancelResidentAuthorization=()=>{const current=job;if(!residentOwned||current.state!=="waiting-user"||!Number.isSafeInteger(current.generation)||typeof current.challengeRef!=="string"||!current.challengeRef)return;return cancellation??=authorization.cancel(requestId,current.generation,current.challengeRef).then(()=>void 0,()=>void 0)};try{stop.signal.throwIfAborted();if(!residentOwned&&job.state==="waiting-user"&&(!Number.isFinite(Date.parse(job.startedAt))||Date.parse(job.startedAt)<started)){ownsFlow=false;releaseExecution(stop);row.state="pending";row.message="Another sign-in is still waiting for authorization.";row.nextStep="Continue the existing transaction through its owning session, then check this source again.";return}const id=job.id;while(!stop.signal.aborted){if(job.id!==id||job.source!==row.source){fail(row);return}clearHandoff(row);if(job.state==="connected"){row.connection="connected";break}if(job.state!=="waiting-user"){fail(row,job.state==="cancelled"?"aborted":job.error?.code);return}if(row.source==="whatsapp-web"){row.state="waiting-user";row.message="Waiting for you to scan the QR code with WhatsApp on your phone.";row.nextStep="Settings \u2192 Linked devices \u2192 Link a device. The latest message will be read automatically after the scan. If you closed the page, use the link below to reopen it."}else{row.state="waiting-user";row.message="Authorization is in progress.";row.nextStep="Please wait. You do not need to click again."}if(typeof job.expiresAt==="string"&&Number.isFinite(Date.parse(job.expiresAt)))row.authorizationExpiresAt=new Date(job.expiresAt).toISOString();const qrImage=authorizationImage(job.authorizationImage);if(qrImage){row.authorizationImage=qrImage;if(row.source!=="whatsapp-web"){row.message="The provider returned a QR authorization challenge.";row.nextStep=""}}const url=safeUrl(row.source,job.authorizationUrl,residentOwned?job.authorizationOrigin:void 0)??reviewedRecoveryAuthorizationUrl(row.source,job)??protectedRecoveryFormUrl(row.source,job,residentOwned);if(url){row.authorizationUrl=url;const prompt=job.devicePrompt;if(prompt?.kind==="device-code"&&typeof prompt.userCode==="string"&&/^[A-Z0-9-]{4,32}$/i.test(prompt.userCode))row.deviceUserCode=prompt.userCode}if(residentOwned&&typeof job.instructions==="string"&&job.instructions.trim()&&Buffer.byteLength(job.instructions)<=2048&&!/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u.test(job.instructions))row.authorizationInstructions=job.instructions;if(url||qrImage||row.authorizationInstructions){row.state="waiting-user";if(row.source!=="whatsapp-web"&&!qrImage){row.message="The connection page has an active sign-in or access step.";row.nextStep="Continue the live page with the available browser or computer tools. Request missing input only if those tools cannot complete the step."}}if(job.browserContinuation){row.browserContinuation=job.browserContinuation;row.nextStep="Continue the retained browser session through the browser-use Actions. Use browser.observe with its sessionId, then the returned controls with browser.click or browser.type. Keep polling this authorization job; only provider verification marks it connected."}progress.update(row.state,"unverified");if(residentOwned&&job.automationActive!==true)releaseExecution(stop);try{await delay(250,void 0,{signal:stop.signal})}catch(error){await cancelResidentAuthorization();throw error}const next=authorization?await authorization.job(requestId,stop.signal):hub.job(id);if(!("ok"in next)){fail(row);return}job=next.ok}}finally{if(stop.signal.aborted)await cancelResidentAuthorization()}}while(active&&owned!==stop)await delay(50,void 0,{signal:stop.signal});stop.signal.throwIfAborted();owned=stop;activeSource=row.source;active=continuations.get(row.source)?.task;activeSources.set(ctx,{source:row.source,owner:token});clearHandoff(row);row.state="reading";row.message="Connection confirmed. Checking available actions or data access.";row.nextStep="Checking available actions or data access.";progress.update("reading","connected");const result=authorization?.check?await authorization.check(row.source,stop.signal):authorization?.read?await authorization.read(row.source,{limit:1},stop.signal).then(result2=>"ok"in result2?{ok:{source:row.source,basis:"read",operation:{state:"succeeded",returned:result2.ok.returned}}}:"empty"in result2?{ok:{source:row.source,basis:"read",operation:{state:"succeeded",returned:0}}}:result2):await hub.check(row.source,{signal:stop.signal,retention:"transient"});stop.signal.throwIfAborted();if(!("ok"in result)){fail(row,"err"in result?browserRecoveryErrorCode(result.err):void 0);return}const check=result.ok;if(check.source!==row.source||check.basis==="actions"&&(!Number.isSafeInteger(check.actions)||check.actions<=0)){fail(row);return}if(!saveRecoveryCheck(ctx,check)){fail(row);row.message="Connection was checked, but progress could not be saved on this computer.";row.nextStep="Repair access to the data folder, then repeat the readiness check. The connection is saved.";return}readiness=check;if(check.basis==="actions"&&authorization?.status)providerReadinessSources.add(row.source);delete row.errorCode;row.availability=check.basis;row.operation=check.operation.state;if(check.basis==="actions")row.actions=check.actions;else delete row.actions;returned=check.operation.state==="succeeded"?check.operation.returned:void 0;row.read=returned===void 0?"not-attempted":returned>0?"first-record":"empty";row.state=row.read==="empty"?"empty":"complete";row.message=row.read==="first-record"?"Connected and the first record has been read.":row.read==="empty"?"The read succeeded, but no data is currently visible.":row.operation==="succeeded"?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.";row.nextStep=row.read==="empty"?emptyHelp():"This source is ready to use."}catch{if(!closed)fail(row,stop.signal.aborted?"aborted":void 0)}finally{progress.finish({connectionState:row.connection==="connected"?"connected":"unverified",...readiness&&!stop.signal.aborted&&["complete","empty"].includes(row.state)?{readiness}:{},...returned!==void 0?{returned}:{},...["failed","unavailable","pending"].includes(row.state)?{errorCode:row.errorCode??(row.state==="unavailable"?"unavailable":"unknown")}:{}});stop.signal.removeEventListener("abort",interrupted);clearHandoff(row);releaseExecution(stop);if(ownsFlow)stop.abort();complete()}}function startRecovery(row,stop,forceAuthorization=false,readOnly=false,repairLegacyClient=false,savedAccessOnly=false,readwiseMcpWrite=false,gmailWrite=false){interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});const task=Promise.resolve().then(()=>withFeedbackFlow(row.source,()=>run(row,stop,forceAuthorization,readOnly,repairLegacyClient,savedAccessOnly,readwiseMcpWrite,gmailWrite),{flowId:randomUUID(),source:row.source,mode:"manual",trigger:"tool"})).catch(()=>{if(!closed)fail(row)}).finally(()=>{if(continuations.get(row.source)?.stop===stop)continuations.delete(row.source);releaseExecution(stop)});continuations.set(row.source,{stop,task});active=task}function finishSetup(row,stop){releaseExecution(stop);if(configured.delete(row.source)&&!closed&&!stop.signal.aborted)startRecovery(row,stop);else stop.abort()}function reply(response,status,value){response.writeHead(status,{"Content-Type":"application/json; charset=utf-8"}).end(JSON.stringify(value))}const server=createServer((request,response)=>{void handle(request,response).catch(()=>{if(!response.headersSent)reply(response,500,{error:"request_failed"});else response.end()})});let lastSeen=0;async function handle(request,response){response.setHeader("Cache-Control","no-store");response.setHeader("Referrer-Policy","no-referrer");response.setHeader("X-Content-Type-Options","nosniff");response.setHeader("Content-Security-Policy",`default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`);if(request.headers.host!==new URL(origin).host){reply(response,403,{error:"forbidden"});return}if(request.method==="GET"&&request.url==="/"){response.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}).end(recoveryLaunch(nonce));return}if(request.method!=="POST"||!["/api","/open"].includes(request.url??"")){reply(response,404,{error:"not_found"});return}const received=request.headers["x-zortex-recovery"];if(request.headers.origin!==origin||typeof received!=="string"||Buffer.byteLength(received)!==Buffer.byteLength(token)||!timingSafeEqual(Buffer.from(received),Buffer.from(token))){reply(response,403,{error:"forbidden"});return}lastSeen=Date.now();if(request.headers["content-type"]!=="application/json"){reply(response,415,{error:"json_required"});return}if(Number(request.headers["content-length"]??0)>MAX_RECOVERY_REQUEST_BYTES){request.resume();reply(response,413,{error:"too_large"});return}let bytes=0;const chunks=[];for await(const chunk of request){bytes+=chunk.length;if(bytes>MAX_RECOVERY_REQUEST_BYTES){reply(response,413,{error:"too_large"});return}chunks.push(chunk)}let body;try{body=JSON.parse(Buffer.concat(chunks).toString("utf8"))}catch{reply(response,400,{error:"invalid_request"});return}if(request.url==="/open"){if(!body||typeof body!=="object"||Array.isArray(body)||Object.keys(body).length){reply(response,400,{error:"invalid_request"});return}if(closed){reply(response,410,{error:"closed"});return}let current=session;const request2=async(input,signal)=>{if(current.snapshot().state==="closed")current=await startGuidedRecovery(ctx,{sources,pageGoneMs,...authorization?{authorization}:{}});return current.request(input,signal)};const url=await recoverySurface(ctx,{request:request2,snapshot:()=>current.snapshot(),...authorization?{authorization}:{},...sources.length===1?{source:sources[0].source}:{}});if(closed){reply(response,410,{error:"closed"});return}reply(response,200,{url});return}if(!body||typeof body!=="object"||Array.isArray(body)||Object.keys(body).some(key=>!["action","source","roots","libraryId","libraryType","port","executable","session","subdomain","region","instanceUrl","selection"].includes(key))||!["status","connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved","cancel","close","discover-native-vault","configure-native-files","configure-zotero","configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-copyq","configure-freshdesk","configure-smartsheet","configure-figma","configure-nextcloud","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))||!["connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved","cancel","discover-native-vault","configure-native-files","configure-zotero","configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-copyq","configure-freshdesk","configure-smartsheet","configure-figma","configure-nextcloud","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))&&body.source!==void 0||body.action!=="configure-native-files"&&body.roots!==void 0||body.action!=="configure-zotero"&&(body.libraryId!==void 0||body.libraryType!==void 0)||!["configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail"].includes(String(body.action))&&body.port!==void 0||body.action!=="configure-copyq"&&(body.executable!==void 0||body.session!==void 0)||body.action!=="configure-freshdesk"&&body.subdomain!==void 0||body.action!=="configure-smartsheet"&&body.region!==void 0||body.action!=="configure-nextcloud"&&body.instanceUrl!==void 0||!["configure-joplin","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-figma","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))&&body.selection!==void 0){reply(response,400,{error:"invalid_request"});return}if(body.action==="authorize-readwise-mcp"&&(body.source!=="readwise"||Object.keys(body).length!==2)){reply(response,400,{error:"invalid_request"});return}if(body.action==="authorize-gmail-write"&&(body.source!=="gmail"||Object.keys(body).length!==2)){reply(response,400,{error:"invalid_request"});return}if(body.action==="discover-native-vault"){const row2=allRows().find(item=>item.source==="obsidian");if(Object.keys(body).length!==2||body.source!=="obsidian"||!row2||!authorization?.configureNativeFiles){reply(response,400,{error:"invalid_request"});return}if(closed){reply(response,410,{error:"closed"});return}const result=await discoverNativeVaultCandidates("obsidian");if(closed){reply(response,410,{error:"closed"});return}reply(response,200,{state:result.state,candidates:result.candidates.filter(path=>path.length<=512)});return}if(body.action==="status"){refreshResidentStatus();reply(response,200,report(true));return}if(body.action==="close"){reply(response,200,{...report(),state:"closed"});setImmediate(()=>{void session.close()});return}if(body.action==="cancel"){const row2=allRows().find(item=>item.source===body.source),continuation=typeof body.source==="string"?continuations.get(body.source):void 0,current=continuation?.task??active,cancelStop=continuation?.stop??owned;if(!row2){reply(response,400,{error:"unknown_source"});return}if(closed){reply(response,410,{error:"closed"});return}if(!current||!continuation&&activeSource!==row2.source||!cancelStop){reply(response,409,{error:"verification_not_active",activeSource:activeSource??activeSources.get(ctx)?.source});return}row2.message="Cancelling verification.";row2.nextStep="Please wait.";cancelStop.abort();let finished=false;await Promise.race([current.then(()=>{finished=true}),delay(5e3)]);if(finished&&!closed){row2.state="failed";row2.read="not-attempted";row2.errorCode="aborted";row2.message="Verification was cancelled. You can choose another source.";row2.nextStep="Choose Connect when you are ready to try again."}reply(response,finished?200:202,report(true));return}if(body.action==="configure-zulip"){const row2=allRows().find(item=>item.source==="zulip");if(!authorization?.configureZulip||!row2||body.source!=="zulip"||!validZulipSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Zulip instance URL and email.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZulip(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zulip setup could not be saved.";row2.nextStep="Check the instance URL and email and try again.";return}row2.message="Zulip instance URL and email saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zulip setup could not be saved.";row2.nextStep="Check the instance URL and email and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-freshrss"){const row2=allRows().find(item=>item.source==="freshrss");if(!authorization?.configureFreshRSS||!row2||body.source!=="freshrss"||!validFreshRSSSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the FreshRSS instance URL and username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureFreshRSS(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The FreshRSS setup could not be saved.";row2.nextStep="Check the instance URL and username and try again.";return}row2.message="FreshRSS instance URL and username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The FreshRSS setup could not be saved.";row2.nextStep="Check the instance URL and username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-miniflux"){const row2=allRows().find(item=>item.source==="miniflux");if(!authorization?.configureMiniflux||!row2||body.source!=="miniflux"||!validMinifluxSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Miniflux instance URL and username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureMiniflux(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Miniflux setup could not be saved.";row2.nextStep="Check the instance URL and username and try again.";return}row2.message="Miniflux instance URL and username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Miniflux setup could not be saved.";row2.nextStep="Check the instance URL and username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-mattermost"){const row2=allRows().find(item=>item.source==="mattermost");if(!authorization?.configureMattermost||!row2||body.source!=="mattermost"||!validMattermostSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Mattermost instance URL and username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureMattermost(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Mattermost setup could not be saved.";row2.nextStep="Check the instance URL and username and try again.";return}row2.message="Mattermost instance URL and username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Mattermost setup could not be saved.";row2.nextStep="Check the instance URL and username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-wallabag"){const row2=allRows().find(item=>item.source==="wallabag");if(!authorization?.configureWallabag||!row2||body.source!=="wallabag"||!validWallabagSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Wallabag instance URL and username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureWallabag(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Wallabag setup could not be saved.";row2.nextStep="Check the instance URL and username and try again.";return}row2.message="Wallabag instance URL and username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Wallabag setup could not be saved.";row2.nextStep="Check the instance URL and username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-calcom"){const row2=allRows().find(item=>item.source==="calcom");if(!authorization?.configureCalcom||!row2||body.source!=="calcom"||!validCalcomSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Cal.com username.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureCalcom(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Cal.com setup could not be saved.";row2.nextStep="Check the username and try again.";return}row2.message="Cal.com username saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Cal.com setup could not be saved.";row2.nextStep="Check the username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-wakatime"){const row2=allRows().find(item=>item.source==="wakatime");if(!authorization?.configureWakatime||!row2||body.source!=="wakatime"||!validWakatimeSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the WakaTime username or account ID.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureWakatime(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The WakaTime setup could not be saved.";row2.nextStep="Check the username and try again.";return}row2.message="WakaTime username or account ID saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The WakaTime setup could not be saved.";row2.nextStep="Check the username and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-nextcloud"){const row2=allRows().find(item=>item.source==="nextcloud");if(!authorization?.configureNextcloud||!row2||body.source!=="nextcloud"||!validNextcloudInstanceUrl(body.instanceUrl)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Nextcloud instance URL.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureNextcloud(body.instanceUrl,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Nextcloud setup could not be saved.";row2.nextStep="Check the instance URL and try again.";return}row2.message="Nextcloud instance URL saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Nextcloud setup could not be saved.";row2.nextStep="Check the instance URL and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-smartsheet"){const row2=allRows().find(item=>item.source==="smartsheet");if(!authorization?.configureSmartsheet||!row2||body.source!=="smartsheet"||typeof body.region!=="string"||!["us","eu","au"].includes(body.region)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Smartsheet region.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureSmartsheet(body.region,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Smartsheet setup could not be saved.";row2.nextStep="Check the region and try again.";return}row2.message="Smartsheet region saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Smartsheet setup could not be saved.";row2.nextStep="Check the region and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-figma"){const row2=allRows().find(item=>item.source==="figma");if(!authorization?.configureFigma||!row2||body.source!=="figma"||!["fields","oauth"].includes(String(body.selection))){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Figma personal access token mode.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureFigma(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Figma setup could not be saved.";row2.nextStep="Check the personal access token mode and try again.";return}row2.message="Figma connection mode saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Figma setup could not be saved.";row2.nextStep="Check the personal access token mode and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-freshdesk"){const row2=allRows().find(item=>item.source==="freshdesk");if(!authorization?.configureFreshdesk||!row2||body.source!=="freshdesk"||typeof body.subdomain!=="string"||!/^(?:[a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])$/.test(body.subdomain)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Freshdesk tenant.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureFreshdesk(body.subdomain,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Freshdesk setup could not be saved.";row2.nextStep="Check the tenant name and try again.";return}row2.message="Freshdesk tenant saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Freshdesk setup could not be saved.";row2.nextStep="Check the tenant name and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-wechat"){const row2=allRows().find(item=>item.source==="wechat");if(!authorization?.configureWeChat||!row2||body.source!=="wechat"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the WeChat local port.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureWeChat(body.port,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The WeChat setup could not be saved.";row2.nextStep="Check the local port and try again.";return}row2.message="WeChat setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The WeChat setup could not be saved.";row2.nextStep="Check the local port and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-joplin"){const row2=allRows().find(item=>item.source==="joplin");try{if(!authorization?.configureJoplin||!row2||body.source!=="joplin"||body.port!==void 0)throw Error();validateJoplinSelection(body.selection)}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy("joplin")){reply(response,409,{error:"connection_in_progress"});return}const selection=body.selection;if("phase"in selection&&selection.phase==="confirm"&&!invalidateRecoveryEvidence(ctx,"joplin")){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;owned=stop2;interactionGeneration++;activeSource="joplin";activeSources.set(ctx,{source:"joplin",owner:token});const disconnect=()=>{if(!response.writableEnded)stop2.abort()};response.once("close",disconnect);let result={err:{code:"invalid_setup_result"}};active=Promise.resolve().then(async()=>{result=validateJoplinResult(await withSetupProgress("joplin",stop2,()=>authorization.configureJoplin(selection,stop2.signal)))}).catch(()=>{result={err:{code:"pairing_failed"}}}).finally(()=>{response.removeListener("close",disconnect);releaseExecution(stop2)});await active;if(closed||response.destroyed)return;if("err"in result){reply(response,400,{error:"pairing_failed"});return}const pairing=result.ok;if(pairing.state==="configured"){row2.state="pending";row2.read="not-attempted";row2.message="Joplin paired. Note access has not been checked.";row2.nextStep=pairing.next;if(pairing.reloadRequired)reloads.set("joplin",pairing.next)}reply(response,200,{pairing});if(pairing.state==="configured")finishSetup(row2,stop2);return}if(body.action==="configure-thunderbird"){const row2=allRows().find(item=>item.source==="thunderbird");if(!authorization?.configureThunderbird||!row2||body.source!=="thunderbird"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Thunderbird local port.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureThunderbird(body.port,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Thunderbird setup could not be saved.";row2.nextStep="Check the local port and try again.";return}row2.message="Thunderbird setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Thunderbird setup could not be saved.";row2.nextStep="Check the local port and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-dropbox"){const row2=allRows().find(item=>item.source==="dropbox");try{const v=body.selection;if(!authorization?.configureDropbox||!row2||body.source!=="dropbox"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedServiceSource("dropbox",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Dropbox selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureDropbox(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Dropbox setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Dropbox setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Dropbox setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-box"){const row2=allRows().find(item=>item.source==="box");try{const v=body.selection;if(!authorization?.configureBox||!row2||body.source!=="box"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedServiceSource("box",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Box selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureBox(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Box setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Box setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Box setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-front"){const row2=allRows().find(item=>item.source==="front");try{const v=body.selection;if(!authorization?.configureFront||!row2||body.source!=="front"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("front",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Front selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureFront(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Front setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Front setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Front setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-hubspot"){const row2=allRows().find(item=>item.source==="hubspot");try{const v=body.selection;if(!authorization?.configureHubSpot||!row2||body.source!=="hubspot"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("hubspot",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving HubSpot selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureHubSpot(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The HubSpot setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="HubSpot setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The HubSpot setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-google-contacts"){const row2=allRows().find(item=>item.source==="google-contacts");try{const v=body.selection;if(!authorization?.configureGoogleContacts||!row2||body.source!=="google-contacts"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key)))throw Error("invalid");createPreparedServiceSource("google-contacts",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Google Contacts selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureGoogleContacts(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Google Contacts setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Google Contacts setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Google Contacts setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-google-chat"){const row2=allRows().find(item=>item.source==="google-chat");try{const v=body.selection;if(!authorization?.configureGoogleChat||!row2||body.source!=="google-chat"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key)))throw Error("invalid");createPreparedServiceSource("google-chat",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Google Chat selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureGoogleChat(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Google Chat setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Google Chat setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Google Chat setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-salesforce"){const row2=allRows().find(item=>item.source==="salesforce");try{const v=body.selection;if(!authorization?.configureSalesforce||!row2||body.source!=="salesforce"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["environment","clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("salesforce",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Salesforce selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureSalesforce(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Salesforce setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Salesforce setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Salesforce setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-zendesk"){const row2=allRows().find(item=>item.source==="zendesk");if(!authorization?.configureZendesk||!row2||body.source!=="zendesk"||!validZendeskSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Zendesk selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZendesk(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zendesk setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Zendesk setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zendesk setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-zoom"){const row2=allRows().find(item=>item.source==="zoom");try{const v=body.selection;if(!authorization?.configureZoom||!row2||body.source!=="zoom"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId"].includes(key)))throw Error("invalid");createPreparedServiceSource("zoom",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Zoom selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZoom(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zoom setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Zoom setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zoom setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-discord"){const row2=allRows().find(item=>item.source==="discord");try{const v=body.selection;if(!authorization?.configureDiscord||!row2||body.source!=="discord"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving Discord selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureDiscord(body.selection,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Discord setup could not be saved.";row2.nextStep="Check the selection and try again.";return}row2.message="Discord setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Discord setup could not be saved.";row2.nextStep="Check the selection and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-proton-mail"){const row2=allRows().find(item=>item.source==="proton-mail");if(!authorization?.configureProtonMail||!row2||body.source!=="proton-mail"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Proton Mail local port.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureProtonMail(body.port,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Proton Mail setup could not be saved.";row2.nextStep="Check the local port and try again.";return}row2.message="Proton Mail setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Proton Mail setup could not be saved.";row2.nextStep="Check the local port and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-copyq"){const row2=allRows().find(item=>item.source==="copyq");if(!authorization?.configureCopyQ||!row2||body.source!=="copyq"||typeof body.executable!=="string"||body.executable.length<1||body.executable.length>512||body.executable.includes("\0")||!isAbsolute(body.executable)||typeof body.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(body.session)){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the CopyQ application and session.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureCopyQ(body.executable,body.session,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The CopyQ setup could not be saved.";row2.nextStep="Check the application path and session and try again.";return}row2.message="CopyQ setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The CopyQ setup could not be saved.";row2.nextStep="Check the application path and session and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-owntracks"){const row2=allRows().find(item=>item.source==="owntracks");if(!authorization?.configureOwnTracks||!row2||body.source!=="owntracks"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the OwnTracks local port.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureOwnTracks(body.port,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The OwnTracks setup could not be saved.";row2.nextStep="Check the local port and try again.";return}row2.message="OwnTracks setup saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The OwnTracks setup could not be saved.";row2.nextStep="Check the local port and try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-zotero"){const row2=allRows().find(item=>item.source==="zotero");if(!authorization?.configureZotero||!row2||body.source!=="zotero"||typeof body.libraryId!=="string"||!(/^[1-9][0-9]{0,19}$/.test(body.libraryId)||body.libraryType==="user"&&body.libraryId==="0")||!["user","group"].includes(String(body.libraryType))){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Zotero library selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZotero(body.libraryId,body.libraryType,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zotero selection could not be saved.";row2.nextStep="Check the library ID and local setup, then try again.";return}row2.message="Zotero selection saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zotero selection could not be saved.";row2.nextStep="Check the local setup, then try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-native-files"){const row2=allRows().find(item=>item.source===body.source),roots=body.roots;if(!authorization?.configureNativeFiles||!row2||typeof body.source!=="string"||!NATIVE_FILE_SOURCES.has(body.source)||!Array.isArray(roots)||roots.length!==1||typeof roots[0]!=="string"||roots[0].length<1||roots[0].length>512||roots[0].includes("\0")||!isAbsolute(roots[0])){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){row2.message="Progress could not be saved on this computer. The folder selection has not been saved.";row2.nextStep="Check that the data folder is writable, then try again.";reply(response,503,report());return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the folder selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureNativeFiles(row2.source,roots,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result){row2.message="The folder selection could not be saved.";row2.nextStep="Check that the folder exists and is accessible, then try again.";return}if(result.ok.state!=="configured"){row2.message="The folder selection needs further setup.";row2.nextStep="Check the folder and its permissions, then try again.";return}row2.message="Folder selection saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The folder selection could not be saved.";row2.nextStep="Check that the folder exists and is accessible, then try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}const pendingReload=allRows().find(item=>item.source===body.source);if(pendingReload&&reloads.has(pendingReload.source)&&!closed&&!active){retainSetupReload(pendingReload);reply(response,200,report(true));return}const other=others.find(item=>item.source===body.source),row=rows.find(item=>item.source===body.source)??(other&&!other.catalogOnly&&connectableOther(other)&&["connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved"].includes(body.action)?other:void 0);if(!row||row.source==="joplin"&&body.action!=="read"||row.registration==="deferred"){reply(response,400,{error:"unknown_source"});return}if(closed){reply(response,410,{error:"closed"});return}if(continuations.has(row.source)){reply(response,200,report(true));return}if(active){reply(response,activeSource===row.source?200:409,activeSource===row.source?report(true):{error:"connection_in_progress",activeSource});return}if(activeSources.has(ctx)){reply(response,409,{error:"connection_in_progress",activeSource:activeSources.get(ctx)?.source});return}if(busy(row.source)){reply(response,409,{error:"connection_in_progress",activeSource:row.source});return}if(row.state==="unavailable"){reply(response,409,{error:"source_unavailable"});return}if(body.action==="reconnect-saved"&&!supportsSavedReconnect(row.source)){reply(response,400,{error:"saved_reconnect_unsupported"});return}if(body.action==="authorize"&&["google-chrome","microsoft-edge"].includes(row.source)){reply(response,400,{error:"authorization_not_supported"});return}if(!invalidateRecoveryEvidence(ctx,row.source)){fail(row);row.message="Progress could not be saved on this computer. A new connection has not been started.";row.nextStep="Check that the data folder is writable, then try again.";reply(response,503,report());return}const repairLegacyClient=row.errorCode==="authorization_client_registration_required";const stop=new AbortController;interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});delete row.errorCode;row.state="connecting";row.read="not-attempted";row.message="Preparing to connect.";if(!other||SIGNED_IN_SOURCES.has(row.source))row.nextStep="Please wait. You do not need to click again.";startRecovery(row,stop,body.action==="authorize"||body.action==="authorize-readwise-mcp"||body.action==="authorize-gmail-write",body.action==="read",repairLegacyClient,body.action==="reconnect-saved",body.action==="authorize-readwise-mcp",body.action==="authorize-gmail-write");reply(response,202,report(true))}server.requestTimeout=5e3;server.headersTimeout=5e3;server.keepAliveTimeout=1e3;await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error("Recovery listener unavailable.");origin=`http://127.0.0.1:${address.port}`;const timer=setTimeout(()=>{void session.close()},18e5);timer.unref();const gone=setInterval(()=>{if(lastSeen&&!active&&!continuations.size&&Date.now()-lastSeen>pageGoneMs)void session.close()},Math.min(15e3,Math.max(50,pageGoneMs/4)));gone.unref();const session={url:origin+"/#"+token,expiresAt,done,closed:closedPromise,snapshot:()=>report(),async request(input,signal){if(closed)return{status:410,body:{error:"closed"}};let body;try{body=JSON.stringify(input);if(typeof body!=="string")throw Error()}catch{return{status:400,body:{error:"invalid_request"}}}if(Buffer.byteLength(body)>MAX_RECOVERY_REQUEST_BYTES)return{status:413,body:{error:"too_large"}};const response=await fetch(origin+"/api",{method:"POST",redirect:"error",headers:{Origin:origin,"Content-Type":"application/json","X-Zortex-Recovery":token},body,signal});return{status:response.status,body:await response.json()}},close(){return closeTask??=(async()=>{closed=true;clearTimeout(timer);clearInterval(gone);owned?.abort();for(const pending of continuations.values())pending.stop.abort();for(const row of allRows()){clearHandoff(row);if(waiting.has(row.state)){row.state="pending";row.message="This connection session has ended.";row.nextStep=""}}server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()));let waitTimer;await Promise.race([Promise.all([active,...[...continuations.values()].map(item=>item.task)]),new Promise(resolve=>{waitTimer=setTimeout(resolve,1e3)})]);if(waitTimer)clearTimeout(waitTimer);if(!active&&activeSources.get(ctx)?.owner===token)activeSources.delete(ctx);sessions.delete(ctx);if(!settled){settled=true;resolveDone()}resolveClosed()})()}};ctx.effect(()=>()=>session.close());complete();return session}