@indecisivedev/openplan 0.2.0-alpha.2

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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +120 -0
  3. package/dist/access-policy.d.ts +35 -0
  4. package/dist/access-policy.js +107 -0
  5. package/dist/access-policy.js.map +1 -0
  6. package/dist/access-store.d.ts +33 -0
  7. package/dist/access-store.js +212 -0
  8. package/dist/access-store.js.map +1 -0
  9. package/dist/admin.d.ts +1 -0
  10. package/dist/admin.js +13 -0
  11. package/dist/admin.js.map +1 -0
  12. package/dist/api.d.ts +2 -0
  13. package/dist/api.js +867 -0
  14. package/dist/api.js.map +1 -0
  15. package/dist/bootstrap-admin.d.ts +1 -0
  16. package/dist/bootstrap-admin.js +35 -0
  17. package/dist/bootstrap-admin.js.map +1 -0
  18. package/dist/browser-security.d.ts +5 -0
  19. package/dist/browser-security.js +53 -0
  20. package/dist/browser-security.js.map +1 -0
  21. package/dist/celld-quickstart.d.ts +51 -0
  22. package/dist/celld-quickstart.js +1175 -0
  23. package/dist/celld-quickstart.js.map +1 -0
  24. package/dist/cli-api-client.d.ts +78 -0
  25. package/dist/cli-api-client.js +272 -0
  26. package/dist/cli-api-client.js.map +1 -0
  27. package/dist/cli-credentials.d.ts +47 -0
  28. package/dist/cli-credentials.js +447 -0
  29. package/dist/cli-credentials.js.map +1 -0
  30. package/dist/cli-endpoint.d.ts +19 -0
  31. package/dist/cli-endpoint.js +56 -0
  32. package/dist/cli-endpoint.js.map +1 -0
  33. package/dist/cli-program.d.ts +11 -0
  34. package/dist/cli-program.js +934 -0
  35. package/dist/cli-program.js.map +1 -0
  36. package/dist/cli.d.ts +2 -0
  37. package/dist/cli.js +7 -0
  38. package/dist/cli.js.map +1 -0
  39. package/dist/client-ip.d.ts +4 -0
  40. package/dist/client-ip.js +49 -0
  41. package/dist/client-ip.js.map +1 -0
  42. package/dist/config.d.ts +35 -0
  43. package/dist/config.js +113 -0
  44. package/dist/config.js.map +1 -0
  45. package/dist/crypto.d.ts +3 -0
  46. package/dist/crypto.js +11 -0
  47. package/dist/crypto.js.map +1 -0
  48. package/dist/database.d.ts +15 -0
  49. package/dist/database.js +155 -0
  50. package/dist/database.js.map +1 -0
  51. package/dist/db.d.ts +31 -0
  52. package/dist/db.js +388 -0
  53. package/dist/db.js.map +1 -0
  54. package/dist/drafts.d.ts +43 -0
  55. package/dist/drafts.js +90 -0
  56. package/dist/drafts.js.map +1 -0
  57. package/dist/feature-settings.d.ts +7 -0
  58. package/dist/feature-settings.js +32 -0
  59. package/dist/feature-settings.js.map +1 -0
  60. package/dist/generated/annotation-client.d.ts +1 -0
  61. package/dist/generated/annotation-client.js +2 -0
  62. package/dist/generated/annotation-client.js.map +1 -0
  63. package/dist/html-policy.d.ts +15 -0
  64. package/dist/html-policy.js +172 -0
  65. package/dist/html-policy.js.map +1 -0
  66. package/dist/ids.d.ts +2 -0
  67. package/dist/ids.js +10 -0
  68. package/dist/ids.js.map +1 -0
  69. package/dist/local-auth.d.ts +36 -0
  70. package/dist/local-auth.js +215 -0
  71. package/dist/local-auth.js.map +1 -0
  72. package/dist/maintenance.d.ts +1 -0
  73. package/dist/maintenance.js +18 -0
  74. package/dist/maintenance.js.map +1 -0
  75. package/dist/oidc.d.ts +39 -0
  76. package/dist/oidc.js +194 -0
  77. package/dist/oidc.js.map +1 -0
  78. package/dist/public-url.d.ts +17 -0
  79. package/dist/public-url.js +96 -0
  80. package/dist/public-url.js.map +1 -0
  81. package/dist/rate-limit.d.ts +25 -0
  82. package/dist/rate-limit.js +55 -0
  83. package/dist/rate-limit.js.map +1 -0
  84. package/dist/reconcile.d.ts +5 -0
  85. package/dist/reconcile.js +18 -0
  86. package/dist/reconcile.js.map +1 -0
  87. package/dist/render-annotations.d.ts +10 -0
  88. package/dist/render-annotations.js +73 -0
  89. package/dist/render-annotations.js.map +1 -0
  90. package/dist/render-web.d.ts +74 -0
  91. package/dist/render-web.js +439 -0
  92. package/dist/render-web.js.map +1 -0
  93. package/dist/render.d.ts +4 -0
  94. package/dist/render.js +85 -0
  95. package/dist/render.js.map +1 -0
  96. package/dist/server.d.ts +1 -0
  97. package/dist/server.js +26 -0
  98. package/dist/server.js.map +1 -0
  99. package/dist/shoo.d.ts +26 -0
  100. package/dist/shoo.js +92 -0
  101. package/dist/shoo.js.map +1 -0
  102. package/dist/sqlite-migrations.d.ts +6 -0
  103. package/dist/sqlite-migrations.js +214 -0
  104. package/dist/sqlite-migrations.js.map +1 -0
  105. package/dist/storage.d.ts +14 -0
  106. package/dist/storage.js +86 -0
  107. package/dist/storage.js.map +1 -0
  108. package/dist/types.d.ts +24 -0
  109. package/dist/types.js +2 -0
  110. package/dist/types.js.map +1 -0
  111. package/dist/upload-state.d.ts +19 -0
  112. package/dist/upload-state.js +118 -0
  113. package/dist/upload-state.js.map +1 -0
  114. package/dist/web-auth.d.ts +33 -0
  115. package/dist/web-auth.js +122 -0
  116. package/dist/web-auth.js.map +1 -0
  117. package/dist/web.d.ts +2 -0
  118. package/dist/web.js +550 -0
  119. package/dist/web.js.map +1 -0
  120. package/package.json +70 -0
@@ -0,0 +1,2 @@
1
+ export const ANNOTATION_CLIENT = "/*!\nOpenplan browser annotation bundle — third-party notices\n\n@drauu/core 1.0.0\nhttps://github.com/antfu/drauu/tree/v1.0.0\n\nMIT License\n\nCopyright (c) 2020-2021 Anthony Fu\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n------------------------------------------------------------\n\nnanoevents 9.1.0 (bundled by @drauu/core)\nhttps://www.npmjs.com/package/nanoevents/v/9.1.0\n\nThe MIT License (MIT)\n\nCopyright 2016 Andrey Sitnik <andrey@sitnik.ru>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n------------------------------------------------------------\n\nperfect-freehand 1.2.2 (bundled by @drauu/core)\nhttps://www.npmjs.com/package/perfect-freehand/v/1.2.2\n\nMIT License\n\nCopyright (c) 2021 Stephen Ruiz Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n------------------------------------------------------------\n\nSimplify.js (adapted by @drauu/core)\nhttps://github.com/mourner/simplify-js/tree/v1.2.4\n\nCopyright (c) 2017, Vladimir Agafonkin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are\npermitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this list of\n conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice, this list\n of conditions and the following disclaimer in the documentation and/or other materials\n provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\nEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\nCOPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\nTORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\"use strict\";(()=>{var Kt=()=>({emit(t,...e){for(let n=this.events[t]||[],s=0,i=n.length;s<i;s++)n[s](...e)},events:{},on(t,e){return(this.events[t]||=[]).push(e),()=>{this.events[t]=this.events[t]?.filter(n=>e!==n)}}});function Q(t,e){return t-e}function Wt(t){return t<0?-1:1}function tt(t){return[Math.abs(t),Wt(t)]}function kt(){let t=()=>((1+Math.random())*65536|0).toString(16).substring(1);return`${t()+t()}-${t()}-${t()}-${t()}-${t()}${t()}${t()}`}var Xt=2,L=Xt;function It(t,e){let n=document.createElementNS(\"http://www.w3.org/2000/svg\",\"defs\"),s=document.createElementNS(\"http://www.w3.org/2000/svg\",\"marker\"),i=document.createElementNS(\"http://www.w3.org/2000/svg\",\"path\");return i.setAttribute(\"fill\",e),s.setAttribute(\"id\",t),s.setAttribute(\"viewBox\",\"0 -5 10 10\"),s.setAttribute(\"refX\",\"5\"),s.setAttribute(\"refY\",\"0\"),s.setAttribute(\"markerWidth\",\"4\"),s.setAttribute(\"markerHeight\",\"4\"),s.setAttribute(\"orient\",\"auto\"),i.setAttribute(\"d\",\"M0,-5L10,0L0,5\"),s.appendChild(i),n.appendChild(s),n}function Yt(t,e){let n=t.x-e.x,s=t.y-e.y;return n*n+s*s}function Zt(t,e,n){let s=e.x,i=e.y,r=n.x-s,a=n.y-i;if(r!==0||a!==0){let o=((t.x-s)*r+(t.y-i)*a)/(r*r+a*a);o>1?(s=n.x,i=n.y):o>0&&(s+=r*o,i+=a*o)}return r=t.x-s,a=t.y-i,r*r+a*a}function Jt(t,e){let n=t[0],s=[n],i;for(let r=1,a=t.length;r<a;r++)i=t[r],Yt(i,n)>e&&(s.push(i),n=i);return n!==i&&i&&s.push(i),s}function dt(t,e,n,s,i){let r=s,a=0;for(let o=e+1;o<n;o++){let h=Zt(t[o],t[e],t[n]);h>r&&(a=o,r=h)}r>s&&(a-e>1&&dt(t,e,a,s,i),i.push(t[a]),n-a>1&&dt(t,a,n,s,i))}function Qt(t,e){let n=t.length-1,s=[t[0]];return dt(t,0,n,e,s),s.push(t[n]),s}function Pt(t,e,n=!1){if(t.length<=2)return t;let s=e!==void 0?e*e:1;return t=n?t:Jt(t,s),t=Qt(t,s),t}var O=class{constructor(t){this.drauu=t,this.event=void 0,this.point=void 0,this.start=void 0,this.el=null}onSelected(t){}onUnselected(){}onStart(t){}onMove(t){return!1}onEnd(t){}get brush(){return this.drauu.brush}get shiftPressed(){return this.drauu.shiftPressed}get altPressed(){return this.drauu.altPressed}get svgElement(){return this.drauu.el}getMousePosition(t){let e=this.drauu.el,n=this.drauu.options.cssZoom??1,s=this.drauu.options.coordinateScale??1,i=this.drauu.options.offset??{x:0,y:0};if(this.drauu.options.coordinateTransform===!1){let r=this.drauu.el.getBoundingClientRect();return{x:(t.pageX/n-r.left+i.x)*s,y:(t.pageY/n-r.top+i.y)*s,pressure:t.pressure}}else{let r=this.drauu.svgPoint;r.x=t.clientX/n+i.x,r.y=t.clientY/n+i.y;let a=r.matrixTransform(e.getScreenCTM()?.inverse());return{x:a.x*s,y:a.y*s,pressure:t.pressure}}}createElement(t,e){let n=document.createElementNS(\"http://www.w3.org/2000/svg\",t),s=e?{...this.brush,...e}:this.brush;return n.setAttribute(\"fill\",s.fill??\"transparent\"),n.setAttribute(\"stroke\",s.color),n.setAttribute(\"stroke-width\",s.size.toString()),n.setAttribute(\"stroke-linecap\",\"round\"),s.dasharray&&n.setAttribute(\"stroke-dasharray\",s.dasharray),n}attr(t,e){this.el.setAttribute(t,typeof e==\"string\"?e:e.toFixed(L))}_setEvent(t){this.event=t,this.point=this.getMousePosition(t)}_eventDown(t){return this._setEvent(t),this.start=this.point,this.onStart(this.point)}_eventMove(t){return this._setEvent(t),this.onMove(this.point)}_eventUp(t){return this._setEvent(t),this.onEnd(this.point)}},te=class $ extends O{constructor(...e){super(...e),this.points=[],this.count=0}onStart(e){if(this.el=this.createElement(\"path\",{fill:\"transparent\"}),this.points=[e],this.brush.arrowEnd){this.arrowId=kt();let n=It(this.arrowId,this.brush.color);this.el.appendChild(n)}return this.el}onMove(e){return this.el||this.onStart(e),this.points[this.points.length-1]!==e&&(this.points.push(e),this.count+=1),this.count>5&&(this.points=Pt(this.points,1,!0),this.count=0),this.attr(\"d\",$.toSvgData(this.points)),!0}onEnd(){let e=this.el;if(this.el=null,!e)return!1;if(e.setAttribute(\"d\",$.toSvgData(Pt(this.points,1,!0))),!e.getTotalLength()){let{x:n,y:s}=this.points[0],i=this.brush.size/2;e.setAttribute(\"d\",`M ${n-i} ${s} a ${i},${i} 0 1,0 ${i*2},0 a ${i},${i} 0 1,0 ${-i*2},0`),e.setAttribute(\"fill\",this.brush.color),e.setAttribute(\"stroke-width\",\"0\")}return!0}static line(e,n){let s=n.x-e.x,i=n.y-e.y;return{length:Math.sqrt(s**2+i**2),angle:Math.atan2(i,s)}}static controlPoint(e,n,s,i){let r=n||e,a=s||e,o=.2,h=$.line(r,a),p=h.angle+(i?Math.PI:0),w=h.length*o;return{x:e.x+Math.cos(p)*w,y:e.y+Math.sin(p)*w}}static bezierCommand(e,n,s){let i=$.controlPoint(s[n-1],s[n-2],e),r=$.controlPoint(e,s[n-1],s[n+1],!0);return`C ${i.x.toFixed(L)},${i.y.toFixed(L)} ${r.x.toFixed(L)},${r.y.toFixed(L)} ${e.x.toFixed(L)},${e.y.toFixed(L)}`}static toSvgData(e){return e.reduce((n,s,i,r)=>i===0?`M ${s.x.toFixed(L)},${s.y.toFixed(L)}`:`${n} ${$.bezierCommand(s,i,r)}`,\"\")}},ee=class extends O{onStart(t){return this.el=this.createElement(\"ellipse\"),this.attr(\"cx\",t.x),this.attr(\"cy\",t.y),this.el}onMove(t){if(!this.el||!this.start)return!1;let[e,n]=tt(t.x-this.start.x),[s,i]=tt(t.y-this.start.y);if(this.shiftPressed){let r=Math.min(e,s);e=r,s=r}if(this.altPressed)this.attr(\"cx\",this.start.x),this.attr(\"cy\",this.start.y),this.attr(\"rx\",e),this.attr(\"ry\",s);else{let[r,a]=[this.start.x,this.start.x+e*n].sort(Q),[o,h]=[this.start.y,this.start.y+s*i].sort(Q);this.attr(\"cx\",(r+a)/2),this.attr(\"cy\",(o+h)/2),this.attr(\"rx\",(a-r)/2),this.attr(\"ry\",(h-o)/2)}return!0}onEnd(){let t=this.el;if(this.el=null,!t)return!1;try{if(!t.getTotalLength())return!1}catch{return!1}return!0}},ne=class extends O{constructor(...t){super(...t),this.pathSubFactor=20,this.pathFragments=[],this._erased=[]}onSelected(t){let e=(n,s)=>{if(n&&n.length)for(let i=0;i<n.length;i++){let r=n[i];if(r.getTotalLength){let a=r.getTotalLength();for(let o=0;o<this.pathSubFactor;o++){let h=r.getPointAtLength(a*o/this.pathSubFactor),p=r.getPointAtLength(a*(o+1)/this.pathSubFactor);this.pathFragments.push({x1:h.x,x2:p.x,y1:h.y,y2:p.y,segment:o,element:s||r})}}else r.children&&e(r.children,r)}};t&&e(t.children)}onUnselected(){this.pathFragments=[]}onStart(t){this.svgPointPrevious=this.svgElement.createSVGPoint(),this.svgPointPrevious.x=t.x,this.svgPointPrevious.y=t.y}onMove(t){this.svgPointCurrent=this.svgElement.createSVGPoint(),this.svgPointCurrent.x=t.x,this.svgPointCurrent.y=t.y;let e=this.checkAndEraseElement();return this.svgPointPrevious=this.svgPointCurrent,e}onEnd(){this.svgPointPrevious=void 0,this.svgPointCurrent=void 0;let t=this._erased;return this._erased=[],{undo:()=>t.forEach(e=>this.drauu._restoreNode(e)),redo:()=>t.forEach(e=>this.drauu._removeNode(e))}}checkAndEraseElement(){if(this.pathFragments.length)for(let t=0;t<this.pathFragments.length;t++){let e=this.pathFragments[t];if(this.svgPointPrevious&&this.svgPointCurrent){let n={x1:this.svgPointPrevious.x,x2:this.svgPointCurrent.x,y1:this.svgPointPrevious.y,y2:this.svgPointCurrent.y};this.lineLineIntersect(e,n)&&(this.drauu._removeNode(e.element),this._erased.push(e.element))}}return this._erased.length&&(this.pathFragments=this.pathFragments.filter(t=>!this._erased.includes(t.element))),this._erased.length>0}lineLineIntersect(t,e){let n=t.x1,s=t.x2,i=e.x1,r=e.x2,a=t.y1,o=t.y2,h=e.y1,p=e.y2,w=(n-s)*(h-p)-(a-o)*(i-r),E=(n*o-a*s)*(i-r)-(n-s)*(i*p-h*r),F=(n*o-a*s)*(h-p)-(a-o)*(i*p-h*r),m=(u,b,D)=>u>=b&&u<=D?!0:u>=D&&u<=b;if(w===0)return!1;{let u={x:E/w,y:F/w};return m(u.x,n,s)&&m(u.y,a,o)&&m(u.x,i,r)&&m(u.y,h,p)}}},se=class extends O{onStart(t){if(this.el=this.createElement(\"line\",{fill:\"transparent\"}),this.attr(\"x1\",t.x),this.attr(\"y1\",t.y),this.attr(\"x2\",t.x),this.attr(\"y2\",t.y),this.brush.arrowEnd){let e=kt(),n=document.createElementNS(\"http://www.w3.org/2000/svg\",\"g\");return n.append(It(e,this.brush.color)),n.append(this.el),this.attr(\"marker-end\",`url(#${e})`),n}return this.el}onMove(t){if(!this.el)return!1;let{x:e,y:n}=t;if(this.shiftPressed){let s=t.x-this.start.x,i=t.y-this.start.y;if(i!==0){let r=s/i;r=Math.round(r),Math.abs(r)<=1?(e=this.start.x+i*r,n=this.start.y+i):(e=this.start.x+s,n=this.start.y)}}return this.altPressed?(this.attr(\"x1\",this.start.x*2-e),this.attr(\"y1\",this.start.y*2-n),this.attr(\"x2\",e),this.attr(\"y2\",n)):(this.attr(\"x1\",this.start.x),this.attr(\"y1\",this.start.y),this.attr(\"x2\",e),this.attr(\"y2\",n)),!0}onEnd(){let t=this.el;if(this.el=null,!t)return!1;try{if(t.getTotalLength()<5)return!1}catch{return!1}return!0}},ie=class extends O{onStart(t){return this.el=this.createElement(\"rect\"),this.brush.cornerRadius&&(this.attr(\"rx\",this.brush.cornerRadius),this.attr(\"ry\",this.brush.cornerRadius)),this.attr(\"x\",t.x),this.attr(\"y\",t.y),this.el}onMove(t){if(!this.el||!this.start)return!1;let[e,n]=tt(t.x-this.start.x),[s,i]=tt(t.y-this.start.y);if(this.shiftPressed){let r=Math.min(e,s);e=r,s=r}if(this.altPressed)this.attr(\"x\",this.start.x-e),this.attr(\"y\",this.start.y-s),this.attr(\"width\",e*2),this.attr(\"height\",s*2);else{let[r,a]=[this.start.x,this.start.x+e*n].sort(Q),[o,h]=[this.start.y,this.start.y+s*i].sort(Q);this.attr(\"x\",r),this.attr(\"y\",o),this.attr(\"width\",a-r),this.attr(\"height\",h-o)}return!0}onEnd(){let t=this.el;if(this.el=null,!t)return!1;try{if(!t.getTotalLength())return!1}catch{return!1}return!0}};function Mt(t,e,n,s=i=>i){return t*s(.5-e*(.5-n))}function re(t){return[-t[0],-t[1]]}function M(t,e){return[t[0]+e[0],t[1]+e[1]]}function _(t,e){return[t[0]-e[0],t[1]-e[1]]}function P(t,e){return[t[0]*e,t[1]*e]}function oe(t,e){return[t[0]/e,t[1]/e]}function U(t){return[t[1],-t[0]]}function Lt(t,e){return t[0]*e[0]+t[1]*e[1]}function ae(t,e){return t[0]===e[0]&&t[1]===e[1]}function he(t){return Math.hypot(t[0],t[1])}function le(t){return t[0]*t[0]+t[1]*t[1]}function Dt(t,e){return le(_(t,e))}function Tt(t){return oe(t,he(t))}function ue(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function G(t,e,n){let s=Math.sin(n),i=Math.cos(n),r=t[0]-e[0],a=t[1]-e[1],o=r*i-a*s,h=r*s+a*i;return[o+e[0],h+e[1]]}function gt(t,e,n){return M(t,P(_(e,t),n))}function At(t,e,n){return M(t,P(e,n))}var{min:z,PI:ce}=Math,Nt=.275,V=ce+1e-4;function de(t,e={}){let{size:n=16,smoothing:s=.5,thinning:i=.5,simulatePressure:r=!0,easing:a=l=>l,start:o={},end:h={},last:p=!1}=e,{cap:w=!0,easing:E=l=>l*(2-l)}=o,{cap:F=!0,easing:m=l=>--l*l*l+1}=h;if(t.length===0||n<=0)return[];let u=t[t.length-1].runningLength,b=o.taper===!1?0:o.taper===!0?Math.max(n,u):o.taper,D=h.taper===!1?0:h.taper===!0?Math.max(n,u):h.taper,bt=Math.pow(n*s,2),B=[],R=[],rt=t.slice(0,10).reduce((l,v)=>{let d=v.pressure;if(r){let f=z(1,v.distance/n);d=z(1,l+(z(1,1-f)-l)*(f*Nt))}return(l+d)/2},t[0].pressure),x=Mt(n,i,t[t.length-1].pressure,a),ot,at=t[0].vector,j=t[0].point,Y=j,T=j,C=Y,ht=!1;for(let l=0;l<t.length;l++){let{pressure:v}=t[l],{point:d,vector:f,distance:qt,runningLength:q}=t[l];if(l<t.length-1&&u-q<3)continue;if(i){if(r){let k=z(1,qt/n),ct=z(1,1-k);v=z(1,rt+(ct-rt)*(k*Nt))}x=Mt(n,i,v,a)}else x=n/2;ot===void 0&&(ot=x);let Ut=q<b?E(q/b):1,Gt=u-q<D?m((u-q)/D):1;x=Math.max(.01,x*Math.min(Ut,Gt));let St=(l<t.length-1?t[l+1]:t[l]).vector,ut=l<t.length-1?Lt(f,St):1,Vt=Lt(f,at)<0&&!ht,Et=ut!==null&&ut<0;if(Vt||Et){let k=P(U(at),x);for(let ct=1/13,J=0;J<=1;J+=ct)T=G(_(d,k),d,V*J),B.push(T),C=G(M(d,k),d,V*-J),R.push(C);j=T,Y=C,Et&&(ht=!0);continue}if(ht=!1,l===t.length-1){let k=P(U(f),x);B.push(_(d,k)),R.push(M(d,k));continue}let _t=P(U(gt(St,f,ut)),x);T=_(d,_t),(l<=1||Dt(j,T)>bt)&&(B.push(T),j=T),C=M(d,_t),(l<=1||Dt(Y,C)>bt)&&(R.push(C),Y=C),rt=v,at=f}let A=t[0].point.slice(0,2),N=t.length>1?t[t.length-1].point.slice(0,2):M(t[0].point,[1,1]),lt=[],Z=[];if(t.length===1){if(!(b||D)||p){let l=At(A,Tt(U(_(A,N))),-(ot||x)),v=[];for(let d=1/13,f=d;f<=1;f+=d)v.push(G(l,A,V*2*f));return v}}else{if(!(b||D&&t.length===1))if(w)for(let v=1/13,d=v;d<=1;d+=v){let f=G(R[0],A,V*d);lt.push(f)}else{let v=_(B[0],R[0]),d=P(v,.5),f=P(v,.51);lt.push(_(A,d),_(A,f),M(A,f),M(A,d))}let l=U(re(t[t.length-1].vector));if(D||b&&t.length===1)Z.push(N);else if(F){let v=At(N,l,x);for(let d=1/29,f=d;f<1;f+=d)Z.push(G(v,N,V*3*f))}else Z.push(M(N,P(l,x)),M(N,P(l,x*.99)),_(N,P(l,x*.99)),_(N,P(l,x)))}return B.concat(Z,R.reverse(),lt)}function ge(t,e={}){var n;let{streamline:s=.5,size:i=16,last:r=!1}=e;if(t.length===0)return[];let a=.15+(1-s)*.85,o=Array.isArray(t[0])?t:t.map(({x:m,y:u,pressure:b=.5})=>[m,u,b]);if(o.length===2){let m=o[1];o=o.slice(0,-1);for(let u=1;u<5;u++)o.push(gt(o[0],m,u/4))}o.length===1&&(o=[...o,[...M(o[0],[1,1]),...o[0].slice(2)]]);let h=[{point:[o[0][0],o[0][1]],pressure:o[0][2]>=0?o[0][2]:.25,vector:[1,1],distance:0,runningLength:0}],p=!1,w=0,E=h[0],F=o.length-1;for(let m=1;m<o.length;m++){let u=r&&m===F?o[m].slice(0,2):gt(E.point,o[m],a);if(ae(E.point,u))continue;let b=ue(u,E.point);if(w+=b,m<F&&!p){if(w<i)continue;p=!0}E={point:u,pressure:o[m][2]>=0?o[m][2]:.5,vector:Tt(_(E.point,u)),distance:b,runningLength:w},h.push(E)}return h[0].vector=((n=h[1])==null?void 0:n.vector)||[0,0],h}function fe(t,e={}){return de(ge(t,e),e)}var pe=class Ct extends O{constructor(...e){super(...e),this.points=[]}onStart(e){return this.el=document.createElementNS(\"http://www.w3.org/2000/svg\",\"path\"),this.points=[e],this.attr(\"fill\",this.brush.color),this.attr(\"d\",this.getSvgData(this.points)),this.el}onMove(e){return this.el||this.onStart(e),this.points[this.points.length-1]!==e&&this.points.push(e),this.attr(\"d\",this.getSvgData(this.points)),!0}onEnd(){let e=this.el;return this.el=null,!!e}getSvgData(e){return Ct.getSvgData(e,this.brush)}static getSvgData(e,n){let s=fe(e,{size:n.size,thinning:.9,simulatePressure:!1,start:{taper:5},end:{taper:5},...n.stylusOptions});if(!s.length)return\"\";let i=s.reduce((r,[a,o],h,p)=>{let[w,E]=p[(h+1)%p.length];return r.push(a,o,(a+w)/2,(o+E)/2),r},[\"M\",...s[0],\"Q\"]);return i.push(\"Z\"),i.map(r=>typeof r==\"number\"?r.toFixed(2):r).join(\" \")}};function me(t){return{draw:new te(t),stylus:new pe(t),line:new se(t),rectangle:new ie(t),ellipse:new ee(t),eraseLine:new ne(t)}}var ve=class{constructor(t={}){this.options=t,this.el=null,this.svgPoint=null,this.eventEl=null,this.shiftPressed=!1,this.altPressed=!1,this.drawing=!1,this._emitter=Kt(),this._originalPointerId=null,this._models=me(this),this._opStack=[],this._opIndex=0,this._disposables=[],this._elements=[],this.options.brush||(this.options.brush={color:\"black\",size:3,mode:\"stylus\"}),t.el&&this.mount(t.el,t.eventTarget,t.window)}get model(){return this._models[this.mode]}get mounted(){return!!this.el}get mode(){return this.options.brush.mode||\"stylus\"}set mode(t){this._models[this.mode].onUnselected(),this.options.brush.mode=t,this.model.onSelected(this.el)}get brush(){return this.options.brush}set brush(t){this.options.brush=t}resolveSelector(t){return typeof t==\"string\"?document.querySelector(t):t||null}mount(t,e,n=window){if(this.el)throw new Error(\"[drauu] already mounted, unmount previous target first\");if(this.el=this.resolveSelector(t),!this.el)throw new Error(\"[drauu] target element not found\");if(this.el.tagName.toLocaleLowerCase()!==\"svg\")throw new Error(\"[drauu] can only mount to a SVG element\");if(!this.el.createSVGPoint)throw new Error(\"[drauu] SVG element must be create by document.createElementNS('http://www.w3.org/2000/svg', 'svg')\");this.svgPoint=this.el.createSVGPoint();let s=this.resolveSelector(e)||this.el,i=this.eventStart.bind(this),r=this.eventMove.bind(this),a=this.eventEnd.bind(this),o=this.eventKeyboard.bind(this),h=this.touchMove.bind(this);s.addEventListener(\"pointerdown\",i,{passive:!1}),n.addEventListener(\"pointermove\",r,{passive:!1}),n.addEventListener(\"pointerup\",a,{passive:!1}),n.addEventListener(\"pointercancel\",a,{passive:!1}),n.addEventListener(\"keydown\",o,!1),n.addEventListener(\"keyup\",o,!1),n.addEventListener(\"touchmove\",h,{passive:!1}),this._disposables.push(()=>{s.removeEventListener(\"pointerdown\",i),n.removeEventListener(\"pointermove\",r),n.removeEventListener(\"pointerup\",a),n.removeEventListener(\"pointercancel\",a),n.removeEventListener(\"keydown\",o,!1),n.removeEventListener(\"keyup\",o,!1),n.removeEventListener(\"touchmove\",h)}),this._emitter.emit(\"mounted\")}unmount(){this._disposables.forEach(t=>t()),this._disposables.length=0,this._elements.length=0,this.el=null,this._emitter.emit(\"unmounted\")}on(t,e){return this._emitter.on(t,e)}undo(){return!this.canUndo()||this.drawing?!1:(this._opStack[--this._opIndex].undo(),this._emitter.emit(\"changed\"),!0)}redo(){return!this.canRedo()||this.drawing?!1:(this._opStack[this._opIndex++].redo(),this._emitter.emit(\"changed\"),!0)}canRedo(){return this._opIndex<this._opStack.length}canUndo(){return this._opIndex>0}eventMove(t){!this.acceptsInput(t)||!this.drawing||this.model._eventMove(t)&&(t.stopPropagation(),t.preventDefault(),this._emitter.emit(\"changed\"))}eventStart(t){this.acceptsInput(t)&&(t.stopPropagation(),t.preventDefault(),this._currentNode&&this.cancel(),this.drawing=!0,this._originalPointerId=t.pointerId,this._emitter.emit(\"start\"),this._currentNode=this.model._eventDown(t),this._currentNode&&this.mode!==\"eraseLine\"&&this.el.appendChild(this._currentNode),this._emitter.emit(\"changed\"))}eventEnd(t){if(!this.acceptsInput(t)||!this.drawing)return;let e=this.model._eventUp(t);if(!e)this.cancel();else if(e===!0){let n=this._currentNode;n&&(this._appendNode(n),this.commit({undo:()=>this._removeNode(n),redo:()=>this._restoreNode(n)}))}else this.commit(e);this.drawing=!1,this._emitter.emit(\"end\"),this._emitter.emit(\"changed\"),this._originalPointerId=null}touchMove(t){Array.from(t.touches).some(e=>e.touchType===\"stylus\"&&e.identifier===this._originalPointerId)&&t.preventDefault()}acceptsInput(t){return(!this.options.acceptsInputTypes||this.options.acceptsInputTypes.includes(t.pointerType))&&!(this._originalPointerId&&this._originalPointerId!==t.pointerId)}eventKeyboard(t){this.shiftPressed===t.shiftKey&&this.altPressed===t.altKey||(this.shiftPressed=t.shiftKey,this.altPressed=t.altKey,this.model.point&&this.model.onMove(this.model.point)&&this._emitter.emit(\"changed\"))}commit(t){this._opStack.length=this._opIndex,this._opStack.push(t),this._opIndex++;let e=this._currentNode;this._currentNode=void 0,this._emitter.emit(\"committed\",e)}clear(){this._opStack.length=0,this._opIndex=0,this._elements=[],this.cancel(),this.el.innerHTML=\"\",this._emitter.emit(\"changed\")}cancel(){this._currentNode&&(this.el.removeChild(this._currentNode),this._currentNode=void 0,this._emitter.emit(\"canceled\"))}dump(){return this.el.innerHTML}load(t){this.clear(),this.el.innerHTML=t}_appendNode(t){let e=this._elements.at(-1);e?e.after(t):this.el.append(t);let n=this._elements.push(t)-1;t.dataset.drauu_index=n.toString()}_removeNode(t){t.remove(),this._elements[+t.dataset.drauu_index]=null}_restoreNode(t){let e=+t.dataset.drauu_index;this._elements[e]=t;for(let n=e-1;n>=0;n--){let s=this._elements[n];if(s){s.after(t);return}}this.el.prepend(t)}};function $t(t){return new ve(t)}var ft=document.body,H=X(\"#openplan-plan-frame\"),ye=X(\"#openplan-annotation-status\"),et=X(\"#openplan-annotation-color\"),mt=X(\"#openplan-annotation-width\"),Ot=X(\"#openplan-annotation-toolbar\"),vt=[\"openplan-annotations-v1\",ft.dataset.draftId,ft.dataset.versionId,ft.dataset.contentHash].join(\":\"),S=null,g=null,c=null,I=null,nt=\"pan\",K=!0,W=[],pt=null;H.addEventListener(\"load\",()=>void Bt());H.contentDocument?.readyState===\"complete\"&&Bt();Ot.addEventListener(\"click\",t=>{let e=t.target?.closest(\"button[data-action]\");e&&we(e.dataset.action||\"\")});et.addEventListener(\"input\",wt);mt.addEventListener(\"input\",wt);async function Bt(){if(!H.contentDocument||!H.contentWindow||!H.contentDocument.body)return;c=H.contentDocument,I=H.contentWindow,c.documentElement.style.position=\"relative\",c.body.style.position||=\"relative\",g?.remove(),g=c.createElementNS(\"http://www.w3.org/2000/svg\",\"svg\"),g.setAttribute(\"aria-hidden\",\"true\"),g.style.position=\"absolute\",g.style.inset=\"0 auto auto 0\",g.style.zIndex=\"2147483646\",g.style.pointerEvents=\"none\",g.style.touchAction=\"none\",g.style.overflow=\"visible\",c.body.append(g),Ht();let t=new ResizeObserver(Ht);t.observe(c.documentElement),t.observe(c.body),S?.unmount(),S=$t({el:g,eventTarget:g,window:I,brush:{mode:\"draw\",color:et.value,size:Number(mt.value)}}),S.on(\"changed\",it),Se(),c.addEventListener(\"mouseup\",xe);let e=await Ee();e?(S.load(e.svg),W=e.highlights||[],st(),e.viewportWidth&&Math.abs(e.viewportWidth-c.documentElement.clientWidth)>240?y(\"Restored annotations; this plan is displayed at a different width, so drawings may have shifted.\"):y(\"Restored annotations from this browser.\")):y(\"Annotations are stored only in this browser.\"),yt(\"pan\")}async function we(t){if(!(!S||!g)){if(t===\"pan\"||t===\"pen\"||t===\"highlighter\"||t===\"text\"){yt(t);return}if(t===\"undo\"){S.undo(),it();return}if(t===\"redo\"){S.redo(),it();return}if(t===\"visibility\"){K=!K,g.style.display=K?\"block\":\"none\",st(),y(K?\"Annotations shown.\":\"Annotations hidden.\");return}if(t===\"clear\"){if(!window.confirm(\"Clear drawings and highlights stored for this plan version in this browser?\"))return;S.clear(),W=[],st(),await Pe(),y(\"Local annotations cleared.\");return}if(t===\"export-json\"){zt(\"openplan-annotations.json\",JSON.stringify(jt(),null,2),\"application/json\"),y(\"Exported annotation data.\");return}if(t===\"export-svg\"){let e=g.getAttribute(\"width\")||\"0\",n=g.getAttribute(\"height\")||\"0\";zt(\"openplan-annotations.svg\",`<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${e}\" height=\"${n}\" viewBox=\"0 0 ${e} ${n}\">${S.dump()}</svg>`,\"image/svg+xml\"),y(\"Exported drawing SVG.\")}}}function yt(t){if(!S||!g)return;nt=t;let e=t===\"pen\"||t===\"highlighter\";if(g.style.pointerEvents=e?\"auto\":\"none\",c?.documentElement.classList.toggle(\"openplan-annotation-drawing\",e),Ot.querySelectorAll(\"button[data-action]\").forEach(n=>{n.classList.toggle(\"active\",n.dataset.action===t),n.setAttribute(\"aria-pressed\",String(n.dataset.action===t))}),wt(),t===\"text\"){let n=I?.CSS?.highlights;y(n?\"Select text in the plan to highlight it.\":\"Native text highlights are unavailable in this browser; use the marker tool instead.\")}else y(e?`${t===\"pen\"?\"Pen\":\"Highlighter\"} active. Press Escape or choose Browse to stop drawing.`:\"Browse mode active.\")}function wt(){if(!S)return;let t=\"draw\",e=nt===\"highlighter\"?`${et.value}66`:et.value,n=Number(mt.value)*(nt===\"highlighter\"?3:1);S.brush={mode:t,color:e,size:n}}function Ht(){if(!g||!c)return;let t=c.documentElement,e=c.body,n=Math.max(t.scrollWidth,t.clientWidth,e.scrollWidth),s=Math.max(t.scrollHeight,t.clientHeight,e.scrollHeight);g.setAttribute(\"width\",String(n)),g.setAttribute(\"height\",String(s)),g.setAttribute(\"viewBox\",`0 0 ${n} ${s}`)}function xe(){if(nt!==\"text\"||!I||!c)return;let t=I.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return;let e=t.getRangeAt(0),n=be(e);!n||!n.text.trim()||(W.push(n),t.removeAllRanges(),st(),it(),y(\"Text highlight saved in this browser.\"))}function be(t){if(!c?.body)return null;let e=Ft(c.body,t.startContainer),n=Ft(c.body,t.endContainer);return!e||!n?null:{startPath:e,startOffset:t.startOffset,endPath:n,endOffset:t.endOffset,text:t.toString()}}function Ft(t,e){let n=[],s=e;for(;s&&s!==t;){let i=s.parentNode;if(!i)return null;n.unshift(Array.prototype.indexOf.call(i.childNodes,s)),s=i}return s===t?n:null}function Rt(t,e){let n=t;for(let s of e)n=n?.childNodes.item(s)||null;return n}function st(){if(!I||!c?.body)return;let e=I.CSS?.highlights;if(!e||(e.delete(\"openplan-local-annotations\"),!K))return;let n=W.flatMap(i=>{let r=Rt(c.body,i.startPath),a=Rt(c.body,i.endPath);if(!r||!a)return[];try{let o=c.createRange();return o.setStart(r,i.startOffset),o.setEnd(a,i.endOffset),o.toString()===i.text?[o]:[]}catch{return[]}}),s=I.Highlight;s&&n.length&&e.set(\"openplan-local-annotations\",new s(...n))}function Se(){if(!c||c.getElementById(\"openplan-annotation-highlight-style\"))return;let t=c.createElement(\"style\");t.id=\"openplan-annotation-highlight-style\",t.textContent=`\n ::highlight(openplan-local-annotations) { background: rgba(250, 204, 21, .48); color: inherit; }\n html.openplan-annotation-drawing, html.openplan-annotation-drawing * { cursor: crosshair !important; user-select: none !important; }\n `,c.head.append(t)}function it(){pt!==null&&window.clearTimeout(pt),pt=window.setTimeout(()=>void _e(jt()),180)}function jt(){return{schema:1,svg:S?.dump()||\"\",viewportWidth:c?.documentElement.clientWidth||0,highlights:W}}function y(t){ye.textContent=t}function zt(t,e,n){let s=URL.createObjectURL(new Blob([e],{type:n})),i=document.createElement(\"a\");i.href=s,i.download=t,i.click(),window.setTimeout(()=>URL.revokeObjectURL(s),0)}function xt(){return new Promise((t,e)=>{let n=indexedDB.open(\"openplan-browser-annotations\",1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(\"documents\")||n.result.createObjectStore(\"documents\")},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function Ee(){try{let t=await xt();return await new Promise((e,n)=>{let s=t.transaction(\"documents\",\"readonly\").objectStore(\"documents\").get(vt);s.onsuccess=()=>e(s.result||null),s.onerror=()=>n(s.error)})}catch{return y(\"Browser storage is unavailable; annotations will last only until this page closes.\"),null}}async function _e(t){try{let e=await xt();await new Promise((n,s)=>{let i=e.transaction(\"documents\",\"readwrite\").objectStore(\"documents\").put(t,vt);i.onsuccess=()=>n(),i.onerror=()=>s(i.error)}),y(\"Saved in this browser.\")}catch{y(\"Could not save annotations in browser storage. Export them before leaving this page.\")}}async function Pe(){try{let t=await xt();await new Promise((e,n)=>{let s=t.transaction(\"documents\",\"readwrite\").objectStore(\"documents\").delete(vt);s.onsuccess=()=>e(),s.onerror=()=>n(s.error)})}catch{y(\"The drawing was cleared, but browser storage could not be updated.\")}}window.addEventListener(\"keydown\",t=>{t.key===\"Escape\"&&yt(\"pan\")});function X(t){let e=document.querySelector(t);if(!e)throw new Error(`Annotation viewer is missing ${t}.`);return e}})();\n";
2
+ //# sourceMappingURL=annotation-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"annotation-client.js","sourceRoot":"","sources":["../../src/generated/annotation-client.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,iBAAiB,GAAW,6t9BAA6t9B,CAAC"}
@@ -0,0 +1,15 @@
1
+ export interface HtmlStats {
2
+ hasInlineScript: boolean;
3
+ externalImageHosts: string[];
4
+ }
5
+ export interface HtmlValidationResult {
6
+ ok: boolean;
7
+ errors: string[];
8
+ warnings: string[];
9
+ title: string | null;
10
+ hasScripts: boolean;
11
+ stats: HtmlStats;
12
+ }
13
+ export declare function validateHtml(html: unknown, options?: {
14
+ maxBytes?: number;
15
+ }): HtmlValidationResult;
@@ -0,0 +1,172 @@
1
+ import * as parse5 from "parse5";
2
+ const BLOCKED_TAGS = new Set([
3
+ "form",
4
+ "iframe",
5
+ "object",
6
+ "embed",
7
+ "applet",
8
+ "base",
9
+ "link"
10
+ ]);
11
+ const URL_ATTRS = new Set([
12
+ "href",
13
+ "src",
14
+ "action",
15
+ "formaction",
16
+ "poster",
17
+ "srcdoc",
18
+ "xlink:href"
19
+ ]);
20
+ const BLOCKED_PROTOCOLS = ["javascript:", "vbscript:", "file:"];
21
+ const ALLOWED_SCRIPT_TYPES = new Set(["", "text/javascript", "application/javascript"]);
22
+ // Far above any real document (browsers themselves flatten around 512), but
23
+ // well below where the recursive parse5 serializer used for the framed view
24
+ // would overflow the call stack (~2000+ levels).
25
+ const MAX_DEPTH = 512;
26
+ export function validateHtml(html, options = {}) {
27
+ const maxBytes = options.maxBytes ?? 512 * 1024;
28
+ const errors = [];
29
+ const warnings = [];
30
+ if (typeof html !== "string" || html.trim() === "") {
31
+ errors.push("HTML document is empty.");
32
+ return { ok: false, errors, warnings, title: null, hasScripts: false, stats: emptyStats() };
33
+ }
34
+ const byteLength = Buffer.byteLength(html, "utf8");
35
+ if (byteLength > maxBytes) {
36
+ errors.push(`HTML document is ${byteLength} bytes; maximum is ${maxBytes} bytes.`);
37
+ }
38
+ let document;
39
+ try {
40
+ // scriptingEnabled: false so <noscript> children parse as real elements:
41
+ // the hosted viewer renders drafts in an iframe without allow-scripts
42
+ // unless consented, and the policy must see what that frame shows.
43
+ document = parse5.parse(html, { scriptingEnabled: false });
44
+ }
45
+ catch {
46
+ errors.push("HTML document could not be parsed.");
47
+ return { ok: false, errors, warnings, title: null, hasScripts: false, stats: emptyStats() };
48
+ }
49
+ let title = null;
50
+ let hasScripts = false;
51
+ const externalImageHosts = new Set();
52
+ function visit(node) {
53
+ if (node.tagName) {
54
+ const tagName = node.tagName.toLowerCase();
55
+ if (BLOCKED_TAGS.has(tagName)) {
56
+ errors.push(`Blocked <${tagName}> tag found.`);
57
+ }
58
+ if (tagName === "script") {
59
+ hasScripts = true;
60
+ const attributes = new Map((node.attrs || []).map((attr) => [attr.name.toLowerCase(), String(attr.value || "").trim()]));
61
+ if (attributes.has("src")) {
62
+ errors.push("External script sources are not allowed.");
63
+ }
64
+ const scriptType = (attributes.get("type") || "").toLowerCase();
65
+ if (!ALLOWED_SCRIPT_TYPES.has(scriptType)) {
66
+ errors.push(`Unsupported script type "${scriptType}" found.`);
67
+ }
68
+ }
69
+ for (const attr of node.attrs || []) {
70
+ const name = attr.name.toLowerCase();
71
+ const value = String(attr.value || "").trim();
72
+ if (name.startsWith("on")) {
73
+ errors.push(`Blocked inline event handler attribute "${name}" found.`);
74
+ }
75
+ if (name === "srcdoc") {
76
+ errors.push('Blocked "srcdoc" attribute found.');
77
+ }
78
+ if (URL_ATTRS.has(name)) {
79
+ const normalized = value.replace(/[\u0000-\u0020]+/g, "").toLowerCase();
80
+ if (BLOCKED_PROTOCOLS.some((protocol) => normalized.startsWith(protocol))) {
81
+ errors.push(`Blocked unsafe URL in "${name}" attribute.`);
82
+ }
83
+ }
84
+ if (name === "style" && /expression\s*\(|behavior\s*:|url\s*\(\s*javascript:/i.test(value)) {
85
+ errors.push("Blocked unsafe inline CSS.");
86
+ }
87
+ }
88
+ if (tagName === "meta") {
89
+ const httpEquiv = (node.attrs || []).find((attr) => attr.name.toLowerCase() === "http-equiv");
90
+ if (httpEquiv && httpEquiv.value.trim().toLowerCase() === "refresh") {
91
+ errors.push("Blocked meta refresh tag found.");
92
+ }
93
+ }
94
+ // Images are the one external resource the serving CSP allows (img-src
95
+ // https: data:), so record which hosts a draft pulls from for later review.
96
+ if (tagName === "img") {
97
+ const src = (node.attrs || []).find((attr) => attr.name.toLowerCase() === "src");
98
+ const host = externalHost(src?.value);
99
+ if (host)
100
+ externalImageHosts.add(host);
101
+ }
102
+ }
103
+ if (node.tagName === "title" && !title) {
104
+ title = collectText(node).trim().slice(0, 140) || null;
105
+ }
106
+ }
107
+ let tooDeep = false;
108
+ const stack = [{ node: document, depth: 0 }];
109
+ while (stack.length) {
110
+ const current = stack.pop();
111
+ if (!current)
112
+ break;
113
+ const { node, depth } = current;
114
+ visit(node);
115
+ if (depth >= MAX_DEPTH) {
116
+ tooDeep = true;
117
+ continue;
118
+ }
119
+ const children = node.childNodes || [];
120
+ for (let i = children.length - 1; i >= 0; i--) {
121
+ stack.push({ node: children[i], depth: depth + 1 });
122
+ }
123
+ }
124
+ if (tooDeep) {
125
+ errors.push(`HTML is nested more than ${MAX_DEPTH} levels deep.`);
126
+ }
127
+ if (!title) {
128
+ warnings.push("No <title> found; Openplan will use a generic title.");
129
+ }
130
+ return {
131
+ ok: errors.length === 0,
132
+ errors: [...new Set(errors)],
133
+ warnings: [...new Set(warnings)],
134
+ title,
135
+ hasScripts,
136
+ stats: {
137
+ hasInlineScript: hasScripts,
138
+ externalImageHosts: [...externalImageHosts].sort()
139
+ }
140
+ };
141
+ }
142
+ function emptyStats() {
143
+ return { hasInlineScript: false, externalImageHosts: [] };
144
+ }
145
+ // Returns the lowercased host of an absolute http(s) (or protocol-relative) URL,
146
+ // or null for relative paths, data: URIs, and anything unparseable.
147
+ function externalHost(value) {
148
+ const raw = String(value || "").trim();
149
+ if (!raw)
150
+ return null;
151
+ const candidate = raw.startsWith("//") ? `https:${raw}` : raw;
152
+ try {
153
+ const url = new URL(candidate);
154
+ if (url.protocol === "http:" || url.protocol === "https:") {
155
+ return url.hostname.toLowerCase();
156
+ }
157
+ }
158
+ catch {
159
+ // relative path, data: URI, etc. — not an external host
160
+ }
161
+ return null;
162
+ }
163
+ function collectText(node) {
164
+ let value = "";
165
+ for (const child of node.childNodes || []) {
166
+ if (child.nodeName === "#text")
167
+ value += child.value || "";
168
+ value += collectText(child);
169
+ }
170
+ return value;
171
+ }
172
+ //# sourceMappingURL=html-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"html-policy.js","sourceRoot":"","sources":["../src/html-policy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAEjC,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC;IAC3B,MAAM;IACN,QAAQ;IACR,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,MAAM;IACN,MAAM;CACP,CAAC,CAAC;AAEH,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC;IACxB,MAAM;IACN,KAAK;IACL,QAAQ;IACR,YAAY;IACZ,QAAQ;IACR,QAAQ;IACR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AC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACvC,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IACtB,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IAC9D,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC;QAC/B,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;YAC1D,OAAO,GAAG,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;QACpC,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,wDAAwD;IAC1D,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,WAAW,CAAC,IAAc;IACjC,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;QAC1C,IAAI,KAAK,CAAC,QAAQ,KAAK,OAAO;YAAE,KAAK,IAAI,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;QAC3D,KAAK,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
package/dist/ids.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare function newDraftId(): string;
2
+ export declare function newInternalId(): string;
package/dist/ids.js ADDED
@@ -0,0 +1,10 @@
1
+ import { customAlphabet } from "nanoid";
2
+ const draftId = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyz", 12);
3
+ const internalId = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 20);
4
+ export function newDraftId() {
5
+ return draftId();
6
+ }
7
+ export function newInternalId() {
8
+ return internalId();
9
+ }
10
+ //# sourceMappingURL=ids.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ids.js","sourceRoot":"","sources":["../src/ids.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAExC,MAAM,OAAO,GAAG,cAAc,CAAC,sCAAsC,EAAE,EAAE,CAAC,CAAC;AAC3E,MAAM,UAAU,GAAG,cAAc,CAAC,gEAAgE,EAAE,EAAE,CAAC,CAAC;AAExG,MAAM,UAAU,UAAU;IACxB,OAAO,OAAO,EAAE,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,UAAU,EAAE,CAAC;AACtB,CAAC"}
@@ -0,0 +1,36 @@
1
+ import type { Request } from "express";
2
+ import type { SessionPayload } from "./types.js";
3
+ export interface LocalAccount {
4
+ accountId: string;
5
+ accountName: string;
6
+ username: string;
7
+ isAdmin: boolean;
8
+ sessionVersion: number;
9
+ }
10
+ export interface LocalUserSummary {
11
+ accountId: string;
12
+ accountName: string;
13
+ username: string;
14
+ isAdmin: boolean;
15
+ createdAt: string;
16
+ }
17
+ export declare function bootstrapLocalAdministrator(input: {
18
+ username: string;
19
+ password: string;
20
+ displayName?: string;
21
+ }): Promise<LocalAccount>;
22
+ export declare function createLocalUser(input: {
23
+ username: string;
24
+ password: string;
25
+ displayName?: string;
26
+ isAdmin?: boolean;
27
+ }): Promise<LocalAccount>;
28
+ export declare function authenticateLocalUser(req: Request, username: string, password: string): Promise<LocalAccount | null>;
29
+ export declare function readWebSession(req: Request): Promise<SessionPayload | null>;
30
+ export declare function changeLocalPassword(input: {
31
+ accountId: string;
32
+ currentPassword: string;
33
+ newPassword: string;
34
+ }): Promise<number>;
35
+ export declare function listLocalUsers(): Promise<LocalUserSummary[]>;
36
+ export declare function normalizeUsername(value: string): string;
@@ -0,0 +1,215 @@
1
+ import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
2
+ import { clientIp } from "./client-ip.js";
3
+ import { browserAuthProvider, config, requireOidcSettings } from "./config.js";
4
+ import { oidcSessionBinding } from "./oidc.js";
5
+ import { pool, withTransaction } from "./db.js";
6
+ import { newInternalId } from "./ids.js";
7
+ import { readSession } from "./web-auth.js";
8
+ const PASSWORD_ALGORITHM = "scrypt-v1";
9
+ const SCRYPT_PARAMETERS = { N: 16_384, r: 8, p: 1, keyLength: 64, maxmem: 64 * 1024 * 1024 };
10
+ const MAX_FAILED_ATTEMPTS = 10;
11
+ const LOCKOUT_MS = 15 * 60 * 1000;
12
+ export async function bootstrapLocalAdministrator(input) {
13
+ assertSelfHosted();
14
+ return withTransaction(async (client) => {
15
+ const count = await client.query("SELECT COUNT(*) AS count FROM local_credentials");
16
+ if (Number(count.rows[0]?.count || 0) > 0) {
17
+ throw new Error("A local Openplan account already exists; bootstrap is disabled.");
18
+ }
19
+ return createLocalAccount(client, { ...input, isAdmin: true });
20
+ });
21
+ }
22
+ export async function createLocalUser(input) {
23
+ assertSelfHosted();
24
+ return withTransaction((client) => createLocalAccount(client, {
25
+ ...input,
26
+ isAdmin: input.isAdmin === true
27
+ }));
28
+ }
29
+ export async function authenticateLocalUser(req, username, password) {
30
+ assertSelfHosted();
31
+ const normalized = normalizeUsername(username);
32
+ const result = await pool.query(`
33
+ SELECT lc.*, a.name AS account_name, a.is_admin
34
+ FROM local_credentials lc
35
+ JOIN accounts a ON a.id = lc.account_id
36
+ WHERE lc.username_normalized = $1
37
+ LIMIT 1
38
+ `, [normalized]);
39
+ const row = result.rows[0];
40
+ if (!row) {
41
+ await recordAuthEvent(null, normalized, "login_failed_unknown", clientIp(req));
42
+ await burnPasswordWork(password);
43
+ return null;
44
+ }
45
+ if (row.locked_until && new Date(row.locked_until).getTime() > Date.now()) {
46
+ await recordAuthEvent(row.account_id, normalized, "login_rejected_locked", clientIp(req));
47
+ return null;
48
+ }
49
+ const valid = await verifyPassword(password, row);
50
+ if (!valid) {
51
+ const attempts = Number(row.failed_attempts || 0) + 1;
52
+ const lockedUntil = attempts >= MAX_FAILED_ATTEMPTS
53
+ ? new Date(Date.now() + LOCKOUT_MS).toISOString()
54
+ : null;
55
+ await pool.query(`
56
+ UPDATE local_credentials
57
+ SET failed_attempts = $1, locked_until = $2, updated_at = CURRENT_TIMESTAMP
58
+ WHERE account_id = $3
59
+ `, [attempts, lockedUntil, row.account_id]);
60
+ await recordAuthEvent(row.account_id, normalized, "login_failed", clientIp(req));
61
+ return null;
62
+ }
63
+ await pool.query(`
64
+ UPDATE local_credentials
65
+ SET failed_attempts = 0, locked_until = NULL, updated_at = CURRENT_TIMESTAMP
66
+ WHERE account_id = $1
67
+ `, [row.account_id]);
68
+ await recordAuthEvent(row.account_id, normalized, "login_succeeded", clientIp(req));
69
+ return mapLocalAccount(row);
70
+ }
71
+ export async function readWebSession(req) {
72
+ const session = readSession(req);
73
+ if (!session)
74
+ return null;
75
+ const provider = browserAuthProvider();
76
+ if (provider === "oidc") {
77
+ if (!config.oidc)
78
+ return null;
79
+ return session.authProvider === "oidc" && session.oidcBinding === oidcSessionBinding(requireOidcSettings())
80
+ ? session : null;
81
+ }
82
+ if (provider === "shoo") {
83
+ // Legacy Shoo cookies omitted authProvider. Local cookies must never gain
84
+ // stateless Shoo authority after a runtime-profile change.
85
+ return session.authProvider === undefined || session.authProvider === "shoo" ? session : null;
86
+ }
87
+ if (session.authProvider !== "local" || !Number.isInteger(session.sessionVersion))
88
+ return null;
89
+ const result = await pool.query("SELECT session_version FROM local_credentials WHERE account_id = $1 LIMIT 1", [session.accountId]);
90
+ return Number(result.rows[0]?.session_version) === Number(session.sessionVersion) ? session : null;
91
+ }
92
+ export async function changeLocalPassword(input) {
93
+ assertSelfHosted();
94
+ validatePassword(input.newPassword);
95
+ return withTransaction(async (client) => {
96
+ const result = await client.query(`
97
+ SELECT lc.*, a.name AS account_name, a.is_admin
98
+ FROM local_credentials lc
99
+ JOIN accounts a ON a.id = lc.account_id
100
+ WHERE lc.account_id = $1
101
+ LIMIT 1
102
+ `, [input.accountId]);
103
+ const row = result.rows[0];
104
+ if (!row || !await verifyPassword(input.currentPassword, row)) {
105
+ throw new Error("Current password is incorrect.");
106
+ }
107
+ const password = await derivePassword(input.newPassword);
108
+ const nextVersion = Number(row.session_version) + 1;
109
+ await client.query(`
110
+ UPDATE local_credentials
111
+ SET password_algorithm = $1, password_salt = $2, password_hash = $3,
112
+ password_parameters = $4, session_version = $5,
113
+ failed_attempts = 0, locked_until = NULL,
114
+ password_changed_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
115
+ WHERE account_id = $6
116
+ `, [PASSWORD_ALGORITHM, password.salt, password.hash, JSON.stringify(SCRYPT_PARAMETERS), nextVersion, input.accountId]);
117
+ await client.query("INSERT INTO local_auth_events (id, account_id, event_type) VALUES ($1, $2, $3)", [newInternalId(), input.accountId, "password_changed"]);
118
+ return nextVersion;
119
+ });
120
+ }
121
+ export async function listLocalUsers() {
122
+ assertSelfHosted();
123
+ const result = await pool.query(`
124
+ SELECT lc.account_id, a.name AS account_name, lc.username, a.is_admin, lc.created_at
125
+ FROM local_credentials lc
126
+ JOIN accounts a ON a.id = lc.account_id
127
+ ORDER BY lc.created_at ASC
128
+ `);
129
+ return result.rows.map((row) => ({
130
+ accountId: row.account_id,
131
+ accountName: row.account_name,
132
+ username: row.username,
133
+ isAdmin: Boolean(row.is_admin),
134
+ createdAt: row.created_at
135
+ }));
136
+ }
137
+ export function normalizeUsername(value) {
138
+ const normalized = String(value || "").trim().toLowerCase();
139
+ if (!/^[a-z0-9][a-z0-9._-]{2,63}$/.test(normalized)) {
140
+ throw new Error("Username must be 3-64 characters using letters, numbers, dots, dashes, or underscores.");
141
+ }
142
+ return normalized;
143
+ }
144
+ function assertSelfHosted() {
145
+ if (config.runtimeProfile !== "self-hosted") {
146
+ throw new Error("Local account operations require OPENPLAN_RUNTIME_PROFILE=self-hosted.");
147
+ }
148
+ }
149
+ async function createLocalAccount(client, input) {
150
+ const username = String(input.username || "").trim();
151
+ const normalized = normalizeUsername(username);
152
+ validatePassword(input.password);
153
+ const existing = await client.query("SELECT account_id FROM local_credentials WHERE username_normalized = $1 LIMIT 1", [normalized]);
154
+ if (existing.rowCount)
155
+ throw new Error("Username is already in use.");
156
+ const password = await derivePassword(input.password);
157
+ const accountId = `acct_${newInternalId()}`;
158
+ const accountName = String(input.displayName || username).trim().slice(0, 120) || username;
159
+ await client.query("INSERT INTO accounts (id, name, is_admin) VALUES ($1, $2, $3)", [accountId, accountName, input.isAdmin]);
160
+ await client.query(`
161
+ INSERT INTO local_credentials (
162
+ account_id, username, username_normalized, password_algorithm,
163
+ password_salt, password_hash, password_parameters
164
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7)
165
+ `, [accountId, username, normalized, PASSWORD_ALGORITHM, password.salt, password.hash, JSON.stringify(SCRYPT_PARAMETERS)]);
166
+ await client.query("INSERT INTO local_auth_events (id, account_id, username_normalized, event_type) VALUES ($1, $2, $3, $4)", [newInternalId(), accountId, normalized, input.isAdmin ? "administrator_bootstrapped" : "user_created"]);
167
+ return { accountId, accountName, username, isAdmin: input.isAdmin, sessionVersion: 1 };
168
+ }
169
+ function validatePassword(password) {
170
+ if (typeof password !== "string" || password.length < 12 || password.length > 512) {
171
+ throw new Error("Password must be between 12 and 512 characters.");
172
+ }
173
+ }
174
+ async function derivePassword(password) {
175
+ const salt = randomBytes(16);
176
+ const hash = await scryptBuffer(password, salt, SCRYPT_PARAMETERS);
177
+ return { salt: salt.toString("base64url"), hash: hash.toString("base64url") };
178
+ }
179
+ async function verifyPassword(password, row) {
180
+ if (row.password_algorithm !== PASSWORD_ALGORITHM)
181
+ return false;
182
+ const parameters = JSON.parse(row.password_parameters);
183
+ const expected = Buffer.from(row.password_hash, "base64url");
184
+ const actual = await scryptBuffer(password, Buffer.from(row.password_salt, "base64url"), parameters);
185
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
186
+ }
187
+ async function burnPasswordWork(password) {
188
+ await scryptBuffer(password || "invalid", Buffer.alloc(16), SCRYPT_PARAMETERS);
189
+ }
190
+ function scryptBuffer(password, salt, parameters) {
191
+ return new Promise((resolve, reject) => {
192
+ scrypt(password, salt, parameters.keyLength, parameters, (error, derivedKey) => {
193
+ if (error)
194
+ reject(error);
195
+ else
196
+ resolve(derivedKey);
197
+ });
198
+ });
199
+ }
200
+ async function recordAuthEvent(accountId, usernameNormalized, eventType, sourceIp) {
201
+ await pool.query(`
202
+ INSERT INTO local_auth_events (id, account_id, username_normalized, event_type, source_ip)
203
+ VALUES ($1, $2, $3, $4, $5)
204
+ `, [newInternalId(), accountId, usernameNormalized, eventType, sourceIp]);
205
+ }
206
+ function mapLocalAccount(row) {
207
+ return {
208
+ accountId: row.account_id,
209
+ accountName: row.account_name,
210
+ username: row.username,
211
+ isAdmin: Boolean(row.is_admin),
212
+ sessionVersion: Number(row.session_version)
213
+ };
214
+ }
215
+ //# sourceMappingURL=local-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local-auth.js","sourceRoot":"","sources":["../src/local-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnE,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,MAAM,kBAAkB,GAAG,WAAW,CAAC;AACvC,MAAM,iBAAiB,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,MAAM,EAA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AAU,EAAE,EAAE;YAC7E,IAAI,KAAK;gBAAE,MAAM,CAAC,KAAK,CAAC,CAAC;;gBACpB,OAAO,CAAC,UAAU,CAAC,CAAC;QAC3B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,KAAK,UAAU,eAAe,CAC5B,SAAwB,EACxB,kBAA0B,EAC1B,SAAiB,EACjB,QAAuB;IAEvB,MAAM,IAAI,CAAC,KAAK,CACd;;;KAGC,EACD,CAAC,aAAa,EAAE,EAAE,SAAS,EAAE,kBAAkB,EAAE,SAAS,EAAE,QAAQ,CAAC,CACtE,CAAC;AACJ,CAAC;AAED,SAAS,eAAe,CAAC,GAAuB;IAC9C,OAAO;QACL,SAAS,EAAE,GAAG,CAAC,UAAU;QACzB,WAAW,EAAE,GAAG,CAAC,YAAY;QAC7B,QAAQ,EAAE,GAAG,CAAC,QAAQ;QACtB,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC9B,cAAc,EAAE,MAAM,CAAC,GAAG,CAAC,eAAe,CAAC;KAC5C,CAAC;AACJ,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ import { assertRuntimeConfigured } from "./config.js";
2
+ import { database } from "./database.js";
3
+ import { initDb } from "./db.js";
4
+ import { runReconciliation } from "./reconcile.js";
5
+ import { assertStorageConfigured } from "./storage.js";
6
+ async function main() {
7
+ assertRuntimeConfigured();
8
+ assertStorageConfigured();
9
+ await initDb();
10
+ console.log(JSON.stringify(await runReconciliation()));
11
+ }
12
+ main()
13
+ .catch((error) => {
14
+ console.error(error instanceof Error ? error.message : String(error));
15
+ process.exitCode = 1;
16
+ })
17
+ .finally(() => database.close());
18
+ //# sourceMappingURL=maintenance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"maintenance.js","sourceRoot":"","sources":["../src/maintenance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAEvD,KAAK,UAAU,IAAI;IACjB,uBAAuB,EAAE,CAAC;IAC1B,uBAAuB,EAAE,CAAC;IAC1B,MAAM,MAAM,EAAE,CAAC;IACf,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,iBAAiB,EAAE,CAAC,CAAC,CAAC;AACzD,CAAC;AAED,IAAI,EAAE;KACH,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACf,OAAO,CAAC,KAAK,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACtE,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC;KACD,OAAO,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC"}
package/dist/oidc.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ export interface OidcEnvironment {
2
+ OPENPLAN_OIDC_ISSUER?: string | undefined;
3
+ OPENPLAN_OIDC_CLIENT_ID?: string | undefined;
4
+ OPENPLAN_OIDC_CLIENT_SECRET?: string | undefined;
5
+ OPENPLAN_OIDC_SCOPES?: string | undefined;
6
+ OPENPLAN_OIDC_TOKEN_ENDPOINT_AUTH_METHOD?: string | undefined;
7
+ }
8
+ export interface OidcSettings {
9
+ issuer: string;
10
+ clientId: string;
11
+ clientSecret?: string;
12
+ scopes: string;
13
+ tokenEndpointAuthMethod: "client_secret_basic" | "client_secret_post" | "none";
14
+ }
15
+ export interface OidcTransaction {
16
+ state: string;
17
+ verifier: string;
18
+ nonce: string;
19
+ }
20
+ export interface OidcIdentity {
21
+ issuer: string;
22
+ subject: string;
23
+ profile: {
24
+ email: string | null;
25
+ emailVerified: boolean;
26
+ displayName: string | null;
27
+ pictureUrl: string | null;
28
+ };
29
+ }
30
+ /** Parse deployment-owned configuration; no issuer or client comes from a request. */
31
+ export declare function parseOidcSettings(env: OidcEnvironment): OidcSettings;
32
+ /** OIDC subjects are unique within an exact issuer, never by email address. */
33
+ export declare function oidcProviderKey(settings: OidcSettings): string;
34
+ /** Changing the issuer or client registration invalidates existing browser sessions. */
35
+ export declare function oidcSessionBinding(settings: OidcSettings): string;
36
+ export declare function beginOidcLogin(settings: OidcSettings, redirectUri: string): Promise<OidcTransaction & {
37
+ url: string;
38
+ }>;
39
+ export declare function completeOidcLogin(settings: OidcSettings, callbackUrl: URL, transaction: OidcTransaction, redirectUri: string): Promise<OidcIdentity>;