Merge pull request #884 from tdurieux/t3/notify-owners-on-repo-errors

feat: notify owners when GitHub access needs attention
This commit is contained in:
Thomas Durieux authored and GitHub committed 2026-10-09 08:50:05 +02:00
commit c55efd14ed
28 files changed
+878 -85

No files matched your search

+22
View File
@@ -95,6 +95,28 @@ the [MongoDB replication guide](docs/mongodb-replication.md).
</details>
### Owner email alerts
Set `RESEND_API_KEY` and `EMAIL_FROM` on the web server and download workers to
send access alerts through [Resend](https://resend.com/docs/api-reference/emails/send-email).
Use a sender address on a domain verified in Resend. `APP_HOSTNAME` sets the
host used for the connections link in emails.
Signed-in owners without an email address see an email form in a popup.
“Remind me later” dismisses it for the current login session; “Never” saves a
permanent preference on the account. Existing addresses are reused, and owners
can add or change their address on the connections page at any time.
Alerts cover invalid GitHub credentials and repository access errors encountered
while reading or refreshing content. No periodic access scan is performed.
Emails contain no repository names, anonymous URLs, or credentials.
An atomic database claim limits alerts to one per owner every 24 hours across
workers and repositories. Sending is best effort: delivery failures do not block
repository requests. A definite provider rejection allows a later access error
to retry after ten minutes; ambiguous timeouts retain the daily limit.
A process interrupted after claiming an alert may skip that day's email.
Leaving either Resend setting empty disables delivery and the email prompt.
## Scope of anonymization
In double-anonymous review, the boundary of anonymization is **the paper plus its online appendix — and only that**. Googling part of the paper or appendix to reveal authorship is considered a deliberate attempt to break anonymity ([explanation](https://www.monperrus.net/martin/open-science-double-blind)).
+2 -2
View File
@@ -1,8 +1,8 @@
{
"core.min.js": "core.3b07189932.min.js",
"vendor.min.js": "vendor.126b1a8e99.min.js",
"vendor.min.js": "vendor.29de243e41.min.js",
"mermaid.min.js": "mermaid.f848a72d16.min.js",
"all.min.css": "all.4c22aa9cd3.min.css",
"all.min.css": "all.8bc90a3e4c.min.css",
"markdown.min.js": "markdown.44f2e93820.min.js",
"pdf.min.js": "pdf.4d9cc6ff49.min.js",
"notebook.min.js": "notebook.c3144c18ae.min.js",
+1 -1
View File
@@ -6,4 +6,4 @@
*/:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus:not(:focus-visible){outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent}a:hover{color:#0056b3;text-decoration:underline}a:not([href]){color:inherit;text-decoration:none}a:not([href]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-weight:500;line-height:1.2}.h1,h1{font-size:2.5rem}.h2,h2{font-size:2rem}.h3,h3{font-size:1.75rem}.h4,h4{font-size:1.5rem}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,.1)}.small,small{font-size:80%;font-weight:400}.mark,mark{padding:.2em;background-color:#fcf8e3}.list-unsLine truncated
* Font Awesome Free 5.15.4 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
*/.fa,.fab,.fad,.fal,.far,.fas{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}.fa-lg{font-size:1.33333em;line-height:.75em;vertical-align:-.0667em}.fa-xs{font-size:.75em}.fa-sm{font-size:.875em}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:2.5em;padding-left:0}.fa-ul>li{position:relative}.fa-li{left:-2em;position:absolute;text-align:center;width:2em;line-height:inherit}.fa-border{border:solid .08em #eee;border-radius:.1em;padding:.2em .25em .15em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.fab.fa-pull-left,.fal.fa-pull-left,.far.fa-pull-left,.fas.fa-pull-left{margin-right:.3em}.fa.fa-pull-right,.fab.fa-pull-right,.fal.fa-pull-right,.far.fa-pull-right,.fas.fa-pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.fa-rotate-90{-webkit-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-webkit-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-webkit-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-webkit-transform:scale(-1,1);transform:scale(-1,1)}.fa-flip-vertical{-webkit-transform:scale(1,-1);transform:scale(1,-1)}.fa-flip-both,.fa-flip-horizontal.fa-flip-vertical{-webkit-transform:scale(-1,-1);transform:scale(-1,-1)}:root .fa-flip-both,:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-rotate-90{-webkit-filter:none;filter:none}.fa-stack{display:inline-block;height:2em;line-height:2em;position:relative;vertical-align:middle;width:2.5em}.fa-stack-1x,.fa-stack-2x{left:0;position:absolute;text-align:center;width:100%}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-500px:before{content:"\f26e"}.fa-accessible-icon:before{content:"\f368"}.fa-accusoft:before{content:"\f369"}.fa-acquisitions-incorporated:before{content:"\f6af"}.fa-ad:before{content:"\f641"}.fa-address-book:before{content:"\f2b9"}.fa-address-card:before{content:"\f2bb"}.fa-adjust:before{content:"\f042"}.fa-adn:before{content:"\f170"}.fa-adversal:before{content:"\f36a"}.fa-affiliatetheme:before{content:"\f36b"}.fa-air-freshener:before{content:"\f5d0"}.fa-airbnb:before{content:"\f834"}.fa-algolia:before{content:"\f36c"}.fa-align-center:before{content:"\f037"}.fa-align-justify:before{content:"\f039"}.fa-align-left:before{content:"\f036"}.fa-align-right:before{content:"\f038"}.fa-alipay:before{content:"\f642"}.fa-allergies:before{content:"\f461"}.fa-amazon:before{content:"\f270"}.fa-amazon-pay:before{content:"\f42c"}.fa-ambulance:before{content:"\f0f9"}.fa-american-sign-language-interpreting:before{content:"\f2a3"}.fa-amilia:before{content:"\f36d"}.fa-anchor:before{content:"\f13d"}.fa-android:before{content:"\f17b"}.fa-angellist:before{content:"\f209"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-down:before{content:"\f107"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angry:before{content:"\f556"}.fa-angrycreative:before{content:"\f36e"}.fa-angular:before{content:"\f420"}.fa-ankh:before{content:"\f644"}.fa-app-store:before{content:"\f36f"}.fa-app-store-ios:before{content:"\f370"}.fa-apper:before{content:"\f371"}.fa-apple:before{content:"\f179"}.fa-apple-alt:before{content:"\f5d1"}.fa-apple-pay:before{content:"\f415"}.fa-archive:before{content:"\f187"}.fa-archway:before{content:"\f557"}.fa-arrow-alt-circle-down:before{content:"\f358"}.fa-arrow-alt-circle-left:before{content:"\f359"}.fa-arrow-alt-circle-right:before{content:"\f35a"}.fa-arrow-alt-circle-up:before{content:"\f35b"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-down:before{content:"\f063"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrows-alt:before{content:"\f0b2"}.fa-arrows-alt-h:before{content:"\f337"}.fa-arrows-alt-v:before{content:"\f338"}.fa-artstation:before{content:"\f77a"}.fa-assistive-listening-systems:before{contentLine truncated
*/.fa,.fab,.fad,.fal,.far,.fas{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}.fa-lg{font-size:1.33333em;line-height:.75em;vertical-align:-.0667em}.fa-xs{font-size:.75em}.fa-sm{font-size:.875em}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:2.5em;padding-left:0}.fa-ul>li{position:relative}.fa-li{left:-2em;position:absolute;text-align:center;width:2em;line-height:inherit}.fa-border{border:solid .08em #eee;border-radius:.1em;padding:.2em .25em .15em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.fab.fa-pull-left,.fal.fa-pull-left,.far.fa-pull-left,.fas.fa-pull-left{margin-right:.3em}.fa.fa-pull-right,.fab.fa-pull-right,.fal.fa-pull-right,.far.fa-pull-right,.fas.fa-pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.fa-rotate-90{-webkit-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-webkit-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-webkit-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-webkit-transform:scale(-1,1);transform:scale(-1,1)}.fa-flip-vertical{-webkit-transform:scale(1,-1);transform:scale(1,-1)}.fa-flip-both,.fa-flip-horizontal.fa-flip-vertical{-webkit-transform:scale(-1,-1);transform:scale(-1,-1)}:root .fa-flip-both,:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-rotate-90{-webkit-filter:none;filter:none}.fa-stack{display:inline-block;height:2em;line-height:2em;position:relative;vertical-align:middle;width:2.5em}.fa-stack-1x,.fa-stack-2x{left:0;position:absolute;text-align:center;width:100%}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-500px:before{content:"\f26e"}.fa-accessible-icon:before{content:"\f368"}.fa-accusoft:before{content:"\f369"}.fa-acquisitions-incorporated:before{content:"\f6af"}.fa-ad:before{content:"\f641"}.fa-address-book:before{content:"\f2b9"}.fa-address-card:before{content:"\f2bb"}.fa-adjust:before{content:"\f042"}.fa-adn:before{content:"\f170"}.fa-adversal:before{content:"\f36a"}.fa-affiliatetheme:before{content:"\f36b"}.fa-air-freshener:before{content:"\f5d0"}.fa-airbnb:before{content:"\f834"}.fa-algolia:before{content:"\f36c"}.fa-align-center:before{content:"\f037"}.fa-align-justify:before{content:"\f039"}.fa-align-left:before{content:"\f036"}.fa-align-right:before{content:"\f038"}.fa-alipay:before{content:"\f642"}.fa-allergies:before{content:"\f461"}.fa-amazon:before{content:"\f270"}.fa-amazon-pay:before{content:"\f42c"}.fa-ambulance:before{content:"\f0f9"}.fa-american-sign-language-interpreting:before{content:"\f2a3"}.fa-amilia:before{content:"\f36d"}.fa-anchor:before{content:"\f13d"}.fa-android:before{content:"\f17b"}.fa-angellist:before{content:"\f209"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-down:before{content:"\f107"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angry:before{content:"\f556"}.fa-angrycreative:before{content:"\f36e"}.fa-angular:before{content:"\f420"}.fa-ankh:before{content:"\f644"}.fa-app-store:before{content:"\f36f"}.fa-app-store-ios:before{content:"\f370"}.fa-apper:before{content:"\f371"}.fa-apple:before{content:"\f179"}.fa-apple-alt:before{content:"\f5d1"}.fa-apple-pay:before{content:"\f415"}.fa-archive:before{content:"\f187"}.fa-archway:before{content:"\f557"}.fa-arrow-alt-circle-down:before{content:"\f358"}.fa-arrow-alt-circle-left:before{content:"\f359"}.fa-arrow-alt-circle-right:before{content:"\f35a"}.fa-arrow-alt-circle-up:before{content:"\f35b"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-down:before{content:"\f063"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrows-alt:before{content:"\f0b2"}.fa-arrows-alt-h:before{content:"\f337"}.fa-arrows-alt-v:before{content:"\f338"}.fa-artstation:before{content:"\f77a"}.fa-assistive-listening-systems:before{contentLine truncated
+16
View File
@@ -7879,3 +7879,19 @@ input[type="date"], select { color-scheme: light; }
.q-job-detail-label { font-family: var(--font-sans); font-size: 12px; letter-spacing: 0; text-transform: none; }
.admin-section-header h2 { font-family: var(--font-sans); font-size: 16px; font-weight: 600; letter-spacing: 0; text-transform: none; color: var(--color); }
.errors-page .sev-label { font-family: var(--font-sans); font-size: 13px; letter-spacing: 0; }
/* Email setup after sign-in. Native dialog traps focus and makes the page inert. */
.email-prompt {
width: min(560px, calc(100vw - 32px));
padding: 28px;
border: 1px solid var(--paper-border, #e5e1d9);
border-radius: 12px;
background: var(--paper-bg, #faf9f6);
color: inherit;
box-shadow: 0 16px 64px #0003;
}
.email-prompt::backdrop { background: #0006; }
.email-prompt h2 { margin: 0 0 12px; font-size: 24px; }
.email-prompt p { margin-bottom: 20px; }
.email-prompt-actions { display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; margin-top: 24px; }
body.dark-mode .email-prompt { background: #242320; color: #faf9f6; }
+10
View File
@@ -8,6 +8,16 @@
<p role="status" v-if="!connections &amp;&amp; !connectionError">Loading your connections…</p>
<button class="btn btn-outline-ink" v-if="!connections &amp;&amp; connectionError" :disabled="busy" @click="loadConnections()">Try again</button>
<div v-if="connections">
<section class="connection-resources" v-if="connections.emailNotificationsEnabled">
<h2>Email alerts</h2>
<p>We will email you if your GitHub connection stops working or a repository becomes inaccessible. Your address is never shown on anonymous pages.</p>
<form @submit.prevent="saveNotificationEmail()">
<label for="notification-email">Email address</label>
<input id="notification-email" class="form-control" type="email" autocomplete="email" maxlength="254" required v-model="notificationEmail" :disabled="busy" />
<button class="btn btn-ink mt-2" type="submit" :disabled="busy">Save email address</button>
<p v-if="emailSaved" role="status">Email address saved.</p>
</form>
</section>
<div class="connections-grid">
<section v-if="connections.appEnabled">
<div class="connection-top"><i class="fab fa-github" aria-hidden="true"></i><span class="connection-badge">Recommended</span></div>
+15
View File
@@ -115,3 +115,18 @@
</div>
</nav>
<div class="navbar shadow generalMessage" v-if="generalMessage" v-html="sanitize(generalMessage)"></div>
<dialog id="email-prompt" class="email-prompt" v-if="emailPromptOpen" aria-labelledby="email-prompt-title" aria-describedby="email-prompt-reason" @cancel.prevent="respondToEmailPrompt('later')">
<form @submit.prevent="respondToEmailPrompt('save')">
<h2 id="email-prompt-title">Stay informed about access problems</h2>
<p id="email-prompt-reason">Get email alerts when your GitHub token or repository access fails.</p>
<label for="email-prompt-address">Email address</label>
<input id="email-prompt-address" class="form-control" type="email" autocomplete="email" maxlength="254" required v-model="emailPromptAddress" :disabled="emailPromptBusy" />
<p class="paper-inline-alert paper-inline-alert-error" role="alert" v-if="emailPromptError">{{ emailPromptError }}</p>
<div class="email-prompt-actions">
<button type="button" class="btn btn-outline-ink" :disabled="emailPromptBusy" @click="respondToEmailPrompt('later')">Remind me later</button>
<button type="button" class="btn btn-outline-ink" :disabled="emailPromptBusy" @click="respondToEmailPrompt('never')">Never</button>
<button type="submit" class="btn btn-ink" :disabled="emailPromptBusy">{{ emailPromptBusy ? 'Saving…' : 'Save' }}</button>
</div>
</form>
</dialog>
+46
View File
@@ -146,10 +146,40 @@ export const mainController = function (state, http, location, timeout) {
state.darkMode(localStorage.getItem("darkMode") == "true");
state.emailPromptOpen = false;
state.emailPromptAddress = "";
state.emailPromptBusy = false;
state.emailPromptError = "";
let emailPromptFocus;
state.respondToEmailPrompt = async (action) => {
if (state.emailPromptBusy) return;
state.emailPromptBusy = true;
state.emailPromptError = "";
try {
const res = await http.post("/github/connections/email", { action, email: state.emailPromptAddress },
{ headers: { "X-CSRF-Token": state.user.emailPromptCSRF } });
if (action === "save") state.user.notificationEmail = res.data.notificationEmail;
state.emailPromptOpen = false;
state.user.showEmailPrompt = false;
emailPromptFocus?.focus();
} catch (error) { state.emailPromptError = error.data?.error || "Unable to save your preference. Please try again."; }
finally { state.emailPromptBusy = false; }
};
function getUser() {
http.get("/api/user").then(
(res) => {
if (res) state.user = res.data;
if (state.user?.emailNotificationsEnabled && state.user.showEmailPrompt && !state.user.notificationEmail) {
emailPromptFocus = document.activeElement;
state.emailPromptOpen = true;
timeout(() => {
const dialog = document.getElementById("email-prompt");
if (dialog?.showModal) dialog.showModal();
else dialog?.setAttribute("open", "");
document.getElementById("email-prompt-address")?.focus();
}, 0);
}
},
() => {
state.user = null;
@@ -3297,11 +3327,27 @@ export const conferenceController = function (state, http, location, params) {
export const connectionsController = function (state, http) {
state.notificationEmail = "";
state.emailSaved = false;
state.saveNotificationEmail = async () => {
state.busy = true;
state.emailSaved = false;
state.connectionError = "";
try {
const res = await http.post("/github/connections/email", { email: state.notificationEmail },
{ headers: { "X-CSRF-Token": state.connections.csrf } });
state.notificationEmail = res.data.notificationEmail;
if (state.user) state.user.notificationEmail = res.data.notificationEmail;
state.emailSaved = true;
} catch (error) { state.connectionError = error.data?.error || "Unable to save email address."; }
finally { state.busy = false; }
};
state.connections = null;
state.connectionError = "";
state.busy = false;
state.loadConnections = () => http.get("/github/connections").then(res => {
state.connections = res.data;
state.notificationEmail = res.data.notificationEmail || "";
}).catch(error => { state.connectionError = error.data?.error || "Unable to load connections."; });
state.changeConnection = async (resource, connection, preview) => {
state.busy = true;
+28 -28
View File
@@ -1,63 +1,63 @@
"use strict";(()=>{var ld=Object.defineProperty;var dd=(e,t)=>{for(var s in t)ld(e,s,{get:t[s],enumerable:!0})};var he=["abap","abc","actionscript","ada","alda","apache_conf","apex","applescript","aql","asciidoc","asl","assembly_x86","autohotkey","batchfile","c9search","c_cpp","cirru","clojure","cobol","coffee","coldfusion","crystal","csharp","csound_document","csound_orchestra","csound_score","csp","css","curly","d","dart","diff","django","dockerfile","dot","drools","edifact","eiffel","ejs","elixir","elm","erlang","forth","fortran","fsharp","fsl","ftl","gcode","gherkin","gitignore","glsl","gobstones","golang","graphqlschema","groovy","haml","handlebars","haskell","haskell_cabal","haxe","hjson","html","html_elixir","html_ruby","ini","io","jack","jade","java","javascript","json","json5","jsoniq","jsp","jssm","jsx","julia","kotlin","latex","less","liquid","lisp","livescript","logiql","logtalk","lsl","lua","luapage","lucene","makefile","markdown","mask","matlab","maze","mediawiki","mel","mixal","mushcode","mysql","nginx","nim","nix","nsis","nunjucks","objectivec","ocaml","pascal","perl","perl6","pgsql","php","php_laravel_blade","pig","plain_text","powershell","praat","prisma","prolog","properties","protobuf","puppet","python","qml","r","razor","rdoc","red","redshift","rhtml","rst","ruby","rust","sass","scad","scala","scheme","scss","sh","sjs","slim","smarty","snippets","soy_template","space","sparql","sql","sqlserver","stylus","svg","swift","tcl","terraform","tex","text","textile","toml","tsx","turtle","twig","typescript","vala","vbscript","velocity","verilog","vhdl","visualforce","wollok","xml","xquery","yaml","zeek"];var ve={editor:"/script/editor.e243722d87.min.js",markdown:"/script/markdown.ad7b1d71c3.min.js",notebook:"/script/notebook.8844e2735f.min.js",org:"/script/org.f4e2a3f59f.min.js",pdf:"/script/pdf.4d9cc6ff49.min.js"};var cs=new Map,pd=ve;function Xt(e){if(!cs.has(e)){let t=document.createElement("script");t.src=pd[e];let s=new Promise((r,n)=>{t.onload=r,t.onerror=()=>{cs.delete(e),t.remove(),n(new Error(`Unable to load ${e}. Please retry.`))}});cs.set(e,s),document.head.appendChild(t)}return cs.get(e)}async function pr(){await Xt("editor"),ace.config.set("basePath","/script/external/ace/")}function ho(e){let t=Object.create(null);for(let s of e.split(","))t[s]=1;return s=>s in t}var Ie={},Zt=[],at=()=>{},an=()=>!1,vo=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),go=e=>e.startsWith("onUpdate:"),Ge=Object.assign,Po=(e,t)=>{let s=e.indexOf(t);s>-1&&e.splice(s,1)},fd=Object.prototype.hasOwnProperty,Ne=(e,t)=>fd.call(e,t),ye=Array.isArray,Lt=e=>Vo(e)==="[object Map]",Ut=e=>Vo(e)==="[object Set]",fr=e=>Vo(e)==="[object Date]";var we=e=>typeof e=="function",Fe=e=>typeof e=="string",mt=e=>typeof e=="symbol",Te=e=>e!==null&&typeof e=="object",ln=e=>(Te(e)||we(e))&&we(e.then)&&we(e.catch),vr=Object.prototype.toString,Vo=e=>vr.call(e),dn=e=>Vo(e).slice(8,-1),ps=e=>Vo(e)==="[object Object]",fs=e=>Fe(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,yo=ho(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted");var ms=e=>{let t=Object.create(null);return(s=>t[s]||(t[s]=e(s)))},md=/-\w/g,Je=ms(e=>e.replace(md,t=>t.slice(1).toUpperCase())),hd=/\B([A-Z])/g,St=ms(e=>e.replace(hd,"-$1").toLowerCase()),xt=ms(e=>e.charAt(0).toUpperCase()+e.slice(1)),qo=ms(e=>e?`on${xt(e)}`:""),gt=(e,t)=>!Object.is(e,t),bo=(e,...t)=>{for(let s=0;s<e.length;s++)e[s](...t)},hs=(e,t,s,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:s})},wo=e=>{let t=parseFloat(e);return isNaN(t)?e:t};var mr,Mo=()=>mr||(mr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function qe(e){if(ye(e)){let t={};for(let s=0;s<e.length;s++){let r=e[s],n=Fe(r)?bd(r):qe(r);if(n)for(let i in n)t[i]=n[i]}return t}else if(Fe(e)||Te(e))return e}var vd=/;(?![^(]*\))/g,gd=/:([^]+)/,yd=/\/\*[^]*?\*\//g;function bd(e){let t={};return e.replace(yd,"").split(vd).forEach(s=>{if(s){let r=s.split(gd);r.length>1&&(t[r[0].trim()]=r[1].trim())}}),t}function A(e){let t="";if(Fe(e))t=e;else if(ye(e))for(let s=0;s<e.length;s++){let r=A(e[s]);r&&(t+=r+" ")}else if(Te(e))for(let s in e)e[s]&&(t+=s+" ");return t.trim()}var gr="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",yr=ho(gr),wd=ho(gr+",async,autofocus,autoplay,controls,default,defer,disabled,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected");function vs(e){return!!e||e===""}function kd(e,t){if(e.length!==t.length)return!1;let s=!0;for(let r=0;s&&r<e.length;r++)s=Nt(e[r],t[r]);return s}function hr(e,t){if(e.size!==t.size)return!1;let s=Array.from(t),r=new Uint8Array(s.length);for(let n of e){let i=-1;for(let a=0;a<s.length;a++)if(!r[a]&&Nt(n,s[a])){i=a;break}if(i<0)return!1;r[i]=1}return!0}function Nt(e,t){if(e===t)return!0;let s=fr(e),r=fr(t);if(s||r)returLine truncated
`))),e[uo]=Ws(n);let i=r||n.props&&n.props.type==="number";lo(e,t?"change":"input",a=>{a.target.composing||e[uo](Bn(e.value,s,i))}),(s||i)&&lo(e,"change",()=>{e.value=Bn(e.value,s,i)}),t||(lo(e,"compositionstart",cc),lo(e,"compositionend",Ji),lo(e,"change",Ji))},mounted(e,{value:t,modifiers:{trim:s,number:r}}){let n=t??"",i=e[js];delete e[js],i!==void 0&&(e.type==="text"||e.type==="textarea")&&e.value!==i?e[uo](Bn(e.value,s,r)):e.value=n},beforeUpdate(e,{value:t,oldValue:s,modifiers:{lazy:r,trim:n,number:i}},a){if(e[uo]=Ws(a),e.composing)return;let u=(i||e.type==="number")&&!/^0\d/.test(e.value)?wo(e.value):e.value,f=t??"";if(u===f)return;let v=e.getRootNode();(v instanceof Document||v instanceof ShadowRoot)&&v.activeElement===e&&e.type!=="range"&&(r&&t===s||n&&e.value.trim()===f)||(e.value=f)}};var ta={deep:!0,created(e,{value:t,modifiers:{number:s}},r){e._modelValue=t,lo(e,"change",()=>{let n=Array.prototype.filter.call(e.options,f=>f.selected).map(f=>s?wo(Ks(f)):Ks(f)),i=e.multiple,a=i?Ut(e._modelValue)?new Set(n):n:n[0],u=e._pendingValue=[i,i?ye(a)?n.slice():n:a];try{e[uo](a)}finally{st(()=>{e._pendingValue===u&&(e._pendingValue=void 0)})}}),e[uo]=Ws(r)},mounted(e,{value:t}){Qi(e,t)},beforeUpdate(e,{value:t},s){e._modelValue=t,e[uo]=Ws(s)},updated(e,{value:t}){let s=e._pendingValue;e._pendingValue=void 0,(!s||s[0]!==e.multiple||!pc(t,s[1],s[0]))&&Qi(e,t)}};function pc(e,t,s){if(!s)return Nt(e,t);if(ye(e))return Nt(e,t);if(Ut(e)){if(e.size!==t.length)return!1;for(let r of t)if(!e.has(r))return!1;return!0}return!1}function Qi(e,t){let s=e.multiple,r=ye(t);if(!(s&&!r&&!Ut(t))){for(let n=0,i=e.options.length;n<i;n++){let a=e.options[n],u=Ks(a);if(s)if(r){let f=typeof u;f==="string"||f==="number"?a.selected=t.some(v=>String(v)===String(u)):a.selected=br(t,u)>-1}else a.selected=t.has(u);else if(Nt(Ks(a),t)){e.selectedIndex!==n&&(e.selectedIndex=n);return}}!s&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function Ks(e){return"_value"in e?e._value:e.value}var fc=["ctrl","shift","alt","meta"],mc={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>fc.some(s=>e[`${s}Key`]&&!t.includes(s))},me=(e,t)=>{if(!e)return e;let s=e._withMods||(e._withMods={}),r=t.join(".");return s[r]||(s[r]=((n,...i)=>{for(let a=0;a<t.length;a++){let u=mc[t[a]];if(u&&u(n,t))return}return e(n,...i)}))},hc={esc:"escape",space:" ",up:"arrow-up",left:"arrow-left",right:"arrow-right",down:"arrow-down",delete:"backspace"},Ro=(e,t)=>{let s=e._withKeys||(e._withKeys={}),r=t.join(".");return s[r]||(s[r]=(n=>{if(!("key"in n))return;let i=St(n.key);if(t.some(a=>a===i||hc[a]===i))return e(n)}))},vc=Ge({patchProp:lc},Wu),Xi;function gc(){return Xi||(Xi=Oi(vc))}var oa=((...e)=>{let t=gc().createApp(...e),{mount:s}=t;return t.mount=r=>{let n=bc(r);if(!n)return;let i=t._component;!we(i)&&!i.render&&!i.template&&(i.template=n.innerHTML),n.nodeType===1&&(n.textContent="");let a=s(n,!1,yc(n));return n instanceof Element&&(n.removeAttribute("v-cloak"),n.setAttribute("data-v-app","")),a},t});function yc(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function bc(e){return Fe(e)?document.querySelector(e):e}var fo=typeof document<"u";function na(e){return typeof e=="object"||"displayName"in e||"props"in e||"__vccOpts"in e}function wc(e){return e.__esModule||e[Symbol.toStringTag]==="Module"||e.default&&na(e.default)}var Ae=Object.assign;function Ys(e,t){let s={};for(let r in t){let n=t[r];s[r]=wt(n)?n.map(e):e(n)}return s}var Ao=()=>{},wt=Array.isArray;function Kn(e,t){let s={};for(let r in e)s[r]=r in t?t[r]:e[r];return s}var ra=/#/g,kc=/&/g,Ec=/\//g,Cc=/=/g,_c=/\?/g,ia=/\+/g,Sc=/%5B/g,Nc=/%5D/g,aa=/%5E/g,Dc=/%60/g,la=/%7B/g,Rc=/%7C/g,da=/%7D/g,Tc=/%20/g;function Yn(e){return e==null?"":encodeURI(""+e).replace(Rc,"|").replace(Sc,"[").replace(Nc,"]")}function ua(e){return Yn(e).replace(la,"{").replace(da,"}").replace(aa,"^")}function Gn(e){return Yn(e).replace(ia,"%2B").replace(Tc,"+").replace(ra,"%23").replace(kc,"%26").replace(Dc,"`").replace(la,"{").replace(da,"}").replace(aa,"^")}function Ac(e){return Gn(e).replace(Cc,"%3D")}function Oc(e){return Yn(e).replace(ra,"%23").replace(_c,"%3F")}function ca(e){return Oc(e).replace(Ec,"%2F")}function To(e){if(e==null)return null;try{return decodeURIComponent(""+e)}catch{}return""+e}var Ic=/\/$/,Pc=e=>e.replace(Ic,"");function Js(e,t,s="/"){let r,n={},i="",a="",u=t.indexOf("#"),f=t.indexOf("?");return f=u>=0&&f>u?-1:f,f>=0&&(r=t.slice(0,f),i=t.slice(f,u>0?u:t.length),n=e(i.slice(1))),u>=0&&(r=r||t.slice(0,u),a=t.slice(u,t.length)),r=qc(r??t,s),{fullPath:r+i+a,path:r,query:n,hash:To(a)}}function pa(e,t){let s=t.query?e(t.query):"";return t.path+(s&&"?")+s+(t.hash||"")}function Jn(e,t){return!t||!e.toLowerCase().sLine truncated
"use strict";(()=>{var hd=Object.defineProperty;var vd=(e,t)=>{for(var n in t)hd(e,n,{get:t[n],enumerable:!0})};var he=["abap","abc","actionscript","ada","alda","apache_conf","apex","applescript","aql","asciidoc","asl","assembly_x86","autohotkey","batchfile","c9search","c_cpp","cirru","clojure","cobol","coffee","coldfusion","crystal","csharp","csound_document","csound_orchestra","csound_score","csp","css","curly","d","dart","diff","django","dockerfile","dot","drools","edifact","eiffel","ejs","elixir","elm","erlang","forth","fortran","fsharp","fsl","ftl","gcode","gherkin","gitignore","glsl","gobstones","golang","graphqlschema","groovy","haml","handlebars","haskell","haskell_cabal","haxe","hjson","html","html_elixir","html_ruby","ini","io","jack","jade","java","javascript","json","json5","jsoniq","jsp","jssm","jsx","julia","kotlin","latex","less","liquid","lisp","livescript","logiql","logtalk","lsl","lua","luapage","lucene","makefile","markdown","mask","matlab","maze","mediawiki","mel","mixal","mushcode","mysql","nginx","nim","nix","nsis","nunjucks","objectivec","ocaml","pascal","perl","perl6","pgsql","php","php_laravel_blade","pig","plain_text","powershell","praat","prisma","prolog","properties","protobuf","puppet","python","qml","r","razor","rdoc","red","redshift","rhtml","rst","ruby","rust","sass","scad","scala","scheme","scss","sh","sjs","slim","smarty","snippets","soy_template","space","sparql","sql","sqlserver","stylus","svg","swift","tcl","terraform","tex","text","textile","toml","tsx","turtle","twig","typescript","vala","vbscript","velocity","verilog","vhdl","visualforce","wollok","xml","xquery","yaml","zeek"];var ve={notebook:"/script/notebook.c3144c18ae.min.js",org:"/script/org.f61f262915.min.js",markdown:"/script/markdown.44f2e93820.min.js",editor:"/script/editor.4f142d3adc.min.js",pdf:"/script/pdf.4d9cc6ff49.min.js"};function hr(e){let t=e.location.hash.slice(1);if(e.history.replaceState(null,"","/review-link"),t.length>2048)return null;let n=new URLSearchParams(t);if([...n.keys()].length!==3||[...n.keys()].some(a=>!["clientId","intentId","token"].includes(a)))return null;let r=n.get("clientId"),s=n.get("intentId"),i=n.get("token");return!/^[a-f0-9]{32}$/.test(r||"")||!/^[a-f0-9]{32}$/.test(s||"")||!/^[a-f0-9]{64}$/.test(i||"")?null:{contract:"4open.artifacts/1",clientId:r,intentId:s,token:i}}function vr(e,t){let{http:n,promises:r,window:s}=t,i=t.takeReviewHandoff(),a=i?{clientId:i.clientId,intentId:i.intentId}:null,u,f,k,h,w,m=!0,E,y=r.defer(),g=()=>[...s.crypto.getRandomValues(new Uint8Array(16))].map(F=>F.toString(16).padStart(2,"0")).join("");Object.assign(e,{repositoryId:"",handoffEnabled:!1,busy:!1,preview:null,acceptAccess:!1,acceptRetention:!1,uncertain:!1,saved:!1,expired:!1,error:i?"":"Open a new artifact link from your submission. This link is missing or invalid."});let _=()=>m&&e.user?.username===w;function R(){m=!1,i=u=f=void 0,y.resolve(),s.clearTimeout(E)}e.on("dispose",R),e.on("routeLeave",R),e.watch(()=>e.user?.username,F=>{!w&&F?w=F:w&&F!==w&&(R(),e.preview=null,e.repositoryId="",e.busy=!1,e.saved=!1,e.handoffEnabled=!1,e.error="Your account changed. Open a new artifact link from your submission.")});let T=()=>({timeout:y.promise,headers:{"Content-Type":"application/json","X-Review-CSRF":f}}),I=F=>F?.status===404?"Artifact linking is not available on this server.":F?.status===401?"Sign in, then open a new artifact link from your submission.":F?.status===403?"This account cannot approve this repository or this link.":"The request could not be completed. You can retry from this page.";e.loadPreview=async()=>{if(!m||!i||e.busy||e.uncertain||e.saved||!e.user?.username)return;w=e.user.username;let F=e.repositoryId.trim();if(!/^[A-Za-z0-9_-]{3,128}$/.test(F)){e.error="Enter the anonymous repository ID from its URL.";return}e.busy=!0,e.error="",e.preview=null,u=void 0,e.acceptAccess=e.acceptRetention=!1,e.expired=!1,s.clearTimeout(E),h||(h=g());try{let P=(await n.get("/api/review-consent/csrf",{timeout:y.promise})).data;if(!_())return;if(f=P.csrf,e.handoffEnabled=P.handoffEnabled===!0,!/^[a-f0-9]{64}$/.test(f||""))throw new Error("invalid_csrf");let M=(await n.post("/api/review-consent/preview",{repositoryId:F,intent:{...i,requestId:h}},T())).data;if(!_())return;if(!M||typeof M.ticket!="string"||!M.ticket||M.ticket.length>8192||typeof M.repositoryName!="string"||!["restricted-review","anonymous-link"].includes(M.policy?.access)||!Number.isSafeInteger(M.policy.version)||!Number.isFinite(Date.parse(M.policy.retainUntil))||!Number.isFinite(Date.parse(M.expiresAt))||Date.parse(M.expiresAt)<=Date.now()||Date.parse(M.expiresAt)>Date.now()+6e5)throw new Error("invalid_preview");u=M.ticket,k=g(),e.preview={repositoryName:M.repositoryName,policy:{...M.policy},expiresAt:M.expiresAt},E=s.setTimeout(()=>{m&&(e.expired=!0)},Math.max(0,Date.parse(M.expiresAt)-Date.now()))}catch(P){_()&&(e.error=I(P))}finally{_()&&(e.busy=!1)}},e.confirmConsent=async()=>{if(!(!_()||e.busy||e.saved||!u||!e.acceptAccesLine truncated
`))),e[Ut]=To(s);let i=r||s.props&&s.props.type==="number";eo(e,t?"change":"input",a=>{a.target.composing||e[Ut](Gs(e.value,n,i))}),(n||i)&&eo(e,"change",()=>{e.value=Gs(e.value,n,i)}),t||(eo(e,"compositionstart",bc),eo(e,"compositionend",ea),eo(e,"change",ea))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let s=t??"",i=e[Jn];delete e[Jn],i!==void 0&&(e.type==="text"||e.type==="textarea")&&e.value!==i?e[Ut](Gs(e.value,n,r)):e.value=s},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:s,number:i}},a){if(e[Ut]=To(a),e.composing)return;let u=(i||e.type==="number")&&!/^0\d/.test(e.value)?ko(e.value):e.value,f=t??"";if(u===f)return;let k=e.getRootNode();(k instanceof Document||k instanceof ShadowRoot)&&k.activeElement===e&&e.type!=="range"&&(r&&t===n||s&&e.value.trim()===f)||(e.value=f)}},Ks={deep:!0,created(e,t,n){e[Ut]=To(n),eo(e,"change",()=>{let r=e._modelValue,s=fn(e),i=e.checked,a=e[Ut];if(ye(r)){let u=kn(r,s),f=u!==-1;if(i&&!f)a(r.concat(s));else if(!i&&f){let k=[...r];k.splice(u,1),a(k)}}else if(Ct(r)){let u=new Set(r);i?u.add(s):u.delete(s),a(u)}else a(aa(e,i))})},mounted:ta,beforeUpdate(e,t,n){e[Ut]=To(n),ta(e,t,n)}};function ta(e,{value:t,oldValue:n},r){e._modelValue=t;let s;if(ye(t))s=kn(t,r.props.value)>-1;else if(Ct(t))s=t.has(r.props.value);else{if(t===n)return;s=_t(t,aa(e,!0))}e.checked!==s&&(e.checked=s)}var ia={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,eo(e,"change",()=>{let s=Array.prototype.filter.call(e.options,f=>f.selected).map(f=>n?ko(fn(f)):fn(f)),i=e.multiple,a=i?Ct(e._modelValue)?new Set(s):s:s[0],u=e._pendingValue=[i,i?ye(a)?s.slice():s:a];try{e[Ut](a)}finally{nt(()=>{e._pendingValue===u&&(e._pendingValue=void 0)})}}),e[Ut]=To(r)},mounted(e,{value:t}){oa(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Ut]=To(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!wc(t,n[1],n[0]))&&oa(e,t)}};function wc(e,t,n){if(!n)return _t(e,t);if(ye(e))return _t(e,t);if(Ct(e)){if(e.size!==t.length)return!1;for(let r of t)if(!e.has(r))return!1;return!0}return!1}function oa(e,t){let n=e.multiple,r=ye(t);if(!(n&&!r&&!Ct(t))){for(let s=0,i=e.options.length;s<i;s++){let a=e.options[s],u=fn(a);if(n)if(r){let f=typeof u;f==="string"||f==="number"?a.selected=t.some(k=>String(k)===String(u)):a.selected=kn(t,u)>-1}else a.selected=t.has(u);else if(_t(fn(a),t)){e.selectedIndex!==s&&(e.selectedIndex=s);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function fn(e){return"_value"in e?e._value:e.value}function aa(e,t){let n=t?"_trueValue":"_falseValue";return n in e?e[n]:t}var kc=["ctrl","shift","alt","meta"],Ec={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>kc.some(n=>e[`${n}Key`]&&!t.includes(n))},de=(e,t)=>{if(!e)return e;let n=e._withMods||(e._withMods={}),r=t.join(".");return n[r]||(n[r]=((s,...i)=>{for(let a=0;a<t.length;a++){let u=Ec[t[a]];if(u&&u(s,t))return}return e(s,...i)}))},Cc={esc:"escape",space:" ",up:"arrow-up",left:"arrow-left",right:"arrow-right",down:"arrow-down",delete:"backspace"},Ao=(e,t)=>{let n=e._withKeys||(e._withKeys={}),r=t.join(".");return n[r]||(n[r]=(s=>{if(!("key"in s))return;let i=Dt(s.key);if(t.some(a=>a===i||Cc[a]===i))return e(s)}))},_c=Ge({patchProp:vc},ec),na;function Sc(){return na||(na=Mi(_c))}var la=((...e)=>{let t=Sc().createApp(...e),{mount:n}=t;return t.mount=r=>{let s=Dc(r);if(!s)return;let i=t._component;!we(i)&&!i.render&&!i.template&&(i.template=s.innerHTML),s.nodeType===1&&(s.textContent="");let a=n(s,!1,Nc(s));return s instanceof Element&&(s.removeAttribute("v-cloak"),s.setAttribute("data-v-app","")),a},t});function Nc(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function Dc(e){return Fe(e)?document.querySelector(e):e}var mo=typeof document<"u";function ua(e){return typeof e=="object"||"displayName"in e||"props"in e||"__vccOpts"in e}function Rc(e){return e.__esModule||e[Symbol.toStringTag]==="Module"||e.default&&ua(e.default)}var Ae=Object.assign;function Xn(e,t){let n={};for(let r in t){let s=t[r];n[r]=kt(s)?s.map(e):e(s)}return n}var Io=()=>{},kt=Array.isArray;function Qs(e,t){let n={};for(let r in e)n[r]=r in t?t[r]:e[r];return n}var ca=/#/g,Tc=/&/g,Ac=/\//g,Oc=/=/g,Ic=/\?/g,pa=/\+/g,Pc=/%5B/g,Vc=/%5D/g,fa=/%5E/g,qc=/%60/g,ma=/%7B/g,Mc=/%7C/g,ha=/%7D/g,$c=/%20/g;function Xs(e){return e==null?"":encodeURI(""+e).replace(Mc,"|").replace(Pc,"[").replace(Vc,"]")}function va(e){return Xs(e).replace(ma,"{").replace(ha,"}").replace(fa,"^")}function Ys(e){return Xs(e).replace(pa,"%2B").replace($c,"+").replace(ca,"%23").replace(Tc,"%26").replace(qc,"`").replace(ma,"{").replace(ha,"}").replace(fa,"^")}function Lc(e){return Ys(e).replace(Oc,"%3D")}function Uc(e){return XLine truncated
${JSON.stringify(e)}${t?`
while being at
`+JSON.stringify(t):""}`},[je.NAVIGATION_GUARD_REDIRECT]({from:e,to:t}){return`Redirected from "${e.fullPath}" to "${Fc(t)}" via a navigation guard.`},[je.NAVIGATION_ABORTED]({from:e,to:t}){return`Navigation aborted from "${e.fullPath}" to "${t.fullPath}" via a navigation guard.`},[je.NAVIGATION_CANCELLED]({from:e,to:t}){return`Navigation cancelled from "${e.fullPath}" to "${t.fullPath}" with a new navigation.`},[je.NAVIGATION_DUPLICATED]({from:e,to:t}){return`Avoided redundant navigation to current location: "${e.fullPath}".`}};function po(e,t){return Ae(new Error,{type:e,[ba]:!0},t)}function $t(e,t){return e instanceof Error&&ba in e&&(t==null||!!(e.type&t))}var Uc=["params","query","hash"];function Fc(e){if(typeof e=="string")return e;if(e.path!=null)return e.path;let t={};for(let s of Uc)s in e&&(t[s]=e[s]);return JSON.stringify(t,null,2)}function wa(e){let t={};if(e===""||e==="?")return t;let s=(e[0]==="?"?e.slice(1):e).split("&");for(let r=0;r<s.length;++r){let n=s[r].replace(ia," "),i=n.indexOf("="),a=To(i<0?n:n.slice(0,i)),u=i<0?null:To(n.slice(i+1));if(a in t){let f=t[a];wt(f)||(f=t[a]=[f]),f.push(u)}else t[a]=u}return t}function xn(e){let t="";for(let s in e){let r=e[s];if(s=Ac(s),r==null){r!==void 0&&(t+=(t.length?"&":"")+s);continue}(wt(r)?r.map(n=>n&&Gn(n)):[r&&Gn(r)]).forEach(n=>{n!==void 0&&(t+=(t.length?"&":"")+s,n!=null&&(t+="="+n))})}return t}function ka(e){let t={};for(let s in e){let r=e[s];r!==void 0&&(t[s]=wt(r)?r.map(n=>n==null?null:""+n):r==null?r:""+r)}return t}var Ea=Symbol(""),er=Symbol(""),Zs=Symbol(""),xs=Symbol(""),en=Symbol("");function Oo(){let e=[];function t(r){return e.push(r),()=>{let n=e.indexOf(r);n>-1&&e.splice(n,1)}}function s(){e=[]}return{add:t,list:()=>e.slice(),reset:s}}function Kt(e,t,s,r,n,i=a=>a()){let a=r&&(r.enterCallbacks[n]=r.enterCallbacks[n]||[]);return()=>new Promise((u,f)=>{let v=m=>{m===!1?f(po(je.NAVIGATION_ABORTED,{from:s,to:t})):m instanceof Error?f(m):Lc(m)?f(po(je.NAVIGATION_GUARD_REDIRECT,{from:t,to:m})):(a&&r.enterCallbacks[n]===a&&typeof m=="function"&&a.push(m),u())},h=i(()=>e.call(r&&r.instances[n],t,s,v)),k=Promise.resolve(h);e.length<3&&(k=k.then(v)),k.catch(m=>f(m))})}function tn(e,t,s,r,n=i=>i()){let i=[];for(let a of e)for(let u in a.components){let f=a.components[u];if(!(t!=="beforeRouteEnter"&&!a.instances[u]))if(na(f)){let v=(f.__vccOpts||f)[t];v&&i.push(Kt(v,s,r,a,u,n))}else{let v=f();i.push(()=>v.then(h=>{if(!h)throw new Error(`Couldn't resolve component "${u}" at "${a.path}"`);let k=wc(h)?h.default:h;a.mods[u]=h,a.components[u]=k;let m=(k.__vccOpts||k)[t];return m&&Kt(m,s,r,a,u,n)()}))}}return i}function Ca(e,t){let s=[],r=[],n=[],i=Math.max(t.matched.length,e.matched.length);for(let a=0;a<i;a++){let u=t.matched[a];u&&(e.matched.find(v=>co(v,u))?r.push(u):s.push(u));let f=e.matched[a];f&&(t.matched.find(v=>co(v,f))||n.push(f))}return[s,r,n]}var zc=()=>location.protocol+"//"+location.host;function Va(e,t){let{pathname:s,search:r,hash:n}=t,i=e.indexOf("#");if(i>-1){let a=n.includes(e.slice(i))?e.slice(i).length:1,u=n.slice(a);return u[0]!=="/"&&(u="/"+u),Jn(u,"")}return Jn(s,e)+r+n}function Hc(e,t,s,r){let n=[],i=[],a=null,u=({state:m})=>{let E=Va(e,location),y=s.value,w=t.value,D=0;if(m){if(s.value=E,t.value=m,a&&a===y){a=null;return}D=w?m.position-w.position:0}else r(E);n.forEach(R=>{R(s.value,y,{delta:D,type:Qs.pop,direction:D?D>0?Xs.forward:Xs.back:Xs.unknown})})};function f(){a=s.value}function v(m){n.push(m);let E=()=>{let y=n.indexOf(m);y>-1&&n.splice(y,1)};return i.push(E),E}function h(){if(document.visibilityState==="hidden"){let{history:m}=window;if(!m.state)return;m.replaceState(Ae({},m.state,{scroll:us()}),"")}}function k(){for(let m of i)m();i=[],window.removeEventListener("popstate",u),window.removeEventListener("pagehide",h),document.removeEventListener("visibilitychange",h)}return window.addEventListener("popstate",u),window.addEventListener("pagehide",h),document.addEventListener("visibilitychange",h),{pauseListeners:f,listen:v,destroy:k}}function _a(e,t,s,r=!1,n=!1){return{back:e,current:t,forward:s,replaced:r,position:window.history.length,scroll:n?us():null}}function Bc(e){let{history:t,location:s}=window,r={value:Va(e,s)},n={value:t.state};n.value||i(r.value,{back:null,current:r.value,forward:null,position:t.length-1,replaced:!0,scroll:null},!0);function i(f,v,h){let k=e.indexOf("#"),m=k>-1?(s.host&&document.querySelector("base")?e:e.slice(k))+f:zc()+e+f;try{t[h?"replaceState":"pushState"](v,"",m),n.value=v}catch(E){console.error(E),s[h?"replace":"assign"](m)}}function a(f,v){i(f,Ae({},t.state,_a(n.value.back,f,n.value.forward,!0),v,{position:n.value.position}),!0),r.value=f}function u(f,v){let h=Ae({},n.value,t.state,{forward:f,scroll:us()});i(h.current,h,!0),i(f,Ae({},_a(r.value,f,null),{position:h.position+1},v),!1),r.value=f}return{location:r,state:n,push:u,replace:a}}function qa(e){e=ma(e);let t=Bc(e),s=Hc(e,t.state,t.location,t.replace);function r(i,a=!0){a||s.pauseListeners(),history.go(i)}let n=Ae({locatLine truncated
`)),e.options=Object.assign({},e.options,v.options),i.restore()})}a();let u=null;e.saveDefault=f=>{if(f&&f.preventDefault&&f.preventDefault(),e.saving)return;let v=i.checkpoint(),h={terms:e.terms.split(`
`).map(k=>k.trim()).filter(k=>k.length>0),options:e.options};e.saving=!0,e.error=null,t.post("/api/user/default",h).then(()=>{i.accept(v),e.saving=!1,e.message=e.unsavedChanges?null:"Saved",u&&r.cancel(u),u=r(()=>{e.message=null},2500)},k=>{e.saving=!1;let m=k&&k.data&&k.data.error,E="Unable to save your defaults. Please try again.";Promise.all([s("ERRORS."+m),s("ERRORS.unknown_error")]).then(([y,w])=>{e.error=m&&y!==w?y:E},()=>{e.error=E})})},e.deleteAccount=()=>{confirm("Delete your account? All your anonymized repositories, gists, and pull requests will be removed, and your personal data will be erased. This cannot be undone.")&&(e.deletingAccount=!0,t.delete("/api/user").then(()=>{window.location.href="/"},()=>{e.deletingAccount=!1,e.deleteError="Unable to delete the account. Please try again."}))}},Ya=function(e,t,s){e.repoId=null,e.repoUrl=null,e.claim=()=>{t.post("/api/repo/claim",{repoId:e.repoId,repoUrl:e.repoUrl}).then(r=>{s.url("/dashboard")},r=>{e.error=r.data,e.claimForm.repoUrl.setValidity("not_found",!1),e.claimForm.repoId.setValidity("not_found",!1)})}},Ja=function(e,t,s,r,n){e.user&&!e.user.status&&s.url("/dashboard"),e.watch("user.status",()=>{e.user&&!e.user.status&&s.url("/dashboard")}),e.features=[{key:"anonymize",num:"01",eyebrow:"Anonymize",title:"Double-anonymous,",accent:"your rules.",text:"Choose what reviewers may see: links, images, PDFs, notebooks, GitHub Pages. Add your own terms, with regex if you need it, and pick the expiration date.",cta:"Start an anonymization",href:"/anonymize",url:"anonymous.4open.science/anonymize",img:"/imgs/anonymize.png",alt:"The anonymize form: source repository, terms to redact, options and a live README preview"},{key:"review",num:"02",eyebrow:"Review",title:"Reviewers browse",accent:"the real thing.",text:"Highlighted source code, rendered PDFs, images, and notebooks, in a familiar file explorer. GitHub Pages is also supported.",cta:"Open the example",href:"https://anonymous.4open.science/r/840c8c57-3c32-451e-bf12-0e20be300389/",target:"_self",url:"anonymous.4open.science/r/840c8c57-\u2026",img:"/imgs/explorer.png",alt:"The repository explorer with a file tree and a rendered README"},{key:"manage",num:"03",eyebrow:"Manage",title:"One dashboard,",accent:"until the decision.",text:"Monitor views, edit configuration, remove or update your repository. Program chairs can group submissions under a conference with one shared expiry.",cta:"Open the dashboard",href:"/dashboard",needsUser:!0,url:"anonymous.4open.science/dashboard",img:"/imgs/dashboard.png",alt:"The dashboard listing anonymized repositories with status, views and expiry"}],e.feature=e.features[0].key,e.selectFeature=function(u){e.feature=u},e.featureHref=function(u){return u.needsUser&&!e.user?"/signin":u.href},e.featureTarget=function(u){return u.needsUser&&!e.user?"_self":u.target||void 0},e.featureKeydown=function(u,f){let v={ArrowDown:1,ArrowRight:1,ArrowUp:-1,ArrowLeft:-1,Home:"first",End:"last"}[u.key];if(v===void 0)return;u.preventDefault();let h=e.features.length,k=v==="first"?0:v==="last"?h-1:(f+v+h)%h;e.feature=e.features[k].key,n(()=>{let m=r.document.getElementById("feature-tab-"+e.feature);m&&m.focus()})},e.cards=[{key:"repositories",total:0,label:"repositories anonymized"},{key:"users",total:0,label:"researchers"},{key:"pageViews",total:0,label:"page views"},{key:"pullRequests",total:0,label:"pull requests"}];function i(){t.get("/api/stat/").then(u=>{e.stat=u.data,e.cards[0].total=u.data.nbRepositories,e.cards[1].total=u.data.nbUsers,e.cards[2].total=u.data.nbPageViews,e.cards[3].total=u.data.nbPullRequests})}i();function a(u){let f={series:u,bars:[],viewW:100,deltaToday:0,pctChange:0,pctAbs:0,isUp:!0};if(!u||u.length<2)return f;let v=new Array(u.length-1);for(let w=1;w<u.length;w++)v[w-1]=u[w]-u[w-1];let h=v.length,k=Math.max.apply(null,v),m=Math.min.apply(null,v),E=Math.min(0,m),y=k-E||1;f.viewW=h*2,f.bars=new Array(h);for(let w=0;w<h;w++){let D=(v[w]-E)/y,R=Math.max(1.5,D*34);f.bars[w]={x:(w*2+.25).toFixed(2),y:(36-R).toFixed(2),w:"1.5",h:R.toFixed(2)}}if(f.deltaToday=v[h-1],h>=2){let w=v[h-2];w&&(f.pctChange=(f.deltaToday-w)/w*100)}return f.pctAbs=Math.round(Math.abs(f.pctChange)),f.isUp=f.pctChange>=0,f}e.history={repositories:a([]),users:a([]),pageViews:a([]),pullRequests:a([])},t.get("/api/stat/history?days=60").then(u=>{let f=u.data||[];e.history={repositories:a(f.map(v=>v.nbRepositories||0)),users:a(f.map(v=>v.nbUsers||0)),pageViews:a(f.map(v=>v.nbPageViews||0)),pullRequests:a(f.map(v=>v.nbPullRequests||0))}})},Qa=function(e,t,s,r,n,i){let a=ct();e.on("routeLeave",function(){$('[data-toggle="tooltip"]').tooltip("dispose")}),e.watch("user.status",()=>{e.user==null&&s.url("/")}),e.user==null&&s.url("/"),a.timeout(()=>{$('[data-toggle="tooltip"]').tooltip()},250),e.quotaExpanded=!1,e.closeQuota=()=>{e.quotaExpanded=!1,st(()=>document.querySelector(".dashboard-quota > summary")?.focus())},Jt()(document,"click",_=>{e.quotaExpanded&&!_.target.closest?.(".dashboard-quota")& Line truncated
`)),e.options=Object.assign({},e.options,B.options),e.options.expirationDate=B.options&&B.options.expirationDate?new Date(B.options.expirationDate):T(),!r.repoId&&!r.pullRequestId&&!r.gistId&&!e.anonymize?.terms?.dirty&&(e.terms=e.defaultTerms),C&&C()})}function U(C,P,B){e.anonymize&&e.anonymize[C]&&e.anonymize[C].setValidity(P,B)}function ae(C){try{let P=parseGithubUrl(C);if(P&&P.owner&&P.repo)return P.owner+"/"+P.repo}catch{}return null}e.reconnectingSource=!1,e.reconnectRepositoryId=void 0,e.reconnectSource=async()=>{if(confirm("Reconnect to the repository currently at this GitHub URL? Review its branch and commit before saving. Saving will replace the published snapshot.")){e.reconnectingSource=!0,e.reconnectRepositoryId=void 0,e.source.commit="",e.source.branch="",e.readme="",e.branches=[];try{await Y()}catch{}}};function ie(){return e.reconnectingSource||!e.isUpdate||!e._originalRepositoryID?void 0:ae(e.sourceUrl)===e._originalFullName?e._originalRepositoryID:void 0}async function _(){e._preservingDraft=!0;try{await e.urlSelected(!0)}finally{e._preservingDraft=!1}}async function O(){let C;try{C=JSON.parse(sessionStorage.getItem("github-access-draft")||"null")}catch{return!1}if(!C||C.path!==n.path()||Date.now()-C.savedAt>=30*6e4)return D.restore()?(e.sourceUrl&&await _(),!0):!1;D.restore();for(let P of["sourceUrl","terms","repoId","pullRequestId","gistId","source","options","conference","githubConnection"])Object.prototype.hasOwnProperty.call(C.draft,P)&&(e[P]=C.draft[P]);return e.options.expirationDate&&(e.options.expirationDate=new Date(e.options.expirationDate)),await _(),sessionStorage.removeItem("github-access-draft"),!0}q(()=>{!r.repoId&&!r.pullRequestId&&!r.gistId&&a(O,0),r.repoId&&r.repoId!=""&&(e.isUpdate=!0,e.detectedType="repo",e.repoId=r.repoId,t.get("/api/repo/"+e.repoId).then(async C=>{e.githubConnection=C.data.connection||"oauth",e.sourceUrl="https://github.com/"+C.data.source.fullName,e._originalFullName=C.data.source.fullName,e.terms=C.data.options.terms.filter(P=>P).join(`
`),e.source=C.data.source,e.role=C.data.role||"owner",e.coauthors=C.data.coauthors||[],e._originalBranch=C.data.source.branch,e.options=Object.assign({},e.options,C.data.options),e.conference=C.data.conference,e._originalConference=C.data.conference,e.repositoryID=C.data.source.repositoryID,e._originalRepositoryID=C.data.source.repositoryID,C.data.options.expirationDate&&(e.options.expirationDate=new Date(C.data.options.expirationDate)),y=w(parseGithubUrl(e.sourceUrl)),!await O()&&(await Promise.all([Y(),Z()]),ue())},()=>{n.url("/404")})),r.pullRequestId&&r.pullRequestId!=""&&(e.isUpdate=!0,e.detectedType="pr",e.pullRequestId=r.pullRequestId,t.get("/api/pr/"+e.pullRequestId).then(async C=>{if(e.githubConnection=C.data.connection||"oauth",e.sourceUrl="https://github.com/"+C.data.source.repositoryFullName+"/pull/"+C.data.source.pullRequestId,e.terms=C.data.options.terms.filter(P=>P).join(`
`),e.source=C.data.source,e.options=Object.assign({},e.options,C.data.options),e.conference=C.data.conference,e._originalConference=C.data.conference,C.data.options.expirationDate&&(e.options.expirationDate=new Date(C.data.options.expirationDate)),y=w(parseGithubUrl(e.sourceUrl)),!await O())try{await pe()}catch{}},()=>{n.url("/404")})),r.gistId&&r.gistId!=""&&(e.isUpdate=!0,e.detectedType="gist",e.gistId=r.gistId,t.get("/api/gist/"+e.gistId).then(async C=>{e.sourceUrl="https://gist.github.com/"+C.data.source.gistId,e.terms=C.data.options.terms.filter(P=>P).join(`
`),e.source=C.data.source,e.options=Object.assign({},e.options,C.data.options),e.conference=C.data.conference,e._originalConference=C.data.conference,C.data.options.expirationDate&&(e.options.expirationDate=new Date(C.data.options.expirationDate)),y=w(parseGithubUrl(e.sourceUrl)),!await O()&&await Ue()},()=>{n.url("/404")}))}),t.get("/github/connections").then(C=>{e.githubConnections=C.data,!r.repoId&&!r.pullRequestId&&!r.gistId&&e.githubConnection===void 0&&C.data.appEnabled&&C.data.appConnected&&(e.githubConnection="github-app",e.sourceUrl&&e.workspaceOpen&&_())}).catch(()=>{}),e.urlSelected=async(C=!1)=>{let P=++f,B;try{B=parseGithubUrl(e.sourceUrl.trim())}catch{e.sourceLoading=!1,se.cancel(),_e.cancel(),Pe.cancel(),e.previewStatus="idle",e.sourceUrlError=e.sourceUrl?"Please provide a valid GitHub URL.":"",U("sourceUrl","github",!1);return}let M=w(B),g=C||y===M;y=M,e.sourceUrlError="",U("sourceUrl","github",!0);let S=document.activeElement?.id==="sourceUrl-landing";e.workspaceOpen=!0,S&&a(()=>document.getElementById("sourceUrl")?.focus(),0),e.reconnectingSource=!1,e.reconnectRepositoryId=void 0,!g&&!e.isUpdate&&(e.repoId="",e.pullRequestId="",e.gistId=""),e.details=null,e.branches=[],g||(e.source={type:"GitHubStream",branch:"",commit:""}),se.cancel(),_e.cancel(),Pe.cancel(),le.clear(),Re.clear(),e.previewStatus="idle",e.anonymize_readme="",e.readme="",e.html_readme="",e.detectedType=null,e.gistOAuthRequired=!1,e.gistAppRequired=!1,e._preservingDraft=g;try{B.gistId&&!B.repo?(e.detectedType="gist",e.source={gistId:B.gistId},await Ue()):B.pullRequestId?(e.detectedType="pr",e.source={repositoryFullName:B.owner+"/"+B.repo,pullRequestId:B.pullRequestId},await pe()):(e.detectedType="repo",await Promise.all([Y(),Z()]),ue())}catch{}finally{P===f&&(e._preservingDraft=!1)}$('[data-toggle="tooltip"]').tooltip()},$('[data-toggle="tooltip"]').tooltip(),e.watch("source.branch",async()=>{if(e.detectedType!=="repo")return;let C=e.branches.filter(B=>B.name==e.source.branch)[0];if(!C)return;!(!e.reconnectingSource&&e.isUpdate&&e._originalBranch===e.source.branch&&!!e.source.commit)&&!(e._preservingDraft&&e.source.commit)&&(e.source.commit=C.commit),e.readme=C.readme,await Z(),ue()}),e.getBranches=async C=>{let P=parseGithubUrl(e.sourceUrl),B=m();try{let M=await t.get(`/api/repo/${P.owner}/${P.repo}/branches`,{params:{reconnect:e.reconnectingSource?"1":void 0,anonymizedRepoId:e.isUpdate&&r.repoId&&ae(e.sourceUrl)===e._originalFullName?r.repoId:void 0,connection:e.githubConnection,force:C===!0||e.reconnectingSource?"1":"0",repositoryID:ie()}});if(!k(B))return;e.branches=M.data,e.sourceUnreachable=!1,e.source.branch||(e.source.branch=e.details.defaultBranch);let g=e.branches.filter(S=>S.name==e.source.branch);g.length>0&&(!(!e.reconnectingSource&&!C&&e.isUpdate&&!e.options.update&&e._originalBranch===e.source.branch&&e.source.commit)&&!(e._preservingDraft&&e.source.commit)&&(e.source.commit=g[0].commit),e.readme=g[0].readme,await Z(C))}catch(M){if(!k(B))return;e.branches=[],e.sourceUnreachable=M&&(M.status===404||M.data&&M.data.error==="repo_not_found");let g=M&&M.data&&M.data.error||(M&&M.status===404?"repo_not_found":"unknown_error");i("ERRORS."+g).then(S=>{e.toasts=e.toasts||[],e.addToast({title:"Error",date:new Date,body:S}),e.error=S},console.error),typeof U=="function"&&U("sourceUrl","missing",!1)}finally{E(B)}};async function Y(){let C=parseGithubUrl(e.sourceUrl),P=m();try{F();let B=await t.get(`/api/repo/${C.owner}/${C.repo}/`,{params:{reconnect:e.reconnectingSource?"1":void 0,anonymizedRepoId:e.isUpdate&&r.repoId&&ae(e.sourceUrl)===e._originalFullName?r.repoId:void 0,connection:e.githubConnection,repositoryID:ie(),force:"1"}});if(!k(P))return;e.details=B.data,e.reconnectingSource&&(e.reconnectRepositoryId=e.details.externalId),e.details&&e.details.id&&(e.repositoryID=e.details.id),e.repoId||(e.repoId=e.details.repo+"-"+generateRandomId(4)),await e.getBranches(e.reconnectingSource)}catch(B){if(!k(P))return;throw B.data&&(i("ERRORS."+B.data.error).then(M=>{e.addToast({title:"Error",date:new Date,body:M}),e.error=M},console.error),Q(B.data.error)),U("sourceUrl","missing",!1),B}finally{E(P)}}async function Z(C){if(e.readme&&!C)return e.readme;let P=parseGithubUrl(e.sourceUrl),B=m();try{let M=await t.get(`/api/repo/${P.owner}/${P.repo}/readme`,{params:{reconnect:e.reconnectingSource?"1":void 0,anonymizedRepoId:e.isUpdate&&r.repoId&&ae(e.sourceUrl)===e._originalFullName?r.repoId:void 0,connection:e.githubConnection,force:C===!0?"1":"0",branch:e.source.branch,repositoryID:ie()}});k(B,!0)&&(e.readme=M.data)}catch{k(B,!0)&&(e.readme="")}finally{E(B)}}function te(){let C={terms:e.terms?e.terms.split(`
`):[],image:!!e.options.image,link:!!e.options.link,repoId:e.repoId};e.source&&e.source.branch&&(C.branchName=e.source.branch);try{let P=parseGithubUrl(e.sourceUrl);C.repoName=`${P.owner}/${P.repo}`}catch{}return C}function J(C,P,B){let M=null,g=0,S=()=>{if(e.detectedType!==C)return;M&&a.cancel(M);let V=++g;e.previewStatus="loading",M=a(()=>{M=null;let z=P();if(!z){e.previewStatus="idle";return}t.post("/api/anonymize-preview",z).then(j=>{V===g&&(B(j.data,z),e.previewStatus="ready")}).catch(()=>{V===g&&(e.previewStatus="error")})},200)};return S.cancel=()=>{g++,M&&a.cancel(M),M=null},e.on("dispose",S.cancel),S}e.retryPreview=()=>{e.detectedType==="repo"&&se(),e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()};let se=J("repo",()=>e.readme?{content:e.readme,options:te()}:null,C=>{if(typeof C?.content!="string")throw Error("Invalid preview response");e.anonymize_readme=C.content;let P="";try{let M=parseGithubUrl(e.sourceUrl),g=e.source.branch||e.details&&e.details.defaultBranch||"main";P=`https://github.com/${M.owner}/${M.repo}/raw/${g}/`}catch{}let B=renderMD(e.anonymize_readme,P);e.html_readme=B,a(Prism.highlightAll,150)});function ue(){!e.anonymize||!e.anonymize.terms||(e.termsRegexWarning=!!e.terms&&!!e.terms.match(/[-[\]{}()*+?.,\\^$|#]/g),se())}async function pe(){let C=parseGithubUrl(e.sourceUrl),P=m();try{F();let B=await t.get(`/api/pr/${C.owner}/${C.repo}/${C.pullRequestId}`,{params:{connection:e.githubConnection}});if(!k(P))return;e.details=B.data,e.pullRequestId||(e.pullRequestId=C.repo+"-PR"+C.pullRequestId+"-"+generateRandomId(4))}catch(B){if(!k(P))return;throw B.data&&(i("ERRORS."+B.data.error).then(M=>{e.addToast({title:"Error",date:new Date,body:M}),e.error=M},console.error),Q(B.data.error)),U("sourceUrl","missing",!1),B}finally{E(P)}}let le=ze(new Map);function Oe(){let C=new Set,P=e.details&&e.details.pullRequest;if(!P)return C;typeof P.title=="string"&&C.add(P.title),typeof P.body=="string"&&C.add(P.body),typeof P.diff=="string"&&C.add(P.diff);let B=P.comments||[];for(let M of B)typeof M.author=="string"&&C.add(M.author),typeof M.body=="string"&&C.add(M.body);return C}let _e=J("pr",()=>{let C=Oe(),P=Array.from(C);return P.length===0?null:{contents:P,options:te()}},(C,P)=>{if(!Array.isArray(C?.contents)||C.contents.length!==P.contents.length||C.contents.some(g=>typeof g!="string"))throw Error("Invalid preview response");let B=P.contents,M=new Map;for(let g=0;g<B.length&&g<C.contents.length;g++)M.set(B[g],C.contents[g]);le.clear(),M.forEach((g,S)=>le.set(S,g))});e.anonymizePrContent=function(C){return C&&(le.has(C)?le.get(C):"")};async function Ue(){let C=parseGithubUrl(e.sourceUrl),P=m();try{F(),e.gistOAuthRequired=!1,e.gistAppRequired=!1;let B=await t.get(`/api/gist/source/${C.gistId}`);if(!k(P))return;e.details=B.data,e.gistId||(e.gistId="gist-"+C.gistId.substring(0,6)+"-"+generateRandomId(4))}catch(B){if(!k(P))return;if(B.data?.error==="github_app_reconnect_required"){e.gistAppRequired=!0,U("sourceUrl","missing",!1);return}if(B.data?.error==="github_oauth_required"){e.gistOAuthRequired=!0,U("sourceUrl","missing",!1);return}throw B.data&&(i("ERRORS."+B.data.error).then(M=>{e.addToast({title:"Error",date:new Date,body:M}),e.error=M},console.error),Q(B.data.error)),U("sourceUrl","missing",!1),B}finally{E(P)}}let Re=ze(new Map);function $e(){let C=new Set,P=e.details&&e.details.gist;if(!P)return C;typeof P.description=="string"&&C.add(P.description),typeof P.ownerLogin=="string"&&C.add(P.ownerLogin);let B=P.files||[];for(let g of B)typeof g.filename=="string"&&C.add(g.filename),typeof g.content=="string"&&C.add(g.content);let M=P.comments||[];for(let g of M)typeof g.author=="string"&&C.add(g.author),typeof g.body=="string"&&C.add(g.body);return C}let Pe=J("gist",()=>{let C=$e(),P=Array.from(C);return P.length===0?null:{contents:P,options:te()}},(C,P)=>{if(!Array.isArray(C?.contents)||C.contents.length!==P.contents.length||C.contents.some(g=>typeof g!="string"))throw Error("Invalid preview response");let B=P.contents,M=new Map;for(let g=0;g<B.length&&g<C.contents.length;g++)M.set(B[g],C.contents[g]);Re.clear(),M.forEach((g,S)=>Re.set(S,g)),He()});e.anonymizeGistContent=function(C){return C&&(Re.has(C)?Re.get(C):"")},e.previewGistFiles=[];function He(){let C=e.details&&e.details.gist&&e.details.gist.files||[];e.previewGistFiles=C.map(P=>({filename:e.anonymizeGistContent(P.filename),content:e.anonymizeGistContent(P.content),language:P.language}))}e.watch("details.gist.files",He,!0),e.watch("terms",He);function Ee(){let C=e.conference;if(e.conference_data=null,!C)return;let P=e.isUpdate&&C===e._originalConference;t.get("/api/conferences/"+C).then(B=>{e.conference===C&&(e.conference_data=B.data,e.conference_data.startDate=new Date(e.conference_data.startDate),e.conference_data.endDate=new Date(e.conference_data.endDate),!P&&(e.options.expirationDate=new Date(e.conference_data.endDate),e.options.expirationMode="remove",e.options.update=e.conference_data.options.update,e.options.image=e.confe Line truncated
`).filter(S=>S),connection:e.githubConnection,fullName:`${B.owner}/${B.repo}`,repository:e.sourceUrl,reconnectRepositoryId:e.reconnectRepositoryId,options:e.options,source:e.source,conference:e.conference};e.details&&(M.options.pageSource=e.details.pageSource),F();let g=e.isUpdate?"/api/repo/"+e.repoId:"/api/repo/";t.post(g,M,{headers:{"Content-Type":"application/json"}}).then(()=>{D.clear(),window.location.href="/status/"+e.repoId},S=>{S.data&&(i("ERRORS."+S.data.error).then(V=>{e.error=V},console.error),Q(S.data.error))}).finally(()=>{P.disabled=!1})},e.anonymizeGist=C=>{if(e.sourceLoading){e.error="Wait for the source to finish loading before saving.";return}if(oe())return;if(e.anonymize?.invalid||e.sourceUrlError){e.error="Please correct the highlighted fields before saving.";return}let P=C.currentTarget||C.target.closest?.("button")||C.target;P.disabled=!0;let B=parseGithubUrl(e.sourceUrl),M={gistId:e.gistId,terms:e.terms.trim().split(`
`).filter(S=>S),source:{gistId:B.gistId},options:e.options,conference:e.conference};F();let g=e.isUpdate?"/api/gist/"+e.gistId:"/api/gist/";t.post(g,M,{headers:{"Content-Type":"application/json"}}).then(()=>{D.clear(),window.location.href="/gist/"+e.gistId},S=>{S.data&&(i("ERRORS."+S.data.error).then(V=>{e.error=V},console.error),Q(S.data.error))}).finally(()=>{P.disabled=!1})},e.anonymizePullRequest=C=>{if(e.sourceLoading){e.error="Wait for the source to finish loading before saving.";return}if(oe())return;if(e.anonymize?.invalid||e.sourceUrlError){e.error="Please correct the highlighted fields before saving.";return}let P=C.currentTarget||C.target.closest?.("button")||C.target;P.disabled=!0;let B=parseGithubUrl(e.sourceUrl),M={pullRequestId:e.pullRequestId,connection:e.githubConnection,terms:e.terms.trim().split(`
`).filter(S=>S),source:{repositoryFullName:`${B.owner}/${B.repo}`,pullRequestId:B.pullRequestId},options:e.options,conference:e.conference};F();let g=e.isUpdate?"/api/pr/"+e.pullRequestId:"/api/pr/";t.post(g,M,{headers:{"Content-Type":"application/json"}}).then(()=>{D.clear(),window.location.href="/pr/"+e.pullRequestId},S=>{S.data&&(i("ERRORS."+S.data.error).then(V=>{e.error=V},console.error),Q(S.data.error))}).finally(()=>{P.disabled=!1})},e.watch("conference",()=>{Ee()}),e.watch("terms",()=>{e.detectedType==="repo"&&ue(),e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()}),e.watch("options.image",()=>{e.detectedType==="repo"&&ue(),e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()}),e.watch("options.link",()=>{e.detectedType==="repo"&&ue(),e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()}),e.watch("details",()=>{e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()},!0)},nr=function(e,t,s,r,n,i){let a=ct();window.Prism?.hooks&&!window.Prism.redactionHook&&(window.Prism.hooks.add("complete",O=>Ha(O.element)),window.Prism.redactionHook=!0);let u=Jt();e.on("dark-mode",(O,Y)=>{e.aceOption&&(Y?e.aceOption.theme="nord_dark":e.aceOption.theme="chrome")});let f=0,v=!1;e.on("dispose",()=>{v=!0,f++,h&&h.resolve()}),e.files=[],e.isMac=/Mac|iPhone|iPad|iPod/.test(navigator.platform||navigator.userAgent),e.fileSearchQuery="",e.fileSearchResults=null,e.fileSearchLoading=!1,u(document,"keydown",function(O){if((O.metaKey||O.ctrlKey)&&O.key==="k"){O.preventDefault();var Y=document.querySelector(".tree-search-input");Y&&(Y.focus(),Y.select())}});var h=null;e.onFileSearchChange=function(){h&&(h.resolve(),h=null);let O=e.fileSearchQuery;if(!O||O.length<2){e.fileSearchResults=null,e.fileSearchLoading=!1;return}e.fileSearchLoading=!0;let Y=i.defer();h=Y,t.get(`/api/repo/${e.repoId}/files/search?q=${encodeURIComponent(O)}`,{timeout:Y.promise}).then(function(Z){if(!(v||h!==Y)){h=null,e.fileSearchLoading=!1;var te={};e.files.forEach(function(F){te[(F.path||"")+"/"+F.name]=!0});for(var J=[],se={},ue=0;ue<Z.data.length;ue++){var pe=Z.data[ue];if(pe.path)for(var le=pe.path.split("/"),Oe="",_e=0;_e<le.length;_e++){var Ue=Oe;Oe=Oe?Oe+"/"+le[_e]:le[_e];var Re=Ue+"/"+le[_e];!te[Re]&&!se[Re]&&(se[Re]=!0,J.push({name:le[_e],path:Ue}))}}J.sort(function(F,oe){return(F.path||"").split("/").length-(oe.path||"").split("/").length}),J.length>0&&e.files.push.apply(e.files,J);for(var $e=[],Pe=0;Pe<Z.data.length;Pe++){var He=Z.data[Pe],Ee=(He.path||"")+"/"+He.name;!te[Ee]&&He.size!=null&&($e.push(He),te[Ee]=!0)}$e.length>0&&e.files.push.apply(e.files,$e),e.fileSearchResults=Z.data}},function(){!v&&h===Y&&(h=null,e.fileSearchLoading=!1,e.fileSearchResults=[])})};let k={yml:"yaml",txt:"text",py:"python",js:"javascript",ts:"typescript"},m=["license","txt"],E=["png","jpg","jpeg","gif","svg","ico","bmp","tiff","tif","webp","avif","heif","heic"],y=["wav","mp3","ogg","wma","flac","aac","m4a"],w=["mp4","avi","webm","mov","mpg","mpeg","mkv","flv","wmv","3gp","3g2","m4v","f4v","f4p","f4a","f4b"];e.on("routeUpdate",function(O,Y){if(e.repoId!=r.repoId)return _();if((r.path||"")!=e.filePath){e.filePath=r.path||"",e.paths=e.filePath.split("/").filter(Z=>Z&&Z.trim().length>0),ie();for(let Z=0;Z<e.paths.length-1;Z++){let te=Z>0?e.paths.slice(0,Z).join("/"):"";e.files.some(se=>se.path===te)||e.getFiles(te)}}});function D(){if(e.paths[0]!="")return;let O=["readme.md","readme.txt","readme.org","readme.1st","readme"],Y={};for(let te of e.files)te.name.toLowerCase().indexOf("readme")>-1&&(Y[te.name.toLowerCase()]=te.name);let Z=null;for(let te of O)if(Y[te]){Z=te;break}if(!Z&&Object.keys(Y).length>0&&(Z=Object.keys(Y)[0]),Z){let te=s.url();te[te.length-1]!="/"&&(te+="/"),s.url(te+encodePathForUrl(Y[Z]))}}e.fileCounts=null,e.getFiles=function(O){let Y=e.repoId;return t.get(`/api/repo/${e.repoId}/files/?path=${encodeURIComponent(O)}&v=${e.options.lastUpdateDate}`).then(function(Z){if(v||Y!==e.repoId)return[];let te=O||"";return e.files=e.files.filter(J=>J.path!==te),e.files.push(...Z.data),Z.data},function(Z){if(v||Y!==e.repoId)return[];e.type="error",e.content=Z&&Z.data&&Z.data.error||"unknown_error",e.files=[]})};function R(){let O=e.repoId;t.get(`/api/repo/${e.repoId}/files/counts`).then(function(Y){v||O!==e.repoId||(e.fileCounts=Y.data)},function(){e.fileCounts={}})}function T(){return e.files.filter(O=>O.name==e.paths[e.paths.length-1]&&O.path==e.paths.slice(0,e.paths.length-1).join("/"))[0]}var I=null;e.on("dispose",function(){I&&a.interval.cancel(I)});function H(O){if(v)return;let Y=e.repoId;t.get(`/api/repo/${e.repoId}/options`).then(Z=>{if(!(v||Y!==e.repoId)){if(e.options=Z.data,e.options.url){window.location=e.options.url;return}O&&O(Z.data)}},Z=>{if(!(v||Y!==e.repoId)){var te=Z.data||{};if(te.error==="rate_limited"&&te.resetAt){let se=function(){var ue=Math.max(0,Math.ceil((e.rateLimitResetAt-Date.now())/1e3));if(ue<=0)e.rateLimitCountdown="",e.rateLimitResetAt=0,I&&(a.interval.cancel(I),I=null),H(O);else{var pe=Math.floor(ue/60),l Line truncated
`+w.join(`
`)],{type:"text/csv"}),R=document.createElement("a");R.href=URL.createObjectURL(D),R.download=r.username+"-repositories.csv",R.click()},e.showStatusMessage=m=>{let E=m.statusMessage||"(no message)";window.prompt(`Status message for ${m.repoId} (${m.status}):`,E)},e.fetchGithubInfo=m=>{let E=window.open("","_blank");E&&E.document.write("<pre>Loading GitHub info for "+m.repoId+"...</pre>"),t.get("/api/admin/repos/"+m.repoId+"/github").then(y=>{E&&(E.document.open(),E.document.write('<pre style="font:13px monospace;padding:16px;white-space:pre-wrap">'+JSON.stringify(y.data,null,2).replace(/[<>]/g,w=>w==="<"?"&lt;":"&gt;")+"</pre>"),E.document.close())},y=>{let w=y&&y.data?JSON.stringify(y.data,null,2):String(y);E&&(E.document.body.innerHTML='<pre style="color:#B42318;padding:16px">'+w+"</pre>")})};function f(m){t.get("/api/admin/users/"+m+"/repos",{}).then(E=>{e.repositories=E.data},E=>{console.error(E)})}function v(m){t.get("/api/admin/users/"+m,{}).then(E=>{e.userInfo=E.data},E=>{console.error(E)})}v(r.username),f(r.username),e.banUser=()=>{confirm(`Ban user ${r.username}?`)&&t.post(`/api/admin/users/${r.username}/ban`).then(()=>v(r.username),m=>console.error(m))},e.activateUser=()=>{t.post(`/api/admin/users/${r.username}/activate`).then(()=>v(r.username),m=>console.error(m))},e.promoteUser=()=>{confirm(`Promote ${r.username} to admin?`)&&t.post(`/api/admin/users/${r.username}/promote`).then(()=>v(r.username),m=>console.error(m))},e.demoteUser=()=>{confirm(`Remove admin privileges from ${r.username}?`)&&t.post(`/api/admin/users/${r.username}/demote`).then(()=>v(r.username),m=>console.error(m))},e.tokens=[],e.tokenForm={name:"",plaintext:null};function h(){t.get("/api/admin/tokens").then(m=>{e.tokens=m.data||[]},m=>{m.status!==401&&m.status!==403&&console.error(m)})}h(),e.createToken=()=>{e.tokenForm.name&&t.post("/api/admin/tokens",{name:e.tokenForm.name}).then(m=>{e.tokenForm.plaintext=m.data.token,e.tokenForm.name="",h()},m=>console.error(m))},e.revokeToken=m=>{confirm(`Revoke token "${m.name}"?`)&&t.delete("/api/admin/tokens/"+m.id).then(()=>h(),E=>console.error(E))},e.removeCache=m=>{confirm("Remove cached files for "+m.repoId+"?")&&t.delete("/api/admin/repos/"+m.repoId).then(()=>f(r.username),E=>console.error(E))},e.removeRepository=m=>{confirm("Remove repository "+m.repoId+"?")&&t.delete("/api/repo/"+m.repoId+"/").then(()=>f(r.username),E=>console.error(E))},e.updateRepository=m=>{let E=ze({title:`Refreshing ${m.repoId}...`,date:new Date,body:`The repository ${m.repoId} is going to be refreshed.`});e.toasts.push(E),t.post(`/api/repo/${m.repoId}/refresh`).then(y=>{y.data.status=="ready"?E.title=`${m.repoId} is refreshed.`:E.title=`Refreshing of ${m.repoId}.`},y=>{E.title=`Error during the refresh of ${m.repoId}.`,E.body=y.body})},e.getGitHubRepositories=m=>{t.get(`/api/user/${e.userInfo.username}/all_repositories`,{params:{force:"1"}}).then(E=>{e.userInfo.repositories=E.data})};let k=null;e.watch("query",()=>{n.timeout.cancel(k),k=n.timeout(()=>{f(r.username)},500)},!0)},al=function(e,t,s){let r=ct(),n=Jt();e.Math=Math,e.watch("user.status",()=>{e.user==null&&s.url("/")}),e.user==null&&s.url("/"),e.conferences=[],e.total=-1,e.totalPage=0,e.statusCounts=[];let i=y=>{if(y.key==="/"&&!["INPUT","TEXTAREA","SELECT"].includes(document.activeElement?.tagName)){y.preventDefault();let w=document.querySelector('.admin-filter-toolbar input[type="search"]');w&&w.focus()}};n(document,"keydown",i),e.on("dispose",()=>document.removeEventListener("keydown",i)),e.clearFilter=y=>{y==="dateRange"?(e.query.dateFrom="",e.query.dateTo=""):e.query[y]="",e.query.page=1},e.chips=[];let a=()=>{let y=[];(e.query.dateFrom||e.query.dateTo)&&y.push({key:"dateRange",label:"Date",value:(e.query.dateFrom||"\u2026")+" \u2013 "+(e.query.dateTo||"\u2026")}),e.chips=y};e.statusCountFor=y=>{let w=(e.statusCounts||[]).find(D=>D._id===y);return w?w.count:0},e.toggleSortDirection=()=>{e.query.direction=e.query.direction==="asc"?"desc":"asc"},e.sortBy=y=>{e.query.sort===y?e.query.direction=e.query.direction==="asc"?"desc":"asc":(e.query.sort=y,e.query.direction="desc"),e.query.page=1},e.sortIcon=y=>e.query.sort===y?e.query.direction==="asc"?"fa-arrow-up":"fa-arrow-down":"";let u="admin.conferences.filterPrefs",f={page:1,limit:25,sort:"name",direction:"asc",search:"",dateFrom:"",dateTo:"",ready:!1,expired:!1,removed:!1,error:!0,preparing:!0},v=loadFilterPrefs(u)||{};e.query=Object.assign({},f,v,{page:1,search:""});let h=s.search();h.search&&(e.query.search=h.search);let k="admin.conferences.presets";e.presets=JSON.parse(localStorage.getItem(k)||"[]"),e.savePreset=()=>{let y=window.prompt("Preset name:");if(!y)return;let w=Object.assign({},e.query);delete w.page,e.presets=(e.presets||[]).filter(D=>D.name!==y),e.presets.push({name:y,query:w}),localStorage.setItem(k,JSON.stringify(e.presets))},e.applyPreset=y=>{Object.assign(e.query,y.query,{page:1})},e.deletePreset=y=>{e.presets=(e.presets||[]).filter(w=>w.name!==y.name),localStorage.setItem(k,JS Line truncated
`).map((ue,pe)=>pe===0?ue:se+ue).join(`
`)}else typeof _=="number"||typeof _=="boolean"?J=String(_):J=JSON.stringify(_);ae.push(`${Z}${J}${te}`)}),ae.push("}"),ae.join(`
`)}function v(R){let T=[],I="",H=/(\w+):(>=|<=|!=|>|<|=)?([^\s]+)/g,q=0,U;for(;U=H.exec(R);)I+=R.slice(q,U.index),q=H.lastIndex,T.push({key:U[1],op:U[2]||"=",val:U[3]});return I+=R.slice(q),{filters:T,free:I.trim().toLowerCase()}}function h(R,T){for(let I of T.filters){let H=(U,ae,ie)=>{let _=parseFloat(U),O=parseFloat(ae);return ie==="="?String(U)===String(ae):ie==="!="?String(U)!==String(ae):ie===">="?_>=O:ie==="<="?_<=O:ie===">"?_>O:ie==="<"?_<O:!0},q;if(I.key==="code")q=R.displayMessage;else if(I.key==="module")q=R.module;else if(I.key==="status")q=R._status;else if(I.key==="url")q=R._url;else if(I.key==="repo")q=R._repoId;else if(I.key==="level")q=R.level;else continue;if(q==null||!H(q,I.val,I.op))return!1}return!(T.free&&((R.displayMessage||"")+" "+(R.module||"")+" "+(R._url||"")+" "+JSON.stringify(R.raw||[])).toLowerCase().indexOf(T.free)===-1)}function k(){let R=v(e.query.search||"");e.parsedFilterCount=R.filters.length;let T=e.query.bucket,I=e.entries.filter(q=>T&&q._bucket!==T?!1:h(q,R)),H=e.query.group;if(H){let q=ie=>H==="module"?ie.module:ie.displayMessage||ie.message||"_",U=new Map;for(let ie of I){let _=q(ie);if(U.has(_)){let O=U.get(_);O.count++,O._related.push(ie),new Date(ie.ts)>new Date(O.ts)&&(O.ts=ie.ts,O._url=ie._url,O._status=ie._status),new Date(ie.ts)<new Date(O._firstSeen)&&(O._firstSeen=ie.ts)}else{let O=Object.assign({},ie);O._key=`${H}:${_}`,O._related=[ie],O._firstSeen=ie.ts,O._lastHourCount=0,O.count=1,U.set(_,O)}}let ae=Date.now()-3600*1e3;for(let ie of U.values())ie._lastHourCount=ie._related.filter(_=>new Date(_.ts).getTime()>=ae).length;I=Array.from(U.values())}else I=I.map((q,U)=>(q._key="row:"+U+":"+q.ts,q._related=[q],q._firstSeen=q.ts,q._lastHourCount=0,q.count=1,q));e.query.sort==="count"?I.sort((q,U)=>U.count-q.count||new Date(U.ts)-new Date(q.ts)):I.sort((q,U)=>new Date(U.ts)-new Date(q.ts)),e.visible=I}function m(R){let T=R?e.entries.length:0,I=R?e.pageSize:Math.max(e.pageSize,e.entries.length||e.pageSize);t.get("/api/admin/errors",{params:{offset:T,limit:I}}).then(H=>{let q=(H.data.entries||[]).map(u);e.entries=R?e.entries.concat(q):q,e.available=!!H.data.available,e.cap=H.data.max||e.cap,e.total=H.data.total||e.entries.length,k()},H=>console.error(H))}e.loadMore=()=>m(!0),e.canLoadMore=()=>e.entries.length<e.total;function E(){t.get("/api/admin/errors/stats").then(R=>{let T=R.data||{},I=T.prev24h?Math.round((T.last24h-T.prev24h)/T.prev24h*100):0;e.stats={last24h:T.last24h||0,prev24h:T.prev24h||0,delta:I,severity:T.severity||{error:0,warn:0,info:0},unique:T.unique||{error:0,warn:0,info:0},buckets:T.buckets||[],dropped:T.dropped||0}},R=>console.error(R))}function y(){m(),E()}e.barPx=(R,T)=>{let I=e.stats.buckets||[],H=0;for(let ie of I)H=Math.max(H,(ie.error||0)+(ie.warn||0)+(ie.info||0));if(!H)return 0;let q=(R.error||0)+(R.warn||0)+(R.info||0);if(!q)return 0;let U=Math.round(q/H*60),ae=R[T]||0;return Math.round(ae/q*U)},e.bucketTitle=R=>`${new Date(R.hour).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})} \xB7 ${R.error||0} err \xB7 ${R.warn||0} warn \xB7 ${R.info||0} info`,e.toggle=R=>{e.expanded[R._key]=!e.expanded[R._key]},e.setBucket=R=>{e.query.bucket=R},e.refreshNow=y,e.clearAll=()=>{confirm("Clear all captured errors?")&&t.delete("/api/admin/errors").then(y,R=>console.error(R))},e.exportCsv=()=>{let R=["ts","level","module","displayMessage","_status","_url","_repoId"],T=[R.join(",")];for(let U of e.visible)T.push(R.map(ae=>{let ie=U[ae]==null?"":String(U[ae]);return/[",\n]/.test(ie)?`"${ie.replace(/"/g,'""')}"`:ie}).join(","));let I=new Blob([T.join(`
`)],{type:"text/csv;charset=utf-8"}),H=URL.createObjectURL(I),q=document.createElement("a");q.href=H,q.download=`errors-${new Date().toISOString().slice(0,19)}.csv`,document.body.appendChild(q),q.click(),document.body.removeChild(q),URL.revokeObjectURL(H)};function w(R){e.copyHint=`${R} copied`,n.timeout(()=>{e.copyHint=""},1500)}e.copyJson=R=>{navigator.clipboard.writeText(R._detailJson).then(()=>w("JSON"))},e.copyCurl=R=>{if(!R._url)return;let I=`curl -X ${R._method||"GET"} '${window.location.origin}${R._url}'`;navigator.clipboard.writeText(I).then(()=>w("curl"))},y();let D=r(()=>{e.query.autoRefresh&&y()},15e3);e.on("dispose",()=>r.cancel(D)),e.watch("query.search",k),e.watch("query.bucket",k),e.watch("query.sort",k),e.watch("query.group",k)},ul=function(e,t,s,r){if(e.Math=Math,e.watch("user.status",()=>{e.user==null&&s.url("/")}),e.user==null){s.url("/");return}e.data=null,e.loading=!0,e.error=null,e.performance=null,e.performanceMinutes=15,e.performanceTab="routes",e.performanceError=null,e.formatMs=function(y){return y==null?"":y<1e3?y+" ms":+(y/1e3).toFixed(1)+" s"},e.latencyBound=function(y,w){return y.count?y[w]==null?"> 60 s":"\u2264 "+e.formatMs(y[w]):"No samples"},e.firstByteBound=function(y){return e.latencyBound({count:y.firstByteCount,p95UpperMs:y.firstByteP95UpperMs},"p95UpperMs")},e.sampleAge=function(y){return Math.max(0,Math.round((Date.now()-y.sampledAt)/1e3))},e.peakRss=function(y){return(e.performance.runtimeSeries||[]).filter(function(w){return w.instance===y.instance}).reduce(function(w,D){return Math.max(w,D.rss)},y.memory.rss)},e.performanceWarning=function(y){return e.sampleAge(y)>45||y.droppedBatches||y.droppedMetrics||y.sockets?.closeWait>0||y.eventLoop.p95Ms>100||y.memoryLimitBytes&&y.memory.rss>y.memoryLimitBytes*.8};var n=!1;e.loadPerformance=function(){var y=e.performanceMinutes;e.performance?.windowMinutes&&e.performance.windowMinutes!==y&&(e.performance=null),!n&&(n=!0,t.get("/api/admin/performance",{params:{minutes:y}}).then(function(w){y===e.performanceMinutes&&(e.performance=w.data,e.performanceError=w.data.available?null:"Performance monitoring is unavailable. Request history may be incomplete.")},function(){y===e.performanceMinutes&&(e.performanceError="Could not refresh performance monitoring. Displayed samples may be stale.")}).finally(function(){n=!1,y!==e.performanceMinutes&&e.loadPerformance()}))};function i(y){if(y==null)return"\u2014";for(var w=["B","KB","MB","GB","TB"],D=0,R=y;R>=1024&&D<w.length-1;)R/=1024,D++;return R.toFixed(D>0?1:0)+" "+w[D]}e.humanBytes=i;function a(y){if(!y)return"\u2014";var w=Math.floor(y/86400),D=Math.floor(y%86400/3600),R=Math.floor(y%3600/60);return w>0?w+"d "+(D<10?"0":"")+D+"h":D>0?D+"h "+(R<10?"0":"")+R+"m":R+"m"}e.humanDuration=a;function u(y){return y==null?"\u2014":y>=1e6?(y/1e6).toFixed(1)+"M":y>=1e3?(y/1e3).toFixed(1)+"K":String(y)}e.humanNum=u,e.queueTotal=function(y){return y?(y.waiting||0)+(y.active||0)+(y.delayed||0)+(y.failed||0):0},e.statusCount=function(y){if(!e.data||!e.data.repos)return 0;for(var w=e.data.repos.statusBreakdown||[],D=0;D<w.length;D++)if(w[D]._id===y)return w[D].count;return 0},e.barPct=function(y){var w=e.data&&e.data.repos?e.data.repos.total:0;if(!w)return 0;var D=[y];y==="expired"&&D.push("expiring"),y==="removed"&&D.push("removing"),y==="preparing"&&D.push("download");var R=0;return D.forEach(function(T){R+=e.statusCount(T)}),Math.max(.4,R/w*100)},e.errPct=function(y){if(!e.data||!e.data.errors)return 0;var w=Math.max(e.data.errors.severity.error,e.data.errors.severity.warn,e.data.errors.severity.info,1);return e.data.errors.severity[y]/w*100};function f(y){var w=y||[];return w.map(function(D,R){var T=w[R-1]||{},I=Object.assign({},D);return I.dailyRepositories=R?Math.max(0,(D.nbRepositories||0)-(T.nbRepositories||0)):0,I.dailyUsers=R?Math.max(0,(D.nbUsers||0)-(T.nbUsers||0)):0,I.dailyPageViews=R?Math.max(0,(D.nbPageViews||0)-(T.nbPageViews||0)):0,I})}function v(y){var w=y&&y.length?y[y.length-1]:{};return{repositories:w.dailyRepositories||0,users:w.dailyUsers||0,pageViews:w.dailyPageViews||0}}var h={},k={};e.historyBarH=function(y,w){return!y||!h[w]?0:Math.max(1,Math.round(y[w]/h[w]*140))},e.historyRangeH=function(y,w){if(!y||h[w]==null)return 0;var D=h[w]-k[w];return D?Math.round(8+(y[w]-k[w])/D*132):70},e.historyRange=function(y){return{min:k[y],max:h[y]}},e.historyLabel=function(y){if(!y||!y.date)return"";var w=new Date(y.date);return w.getUTCMonth()+1+"/"+w.getUTCDate()};function m(){e.loadPerformance(),t.get("/api/admin/overview").then(function(y){y.data.history=f(y.data.history),y.data.daily={today:v(y.data.history)},e.data=y.data,e.loading=!1,e.error=null,h={},k={},(y.data.history||[]).forEach(function(w){["dailyPageViews","dailyRepositories","dailyUsers","nbUsers"].forEach(function(D){(!h[D]||w[D]>h[D])&&(h[D]=w[D]),(k[D]==null||w[D]<k[D])&&(k[D]=w[D])})})},function(y){e.loading=!1,e.error=y.data&&y.data.error||"Failed to load overview"})}m();var E=r(m,3e4);e.on("dispose",function(){r.can Line truncated
anonymous_github`)])])])])]),p(" Limitations "),o("h4",{class:"faq-cat"},[o("svg",{class:"ui-icon mr-2","aria-hidden":"true"},[o("use",{href:"#ui-icon-warning"})]),b("Limitations ")]),o("div",{class:"panel-group",id:"faq-limitations",role:"tablist","aria-multiselectable":"true"},[o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingLimitation"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-limitations",href:"#limitation","aria-expanded":"false","aria-controls":"limitation"}," What are the limitations of Anonymous GitHub? ")])]),o("div",{id:"limitation",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingLimitation"},[o("div",{class:"panel-body p-3"},[o("ul",null,[o("li",null," Anonymous GitHub only anonymizes text-based files. Binary files (compiled executables, archives, etc.) are served as-is without anonymization. "),o("li",null," Files larger than 8 MB are not supported. "),o("li",null," Static site generators (such as Jekyll) used with GitHub Pages are not fully supported, although Markdown files are converted to HTML. "),o("li",null," The anonymization of terms within source code may change the behavior of the program (e.g., if a replaced term appears in a string literal or identifier). ")])])])])]),p(" Privacy & Security "),o("h4",{class:"faq-cat"},[o("svg",{class:"ui-icon mr-2","aria-hidden":"true"},[o("use",{href:"#ui-icon-shield"})]),b("Privacy & Security ")]),o("div",{class:"panel-group",id:"faq-privacy",role:"tablist","aria-multiselectable":"true"},[o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingData"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-privacy",href:"#data","aria-expanded":"false","aria-controls":"data"}," How is my data handled? ")])]),o("div",{id:"data",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingData"},[o("div",{class:"panel-body p-3"},[o("p",null," Data stored on Anonymous GitHub is never shared or used for any purpose beyond providing the anonymization service. When a repository is removed or expires, only its configuration is retained \u2014 this makes it easy to restore the repository if needed and ensures that no future repository reuses the same ID. ")])])]),o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingPermissions"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-privacy",href:"#permissions","aria-expanded":"false","aria-controls":"permissions"}," Why does GitHub say Anonymous GitHub asks for write access? ")])]),o("div",{id:"permissions",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingPermissions"},[o("div",{class:"panel-body p-3"},[o("p",null,[b("The GitHub App has read-only access to the repositories you choose. You can change repository access on your "),o("a",{href:"/connections"},"GitHub connections"),b(" page.")]),o("p",null,"Legacy GitHub OAuth includes write access to private repositories because GitHub's OAuth scopes do not offer a read-only option for them. Existing OAuth anonymizations and gists can still use this connection."),o("p",null,"Anonymous GitHub reads repository content. It never pushes, modifies, or deletes files on GitHub.")])])]),o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingViewer"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-privacy",href:"#viewer","aria-expanded":"false","aria-controls":"viewer"}," Can repository owners see who viewed their anonymized repository? ")])]),o("div",{id:"viewer",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingViewer"},[o("div",{class:"panel-body p-3"},[o("p",null," No. Only the total number of views is tracked as an incremental counter. It is not possible for the repository owner or for Anonymous GitHub to identify individual viewers. Reviewer anonymity is fully preserved. ")])])])]),p(" Self-Hosting "),o("h4",{class:"faq-cat"},[o("svg",{class:"ui-icon mr-2","aria-hidden":"true"},[o("use",{href:"#project-icon-storage"})]),b("Self-Hosting ")]),o("div",{class:"panel-group",id:"faq-hosting",role:"tablist","aria-multiselectable":"true"},[o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingDeploy"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-hosting",href:"#deploy","aria-expanded":"false","aria-controls":"deploy"}," Can I deploy my own instance? ")])]),o("div",{id:"deploy",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingDeploy"},[o("div",{class:"panel-body p-3"},[o("p",null,[b(" Yes. Anonymous Git Line truncated
`+JSON.stringify(t):""}`},[je.NAVIGATION_GUARD_REDIRECT]({from:e,to:t}){return`Redirected from "${e.fullPath}" to "${Yc(t)}" via a navigation guard.`},[je.NAVIGATION_ABORTED]({from:e,to:t}){return`Navigation aborted from "${e.fullPath}" to "${t.fullPath}" via a navigation guard.`},[je.NAVIGATION_CANCELLED]({from:e,to:t}){return`Navigation cancelled from "${e.fullPath}" to "${t.fullPath}" with a new navigation.`},[je.NAVIGATION_DUPLICATED]({from:e,to:t}){return`Avoided redundant navigation to current location: "${e.fullPath}".`}};function fo(e,t){return Ae(new Error,{type:e,[Sa]:!0},t)}function Ft(e,t){return e instanceof Error&&Sa in e&&(t==null||!!(e.type&t))}var Kc=["params","query","hash"];function Yc(e){if(typeof e=="string")return e;if(e.path!=null)return e.path;let t={};for(let n of Kc)n in e&&(t[n]=e[n]);return JSON.stringify(t,null,2)}function Na(e){let t={};if(e===""||e==="?")return t;let n=(e[0]==="?"?e.slice(1):e).split("&");for(let r=0;r<n.length;++r){let s=n[r].replace(pa," "),i=s.indexOf("="),a=Oo(i<0?s:s.slice(0,i)),u=i<0?null:Oo(s.slice(i+1));if(a in t){let f=t[a];kt(f)||(f=t[a]=[f]),f.push(u)}else t[a]=u}return t}function or(e){let t="";for(let n in e){let r=e[n];if(n=Lc(n),r==null){r!==void 0&&(t+=(t.length?"&":"")+n);continue}(kt(r)?r.map(s=>s&&Ys(s)):[r&&Ys(r)]).forEach(s=>{s!==void 0&&(t+=(t.length?"&":"")+n,s!=null&&(t+="="+s))})}return t}function Da(e){let t={};for(let n in e){let r=e[n];r!==void 0&&(t[n]=kt(r)?r.map(s=>s==null?null:""+s):r==null?r:""+r)}return t}var Ra=Symbol(""),nr=Symbol(""),ts=Symbol(""),os=Symbol(""),ns=Symbol("");function Po(){let e=[];function t(r){return e.push(r),()=>{let s=e.indexOf(r);s>-1&&e.splice(s,1)}}function n(){e=[]}return{add:t,list:()=>e.slice(),reset:n}}function Jt(e,t,n,r,s,i=a=>a()){let a=r&&(r.enterCallbacks[s]=r.enterCallbacks[s]||[]);return()=>new Promise((u,f)=>{let k=m=>{m===!1?f(fo(je.NAVIGATION_ABORTED,{from:n,to:t})):m instanceof Error?f(m):Wc(m)?f(fo(je.NAVIGATION_GUARD_REDIRECT,{from:t,to:m})):(a&&r.enterCallbacks[s]===a&&typeof m=="function"&&a.push(m),u())},h=i(()=>e.call(r&&r.instances[s],t,n,k)),w=Promise.resolve(h);e.length<3&&(w=w.then(k)),w.catch(m=>f(m))})}function ss(e,t,n,r,s=i=>i()){let i=[];for(let a of e)for(let u in a.components){let f=a.components[u];if(!(t!=="beforeRouteEnter"&&!a.instances[u]))if(ua(f)){let k=(f.__vccOpts||f)[t];k&&i.push(Jt(k,n,r,a,u,s))}else{let k=f();i.push(()=>k.then(h=>{if(!h)throw new Error(`Couldn't resolve component "${u}" at "${a.path}"`);let w=Rc(h)?h.default:h;a.mods[u]=h,a.components[u]=w;let m=(w.__vccOpts||w)[t];return m&&Jt(m,n,r,a,u,s)()}))}}return i}function Ta(e,t){let n=[],r=[],s=[],i=Math.max(t.matched.length,e.matched.length);for(let a=0;a<i;a++){let u=t.matched[a];u&&(e.matched.find(k=>po(k,u))?r.push(u):n.push(u));let f=e.matched[a];f&&(t.matched.find(k=>po(k,f))||s.push(f))}return[n,r,s]}var Jc=()=>location.protocol+"//"+location.host;function Fa(e,t){let{pathname:n,search:r,hash:s}=t,i=e.indexOf("#");if(i>-1){let a=s.includes(e.slice(i))?e.slice(i).length:1,u=s.slice(a);return u[0]!=="/"&&(u="/"+u),Zs(u,"")}return Zs(n,e)+r+s}function Qc(e,t,n,r){let s=[],i=[],a=null,u=({state:m})=>{let E=Fa(e,location),y=n.value,g=t.value,_=0;if(m){if(n.value=E,t.value=m,a&&a===y){a=null;return}_=g?m.position-g.position:0}else r(E);s.forEach(R=>{R(n.value,y,{delta:_,type:xn.pop,direction:_?_>0?es.forward:es.back:es.unknown})})};function f(){a=n.value}function k(m){s.push(m);let E=()=>{let y=s.indexOf(m);y>-1&&s.splice(y,1)};return i.push(E),E}function h(){if(document.visibilityState==="hidden"){let{history:m}=window;if(!m.state)return;m.replaceState(Ae({},m.state,{scroll:mn()}),"")}}function w(){for(let m of i)m();i=[],window.removeEventListener("popstate",u),window.removeEventListener("pagehide",h),document.removeEventListener("visibilitychange",h)}return window.addEventListener("popstate",u),window.addEventListener("pagehide",h),document.addEventListener("visibilitychange",h),{pauseListeners:f,listen:k,destroy:w}}function Aa(e,t,n,r=!1,s=!1){return{back:e,current:t,forward:n,replaced:r,position:window.history.length,scroll:s?mn():null}}function Xc(e){let{history:t,location:n}=window,r={value:Fa(e,n)},s={value:t.state};s.value||i(r.value,{back:null,current:r.value,forward:null,position:t.length-1,replaced:!0,scroll:null},!0);function i(f,k,h){let w=e.indexOf("#"),m=w>-1?(n.host&&document.querySelector("base")?e:e.slice(w))+f:Jc()+e+f;try{t[h?"replaceState":"pushState"](k,"",m),s.value=k}catch(E){console.error(E),n[h?"replace":"assign"](m)}}function a(f,k){i(f,Ae({},t.state,Aa(s.value.back,f,s.value.forward,!0),k,{position:s.value.position}),!0),r.value=f}function u(f,k){let h=Ae({},s.value,t.state,{forward:f,scroll:mn()});i(h.current,h,!0),i(f,Ae({},Aa(r.value,f,null),{position:h.position+1},k),!1),r.value=f}return{location:r,state:s,push:u,replace:a}}function za(e){e=wa(e);let t=Xc(e),n=Qc(e,t.state,t.location,t.replace);function r(i,a=!0){a||n.pauseListeners(),history.go(i)}let s=Ae({locatLine truncated
`)),e.options=Object.assign({},e.options,k.options),i.restore()})}a();let u=null;e.saveDefault=f=>{if(f&&f.preventDefault&&f.preventDefault(),e.saving)return;let k=i.checkpoint(),h={terms:e.terms.split(`
`).map(w=>w.trim()).filter(w=>w.length>0),options:e.options};e.saving=!0,e.error=null,t.post("/api/user/default",h).then(()=>{i.accept(k),e.saving=!1,e.message=e.unsavedChanges?null:"Saved",u&&r.cancel(u),u=r(()=>{e.message=null},2500)},w=>{e.saving=!1;let m=w&&w.data&&w.data.error,E="Unable to save your defaults. Please try again.";Promise.all([n("ERRORS."+m),n("ERRORS.unknown_error")]).then(([y,g])=>{e.error=m&&y!==g?y:E},()=>{e.error=E})})},e.deleteAccount=()=>{confirm("Delete your account? All your anonymized repositories, gists, and pull requests will be removed, and your personal data will be erased. This cannot be undone.")&&(e.deletingAccount=!0,t.delete("/api/user").then(()=>{window.location.href="/"},()=>{e.deletingAccount=!1,e.deleteError="Unable to delete the account. Please try again."}))}},el=function(e,t,n){e.repoId=null,e.repoUrl=null,e.claim=()=>{t.post("/api/repo/claim",{repoId:e.repoId,repoUrl:e.repoUrl}).then(r=>{n.url("/dashboard")},r=>{e.error=r.data,e.claimForm.repoUrl.setValidity("not_found",!1),e.claimForm.repoId.setValidity("not_found",!1)})}},tl=function(e,t,n,r,s){e.user&&!e.user.status&&n.url("/dashboard"),e.watch("user.status",()=>{e.user&&!e.user.status&&n.url("/dashboard")}),e.features=[{key:"anonymize",num:"01",eyebrow:"Anonymize",title:"Double-anonymous,",accent:"your rules.",text:"Choose what reviewers may see: links, images, PDFs, notebooks, GitHub Pages. Add your own terms, with regex if you need it, and pick the expiration date.",cta:"Start an anonymization",href:"/anonymize",url:"anonymous.4open.science/anonymize",img:"/imgs/anonymize.png",alt:"The anonymize form: source repository, terms to redact, options and a live README preview"},{key:"review",num:"02",eyebrow:"Review",title:"Reviewers browse",accent:"the real thing.",text:"Highlighted source code, rendered PDFs, images, and notebooks, in a familiar file explorer. GitHub Pages is also supported.",cta:"Open the example",href:"https://anonymous.4open.science/r/840c8c57-3c32-451e-bf12-0e20be300389/",target:"_self",url:"anonymous.4open.science/r/840c8c57-\u2026",img:"/imgs/explorer.png",alt:"The repository explorer with a file tree and a rendered README"},{key:"manage",num:"03",eyebrow:"Manage",title:"One dashboard,",accent:"until the decision.",text:"Monitor views, edit configuration, remove or update your repository. Program chairs can group submissions under a conference with one shared expiry.",cta:"Open the dashboard",href:"/dashboard",needsUser:!0,url:"anonymous.4open.science/dashboard",img:"/imgs/dashboard.png",alt:"The dashboard listing anonymized repositories with status, views and expiry"}],e.feature=e.features[0].key,e.selectFeature=function(u){e.feature=u},e.featureHref=function(u){return u.needsUser&&!e.user?"/signin":u.href},e.featureTarget=function(u){return u.needsUser&&!e.user?"_self":u.target||void 0},e.featureKeydown=function(u,f){let k={ArrowDown:1,ArrowRight:1,ArrowUp:-1,ArrowLeft:-1,Home:"first",End:"last"}[u.key];if(k===void 0)return;u.preventDefault();let h=e.features.length,w=k==="first"?0:k==="last"?h-1:(f+k+h)%h;e.feature=e.features[w].key,s(()=>{let m=r.document.getElementById("feature-tab-"+e.feature);m&&m.focus()})},e.cards=[{key:"repositories",total:0,label:"repositories anonymized"},{key:"users",total:0,label:"researchers"},{key:"pageViews",total:0,label:"page views"},{key:"pullRequests",total:0,label:"pull requests"}];function i(){t.get("/api/stat/").then(u=>{e.stat=u.data,e.cards[0].total=u.data.nbRepositories,e.cards[1].total=u.data.nbUsers,e.cards[2].total=u.data.nbPageViews,e.cards[3].total=u.data.nbPullRequests})}i();function a(u){let f={series:u,bars:[],viewW:100,deltaToday:0,pctChange:0,pctAbs:0,isUp:!0};if(!u||u.length<2)return f;let k=new Array(u.length-1);for(let g=1;g<u.length;g++)k[g-1]=u[g]-u[g-1];let h=k.length,w=Math.max.apply(null,k),m=Math.min.apply(null,k),E=Math.min(0,m),y=w-E||1;f.viewW=h*2,f.bars=new Array(h);for(let g=0;g<h;g++){let _=(k[g]-E)/y,R=Math.max(1.5,_*34);f.bars[g]={x:(g*2+.25).toFixed(2),y:(36-R).toFixed(2),w:"1.5",h:R.toFixed(2)}}if(f.deltaToday=k[h-1],h>=2){let g=k[h-2];g&&(f.pctChange=(f.deltaToday-g)/g*100)}return f.pctAbs=Math.round(Math.abs(f.pctChange)),f.isUp=f.pctChange>=0,f}e.history={repositories:a([]),users:a([]),pageViews:a([]),pullRequests:a([])},t.get("/api/stat/history?days=60").then(u=>{let f=u.data||[];e.history={repositories:a(f.map(k=>k.nbRepositories||0)),users:a(f.map(k=>k.nbUsers||0)),pageViews:a(f.map(k=>k.nbPageViews||0)),pullRequests:a(f.map(k=>k.nbPullRequests||0))}})},ol=function(e,t,n,r,s,i){let a=ct();e.on("routeLeave",function(){$('[data-toggle="tooltip"]').tooltip("dispose")}),e.watch("user.status",()=>{e.user==null&&n.url("/")}),e.user==null&&n.url("/"),a.timeout(()=>{$('[data-toggle="tooltip"]').tooltip()},250),e.quotaExpanded=!1,e.closeQuota=()=>{e.quotaExpanded=!1,nt(()=>document.querySelector(".dashboard-quota > summary")?.focus())},Xt()(document,"click",S=>{e.quotaExpanded&&!S.target.closest?.(".dashboard-quota")& Line truncated
`)),e.options=Object.assign({},e.options,B.options),e.options.expirationDate=B.options&&B.options.expirationDate?new Date(B.options.expirationDate):T(),!r.repoId&&!r.pullRequestId&&!r.gistId&&!e.anonymize?.terms?.dirty&&(e.terms=e.defaultTerms),C&&C()})}function M(C,V,B){e.anonymize&&e.anonymize[C]&&e.anonymize[C].setValidity(V,B)}function se(C){try{let V=parseGithubUrl(C);if(V&&V.owner&&V.repo)return V.owner+"/"+V.repo}catch{}return null}e.reconnectingSource=!1,e.reconnectRepositoryId=void 0,e.reconnectSource=async()=>{if(confirm("Reconnect to the repository currently at this GitHub URL? Review its branch and commit before saving. Saving will replace the published snapshot.")){e.reconnectingSource=!0,e.reconnectRepositoryId=void 0,e.source.commit="",e.source.branch="",e.readme="",e.branches=[];try{await Y()}catch{}}};function oe(){return e.reconnectingSource||!e.isUpdate||!e._originalRepositoryID?void 0:se(e.sourceUrl)===e._originalFullName?e._originalRepositoryID:void 0}async function S(){e._preservingDraft=!0;try{await e.urlSelected(!0)}finally{e._preservingDraft=!1}}async function O(){let C;try{C=JSON.parse(sessionStorage.getItem("github-access-draft")||"null")}catch{return!1}if(!C||C.path!==s.path()||Date.now()-C.savedAt>=30*6e4)return _.restore()?(e.sourceUrl&&await S(),!0):!1;_.restore();for(let V of["sourceUrl","terms","repoId","pullRequestId","gistId","source","options","conference","githubConnection"])Object.prototype.hasOwnProperty.call(C.draft,V)&&(e[V]=C.draft[V]);return e.options.expirationDate&&(e.options.expirationDate=new Date(e.options.expirationDate)),await S(),sessionStorage.removeItem("github-access-draft"),!0}P(()=>{!r.repoId&&!r.pullRequestId&&!r.gistId&&a(O,0),r.repoId&&r.repoId!=""&&(e.isUpdate=!0,e.detectedType="repo",e.repoId=r.repoId,t.get("/api/repo/"+e.repoId).then(async C=>{e.githubConnection=C.data.connection||"oauth",e.sourceUrl="https://github.com/"+C.data.source.fullName,e._originalFullName=C.data.source.fullName,e.terms=C.data.options.terms.filter(V=>V).join(`
`),e.source=C.data.source,e.role=C.data.role||"owner",e.coauthors=C.data.coauthors||[],e._originalBranch=C.data.source.branch,e.options=Object.assign({},e.options,C.data.options),e.conference=C.data.conference,e._originalConference=C.data.conference,e.repositoryID=C.data.source.repositoryID,e._originalRepositoryID=C.data.source.repositoryID,C.data.options.expirationDate&&(e.options.expirationDate=new Date(C.data.options.expirationDate)),y=g(parseGithubUrl(e.sourceUrl)),!await O()&&(await Promise.all([Y(),Z()]),ce())},()=>{s.url("/404")})),r.pullRequestId&&r.pullRequestId!=""&&(e.isUpdate=!0,e.detectedType="pr",e.pullRequestId=r.pullRequestId,t.get("/api/pr/"+e.pullRequestId).then(async C=>{if(e.githubConnection=C.data.connection||"oauth",e.sourceUrl="https://github.com/"+C.data.source.repositoryFullName+"/pull/"+C.data.source.pullRequestId,e.terms=C.data.options.terms.filter(V=>V).join(`
`),e.source=C.data.source,e.options=Object.assign({},e.options,C.data.options),e.conference=C.data.conference,e._originalConference=C.data.conference,C.data.options.expirationDate&&(e.options.expirationDate=new Date(C.data.options.expirationDate)),y=g(parseGithubUrl(e.sourceUrl)),!await O())try{await fe()}catch{}},()=>{s.url("/404")})),r.gistId&&r.gistId!=""&&(e.isUpdate=!0,e.detectedType="gist",e.gistId=r.gistId,t.get("/api/gist/"+e.gistId).then(async C=>{e.sourceUrl="https://gist.github.com/"+C.data.source.gistId,e.terms=C.data.options.terms.filter(V=>V).join(`
`),e.source=C.data.source,e.options=Object.assign({},e.options,C.data.options),e.conference=C.data.conference,e._originalConference=C.data.conference,C.data.options.expirationDate&&(e.options.expirationDate=new Date(C.data.options.expirationDate)),y=g(parseGithubUrl(e.sourceUrl)),!await O()&&await Ue()},()=>{s.url("/404")}))}),t.get("/github/connections").then(C=>{e.githubConnections=C.data,!r.repoId&&!r.pullRequestId&&!r.gistId&&e.githubConnection===void 0&&C.data.appEnabled&&C.data.appConnected&&(e.githubConnection="github-app",e.sourceUrl&&e.workspaceOpen&&S())}).catch(()=>{}),e.urlSelected=async(C=!1)=>{let V=++f,B;try{B=parseGithubUrl(e.sourceUrl.trim())}catch{e.sourceLoading=!1,re.cancel(),_e.cancel(),Pe.cancel(),e.previewStatus="idle",e.sourceUrlError=e.sourceUrl?"Please provide a valid GitHub URL.":"",M("sourceUrl","github",!1);return}let L=g(B),v=C||y===L;y=L,e.sourceUrlError="",M("sourceUrl","github",!0);let N=document.activeElement?.id==="sourceUrl-landing";e.workspaceOpen=!0,N&&a(()=>document.getElementById("sourceUrl")?.focus(),0),e.reconnectingSource=!1,e.reconnectRepositoryId=void 0,!v&&!e.isUpdate&&(e.repoId="",e.pullRequestId="",e.gistId=""),e.details=null,e.branches=[],v||(e.source={type:"GitHubStream",branch:"",commit:""}),re.cancel(),_e.cancel(),Pe.cancel(),le.clear(),Re.clear(),e.previewStatus="idle",e.anonymize_readme="",e.readme="",e.html_readme="",e.detectedType=null,e.gistOAuthRequired=!1,e.gistAppRequired=!1,e._preservingDraft=v;try{B.gistId&&!B.repo?(e.detectedType="gist",e.source={gistId:B.gistId},await Ue()):B.pullRequestId?(e.detectedType="pr",e.source={repositoryFullName:B.owner+"/"+B.repo,pullRequestId:B.pullRequestId},await fe()):(e.detectedType="repo",await Promise.all([Y(),Z()]),ce())}catch{}finally{V===f&&(e._preservingDraft=!1)}$('[data-toggle="tooltip"]').tooltip()},$('[data-toggle="tooltip"]').tooltip(),e.watch("source.branch",async()=>{if(e.detectedType!=="repo")return;let C=e.branches.filter(B=>B.name==e.source.branch)[0];if(!C)return;!(!e.reconnectingSource&&e.isUpdate&&e._originalBranch===e.source.branch&&e.source.commit)&&!(e._preservingDraft&&e.source.commit)&&(e.source.commit=C.commit),e.readme=C.readme,await Z(),ce()}),e.getBranches=async C=>{let V=parseGithubUrl(e.sourceUrl),B=m();try{let L=await t.get(`/api/repo/${V.owner}/${V.repo}/branches`,{params:{reconnect:e.reconnectingSource?"1":void 0,anonymizedRepoId:e.isUpdate&&r.repoId&&se(e.sourceUrl)===e._originalFullName?r.repoId:void 0,connection:e.githubConnection,force:C===!0||e.reconnectingSource?"1":"0",repositoryID:oe()}});if(!w(B))return;e.branches=L.data,e.sourceUnreachable=!1,e.source.branch||(e.source.branch=e.details.defaultBranch);let v=e.branches.filter(N=>N.name==e.source.branch);v.length>0&&(!(!e.reconnectingSource&&!C&&e.isUpdate&&!e.options.update&&e._originalBranch===e.source.branch&&e.source.commit)&&!(e._preservingDraft&&e.source.commit)&&(e.source.commit=v[0].commit),e.readme=v[0].readme,await Z(C))}catch(L){if(!w(B))return;e.branches=[],e.sourceUnreachable=L&&(L.status===404||L.data&&L.data.error==="repo_not_found");let v=L&&L.data&&L.data.error||(L&&L.status===404?"repo_not_found":"unknown_error");i("ERRORS."+v).then(N=>{e.toasts=e.toasts||[],e.addToast({title:"Error",date:new Date,body:N}),e.error=N},console.error),typeof M=="function"&&M("sourceUrl","missing",!1)}finally{E(B)}};async function Y(){let C=parseGithubUrl(e.sourceUrl),V=m();try{z();let B=await t.get(`/api/repo/${C.owner}/${C.repo}/`,{params:{reconnect:e.reconnectingSource?"1":void 0,anonymizedRepoId:e.isUpdate&&r.repoId&&se(e.sourceUrl)===e._originalFullName?r.repoId:void 0,connection:e.githubConnection,repositoryID:oe(),force:"1"}});if(!w(V))return;e.details=B.data,e.reconnectingSource&&(e.reconnectRepositoryId=e.details.externalId),e.details&&e.details.id&&(e.repositoryID=e.details.id),e.repoId||(e.repoId=e.details.repo+"-"+generateRandomId(4)),await e.getBranches(e.reconnectingSource)}catch(B){if(!w(V))return;throw B.data&&(i("ERRORS."+B.data.error).then(L=>{e.addToast({title:"Error",date:new Date,body:L}),e.error=L},console.error),Q(B.data.error)),M("sourceUrl","missing",!1),B}finally{E(V)}}async function Z(C){if(e.readme&&!C)return e.readme;let V=parseGithubUrl(e.sourceUrl),B=m();try{let L=await t.get(`/api/repo/${V.owner}/${V.repo}/readme`,{params:{reconnect:e.reconnectingSource?"1":void 0,anonymizedRepoId:e.isUpdate&&r.repoId&&se(e.sourceUrl)===e._originalFullName?r.repoId:void 0,connection:e.githubConnection,force:C===!0?"1":"0",branch:e.source.branch,repositoryID:oe()}});w(B,!0)&&(e.readme=L.data)}catch{w(B,!0)&&(e.readme="")}finally{E(B)}}function te(){let C={terms:e.terms?e.terms.split(`
`):[],image:!!e.options.image,link:!!e.options.link,repoId:e.repoId};e.source&&e.source.branch&&(C.branchName=e.source.branch);try{let V=parseGithubUrl(e.sourceUrl);C.repoName=`${V.owner}/${V.repo}`}catch{}return C}function J(C,V,B){let L=null,v=0,N=()=>{if(e.detectedType!==C)return;L&&a.cancel(L);let q=++v;e.previewStatus="loading",L=a(()=>{L=null;let H=V();if(!H){e.previewStatus="idle";return}t.post("/api/anonymize-preview",H).then(j=>{q===v&&(B(j.data,H),e.previewStatus="ready")}).catch(()=>{q===v&&(e.previewStatus="error")})},200)};return N.cancel=()=>{v++,L&&a.cancel(L),L=null},e.on("dispose",N.cancel),N}e.retryPreview=()=>{e.detectedType==="repo"&&re(),e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()};let re=J("repo",()=>e.readme?{content:e.readme,options:te()}:null,C=>{if(typeof C?.content!="string")throw Error("Invalid preview response");e.anonymize_readme=C.content;let V="";try{let L=parseGithubUrl(e.sourceUrl),v=e.source.branch||e.details&&e.details.defaultBranch||"main";V=`https://github.com/${L.owner}/${L.repo}/raw/${v}/`}catch{}let B=renderMD(e.anonymize_readme,V);e.html_readme=B,a(Prism.highlightAll,150)});function ce(){!e.anonymize||!e.anonymize.terms||(e.termsRegexWarning=!!e.terms&&!!e.terms.match(/[-[\]{}()*+?.,\\^$|#]/g),re())}async function fe(){let C=parseGithubUrl(e.sourceUrl),V=m();try{z();let B=await t.get(`/api/pr/${C.owner}/${C.repo}/${C.pullRequestId}`,{params:{connection:e.githubConnection}});if(!w(V))return;e.details=B.data,e.pullRequestId||(e.pullRequestId=C.repo+"-PR"+C.pullRequestId+"-"+generateRandomId(4))}catch(B){if(!w(V))return;throw B.data&&(i("ERRORS."+B.data.error).then(L=>{e.addToast({title:"Error",date:new Date,body:L}),e.error=L},console.error),Q(B.data.error)),M("sourceUrl","missing",!1),B}finally{E(V)}}let le=ze(new Map);function Oe(){let C=new Set,V=e.details&&e.details.pullRequest;if(!V)return C;typeof V.title=="string"&&C.add(V.title),typeof V.body=="string"&&C.add(V.body),typeof V.diff=="string"&&C.add(V.diff);let B=V.comments||[];for(let L of B)typeof L.author=="string"&&C.add(L.author),typeof L.body=="string"&&C.add(L.body);return C}let _e=J("pr",()=>{let C=Oe(),V=Array.from(C);return V.length===0?null:{contents:V,options:te()}},(C,V)=>{if(!Array.isArray(C?.contents)||C.contents.length!==V.contents.length||C.contents.some(v=>typeof v!="string"))throw Error("Invalid preview response");let B=V.contents,L=new Map;for(let v=0;v<B.length&&v<C.contents.length;v++)L.set(B[v],C.contents[v]);le.clear(),L.forEach((v,N)=>le.set(N,v))});e.anonymizePrContent=function(C){return C&&(le.has(C)?le.get(C):"")};async function Ue(){let C=parseGithubUrl(e.sourceUrl),V=m();try{z(),e.gistOAuthRequired=!1,e.gistAppRequired=!1;let B=await t.get(`/api/gist/source/${C.gistId}`);if(!w(V))return;e.details=B.data,e.gistId||(e.gistId="gist-"+C.gistId.substring(0,6)+"-"+generateRandomId(4))}catch(B){if(!w(V))return;if(B.data?.error==="github_app_reconnect_required"){e.gistAppRequired=!0,M("sourceUrl","missing",!1);return}if(B.data?.error==="github_oauth_required"){e.gistOAuthRequired=!0,M("sourceUrl","missing",!1);return}throw B.data&&(i("ERRORS."+B.data.error).then(L=>{e.addToast({title:"Error",date:new Date,body:L}),e.error=L},console.error),Q(B.data.error)),M("sourceUrl","missing",!1),B}finally{E(V)}}let Re=ze(new Map);function Me(){let C=new Set,V=e.details&&e.details.gist;if(!V)return C;typeof V.description=="string"&&C.add(V.description),typeof V.ownerLogin=="string"&&C.add(V.ownerLogin);let B=V.files||[];for(let v of B)typeof v.filename=="string"&&C.add(v.filename),typeof v.content=="string"&&C.add(v.content);let L=V.comments||[];for(let v of L)typeof v.author=="string"&&C.add(v.author),typeof v.body=="string"&&C.add(v.body);return C}let Pe=J("gist",()=>{let C=Me(),V=Array.from(C);return V.length===0?null:{contents:V,options:te()}},(C,V)=>{if(!Array.isArray(C?.contents)||C.contents.length!==V.contents.length||C.contents.some(v=>typeof v!="string"))throw Error("Invalid preview response");let B=V.contents,L=new Map;for(let v=0;v<B.length&&v<C.contents.length;v++)L.set(B[v],C.contents[v]);Re.clear(),L.forEach((v,N)=>Re.set(N,v)),He()});e.anonymizeGistContent=function(C){return C&&(Re.has(C)?Re.get(C):"")},e.previewGistFiles=[];function He(){let C=e.details&&e.details.gist&&e.details.gist.files||[];e.previewGistFiles=C.map(V=>({filename:e.anonymizeGistContent(V.filename),content:e.anonymizeGistContent(V.content),language:V.language}))}e.watch("details.gist.files",He,!0),e.watch("terms",He);function Ee(){let C=e.conference;if(e.conference_data=null,!C)return;let V=e.isUpdate&&C===e._originalConference;t.get("/api/conferences/"+C).then(B=>{e.conference===C&&(e.conference_data=B.data,e.conference_data.startDate=new Date(e.conference_data.startDate),e.conference_data.endDate=new Date(e.conference_data.endDate),!V&&(e.options.expirationDate=new Date(e.conference_data.endDate),e.options.expirationMode="remove",e.options.update=e.conference_data.options.update,e.options.image=e.confe Line truncated
`).filter(N=>N),connection:e.githubConnection,fullName:`${B.owner}/${B.repo}`,repository:e.sourceUrl,reconnectRepositoryId:e.reconnectRepositoryId,options:e.options,source:e.source,conference:e.conference};e.details&&(L.options.pageSource=e.details.pageSource),z();let v=e.isUpdate?"/api/repo/"+e.repoId:"/api/repo/";t.post(v,L,{headers:{"Content-Type":"application/json"}}).then(()=>{_.clear(),window.location.href="/status/"+e.repoId},N=>{N.data&&(i("ERRORS."+N.data.error).then(q=>{e.error=q},console.error),Q(N.data.error))}).finally(()=>{V.disabled=!1})},e.anonymizeGist=C=>{if(e.sourceLoading){e.error="Wait for the source to finish loading before saving.";return}if(ne())return;if(e.anonymize?.invalid||e.sourceUrlError){e.error="Please correct the highlighted fields before saving.";return}let V=C.currentTarget||C.target.closest?.("button")||C.target;V.disabled=!0;let B=parseGithubUrl(e.sourceUrl),L={gistId:e.gistId,terms:e.terms.trim().split(`
`).filter(N=>N),source:{gistId:B.gistId},options:e.options,conference:e.conference};z();let v=e.isUpdate?"/api/gist/"+e.gistId:"/api/gist/";t.post(v,L,{headers:{"Content-Type":"application/json"}}).then(()=>{_.clear(),window.location.href="/gist/"+e.gistId},N=>{N.data&&(i("ERRORS."+N.data.error).then(q=>{e.error=q},console.error),Q(N.data.error))}).finally(()=>{V.disabled=!1})},e.anonymizePullRequest=C=>{if(e.sourceLoading){e.error="Wait for the source to finish loading before saving.";return}if(ne())return;if(e.anonymize?.invalid||e.sourceUrlError){e.error="Please correct the highlighted fields before saving.";return}let V=C.currentTarget||C.target.closest?.("button")||C.target;V.disabled=!0;let B=parseGithubUrl(e.sourceUrl),L={pullRequestId:e.pullRequestId,connection:e.githubConnection,terms:e.terms.trim().split(`
`).filter(N=>N),source:{repositoryFullName:`${B.owner}/${B.repo}`,pullRequestId:B.pullRequestId},options:e.options,conference:e.conference};z();let v=e.isUpdate?"/api/pr/"+e.pullRequestId:"/api/pr/";t.post(v,L,{headers:{"Content-Type":"application/json"}}).then(()=>{_.clear(),window.location.href="/pr/"+e.pullRequestId},N=>{N.data&&(i("ERRORS."+N.data.error).then(q=>{e.error=q},console.error),Q(N.data.error))}).finally(()=>{V.disabled=!1})},e.watch("conference",()=>{Ee()}),e.watch("terms",()=>{e.detectedType==="repo"&&ce(),e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()}),e.watch("options.image",()=>{e.detectedType==="repo"&&ce(),e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()}),e.watch("options.link",()=>{e.detectedType==="repo"&&ce(),e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()}),e.watch("details",()=>{e.detectedType==="pr"&&_e(),e.detectedType==="gist"&&Pe()},!0)},ar=function(e,t,n,r,s,i){let a=ct();window.Prism?.hooks&&!window.Prism.redactionHook&&(window.Prism.hooks.add("complete",O=>Ya(O.element)),window.Prism.redactionHook=!0);let u=Xt();e.on("dark-mode",(O,Y)=>{e.aceOption&&(Y?e.aceOption.theme="nord_dark":e.aceOption.theme="chrome")});let f=0,k=!1;e.on("dispose",()=>{k=!0,f++,h&&h.resolve()}),e.files=[],e.isMac=/Mac|iPhone|iPad|iPod/.test(navigator.platform||navigator.userAgent),e.fileSearchQuery="",e.fileSearchResults=null,e.fileSearchLoading=!1,u(document,"keydown",function(O){if((O.metaKey||O.ctrlKey)&&O.key==="k"){O.preventDefault();var Y=document.querySelector(".tree-search-input");Y&&(Y.focus(),Y.select())}});var h=null;e.onFileSearchChange=function(){h&&(h.resolve(),h=null);let O=e.fileSearchQuery;if(!O||O.length<2){e.fileSearchResults=null,e.fileSearchLoading=!1;return}e.fileSearchLoading=!0;let Y=i.defer();h=Y,t.get(`/api/repo/${e.repoId}/files/search?q=${encodeURIComponent(O)}`,{timeout:Y.promise}).then(function(Z){if(!(k||h!==Y)){h=null,e.fileSearchLoading=!1;var te={};e.files.forEach(function(z){te[(z.path||"")+"/"+z.name]=!0});for(var J=[],re={},ce=0;ce<Z.data.length;ce++){var fe=Z.data[ce];if(fe.path)for(var le=fe.path.split("/"),Oe="",_e=0;_e<le.length;_e++){var Ue=Oe;Oe=Oe?Oe+"/"+le[_e]:le[_e];var Re=Ue+"/"+le[_e];!te[Re]&&!re[Re]&&(re[Re]=!0,J.push({name:le[_e],path:Ue}))}}J.sort(function(z,ne){return(z.path||"").split("/").length-(ne.path||"").split("/").length}),J.length>0&&e.files.push.apply(e.files,J);for(var Me=[],Pe=0;Pe<Z.data.length;Pe++){var He=Z.data[Pe],Ee=(He.path||"")+"/"+He.name;!te[Ee]&&He.size!=null&&(Me.push(He),te[Ee]=!0)}Me.length>0&&e.files.push.apply(e.files,Me),e.fileSearchResults=Z.data}},function(){!k&&h===Y&&(h=null,e.fileSearchLoading=!1,e.fileSearchResults=[])})};let w={yml:"yaml",txt:"text",py:"python",js:"javascript",ts:"typescript"},m=["license","txt"],E=["png","jpg","jpeg","gif","svg","ico","bmp","tiff","tif","webp","avif","heif","heic"],y=["wav","mp3","ogg","wma","flac","aac","m4a"],g=["mp4","avi","webm","mov","mpg","mpeg","mkv","flv","wmv","3gp","3g2","m4v","f4v","f4p","f4a","f4b"];e.on("routeUpdate",function(O,Y){if(e.repoId!=r.repoId)return S();if((r.path||"")!=e.filePath){e.filePath=r.path||"",e.paths=e.filePath.split("/").filter(Z=>Z&&Z.trim().length>0),oe();for(let Z=0;Z<e.paths.length-1;Z++){let te=Z>0?e.paths.slice(0,Z).join("/"):"";e.files.some(re=>re.path===te)||e.getFiles(te)}}});function _(){if(e.paths[0]!="")return;let O=["readme.md","readme.txt","readme.org","readme.1st","readme"],Y={};for(let te of e.files)te.name.toLowerCase().indexOf("readme")>-1&&(Y[te.name.toLowerCase()]=te.name);let Z=null;for(let te of O)if(Y[te]){Z=te;break}if(!Z&&Object.keys(Y).length>0&&(Z=Object.keys(Y)[0]),Z){let te=n.url();te[te.length-1]!="/"&&(te+="/"),n.url(te+encodePathForUrl(Y[Z]))}}e.fileCounts=null,e.getFiles=function(O){let Y=e.repoId;return t.get(`/api/repo/${e.repoId}/files/?path=${encodeURIComponent(O)}&v=${e.options.lastUpdateDate}`).then(function(Z){if(k||Y!==e.repoId)return[];let te=O||"";return e.files=e.files.filter(J=>J.path!==te),e.files.push(...Z.data),Z.data},function(Z){if(k||Y!==e.repoId)return[];e.type="error",e.content=Z&&Z.data&&Z.data.error||"unknown_error",e.files=[]})};function R(){let O=e.repoId;t.get(`/api/repo/${e.repoId}/files/counts`).then(function(Y){k||O!==e.repoId||(e.fileCounts=Y.data)},function(){e.fileCounts={}})}function T(){return e.files.filter(O=>O.name==e.paths[e.paths.length-1]&&O.path==e.paths.slice(0,e.paths.length-1).join("/"))[0]}var I=null;e.on("dispose",function(){I&&a.interval.cancel(I)});function F(O){if(k)return;let Y=e.repoId;t.get(`/api/repo/${e.repoId}/options`).then(Z=>{if(!(k||Y!==e.repoId)){if(e.options=Z.data,e.options.url){window.location=e.options.url;return}O&&O(Z.data)}},Z=>{if(!(k||Y!==e.repoId)){var te=Z.data||{};if(te.error==="rate_limited"&&te.resetAt){let re=function(){var ce=Math.max(0,Math.ceil((e.rateLimitResetAt-Date.now())/1e3));if(ce<=0)e.rateLimitCountdown="",e.rateLimitResetAt=0,I&&(a.interval.cancel(I),I=null),F(O);else{var fe=Math.floor(ce/60),l Line truncated
`+g.join(`
`)],{type:"text/csv"}),R=document.createElement("a");R.href=URL.createObjectURL(_),R.download=r.username+"-repositories.csv",R.click()},e.showStatusMessage=m=>{let E=m.statusMessage||"(no message)";window.prompt(`Status message for ${m.repoId} (${m.status}):`,E)},e.fetchGithubInfo=m=>{let E=window.open("","_blank");E&&E.document.write("<pre>Loading GitHub info for "+m.repoId+"...</pre>"),t.get("/api/admin/repos/"+m.repoId+"/github").then(y=>{E&&(E.document.open(),E.document.write('<pre style="font:13px monospace;padding:16px;white-space:pre-wrap">'+JSON.stringify(y.data,null,2).replace(/[<>]/g,g=>g==="<"?"&lt;":"&gt;")+"</pre>"),E.document.close())},y=>{let g=y&&y.data?JSON.stringify(y.data,null,2):String(y);E&&(E.document.body.innerHTML='<pre style="color:#B42318;padding:16px">'+g+"</pre>")})};function f(m){t.get("/api/admin/users/"+m+"/repos",{}).then(E=>{e.repositories=E.data},E=>{console.error(E)})}function k(m){t.get("/api/admin/users/"+m,{}).then(E=>{e.userInfo=E.data},E=>{console.error(E)})}k(r.username),f(r.username),e.banUser=()=>{confirm(`Ban user ${r.username}?`)&&t.post(`/api/admin/users/${r.username}/ban`).then(()=>k(r.username),m=>console.error(m))},e.activateUser=()=>{t.post(`/api/admin/users/${r.username}/activate`).then(()=>k(r.username),m=>console.error(m))},e.promoteUser=()=>{confirm(`Promote ${r.username} to admin?`)&&t.post(`/api/admin/users/${r.username}/promote`).then(()=>k(r.username),m=>console.error(m))},e.demoteUser=()=>{confirm(`Remove admin privileges from ${r.username}?`)&&t.post(`/api/admin/users/${r.username}/demote`).then(()=>k(r.username),m=>console.error(m))},e.tokens=[],e.tokenForm={name:"",plaintext:null};function h(){t.get("/api/admin/tokens").then(m=>{e.tokens=m.data||[]},m=>{m.status!==401&&m.status!==403&&console.error(m)})}h(),e.createToken=()=>{e.tokenForm.name&&t.post("/api/admin/tokens",{name:e.tokenForm.name}).then(m=>{e.tokenForm.plaintext=m.data.token,e.tokenForm.name="",h()},m=>console.error(m))},e.revokeToken=m=>{confirm(`Revoke token "${m.name}"?`)&&t.delete("/api/admin/tokens/"+m.id).then(()=>h(),E=>console.error(E))},e.removeCache=m=>{confirm("Remove cached files for "+m.repoId+"?")&&t.delete("/api/admin/repos/"+m.repoId).then(()=>f(r.username),E=>console.error(E))},e.removeRepository=m=>{confirm("Remove repository "+m.repoId+"?")&&t.delete("/api/repo/"+m.repoId+"/").then(()=>f(r.username),E=>console.error(E))},e.updateRepository=m=>{let E=ze({title:`Refreshing ${m.repoId}...`,date:new Date,body:`The repository ${m.repoId} is going to be refreshed.`});e.toasts.push(E),t.post(`/api/repo/${m.repoId}/refresh`).then(y=>{y.data.status=="ready"?E.title=`${m.repoId} is refreshed.`:E.title=`Refreshing of ${m.repoId}.`},y=>{E.title=`Error during the refresh of ${m.repoId}.`,E.body=y.body})},e.getGitHubRepositories=m=>{t.get(`/api/user/${e.userInfo.username}/all_repositories`,{params:{force:"1"}}).then(E=>{e.userInfo.repositories=E.data})};let w=null;e.watch("query",()=>{s.timeout.cancel(w),w=s.timeout(()=>{f(r.username)},500)},!0)},fl=function(e,t,n){let r=ct(),s=Xt();e.Math=Math,e.watch("user.status",()=>{e.user==null&&n.url("/")}),e.user==null&&n.url("/"),e.conferences=[],e.total=-1,e.totalPage=0,e.statusCounts=[];let i=y=>{if(y.key==="/"&&!["INPUT","TEXTAREA","SELECT"].includes(document.activeElement?.tagName)){y.preventDefault();let g=document.querySelector('.admin-filter-toolbar input[type="search"]');g&&g.focus()}};s(document,"keydown",i),e.on("dispose",()=>document.removeEventListener("keydown",i)),e.clearFilter=y=>{y==="dateRange"?(e.query.dateFrom="",e.query.dateTo=""):e.query[y]="",e.query.page=1},e.chips=[];let a=()=>{let y=[];(e.query.dateFrom||e.query.dateTo)&&y.push({key:"dateRange",label:"Date",value:(e.query.dateFrom||"\u2026")+" \u2013 "+(e.query.dateTo||"\u2026")}),e.chips=y};e.statusCountFor=y=>{let g=(e.statusCounts||[]).find(_=>_._id===y);return g?g.count:0},e.toggleSortDirection=()=>{e.query.direction=e.query.direction==="asc"?"desc":"asc"},e.sortBy=y=>{e.query.sort===y?e.query.direction=e.query.direction==="asc"?"desc":"asc":(e.query.sort=y,e.query.direction="desc"),e.query.page=1},e.sortIcon=y=>e.query.sort===y?e.query.direction==="asc"?"fa-arrow-up":"fa-arrow-down":"";let u="admin.conferences.filterPrefs",f={page:1,limit:25,sort:"name",direction:"asc",search:"",dateFrom:"",dateTo:"",ready:!1,expired:!1,removed:!1,error:!0,preparing:!0},k=loadFilterPrefs(u)||{};e.query=Object.assign({},f,k,{page:1,search:""});let h=n.search();h.search&&(e.query.search=h.search);let w="admin.conferences.presets";e.presets=JSON.parse(localStorage.getItem(w)||"[]"),e.savePreset=()=>{let y=window.prompt("Preset name:");if(!y)return;let g=Object.assign({},e.query);delete g.page,e.presets=(e.presets||[]).filter(_=>_.name!==y),e.presets.push({name:y,query:g}),localStorage.setItem(w,JSON.stringify(e.presets))},e.applyPreset=y=>{Object.assign(e.query,y.query,{page:1})},e.deletePreset=y=>{e.presets=(e.presets||[]).filter(g=>g.name!==y.name),localStorage.setItem(w,JS Line truncated
`).map((ce,fe)=>fe===0?ce:re+ce).join(`
`)}else typeof S=="number"||typeof S=="boolean"?J=String(S):J=JSON.stringify(S);se.push(`${Z}${J}${te}`)}),se.push("}"),se.join(`
`)}function k(R){let T=[],I="",F=/(\w+):(>=|<=|!=|>|<|=)?([^\s]+)/g,P=0,M;for(;M=F.exec(R);)I+=R.slice(P,M.index),P=F.lastIndex,T.push({key:M[1],op:M[2]||"=",val:M[3]});return I+=R.slice(P),{filters:T,free:I.trim().toLowerCase()}}function h(R,T){for(let I of T.filters){let F=(M,se,oe)=>{let S=parseFloat(M),O=parseFloat(se);return oe==="="?String(M)===String(se):oe==="!="?String(M)!==String(se):oe===">="?S>=O:oe==="<="?S<=O:oe===">"?S>O:oe==="<"?S<O:!0},P;if(I.key==="code")P=R.displayMessage;else if(I.key==="module")P=R.module;else if(I.key==="status")P=R._status;else if(I.key==="url")P=R._url;else if(I.key==="repo")P=R._repoId;else if(I.key==="level")P=R.level;else continue;if(P==null||!F(P,I.val,I.op))return!1}return!(T.free&&((R.displayMessage||"")+" "+(R.module||"")+" "+(R._url||"")+" "+JSON.stringify(R.raw||[])).toLowerCase().indexOf(T.free)===-1)}function w(){let R=k(e.query.search||"");e.parsedFilterCount=R.filters.length;let T=e.query.bucket,I=e.entries.filter(P=>T&&P._bucket!==T?!1:h(P,R)),F=e.query.group;if(F){let P=oe=>F==="module"?oe.module:oe.displayMessage||oe.message||"_",M=new Map;for(let oe of I){let S=P(oe);if(M.has(S)){let O=M.get(S);O.count++,O._related.push(oe),new Date(oe.ts)>new Date(O.ts)&&(O.ts=oe.ts,O._url=oe._url,O._status=oe._status),new Date(oe.ts)<new Date(O._firstSeen)&&(O._firstSeen=oe.ts)}else{let O=Object.assign({},oe);O._key=`${F}:${S}`,O._related=[oe],O._firstSeen=oe.ts,O._lastHourCount=0,O.count=1,M.set(S,O)}}let se=Date.now()-3600*1e3;for(let oe of M.values())oe._lastHourCount=oe._related.filter(S=>new Date(S.ts).getTime()>=se).length;I=Array.from(M.values())}else I=I.map((P,M)=>(P._key="row:"+M+":"+P.ts,P._related=[P],P._firstSeen=P.ts,P._lastHourCount=0,P.count=1,P));e.query.sort==="count"?I.sort((P,M)=>M.count-P.count||new Date(M.ts)-new Date(P.ts)):I.sort((P,M)=>new Date(M.ts)-new Date(P.ts)),e.visible=I}function m(R){let T=R?e.entries.length:0,I=R?e.pageSize:Math.max(e.pageSize,e.entries.length||e.pageSize);t.get("/api/admin/errors",{params:{offset:T,limit:I}}).then(F=>{let P=(F.data.entries||[]).map(u);e.entries=R?e.entries.concat(P):P,e.available=!!F.data.available,e.cap=F.data.max||e.cap,e.total=F.data.total||e.entries.length,w()},F=>console.error(F))}e.loadMore=()=>m(!0),e.canLoadMore=()=>e.entries.length<e.total;function E(){t.get("/api/admin/errors/stats").then(R=>{let T=R.data||{},I=T.prev24h?Math.round((T.last24h-T.prev24h)/T.prev24h*100):0;e.stats={last24h:T.last24h||0,prev24h:T.prev24h||0,delta:I,severity:T.severity||{error:0,warn:0,info:0},unique:T.unique||{error:0,warn:0,info:0},buckets:T.buckets||[],dropped:T.dropped||0}},R=>console.error(R))}function y(){m(),E()}e.barPx=(R,T)=>{let I=e.stats.buckets||[],F=0;for(let oe of I)F=Math.max(F,(oe.error||0)+(oe.warn||0)+(oe.info||0));if(!F)return 0;let P=(R.error||0)+(R.warn||0)+(R.info||0);if(!P)return 0;let M=Math.round(P/F*60),se=R[T]||0;return Math.round(se/P*M)},e.bucketTitle=R=>`${new Date(R.hour).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})} \xB7 ${R.error||0} err \xB7 ${R.warn||0} warn \xB7 ${R.info||0} info`,e.toggle=R=>{e.expanded[R._key]=!e.expanded[R._key]},e.setBucket=R=>{e.query.bucket=R},e.refreshNow=y,e.clearAll=()=>{confirm("Clear all captured errors?")&&t.delete("/api/admin/errors").then(y,R=>console.error(R))},e.exportCsv=()=>{let R=["ts","level","module","displayMessage","_status","_url","_repoId"],T=[R.join(",")];for(let M of e.visible)T.push(R.map(se=>{let oe=M[se]==null?"":String(M[se]);return/[",\n]/.test(oe)?`"${oe.replace(/"/g,'""')}"`:oe}).join(","));let I=new Blob([T.join(`
`)],{type:"text/csv;charset=utf-8"}),F=URL.createObjectURL(I),P=document.createElement("a");P.href=F,P.download=`errors-${new Date().toISOString().slice(0,19)}.csv`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(F)};function g(R){e.copyHint=`${R} copied`,s.timeout(()=>{e.copyHint=""},1500)}e.copyJson=R=>{navigator.clipboard.writeText(R._detailJson).then(()=>g("JSON"))},e.copyCurl=R=>{if(!R._url)return;let I=`curl -X ${R._method||"GET"} '${window.location.origin}${R._url}'`;navigator.clipboard.writeText(I).then(()=>g("curl"))},y();let _=r(()=>{e.query.autoRefresh&&y()},15e3);e.on("dispose",()=>r.cancel(_)),e.watch("query.search",w),e.watch("query.bucket",w),e.watch("query.sort",w),e.watch("query.group",w)},vl=function(e,t,n,r){if(e.Math=Math,e.watch("user.status",()=>{e.user==null&&n.url("/")}),e.user==null){n.url("/");return}e.data=null,e.loading=!0,e.error=null,e.performance=null,e.performanceMinutes=15,e.performanceTab="routes",e.performanceError=null,e.formatMs=function(y){return y==null?"":y<1e3?y+" ms":+(y/1e3).toFixed(1)+" s"},e.latencyBound=function(y,g){return y.count?y[g]==null?"> 60 s":"\u2264 "+e.formatMs(y[g]):"No samples"},e.firstByteBound=function(y){return e.latencyBound({count:y.firstByteCount,p95UpperMs:y.firstByteP95UpperMs},"p95UpperMs")},e.sampleAge=function(y){return Math.max(0,Math.round((Date.now()-y.sampledAt)/1e3))},e.peakRss=function(y){return(e.performance.runtimeSeries||[]).filter(function(g){return g.instance===y.instance}).reduce(function(g,_){return Math.max(g,_.rss)},y.memory.rss)},e.performanceWarning=function(y){return e.sampleAge(y)>45||y.droppedBatches||y.droppedMetrics||y.sockets?.closeWait>0||y.eventLoop.p95Ms>100||y.memoryLimitBytes&&y.memory.rss>y.memoryLimitBytes*.8};var s=!1;e.loadPerformance=function(){var y=e.performanceMinutes;e.performance?.windowMinutes&&e.performance.windowMinutes!==y&&(e.performance=null),!s&&(s=!0,t.get("/api/admin/performance",{params:{minutes:y}}).then(function(g){y===e.performanceMinutes&&(e.performance=g.data,e.performanceError=g.data.available?null:"Performance monitoring is unavailable. Request history may be incomplete.")},function(){y===e.performanceMinutes&&(e.performanceError="Could not refresh performance monitoring. Displayed samples may be stale.")}).finally(function(){s=!1,y!==e.performanceMinutes&&e.loadPerformance()}))};function i(y){if(y==null)return"\u2014";for(var g=["B","KB","MB","GB","TB"],_=0,R=y;R>=1024&&_<g.length-1;)R/=1024,_++;return R.toFixed(_>0?1:0)+" "+g[_]}e.humanBytes=i;function a(y){if(!y)return"\u2014";var g=Math.floor(y/86400),_=Math.floor(y%86400/3600),R=Math.floor(y%3600/60);return g>0?g+"d "+(_<10?"0":"")+_+"h":_>0?_+"h "+(R<10?"0":"")+R+"m":R+"m"}e.humanDuration=a;function u(y){return y==null?"\u2014":y>=1e6?(y/1e6).toFixed(1)+"M":y>=1e3?(y/1e3).toFixed(1)+"K":String(y)}e.humanNum=u,e.queueTotal=function(y){return y?(y.waiting||0)+(y.active||0)+(y.delayed||0)+(y.failed||0):0},e.statusCount=function(y){if(!e.data||!e.data.repos)return 0;for(var g=e.data.repos.statusBreakdown||[],_=0;_<g.length;_++)if(g[_]._id===y)return g[_].count;return 0},e.barPct=function(y){var g=e.data&&e.data.repos?e.data.repos.total:0;if(!g)return 0;var _=[y];y==="expired"&&_.push("expiring"),y==="removed"&&_.push("removing"),y==="preparing"&&_.push("download");var R=0;return _.forEach(function(T){R+=e.statusCount(T)}),Math.max(.4,R/g*100)},e.errPct=function(y){if(!e.data||!e.data.errors)return 0;var g=Math.max(e.data.errors.severity.error,e.data.errors.severity.warn,e.data.errors.severity.info,1);return e.data.errors.severity[y]/g*100};function f(y){var g=y||[];return g.map(function(_,R){var T=g[R-1]||{},I=Object.assign({},_);return I.dailyRepositories=R?Math.max(0,(_.nbRepositories||0)-(T.nbRepositories||0)):0,I.dailyUsers=R?Math.max(0,(_.nbUsers||0)-(T.nbUsers||0)):0,I.dailyPageViews=R?Math.max(0,(_.nbPageViews||0)-(T.nbPageViews||0)):0,I})}function k(y){var g=y&&y.length?y[y.length-1]:{};return{repositories:g.dailyRepositories||0,users:g.dailyUsers||0,pageViews:g.dailyPageViews||0}}var h={},w={};e.historyBarH=function(y,g){return!y||!h[g]?0:Math.max(1,Math.round(y[g]/h[g]*140))},e.historyRangeH=function(y,g){if(!y||h[g]==null)return 0;var _=h[g]-w[g];return _?Math.round(8+(y[g]-w[g])/_*132):70},e.historyRange=function(y){return{min:w[y],max:h[y]}},e.historyLabel=function(y){if(!y||!y.date)return"";var g=new Date(y.date);return g.getUTCMonth()+1+"/"+g.getUTCDate()};function m(){e.loadPerformance(),t.get("/api/admin/overview").then(function(y){y.data.history=f(y.data.history),y.data.daily={today:k(y.data.history)},e.data=y.data,e.loading=!1,e.error=null,h={},w={},(y.data.history||[]).forEach(function(g){["dailyPageViews","dailyRepositories","dailyUsers","nbUsers"].forEach(function(_){(!h[_]||g[_]>h[_])&&(h[_]=g[_]),(w[_]==null||g[_]<w[_])&&(w[_]=g[_])})})},function(y){e.loading=!1,e.error=y.data&&y.data.error||"Failed to load overview"})}m();var E=r(m,3e4);e.on("dispose",function(){r.can Line truncated
anonymous_github`)])])])])]),p(" Limitations "),o("h4",{class:"faq-cat"},[o("svg",{class:"ui-icon mr-2","aria-hidden":"true"},[o("use",{href:"#ui-icon-warning"})]),b("Limitations ")]),o("div",{class:"panel-group",id:"faq-limitations",role:"tablist","aria-multiselectable":"true"},[o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingLimitation"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-limitations",href:"#limitation","aria-expanded":"false","aria-controls":"limitation"}," What are the limitations of Anonymous GitHub? ")])]),o("div",{id:"limitation",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingLimitation"},[o("div",{class:"panel-body p-3"},[o("ul",null,[o("li",null," Anonymous GitHub only anonymizes text-based files. Binary files (compiled executables, archives, etc.) are served as-is without anonymization. "),o("li",null," Files larger than 8 MB are not supported. "),o("li",null," Static site generators (such as Jekyll) used with GitHub Pages are not fully supported, although Markdown files are converted to HTML. "),o("li",null," The anonymization of terms within source code may change the behavior of the program (e.g., if a replaced term appears in a string literal or identifier). ")])])])])]),p(" Privacy & Security "),o("h4",{class:"faq-cat"},[o("svg",{class:"ui-icon mr-2","aria-hidden":"true"},[o("use",{href:"#ui-icon-shield"})]),b("Privacy & Security ")]),o("div",{class:"panel-group",id:"faq-privacy",role:"tablist","aria-multiselectable":"true"},[o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingData"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-privacy",href:"#data","aria-expanded":"false","aria-controls":"data"}," How is my data handled? ")])]),o("div",{id:"data",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingData"},[o("div",{class:"panel-body p-3"},[o("p",null," Data stored on Anonymous GitHub is never shared or used for any purpose beyond providing the anonymization service. When a repository is removed or expires, only its configuration is retained \u2014 this makes it easy to restore the repository if needed and ensures that no future repository reuses the same ID. ")])])]),o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingPermissions"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-privacy",href:"#permissions","aria-expanded":"false","aria-controls":"permissions"}," Why does GitHub say Anonymous GitHub asks for write access? ")])]),o("div",{id:"permissions",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingPermissions"},[o("div",{class:"panel-body p-3"},[o("p",null,[b("The GitHub App has read-only access to the repositories you choose. You can change repository access on your "),o("a",{href:"/connections"},"GitHub connections"),b(" page.")]),o("p",null,"Legacy GitHub OAuth includes write access to private repositories because GitHub's OAuth scopes do not offer a read-only option for them. Existing OAuth anonymizations and gists can still use this connection."),o("p",null,"Anonymous GitHub reads repository content. It never pushes, modifies, or deletes files on GitHub.")])])]),o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingViewer"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-privacy",href:"#viewer","aria-expanded":"false","aria-controls":"viewer"}," Can repository owners see who viewed their anonymized repository? ")])]),o("div",{id:"viewer",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingViewer"},[o("div",{class:"panel-body p-3"},[o("p",null," No. Only the total number of views is tracked as an incremental counter. It is not possible for the repository owner or for Anonymous GitHub to identify individual viewers. Reviewer anonymity is fully preserved. ")])])])]),p(" Self-Hosting "),o("h4",{class:"faq-cat"},[o("svg",{class:"ui-icon mr-2","aria-hidden":"true"},[o("use",{href:"#project-icon-storage"})]),b("Self-Hosting ")]),o("div",{class:"panel-group",id:"faq-hosting",role:"tablist","aria-multiselectable":"true"},[o("div",{class:"panel panel-default mb-3"},[o("div",{class:"panel-heading p-3",role:"tab",id:"headingDeploy"},[o("h3",{class:"panel-title"},[o("a",{class:"collapsed",role:"button","data-toggle":"collapse","data-parent":"#faq-hosting",href:"#deploy","aria-expanded":"false","aria-controls":"deploy"}," Can I deploy my own instance? ")])]),o("div",{id:"deploy",class:"panel-collapse collapse",role:"tabpanel","aria-labelledby":"headingDeploy"},[o("div",{class:"panel-body p-3"},[o("p",null,[b(" Yes. Anonymous Git Line truncated
anonymized repository often think it is about the paper, so the
label names the service and the tooltip says who to contact. `),t[12]||(t[12]=o("li",{class:"nav-item d-none d-lg-block"},[o("a",{class:"nav-link",target:"_blank",rel:"noopener",href:"https://github.com/tdurieux/anonymous_github/issues/new?template=issue_report.yml",title:"Report a problem with the Anonymous GitHub service. Questions about an anonymized repository or paper go to its authors.","data-offset":"30"},[o("svg",{class:"ui-icon d-lg-none mr-1","aria-hidden":"true"},[o("use",{href:"#ui-icon-bug"})]),b("Report a bug ")])],-1)),e.isDarkMode?p("v-if",!0):(l(),d("li",s3,[o("a",{class:"nav-link nav-icon",href:"#",title:"Switch to dark mode","aria-label":"Switch to dark mode",role:"button",onClick:t[0]||(t[0]=me(s=>{e.darkMode(!0)},["prevent"]))},[...t[8]||(t[8]=[o("svg",{class:"ui-icon","aria-hidden":"true"},[o("use",{href:"#ui-icon-moon"})],-1)])])])),e.isDarkMode?(l(),d("li",n3,[o("a",{class:"nav-link nav-icon",href:"#",title:"Switch to light mode","aria-label":"Switch to light mode",role:"button",onClick:t[1]||(t[1]=me(s=>{e.darkMode(!1)},["prevent"]))},[...t[9]||(t[9]=[o("svg",{class:"ui-icon","aria-hidden":"true"},[o("use",{href:"#ui-icon-sun"})],-1)])])])):p("v-if",!0),!e.user&&!e.isReviewerRoute?(l(),d("li",r3,[...t[10]||(t[10]=[o("a",{class:"nav-link btn-signin",target:"_self",href:"/signin","data-offset":"30"},[o("i",{class:"fab fa-github mr-1"}),b(" Sign in ")],-1)])])):p("v-if",!0),e.user?(l(),d("li",i3,[o("a",a3,[e.user?.photo?(l(),d("img",{key:0,width:"22",height:"22",class:"rounded-circle",src:e.safeUrl(e.user?.photo)},null,8,l3)):p("v-if",!0),o("span",d3,c(e.user?.username),1)]),o("div",u3,[o("h6",c3,"Signed in as @"+c(e.user?.username),1),t[11]||(t[11]=ce('<a class="dropdown-item" href="/profile"><svg class="ui-icon" aria-hidden="true"><use href="#project-icon-filter"></use></svg><span>Settings<small>Defaults, quotas, account</small></span></a><a class="dropdown-item" href="/connections"><i class="fab fa-github" aria-hidden="true"></i><span>GitHub connections<small>Repository access and OAuth</small></span></a><a class="dropdown-item" href="/claim"><svg class="ui-icon" aria-hidden="true"><use href="#ui-icon-link"></use></svg><span>Claim an anonymization<small>Attach an existing mirror to your account</small></span></a><div class="dropdown-divider"></div><a class="dropdown-item" href="https://github.com/tdurieux/anonymous_github/issues/new?template=issue_report.yml" target="_blank" rel="noopener"><svg class="ui-icon" aria-hidden="true"><use href="#ui-icon-bug"></use></svg><span>Report a bug<small>About this service, not a paper</small></span></a><a class="dropdown-item" href="https://github.com/tdurieux/anonymous_github/" target="_blank" rel="noopener"><i class="fab fa-github" aria-hidden="true"></i><span>Source code</span></a><a class="dropdown-item" href="https://ko-fi.com/tdurieux" target="_blank" rel="noopener"><svg class="ui-icon" aria-hidden="true"><use href="#ui-icon-heart"></use></svg><span>Support the project</span></a><div class="dropdown-divider"></div><a class="dropdown-item" href="/api/user/logout" target="_self"><svg class="ui-icon" aria-hidden="true"><use href="#ui-icon-logout"></use></svg><span>Sign out</span></a>',9))])])):p("v-if",!0)])])],2),e.generalMessage?(l(),d("div",{key:0,class:"navbar shadow generalMessage",innerHTML:e.sanitize(e.generalMessage)},null,8,p3)):p("v-if",!0)],64)}var f3={class:"paper-landing"},m3={class:"paper-hero"},h3={class:"paper-hero-copy"},v3={class:"paper-cta-row"},g3={key:0,href:"/signin",target:"_self",class:"btn-hero"},y3={key:1,href:"/anonymize",class:"btn-hero"},b3={class:"paper-stats paper-wrap",id:"metrics","aria-label":"Usage over the last 60 days"},w3={class:"paper-stats-grid"},k3={class:"paper-stat-value"},E3={class:"paper-stat-label"},C3=["viewBox"],_3=["x","y","width","height"],S3={key:1,class:"paper-stat-delta"},N3={class:"paper-features paper-wrap","aria-label":"Product features"},D3={class:"paper-features-list",role:"tablist","aria-label":"Features","aria-orientation":"vertical"},R3=["onClick","onKeydown","id","aria-controls","aria-selected","tabindex"],T3={class:"paper-eyebrow"},A3={class:"paper-feature-title"},O3={class:"paper-feature-more"},I3={class:"paper-feature-title paper-feature-title-m","aria-hidden":"true"},P3=["href","target"],V3={class:"paper-features-stage"},q3=["id","aria-labelledby"],M3={class:"paper-frame"},$3={class:"paper-frame-bar","aria-hidden":"true"},L3={class:"url"},U3=["src","alt"],F3={class:"paper-footer"},z3={class:"paper-footer-inner"},H3={class:"paper-footer-col"},B3={key:0,href:"/dashboard"},j3={key:1,href:"/conferences"},G3={class:"paper-footer-foot"};function Il(e,t){return l(),d("div",f3,[p(" Hero: copy on the left, the product on the right "),o("section",m3,[o("div",h3,[t[2]||(t[2]=o("div",{class:"paper-eyebrow"},"For double-blind peer review",-1)),t[3]||(t[3]=o("h1",{class:"hero-title"},[b(" Share the code,"),o("br"),o("span",{class:"accent"},"not the author.")],-1)),t[4]||(t[4]=o("p Line truncated
label names the service and the tooltip says who to contact. `),t[17]||(t[17]=o("li",{class:"nav-item d-none d-lg-block"},[o("a",{class:"nav-link",target:"_blank",rel:"noopener",href:"https://github.com/tdurieux/anonymous_github/issues/new?template=issue_report.yml",title:"Report a problem with the Anonymous GitHub service. Questions about an anonymized repository or paper go to its authors.","data-offset":"30"},[o("svg",{class:"ui-icon d-lg-none mr-1","aria-hidden":"true"},[o("use",{href:"#ui-icon-bug"})]),b("Report a bug ")])],-1)),e.isDarkMode?p("v-if",!0):(l(),d("li",O3,[o("a",{class:"nav-link nav-icon",href:"#",title:"Switch to dark mode","aria-label":"Switch to dark mode",role:"button",onClick:t[0]||(t[0]=de(n=>{e.darkMode(!0)},["prevent"]))},[...t[13]||(t[13]=[o("svg",{class:"ui-icon","aria-hidden":"true"},[o("use",{href:"#ui-icon-moon"})],-1)])])])),e.isDarkMode?(l(),d("li",I3,[o("a",{class:"nav-link nav-icon",href:"#",title:"Switch to light mode","aria-label":"Switch to light mode",role:"button",onClick:t[1]||(t[1]=de(n=>{e.darkMode(!1)},["prevent"]))},[...t[14]||(t[14]=[o("svg",{class:"ui-icon","aria-hidden":"true"},[o("use",{href:"#ui-icon-sun"})],-1)])])])):p("v-if",!0),!e.user&&!e.isReviewerRoute?(l(),d("li",P3,[...t[15]||(t[15]=[o("a",{class:"nav-link btn-signin",target:"_self",href:"/signin","data-offset":"30"},[o("i",{class:"fab fa-github mr-1"}),b(" Sign in ")],-1)])])):p("v-if",!0),e.user?(l(),d("li",V3,[o("a",q3,[e.user?.photo?(l(),d("img",{key:0,width:"22",height:"22",class:"rounded-circle",src:e.safeUrl(e.user?.photo)},null,8,M3)):p("v-if",!0),o("span",$3,c(e.user?.username),1)]),o("div",L3,[o("h6",U3,"Signed in as @"+c(e.user?.username),1),t[16]||(t[16]=pe('<a class="dropdown-item" href="/profile"><svg class="ui-icon" aria-hidden="true"><use href="#project-icon-filter"></use></svg><span>Settings<small>Defaults, quotas, account</small></span></a><a class="dropdown-item" href="/connections"><i class="fab fa-github" aria-hidden="true"></i><span>GitHub connections<small>Repository access and OAuth</small></span></a><a class="dropdown-item" href="/claim"><svg class="ui-icon" aria-hidden="true"><use href="#ui-icon-link"></use></svg><span>Claim an anonymization<small>Attach an existing mirror to your account</small></span></a><div class="dropdown-divider"></div><a class="dropdown-item" href="https://github.com/tdurieux/anonymous_github/issues/new?template=issue_report.yml" target="_blank" rel="noopener"><svg class="ui-icon" aria-hidden="true"><use href="#ui-icon-bug"></use></svg><span>Report a bug<small>About this service, not a paper</small></span></a><a class="dropdown-item" href="https://github.com/tdurieux/anonymous_github/" target="_blank" rel="noopener"><i class="fab fa-github" aria-hidden="true"></i><span>Source code</span></a><a class="dropdown-item" href="https://ko-fi.com/tdurieux" target="_blank" rel="noopener"><svg class="ui-icon" aria-hidden="true"><use href="#ui-icon-heart"></use></svg><span>Support the project</span></a><div class="dropdown-divider"></div><a class="dropdown-item" href="/api/user/logout" target="_self"><svg class="ui-icon" aria-hidden="true"><use href="#ui-icon-logout"></use></svg><span>Sign out</span></a>',9))])])):p("v-if",!0)])])],2),e.generalMessage?(l(),d("div",{key:0,class:"navbar shadow generalMessage",innerHTML:e.sanitize(e.generalMessage)},null,8,F3)):p("v-if",!0),e.emailPromptOpen?(l(),d("dialog",{key:1,id:"email-prompt",class:"email-prompt","aria-labelledby":"email-prompt-title","aria-describedby":"email-prompt-reason",onCancel:t[6]||(t[6]=de(n=>e.respondToEmailPrompt("later"),["prevent"]))},[o("form",{onSubmit:t[5]||(t[5]=de(n=>e.respondToEmailPrompt("save"),["prevent"]))},[t[19]||(t[19]=o("h2",{id:"email-prompt-title"},"Stay informed about access problems",-1)),t[20]||(t[20]=o("p",{id:"email-prompt-reason"},"Get email alerts when your GitHub token or repository access fails.",-1)),t[21]||(t[21]=o("label",{for:"email-prompt-address"},"Email address",-1)),D(o("input",{id:"email-prompt-address",class:"form-control",type:"email",autocomplete:"email",maxlength:"254",required:"","onUpdate:modelValue":t[2]||(t[2]=n=>e.emailPromptAddress=n),disabled:e.emailPromptBusy},null,8,z3),[[to,e.emailPromptAddress]]),e.emailPromptError?(l(),d("p",H3,c(e.emailPromptError),1)):p("v-if",!0),o("div",B3,[o("button",{type:"button",class:"btn btn-outline-ink",disabled:e.emailPromptBusy,onClick:t[3]||(t[3]=n=>e.respondToEmailPrompt("later"))},"Remind me later",8,j3),o("button",{type:"button",class:"btn btn-outline-ink",disabled:e.emailPromptBusy,onClick:t[4]||(t[4]=n=>e.respondToEmailPrompt("never"))},"Never",8,G3),o("button",{type:"submit",class:"btn btn-ink",disabled:e.emailPromptBusy},c(e.emailPromptBusy?"Saving\u2026":"Save"),9,W3)])],32)],32)):p("v-if",!0)],64)}var K3={class:"paper-landing"},Y3={class:"paper-hero"},J3={class:"paper-hero-copy"},Q3={class:"paper-cta-row"},X3={key:0,href:"/signin",target:"_self",class:"btn-hero"},Z3={key:1,href:"/anonymize",cla Line truncated
MIT CSAIL
jane.smith@example.org`},M5={id:"termsHelp",class:"form-text text-muted"},$5={class:"invalid-feedback"},L5={id:"settings-display",class:"paper-settings-section"},U5={class:"form-group paper-check-list"},F5={class:"form-check"},z5={class:"form-check-input",type:"checkbox",id:"link",name:"link"},H5={class:"form-check"},B5={class:"form-check-input",type:"checkbox",id:"image",name:"image"},j5={class:"form-check"},G5={class:"form-check-input",type:"checkbox",id:"pdf",name:"pdf"},W5={class:"form-check"},K5={class:"form-check-input",type:"checkbox",id:"notebook",name:"notebook"},Y5={id:"settings-features",class:"paper-settings-section"},J5={class:"form-group paper-check-list"},Q5={class:"form-check"},X5={class:"form-check-input",type:"checkbox",id:"page",name:"page"},Z5={class:"form-check"},x5={class:"form-check-input",type:"checkbox",id:"loc",name:"loc"},eq={class:"form-check"},tq={class:"form-check-input",type:"checkbox",id:"update",name:"update"},oq={class:"form-group"},sq={class:"form-control",id:"mode",name:"mode"},nq={class:"form-text text-muted"},rq={id:"settings-expiration",class:"paper-settings-section"},iq={class:"form-group"},aq={class:"form-control",id:"expiration",name:"expiration"},lq={key:0,class:"draft-status",role:"status"},dq={key:1,class:"draft-status"},uq={class:"paper-settings-footer"},cq={key:0,class:"paper-inline-alert paper-inline-alert-error",role:"alert"},pq=["textContent"],fq={class:"paper-settings-actions"},mq=["disabled"],hq={key:0,class:"ui-icon mr-1","aria-hidden":"true"},vq={id:"settings-account",class:"paper-settings-section"},gq={class:"paper-account-card"},yq=["src"],bq={class:"paper-account-identity"},wq={class:"paper-account-name"},kq={class:"paper-danger-zone"},Eq={key:0,class:"paper-inline-alert paper-inline-alert-error",role:"alert"},Cq=["textContent"],_q=["disabled"];function $l(e,t){let s=We("quota-usage"),r=be("paper-scrollspy"),n=be("field"),i=be("form");return l(),d("div",N5,[t[52]||(t[52]=ce('<div class="paper-crumbs"><a href="/dashboard">My work</a> \xA0/\xA0 <span class="here">Settings</span></div><h1 class="paper-page-title">Your <em>settings</em></h1><p class="paper-page-lede">Defaults applied to every new anonymization, your quotas, and your account.</p>',3)),o("div",D5,[N((l(),d("aside",R5,[...t[4]||(t[4]=[ce('<div class="paper-settings-toc-head">On this page</div><nav><a href="#settings-quota">Quota</a><a href="#settings-terms">Terms to redact</a><a href="#settings-display">Display</a><a href="#settings-features">Features</a><a href="#settings-expiration">Expiration</a><a href="#settings-account">Account</a></nav>',2)])])),[[r]]),o("div",T5,[p(" Account usage shares the dashboard component. "),o("section",A5,[t[6]||(t[6]=o("div",{class:"paper-section-eyebrow"},"Quota",-1)),t[7]||(t[7]=o("p",{class:"paper-section-copy"},"What you are using across all your anonymizations. Conferences can lift these limits during a review window.",-1)),e.quota?(l(),Mt(s,{key:0,quota:e.quota,fmt:e.fmt},null,8,["quota","fmt"])):p("v-if",!0),e.quota?p("v-if",!0):(l(),d("div",O5,[(l(),d(X,null,re([1,2,3],(a,u)=>o("div",I5,[...t[5]||(t[5]=[o("div",{class:"quota-header"},[o("span",{class:"skeleton skeleton-line",style:{width:"40%"}}),o("span",{class:"skeleton skeleton-line",style:{width:"25%"}})],-1),o("div",{class:"quota-track"},null,-1)])])),64))]))]),N((l(),d("form",{class:"form needs-validation",name:"defaultsForm",novalidate:"",onSubmit:t[2]||(t[2]=me(a=>e.submitForm(a,()=>{e.saveDefault(a)}),["prevent"]))},[o("section",P5,[t[13]||(t[13]=o("div",{class:"paper-section-eyebrow"},"Terms to redact",-1)),t[14]||(t[14]=o("p",{class:"paper-section-copy"},"Pre-filled in every new anonymization. You can still edit the list per anonymization.",-1)),o("div",V5,[t[12]||(t[12]=o("label",{class:"paper-field-label",for:"terms"},"Default terms",-1)),N(o("textarea",q5,null,512),[[n,{state:e.viewState,set:a=>{e.terms=a},value:e.terms,form:"defaultsForm",options:{debounce:250}}]]),o("small",M5,[t[8]||(t[8]=b(" One term per line (regex allowed). Each match is replaced by ",-1)),o("code",null,c(e.site_options?.ANONYMIZATION_MASK||"XXX")+"-[N]",1),t[9]||(t[9]=b(", or use ",-1)),t[10]||(t[10]=o("code",null,"term=>replacement",-1)),t[11]||(t[11]=b(" to pick your own. ",-1))]),N(o("div",$5," Terms are in an invalid format ",512),[[W,e.defaultsForm?.terms?.errors?.format]])])]),o("section",L5,[t[23]||(t[23]=o("div",{class:"paper-section-eyebrow"},"Display",-1)),t[24]||(t[24]=o("p",{class:"paper-section-copy"},"What reviewers can see inside an anonymized repository.",-1)),o("div",U5,[o("div",F5,[N(o("input",z5,null,512),[[n,{state:e.viewState,set:a=>{e.options.link=a},value:e.options?.link,form:"defaultsForm",options:{}}]]),t[15]||(t[15]=o("label",{class:"form-check-label",for:"link"},"Keep links",-1)),t[16]||(t[16]=o("small",{class:"form-text text-muted"},"Unchecked, every link in text files is removed.",-1))]),o("div",H5,[N(o("input",B5,null,512),[[n,{state:e.viewState,set:a=>{e.options.image=a},value:e.op Line truncated
`);for(let k=0;k<h.length;k++){let m=h[k];if(m.startsWith("diff --git")){v(),f();continue}if(m.startsWith("--- ")){i&&i.lines.length&&v(),f().oldPath=m.replace(/^--- (a\/)?/,"").trim();continue}if(m.startsWith("+++ ")){f().newPath=m.replace(/^\+\+\+ (b\/)?/,"").trim();continue}if(!(m.startsWith("index ")||m.startsWith("similarity index")||m.startsWith("rename ")||m.startsWith("new file mode")||m.startsWith("deleted file mode")||m.startsWith("Binary files"))){if(m.startsWith("@@")){let E=m.match(/@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/);E&&(a=parseInt(E[1],10),u=parseInt(E[2],10)),f().lines.push({kind:"hunk",oldNo:"",newNo:"",text:m});continue}i&&(m.startsWith("+")?(i.lines.push({kind:"add",oldNo:"",newNo:u,text:m.slice(1)}),u++):m.startsWith("-")?(i.lines.push({kind:"remove",oldNo:a,newNo:"",text:m.slice(1)}),a++):(i.lines.push({kind:"ctx",oldNo:a,newNo:u,text:m.startsWith(" ")?m.slice(1):m}),a++,u++))}}return s(n,i),n.join("")}})({trustAsHtml:e=>e});function zM(e,t){return e==null?"":Number(e).toLocaleString(void 0,t==null?{}:{minimumFractionDigits:t,maximumFractionDigits:t})}function HM(e){return String(e??"").toUpperCase()}function BM(e,t,s=0){return(e||[]).slice(s,s+t)}function jM(e,t){return Array.isArray(e)?typeof t=="function"?e.filter(t):e:[]}function GM(e,t){if(!t)return e||[];let s=Array.isArray(t)?t:[t];return[...e||[]].sort((r,n)=>{for(let i of s){let a=i[0]==="-"?-1:1;i=i.replace(/^[+-]/,"");let u=i.split(".").reduce((v,h)=>v?.[h],r),f=i.split(".").reduce((v,h)=>v?.[h],n);if(typeof u=="string"&&(u=u.toLowerCase()),typeof f=="string"&&(f=f.toLowerCase()),u!==f)return(u==null?-1:f==null?1:u<f?-1:1)*a}return 0})}function WM(e,t){if(!e)return"";let s=new Date(e);if(isNaN(s))return String(e);if(!t||t==="mediumDate")return s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});let r={yyyy:s.getFullYear(),MMM:s.toLocaleDateString(void 0,{month:"short"}),MM:String(s.getMonth()+1).padStart(2,"0"),dd:String(s.getDate()).padStart(2,"0"),d:s.getDate(),HH:String(s.getHours()).padStart(2,"0"),mm:String(s.getMinutes()).padStart(2,"0"),ss:String(s.getSeconds()).padStart(2,"0")};return t.replace(/yyyy|MMM|MM|dd|HH|mm|ss|d/g,n=>r[n])}function KM(e,t){return(t?.[e]??t?.[e===1?"one":"other"]??"").replace(/\{\}/g,e??0)}var ar={ERRORS:{cache_busy:"Downloads are busy. Please try again shortly.",invalid_sort:"The selected sort order is invalid.",invalid_cursor:"This project page is no longer valid. Reload the list.",repository_changed:"The repository changed while processing. Please retry.",repository_job_cancelled:"The repository changed or was removed while processing.",storage_delete_failed:"Unable to remove cached files. Please try again later.",unknown_error:"Unknown error, contact the admin.",unreachable:"Anonymous GitHub is unreachable, contact the admin.",request_error:"Unable to download the file, check your connection or contact the admin.",not_found:"The requested resource could not be found.",not_connected:"You must be logged in to perform this action.",not_authorized:"You do not have permission to perform this action.",unable_to_connect_user:"Unable to connect your account. Please try again later.",user_not_found:"The requested user could not be found.",user_banned:"Your account has been banned. Contact the admin for more information.",repo_access_limited:"GitHub blocked access because the repository's organization restricts third-party OAuth apps. Ask an org owner to approve Anonymous GitHub under Settings \u2192 Third-party Access \u2192 OAuth app policy, or anonymize a personal fork instead.",repo_saml_enforcement:"The repository's organization enforces SAML single sign-on. Authorize your token for that organization (GitHub \u2192 Settings \u2192 Applications, or re-run the org's SSO sign-in), then retry. Alternatively, anonymize a personal fork.",repo_not_found:"The repository was not found on GitHub. Check the URL and spelling, make sure you are signed in to the account that can see it, and confirm the repo isn't hidden under an org that restricts third-party app access.",repo_empty:"The selected branch has no commits on GitHub. Push at least one commit, or pick a different branch, then retry.",repo_not_accessible:"Anonymous GitHub cannot access this repository. Verify the repository exists and that Anonymous GitHub has been authorized for the owning organization.",repository_archived:"This repository has been archived and its files are no longer available.",repository_expired:"The repository is expired.",invalid_status:"This action cannot be performed while the resource is in its current state.",repository_not_ready:"Anonymous GitHub is still processing the repository, it can take several minutes.",repository_not_accessible:"This repository is currently not accessible.",repo_is_updating:"Anonymous GitHub is still processing the repository, it can take several minutes.",invalid_repo:"The provided repository is not valid.",invalid_source_repository:"The repository source name Line truncated
jane.smith@example.org`},vq={id:"termsHelp",class:"form-text text-muted"},yq={class:"invalid-feedback"},gq={id:"settings-display",class:"paper-settings-section"},bq={class:"form-group paper-check-list"},wq={class:"form-check"},kq={class:"form-check-input",type:"checkbox",id:"link",name:"link"},Eq={class:"form-check"},Cq={class:"form-check-input",type:"checkbox",id:"image",name:"image"},_q={class:"form-check"},Sq={class:"form-check-input",type:"checkbox",id:"pdf",name:"pdf"},Nq={class:"form-check"},Dq={class:"form-check-input",type:"checkbox",id:"notebook",name:"notebook"},Rq={id:"settings-features",class:"paper-settings-section"},Tq={class:"form-group paper-check-list"},Aq={class:"form-check"},Oq={class:"form-check-input",type:"checkbox",id:"page",name:"page"},Iq={class:"form-check"},Pq={class:"form-check-input",type:"checkbox",id:"loc",name:"loc"},Vq={class:"form-check"},qq={class:"form-check-input",type:"checkbox",id:"update",name:"update"},Mq={class:"form-group"},$q={class:"form-control",id:"mode",name:"mode"},Lq={class:"form-text text-muted"},Uq={id:"settings-expiration",class:"paper-settings-section"},Fq={class:"form-group"},zq={class:"form-control",id:"expiration",name:"expiration"},Hq={key:0,class:"draft-status",role:"status"},Bq={key:1,class:"draft-status"},jq={class:"paper-settings-footer"},Gq={key:0,class:"paper-inline-alert paper-inline-alert-error",role:"alert"},Wq=["textContent"],Kq={class:"paper-settings-actions"},Yq=["disabled"],Jq={key:0,class:"ui-icon mr-1","aria-hidden":"true"},Qq={id:"settings-account",class:"paper-settings-section"},Xq={class:"paper-account-card"},Zq=["src"],xq={class:"paper-account-identity"},eM={class:"paper-account-name"},tM={class:"paper-danger-zone"},oM={key:0,class:"paper-inline-alert paper-inline-alert-error",role:"alert"},nM=["textContent"],sM=["disabled"];function jl(e,t){let n=We("quota-usage"),r=be("paper-scrollspy"),s=be("field"),i=be("form");return l(),d("div",iq,[t[52]||(t[52]=pe('<div class="paper-crumbs"><a href="/dashboard">My work</a> \xA0/\xA0 <span class="here">Settings</span></div><h1 class="paper-page-title">Your <em>settings</em></h1><p class="paper-page-lede">Defaults applied to every new anonymization, your quotas, and your account.</p>',3)),o("div",aq,[D((l(),d("aside",lq,[...t[4]||(t[4]=[pe('<div class="paper-settings-toc-head">On this page</div><nav><a href="#settings-quota">Quota</a><a href="#settings-terms">Terms to redact</a><a href="#settings-display">Display</a><a href="#settings-features">Features</a><a href="#settings-expiration">Expiration</a><a href="#settings-account">Account</a></nav>',2)])])),[[r]]),o("div",dq,[p(" Account usage shares the dashboard component. "),o("section",uq,[t[6]||(t[6]=o("div",{class:"paper-section-eyebrow"},"Quota",-1)),t[7]||(t[7]=o("p",{class:"paper-section-copy"},"What you are using across all your anonymizations. Conferences can lift these limits during a review window.",-1)),e.quota?(l(),Lt(n,{key:0,quota:e.quota,fmt:e.fmt},null,8,["quota","fmt"])):p("v-if",!0),e.quota?p("v-if",!0):(l(),d("div",cq,[(l(),d(X,null,ae([1,2,3],(a,u)=>o("div",pq,[...t[5]||(t[5]=[o("div",{class:"quota-header"},[o("span",{class:"skeleton skeleton-line",style:{width:"40%"}}),o("span",{class:"skeleton skeleton-line",style:{width:"25%"}})],-1),o("div",{class:"quota-track"},null,-1)])])),64))]))]),D((l(),d("form",{class:"form needs-validation",name:"defaultsForm",novalidate:"",onSubmit:t[2]||(t[2]=de(a=>e.submitForm(a,()=>{e.saveDefault(a)}),["prevent"]))},[o("section",fq,[t[13]||(t[13]=o("div",{class:"paper-section-eyebrow"},"Terms to redact",-1)),t[14]||(t[14]=o("p",{class:"paper-section-copy"},"Pre-filled in every new anonymization. You can still edit the list per anonymization.",-1)),o("div",mq,[t[12]||(t[12]=o("label",{class:"paper-field-label",for:"terms"},"Default terms",-1)),D(o("textarea",hq,null,512),[[s,{state:e.viewState,set:a=>{e.terms=a},value:e.terms,form:"defaultsForm",options:{debounce:250}}]]),o("small",vq,[t[8]||(t[8]=b(" One term per line (regex allowed). Each match is replaced by ",-1)),o("code",null,c(e.site_options?.ANONYMIZATION_MASK||"XXX")+"-[N]",1),t[9]||(t[9]=b(", or use ",-1)),t[10]||(t[10]=o("code",null,"term=>replacement",-1)),t[11]||(t[11]=b(" to pick your own. ",-1))]),D(o("div",yq," Terms are in an invalid format ",512),[[K,e.defaultsForm?.terms?.errors?.format]])])]),o("section",gq,[t[23]||(t[23]=o("div",{class:"paper-section-eyebrow"},"Display",-1)),t[24]||(t[24]=o("p",{class:"paper-section-copy"},"What reviewers can see inside an anonymized repository.",-1)),o("div",bq,[o("div",wq,[D(o("input",kq,null,512),[[s,{state:e.viewState,set:a=>{e.options.link=a},value:e.options?.link,form:"defaultsForm",options:{}}]]),t[15]||(t[15]=o("label",{class:"form-check-label",for:"link"},"Keep links",-1)),t[16]||(t[16]=o("small",{class:"form-text text-muted"},"Unchecked, every link in text files is removed.",-1))]),o("div",Eq,[D(o("input",Cq,null,512),[[s,{state:e.viewState,set:a=>{e.options.image=a},value:e.op Line truncated
`);for(let w=0;w<h.length;w++){let m=h[w];if(m.startsWith("diff --git")){k(),f();continue}if(m.startsWith("--- ")){i&&i.lines.length&&k(),f().oldPath=m.replace(/^--- (a\/)?/,"").trim();continue}if(m.startsWith("+++ ")){f().newPath=m.replace(/^\+\+\+ (b\/)?/,"").trim();continue}if(!(m.startsWith("index ")||m.startsWith("similarity index")||m.startsWith("rename ")||m.startsWith("new file mode")||m.startsWith("deleted file mode")||m.startsWith("Binary files"))){if(m.startsWith("@@")){let E=m.match(/@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/);E&&(a=parseInt(E[1],10),u=parseInt(E[2],10)),f().lines.push({kind:"hunk",oldNo:"",newNo:"",text:m});continue}i&&(m.startsWith("+")?(i.lines.push({kind:"add",oldNo:"",newNo:u,text:m.slice(1)}),u++):m.startsWith("-")?(i.lines.push({kind:"remove",oldNo:a,newNo:"",text:m.slice(1)}),a++):(i.lines.push({kind:"ctx",oldNo:a,newNo:u,text:m.startsWith(" ")?m.slice(1):m}),a++,u++))}}return n(s,i),s.join("")}})({trustAsHtml:e=>e});function k8(e,t){return e==null?"":Number(e).toLocaleString(void 0,t==null?{}:{minimumFractionDigits:t,maximumFractionDigits:t})}function E8(e){return String(e??"").toUpperCase()}function C8(e,t,n=0){return(e||[]).slice(n,n+t)}function _8(e,t){return Array.isArray(e)?typeof t=="function"?e.filter(t):e:[]}function S8(e,t){if(!t)return e||[];let n=Array.isArray(t)?t:[t];return[...e||[]].sort((r,s)=>{for(let i of n){let a=i[0]==="-"?-1:1;i=i.replace(/^[+-]/,"");let u=i.split(".").reduce((k,h)=>k?.[h],r),f=i.split(".").reduce((k,h)=>k?.[h],s);if(typeof u=="string"&&(u=u.toLowerCase()),typeof f=="string"&&(f=f.toLowerCase()),u!==f)return(u==null?-1:f==null?1:u<f?-1:1)*a}return 0})}function N8(e,t){if(!e)return"";let n=new Date(e);if(isNaN(n))return String(e);if(!t||t==="mediumDate")return n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});let r={yyyy:n.getFullYear(),MMM:n.toLocaleDateString(void 0,{month:"short"}),MM:String(n.getMonth()+1).padStart(2,"0"),dd:String(n.getDate()).padStart(2,"0"),d:n.getDate(),HH:String(n.getHours()).padStart(2,"0"),mm:String(n.getMinutes()).padStart(2,"0"),ss:String(n.getSeconds()).padStart(2,"0")};return t.replace(/yyyy|MMM|MM|dd|HH|mm|ss|d/g,s=>r[s])}function D8(e,t){return(t?.[e]??t?.[e===1?"one":"other"]??"").replace(/\{\}/g,e??0)}var ur={ERRORS:{cache_busy:"Downloads are busy. Please try again shortly.",invalid_sort:"The selected sort order is invalid.",invalid_cursor:"This project page is no longer valid. Reload the list.",repository_changed:"The repository changed while processing. Please retry.",repository_job_cancelled:"The repository changed or was removed while processing.",storage_delete_failed:"Unable to remove cached files. Please try again later.",unknown_error:"Unknown error, contact the admin.",unreachable:"Anonymous GitHub is unreachable, contact the admin.",request_error:"Unable to download the file, check your connection or contact the admin.",not_found:"The requested resource could not be found.",not_connected:"You must be logged in to perform this action.",not_authorized:"You do not have permission to perform this action.",unable_to_connect_user:"Unable to connect your account. Please try again later.",user_not_found:"The requested user could not be found.",user_banned:"Your account has been banned. Contact the admin for more information.",repo_access_limited:"GitHub blocked access because the repository's organization restricts third-party OAuth apps. Ask an org owner to approve Anonymous GitHub under Settings \u2192 Third-party Access \u2192 OAuth app policy, or anonymize a personal fork instead.",repo_saml_enforcement:"The repository's organization enforces SAML single sign-on. Authorize your token for that organization (GitHub \u2192 Settings \u2192 Applications, or re-run the org's SSO sign-in), then retry. Alternatively, anonymize a personal fork.",repo_not_found:"The repository was not found on GitHub. Check the URL and spelling, make sure you are signed in to the account that can see it, and confirm the repo isn't hidden under an org that restricts third-party app access.",repo_empty:"The selected branch has no commits on GitHub. Push at least one commit, or pick a different branch, then retry.",repo_not_accessible:"Anonymous GitHub cannot access this repository. Verify the repository exists and that Anonymous GitHub has been authorized for the owning organization.",repository_archived:"This repository has been archived and its files are no longer available.",repository_expired:"The repository is expired.",invalid_status:"This action cannot be performed while the resource is in its current state.",repository_not_ready:"Anonymous GitHub is still processing the repository, it can take several minutes.",repository_not_accessible:"This repository is currently not accessible.",repo_is_updating:"Anonymous GitHub is still processing the repository, it can take several minutes.",invalid_repo:"The provided repository is not valid.",invalid_source_repository:"The repository source name Line truncated
/*! Bundled license information:
@vue/shared/dist/shared.esm-bundler.js:
(**
* @vue/shared v3.5.42
* @vue/shared v3.5.43
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**)
@vue/reactivity/dist/reactivity.esm-bundler.js:
(**
* @vue/reactivity v3.5.42
* @vue/reactivity v3.5.43
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**)
@vue/runtime-core/dist/runtime-core.esm-bundler.js:
(**
* @vue/runtime-core v3.5.42
* @vue/runtime-core v3.5.43
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**)
@vue/runtime-dom/dist/runtime-dom.esm-bundler.js:
(**
* @vue/runtime-dom v3.5.42
* @vue/runtime-dom v3.5.43
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**)
vue/dist/vue.runtime.esm-bundler.js:
(**
* vue v3.5.42
* vue v3.5.43
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**)
+4
View File
@@ -2,6 +2,8 @@ import { resolve } from "path";
import { randomBytes } from "crypto";
interface Config {
RESEND_API_KEY: string;
EMAIL_FROM: string;
GITHUB_APP_ENABLED: boolean;
GITHUB_APP_NEW_CONNECTIONS: boolean;
GITHUB_OAUTH_ENABLED: boolean;
@@ -67,6 +69,8 @@ interface Config {
RATE_LIMIT: number;
}
const config: Config = {
RESEND_API_KEY: "",
EMAIL_FROM: "",
GITHUB_APP_ENABLED: false,
GITHUB_APP_NEW_CONNECTIONS: true,
GITHUB_OAUTH_ENABLED: true,
+17 -3
View File
@@ -1,3 +1,4 @@
import { notifyOwnerAccessProblem } from "./owner-notifications";
import { streamResponse } from "./response-stream";
import { join, basename, dirname } from "path";
import { Response } from "express";
@@ -269,7 +270,10 @@ export default class AnonymizedFile {
fetchFileInfoFromPath?: (filePath: string) => Promise<IFile | null>;
};
if (typeof source.fetchFileInfoFromPath !== "function") return null;
const recovered = await source.fetchFileInfoFromPath(this.anonymizedPath);
const recovered = await source.fetchFileInfoFromPath(this.anonymizedPath).catch(error => {
void notifyOwnerAccessProblem(this.repository.owner.id, error);
throw error;
});
if (!recovered) return null;
recovered.repoId = this.repository.repoId;
recovered.treeGeneration = this.repository.model.treeGeneration;
@@ -355,7 +359,11 @@ export default class AnonymizedFile {
httpStatus: 413,
});
}
const content = await this.repository.source?.getFileContent(this);
const content = await this.repository.source?.getFileContent(this).catch(error => {
void notifyOwnerAccessProblem(this.repository.owner.id, error);
throw error;
});
content.on("error", error => { void notifyOwnerAccessProblem(this.repository.owner.id, error); });
const cacheWasReset = this.repository.model.isReseted;
if (cacheWasReset) {
await this.repository.markCachePresent();
@@ -378,7 +386,7 @@ export default class AnonymizedFile {
}
// use the streamer service
return got.stream(join(config.STREAMER_ENTRYPOINT, "api"), {
const content = got.stream(join(config.STREAMER_ENTRYPOINT, "api"), {
method: "POST",
headers: requestHeaders(),
json: {
@@ -395,6 +403,11 @@ export default class AnonymizedFile {
anonymizerOptions: anonymizer.opt,
},
});
content.on("error", err => {
const { error } = streamerErrorToAnonymous(err, { repoId: this.repository.repoId, filePath: this.anonymizedPath });
void notifyOwnerAccessProblem(this.repository.owner.id, error);
});
return content;
}
get filePath() {
@@ -472,6 +485,7 @@ export default class AnonymizedFile {
filePath: this.anonymizedPath,
}
);
void notifyOwnerAccessProblem(this.repository.owner.id, error);
error.value = this;
handleError(error, res);
if (res.headersSent && !res.writableEnded) res.destroy();
+9
View File
@@ -1,3 +1,4 @@
import { notifyOwnerAccessProblem } from "./owner-notifications";
import { registerGitHubToken } from "./github-token-context";
import { isConnected } from "../server/database";
import { expireEmbeddedContent } from "./content-expiration";
@@ -67,6 +68,14 @@ export default class Gist {
}
async download() {
try { await this.downloadWithAccess(); }
catch (error) {
void notifyOwnerAccessProblem(this.owner.id, error);
throw error;
}
}
private async downloadWithAccess() {
const access = await this.getAccess();
try {
await this.downloadContent(access.token);
+15 -38
View File
@@ -1,4 +1,6 @@
import { isGitHubRateLimitError, OctokitRequestErrorLike } from "./github-rate-limit";
import { refreshLegacyToken } from "./legacy-token-refresh";
import { notifyOwnerAccessProblem } from "./owner-notifications";
import AnonymizedRepositoryModel from "./model/anonymizedRepositories/anonymizedRepositories.model";
import { isConnected } from "../server/database";
import { githubQuotaKey, githubTokenContext } from "./github-token-context";
@@ -16,35 +18,7 @@ import { measureStage } from "./request-monitoring";
const logger = createLogger("github");
// Octokit RequestError shape (subset we care about for rate-limit detection).
interface OctokitRequestErrorLike {
status?: number;
message?: string;
response?: {
headers?: Record<string, string | undefined>;
};
}
/**
* Detect GitHub rate-limit / abuse responses (primary 5k/h or undocumented
* "secondary" limits) and rewrap them as a translatable AnonymousError so
* the UI can show a friendly message instead of a raw HttpError stack. The
* GitHub `x-github-request-id` header is preserved in `detail` so users can
* cite it if they reach out to GitHub Support.
*/
export function isGitHubRateLimitError(err: unknown): boolean {
if (!err || typeof err !== "object") return false;
const e = err as OctokitRequestErrorLike;
const msg = (e.message ?? "").toLowerCase();
// Primary limits return 403 with "x-ratelimit-remaining: 0"; secondary
// limits return 403 (sometimes 429) with "secondary rate limit" in the
// body. Match on either signal so we catch both.
const status = e.status ?? 0;
if (status !== 403 && status !== 429) return false;
if (msg.includes("rate limit") || msg.includes("abuse")) return true;
const remaining = e.response?.headers?.["x-ratelimit-remaining"];
return remaining === "0";
}
export { isGitHubRateLimitError } from "./github-rate-limit";
function rateLimitDetail(err: OctokitRequestErrorLike): string {
const headers = err.response?.headers ?? {};
@@ -289,7 +263,7 @@ export function octokit(token: string) {
export { waitForTokenGate };
export async function checkToken(token: string) {
export async function checkToken(token: string, ownerId?: string) {
const oct = octokit(token);
try {
const context = githubTokenContext(token);
@@ -298,12 +272,10 @@ export async function checkToken(token: string) {
else await oct.users.getAuthenticated();
return true;
} catch (err) {
if (
err instanceof AnonymousError &&
err.message === "github_rate_limit_exceeded"
) {
throw err;
}
// Only a confirmed invalid credential permits fallback. Network failures,
// permission failures and rate limits must retain their original meaning.
if ((err as { status?: number })?.status !== 401) throw err;
if (ownerId) void notifyOwnerAccessProblem(ownerId, "token_expired");
return false;
}
}
@@ -311,7 +283,12 @@ export async function checkToken(token: string) {
const checkedRepositoryTokens = new WeakMap<Repository, string>();
export async function getToken(repository: Repository) {
return measureStage("authorization", () => resolveRepositoryToken(repository));
try {
return await measureStage("authorization", () => resolveRepositoryToken(repository));
} catch (error) {
void notifyOwnerAccessProblem(repository.owner.id, error);
throw error;
}
}
async function resolveRepositoryToken(repository: Repository) {
@@ -344,7 +321,7 @@ async function resolveRepositoryToken(repository: Repository) {
return refreshed;
}
}
const check = await checkToken(ownerAccessToken);
const check = await checkToken(ownerAccessToken, repository.owner.id);
if (check) {
checkedRepositoryTokens.set(repository, ownerAccessToken);
return ownerAccessToken;
+9
View File
@@ -1,3 +1,4 @@
import { notifyOwnerAccessProblem } from "./owner-notifications";
import { isConnected } from "../server/database";
import { expireEmbeddedContent } from "./content-expiration";
import { boundAppToken } from "./github-app";
@@ -33,6 +34,14 @@ export default class PullRequest {
}
async download() {
try { await this.downloadContent(); }
catch (error) {
void notifyOwnerAccessProblem(this.owner.id, error);
throw error;
}
}
private async downloadContent() {
logger.info("downloading pull request", {
pullRequestId: this._model.source.pullRequestId,
});
+13 -1
View File
@@ -1,3 +1,4 @@
import { notifyOwnerAccessProblem } from "./owner-notifications";
import AnonymizedPathModel from "./model/anonymized-path";
import storage from "./storage";
import { contentGenerationPrefix, contentRetirementMarker } from "./content-generation";
@@ -223,7 +224,10 @@ export default class Repository {
const previousPrefix = contentGenerationPrefix(`${previousGeneration || "legacy"}:${this.model.anonymizeDate?.toISOString() || ""}`);
const streamed = this.model.source.type !== "Zip";
const source = this.source;
const files = await source.getFiles(opt.progress);
const files = await source.getFiles(opt.progress).catch(error => {
void notifyOwnerAccessProblem(this.owner.id, error);
throw error;
});
const sourceWithTruncation = source as unknown as { truncatedFolderList?: string[] };
const truncatedFolders = Array.isArray(sourceWithTruncation.truncatedFolderList)
? [...sourceWithTruncation.truncatedFolderList] : [];
@@ -624,6 +628,14 @@ export default class Repository {
/** Update the repository if a new commit exists. */
async updateIfNeeded(opt?: { force: boolean }): Promise<void> {
try { await this.refreshIfNeeded(opt); }
catch (error) {
void notifyOwnerAccessProblem(this.owner.id, error);
throw error;
}
}
private async refreshIfNeeded(opt?: { force: boolean }): Promise<void> {
this.assertNotArchived();
if (
this._model.options.expirationMode !== "never" &&
+9
View File
@@ -1,3 +1,4 @@
import { notifyOwnerAccessProblem } from "./owner-notifications";
import { registerGitHubToken } from "./github-token-context";
import { createSign, randomUUID } from "crypto";
import { readFileSync } from "fs";
@@ -87,6 +88,14 @@ export async function saveAppGrant(ownerId: string, data: AppTokenResponse) {
}
export async function appUserToken(ownerId: string): Promise<string> {
try { return await resolveAppUserToken(ownerId); }
catch (error) {
void notifyOwnerAccessProblem(ownerId, error);
throw error;
}
}
async function resolveAppUserToken(ownerId: string): Promise<string> {
if (!config.GITHUB_APP_ENABLED) throw appError("github_app_disabled", 503);
const user = await UserModel.findById(ownerId).select("status externalIDs").lean();
if (!user || user.status === "removed" || user.status === "banned") throw appError();
+26
View File
@@ -0,0 +1,26 @@
// Octokit RequestError shape (subset we care about for rate-limit detection).
export interface OctokitRequestErrorLike {
status?: number;
httpStatus?: number;
message?: string;
response?: {
statusCode?: number;
headers?: Record<string, string | undefined>;
};
}
/** Detect GitHub primary and secondary rate limits in API and stream errors. */
export function isGitHubRateLimitError(err: unknown): boolean {
if (!err || typeof err !== "object") return false;
const e = err as OctokitRequestErrorLike;
const msg = (e.message ?? "").toLowerCase();
// Primary limits return 403 with "x-ratelimit-remaining: 0"; secondary
// limits return 403 (sometimes 429) with "secondary rate limit" in the
// body. Match on either signal so we catch both.
const status = e.status ?? e.response?.statusCode ?? e.httpStatus ?? 0;
if (status !== 403 && status !== 429) return false;
if (msg.includes("rate limit") || msg.includes("abuse")) return true;
const remaining = e.response?.headers?.["x-ratelimit-remaining"];
return remaining === "0";
}
+3
View File
@@ -15,6 +15,9 @@ const UserSchema = new Schema({
type: String,
index: { unique: true },
},
notificationEmail: { type: String },
emailPromptNever: { type: Boolean, default: false },
accessAlertAfter: { type: Date, select: false },
emails: [
{
email: { type: String },
+2
View File
@@ -20,6 +20,8 @@ export interface IUser {
createdAt?: Date;
lastUsedAt?: Date;
}[];
notificationEmail?: string;
emailPromptNever?: boolean;
emails: {
email: string;
default: boolean;
+88
View File
@@ -0,0 +1,88 @@
import { isGitHubRateLimitError } from "./github-rate-limit";
import config from "../config";
import UserModel from "./model/users/users.model";
import { createLogger } from "./logger";
const logger = createLogger("owner-notifications");
const DAY = 24 * 60 * 60 * 1000;
const accessErrors = new Set([
"token_expired", "github_oauth_required", "github_app_reconnect_required",
"github_app_access_required", "repo_not_found", "repository_not_found",
"file_not_accessible", "file_not_found", "pull_request_not_found", "gist_not_found", "repo_not_accessible", "repo_access_limited", "repo_saml_enforcement",
]);
export function normalizeEmail(value: unknown): string | null {
if (typeof value !== "string") return null;
const email = value.trim();
// Accept one plain mailbox, never a display name or recipient list.
if (email.length > 254 || !/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?\.[a-zA-Z]{2,}$/.test(email)) return null;
const local = email.split("@")[0];
if (local.length > 64 || local.startsWith(".") || local.endsWith(".") || email.includes("..")) return null;
return email;
}
export function notificationEmail(emails?: { email: string; default: boolean }[], preferred?: string): string {
return normalizeEmail(preferred) || normalizeEmail(emails?.find(e => e.default)?.email) ||
emails?.map(e => normalizeEmail(e.email)).find(Boolean) || "";
}
export function isAccessFailure(error: unknown): boolean {
if (isGitHubRateLimitError(error)) return false;
const code = typeof error === "string" ? error : error instanceof Error ? error.message : "";
const rawStatus = error instanceof Error ? (error as Error & { status?: number }).status : undefined;
if (!accessErrors.has(code) && ![401, 403, 404].includes(rawStatus || 0)) return false;
if (error instanceof Error) {
const upstream = (error as Error & { cause?: { status?: number; httpStatus?: number; response?: { statusCode?: number } } }).cause;
// Some legacy paths wrap timeouts or 5xx responses as repo_not_found.
// Only a confirmed access failure should prompt the owner to reconnect.
if (isGitHubRateLimitError(upstream)) return false;
if (upstream && ![401, 403, 404].includes(upstream.status || upstream.response?.statusCode || upstream.httpStatus || 0)) return false;
const status = (error as Error & { httpStatus?: number }).httpStatus;
if (status && (status === 429 || status >= 500)) return false;
}
return true;
}
/** Best effort; mail and database failures must not change repository behavior. */
export async function notifyOwnerAccessProblem(ownerId: string, error: unknown): Promise<void> {
if (!config.RESEND_API_KEY || !config.EMAIL_FROM || !isAccessFailure(error)) return;
try {
const now = new Date();
// The atomic claim limits all repositories and workers to one email per owner
// per day. Claim before sending so concurrent requests cannot flood an inbox.
const owner = await UserModel.findOneAndUpdate({
_id: ownerId, status: { $nin: ["removed", "banned"] },
$and: [{ $or: [{ "emails.0": { $exists: true } }, { notificationEmail: { $exists: true, $ne: "" } }] }],
$or: [{ accessAlertAfter: { $exists: false } }, { accessAlertAfter: { $lte: now } }],
}, { $set: { accessAlertAfter: new Date(now.getTime() + DAY) } }, { new: true }).lean();
if (!owner) return;
const to = notificationEmail(owner.emails, owner.notificationEmail);
if (!to) return;
const base = /^https?:\/\//.test(config.APP_HOSTNAME) ? config.APP_HOSTNAME : `https://${config.APP_HOSTNAME}`;
const url = new URL("/connections", base).href;
let rejected = false;
try {
const response = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: { Authorization: `Bearer ${config.RESEND_API_KEY}`, "Content-Type": "application/json" },
signal: AbortSignal.timeout(15000),
body: JSON.stringify({
from: config.EMAIL_FROM, to: [to],
subject: "Your Anonymous GitHub connection needs attention",
text: `Anonymous GitHub could not access GitHub using your connection, or could not read a repository.\n\nOpen your connections page to reconnect your account or restore repository access:\n${url}\n\nYou are receiving this email because you own content on Anonymous GitHub. You can change your alert address on the connections page.\n`,
}),
});
rejected = !response.ok;
if (rejected) throw new Error("email_delivery_failed");
} catch {
// Only a definite rejection may retry early. A timeout can occur after
// Resend accepted the message, so retain the daily claim in that case.
if (rejected) await UserModel.updateOne({ _id: ownerId, accessAlertAfter: new Date(now.getTime() + DAY) },
{ $set: { accessAlertAfter: new Date(now.getTime() + 10 * 60000) } });
logger.warn("owner access email delivery failed");
}
} catch {
// Do not log provider errors, which can contain credentials or addresses.
logger.warn("owner access email unavailable");
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
const sensitive = /^(?:authorization|proxy-authorization|cookie|set-cookie|token|access_?tokens?|refresh_?token|encryptedToken|encryptedRefreshToken|private_?key|GITHUB_APP_PRIVATE_KEY|GITHUB_APP_CLIENT_SECRET|GITHUB_APP_WEBHOOK_SECRET|ciphertext|nonce|tag|password|client_?secret|CREDENTIAL_KEYS)$/i;
const sensitive = /^(?:authorization|proxy-authorization|cookie|set-cookie|token|access_?tokens?|refresh_?token|encryptedToken|encryptedRefreshToken|private_?key|GITHUB_APP_PRIVATE_KEY|GITHUB_APP_CLIENT_SECRET|GITHUB_APP_WEBHOOK_SECRET|ciphertext|nonce|tag|password|client_?secret|CREDENTIAL_KEYS|RESEND_API_KEY)$/i;
export function redactSecrets(value: unknown, seen = new WeakSet<object>()): unknown {
if (typeof value === "string") return value
.replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+)\b/g, "[REDACTED]")
+6 -2
View File
@@ -52,7 +52,9 @@ export async function classifyGitHubMissError(
repo: data.repoName,
});
return "commit_not_found";
} catch {
} catch (probeError) {
if ((probeError as { status?: number; httpStatus?: number }).status !== 404 &&
(probeError as { httpStatus?: number }).httpStatus !== 404) throw probeError;
// Repo no longer exists at owner/repo. Try to recover via the cached
// numeric GitHub id — if the repo was renamed, GET /repositories/{id}
// resolves to its new full_name. See #409.
@@ -87,7 +89,9 @@ export async function classifyGitHubMissError(
return "repo_renamed";
}
return "repo_not_found";
} catch {
} catch (probeError) {
if ((probeError as { status?: number; httpStatus?: number }).status !== 404 &&
(probeError as { httpStatus?: number }).httpStatus !== 404) throw probeError;
return "repo_not_found";
}
}
+2 -1
View File
@@ -77,7 +77,8 @@ export class GitHubRepository {
try {
await oct.repos.get({ owner: this.owner, repo: this.repo });
repoExists = true;
} catch {
} catch (probeError) {
if ((probeError as { status?: number }).status !== 404) throw probeError;
repoExists = false;
}
throw new AnonymousError(
+7 -4
View File
@@ -412,10 +412,13 @@ export default class GitHubStream extends GitHubBase {
size: data.size,
};
} catch (error) {
logger.debug("fetchFileInfoFromPath miss", {
filePath,
error: serializeError(error),
});
if ((error as { status?: number }).status !== 404) throw error;
// A missing file and lost repository access both return 404. Only
// report a normal miss after the repository probe remains readable.
const code = await classifyGitHubMissError(error, this.data);
if (code === "repo_not_found") {
throw new AnonymousError(code, { httpStatus: 404, cause: error as Error });
}
return null;
}
}
@@ -2,6 +2,7 @@ import { githubQuotaKey } from "../../core/github-token-context";
import { SandboxedJob } from "bullmq";
import { config } from "dotenv";
config();
import { notifyOwnerAccessProblem } from "../../core/owner-notifications";
import { getRepository as getRepositoryImport } from "../../server/database";
import { RepositoryStatus } from "../../core/types";
import { RepoJobData } from "../index";
@@ -142,6 +143,7 @@ export default async function (job: SandboxedJob<RepoJobData, void>) {
if (error instanceof DelayedError || (error instanceof Error && error.name === "DelayedError")) {
throw error;
}
await notifyOwnerAccessProblem(repo.owner.id, error);
logger.error("finished with error", {
...serializeError(error),
repoId: job.data.repoId,
+29 -3
View File
@@ -1,3 +1,4 @@
import { notificationEmail, normalizeEmail } from "../../core/owner-notifications";
import * as express from "express";
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "crypto";
import config from "../../config";
@@ -16,7 +17,7 @@ import { isDisabledAccount, safeAuthReturnTo } from "./auth-utils";
type Flow = { state: string; expires: number; ownerId?: string; returnTo: string; repository?: string; install?: boolean };
declare module "express-session" {
interface SessionData { githubAppFlow?: Flow; githubInstallFlow?: Flow; githubConnectionCSRF?: string; }
interface SessionData { githubAppFlow?: Flow; githubInstallFlow?: Flow; githubConnectionCSRF?: string; emailPromptDismissed?: boolean; }
}
export function safeReturnTo(value: unknown): string {
return safeAuthReturnTo(value, "/connections");
@@ -28,6 +29,12 @@ export function consumeFlow(flow: Flow | undefined, state: unknown): Flow {
function newFlow(ownerId: string | undefined, returnTo: unknown): Flow {
return { state: randomBytes(32).toString("hex"), expires: Date.now() + 10 * 60000, ownerId, returnTo: safeReturnTo(returnTo) };
}
// Parallel user/connections reads must initialize the same token even when
// both loaded the session before either request saved it.
export function connectionCSRF(req: express.Request): string {
return req.session.githubConnectionCSRF ||= createHmac("sha256", config.SESSION_SECRET)
.update(`github-connections:${req.sessionID}`).digest("hex");
}
function saveSession(req: express.Request) { return new Promise<void>((resolve, reject) => req.session.save(err => err ? reject(err) : resolve())); }
function enabled(req: express.Request, res: express.Response, next: express.NextFunction) {
if (!config.GITHUB_APP_ENABLED || !config.GITHUB_APP_NEW_CONNECTIONS) return res.status(503).json({ error: "github_app_disabled" });
@@ -150,7 +157,7 @@ router.get("/app/setup", enabled, async (req, res) => {
router.get("/connections", async (req, res) => {
try {
const user = await getUser(req);
req.session.githubConnectionCSRF ||= randomBytes(32).toString("hex");
connectionCSRF(req);
await saveSession(req);
const credentials = await CredentialModel.find({ ownerId: user.id }).select("provider revoked").lean();
const appConnected = credentials.some(c => c.provider === APP_PROVIDER && !c.revoked);
@@ -167,7 +174,8 @@ router.get("/connections", async (req, res) => {
const repos = await RepositoryModel.find({ owner: user.id, status: { $ne: "removed" } }).select("repoId source.repositoryName githubAccess status statusDate").lean();
const prs = await PullRequestModel.find({ owner: user.id, status: { $ne: "removed" } }).select("pullRequestId source.repositoryFullName githubAccess status statusDate").lean();
const gistCount = await GistModel.countDocuments({ owner: user.id, status: { $ne: "removed" } });
res.json({ csrf: req.session.githubConnectionCSRF, appEnabled: config.GITHUB_APP_ENABLED && config.GITHUB_APP_NEW_CONNECTIONS,
res.json({ notificationEmail: notificationEmail(user.model.emails, user.model.notificationEmail), emailNotificationsEnabled: !!(config.RESEND_API_KEY && config.EMAIL_FROM),
csrf: req.session.githubConnectionCSRF, appEnabled: config.GITHUB_APP_ENABLED && config.GITHUB_APP_NEW_CONNECTIONS,
gistConnection: config.GITHUB_APP_ENABLED && credentials.some(c => c.provider === APP_PROVIDER) ? "github-app" : "oauth",
oauthEnabled: config.GITHUB_OAUTH_ENABLED, oauthConnected: !!(await getCredentialToken(user.id)), appConnected, appError: appErrorCode,
installations, gistCount, resources: [
@@ -184,6 +192,24 @@ router.use("/connections", (req, res, next) => {
next();
});
router.post("/connections/email", async (req, res) => {
try {
const user = await getUser(req);
const action = req.body?.action || "save";
if (!["save", "later", "never"].includes(action)) return res.status(400).json({ error: "Invalid email preference." });
if (action === "later" || action === "never") {
if (action === "never") await UserModel.updateOne({ _id: user.id }, { $set: { emailPromptNever: true } });
req.session.emailPromptDismissed = true;
await saveSession(req);
return res.json({ ok: true });
}
const email = normalizeEmail(req.body?.email);
if (!email) return res.status(400).json({ error: "Enter a valid email address." });
await UserModel.updateOne({ _id: user.id }, { $set: { notificationEmail: email } });
res.json({ notificationEmail: email });
} catch (error) { handleError(error, res, req); }
});
router.post("/connections/migrate", async (req, res) => {
try {
const user = await getUser(req);
+16 -1
View File
@@ -1,6 +1,7 @@
import { notificationEmail } from "../../core/owner-notifications";
import DashboardName from "../../core/model/dashboard-name";
import { dashboardSummary } from "./dashboard-summary";
import { revokeGrant } from "./github-app";
import { connectionCSRF, revokeGrant } from "./github-app";
import CredentialModel from "../../core/model/credentials/credentials.model";
import * as express from "express";
import config from "../../config";
@@ -40,7 +41,18 @@ router.get("/logout", async (req, res) => {
router.get("/", async (req, res) => {
try {
const user = await getUser(req);
const showEmailPrompt = !!(config.RESEND_API_KEY && config.EMAIL_FROM) &&
!notificationEmail(user.model.emails, user.model.notificationEmail) && !user.model.emailPromptNever && !req.session.emailPromptDismissed;
if (showEmailPrompt) {
connectionCSRF(req);
await new Promise<void>((resolve, reject) => req.session.save(error => error ? reject(error) : resolve()));
}
res.set("Cache-Control", "no-store");
res.json({
showEmailPrompt,
emailPromptCSRF: showEmailPrompt ? req.session.githubConnectionCSRF : undefined,
notificationEmail: notificationEmail(user.model.emails, user.model.notificationEmail),
emailNotificationsEnabled: !!(config.RESEND_API_KEY && config.EMAIL_FROM),
username: user.username,
photo: user.photo,
isAdmin: user.isAdmin,
@@ -226,6 +238,9 @@ router.delete("/", async (req, res) => {
repositories: [],
},
$unset: {
notificationEmail: "",
emailPromptNever: "",
accessAlertAfter: "",
accessTokens: "",
accessTokenDates: "",
externalIDs: "",
+427
View File
@@ -0,0 +1,427 @@
const { expect } = require("chai");
require("ts-node/register/transpile-only");
const config = require("../src/config").default;
const User = require("../src/core/model/users/users.model").default;
const notifications = require("../src/core/owner-notifications");
const { normalizeEmail, notificationEmail, notifyOwnerAccessProblem } = notifications;
describe("owner access notifications", () => {
const restores = [];
const stub = (object, key, value) => { const old = object[key]; restores.push(() => object[key] = old); object[key] = value; };
let sent, claims, retryWrites, owner, after;
beforeEach(() => {
sent = []; claims = []; retryWrites = []; after = null;
owner = { status: "active", emails: [{ email: "owner@example.com", default: true }] };
stub(config, "RESEND_API_KEY", "test-resend-key");
stub(config, "EMAIL_FROM", "alerts@example.com");
stub(config, "APP_HOSTNAME", "anonymous.example.com");
stub(User, "findOneAndUpdate", (filter, update) => ({ lean: async () => {
claims.push(filter);
if (!owner || ["removed", "banned"].includes(owner.status) || (!owner.emails.length && !owner.notificationEmail) || after > new Date()) return null;
after = update.$set.accessAlertAfter;
return owner;
} }));
stub(User, "updateOne", async (filter, update) => { retryWrites.push({ filter, update }); after = update.$set.accessAlertAfter; });
stub(global, "fetch", async (url, options) => { sent.push({ url, options, body: JSON.parse(options.body) }); return { ok: true }; });
});
afterEach(() => { while (restores.length) restores.pop()(); });
it("accepts one mailbox and rejects recipient lists and header injection", () => {
expect(normalizeEmail(" Owner+alerts@example.com ")).to.equal("Owner+alerts@example.com");
for (const value of [undefined, {}, "a@b.com,b@b.com", "Person <a@b.com>", "a@b.com\r\nBcc: x@y.com", ".a@b.com", "a..b@b.com", "a".repeat(65) + "@example.com"]) {
expect(normalizeEmail(value)).to.equal(null);
}
expect(notificationEmail([{ email: "first@example.com", default: false }, { email: "primary@example.com", default: true }])).to.equal("primary@example.com");
});
it("sends one private Resend message across concurrent failures", async () => {
await Promise.all(Array.from({ length: 10 }, () => notifyOwnerAccessProblem("owner-id", "token_expired")));
expect(sent).to.have.length(1);
expect(sent[0].url).to.equal("https://api.resend.com/emails");
expect(sent[0].options.headers.Authorization).to.equal("Bearer test-resend-key");
expect(sent[0].body.to).to.deep.equal(["owner@example.com"]);
expect(sent[0].body.text).to.include("https://anonymous.example.com/connections");
expect(JSON.stringify(sent[0].body)).not.to.include("test-resend-key");
expect(claims[0].status).to.deep.equal({ $nin: ["removed", "banned"] });
expect(claims[0].$or).to.have.length(2);
});
it("ignores disabled delivery, missing recipients and transient failures", async () => {
for (const code of ["github_rate_limit_exceeded", "github_unavailable", "ETIMEDOUT", "quota_exceeded"]) {
await notifyOwnerAccessProblem("owner-id", new Error(code));
}
await notifyOwnerAccessProblem("owner-id", Object.assign(new Error("repo_not_found"), { cause: { status: 503 } }));
await notifyOwnerAccessProblem("owner-id", Object.assign(new Error("token_expired"), { cause: new Error("network timeout") }));
expect(claims).to.have.length(0);
owner.emails = [];
await notifyOwnerAccessProblem("owner-id", "repo_not_found");
owner.emails = [{ email: "owner@example.com", default: true }];
owner.status = "banned";
await notifyOwnerAccessProblem("owner-id", "repo_not_found");
config.RESEND_API_KEY = "";
await notifyOwnerAccessProblem("owner-id", "token_expired");
expect(sent).to.have.length(0);
});
it("backs off after delivery failure without throwing", async () => {
stub(global, "fetch", async () => ({ ok: false }));
await notifyOwnerAccessProblem("owner-id", "repo_not_accessible");
expect(retryWrites).to.have.length(1);
expect(after.getTime() - Date.now()).to.be.within(590000, 600000);
await notifyOwnerAccessProblem("owner-id", "repo_not_accessible");
expect(retryWrites).to.have.length(1);
});
it("retains the daily claim when delivery may already have happened", async () => {
let attempts = 0;
stub(global, "fetch", async () => { attempts++; throw new Error("response timed out after acceptance"); });
await notifyOwnerAccessProblem("owner-id", "token_expired");
expect(retryWrites).to.have.length(0);
expect(after.getTime() - Date.now()).to.be.within(86390000, 86400000);
await notifyOwnerAccessProblem("owner-id", "token_expired");
expect(attempts).to.equal(1);
});
it("uses a dedicated alert address without requiring or replacing profile emails", async () => {
owner.notificationEmail = "alerts@example.com";
const original = JSON.stringify(owner.emails);
await notifyOwnerAccessProblem("owner-id", "token_expired");
expect(sent[0].body.to).to.deep.equal(["alerts@example.com"]);
expect(JSON.stringify(owner.emails)).to.equal(original);
after = null; owner.emails = [];
await notifyOwnerAccessProblem("owner-id", "token_expired");
expect(sent).to.have.length(2);
});
it("recognizes raw authentication and missing-resource errors without alerting for outages", () => {
for (const status of [401, 403, 404]) expect(notifications.isAccessFailure(Object.assign(new Error("GitHub rejected access"), { status }))).to.equal(true);
for (const status of [429, 500, 503]) expect(notifications.isAccessFailure(Object.assign(new Error("upstream error"), { status }))).to.equal(false);
});
it("suppresses primary and secondary rate limits including wrapped streaming errors", () => {
const AnonymousError = require("../src/core/AnonymousError").default;
for (const error of [
Object.assign(new Error("API rate limit exceeded"), { status: 403 }),
Object.assign(new Error("abuse detection"), { status: 403 }),
Object.assign(new Error("Forbidden"), { status: 403, response: { headers: { "x-ratelimit-remaining": "0" } } }),
Object.assign(new Error("secondary rate limit"), { response: { statusCode: 403 } }),
]) {
expect(notifications.isAccessFailure(error)).to.equal(false);
expect(notifications.isAccessFailure(new AnonymousError("file_not_accessible", { httpStatus: 403, cause: error }))).to.equal(false);
}
const forbidden = Object.assign(new Error("SAML enforcement"), { response: { statusCode: 403 } });
expect(notifications.isAccessFailure(new AnonymousError("file_not_accessible", { httpStatus: 403, cause: forbidden }))).to.equal(true);
});
it("does not let database failures escape", async () => {
stub(User, "findOneAndUpdate", () => { throw new Error("database down"); });
await notifyOwnerAccessProblem("owner-id", "token_expired");
expect(sent).to.have.length(0);
});
});
describe("owner email settings", () => {
const utils = require("../src/server/routes/route-utils");
const router = require("../src/server/routes/github-app").githubAppRouter;
const endpoint = router.stack.find(layer => layer.route?.path === "/connections/email").route.stack[0].handle;
const csrf = router.stack.find(layer => !layer.route && layer.handle.toString().includes("x-csrf-token")).handle;
let oldUser, oldUpdate, writes;
beforeEach(() => {
writes = [];
oldUser = utils.getUser; oldUpdate = User.updateOne;
utils.getUser = async () => ({ id: "signed-in-owner" });
User.updateOne = async (...args) => { writes.push(args); };
});
afterEach(() => { utils.getUser = oldUser; User.updateOne = oldUpdate; });
const response = () => ({ statusCode: 200, status(code) { this.statusCode = code; return this; }, json(body) { this.body = body; } });
it("updates only the signed-in owner's address", async () => {
const res = response();
await endpoint({ body: { email: " owner@example.com ", ownerId: "someone-else" } }, res);
expect(writes).to.deep.equal([[{ _id: "signed-in-owner" }, { $set: { notificationEmail: "owner@example.com" } }]]);
expect(res.body.notificationEmail).to.equal("owner@example.com");
});
it("rejects malformed input without a database write", async () => {
const res = response();
await endpoint({ body: { email: ["one@example.com", "two@example.com"] } }, res);
expect(res.statusCode).to.equal(400);
expect(writes).to.have.length(0);
});
for (const action of ["later", "never"]) it(`persists ${action} at the right scope`, async () => {
const req = { body: { action }, session: { save: callback => callback() } };
const res = response();
await endpoint(req, res);
expect(req.session.emailPromptDismissed).to.equal(true);
expect(res.body.ok).to.equal(true);
expect(writes).to.deep.equal(action === "never" ? [[{ _id: "signed-in-owner" }, { $set: { emailPromptNever: true } }]] : []);
});
it("rejects unknown preference actions", async () => {
const res = response();
await endpoint({ body: { action: "invalid" } }, res);
expect(res.statusCode).to.equal(400);
expect(writes).to.have.length(0);
});
it("initializes the same CSRF token for parallel session snapshots", () => {
const { connectionCSRF } = require("../src/server/routes/github-app");
const userRequest = { sessionID: "same-login-session", session: {} };
const connectionsRequest = { sessionID: "same-login-session", session: {} };
const popupToken = connectionCSRF(userRequest);
const pageToken = connectionCSRF(connectionsRequest);
expect(popupToken).to.equal(pageToken);
expect(connectionCSRF({ sessionID: "another-login", session: {} })).not.to.equal(pageToken);
for (const token of [popupToken, pageToken]) {
let accepted = false;
csrf({ method: "POST", session: connectionsRequest.session, headers: { "x-csrf-token": token } }, response(), () => { accepted = true; });
expect(accepted).to.equal(true);
}
});
it("requires the session's CSRF token before changing email", () => {
const res = response(); let next = false;
csrf({ method: "POST", session: { githubConnectionCSRF: "secret" }, headers: {} }, res, () => { next = true; });
expect(res.statusCode).to.equal(403); expect(next).to.equal(false);
csrf({ method: "POST", session: { githubConnectionCSRF: "secret" }, headers: { "x-csrf-token": "secret" } }, response(), () => { next = true; });
expect(next).to.equal(true);
});
});
describe("email popup eligibility", () => {
const utils = require("../src/server/routes/route-utils");
const router = require("../src/server/routes/user").default;
const endpoint = router.stack.find(layer => layer.route?.path === "/" && layer.route.methods.get).route.stack[0].handle;
let oldUser, oldKey, oldFrom;
beforeEach(() => {
oldUser = utils.getUser; oldKey = config.RESEND_API_KEY; oldFrom = config.EMAIL_FROM;
config.RESEND_API_KEY = "test"; config.EMAIL_FROM = "alerts@example.com";
});
afterEach(() => { utils.getUser = oldUser; config.RESEND_API_KEY = oldKey; config.EMAIL_FROM = oldFrom; });
for (const reason of ["eligible", "email", "alert-email", "never", "later", "no-key", "no-sender"]) {
it(`checks ${reason} before showing the form`, async () => {
utils.getUser = async () => ({ username: "owner", model: {
emails: reason === "email" ? [{ email: "owner@example.com", default: true }] : [],
notificationEmail: reason === "alert-email" ? "alerts@example.com" : undefined,
emailPromptNever: reason === "never",
} });
if (reason === "no-key") config.RESEND_API_KEY = "";
if (reason === "no-sender") config.EMAIL_FROM = "";
const req = { session: { emailPromptDismissed: reason === "later", save: cb => cb() } };
const res = { set() {}, json(body) { this.body = body; } };
await endpoint(req, res);
expect(res.body.showEmailPrompt).to.equal(reason === "eligible");
expect(!!res.body.emailPromptCSRF).to.equal(reason === "eligible");
});
}
});
describe("repository notification hooks", () => {
const Repository = require("../src/core/Repository").default;
const RepositoryModel = require("../src/core/model/anonymizedRepositories/anonymizedRepositories.model").default;
const Files = require("../src/core/model/files/files.model").default;
const github = require("../src/core/source/GitHubRepository");
const tokens = require("../src/core/GitHubUtils");
const app = require("../src/core/github-app");
const restores = [];
const stub = (object, key, value) => { const old = object[key]; restores.push(() => object[key] = old); object[key] = value; };
let repo, sent;
beforeEach(() => {
sent = [];
repo = new Repository(new RepositoryModel({ repoId: "anonymous-id", owner: "507f1f77bcf86cd799439011", status: "ready",
source: { repositoryName: "private/source", branch: "main" }, options: { expirationMode: "never", update: true } }));
stub(notifications, "notifyOwnerAccessProblem", async (...args) => { sent.push(args); });
});
afterEach(() => { while (restores.length) restores.pop()(); });
async function failsWith(work, error) {
try { await work(); } catch (caught) { expect(caught).to.equal(error); return; }
throw new Error("Expected original failure");
}
it("notifies the saved owner when an App repository token cannot be resolved", async () => {
repo.model.githubAccess = { kind: "github-app", revision: "test" };
const error = new Error("github_app_access_required");
stub(app, "boundAppToken", async () => { throw error; });
await failsWith(() => tokens.getToken(repo), error);
expect(sent).to.deep.equal([[repo.owner.id, error]]);
});
it("notifies the saved owner when reading the repository tree fails", async () => {
const error = new Error("repo_not_found");
stub(Files, "exists", () => ({ exec: async () => null }));
Object.defineProperty(repo, "source", { value: { getFiles: async () => { throw error; } } });
await failsWith(() => repo.files(), error);
expect(sent).to.deep.equal([[repo.owner.id, error]]);
});
for (const step of ["branches", "commit"]) it(`notifies on ${step} access errors during refresh`, async () => {
const error = Object.assign(new Error("Forbidden"), { status: 403 });
repo.getToken = async () => "token";
stub(github, "getRepositoryFromGitHub", async () => ({
fullName: repo.model.source.repositoryName, model: { defaultBranch: "main" },
branches: async () => { if (step === "branches") throw error; return [{ name: "main", commit: "new-sha" }]; },
getCommitInfo: async () => { throw error; },
}));
await failsWith(() => repo.updateIfNeeded({ force: true }), error);
expect(sent).to.deep.equal([[repo.owner.id, error]]);
});
it("notifies the saved owner when a repository refresh cannot read GitHub", async () => {
const error = new Error("repo_not_found");
repo.getToken = async () => "token";
stub(github, "getRepositoryFromGitHub", async () => { throw error; });
await failsWith(() => repo.updateIfNeeded({ force: true }), error);
expect(sent).to.deep.equal([[repo.owner.id, error]]);
});
});
describe("gist and pull-request notification hooks", () => {
const Gist = require("../src/core/Gist").default;
const GistModel = require("../src/core/model/anonymizedGists/anonymizedGists.model").default;
const PullRequest = require("../src/core/PullRequest").default;
const PullRequestModel = require("../src/core/model/anonymizedPullRequests/anonymizedPullRequests.model").default;
const github = require("../src/core/GitHubUtils");
const restores = [];
const stub = (object, key, value) => { const old = object[key]; restores.push(() => object[key] = old); object[key] = value; };
let sent;
beforeEach(() => { sent = []; stub(notifications, "notifyOwnerAccessProblem", async (...args) => { sent.push(args); }); });
afterEach(() => { while (restores.length) restores.pop()(); });
for (const type of ["gist", "pull-request"]) for (const failure of ["oauth", "app-access"]) {
it(`alerts the owner on ${type} ${failure} failure and preserves the error`, async () => {
const data = { owner: "507f1f77bcf86cd799439011", source: { gistId: "gist", repositoryFullName: "private/source", pullRequestId: 1 }, options: { expirationMode: "never" } };
const resource = type === "gist" ? new Gist(new GistModel(data)) : new PullRequest(new PullRequestModel(data));
const error = failure === "oauth" ? Object.assign(new Error("Bad credentials"), { status: 401 }) : new Error("github_app_access_required");
if (type === "gist") {
resource.getAccess = async () => {
if (failure === "app-access") throw error;
return { token: "token", connection: "oauth" };
};
resource.downloadContent = async () => { throw error; };
} else {
resource.getToken = async () => { if (failure === "app-access") throw error; return "token"; };
stub(github, "octokit", () => ({ rest: { pulls: { get: async () => { throw error; } } } }));
}
let caught;
try { await resource.download(); } catch (err) { caught = err; }
expect(caught).to.be.instanceOf(Error);
expect(caught.message).to.equal(type === "gist" && failure === "oauth" ? "github_oauth_required" : error.message);
expect(sent).to.deep.equal([[resource.owner.id, caught]]);
});
}
});
describe("streamed file access alerts", () => {
const File = require("../src/core/AnonymizedFile").default;
const AnonymousError = require("../src/core/AnonymousError").default;
const { PassThrough } = require("stream");
const got = require("got");
const restores = [];
const stub = (object, key, value) => { const old = object[key]; restores.push(() => object[key] = old); object[key] = value; };
let sent, repository, file;
beforeEach(() => {
sent = [];
stub(notifications, "notifyOwnerAccessProblem", async (owner, error) => { if (notifications.isAccessFailure(error)) sent.push({ owner, error }); });
repository = { owner: { id: "saved-owner" }, options: { terms: [] }, model: { source: {} }, repoId: "anon-id", status: "ready", source: {},
getToken: async () => "token", generateAnonymizeTransformer: () => new PassThrough() };
file = new File({ repository, anonymizedPath: "README.md" });
});
afterEach(() => { while (restores.length) restores.pop()(); });
for (const status of [403, 404, 503]) it(`handles local file download failure ${status}`, async () => {
const cause = Object.assign(new Error("upstream"), { response: { statusCode: status } });
const error = new AnonymousError(status === 403 ? "file_not_accessible" : status === 404 ? "file_not_found" : "upstream_error", { httpStatus: status, cause });
repository.source.getFileContent = async () => { throw error; };
let caught;
try { await file.content(); } catch (err) { caught = err; }
expect(caught).to.equal(error);
expect(sent).to.have.length(status === 503 ? 0 : 1);
if (sent.length) expect(sent[0].owner).to.equal("saved-owner");
});
for (const status of [403, 404, 503]) it(`handles remote streamer error ${status}`, async () => {
stub(config, "STREAMER_ENTRYPOINT", "http://streamer/");
const stream = new PassThrough();
stub(got, "stream", () => stream);
file.originalPath = async () => "README.md";
file.sha = async () => "sha";
file.size = async () => 10;
const returned = await file.anonymizedContent();
expect(returned).to.equal(stream);
const error = Object.assign(new Error("streamer failure"), { response: { statusCode: status, body: JSON.stringify({ error: status === 503 ? "upstream_error" : "file_not_accessible" }) } });
stream.emit("error", error);
expect(sent).to.have.length(status === 503 ? 0 : 1);
stream.destroy();
});
});
describe("token validation preserves upstream failures", () => {
const tokens = require("../src/core/GitHubUtils");
const { registerGitHubToken } = require("../src/core/github-token-context");
for (const status of [undefined, 403, 429, 500, 503]) it(`propagates token-check failure ${status}`, async () => {
const error = Object.assign(new Error("upstream check failed"), { status });
const token = `test-token-check-${status}`;
registerGitHubToken(token, { quotaKey: token, publicRepository: "owner/repo", renew: async () => { throw error; } });
let caught;
try { await tokens.checkToken(token); } catch (err) { caught = err; }
expect(caught).to.equal(error);
});
it("returns false only for a confirmed invalid token", async () => {
const token = "test-token-check-invalid";
registerGitHubToken(token, { quotaKey: token, publicRepository: "owner/repo", renew: async () => { throw Object.assign(new Error("Bad credentials"), { status: 401 }); } });
expect(await tokens.checkToken(token)).to.equal(false);
});
});
describe("repository probes and truncated file recovery", () => {
const github = require("../src/core/GitHubUtils");
const db = require("../src/server/database");
const Model = require("../src/core/model/repositories/repositories.model").default;
const Files = require("../src/core/model/files/files.model").default;
const File = require("../src/core/AnonymizedFile").default;
const GitHubStream = require("../src/core/source/GitHubStream").default;
const { classifyGitHubMissError } = require("../src/core/source/GitHubBase");
const restores = [];
const stub = (object, key, value) => { const old = object[key]; restores.push(() => object[key] = old); object[key] = value; };
const source = { getToken: async () => "probe-test", repoId: "anon", organization: "owner", repoName: "repo", commit: "sha" };
const missing = () => Object.assign(new Error("Not found"), { status: 404 });
afterEach(() => { while (restores.length) restores.pop()(); });
for (const stage of ["name", "id"]) for (const status of [undefined, 429, 503]) {
it(`propagates inconclusive ${stage} probe ${status}`, async () => {
const error = Object.assign(new Error("probe failed"), { status });
stub(db, "isConnected", true);
stub(Model, "findOne", async () => ({ name: "owner/repo", externalId: "gh_123" }));
stub(github, "octokit", () => ({ repos: { get: async () => { throw stage === "name" ? error : missing(); } }, request: async () => { throw error; } }));
let caught;
try { await classifyGitHubMissError(missing(), source); } catch (err) { caught = err; }
expect(caught).to.equal(error);
expect(notifications.isAccessFailure(caught)).to.equal(false);
});
}
it("preserves an inconclusive repository probe during commit refresh", async () => {
const { GitHubRepository } = require("../src/core/source/GitHubRepository");
const error = Object.assign(new Error("probe unavailable"), { status: 503 });
stub(github, "octokit", () => ({ repos: {
getCommit: async () => { throw missing(); }, get: async () => { throw error; },
} }));
let caught;
try { await new GitHubRepository({ name: "owner/repo" }).getCommitInfo("sha", { accessToken: "token" }); } catch (err) { caught = err; }
expect(caught).to.equal(error);
expect(notifications.isAccessFailure(caught)).to.equal(false);
});
for (const status of [403, 503]) it(`preserves truncated recovery error ${status} before file content is read`, async () => {
const error = Object.assign(new Error("contents lookup failed"), { status });
stub(github, "octokit", () => ({ repos: { getContent: async () => { throw error; } } }));
stub(Files, "findOne", async () => null);
const sent = [];
stub(notifications, "notifyOwnerAccessProblem", async (owner, err) => { if (notifications.isAccessFailure(err)) sent.push(owner); });
const file = new File({ anonymizedPath: "large/missing.txt", repository: {
owner: { id: "saved-owner" }, repoId: "anon", options: { terms: [] },
model: { truncatedFolders: ["large"] }, source: new GitHubStream(source),
} });
let caught;
try { await file.originalPath(); } catch (err) { caught = err; }
expect(caught).to.equal(error);
expect(sent).to.deep.equal(status === 403 ? ["saved-owner"] : []);
});
for (const repoMissing of [false, true]) it(`distinguishes a missing truncated file from lost repository access: ${repoMissing}`, async () => {
stub(db, "isConnected", false);
stub(github, "octokit", () => ({ repos: {
getContent: async () => { throw missing(); },
get: async () => { if (repoMissing) throw missing(); return {}; },
} }));
let result, caught;
try { result = await new GitHubStream(source).fetchFileInfoFromPath("large/missing.txt"); } catch (err) { caught = err; }
if (repoMissing) expect(caught.message).to.equal("repo_not_found");
else { expect(caught).to.equal(undefined); expect(result).to.equal(null); }
});
});
+53
View File
@@ -80,6 +80,59 @@ describe("Vue 3 UI", function () {
let ui;
afterEach(() => ui?.close());
it("prompts owners without email and saves their alert address with CSRF", async () => {
ui = await browser("/dashboard", {
"/api/user": { username: "owner", notificationEmail: "", emailNotificationsEnabled: true, showEmailPrompt: true, emailPromptCSRF: "email-csrf" },
"/github/connections": { csrf: "email-csrf", emailNotificationsEnabled: true, notificationEmail: "", resources: [] },
"/github/connections/email": request => ({ notificationEmail: request.payload.email }),
});
expect(ui.window.document.querySelector("#email-prompt").open).to.equal(true);
await ui.input("#email-prompt-address", "owner@example.com");
ui.window.document.querySelector("#email-prompt-address").closest("form")
.dispatchEvent(new ui.window.Event("submit", { bubbles: true, cancelable: true }));
await delay(30);
const saved = ui.requests.find(r => r.url.pathname === "/github/connections/email");
expect(saved.payload).to.deep.equal({ action: "save", email: "owner@example.com" });
expect(saved.headers["X-CSRF-Token"]).to.equal("email-csrf");
expect(ui.window.document.querySelector("#email-prompt")).to.equal(null);
await ui.go("/dashboard");
expect(ui.window.document.querySelector("#email-prompt")).to.equal(null);
expect(ui.errors).to.deep.equal([]);
});
for (const action of ["later", "never"]) it(`dismisses the email popup with ${action} without requiring an address`, async () => {
ui = await browser("/dashboard", {
"/api/user": { username: "owner", notificationEmail: "", emailNotificationsEnabled: true, showEmailPrompt: true, emailPromptCSRF: "csrf" },
"/github/connections/email": { ok: true },
});
const text = action === "later" ? "Remind me later" : "Never";
[...ui.window.document.querySelectorAll("#email-prompt button")].find(b => b.textContent === text).click();
await delay(30);
expect(ui.requests.find(r => r.url.pathname === "/github/connections/email").payload.action).to.equal(action);
expect(ui.window.document.querySelector("#email-prompt")).to.equal(null);
});
for (const user of [
{ emailNotificationsEnabled: false, showEmailPrompt: true },
{ emailNotificationsEnabled: true, showEmailPrompt: false },
{ emailNotificationsEnabled: true, showEmailPrompt: true, notificationEmail: "owner@example.com" },
]) it(`does not show the email popup for ${JSON.stringify(user)}`, async () => {
ui = await browser("/dashboard", { "/api/user": { username: "owner", ...user } });
expect(ui.window.document.querySelector("#email-prompt")).to.equal(null);
});
it("keeps the popup open and shows an error if saving fails", async () => {
ui = await browser("/dashboard", {
"/api/user": { username: "owner", emailNotificationsEnabled: true, showEmailPrompt: true, emailPromptCSRF: "csrf" },
"/github/connections/email": { __status: 500, body: { error: "Unable to save." } },
});
await ui.input("#email-prompt-address", "owner@example.com");
ui.window.document.querySelector("#email-prompt form").dispatchEvent(new ui.window.Event("submit", { bubbles: true, cancelable: true }));
await delay(30);
expect(ui.window.document.querySelector("#email-prompt").textContent).to.include("Unable to save.");
expect(ui.window.document.querySelector("#email-prompt-address").value).to.equal("owner@example.com");
});
const repositorySource = {
"/api/user": { username: "owner" },
"/api/user/default": { terms: ["Default Author"], options: {} },