@capagents/forgeqe 3.1.1 → 3.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/HOW_TO_USE.md +5152 -1869
  2. package/README.md +155 -434
  3. package/THIRD_PARTY_NOTICES.md +210 -1
  4. package/dist/docs-site/CREDITS.md +6 -0
  5. package/dist/docs-site/architecture-map/index.html +1 -1
  6. package/dist/docs-site/docs/app-theme.css +126 -13
  7. package/dist/docs-site/docs/architecture/index.html +56 -530
  8. package/dist/docs-site/docs/architecture-reference/index.html +1781 -0
  9. package/dist/docs-site/docs/area-api/index.html +491 -0
  10. package/dist/docs-site/docs/area-automated-tests/index.html +1777 -0
  11. package/dist/docs-site/docs/area-browser/index.html +472 -0
  12. package/dist/docs-site/docs/area-data/index.html +595 -0
  13. package/dist/docs-site/docs/area-desktop/index.html +802 -0
  14. package/dist/docs-site/docs/area-mobile/index.html +683 -0
  15. package/dist/docs-site/docs/area-operations/index.html +1243 -0
  16. package/dist/docs-site/docs/area-pull-requests/index.html +290 -0
  17. package/dist/docs-site/docs/area-quality/index.html +427 -0
  18. package/dist/docs-site/docs/area-release/index.html +435 -0
  19. package/dist/docs-site/docs/area-setup/index.html +1595 -0
  20. package/dist/docs-site/docs/area-systems/index.html +191 -0
  21. package/dist/docs-site/docs/area-test-cases/index.html +927 -0
  22. package/dist/docs-site/docs/containers/index.html +168 -189
  23. package/dist/docs-site/docs/cost-architecture/index.html +110 -113
  24. package/dist/docs-site/docs/custom-agents-first-run/index.html +121 -67
  25. package/dist/docs-site/docs/desktop/index.html +363 -373
  26. package/dist/docs-site/docs/desktop-ci/index.html +39 -36
  27. package/dist/docs-site/docs/docs-tabs.js +56 -0
  28. package/dist/docs-site/docs/evidence/index.html +297 -300
  29. package/dist/docs-site/docs/feature-test-prompts/index.html +79 -73
  30. package/dist/docs-site/docs/get-started/index.html +791 -0
  31. package/dist/docs-site/docs/graphify/index.html +45 -48
  32. package/dist/docs-site/docs/guardrails/index.html +35 -23
  33. package/dist/docs-site/docs/index.html +18 -6729
  34. package/dist/docs-site/docs/mobile/index.html +223 -210
  35. package/dist/docs-site/docs/model-routing/index.html +84 -65
  36. package/dist/docs-site/docs/overview/index.html +192 -0
  37. package/dist/docs-site/docs/product-graph/index.html +60 -62
  38. package/dist/docs-site/docs/product-knowledge/index.html +24 -17
  39. package/dist/docs-site/docs/product-views/index.html +57 -60
  40. package/dist/docs-site/docs/reference/index.html +409 -0
  41. package/dist/docs-site/docs/search.js +1 -1
  42. package/dist/docs-site/docs/using/index.html +798 -0
  43. package/dist/docs-site/docs/web-app/index.html +168 -111
  44. package/dist/docs-site/security/index.html +930 -0
  45. package/dist/docs-site/security/security-theme.css +161 -0
  46. package/dist/docs-site/security/security.js +1465 -0
  47. package/dist/docs-site/vendor/react-18.3.1.production.min.js +31 -0
  48. package/dist/docs-site/vendor/react-dom-18.3.1.production.min.js +267 -0
  49. package/dist/docs-site/vendor/reactflow-11.11.4.umd.js +10 -0
  50. package/dist/forgeqe.js +1903 -1896
  51. package/dist/web/THIRD_PARTY_NOTICES.md +0 -136
  52. package/dist/web/assets/Agent-3pV8Rwap.js +8 -0
  53. package/dist/web/assets/AgentWork-DAnmH0My.js +2 -0
  54. package/dist/web/assets/ApiTests-DW4MRFzG.js +10 -0
  55. package/dist/web/assets/Browse-Bd0ZZfc2.js +1 -0
  56. package/dist/web/assets/Chat-DnBUm_97.js +3 -0
  57. package/dist/web/assets/CommandPalette-B1O9aDTk.js +1 -0
  58. package/dist/web/assets/Compare-1v7_ca7z.js +1 -0
  59. package/dist/web/assets/Cost-CWrc4McH.js +1 -0
  60. package/dist/web/assets/Data-rWSiG4Cq.js +6 -0
  61. package/dist/web/assets/Desktop-3x6EQqos.js +1 -0
  62. package/dist/web/assets/DesktopReview-cSA10Rm3.js +1 -0
  63. package/dist/web/assets/Evidence-CKy3o7cw.js +1 -0
  64. package/dist/web/assets/Explore-CMAxWE_8.js +2 -0
  65. package/dist/web/assets/Features-haQchkhA.js +1 -0
  66. package/dist/web/assets/Flags-BaQjYi_t.js +2 -0
  67. package/dist/web/assets/Flaky-DUuC0qTn.js +1 -0
  68. package/dist/web/assets/Impact-CP0H8ygo.js +3 -0
  69. package/dist/web/assets/Jobs-cYxoYd3i.js +5 -0
  70. package/dist/web/assets/KindPage-DWW8gN5_.js +6 -0
  71. package/dist/web/assets/Migration-Bsm7WU1d.js +2 -0
  72. package/dist/web/assets/PageAgent-c95zT2PJ.js +1 -0
  73. package/dist/web/assets/Product-BQSiR28a.js +7 -0
  74. package/dist/web/assets/Production-CAv0Vtoy.js +1 -0
  75. package/dist/web/assets/Quality-aQPaPYQc.js +1 -0
  76. package/dist/web/assets/Readiness-CkknP87n.js +1 -0
  77. package/dist/web/assets/Record-09IsC9U-.js +1 -0
  78. package/dist/web/assets/Regression-BL4MfN47.js +5 -0
  79. package/dist/web/assets/RelationGraph-Dg4fqt7l.js +1 -0
  80. package/dist/web/assets/Reports-CMV1l-iS.js +2 -0
  81. package/dist/web/assets/Response-DTBFBeKB.js +9 -0
  82. package/dist/web/assets/Responsive-DBRQ9FUO.js +3 -0
  83. package/dist/web/assets/RunDiff-CMDrnsA3.js +1 -0
  84. package/dist/web/assets/Runs-Dkeu6_vZ.js +2 -0
  85. package/dist/web/assets/Settings-KjKm8h-_.js +21 -0
  86. package/dist/web/assets/Steps-HYHK9psI.js +2 -0
  87. package/dist/web/assets/TestCases-Cv6-OSv0.js +1 -0
  88. package/dist/web/assets/TestData-DbEfNlUE.js +2 -0
  89. package/dist/web/assets/TestDebt-DzHQIU4X.js +1 -0
  90. package/dist/web/assets/TestManagement-BgRTGHMT.js +1 -0
  91. package/dist/web/assets/Tosca-DZpHAtnH.js +3 -0
  92. package/dist/web/assets/WhatsNew-jp0c4WSV.js +1 -0
  93. package/dist/web/assets/agents-C0Jg2pN8.js +1 -0
  94. package/dist/web/assets/coverage-BB9BLjGz.js +5 -0
  95. package/dist/web/assets/dataParts-DEPK4eQE.js +3 -0
  96. package/dist/web/assets/diff-CcNwLCX6.js +2 -0
  97. package/dist/web/assets/families-gkpkloLT.js +1 -0
  98. package/dist/web/assets/filters-C7phIFfd.js +1 -0
  99. package/dist/web/assets/fold-i73P-EDV.js +1 -0
  100. package/dist/web/assets/head-BtTqyLlj.js +1 -0
  101. package/dist/web/assets/highlight-DZI39CzZ.js +4 -0
  102. package/dist/web/assets/index-ClFOh63x.css +2 -0
  103. package/dist/web/assets/index-YGWJEkAT.js +64 -0
  104. package/dist/web/assets/input-C2vQ9O3a.js +1 -0
  105. package/dist/web/assets/jsx-runtime-LKYXHABd.js +1 -0
  106. package/dist/web/assets/logos-BmbNTDu2.js +1 -0
  107. package/dist/web/assets/palette-XFlqvgZl.js +1 -0
  108. package/dist/web/assets/paletteCommands-DsbD2ASU.js +1 -0
  109. package/dist/web/assets/parts-DEVx2Sea.js +1 -0
  110. package/dist/web/assets/productParts-Bi-XjszL.js +1 -0
  111. package/dist/web/assets/qualityParts-Dbu01g7G.js +1 -0
  112. package/dist/web/assets/recordTest--Wr40QdN.js +1 -0
  113. package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  114. package/dist/web/assets/route-Dg53WdFu.js +1 -0
  115. package/dist/web/index.html +11 -6
  116. package/docs/ARCHITECTURE.md +50 -563
  117. package/docs/ARCHITECTURE_REFERENCE.md +1484 -0
  118. package/docs/BASAL.md +1 -1
  119. package/docs/CONTAINERS.md +87 -87
  120. package/docs/CUSTOM_AGENTS_FIRST_RUN.md +125 -43
  121. package/docs/DESKTOP-CI.md +18 -3
  122. package/docs/DESKTOP.md +306 -286
  123. package/docs/EVIDENCE.md +1 -1
  124. package/docs/MOBILE.md +107 -75
  125. package/docs/MODEL_ROUTING.md +48 -15
  126. package/docs/PRODUCT_KNOWLEDGE.md +2 -0
  127. package/docs/WEB_APP.md +143 -75
  128. package/docs/feature-test-prompts.md +29 -16
  129. package/docs/user-guide.html +5402 -2269
  130. package/forgeqe.example.yaml +3 -3
  131. package/guardrails/README.md +22 -2
  132. package/knowledge/README.md +15 -2
  133. package/package.json +1 -1
  134. package/prompts/brain.md +1 -0
  135. package/prompts/page-differs.md +1 -1
  136. package/prompts/requests-rule.md +1 -1
  137. package/prompts/test-reviewer.md +1 -1
  138. package/prompts/test-rules.md +3 -4
  139. package/py/forgeqe_engine/recordsession.py +100 -24
  140. package/skills/web-guidance/LICENSE +202 -0
  141. package/skills/web-guidance/SKILL.md +76 -0
  142. package/skills/web-guidance/UPSTREAM +67 -0
  143. package/skills/web-guidance/references/accessibility/accessibility.md +585 -0
  144. package/skills/web-guidance/references/accessibility/accessible-error-announcement.md +302 -0
  145. package/skills/web-guidance/references/accessibility/accessible-generated-content.md +41 -0
  146. package/skills/web-guidance/references/accessibility/respect-os-text-scale.md +127 -0
  147. package/skills/web-guidance/references/css/responsive-design.md +16 -0
  148. package/skills/web-guidance/references/forms/autofill-address-form.md +86 -0
  149. package/skills/web-guidance/references/forms/autofill-payment-form.md +142 -0
  150. package/skills/web-guidance/references/forms/autofill-sign-in-form.md +145 -0
  151. package/skills/web-guidance/references/forms/autofill-sign-up-form.md +155 -0
  152. package/skills/web-guidance/references/forms/forms.md +415 -0
  153. package/skills/web-guidance/references/forms/ime-safe-enter-submit.md +115 -0
  154. package/skills/web-guidance/references/forms/required-field-feedback.md +317 -0
  155. package/skills/web-guidance/references/forms/select-menu-interaction.md +310 -0
  156. package/skills/web-guidance/references/forms/slider.md +184 -0
  157. package/skills/web-guidance/references/forms/sms-otp-form.md +208 -0
  158. package/skills/web-guidance/references/forms/switch.md +60 -0
  159. package/skills/web-guidance/references/forms/validate-input-after-interaction.md +406 -0
  160. package/skills/web-guidance/references/performance/break-up-long-tasks.md +64 -0
  161. package/skills/web-guidance/references/performance/identify-heavy-scripts.md +69 -0
  162. package/skills/web-guidance/references/performance/identify-inp-causes.md +105 -0
  163. package/skills/web-guidance/references/performance/interaction-paint-timing.md +200 -0
  164. package/skills/web-guidance/references/performance/optimize-image-priority.md +73 -0
  165. package/skills/web-guidance/references/performance/performance.md +384 -0
  166. package/skills/web-guidance/references/privacy/privacy.md +247 -0
  167. package/skills/web-guidance/references/security/passkey-authentication.md +218 -0
  168. package/skills/web-guidance/references/security/passkey-management.md +310 -0
  169. package/skills/web-guidance/references/security/passkey-reauthentication.md +142 -0
  170. package/skills/web-guidance/references/security/passkey-registration.md +186 -0
  171. package/skills/web-guidance/references/security/passkeys.md +39 -0
  172. package/skills/web-guidance/references/security/sanitize-untrusted-html.md +105 -0
  173. package/skills/web-guidance/references/security/secure-external-subresources.md +202 -0
  174. package/skills/web-guidance/references/security/security.md +390 -0
  175. package/skills/web-guidance/references/security/trusted-types.md +141 -0
  176. package/skills/web-guidance/references/security/validate-origins.md +197 -0
  177. package/skills/web-guidance/references/security/verify-email-ownership.md +235 -0
  178. package/skills/web-guidance/references/ui-atoms/position-aware-tooltips.md +173 -0
  179. package/skills/web-guidance/references/ui-atoms/responsive-table.md +122 -0
  180. package/skills/web-guidance/references/ui-atoms/viewport-aware-dropdowns.md +178 -0
  181. package/skills/web-guidance/references/ui-behaviors/drag-and-drop.md +108 -0
  182. package/skills/web-guidance/references/ui-behaviors/light-dismiss-a-dialog.md +89 -0
  183. package/skills/web-guidance/references/ui-behaviors/motion.md +97 -0
  184. package/skills/web-guidance/references/ui-behaviors/platform-controls-dismiss-dialog.md +40 -0
  185. package/skills/web-guidance/references/ui-behaviors/prevent-page-scroll-under-modal-dialog.md +59 -0
  186. package/skills/web-guidance/references/ui-behaviors/search-hidden-content.md +141 -0
  187. package/skills/web-guidance/references/ui-behaviors/sortable-table.md +140 -0
  188. package/skills/web-guidance/references/ui-components/accordion.md +343 -0
  189. package/skills/web-guidance/references/ui-components/breadcrumbs.md +168 -0
  190. package/skills/web-guidance/references/ui-components/carousel.md +206 -0
  191. package/skills/web-guidance/references/ui-components/checkbox.md +144 -0
  192. package/skills/web-guidance/references/ui-components/dialog.md +218 -0
  193. package/skills/web-guidance/references/ui-components/hovercard.md +391 -0
  194. package/skills/web-guidance/references/ui-components/menu.md +415 -0
  195. package/skills/web-guidance/references/ui-components/navbar.md +281 -0
  196. package/skills/web-guidance/references/ui-components/navigation-drawer.md +429 -0
  197. package/skills/web-guidance/references/ui-components/persistent-toast-notifications.md +185 -0
  198. package/skills/web-guidance/references/ui-components/progress.md +181 -0
  199. package/skills/web-guidance/references/ui-components/spinner.md +179 -0
  200. package/skills/web-guidance/references/ui-components/tabs.md +371 -0
  201. package/skills/web-guidance/references/ui-components/toolbar.md +277 -0
  202. package/skills/web-guidance/references/user-experience/form-factor-adaptation.md +120 -0
  203. package/skills/web-guidance/references/user-experience/natural-interactions.md +155 -0
  204. package/skills/web-guidance/references/visual-design/color.md +43 -0
  205. package/skills/web-guidance/references/visual-design/dark-mode.md +350 -0
  206. package/dist/web/assets/AgentWork-DwAI0_Of.js +0 -2
  207. package/dist/web/assets/ApiTests-C0vFSHmM.js +0 -10
  208. package/dist/web/assets/Browse-5jfdtRc5.js +0 -2
  209. package/dist/web/assets/Chat-B3uhI94O.js +0 -3
  210. package/dist/web/assets/CommandPalette-D2J4nf5y.js +0 -1
  211. package/dist/web/assets/Compare-CN75w1p9.js +0 -1
  212. package/dist/web/assets/Cost-QoxyjR95.js +0 -1
  213. package/dist/web/assets/Data-BAvkcBVt.js +0 -6
  214. package/dist/web/assets/Desktop-BXdOIalN.js +0 -1
  215. package/dist/web/assets/DesktopReview-Bl2SrPP0.js +0 -1
  216. package/dist/web/assets/Evidence-BJ_I52CD.js +0 -1
  217. package/dist/web/assets/Explore-D9AuyTip.js +0 -2
  218. package/dist/web/assets/Features-CusGMDR9.js +0 -1
  219. package/dist/web/assets/Flags-CycGFuUP.js +0 -2
  220. package/dist/web/assets/Flaky-BcSzJogN.js +0 -1
  221. package/dist/web/assets/Impact-CJHnyZ21.js +0 -3
  222. package/dist/web/assets/Jobs-4xcFzEFo.js +0 -5
  223. package/dist/web/assets/KindPage-BielEIej.js +0 -6
  224. package/dist/web/assets/Migration-NwanKpJg.js +0 -2
  225. package/dist/web/assets/PageAgent-CNw4NXva.js +0 -1
  226. package/dist/web/assets/Product-DS3LJZ4P.js +0 -7
  227. package/dist/web/assets/Production-D3zsyNIS.js +0 -1
  228. package/dist/web/assets/Quality-Ctj2YpC4.js +0 -1
  229. package/dist/web/assets/Readiness-DGcRr_co.js +0 -1
  230. package/dist/web/assets/Record-Cc-wGe_Y.js +0 -1
  231. package/dist/web/assets/Regression-DcsbrRa1.js +0 -5
  232. package/dist/web/assets/Reports-BkCn0-Sf.js +0 -2
  233. package/dist/web/assets/Response-BP0UwQcW.js +0 -9
  234. package/dist/web/assets/Responsive-C8U7dumd.js +0 -3
  235. package/dist/web/assets/RunDiff-BhABuhF_.js +0 -1
  236. package/dist/web/assets/Runs-OwdWEYBv.js +0 -2
  237. package/dist/web/assets/Steps-BvzbQyoD.js +0 -2
  238. package/dist/web/assets/TestCases-CLq_6JA5.js +0 -1
  239. package/dist/web/assets/TestData-B0oKAhp6.js +0 -2
  240. package/dist/web/assets/TestDebt-8NLQ5YV_.js +0 -1
  241. package/dist/web/assets/TestManagement-2LYQ7vsN.js +0 -1
  242. package/dist/web/assets/Tosca-DfvMpPTG.js +0 -3
  243. package/dist/web/assets/WhatsNew-BGFNGwqN.js +0 -1
  244. package/dist/web/assets/families-DYlN5v0i.js +0 -1
  245. package/dist/web/assets/filters-faaSnoIq.js +0 -1
  246. package/dist/web/assets/fold-CUjwWAK3.js +0 -1
  247. package/dist/web/assets/frame-BLPdAXUq.js +0 -13
  248. package/dist/web/assets/head-CsTxBsO0.js +0 -1
  249. package/dist/web/assets/index-CxiCvGZq.js +0 -78
  250. package/dist/web/assets/index-dOIsrzhD.css +0 -2
  251. package/dist/web/assets/line-icons-CwZWt93L.js +0 -1
  252. package/dist/web/assets/logos-dGuc1jIM.js +0 -1
  253. package/dist/web/assets/markdown-BI3F-SJ1.js +0 -10
  254. package/dist/web/assets/paletteCommands-QJiCuUEr.js +0 -1
  255. package/dist/web/assets/parts-CdF1f7yS.js +0 -1
  256. package/dist/web/assets/productParts-hNLD9fN0.js +0 -1
  257. package/dist/web/assets/qualityParts-CT25lBWU.js +0 -1
  258. package/dist/web/assets/recordTest-P792aBUt.js +0 -1
@@ -0,0 +1,197 @@
1
+ # Compare and validate web origins and sites
2
+
3
+ While comparing `event.origin` against a fixed, port-normalized string literal (such as `event.origin === 'https://app.example.com'`) works for simple allowlists, manual string comparisons and regular expressions break down when validating arbitrary URLs, DOM link elements, cross-subdomain redirects, or sandboxed messages:
4
+
5
+ - **Prefix and substring spoofing:** Checking `url.startsWith('https://app.example.com')` is bypassed by `'https://app.example.com.attacker.example'`.
6
+ - **Unnormalized URLs:** Full URLs with paths, query strings, or explicit default ports (`'https://app.example.com:443/path'`) do not match `'https://app.example.com'` under string equality without first parsing and normalizing.
7
+ - **Public Suffix List mistakes:** Splitting hostnames on `.` to check same-site relationships fails on multi-label public suffixes (such as `.co.uk` or shared hosting domains like `.github.io`) and ignores scheme mismatches (`http:` vs. `https:`).
8
+ - **Opaque `"null"` origin collisions:** Sandboxed iframes (`<iframe sandbox="allow-scripts">`) and `data:` URLs serialize `event.origin` to the literal string `"null"`. Comparing two serialized runtime origins with `originA === originB` falsely equates two unrelated opaque contexts (`"null" === "null"`).
9
+
10
+ The **`Origin` API** (`Origin.from()`, `isSameOrigin()`, `isSameSite()`, and `opaque`) provides structured, spec-compliant origin and schemeful same-site comparisons backed by the browser's URL parser and Public Suffix List.
11
+
12
+ ## Choosing the right comparison for your scenario
13
+
14
+ - **Use `isSameOrigin()` for strict privilege boundaries:** Require an exact `(scheme, host, port)` match when handling cross-window `postMessage` commands (such as an embedded checkout or auth popup) or deciding whether to attach credentials. Even a different subdomain (`https://blog.example.com` vs. `https://app.example.com`) is a different origin and must be rejected so a vulnerability on one subdomain cannot control another.
15
+ - **Use `isSameSite()` for cross-subdomain navigation and link classification:** Allow any subdomain or port sharing the same scheme and registrable domain when validating post-login redirect URLs (`?returnTo=https://billing.example.co.uk/orders`) or classifying links as internal vs. external. `isSameSite()` rejects both `http:` scheme downgrades and sibling tenants on shared public suffixes (`.co.uk`, `.github.io`).
16
+ - **Use `origin.opaque` and `Origin.from(event)` for opaque or sandboxed contexts:** Reject `data:` URLs for redirects (`origin.opaque === true`), or pin the opaque `Origin` extracted via `Origin.from(event)` when communicating with a specific `<iframe sandbox="allow-scripts">` widget whose serialized `event.origin` is `"null"`.
17
+
18
+ ## 1. Verify Exact Origins for Privileged Actions (`Origin.from()` and `isSameOrigin()`)
19
+
20
+ Use `Origin.from()` to extract an `Origin` object and compare it against a trusted `Origin` using `isSameOrigin()`:
21
+
22
+ - **Both sides must be `Origin` instances:** `isSameOrigin(other)` and `isSameSite(other)` only accept an `Origin` object—passing a raw string throws a `TypeError`.
23
+ - **Supported `Origin.from()` inputs:**
24
+ - Serialized URL strings (for example, `'https://app.example.com:443/path'`). Note that any invalid URL string—for instance `'example'`, or the `'null'` string serialized by `event.origin` for opaque origins—causes `Origin.from()` to throw a `TypeError`.
25
+ - Platform objects that define origin-extraction steps in the HTML specification: `Origin`, `URL`, `HTMLAnchorElement` (`<a>`), `HTMLAreaElement` (`<area>`), same-origin `Window` or `WorkerGlobalScope` (`Origin.from(self)`), and browser-dispatched `MessageEvent` instances (`Origin.from(event)`).
26
+ - Objects such as `Location`, `WorkerLocation`, `Document`, `Request`, and `Response` do **not** define origin-extraction steps and throw a `TypeError` if passed directly to `Origin.from()`—pass `self` (for the current context) or `request.url` / `response.url` instead.
27
+ - **Handle both browser-dispatched and synthetic `MessageEvent` instances:** Real browser `postMessage` events carry an internal origin extracted by `Origin.from(event)`, whereas synthetic `new MessageEvent('message', { origin })` events created in unit tests only populate the `event.origin` string and throw on `Origin.from(event)`. Falling back to `Origin.from(event.origin)` inside a `try...catch` handles both cleanly while still rejecting invalid or `"null"` strings.
28
+
29
+ ```javascript
30
+ // Replace with your application's trusted origin(s)
31
+ const TRUSTED_ORIGIN = Origin.from('https://app.example.com');
32
+
33
+ function extractOrigin(candidate) {
34
+ try {
35
+ return Origin.from(candidate);
36
+ } catch (err) {
37
+ // Synthetic new MessageEvent('message', { origin }) objects in tests lack an
38
+ // internal browser origin; fall back to parsing candidate.origin if it is a URL.
39
+ if (typeof MessageEvent !== 'undefined' && candidate instanceof MessageEvent) {
40
+ return Origin.from(candidate.origin);
41
+ }
42
+ throw err;
43
+ }
44
+ }
45
+
46
+ export function isTrustedSameOrigin(candidate) {
47
+ try {
48
+ return extractOrigin(candidate).isSameOrigin(TRUSTED_ORIGIN);
49
+ } catch {
50
+ // Rejects invalid URLs, "null" strings, or unsupported objects
51
+ return false;
52
+ }
53
+ }
54
+
55
+ window.addEventListener('message', (event) => {
56
+ if (!isTrustedSameOrigin(event)) return;
57
+
58
+ // Safe to process privileged commands from the verified origin
59
+ });
60
+ ```
61
+
62
+ ## 2. Validate Cross-Subdomain Redirects and Links (`isSameSite()`)
63
+
64
+ When validating redirect targets (such as `?returnTo=` parameters) or internal links across subdomains of the same registrable domain (for example, `https://app.example.co.uk` and `https://billing.example.co.uk:8443`), use `isSameSite()`:
65
+
66
+ - `isSameSite()` performs a **schemeful same-site** comparison: `https://sub.example.com` and `http://sub.example.com` are **not** same-site because their schemes differ.
67
+ - `isSameSite()` uses the browser's built-in **Public Suffix List**, so distinct tenants on shared public suffixes (such as `https://tenant-a.github.io` and `https://tenant-b.github.io`, or `https://a.co.uk` and `https://b.co.uk`) evaluate to `false`.
68
+
69
+ ```javascript
70
+ // Replace with your application's primary origin
71
+ const APP_ORIGIN = Origin.from('https://app.example.co.uk');
72
+
73
+ export function isAllowedSameSiteUrl(candidateUrlOrElement) {
74
+ try {
75
+ return extractOrigin(candidateUrlOrElement).isSameSite(APP_ORIGIN);
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ // true: same scheme (https) and same registrable domain (example.co.uk)
82
+ isAllowedSameSiteUrl('https://billing.example.co.uk:8443/checkout');
83
+
84
+ // false: scheme downgrade (http vs. https) is rejected by schemeful same-site
85
+ isAllowedSameSiteUrl('http://billing.example.co.uk/checkout');
86
+ ```
87
+
88
+ ## 3. Distinguish and Pin Opaque Origins (`origin.opaque` and `Origin.from(event)`)
89
+
90
+ Sandboxed iframes (`<iframe sandbox="allow-scripts">`), `data:` URLs, and `new Origin()` produce **opaque origins** (`origin.opaque === true`). While their string serialization is always `"null"`, `Origin.from(event)` extracts the sender's actual underlying opaque origin from a browser-dispatched `MessageEvent`:
91
+
92
+ - Two messages sent from the **same** sandboxed iframe yield `Origin` objects that are `isSameOrigin()` with each other (`true`).
93
+ - Messages sent from **different** sandboxed iframes—or separate `Origin.from('data:...')` / `new Origin()` calls—yield distinct opaque origins that evaluate `isSameOrigin()` to `false`, preventing `"null" === "null"` spoofing across unrelated opaque contexts.
94
+ - `new Origin()` creates a fresh, unique opaque origin that matches nothing except itself, which is useful as a default deny-all sentinel before an expected peer origin is pinned once on initialization.
95
+
96
+ ```javascript
97
+ // Initialize with a unique opaque sentinel that matches no other origin
98
+ let pinnedSandboxOrigin = new Origin();
99
+ let isSandboxPinned = false;
100
+
101
+ export function handleSandboxedWidgetMessage(event, expectedWidgetWindow) {
102
+ try {
103
+ const senderOrigin = Origin.from(event);
104
+
105
+ // Pin the opaque origin only once on initialization from the expected sandboxed iframe
106
+ if (!isSandboxPinned && event.source === expectedWidgetWindow && event.data?.type === 'init') {
107
+ pinnedSandboxOrigin = senderOrigin;
108
+ isSandboxPinned = true;
109
+ }
110
+
111
+ // Subsequent messages from the SAME sandboxed iframe match pinnedSandboxOrigin;
112
+ // messages from any other sandboxed iframe (also event.origin === "null") return false.
113
+ return senderOrigin.isSameOrigin(pinnedSandboxOrigin);
114
+ } catch {
115
+ return false;
116
+ }
117
+ }
118
+ ```
119
+
120
+ ## Best practices
121
+
122
+ - **DO** convert both sides of a comparison to `Origin` instances via `Origin.from()` before calling `isSameOrigin(other)` or `isSameSite(other)`.
123
+ - **DO** pass a browser-dispatched `MessageEvent` directly to `Origin.from(event)` when you need to preserve opaque origin identity, and use `Origin.from(self)` (rather than `Location` or `Document`, which throw `TypeError`) to obtain the current execution context's `Origin`.
124
+ - **DO** wrap `Origin.from()` calls on untrusted or runtime inputs in a `try...catch` block so invalid URLs, `"null"` strings, or unsupported objects safely return `false` instead of throwing an uncaught `TypeError`.
125
+ - **DO NOT** compare two runtime `event.origin` or `url.origin` strings directly without first rejecting `"null"` (`origin !== 'null'`), as two unrelated opaque origins both serialize to `"null"`.
126
+ - **DO NOT** validate origins or sites with `startsWith()`, `includes()`, `endsWith()`, or naive `.split('.')` hostname slicing.
127
+
128
+ ## Fallback strategy
129
+
130
+ Browser support for Origin: Limited availability.
131
+ Supported by: Chrome 145 (Feb 2026), Edge 145 (Feb 2026), and Safari 26.5 (May 2026).
132
+ Unsupported in: Firefox.
133
+
134
+ If your Baseline target includes browsers that do not yet support the `Origin` interface, feature-detect `'Origin' in globalThis` and fall back to parsing URLs with `new URL()`:
135
+
136
+ - **Same-origin fallback (tuple origins):** Extract the URL string (using `event.origin` for `MessageEvent` objects or `candidate.href` for link elements), parse both the candidate and trusted URLs with `new URL()`, reject `"null"` opaque origins (`candidateUrl.origin !== 'null'`), and compare `candidateUrl.origin === trustedUrl.origin`. Because an opaque origin is never same-origin with a tuple origin like `'https://app.example.com'`, immediately rejecting `'null'` matches `Origin.isSameOrigin()`.
137
+ - **Same-site fallback (caveat):** The `URL` interface does not expose the browser's Public Suffix List. In browsers without `Origin`, only perform suffix matching against an explicit, known private registrable domain that you control (verifying both `protocol` and an exact or dot-prefixed `hostname` match), or use a maintained Public Suffix List library.
138
+ - **Opaque / sandboxed iframe fallback:** Browsers without `Origin` do not expose distinct opaque origin identities on `MessageEvent` (`event.origin` is always `"null"`). If you intentionally accept messages from a known sandboxed `<iframe sandbox="allow-scripts">`, verify `event.source === expectedWidgetWindow` (or communicate over a dedicated `MessageChannel` `MessagePort` transferred to the iframe on initialization) rather than comparing `event.origin`.
139
+
140
+ ```javascript
141
+ // Replace with your trusted reference URL and known registrable domain
142
+ const TRUSTED_URL = 'https://app.example.com';
143
+ const TRUSTED_SITE_DOMAIN = 'example.com';
144
+
145
+ function extractUrlString(candidate) {
146
+ if (typeof candidate === 'string') return candidate;
147
+ if (typeof MessageEvent !== 'undefined' && candidate instanceof MessageEvent) {
148
+ return candidate.origin;
149
+ }
150
+ if (candidate === globalThis) {
151
+ return globalThis.location?.href ?? '';
152
+ }
153
+ return candidate?.href ?? '';
154
+ }
155
+
156
+ function extractOrigin(candidate) {
157
+ try {
158
+ return Origin.from(candidate);
159
+ } catch (err) {
160
+ if (typeof MessageEvent !== 'undefined' && candidate instanceof MessageEvent) {
161
+ return Origin.from(candidate.origin);
162
+ }
163
+ throw err;
164
+ }
165
+ }
166
+
167
+ export function checkSameOriginWithFallback(candidate) {
168
+ try {
169
+ if ('Origin' in globalThis) {
170
+ return extractOrigin(candidate).isSameOrigin(Origin.from(TRUSTED_URL));
171
+ }
172
+ const candidateUrl = new URL(extractUrlString(candidate));
173
+ const trustedUrl = new URL(TRUSTED_URL);
174
+ return candidateUrl.origin !== 'null' && candidateUrl.origin === trustedUrl.origin;
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+
180
+ export function checkSameSiteWithFallback(candidate) {
181
+ try {
182
+ if ('Origin' in globalThis) {
183
+ return extractOrigin(candidate).isSameSite(Origin.from(TRUSTED_URL));
184
+ }
185
+ const candidateUrl = new URL(extractUrlString(candidate));
186
+ const trustedUrl = new URL(TRUSTED_URL);
187
+ return (
188
+ candidateUrl.origin !== 'null' &&
189
+ candidateUrl.protocol === trustedUrl.protocol &&
190
+ (candidateUrl.hostname === TRUSTED_SITE_DOMAIN ||
191
+ candidateUrl.hostname.endsWith(`.${TRUSTED_SITE_DOMAIN}`))
192
+ );
193
+ } catch {
194
+ return false;
195
+ }
196
+ }
197
+ ```
@@ -0,0 +1,235 @@
1
+ # Verify email address ownership
2
+
3
+ When collecting an email address during sign-up, sign-in, checkout, or account recovery, verifying ownership traditionally requires sending an out-of-band one-time passcode (OTP) or magic link. This forces users to leave your page, wait for email delivery, and copy codes—introducing friction, drop-off, and phishing risk, while also revealing to the email provider which relying party (RP) the user is visiting.
4
+
5
+ The **Email Verification API** (client-side HTML extension) and **Email Verification Protocol (EVP)** (backend cryptographic protocol) enable a relying party to verify that a user controls an email address without sending a verification email. The browser intermediates between the relying party and the user's email provider (the issuer):
6
+
7
+ 1. The relying party includes a hidden `<input>` with `autocomplete="email-verification-token"` and a single-use cryptographic `nonce` in the same `<form>` as the email input.
8
+ 2. When the user selects or enters an email address, the browser looks up the domain's `_email-verification.<domain>` DNS `TXT` record, verifies the user has an active session with the authoritative issuer, and requests an **Email Verification Token (EVT)** without disclosing the relying party's identity to the issuer.
9
+ 3. The browser binds the EVT to the relying party's origin and session `nonce` in a **Key Binding JWT (KB-JWT)** signed with an ephemeral browser key pair (`EVT + KB-JWT`), populates the hidden input, and submits the form.
10
+ 4. The relying party's backend verifies the cryptographic chain and, if valid, skips the email OTP or magic link step.
11
+
12
+ ## 1. Enable the Origin Trial and Render the Verification Form
13
+
14
+ To participate as a verifying site (relying party):
15
+
16
+ 1. **Provide the Origin Trial token** on the page hosting the form using either the `Origin-Trial` HTTP response header or a `<meta http-equiv="origin-trial">` element.
17
+ - **Third-party origin trials:** Embedded identity SDKs can inject a third-party trial token, provided the Origin Trial registrant origin matches the issuer domain (same-site with the issuer, such as `https://issuer.example`).
18
+ 2. **Generate a cryptographically random nonce per form render** with at least 128 bits of entropy (for example, `randomBytes(32).toString('base64url')` from `node:crypto`), store it in **server-side session state** keyed by an `HttpOnly`, `Secure`, `SameSite=Lax` session ID cookie (never store the expected `nonce` value directly inside a client cookie where an attacker could replay both the cookie and token), and render it into the hidden token input's `nonce` attribute. Serve the page with `Cache-Control: no-store` so back/forward navigation does not reuse an already-consumed nonce.
19
+ 3. **Add the hidden token input** (`autocomplete="email-verification-token"`) inside the same `<form>` as the email input (`autocomplete="email"`).
20
+
21
+ ```html
22
+ <!-- Serve with:
23
+ Origin-Trial: <YOUR_ORIGIN_TRIAL_TOKEN>
24
+ Cache-Control: no-store -->
25
+ <form method="POST" action="/api/verify-email">
26
+ <label for="email">Email address:</label>
27
+ <input
28
+ type="email"
29
+ id="email"
30
+ name="email"
31
+ autocomplete="email"
32
+ required
33
+ />
34
+
35
+ <!-- MANDATORY: Must be in the same <form> as the email input.
36
+ The nonce value must be freshly generated on the server per form render. -->
37
+ <input
38
+ type="hidden"
39
+ name="token"
40
+ nonce="SERVER_GENERATED_PER_FORM_NONCE"
41
+ autocomplete="email-verification-token"
42
+ />
43
+
44
+ <button type="submit">Continue</button>
45
+ </form>
46
+ ```
47
+
48
+ ## 2. Verify the Submitted Token on the Server
49
+
50
+ When the form is submitted, treat the `token` field as untrusted input. Atomically read and delete the expected `nonce` from your server-side session store on receipt. If the `token` field is empty (for example, in browsers that do not support EVP or when the user is signed out of their email provider) or if verification fails, fall back immediately to your standard email OTP or magic link flow:
51
+
52
+ ```javascript
53
+ // Replace with your public relying-party origin
54
+ const RP_ORIGIN = 'https://rp.example.com';
55
+
56
+ export async function handleSignupSubmission(request) {
57
+ const formData = await request.formData();
58
+ const submittedEmail = String(formData.get('email') || '').trim();
59
+ const rawToken = String(formData.get('token') || '').trim();
60
+ // Atomically read and delete the single-use nonce from server-side session state
61
+ const expectedNonce = await consumeSessionNonce(request);
62
+
63
+ if (rawToken && expectedNonce) {
64
+ try {
65
+ await verifyEmailVerificationToken({
66
+ rawToken,
67
+ submittedEmail,
68
+ expectedNonce,
69
+ expectedAudience: RP_ORIGIN,
70
+ });
71
+ // Fast path: email ownership is cryptographically verified; skip OTP email.
72
+ return completeAccountCreation(submittedEmail);
73
+ } catch (err) {
74
+ // Log token verification failures before falling back to standard email verification.
75
+ console.error('Email verification token check failed:', err);
76
+ }
77
+ }
78
+
79
+ // Fallback path: send standard OTP code or magic link email to submittedEmail.
80
+ return sendTraditionalVerificationEmail(submittedEmail);
81
+ }
82
+ ```
83
+
84
+ Always use established SD-JWT and JOSE/JWT libraries for your backend platform (such as `@sd-jwt/core` and `jose` in Node.js, `sd-jwt-python` / `jwcrypto` in Python, or `sd-jwt-java` / Nimbus JOSE+JWT on the JVM) to implement `verifyEmailVerificationToken` rather than hand-rolling custom JWT or SD-JWT parsing code.
85
+
86
+ ### Step 1: Parse the SD-JWT claims and validate the email address
87
+
88
+ After consuming the single-use `expectedNonce` from server-side session storage, decode the SD-JWT presentation (`EVT + KB-JWT`) and verify that:
89
+ - Both the issuer JWT (`jwt`) and Key Binding JWT (`kbJwt`) are present, along with the issuer claim (`iss`).
90
+ - `evtPayload.email_verified === true`.
91
+ - `evtPayload.email` matches the submitted form email using a **case-insensitive comparison** (`toLowerCase()`).
92
+
93
+ ```javascript
94
+ import { createHash } from 'node:crypto';
95
+ import { decodeSdJwtSync } from '@sd-jwt/core';
96
+
97
+ const hasher = (data, alg) =>
98
+ createHash(alg === 'sha-256' ? 'sha256' : alg).update(data).digest();
99
+
100
+ const decoded = decodeSdJwtSync(rawToken, hasher);
101
+ const evtPayload = decoded.jwt.payload;
102
+ const iss = evtPayload.iss;
103
+
104
+ if (!expectedNonce || !decoded.kbJwt || !iss || evtPayload.email_verified !== true) {
105
+ throw new Error('Missing nonce, KB-JWT, issuer, or email_verified !== true.');
106
+ }
107
+ // MANDATORY: Compare email addresses case-insensitively
108
+ if (evtPayload.email?.toLowerCase() !== submittedEmail.toLowerCase()) {
109
+ throw new Error('Submitted email does not match the EVT email claim.');
110
+ }
111
+ ```
112
+
113
+ ### Step 2: Validate DNS TXT delegation and load the issuer JWKS
114
+
115
+ Before making any network request to `iss`, verify that the submitted email's domain delegates authority to that exact issuer via a `_email-verification.<domain>` DNS `TXT` record (`iss=<issuer-host>` -> `https://<issuer-host>` with no port, path, or trailing slash). Once DNS delegation matches `iss` byte-for-byte, fetch `${iss}/.well-known/email-verification` over HTTPS, confirm that `metadata.issuer === iss`, and load the issuer's JSON Web Key Set (JWKS).
116
+
117
+ > **Note on `kid` handling:** Some major email providers (such as Gmail) omit `kid` from the EVT header. When `kid` is absent and the JWKS contains multiple keys, `jose` throws `ERR_JWKS_MULTIPLE_MATCHING_KEYS` (an `AsyncIterable` of matching `CryptoKey`s)—iterate `for await (const publicKey of err)` to trial-verify each key, as shown in Step 3.
118
+
119
+ ```javascript
120
+ import dns from 'node:dns/promises';
121
+ import { createRemoteJWKSet } from 'jose';
122
+
123
+ const domain = submittedEmail.split('@')[1];
124
+ const txtRecords = (await dns.resolveTxt(`_email-verification.${domain}`)).map((r) => r.join(''));
125
+ if (!txtRecords.some((txt) => txt.startsWith('iss=') && `https://${txt.slice(4).trim()}` === iss)) {
126
+ throw new Error(`Issuer "${iss}" is not delegated via DNS for "${domain}".`);
127
+ }
128
+
129
+ const discoveryUrl = new URL('/.well-known/email-verification', iss);
130
+ if (discoveryUrl.protocol !== 'https:') throw new Error('Issuer must use HTTPS.');
131
+ const metadata = await (await fetch(discoveryUrl)).json();
132
+ if (metadata.issuer !== iss || !metadata.jwks_uri?.startsWith('https://')) {
133
+ throw new Error('Invalid issuer metadata or non-HTTPS jwks_uri.');
134
+ }
135
+ const issuerJwks = createRemoteJWKSet(new URL(metadata.jwks_uri));
136
+ ```
137
+
138
+ ### Step 3: Verify the EVT signature and Key Binding JWT (`KB-JWT`)
139
+
140
+ Finally, verify both signatures and the cryptographic binding between the two tokens using the explicit asymmetric algorithm allowlist (`['Ed25519', 'EdDSA', 'ES256']`):
141
+ 1. **EVT signature (`verifier`):** Verify against `issuerJwks` (catching `ERR_JWKS_MULTIPLE_MATCHING_KEYS` to iterate candidate keys when `kid` is omitted), enforcing `iss` and a tight freshness window (`maxTokenAge: '5m'`, `clockTolerance: '1m'`).
142
+ 2. **Holder binding (`kbVerifier` and `sdJwt.verify` options):** Extract the browser's ephemeral public key from `evtPayload.cnf.jwk`, confirm both `cnf.jwk.alg` and `decoded.kbJwt.header.alg` are in `ALLOWED_ALGS` and match (treating `'Ed25519'` and `'EdDSA'` as equivalent while Origin Trial implementations transition to RFC 9864 `'Ed25519'`), and verify the `KB-JWT` signature with `typ: 'kb+jwt'`. Pass `keyBindingNonce: expectedNonce`, `expectedKeyBindingAudience: expectedAudience`, and `keyBindingMaxAgeSeconds: 300` to `sdJwt.verify()`—`@sd-jwt/core` only invokes `kbVerifier` and validates `nonce`, `aud`, `iat`, and `sd_hash` when `keyBindingNonce` is supplied.
143
+
144
+ ```javascript
145
+ import { SDJwtInstance } from '@sd-jwt/core';
146
+ import { importJWK, jwtVerify } from 'jose';
147
+
148
+ // IETF draft-hardt-email-verification-02 (§3.3, §5.1.1) specifies RFC 9864 'Ed25519' and 'ES256'.
149
+ // TODO: Remove 'EdDSA' once live issuers (e.g. Gmail) and Chrome Origin Trial builds finish
150
+ // transitioning from 'EdDSA' (with crv: 'Ed25519') to 'Ed25519'.
151
+ const ALLOWED_ALGS = ['Ed25519', 'EdDSA', 'ES256'];
152
+ const normalizeAlg = (alg) => (alg === 'Ed25519' ? 'EdDSA' : alg);
153
+ const evtOptions = {
154
+ typ: 'ev+sd-jwt',
155
+ issuer: iss,
156
+ algorithms: ALLOWED_ALGS,
157
+ maxTokenAge: '5m',
158
+ clockTolerance: '1m',
159
+ };
160
+
161
+ const sdJwt = new SDJwtInstance({
162
+ hasher,
163
+ verifier: async (data, sig) => {
164
+ const compactEvt = `${data}.${sig}`;
165
+ try {
166
+ await jwtVerify(compactEvt, issuerJwks, evtOptions);
167
+ } catch (err) {
168
+ // When `kid` is omitted (e.g. Gmail) and multiple keys match in the JWKS,
169
+ // jose throws JWKSMultipleMatchingKeys, which yields each matching CryptoKey.
170
+ if (err?.code !== 'ERR_JWKS_MULTIPLE_MATCHING_KEYS') throw err;
171
+ let matched = false;
172
+ for await (const publicKey of err) {
173
+ try {
174
+ await jwtVerify(compactEvt, publicKey, evtOptions);
175
+ matched = true;
176
+ break;
177
+ } catch {}
178
+ }
179
+ if (!matched) throw err;
180
+ }
181
+ return true;
182
+ },
183
+ kbVerifier: async (data, sig) => {
184
+ const holderJwk = evtPayload.cnf?.jwk;
185
+ const holderAlg = holderJwk?.alg;
186
+ const kbAlg = decoded.kbJwt.header.alg;
187
+ if (
188
+ !holderAlg ||
189
+ !kbAlg ||
190
+ !ALLOWED_ALGS.includes(holderAlg) ||
191
+ !ALLOWED_ALGS.includes(kbAlg) ||
192
+ normalizeAlg(kbAlg) !== normalizeAlg(holderAlg)
193
+ ) {
194
+ throw new Error('Missing, disallowed, or mismatched KB-JWT algorithm.');
195
+ }
196
+ const holderKey = await importJWK(holderJwk, kbAlg);
197
+ await jwtVerify(`${data}.${sig}`, holderKey, {
198
+ typ: 'kb+jwt',
199
+ audience: expectedAudience,
200
+ algorithms: [kbAlg],
201
+ maxTokenAge: '5m',
202
+ clockTolerance: '1m',
203
+ });
204
+ return true;
205
+ },
206
+ });
207
+
208
+ const verified = await sdJwt.verify(rawToken, {
209
+ requiredClaimKeys: ['email', 'email_verified'],
210
+ keyBindingNonce: expectedNonce,
211
+ expectedKeyBindingAudience: expectedAudience,
212
+ keyBindingMaxAgeSeconds: 300,
213
+ skewSeconds: 60,
214
+ });
215
+ ```
216
+
217
+ ## Best practices
218
+
219
+ - **DO** perform all token verification strictly on the server. **DO NOT** validate tokens in client-side JavaScript or trust any client-side verification state—client-side checks can be trivially bypassed or forged and provide zero trust guarantee to the relying party.
220
+ - **DO** use established SD-JWT and JOSE/JWT libraries for your backend platform (for example, `@sd-jwt/core` and `jose` in Node.js) to parse and validate the `EVT~KB-JWT` presentation, and pass `keyBindingNonce` to `sdJwt.verify()` so Key Binding verification cannot be bypassed. **DO NOT** hand-roll custom JWT, SD-JWT, or `sd_hash` parsing and signature verification routines.
221
+ - **DO** generate a fresh cryptographic `nonce` (at least 128 bits, such as `randomBytes(32).toString('base64url')`) on the server for each form render, store it in **server-side session state** (not directly in a client cookie), and serve the form page with `Cache-Control: no-store`.
222
+ - **DO** atomically read and delete the expected `nonce` from server-side session storage immediately when the `POST` request arrives so an intercepted token cannot be replayed.
223
+ - **DO** perform a **case-insensitive comparison** between `evtPayload.email` and the submitted form email address (`email.toLowerCase()`), while preserving the submitted email string.
224
+ - **DO** trial-verify all keys in the issuer's JWKS when `kid` is absent from the EVT header (providers such as Gmail omit `kid`).
225
+ - **DO** verify DNS delegation (`_email-verification.<domain>`) before trusting any `iss` claim in an EVT, and confirm `metadata.issuer === iss` in the `.well-known/email-verification` response.
226
+ - **DO NOT** treat email ownership verification as proof of inbox deliverability. EVP proves that the user controls the email account with the authoritative provider; still send transactional welcome emails and handle bounces normally.
227
+ - **DO NOT** block account creation or sign-in when `token` is empty or when verification fails—always degrade gracefully to your standard email OTP or magic link flow.
228
+
229
+ ## Fallback strategy
230
+
231
+ Email Verification (`autocomplete="email-verification-token"`) is designed as a **progressive enhancement** over traditional out-of-band email verification (OTP codes or magic links):
232
+
233
+ - **Unsupported browsers:** Browsers that do not support `autocomplete="email-verification-token"` ignore the hidden input and submit the form with an empty `token` value.
234
+ - **Unauthenticated or non-participating email domains:** When a user enters an email address whose domain does not publish an `_email-verification` DNS `TXT` record, or when the user does not have an active session with their email provider in the browser, the browser submits the form with an empty `token`.
235
+ - **Expired or invalid tokens:** If the `nonce` has expired, was already consumed, or fails any step of `verifyEmailVerificationToken` in `handleSignupSubmission`, the server catches the error and sends a traditional OTP or magic link email without interrupting the user's sign-up or sign-in flow.
@@ -0,0 +1,173 @@
1
+ # Position Aware Tooltips
2
+
3
+ When building tooltips or popovers with CSS Anchor Positioning, the browser can automatically "flip" the element to a fallback position if it would otherwise overflow the viewport. When this happens, you may want to adjust the style of the positioned content, for instance to reposition an arrow that points from the positioned content to the anchor.
4
+
5
+ **Anchored Container Queries** solve this by allowing you to query the active positioning state of an element and apply styles accordingly. For general anchored dropdown and flyout positioning with viewport collision flipping (without directional arrow restyling), see `viewport-aware-dropdowns` (references/ui-atoms/viewport-aware-dropdowns.md).
6
+
7
+ ## The problem
8
+
9
+ Imagine a tooltip that appears above its anchor by default. It has a "down" arrow at the bottom. If the user scrolls and the tooltip flips to appear *below* the anchor, the arrow is now pointing the wrong way and is on the wrong side of the tooltip.
10
+
11
+ ## The solution: Anchored Container Queries
12
+
13
+ By setting `container-type: anchored` on your positioned element, you turn it into a query container that knows about its own anchor-positioned state. You can then use the `@container anchored()` query to update its descendants or pseudo-elements.
14
+
15
+ ### 1. Create the tooltip and trigger
16
+
17
+ Use the Popover API to create a tooltip. Invoking the popover via `popovertarget` automatically establishes an **implicit anchor connection** with the trigger button, so no explicit `anchor-name` or `position-anchor` is required.
18
+
19
+ ```html
20
+ <button popovertarget="tooltip" id="anchor" aria-describedby="tooltip">anchor</button>
21
+ <div id="tooltip" popover role="tooltip"></div>
22
+ ```
23
+
24
+ Reset the popover inset and margin styles for use with anchor positioning, but only if anchor positioning is supported.
25
+
26
+ ```css
27
+ @supports (anchor-name: --my-anchor) {
28
+ [popover] {
29
+ inset: auto;
30
+ margin: unset;
31
+ }
32
+ }
33
+ ```
34
+
35
+ ### 2. Set up the container
36
+
37
+ Apply `container-type: anchored` to the element being positioned. This element must also have `position-try-fallbacks` defined to enable the flipping behavior.
38
+
39
+ ```css
40
+ #tooltip {
41
+ position: fixed;
42
+ position-area: block-start;
43
+ position-try-fallbacks: flip-block;
44
+
45
+ /* Enable anchored container queries */
46
+ container-type: anchored;
47
+ }
48
+ ```
49
+
50
+ ### 3. Style based on the fallback
51
+
52
+ Use `@container anchored(fallback: <value>)` to apply styles when a specific fallback is active.
53
+
54
+ Like all container queries, `@container` can only style **descendants** of the container. A common strategy to create the arrows is with the `::before` and `::after` pseudo-elements, which are treated as descendants and can be styled directly. However, to style the tooltip itself (as seen in step 4), we will add a child element to the tooltip, and create the arrow in its `::before` pseudo-element.
55
+
56
+ ```html
57
+ <div id="tooltip" popover role="tooltip">
58
+ <div class="tooltip-content">Tooltip</div>
59
+ </div>
60
+ ```
61
+
62
+ ```css
63
+ .tooltip-content::before {
64
+ /* Default "down" arrow for the 'top' position */
65
+ content: "▼" / "";
66
+ position: absolute;
67
+ inset-block-end: 0;
68
+ inset-inline-start: 1rem;
69
+ }
70
+
71
+ /* Update to an "up" arrow when the 'flip-block' fallback (bottom) is active */
72
+ @container anchored(fallback: flip-block) {
73
+ .tooltip-content::before {
74
+ content: "▲" / "";
75
+ inset-block-start: 0;
76
+ inset-block-end: auto;
77
+ }
78
+ }
79
+ ```
80
+
81
+ ## 4. Styling the container itself
82
+
83
+ If you need to change properties on the container itself (like `margin` or `background-color`) when it flips, you should use an **inner wrapper element**.
84
+
85
+ 1. Apply `container-type: anchored` to the outer positioned element.
86
+ 2. Target the inner element inside the `@container` block.
87
+
88
+
89
+ ```css
90
+ @container anchored(fallback: flip-block) {
91
+ .tooltip-content {
92
+ border-radius: 0 0 .5rem .5rem;
93
+ margin-block-start: 0.25rem;
94
+ }
95
+ }
96
+ ```
97
+
98
+ ## 5. Styling the inner container (optional)
99
+
100
+ If the tooltip text is particularly long, use an inner container in the tooltip to ensure that, when visible, the tooltip will always fit between the trigger control and a side of the viewport. As an example, the following code will adhere to this when flipping the tooltip content on the block axis with `position-try: flip-block`.
101
+
102
+ ```html
103
+ <button popovertarget="tooltip" id="anchor" aria-describedby="tooltip">anchor</button>
104
+ <div id="tooltip" popover role="tooltip">
105
+ <div class="tooltip-content-inner"></div>
106
+ </div>
107
+ ```
108
+
109
+ ```css
110
+ .tooltip-content-inner {
111
+ max-block-size: calc(50dvb - var(--trigger-height));
112
+ overflow-block: auto;
113
+ }
114
+ ```
115
+
116
+ ## Best practices
117
+
118
+ - **Prefer logical fallbacks**: Use keywords like `flip-block` and `flip-inline` in `position-try-fallbacks` for simpler queries that handle RTL and different writing modes automatically.
119
+ - **Use pseudo-elements for arrows**: Tooltip arrows are purely decorative and are perfect candidates for `::before` or `::after`, which can be styled via anchored container queries without extra DOM.
120
+
121
+ ## Accessibility considerations
122
+
123
+ Using these tooltips may result in controls being obscured when they receive focus, which would result in a fail against WCAG 2.4.11 Focus Not Obscured (Minimum) (Level AA), as focused items cannot be completely obscured. While there may not be generic guidance to completely mitigate against this issue, consider strategies that adjust the position of the tooltip or its presence.
124
+
125
+ Keyboard navigation does not close a `popover=auto` tooltip, so ensure that tooltips do not obscure interactive elements as they receive focus via keyboard. If the tooltip is likely to obscure an interactive element when it receives focus, either change the position of the tooltip to prevent focus being obscured, or dismiss the tooltip if it is no longer relevant to the user.
126
+
127
+ ## Fallback strategies
128
+
129
+ Browser support for Anchor position container queries: Limited availability.
130
+ Supported by: Chrome 143 (Dec 2025) and Edge 143 (Dec 2025).
131
+ Unsupported in: Firefox and Safari.
132
+
133
+ Positioning the arrow based on the applied fallback is a progressive enhancement, and there is not another way of reacting to the fallback position. To hide the arrow in browsers that don't support anchor position container queries, test for CSS support with `@supports (container-type: anchored)`.
134
+
135
+ ```css
136
+ @supports (container-type: anchored) {
137
+ .tooltip-content::before {
138
+ content: "▼" / "";
139
+ }
140
+ }
141
+ ```
142
+
143
+ ### Fallbacks & browser support for Popover
144
+
145
+ Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.
146
+ Supported by: Chrome 116 (Aug 2023), Edge 116 (Aug 2023), Firefox 125 (Apr 2024), Safari 17 (Sep 2023), and Safari iOS 18.3 (Jan 2025).
147
+
148
+ The Popover API is mostly **progressive enhancement**, but its defining behaviors — top-layer promotion, light-dismiss, and `popovertarget` invocation — have no CSS-only equivalent. Older browsers need a polyfill, or a manual fallback if you would rather not ship one.
149
+
150
+ **Polyfill:** To support the `popover` attribute in older browsers, conditionally load [`@oddbird/popover-polyfill`](https://github.com/oddbird/popover-polyfill). **MANDATORY:** Feature detect by checking for the `popover` property on `HTMLElement.prototype`, and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
151
+
152
+ With a bundler or import map:
153
+
154
+ ```js
155
+ // MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
156
+ if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
157
+ import("@oddbird/popover-polyfill");
158
+ }
159
+ ```
160
+
161
+ If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
162
+
163
+ Caveats when using the polyfill:
164
+ - Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
165
+ - **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
166
+
167
+ ```css
168
+ [popover]:is(:popover-open, .\:popover-open) {
169
+ display: block;
170
+ }
171
+ ```
172
+
173
+ Browsers without support for the Popover API also do not support anchor positioning, so the tooltip will appear in the center of the screen.