@zortexhq/indra-v2.5 0.2.5 → 0.2.7

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 (790) hide show
  1. package/README.md +129 -109
  2. package/dist/cli-run.js +1 -1
  3. package/dist/codex-setup.js +1 -1
  4. package/dist/connector-worker.js +1 -1
  5. package/dist/content-find.js +2 -0
  6. package/dist/ensure-ready.js +1 -0
  7. package/dist/gateway.js +1 -1
  8. package/dist/help-launch.js +1 -1
  9. package/dist/local-cloud-policy.js +1 -1
  10. package/dist/mcp.js +2 -2
  11. package/dist/onboarding.js +1 -1
  12. package/dist/operation-telemetry.js +1 -1
  13. package/dist/profile-upgrade.js +1 -1
  14. package/dist/public-tool.js +1 -0
  15. package/dist/recovery-progress.js +1 -1
  16. package/dist/recovery-text.js +1 -1
  17. package/dist/recovery.js +1 -1
  18. package/dist/resident-ensure-ready.js +1 -0
  19. package/dist/resident-host.js +2 -2
  20. package/dist/resident-jobs.js +1 -1
  21. package/dist/resident-platform.js +1 -1
  22. package/dist/resident-telemetry.js +1 -1
  23. package/dist/source-catalog.js +1 -1
  24. package/dist/startup.js +1 -2
  25. package/dist/supervised-sync.js +1 -1
  26. package/dist/tools.js +1 -1
  27. package/dist/update-cli.js +1 -1
  28. package/dist/web.js +2 -2
  29. package/node_modules/@zortexhq/plugin-auth-core/dist/device-admission.js +2 -2
  30. package/node_modules/@zortexhq/plugin-auth-core/dist/index.js +1 -1
  31. package/node_modules/@zortexhq/plugin-auth-core/package.json +1 -8
  32. package/node_modules/@zortexhq/plugin-auto-connect/dist/api/index.js +1 -1
  33. package/node_modules/@zortexhq/plugin-auto-connect/package.json +0 -3
  34. package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
  35. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  36. package/node_modules/@zortexhq/plugin-connector-core/dist/enrollment.js +1 -1
  37. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  38. package/node_modules/@zortexhq/plugin-connector-core/package.json +1 -3
  39. package/node_modules/@zortexhq/plugin-connector-fleet/dist/index.js +1 -1
  40. package/node_modules/@zortexhq/plugin-connector-fleet/package.json +1 -4
  41. package/node_modules/@zortexhq/plugin-connector-framework/dist/api/browser-authorization.js +1 -0
  42. package/node_modules/@zortexhq/plugin-connector-framework/dist/api/index.js +1 -1
  43. package/node_modules/@zortexhq/plugin-connector-framework/dist/runner.js +1 -1
  44. package/node_modules/@zortexhq/plugin-connector-framework/package.json +0 -3
  45. package/node_modules/@zortexhq/plugin-connector-level1/dist/additional-sources.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-level1/dist/matrix-login.js +1 -1
  48. package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
  49. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  50. package/node_modules/@zortexhq/plugin-connector-level1/dist/sources.js +1 -1
  51. package/node_modules/@zortexhq/plugin-connector-level1/package.json +1 -4
  52. package/node_modules/@zortexhq/plugin-connector-notion/dist/broker.js +1 -1
  53. package/node_modules/@zortexhq/plugin-connector-notion/dist/index.js +1 -1
  54. package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
  55. package/node_modules/@zortexhq/plugin-connector-notion/package.json +1 -3
  56. package/node_modules/@zortexhq/plugin-connector-steam/dist/index.js +1 -1
  57. package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
  58. package/node_modules/@zortexhq/plugin-connector-steam/package.json +1 -3
  59. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
  60. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-panel.js +1 -1
  61. package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
  62. package/node_modules/@zortexhq/plugin-google-auth/package.json +1 -3
  63. package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
  64. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  65. package/package.json +6 -20
  66. package/profiles/core.yml +0 -18
  67. package/release-provenance.json +27 -93
  68. package/update-manifest.json +362 -4744
  69. package/dist/cloud-action-proof.js +0 -1
  70. package/dist/cloud-device-host.js +0 -1
  71. package/dist/cloud-device-identity.js +0 -1
  72. package/dist/cloud-download-sink.js +0 -1
  73. package/dist/cloud-gmail-actions.js +0 -1
  74. package/dist/cloud-gmail-audit.js +0 -1
  75. package/dist/cloud-gmail-bound-audit-runner.js +0 -1
  76. package/dist/cloud-gmail-bound-epoch.js +0 -1
  77. package/dist/cloud-gmail-bound-identity.js +0 -1
  78. package/dist/cloud-gmail-bound-runner.js +0 -1
  79. package/dist/cloud-gmail-provider.js +0 -1
  80. package/dist/cloud-gmail-rpc.js +0 -1
  81. package/dist/cloud-gmail-sync.js +0 -1
  82. package/node_modules/@zortexhq/plugin-auth-core/dist/cloud-frame.js +0 -1
  83. package/node_modules/@zortexhq/plugin-auth-core/dist/cloud-vault-keyring.js +0 -1
  84. package/node_modules/@zortexhq/plugin-cloud-ai/dist/account.js +0 -1
  85. package/node_modules/@zortexhq/plugin-cloud-ai/dist/adopt.js +0 -1
  86. package/node_modules/@zortexhq/plugin-cloud-ai/dist/index.js +0 -1
  87. package/node_modules/@zortexhq/plugin-cloud-ai/dist/pack.js +0 -1
  88. package/node_modules/@zortexhq/plugin-cloud-ai/dist/publish.js +0 -1
  89. package/node_modules/@zortexhq/plugin-cloud-ai/dist/records.js +0 -1
  90. package/node_modules/@zortexhq/plugin-cloud-ai/package.json +0 -17
  91. package/node_modules/@zortexhq/plugin-cloud-vault/dist/device-trust.js +0 -1
  92. package/node_modules/@zortexhq/plugin-cloud-vault/dist/owner-admission.js +0 -1
  93. package/node_modules/@zortexhq/plugin-cloud-vault/package.json +0 -19
  94. package/node_modules/@zortexhq/plugin-connector-core/dist/api/browser-authorization.js +0 -1
  95. package/node_modules/@zortexhq/plugin-connector-framework/dist/api/original-miner.js +0 -1
  96. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-codec.js +0 -2
  97. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-fs.js +0 -1
  98. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-move-worker.js +0 -1
  99. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-move.js +0 -1
  100. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-posix.js +0 -1
  101. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-public.js +0 -1
  102. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-replay.js +0 -1
  103. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-store.js +0 -1
  104. package/node_modules/@zortexhq/plugin-connector-framework/dist/chromium-local/chromium-history.js +0 -1
  105. package/node_modules/@zortexhq/plugin-connector-framework/dist/chromium-local/index.js +0 -1
  106. package/node_modules/@zortexhq/plugin-connector-framework/dist/chromium-local/normalize-visit.js +0 -1
  107. package/node_modules/@zortexhq/plugin-connector-framework/dist/connection-health.js +0 -1
  108. package/node_modules/@zortexhq/plugin-connector-framework/dist/connector.js +0 -1
  109. package/node_modules/@zortexhq/plugin-connector-framework/dist/failure-type.js +0 -1
  110. package/node_modules/@zortexhq/plugin-connector-framework/dist/index.js +0 -1
  111. package/node_modules/@zortexhq/plugin-connector-framework/dist/windows-custody.js +0 -1
  112. package/node_modules/@zortexhq/plugin-connector-level1/dist/chatgpt.js +0 -1
  113. package/node_modules/@zortexhq/plugin-connector-level1/dist/signed-in.js +0 -1
  114. package/node_modules/@zortexhq/plugin-connector-social/dist/full-sync.js +0 -1
  115. package/node_modules/@zortexhq/plugin-connector-social/dist/index.js +0 -1
  116. package/node_modules/@zortexhq/plugin-connector-social/dist/provider.js +0 -1
  117. package/node_modules/@zortexhq/plugin-connector-social/dist/sites.js +0 -1
  118. package/node_modules/@zortexhq/plugin-connector-social/package.json +0 -22
  119. package/node_modules/@zortexhq/plugin-connector-steam/dist/browser-session.js +0 -1
  120. package/node_modules/@zortexhq/plugin-connectors/package.json +0 -17
  121. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/attached.js +0 -11
  122. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/browser.js +0 -1
  123. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/decision.js +0 -1
  124. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/extension-transport.js +0 -1
  125. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/feedback.js +0 -1
  126. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-bridge.js +0 -1
  127. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-driver.js +0 -1
  128. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-uia-decision.js +0 -1
  129. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/index.js +0 -1
  130. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/microsoft-oauth-bridge.js +0 -1
  131. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/microsoft-oauth-driver.js +0 -1
  132. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/page-inspect.js +0 -6
  133. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/runner.js +0 -1
  134. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/slack-oauth-bridge.js +0 -1
  135. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/slack-oauth-driver.js +0 -1
  136. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/whatsapp-session.js +0 -1
  137. package/node_modules/@zortexhq/plugin-jev-autopilot/extension/manifest.json +0 -9
  138. package/node_modules/@zortexhq/plugin-jev-autopilot/package.json +0 -21
  139. package/node_modules/@zortexhq/plugin-jev-browser-driver/assets/ax-page.js +0 -1
  140. package/node_modules/@zortexhq/plugin-jev-browser-driver/assets/uia-page.ps1 +0 -545
  141. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/approved-control.js +0 -1
  142. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/attached-session.js +0 -8
  143. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/authorization-account-policy.js +0 -1
  144. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/authorization-memory.js +0 -1
  145. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/authorization-planner.js +0 -8
  146. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/authorization-task.js +0 -1
  147. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-actions.js +0 -1
  148. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-task.js +0 -7
  149. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/combined.js +0 -1
  150. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/decision.js +0 -5
  151. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/driver.js +0 -1
  152. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/google-oauth-driver.js +0 -1
  153. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/index.js +0 -1
  154. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/isolated-display.js +0 -1
  155. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/microsoft-oauth-driver.js +0 -1
  156. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/native-session.js +0 -1
  157. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/notion-oauth-driver.js +0 -1
  158. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/observe-log.js +0 -1
  159. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/operational-browser.js +0 -1
  160. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/page-settle.js +0 -1
  161. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/planned-oauth.js +0 -1
  162. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/session-routes.js +0 -1
  163. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/shared-session.js +0 -1
  164. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/site-read.js +0 -1
  165. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/slack-oauth-driver.js +0 -1
  166. package/node_modules/@zortexhq/plugin-jev-browser-driver/package.json +0 -20
  167. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-oauth-background.cs +0 -492
  168. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-oauth-guard-x64.build.json +0 -30
  169. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-oauth-guard-x64.dll +0 -0
  170. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-oauth-guard.c +0 -692
  171. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-uia-oauth.ps1 +0 -3840
  172. package/node_modules/@zortexhq/plugin-oauth-browser-driver/dist/api/index.js +0 -1
  173. package/node_modules/@zortexhq/plugin-oauth-browser-driver/dist/driver.js +0 -3
  174. package/node_modules/@zortexhq/plugin-oauth-browser-driver/dist/index.js +0 -1
  175. package/node_modules/@zortexhq/plugin-oauth-browser-driver/package.json +0 -19
  176. package/node_modules/chatgpt-web-mcp/.env.example +0 -30
  177. package/node_modules/chatgpt-web-mcp/CONTRIBUTING.md +0 -65
  178. package/node_modules/chatgpt-web-mcp/LICENSE +0 -21
  179. package/node_modules/chatgpt-web-mcp/README.en.md +0 -149
  180. package/node_modules/chatgpt-web-mcp/README.md +0 -194
  181. package/node_modules/chatgpt-web-mcp/SECURITY.md +0 -37
  182. package/node_modules/chatgpt-web-mcp/node_modules/zod/LICENSE +0 -21
  183. package/node_modules/chatgpt-web-mcp/node_modules/zod/README.md +0 -208
  184. package/node_modules/chatgpt-web-mcp/node_modules/zod/index.cjs +0 -33
  185. package/node_modules/chatgpt-web-mcp/node_modules/zod/index.d.cts +0 -4
  186. package/node_modules/chatgpt-web-mcp/node_modules/zod/index.d.ts +0 -4
  187. package/node_modules/chatgpt-web-mcp/node_modules/zod/index.js +0 -4
  188. package/node_modules/chatgpt-web-mcp/node_modules/zod/package.json +0 -118
  189. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/index.ts +0 -4
  190. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/ZodError.ts +0 -330
  191. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/datetime.ts +0 -58
  192. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts +0 -80
  193. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/index.ts +0 -59
  194. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/ipv4.ts +0 -57
  195. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/object.ts +0 -69
  196. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/primitives.ts +0 -162
  197. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/realworld.ts +0 -63
  198. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/string.ts +0 -55
  199. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/union.ts +0 -80
  200. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/errors.ts +0 -13
  201. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/external.ts +0 -6
  202. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/enumUtil.ts +0 -17
  203. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/errorUtil.ts +0 -8
  204. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/parseUtil.ts +0 -176
  205. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/partialUtil.ts +0 -34
  206. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/typeAliases.ts +0 -2
  207. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/util.ts +0 -224
  208. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/index.ts +0 -4
  209. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/locales/en.ts +0 -124
  210. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/standard-schema.ts +0 -113
  211. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/Mocker.ts +0 -54
  212. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/all-errors.test.ts +0 -157
  213. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/anyunknown.test.ts +0 -28
  214. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/array.test.ts +0 -71
  215. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/async-parsing.test.ts +0 -388
  216. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/async-refinements.test.ts +0 -46
  217. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/base.test.ts +0 -29
  218. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/bigint.test.ts +0 -55
  219. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/branded.test.ts +0 -53
  220. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/catch.test.ts +0 -220
  221. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/coerce.test.ts +0 -133
  222. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/complex.test.ts +0 -56
  223. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/custom.test.ts +0 -31
  224. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/date.test.ts +0 -32
  225. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/deepmasking.test.ts +0 -186
  226. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/default.test.ts +0 -112
  227. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/description.test.ts +0 -33
  228. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/discriminated-unions.test.ts +0 -315
  229. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/enum.test.ts +0 -80
  230. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/error.test.ts +0 -551
  231. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/firstparty.test.ts +0 -87
  232. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts +0 -21
  233. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/function.test.ts +0 -257
  234. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/generics.test.ts +0 -48
  235. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/instanceof.test.ts +0 -37
  236. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/intersection.test.ts +0 -110
  237. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/language-server.source.ts +0 -76
  238. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/language-server.test.ts +0 -207
  239. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/literal.test.ts +0 -36
  240. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/map.test.ts +0 -110
  241. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/masking.test.ts +0 -4
  242. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/mocker.test.ts +0 -19
  243. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/nan.test.ts +0 -21
  244. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/nativeEnum.test.ts +0 -87
  245. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/nullable.test.ts +0 -42
  246. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/number.test.ts +0 -176
  247. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/object-augmentation.test.ts +0 -29
  248. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts +0 -29
  249. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/object.test.ts +0 -434
  250. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/optional.test.ts +0 -42
  251. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/parseUtil.test.ts +0 -23
  252. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/parser.test.ts +0 -41
  253. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/partials.test.ts +0 -243
  254. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/pickomit.test.ts +0 -111
  255. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/pipeline.test.ts +0 -29
  256. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/preprocess.test.ts +0 -186
  257. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/primitive.test.ts +0 -440
  258. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/promise.test.ts +0 -90
  259. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/readonly.test.ts +0 -194
  260. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/record.test.ts +0 -171
  261. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/recursive.test.ts +0 -197
  262. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/refine.test.ts +0 -313
  263. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/safeparse.test.ts +0 -27
  264. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/set.test.ts +0 -142
  265. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/standard-schema.test.ts +0 -83
  266. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/string.test.ts +0 -916
  267. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/transformer.test.ts +0 -233
  268. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/tuple.test.ts +0 -90
  269. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/unions.test.ts +0 -57
  270. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/validations.test.ts +0 -133
  271. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/void.test.ts +0 -15
  272. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/types.ts +0 -5136
  273. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/checks.ts +0 -30
  274. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/coerce.ts +0 -27
  275. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/compat.ts +0 -66
  276. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/errors.ts +0 -75
  277. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/external.ts +0 -50
  278. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/index.ts +0 -5
  279. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/iso.ts +0 -90
  280. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/parse.ts +0 -33
  281. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/schemas.ts +0 -2054
  282. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/anyunknown.test.ts +0 -26
  283. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/array.test.ts +0 -264
  284. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/assignability.test.ts +0 -210
  285. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts +0 -381
  286. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts +0 -68
  287. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/base.test.ts +0 -7
  288. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/bigint.test.ts +0 -54
  289. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/brand.test.ts +0 -63
  290. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/catch.test.ts +0 -252
  291. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/coalesce.test.ts +0 -20
  292. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/coerce.test.ts +0 -160
  293. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/continuability.test.ts +0 -352
  294. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/custom.test.ts +0 -40
  295. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/date.test.ts +0 -31
  296. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/datetime.test.ts +0 -296
  297. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/default.test.ts +0 -313
  298. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/description.test.ts +0 -32
  299. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts +0 -619
  300. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/enum.test.ts +0 -285
  301. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/error-utils.test.ts +0 -527
  302. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/error.test.ts +0 -711
  303. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/file.test.ts +0 -91
  304. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/firstparty.test.ts +0 -175
  305. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/function.test.ts +0 -268
  306. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/generics.test.ts +0 -72
  307. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/index.test.ts +0 -829
  308. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/instanceof.test.ts +0 -34
  309. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/intersection.test.ts +0 -171
  310. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/json.test.ts +0 -108
  311. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/lazy.test.ts +0 -227
  312. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/literal.test.ts +0 -92
  313. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/map.test.ts +0 -196
  314. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/nan.test.ts +0 -21
  315. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts +0 -168
  316. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts +0 -86
  317. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/nullable.test.ts +0 -22
  318. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/number.test.ts +0 -247
  319. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/object.test.ts +0 -563
  320. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/optional.test.ts +0 -123
  321. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/partial.test.ts +0 -147
  322. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/pickomit.test.ts +0 -127
  323. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/pipe.test.ts +0 -81
  324. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/prefault.test.ts +0 -37
  325. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/preprocess.test.ts +0 -298
  326. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/primitive.test.ts +0 -175
  327. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/promise.test.ts +0 -81
  328. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/prototypes.test.ts +0 -23
  329. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/readonly.test.ts +0 -252
  330. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/record.test.ts +0 -342
  331. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts +0 -356
  332. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/refine.test.ts +0 -532
  333. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/registries.test.ts +0 -204
  334. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/set.test.ts +0 -179
  335. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts +0 -57
  336. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/string-formats.test.ts +0 -109
  337. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/string.test.ts +0 -881
  338. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/stringbool.test.ts +0 -66
  339. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/template-literal.test.ts +0 -758
  340. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts +0 -2314
  341. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/transform.test.ts +0 -250
  342. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/tuple.test.ts +0 -163
  343. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/union.test.ts +0 -94
  344. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/validations.test.ts +0 -283
  345. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/void.test.ts +0 -12
  346. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/api.ts +0 -1594
  347. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/checks.ts +0 -1283
  348. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/config.ts +0 -15
  349. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/core.ts +0 -134
  350. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/doc.ts +0 -44
  351. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/errors.ts +0 -424
  352. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/function.ts +0 -176
  353. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/index.ts +0 -15
  354. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/json-schema.ts +0 -143
  355. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/parse.ts +0 -94
  356. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/regexes.ts +0 -135
  357. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/registries.ts +0 -96
  358. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/schemas.ts +0 -3842
  359. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/standard-schema.ts +0 -64
  360. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/index.test.ts +0 -46
  361. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/locales/be.test.ts +0 -124
  362. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/locales/en.test.ts +0 -22
  363. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/locales/ru.test.ts +0 -128
  364. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/locales/tr.test.ts +0 -69
  365. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/to-json-schema.ts +0 -977
  366. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/util.ts +0 -775
  367. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/versions.ts +0 -5
  368. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/zsf.ts +0 -323
  369. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/index.ts +0 -4
  370. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ar.ts +0 -125
  371. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/az.ts +0 -121
  372. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/be.ts +0 -184
  373. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ca.ts +0 -127
  374. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/cs.ts +0 -142
  375. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/de.ts +0 -124
  376. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/en.ts +0 -127
  377. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/eo.ts +0 -125
  378. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/es.ts +0 -125
  379. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/fa.ts +0 -134
  380. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/fi.ts +0 -131
  381. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/fr-CA.ts +0 -126
  382. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/fr.ts +0 -124
  383. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/he.ts +0 -125
  384. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/hu.ts +0 -126
  385. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/id.ts +0 -125
  386. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/index.ts +0 -39
  387. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/it.ts +0 -125
  388. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ja.ts +0 -122
  389. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/kh.ts +0 -126
  390. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ko.ts +0 -131
  391. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/mk.ts +0 -127
  392. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ms.ts +0 -124
  393. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/nl.ts +0 -126
  394. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/no.ts +0 -124
  395. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ota.ts +0 -125
  396. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/pl.ts +0 -126
  397. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ps.ts +0 -133
  398. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/pt.ts +0 -123
  399. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ru.ts +0 -184
  400. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/sl.ts +0 -126
  401. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/sv.ts +0 -127
  402. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ta.ts +0 -125
  403. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/th.ts +0 -126
  404. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/tr.ts +0 -121
  405. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ua.ts +0 -126
  406. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ur.ts +0 -126
  407. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/vi.ts +0 -125
  408. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/zh-CN.ts +0 -123
  409. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/zh-TW.ts +0 -125
  410. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/checks.ts +0 -32
  411. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/coerce.ts +0 -22
  412. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/external.ts +0 -40
  413. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/index.ts +0 -3
  414. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/iso.ts +0 -62
  415. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/parse.ts +0 -1
  416. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/schemas.ts +0 -1579
  417. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/assignability.test.ts +0 -129
  418. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/brand.test.ts +0 -51
  419. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/checks.test.ts +0 -144
  420. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/computed.test.ts +0 -36
  421. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/error.test.ts +0 -22
  422. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/functions.test.ts +0 -43
  423. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/index.test.ts +0 -871
  424. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/number.test.ts +0 -95
  425. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/object.test.ts +0 -185
  426. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/prototypes.test.ts +0 -43
  427. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/recursive-types.test.ts +0 -275
  428. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/string.test.ts +0 -299
  429. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4-mini/index.ts +0 -1
  430. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/ZodError.cjs +0 -138
  431. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/ZodError.d.cts +0 -164
  432. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/ZodError.d.ts +0 -164
  433. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/ZodError.js +0 -133
  434. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/errors.cjs +0 -17
  435. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/errors.d.cts +0 -5
  436. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/errors.d.ts +0 -5
  437. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/errors.js +0 -9
  438. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/external.cjs +0 -22
  439. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/external.d.cts +0 -6
  440. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/external.d.ts +0 -6
  441. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/external.js +0 -6
  442. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/enumUtil.cjs +0 -2
  443. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/enumUtil.d.cts +0 -8
  444. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/enumUtil.d.ts +0 -8
  445. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/enumUtil.js +0 -1
  446. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/errorUtil.cjs +0 -9
  447. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/errorUtil.d.cts +0 -9
  448. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/errorUtil.d.ts +0 -9
  449. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/errorUtil.js +0 -6
  450. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/parseUtil.cjs +0 -124
  451. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/parseUtil.d.cts +0 -78
  452. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/parseUtil.d.ts +0 -78
  453. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/parseUtil.js +0 -109
  454. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/partialUtil.cjs +0 -2
  455. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/partialUtil.d.cts +0 -8
  456. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/partialUtil.d.ts +0 -8
  457. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/partialUtil.js +0 -1
  458. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/typeAliases.cjs +0 -2
  459. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/typeAliases.d.cts +0 -2
  460. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/typeAliases.d.ts +0 -2
  461. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/typeAliases.js +0 -1
  462. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/util.cjs +0 -137
  463. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/util.d.cts +0 -85
  464. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/util.d.ts +0 -85
  465. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/util.js +0 -133
  466. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/index.cjs +0 -33
  467. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/index.d.cts +0 -4
  468. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/index.d.ts +0 -4
  469. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/index.js +0 -4
  470. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/locales/en.cjs +0 -111
  471. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/locales/en.d.cts +0 -3
  472. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/locales/en.d.ts +0 -3
  473. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/locales/en.js +0 -109
  474. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/standard-schema.cjs +0 -2
  475. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/standard-schema.d.cts +0 -102
  476. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/standard-schema.d.ts +0 -102
  477. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/standard-schema.js +0 -1
  478. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/types.cjs +0 -3775
  479. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/types.d.cts +0 -1031
  480. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/types.d.ts +0 -1031
  481. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/types.js +0 -3693
  482. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/checks.cjs +0 -32
  483. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/checks.d.cts +0 -1
  484. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/checks.d.ts +0 -1
  485. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/checks.js +0 -1
  486. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/coerce.cjs +0 -47
  487. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/coerce.d.cts +0 -17
  488. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/coerce.d.ts +0 -17
  489. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/coerce.js +0 -17
  490. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/compat.cjs +0 -57
  491. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/compat.d.cts +0 -46
  492. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/compat.d.ts +0 -46
  493. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/compat.js +0 -27
  494. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/errors.cjs +0 -67
  495. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/errors.d.cts +0 -30
  496. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/errors.d.ts +0 -30
  497. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/errors.js +0 -41
  498. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/external.cjs +0 -70
  499. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/external.d.cts +0 -13
  500. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/external.d.ts +0 -13
  501. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/external.js +0 -18
  502. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/index.cjs +0 -33
  503. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/index.d.cts +0 -4
  504. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/index.d.ts +0 -4
  505. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/index.js +0 -4
  506. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/iso.cjs +0 -60
  507. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/iso.d.cts +0 -22
  508. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/iso.d.ts +0 -22
  509. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/iso.js +0 -30
  510. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/parse.cjs +0 -32
  511. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/parse.d.cts +0 -23
  512. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/parse.d.ts +0 -23
  513. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/parse.js +0 -6
  514. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/schemas.cjs +0 -1109
  515. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/schemas.d.cts +0 -630
  516. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/schemas.d.ts +0 -630
  517. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/schemas.js +0 -1006
  518. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/api.cjs +0 -1039
  519. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/api.d.cts +0 -284
  520. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/api.d.ts +0 -284
  521. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/api.js +0 -906
  522. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/checks.cjs +0 -591
  523. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/checks.d.cts +0 -278
  524. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/checks.d.ts +0 -278
  525. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/checks.js +0 -565
  526. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/core.cjs +0 -67
  527. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/core.d.cts +0 -49
  528. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/core.d.ts +0 -49
  529. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/core.js +0 -61
  530. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/doc.cjs +0 -39
  531. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/doc.d.cts +0 -14
  532. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/doc.d.ts +0 -14
  533. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/doc.js +0 -35
  534. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/errors.cjs +0 -226
  535. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/errors.d.cts +0 -208
  536. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/errors.d.ts +0 -208
  537. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/errors.js +0 -195
  538. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/function.cjs +0 -102
  539. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/function.d.cts +0 -52
  540. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/function.d.ts +0 -52
  541. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/function.js +0 -75
  542. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/index.cjs +0 -44
  543. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/index.d.cts +0 -15
  544. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/index.d.ts +0 -15
  545. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/index.js +0 -15
  546. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/json-schema.cjs +0 -2
  547. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/json-schema.d.cts +0 -87
  548. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/json-schema.d.ts +0 -87
  549. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/json-schema.js +0 -1
  550. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/parse.cjs +0 -87
  551. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/parse.d.cts +0 -25
  552. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/parse.d.ts +0 -25
  553. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/parse.js +0 -57
  554. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/regexes.cjs +0 -103
  555. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/regexes.d.cts +0 -62
  556. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/regexes.d.ts +0 -62
  557. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/regexes.js +0 -95
  558. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/registries.cjs +0 -56
  559. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/registries.d.cts +0 -35
  560. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/registries.d.ts +0 -35
  561. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/registries.js +0 -51
  562. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/schemas.cjs +0 -1748
  563. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/schemas.d.cts +0 -1041
  564. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/schemas.d.ts +0 -1041
  565. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/schemas.js +0 -1717
  566. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/standard-schema.cjs +0 -2
  567. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/standard-schema.d.cts +0 -55
  568. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/standard-schema.d.ts +0 -55
  569. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/standard-schema.js +0 -1
  570. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/to-json-schema.cjs +0 -854
  571. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/to-json-schema.d.cts +0 -88
  572. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/to-json-schema.d.ts +0 -88
  573. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/to-json-schema.js +0 -849
  574. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/util.cjs +0 -539
  575. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/util.d.cts +0 -183
  576. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/util.d.ts +0 -183
  577. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/util.js +0 -493
  578. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/versions.cjs +0 -8
  579. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/versions.d.cts +0 -5
  580. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/versions.d.ts +0 -5
  581. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/versions.js +0 -5
  582. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/index.cjs +0 -22
  583. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/index.d.cts +0 -3
  584. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/index.d.ts +0 -3
  585. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/index.js +0 -3
  586. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ar.cjs +0 -142
  587. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ar.d.cts +0 -4
  588. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ar.d.ts +0 -4
  589. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ar.js +0 -116
  590. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/az.cjs +0 -141
  591. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/az.d.cts +0 -4
  592. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/az.d.ts +0 -4
  593. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/az.js +0 -115
  594. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/be.cjs +0 -190
  595. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/be.d.cts +0 -4
  596. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/be.d.ts +0 -4
  597. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/be.js +0 -164
  598. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ca.cjs +0 -144
  599. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ca.d.cts +0 -4
  600. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ca.d.ts +0 -4
  601. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ca.js +0 -118
  602. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/cs.cjs +0 -161
  603. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/cs.d.cts +0 -4
  604. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/cs.d.ts +0 -4
  605. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/cs.js +0 -135
  606. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/de.cjs +0 -142
  607. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/de.d.cts +0 -4
  608. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/de.d.ts +0 -4
  609. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/de.js +0 -116
  610. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/en.cjs +0 -145
  611. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/en.d.cts +0 -5
  612. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/en.d.ts +0 -5
  613. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/en.js +0 -117
  614. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/eo.cjs +0 -144
  615. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/eo.d.cts +0 -5
  616. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/eo.d.ts +0 -5
  617. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/eo.js +0 -116
  618. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/es.cjs +0 -143
  619. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/es.d.cts +0 -4
  620. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/es.d.ts +0 -4
  621. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/es.js +0 -117
  622. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fa.cjs +0 -148
  623. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fa.d.cts +0 -4
  624. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fa.d.ts +0 -4
  625. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fa.js +0 -122
  626. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fi.cjs +0 -148
  627. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fi.d.cts +0 -4
  628. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fi.d.ts +0 -4
  629. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fi.js +0 -122
  630. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr-CA.cjs +0 -143
  631. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr-CA.d.cts +0 -4
  632. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr-CA.d.ts +0 -4
  633. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr-CA.js +0 -117
  634. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr.cjs +0 -142
  635. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr.d.cts +0 -4
  636. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr.d.ts +0 -4
  637. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr.js +0 -116
  638. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/he.cjs +0 -143
  639. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/he.d.cts +0 -4
  640. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/he.d.ts +0 -4
  641. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/he.js +0 -117
  642. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/hu.cjs +0 -143
  643. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/hu.d.cts +0 -4
  644. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/hu.d.ts +0 -4
  645. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/hu.js +0 -117
  646. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/id.cjs +0 -142
  647. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/id.d.cts +0 -4
  648. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/id.d.ts +0 -4
  649. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/id.js +0 -116
  650. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/index.cjs +0 -84
  651. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/index.d.cts +0 -39
  652. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/index.d.ts +0 -39
  653. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/index.js +0 -39
  654. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/it.cjs +0 -143
  655. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/it.d.cts +0 -4
  656. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/it.d.ts +0 -4
  657. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/it.js +0 -117
  658. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ja.cjs +0 -141
  659. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ja.d.cts +0 -4
  660. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ja.d.ts +0 -4
  661. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ja.js +0 -115
  662. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/kh.cjs +0 -143
  663. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/kh.d.cts +0 -4
  664. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/kh.d.ts +0 -4
  665. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/kh.js +0 -117
  666. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ko.cjs +0 -147
  667. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ko.d.cts +0 -4
  668. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ko.d.ts +0 -4
  669. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ko.js +0 -121
  670. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/mk.cjs +0 -144
  671. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/mk.d.cts +0 -4
  672. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/mk.d.ts +0 -4
  673. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/mk.js +0 -118
  674. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ms.cjs +0 -142
  675. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ms.d.cts +0 -4
  676. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ms.d.ts +0 -4
  677. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ms.js +0 -116
  678. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/nl.cjs +0 -143
  679. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/nl.d.cts +0 -4
  680. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/nl.d.ts +0 -4
  681. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/nl.js +0 -117
  682. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/no.cjs +0 -142
  683. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/no.d.cts +0 -4
  684. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/no.d.ts +0 -4
  685. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/no.js +0 -116
  686. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ota.cjs +0 -143
  687. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ota.d.cts +0 -4
  688. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ota.d.ts +0 -4
  689. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ota.js +0 -117
  690. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pl.cjs +0 -143
  691. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pl.d.cts +0 -4
  692. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pl.d.ts +0 -4
  693. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pl.js +0 -117
  694. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ps.cjs +0 -148
  695. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ps.d.cts +0 -4
  696. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ps.d.ts +0 -4
  697. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ps.js +0 -122
  698. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pt.cjs +0 -142
  699. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pt.d.cts +0 -4
  700. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pt.d.ts +0 -4
  701. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pt.js +0 -116
  702. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ru.cjs +0 -190
  703. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ru.d.cts +0 -4
  704. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ru.d.ts +0 -4
  705. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ru.js +0 -164
  706. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sl.cjs +0 -143
  707. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sl.d.cts +0 -4
  708. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sl.d.ts +0 -4
  709. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sl.js +0 -117
  710. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sv.cjs +0 -144
  711. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sv.d.cts +0 -4
  712. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sv.d.ts +0 -4
  713. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sv.js +0 -118
  714. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ta.cjs +0 -143
  715. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ta.d.cts +0 -4
  716. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ta.d.ts +0 -4
  717. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ta.js +0 -117
  718. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/th.cjs +0 -143
  719. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/th.d.cts +0 -4
  720. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/th.d.ts +0 -4
  721. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/th.js +0 -117
  722. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/tr.cjs +0 -143
  723. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/tr.d.cts +0 -5
  724. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/tr.d.ts +0 -5
  725. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/tr.js +0 -115
  726. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ua.cjs +0 -143
  727. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ua.d.cts +0 -4
  728. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ua.d.ts +0 -4
  729. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ua.js +0 -117
  730. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ur.cjs +0 -143
  731. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ur.d.cts +0 -4
  732. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ur.d.ts +0 -4
  733. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ur.js +0 -117
  734. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/vi.cjs +0 -142
  735. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/vi.d.cts +0 -4
  736. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/vi.d.ts +0 -4
  737. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/vi.js +0 -116
  738. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-CN.cjs +0 -142
  739. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-CN.d.cts +0 -4
  740. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-CN.d.ts +0 -4
  741. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-CN.js +0 -116
  742. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-TW.cjs +0 -143
  743. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-TW.d.cts +0 -4
  744. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-TW.d.ts +0 -4
  745. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-TW.js +0 -117
  746. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/checks.cjs +0 -34
  747. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/checks.d.cts +0 -1
  748. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/checks.d.ts +0 -1
  749. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/checks.js +0 -1
  750. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/coerce.cjs +0 -47
  751. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/coerce.d.cts +0 -7
  752. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/coerce.d.ts +0 -7
  753. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/coerce.js +0 -17
  754. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/external.cjs +0 -62
  755. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/external.d.cts +0 -11
  756. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/external.d.ts +0 -11
  757. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/external.js +0 -13
  758. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/index.cjs +0 -32
  759. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/index.d.cts +0 -3
  760. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/index.d.ts +0 -3
  761. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/index.js +0 -3
  762. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/iso.cjs +0 -60
  763. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/iso.d.cts +0 -22
  764. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/iso.d.ts +0 -22
  765. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/iso.js +0 -30
  766. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/parse.cjs +0 -8
  767. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/parse.d.cts +0 -1
  768. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/parse.d.ts +0 -1
  769. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/parse.js +0 -1
  770. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/schemas.cjs +0 -839
  771. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/schemas.d.cts +0 -356
  772. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/schemas.d.ts +0 -356
  773. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/schemas.js +0 -732
  774. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4-mini/index.cjs +0 -17
  775. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4-mini/index.d.cts +0 -1
  776. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4-mini/index.d.ts +0 -1
  777. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4-mini/index.js +0 -1
  778. package/node_modules/chatgpt-web-mcp/package.json +0 -50
  779. package/node_modules/chatgpt-web-mcp/scripts/doctor.js +0 -40
  780. package/node_modules/chatgpt-web-mcp/scripts/inspect.js +0 -16
  781. package/node_modules/chatgpt-web-mcp/scripts/login.js +0 -32
  782. package/node_modules/chatgpt-web-mcp/scripts/smoke-mcp.js +0 -26
  783. package/node_modules/chatgpt-web-mcp/src/browser.js +0 -4670
  784. package/node_modules/chatgpt-web-mcp/src/cli.js +0 -27
  785. package/node_modules/chatgpt-web-mcp/src/config.js +0 -210
  786. package/node_modules/chatgpt-web-mcp/src/errors.js +0 -20
  787. package/node_modules/chatgpt-web-mcp/src/index.js +0 -381
  788. package/node_modules/chatgpt-web-mcp/src/login-lifecycle.js +0 -39
  789. package/node_modules/chatgpt-web-mcp/src/selectors.js +0 -151
  790. package/profiles/social-worker.yml +0 -18
@@ -1,3840 +0,0 @@
1
- param([switch]$SelfTest, [switch]$SelfTestNative, [switch]$SelfTestJev, [switch]$SelfTestJevPolicy)
2
-
3
- Set-StrictMode -Version Latest
4
- $ErrorActionPreference = "Stop"
5
-
6
-
7
- $script:OwnedBrowserHandle = [IntPtr]::Zero
8
- $script:Automatic = $false
9
- $script:NextDriver = $false
10
- $script:ForegroundObserved = $false
11
- $script:AccountUiaActionDiagnostic = 'not_attempted'
12
- $script:BackgroundGuardStarted = $false
13
- $script:BackgroundRaised = $false
14
- $script:BackgroundMutexOwned = $false
15
- $script:BackgroundMutex = $null
16
- $script:BackgroundIdentity = $null
17
- $script:BackgroundNonce = ''
18
- $script:RevealPages = [Collections.Generic.HashSet[string]]::new()
19
- $script:RevealCount = 0
20
- $script:RevealRetries = @{}
21
- $script:RendererMissingSince = $null
22
- $script:RendererUnresolvedSince = $null
23
- $script:RendererUnresolvedUrl = ''
24
- $script:RendererRevealedAt = $null
25
- $script:RendererReveals = @{}
26
- $script:HiddenFirstAt = @{}
27
- $script:BackgroundPageFirstSeen = @{}
28
- $script:OwnedTransactionBound = $false
29
- $script:PageSession = $false
30
- $script:CleanupDiagnostic = $null
31
- $script:ConsentDiagnostic = $null
32
- $script:DiagnosticNamed = @()
33
- $script:DiagnosticRoot = [IntPtr]::Zero
34
- $script:OAuthTrace = [Collections.Generic.List[string]]::new()
35
-
36
- function Get-DefaultChromeUserDataDir {
37
- $override = $env:ZORTEX_OAUTH_CHROME_USER_DATA_DIR
38
- if (-not [string]::IsNullOrWhiteSpace($override) -and (Test-Path -LiteralPath $override)) { return $override }
39
- $candidate = Join-Path $env:LocalAppData 'Google\Chrome\User Data'
40
- if (-not [string]::IsNullOrWhiteSpace($candidate) -and (Test-Path -LiteralPath $candidate)) { return $candidate }
41
- return $null
42
- }
43
-
44
- function Get-DefaultChromeProfileDirectory([string]$UserDataDir) {
45
- $override = $env:ZORTEX_OAUTH_CHROME_PROFILE_DIRECTORY
46
- if (-not [string]::IsNullOrWhiteSpace($override)) { return $override }
47
- $localState = Join-Path $UserDataDir 'Local State'
48
- if (Test-Path -LiteralPath $localState) {
49
- try {
50
- $state = Get-Content -LiteralPath $localState -Raw | ConvertFrom-Json
51
- $last = [string]$state.profile.last_used
52
- if (-not [string]::IsNullOrWhiteSpace($last)) { return $last }
53
- } catch {}
54
- }
55
- return 'Default'
56
- }
57
-
58
- function Find-FirstExistingPath([string[]]$Paths) {
59
- foreach ($path in $Paths) {
60
- if (-not [string]::IsNullOrWhiteSpace($path) -and (Test-Path -LiteralPath $path)) { return $path }
61
- }
62
- return $null
63
- }
64
-
65
- function Get-ChromeLaunchPath {
66
- $override = $env:ZORTEX_OAUTH_CHROME_BIN
67
- if (-not [string]::IsNullOrWhiteSpace($override) -and (Test-Path -LiteralPath $override)) { return $override }
68
- foreach ($process in @(Get-Process -Name chrome -ErrorAction SilentlyContinue)) {
69
- if (-not [string]::IsNullOrWhiteSpace($process.Path)) { return $process.Path }
70
- }
71
- return Find-FirstExistingPath @(
72
- "$env:ProgramFiles\Google\Chrome\Application\chrome.exe",
73
- "${env:ProgramFiles(x86)}\Google\Chrome\Application\chrome.exe",
74
- "$env:LocalAppData\Google\Chrome\Application\chrome.exe"
75
- )
76
- }
77
-
78
- function Quote-BrowserArgument([string]$Value) {
79
- if ($Value -notmatch '\s|"' ) { return $Value }
80
- return '"' + ($Value -replace '"', '\"') + '"'
81
- }
82
-
83
- function Test-ShouldCloseBrowser([string]$State) {
84
- # Task-owned windows are released before another supported route retries the task.
85
- return $State -in @('code', 'completed', 'accounts', 'failed', 'browser_unsupported', 'ui_drift', 'login_required', 'multiple_accounts')
86
- }
87
-
88
- function Test-Cancellation($Pending) {
89
- return $Pending.IsCompleted -and ($null -eq $Pending.Result -or $Pending.Result -ceq 'cancel')
90
- }
91
-
92
- function Write-Result([hashtable]$Value, [int]$ExitCode = 0) {
93
- if ($script:ForegroundObserved) { $Value.foregroundObserved = $true }
94
- if ($null -ne $script:ConsentDiagnostic) { $Value.consentDiagnostic = $script:ConsentDiagnostic }
95
- if ($script:OAuthTrace.Count -gt 0) { $Value.publicOAuthTrace = Get-PublicOAuthTrace }
96
- if ($script:BackgroundGuardStarted) {
97
- # Counts only, for a tester without PostHog: was the covered window raised, how often revealed, how long the
98
- # renderer had been missing, and how often an emptied foreground was given back.
99
- $waitMs = $(if ($null -ne $script:RendererMissingSince) { [int]([DateTime]::UtcNow - $script:RendererMissingSince).TotalMilliseconds } else { 0 })
100
- $Value.backgroundWindow = @{ raised = [int](Test-BackgroundRaised); reveals = [int]$script:RevealCount;
101
- rendererWaitMs = $waitMs; foregroundReturned = [int][OAuthBackground]::ForegroundReturned }
102
- # Metadata only, before teardown changes the renderer/root lifecycle.
103
- try {
104
- $before = New-Object OAuthBackground+Stats
105
- $readError = [OAuthBackground]::Read([ref]$before)
106
- $Value.backgroundBeforeClose = @{ readError = $readError; heartbeat = [OAuthBackground]::KeepAliveError;
107
- boundHwnd = [long]$before.Bound;
108
- rejectReason = [long][OAuthBackground]::RendererRejectReason();
109
- lease = $before.LeaseActive; stopped = $before.Stopped; overflow = $before.Overflow;
110
- rootAmbiguous = $before.RootAmbiguous; rendererAmbiguous = $before.RendererAmbiguous;
111
- rendererPresent = [int]($before.Renderer -ne 0); generation = $before.Generation;
112
- captured = $before.RendererCaptured; destroyed = $before.RendererDestroyed; seen = $before.RendererSeen }
113
- } catch { $Value.backgroundBeforeClose = @{ readError = -1 } }
114
- try {
115
- $history = [OAuthBackground]::AcceptedRendererHistory()
116
- $rows = @($history.Records | ForEach-Object { @{ hwnd = $_.Hwnd; lifetime = $_.Lifetime;
117
- acceptedGeneration = $_.AcceptedGeneration; destroyed = $_.Destroyed;
118
- activationSeen = $_.ActivationSeen; activationBlocked = $_.ActivationBlocked; focusSeen = $_.FocusSeen } })
119
- $Value.backgroundRendererHistory = @{ readError = $history.ReadError; version = $history.Version;
120
- count = $history.Count; dropped = $history.Dropped; records = $rows }
121
- } catch { $Value.backgroundRendererHistory = @{ readError = -1; records = @() } }
122
- }
123
- try {
124
- $cleanup = Get-Command Close-OwnedBrowser -ErrorAction SilentlyContinue
125
- if ($null -ne $cleanup -and (Test-ShouldCloseBrowser ([string]$Value.state))) { Close-OwnedBrowser ([string]$Value.state) }
126
- elseif ($script:BackgroundGuardStarted -and $script:OwnedBrowserHandle -ne [IntPtr]::Zero) {
127
- # Left for the person: it must be in the taskbar and Alt+Tab again, still behind and not activated.
128
- $id = $script:BackgroundIdentity
129
- $Value.shownForPerson = [int][OAuthBackground]::ShowInSwitcher($script:OwnedBrowserHandle, $id.Pid, $id.Tid, $script:BackgroundNonce)
130
- }
131
- } catch {} finally {
132
- if ($script:BackgroundGuardStarted) {
133
- try {
134
- $guardStats = New-Object OAuthBackground+Stats
135
- $readError = [OAuthBackground]::Read([ref]$guardStats)
136
- $Value.backgroundGuard = @{ blocked = $guardStats.Blocked; passed = $guardStats.Passed; readError = $readError;
137
- heartbeatStopped = [OAuthBackground]::EndKeepAlive(); stopError = [OAuthBackground]::Stop(); reveals = $script:RevealCount }
138
- } catch { $Value.backgroundGuard = @{ stopError = -1; reveals = $script:RevealCount } }
139
- $script:BackgroundGuardStarted = $false
140
- }
141
- if ($script:BackgroundMutexOwned) { $script:BackgroundMutex.ReleaseMutex(); $script:BackgroundMutexOwned = $false }
142
- if ($null -ne $script:BackgroundMutex) { $script:BackgroundMutex.Dispose(); $script:BackgroundMutex = $null }
143
- }
144
- if ($null -ne $script:CleanupDiagnostic) { $Value.backgroundCleanup = $script:CleanupDiagnostic }
145
- [Console]::Out.WriteLine(($Value | ConvertTo-Json -Depth 5 -Compress))
146
- exit $ExitCode
147
- }
148
-
149
- function Confirm-JevControl([string]$Phase, [string]$ControlId, [string]$Role, [int]$RequestedAccountIndex = -1) {
150
- if ($env:ZORTEX_JEV_UIA_MODE -ne '1') { return $true }
151
- $token = [string]$env:ZORTEX_JEV_OAUTH_TOKEN
152
- $rawEndpoint = [string]$env:ZORTEX_JEV_OAUTH_ENDPOINT
153
- if ($token -cnotmatch '^[A-Za-z0-9_-]{24,256}$') { Write-Result @{ state = 'ui_drift'; reason = 'jev_decision_unavailable' } 1 }
154
- try {
155
- $endpoint = [uri]$rawEndpoint
156
- if ($endpoint.Scheme -cne 'http' -or $endpoint.Host -cne '127.0.0.1' -or $endpoint.Port -le 0 -or
157
- -not [string]::IsNullOrEmpty($endpoint.UserInfo) -or -not [string]::IsNullOrEmpty($endpoint.Query) -or
158
- -not [string]::IsNullOrEmpty($endpoint.Fragment)) { throw 'invalid local endpoint' }
159
- $decisionUri = [uri]($endpoint.AbsoluteUri.TrimEnd('/') + '/decision')
160
- $control = @{ id = $ControlId; role = $Role }
161
- $body = @{ version = 1; provider = 'google'; phase = $Phase; controls = @($control) }
162
- if ($RequestedAccountIndex -ge 0) { $body.requestedAccountIndex = $RequestedAccountIndex }
163
- $answer = Invoke-RestMethod -Uri $decisionUri -Method Post -Headers @{ Authorization = "Bearer $token" } `
164
- -ContentType 'application/json' -Body ($body | ConvertTo-Json -Depth 4 -Compress) -TimeoutSec 30 -UseBasicParsing
165
- if ($null -eq $answer) { throw 'empty local decision' }
166
- $fields = @($answer.PSObject.Properties.Name | Sort-Object) -join ','
167
- if ($answer.state -ceq 'selected' -and $fields -ceq 'controlId,state' -and $answer.controlId -ceq $ControlId) {
168
- $script:LastJevPhase = $Phase
169
- return $true
170
- }
171
- if ($answer.state -ceq 'needs_user' -and $fields -ceq 'state') {
172
- Write-Result @{ state = 'ui_drift'; reason = 'jev_decision_unavailable' } 1
173
- }
174
- } catch {}
175
- Write-Result @{ state = 'ui_drift'; reason = 'jev_decision_unavailable' } 1
176
- }
177
-
178
- if ($SelfTestJev) {
179
- if ($env:ZORTEX_JEV_UIA_MODE -ne '1') { Write-Result @{ state = 'failed'; reason = 'jev_mode_not_enabled' } 1 }
180
- Confirm-JevControl 'scope' 'scope:all' 'scope-all' | Out-Null
181
- Write-Result @{ state = 'self_test'; ok = $true }
182
- }
183
-
184
- function Test-CallbackAddress([uri]$Uri, [uri]$Redirect) {
185
- return $Uri.Scheme -eq $Redirect.Scheme -and $Uri.Host -eq $Redirect.Host -and $Uri.Port -eq $Redirect.Port -and $Uri.AbsolutePath -ceq $Redirect.AbsolutePath
186
- }
187
-
188
- function Test-OwnedBrowserCloseCandidate([int]$TabCount, [string]$CurrentTab, [string]$BoundTab, [uri]$CurrentUrl, [uri]$Redirect) {
189
- return $TabCount -eq 1 -and -not [string]::IsNullOrWhiteSpace($BoundTab) -and
190
- $CurrentTab -ceq $BoundTab -and $null -ne $CurrentUrl -and
191
- (Test-CallbackAddress $CurrentUrl $Redirect)
192
- }
193
-
194
- function Test-OwnedDiscoveryCloseCandidate([int]$TabCount, [string]$CurrentTab, [string]$BoundTab, [uri]$CurrentUrl) {
195
- return $TabCount -eq 1 -and -not [string]::IsNullOrWhiteSpace($BoundTab) -and
196
- $CurrentTab -ceq $BoundTab -and $null -ne $CurrentUrl -and
197
- $CurrentUrl.Scheme -eq 'https' -and $CurrentUrl.Host -eq 'accounts.google.com' -and
198
- $CurrentUrl.AbsolutePath -ceq '/v3/signin/accountchooser'
199
- }
200
-
201
- function Test-OwnedAutomaticCloseCandidate([int]$TabCount, [string]$CurrentTab, [string]$BoundTab, [uri]$CurrentUrl) {
202
- if (-not $script:Automatic -or $TabCount -ne 1 -or [string]::IsNullOrWhiteSpace($BoundTab) -or
203
- $CurrentTab -cne $BoundTab -or $null -eq $CurrentUrl -or
204
- -not (Test-AllowedOrigin $script:request.provider $CurrentUrl $script:redirect)) { return $false }
205
- if ($script:request.provider -eq 'notion') { return Test-NotionTransaction $CurrentUrl $script:expectedClientId $script:expectedState }
206
- $query = [Web.HttpUtility]::ParseQueryString($CurrentUrl.Query)
207
- return $query.Get('state') -ceq $script:expectedState -and $query.Get('client_id') -ceq $script:expectedClientId
208
- }
209
-
210
- function Test-OwnedGoogleTransitionClose([int]$TabCount, [string]$CurrentTab, [string]$BoundTab, [uri]$CurrentUrl) {
211
- # Google drops state on its warning/consent URL. Close only the original,
212
- # previously transaction-bound sole tab, with the same explicit client_id.
213
- # The caller also requires the native newly-created nonce root and live veto.
214
- if (-not $script:Automatic -or -not $script:OwnedTransactionBound -or $script:request.provider -cne 'google' -or
215
- $TabCount -ne 1 -or [string]::IsNullOrWhiteSpace($BoundTab) -or $CurrentTab -cne $BoundTab -or
216
- $null -eq $CurrentUrl -or $CurrentUrl.Scheme -cne 'https' -or $CurrentUrl.Host -cne 'accounts.google.com' -or
217
- $CurrentUrl.AbsolutePath -cnotmatch '^/signin/oauth/(?:warning|delegation|(?:v2/)?consent(?:summary)?)$') { return $false }
218
- $query = [Web.HttpUtility]::ParseQueryString($CurrentUrl.Query)
219
- return @($query.GetValues('client_id')).Count -eq 1 -and $query.Get('client_id') -ceq $script:expectedClientId -and
220
- ([string]::IsNullOrEmpty($query.Get('state')) -or $query.Get('state') -ceq $script:expectedState)
221
- }
222
-
223
- function Get-OAuthCallbackResult([uri]$Uri, [uri]$Redirect, [string]$ExpectedState) {
224
- if (-not (Test-CallbackAddress $Uri $Redirect)) { return $null }
225
- $query = [Web.HttpUtility]::ParseQueryString($Uri.Query)
226
- if ($query.Get('state') -cne $ExpectedState) { return @{ state = 'failed'; reason = 'state_mismatch' } }
227
- if (-not [string]::IsNullOrEmpty($query.Get('error'))) { return @{ state = 'failed'; reason = 'provider_error' } }
228
- if (-not [string]::IsNullOrEmpty($query.Get('code'))) { return @{ state = 'code'; code = $query.Get('code') } }
229
- return @{ state = 'completed' }
230
- }
231
-
232
- function Get-NotionCallbackResult([uri]$Uri, [uri]$Redirect, [string]$ExpectedState) {
233
- if (-not (Test-CallbackAddress $Uri $Redirect)) { return $null }
234
- $query = [Web.HttpUtility]::ParseQueryString($Uri.Query)
235
- if (@($query.GetValues('state')).Count -ne 1 -or $query.Get('state') -cne $ExpectedState) { return @{ state = 'failed'; reason = 'state_mismatch' } }
236
- if ($query.Get('error')) { return @{ state = 'failed'; reason = 'provider_error' } }
237
- if (@($query.GetValues('ticket')).Count -ne 1 -or $query.Get('ticket') -cnotmatch '^n1\.ticket\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+$') { return @{ state = 'failed'; reason = 'invalid_handoff' } }
238
- return @{ state = 'completed' }
239
- }
240
- function Test-NotionLoginPage([uri]$Uri) {
241
- return $null -ne $Uri -and $Uri.Scheme -ceq 'https' -and $Uri.Host -in @('app.notion.com', 'www.notion.so', 'notion.so') -and
242
- $Uri.AbsolutePath -match '^/(?:login|signup)(?:/|$)'
243
- }
244
- function Test-NotionTransaction([uri]$Uri, [string]$ClientId, [string]$State) {
245
- $query = [Web.HttpUtility]::ParseQueryString($Uri.Query)
246
- if (@($query.GetValues('state')).Count -ne 1 -or $query.Get('state') -cne $State -or $Uri.Scheme -ne 'https') { return $false }
247
- if ($Uri.Host -ceq 'zortex-auth.pages.dev' -and $Uri.AbsolutePath -ceq '/notion/authorize') { return $true }
248
- return $Uri.Host -in @('api.notion.com', 'app.notion.com', 'www.notion.so', 'notion.so') -and
249
- @($query.GetValues('client_id')).Count -eq 1 -and $query.Get('client_id') -ceq $ClientId
250
- }
251
- function Test-NotionSelectedCheckbox([string]$ControlType, [bool]$Visible, [string]$ToggleState) {
252
- # Accessible page checkboxes can have an empty Name. Selection depends only on
253
- # the actual page control type, visibility and provider's current toggle state.
254
- return $ControlType -ceq 'ControlType.CheckBox' -and $Visible -and $ToggleState -ceq 'On'
255
- }
256
- function Test-NotionNamedControl($Item, [string]$ControlType) {
257
- return $null -ne $Item -and [string]$Item['kind'] -ceq 'current_name' -and
258
- [bool]$Item['visible'] -and [string]$Item['controlType'] -ceq $ControlType
259
- }
260
- function Get-NotionSelectedPageCount($Elements) {
261
- $count = 0
262
- foreach ($element in $Elements) {
263
- try {
264
- if ([string]$element.Current.ControlType.ProgrammaticName -cne 'ControlType.CheckBox') { continue }
265
- $rect = $element.Current.BoundingRectangle
266
- $visible = -not $element.Current.IsOffscreen -and -not $rect.IsEmpty -and $rect.Width -gt 0 -and $rect.Height -gt 0
267
- $toggle = Get-Pattern $element ([Windows.Automation.TogglePattern]::Pattern)
268
- if ($null -ne $toggle -and (Test-NotionSelectedCheckbox ([string]$element.Current.ControlType.ProgrammaticName) $visible ([string]$toggle.Current.ToggleState))) { $count++ }
269
- } catch {}
270
- }
271
- return $count
272
- }
273
- function Test-NotionSelectionEvidence([int]$SelectedPages, $Named) {
274
- return $SelectedPages -gt 0 -or @($Named | Where-Object {
275
- (Test-NotionNamedControl $_ 'ControlType.Text') -and
276
- ([string]$_['name']).Trim() -match '(?i)^(?:[1-9][0-9]* pages? selected|\u5df2\u9078\u53d6\s*[1-9][0-9]*\s*\u500b\u9801\u9762|\u5df2\u9078\u64c7\s*[1-9][0-9]*\s*\u500b\u9801\u9762|\u5df2\u9009\u62e9\s*[1-9][0-9]*\s*\u4e2a\u9875\u9762)$'
277
- }).Count -gt 0
278
- }
279
- function Get-NotionFreshConsent($Elements, $Named, [string]$ExpectedName, [string]$ExpectedAction) {
280
- $selectedPages = Get-NotionSelectedPageCount $Elements
281
- $hasSelectedPages = Test-NotionSelectionEvidence $selectedPages $Named
282
- $result = @{ selectedPages = $selectedPages; hasSelectedPages = $hasSelectedPages; target = $null }
283
- if ($ExpectedAction -ceq 'allow' -and -not $hasSelectedPages) { return $result }
284
- $seen = [Collections.Generic.HashSet[string]]::new()
285
- $targets = @()
286
- foreach ($candidate in $Named) {
287
- if (-not (Test-NotionNamedControl $candidate 'ControlType.Button') -or [string]$candidate['name'] -cne $ExpectedName -or
288
- (Get-NotionConsentAction ([string]$candidate['name']) $hasSelectedPages) -cne $ExpectedAction) { continue }
289
- try {
290
- $element = $candidate['element']
291
- if ([string]$element.Current.Name -cne $ExpectedName -or -not (Test-FreshActionable $element)) { continue }
292
- if ($seen.Add(($element.GetRuntimeId() -join '.'))) { $targets += $element }
293
- } catch { if (Test-BackgroundGuardException $_) { throw } }
294
- }
295
- if ($targets.Count -eq 1) { $result.target = $targets[0] }
296
- return $result
297
- }
298
- function Test-NotionPageSection([string]$Name, [string]$ExpandState) {
299
- return $ExpandState -ceq 'Collapsed' -and $Name.Trim().ToLowerInvariant() -in @('private', [regex]::Unescape('\u79c1\u4eba'), [regex]::Unescape('\u79c1\u6709'))
300
- }
301
- function Get-NotionConsentAction([string]$Name, [bool]$HasSelectedPages) {
302
- $normalized = $Name.Trim().ToLowerInvariant()
303
- if ($normalized -in @('select pages', 'select pages to access', [regex]::Unescape('\u9078\u53d6\u9801\u9762'), [regex]::Unescape('\u9078\u64c7\u9801\u9762'), [regex]::Unescape('\u9009\u62e9\u9875\u9762'), [regex]::Unescape('\u9009\u53d6\u9875\u9762'))) { return 'picker' }
304
- if ($HasSelectedPages -and $normalized -in @('allow access', 'allow', [regex]::Unescape('\u5141\u8a31\u5b58\u53d6'), [regex]::Unescape('\u5141\u8a31\u5b58\u53d6\u6b0a\u9650'), [regex]::Unescape('\u5141\u8bb8\u8bbf\u95ee'), [regex]::Unescape('\u5141\u8a31'), [regex]::Unescape('\u5141\u8bb8'))) { return 'allow' }
305
- return ''
306
- }
307
- function Resolve-NotionSelection([bool]$HasSelectedPages, [bool]$HasAllowButton, [string]$Page, $Previous, [DateTime]$Now) {
308
- # The allow button can render before the remembered checkboxes. Do not turn
309
- # that transient snapshot into a request for new permissions.
310
- if ($HasSelectedPages -or -not $HasAllowButton) { return @{ action = 'proceed'; page = $Page; since = $null } }
311
- $since = $Now
312
- if ($null -ne $Previous -and $Previous.page -ceq $Page -and $null -ne $Previous.since) { $since = $Previous.since }
313
- $action = $(if (($Now - $since).TotalMilliseconds -lt 5000) { 'wait' } else { 'needs_selection' })
314
- return @{ action = $action; page = $Page; since = $since }
315
- }
316
- function Test-OAuthTransaction($Query, [string]$ClientId, [string]$State) {
317
- return $Query.Get('client_id') -ceq $ClientId -and $Query.Get('state') -ceq $State
318
- }
319
-
320
- function Test-AllowedOrigin([string]$Provider, [uri]$Uri, [uri]$Redirect) {
321
- if (Test-CallbackAddress $Uri $Redirect) { return $true }
322
- if ($Uri.Scheme -ne "https") { return $false }
323
- if ($Provider -eq "notion") {
324
- return ($Uri.Host -ceq 'zortex-auth.pages.dev' -and $Uri.AbsolutePath -in @('/notion/authorize', '/notion/callback')) -or
325
- $Uri.Host -in @('api.notion.com', 'app.notion.com', 'www.notion.so', 'notion.so')
326
- }
327
- if ($Provider -eq "google") { return $Uri.Host -eq "accounts.google.com" }
328
- if ($Provider -eq "slack") { return $Uri.Host -eq "slack.com" -or $Uri.Host.EndsWith(".slack.com") }
329
- # A personal Microsoft account signs in on login.live.com and grants consent on
330
- # account.live.com/Consent/Update ("Let this app access your info?").
331
- return $Uri.Host -in @("login.microsoftonline.com", "login.live.com", "account.live.com")
332
- }
333
-
334
- function Test-MicrosoftSignedInAccount([string]$Name) {
335
- # On login.microsoftonline.com an already-signed-in account is offered as one row named
336
- # "<display name> <email> <Signed in>". The "signed in" marker (and its CJK forms) is what
337
- # separates a usable account row from the plain email-entry field, so match both together.
338
- if ($Name -notmatch '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}') { return $false }
339
- return $Name -match ("(?i)signed in|" + [string][char]0x5df2 + [string][char]0x767b + [string][char]0x5f55 + "|" + [string][char]0x5df2 + [string][char]0x767b + [string][char]0x5165 + "|" + [string][char]0x5df2 + [string][char]0x767b + [string][char]0x9304)
340
- }
341
-
342
- function Get-MicrosoftSignedInEmails($Named) {
343
- return @($Named | Where-Object { Test-MicrosoftSignedInAccount ([string]$_.name) } | ForEach-Object {
344
- [regex]::Match([string]$_.name, '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}').Value.ToLowerInvariant()
345
- } | Sort-Object -Unique)
346
- }
347
-
348
- function Test-MicrosoftPersonalEmail([string]$Email) {
349
- # Work and school (Entra) accounts can only use domains their organization verified, and
350
- # consumer mail domains can never be verified that way. A row on one of these domains is
351
- # therefore a personal Microsoft account; every other domain may be work or school.
352
- $domain = $Email.Split('@')[-1].ToLowerInvariant()
353
- if ($domain -match '^(?:outlook|hotmail|live|msn)\.(?:com|[a-z]{2}|co\.[a-z]{2}|com\.[a-z]{2})$') { return $true }
354
- return $domain -in @('passport.com', 'windowslive.com', 'gmail.com', 'googlemail.com', 'yahoo.com', 'ymail.com',
355
- 'icloud.com', 'me.com', 'mac.com', 'aol.com', 'proton.me', 'protonmail.com', 'gmx.com', 'gmx.net',
356
- 'yandex.com', 'mail.com', 'qq.com', 'foxmail.com', '163.com', '126.com', 'yeah.net', 'sina.com', 'sohu.com')
357
- }
358
-
359
- function Get-MicrosoftAccountKind([string]$Name, [string]$Email) {
360
- # Microsoft's chooser button states the account type ("... work or school account." /
361
- # "... personal Microsoft account."); when it does not, fall back to the mail domain.
362
- if ($Name -match '(?i)work or school|school account|work account|organi[sz]ation|\u5de5\u4f5c\u6216\u5b66\u6821|\u5de5\u4f5c\u6216\u5b78\u6821|\u5b66\u6821\u5e10\u6237|\u5b78\u6821\u5e33\u6236|\u5de5\u4f5c\u5e10\u6237|\u5de5\u4f5c\u5e33\u6236|\u7ec4\u7ec7|\u7d44\u7e54') { return 'work' }
363
- if ($Name -match '(?i)personal|\u4e2a\u4eba|\u500b\u4eba') { return 'personal' }
364
- if (Test-MicrosoftPersonalEmail $Email) { return 'personal' }
365
- return 'unknown'
366
- }
367
-
368
- function Test-SameRectangle($A, $B) {
369
- try {
370
- $a = $A.Current.BoundingRectangle; $b = $B.Current.BoundingRectangle
371
- return -not $a.IsEmpty -and -not $b.IsEmpty -and [Math]::Abs($a.Left - $b.Left) -le 4 -and [Math]::Abs($a.Top - $b.Top) -le 4 -and
372
- [Math]::Abs($a.Width - $b.Width) -le 4 -and [Math]::Abs($a.Height - $b.Height) -le 4
373
- } catch { return $false }
374
- }
375
-
376
- function Get-MicrosoftAccountChoices($Named) {
377
- # Chrome exposes each chooser row twice at one rectangle: a passive ListItem
378
- # ("<name><email>Signed in") and the clickable Button ("Sign in with <email> <type> account.").
379
- # A ListItem accepts SelectionItem.Select() without navigating, so prefer the Button.
380
- $emailPattern = '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
381
- $rows = @(@($Named) | Where-Object { $null -ne $_ -and (Test-MicrosoftSignedInAccount ([string]$_['name'])) })
382
- $choices = @(); $index = 0
383
- foreach ($candidate in @($Named)) {
384
- $index++
385
- if ($null -eq $candidate) { continue }
386
- if ([string]$candidate['controlType'] -cne 'ControlType.Button' -or ($candidate.ContainsKey('visible') -and -not [bool]$candidate['visible'])) { continue }
387
- $name = [string]$candidate['name']
388
- $email = [regex]::Match($name, $emailPattern).Value
389
- if (-not $email -or $name -match '(?i)menu|more options|remove|forget|sign out|\u83dc\u5355|\u79fb\u9664|\u5220\u9664|\u522a\u9664|\u6ce8\u9500|\u767b\u51fa') { continue }
390
- $row = @($rows | Where-Object { $null -ne $candidate['element'] -and $null -ne $_['element'] -and (Test-SameRectangle $candidate['element'] $_['element']) } | Select-Object -First 1)
391
- $choices += @{ element = $candidate['element']; name = $name; email = $email.ToLowerInvariant(); kind = (Get-MicrosoftAccountKind $name $email); signedIn = ($row.Count -gt 0); button = $true; order = $index }
392
- }
393
- if ($choices.Count -eq 0) {
394
- $index = 0
395
- foreach ($row in $rows) {
396
- $index++
397
- $email = [regex]::Match([string]$row['name'], $emailPattern).Value
398
- $choices += @{ element = $row['element']; name = [string]$row['name']; email = $email.ToLowerInvariant(); kind = (Get-MicrosoftAccountKind '' $email); signedIn = $true; button = $false; order = $index }
399
- }
400
- }
401
- return @($choices | Sort-Object { try { $_['element'].Current.BoundingRectangle.Top } catch { 0 } }, { $_['order'] })
402
- }
403
-
404
- function Select-MicrosoftPersonalAccount($Choices) {
405
- # Prefer a signed-in personal account, then another available signed-in account.
406
- $personal = @(@($Choices) | Where-Object { $null -ne $_ -and $_['kind'] -ceq 'personal' })
407
- $signedIn = @($personal | Where-Object { $_['signedIn'] })
408
- if ($signedIn.Count -gt 0) { return $signedIn[0] }
409
- if ($personal.Count -gt 0) { return $personal[0] }
410
- $available = @(@($Choices) | Where-Object { $null -ne $_ })
411
- $signedIn = @($available | Where-Object { $_['signedIn'] })
412
- if ($signedIn.Count -gt 0) { return $signedIn[0] }
413
- if ($available.Count -gt 0) { return $available[0] }
414
- return $null
415
- }
416
-
417
- function Select-MicrosoftPersonalAccountRow($Rows) {
418
- $choice = Select-MicrosoftPersonalAccount (Get-MicrosoftAccountChoices $Rows)
419
- if ($null -eq $choice) { return $null }
420
- return @{ name = $choice['name']; element = $choice['element'] }
421
- }
422
-
423
- function Get-GoogleAdvancedControlNames {
424
- # Expanding the notice is a toggle: pressing it again hides the approved continue link.
425
- return @('Advanced', 'Show advanced', 'Show advanced settings',
426
- ([regex]::Unescape('\u9ad8\u7ea7')), ([regex]::Unescape('\u663e\u793a\u9ad8\u7ea7')), ([regex]::Unescape('\u663e\u793a\u9ad8\u7ea7\u8bbe\u7f6e')),
427
- ([regex]::Unescape('\u9032\u968e')), ([regex]::Unescape('\u986f\u793a\u9032\u968e\u8a2d\u5b9a')))
428
- }
429
-
430
- function Get-GoogleWarningContinueNames {
431
- return @('Go to Zortex (unsafe)', ([regex]::Unescape('\u8f6c\u81f3Zortex\uff08\u4e0d\u5b89\u5168\uff09')),
432
- ([regex]::Unescape('\u524d\u5f80\u300cZortex\u300d(\u4e0d\u5b89\u5168)')),
433
- ([regex]::Unescape('\u524d\u5f80\u300cZortex\u300d\uff08\u4e0d\u5b89\u5168\uff09')))
434
- }
435
-
436
- function Get-GoogleWarningControlNames {
437
- # Provider OAuth notice for the explicitly authorized Zortex client, reached
438
- # only after origin/client/state binding. Never match an arbitrary unsafe app.
439
- return @(Get-GoogleAdvancedControlNames) + @(Get-GoogleWarningContinueNames)
440
- }
441
-
442
- function Test-GoogleAdvancedControl([string]$Name) {
443
- return $Name.Trim() -in @(Get-GoogleAdvancedControlNames)
444
- }
445
-
446
- function Get-GoogleClickableConsentNames([bool]$AdvancedDone) {
447
- return @(Get-GoogleConsentControlNames | Where-Object { -not ($AdvancedDone -and (Test-GoogleAdvancedControl $_)) })
448
- }
449
-
450
- function Get-OAuthClickCategory([string]$Name) {
451
- # Diagnostics carry a category, never the control's accessible name.
452
- if (Test-GoogleAdvancedControl $Name) { return 'advanced' }
453
- if ($Name.Trim() -in @(Get-GoogleWarningContinueNames)) { return 'notice-continue' }
454
- if (Test-ConsentControl 'google' $Name) { return 'consent' }
455
- return 'other'
456
- }
457
-
458
- function Add-OAuthTrace([string]$Path, [string]$Category, [string]$Via) {
459
- if ($script:OAuthTrace.Count -lt 30) { $script:OAuthTrace.Add("${Path}:$Category/$Via") }
460
- }
461
-
462
- function Format-OAuthTrace {
463
- return ($script:OAuthTrace -join ',')
464
- }
465
-
466
- function Get-PublicOAuthTrace {
467
- # Only fixed public provider paths and enumerated action categories leave the
468
- # helper. Unknown paths lose their detail; queries and control text never pass.
469
- $paths = @('/v3/signin/accountchooser', '/signin/oauth/warning', '/signin/oauth/delegation',
470
- '/signin/oauth/v2/consent', '/signin/oauth/v2/consentsummary', '/signin/oauth/consent', '/signin/oauth/consentsummary',
471
- '/o/oauth2/v2/auth', '/oauth/v2/authorize', '/oauth/authorize', '/Consent/Update',
472
- '/common/oauth2/v2.0/authorize', '/common/oauth2/authorize', '/oauth2/authorize', '/install-integration', '/notion/authorize', '/notion/callback', '/callback')
473
- $result = @()
474
- foreach ($entry in $script:OAuthTrace) {
475
- if ($entry -cnotmatch '^(?<path>/[^:?@ ]*):(?<category>[a-z-]+)/(?<via>[a-z-]+)$') { continue }
476
- $path = $(if ($Matches.path -cin $paths) { $Matches.path } else { '/other' })
477
- $category = $Matches.category; $via = $Matches.via
478
- if ($category -cnotin @('account', 'consent', 'advanced', 'notice-continue', 'scope', 'other', 'page-hidden', 'consent-stuck') -or
479
- $via -cnotin @('uia', 'msaa', 'helper', 'nudge', 'background-reveal', 'reveal-moved')) { continue }
480
- $result += "${path}:$category/$via"
481
- }
482
- return ($result -join ',')
483
- }
484
-
485
- function Test-StuckPageRecovery([IntPtr]$Handle, [DateTime]$Since, [DateTime]$LastNudge, [uri]$CurrentUrl = $null,
486
- [ValidateSet('page', 'advanced', 'notion-picker', 'notion-private')][string]$RefreshPhase = 'page') {
487
- # Retry accessibility in place. Never activate the OAuth window to recover a page.
488
- $now = [DateTime]::UtcNow
489
- if (($now - $Since).TotalMilliseconds -lt 3000 -or ($now - $LastNudge).TotalMilliseconds -lt 3000) { return $false }
490
- if ($Handle -ne [IntPtr]::Zero) {
491
- if ($script:BackgroundGuardStarted -and $null -ne $CurrentUrl -and -not [string]::IsNullOrWhiteSpace($script:boundTab)) {
492
- # A document can exist while a background page's next UI state has not
493
- # appeared. An already-invoked Advanced action gets one separate refresh
494
- # at the same URL. Retain the prior-click marker and never click again.
495
- $refresh = Request-BackgroundPage $Handle $script:boundTab $CurrentUrl $Since $RefreshPhase
496
- if ($refresh -eq 'revealed') { Add-OAuthTrace $CurrentUrl.AbsolutePath 'consent-stuck' 'background-reveal' }
497
- }
498
- Request-ChromiumPageAccessibility $Handle
499
- }
500
- return $true
501
- }
502
-
503
- function Get-GoogleConsentControlNames {
504
- # The caller has already bound this page to the current OAuth transaction.
505
- $names = @('Allow', 'Continue', ([regex]::Unescape('\u5141\u8bb8')), ([regex]::Unescape('\u7ee7\u7eed')),
506
- ([regex]::Unescape('\u5141\u8a31')), ([regex]::Unescape('\u7e7c\u7e8c')))
507
- $names += @(Get-GoogleWarningControlNames)
508
- return $names
509
- }
510
-
511
- function Get-JevGoogleConsentControlNames {
512
- return @(Get-GoogleConsentControlNames)
513
- }
514
-
515
- function Test-JevGoogleUnverified($Named) {
516
- foreach ($candidate in $Named) {
517
- $name = [string]$candidate.name
518
- if ($name -match '(?i)hasn.t verified this app|isn.t verified|unverified app|go to zortex \(unsafe\)|\u672a\u7d93 Google \u9a57\u8b49|\u672a\u7ecf Google \u9a8c\u8bc1|\u4e0d\u5b89\u5168') { return $true }
519
- if ($name.Trim() -in @(Get-GoogleWarningControlNames)) { return $true }
520
- }
521
- return $false
522
- }
523
-
524
- function Test-JevApprovedUnverifiedTest([string]$ClientId, $Named, [string]$Path) {
525
- return -not [string]::IsNullOrEmpty($ClientId) -and
526
- $Path -cmatch '^/signin/oauth(?:/|$)' -and (Test-JevGoogleUnverified $Named)
527
- }
528
-
529
- function Get-JevTestNoticeAction($Named) {
530
- $advancedNames = @('Advanced', 'Show advanced', 'Show advanced settings',
531
- ([regex]::Unescape('\u9ad8\u7ea7')), ([regex]::Unescape('\u9032\u968e')),
532
- ([regex]::Unescape('\u986f\u793a\u9032\u968e\u8a2d\u5b9a')))
533
- $continueNames = @('Go to Zortex (unsafe)',
534
- ([regex]::Unescape('\u8f6c\u81f3Zortex\uff08\u4e0d\u5b89\u5168\uff09')),
535
- ([regex]::Unescape('\u524d\u5f80\u300cZortex\u300d(\u4e0d\u5b89\u5168)')),
536
- ([regex]::Unescape('\u524d\u5f80\u300cZortex\u300d\uff08\u4e0d\u5b89\u5168\uff09')))
537
- foreach ($phase in @('continue', 'advanced')) {
538
- $names = $(if ($phase -eq 'continue') { $continueNames } else { $advancedNames })
539
- $seen = [Collections.Generic.HashSet[string]]::new()
540
- $matches = @($Named | Where-Object {
541
- [string]$_['kind'] -ceq 'current_name' -and [bool]$_['visible'] -and
542
- [string]$_.name -cin $names -and (Test-FreshActionable $_.element) -and
543
- $seen.Add(($_.element.GetRuntimeId() -join '.'))
544
- })
545
- if ($matches.Count -eq 1) { return @{ id = "notice:$phase"; role = "notice-$phase"; name = [string]$matches[0].name; element = $matches[0].element } }
546
- if ($matches.Count -gt 1) { return $null }
547
- }
548
- return $null
549
- }
550
-
551
- function Test-JevGoogleConsentContext($Named, [string]$Path) {
552
- if ($Path -cnotmatch '^/signin/oauth(?:/|$)' -or (Test-JevGoogleUnverified $Named)) { return $false }
553
- foreach ($candidate in $Named) {
554
- # The app identity must be the accessible Name of a visible heading/text
555
- # element. A button HelpText or editable Value can echo a misleading phrase.
556
- if ([string]$candidate['kind'] -cne 'current_name' -or -not [bool]$candidate['visible'] -or
557
- [string]$candidate['controlType'] -notin @('ControlType.Header', 'ControlType.Text')) { continue }
558
- $name = ([string]$candidate.name).Trim()
559
- if ($name -match '(?i)^Zortex\s+(?:wants (?:to )?access(?: to your Google Account)?|\u8981\u6c42\u5b58\u53d6|\u8bf7\u6c42\u8bbf\u95ee|\u60f3\u5b58\u53d6\u60a8\u7684 Google \u5e33\u6236)$') { return $true }
560
- }
561
- return $false
562
- }
563
-
564
- function Test-JevApprovedConsentTest([string]$ClientId, $Named, [string]$Path, [string]$LastNoticeId) {
565
- # A provider can retain warning text after its continuation has been activated.
566
- if ([string]::IsNullOrEmpty($ClientId) -or
567
- $LastNoticeId -cne 'notice:continue' -or
568
- $Path -cnotmatch '^/signin/oauth/(?:v\d+/)?consent(?:/|$)') { return $false }
569
- $appNames = @($Named | Where-Object {
570
- [string]$_['kind'] -ceq 'current_name' -and [bool]$_['visible'] -and
571
- [string]$_['controlType'] -in @('ControlType.Header', 'ControlType.Text') -and
572
- [string]$_.name -match '(?i)\bZortex\b'
573
- })
574
- $noticeControls = @($Named | Where-Object {
575
- [string]$_['kind'] -ceq 'current_name' -and [bool]$_['visible'] -and
576
- [string]$_.name -cin @(Get-GoogleWarningControlNames)
577
- })
578
- $consentControls = @($Named | Where-Object {
579
- [string]$_['kind'] -ceq 'current_name' -and [bool]$_['visible'] -and
580
- [string]$_.name -cin @(Get-JevGoogleConsentControlNames)
581
- })
582
- return $appNames.Count -gt 0 -and $noticeControls.Count -eq 0 -and $consentControls.Count -eq 1
583
- }
584
-
585
- function Test-ConsentControl([string]$Provider, [string]$Name) {
586
- $normalized = $Name.Trim().ToLowerInvariant()
587
- $allow = [string][char]0x5141 + [string][char]0x8bb8
588
- $allowTraditional = [string][char]0x5141 + [string][char]0x8a31
589
- $continue = [string][char]0x7ee7 + [string][char]0x7eed
590
- $accept = [string][char]0x63a5 + [string][char]0x53d7
591
- $yes = [string][char]0x662f
592
- if ($Provider -eq "google") {
593
- $allowed = @(if ($env:ZORTEX_JEV_UIA_MODE -eq '1') { Get-JevGoogleConsentControlNames } else { Get-GoogleConsentControlNames })
594
- return $normalized -in $allowed
595
- }
596
- return $normalized -in @('accept', 'yes', 'continue', 'allow', $accept, $yes, $continue, $allow, $allowTraditional)
597
- }
598
-
599
- function Test-AccountChooserPage($Named, [string]$Path = '') {
600
- # Called only after the current tab's origin, client and state have been bound.
601
- if ($Path -ceq '/v3/signin/accountchooser') { return $true }
602
- foreach ($candidate in $Named) {
603
- $normalized = ([string]$candidate.name).Trim().ToLowerInvariant()
604
- # Google's signing-back-in page (/signin/oauth/id) names the chosen account in a "Selected <account>. Switch account"
605
- # link (zh-CN 2026-10-22), whose wording also reads as "choose ... account"; it offers no account to choose.
606
- if ($normalized -match '(?i)switch account|(?:\u5207\u6362|\u5207\u63db)(?:\u8d26|\u5e10|\u5e33|\u8cec)(?:\u53f7|\u6237|\u865f|\u6236)') { continue }
607
- if ($normalized -match '(?i)choose an account|use another account|\u9009\u62e9.*(\u8d26|\u5e10)\u53f7|\u4f7f\u7528\u5176\u4ed6.*(\u8d26|\u5e10)\u53f7|\u9078\u64c7.*(?:\u5e33|\u8cec)(?:\u6236|\u865f)|\u4f7f\u7528\u5176\u4ed6.*(?:\u5e33|\u8cec)(?:\u6236|\u865f)') { return $true }
608
- }
609
- return $false
610
- }
611
-
612
- function Test-GoogleAccountCandidate([string]$Name) {
613
- $normalized = $Name.Trim()
614
- if ([string]::IsNullOrWhiteSpace($normalized)) { return $false }
615
- $emails = @([regex]::Matches($normalized, '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'))
616
- if ($emails.Count -ne 1) { return $false }
617
- $outsideEmail = $normalized.Remove($emails[0].Index, $emails[0].Length)
618
- return $outsideEmail -notmatch '(?i)choose an account|use another account|to continue|zortex|\b(remove|delete|manage|sign out|log ?out|disconnect|forget)\b|\u79fb\u9664|\u522a\u9664|\u7ba1\u7406|\u9000\u51fa|\u9009\u62e9.*(\u8d26|\u5e10)\u53f7|\u4f7f\u7528\u5176\u4ed6.*(\u8d26|\u5e10)\u53f7|\u9078\u64c7.*(?:\u5e33|\u8cec)(?:\u6236|\u865f)|\u4f7f\u7528\u5176\u4ed6.*(?:\u5e33|\u8cec)(?:\u6236|\u865f)|\u767b\u51fa|\u7e7c\u7e8c'
619
- }
620
-
621
- function Test-GoogleAccountAmbiguity([int]$AccountCount, $Named) {
622
- $emails = @($Named | Where-Object { Test-GoogleAccountCandidate ([string]$_.name) } | ForEach-Object {
623
- [regex]::Matches([string]$_.name, '[^@\s]+@[^@\s]+\.[^@\s]+') | ForEach-Object { $_.Value.ToLowerInvariant() }
624
- } | Sort-Object -Unique)
625
- return $AccountCount -gt 1 -or $emails.Count -gt 1
626
- }
627
-
628
- function Get-GoogleAccountEmail([string]$Name) {
629
- if (-not (Test-GoogleAccountCandidate $Name)) { return $null }
630
- $matches = @([regex]::Matches($Name, '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'))
631
- if ($matches.Count -ne 1) { return $null }
632
- return $matches[0].Value.ToLowerInvariant()
633
- }
634
-
635
- function Get-GoogleVisibleAccountEmails($Candidates) {
636
- # Only an actionable element names an account row. Chrome exposes each row's passive
637
- # ListItem with the display name glued onto the email ("Ada Lovelaceada@..."), which
638
- # would read as a second, nonexistent address.
639
- return @($Candidates | Where-Object { $_.actionable } | ForEach-Object { Get-GoogleAccountEmail ([string]$_.name) } |
640
- Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Sort-Object -Unique)
641
- }
642
-
643
- function Select-UsableGoogleMsaaEmails($MsaaEmails, $Candidates) {
644
- # MSAA can read a signed-out row without its status text. Drop an address the chooser
645
- # shows only on rejected actionable rows, so both trees describe the same usable accounts.
646
- $visible = @(Get-GoogleVisibleAccountEmails $Candidates)
647
- $rejected = @($Candidates | Where-Object { $_.actionable -and -not (Test-GoogleAccountCandidate ([string]$_.name)) } | ForEach-Object {
648
- [regex]::Matches([string]$_.name, '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}') | ForEach-Object { $_.Value.ToLowerInvariant() }
649
- })
650
- return @($MsaaEmails | Where-Object { $_ -in $visible -or $_ -notin $rejected })
651
- }
652
-
653
- function Resolve-TabBinding([string]$CurrentTab, [string]$BoundTab, [bool]$TransactionMatches, $MismatchSince, [datetime]$Now, [int]$WindowMs) {
654
- # Keep acting only on the OAuth tab we bound. The same tab proceeds; a different tab that still
655
- # carries the expected OAuth transaction is a legitimate rebind; anything else waits out a bounded
656
- # window (a navigation can briefly report no selected tab or drop the query) and only then fails.
657
- # While waiting, the caller must not act — the tab is unverified.
658
- if ($CurrentTab -ceq $BoundTab) { return @{ action = 'proceed'; boundTab = $BoundTab } }
659
- if (-not [string]::IsNullOrWhiteSpace($CurrentTab) -and $TransactionMatches) { return @{ action = 'proceed'; boundTab = $CurrentTab } }
660
- if ($null -ne $MismatchSince -and -not (Test-StillSettling $MismatchSince $Now $WindowMs)) { return @{ action = 'fail'; boundTab = $BoundTab } }
661
- return @{ action = 'wait'; boundTab = $BoundTab }
662
- }
663
-
664
- function Test-StillSettling($Since, [datetime]$Now, [int]$WindowMs) {
665
- # $Since is when this unresolved state was first seen; $null means it is being seen now.
666
- if ($null -eq $Since) { return $true }
667
- return ($Now - [datetime]$Since).TotalMilliseconds -lt $WindowMs
668
- }
669
-
670
- function Test-PageContentMissing([int]$DocumentCount) {
671
- # During a navigation Chrome briefly exposes no page document; then only browser chrome is named.
672
- return $DocumentCount -eq 0
673
- }
674
-
675
- function Test-DocumentContentAvailable([bool]$Offscreen, [int]$ElementCount) {
676
- # An empty navigation fragment must not hide the exact renderer fallback or
677
- # prevent this page's bounded inactive refresh. Offscreen content stays inert.
678
- return -not $Offscreen -and $ElementCount -gt 0
679
- }
680
-
681
- function Test-GoogleAccountChooserLoading([bool]$ObservedAccounts, [int]$NamedEmailCount, [int]$AcceptedRowCount, [int]$MsaaEmailCount, [int]$MsaaAccountCount) {
682
- # An initially empty accessibility tree is not proof that the requested account
683
- # is absent. Once any identity was observed, retain the existing failure policy.
684
- return -not $ObservedAccounts -and $NamedEmailCount -eq 0 -and $AcceptedRowCount -eq 0 -and $MsaaEmailCount -eq 0 -and $MsaaAccountCount -eq 0
685
- }
686
-
687
- function Test-GoogleAccountEvidenceAgreement($MsaaEmails, $Rows) {
688
- if ($MsaaEmails.Count -eq 0 -or $MsaaEmails.Count -ne $Rows.Count) { return $false }
689
- $remaining = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal)
690
- foreach ($row in $Rows) {
691
- $email = [string]$row.email
692
- if ([string]::IsNullOrWhiteSpace($email) -or -not $remaining.Add($email)) { return $false }
693
- }
694
- foreach ($email in $MsaaEmails) {
695
- if (-not $remaining.Remove([string]$email)) { return $false }
696
- }
697
- return $remaining.Count -eq 0
698
- }
699
-
700
- function Test-GoogleAccountChooserPendingNavigation([bool]$IsAccountChooser, [bool]$SelectedRequestedAccount) {
701
- return $IsAccountChooser -and $SelectedRequestedAccount
702
- }
703
-
704
- function Test-GoogleAccountRowShape([string]$ControlType, [bool]$IsOffscreen, [double]$Width, [double]$Height, [bool]$HasActionPattern) {
705
- # Google chooser rows may be accessible links. Accept only a visible, actionable
706
- # row; its exact email and uniqueness are checked separately before selection.
707
- return -not $IsOffscreen -and $HasActionPattern -and $Width -ge 160 -and $Height -ge 28 -and
708
- $ControlType -in @('ControlType.Button', 'ControlType.ListItem', 'ControlType.Hyperlink')
709
- }
710
-
711
- function Format-GoogleAccountRowShape([string]$ControlType, [double]$Width, [double]$Height, [bool]$IsOffscreen, [bool]$Invoke, [bool]$Select, [bool]$Legacy) {
712
- # Only platform metadata enters an error. Never include accessible names, emails,
713
- # URLs, absolute coordinates or exception text in an account-row diagnostic.
714
- $type = $(if ($ControlType -cmatch '^ControlType\.[A-Za-z]+$') { $ControlType } else { 'ControlType.Unknown' })
715
- $w = ([Math]::Round($Width, 1)).ToString([Globalization.CultureInfo]::InvariantCulture)
716
- $h = ([Math]::Round($Height, 1)).ToString([Globalization.CultureInfo]::InvariantCulture)
717
- return "$type(width=$w,height=$h,offscreen=$IsOffscreen,invoke=$Invoke,select=$Select,legacy=$Legacy)"
718
- }
719
-
720
- function Format-GoogleAccountRowException($Record) {
721
- $exception = $Record.Exception
722
- $type = $exception.GetType().Name
723
- $hresult = '{0:X8}' -f [int]$exception.HResult
724
- $inner = $exception.InnerException
725
- $innerDetail = $(if ($null -ne $inner) { ",innerType=$($inner.GetType().Name),innerHresult=0x$('{0:X8}' -f [int]$inner.HResult)" } else { '' })
726
- $line = $(if ($null -ne $Record.InvocationInfo) { $Record.InvocationInfo.ScriptLineNumber } else { 0 })
727
- return "unreadable(type=$type,hresult=0x$hresult$innerDetail,line=$line)"
728
- }
729
-
730
- function Select-UniqueGoogleAccountRows($Candidates) {
731
- $byEmail = @{}
732
- $ambiguous = $false
733
- foreach ($candidate in $Candidates) {
734
- $email = [string]$candidate.email
735
- if ([string]::IsNullOrWhiteSpace($email)) { continue }
736
- if ($byEmail.ContainsKey($email)) {
737
- if (-not [object]::ReferenceEquals($byEmail[$email].element, $candidate.element)) { $ambiguous = $true }
738
- continue
739
- }
740
- $byEmail[$email] = $candidate
741
- }
742
- return @{ rows = @($byEmail.Values | Sort-Object email); ambiguous = $ambiguous }
743
- }
744
-
745
- function Test-YouTubeDelegationPage([uri]$Uri, [string]$Scopes, $Named) {
746
- if ($Uri.Scheme -cne 'https' -or $Uri.Host -cne 'accounts.google.com' -or $Uri.AbsolutePath -cne '/signin/oauth/delegation' -or
747
- 'https://www.googleapis.com/auth/youtube.readonly' -cnotin @($Scopes -split ' ')) { return $false }
748
- # A person without Brand accounts gets the same page headed only "Choose an account" (zh-CN 2026-10-22: one row, their own).
749
- $headings = @('Choose an account or a brand account', 'Choose your account or a brand account', 'Choose an account', 'Choose your account',
750
- [regex]::Unescape('\u9078\u64c7\u4f60\u7684\u5e33\u6236\u6216\u54c1\u724c\u5e33\u6236'))
751
- # Chinese wordings differ in the account noun and the pronoun: "choose (your) account (or a brand account)".
752
- $account = '(?:\u5e10\u53f7|\u8d26\u53f7|\u5e10\u6237|\u8d26\u6237|\u5e33\u865f|\u5e33\u6236)'
753
- $chinese = [regex]::Unescape("^(?:\u9009\u62e9|\u9078\u64c7).{0,4}$account(?:\u6216\u54c1\u724c$account)?$")
754
- $heading = @($Named | Where-Object { [string]$_['kind'] -ceq 'current_name' -and [bool]$_['visible'] -and
755
- [string]$_['controlType'] -in @('ControlType.Header', 'ControlType.Text') -and
756
- (([string]$_.name).Trim() -in $headings -or ([string]$_.name).Trim() -cmatch $chinese) })
757
- $app = @($Named | Where-Object { [string]$_['kind'] -ceq 'current_name' -and [bool]$_['visible'] -and
758
- [string]$_['controlType'] -in @('ControlType.Button', 'ControlType.Hyperlink') -and ([string]$_.name).Trim() -ceq 'Zortex' })
759
- return $heading.Count -gt 0 -and $app.Count -eq 1
760
- }
761
- # The email of the one Google account a page offers: Chrome's account list or the account rows, when exactly one
762
- # address is shown. A chooser with a single account says nothing else about who was picked.
763
- function Get-UniqueGoogleEmail($MsaaEmails, $Named) {
764
- $emails = [Collections.Generic.HashSet[string]]::new()
765
- foreach ($email in @($MsaaEmails)) { if (-not [string]::IsNullOrWhiteSpace([string]$email)) { [void]$emails.Add(([string]$email).Trim().ToLowerInvariant()) } }
766
- foreach ($control in @($Named)) {
767
- $name = [string]$control.name
768
- if (-not (Test-GoogleAccountCandidate $name)) { continue }
769
- foreach ($match in [regex]::Matches($name, '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}')) { [void]$emails.Add($match.Value.ToLowerInvariant()) }
770
- }
771
- if ($emails.Count -eq 1) { return @($emails)[0] }
772
- return ''
773
- }
774
- function Select-YouTubePrimaryAccount($Named, [string]$Email) {
775
- if ($Email -cnotmatch '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$') { return $null }
776
- $rows = @($Named | Where-Object {
777
- if ([string]$_['kind'] -cne 'current_name' -or -not [bool]$_['visible'] -or [string]$_['controlType'] -cne 'ControlType.Hyperlink') { return $false }
778
- $emails = @([regex]::Matches([string]$_.name, '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}') | ForEach-Object { $_.Value.ToLowerInvariant() })
779
- return $emails.Count -eq 1 -and $emails[0] -ceq $Email
780
- })
781
- if ($rows.Count -eq 1) { return $rows[0] }
782
- return $null
783
- }
784
- function Test-GoogleScopeControl([string]$Name) {
785
- $normalized = $Name.Trim().ToLowerInvariant()
786
- if ([string]::IsNullOrWhiteSpace($normalized)) { return $false }
787
- return $normalized -match '(?i)gmail|google drive|drive|calendar|mail|email|zortex|select all|see|view|read|metadata|\u65e5\u5386|\u884c\u4e8b\u5386|\u90ae\u4ef6|\u4e91\u7aef\u786c\u76d8|\u5168\u9009|\u67e5\u770b|\u8bfb\u53d6|\u65e5\u66c6|\u884c\u4e8b\u66c6|\u90f5\u4ef6|\u96f2\u7aef\u786c\u789f|\u5168\u9078|\u8b80\u53d6'
788
- }
789
-
790
- function Test-GoogleScopeRowText([string]$Name) {
791
- $normalized = $Name.Trim().ToLowerInvariant()
792
- if ([string]::IsNullOrWhiteSpace($normalized)) { return $false }
793
- return $normalized -match '(?i)gmail|google drive|drive|calendar|mail|email|select all|see|view|read|metadata|\u65e5\u5386|\u884c\u4e8b\u5386|\u7535\u5b50\u90ae\u4ef6|\u90ae\u4ef6|\u4e91\u7aef\u786c\u76d8|\u5168\u9009|\u67e5\u770b|\u8bfb\u53d6|\u65e5\u66c6|\u884c\u4e8b\u66c6|\u96fb\u5b50\u90f5\u4ef6|\u90f5\u4ef6|\u96f2\u7aef\u786c\u789f|\u5168\u9078|\u8b80\u53d6'
794
- }
795
-
796
- function Test-SameRow($A, $B) {
797
- $centerA = $A.Top + ($A.Height / 2)
798
- $centerB = $B.Top + ($B.Height / 2)
799
- return [Math]::Abs($centerA - $centerB) -le 36 -and $B.Left -lt ($A.Right + 64) -and $B.Right -gt ($A.Left - 900)
800
- }
801
-
802
- function ConvertTo-BrowserUri([string]$Value) {
803
- $candidate = $Value.Trim()
804
- if ($candidate -match '^(accounts\.google\.com|login\.microsoftonline\.com|login\.live\.com|account\.live\.com|zortex-auth\.pages\.dev|api\.notion\.com|app\.notion\.com|www\.notion\.so|notion\.so|slack\.com|[a-z0-9-]+\.slack\.com|x\.com|twitter\.com|(?:www\.)?instagram\.com|(?:www\.)?linkedin\.com|steamcommunity\.com|mail\.1(?:63|26)\.com|(?:www\.)?reddit\.com|open\.spotify\.com|notebook(?:lm)?\.google\.com|web\.whatsapp\.com)(?:/|$)') { $candidate = "https://$candidate" }
805
- elseif ($candidate -match '^(127\.0\.0\.1|localhost)(?::\d+)?(?:/|$)') { $candidate = "http://$candidate" }
806
- $parsed = $null
807
- if ([uri]::TryCreate($candidate, [UriKind]::Absolute, [ref]$parsed) -and $parsed.Scheme -in @('http', 'https')) { return $parsed }
808
- return $null
809
- }
810
-
811
- if ($SelfTestJevPolicy) {
812
- $env:ZORTEX_JEV_UIA_MODE = '1'
813
- $consent = @(@{ name = 'Zortex wants access to your Google Account'; kind = 'current_name'; controlType = 'ControlType.Text'; visible = $true }, @{ name = 'Allow' })
814
- if (-not (Test-JevGoogleConsentContext $consent '/signin/oauth/v2/consentsummary')) { throw 'Zortex consent rejected' }
815
- if (Test-JevGoogleConsentContext $consent '/v3/signin/accountchooser') { throw 'chooser treated as consent' }
816
- if (Test-JevGoogleConsentContext @(@{ name = 'OtherApp wants access to your Google Account' }, @{ name = 'Allow' }) '/signin/oauth/v2/consentsummary') { throw 'other app consent accepted' }
817
- if (Test-JevGoogleConsentContext @(@{ name = 'Allow' }) '/signin/oauth/v2/consentsummary') { throw 'consent without Zortex heading accepted' }
818
- if (Test-JevGoogleConsentContext @(@{ name = 'Zortex wants access to your Google Account'; kind = 'help_text'; controlType = 'ControlType.Text' }, @{ name = 'Allow' }) '/signin/oauth/v2/consentsummary') { throw 'HelpText forged Zortex heading' }
819
- if (Test-JevGoogleConsentContext @(@{ name = 'Zortex wants access to your Google Account'; kind = 'current_name'; controlType = 'ControlType.Edit' }, @{ name = 'Allow' }) '/signin/oauth/v2/consentsummary') { throw 'editable forged Zortex heading' }
820
- if (Test-JevGoogleConsentContext @(@{ name = 'Zortex wants access to your Google Account'; kind = 'current_name'; controlType = 'ControlType.Text'; visible = $false }, @{ name = 'Allow' }) '/signin/oauth/v2/consentsummary') { throw 'hidden forged Zortex heading' }
821
- if (Test-JevGoogleConsentContext @($consent + @(@{ name = "Google hasn't verified this app" })) '/signin/oauth/v2/consentsummary') { throw 'unverified app consent accepted' }
822
- if (-not (Test-JevGoogleUnverified @(@{ name = 'Go to Zortex (unsafe)' }))) { throw 'unsafe warning missed' }
823
- if (-not (Test-ConsentControl 'google' 'Advanced') -or -not (Test-ConsentControl 'google' 'Go to Zortex (unsafe)')) { throw 'Jev warning continuation unavailable' }
824
- if (-not (Test-ConsentControl 'google' 'Allow')) { throw 'ordinary Jev consent refused' }
825
- $testNotice = @(@{ name = "Google hasn't verified this app"; kind = 'current_name'; controlType = 'ControlType.Header'; visible = $true })
826
-
827
- if (-not (Test-JevApprovedUnverifiedTest '230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com' $testNotice '/signin/oauth/v2/consent')) { throw 'approved Zortex test notice refused' }
828
- if (-not (Test-JevApprovedUnverifiedTest 'other-client.apps.googleusercontent.com' $testNotice '/signin/oauth/v2/consent')) { throw 'current transaction warning refused' }
829
- if (Test-JevApprovedUnverifiedTest '230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com' $testNotice '/v3/signin/accountchooser') { throw 'non-consent warning accepted' }
830
-
831
- if (-not (Test-JevApprovedUnverifiedTest '230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com' $testNotice '/signin/oauth/v2/consent')) { throw 'warning incorrectly requires a separate opt-in' }
832
- $approvedConsent = @(
833
- @{ name = 'Zortex'; kind = 'current_name'; controlType = 'ControlType.Text'; visible = $true },
834
- @{ name = "Google hasn't verified this app"; kind = 'current_name'; controlType = 'ControlType.Text'; visible = $true },
835
- @{ name = 'Allow'; kind = 'current_name'; controlType = 'ControlType.Button'; visible = $true })
836
-
837
- if (-not (Test-JevApprovedConsentTest '230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com' $approvedConsent '/signin/oauth/v2/consent' 'notice:continue')) { throw 'approved consent refused' }
838
- if (-not (Test-JevApprovedConsentTest 'other-client.apps.googleusercontent.com' $approvedConsent '/signin/oauth/v2/consent' 'notice:continue')) { throw 'current transaction consent refused' }
839
- if (Test-JevApprovedConsentTest '230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com' $approvedConsent '/signin/oauth/v2/consent' 'none') { throw 'consent without completed warning accepted' }
840
- if (Test-JevApprovedConsentTest '230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com' $approvedConsent '/v3/signin/accountchooser' 'notice:continue') { throw 'chooser as consent accepted' }
841
- if (Test-JevApprovedConsentTest '230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com' @($approvedConsent + @{ name = 'Advanced'; kind = 'current_name'; visible = $true }) '/signin/oauth/v2/consent' 'notice:continue') { throw 'warning control as consent accepted' }
842
-
843
- Write-Result @{ state = 'self_test'; ok = $true }
844
- }
845
-
846
- if ($SelfTest) {
847
- Add-Type -AssemblyName System.Web
848
- $delegationRows = @(
849
- @{name='Choose an account or a brand account'; kind='current_name'; visible=$true; controlType='ControlType.Header'},
850
- @{name='Zortex'; kind='current_name'; visible=$true; controlType='ControlType.Button'},
851
- @{name='Owner owner@example.invalid'; kind='current_name'; visible=$true; controlType='ControlType.Hyperlink'; element='primary'},
852
- @{name='Owner YouTube'; kind='current_name'; visible=$true; controlType='ControlType.Hyperlink'; element='brand'},
853
- @{name='owner@example.invalid'; element='metadata'}
854
- )
855
- $delegationUri = [uri]'https://accounts.google.com/signin/oauth/delegation'
856
- if (-not (Test-YouTubeDelegationPage $delegationUri 'https://www.googleapis.com/auth/youtube.readonly openid email' $delegationRows)) { throw 'YouTube delegation context refused' }
857
- foreach ($wrongUri in @('https://accounts.google.com.evil.test/signin/oauth/delegation','https://accounts.google.com/signin/oauth/consent','http://accounts.google.com/signin/oauth/delegation')) {
858
- if (Test-YouTubeDelegationPage ([uri]$wrongUri) 'https://www.googleapis.com/auth/youtube.readonly' $delegationRows) { throw 'foreign delegation context accepted' }
859
- }
860
- if (Test-YouTubeDelegationPage $delegationUri 'https://www.googleapis.com/auth/gmail.readonly' $delegationRows) { throw 'non YouTube delegation accepted' }
861
- if ((Select-YouTubePrimaryAccount $delegationRows 'owner@example.invalid').element -cne 'primary') { throw 'YouTube primary account not selected' }
862
- if ($null -ne (Select-YouTubePrimaryAccount $delegationRows 'other@example.invalid')) { throw 'wrong YouTube account selected' }
863
- if ($null -ne (Select-YouTubePrimaryAccount @($delegationRows + $delegationRows[2]) 'owner@example.invalid')) { throw 'ambiguous YouTube account selected' }
864
- $delegationRows[0].name = [regex]::Unescape('\u9078\u64c7\u4f60\u7684\u5e33\u6236\u6216\u54c1\u724c\u5e33\u6236')
865
- if (-not (Test-YouTubeDelegationPage $delegationUri 'https://www.googleapis.com/auth/youtube.readonly' $delegationRows)) { throw 'Chinese YouTube delegation refused' }
866
- foreach ($zh in @('\u9009\u62e9\u5e10\u53f7\u6216\u54c1\u724c\u5e10\u53f7', '\u9009\u62e9\u60a8\u7684\u8d26\u53f7\u6216\u54c1\u724c\u8d26\u53f7', '\u9009\u62e9\u4f60\u7684\u5e10\u6237\u6216\u54c1\u724c\u5e10\u6237')) {
867
- $delegationRows[0].name = [regex]::Unescape($zh)
868
- if (-not (Test-YouTubeDelegationPage $delegationUri 'https://www.googleapis.com/auth/youtube.readonly' $delegationRows)) { throw "zh-CN YouTube delegation refused: $zh" }
869
- }
870
- # Without Brand accounts: the traced zh-CN page, headed "Choose an account" with the person's own row only.
871
- $plainRows = @(
872
- @{name=[regex]::Unescape('\u9009\u62e9\u8d26\u53f7'); kind='current_name'; visible=$true; controlType='ControlType.Text'},
873
- @{name='Zortex'; kind='current_name'; visible=$true; controlType='ControlType.Button'},
874
- @{name='Owner owner@example.invalid'; kind='current_name'; visible=$true; controlType='ControlType.Hyperlink'; element='primary'}
875
- )
876
- if (-not (Test-YouTubeDelegationPage $delegationUri 'https://www.googleapis.com/auth/youtube.readonly' $plainRows)) { throw 'zh-CN YouTube delegation without Brand accounts refused' }
877
- if ((Select-YouTubePrimaryAccount $plainRows (Get-UniqueGoogleEmail @() $plainRows)).element -cne 'primary') { throw 'own channel not picked without Brand accounts' }
878
- $plainRows[0].name = 'Choose an account'
879
- if (-not (Test-YouTubeDelegationPage $delegationUri 'https://www.googleapis.com/auth/youtube.readonly' $plainRows)) { throw 'YouTube delegation without Brand accounts refused' }
880
- if (Test-YouTubeDelegationPage ([uri]'https://accounts.google.com/v3/signin/accountchooser') 'https://www.googleapis.com/auth/youtube.readonly' $plainRows) { throw 'account chooser taken for YouTube delegation' }
881
- $plainRows[0].name = [regex]::Unescape('\u9009\u62e9\u8d26\u53f7\u4ee5\u7ee7\u7eed')
882
- if (Test-YouTubeDelegationPage $delegationUri 'https://www.googleapis.com/auth/youtube.readonly' $plainRows) { throw 'other heading taken for YouTube delegation' }
883
- $delegationRows[0].name = 'Choose an account or a brand account'
884
- if ((Get-UniqueGoogleEmail @('Owner@Example.invalid') @()) -cne 'owner@example.invalid') { throw 'unique Chrome account email missed' }
885
- if ((Get-UniqueGoogleEmail @() @(@{ name = 'Owner owner@example.invalid' })) -cne 'owner@example.invalid') { throw 'unique account row email missed' }
886
- if ((Get-UniqueGoogleEmail @('a@example.invalid', 'b@example.invalid') @()) -cne '') { throw 'two accounts taken as one' }
887
- if ((Get-UniqueGoogleEmail @() @(@{ name = 'Owner owner@example.invalid' }, @{ name = 'Other other@example.invalid' })) -cne '') { throw 'two account rows taken as one' }
888
- if ((Get-UniqueGoogleEmail @() $delegationRows) -cne 'owner@example.invalid') { throw 'delegation page address missed' }
889
- if ((Get-UniqueGoogleEmail @() @(@{ name = 'Owner YouTube' })) -cne '') { throw 'Brand account name taken as an address' }
890
- $notionCheckboxFixtures = @(
891
- @{ name = ''; controlType = 'ControlType.CheckBox'; visible = $true; toggleState = 'On'; expected = $true },
892
- @{ name = ''; controlType = 'ControlType.CheckBox'; visible = $false; toggleState = 'On'; expected = $false },
893
- @{ name = ''; controlType = 'ControlType.CheckBox'; visible = $true; toggleState = 'Off'; expected = $false },
894
- @{ name = 'Page'; controlType = 'ControlType.CheckBox'; visible = $true; toggleState = 'Indeterminate'; expected = $false },
895
- @{ name = ''; controlType = 'ControlType.Button'; visible = $true; toggleState = 'On'; expected = $false }
896
- )
897
- foreach ($checkbox in $notionCheckboxFixtures) {
898
- if ((Test-NotionSelectedCheckbox $checkbox.controlType $checkbox.visible $checkbox.toggleState) -ne $checkbox.expected) { throw 'Notion unnamed checkbox selection evidence failed' }
899
- }
900
- # Real Get-NamedPageControls mixes current_name records with HelpText/Value/legacy
901
- # metadata containing only name and element. Run the same production predicate
902
- # under this script's StrictMode so missing keys can never crash enrollment.
903
- $notionMixedNamed = @(
904
- @{ element = 'fixture'; name = 'HelpText' },
905
- @{ element = 'fixture'; name = 'Value' },
906
- @{ element = 'fixture'; name = 'Private'; kind = 'current_name'; visible = $true; controlType = 'ControlType.Button' },
907
- @{ element = 'fixture'; name = 'Page'; kind = 'current_name'; visible = $true; controlType = 'ControlType.CheckBox' },
908
- @{ element = 'fixture'; name = '1 page selected'; kind = 'current_name'; visible = $true; controlType = 'ControlType.Text' },
909
- @{ element = 'fixture'; name = 'Hidden'; kind = 'current_name'; visible = $false; controlType = 'ControlType.Button' }
910
- )
911
- foreach ($type in @('ControlType.Button', 'ControlType.CheckBox', 'ControlType.Text')) {
912
- if (@($notionMixedNamed | Where-Object { Test-NotionNamedControl $_ $type }).Count -ne 1) { throw 'Notion mixed metadata filter failed' }
913
- }
914
- if ((Test-NotionNamedControl $null 'ControlType.Button') -or (Test-NotionNamedControl @{} 'ControlType.Button')) { throw 'Notion missing metadata accepted' }
915
- if (-not (Test-NotionPageSection 'Private' 'Collapsed')) { throw 'Notion private section expansion refused' }
916
- if (-not (Test-NotionPageSection ([regex]::Unescape('\u79c1\u4eba')) 'Collapsed')) { throw 'Notion Chinese private section refused' }
917
- if ((Test-NotionPageSection 'Private' 'Expanded') -or (Test-NotionPageSection 'Teamspace' 'Collapsed') -or (Test-NotionPageSection 'Select all' 'Collapsed')) { throw 'Notion unrelated or already-open section expanded' }
918
- $notionRedirect = [uri]'http://127.0.0.1:8123/notion/callback'
919
- $notionState = 'n1.state.abcdefghijklmnop.payload'
920
- if (-not (Test-NotionTransaction ([uri]("https://zortex-auth.pages.dev/notion/authorize?state=$notionState")) 'client' $notionState)) { throw 'Notion broker binding failed' }
921
- if (Test-NotionTransaction ([uri]("https://notion.so/oauth?client_id=wrong&state=$notionState")) 'client' $notionState) { throw 'Notion foreign client accepted' }
922
- if (-not (Test-NotionTransaction ([uri]("https://app.notion.com/install-integration?client_id=client&state=$notionState")) 'client' $notionState)) { throw 'Notion app transaction refused' }
923
- if (Test-NotionTransaction ([uri]("https://app.notion.com/install-integration?client_id=client&state=wrong")) 'client' $notionState) { throw 'Notion app changed state accepted' }
924
- if ((ConvertTo-BrowserUri 'app.notion.com/install-integration').Host -ne 'app.notion.com') { throw 'scheme-less Notion app URL refused' }
925
- if (Test-AllowedOrigin 'notion' ([uri]'https://notion.so.evil.test/oauth') $notionRedirect) { throw 'Notion lookalike accepted' }
926
- if ((Get-NotionConsentAction 'Allow access' $false) -ne '') { throw 'Notion empty selection allowed' }
927
- if ((Get-NotionConsentAction 'Allow access' $true) -ne 'allow') { throw 'Notion selected-page consent refused' }
928
- if ((Get-NotionConsentAction 'Select pages to access' $false) -ne 'picker') { throw 'Notion picker refused' }
929
- foreach ($pickerName in @('\u9078\u53d6\u9801\u9762', '\u9078\u64c7\u9801\u9762', '\u9009\u62e9\u9875\u9762')) {
930
- if ((Get-NotionConsentAction ([regex]::Unescape($pickerName)) $false) -ne 'picker') { throw 'Notion Chinese picker refused' }
931
- }
932
- foreach ($allowName in @('\u5141\u8a31\u5b58\u53d6', '\u5141\u8bb8\u8bbf\u95ee')) {
933
- if ((Get-NotionConsentAction ([regex]::Unescape($allowName)) $true) -ne 'allow') { throw 'Notion Chinese allow refused' }
934
- if ((Get-NotionConsentAction ([regex]::Unescape($allowName)) $false) -ne '') { throw 'Notion Chinese empty selection accepted' }
935
- }
936
- if ((Get-NotionConsentAction ([regex]::Unescape('\u5168\u9078')) $true) -ne '') { throw 'Notion Chinese select-all accepted' }
937
- if ((Get-NotionConsentAction 'Select all' $true) -ne '') { throw 'Notion broad selection accepted' }
938
- $notionCallback = Get-NotionCallbackResult ([uri]'http://127.0.0.1:8123/notion/callback?state=local&ticket=n1.ticket.abcdefghijklmnop.payload') $notionRedirect 'local'
939
- if ($notionCallback.state -ne 'completed' -or $notionCallback.ContainsKey('ticket')) { throw 'Notion ticket disclosure or callback failure' }
940
- if ((Get-NotionCallbackResult ([uri]'http://127.0.0.1:8123/notion/callback?state=local') $notionRedirect 'local').state -ne 'failed') { throw 'Notion missing ticket accepted' }
941
-
942
- $redirect = [uri]'http://127.0.0.1:8123/callback'
943
- if ($null -ne (Get-OAuthCallbackResult ([uri]'http://127.0.0.1:8124/callback?state=old') $redirect 'current')) { throw 'old callback port accepted' }
944
- if ($null -ne (Get-OAuthCallbackResult ([uri]'http://127.0.0.1:8123/other?state=old') $redirect 'current')) { throw 'different callback path accepted' }
945
- if ($null -ne (Get-OAuthCallbackResult ([uri]'https://127.0.0.1:8123/callback?state=current') $redirect 'current')) { throw 'different callback scheme accepted' }
946
- if ($null -ne (Get-OAuthCallbackResult ([uri]'http://localhost:8123/callback?state=current') $redirect 'current')) { throw 'different callback host accepted' }
947
- if ((Get-OAuthCallbackResult ([uri]'http://127.0.0.1:8123/callback?state=wrong&code=code') $redirect 'current').reason -ne 'state_mismatch') { throw 'wrong callback state accepted' }
948
- if ((Get-OAuthCallbackResult ([uri]'http://127.0.0.1:8123/callback?state=CURRENT&code=code') $redirect 'current').reason -ne 'state_mismatch') { throw 'case-changed callback state accepted' }
949
- if ((Get-OAuthCallbackResult ([uri]'http://127.0.0.1:8123/callback?state=current&code=code') $redirect 'current').code -ne 'code') { throw 'current callback refused' }
950
- if (-not (Test-OwnedBrowserCloseCandidate 1 'owned-tab' 'owned-tab' ([uri]'http://127.0.0.1:8123/callback?state=current') $redirect)) { throw 'sole bound OAuth tab was not closable' }
951
- if ((Test-OwnedBrowserCloseCandidate 2 'owned-tab' 'owned-tab' ([uri]'http://127.0.0.1:8123/callback?state=current') $redirect) -or
952
- (Test-OwnedBrowserCloseCandidate 1 'other-tab' 'owned-tab' ([uri]'http://127.0.0.1:8123/callback?state=current') $redirect) -or
953
- (Test-OwnedBrowserCloseCandidate 1 'owned-tab' 'owned-tab' ([uri]'https://example.com') $redirect)) { throw 'a shared or changed browser window was closable' }
954
- if (Test-OAuthTransaction ([Web.HttpUtility]::ParseQueryString('')) 'client' 'current') { throw 'continuation without transaction proof accepted' }
955
- if (Test-OAuthTransaction ([Web.HttpUtility]::ParseQueryString('client_id=client&state=other')) 'client' 'current') { throw 'different tab transaction accepted' }
956
- if (-not (Test-OAuthTransaction ([Web.HttpUtility]::ParseQueryString('client_id=client&state=current')) 'client' 'current')) { throw 'current tab transaction refused' }
957
- if (-not (Test-AllowedOrigin 'google' ([uri]'https://accounts.google.com/o/oauth2/v2/auth') $redirect)) { throw 'google origin refused' }
958
- if (Test-AllowedOrigin 'google' ([uri]'https://evil.example/allow') $redirect) { throw 'foreign origin accepted' }
959
- if (Test-AllowedOrigin 'google' ([uri]'https://accounts.google.com.evil.example/allow') $redirect) { throw 'lookalike origin accepted' }
960
- if (Test-AllowedOrigin 'google' ([uri]'http://accounts.google.com/allow') $redirect) { throw 'insecure provider origin accepted' }
961
- if (-not (Test-AllowedOrigin 'slack' ([uri]'https://slack.com/oauth/v2/authorize') $redirect)) { throw 'slack origin refused' }
962
- if (-not (Test-AllowedOrigin 'slack' ([uri]'https://app.slack.com/oauth') $redirect)) { throw 'slack subdomain refused' }
963
- if (Test-AllowedOrigin 'slack' ([uri]'https://slack.com.evil.example/allow') $redirect) { throw 'slack lookalike origin accepted' }
964
- if (Test-AllowedOrigin 'slack' ([uri]'https://evilslack.com/allow') $redirect) { throw 'slack suffix lookalike origin accepted' }
965
- if (-not (Test-ConsentControl 'slack' 'Allow')) { throw 'slack allow consent refused' }
966
- if (-not (Test-ConsentControl 'slack' ([string][char]0x5141 + [string][char]0x8a31))) { throw 'slack traditional chinese allow consent refused' }
967
- if (Test-ConsentControl 'slack' 'Cancel') { throw 'slack cancel accepted as consent' }
968
- if (-not (Test-AllowedOrigin 'microsoft' ([uri]'https://account.live.com/Consent/Update') $redirect)) { throw 'personal microsoft consent origin refused' }
969
- if (Test-AllowedOrigin 'microsoft' ([uri]'https://account.live.com.evil.example/Consent/Update') $redirect) { throw 'microsoft consent lookalike accepted' }
970
- if (Test-AllowedOrigin 'google' ([uri]'https://account.live.com/Consent/Update') $redirect) { throw 'microsoft consent origin leaked to google' }
971
- if (-not (Test-ConsentControl 'microsoft' 'Accept')) { throw 'known consent refused' }
972
- if (-not (Test-ConsentControl 'microsoft' 'Yes')) { throw 'microsoft KMSI yes refused' }
973
- if (-not (Test-MicrosoftSignedInAccount 'Ada Lovelace ada@example.com Signed in')) { throw 'ms signed-in account row refused' }
974
- if (-not (Test-MicrosoftSignedInAccount ('Ada ada@example.com ' + [char]0x5df2 + [char]0x767b + [char]0x5f55))) { throw 'ms chinese signed-in account row refused' }
975
- if (Test-MicrosoftSignedInAccount 'ada@example.com') { throw 'bare email treated as ms signed-in account' }
976
- if (Test-MicrosoftSignedInAccount ('Signed in ' + [char]0x5df2 + [char]0x767b + [char]0x5f55)) { throw 'signed-in text without email treated as ms account' }
977
- if (@(Get-MicrosoftSignedInEmails @(@{ name = 'Ada ada@example.com Signed in' }, @{ name = 'Ada ada@example.com Signed in' })).Count -ne 1) { throw 'duplicate Microsoft account rows were treated as distinct accounts' }
978
- if (@(Get-MicrosoftSignedInEmails @(@{ name = 'Ada ada@example.com Signed in' }, @{ name = 'Bob bob@example.com Signed in' })).Count -ne 2) { throw 'different Microsoft accounts were collapsed' }
979
- $msSignedIn = [string][char]0x5df2 + [string][char]0x767b + [string][char]0x5165
980
- $mixedAccounts = @(@{ name = "Ada ada@u.school.edu $msSignedIn" }, @{ name = "Ada ada@outlook.com $msSignedIn" }, @{ name = "Ada ada@gmail.com $msSignedIn" })
981
- if ([string](Select-MicrosoftPersonalAccountRow $mixedAccounts)['name'] -cne "Ada ada@outlook.com $msSignedIn") { throw 'mixed Microsoft chooser did not pick the first personal account' }
982
- if ([string](Select-MicrosoftPersonalAccountRow @(@{ name = 'Ada ada@contoso.com Signed in' }, @{ name = 'Ada ada@gmail.com Signed in' }))['name'] -cne 'Ada ada@gmail.com Signed in') { throw 'personal Microsoft account on gmail was skipped' }
983
- if ($null -eq (Select-MicrosoftPersonalAccountRow @(@{ name = 'Ada ada@contoso.com Signed in' }))) { throw 'available work account was refused' }
984
- if ($null -eq (Select-MicrosoftPersonalAccountRow @(@{ name = 'Ada ada@u.school.edu Signed in' }, @{ name = 'Bob bob@contoso.com Signed in' }))) { throw 'available work or school account was refused' }
985
- if ($null -ne (Select-MicrosoftPersonalAccountRow @(@{ name = 'Use another account ada@outlook.com' }))) { throw 'unsigned Microsoft row was selected' }
986
- function New-MsRect([double]$Top) { [pscustomobject]@{ Current = [pscustomobject]@{ BoundingRectangle = [pscustomobject]@{ IsEmpty = $false; Left = 530; Top = $Top; Width = 880; Height = 149 } } } }
987
- function New-MsControl([string]$Type, [string]$Name, [double]$Top) { @{ element = (New-MsRect $Top); name = $Name; kind = 'current_name'; controlType = "ControlType.$Type"; visible = $true } }
988
- $realChooser = @(
989
- (New-MsControl 'ListItem' "a@mails.school.edu.cn$([regex]::Unescape('\u5df2\u767b\u5f55'))" 747), (New-MsControl 'Button' "$([regex]::Unescape('\u4f7f\u7528')) a@mails.school.edu.cn $([regex]::Unescape('\u5de5\u4f5c\u6216\u5b66\u6821\u5e10\u6237\u767b\u5f55'))" 747), (New-MsControl 'Button' "$([regex]::Unescape('\u6253\u5f00\u83dc\u5355'))" 799),
990
- (New-MsControl 'ListItem' "Name b@qq.com$([regex]::Unescape('\u5df2\u767b\u5f55'))" 895), (New-MsControl 'Button' "$([regex]::Unescape('\u4f7f\u7528')) b@qq.com $([regex]::Unescape('\u4e2a\u4eba Microsoft \u5e10\u6237\u767b\u5f55'))" 895),
991
- (New-MsControl 'ListItem' "$([regex]::Unescape('\u4f7f\u7528\u53e6\u4e00\u4e2a\u5e10\u6237'))" 1043), (New-MsControl 'Button' "$([regex]::Unescape('\u4f7f\u7528\u53e6\u4e00\u4e2a\u5e10\u6237'))" 1043))
992
- $realChoice = Select-MicrosoftPersonalAccount (Get-MicrosoftAccountChoices $realChooser)
993
- if ($null -eq $realChoice -or -not $realChoice['button'] -or $realChoice['email'] -cne 'b@qq.com' -or -not $realChoice['signedIn']) { throw 'zh-CN Microsoft chooser did not press the personal account button' }
994
- $twChooser = @((New-MsControl 'Button' "$([regex]::Unescape('\u4f7f\u7528')) a@u.nus.edu $([regex]::Unescape('\u5de5\u4f5c\u6216\u5b78\u6821\u5e33\u6236\u767b\u5165'))" 747), (New-MsControl 'Button' "$([regex]::Unescape('\u4f7f\u7528')) b@contoso.com $([regex]::Unescape('\u500b\u4eba Microsoft \u5e33\u6236\u767b\u5165'))" 895), (New-MsControl 'Button' "$([regex]::Unescape('\u4f7f\u7528')) c@gmail.com $([regex]::Unescape('\u500b\u4eba Microsoft \u5e33\u6236\u767b\u5165'))" 1043),
995
- (New-MsControl 'ListItem' "A a@u.nus.edu $([regex]::Unescape('\u5df2\u767b\u5165'))" 747), (New-MsControl 'ListItem' "B b@contoso.com $([regex]::Unescape('\u5df2\u767b\u5165'))" 895))
996
- if ([string](Select-MicrosoftPersonalAccount (Get-MicrosoftAccountChoices $twChooser))['email'] -cne 'b@contoso.com') { throw 'zh-TW personal label on a custom domain was not chosen first' }
997
- $enChooser = @((New-MsControl 'Button' 'Sign in with a@outlook.com work or school account.' 747), (New-MsControl 'Button' 'Sign in with b@hotmail.com personal Microsoft account.' 895))
998
- if ([string](Select-MicrosoftPersonalAccount (Get-MicrosoftAccountChoices $enChooser))['email'] -cne 'b@hotmail.com') { throw 'work label did not override a consumer domain' }
999
- $schoolOnly = @((New-MsControl 'Button' "$([regex]::Unescape('\u4f7f\u7528')) a@u.nus.edu $([regex]::Unescape('\u5de5\u4f5c\u6216\u5b78\u6821\u5e33\u6236\u767b\u5165'))" 747), (New-MsControl 'Button' 'Sign in with b@gmail.com work or school account.' 895), (New-MsControl 'Button' "$([regex]::Unescape('\u4f7f\u7528\u53e6\u4e00\u4e2a\u5e10\u6237'))" 1043))
1000
- if (@(Get-MicrosoftAccountChoices $schoolOnly).Count -ne 2 -or $null -eq (Select-MicrosoftPersonalAccount (Get-MicrosoftAccountChoices $schoolOnly))) { throw 'school-only Microsoft chooser was refused' }
1001
- $signedOutFirst = @((New-MsControl 'Button' 'Sign in with a@outlook.com personal Microsoft account.' 747), (New-MsControl 'Button' 'Sign in with b@live.com personal Microsoft account.' 895), (New-MsControl 'ListItem' 'B b@live.com Signed in' 895))
1002
- if ([string](Select-MicrosoftPersonalAccount (Get-MicrosoftAccountChoices $signedOutFirst))['email'] -cne 'b@live.com') { throw 'signed-in personal account was not preferred' }
1003
- $stuckNow = [DateTime]::UtcNow
1004
- if (Test-StuckPageRecovery ([IntPtr]::Zero) $stuckNow ([DateTime]::MinValue)) { throw 'stuck-page recovery nudged before the page had 3 s to render' }
1005
- if (-not (Test-StuckPageRecovery ([IntPtr]::Zero) $stuckNow.AddSeconds(-4) ([DateTime]::MinValue))) { throw 'stuck-page recovery did not nudge after 3 s' }
1006
- if (Test-StuckPageRecovery ([IntPtr]::Zero) $stuckNow.AddSeconds(-10) $stuckNow.AddSeconds(-1)) { throw 'stuck-page recovery nudged again within 3 s' }
1007
- if (-not (Test-StuckPageRecovery ([IntPtr]::Zero) $stuckNow.AddSeconds(-10) $stuckNow.AddSeconds(-4))) { throw 'stuck-page recovery did not repeat after 3 s' }
1008
- foreach ($domain in @('outlook.com', 'hotmail.co.uk', 'live.cn', 'outlook.com.au', 'msn.com', 'qq.com')) { if (-not (Test-MicrosoftPersonalEmail "a@$domain")) { throw "personal domain refused: $domain" } }
1009
- foreach ($domain in @('live.ac.uk', 'outlook.contoso.com', 'u.nus.edu', 'contoso.onmicrosoft.com', 'hotmail.com.evil.example')) { if (Test-MicrosoftPersonalEmail "a@$domain") { throw "work domain treated as personal: $domain" } }
1010
- if (-not (Test-ShouldCloseBrowser 'login_required') -or -not (Test-ShouldCloseBrowser 'multiple_accounts') -or -not (Test-ShouldCloseBrowser 'code') -or -not (Test-ShouldCloseBrowser 'accounts')) { throw 'owned browser cleanup incomplete' }
1011
- if (-not (Test-OwnedDiscoveryCloseCandidate 1 'owned' 'owned' ([uri]'https://accounts.google.com/v3/signin/accountchooser'))) { throw 'owned account discovery window was not closeable' }
1012
- if ((Test-OwnedDiscoveryCloseCandidate 2 'owned' 'owned' ([uri]'https://accounts.google.com/v3/signin/accountchooser')) -or
1013
- (Test-OwnedDiscoveryCloseCandidate 1 'other' 'owned' ([uri]'https://accounts.google.com/v3/signin/accountchooser')) -or
1014
- (Test-OwnedDiscoveryCloseCandidate 1 'owned' 'owned' ([uri]'https://accounts.google.com.evil.example/v3/signin/accountchooser'))) { throw 'unowned discovery tab was closeable' }
1015
- foreach ($control in @('Advanced', 'Show advanced', 'Go to Zortex (unsafe)',
1016
- ([string][char]0x9ad8 + [string][char]0x7ea7),
1017
- ([string][char]0x8f6c + [string][char]0x81f3 + 'Zortex' + [string][char]0xff08 + [string][char]0x4e0d + [string][char]0x5b89 + [string][char]0x5168 + [string][char]0xff09))) {
1018
- if (-not (Test-ConsentControl 'google' $control)) { throw 'Google warning continuation unavailable' }
1019
- }
1020
-
1021
- foreach ($control in @('Advanced', ([string][char]0x9ad8 + [string][char]0x7ea7), 'Go to Zortex (unsafe)',
1022
- ([string][char]0x8f6c + [string][char]0x81f3 + 'Zortex' + [string][char]0xff08 + [string][char]0x4e0d + [string][char]0x5b89 + [string][char]0x5168 + [string][char]0xff09))) {
1023
- if (-not (Test-ConsentControl 'google' $control)) { throw 'Zortex warning control refused for the Zortex client' }
1024
- }
1025
- if (Test-ConsentControl 'google' 'Go to Evil App (unsafe)') { throw 'another app warning accepted for the Zortex client' }
1026
-
1027
-
1028
- foreach ($control in @('Continue', 'Allow')) {
1029
- if (-not (Test-ConsentControl 'google' $control)) { throw 'Google consent refused' }
1030
- }
1031
- if (Test-ConsentControl 'google' ([string][char]0x9690 + [string][char]0x85cf + [string][char]0x9ad8 + [string][char]0x7ea7 + [string][char]0x90e8 + [string][char]0x5206)) { throw 'google hide advanced accepted' }
1032
- foreach ($control in @('\u9032\u968e', '\u986f\u793a\u9032\u968e\u8a2d\u5b9a', '\u524d\u5f80\u300cZortex\u300d(\u4e0d\u5b89\u5168)', '\u524d\u5f80\u300cZortex\u300d\uff08\u4e0d\u5b89\u5168\uff09')) {
1033
- if (-not (Test-ConsentControl 'google' ([regex]::Unescape($control)))) { throw 'traditional Google warning continuation unavailable' }
1034
- }
1035
- foreach ($control in @('Hide advanced', 'Go to OtherApp (unsafe)', 'Go to Zortex.evil (unsafe)', 'Continue to OtherApp', 'Proceed anyway',
1036
- ([regex]::Unescape('\u96b1\u85cf\u9032\u968e\u8a2d\u5b9a')), ([regex]::Unescape('\u524d\u5f80\u300cOtherApp\u300d(\u4e0d\u5b89\u5168)')),
1037
- ([regex]::Unescape('\u8f6c\u81f3OtherApp\uff08\u4e0d\u5b89\u5168\uff09')))) {
1038
- if (Test-ConsentControl 'google' $control) { throw 'unapproved app or hide-advanced notice control accepted' }
1039
- }
1040
-
1041
- if (-not (Test-AccountChooserPage @(@{ name = ([string][char]0x9009 + [string][char]0x62e9 + [string][char]0x8d26 + [string][char]0x53f7) }))) { throw 'account chooser missed' }
1042
- if (Test-AccountChooserPage @(@{ name = 'person@example.com' })) { throw 'email treated as account chooser' }
1043
- # The traced zh-CN signing-back-in page: "Selected <account>. Switch account" beside Cancel and Continue.
1044
- $selectedLink = [regex]::Unescape('\u5df2\u9009\u62e9\u201cperson@example.com\u201d\u3002\u5207\u6362\u8d26\u53f7')
1045
- if (Test-AccountChooserPage @(@{ name = $selectedLink }, @{ name = [regex]::Unescape('\u7ee7\u7eed') }) '/signin/oauth/id') { throw 'signing-back-in page treated as account chooser' }
1046
- if (Test-AccountChooserPage @(@{ name = 'Selected person@example.com. Switch account' }) '/signin/oauth/id') { throw 'English switch-account link treated as account chooser' }
1047
- if (-not (Test-AccountChooserPage @(@{ name = $selectedLink }, @{ name = [regex]::Unescape('\u4f7f\u7528\u5176\u4ed6\u8d26\u53f7') }))) { throw 'chooser with another-account row missed' }
1048
- $traditionalChooser = [regex]::Unescape('\u9078\u64c7\u5e33\u6236')
1049
- $traditionalAnother = [regex]::Unescape('\u4f7f\u7528\u5176\u4ed6\u5e33\u6236')
1050
- foreach ($heading in @($traditionalChooser, $traditionalAnother)) {
1051
- if (-not (Test-AccountChooserPage @(@{ name = $heading }))) { throw 'traditional account chooser missed' }
1052
- if ($null -ne (Get-GoogleAccountEmail "$heading person@example.com")) { throw 'traditional chooser action treated as an account row' }
1053
- }
1054
- if (-not (Test-AccountChooserPage @() '/v3/signin/accountchooser')) { throw 'bound Google account chooser path missed' }
1055
- foreach ($path in @('/v3/signin/accountchooser/other', '/other/accountchooser', '/v3/signin/AccountChooser', '/signin/oauth/v2/consentsummary')) {
1056
- if (Test-AccountChooserPage @() $path) { throw 'unknown path treated as Google account chooser' }
1057
- }
1058
- foreach ($name in @('Remove person@example.com', ([regex]::Unescape('\u522a\u9664') + ' person@example.com'), ([regex]::Unescape('\u767b\u51fa') + ' person@example.com'))) {
1059
- if ($null -ne (Get-GoogleAccountEmail $name)) { throw 'account management action treated as an account row' }
1060
- }
1061
- foreach ($control in @('Allow', 'Continue', [regex]::Unescape('\u5141\u8a31'), [regex]::Unescape('\u7e7c\u7e8c'))) {
1062
- if (-not (Test-ConsentControl 'google' $control)) { throw 'ordinary Google consent refused' }
1063
- }
1064
- if (-not (Test-GoogleAccountCandidate 'person@example.com')) { throw 'google account candidate missed' }
1065
- if (Test-GoogleAccountCandidate 'Use another account') { throw 'google account action treated as account candidate' }
1066
- if ((Get-GoogleAccountEmail 'Person person@example.com') -ne 'person@example.com') { throw 'exact Google account email missed' }
1067
- if ((Get-GoogleAccountEmail 'Google Account person@example.com') -ne 'person@example.com') { throw 'Google account row label missed' }
1068
- if ($null -ne (Get-GoogleAccountEmail 'Remove person@example.com')) { throw 'remove-account action accepted' }
1069
- if ($null -ne (Get-GoogleAccountEmail (([string][char]0x79fb + [string][char]0x9664) + ' person@example.com'))) { throw 'localized remove-account action accepted' }
1070
- if ((Get-GoogleAccountEmail 'manager@example.com') -ne 'manager@example.com') { throw 'action word inside email rejected' }
1071
- if ($null -ne (Get-GoogleAccountEmail 'one@example.com and two@example.com')) { throw 'ambiguous Google account label accepted' }
1072
- foreach ($rowType in @('ControlType.Button', 'ControlType.ListItem', 'ControlType.Hyperlink')) {
1073
- if (-not (Test-GoogleAccountRowShape $rowType $false 240 40 $true)) { throw 'visible actionable Google account row missed' }
1074
- }
1075
- if (Test-GoogleAccountRowShape 'ControlType.Text' $false 240 40 $true) { throw 'account text treated as an actionable row' }
1076
- if (Test-GoogleAccountRowShape 'ControlType.Hyperlink' $true 240 40 $true) { throw 'offscreen account link accepted' }
1077
- if (Test-GoogleAccountRowShape 'ControlType.Hyperlink' $false 240 40 $false) { throw 'account link without an action pattern accepted' }
1078
- if (Test-GoogleAccountRowShape 'ControlType.Hyperlink' $false 100 40 $true) { throw 'small account link accepted' }
1079
- if (Test-GoogleAccountRowShape 'ControlType.Hyperlink' $false 240 10 $true) { throw 'short account link accepted' }
1080
- $shape = Format-GoogleAccountRowShape 'ControlType.Hyperlink' 240 40 $false $true $false $false
1081
- if ($shape -ne 'ControlType.Hyperlink(width=240,height=40,offscreen=False,invoke=True,select=False,legacy=False)') { throw 'account shape diagnostic drifted' }
1082
- $privateShape = Format-GoogleAccountRowShape 'person@example.com https://example.invalid/private' 240 40 $false $false $false $false
1083
- if ($privateShape -match '@|https?://|person|private') { throw 'account shape diagnostic leaked private text' }
1084
- $privateException = [InvalidOperationException]::new('person@example.com https://example.invalid/private')
1085
- $privateRecord = [Management.Automation.ErrorRecord]::new($privateException, 'private-id', [Management.Automation.ErrorCategory]::NotSpecified, $null)
1086
- $exceptionDetail = Format-GoogleAccountRowException $privateRecord
1087
- if ($exceptionDetail -notmatch 'type=InvalidOperationException,hresult=0x[0-9A-F]{8}.*line=0') { throw 'account exception diagnostic drifted' }
1088
- if ($exceptionDetail -match '@|https?://|person|private') { throw 'account exception diagnostic leaked private text' }
1089
- foreach ($fixture in @(@{ values = @(); expected = 0 }, @{ values = @('one@example.test'); expected = 1 },
1090
- @{ values = @('one@example.test', 'two@example.test', 'three@example.test'); expected = 3 })) {
1091
- $accountArray = @(if ($true) { $fixture.values })
1092
- if ($accountArray.Count -ne $fixture.expected) { throw 'MSAA account array lost empty, single or multiple semantics' }
1093
- }
1094
- $notChooserAccounts = @(if ($false) { 'one@example.test' })
1095
- if ($notChooserAccounts.Count -ne 0) { throw 'non-chooser MSAA account array was not empty' }
1096
- $first = [pscustomobject]@{ email = 'one@example.com'; element = [object]::new() }
1097
- $same = [pscustomobject]@{ email = 'one@example.com'; element = $first.element }
1098
- $second = [pscustomobject]@{ email = 'two@example.com'; element = [object]::new() }
1099
- $unique = Select-UniqueGoogleAccountRows @($first, $same, $second)
1100
- if ($unique.ambiguous -or $unique.rows.Count -ne 2) { throw 'two unique account rows were not accepted' }
1101
- if (-not (Test-GoogleAccountEvidenceAgreement @('two@example.com', 'one@example.com') $unique.rows)) { throw 'two independent account trees did not agree' }
1102
- if (Test-GoogleAccountEvidenceAgreement @('one@example.com', 'other@example.com') $unique.rows) { throw 'different account trees were accepted' }
1103
- if (Test-GoogleAccountEvidenceAgreement @('one@example.com', 'one@example.com') $unique.rows) { throw 'duplicate account evidence was accepted' }
1104
- if (Test-GoogleAccountEvidenceAgreement @() $unique.rows) { throw 'empty account evidence was accepted' }
1105
- $duplicate = Select-UniqueGoogleAccountRows @($first, [pscustomobject]@{ email = 'one@example.com'; element = [object]::new() })
1106
- if (-not $duplicate.ambiguous) { throw 'two different actions for one account accepted' }
1107
- if (-not (Test-GoogleAccountAmbiguity 2 @())) { throw 'multiple accessible accounts accepted' }
1108
- if (-not (Test-GoogleAccountAmbiguity 0 @(@{ name = 'one@example.com' }, @{ name = 'two@example.com' }))) { throw 'multiple fallback accounts accepted' }
1109
- if (Test-GoogleAccountAmbiguity 1 @(@{ name = 'one@example.com' }, @{ name = 'ONE@example.com' })) { throw 'duplicate accessible labels treated as separate accounts' }
1110
- if (-not (Test-GoogleAccountChooserLoading $false 0 0 0 0)) { throw 'initial empty chooser failed before account identities loaded' }
1111
- foreach ($counts in @(@(1, 0, 0, 0), @(0, 1, 0, 0), @(0, 0, 1, 0), @(0, 0, 0, 1))) {
1112
- if (Test-GoogleAccountChooserLoading $false $counts[0] $counts[1] $counts[2] $counts[3]) { throw 'observed account identity treated as initial loading' }
1113
- }
1114
- if (Test-GoogleAccountChooserLoading $true 0 0 0 0) { throw 'previously observed account identities forgotten' }
1115
- if (-not (Test-GoogleAccountChooserPendingNavigation $true $true)) { throw 'selected requested account was not allowed to navigate' }
1116
- if ((Test-GoogleAccountChooserPendingNavigation $true $false) -or
1117
- (Test-GoogleAccountChooserPendingNavigation $false $true) -or
1118
- (Test-GoogleAccountChooserPendingNavigation $false $false)) { throw 'unselected chooser or following page skipped' }
1119
- # Live Windows chooser shape (2026-10-06): each row is a passive ListItem whose name glues the
1120
- # display name onto the email, around an actionable link; a signed-out row's link carries its
1121
- # status, while MSAA reads the same account without it.
1122
- $signedOut = [string][char]0x5df2 + [string][char]0x9000 + [string][char]0x51fa
1123
- $chooser = @(
1124
- @{ name = 'Ada Lovelaceada@example.com'; actionable = $false },
1125
- @{ name = 'Ada Lovelace ada@example.com'; actionable = $true },
1126
- @{ name = "Bob Byrnebob@example.com$signedOut"; actionable = $false },
1127
- @{ name = "Bob Byrne bob@example.com $signedOut"; actionable = $true },
1128
- @{ name = 'Cy Young cy@example.com'; actionable = $true },
1129
- @{ name = 'Remove cy@example.com'; actionable = $true })
1130
- if ((@(Get-GoogleVisibleAccountEmails $chooser) -join ',') -ne 'ada@example.com,cy@example.com') { throw 'glued row text or a signed-out row counted as a visible account' }
1131
- if ((@(Select-UsableGoogleMsaaEmails @('ada@example.com', 'bob@example.com', 'cy@example.com') $chooser) -join ',') -ne 'ada@example.com,cy@example.com') { throw 'MSAA kept an account the chooser marks unusable, or dropped a usable one' }
1132
- if (@(Get-GoogleVisibleAccountEmails @(@{ name = 'one@example.com'; actionable = $false })).Count -ne 0) { throw 'passive account text counted as a visible account' }
1133
- # "Advanced" toggles the notice; pressing it again hides the approved continue link.
1134
- $advancedTraditional = [string][char]0x9032 + [string][char]0x968e
1135
- foreach ($name in @('Advanced', ' Show advanced ', $advancedTraditional)) {
1136
- if (-not (Test-GoogleAdvancedControl $name)) { throw 'notice expansion control missed' }
1137
- }
1138
- foreach ($name in @('Go to Zortex (unsafe)', 'Continue', 'Hide advanced')) {
1139
- if (Test-GoogleAdvancedControl $name) { throw 'non-expansion control treated as notice expansion' }
1140
- }
1141
- $afterAdvanced = @(Get-GoogleClickableConsentNames $true)
1142
- if (@($afterAdvanced | Where-Object { Test-GoogleAdvancedControl $_ }).Count -ne 0) { throw 'notice expansion offered twice on one page' }
1143
- if ('Go to Zortex (unsafe)' -in $afterAdvanced -or 'Continue' -notin $afterAdvanced) { throw 'warning was offered or consent dropped after expansion' }
1144
- if ('Advanced' -in @(Get-GoogleClickableConsentNames $false)) { throw 'notice expansion offered as consent' }
1145
- if ((Get-OAuthClickCategory 'Advanced') -ne 'advanced' -or (Get-OAuthClickCategory 'Go to Zortex (unsafe)') -ne 'notice-continue' -or
1146
- (Get-OAuthClickCategory 'Continue') -ne 'consent') { throw 'OAuth click category drifted' }
1147
- # A chooser row or a page document can be mid-render on one look; failures wait a bounded settle window.
1148
- $t0 = [DateTime]::new(2026, 10, 6, 12, 0, 0, [DateTimeKind]::Utc)
1149
- if (-not (Test-StillSettling $null $t0 5000)) { throw 'first unresolved observation did not start a settle window' }
1150
- if (-not (Test-StillSettling $t0 $t0.AddMilliseconds(4900) 5000)) { throw 'settle window ended early' }
1151
- if (Test-StillSettling $t0 $t0.AddMilliseconds(5000) 5000) { throw 'settle window never ends' }
1152
- if (-not (Test-PageContentMissing 0) -or (Test-PageContentMissing 1)) { throw 'missing page document misjudged' }
1153
- # Tab binding: the same tab proceeds; a different tab still carrying the OAuth transaction
1154
- # rebinds; otherwise wait a bounded window (a navigation can momentarily drop the selected
1155
- # tab or its query) before failing, and never act while unverified.
1156
- if ((Resolve-TabBinding '1.2' '1.2' $true $null $t0 4000).action -ne 'proceed') { throw 'same tab was not allowed to proceed' }
1157
- if ((Resolve-TabBinding '1.3' '1.2' $true $null $t0 4000).boundTab -cne '1.3') { throw 'same-transaction tab did not rebind' }
1158
- if ((Resolve-TabBinding '' '1.2' $false $null $t0 4000).action -ne 'wait') { throw 'a momentarily unreadable tab did not wait' }
1159
- if ((Resolve-TabBinding '1.9' '1.2' $false $t0 $t0.AddMilliseconds(3999) 4000).action -ne 'wait') { throw 'tab mismatch failed before the settle window' }
1160
- if ((Resolve-TabBinding '1.9' '1.2' $false $t0 $t0.AddMilliseconds(4000) 4000).action -ne 'fail') { throw 'a persistent foreign tab was not failed' }
1161
- $script:OAuthTrace = [Collections.Generic.List[string]]::new()
1162
- Add-OAuthTrace '/signin/oauth/warning' (Get-OAuthClickCategory 'person@example.com https://example.invalid/private') 'uia'
1163
- if ((Format-OAuthTrace) -ne '/signin/oauth/warning:other/uia') { throw 'OAuth trace format drifted' }
1164
- if ((Format-OAuthTrace) -match '@|https?://|person|private') { throw 'OAuth trace leaked private text' }
1165
- if (-not (Test-GoogleScopeControl 'See and download all your Google Drive files')) { throw 'google drive scope refused' }
1166
- if (-not (Test-GoogleScopeControl 'Read all resources and their metadata')) { throw 'google scope metadata refused' }
1167
- if (-not (Test-GoogleScopeRowText ([string][char]0x5168 + [string][char]0x9009))) { throw 'google chinese select all scope row refused' }
1168
- if (-not (Test-GoogleScopeControl ([regex]::Unescape('\u5168\u9078'))) -or
1169
- -not (Test-GoogleScopeRowText ([regex]::Unescape('\u5168\u9078')))) { throw 'traditional select all scope control refused' }
1170
- if (-not (Test-GoogleScopeRowText ([regex]::Unescape('\u8b80\u53d6\u96fb\u5b50\u90f5\u4ef6')))) { throw 'traditional read scope row refused' }
1171
- if (-not (Test-SameRow @{ Top = 120; Height = 20; Left = 900; Right = 920 } @{ Top = 116; Height = 24; Left = 200; Right = 850 })) { throw 'scope row alignment missed' }
1172
- $quoted = Quote-BrowserArgument 'C:\Profiles\me\Chrome User Data'
1173
- if ($quoted -ne '"C:\Profiles\me\Chrome User Data"') { throw 'browser argument quoting drifted' }
1174
- if (Test-ConsentControl 'microsoft' 'Go to unsafe') { throw 'microsoft unsafe control accepted' }
1175
-
1176
- if (-not (Test-NotionLoginPage ([uri]'https://app.notion.com/login'))) { throw 'Notion sign-in page missed' }
1177
- if (Test-NotionLoginPage ([uri]'https://app.notion.com/install-integration')) { throw 'Notion consent page treated as sign-in' }
1178
-
1179
- if ((ConvertTo-BrowserUri 'accounts.google.com/v3/signin').AbsoluteUri -ne 'https://accounts.google.com/v3/signin') { throw 'scheme-less Google URL drifted' }
1180
- if ((ConvertTo-BrowserUri '127.0.0.1:8123/callback').AbsoluteUri -ne 'http://127.0.0.1:8123/callback') { throw 'scheme-less loopback URL drifted' }
1181
- Write-Result @{ state = 'self_test'; ok = $true }
1182
- }
1183
-
1184
- Add-Type -AssemblyName UIAutomationClient
1185
- Add-Type -AssemblyName UIAutomationTypes
1186
- Add-Type -AssemblyName System.Web
1187
- Add-Type -AssemblyName System.Windows.Forms
1188
- Add-Type -AssemblyName Accessibility
1189
- Add-Type -AssemblyName WindowsBase
1190
- Add-Type -ReferencedAssemblies @('Accessibility.dll') -TypeDefinition @'
1191
- using System;
1192
- using System.Collections.Generic;
1193
- using System.Runtime.InteropServices;
1194
- using System.Text;
1195
- using System.Text.RegularExpressions;
1196
- using Accessibility;
1197
-
1198
- public static class ChromiumAccessibility {
1199
- private delegate bool EnumChildProc(IntPtr hwnd, IntPtr lParam);
1200
- private const uint ClientObjectId = unchecked((uint)-4); // OBJID_CLIENT
1201
- [DllImport("user32.dll")] private static extern bool EnumChildWindows(IntPtr parent, EnumChildProc callback, IntPtr lParam);
1202
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(IntPtr hwnd, StringBuilder name, int maxCount);
1203
- [DllImport("oleacc.dll")] private static extern int AccessibleObjectFromWindow(IntPtr hwnd, uint objectId, ref Guid iid, [MarshalAs(UnmanagedType.Interface)] out object root);
1204
-
1205
- public static void Enable(IntPtr browserWindow) {
1206
- if (browserWindow == IntPtr.Zero) return;
1207
- EnumChildWindows(browserWindow, (hwnd, _) => {
1208
- var name = new StringBuilder(256);
1209
- GetClassName(hwnd, name, name.Capacity);
1210
- if (name.ToString() == "Chrome_RenderWidgetHostHWND") {
1211
- // Ask the accessibility client API to obtain OBJID_CLIENT. It owns the
1212
- // WM_GETOBJECT flags, object id and interface marshaling for the provider.
1213
- var iid = new Guid("618736e0-3c3d-11cf-810c-00aa00389b71"); // IID_IAccessible
1214
- object root = null;
1215
- try { AccessibleObjectFromWindow(hwnd, ClientObjectId, ref iid, out root); }
1216
- finally { if (root != null && Marshal.IsComObject(root)) Marshal.ReleaseComObject(root); }
1217
- }
1218
- return true;
1219
- }, IntPtr.Zero);
1220
- }
1221
- }
1222
-
1223
- public static class ChromiumMsaa {
1224
- private static Func<IntPtr,long[]> rendererPolicy;
1225
- private static Func<IntPtr,IntPtr,long,bool> actionPolicy;
1226
- public static void InstallPolicies(Func<IntPtr,long[]> renderer,Func<IntPtr,IntPtr,long,bool> action) {
1227
- if(renderer==null || action==null) throw new InvalidOperationException("background_msaa_policy_unavailable");
1228
- rendererPolicy=renderer;actionPolicy=action;
1229
- }
1230
- private delegate bool EnumChildProc(IntPtr hwnd, IntPtr lParam);
1231
- [DllImport("user32.dll")] private static extern bool EnumChildWindows(IntPtr parent, EnumChildProc callback, IntPtr lParam);
1232
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(IntPtr hwnd, StringBuilder name, int maxCount);
1233
- [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hwnd);
1234
- [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hwnd, out RECT rect);
1235
- [DllImport("oleacc.dll")] private static extern int AccessibleObjectFromWindow(IntPtr hwnd, uint objectId, ref Guid iid, [MarshalAs(UnmanagedType.Interface)] out object root);
1236
- [DllImport("oleacc.dll")] private static extern int AccessibleChildren(IAccessible container, int start, int count, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] object[] children, out int obtained);
1237
-
1238
- private struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
1239
-
1240
- private sealed class Item {
1241
- public IntPtr Root,Renderer;
1242
- public long Generation;
1243
- public IAccessible Acc;
1244
- public object Child;
1245
- public string Name;
1246
- public string Action;
1247
- public string Bounds;
1248
- public int Left;
1249
- public int Top;
1250
- public int Width;
1251
- public int Height;
1252
- }
1253
-
1254
- private static IEnumerable<IntPtr> RenderWindows(IntPtr browserWindow, bool visibleOnly = true) {
1255
- var result = new List<IntPtr>();
1256
- EnumChildWindows(browserWindow, (hwnd, _) => {
1257
- var name = new StringBuilder(256);
1258
- GetClassName(hwnd, name, name.Capacity);
1259
- if (name.ToString() == "Chrome_RenderWidgetHostHWND" && (!visibleOnly || IsWindowVisible(hwnd))) result.Add(hwnd);
1260
- return true;
1261
- }, IntPtr.Zero);
1262
- return result;
1263
- }
1264
-
1265
- public static int RenderWindowCount(IntPtr browserWindow, bool visibleOnly) {
1266
- return new List<IntPtr>(RenderWindows(browserWindow, visibleOnly)).Count;
1267
- }
1268
-
1269
- private static void Add(List<Item> items, IAccessible acc, object child) {
1270
- try {
1271
- var name = acc.get_accName(child) ?? "";
1272
- var action = acc.get_accDefaultAction(child) ?? "";
1273
- int left, top, width, height;
1274
- acc.accLocation(out left, out top, out width, out height, child);
1275
- if (name.Length > 0) items.Add(new Item { Acc = acc, Child = child, Name = name, Action = action, Bounds = left + "," + top + "," + width + "," + height, Left = left, Top = top, Width = width, Height = height });
1276
- } catch {}
1277
- }
1278
-
1279
- private static void Walk(IAccessible acc, List<Item> items, int depth) {
1280
- if (depth > 50 || items.Count > 10000) return;
1281
- Add(items, acc, 0);
1282
- int count;
1283
- try { count = acc.accChildCount; } catch { return; }
1284
- if (count <= 0) return;
1285
- var children = new object[count];
1286
- int obtained;
1287
- if (AccessibleChildren(acc, 0, count, children, out obtained) < 0) return;
1288
- for (var i = 0; i < obtained; i++) {
1289
- var child = children[i];
1290
- var nested = child as IAccessible;
1291
- if (nested != null) Walk(nested, items, depth + 1);
1292
- else Add(items, acc, child);
1293
- }
1294
- }
1295
-
1296
- public static IntPtr ActiveRenderWindow(IntPtr browserWindow) {
1297
- var windows = new List<IntPtr>(RenderWindows(browserWindow));
1298
- if (windows.Count == 0) return IntPtr.Zero;
1299
- IntPtr best = IntPtr.Zero;
1300
- long bestArea = -1;
1301
- foreach (var hwnd in windows) {
1302
- RECT rect;
1303
- long area = 0;
1304
- if (GetWindowRect(hwnd, out rect)) area = Math.Max(0, rect.Right - rect.Left) * (long)Math.Max(0, rect.Bottom - rect.Top);
1305
- if (area > bestArea) { bestArea = area; best = hwnd; }
1306
- }
1307
- return best;
1308
- }
1309
-
1310
- public static long[] RendererMetrics(IntPtr browserWindow,IntPtr renderer) {
1311
- var largest=ActiveRenderWindow(browserWindow);
1312
- RECT nativeRect=new RECT(),largestRect=new RECT();
1313
- bool nativeBounds=renderer!=IntPtr.Zero && GetWindowRect(renderer,out nativeRect);
1314
- bool largestBounds=largest!=IntPtr.Zero && GetWindowRect(largest,out largestRect);
1315
- return new long[] {renderer!=IntPtr.Zero && renderer==largest ? 1 : 0,
1316
- nativeBounds ? Math.Max(0,nativeRect.Right-(long)nativeRect.Left) : -1,
1317
- nativeBounds ? Math.Max(0,nativeRect.Bottom-(long)nativeRect.Top) : -1,
1318
- largestBounds ? Math.Max(0,largestRect.Right-(long)largestRect.Left) : -1,
1319
- largestBounds ? Math.Max(0,largestRect.Bottom-(long)largestRect.Top) : -1,
1320
- renderer!=IntPtr.Zero && IsWindowVisible(renderer) ? 1 : 0,largest!=IntPtr.Zero ? 1 : 0};
1321
- }
1322
-
1323
- private static List<Item> Items(IntPtr browserWindow) {
1324
- var items = new List<Item>();
1325
- if(rendererPolicy==null || actionPolicy==null) throw new InvalidOperationException("background_msaa_policy_unavailable");
1326
- var verified=rendererPolicy(browserWindow);
1327
- if(verified==null || verified.Length!=2 || verified[0]==0 || verified[1]<=0 || (verified[1]&1)!=0) return items;
1328
- var iid = new Guid("618736e0-3c3d-11cf-810c-00aa00389b71");
1329
- var hwnd = new IntPtr(verified[0]);
1330
- object root;
1331
- if (hwnd != IntPtr.Zero && AccessibleObjectFromWindow(hwnd, unchecked((uint)-4), ref iid, out root) >= 0 && root is IAccessible) Walk((IAccessible)root, items, 0);
1332
- foreach(var item in items) { item.Root=browserWindow;item.Renderer=hwnd;item.Generation=verified[1]; }
1333
- return items;
1334
- }
1335
-
1336
- private static bool InvokeItem(Item item) {
1337
- // Compiled policies re-read cancellation, chrome and the native epoch after
1338
- // the MSAA walk; never invoke against a newly chosen/largest renderer.
1339
- if(item==null || actionPolicy==null || item.Root==IntPtr.Zero || item.Renderer==IntPtr.Zero ||
1340
- item.Generation<=0 || (item.Generation&1)!=0 || !actionPolicy(item.Root,item.Renderer,item.Generation))
1341
- throw new InvalidOperationException("background_msaa_action_refused");
1342
- // A DOM child id can be reused without replacing the native renderer.
1343
- // Require this same live control to remain named, enabled and onscreen.
1344
- if(item.Acc.get_accName(item.Child)!=item.Name || item.Acc.get_accDefaultAction(item.Child)!=item.Action) return false;
1345
- long state=Convert.ToInt64(item.Acc.get_accState(item.Child));
1346
- if((state&(0x0001|0x8000|0x10000))!=0) return false;
1347
- int left,top,width,height;
1348
- item.Acc.accLocation(out left,out top,out width,out height,item.Child);
1349
- if(width<=0 || height<=0) return false;
1350
- if(!actionPolicy(item.Root,item.Renderer,item.Generation)) throw new InvalidOperationException("background_msaa_action_refused");
1351
- item.Acc.accDoDefaultAction(item.Child);return true;
1352
- }
1353
-
1354
- private static List<Item> Accounts(IntPtr browserWindow) {
1355
- var candidates = Items(browserWindow).FindAll(item => item.Action.Length > 0 && AccountEmail(item.Name) != null && item.Width >= 160 && item.Height >= 28);
1356
- candidates.Sort((a, b) => (b.Width * b.Height).CompareTo(a.Width * a.Height));
1357
- var result = new List<Item>();
1358
- var seen = new HashSet<string>();
1359
- foreach (var item in candidates) {
1360
- var centerX = item.Left + item.Width / 2;
1361
- var centerY = item.Top + item.Height / 2;
1362
- if (seen.Add(item.Bounds) && !result.Exists(parent => centerX >= parent.Left && centerX <= parent.Left + parent.Width && centerY >= parent.Top && centerY <= parent.Top + parent.Height)) result.Add(item);
1363
- }
1364
- result.Sort((a, b) => a.Top != b.Top ? a.Top.CompareTo(b.Top) : a.Left.CompareTo(b.Left));
1365
- return result;
1366
- }
1367
-
1368
- private static string AccountEmail(string name) {
1369
- var matches = Regex.Matches(name, "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
1370
- if (matches.Count != 1) return null;
1371
- var outsideEmail = name.Remove(matches[0].Index, matches[0].Length);
1372
- if (Regex.IsMatch(outsideEmail, "choose an account|use another account|to continue|zortex|\\b(remove|delete|manage|sign out|log ?out|disconnect|forget)\\b|\\u79fb\\u9664|\\u522a\\u9664|\\u7ba1\\u7406|\\u9000\\u51fa|\\u9009\\u62e9.*(\\u8d26|\\u5e10)\\u53f7|\\u4f7f\\u7528\\u5176\\u4ed6.*(\\u8d26|\\u5e10)\\u53f7|\\u9078\\u64c7.*(?:\\u5e33|\\u8cec)(?:\\u6236|\\u865f)|\\u4f7f\\u7528\\u5176\\u4ed6.*(?:\\u5e33|\\u8cec)(?:\\u6236|\\u865f)|\\u767b\\u51fa|\\u7e7c\\u7e8c", RegexOptions.IgnoreCase)) return null;
1373
- return matches[0].Value.ToLowerInvariant();
1374
- }
1375
-
1376
- public static string[] AccountEmails(IntPtr browserWindow) {
1377
- var accounts = Accounts(browserWindow);
1378
- var seenEmails = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
1379
- var emails = new List<string>();
1380
- foreach (var item in accounts) {
1381
- var email = AccountEmail(item.Name);
1382
- if (email == null || !seenEmails.Add(email)) return new string[0];
1383
- emails.Add(email);
1384
- }
1385
- // Preserve the same top-to-bottom order used by InvokeAccount(index).
1386
- return emails.ToArray();
1387
- }
1388
-
1389
- private static string accountInvokeDiagnostic = "not_attempted";
1390
-
1391
- private static string SafeAccountInvokeException(Exception error) {
1392
- return "type=" + error.GetType().Name + ",hresult=0x" + unchecked((uint)error.HResult).ToString("X8");
1393
- }
1394
-
1395
- public static string AccountInvokeDiagnostic() { return accountInvokeDiagnostic; }
1396
-
1397
- public static bool InvokeAccountByEmail(IntPtr browserWindow, string email) {
1398
- var matches = Accounts(browserWindow).FindAll(item => string.Equals(AccountEmail(item.Name), email, StringComparison.OrdinalIgnoreCase));
1399
- accountInvokeDiagnostic = "matches=" + matches.Count + ",outcome=not_unique";
1400
- if (matches.Count != 1) return false;
1401
- try {
1402
- if(!InvokeItem(matches[0])) { accountInvokeDiagnostic="matches=1,outcome=changed";return false; }
1403
- accountInvokeDiagnostic = "matches=1,outcome=completed";
1404
- return true;
1405
- } catch (Exception error) {
1406
- if(error.Message.StartsWith("background_",StringComparison.Ordinal)) throw;
1407
- accountInvokeDiagnostic = "matches=1,outcome=exception," + SafeAccountInvokeException(error);
1408
- return false;
1409
- }
1410
- }
1411
-
1412
- public static int AccountCount(IntPtr browserWindow) { return Accounts(browserWindow).Count; }
1413
-
1414
- public static bool InvokeAccount(IntPtr browserWindow, int index) {
1415
- var accounts = Accounts(browserWindow);
1416
- if (index < 0 || index >= accounts.Count) return false;
1417
- try { return InvokeItem(accounts[index]); }
1418
- catch(Exception error) { if(error.Message.StartsWith("background_",StringComparison.Ordinal)) throw;return false; }
1419
- }
1420
-
1421
- // The accessible name of the last control InvokeNamed pressed; callers reduce it to a category.
1422
- public static string LastInvoked = "";
1423
-
1424
- public static bool InvokeNamed(IntPtr browserWindow, string[] allowed) {
1425
- foreach (var item in Items(browserWindow)) {
1426
- if (item.Action.Length == 0) continue;
1427
- foreach (var name in allowed) {
1428
- if (!string.Equals(item.Name.Trim(), name, StringComparison.OrdinalIgnoreCase)) continue;
1429
- try { LastInvoked = item.Name.Trim();return InvokeItem(item); }
1430
- catch(Exception error) { if(error.Message.StartsWith("background_",StringComparison.Ordinal)) throw;return false; }
1431
- }
1432
- }
1433
- return false;
1434
- }
1435
-
1436
- public static int CountNamed(IntPtr browserWindow, string[] allowed) {
1437
- var count = 0;
1438
- foreach (var item in Items(browserWindow)) foreach (var name in allowed) if (item.Action.Length > 0 && string.Equals(item.Name.Trim(), name, StringComparison.OrdinalIgnoreCase)) count++;
1439
- return count;
1440
- }
1441
- }
1442
-
1443
- public static class ZortexNativeWindow {
1444
- public static System.Threading.Tasks.Task<string> ReadCancellation() {
1445
- return System.Threading.Tasks.Task.Run(() => Console.In.ReadLine());
1446
- }
1447
- private delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
1448
- [DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc callback, IntPtr lParam);
1449
- [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out int processId);
1450
- [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hwnd);
1451
- [DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hwnd, uint message, IntPtr wParam, IntPtr lParam);
1452
- [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
1453
-
1454
- public static IntPtr[] VisibleTopLevelWindowsForProcess(int pid) {
1455
- var handles = new List<IntPtr>();
1456
- EnumWindows((hwnd, _) => {
1457
- int ownerPid;
1458
- GetWindowThreadProcessId(hwnd, out ownerPid);
1459
- if (ownerPid == pid && IsWindowVisible(hwnd)) handles.Add(hwnd);
1460
- return true;
1461
- }, IntPtr.Zero);
1462
- return handles.ToArray();
1463
- }
1464
-
1465
-
1466
-
1467
- public static bool Close(IntPtr hwnd) {
1468
- if (hwnd == IntPtr.Zero) return false;
1469
- return PostMessage(hwnd, 0x0010, IntPtr.Zero, IntPtr.Zero);
1470
- }
1471
-
1472
-
1473
-
1474
- public static bool IsForeground(IntPtr hwnd) {
1475
- return hwnd != IntPtr.Zero && GetForegroundWindow() == hwnd;
1476
- }
1477
- }
1478
-
1479
- '@
1480
-
1481
- Add-Type -Path (Join-Path $PSScriptRoot 'windows-oauth-background.cs') -ReferencedAssemblies @(
1482
- 'System.dll', 'Accessibility.dll', [Windows.Automation.AutomationElement].Assembly.Location,
1483
- [Windows.Automation.ControlType].Assembly.Location, [Windows.Rect].Assembly.Location)
1484
-
1485
- # Compiled delegates avoid calling a PowerShell runspace from a COM callback.
1486
- $policyFlags = [Reflection.BindingFlags]::Public -bor [Reflection.BindingFlags]::Static
1487
- [ChromiumMsaa]::InstallPolicies(
1488
- [Delegate]::CreateDelegate([Func[IntPtr,long[]]], [OAuthBackground].GetMethod('PageRenderer', $policyFlags)),
1489
- [Delegate]::CreateDelegate([Func[IntPtr,IntPtr,long,bool]], [OAuthBackground].GetMethod('PageActionAllowed', $policyFlags)))
1490
-
1491
- function Test-BackgroundGuardException($ErrorRecord) {
1492
- return $ErrorRecord.Exception.GetBaseException().Message.StartsWith('background_', [StringComparison]::Ordinal)
1493
- }
1494
-
1495
- function Get-Pattern($Element, $Pattern) {
1496
- $value = $null
1497
- if ($Element.TryGetCurrentPattern($Pattern, [ref]$value)) { return $value }
1498
- return $null
1499
- }
1500
-
1501
- function Get-LegacyPattern($Element) {
1502
- # Windows PowerShell's managed UIAutomationClient can omit this pattern type.
1503
- # Keep Invoke/SelectionItem and the native MSAA route available on that host.
1504
- $type = [Windows.Automation.AutomationElement].Assembly.GetType('System.Windows.Automation.LegacyIAccessiblePattern', $false)
1505
- if ($null -eq $type) { return $null }
1506
- $field = $type.GetField('Pattern', ([Reflection.BindingFlags]::Public -bor [Reflection.BindingFlags]::Static))
1507
- if ($null -eq $field) { return $null }
1508
- return Get-Pattern $Element ($field.GetValue($null))
1509
- }
1510
-
1511
- function Get-ConsentDiagnostic($Named, [IntPtr]$Root, [string]$Provider, [int]$NamedCount, [int]$MsaaCount, [int]$ScopeCount) {
1512
- $policy = [OAuthBackground]::PagePolicyDiagnostics()
1513
- $result = @{ lastNamedCount = $NamedCount; msaaConsentCount = $MsaaCount; scopeToggleCount = $ScopeCount;
1514
- candidateCount = 0; enabledCount = 0; offscreenCount = 0; invokePatternCount = 0; selectionPatternCount = 0;
1515
- togglePatternCount = 0; expandPatternCount = 0; legacyPatternCount = 0; actionableCount = 0;
1516
- pageFailure = $policy[0]; snapshotComplete = $policy[1]; snapshotTabs = $policy[2]; snapshotMs = $policy[3]; snapshotSameTab = $policy[4]; snapshotSameUrl = $policy[5];
1517
- nativeMatchesLargest = -1; nativeWidth = -1; nativeHeight = -1; largestWidth = -1; largestHeight = -1; nativeVisible = -1; largestPresent = -1;
1518
- topDocumentCount = 0; topDocumentNativeMatchCount = 0; error = 0 }
1519
- $clock = [Diagnostics.Stopwatch]::StartNew()
1520
- $seen = [Collections.Generic.HashSet[string]]::new()
1521
- foreach ($candidate in $Named) {
1522
- if ($clock.ElapsedMilliseconds -gt 1000 -or $seen.Count -ge 512) { break }
1523
- $matches = $(if ($Provider -ceq 'notion') { [bool](Get-NotionConsentAction ([string]$candidate.name) $true) } else { Test-ConsentControl $Provider ([string]$candidate.name) })
1524
- if (-not $matches) { continue }
1525
- try {
1526
- $element = $candidate.element
1527
- if (-not $seen.Add(($element.GetRuntimeId() -join '.'))) { continue }
1528
- $result.candidateCount++
1529
- $current = $element.Current
1530
- if ($current.IsEnabled) { $result.enabledCount++ }
1531
- if ($current.IsOffscreen) { $result.offscreenCount++ }
1532
- $actionable = $false
1533
- foreach ($entry in @(@('invokePatternCount', [Windows.Automation.InvokePattern]::Pattern),
1534
- @('selectionPatternCount', [Windows.Automation.SelectionItemPattern]::Pattern),
1535
- @('togglePatternCount', [Windows.Automation.TogglePattern]::Pattern),
1536
- @('expandPatternCount', [Windows.Automation.ExpandCollapsePattern]::Pattern))) {
1537
- if ($null -ne (Get-Pattern $element $entry[1])) { $result[$entry[0]]++; $actionable = $true }
1538
- }
1539
- if ($null -ne (Get-LegacyPattern $element)) { $result.legacyPatternCount++; $actionable = $true }
1540
- $rect = $current.BoundingRectangle
1541
- if ($actionable -and $current.IsEnabled -and -not $current.IsOffscreen -and -not $rect.IsEmpty -and $rect.Width -gt 0 -and $rect.Height -gt 0) { $result.actionableCount++ }
1542
- } catch { $result.error = [int]$_.Exception.GetBaseException().HResult }
1543
- }
1544
- try {
1545
- $native = New-Object OAuthBackground+Stats
1546
- $id = $script:BackgroundIdentity
1547
- if ($null -ne $id -and [OAuthBackground]::Read([ref]$native) -eq 0 -and
1548
- [OAuthBackground]::RootValid($Root, $id.Pid, $id.Tid, $script:BackgroundNonce)) {
1549
- $metrics = [ChromiumMsaa]::RendererMetrics($Root, [IntPtr]([long]$native.Renderer))
1550
- $keys = @('nativeMatchesLargest', 'nativeWidth', 'nativeHeight', 'largestWidth', 'largestHeight', 'nativeVisible', 'largestPresent')
1551
- for ($index = 0; $index -lt $keys.Count; $index++) { $result[$keys[$index]] = $metrics[$index] }
1552
- if ($clock.ElapsedMilliseconds -le 1000) {
1553
- $window = [Windows.Automation.AutomationElement]::FromHandle($Root)
1554
- $condition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ControlTypeProperty, [Windows.Automation.ControlType]::Document)
1555
- $documents = $window.FindAll([Windows.Automation.TreeScope]::Descendants, $condition)
1556
- foreach ($document in $documents) {
1557
- if ($clock.ElapsedMilliseconds -gt 1000) { break }
1558
- $result.topDocumentCount++
1559
- if ([long]$document.Current.NativeWindowHandle -eq [long]$native.Renderer) { $result.topDocumentNativeMatchCount++ }
1560
- }
1561
- }
1562
- }
1563
- } catch { $result.error = [int]$_.Exception.GetBaseException().HResult }
1564
- return $result
1565
- }
1566
-
1567
- if ($SelfTestNative) {
1568
- $flags = [Reflection.BindingFlags]::NonPublic -bor [Reflection.BindingFlags]::Static
1569
- $activationApi = [ChromiumAccessibility].GetMethod('AccessibleObjectFromWindow', $flags)
1570
- if ($null -eq $activationApi) { throw 'native accessibility client API did not compile' }
1571
- $import = @($activationApi.GetCustomAttributes([Runtime.InteropServices.DllImportAttribute], $false))
1572
- if ($import.Count -ne 1 -or $import[0].Value -ne 'oleacc.dll' -or $import[0].EntryPoint -ne 'AccessibleObjectFromWindow') { throw 'native accessibility client API binding drifted' }
1573
- $parameters = $activationApi.GetParameters()
1574
- if ($parameters.Count -ne 4 -or $parameters[0].ParameterType -ne [IntPtr] -or $parameters[1].ParameterType -ne [uint32] -or -not $parameters[2].ParameterType.IsByRef -or -not $parameters[3].IsOut) { throw 'native accessibility client API signature drifted' }
1575
- $objectId = [ChromiumAccessibility].GetField('ClientObjectId', $flags)
1576
- if ($null -eq $objectId -or $objectId.GetRawConstantValue() -ne [uint32]4294967292) { throw 'native accessibility client object id drifted' }
1577
- [ChromiumAccessibility]::Enable([IntPtr]::Zero) # Must not enumerate existing windows.
1578
- if ([ZortexNativeWindow]::IsForeground([IntPtr]::Zero)) {
1579
- throw 'invalid OAuth window accepted as foreground'
1580
- }
1581
- $email = [ChromiumMsaa].GetMethod('AccountEmail', $flags)
1582
- if ($null -eq $email) { throw 'native account row validator did not compile' }
1583
- if ($email.Invoke($null, @('manager@example.com')) -ne 'manager@example.com') { throw 'native validator rejected an account email' }
1584
- foreach ($heading in @('\u9078\u64c7\u5e33\u6236', '\u4f7f\u7528\u5176\u4ed6\u5e33\u6236', '\u522a\u9664', '\u767b\u51fa')) {
1585
- if ($null -ne $email.Invoke($null, @(([regex]::Unescape($heading) + ' person@example.com')))) { throw 'native validator accepted a traditional account action' }
1586
- }
1587
- if ($null -ne $email.Invoke($null, @('Remove manager@example.com'))) { throw 'native validator accepted a remove action' }
1588
- $safeException = [ChromiumMsaa].GetMethod('SafeAccountInvokeException', $flags)
1589
- if ($null -eq $safeException) { throw 'native invocation diagnostic did not compile' }
1590
- $privateException = [Runtime.InteropServices.COMException]::new('person@example.com https://example.invalid/private', -2147467263)
1591
- $exceptionDetail = $safeException.Invoke($null, @($privateException))
1592
- if ($exceptionDetail -ne 'type=COMException,hresult=0x80004001') { throw 'native invocation diagnostic drifted' }
1593
- if ($exceptionDetail -match '@|https?://|person|private') { throw 'native invocation diagnostic leaked private text' }
1594
- $legacyType = [Windows.Automation.AutomationElement].Assembly.GetType('System.Windows.Automation.LegacyIAccessiblePattern', $false)
1595
- $legacy = Get-LegacyPattern ([Windows.Automation.AutomationElement]::RootElement)
1596
- if ($null -eq $legacyType -and $null -ne $legacy) { throw 'absent managed legacy pattern returned a value' }
1597
- Write-Result @{ state = 'self_test'; ok = $true }
1598
- }
1599
-
1600
- function Get-RequestedAccountRowFailureReason($Named, [string]$RequestedEmail, [int]$AcceptedRowCount, [int]$RequestedRowCount, [bool]$Ambiguous, [int]$MsaaEmailCount, [bool]$MsaaMatch, [bool]$Selected) {
1601
- $matching = @($Named | Where-Object { (Get-GoogleAccountEmail ([string]$_.name)) -ceq $RequestedEmail })
1602
- $shapes = @()
1603
- foreach ($candidate in $matching) {
1604
- try {
1605
- $element = $candidate.element
1606
- $rect = $element.Current.BoundingRectangle
1607
- $invoke = $null -ne (Get-Pattern $element ([Windows.Automation.InvokePattern]::Pattern))
1608
- $select = $null -ne (Get-Pattern $element ([Windows.Automation.SelectionItemPattern]::Pattern))
1609
- $legacy = $null -ne (Get-LegacyPattern $element)
1610
- $shapes += Format-GoogleAccountRowShape $element.Current.ControlType.ProgrammaticName $rect.Width $rect.Height $element.Current.IsOffscreen $invoke $select $legacy
1611
- } catch { $shapes += Format-GoogleAccountRowException $_ }
1612
- }
1613
- $summary = (@($shapes | Group-Object | Select-Object -First 6 | ForEach-Object { "$($_.Name)x$($_.Count)" }) -join ';')
1614
- $msaaInvoke = [ChromiumMsaa]::AccountInvokeDiagnostic()
1615
- return "requested_account_row_unavailable namedMatches=$($matching.Count) acceptedRows=$AcceptedRowCount requestedRows=$RequestedRowCount ambiguous=$Ambiguous msaaEmailCount=$MsaaEmailCount msaaMatch=$MsaaMatch selected=$Selected msaaInvoke=[$msaaInvoke] uiaInvoke=[$script:AccountUiaActionDiagnostic] shapes=[$summary]"
1616
- }
1617
-
1618
- function Get-GoogleAccountRows($Named) {
1619
- $candidates = @()
1620
- foreach ($candidate in $Named) {
1621
- $email = Get-GoogleAccountEmail ([string]$candidate.name)
1622
- if ($null -eq $email) { continue }
1623
- $element = $candidate.element
1624
- try {
1625
- $rect = $element.Current.BoundingRectangle
1626
- $hasAction = $null -ne (Get-Pattern $element ([Windows.Automation.InvokePattern]::Pattern)) -or
1627
- $null -ne (Get-Pattern $element ([Windows.Automation.SelectionItemPattern]::Pattern)) -or
1628
- $null -ne (Get-LegacyPattern $element)
1629
- if ($rect.IsEmpty -or -not (Test-GoogleAccountRowShape $element.Current.ControlType.ProgrammaticName $element.Current.IsOffscreen $rect.Width $rect.Height $hasAction)) { continue }
1630
- $candidates += [pscustomobject]@{ email = $email; element = $element }
1631
- } catch {}
1632
- }
1633
- return Select-UniqueGoogleAccountRows $candidates
1634
- }
1635
-
1636
- function Invoke-GoogleAccountRow($Row) {
1637
- if (Get-Variable BackgroundGuardStarted -Scope Script -ValueOnly -ErrorAction SilentlyContinue) { Assert-BackgroundAction }
1638
- $element = $Row.element
1639
- $attempts = 0
1640
- $failures = @()
1641
- $stage = 'invoke-pattern'
1642
- try {
1643
- $invoke = Get-Pattern $element ([Windows.Automation.InvokePattern]::Pattern)
1644
- if ($null -ne $invoke) {
1645
- $stage = 'invoke-action'; $attempts++
1646
- Assert-BackgroundAction
1647
- $invoke.Invoke()
1648
- $script:AccountUiaActionDiagnostic = "attempts=$attempts,outcome=completed,pattern=invoke"
1649
- return $true
1650
- }
1651
- } catch { if (Test-BackgroundGuardException $_) { throw }; $failures += "$stage($(Format-GoogleAccountRowException $_))" }
1652
- $stage = 'selection-pattern'
1653
- try {
1654
- $select = Get-Pattern $element ([Windows.Automation.SelectionItemPattern]::Pattern)
1655
- if ($null -ne $select) {
1656
- $stage = 'selection-action'; $attempts++
1657
- Assert-BackgroundAction
1658
- $select.Select()
1659
- $script:AccountUiaActionDiagnostic = "attempts=$attempts,outcome=completed,pattern=selection"
1660
- return $true
1661
- }
1662
- } catch { if (Test-BackgroundGuardException $_) { throw }; $failures += "$stage($(Format-GoogleAccountRowException $_))" }
1663
- $stage = 'legacy-pattern'
1664
- try {
1665
- $legacy = Get-LegacyPattern $element
1666
- if ($null -ne $legacy) {
1667
- $stage = 'legacy-action'; $attempts++
1668
- Assert-BackgroundAction
1669
- $legacy.DoDefaultAction()
1670
- $script:AccountUiaActionDiagnostic = "attempts=$attempts,outcome=completed,pattern=legacy"
1671
- return $true
1672
- }
1673
- } catch { if (Test-BackgroundGuardException $_) { throw }; $failures += "$stage($(Format-GoogleAccountRowException $_))" }
1674
- $outcome = $(if ($failures.Count -gt 0) { 'failed' } else { 'no_action' })
1675
- $script:AccountUiaActionDiagnostic = "attempts=$attempts,outcome=$outcome,failures=[$($failures -join ';')]"
1676
- return $false
1677
- }
1678
-
1679
- function Get-BrowserWindows {
1680
- if ($script:BackgroundGuardStarted) {
1681
- Assert-BackgroundGuard
1682
- $stats = New-Object OAuthBackground+Stats
1683
- if ([OAuthBackground]::Read([ref]$stats) -ne 0) { throw 'background_guard_read_failed' }
1684
- if ($stats.Bound -eq 0) { return @() }
1685
- $handle = [IntPtr]([long]$stats.Bound)
1686
- $identity = $script:BackgroundIdentity
1687
- if (-not [OAuthBackground]::RootValid($handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce)) { throw 'background_window_changed' }
1688
- $script:OwnedBrowserHandle = $handle
1689
- if ($script:Automatic -and -not [OAuthBackground]::KeepBehind($handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce)) { throw 'background_position_refused' }
1690
- # Not listed in the taskbar or Alt+Tab either, in every mode; a window then left for the person is listed again
1691
- # by Write-Result. A failure here only leaves it listed, as before.
1692
- [OAuthBackground]::HideFromSwitcher($handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce) | Out-Null
1693
- $element = [Windows.Automation.AutomationElement]::FromHandle($handle)
1694
- if ($null -ne $element) { return @(@{ element = $element; handle = $handle }) }
1695
- return @()
1696
- }
1697
- $session = (Get-Process -Id $PID).SessionId
1698
- $windows = @()
1699
- $seen = [Collections.Generic.HashSet[string]]::new()
1700
- foreach ($name in @('chrome', 'msedge')) {
1701
- foreach ($process in @(Get-Process -Name $name -ErrorAction SilentlyContinue)) {
1702
- if ($process.SessionId -ne $session) { continue }
1703
- foreach ($handle in @([ZortexNativeWindow]::VisibleTopLevelWindowsForProcess($process.Id))) {
1704
- if ($handle -eq [IntPtr]::Zero -or -not $seen.Add("$handle")) { continue }
1705
- # Before launching, only record HWND ownership metadata. Existing user
1706
- # windows are never queried for page accessibility or URL contents.
1707
- $windows += @{ element = $null; handle = $handle }
1708
- }
1709
- }
1710
- }
1711
- return $windows
1712
- }
1713
- function Get-BrowserLaunchPath {
1714
- foreach ($name in @('chrome', 'msedge')) {
1715
- foreach ($process in @(Get-Process -Name $name -ErrorAction SilentlyContinue)) {
1716
- if (-not [string]::IsNullOrWhiteSpace($process.Path)) { return $process.Path }
1717
- }
1718
- }
1719
- foreach ($path in @(
1720
- "$env:ProgramFiles\Google\Chrome\Application\chrome.exe",
1721
- "${env:ProgramFiles(x86)}\Google\Chrome\Application\chrome.exe",
1722
- "$env:LocalAppData\Google\Chrome\Application\chrome.exe",
1723
- "$env:ProgramFiles\Microsoft\Edge\Application\msedge.exe",
1724
- "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe"
1725
- )) {
1726
- if (-not [string]::IsNullOrWhiteSpace($path) -and (Test-Path -LiteralPath $path)) { return $path }
1727
- }
1728
- return $null
1729
- }
1730
-
1731
- function Start-OAuthBrowser([uri]$Authorization, [string]$Provider) {
1732
- if ($Provider -notin @('google', 'slack', 'microsoft', 'notion')) { throw 'unsupported_background_provider' }
1733
- Start-GuardedOAuthBrowser $Authorization
1734
- }
1735
-
1736
- function Get-GuardedChromeIdentity([string]$Chrome, [string]$UserDataDir) {
1737
- if ([string]::IsNullOrWhiteSpace($Chrome) -or [string]::IsNullOrWhiteSpace($UserDataDir)) { return $null }
1738
- $session = (Get-Process -Id $PID).SessionId
1739
- $identities = @{}
1740
- foreach ($process in @(Get-Process -Name chrome -ErrorAction SilentlyContinue)) {
1741
- if ($process.SessionId -ne $session -or $process.Path -ine $Chrome) { continue }
1742
- $windows = @([OAuthBackground]::BrowserWindows($process.Id))
1743
- # Chrome kept running with every window closed: its UI thread is the one owning the hidden power window.
1744
- if ($windows.Count -eq 0) { $windows = @([OAuthBackground]::HiddenBrowserThreads($process.Id)) }
1745
- if ($windows.Count -eq 0) { continue }
1746
- $metadata = Get-CimInstance Win32_Process -Filter "ProcessId=$($process.Id)"
1747
- $command = [string]$metadata.CommandLine
1748
- if ($command -match '(?:^|\s)--type(?:=|\s)') { continue }
1749
- $actualRoot = Join-Path $env:LocalAppData 'Google\Chrome\User Data'
1750
- if ($command -match '--user-data-dir=(?:"([^"]+)"|([^\s]+))') { $actualRoot = $(if ($Matches[1]) { $Matches[1] } else { $Matches[2] }) }
1751
- if ([IO.Path]::GetFullPath($actualRoot).TrimEnd('\') -ine [IO.Path]::GetFullPath($UserDataDir).TrimEnd('\')) { continue }
1752
- foreach ($window in $windows) { $identities["$($window.Pid):$($window.Tid)"] = $window }
1753
- }
1754
- if ($identities.Count -ne 1) { return $null }
1755
- return @($identities.Values)[0]
1756
- }
1757
-
1758
- function Test-ChromeProfileRunning([string]$Chrome, [string]$UserDataDir) {
1759
- $session = (Get-Process -Id $PID).SessionId
1760
- foreach ($process in @(Get-Process -Name chrome -ErrorAction SilentlyContinue)) {
1761
- if ($process.SessionId -ne $session -or $process.Path -ine $Chrome) { continue }
1762
- $command = [string](Get-CimInstance Win32_Process -Filter "ProcessId=$($process.Id)").CommandLine
1763
- if ($command -match '(?:^|\s)--type(?:=|\s)') { continue }
1764
- $actualRoot = Join-Path $env:LocalAppData 'Google\Chrome\User Data'
1765
- if ($command -match '--user-data-dir=(?:"([^"]+)"|([^\s]+))') { $actualRoot = $(if ($Matches[1]) { $Matches[1] } else { $Matches[2] }) }
1766
- if ([IO.Path]::GetFullPath($actualRoot).TrimEnd('\') -ieq [IO.Path]::GetFullPath($UserDataDir).TrimEnd('\')) { return $true }
1767
- }
1768
- return $false
1769
- }
1770
-
1771
- # Chrome is not running for the person's profile: start it minimized without activation (its normal startup, restored
1772
- # tabs or a new tab, stays in that minimized window) and wait for the browser identity the guard binds to. Chrome
1773
- # started here does not compute native window occlusion, so the guarded window behind other windows keeps rendering;
1774
- # this lasts only until that Chrome exits. Never used while the profile is already open.
1775
- function Start-QuietChrome([string]$Chrome, [string]$UserDataDir, [string]$ProfileDirectory) {
1776
- # Two helpers starting at once must not both launch: a second launch is forwarded to the first Chrome as a normal,
1777
- # activated new window. The second helper waits here and then finds the browser running.
1778
- $gate = [Threading.Mutex]::new($false, 'Local\ZortexQuietChromeStart')
1779
- $owned = $false
1780
- try {
1781
- try { $owned = $gate.WaitOne(25000) } catch [Threading.AbandonedMutexException] { $owned = $true }
1782
- if (-not $owned) { return $null }
1783
- $identity = Get-GuardedChromeIdentity $Chrome $UserDataDir
1784
- if ($null -ne $identity) { return $identity }
1785
- return Start-QuietChromeOwned $Chrome $UserDataDir $ProfileDirectory
1786
- } finally { if ($owned) { $gate.ReleaseMutex() }; $gate.Dispose() }
1787
- }
1788
-
1789
- function Start-QuietChromeOwned([string]$Chrome, [string]$UserDataDir, [string]$ProfileDirectory) {
1790
- if (Test-ChromeProfileRunning $Chrome $UserDataDir) { return $null }
1791
- $command = "$(Quote-BrowserArgument $Chrome) --user-data-dir=$(Quote-BrowserArgument $UserDataDir) --profile-directory=$(Quote-BrowserArgument $ProfileDirectory) --disable-features=CalculateNativeWinOcclusion"
1792
- if ([OAuthBackground]::StartMinimizedNoActivate($Chrome, $command) -eq 0) { return $null }
1793
- $until = [DateTime]::UtcNow.AddSeconds(20)
1794
- while ([DateTime]::UtcNow -lt $until -and [DateTime]::UtcNow -lt $script:deadline) {
1795
- if (Test-Cancellation $script:cancellation) { Write-Result @{ state = 'failed'; reason = 'cancelled' } 1 }
1796
- $identity = Get-GuardedChromeIdentity $Chrome $UserDataDir
1797
- if ($null -ne $identity) { return $identity }
1798
- Start-Sleep -Milliseconds 250
1799
- }
1800
- return $null
1801
- }
1802
-
1803
- function Assert-BackgroundGuard {
1804
- if (-not $script:BackgroundGuardStarted) { return }
1805
- $stats = New-Object OAuthBackground+Stats
1806
- $readError = [OAuthBackground]::Read([ref]$stats)
1807
- if ([OAuthBackground]::KeepAliveError -ne 0 -or $readError -ne 0 -or
1808
- $stats.LeaseActive -ne 1 -or $stats.ControllerAlive -ne 1 -or $stats.Stopped -ne 0 -or
1809
- $stats.RootAmbiguous -ne 0 -or $stats.RendererAmbiguous -ne 0 -or $stats.Overflow -ne 0) {
1810
- throw "background_guard_unavailable readError=$readError heartbeat=$([OAuthBackground]::KeepAliveError) lease=$($stats.LeaseActive) stopped=$($stats.Stopped) rootAmbiguous=$($stats.RootAmbiguous) rendererAmbiguous=$($stats.RendererAmbiguous) overflow=$($stats.Overflow) rejectReason=$([OAuthBackground]::RendererRejectReason())"
1811
- }
1812
- if ($stats.Bound -ne 0 -and -not [OAuthBackground]::Valid([IntPtr]([long]$stats.Bound), $script:BackgroundIdentity.Pid, $script:BackgroundIdentity.Tid, $script:BackgroundNonce)) { throw 'background_window_changed' }
1813
- }
1814
-
1815
- function Assert-BackgroundAction {
1816
- Assert-BackgroundGuard
1817
- if (-not $script:BackgroundGuardStarted) { return }
1818
- if (Test-Cancellation $script:cancellation) { throw 'background_action_cancelled' }
1819
- if (-not [OAuthBackground]::CanAct()) { throw 'background_action_stopped' }
1820
- $stats = New-Object OAuthBackground+Stats
1821
- if ([OAuthBackground]::Read([ref]$stats) -ne 0 -or $stats.Renderer -eq 0 -or
1822
- $stats.Generation -ne $script:ActionGeneration) { throw 'background_action_renderer_changed' }
1823
- $id = $script:BackgroundIdentity
1824
- $snapshot = [OAuthBackground]::Snapshot($script:boundHandle, $id.Pid, $id.Tid, $script:BackgroundNonce)
1825
- if (-not [OAuthBackground]::SameSnapshot($snapshot, $script:boundTab, $script:ActionUrl)) {
1826
- throw "background_action_page_changed complete=$([int]$snapshot.Complete) tabs=$($snapshot.Tabs) durationMs=$($snapshot.DurationMs) sameTab=$([int]($snapshot.Tab -ceq $script:boundTab)) sameUrl=$([int]($snapshot.Url -ceq $script:ActionUrl))"
1827
- }
1828
- if (Test-Cancellation $script:cancellation) { throw 'background_action_cancelled' }
1829
- if (-not [OAuthBackground]::CanAct()) { throw 'background_action_stopped' }
1830
- if (-not [OAuthBackground]::RendererValid($script:boundHandle, $id.Pid, $id.Tid, $script:BackgroundNonce, $stats)) {
1831
- throw 'background_action_renderer_changed'
1832
- }
1833
- }
1834
-
1835
- function Test-BackgroundNavigationDrift([string]$Reason) {
1836
- # Only a discarded page epoch may be observed again. Guard, cancellation,
1837
- # nonce/ownership and provider failures must escape to terminal teardown.
1838
- return $Reason -cmatch '^background_action_(?:page|renderer)_changed(?: [a-zA-Z]+=-?[0-9]+)*$'
1839
- }
1840
-
1841
- function Start-GuardedOAuthBrowser([uri]$Authorization) {
1842
- $chrome = Get-ChromeLaunchPath
1843
- $userDataDir = Get-DefaultChromeUserDataDir
1844
- [OAuthBackground]::Load((Join-Path $PSScriptRoot 'windows-oauth-guard-x64.dll'))
1845
- $profileDirectory = Get-DefaultChromeProfileDirectory $userDataDir
1846
- if ($profileDirectory -cnotmatch '^(Default|Profile [0-9]+)$') { throw 'invalid_browser_profile' }
1847
- $identity = Get-GuardedChromeIdentity $chrome $userDataDir
1848
- if ($null -eq $identity) { $identity = Start-QuietChrome $chrome $userDataDir $profileDirectory }
1849
- if ($null -eq $identity -or -not [OAuthBackground]::X64($identity.Pid)) { Write-Result @{ state = 'browser_unsupported'; reason = 'background_browser_session_unavailable' } 1 }
1850
- $script:BackgroundIdentity = $identity
1851
- $script:BackgroundNonce = [Guid]::NewGuid().ToString('N')
1852
- $script:BackgroundMutex = [Threading.Mutex]::new($false, "Local\ZortexOAuthUI-$($identity.Pid)-$($identity.Tid)")
1853
- while (-not $script:BackgroundMutexOwned) {
1854
- if (Test-Cancellation $script:cancellation) { Write-Result @{ state = 'failed'; reason = 'cancelled' } 1 }
1855
- if ([DateTime]::UtcNow -ge $script:deadline) { Write-Result @{ state = 'ui_drift'; reason = 'background_browser_busy' } 1 }
1856
- try { $script:BackgroundMutexOwned = $script:BackgroundMutex.WaitOne(100) }
1857
- catch [Threading.AbandonedMutexException] { $script:BackgroundMutexOwned = $true }
1858
- }
1859
- $remaining = [int]($script:deadline - [DateTime]::UtcNow).TotalMilliseconds
1860
- if ($remaining -lt 1000) { throw 'background_browser_deadline' }
1861
- if ([OAuthBackground]::Start($identity.Tid, $identity.Pid, $script:BackgroundNonce) -ne 0) { throw 'background_guard_start_failed' }
1862
- $script:BackgroundGuardStarted = $true
1863
- [OAuthBackground]::BeginKeepAlive($remaining, $script:cancellation)
1864
- Assert-BackgroundGuard
1865
- Start-Process -FilePath $chrome -WindowStyle Hidden -ArgumentList @(
1866
- "--user-data-dir=$(Quote-BrowserArgument $userDataDir)",
1867
- "--profile-directory=$(Quote-BrowserArgument $profileDirectory)",
1868
- '--new-window', "--window-name=$script:BackgroundNonce", (Quote-BrowserArgument $Authorization.AbsoluteUri))
1869
- }
1870
-
1871
- # The person's own Chrome computes native occlusion: a guarded window fully covered by other windows (a maximized
1872
- # terminal, say) gets no rendered page however often it is revealed. After a reveal and 12 s without a page, the window
1873
- # is raised above the other windows without activation, once per transaction: visible, but the person's window keeps
1874
- # the keyboard. It stays raised until the window closes; later reveals restore it above, not behind. ZORTEX_BACKGROUND_RAISE=0 keeps it behind (the foreground
1875
- # route then finishes, taking the foreground).
1876
- function Test-BackgroundRaised {
1877
- # Read without the script prologue too (policy tests run these functions on their own).
1878
- return [bool](Get-Variable -Scope Script -Name BackgroundRaised -ValueOnly -ErrorAction SilentlyContinue)
1879
- }
1880
-
1881
- function Request-BackgroundRaise([IntPtr]$Handle, [DateTime]$Since) {
1882
- if ((Test-BackgroundRaised) -or $env:ZORTEX_BACKGROUND_RAISE -eq '0') { return $false }
1883
- # ZORTEX_BACKGROUND_RAISE_AFTER_MS shortens the wait so a tester can exercise the raise on a screen that renders anyway.
1884
- $after = 0
1885
- if (-not [int]::TryParse([string]$env:ZORTEX_BACKGROUND_RAISE_AFTER_MS, [ref]$after) -or $after -lt 0) { $after = 12000 }
1886
- if (([DateTime]::UtcNow - $Since).TotalMilliseconds -lt $after) { return $false }
1887
- $identity = $script:BackgroundIdentity
1888
- if (-not [OAuthBackground]::RaiseWithoutActivation($Handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce)) { return $false }
1889
- $script:BackgroundRaised = $true
1890
- # The page renders from now on: its unresolved-renderer deadline starts again.
1891
- $script:RendererMissingSince = [DateTime]::UtcNow
1892
- $script:RendererUnresolvedSince = $null
1893
- if ($env:ZORTEX_PAGE_SESSION_DIAG -eq '1' -and (Test-Path variable:script:SessionDiag) -and $script:SessionDiag -is [hashtable]) { $script:SessionDiag['raised'] = 1 }
1894
- return $true
1895
- }
1896
-
1897
- function Request-BackgroundPage([IntPtr]$Handle, [string]$Tab, [uri]$Url, [DateTime]$Since,
1898
- [ValidateSet('page', 'advanced', 'notion-picker', 'notion-private', 'renderer')][string]$RefreshPhase = 'page') {
1899
- if (-not $script:BackgroundGuardStarted) { return 'waiting' }
1900
- Assert-BackgroundGuard
1901
- if (Request-BackgroundRaise $Handle $Since) { return 'revealed' }
1902
- if ($script:RevealCount -ge 8) { return 'waiting' }
1903
- Assert-BackgroundGuard
1904
- $address = $Url.AbsoluteUri
1905
- $key = "$address|$RefreshPhase"
1906
- if ($script:RevealPages.Contains($key)) { return 'already_attempted' }
1907
- # A new URL gets its own settling interval. The previous page's timer must
1908
- # not spend this page's one refresh while Chrome is still loading it.
1909
- if (-not $script:BackgroundPageFirstSeen.ContainsKey($key)) { $script:BackgroundPageFirstSeen[$key] = [DateTime]::UtcNow }
1910
- $identity = $script:BackgroundIdentity
1911
- $snapshot = [OAuthBackground]::Snapshot($Handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce)
1912
- if (-not [OAuthBackground]::SameSnapshot($snapshot, $Tab, $address)) { return 'waiting' }
1913
- if (-not (Test-BackgroundPageReady (([DateTime]::UtcNow - $script:BackgroundPageFirstSeen[$key]).TotalMilliseconds) $snapshot.LoadingObserved $snapshot.Loading)) { return 'waiting' }
1914
- if (-not [OAuthBackground]::RequestAccessibility($Handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce) -and
1915
- -not [OAuthBackground]::RendererPending($Handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce)) { return 'waiting_renderer' }
1916
- $script:RevealPages.Add($key) | Out-Null
1917
- $script:RevealCount++
1918
- return [OAuthBackground]::Reveal($Handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce, $Tab, $Url.AbsoluteUri)
1919
- }
1920
-
1921
- # Chrome 155.0.8059.41 can keep several hidden views of one page under the guarded window (a second, never-shown
1922
- # view, or a new page's view next to a speculative one). The guard then publishes no renderer until one retires or
1923
- # Chrome shows one. Showing our window once (minimize/restore, never activated) makes Chrome show the current
1924
- # page's view: up to three times per address, 8 s apart, each only after the renderer has been missing for 3.5 s
1925
- # without a break (Chrome replaces a page's view within ~50 ms, which must never cause a visible minimize/restore).
1926
- # A renderer still unresolved after 45 s ends the background route with a background_* reason, so a caller can
1927
- # finish in a visible window.
1928
- function Update-BackgroundRendererWait([uri]$Url, [bool]$Readable, [DateTime]$Now) {
1929
- if ($Readable) { $script:RendererUnresolvedSince = $null; $script:RendererUnresolvedUrl = ''; return }
1930
- if ($null -eq $Url) { return }
1931
- $address = $Url.AbsoluteUri
1932
- if ($null -eq $script:RendererUnresolvedSince -or $script:RendererUnresolvedUrl -cne $address) {
1933
- $script:RendererUnresolvedSince = $Now
1934
- $script:RendererUnresolvedUrl = $address
1935
- }
1936
- # A reveal can publish a renderer for milliseconds without exposing a usable document. Only an actual
1937
- # readable page or a different address resets this deadline, not the native handle's oscillation.
1938
- if (($Now - $script:RendererUnresolvedSince).TotalMilliseconds -ge 45000) { throw 'background_renderer_unresolved' }
1939
- }
1940
-
1941
- function Resolve-BackgroundRenderer([IntPtr]$Handle, [string]$Tab, [uri]$Url) {
1942
- $now = [DateTime]::UtcNow
1943
- Update-BackgroundRendererWait $Url $false $now
1944
- if ($null -eq $script:RendererMissingSince) { $script:RendererMissingSince = $now }
1945
- if (($now - $script:RendererMissingSince).TotalMilliseconds -ge 45000) { throw 'background_renderer_unresolved' }
1946
- if ([string]::IsNullOrWhiteSpace($Tab) -or $null -eq $Url) { return }
1947
- $address = $Url.AbsoluteUri
1948
- $key = "$address|renderer"
1949
- $tries = [int]$script:RendererReveals[$address]
1950
- # The settling interval is this gap's, not the address's first gap.
1951
- $script:BackgroundPageFirstSeen[$key] = $script:RendererMissingSince
1952
- if ($script:RevealPages.Contains($key) -and $tries -lt 3 -and $null -ne $script:RendererRevealedAt -and
1953
- ($now - $script:RendererRevealedAt).TotalMilliseconds -ge 8000) { $script:RevealPages.Remove($key) | Out-Null }
1954
- $reveal = Request-BackgroundPage $Handle $Tab $Url $script:RendererMissingSince 'renderer'
1955
- if ($reveal -eq 'revealed') { $script:RendererRevealedAt = [DateTime]::UtcNow; $script:RendererReveals[$address] = $tries + 1 }
1956
- }
1957
-
1958
- function Test-BackgroundPageReady([double]$ElapsedMs, [bool]$LoadingObserved, [bool]$Loading) {
1959
- return $ElapsedMs -ge 3500 -and (-not $LoadingObserved -or -not $Loading)
1960
- }
1961
-
1962
- function Register-OwnedBrowser([IntPtr]$Handle, [bool]$OwnsWindow) {
1963
- if (-not $OwnsWindow) { return }
1964
- # Keep OAuth windows visible while acting. Chrome can expose UIA elements on a
1965
- # transparent layered window while ignoring synthetic account-row clicks. We
1966
- # still remember owned windows and close them on completion.
1967
- $script:OwnedBrowserHandle = $Handle
1968
- if ([ZortexNativeWindow]::IsForeground($Handle)) { $script:ForegroundObserved = $true }
1969
- }
1970
- function New-BrowserTabCondition {
1971
- # Only the tab strip's tabs (class "Tab"). Chrome's translate bar adds TabItems of class "TabbedPaneTab"
1972
- # (e.g. two language choices) whenever the page language differs from the browser's; they are not tabs.
1973
- return New-Object Windows.Automation.AndCondition(
1974
- (New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ControlTypeProperty, [Windows.Automation.ControlType]::TabItem)),
1975
- (New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ClassNameProperty, 'Tab')))
1976
- }
1977
-
1978
- function Close-OwnedBrowser([string]$State) {
1979
- if ($script:OwnedBrowserHandle -ne [IntPtr]::Zero) {
1980
- try {
1981
- if ($script:BackgroundGuardStarted) {
1982
- $id = $script:BackgroundIdentity
1983
- $script:CleanupDiagnostic = @{ attempts = 0; snapshotComplete = 0; snapshotMs = 0; tabs = 0;
1984
- tabMatches = 0; policyAccepted = 0; closePosted = 0; windowRemaining = 1; error = 0; urlClass = 'missing' }
1985
- $cleanupClock = [Diagnostics.Stopwatch]::StartNew()
1986
- # Cancellation can arrive while Chrome commits the localhost navigation.
1987
- # Re-observe within a short budget; every attempt keeps the same policy
1988
- # and takes another fresh snapshot before posting the owned-window close.
1989
- while ($script:CleanupDiagnostic.attempts -lt 4 -and $cleanupClock.ElapsedMilliseconds -lt 1000) {
1990
- $script:CleanupDiagnostic.attempts++
1991
- try {
1992
- if (-not [OAuthBackground]::IsWindow($script:OwnedBrowserHandle)) { break }
1993
- $snapshot = [OAuthBackground]::Snapshot($script:OwnedBrowserHandle, $id.Pid, $id.Tid, $script:BackgroundNonce)
1994
- $script:CleanupDiagnostic.snapshotComplete = [int]$snapshot.Complete
1995
- $script:CleanupDiagnostic.snapshotMs = $snapshot.DurationMs
1996
- $script:CleanupDiagnostic.tabs = $snapshot.Tabs
1997
- $tab = $script:boundTab
1998
- if ([string]::IsNullOrWhiteSpace($tab)) { $tab = $snapshot.Tab }
1999
- $script:CleanupDiagnostic.tabMatches = [int](-not [string]::IsNullOrWhiteSpace($tab) -and $snapshot.Tab -ceq $tab)
2000
- if ($snapshot.Complete) {
2001
- $url = [uri]$snapshot.Url
2002
- $callback = Test-OwnedBrowserCloseCandidate $snapshot.Tabs $snapshot.Tab $tab $url $script:redirect
2003
- $discovery = $State -eq 'accounts' -and (Test-OwnedDiscoveryCloseCandidate $snapshot.Tabs $snapshot.Tab $tab $url)
2004
- $transaction = Test-OwnedAutomaticCloseCandidate $snapshot.Tabs $snapshot.Tab $tab $url
2005
- $transition = Test-OwnedGoogleTransitionClose $snapshot.Tabs $snapshot.Tab $script:boundTab $url
2006
- $siteRead = Test-OwnedSiteCloseCandidate $snapshot.Tabs $snapshot.Tab $script:boundTab $url
2007
- $script:CleanupDiagnostic.urlClass = $(if ($callback) { 'callback' } elseif ($discovery) { 'discovery' } elseif ($transaction) { 'transaction' } elseif ($transition) { 'transition' } elseif ($siteRead) { 'site' } else { 'other' })
2008
- $script:CleanupDiagnostic.policyAccepted = [int]($callback -or $discovery -or $transaction -or $transition -or $siteRead)
2009
- if ($script:CleanupDiagnostic.policyAccepted -eq 1 -and
2010
- [OAuthBackground]::CloseVerified($script:OwnedBrowserHandle, $id.Pid, $id.Tid, $script:BackgroundNonce, $tab, $url.AbsoluteUri)) {
2011
- $script:CleanupDiagnostic.closePosted = 1
2012
- $closeUntil = [DateTime]::UtcNow.AddMilliseconds(400)
2013
- while ([OAuthBackground]::IsWindow($script:OwnedBrowserHandle) -and [DateTime]::UtcNow -lt $closeUntil) { Start-Sleep -Milliseconds 20 }
2014
- break
2015
- }
2016
- }
2017
- } catch { $script:CleanupDiagnostic.error = [int]$_.Exception.GetBaseException().HResult }
2018
- Start-Sleep -Milliseconds 50
2019
- }
2020
- # A site read and a page session have no transaction URL to verify, and a run can end on a page no close rule
2021
- # names (the account chooser, a stuck consent page). This function runs only when nobody is left to use the
2022
- # window (Test-ShouldCloseBrowser), and it is still provably ours by the native nonce root, so close it even
2023
- # when no rule matched or Chrome never reported a complete page snapshot. Otherwise it stays on screen.
2024
- if ($script:CleanupDiagnostic.closePosted -eq 0 -and
2025
- [OAuthBackground]::IsWindow($script:OwnedBrowserHandle) -and
2026
- [OAuthBackground]::RootValid($script:OwnedBrowserHandle, $id.Pid, $id.Tid, $script:BackgroundNonce)) {
2027
- [ZortexNativeWindow]::Close($script:OwnedBrowserHandle) | Out-Null
2028
- $script:CleanupDiagnostic.closePosted = 2
2029
- $closeUntil = [DateTime]::UtcNow.AddMilliseconds(600)
2030
- while ([OAuthBackground]::IsWindow($script:OwnedBrowserHandle) -and [DateTime]::UtcNow -lt $closeUntil) { Start-Sleep -Milliseconds 20 }
2031
- }
2032
- $script:CleanupDiagnostic.windowRemaining = [int][OAuthBackground]::IsWindow($script:OwnedBrowserHandle)
2033
- return
2034
- }
2035
- $window = [Windows.Automation.AutomationElement]::FromHandle($script:OwnedBrowserHandle)
2036
- $tabCondition = New-BrowserTabCondition
2037
- $tabCount = $window.FindAll([Windows.Automation.TreeScope]::Descendants, $tabCondition).Count
2038
- $currentTab = Get-SelectedTabIdentity $window
2039
- $page = Get-Page $window
2040
- if ($null -ne $page -and ((Test-OwnedBrowserCloseCandidate $tabCount $currentTab $script:boundTab $page.url $script:redirect) -or
2041
- ($State -eq 'accounts' -and (Test-OwnedDiscoveryCloseCandidate $tabCount $currentTab $script:boundTab $page.url)) -or
2042
- (Test-OwnedAutomaticCloseCandidate $tabCount $currentTab $script:boundTab $page.url))) {
2043
- [ZortexNativeWindow]::Close($script:OwnedBrowserHandle) | Out-Null
2044
- }
2045
- } catch {}
2046
- $script:OwnedBrowserHandle = [IntPtr]::Zero
2047
- }
2048
- }
2049
-
2050
- function Get-ChromiumRenderRoot($Window) {
2051
- $script:RenderLookupDiagnostic = @{ window = -1; renderer = -1; offscreen = -1; stage = 0; error = 0; allWidgets = -1; visibleWidgets = -1 }
2052
- try { $script:RenderLookupDiagnostic.offscreen = [int][bool]$Window.Current.IsOffscreen } catch {}
2053
- try {
2054
- $script:RenderLookupDiagnostic.stage = 1
2055
- $handle = [IntPtr]$Window.Current.NativeWindowHandle
2056
- $script:RenderLookupDiagnostic.window = [int]($handle -ne [IntPtr]::Zero)
2057
- $script:RenderLookupDiagnostic.stage = 2
2058
- if ($script:BackgroundGuardStarted) {
2059
- Assert-BackgroundGuard
2060
- $native = New-Object OAuthBackground+Stats
2061
- $identity = $script:BackgroundIdentity
2062
- if ([OAuthBackground]::Read([ref]$native) -ne 0 -or $native.Renderer -eq 0 -or
2063
- $native.Generation -ne $script:ReadGeneration -or
2064
- -not [OAuthBackground]::RendererValid($handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce, $native)) { return $null }
2065
- # Chromium can detach its fully occluded renderer from the visible root.
2066
- # The guard retains only the exact previously proven renderer for this
2067
- # transaction; never enumerate hidden browser windows to replace it.
2068
- $render = [IntPtr]([long]$native.Renderer)
2069
- } else { $render = [ChromiumMsaa]::ActiveRenderWindow($handle) }
2070
- $script:RenderLookupDiagnostic.allWidgets = [ChromiumMsaa]::RenderWindowCount($handle, $false)
2071
- $script:RenderLookupDiagnostic.visibleWidgets = [ChromiumMsaa]::RenderWindowCount($handle, $true)
2072
- $script:RenderLookupDiagnostic.renderer = [int]($render -ne [IntPtr]::Zero)
2073
- if ($render -eq [IntPtr]::Zero) { return $null }
2074
- $script:RenderLookupDiagnostic.stage = 3
2075
- if ($script:BackgroundGuardStarted) {
2076
- [OAuthBackground]::RequestAccessibility($handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce) | Out-Null
2077
- } else { [ChromiumAccessibility]::Enable($handle) }
2078
- $script:RenderLookupDiagnostic.stage = 4
2079
- $root = [Windows.Automation.AutomationElement]::FromHandle($render)
2080
- if ($script:BackgroundGuardStarted -and
2081
- -not [OAuthBackground]::RendererValid($handle, $identity.Pid, $identity.Tid, $script:BackgroundNonce, $native)) { return $null }
2082
- $script:RenderLookupDiagnostic.stage = 5
2083
- return $root
2084
- } catch {
2085
- $script:RenderLookupDiagnostic.error = [int]$_.Exception.GetBaseException().HResult
2086
- throw
2087
- }
2088
- }
2089
-
2090
- function Get-Page($Window) {
2091
- $all = $Window.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition)
2092
- $url = $null
2093
- foreach ($element in $all) {
2094
- try {
2095
- if ($element.Current.ControlType -ne [Windows.Automation.ControlType]::Edit) { continue }
2096
- $pattern = Get-Pattern $element ([Windows.Automation.ValuePattern]::Pattern)
2097
- if ($null -eq $pattern) { continue }
2098
- $parsed = ConvertTo-BrowserUri $pattern.Current.Value
2099
- if ($null -ne $parsed) {
2100
- $url = $parsed
2101
- break
2102
- }
2103
- } catch {}
2104
- }
2105
- if ($null -eq $url) { return $null }
2106
- if (Get-Variable BackgroundGuardStarted -Scope Script -ValueOnly -ErrorAction SilentlyContinue) {
2107
- Assert-BackgroundGuard
2108
- $stats = New-Object OAuthBackground+Stats
2109
- if ([OAuthBackground]::Read([ref]$stats) -ne 0 -or $stats.Renderer -eq 0 -or
2110
- $stats.Generation -ne $script:ReadGeneration -or $url.AbsoluteUri -cne $script:ReadUrl) { return $null }
2111
- $id = $script:BackgroundIdentity
2112
- $freshChrome = [OAuthBackground]::Snapshot([IntPtr]$Window.Current.NativeWindowHandle, $id.Pid, $id.Tid, $script:BackgroundNonce)
2113
- if (-not [OAuthBackground]::SameSnapshot($freshChrome, $script:ReadTab, $url.AbsoluteUri)) { return $null }
2114
- }
2115
- $documentCondition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ControlTypeProperty, [Windows.Automation.ControlType]::Document)
2116
- try { $documents = $Window.FindAll([Windows.Automation.TreeScope]::Descendants, $documentCondition) }
2117
- catch { $documents = @() }
2118
- $topDocumentCount = $documents.Count
2119
- $renderDocumentCount = 0
2120
- foreach ($document in $documents) {
2121
- try {
2122
- if (-not $document.Current.IsOffscreen) {
2123
- $content = $document.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition)
2124
- if (Test-DocumentContentAvailable $false $content.Count) { return @{ url = $url; documents = $documents.Count; elements = $content; document = $document } }
2125
- }
2126
- } catch {}
2127
- }
2128
- # No usable top-level document: a stale/offscreen fragment must not suppress
2129
- # the selected renderer lookup. Neither candidate may expose offscreen content.
2130
- $documents = @()
2131
- $renderRoot = $null
2132
- $script:RenderLookupDiagnostic = @{ window = -1; renderer = -1; offscreen = -1; stage = 0; error = 0; allWidgets = -1; visibleWidgets = -1 }
2133
- try {
2134
- # Chromium's renderer fragment need not be attached to the top-level UIA tree.
2135
- # Query the selected visible render widget directly, without activating it.
2136
- $renderRoot = Get-ChromiumRenderRoot $Window
2137
- if ($null -ne $renderRoot) {
2138
- if ($renderRoot.Current.ControlType -eq [Windows.Automation.ControlType]::Document) { $documents = @($renderRoot) }
2139
- else { $documents = $renderRoot.FindAll([Windows.Automation.TreeScope]::Descendants, $documentCondition) }
2140
- }
2141
- } catch { $documents = @() }
2142
- $renderDocumentCount = $documents.Count
2143
- foreach ($document in $documents) {
2144
- try {
2145
- if (-not $document.Current.IsOffscreen) {
2146
- $content = $document.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition)
2147
- if (Test-DocumentContentAvailable $false $content.Count) { return @{ url = $url; documents = $documents.Count; elements = $content; document = $document } }
2148
- }
2149
- } catch {}
2150
- }
2151
- # Counts only: distinguish a missing renderer from an inaccessible document.
2152
- # Never return names, text or these diagnostic descendants as actionable content.
2153
- $renderExists = [int]($null -ne $renderRoot)
2154
- $renderOffscreen = -1
2155
- $renderElements = -1
2156
- if ($null -ne $renderRoot) {
2157
- try { $renderOffscreen = [int][bool]$renderRoot.Current.IsOffscreen } catch {}
2158
- try { $renderElements = $renderRoot.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition).Count } catch {}
2159
- }
2160
- return @{ url = $url; documents = 0; elements = @(); topDocuments = $topDocumentCount; renderDocuments = $renderDocumentCount; renderExists = $renderExists; renderOffscreen = $renderOffscreen; renderElements = $renderElements; lookup = $script:RenderLookupDiagnostic }
2161
- }
2162
-
2163
- function Request-ChromiumPageAccessibility([IntPtr]$Handle) {
2164
- if ($script:BackgroundGuardStarted) {
2165
- Assert-BackgroundGuard
2166
- $id = $script:BackgroundIdentity
2167
- [OAuthBackground]::RequestAccessibility($Handle, $id.Pid, $id.Tid, $script:BackgroundNonce) | Out-Null
2168
- return
2169
- }
2170
- # A UIA query on the render widget asks Chrome to build the page's accessibility tree again.
2171
- $render = [ChromiumMsaa]::ActiveRenderWindow($Handle)
2172
- if ($render -ne [IntPtr]::Zero) {
2173
- try { $null = [Windows.Automation.AutomationElement]::FromHandle($render).FindFirst([Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition) } catch {}
2174
- }
2175
- [ChromiumAccessibility]::Enable($Handle)
2176
- }
2177
-
2178
- function Invoke-Control($Element) {
2179
- if (Get-Variable BackgroundGuardStarted -Scope Script -ValueOnly -ErrorAction SilentlyContinue) { Assert-BackgroundAction }
2180
- try {
2181
- $scroll = Get-Pattern $Element ([Windows.Automation.ScrollItemPattern]::Pattern)
2182
- if ($null -ne $scroll) { Assert-BackgroundAction; $scroll.ScrollIntoView(); Start-Sleep -Milliseconds 50 }
2183
- } catch { if (Test-BackgroundGuardException $_) { throw } }
2184
- try {
2185
- $invoke = Get-Pattern $Element ([Windows.Automation.InvokePattern]::Pattern)
2186
- if ($null -ne $invoke) { Assert-BackgroundAction; $invoke.Invoke(); return $true }
2187
- } catch { if (Test-BackgroundGuardException $_) { throw } }
2188
- try {
2189
- $select = Get-Pattern $Element ([Windows.Automation.SelectionItemPattern]::Pattern)
2190
- if ($null -ne $select) { Assert-BackgroundAction; $select.Select(); return $true }
2191
- } catch { if (Test-BackgroundGuardException $_) { throw } }
2192
- try {
2193
- $toggle = Get-Pattern $Element ([Windows.Automation.TogglePattern]::Pattern)
2194
- if ($null -ne $toggle -and $toggle.Current.ToggleState -eq [Windows.Automation.ToggleState]::Off) { Assert-BackgroundAction; $toggle.Toggle(); return $true }
2195
- } catch { if (Test-BackgroundGuardException $_) { throw } }
2196
- try {
2197
- $expand = Get-Pattern $Element ([Windows.Automation.ExpandCollapsePattern]::Pattern)
2198
- if ($null -ne $expand -and $expand.Current.ExpandCollapseState -eq [Windows.Automation.ExpandCollapseState]::Collapsed) { Assert-BackgroundAction; $expand.Expand(); return $true }
2199
- } catch { if (Test-BackgroundGuardException $_) { throw } }
2200
- try {
2201
- $legacy = Get-LegacyPattern $Element
2202
- if ($null -ne $legacy) { Assert-BackgroundAction; $legacy.DoDefaultAction(); return $true }
2203
- } catch { if (Test-BackgroundGuardException $_) { throw } }
2204
- return $false
2205
- }
2206
-
2207
- function Test-OAuthForeground {
2208
- return [ZortexNativeWindow]::IsForeground($script:boundHandle)
2209
- }
2210
-
2211
- function Invoke-ControlOrAncestor($Element) {
2212
- $current = $Element
2213
- for ($i = 0; $i -lt 5 -and $null -ne $current; $i++) {
2214
- if (Invoke-Control $current) { return $true }
2215
- try { $current = [Windows.Automation.TreeWalker]::ControlViewWalker.GetParent($current) } catch { $current = $null }
2216
- }
2217
- return $false
2218
- }
2219
-
2220
- function Invoke-GoogleAccountCandidate($Named) {
2221
- $candidates = @()
2222
- foreach ($candidate in $Named) {
2223
- if (-not (Test-GoogleAccountCandidate ([string]$candidate.name))) { continue }
2224
- try {
2225
- $rect = $candidate.element.Current.BoundingRectangle
2226
- if ($rect.IsEmpty -or $rect.Width -le 0 -or $rect.Height -le 0) { continue }
2227
- $candidates += @{ element = $candidate.element; name = $candidate.name; top = $rect.Top; left = $rect.Left }
2228
- } catch {}
2229
- }
2230
- $candidates = @($candidates | Sort-Object top, left)
2231
- foreach ($candidate in $candidates) {
2232
- if (Invoke-ControlOrAncestor $candidate.element) { return $true }
2233
- return $false
2234
- }
2235
- return $false
2236
- }
2237
-
2238
- function Invoke-GoogleScopeControls($Elements, [bool]$Single = $false) {
2239
- $changed = 0
2240
- $scopeRows = @()
2241
- foreach ($element in $Elements) {
2242
- try {
2243
- $texts = @([string]$element.Current.Name, [string]$element.Current.HelpText)
2244
- $value = Get-Pattern $element ([Windows.Automation.ValuePattern]::Pattern)
2245
- if ($null -ne $value) { $texts += [string]$value.Current.Value }
2246
- $legacy = Get-LegacyPattern $element
2247
- if ($null -ne $legacy) { $texts += @([string]$legacy.Current.Name, [string]$legacy.Current.Value) }
2248
- if ($texts.Where({ Test-GoogleScopeRowText $_ }).Count -eq 0) { continue }
2249
- $rect = $element.Current.BoundingRectangle
2250
- if ($rect.IsEmpty -or $rect.Width -le 0 -or $rect.Height -le 0) { continue }
2251
- $scopeRows += $rect
2252
- } catch {}
2253
- }
2254
- foreach ($element in $Elements) {
2255
- try {
2256
- if ($element.Current.ControlType -ne [Windows.Automation.ControlType]::CheckBox) { continue }
2257
- $name = "$($element.Current.Name) $($element.Current.HelpText)"
2258
- $toggle = Get-Pattern $element ([Windows.Automation.TogglePattern]::Pattern)
2259
- if ($null -eq $toggle -or $toggle.Current.ToggleState -ne [Windows.Automation.ToggleState]::Off) { continue }
2260
- $matchesScope = Test-GoogleScopeControl $name
2261
- if (-not $matchesScope) {
2262
- $rect = $element.Current.BoundingRectangle
2263
- $matchesScope = -not $rect.IsEmpty -and $scopeRows.Where({ Test-SameRow $rect $_ }).Count -gt 0
2264
- }
2265
- if (-not $matchesScope) { continue }
2266
- if (Get-Variable BackgroundGuardStarted -Scope Script -ValueOnly -ErrorAction SilentlyContinue) { Assert-BackgroundAction }
2267
- $toggle.Toggle()
2268
- $changed += 1
2269
- if ($Single) { break }
2270
- } catch { if (Test-BackgroundGuardException $_) { throw } }
2271
- }
2272
- return $changed
2273
- }
2274
-
2275
- function Get-SelectedTabIdentity($Window) {
2276
- $condition = New-BrowserTabCondition
2277
- foreach ($tab in $Window.FindAll([Windows.Automation.TreeScope]::Descendants, $condition)) {
2278
- try {
2279
- $selection = Get-Pattern $tab ([Windows.Automation.SelectionItemPattern]::Pattern)
2280
- if ($null -ne $selection -and $selection.Current.IsSelected) { return (($tab.GetRuntimeId()) -join '.') }
2281
- } catch {}
2282
- }
2283
- return $null
2284
- }
2285
-
2286
- function Get-NamedPageControls($Elements) {
2287
- $named = @()
2288
- foreach ($element in $Elements) {
2289
- try {
2290
- $value = [string]$element.Current.Name
2291
- if (-not [string]::IsNullOrWhiteSpace($value)) {
2292
- $rect = $element.Current.BoundingRectangle
2293
- $visible = -not $element.Current.IsOffscreen -and -not $rect.IsEmpty -and $rect.Width -gt 0 -and $rect.Height -gt 0
2294
- $named += @{ element = $element; name = $value; kind = 'current_name'; controlType = [string]$element.Current.ControlType.ProgrammaticName; visible = $visible }
2295
- }
2296
- } catch {}
2297
- try { $value = [string]$element.Current.HelpText; if (-not [string]::IsNullOrWhiteSpace($value)) { $named += @{ element = $element; name = $value } } } catch {}
2298
- try { $pattern = Get-Pattern $element ([Windows.Automation.ValuePattern]::Pattern); if ($null -ne $pattern -and -not [string]::IsNullOrWhiteSpace([string]$pattern.Current.Value)) { $named += @{ element = $element; name = [string]$pattern.Current.Value } } } catch {}
2299
- try { $legacy = Get-LegacyPattern $element; if ($null -ne $legacy -and -not [string]::IsNullOrWhiteSpace([string]$legacy.Current.Name)) { $named += @{ element = $element; name = [string]$legacy.Current.Name } } } catch {}
2300
- try { if ($null -ne $legacy -and -not [string]::IsNullOrWhiteSpace([string]$legacy.Current.Value)) { $named += @{ element = $element; name = [string]$legacy.Current.Value } } } catch {}
2301
- }
2302
- return $named
2303
- }
2304
-
2305
- # Read-only diagnostic (ZORTEX_OAUTH_OBSERVE=1): record what a provider's real login /
2306
- # consent / chooser pages expose, so per-provider matchers are written from observed
2307
- # structure, never guessed. Account addresses and any token-shaped text are redacted;
2308
- # this never invokes a control.
2309
- function Format-ObserveName([string]$Name) {
2310
- $n = $Name -replace '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', 'U***@***'
2311
- $n = $n -replace '[A-Za-z0-9_\-]{40,}', '<redacted>'
2312
- $n = ($n -replace '\s+', ' ').Trim()
2313
- if ($n.Length -gt 140) { $n = $n.Substring(0, 140) + [char]0x2026 }
2314
- return $n
2315
- }
2316
- function Add-ObserveSnapshot([string]$Log, [string]$Provider, [uri]$Url, $Named) {
2317
- if ([string]::IsNullOrEmpty($Log)) { return }
2318
- $lines = @("=== $Provider $($Url.Host)$($Url.AbsolutePath) ===")
2319
- foreach ($c in $Named) {
2320
- $ct = if ($c.ContainsKey('controlType')) { [string]$c['controlType'] } else { 'Text' }
2321
- $vis = if ($c.ContainsKey('visible')) { if ($c['visible']) { 'vis' } else { 'off' } } else { '?' }
2322
- $nm = if ($c.ContainsKey('name')) { [string]$c['name'] } else { '' }
2323
- $lines += (" [{0}|{1}] {2}" -f ($ct -replace '^ControlType\.', ''), $vis, (Format-ObserveName $nm))
2324
- }
2325
- try { Add-Content -Path $Log -Value $lines -Encoding UTF8 } catch {}
2326
- }
2327
-
2328
- function Get-FreshJevPage([IntPtr]$Handle, [string]$Tab, [uri]$ExpectedUrl, [string]$Provider, [uri]$Redirect, [string]$ClientId, [string]$State) {
2329
- # The decision endpoint can take 30 seconds. Nothing from the pre-decision UIA
2330
- # tree may be used to click after it returns: the tab, URL, and controls can
2331
- # all have changed while Jev was deciding.
2332
- if ($env:ZORTEX_JEV_UIA_MODE -ne '1') { return $null }
2333
- $windows = @(Get-BrowserWindows | Where-Object { $_.handle -eq $Handle })
2334
- if ($windows.Count -ne 1) { Write-Result @{ state = 'ui_drift'; reason = 'jev_window_changed' } 1 }
2335
- $freshWindow = $windows[0]
2336
- $freshTab = Get-SelectedTabIdentity $freshWindow.element
2337
- if ([string]::IsNullOrWhiteSpace($freshTab) -or $freshTab -cne $Tab) {
2338
- Write-Result @{ state = 'ui_drift'; reason = 'jev_tab_changed' } 1
2339
- }
2340
- try { $freshPage = Get-Page $freshWindow.element } catch { $freshPage = $null }
2341
- if ($null -eq $freshPage -or $freshPage.url.AbsoluteUri -cne $ExpectedUrl.AbsoluteUri -or
2342
- -not (Test-AllowedOrigin $Provider $freshPage.url $Redirect) -or
2343
- (Test-CallbackAddress $freshPage.url $Redirect)) {
2344
- $expectedKind = $(if ($ExpectedUrl.AbsolutePath -match 'consent') { 'consent' } elseif ($ExpectedUrl.AbsolutePath -match 'accountchooser') { 'chooser' } else { 'other' })
2345
- $currentKind = $(if ($null -eq $freshPage) { 'none' } elseif (Test-CallbackAddress $freshPage.url $Redirect) { 'callback' } elseif ($freshPage.url.AbsolutePath -match 'consent') { 'consent' } elseif ($freshPage.url.AbsolutePath -match 'accountchooser') { 'chooser' } else { 'other' })
2346
- $sameHost = $null -ne $freshPage -and $freshPage.url.Host -ceq $ExpectedUrl.Host
2347
- Write-Result @{ state = 'ui_drift'; reason = "jev_page_changed phase=$script:LastJevPhase expected=$expectedKind current=$currentKind sameHost=$sameHost" } 1
2348
- }
2349
- $query = [Web.HttpUtility]::ParseQueryString($freshPage.url.Query)
2350
- if ((-not [string]::IsNullOrWhiteSpace($query.Get('client_id')) -and $query.Get('client_id') -cne $ClientId) -or
2351
- (-not [string]::IsNullOrWhiteSpace($query.Get('state')) -and $query.Get('state') -cne $State)) {
2352
- Write-Result @{ state = 'ui_drift'; reason = 'jev_transaction_changed' } 1
2353
- }
2354
- return @{ window = $freshWindow; page = $freshPage; named = @(Get-NamedPageControls $freshPage.elements) }
2355
- }
2356
-
2357
- # ---- Signed-in site read (X, Instagram, LinkedIn) ---------------------------------------------
2358
- # Opens one allowlisted page in the user's default Chrome profile inside the same guarded background
2359
- # window used for OAuth, reads article and link accessibility names, and closes only that window.
2360
- # It never types or reads cookies, and clicks nothing except a modal prompt's "Not now"; the page text goes
2361
- # to the caller over stdout only.
2362
- $script:SiteName = ''
2363
- function Test-SiteHost([string]$Site, [uri]$Uri) {
2364
- if ($null -eq $Uri -or $Uri.Scheme -cne 'https' -or $Uri.UserInfo) { return $false }
2365
- switch ($Site) {
2366
- 'x' { return $Uri.Host -in @('x.com', 'twitter.com', 'mobile.x.com') }
2367
- # Chrome's address bar elides "www.", so the bare host is the same site.
2368
- 'instagram' { return $Uri.Host -in @('www.instagram.com', 'instagram.com') }
2369
- 'linkedin' { return $Uri.Host -in @('www.linkedin.com', 'linkedin.com') }
2370
- 'steam' { return $Uri.Host -ceq 'steamcommunity.com' }
2371
- 'netease-mail' { return $Uri.Host -in @('mail.163.com', 'mail.126.com') }
2372
- 'reddit' { return $Uri.Host -in @('www.reddit.com', 'reddit.com') }
2373
- 'spotify' { return $Uri.Host -ceq 'open.spotify.com' }
2374
- 'notebooklm' { return $Uri.Host -in @('notebooklm.google.com', 'notebook.google.com') }
2375
- 'whatsapp' { return $Uri.Host -ceq 'web.whatsapp.com' }
2376
- }
2377
- return $false
2378
- }
2379
- # A signed-out visitor is redirected to a separate sign-in host; that page is never read or operated.
2380
- function Test-SiteLoginHost([string]$Site, [uri]$Uri) {
2381
- if ($null -eq $Uri -or $Uri.Scheme -cne 'https') { return $false }
2382
- switch ($Site) {
2383
- 'steam' { return $Uri.Host -ceq 'store.steampowered.com' -and $Uri.AbsolutePath -match '^/login(?:/|$)' }
2384
- 'netease-mail' { return $Uri.Host -in @('reg.163.com', 'dl.reg.163.com', 'passport.163.com') }
2385
- 'spotify' { return $Uri.Host -ceq 'accounts.spotify.com' }
2386
- 'notebooklm' { return $Uri.Host -ceq 'accounts.google.com' }
2387
- }
2388
- return $false
2389
- }
2390
- function Test-SiteLoginPath([string]$Site, [uri]$Uri, [uri]$Target) {
2391
- $path = $Uri.AbsolutePath.ToLowerInvariant()
2392
- switch ($Site) {
2393
- 'x' { return $path -match '^/(?:i/flow/(?:login|signup)|login|signup|logout)(?:/|$)' -or ($path -eq '/' -and $Target.AbsolutePath -ne '/') }
2394
- 'instagram' { return $path -match '^/(?:accounts/(?:login|signup|emailsignup|suspended)|challenge)(?:/|$)' }
2395
- 'linkedin' { return $path -match '^/(?:login|signup|authwall|uas/login|checkpoint|start/join)(?:/|$)' }
2396
- 'steam' { return $path -match '^/(?:login|openid/login)(?:/|$)' }
2397
- 'reddit' { return $path -match '^/(?:login|register|account/(?:login|register))(?:/|$)' }
2398
- # Signed out, Spotify Web sends /collection/tracks to its public home page instead of a sign-in page (2026-10-21).
2399
- 'spotify' { return $path -match '^/(?:login|signup)(?:/|$)' -or ($path -eq '/' -and $Target.AbsolutePath -ne '/') }
2400
- }
2401
- return $false
2402
- }
2403
- function Test-OwnedSiteCloseCandidate([int]$TabCount, [string]$CurrentTab, [string]$BoundTab, [uri]$CurrentUrl) {
2404
- return -not [string]::IsNullOrEmpty($script:SiteName) -and $TabCount -eq 1 -and -not [string]::IsNullOrWhiteSpace($BoundTab) -and
2405
- $CurrentTab -ceq $BoundTab -and (Test-SiteHost $script:SiteName $CurrentUrl)
2406
- }
2407
- function Get-SiteText($Value, [int]$Max) {
2408
- if ($Value -isnot [string]) { return '' }
2409
- $text = ($Value -replace '\s+', ' ').Trim()
2410
- if ($text.Length -gt $Max) { $text = $text.Substring(0, $Max) }
2411
- return $text
2412
- }
2413
- function Get-SiteLink($Element, [string]$Site) {
2414
- $href = Get-SiteText ($Element.GetCachedPropertyValue([Windows.Automation.ValuePattern]::ValueProperty)) 600
2415
- $parsed = $null
2416
- if (-not [uri]::TryCreate($href, [UriKind]::Absolute, [ref]$parsed) -or -not (Test-SiteHost $Site $parsed)) { return $null }
2417
- return @{ name = Get-SiteText $Element.Cached.Name 300; href = $parsed.GetLeftPart([UriPartial]::Path) }
2418
- }
2419
- function Get-SiteEntries($Document, [string]$Site, [int]$MaxArticles = 12) {
2420
- $cache = New-Object Windows.Automation.CacheRequest
2421
- foreach ($property in @([Windows.Automation.AutomationElement]::NameProperty, [Windows.Automation.AutomationElement]::ControlTypeProperty,
2422
- [Windows.Automation.AutomationElement]::LocalizedControlTypeProperty, [Windows.Automation.AutomationElement]::IsPasswordProperty,
2423
- [Windows.Automation.ValuePattern]::ValueProperty)) { $cache.Add($property) }
2424
- $cache.TreeScope = [Windows.Automation.TreeScope]::Element
2425
- $link = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ControlTypeProperty, [Windows.Automation.ControlType]::Hyperlink)
2426
- $condition = [Windows.Automation.OrCondition]::new([Windows.Automation.Condition[]]@($link,
2427
- (New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::LocalizedControlTypeProperty, 'article')),
2428
- (New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::LocalizedControlTypeProperty, ([string][char]0x6587 + [char]0x7AE0))),
2429
- (New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ControlTypeProperty, [Windows.Automation.ControlType]::ListItem)),
2430
- (New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::IsPasswordProperty, $true))))
2431
- $activation = $cache.Activate()
2432
- try {
2433
- $found = $Document.FindAll([Windows.Automation.TreeScope]::Descendants, $condition)
2434
- $articles = [Collections.Generic.List[object]]::new()
2435
- $links = [Collections.Generic.List[object]]::new()
2436
- $items = [Collections.Generic.List[object]]::new()
2437
- $password = $false
2438
- foreach ($element in $found) {
2439
- try {
2440
- if ($element.GetCachedPropertyValue([Windows.Automation.AutomationElement]::IsPasswordProperty) -eq $true) { $password = $true; continue }
2441
- # Chrome reports role=article as a Group whose localized type is 'article' (U+6587 U+7AE0 in a Chinese UI).
2442
- $role = [string]$element.GetCachedPropertyValue([Windows.Automation.AutomationElement]::LocalizedControlTypeProperty)
2443
- if ($element.Cached.ControlType -ne [Windows.Automation.ControlType]::Hyperlink -and $role -in @('article', ([string][char]0x6587 + [char]0x7AE0))) {
2444
- if ($articles.Count -ge $MaxArticles) { continue }
2445
- $inner = [Collections.Generic.List[object]]::new()
2446
- foreach ($child in $element.FindAll([Windows.Automation.TreeScope]::Descendants, $link)) {
2447
- if ($inner.Count -ge 20) { break }
2448
- $entry = Get-SiteLink $child $Site
2449
- if ($null -ne $entry) { $inner.Add($entry) }
2450
- }
2451
- $name = Get-SiteText $element.Cached.Name 4000
2452
- if ($name.Length -eq 0) {
2453
- # Instagram leaves the article unnamed; its visible text is in descendant Text elements.
2454
- $parts = [Collections.Generic.List[string]]::new()
2455
- $textCondition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ControlTypeProperty, [Windows.Automation.ControlType]::Text)
2456
- foreach ($text in $element.FindAll([Windows.Automation.TreeScope]::Descendants, $textCondition)) {
2457
- $part = Get-SiteText $text.Cached.Name 1000
2458
- if ($part.Length -gt 0 -and ($parts.Count -eq 0 -or $parts[$parts.Count - 1] -cne $part)) { $parts.Add($part) }
2459
- if ($parts.Count -ge 60) { break }
2460
- }
2461
- $name = Get-SiteText ($parts -join ' ') 4000
2462
- }
2463
- $articles.Add(@{ name = $name; links = @($inner) })
2464
- } elseif ($element.Cached.ControlType -eq [Windows.Automation.ControlType]::ListItem) {
2465
- if ($items.Count -ge 40) { continue }
2466
- $text = Get-SiteText $element.Cached.Name 2000
2467
- if ($text.Length -eq 0) { continue }
2468
- $inner = [Collections.Generic.List[object]]::new()
2469
- foreach ($child in $element.FindAll([Windows.Automation.TreeScope]::Descendants, $link)) {
2470
- if ($inner.Count -ge 5) { break }
2471
- $entry = Get-SiteLink $child $Site
2472
- if ($null -ne $entry) { $inner.Add($entry) }
2473
- }
2474
- $items.Add(@{ name = $text; links = @($inner) })
2475
- } elseif ($element.Cached.ControlType -eq [Windows.Automation.ControlType]::Hyperlink -and $links.Count -lt 300) {
2476
- $entry = Get-SiteLink $element $Site
2477
- if ($null -ne $entry) { $links.Add($entry) }
2478
- }
2479
- } catch {}
2480
- }
2481
- } finally { $activation.Dispose() }
2482
- return @{ password = $password; articles = @($articles); items = @($items); links = @($links) }
2483
- }
2484
- function Test-SiteReadReady($Site, $Entries, $ElapsedMs, $SettleMs) {
2485
- if ($ElapsedMs -ge $SettleMs) { return $true }
2486
- if ($Site -notin @('x', 'instagram', 'linkedin')) {
2487
- # List-shaped pages (games, mail rows, chats, tracks, notebooks): settle once rows or a page of links have rendered.
2488
- return $ElapsedMs -ge 3000 -and ($Entries.items.Count -ge 3 -or $Entries.articles.Count -gt 0 -or $Entries.links.Count -ge 12)
2489
- }
2490
- if ($Site -eq 'linkedin') {
2491
- # Navigation renders before the messaging list. Match the reader's conversation
2492
- # shape instead of returning a successful empty first read from navigation alone.
2493
- foreach ($item in $Entries.items) {
2494
- if ($item.links.Count -eq 0 -and $item.name.Length -ge 40) { return $true }
2495
- }
2496
- return $false
2497
- }
2498
- # A home-feed article can arrive before the signed-in profile navigation.
2499
- # Keep collecting that navigation so the caller can request the person's own
2500
- # profile. Missing navigation still completes at the existing settle bound;
2501
- # neither a feed article nor this readiness check establishes account identity.
2502
- $profileNavigationReady = $false
2503
- foreach ($link in $Entries.links) {
2504
- if (([string]$link.name).Trim() -match '(?:^|\s)(?:profile|\u500b\u4eba\u8cc7\u6599|\u4e2a\u4eba\u8d44\u6599|\u500b\u4eba\u6a94\u6848|\u4e2a\u4eba\u4e3b\u9875|\u500b\u4eba\u4e3b\u9801|\u30d7\u30ed\u30d5\u30a3\u30fc\u30eb|\ud504\ub85c\ud544|perfil|profil)$') {
2505
- $profileNavigationReady = $true
2506
- break
2507
- }
2508
- }
2509
- if (-not $profileNavigationReady) { return $false }
2510
- if ($Entries.articles.Count -gt 0) { return $true }
2511
- return ($Site -eq 'instagram' -and $Entries.links.Count -ge 8 -and $ElapsedMs -ge 4000)
2512
- }
2513
-
2514
- function Invoke-SiteRead($Request) {
2515
- $site = [string]$Request.site
2516
- $target = [uri]$Request.url
2517
- $timeoutMs = [int]$Request.timeoutMs
2518
- $settleMs = $(if ($null -ne $Request.PSObject.Properties['settleMs']) { [int]$Request.settleMs } else { 8000 })
2519
- if ($site -notin @('x', 'instagram', 'linkedin', 'steam', 'netease-mail', 'reddit', 'spotify', 'notebooklm', 'whatsapp') -or -not (Test-SiteHost $site $target) -or $target.Query -or $target.Fragment -or
2520
- $timeoutMs -lt 5000 -or $timeoutMs -gt 120000 -or $settleMs -lt 1000 -or $settleMs -gt 30000) { throw 'invalid site read request' }
2521
- $script:SiteName = $site
2522
- $script:Automatic = $true
2523
- # Page text is not ASCII; the caller decodes stdout as UTF-8.
2524
- [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
2525
- $script:deadline = [DateTime]::UtcNow.AddMilliseconds($timeoutMs)
2526
- if (Test-Cancellation $script:cancellation) { Write-Result @{ state = 'failed'; reason = 'cancelled' } 1 }
2527
- Start-GuardedOAuthBrowser $target
2528
- $script:boundHandle = [IntPtr]::Zero
2529
- $script:boundTab = $null
2530
- $contentSince = $null
2531
- $hiddenSince = $null
2532
- $last = $null
2533
- $nudgedAt = [DateTime]::MinValue
2534
- $revealedAt = $null
2535
- $siteReveals = 0
2536
- $dismissed = $false
2537
- $diag = @{ other = "none"; reveal = "none"; windows = 0; complete = 0; tabs = -1; host = 0; native = 0; page = 0; hidden = 0; content = 0; ms = 0 }
2538
- while ([DateTime]::UtcNow -lt $script:deadline) {
2539
- Assert-BackgroundGuard
2540
- if ([ZortexNativeWindow]::IsForeground($script:OwnedBrowserHandle)) { $script:ForegroundObserved = $true }
2541
- if (Test-Cancellation $script:cancellation) { Write-Result @{ state = 'failed'; reason = 'cancelled' } 1 }
2542
- foreach ($window in @(Get-BrowserWindows)) {
2543
- try {
2544
- $id = $script:BackgroundIdentity
2545
- $diag.windows++
2546
- $snapshot = [OAuthBackground]::Snapshot($window.handle, $id.Pid, $id.Tid, $script:BackgroundNonce)
2547
- $diag.tabs = $snapshot.Tabs; $diag.ms = $snapshot.DurationMs
2548
- if (-not $snapshot.Complete -or $snapshot.Tabs -ne 1) { continue }
2549
- $diag.complete++
2550
- $current = [uri]$snapshot.Url
2551
- if ($script:boundHandle -eq [IntPtr]::Zero) {
2552
- $script:boundHandle = $window.handle
2553
- $script:boundTab = Get-SelectedTabIdentity $window.element
2554
- if ([string]::IsNullOrWhiteSpace($script:boundTab)) { continue }
2555
- Register-OwnedBrowser $window.handle $true
2556
- } elseif ($window.handle -ne $script:boundHandle -or $snapshot.Tab -cne $script:boundTab) { Write-Result @{ state = 'ui_drift'; reason = 'tab_changed' } 1 }
2557
- if (Test-SiteLoginHost $site $current) { Write-Result @{ state = 'login_required'; reason = 'site_signed_out' } 1 }
2558
- if (-not (Test-SiteHost $site $current)) { $diag.other = "$($current.Scheme):$($current.Host)"; continue }
2559
- $diag.host++
2560
- if (Test-SiteLoginPath $site $current $target) { Write-Result @{ state = 'login_required'; reason = 'site_signed_out' } 1 }
2561
- $native = New-Object OAuthBackground+Stats
2562
- if ([OAuthBackground]::Read([ref]$native) -ne 0) { continue }
2563
- if ($native.Renderer -eq 0) { Resolve-BackgroundRenderer $window.handle $snapshot.Tab $current; continue }
2564
- $script:RendererMissingSince = $null
2565
- $diag.native++
2566
- $script:ReadGeneration = $native.Generation
2567
- $script:ReadUrl = $current.AbsoluteUri
2568
- $script:ReadTab = $snapshot.Tab
2569
- [OAuthBackground]::ConfigurePage($window.handle, $id.Pid, $id.Tid, $script:BackgroundNonce, $script:ReadTab, $script:ReadUrl, $script:ReadGeneration)
2570
- try { $page = Get-Page $window.element } catch { continue }
2571
- if ($null -eq $page) { continue }
2572
- $diag.page++
2573
- if (Test-PageContentMissing $page.documents) {
2574
- $diag.hidden++
2575
- if ($null -eq $hiddenSince) { $hiddenSince = [DateTime]::UtcNow }
2576
- $revealsBefore = $script:RevealCount
2577
- if (Test-StuckPageRecovery $window.handle $hiddenSince $nudgedAt $current) { $nudgedAt = [DateTime]::UtcNow; $diag.reveal = 'nudged' }
2578
- if ($script:RevealCount -gt $revealsBefore) { $revealedAt = [DateTime]::UtcNow; $siteReveals++ }
2579
- # A reveal that left the renderer hidden (fully occluded window) is
2580
- # retried for a read-only page: up to 3 minimize/restore cycles, 8 s apart.
2581
- elseif ($null -ne $revealedAt -and $siteReveals -lt 3 -and ([DateTime]::UtcNow - $revealedAt).TotalMilliseconds -ge 8000) {
2582
- $script:RevealPages.Remove("$($current.AbsoluteUri)|page") | Out-Null
2583
- $revealedAt = $null
2584
- }
2585
- continue
2586
- }
2587
- Update-BackgroundRendererWait $current $true ([DateTime]::UtcNow)
2588
- $diag.content++
2589
- $hiddenSince = $null
2590
- if ($null -eq $contentSince) { $contentSince = [DateTime]::UtcNow }
2591
- $last = Get-SiteEntries $page.document $site
2592
- if (-not $dismissed -and $last.articles.Count -eq 0 -and $last.links.Count -lt 8) {
2593
- # A modal prompt (Instagram's "Turn on notifications") hides the page from accessibility. Only its
2594
- # "Not now" button is ever pressed: it changes no account setting, grants nothing and posts nothing.
2595
- $notNow = @('Not Now', 'Not now', ([string][char]0x7A0D + [char]0x5F8C + [char]0x518D + [char]0x8AAA), ([string][char]0x7A0D + [char]0x540E + [char]0x518D + [char]0x8BF4))
2596
- foreach ($element in $page.elements) {
2597
- try {
2598
- if ($element.Current.ControlType -ne [Windows.Automation.ControlType]::Button -or $element.Current.Name -cnotin $notNow) { continue }
2599
- $script:ActionUrl = $current.AbsoluteUri
2600
- $script:ActionGeneration = $native.Generation
2601
- if (Invoke-Control $element) { $dismissed = $true; $contentSince = [DateTime]::UtcNow; $diag.reveal = 'dismissed' }
2602
- break
2603
- } catch { if (Test-BackgroundGuardException $_) { throw } }
2604
- }
2605
- if ($dismissed) { continue }
2606
- }
2607
- # A splash screen is content too: wait for posts, or for the page's own links to render, before settling.
2608
- # X's navigation alone has more than 8 links before its timeline renders, so X settles on posts or time only.
2609
- $elapsed = ([DateTime]::UtcNow - $contentSince).TotalMilliseconds
2610
- if (Test-SiteReadReady $site $last $elapsed $settleMs) {
2611
- $result = @{ state = 'completed'; site = $site; url = $current.GetLeftPart([UriPartial]::Path); articles = $last.articles; items = $last.items; links = $last.links }
2612
- if ($env:ZORTEX_SITE_INVENTORY -eq '1') {
2613
- # Development aid: control type counts only, never names or values.
2614
- $types = @{}
2615
- foreach ($element in $page.elements) { try { $key = "$($element.Current.ControlType.ProgrammaticName)|$($element.Current.LocalizedControlType)"; $types[$key] = 1 + [int]$types[$key] } catch {} }
2616
- $result.inventory = $types
2617
- }
2618
- Write-Result $result
2619
- }
2620
- } catch {
2621
- if (Test-BackgroundNavigationDrift $_.Exception.Message) { continue }
2622
- throw
2623
- }
2624
- }
2625
- Start-Sleep -Milliseconds 400
2626
- }
2627
- if ($null -ne $last) { Write-Result @{ state = 'completed'; site = $site; url = $script:ReadUrl; articles = $last.articles; items = $last.items; links = $last.links } }
2628
- $counts = "windows=$($diag.windows) complete=$($diag.complete) tabs=$($diag.tabs) snapshotMs=$($diag.ms) host=$($diag.host) native=$($diag.native) page=$($diag.page) hidden=$($diag.hidden) content=$($diag.content) reveal=$($diag.reveal) reveals=$($script:RevealCount) other=$($diag.other)"
2629
- Write-Result @{ state = 'ui_drift'; reason = $(if ($null -ne $hiddenSince) { "page_accessibility_unavailable $counts" } else { "site_page_timeout $counts" }) } 1
2630
- }
2631
-
2632
- # Page session: the same guarded background window, driven one command per line by a caller that decides (Jev).
2633
- # Commands and answers match Jev's page helper (open, observe, act, scroll, readsite, reveal, close); nothing here
2634
- # activates or focuses the window, and the window is opened only on an allowlisted provider or site origin.
2635
- function Write-SessionAnswer($Value) {
2636
- [Console]::Out.WriteLine(($Value | ConvertTo-Json -Depth 6 -Compress)); [Console]::Out.Flush()
2637
- # Development aid: ZORTEX_PAGE_SESSION_LOG=<absolute file> records command, result code, URL path and counts; never names or text.
2638
- $log = [string]$env:ZORTEX_PAGE_SESSION_LOG
2639
- if ($log -and [IO.Path]::IsPathRooted($log)) {
2640
- try {
2641
- $path = ''; try { $path = ([uri]$script:ReadUrl).AbsolutePath } catch {}
2642
- $row = [ordered]@{ t = [DateTime]::UtcNow.ToString('HH:mm:ss.fff'); cmd = $script:SessionCommand; ok = $Value['ok']; reason = $Value['reason']; detail = $script:SessionDetail; path = $path; done = $Value['done']; via = $Value['via']
2643
- controls = $(if ($null -ne $Value['page']) { @($Value['page']['controls']).Count } else { $null }); reveals = $script:RevealCount; foreground = [int]$script:ForegroundObserved }
2644
- Add-Content -LiteralPath $log -Value ($row | ConvertTo-Json -Compress) -Encoding UTF8
2645
- } catch {}
2646
- }
2647
- $script:SessionDetail = $null
2648
- }
2649
-
2650
- function Test-SessionOpenUrl([uri]$Uri) {
2651
- return $null -ne $Uri -and $Uri.IsAbsoluteUri -and -not $Uri.UserInfo -and $Uri.Scheme -in @('https', 'http')
2652
- }
2653
-
2654
- # The signed-in site a page session was opened on; an authorization page is no site, so readsite refuses it.
2655
- function Get-SessionSite([uri]$Uri) {
2656
- foreach ($site in @('x', 'instagram', 'linkedin', 'steam', 'netease-mail', 'reddit', 'spotify', 'notebooklm', 'whatsapp')) {
2657
- if (Test-SiteHost $site $Uri) { return $site }
2658
- }
2659
- return ''
2660
- }
2661
-
2662
- # Articles read per readsite answer: the default is one screen's worth; a scrolling caller asks for more (at most 60).
2663
- function Get-SessionReadLimit($Command) {
2664
- if ($null -eq $Command.PSObject.Properties['max']) { return 12 }
2665
- $max = 0
2666
- if (-not [int]::TryParse([string]$Command.max, [ref]$max)) { return 12 }
2667
- return [Math]::Max(1, [Math]::Min(60, $max))
2668
- }
2669
-
2670
- function Get-SessionWindow {
2671
- $id = $script:BackgroundIdentity
2672
- foreach ($window in @(Get-BrowserWindows)) {
2673
- $snapshot = [OAuthBackground]::Snapshot($window.handle, $id.Pid, $id.Tid, $script:BackgroundNonce)
2674
- if (-not $snapshot.Complete -or $snapshot.Tabs -ne 1) { continue }
2675
- if ($script:boundHandle -eq [IntPtr]::Zero) {
2676
- $tab = Get-SelectedTabIdentity $window.element
2677
- if ([string]::IsNullOrWhiteSpace($tab)) { continue }
2678
- $script:boundHandle = $window.handle
2679
- $script:boundTab = $tab
2680
- Register-OwnedBrowser $window.handle $true
2681
- } elseif ($window.handle -ne $script:boundHandle -or $snapshot.Tab -cne $script:boundTab) { throw 'jev:tab_changed' }
2682
- return @{ window = $window; snapshot = $snapshot }
2683
- }
2684
- return $null
2685
- }
2686
-
2687
- function Get-SessionPage([int]$WaitMs) {
2688
- $until = [DateTime]::UtcNow.AddMilliseconds($WaitMs)
2689
- $hiddenSince = $null
2690
- $nudgedAt = [DateTime]::MinValue
2691
- $lastUrl = $null
2692
- $script:SessionDiag = @{ window = 0; renderer = 0; page = 0; hidden = 0; nudged = 0 }
2693
- while ($true) {
2694
- if ([ZortexNativeWindow]::IsForeground($script:OwnedBrowserHandle)) { $script:ForegroundObserved = $true }
2695
- $found = Get-SessionWindow
2696
- if ($null -ne $found) {
2697
- $script:SessionDiag.window++
2698
- $current = [uri]$found.snapshot.Url
2699
- $lastUrl = $current
2700
- $native = New-Object OAuthBackground+Stats
2701
- $nativeError = [OAuthBackground]::Read([ref]$native)
2702
- if ($nativeError -eq 0 -and $native.Renderer -eq 0) { Resolve-BackgroundRenderer $found.window.handle $found.snapshot.Tab $current }
2703
- if ($nativeError -eq 0 -and $native.Renderer -ne 0) {
2704
- $script:RendererMissingSince = $null
2705
- $script:SessionDiag.renderer++
2706
- $id = $script:BackgroundIdentity
2707
- $script:ReadGeneration = $native.Generation
2708
- $script:ReadUrl = $current.AbsoluteUri
2709
- $script:ReadTab = $found.snapshot.Tab
2710
- [OAuthBackground]::ConfigurePage($found.window.handle, $id.Pid, $id.Tid, $script:BackgroundNonce, $script:ReadTab, $script:ReadUrl, $script:ReadGeneration)
2711
- $page = $null
2712
- try { $page = Get-Page $found.window.element } catch { if (-not (Test-BackgroundNavigationDrift $_.Exception.Message)) { throw } }
2713
- if ($null -ne $page -and -not (Test-PageContentMissing $page.documents)) {
2714
- Update-BackgroundRendererWait $current $true ([DateTime]::UtcNow)
2715
- return @{ page = $page; url = $current; window = $found.window }
2716
- }
2717
- if ($null -ne $page) {
2718
- $script:SessionDiag.hidden++
2719
- if ($null -eq $hiddenSince) { $hiddenSince = [DateTime]::UtcNow }
2720
- if (Test-StuckPageRecovery $found.window.handle $hiddenSince $nudgedAt $current) { $nudgedAt = [DateTime]::UtcNow; $script:SessionDiag.nudged++ }
2721
- # As for a site read: a reveal that left a fully covered window's page hidden is repeated, up to 3 times
2722
- # per page, 8 s apart. The window is never activated.
2723
- $key = "$($current.AbsoluteUri)|page"
2724
- if ($script:RevealCount -gt $script:SessionRevealCount) { $script:SessionRevealCount = $script:RevealCount; $script:SessionRevealedAt[$key] = [DateTime]::UtcNow; $script:SessionReveals[$key] = 1 + [int]$script:SessionReveals[$key] }
2725
- elseif ($script:SessionRevealedAt.ContainsKey($key) -and [int]$script:SessionReveals[$key] -lt 3 -and ([DateTime]::UtcNow - $script:SessionRevealedAt[$key]).TotalMilliseconds -ge 8000) {
2726
- $script:RevealPages.Remove($key) | Out-Null
2727
- $script:SessionRevealedAt.Remove($key)
2728
- }
2729
- }
2730
- }
2731
- }
2732
- if ([DateTime]::UtcNow -ge $until) { return @{ page = $null; url = $lastUrl; window = $(if ($null -ne $found) { $found.window } else { $null }) } }
2733
- Start-Sleep -Milliseconds 300
2734
- }
2735
- }
2736
-
2737
- function Get-SessionRole($Element) {
2738
- $type = $Element.Current.ControlType
2739
- if ($type -eq [Windows.Automation.ControlType]::Hyperlink) { return 'link' }
2740
- if ($type -in @([Windows.Automation.ControlType]::Button, [Windows.Automation.ControlType]::CheckBox, [Windows.Automation.ControlType]::RadioButton,
2741
- [Windows.Automation.ControlType]::ListItem, [Windows.Automation.ControlType]::MenuItem, [Windows.Automation.ControlType]::TabItem)) { return 'button' }
2742
- if ($type -in @([Windows.Automation.ControlType]::Edit, [Windows.Automation.ControlType]::ComboBox)) { return 'textbox' }
2743
- return $null
2744
- }
2745
-
2746
- function Test-SessionActionable($Element) {
2747
- foreach ($pattern in @([Windows.Automation.InvokePattern]::Pattern, [Windows.Automation.TogglePattern]::Pattern,
2748
- [Windows.Automation.SelectionItemPattern]::Pattern, [Windows.Automation.ExpandCollapsePattern]::Pattern)) {
2749
- if ($null -ne (Get-Pattern $Element $pattern)) { return $true }
2750
- }
2751
- return $false
2752
- }
2753
-
2754
- function Get-SessionSnapshot {
2755
- $found = Get-SessionPage 10000
2756
- $title = ''
2757
- if ($null -ne $found.window) { try { $title = [string]$found.window.element.Current.Name -replace ' - Google Chrome$', '' } catch {} }
2758
- $controls = New-Object System.Collections.ArrayList
2759
- $headings = New-Object System.Collections.ArrayList
2760
- $text = New-Object System.Text.StringBuilder
2761
- $script:SessionControls = @{}
2762
- $script:SessionNames = @{}
2763
- $script:SessionTypes = @{}
2764
- if ($null -ne $found.page) {
2765
- $headingLevel = $null
2766
- try { $headingLevel = [Windows.Automation.AutomationProperty]::LookupById(30173) } catch {}
2767
- $headingType = '^(heading|' + [char]0x6807 + [char]0x9898 + '|' + [char]0x6A19 + [char]0x984C + ')'
2768
- $n = 0
2769
- $lastName = ''
2770
- foreach ($element in $found.page.elements) {
2771
- if (++$n -gt 3000) { break }
2772
- try {
2773
- $current = $element.Current
2774
- $name = ([string]$current.Name).Trim()
2775
- $heading = $false
2776
- if ($null -ne $headingLevel) { try { $level = [int]$element.GetCurrentPropertyValue($headingLevel); $heading = $level -gt 80050 -and $level -le 80059 } catch {} }
2777
- if (-not $heading) { $heading = $current.ControlType -eq [Windows.Automation.ControlType]::Header -or [string]$current.LocalizedControlType -match $headingType }
2778
- if ($heading -and $name) { [void]$headings.Add($name) }
2779
- if ($name -and $text.Length -lt 8000 -and $name -ne $lastName) { [void]$text.Append($name).Append(' '); $lastName = $name }
2780
- $role = Get-SessionRole $element
2781
- if (-not $role -or $current.IsOffscreen) { continue }
2782
- $id = ($element.GetRuntimeId() -join '.')
2783
- $control = [ordered]@{ id = $id; role = $role; label = $name; enabled = [bool]$current.IsEnabled }
2784
- if ($current.IsPassword) { $control.secure = $true }
2785
- $toggle = Get-Pattern $element ([Windows.Automation.TogglePattern]::Pattern)
2786
- if ($null -ne $toggle) { $control.selected = ($toggle.Current.ToggleState -eq [Windows.Automation.ToggleState]::On) }
2787
- if ($role -ne 'textbox' -and -not (Test-SessionActionable $element)) { continue }
2788
- if (-not $name -and $role -ne 'textbox' -and -not $control.Contains('selected')) { continue }
2789
- $script:SessionControls[$id] = $element
2790
- $script:SessionNames[$id] = $name
2791
- $script:SessionTypes[$id] = $current.ControlType
2792
- [void]$controls.Add($control)
2793
- } catch {}
2794
- }
2795
- $script:SessionDocument = $found.page.document
2796
- } else { $script:SessionDocument = $null }
2797
- $url = $(if ($null -ne $found.url) { $found.url.AbsoluteUri } else { '' })
2798
- $snapshot = [ordered]@{ url = $url; title = $title; text = $text.ToString().Trim(); headings = @($headings); controls = @($controls) }
2799
- # Counts only, for diagnosing a page that stayed hidden; never names or text.
2800
- if ($env:ZORTEX_PAGE_SESSION_DIAG -eq '1') { $snapshot.diag = $script:SessionDiag + @{ reveals = $script:RevealCount; foreground = [int]$script:ForegroundObserved; boundTab = [int](-not [string]::IsNullOrWhiteSpace($script:boundTab)) } }
2801
- return $snapshot
2802
- }
2803
-
2804
- function Invoke-PageSession($Request) {
2805
- $script:Automatic = $true
2806
- $script:PageSession = $true
2807
- $script:cancellation = [Threading.Tasks.TaskCompletionSource[string]]::new().Task
2808
- [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
2809
- $timeoutMs = [int]$Request.timeoutMs
2810
- if ($timeoutMs -lt 5000 -or $timeoutMs -gt 900000) { throw 'invalid page session timeout' }
2811
- $script:deadline = [DateTime]::UtcNow.AddMilliseconds($timeoutMs)
2812
- $script:boundHandle = [IntPtr]::Zero
2813
- $script:boundTab = $null
2814
- $script:SessionControls = @{}
2815
- $script:SessionNames = @{}
2816
- $script:SessionTypes = @{}
2817
- $script:SessionCommand = ''
2818
- $script:SessionPressedUrl = ''
2819
- $script:SessionDetail = $null
2820
- $script:SessionDocument = $null
2821
- $script:SessionSite = ''
2822
- $script:ReadUrl = ''
2823
- $script:ReadGeneration = 0
2824
- $script:SessionRevealCount = 0
2825
- $script:SessionRevealedAt = @{}
2826
- $script:SessionReveals = @{}
2827
- $opened = $false
2828
- while ($true) {
2829
- $line = [Console]::In.ReadLine()
2830
- if ($null -eq $line) { break }
2831
- try {
2832
- $command = $line | ConvertFrom-Json
2833
- $script:SessionCommand = [string]$command.cmd
2834
- switch ([string]$command.cmd) {
2835
- 'open' {
2836
- if ($opened) { throw 'jev:window_already_open' }
2837
- $target = $null
2838
- if (-not [uri]::TryCreate([string]$command.url, [UriKind]::Absolute, [ref]$target) -or -not (Test-SessionOpenUrl $target)) { throw 'jev:invalid_url' }
2839
- Start-GuardedOAuthBrowser $target
2840
- $opened = $true
2841
- $script:SessionSite = Get-SessionSite $target
2842
- $until = [DateTime]::UtcNow.AddSeconds(30)
2843
- while ($null -eq (Get-SessionWindow)) {
2844
- if ([DateTime]::UtcNow -ge $until) { throw 'jev:window_not_opened' }
2845
- Start-Sleep -Milliseconds 200
2846
- }
2847
- Write-SessionAnswer @{ ok = $true }
2848
- }
2849
- 'observe' {
2850
- if (-not $opened) { throw 'jev:window_closed' }
2851
- # A press that kept the address (Advanced on Google's warning) can leave a background page's accessibility
2852
- # tree unchanged. As the UIA rules do after Advanced, that address gets one more reveal once it has settled.
2853
- if ($script:SessionPressedUrl) {
2854
- $found = Get-SessionWindow
2855
- if ($null -ne $found -and [string]$found.snapshot.Url -ceq $script:SessionPressedUrl) {
2856
- $refresh = Request-BackgroundPage $found.window.handle $script:boundTab ([uri]$script:SessionPressedUrl) ([DateTime]::UtcNow) 'advanced'
2857
- if ($refresh -notin @('waiting', 'waiting_renderer')) { $script:SessionPressedUrl = '' }
2858
- } elseif ($null -ne $found) { $script:SessionPressedUrl = '' }
2859
- }
2860
- Write-SessionAnswer @{ ok = $true; page = (Get-SessionSnapshot) }
2861
- }
2862
- 'readsite' {
2863
- # The entries a one-shot site read returns (articles, list items, same-site links), from the signed-in site
2864
- # page this session opened. The document is remembered, so 'scroll' then moves this page. Nothing is pressed.
2865
- if (-not $opened) { throw 'jev:window_closed' }
2866
- if (-not $script:SessionSite) { throw 'jev:not_a_site' }
2867
- $found = Get-SessionPage 3000
2868
- $read = [ordered]@{ url = ''; rendered = ($null -ne $found.page); password = $false; articles = @(); items = @(); links = @() }
2869
- if ($null -ne $found.url) { $read.url = $found.url.AbsoluteUri }
2870
- if ($null -ne $found.page) {
2871
- $entries = Get-SiteEntries $found.page.document $script:SessionSite (Get-SessionReadLimit $command)
2872
- $script:SessionDocument = $found.page.document
2873
- $read.password = [bool]$entries.password
2874
- $read.articles = @($entries.articles); $read.items = @($entries.items); $read.links = @($entries.links)
2875
- }
2876
- Write-SessionAnswer @{ ok = $true; site = $read }
2877
- }
2878
- 'type' {
2879
- $wanted = [string]$command.id
2880
- $value = [string]$command.value
2881
- if (-not $script:SessionControls.ContainsKey($wanted)) { throw 'jev:control_unknown' }
2882
- $expectedName = [string]$script:SessionNames[$wanted]
2883
- $now = Get-SessionPage 3000
2884
- $element = $null
2885
- if ($null -ne $now.page) {
2886
- foreach ($candidate in $now.page.elements) {
2887
- try {
2888
- if (($candidate.GetRuntimeId() -join '.') -ceq $wanted -and ([string]$candidate.Current.Name).Trim() -ceq $expectedName -and
2889
- (Get-SessionRole $candidate) -eq 'textbox' -and $candidate.Current.IsEnabled -and -not $candidate.Current.IsOffscreen) { $element = $candidate; break }
2890
- } catch {}
2891
- }
2892
- }
2893
- $pattern = $(if ($null -ne $element) { Get-Pattern $element ([Windows.Automation.ValuePattern]::Pattern) } else { $null })
2894
- $done = $false
2895
- if ($null -ne $pattern -and -not $pattern.Current.IsReadOnly -and $value.Length -ge 1 -and $value.Length -le 4000) {
2896
- $script:ActionUrl = $script:ReadUrl
2897
- $script:ActionGeneration = $script:ReadGeneration
2898
- Assert-BackgroundAction
2899
- $pattern.SetValue($value)
2900
- $done = $true
2901
- }
2902
- Write-SessionAnswer @{ ok = $true; done = $done; via = 'value' }
2903
- }
2904
- 'act' {
2905
- $wanted = [string]$command.id
2906
- $element = $script:SessionControls[$wanted]
2907
- if ($null -eq $element) { throw 'jev:control_unknown' }
2908
- $label = [string]$script:SessionNames[$wanted]
2909
- # Google re-renders between the read and the press; press the same control (runtime id) of the page as it is now.
2910
- $now = Get-SessionPage 3000
2911
- $type = $null
2912
- try { $type = $element.Current.ControlType } catch {}
2913
- if ($null -eq $type) { $type = $script:SessionTypes[$wanted] }
2914
- $byId = $null; $byName = @()
2915
- if ($null -ne $now.page) {
2916
- foreach ($candidate in $now.page.elements) {
2917
- try {
2918
- if (($candidate.GetRuntimeId() -join '.') -ceq $wanted) { $byId = $candidate; break }
2919
- if ($label -and $candidate.Current.ControlType -eq $type -and ([string]$candidate.Current.Name).Trim() -ceq $label -and -not $candidate.Current.IsOffscreen) { $byName += $candidate }
2920
- } catch {}
2921
- }
2922
- # Google rebuilds its nodes between reads: the same control is then the only one with its name and type.
2923
- if ($null -ne $byId) { $element = $byId } elseif ($byName.Count -eq 1) { $element = $byName[0] }
2924
- }
2925
- $usable = $false
2926
- try { $probe = $null; [void]$element.TryGetCurrentPattern([Windows.Automation.InvokePattern]::Pattern, [ref]$probe); $null = $element.Current.IsOffscreen; $usable = $true } catch {}
2927
- if (-not $usable) {
2928
- # A background page that changed (an expanded section, a navigation) keeps its old accessibility nodes until
2929
- # it is refreshed. Refresh it once at this URL, as the UIA rules do after Advanced; the caller reads again.
2930
- $found = Get-SessionWindow
2931
- if ($null -ne $found) { Test-StuckPageRecovery $found.window.handle ([DateTime]::MinValue) ([DateTime]::MinValue) ([uri]$found.snapshot.Url) 'advanced' | Out-Null }
2932
- throw 'stale_control'
2933
- }
2934
- $script:ActionUrl = $script:ReadUrl
2935
- $script:ActionGeneration = $script:ReadGeneration
2936
- # The same escalation the UIA rules use: the control, then its ancestors (a link's text inside a span), then
2937
- # Chrome's MSAA default action by the control's own name.
2938
- $via = 'uia'
2939
- $done = Invoke-Control $element
2940
- if (-not $done) { $via = 'ancestor'; $done = Invoke-ControlOrAncestor $element }
2941
- if (-not $done) {
2942
- $name = $label
2943
- try { $current = ([string]$element.Current.Name).Trim(); if ($current) { $name = $current } } catch {}
2944
- if ($name) { Assert-BackgroundAction; $via = 'msaa'; $done = [ChromiumMsaa]::InvokeNamed($script:boundHandle, [string[]]@($name)) }
2945
- # After Advanced, a background page can show the Zortex warning link to UIA before Chrome's MSAA tree
2946
- # has it. Ask Chrome for its accessibility tree again, as the UIA rules do, then press it by name once
2947
- # it is the only such control.
2948
- if (-not $done -and [string]$name -cin @(Get-GoogleWarningControlNames)) {
2949
- $until = [DateTime]::UtcNow.AddSeconds(6)
2950
- while (-not $done -and [DateTime]::UtcNow -lt $until) {
2951
- Request-ChromiumPageAccessibility $script:boundHandle
2952
- Start-Sleep -Milliseconds 500
2953
- if ([ChromiumMsaa]::CountNamed($script:boundHandle, [string[]]@($name)) -eq 1) {
2954
- Assert-BackgroundAction; $via = 'msaa-refreshed'; $done = [ChromiumMsaa]::InvokeNamed($script:boundHandle, [string[]]@($name))
2955
- }
2956
- }
2957
- }
2958
- }
2959
- if (-not $done) {
2960
- # Diagnostic codes only: control type and the press methods it offers, never its name.
2961
- $kinds = @()
2962
- try {
2963
- foreach ($pair in @(@('invoke', [Windows.Automation.InvokePattern]::Pattern), @('toggle', [Windows.Automation.TogglePattern]::Pattern),
2964
- @('select', [Windows.Automation.SelectionItemPattern]::Pattern), @('expand', [Windows.Automation.ExpandCollapsePattern]::Pattern))) {
2965
- if ($null -ne (Get-Pattern $element $pair[1])) { $kinds += $pair[0] }
2966
- }
2967
- $msaa = -1; try { $msaa = [ChromiumMsaa]::CountNamed($script:boundHandle, [string[]]@($name)) } catch {}
2968
- $known = [int]([string]$name -cin @(Get-GoogleWarningControlNames))
2969
- $script:SessionDetail = "no_press_method patterns=$($kinds -join '+') refound=$([int]($null -ne $now.page)) msaa=$msaa known=$known len=$(([string]$name).Length)"
2970
- } catch { $script:SessionDetail = "no_press_method error=$($_.Exception.GetBaseException().GetType().Name) line=$($_.InvocationInfo.ScriptLineNumber) page=$([int]($null -ne $now.page)) byId=$([int]($null -ne $byId)) byName=$($byName.Count) label=$([int][bool]$label) type=$([int]($null -ne $type))" }
2971
- }
2972
- if ($done) { $script:SessionPressedUrl = [string]$script:ReadUrl }
2973
- Write-SessionAnswer @{ ok = $true; done = [bool]$done; via = $via }
2974
- }
2975
- 'scroll' {
2976
- # UI Automation ScrollPattern on the page's document: Chrome scrolls the page itself, the window is never
2977
- # activated. available: the document offers the pattern; scrollable: the page is taller than the window.
2978
- $moved = $false; $available = $false; $scrollable = $false
2979
- if ($null -ne $script:SessionDocument) {
2980
- $scroll = Get-Pattern $script:SessionDocument ([Windows.Automation.ScrollPattern]::Pattern)
2981
- $available = $null -ne $scroll
2982
- $scrollable = $available -and $scroll.Current.VerticallyScrollable
2983
- if ($scrollable -and $scroll.Current.VerticalScrollPercent -lt 99.9) {
2984
- $before = $scroll.Current.VerticalScrollPercent
2985
- $scroll.Scroll([Windows.Automation.ScrollAmount]::NoAmount, [Windows.Automation.ScrollAmount]::LargeIncrement)
2986
- Start-Sleep -Milliseconds 150
2987
- $moved = $scroll.Current.VerticalScrollPercent -gt $before
2988
- }
2989
- }
2990
- Write-SessionAnswer @{ ok = $true; moved = $moved; available = $available; scrollable = [bool]$scrollable }
2991
- }
2992
- 'reveal' {
2993
- $found = Get-SessionWindow
2994
- $done = $false
2995
- if ($null -ne $found) {
2996
- $script:RevealPages.Remove("$(([uri]$found.snapshot.Url).AbsoluteUri)|page") | Out-Null
2997
- $done = Test-StuckPageRecovery $found.window.handle ([DateTime]::MinValue) ([DateTime]::MinValue) ([uri]$found.snapshot.Url)
2998
- }
2999
- Write-SessionAnswer @{ ok = $true; done = [bool]$done }
3000
- }
3001
- 'close' {
3002
- if ($opened) { Close-OwnedBrowser 'completed'; $script:OwnedBrowserHandle = [IntPtr]::Zero }
3003
- $opened = $false
3004
- Write-SessionAnswer @{ ok = $true }
3005
- }
3006
- default { Write-SessionAnswer @{ ok = $false; reason = 'unknown_command' } }
3007
- }
3008
- } catch {
3009
- $message = [string]$_.Exception.Message
3010
- if ($message -match '^([a-z_]{1,64})') { $script:SessionDetail = $Matches[1] }
3011
- # Ownership, guard and cancellation failures end the session: the window is closed and the guard stopped.
3012
- if ($message -match '^background_(guard|window|position|browser|renderer)' -or $message -match '^invalid_browser_profile') {
3013
- $reason = $(if ($message -ceq 'background_renderer_unresolved') { $message } else { 'background_session_stopped' })
3014
- Write-Result @{ state = 'failed'; reason = $reason } 1
3015
- }
3016
- Write-SessionAnswer @{ ok = $false; reason = $(if ($message -match '^jev:([a-z_]{1,64})$') { $Matches[1] } else { 'automation_error' }) }
3017
- }
3018
- }
3019
- Write-Result @{ state = 'completed'; reason = 'session_closed' }
3020
- }
3021
-
3022
- # The address of the bound tab now: Chrome's own tab record when the background guard runs, else the page reader.
3023
- function Get-TabAddress($Window) {
3024
- try {
3025
- if ($script:BackgroundGuardStarted) {
3026
- $id = $script:BackgroundIdentity
3027
- $snapshot = [OAuthBackground]::Snapshot($Window.handle, $id.Pid, $id.Tid, $script:BackgroundNonce)
3028
- if (-not $snapshot.Complete -or $snapshot.Tabs -ne 1) { return $null }
3029
- return [uri]$snapshot.Url
3030
- }
3031
- $read = Get-Page $Window.element
3032
- if ($null -eq $read) { return $null }
3033
- return $read.url
3034
- } catch { if (Test-BackgroundGuardException $_) { throw }; return $null }
3035
- }
3036
-
3037
- function Test-FreshActionable($Element) {
3038
- if (Get-Variable BackgroundGuardStarted -Scope Script -ValueOnly -ErrorAction SilentlyContinue) { Assert-BackgroundAction }
3039
- try {
3040
- $rect = $Element.Current.BoundingRectangle
3041
- return $Element.Current.IsEnabled -and -not $Element.Current.IsOffscreen -and
3042
- -not $rect.IsEmpty -and $rect.Width -gt 0 -and $rect.Height -gt 0
3043
- } catch { return $false }
3044
- }
3045
-
3046
- $script:OAuthTrace = [Collections.Generic.List[string]]::new()
3047
- try {
3048
- $request = ([Console]::In.ReadLine() | ConvertFrom-Json)
3049
- if ($null -ne $request.PSObject.Properties['kind'] -and $request.kind -ceq 'site-read') {
3050
- $cancellation = [ZortexNativeWindow]::ReadCancellation()
3051
- Invoke-SiteRead $request
3052
- }
3053
- if ($null -ne $request.PSObject.Properties['kind'] -and $request.kind -ceq 'page-session') { Invoke-PageSession $request }
3054
- $script:Automatic = $null -ne $request.PSObject.Properties['automatic'] -and $request.automatic -eq $true
3055
- $script:NextDriver = $null -ne $request.PSObject.Properties['nextDriver'] -and $request.nextDriver -eq $true
3056
- $cancellation = [ZortexNativeWindow]::ReadCancellation()
3057
- if ($request.provider -notin @('google', 'microsoft', 'slack', 'notion')) { throw 'unsupported OAuth provider' }
3058
- $authorization = [uri]$request.authorizationUrl
3059
- $redirect = [uri]$request.redirectUri
3060
- $expectedState = [string]$request.state
3061
- $expectedClientId = [Web.HttpUtility]::ParseQueryString($authorization.Query).Get('client_id')
3062
- $requestedScopes = [Web.HttpUtility]::ParseQueryString($authorization.Query).Get('scope')
3063
- $isYouTube = $request.provider -eq 'google' -and 'https://www.googleapis.com/auth/youtube.readonly' -cin @($requestedScopes -split ' ')
3064
- $selectedGoogleEmail = ''
3065
- $uniqueGoogleEmail = ''
3066
- $delegationSelected = $false
3067
- $localState = $expectedState
3068
- if ($request.provider -eq 'notion') {
3069
- $expectedState = [string]$request.authorizationState
3070
- $expectedClientId = [string]$request.clientId
3071
- if ($expectedClientId -cne '3e2d872b-594c-81be-8038-00376fbca2ad' -or
3072
- $localState -cnotmatch '^[A-Za-z0-9_-]{43}$' -or $expectedState.Length -gt 12000 -or
3073
- $expectedState -cnotmatch '^n1\.state\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+$' -or
3074
- $authorization.Host -cne 'zortex-auth.pages.dev' -or $authorization.AbsolutePath -cne '/notion/authorize' -or
3075
- -not (Test-NotionTransaction $authorization $expectedClientId $expectedState) -or
3076
- $redirect.AbsoluteUri -cnotmatch '^http://127\.0\.0\.1:[1-9][0-9]{0,4}/notion/callback$') { throw 'invalid Notion handoff' }
3077
- }
3078
-
3079
- $timeoutMs = [int]$request.timeoutMs
3080
- $discoverAccounts = $null -ne $request.PSObject.Properties['discoverAccounts'] -and [bool]$request.discoverAccounts
3081
- $accountIndex = $(if ($null -ne $request.PSObject.Properties['accountIndex']) { [int]$request.accountIndex } else { -1 })
3082
- $accountEmail = $(if ($null -ne $request.PSObject.Properties['account']) { [string]$request.account.Trim().ToLowerInvariant() } else { '' })
3083
- if ($accountIndex -ge 0 -and $accountEmail.Length -gt 0) { throw 'choose either an account index or exact account email' }
3084
- if ($accountEmail.Length -gt 0 -and $accountEmail -cnotmatch '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$') { throw 'invalid account email' }
3085
- if ($authorization.Scheme -ne 'https' -or -not (Test-AllowedOrigin $request.provider $authorization $redirect)) { throw 'authorization origin is not allowlisted' }
3086
- if ($expectedState.Length -lt 16 -or [string]::IsNullOrWhiteSpace($expectedClientId) -or $timeoutMs -lt 1000 -or $timeoutMs -gt 900000) { throw 'invalid state, client, or timeout' }
3087
-
3088
- $deadline = [DateTime]::UtcNow.AddMilliseconds($timeoutMs)
3089
- if (Test-Cancellation $cancellation) { Write-Result @{ state = 'failed'; reason = 'cancelled' } 1 }
3090
- $knownHandles = [Collections.Generic.HashSet[string]]::new()
3091
- foreach ($window in @(Get-BrowserWindows)) { $knownHandles.Add("$($window.handle)") | Out-Null }
3092
- if (Test-Cancellation $cancellation) { Write-Result @{ state = 'failed'; reason = 'cancelled' } 1 }
3093
- Start-OAuthBrowser $authorization $request.provider
3094
- $acted = [Collections.Generic.HashSet[string]]::new()
3095
- $sawBrowser = $false
3096
- $pageCount = 0
3097
- $lastNamedCount = 0
3098
- $lastAccountCount = 0
3099
- $lastConsentCount = 0
3100
- $lastScopeToggleCount = 0
3101
- $lastNoticeId = 'none'
3102
- $lastPageKind = 'none'
3103
- $chooserPages = 0
3104
- $lastVisibleEmailCount = 0
3105
- $lastNames = @()
3106
- $boundHandle = [IntPtr]::Zero
3107
- $boundTab = $null
3108
- $selectedRequestedAccount = $false
3109
- $msPickAttempts = 0
3110
- $msPickedAt = [DateTime]::MinValue
3111
- $observedGoogleAccounts = $false
3112
- $pageHiddenSince = $null
3113
- $pageHiddenNudgedAt = [DateTime]::MinValue
3114
- $pageRevealedAt = $null
3115
- $chooserUnresolvedSince = $null
3116
- $consentStuckKey = ''
3117
- $consentStuckSince = $null
3118
- $observe = ($env:ZORTEX_OAUTH_OBSERVE -eq '1')
3119
- $observeLog = $env:ZORTEX_OAUTH_OBSERVE_LOG
3120
- $observeSeen = @{}
3121
- $consentAttempts = @{}
3122
- $consentClickedAt = @{}
3123
- $consentStuckNudgedAt = [DateTime]::MinValue
3124
- $tabMismatchSince = $null
3125
- $notionSelection = $null
3126
- $notionRefresh = $null
3127
-
3128
- while ([DateTime]::UtcNow -lt $deadline) {
3129
- Assert-BackgroundGuard
3130
- if ([ZortexNativeWindow]::IsForeground($script:OwnedBrowserHandle)) { $script:ForegroundObserved = $true }
3131
- if (Test-Cancellation $cancellation) { Write-Result @{ state = 'failed'; reason = 'cancelled' } 1 }
3132
- foreach ($window in @(Get-BrowserWindows)) {
3133
- try {
3134
- $sawBrowser = $true
3135
- if ($boundHandle -ne [IntPtr]::Zero -and $window.handle -ne $boundHandle) { continue }
3136
- $id = $script:BackgroundIdentity
3137
- $chromeSnapshot = [OAuthBackground]::Snapshot($window.handle, $id.Pid, $id.Tid, $script:BackgroundNonce)
3138
- if (-not $chromeSnapshot.Complete -or $chromeSnapshot.Tabs -ne 1) { continue }
3139
- $chromeUrl = [uri]$chromeSnapshot.Url
3140
- if (-not (Test-AllowedOrigin $request.provider $chromeUrl $redirect)) { continue }
3141
- if (-not [string]::IsNullOrWhiteSpace($boundTab) -and $chromeSnapshot.Tab -cne $boundTab) {
3142
- $chromeQuery = [Web.HttpUtility]::ParseQueryString($chromeUrl.Query)
3143
- $sameTransaction = $(if ($request.provider -eq 'notion') { Test-NotionTransaction $chromeUrl $expectedClientId $expectedState } else { Test-OAuthTransaction $chromeQuery $expectedClientId $expectedState })
3144
- if (-not $sameTransaction) { Write-Result @{ state = 'ui_drift'; reason = 'tab_changed' } 1 }
3145
- }
3146
- $nativePage = New-Object OAuthBackground+Stats
3147
- if ([OAuthBackground]::Read([ref]$nativePage) -ne 0) { continue }
3148
- if ($nativePage.Renderer -eq 0) { Resolve-BackgroundRenderer $window.handle $chromeSnapshot.Tab $chromeUrl; continue }
3149
- $script:RendererMissingSince = $null
3150
- $script:ReadGeneration = $nativePage.Generation
3151
- $script:ReadUrl = $chromeUrl.AbsoluteUri
3152
- $script:ReadTab = $chromeSnapshot.Tab
3153
- [OAuthBackground]::ConfigurePage($window.handle, $id.Pid, $id.Tid, $script:BackgroundNonce, $script:ReadTab, $script:ReadUrl, $script:ReadGeneration)
3154
- try { $page = Get-Page $window.element } catch { continue }
3155
- if ($null -eq $page -or -not (Test-AllowedOrigin $request.provider $page.url $redirect)) {
3156
- # Diagnostic: an off-allowlist host on the tab this flow owns is exactly where an
3157
- # unmapped provider step hides; record host+path only (no query, no controls).
3158
- if ($null -ne $page -and $boundHandle -ne [IntPtr]::Zero -and -not [string]::IsNullOrEmpty($observeLog)) {
3159
- $offKey = "off:$($page.url.Host)$($page.url.AbsolutePath)"
3160
- if (-not $observeSeen.ContainsKey($offKey)) { $observeSeen[$offKey] = $true; try { Add-Content -Path $observeLog -Value "=== OFF-ALLOWLIST $($page.url.Host)$($page.url.AbsolutePath) ===" -Encoding UTF8 } catch {} }
3161
- }
3162
- continue
3163
- }
3164
- $pageQuery = [Web.HttpUtility]::ParseQueryString($page.url.Query)
3165
- if (Test-CallbackAddress $page.url $redirect) {
3166
- if ($boundHandle -eq [IntPtr]::Zero -and $knownHandles.Contains("$($window.handle)")) { continue }
3167
- if ($boundHandle -eq [IntPtr]::Zero) {
3168
- $boundHandle = $window.handle
3169
- $boundTab = Get-SelectedTabIdentity $window.element
3170
- Register-OwnedBrowser $window.handle $true
3171
- }
3172
- if (($accountIndex -ge 0 -or $accountEmail.Length -gt 0) -and -not $selectedRequestedAccount) { Write-Result @{ state = 'ui_drift'; reason = 'requested_account_not_selected' } 1 }
3173
- $callbackResult = $(if ($request.provider -eq 'notion') { Get-NotionCallbackResult $page.url $redirect $localState } else { Get-OAuthCallbackResult $page.url $redirect $expectedState })
3174
- Write-Result $callbackResult $(if ($callbackResult.state -eq 'failed') { 1 } else { 0 })
3175
- }
3176
- $transactionMatches = $(if ($request.provider -eq 'notion') { Test-NotionTransaction $page.url $expectedClientId $expectedState } else { Test-OAuthTransaction $pageQuery $expectedClientId $expectedState })
3177
- if ($boundHandle -eq [IntPtr]::Zero) {
3178
- $isKnownWindow = $knownHandles.Contains("$($window.handle)")
3179
- if (-not $transactionMatches) { continue }
3180
- $boundHandle = $window.handle
3181
- $boundTab = Get-SelectedTabIdentity $window.element
3182
- if ([string]::IsNullOrWhiteSpace($boundTab)) { Write-Result @{ state = 'failed'; reason = 'tab_identity_missing' } 1 }
3183
- Register-OwnedBrowser $boundHandle (-not $isKnownWindow)
3184
- $script:OwnedTransactionBound = $true
3185
- } elseif ($window.handle -ne $boundHandle) { continue }
3186
- $currentTab = Get-SelectedTabIdentity $window.element
3187
- $tabBinding = Resolve-TabBinding $currentTab $boundTab $transactionMatches $tabMismatchSince ([DateTime]::UtcNow) 4000
3188
- if ($tabBinding.action -eq 'fail') { Write-Result @{ state = 'failed'; reason = 'tab_changed' } 1 }
3189
- elseif ($tabBinding.action -eq 'wait') {
3190
- # A transient navigation can drop the selected tab or its query for one poll. Do not act
3191
- # on an unverified tab; re-observe until it settles or the window elapses.
3192
- if ($null -eq $tabMismatchSince) { $tabMismatchSince = [DateTime]::UtcNow }
3193
- continue
3194
- }
3195
- $boundTab = $tabBinding.boundTab
3196
- $tabMismatchSince = $null
3197
- $pageClientId = $pageQuery.Get('client_id')
3198
- if (-not [string]::IsNullOrWhiteSpace($pageClientId) -and $pageClientId -ne $expectedClientId) { Write-Result @{ state = 'failed'; reason = 'transaction_mismatch' } 1 }
3199
- $pageState = $pageQuery.Get('state')
3200
- if (-not [string]::IsNullOrWhiteSpace($pageState) -and $pageState -ne $expectedState) { Write-Result @{ state = 'failed'; reason = 'state_mismatch' } 1 }
3201
- $pageCount += 1
3202
- $lastPageKind = $(if ($page.url.AbsolutePath -ceq '/v3/signin/accountchooser') { 'chooser' }
3203
- elseif ($page.url.AbsolutePath -match '^/signin/oauth/v2/consent') { 'consent' }
3204
- elseif ($page.url.AbsolutePath -match '^/signin/(v2/)?identifier') { 'identifier' }
3205
- elseif ($page.url.AbsolutePath -ceq '/o/oauth2/v2/auth') { 'oauth_entry' }
3206
- else { 'other' })
3207
- if ($request.provider -eq 'google' -and $env:ZORTEX_JEV_UIA_MODE -ne '1' -and
3208
- $page.url.Host -eq 'accounts.google.com' -and $page.url.AbsolutePath -eq '/o/oauth2/v2/auth') {
3209
- $submitKey = "$($page.url.AbsoluteUri)|submit-auth-url"
3210
- if ((Test-OAuthForeground) -and $acted.Add($submitKey)) {
3211
- try { [System.Windows.Forms.SendKeys]::SendWait('{ENTER}') } catch {}
3212
- Start-Sleep -Milliseconds 500
3213
- continue
3214
- }
3215
- }
3216
- if ($request.provider -eq 'google' -and $page.url.Host -eq 'accounts.google.com' -and $page.url.AbsolutePath -match '^/signin/oauth/v2/consentsummary') {
3217
- $scrollKey = "$($page.url.AbsoluteUri)|consent-scroll"
3218
- if ((Test-OAuthForeground) -and $acted.Add($scrollKey)) {
3219
- try { [System.Windows.Forms.SendKeys]::SendWait('{END}') } catch {}
3220
- Start-Sleep -Milliseconds 300
3221
- }
3222
- }
3223
-
3224
- if (Test-PageContentMissing $page.documents) {
3225
- # Never act on browser-chrome names. Wait for the page and ask Chrome
3226
- # for the tree every few seconds, then stop with a reason.
3227
- if ($null -eq $pageHiddenSince) { $pageHiddenSince = [DateTime]::UtcNow }
3228
- # Each reveal shows the page for a moment and restarts the wait above; bound the whole time one address stays hidden.
3229
- if (-not $script:HiddenFirstAt.ContainsKey($page.url.AbsoluteUri)) { $script:HiddenFirstAt[$page.url.AbsoluteUri] = [DateTime]::UtcNow }
3230
- $reveal = Request-BackgroundPage $window.handle $boundTab $page.url $pageHiddenSince
3231
- if ($reveal -eq 'revealed') { Add-OAuthTrace $page.url.AbsolutePath 'page-hidden' 'background-reveal'; $pageRevealedAt = [DateTime]::UtcNow; continue }
3232
- # The page navigated while it was being revealed (the provider moved on): observe the new page.
3233
- if ($reveal -in @('stale', 'changed_after_restore')) { Add-OAuthTrace $page.url.AbsolutePath 'page-hidden' 'reveal-moved'; continue }
3234
- # A reveal that left a fully occluded renderer hidden is repeated, 8 s apart, up to 3 times per page.
3235
- if ($reveal -eq 'already_attempted' -and $null -ne $pageRevealedAt -and ([DateTime]::UtcNow - $pageRevealedAt).TotalMilliseconds -ge 8000) {
3236
- $retryKey = $page.url.AbsoluteUri
3237
- $done = [int]$script:RevealRetries[$retryKey]
3238
- if ($done -lt 2) { $script:RevealRetries[$retryKey] = $done + 1; $script:RevealPages.Remove("$retryKey|page") | Out-Null }
3239
- $pageRevealedAt = $null
3240
- }
3241
- if ($reveal -notin @('waiting', 'waiting_renderer', 'already_attempted')) {
3242
- Write-Result @{ state = 'ui_drift'; reason = "background_page_reveal_$reveal" } 1
3243
- }
3244
- if (Test-StuckPageRecovery $window.handle $pageHiddenSince $pageHiddenNudgedAt $page.url) {
3245
- $pageHiddenNudgedAt = [DateTime]::UtcNow
3246
- Add-OAuthTrace $page.url.AbsolutePath 'page-hidden' 'nudge'
3247
- }
3248
- if (-not (Test-StillSettling $pageHiddenSince ([DateTime]::UtcNow) 45000) -or
3249
- -not (Test-StillSettling $script:HiddenFirstAt[$page.url.AbsoluteUri] ([DateTime]::UtcNow) 75000)) {
3250
- Write-Result @{ state = 'ui_drift'; reason = "page_accessibility_unavailable top=$($page.topDocuments) render=$($page.renderDocuments) root=$($page.renderExists) offscreen=$($page.renderOffscreen) elements=$($page.renderElements) win=$($page.lookup.window) widget=$($page.lookup.renderer) allWidgets=$($page.lookup.allWidgets) visibleWidgets=$($page.lookup.visibleWidgets) woff=$($page.lookup.offscreen) stage=$($page.lookup.stage) hr=$($page.lookup.error) trace=$(Format-OAuthTrace)" } 1
3251
- }
3252
- continue
3253
- }
3254
- Update-BackgroundRendererWait $page.url $true ([DateTime]::UtcNow)
3255
- $pageHiddenSince = $null
3256
- $pageHiddenNudgedAt = [DateTime]::MinValue
3257
- $script:ActionUrl = $page.url.AbsoluteUri
3258
- $script:ActionGeneration = $nativePage.Generation
3259
- Assert-BackgroundAction
3260
-
3261
- $named = @(Get-NamedPageControls $page.elements)
3262
- $lastNamedCount = $named.Count
3263
- $script:DiagnosticNamed = $named
3264
- $script:DiagnosticRoot = $window.handle
3265
- if (-not $observe -and -not [string]::IsNullOrEmpty($observeLog)) {
3266
- # Drive-and-trace: same redacted page record as observe mode, but the driver still acts.
3267
- $traceKey = "trace:$($page.url.AbsolutePath)#$($named.Count)"
3268
- if (-not $observeSeen.ContainsKey($traceKey)) { $observeSeen[$traceKey] = $true; Add-ObserveSnapshot $observeLog $request.provider $page.url $named }
3269
- }
3270
- if ($observe) {
3271
- # Record each distinct page (URL + redacted controls). The only action taken is
3272
- # selecting the already-signed-in account (safe: it picks an account, grants nothing),
3273
- # so the flow reaches and records the consent page without a human; consent is never
3274
- # clicked here.
3275
- $sawBrowser = $true
3276
- $observeKey = "$($page.url.AbsolutePath)#$($named.Count)"
3277
- if (-not $observeSeen.ContainsKey($observeKey)) {
3278
- $observeSeen[$observeKey] = $true
3279
- Add-ObserveSnapshot $observeLog $request.provider $page.url $named
3280
- }
3281
- if ($request.provider -eq 'microsoft' -and -not $selectedRequestedAccount) {
3282
- $obsRow = Select-MicrosoftPersonalAccountRow $named
3283
- if ($null -ne $obsRow -and (Invoke-ControlOrAncestor $obsRow.element)) { $selectedRequestedAccount = $true; Start-Sleep -Milliseconds 400 }
3284
- }
3285
- continue
3286
- }
3287
- $lastNames = @($named | Select-Object -First 40 | ForEach-Object {
3288
- try {
3289
- $element = $_['element']
3290
- $name = [string]($_['name'])
3291
- $rect = $element.Current.BoundingRectangle
3292
- "$name @ $([int]$rect.Left),$([int]$rect.Top),$([int]$rect.Width),$([int]$rect.Height)"
3293
- } catch { try { [string]($_['name']) } catch { "" } }
3294
- })
3295
- if ($request.provider -eq 'google' -and $page.url.AbsolutePath -ceq '/signin/oauth/delegation') {
3296
- # This is a channel identity choice, not the generic Google account picker.
3297
- # Preserve the selected Google identity; never guess a name-only Brand account.
3298
- if ($delegationSelected) { continue }
3299
- # The Google account is the requested one, else the only one the chooser offered, else the only address this page
3300
- # shows (Google skipped the chooser). A Brand account shows a name only and is never picked.
3301
- $delegationEmail = @($selectedGoogleEmail, $uniqueGoogleEmail, (Get-UniqueGoogleEmail @() $named)) |
3302
- Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -First 1
3303
- if (-not $isYouTube -or [string]::IsNullOrWhiteSpace($delegationEmail) -or
3304
- -not (Test-YouTubeDelegationPage $page.url $requestedScopes $named)) {
3305
- Write-Result @{ state = 'multiple_accounts'; reason = 'youtube_delegation_requires_account_selection' } 1
3306
- }
3307
- $primary = Select-YouTubePrimaryAccount $named $delegationEmail
3308
- if ($null -eq $primary) { Write-Result @{ state = 'multiple_accounts'; reason = 'youtube_primary_account_not_unique' } 1 }
3309
- Confirm-JevControl 'account' 'account:youtube-primary' 'account' $accountIndex | Out-Null
3310
- # Re-read the bound tab and exact transaction URL before using any element.
3311
- $freshTab = Get-SelectedTabIdentity $window.element
3312
- try { $freshPage = Get-Page $window.element } catch { $freshPage = $null }
3313
- if ($freshTab -cne $boundTab -or $null -eq $freshPage -or $freshPage.url.AbsoluteUri -cne $page.url.AbsoluteUri) {
3314
- Write-Result @{ state = 'ui_drift'; reason = 'youtube_delegation_changed' } 1
3315
- }
3316
- $freshNamed = @(Get-NamedPageControls $freshPage.elements)
3317
- $freshPrimary = Select-YouTubePrimaryAccount $freshNamed $delegationEmail
3318
- if (-not (Test-YouTubeDelegationPage $freshPage.url $requestedScopes $freshNamed) -or
3319
- $null -eq $freshPrimary -or
3320
- $freshPrimary.name -cne $primary.name -or -not (Test-FreshActionable $freshPrimary.element)) {
3321
- Write-Result @{ state = 'ui_drift'; reason = 'youtube_delegation_changed' } 1
3322
- }
3323
- if (-not (Invoke-Control $freshPrimary.element)) {
3324
- # Pressing the row can navigate before UI Automation returns, so the press reads as failed and the row is gone
3325
- # (zh-CN, 2026-10-22: no patterns left, no MSAA row). A page that moved on was pressed; the loop reads the next one.
3326
- # The page reader refuses a page it was not configured for, so the address comes from the tab itself.
3327
- $afterPress = $null
3328
- for ($look = 0; $look -lt 6 -and $null -eq $afterPress; $look++) {
3329
- Start-Sleep -Milliseconds 500
3330
- $afterPress = Get-TabAddress $window
3331
- }
3332
- $movedOn = $null -ne $afterPress -and $afterPress.AbsolutePath -cne '/signin/oauth/delegation'
3333
- # Still on the page: Chrome's MSAA tree presses the same row by its address, as on the account chooser.
3334
- if (-not $movedOn -and -not ([ChromiumMsaa]::InvokeAccountByEmail($window.handle, $delegationEmail))) {
3335
- $patterns = try { @($freshPrimary.element.GetSupportedPatterns() | ForEach-Object { $_.ProgrammaticName -replace 'PatternIdentifiers\.Pattern$', '' }) -join ',' } catch { 'unreadable' }
3336
- $where = $(if ($null -eq $afterPress) { 'unread' } else { 'delegation' })
3337
- Write-Result @{ state = 'ui_drift'; reason = "youtube_primary_account_not_actionable page=$where uia=[$patterns] msaa=[$([ChromiumMsaa]::AccountInvokeDiagnostic())]" } 1
3338
- }
3339
- }
3340
- $delegationSelected = $true
3341
- Add-OAuthTrace $page.url.AbsolutePath 'account' 'uia'
3342
- Start-Sleep -Milliseconds 300
3343
- continue
3344
- }
3345
- $isAccountChooser = Test-AccountChooserPage $named $page.url.AbsolutePath
3346
- if ($isAccountChooser) { $chooserPages += 1 }
3347
- if ($request.provider -eq 'google' -and (Test-GoogleAccountChooserPendingNavigation $isAccountChooser $selectedRequestedAccount)) {
3348
- # Invoke already succeeded for the exact requested row. Let the bound tab
3349
- # navigate; a stale chooser snapshot must not trigger a second selection.
3350
- continue
3351
- }
3352
- $lastAccountCount = [ChromiumMsaa]::AccountCount($window.handle)
3353
- $msaaEmails = @(if ($isAccountChooser) { [ChromiumMsaa]::AccountEmails($window.handle) })
3354
- $accountRows = $(if ($isAccountChooser) { Get-GoogleAccountRows $named } else { @{ rows = @(); ambiguous = $false } })
3355
- $accountCandidates = @(if ($isAccountChooser) {
3356
- foreach ($candidate in @($named | Where-Object { ([string]$_.name) -match '@' })) {
3357
- $actionable = $false
3358
- try {
3359
- $actionable = $null -ne (Get-Pattern $candidate.element ([Windows.Automation.InvokePattern]::Pattern)) -or
3360
- $null -ne (Get-Pattern $candidate.element ([Windows.Automation.SelectionItemPattern]::Pattern)) -or
3361
- $null -ne (Get-LegacyPattern $candidate.element)
3362
- } catch {}
3363
- @{ name = [string]$candidate.name; actionable = $actionable }
3364
- }
3365
- })
3366
- $msaaEmails = @(Select-UsableGoogleMsaaEmails $msaaEmails $accountCandidates)
3367
- $visibleEmails = @(Get-GoogleVisibleAccountEmails $accountCandidates)
3368
- $lastVisibleEmailCount = $visibleEmails.Count
3369
- if ($request.provider -eq 'google' -and $isAccountChooser) {
3370
- if (Test-GoogleAccountChooserLoading $observedGoogleAccounts $visibleEmails.Count $accountRows.rows.Count $msaaEmails.Count $lastAccountCount) {
3371
- continue
3372
- }
3373
- $observedGoogleAccounts = $true
3374
- }
3375
- if ($discoverAccounts -and $isAccountChooser) {
3376
- # Chrome can repeat unrelated identity text in its UIA tree. Require
3377
- # exact agreement between the independent actionable UIA rows and the
3378
- # MSAA account rows, instead of counting every email-like text node.
3379
- if (-not $accountRows.ambiguous -and (Test-GoogleAccountEvidenceAgreement $msaaEmails $accountRows.rows)) {
3380
- Write-Result @{ state = 'accounts'; accounts = $msaaEmails }
3381
- }
3382
- if ($msaaEmails.Count -gt 0 -and ($visibleEmails.Count -eq 0 -or
3383
- (@($msaaEmails | Where-Object { $_ -notin $visibleEmails }).Count -eq 0 -and $msaaEmails.Count -eq $visibleEmails.Count))) {
3384
- Write-Result @{ state = 'accounts'; accounts = $msaaEmails }
3385
- }
3386
- if (-not $accountRows.ambiguous -and $accountRows.rows.Count -gt 0 -and $accountRows.rows.Count -eq $visibleEmails.Count) {
3387
- Write-Result @{ state = 'accounts'; accounts = @($accountRows.rows | ForEach-Object { $_.email }) }
3388
- }
3389
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1' -and $msaaEmails.Count -eq 0 -and
3390
- -not $accountRows.ambiguous -and $accountRows.rows.Count -gt 0) {
3391
- # Chromium sometimes omits MSAA rows while UIA still exposes the
3392
- # actionable chooser rows. Accept only an identical second UIA read
3393
- # from the same bound tab and OAuth URL.
3394
- Start-Sleep -Milliseconds 200
3395
- $freshChooser = Get-FreshJevPage $boundHandle $boundTab $page.url $request.provider $redirect $expectedClientId $expectedState
3396
- $freshRows = Get-GoogleAccountRows $freshChooser.named
3397
- $before = @($accountRows.rows | ForEach-Object { $_.email })
3398
- $after = @($freshRows.rows | ForEach-Object { $_.email })
3399
- if (-not $freshRows.ambiguous -and $after.Count -eq $before.Count -and
3400
- (($after -join '|') -ceq ($before -join '|')) -and
3401
- (Test-AccountChooserPage $freshChooser.named $freshChooser.page.url.AbsolutePath) -and
3402
- @($freshRows.rows | Where-Object { -not (Test-FreshActionable $_.element) }).Count -eq 0) {
3403
- Write-Result @{ state = 'accounts'; accounts = $after }
3404
- }
3405
- }
3406
- if ($null -eq $chooserUnresolvedSince) { $chooserUnresolvedSince = [DateTime]::UtcNow }
3407
- if (Test-StillSettling $chooserUnresolvedSince ([DateTime]::UtcNow) 5000) { continue }
3408
- # Counts only: enough to diagnose a changing accessibility tree without
3409
- # putting account names, addresses, or the authorization URL in logs.
3410
- $identityReason = "account_chooser_identity_unreliable msaa=$($msaaEmails.Count) visible=$($visibleEmails.Count) rows=$($accountRows.rows.Count) ambiguous=$($accountRows.ambiguous) named=$($named.Count)"
3411
- Write-Result @{ state = 'ui_drift'; reason = $identityReason } 1
3412
- }
3413
- if ($request.provider -eq 'microsoft' -and $msPickAttempts -lt 3 -and
3414
- (-not $selectedRequestedAccount -or ([DateTime]::UtcNow - $msPickedAt).TotalMilliseconds -gt 3000)) {
3415
- # Choose an available account and retry while the chooser remains visible.
3416
- $msChoices = @(Get-MicrosoftAccountChoices $named)
3417
- if ($msChoices.Count -gt 0) {
3418
- $msChoice = Select-MicrosoftPersonalAccount $msChoices
3419
- if ($null -eq $msChoice) { continue }
3420
- $msInvoked = Invoke-ControlOrAncestor $msChoice['element']
3421
- if ($msInvoked) {
3422
- $selectedRequestedAccount = $true
3423
- $msPickAttempts += 1
3424
- $msPickedAt = [DateTime]::UtcNow
3425
- Start-Sleep -Milliseconds 400
3426
- continue
3427
- }
3428
- }
3429
- }
3430
- if ($request.provider -eq 'notion') {
3431
- # Signed out of Notion, install-integration sends the page to app.notion.com/login (2026-10-21).
3432
- # Same-URL picker/section updates can be missing from an occluded AX
3433
- # tree after the action is delivered. Refresh once per recorded action;
3434
- # never repeat it or select a new page to compensate for a stale tree.
3435
- if ($null -ne $notionRefresh -and $notionRefresh.page -ceq $page.url.AbsoluteUri) {
3436
- $reveal = Request-BackgroundPage $window.handle $boundTab $page.url $notionRefresh.since $notionRefresh.phase
3437
- if ($reveal -eq 'revealed') {
3438
- $notionSelection = $null
3439
- Add-OAuthTrace $page.url.AbsolutePath 'consent-stuck' 'background-reveal'; continue
3440
- }
3441
- }
3442
- # Notion hides previously selected pages under its collapsed Private section.
3443
- # Expand that section only; expanding does not change a checkbox or grant.
3444
- $sectionExpanded = $false
3445
- $privateKey = "$($page.url.AbsoluteUri)|notion:private"
3446
- foreach ($item in $named) {
3447
- if ($acted.Contains($privateKey)) { break }
3448
- if (-not (Test-NotionNamedControl $item 'ControlType.Button')) { continue }
3449
- try {
3450
- $expansion = Get-Pattern $item['element'] ([Windows.Automation.ExpandCollapsePattern]::Pattern)
3451
- if ($null -eq $expansion -or -not (Test-NotionPageSection ([string]$item['name']) ([string]$expansion.Current.ExpandCollapseState))) { continue }
3452
- $fresh = Get-Page $window.element
3453
- if ($null -eq $fresh -or $fresh.url.AbsoluteUri -cne $page.url.AbsoluteUri -or
3454
- (Get-SelectedTabIdentity $window.element) -cne $boundTab -or -not (Test-FreshActionable $item['element'])) { break }
3455
- # Re-check state after verifying this is still the owned authorization tab.
3456
- if ([string]$expansion.Current.ExpandCollapseState -ceq 'Collapsed') {
3457
- Assert-BackgroundAction
3458
- $expansion.Expand(); $acted.Add($privateKey) | Out-Null
3459
- $notionSelection = $null
3460
- $notionRefresh = @{ page = $page.url.AbsoluteUri; phase = 'notion-private'; since = [DateTime]::UtcNow }
3461
- $script:BackgroundPageFirstSeen["$($page.url.AbsoluteUri)|notion-private"] = $notionRefresh.since
3462
- Add-OAuthTrace $page.url.AbsolutePath 'other' 'uia'
3463
- $sectionExpanded = $true; break
3464
- }
3465
- } catch { if (Test-BackgroundGuardException $_) { throw } }
3466
- }
3467
- if ($sectionExpanded) { Start-Sleep -Milliseconds 200; continue }
3468
- # Reuse an existing selection; select an available page if this connection needs one.
3469
- $selectedPages = Get-NotionSelectedPageCount $page.elements
3470
- $hasSelectedPages = Test-NotionSelectionEvidence $selectedPages $named
3471
- $invoked = $false
3472
- foreach ($item in $named) {
3473
- if (-not (Test-NotionNamedControl $item 'ControlType.Button')) { continue }
3474
- $action = Get-NotionConsentAction ([string]$item['name']) $hasSelectedPages
3475
- if (-not $action) { continue }
3476
- $key = "$($page.url.AbsoluteUri)|notion:$action"
3477
- if ($acted.Contains($key)) { continue }
3478
- $fresh = Get-Page $window.element
3479
- if ($null -eq $fresh -or $fresh.url.AbsoluteUri -cne $page.url.AbsoluteUri -or
3480
- (Get-SelectedTabIdentity $window.element) -cne $boundTab) { break }
3481
- $freshNamed = @(Get-NamedPageControls $fresh.elements)
3482
- $freshConsent = Get-NotionFreshConsent $fresh.elements $freshNamed ([string]$item['name']) $action
3483
- $selectedPages = $freshConsent.selectedPages
3484
- $hasSelectedPages = $freshConsent.hasSelectedPages
3485
- if ($null -ne $freshConsent.target -and (Invoke-Control $freshConsent.target)) {
3486
- $acted.Add($key) | Out-Null; $invoked = $true; Add-OAuthTrace $page.url.AbsolutePath 'consent' 'uia'; break
3487
- }
3488
- }
3489
- if ($invoked -and $action -ceq 'picker') {
3490
- $notionSelection = $null
3491
- $notionRefresh = @{ page = $page.url.AbsoluteUri; phase = 'notion-picker'; since = [DateTime]::UtcNow }
3492
- $script:BackgroundPageFirstSeen["$($page.url.AbsoluteUri)|notion-picker"] = $notionRefresh.since
3493
- }
3494
- $hasAllowButton = @($named | Where-Object {
3495
- (Test-NotionNamedControl $_ 'ControlType.Button') -and (Get-NotionConsentAction ([string]$_['name']) $true) -eq 'allow'
3496
- }).Count -gt 0
3497
- $notionSelection = Resolve-NotionSelection $hasSelectedPages $hasAllowButton $page.url.AbsoluteUri $notionSelection ([DateTime]::UtcNow)
3498
- if (-not $invoked -and $notionSelection.action -eq 'needs_selection') {
3499
- $script:ConsentDiagnostic = Get-ConsentDiagnostic $named $window.handle $request.provider $lastNamedCount 0 $selectedPages
3500
- $fresh = Get-Page $window.element
3501
- if ($null -eq $fresh -or $fresh.url.AbsoluteUri -cne $page.url.AbsoluteUri -or
3502
- (Get-SelectedTabIdentity $window.element) -cne $boundTab) { continue }
3503
- foreach ($element in $fresh.elements) {
3504
- try {
3505
- if (-not (Test-FreshActionable $element) -or
3506
- [string]$element.Current.ControlType.ProgrammaticName -cne 'ControlType.CheckBox') { continue }
3507
- $toggle = Get-Pattern $element ([Windows.Automation.TogglePattern]::Pattern)
3508
- if ($null -ne $toggle -and [string]$toggle.Current.ToggleState -ceq 'Off') {
3509
- Assert-BackgroundAction
3510
- $toggle.Toggle(); $notionSelection = $null; $invoked = $true
3511
- Add-OAuthTrace $page.url.AbsolutePath 'consent' 'uia'
3512
- break
3513
- }
3514
- } catch { if (Test-BackgroundGuardException $_) { throw } }
3515
- }
3516
- if (-not $invoked) { Write-Result @{ state = 'ui_drift'; reason = 'notion_page_control_unavailable' } 1 }
3517
- }
3518
- # Never fall through to another provider's generic consent selectors.
3519
- continue
3520
- }
3521
- if ($discoverAccounts) {
3522
- if ($page.url.AbsolutePath -match '^/signin/oauth') { Write-Result @{ state = 'ui_drift'; reason = 'account_chooser_not_shown' } 1 }
3523
- continue
3524
- }
3525
- if (($accountIndex -ge 0 -or $accountEmail.Length -gt 0) -and -not $selectedRequestedAccount -and -not $isAccountChooser) {
3526
- if ($page.url.AbsolutePath -match '^/signin/oauth') { Write-Result @{ state = 'ui_drift'; reason = 'requested_account_chooser_not_shown' } 1 }
3527
- # Never approve an unknown consent layout before the requested row was selected.
3528
- continue
3529
- }
3530
- if ($request.provider -eq 'google' -and $isAccountChooser -and $accountIndex -lt 0 -and $accountEmail.Length -eq 0 -and (Test-GoogleAccountAmbiguity $lastAccountCount $named)) {
3531
- $accountIndex = 0
3532
- }
3533
- $accountInvoked = $false
3534
- if ($accountEmail.Length -gt 0 -and $isAccountChooser) {
3535
- $row = @($accountRows.rows | Where-Object { $_.email -ceq $accountEmail })
3536
- $selected = $false
3537
- Confirm-JevControl 'account' 'account:requested' 'account' $accountIndex | Out-Null
3538
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1') {
3539
- $fresh = Get-FreshJevPage $boundHandle $boundTab $page.url $request.provider $redirect $expectedClientId $expectedState
3540
- $named = $fresh.named
3541
- if (-not (Test-AccountChooserPage $named $fresh.page.url.AbsolutePath)) {
3542
- Write-Result @{ state = 'ui_drift'; reason = 'jev_account_chooser_changed' } 1
3543
- }
3544
- $accountRows = Get-GoogleAccountRows $named
3545
- $row = @($accountRows.rows | Where-Object { $_.email -ceq $accountEmail })
3546
- $msaaEmails = @([ChromiumMsaa]::AccountEmails($boundHandle))
3547
- if ($accountRows.ambiguous -or ($row.Count -ne 1 -and @($msaaEmails | Where-Object { $_ -ceq $accountEmail }).Count -ne 1)) {
3548
- Write-Result @{ state = 'ui_drift'; reason = 'jev_requested_account_changed' } 1
3549
- }
3550
- }
3551
- # Prefer the visible unique UIA row observed in this bound page. A later
3552
- # MSAA tree walk can miss it even when the earlier enumeration saw it.
3553
- if (-not $accountRows.ambiguous -and $row.Count -eq 1 -and ($env:ZORTEX_JEV_UIA_MODE -ne '1' -or (Test-FreshActionable $row[0].element))) { $selected = Invoke-GoogleAccountRow $row[0] }
3554
- elseif (@($msaaEmails | Where-Object { $_ -ceq $accountEmail }).Count -eq 1) { $selected = [ChromiumMsaa]::InvokeAccountByEmail($window.handle, $accountEmail) }
3555
- if (-not $selected) {
3556
- if ($null -eq $chooserUnresolvedSince) { $chooserUnresolvedSince = [DateTime]::UtcNow }
3557
- if (Test-StillSettling $chooserUnresolvedSince ([DateTime]::UtcNow) 5000) { continue }
3558
- $failureReason = Get-RequestedAccountRowFailureReason $named $accountEmail $accountRows.rows.Count $row.Count $accountRows.ambiguous $msaaEmails.Count ($msaaEmails -contains $accountEmail) $selected
3559
- Write-Result @{ state = 'ui_drift'; reason = $failureReason } 1
3560
- }
3561
- $accountInvoked = $true
3562
- $selectedRequestedAccount = $true
3563
- $selectedGoogleEmail = $accountEmail
3564
- }
3565
- elseif ($request.provider -eq 'google' -and $accountIndex -ge 0 -and $isAccountChooser) {
3566
- # UIA row identity and the actual clicked element must come from the same
3567
- # snapshot. MSAA AccountCount and AccountEmails can settle independently.
3568
- $orderedRows = @($accountRows.rows | Sort-Object { $_.element.Current.BoundingRectangle.Top })
3569
- $candidate = $(if (-not $accountRows.ambiguous -and $orderedRows.Count -gt $accountIndex) { $orderedRows[$accountIndex] } else { $null })
3570
- $stable = $false
3571
- if ($null -ne $candidate) {
3572
- Confirm-JevControl 'account' "account:$accountIndex" 'account' $accountIndex | Out-Null
3573
- $freshTab = Get-SelectedTabIdentity $window.element
3574
- try { $freshPage = Get-Page $window.element } catch { $freshPage = $null }
3575
- if ($freshTab -ceq $boundTab -and $null -ne $freshPage -and $freshPage.url.AbsoluteUri -ceq $page.url.AbsoluteUri) {
3576
- $freshNamed = @(Get-NamedPageControls $freshPage.elements)
3577
- $freshRows = Get-GoogleAccountRows $freshNamed
3578
- $orderedFresh = @($freshRows.rows | Sort-Object { $_.element.Current.BoundingRectangle.Top })
3579
- $stable = -not $freshRows.ambiguous -and $orderedFresh.Count -eq $orderedRows.Count -and
3580
- (@($orderedFresh | ForEach-Object { $_.email }) -join '|') -ceq (@($orderedRows | ForEach-Object { $_.email }) -join '|') -and
3581
- (Test-AccountChooserPage $freshNamed $freshPage.url.AbsolutePath)
3582
- if ($stable) {
3583
- $candidate = $orderedFresh[$accountIndex]
3584
- $stable = (Test-FreshActionable $candidate.element) -and (Invoke-GoogleAccountRow $candidate)
3585
- }
3586
- }
3587
- }
3588
- if (-not $stable) {
3589
- if ($null -eq $chooserUnresolvedSince) { $chooserUnresolvedSince = [DateTime]::UtcNow }
3590
- if (Test-StillSettling $chooserUnresolvedSince ([DateTime]::UtcNow) 5000) { continue }
3591
- Write-Result @{ state = 'ui_drift'; reason = "requested_account_identity_unavailable rows=$($orderedRows.Count) ambiguous=$($accountRows.ambiguous) uia=[$script:AccountUiaActionDiagnostic]" } 1
3592
- }
3593
- $selectedGoogleEmail = [string]$candidate.email
3594
- $accountInvoked = $true
3595
- $selectedRequestedAccount = $true
3596
- }
3597
- elseif ($accountIndex -lt 0 -and $request.provider -eq 'google' -and $isAccountChooser -and $lastAccountCount -eq 1) {
3598
- Confirm-JevControl 'account' 'account:0' 'account' | Out-Null
3599
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1') {
3600
- $fresh = Get-FreshJevPage $boundHandle $boundTab $page.url $request.provider $redirect $expectedClientId $expectedState
3601
- $freshEmails = @([ChromiumMsaa]::AccountEmails($boundHandle))
3602
- if (-not (Test-AccountChooserPage $fresh.named $fresh.page.url.AbsolutePath) -or
3603
- [ChromiumMsaa]::AccountCount($boundHandle) -ne 1 -or
3604
- $msaaEmails.Count -ne 1 -or $freshEmails.Count -ne 1 -or $freshEmails[0] -cne $msaaEmails[0]) {
3605
- Write-Result @{ state = 'ui_drift'; reason = 'jev_unique_account_changed' } 1
3606
- }
3607
- }
3608
- if ([ChromiumMsaa]::InvokeAccount($window.handle, 0)) { $accountInvoked = $true; $uniqueGoogleEmail = Get-UniqueGoogleEmail $msaaEmails $named }
3609
- }
3610
- elseif ($accountIndex -lt 0 -and $request.provider -eq 'google' -and $isAccountChooser -and $lastAccountCount -eq 0) {
3611
- Confirm-JevControl 'account' 'account:unique' 'account' | Out-Null
3612
- $jevUniqueAccountTarget = $null
3613
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1') {
3614
- $fresh = Get-FreshJevPage $boundHandle $boundTab $page.url $request.provider $redirect $expectedClientId $expectedState
3615
- if (-not (Test-AccountChooserPage $fresh.named $fresh.page.url.AbsolutePath) -or [ChromiumMsaa]::AccountCount($boundHandle) -ne 0) {
3616
- Write-Result @{ state = 'ui_drift'; reason = 'jev_unique_account_changed' } 1
3617
- }
3618
- $oldCandidates = @($named | Where-Object { Test-GoogleAccountCandidate ([string]$_.name) } | ForEach-Object { [string]$_.name } | Sort-Object -Unique)
3619
- $newCandidates = @($fresh.named | Where-Object { Test-GoogleAccountCandidate ([string]$_.name) -and (Test-FreshActionable $_.element) } | ForEach-Object { [string]$_.name } | Sort-Object -Unique)
3620
- if ($oldCandidates.Count -ne 1 -or $newCandidates.Count -ne 1 -or $oldCandidates[0] -cne $newCandidates[0]) {
3621
- Write-Result @{ state = 'ui_drift'; reason = 'jev_unique_account_changed' } 1
3622
- }
3623
- $seenTargets = [Collections.Generic.HashSet[string]]::new()
3624
- $targets = @($fresh.named | Where-Object { [string]$_.name -ceq $newCandidates[0] -and (Test-FreshActionable $_.element) } |
3625
- Where-Object { $seenTargets.Add(($_.element.GetRuntimeId() -join '.')) })
3626
- if ($targets.Count -ne 1) { Write-Result @{ state = 'ui_drift'; reason = 'jev_unique_account_changed' } 1 }
3627
- $jevUniqueAccountTarget = $targets[0].element
3628
- }
3629
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1') {
3630
- if (Invoke-Control $jevUniqueAccountTarget) { $accountInvoked = $true }
3631
- else { Write-Result @{ state = 'ui_drift'; reason = 'jev_unique_account_not_actionable' } 1 }
3632
- } elseif (Invoke-GoogleAccountCandidate $named) { $accountInvoked = $true }
3633
- if ($accountInvoked) { $uniqueGoogleEmail = Get-UniqueGoogleEmail $msaaEmails $named }
3634
- }
3635
- if ($accountInvoked) { Add-OAuthTrace $page.url.AbsolutePath 'account' 'helper'; Start-Sleep -Milliseconds 300; continue }
3636
-
3637
- if ($request.provider -eq 'google' -and $env:ZORTEX_JEV_UIA_MODE -eq '1') {
3638
- $approvedConsent = Test-JevApprovedConsentTest $expectedClientId $named $page.url.AbsolutePath $lastNoticeId
3639
- if ((Test-JevGoogleUnverified $named) -and -not $approvedConsent) {
3640
- $notice = Get-JevTestNoticeAction $named
3641
- if ($null -eq $notice -or -not $acted.Add("$($page.url.AbsoluteUri)|$($notice.id)")) {
3642
- $candidate = $(if ($null -eq $notice) { 'none' } else { $notice.id })
3643
- $advanced = @($named | Where-Object { [string]$_.name -match '(?i)^Advanced$|^Show advanced|\u9032\u968e|\u9ad8\u7ea7' }).Count
3644
- $zortex = @($named | Where-Object { [string]$_.name -match '(?i)Zortex.*(?:unsafe|\u4e0d\u5b89\u5168)' }).Count
3645
- $heading = @($named | Where-Object { [string]$_.name -match '(?i)^Zortex\s+(?:wants|\u8981\u6c42|\u8bf7\u6c42|\u60f3)' }).Count
3646
- $pageClass = $(if ($page.url.AbsolutePath -match 'error|blocked') { 'error' }
3647
- elseif ($page.url.AbsolutePath -match 'consent') { 'consent' }
3648
- elseif ($page.url.AbsolutePath -match 'signin/oauth') { 'oauth_other' }
3649
- else { 'other' })
3650
- $blocked = @($named | Where-Object { [string]$_.name -match '(?i)access blocked|this app is blocked|has not completed.*verification|\u5b58\u53d6\u5df2\u88ab\u5c01\u9396|\u5df2\u5c01\u9396|\u5df2\u963b\u6b62|\u9a57\u8b49\u7a0b\u5e8f' }).Count
3651
- $allow = @($named | Where-Object { [string]$_.name -cin @(Get-JevGoogleConsentControlNames) }).Count
3652
- $appMentions = @($named | Where-Object { [string]$_.name -match '(?i)\bZortex\b' }).Count
3653
- $visibleApp = @($named | Where-Object { [string]$_['kind'] -ceq 'current_name' -and [bool]$_['visible'] -and [string]$_.name -match '(?i)\bZortex\b' }).Count
3654
- $visibleWarning = @($named | Where-Object {
3655
- [string]$_['kind'] -ceq 'current_name' -and [bool]$_['visible'] -and
3656
- ([string]$_.name -match '(?i)hasn.t verified this app|isn.t verified|unverified app|go to zortex \(unsafe\)|\u672a\u7d93 Google \u9a57\u8b49|\u672a\u7ecf Google \u9a8c\u8bc1|\u4e0d\u5b89\u5168' -or
3657
- [string]$_.name -cin @(Get-GoogleWarningControlNames))
3658
- }).Count
3659
- $visibleAllow = @($named | Where-Object { [string]$_['kind'] -ceq 'current_name' -and [bool]$_['visible'] -and [string]$_.name -cin @(Get-JevGoogleConsentControlNames) }).Count
3660
- Write-Result @{ state = 'ui_drift'; reason = "jev_test_notice_control_unavailable last=$lastNoticeId current=$candidate page=$pageClass advanced=$advanced zortex=$zortex heading=$heading blocked=$blocked allow=$allow app=$appMentions visibleApp=$visibleApp visibleWarning=$visibleWarning visibleAllow=$visibleAllow named=$($named.Count)" } 1
3661
- }
3662
- Confirm-JevControl 'notice' $notice.id $notice.role | Out-Null
3663
- $fresh = Get-FreshJevPage $boundHandle $boundTab $page.url $request.provider $redirect $expectedClientId $expectedState
3664
- if (-not (Test-JevApprovedUnverifiedTest $expectedClientId $fresh.named $fresh.page.url.AbsolutePath)) {
3665
- Write-Result @{ state = 'ui_drift'; reason = 'jev_test_notice_changed' } 1
3666
- }
3667
- $target = Get-JevTestNoticeAction $fresh.named
3668
- if ($null -eq $target -or $target.id -cne $notice.id -or $target.name -cne $notice.name) {
3669
- Write-Result @{ state = 'ui_drift'; reason = 'jev_test_notice_changed' } 1
3670
- }
3671
- $invoked = $false
3672
- if ($target.id -ceq 'notice:continue' -and
3673
- [ChromiumMsaa]::CountNamed($boundHandle, [string[]]@($target.name)) -eq 1) {
3674
- $invoked = [ChromiumMsaa]::InvokeNamed($boundHandle, [string[]]@($target.name))
3675
- } else { $invoked = Invoke-Control $target.element }
3676
- if (-not $invoked) { Write-Result @{ state = 'ui_drift'; reason = 'jev_test_notice_not_actionable' } 1 }
3677
- $lastNoticeId = $notice.id
3678
- Start-Sleep -Milliseconds 300
3679
- continue
3680
- }
3681
- }
3682
-
3683
- if ($request.provider -eq 'google') {
3684
- $scopeConsentNames = @('Select all', ([string][char]0x5168 + [string][char]0x9009), ([string][char]0x5168 + [string][char]0x9078))
3685
- $scopeConsentKey = "$($page.url.AbsoluteUri)|scope-select-all"
3686
- if (-not $acted.Contains($scopeConsentKey) -and [ChromiumMsaa]::CountNamed($window.handle, [string[]]$scopeConsentNames) -gt 0) {
3687
- Confirm-JevControl 'scope' 'scope:all' 'scope-all' | Out-Null
3688
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1') {
3689
- $fresh = Get-FreshJevPage $boundHandle $boundTab $page.url $request.provider $redirect $expectedClientId $expectedState
3690
-
3691
- if ([ChromiumMsaa]::CountNamed($boundHandle, [string[]]$scopeConsentNames) -ne 1) {
3692
- Write-Result @{ state = 'ui_drift'; reason = 'jev_scope_control_changed' } 1
3693
- }
3694
- }
3695
- $acted.Add($scopeConsentKey) | Out-Null
3696
- if ([ChromiumMsaa]::InvokeNamed($window.handle, [string[]]$scopeConsentNames)) {
3697
- $lastScopeToggleCount += 1
3698
- Start-Sleep -Milliseconds 300
3699
- continue
3700
- }
3701
- }
3702
- Confirm-JevControl 'scope' 'scope:toggle' 'scope-toggle' | Out-Null
3703
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1') {
3704
- $fresh = Get-FreshJevPage $boundHandle $boundTab $page.url $request.provider $redirect $expectedClientId $expectedState
3705
-
3706
- $toggled = Invoke-GoogleScopeControls $fresh.page.elements $true
3707
- } else { $toggled = Invoke-GoogleScopeControls $page.elements }
3708
- if ($toggled -gt 0) {
3709
- $lastScopeToggleCount += $toggled
3710
- Start-Sleep -Milliseconds 300
3711
- continue
3712
- }
3713
- }
3714
-
3715
- # "Advanced" toggles the notice; a second press on one page hides the approved continue link.
3716
- $advancedKey = "$($page.url.AbsolutePath)|notice-advanced"
3717
- $advancedDone = $request.provider -eq 'google' -and $acted.Contains($advancedKey)
3718
- $consentInvoked = $false
3719
- foreach ($candidate in $named) {
3720
- if (-not (Test-ConsentControl $request.provider $candidate.name)) { continue }
3721
- $category = Get-OAuthClickCategory ([string]$candidate.name)
3722
- if ($advancedDone -and $category -eq 'advanced') { continue }
3723
- $target = $candidate.element
3724
- if ($request.provider -eq 'google') {
3725
- Confirm-JevControl 'consent' 'consent:approve' 'consent' | Out-Null
3726
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1') {
3727
- $fresh = Get-FreshJevPage $boundHandle $boundTab $page.url $request.provider $redirect $expectedClientId $expectedState
3728
-
3729
- $seenTargets = [Collections.Generic.HashSet[string]]::new()
3730
- $targets = @($fresh.named | Where-Object { [string]$_.name -ceq [string]$candidate.name -and (Test-ConsentControl $request.provider $_.name) -and (Test-FreshActionable $_.element) } |
3731
- Where-Object { $seenTargets.Add(($_.element.GetRuntimeId() -join '.')) })
3732
- if ($targets.Count -ne 1) { Write-Result @{ state = 'ui_drift'; reason = 'jev_consent_control_changed' } 1 }
3733
- $target = $targets[0].element
3734
- }
3735
- }
3736
- if ($request.provider -ne 'google') {
3737
- # Live (personal MSA, account.live.com/Consent/Update): pressing Accept every poll kept
3738
- # re-submitting the form before its navigation committed, so the page never left. After
3739
- # a press, let the page navigate (up to 6s) before pressing again; if it is still the same
3740
- # page, escalate the press method: UIA Invoke ->
3741
- # MSAA default action.
3742
- $consentKey = $page.url.AbsoluteUri
3743
- if ($consentClickedAt.ContainsKey($consentKey) -and ([DateTime]::UtcNow - $consentClickedAt[$consentKey]).TotalMilliseconds -lt 6000) { $consentInvoked = $true; break }
3744
- $attempt = $(if ($consentAttempts.ContainsKey($consentKey)) { [int]$consentAttempts[$consentKey] } else { 0 })
3745
- $consentAttempts[$consentKey] = $attempt + 1
3746
- $method = @('uia-invoke', 'msaa')[$attempt % 2]
3747
- $invoked = switch ($method) {
3748
- 'uia-invoke' { Invoke-Control $target }
3749
- default { [ChromiumMsaa]::InvokeNamed($window.handle, [string[]]@([string]$candidate.name)) }
3750
- }
3751
- $consentClickedAt[$consentKey] = [DateTime]::UtcNow
3752
- if (-not [string]::IsNullOrEmpty($observeLog)) {
3753
- try { Add-Content -Path $observeLog -Value (" >> consent press '{0}' via {1} (attempt {2}) invoked={3}" -f (Format-ObserveName ([string]$candidate.name)), $method, ($attempt + 1), $invoked) -Encoding UTF8 } catch {}
3754
- }
3755
- if ($invoked) { Add-OAuthTrace $page.url.AbsolutePath $category $method; $consentInvoked = $true; break }
3756
- continue
3757
- }
3758
- $invoked = $(if ($env:ZORTEX_JEV_UIA_MODE -eq '1') { Invoke-Control $target } else { Invoke-ControlOrAncestor $target })
3759
- if ($invoked) {
3760
- if ($request.provider -eq 'google' -and $category -eq 'advanced') { $acted.Add($advancedKey) | Out-Null }
3761
- Add-OAuthTrace $page.url.AbsolutePath $category 'uia'
3762
- $consentInvoked = $true; Start-Sleep -Milliseconds 300; break
3763
- }
3764
- }
3765
- # One press per observed page: the page this loop checked can be gone after any press.
3766
- if ($consentInvoked) { continue }
3767
- $consentNames = $(if ($request.provider -eq 'google') {
3768
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1') { Get-JevGoogleConsentControlNames } else { Get-GoogleClickableConsentNames $advancedDone }
3769
- } else { @('Accept', 'Yes', 'Continue', 'Allow', ([string][char]0x63a5 + [string][char]0x53d7), ([string][char]0x662f), ([string][char]0x7ee7 + [string][char]0x7eed), ([string][char]0x5141 + [string][char]0x8bb8), ([string][char]0x5141 + [string][char]0x8a31)) })
3770
- $lastConsentCount = [ChromiumMsaa]::CountNamed($window.handle, [string[]]$consentNames)
3771
- if ($request.provider -eq 'google' -and $lastConsentCount -gt 0) {
3772
- Confirm-JevControl 'consent' 'consent:approve' 'consent' | Out-Null
3773
- if ($env:ZORTEX_JEV_UIA_MODE -eq '1') {
3774
- $fresh = Get-FreshJevPage $boundHandle $boundTab $page.url $request.provider $redirect $expectedClientId $expectedState
3775
-
3776
- if ([ChromiumMsaa]::CountNamed($boundHandle, [string[]]$consentNames) -ne 1) {
3777
- Write-Result @{ state = 'ui_drift'; reason = 'jev_consent_control_changed' } 1
3778
- }
3779
- }
3780
- }
3781
- # MSAA presses whatever is rendered now, so first confirm the address is still the observed page.
3782
- # Jev mode has already re-read and bound this exact page above.
3783
- $samePage = $env:ZORTEX_JEV_UIA_MODE -eq '1'
3784
- if (-not $samePage) {
3785
- $current = $null
3786
- try { $current = Get-Page $window.element } catch {}
3787
- $samePage = $null -ne $current -and $current.url.AbsoluteUri -ceq $page.url.AbsoluteUri
3788
- }
3789
- if ($samePage -and [ChromiumMsaa]::InvokeNamed($window.handle, [string[]]$consentNames)) {
3790
- $category = Get-OAuthClickCategory ([ChromiumMsaa]::LastInvoked)
3791
- if ($request.provider -eq 'google' -and $category -eq 'advanced') { $acted.Add($advancedKey) | Out-Null }
3792
- Add-OAuthTrace $page.url.AbsolutePath $category 'msaa'
3793
- Start-Sleep -Milliseconds 300
3794
- continue
3795
- }
3796
- if ($acted.Count -gt 12) { Write-Result @{ state = 'ui_drift'; reason = "action_limit trace=$(Format-OAuthTrace)" } 1 }
3797
- # Stuck on a recognised Google consent/warning page with no actionable control this pass:
3798
- # Chrome can leave the expanded notice's continue link (and the Allow button) out of the
3799
- # accessibility tree for a while after a click. Wait, then ask Chrome to rebuild the tree
3800
- # once; if it still never exposes a control, stop with a specific reason rather than a
3801
- # blind timeout. A read-only nudge: it clicks nothing.
3802
- if ($request.provider -eq 'google' -and -not $isAccountChooser -and
3803
- $page.url.AbsolutePath -cmatch '^/signin/oauth(?:/|$)') {
3804
- if ($consentStuckKey -cne $page.url.AbsoluteUri) {
3805
- $consentStuckKey = $page.url.AbsoluteUri
3806
- $consentStuckSince = [DateTime]::UtcNow
3807
- $consentStuckNudgedAt = [DateTime]::MinValue
3808
- }
3809
- $refreshPhase = $(if ($advancedDone -and $page.url.AbsolutePath -ceq '/signin/oauth/warning') { 'advanced' } else { 'page' })
3810
- if (Test-StuckPageRecovery $window.handle $consentStuckSince $consentStuckNudgedAt $page.url $refreshPhase) {
3811
- $consentStuckNudgedAt = [DateTime]::UtcNow
3812
- Add-OAuthTrace $page.url.AbsolutePath 'consent-stuck' 'nudge'
3813
- }
3814
- if (-not (Test-StillSettling $consentStuckSince ([DateTime]::UtcNow) 45000)) {
3815
- $script:ConsentDiagnostic = Get-ConsentDiagnostic $script:DiagnosticNamed $script:DiagnosticRoot $request.provider $lastNamedCount $lastConsentCount $lastScopeToggleCount
3816
- Write-Result @{ state = 'ui_drift'; reason = "consent_control_unavailable trace=$(Format-OAuthTrace)" } 1
3817
- }
3818
- } else {
3819
- $consentStuckKey = ''
3820
- $consentStuckSince = $null
3821
- $consentStuckNudgedAt = [DateTime]::MinValue
3822
- }
3823
- } catch {
3824
- if (Test-BackgroundNavigationDrift $_.Exception.Message) { continue }
3825
- throw
3826
- }
3827
- }
3828
- Start-Sleep -Milliseconds 250
3829
- }
3830
- $reason = "timeout windows=$sawBrowser pages=$pageCount kind=$lastPageKind chooser=$chooserPages named=$lastNamedCount visible=$lastVisibleEmailCount accounts=$lastAccountCount consent=$lastConsentCount scopes=$lastScopeToggleCount trace=$(Format-OAuthTrace)"
3831
- $script:ConsentDiagnostic = Get-ConsentDiagnostic $script:DiagnosticNamed $script:DiagnosticRoot $request.provider $lastNamedCount $lastConsentCount $lastScopeToggleCount
3832
- if ($env:ZORTEX_OAUTH_DEBUG_NAMES -eq '1') { $debugReason = "$reason names=$($lastNames -join ' || ')"; Write-Result @{ state = $(if ($sawBrowser) { 'ui_drift' } else { 'browser_unsupported' }); reason = $debugReason; names = $lastNames } 1 }
3833
- Write-Result @{ state = $(if ($sawBrowser) { 'ui_drift' } else { 'browser_unsupported' }); reason = $reason } 1
3834
- } catch {
3835
- $backgroundReason = $_.Exception.GetBaseException().Message
3836
- if ($backgroundReason -cmatch '^background_[a-z_]+(?: [a-zA-Z]+=-?[0-9]+)*$') {
3837
- Write-Result @{ state = 'ui_drift'; reason = $backgroundReason } 1
3838
- }
3839
- Write-Result @{ state = 'failed'; reason = "helper_error:$($_.Exception.GetType().Name):line$($_.InvocationInfo.ScriptLineNumber)" } 1
3840
- }